R/parallel.R

Defines functions collect_parallel parallel_task apply_agent_states capture_agent_states find_agents configure_daemons running_daemons

# Parallel execution helpers shared by Workflow (parallel groups) and
# LeadAgent (parallel broadcast).
#
# mirai daemons belong to the R session, not to one object: every Workflow
# and LeadAgent shares the same pool. And a daemon works on a copy of each
# agent it runs, so the agent's conversation, cost and traces have to be
# brought back to the original once the daemon is done.

# Number of daemons running in the session's default compute profile.
running_daemons <- function() {
  if (!isTRUE(tryCatch(mirai::daemons_set(), error = function(e) FALSE))) return(0L)
  n <- tryCatch(mirai::status()$connections, error = function(e) 0L)
  if (is.numeric(n) && length(n) == 1L && !is.na(n)) as.integer(n) else 0L
}

# Makes the session's daemon pool `n` workers strong (0 shuts it down),
# whichever object started the current pool.
configure_daemons <- function(n) {
  current <- running_daemons()
  if (identical(current, n)) return(invisible(n))
  if (current > 0L || isTRUE(tryCatch(mirai::daemons_set(), error = function(e) FALSE))) {
    mirai::daemons(0)
  }
  if (n > 0L) mirai::daemons(n)
  invisible(n)
}

# The agents a station handler runs: the handler itself when it is an agent,
# the agents a LeadAgent or RouterAgent delegates to, the agents it calls as
# tools, the stations of a wrapped Workflow, and the agents a closure
# handler or tool refers to (eg.
# `function(x) writer$invoke(x)` defined inside a function). Returns a list
# keyed by agent_id.
#
# It runs inside the daemons too, so it only uses base R.
find_agents <- function(handler) {
  found <- list()
  visit <- function(x, depth) {
    if (depth > 6L) return(invisible())
    if (inherits(x, "Agent")) {
      id <- x$agent_id
      if (!is.character(id) || length(id) != 1L || !is.null(found[[id]])) return(invisible())
      found[[id]] <<- x
      children <- tryCatch(x$agents, error = function(e) NULL)
      if (is.list(children)) for (child in children) visit(child, depth + 1L)
      # Agents it calls as tools (see $as_tool()).
      tools <- tryCatch(x$tools, error = function(e) NULL)
      if (is.list(tools)) for (tool in tools) visit(tool, depth + 1L)
    } else if (inherits(x, "WorkflowAgent")) {
      stations <- tryCatch(x$workflow$.__enclos_env__$private$.stations, error = function(e) NULL)
      for (station in stations) visit(station$handler, depth + 1L)
    } else if (is.function(x)) {
      env <- environment(x)
      if (is.null(env) || identical(env, globalenv()) || identical(env, baseenv()) ||
          identical(env, emptyenv()) || isNamespace(env)) {
        return(invisible())
      }
      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"))) visit(obj, depth + 1L)
      }
    }
    invisible()
  }
  visit(handler, 0L)
  found
}

# Fields that an agent's run changes, kept when present.
agent_state_fields <- c(
  "cost", "budget_warned", "trace", "last_plan", "routing_history",
  "agents_interaction", "plan", "prompt_for_plan", "agents_for_plan",
  "dialog_history", "broadcast_history", "transcript", "blueprint",
  "todos", "notes", "last_task", "approved_tools"
)

# In a daemon: the state of each agent the handler can reach, as a list keyed
# by agent_id. With `before` (such a list taken before the run), only the
# agents whose conversation changed are kept, so that an agent the run did
# not use never overwrites the original with a stale copy.
# Only base R, and `find` is passed in, so that it works whatever mini007
# version the daemon has loaded.
capture_agent_states <- function(handler, find, fields, before = NULL) {
  agents <- find(handler)
  states <- lapply(agents, function(agent) {
    private <- agent$.__enclos_env__$private
    present <- intersect(fields, names(agent))
    list(
      turns = agent$llm_object$get_turns(),
      cost_offset = if (is.numeric(private$.cost_offset)) private$.cost_offset else 0,
      fields = mget(present, envir = agent)
    )
  })
  if (is.null(before)) return(states)
  changed <- vapply(names(states), function(id) {
    old <- before[[id]]
    is.null(old) || !identical(old$turns, states[[id]]$turns) ||
      !identical(old$cost_offset, states[[id]]$cost_offset)
  }, logical(1))
  states[changed]
}

# Back in the main process: copy each captured state onto the original
# agent. Returns the ids applied.
apply_agent_states <- function(states, handler) {
  if (!length(states)) return(character())
  agents <- find_agents(handler)
  for (id in names(states)) {
    agent <- agents[[id]]
    state <- states[[id]]
    if (is.null(agent) || is.null(state)) next
    private <- agent$.__enclos_env__$private
    agent$llm_object$set_turns(state$turns)
    private$.cost_offset <- state$cost_offset
    for (field in names(state$fields)) {
      if (!bindingIsLocked(field, agent)) assign(field, state$fields[[field]], envir = agent)
    }
    private$.set_messages_from_turns()
    private$.update_cost()
  }
  names(states)
}

# Runs `run(target)` in a daemon, where `target` is an agent or a Workflow
# station (a list with a `handler`). Never fails: errors are returned, along
# with the state of the agents, so that what they spent is not lost. The
# state is read from the very object that ran.
parallel_task <- function(target, run) {
  # Looking the agents up here forces the promises of a closure handler (eg.
  # the `agent` argument of `function(agent) function(x) agent$invoke(x)`),
  # which the daemon could not evaluate.
  find_agents(if (is.list(target)) target$handler else target)
  capture <- capture_agent_states
  find <- find_agents
  fields <- agent_state_fields
  prices <- .prices$table
  mirai::mirai(
    {
      # Prices set with set_prices() live in the main process only.
      tryCatch({
        ns <- asNamespace("mini007")
        if (is.environment(ns$.prices)) ns$.prices$table <- prices
      }, error = function(e) NULL)

      handler <- if (is.list(target)) target$handler else target
      before <- tryCatch(capture(handler, find, character()), error = function(e) NULL)
      out <- tryCatch(
        list(value = run(target), error = NULL),
        error = function(e) list(value = NULL, error = conditionMessage(e))
      )
      out$states <- tryCatch(capture(handler, find, fields, before), error = function(e) list())
      out
    },
    target = target,
    run = run,
    capture = capture,
    find = find,
    fields = fields,
    prices = prices
  )
}

# Waits for the tasks, brings the agents' state back, and fails with every
# error at once. `handlers` is aligned with `tasks`; a task that is not a
# mirai (eg. a cached value) is returned as is.
collect_parallel <- function(tasks, handlers, what = "Parallel task") {
  values <- vector("list", length(tasks))
  names(values) <- names(tasks)
  errors <- character()
  seen <- character()
  repeated <- character()

  for (i in seq_along(tasks)) {
    task <- tasks[[i]]
    label <- if (!is.null(names(tasks)) && nzchar(names(tasks)[[i]])) names(tasks)[[i]] else as.character(i)
    if (!inherits(task, "mirai")) {
      values[[i]] <- task
      next
    }
    out <- task[]
    if (mirai::is_error_value(out) || !is.list(out)) {
      errors[[label]] <- one_line(paste(as.character(out), collapse = " "))
      next
    }
    ids <- apply_agent_states(out$states, handlers[[i]])
    repeated <- c(repeated, intersect(ids, seen))
    seen <- c(seen, ids)
    if (!is.null(out$error)) {
      errors[[label]] <- one_line(out$error)
    } else {
      values[i] <- list(out$value)
    }
  }

  if (length(repeated)) {
    cli::cli_alert_warning(paste(
      "The same agent ran in several parallel tasks; only the conversation",
      "of the last one was kept."
    ))
  }
  if (length(errors)) {
    cli::cli_abort(
      c(
        "{length(errors)} parallel {what}{?s} failed:",
        stats::setNames(paste0(names(errors), ": ", errors), rep("x", length(errors)))
      ),
      class = "mini007_parallel_error",
      call = NULL
    )
  }
  values
}

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.