R/visualize.R

Defines functions plan_dot dot_id dot_escape html_escape html_row wrap_label condition_code route_label station_tooltip closure_agent station_kind workflow_dot

# The DOT code behind Workflow$visualize().
#
# The graph follows the rules of $run() (see workflow_flow()): it shows
# where the run starts and where it can stop, the parallel groups and how
# their results are merged, and the problems $validate() finds - Stations
# that never run, loops the run can never leave and Routes that are never
# followed.

viz_colors <- list(
  text      = "#0F172A",
  muted     = "#475569",
  faint     = "#94A3B8",
  line      = "#64748B",
  ignored   = "#A8B4C4",
  terminal  = "#1E293B",
  parallel  = "#D97706",
  group_bg  = "#FFFBEB",
  group_bd  = "#FCD34D",
  error     = "#DC2626",
  kinds = list(
    agent    = list(fill = "#EEF2FF", border = "#818CF8", accent = "#4F46E5"),
    workflow = list(fill = "#ECFDF5", border = "#34D399", accent = "#047857"),
    fn       = list(fill = "#F8FAFC", border = "#CBD5E1", accent = "#475569")
  )
)

workflow_dot <- function(stations, routes, groups, entry, name,
                         description = NULL, direction = "LR") {
  flow <- workflow_flow(stations, routes, groups, entry)
  col <- viz_colors
  names_all <- names(stations)
  members <- unique(unlist(lapply(groups, function(group) group$stations)))
  only_in_groups <- setdiff(flow$in_groups, flow$visited)
  never <- setdiff(names_all, union(flow$visited, flow$in_groups))

  # -- Stations ---------------------------------------------------------------
  node_def <- function(n) {
    s <- stations[[n]]
    kind <- station_kind(s$handler)
    pal <- col$kinds[[kind$type]]
    fill <- pal$fill
    border <- pal$border
    accent <- pal$accent
    text <- col$text
    style <- "rounded,filled"
    penwidth <- 1.2
    notes <- character()

    if (s$max_retries > 0L) {
      notes <- c(notes, sprintf("\u21bb %d retr%s", s$max_retries, if (s$max_retries == 1L) "y" else "ies"))
    }
    if (!is.null(s$fallback)) notes <- c(notes, "fallback")

    status <- NULL
    if (n %in% never) {
      fill <- "#FFFFFF"
      border <- col$faint
      accent <- col$faint
      text <- col$faint
      style <- "rounded,filled,dashed"
      status <- list(text = "never runs", color = col$faint)
    } else if (n %in% flow$stuck) {
      border <- col$error
      penwidth <- 2
      status <- list(text = "endless loop", color = col$error)
    }

    rows <- c(
      html_row(html_escape(kind$label), size = 9, color = accent),
      html_row(paste0("<B>", html_escape(n), "</B>"), size = 13, color = text)
    )
    if (!is.null(s$description) && nzchar(s$description)) {
      rows <- c(rows, html_row(
        paste(html_escape(wrap_label(s$description)), collapse = '<BR ALIGN="LEFT"/>'),
        size = 10, color = if (n %in% never) col$faint else col$muted
      ))
    }
    if (length(notes)) {
      rows <- c(rows, html_row(html_escape(paste(notes, collapse = "  \u00b7  ")),
                               size = 9, color = col$muted))
    }
    if (!is.null(status)) {
      rows <- c(rows, html_row(paste0("<B>", status$text, "</B>"), size = 9, color = status$color))
    }

    sprintf(
      '  %s [label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="1">%s</TABLE>>, style="%s", fillcolor="%s", color="%s", penwidth=%s, tooltip="%s"]',
      dot_id(n), paste(rows, collapse = ""), style, fill, border, penwidth,
      dot_escape(station_tooltip(n, s, kind))
    )
  }

  # Stations drawn inside a parallel group's box; each Station in one box.
  boxed <- character()
  clusters <- character()
  group_edges <- character()
  all_groups <- c(
    lapply(flow$group_of, function(g) c(g, list(runs = TRUE))),
    lapply(flow$extra_groups, function(g) c(g, list(runs = FALSE)))
  )
  for (i in seq_along(all_groups)) {
    g <- all_groups[[i]]
    merge_id <- dot_id(paste0("__merge_", i, "__"))
    edge_col <- if (g$runs) col$parallel else col$ignored
    edge_style <- if (g$runs) "solid" else "dotted"
    inside <- setdiff(g$stations, boxed)
    boxed <- c(boxed, inside)
    clusters <- c(clusters, paste0(
      "  subgraph cluster_parallel_", i, " {\n",
      '    label=<<FONT POINT-SIZE="9" COLOR="', if (g$runs) col$parallel else col$faint,
      '"><B>PARALLEL</B></FONT>>; labeljust=l; style="rounded,dashed,filled";',
      ' color="', if (g$runs) col$group_bd else col$ignored,
      '"; fillcolor="', if (g$runs) col$group_bg else "#FFFFFF", '"; margin=12\n',
      if (length(inside)) paste0("    ", vapply(inside, dot_id, ""), "\n", collapse = ""),
      "  }"
    ))
    group_edges <- c(
      group_edges,
      sprintf(
        '  %s [shape=diamond, label="", width=0.18, height=0.18, style=filled, fillcolor="%s", color="%s", tooltip="%s"]',
        merge_id, edge_col, edge_col,
        dot_escape(if (g$runs) "The results of the parallel Stations are merged here" else
          paste0("Never runs: '", g$from, "' starts another parallel group first"))
      ),
      sprintf('  %s -> %s [color="%s", style=%s, penwidth=1.4]',
              dot_id(g$from), vapply(g$stations, dot_id, ""), edge_col, edge_style),
      sprintf('  %s -> %s [color="%s", style=%s, penwidth=1.4, arrowhead=none]',
              vapply(g$stations, dot_id, ""), merge_id, edge_col, edge_style),
      if (!is.null(g$to)) {
        sprintf('  %s -> %s [color="%s", style=%s, penwidth=1.4]',
                merge_id, dot_id(g$to), edge_col, edge_style)
      } else if (g$runs && g$from %in% flow$visited) {
        sprintf('  %s -> "__end__" [color="%s", penwidth=1.4]', merge_id, edge_col)
      }
    )
  }

  # -- Routes -----------------------------------------------------------------
  route_edges <- character()
  for (n in names_all) {
    out <- Filter(function(route) identical(route$from, n), routes)
    if (!length(out)) next
    has_conditional <- any(vapply(out, function(r) !is.null(r$condition), logical(1)))
    first_unconditional <- TRUE
    for (r in out) {
      # Why a Route is never followed, if it is not.
      ignored <- if (!is.null(flow$group_of[[n]])) {
        "the Station starts a parallel group"
      } else if (n %in% only_in_groups) {
        "the Station only runs inside a parallel group"
      } else if (is.null(r$condition) && !first_unconditional) {
        "only the first unconditional Route from a Station is followed"
      }
      if (is.null(r$condition)) first_unconditional <- FALSE

      label <- route_label(r, has_conditional)
      in_loop <- r$from %in% flow$stuck && r$to %in% flow$stuck
      attrs <- if (!is.null(ignored)) {
        c(sprintf('color="%s"', col$ignored), "style=dotted",
          sprintf('label=" ignored "'), sprintf('fontcolor="%s"', col$faint),
          sprintf('tooltip="%s"', dot_escape(paste("Never followed:", ignored))))
      } else {
        c(sprintf('color="%s"', if (in_loop) col$error else col$line),
          if (!is.null(r$condition)) "style=dashed",
          if (in_loop) "penwidth=1.6",
          if (!is.null(label)) sprintf('label=" %s "', dot_escape(label)),
          sprintf('fontcolor="%s"', if (in_loop) col$error else col$muted))
      }
      route_edges <- c(route_edges, sprintf(
        "  %s -> %s [%s]", dot_id(r$from), dot_id(r$to), paste(attrs, collapse = ", ")
      ))
    }
  }

  # -- Start and end ----------------------------------------------------------
  end_edges <- character()
  for (n in flow$visited) {
    if (!is.null(flow$group_of[[n]]) || !isTRUE(flow$can_stop[[n]])) next
    has_routes <- any(vapply(routes, function(r) identical(r$from, n), logical(1)))
    end_edges <- c(end_edges, if (has_routes) {
      sprintf('  %s -> "__end__" [color="%s", style=dashed, label=" otherwise ", fontcolor="%s"]',
              dot_id(n), col$line, col$muted)
    } else {
      sprintf('  %s -> "__end__" [color="%s"]', dot_id(n), col$line)
    })
  }
  has_end <- length(end_edges) > 0L || any(grepl('"__end__"', group_edges, fixed = TRUE))

  terminal <- function(id, label, tooltip) {
    sprintf(
      '  "%s" [label="%s", shape=box, style="rounded,filled", fillcolor="%s", color="%s", fontcolor="#FFFFFF", fontsize=10, width=0.5, height=0.3, margin="0.1,0.04", tooltip="%s"]',
      id, label, col$terminal, col$terminal, tooltip
    )
  }

  # The title is a table, so that the space under the name can be set.
  title_rows <- sprintf(
    '<TR><TD ALIGN="LEFT"><FONT POINT-SIZE="16" COLOR="%s"><B>%s</B></FONT></TD></TR>',
    col$text, html_escape(name)
  )
  if (!is.null(description) && nzchar(description)) {
    title_rows <- c(
      title_rows,
      '<TR><TD HEIGHT="6"></TD></TR>',
      sprintf(
        '<TR><TD ALIGN="LEFT" BALIGN="LEFT"><FONT POINT-SIZE="11" COLOR="%s">%s</FONT></TD></TR>',
        col$muted,
        paste(html_escape(wrap_label(description, 90L, 2L)), collapse = '<BR ALIGN="LEFT"/>')
      )
    )
  }
  title <- paste0(
    '<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0">',
    paste(title_rows, collapse = ""),
    '<TR><TD HEIGHT="10"></TD></TR></TABLE>'
  )

  paste0(
    "digraph workflow {\n",
    "  graph [rankdir=", direction, ", label=<", title, ">,",
    ' labelloc=t, labeljust=l, fontname="Helvetica", nodesep=0.35, ranksep=0.45,',
    ' pad=0.25, bgcolor="transparent"]\n',
    '  node [fontname="Helvetica", shape=box, margin="0.16,0.08"]\n',
    '  edge [fontname="Helvetica", fontsize=9, arrowsize=0.7, penwidth=1.2]\n',
    terminal("__start__", "Start", "Where the run starts"), "\n",
    if (has_end) paste0(terminal("__end__", "End", "Where the run can stop"), "\n"),
    paste(vapply(names_all, node_def, ""), collapse = "\n"), "\n",
    if (length(clusters)) paste0(paste(clusters, collapse = "\n"), "\n"),
    sprintf('  "__start__" -> %s [color="%s"]\n', dot_id(flow$entry), col$line),
    if (length(route_edges)) paste0(paste(route_edges, collapse = "\n"), "\n"),
    if (length(group_edges)) paste0(paste(group_edges, collapse = "\n"), "\n"),
    if (length(end_edges)) paste0(paste(end_edges, collapse = "\n"), "\n"),
    "}\n"
  )
}

# The type of a Station's handler and the label shown above its name.
station_kind <- function(handler) {
  if (inherits(handler, "WorkflowAgent")) {
    inner <- if (inherits(handler$workflow, "Workflow")) {
      length(handler$workflow$.__enclos_env__$private$.stations)
    }
    label <- "Workflow"
    if (!is.null(inner)) label <- sprintf("Workflow \u00b7 %d station%s", inner, if (inner == 1L) "" else "s")
    return(list(type = "workflow", label = label))
  }
  if (inherits(handler, "Agent")) {
    label <- class(handler)[[1L]]
    model <- tryCatch(handler$model_name, error = function(e) NULL)
    if (is.character(model) && length(model) == 1L && nzchar(model)) {
      label <- paste(label, "\u00b7", model)
    }
    return(list(type = "agent", label = label))
  }
  # A function that calls one agent, such as the Stations ArchitectAgent
  # builds, is shown as that agent.
  agent <- closure_agent(handler)
  if (!is.null(agent)) return(station_kind(agent))
  list(type = "fn", label = "Function")
}

# The one Agent or WorkflowAgent a closure refers to, if there is exactly
# one. Functions defined at the top level are not looked into.
closure_agent <- function(fn) {
  env <- environment(fn)
  if (is.null(env) || identical(env, globalenv()) || identical(env, baseenv()) ||
      identical(env, emptyenv()) || isNamespace(env)) {
    return(NULL)
  }
  agents <- list()
  for (name in ls(env, all.names = TRUE)) {
    obj <- tryCatch(get(name, envir = env, inherits = FALSE), error = function(e) NULL)
    if (inherits(obj, c("Agent", "WorkflowAgent"))) agents[[length(agents) + 1L]] <- obj
  }
  if (length(agents) == 1L) agents[[1L]] else NULL
}

station_tooltip <- function(name, station, kind) {
  parts <- c(paste0(name, " (", kind$label, ")"))
  if (!is.null(station$description)) parts <- c(parts, station$description)
  handler <- station$handler
  if (is.function(handler)) handler <- closure_agent(handler)
  instruction <- tryCatch(handler$instruction, error = function(e) NULL)
  if (is.character(instruction) && length(instruction) == 1L && nzchar(instruction)) {
    if (nchar(instruction) > 300L) instruction <- paste0(substr(instruction, 1L, 297L), "...")
    parts <- c(parts, paste("Instruction:", instruction))
  }
  paste(parts, collapse = "\n")
}

# The label of a Route: its own label, the condition's code when it is
# short, or "otherwise" for the Route taken when no condition matches.
route_label <- function(route, has_conditional) {
  if (!is.null(route$label)) return(route$label)
  if (is.null(route$condition)) return(if (has_conditional) "otherwise" else NULL)
  code <- condition_code(route$condition)
  if (is.null(code)) "if condition" else paste("if", code)
}

condition_code <- function(fn) {
  code <- body(fn)
  if (is.null(code)) return(NULL)
  if (is.call(code) && identical(code[[1L]], as.name("{"))) {
    if (length(code) != 2L) return(NULL)
    code <- code[[2L]]
  }
  text <- gsub("\\s+", " ", paste(deparse(code, width.cutoff = 500L), collapse = " "))
  if (nchar(text) > 36L) return(NULL)
  text
}

wrap_label <- function(x, width = 30L, max_lines = 3L) {
  lines <- strwrap(x, width = width)
  if (length(lines) > max_lines) {
    lines <- lines[seq_len(max_lines)]
    lines[[max_lines]] <- paste0(sub("\\s*\\S*$", "", lines[[max_lines]]), " \u2026")
  }
  lines
}

html_row <- function(content, size, color) {
  sprintf('<TR><TD ALIGN="LEFT" BALIGN="LEFT"><FONT POINT-SIZE="%s" COLOR="%s">%s</FONT></TD></TR>',
          size, color, content)
}

html_escape <- function(x) {
  x <- gsub("&", "&amp;", x, fixed = TRUE)
  x <- gsub("<", "&lt;", x, fixed = TRUE)
  x <- gsub(">", "&gt;", x, fixed = TRUE)
  x <- gsub('"', "&quot;", x, fixed = TRUE)
  gsub("'", "&#39;", x, fixed = TRUE)
}

dot_escape <- function(x) {
  x <- gsub("\\", "\\\\", x, fixed = TRUE)
  x <- gsub('"', '\\"', x, fixed = TRUE)
  # DiagrammeR::grViz() turns every ' into ", so ' is written as an entity.
  x <- gsub("'", "&#39;", x, fixed = TRUE)
  gsub("\n", "\\n", x, fixed = TRUE)
}

dot_id <- function(x) paste0('"', dot_escape(x), '"')

# The DOT code behind LeadAgent$visualize_plan(): the request, then one card
# per step of the plan (the agent, its model and the subtask it receives),
# in the order they run, each step receiving the previous step's response.
plan_dot <- function(plan, name, request = NULL, hitl_steps = NULL, direction = "LR") {
  col <- viz_colors
  pal <- col$kinds$agent
  n <- length(plan)
  ids <- dot_id(paste0("__step_", seq_len(n), "__"))

  node_def <- function(i) {
    step <- plan[[i]]
    kind <- paste0("Step ", i, " \u00b7 Agent")
    model <- step$model_name
    if (is.character(model) && length(model) == 1L && !is.na(model) && nzchar(model)) {
      kind <- paste(kind, "\u00b7", model)
    }
    hitl <- i %in% hitl_steps
    rows <- c(
      html_row(html_escape(kind), size = 9, color = pal$accent),
      html_row(paste0("<B>", html_escape(step$agent_name), "</B>"), size = 13, color = col$text),
      html_row(
        paste(html_escape(wrap_label(step$prompt, 34L, 4L)), collapse = '<BR ALIGN="LEFT"/>'),
        size = 10, color = col$muted
      )
    )
    if (hitl) {
      rows <- c(rows, html_row("<B>human review</B>", size = 9, color = col$parallel))
    }
    tooltip <- paste0(
      "Step ", i, ": ", step$agent_name,
      if (!is.null(model) && !is.na(model)) paste0(" (", model, ")"),
      "\nSubtask: ", step$prompt,
      if (hitl) "\nA human reviews the response before the next step."
    )
    sprintf(
      '  %s [label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="1">%s</TABLE>>, style="rounded,filled", fillcolor="%s", color="%s", penwidth=%s, tooltip="%s"]',
      ids[[i]], paste(rows, collapse = ""), pal$fill,
      if (hitl) col$parallel else pal$border, if (hitl) 1.8 else 1.2,
      dot_escape(tooltip)
    )
  }

  terminal <- function(id, label, tooltip) {
    sprintf(
      '  "%s" [label="%s", shape=box, style="rounded,filled", fillcolor="%s", color="%s", fontcolor="#FFFFFF", fontsize=10, width=0.5, height=0.3, margin="0.1,0.04", tooltip="%s"]',
      id, label, col$terminal, col$terminal, dot_escape(tooltip)
    )
  }

  chain <- c('"__start__"', ids, '"__end__"')
  # Between two steps, the response of one is handed to the next.
  labels <- c("", rep(sprintf(', label=" response ", fontcolor="%s"', col$muted), max(n - 1L, 0L)), "")
  edges <- sprintf('  %s -> %s [color="%s"%s]', chain[-length(chain)], chain[-1L], col$line, labels)

  title_rows <- sprintf(
    '<TR><TD ALIGN="LEFT"><FONT POINT-SIZE="16" COLOR="%s"><B>%s</B></FONT></TD></TR>',
    col$text, html_escape(paste0("Plan of ", name))
  )
  if (!is.null(request) && length(request) == 1L && nzchar(request)) {
    title_rows <- c(
      title_rows,
      '<TR><TD HEIGHT="6"></TD></TR>',
      sprintf(
        '<TR><TD ALIGN="LEFT" BALIGN="LEFT"><FONT POINT-SIZE="11" COLOR="%s">%s</FONT></TD></TR>',
        col$muted,
        paste(html_escape(wrap_label(paste0("Request: ", request), 90L, 2L)), collapse = '<BR ALIGN="LEFT"/>')
      )
    )
  }
  title <- paste0(
    '<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0">',
    paste(title_rows, collapse = ""),
    '<TR><TD HEIGHT="10"></TD></TR></TABLE>'
  )

  paste0(
    "digraph plan {\n",
    "  graph [rankdir=", direction, ", label=<", title, ">,",
    ' labelloc=t, labeljust=l, fontname="Helvetica", nodesep=0.35, ranksep=0.45,',
    ' pad=0.25, bgcolor="transparent"]\n',
    '  node [fontname="Helvetica", shape=box, margin="0.16,0.08"]\n',
    '  edge [fontname="Helvetica", fontsize=9, arrowsize=0.7, penwidth=1.2]\n',
    terminal("__start__", "Request", "The request the plan answers"), "\n",
    terminal("__end__", "Answer", "The response of the last step is the final answer"), "\n",
    paste(vapply(seq_len(n), node_def, ""), collapse = "\n"), "\n",
    paste(edges, collapse = "\n"), "\n",
    "}\n"
  )
}

Try the mini007 package in your browser

Any scripts or data that you put into this service are public.

mini007 documentation built on Dec. 3, 2026, 5:10 p.m.