R/Workflow.R

Defines functions read_checkpoint write_checkpoint

#' @importFrom mirai mirai daemons
#' @title Workflow
#'
#' @description
#' An R6 class for building sequential multi-agent pipelines. A `Workflow`
#' is composed of **Stations** (processing units - an `Agent`, a
#' `WorkflowAgent`, or any plain R function) connected by **Routes** (directed
#' links, optionally gated by a condition function). Execution is always
#' sequential: the output of one Station becomes the input of the next.
#'
#' Stations whose results have already been computed can be retrieved from an
#' internal cache instead of being re-executed, which is useful when iterating
#' on later parts of the pipeline without paying the cost (or latency) of
#' earlier LLM calls.
#'
#' A finished `Workflow` can be wrapped as a `WorkflowAgent` via
#' \code{$as_agent()}, making it composable with `LeadAgent` or embeddable as
#' a Station inside another `Workflow`.
#'
#' @export
Workflow <- R6::R6Class(
  "Workflow",
  cloneable = FALSE,

  # -- public -----------------------------------------------------------------
  public = list(

    #' @field name Workflow identifier.
    name = NULL,

    #' @field description Optional human-readable description.
    description = NULL,

    #' @field use_cache Whether to cache and reuse Station results.
    use_cache = NULL,

    #' @field cache Environment used as a hash-map for cached Station outputs.
    cache = NULL,

    #' @field run_history List of records from every \code{$run()} call.
    run_history = NULL,

    #' @field hitl_steps Integer vector of step numbers at which execution pauses
    #'   for human review. Set via \code{$set_hitl()}.
    hitl_steps = NULL,

    #' @field hitl_mode Either `"console"` (blocking \code{readline()} prompt,
    #'   the default) or `"pause"` (non-blocking: \code{$run()} returns a
    #'   `mini007_pending` object instead of blocking). Set via
    #'   \code{$set_hitl()}.
    hitl_mode = "console",

    #' @field n_daemons Number of parallel daemons. Set via \code{$set_daemons()}.
    n_daemons = NULL,

    # -- initialize ------------------------------------------------------------

    #' @description Create a new `Workflow`.
    #'
    #' @param name `[character(1)]` Workflow name.
    #' @param description `[character(1)]` Optional description.
    #' @param use_cache `[logical(1)]` Enable result caching (default `TRUE`).
    initialize = function(name, description = NULL, use_cache = TRUE) {
      checkmate::assert_string(name)
      checkmate::assert_flag(use_cache)
      if (!is.null(description)) checkmate::assert_string(description)

      self$name        <- name
      self$description <- description
      self$use_cache   <- use_cache
      self$cache       <- new.env(hash = TRUE, parent = emptyenv())
      self$run_history <- list()
      self$n_daemons   <- 0L
    },

    # -- add_station -----------------------------------------------------------

    #' @description Add a Station to the workflow.
    #'
    #' A Station is a named processing unit. Its `handler` can be:
    #' \itemize{
    #'   \item An `Agent` or `WorkflowAgent` - the Station calls
    #'         \code{handler$invoke(input)}.
    #'   \item A plain R \code{function(input)} - called directly; return value
    #'         is coerced to `character`.
    #' }
    #'
    #' @param name `[character(1)]` Unique Station name within this workflow.
    #' @param handler An `Agent`, `WorkflowAgent`, or `function`.
    #' @param description `[character(1)]` Optional human-readable description
    #'   (shown in \code{$visualize()}).
    #' @param max_retries `[integerish(1)]` Number of additional attempts after
    #'   the first failure (default `0`, i.e. no retries).
    #' @param retry_delay `[numeric(1)]` Seconds to wait between retry attempts
    #'   (default `1`).
    #' @param fallback `[function | NULL]` A \code{function(input, error)}
    #'   invoked when all retry attempts are exhausted. `NULL` re-raises the
    #'   last error.
    #'
    #' @return Invisibly returns `self` for method chaining.
    add_station = function(name, handler, description = NULL,
                           max_retries = 0, retry_delay = 1,
                           fallback = NULL) {
      checkmate::assert_string(name)
      if (!is.null(description)) checkmate::assert_string(description)
      checkmate::assert_integerish(max_retries, lower = 0L, len = 1L,
                                   any.missing = FALSE)
      checkmate::assert_number(retry_delay, lower = 0)
      if (!is.null(fallback) && !is.function(fallback)) {
        cli::cli_abort(
          "{.arg fallback} must be a {.cls function}(input, error) or {.val NULL}."
        )
      }

      is_agent    <- inherits(handler, "Agent") || inherits(handler, "WorkflowAgent")
      is_function <- is.function(handler)

      if (!is_agent && !is_function) {
        cli::cli_abort(c(
          "{.arg handler} must be an {.cls Agent}, {.cls WorkflowAgent}, or a {.cls function}.",
          "i" = "Received: {.cls {class(handler)[[1L]]}}."
        ))
      }

      if (name %in% names(private$.stations)) {
        cli::cli_abort("A Station named {.val {name}} already exists in workflow {.val {self$name}}.")
      }

      private$.stations[[name]] <- list(
        name        = name,
        handler     = handler,
        description = description,
        max_retries = as.integer(max_retries),
        retry_delay = retry_delay,
        fallback    = fallback
      )

      cli::cli_alert_success("Station {.val {name}} added.")
      invisible(self)
    },

    # -- add_route -------------------------------------------------------------

    #' @description Add a Route between two Stations.
    #'
    #' Routes define the execution order. An optional `condition` function
    #' receives the output of the `from` Station and must return `TRUE` or
    #' `FALSE`. Conditional routes are evaluated first (in insertion order);
    #' the first matching one is followed. If none match, the first
    #' unconditional route from that Station is used as a default.
    #'
    #' @param from `[character(1)]` Name of the source Station.
    #' @param to `[character(1)]` Name of the destination Station.
    #' @param condition `[function | NULL]` A function \code{function(output)}
    #'   returning a single logical value. `NULL` means "always follow this
    #'   route" (i.e., unconditional).
    #' @param label `[character(1) | NULL]` Optional text shown on the Route
    #'   in \code{$visualize()}. By default a conditional Route shows its
    #'   condition's code.
    #'
    #' @return Invisibly returns `self` for method chaining.
    add_route = function(from, to, condition = NULL, label = NULL) {
      checkmate::assert_string(from)
      checkmate::assert_string(to)
      checkmate::assert_string(label, null.ok = TRUE)

      if (!from %in% names(private$.stations)) {
        cli::cli_abort("Station {.val {from}} not found. Add it first with {.fn add_station}.")
      }
      if (!to %in% names(private$.stations)) {
        cli::cli_abort("Station {.val {to}} not found. Add it first with {.fn add_station}.")
      }
      if (!is.null(condition) && !is.function(condition)) {
        cli::cli_abort(
          "{.arg condition} must be a {.cls function} returning {.val TRUE}/{.val FALSE}, or {.val NULL}."
        )
      }

      private$.routes <- c(
        private$.routes,
        list(list(from = from, to = to, condition = condition, label = label))
      )

      cli::cli_alert_success("Route {.val {from}} -> {.val {to}} registered.")
      invisible(self)
    },

    # -- set_entry -------------------------------------------------------------

    #' @description Set the entry Station where execution begins.
    #'
    #' If not called, \code{$run()} defaults to the first Station added.
    #'
    #' @param station_name `[character(1)]` Name of the entry Station.
    #'
    #' @return Invisibly returns `self` for method chaining.
    set_entry = function(station_name) {
      checkmate::assert_string(station_name)

      if (!station_name %in% names(private$.stations)) {
        cli::cli_abort("Station {.val {station_name}} not found. Add it with {.fn add_station}.")
      }

      private$.entry <- station_name
      cli::cli_alert_success("Entry Station set to {.val {station_name}}.")
      invisible(self)
    },

    # -- validate --------------------------------------------------------------

    #' @description Check the workflow before running it.
    #'
    #' Looks at the Stations, Routes and parallel groups, without running
    #' anything or calling an LLM, and reports:
    #'
    #' - **errors**: loops the run can never leave, where every Route leads
    #'   back into the loop (the run would go on until the 500-step limit,
    #'   calling its agents each time), and a workflow without Stations.
    #'   \code{$run()} refuses to start when there is one.
    #' - **warnings**: Stations that never run because nothing leads to
    #'   them; Routes that are never followed (a second unconditional Route
    #'   from the same Station, the Routes of a Station that starts a
    #'   parallel group or only runs inside one); and a Station that
    #'   starts several parallel groups.
    #'
    #' Workflows wrapped with \code{$as_agent()} and used as Stations are
    #' checked too. Conditions on Routes are not run: a conditional Route
    #' counts as one the run may follow.
    #'
    #' @param quiet `[logical(1)]` If `TRUE`, nothing is printed.
    #' @return Invisibly, a data frame with one row per issue and the
    #'   columns `level` (`"error"` or `"warning"`), `check`, `stations`
    #'   and `message`. It has no rows when nothing was found.
    #' @examples
    #' wf <- Workflow$new("guide")
    #' wf$add_station("draft", function(x) paste("Draft about", x))
    #' wf$add_station("review", function(x) paste("Reviewed:", x))
    #' wf$add_station("translate", function(x) x)
    #' wf$add_route("draft", "review")
    #' wf$add_route("review", "draft")
    #' wf$validate()
    validate = function(quiet = FALSE) {
      checkmate::assert_flag(quiet)
      issues <- private$.issues()
      if (!quiet) print_workflow_issues(issues, self$name)
      invisible(issues)
    },

    # -- run -------------------------------------------------------------------

    #' @description Execute the workflow sequentially.
    #'
    #' The `input` string is passed to the entry Station. Each Station's
    #' output becomes the next Station's input. Execution stops when a Station
    #' has no outgoing Route (or no Route whose condition evaluates to `TRUE`).
    #'
    #' When \code{use_cache = TRUE}, a Station whose (name, input) pair has
    #' been seen before returns the cached output without re-invoking the
    #' handler. Use \code{$clear_cache()} to force re-execution.
    #'
    #' With \code{stream = TRUE} (or an `on_event` callback), progress is
    #' delivered as `mini007_event` objects while the workflow executes:
    #' station start/completion, retries, fallbacks, HITL requests, the final
    #' output, and the token deltas of every Agent Station (see
    #' \code{\link{mini007_event}}).
    #'
    #' @param input `[character(1)]` The initial prompt / payload.
    #' @param stream `[logical(1)]` Whether to stream progress. Without
    #'   `on_event`, Agent token deltas are printed to the console.
    #' @param on_event `[function | NULL]` Callback receiving each
    #'   `mini007_event`. Supplying it implies \code{stream = TRUE}. Raising an
    #'   error inside it cancels the run.
    #' @param checkpoint `[character(1) | NULL]` A file (eg. `"run.rds"`)
    #'   where the run is saved after every step, so that it can go on after
    #'   a failure, an interruption or a restart of R instead of starting
    #'   over. When the file holds an unfinished run of this workflow with
    #'   the same `input`, \code{$run()} picks it up where it stopped: the
    #'   Stations already done are not run again. See
    #'   \code{$resume_from()}. `NULL` (the default) saves nothing.
    #'
    #' @return `[character(1)]` The output of the last Station executed, or -
    #'   if execution reaches an HITL step while \code{hitl_mode = "pause"} -
    #'   a `mini007_pending` object. Use \code{\link{is_pending}()} to check.
    run = function(input, stream = FALSE, on_event = NULL, checkpoint = NULL) {
      checkmate::assert_string(input)
      checkmate::assert_string(checkpoint, null.ok = TRUE)
      on_event <- resolve_on_event(stream, on_event)

      if (length(private$.stations) == 0L) {
        cli::cli_abort("No Stations defined. Use {.fn add_station} first.")
      }

      # Refuse a run that could never end, before any agent is called.
      issues <- private$.issues()
      errors <- issues[issues$level == "error", , drop = FALSE]
      if (nrow(errors)) {
        cli::cli_abort(c(
          "Workflow {.val {self$name}} cannot run:",
          stats::setNames(cli_escape(errors$message), rep("x", nrow(errors))),
          "i" = "Call {.code $validate()} to see every issue."
        ), class = "mini007_invalid_workflow", call = NULL)
      }

      entry <- if (!is.null(private$.entry)) {
        private$.entry
      } else {
        names(private$.stations)[[1L]]
      }

      if (is.null(private$.entry)) {
        cli::cli_alert_info(
          "No entry Station set - defaulting to first Station: {.val {entry}}."
        )
      }

      if (!is.null(checkpoint) && file.exists(checkpoint)) {
        saved <- read_checkpoint(checkpoint)
        if (identical(saved$workflow, self$name) && !identical(saved$status, "complete") &&
            identical(saved$state$original_input, input)) {
          cli::cli_alert_info(
            "Picking up the unfinished run saved in {.file {checkpoint}} (after step {saved$state$steps_taken})."
          )
          return(private$.continue_checkpoint(saved, checkpoint, NULL, NULL, on_event))
        }
      }

      cli::cli_rule(left = glue::glue("Workflow: {self$name}"))

      emit_event(on_event, new_event(
        "workflow_started", self$name, input = input, entry = entry
      ))

      state <- list(
        current        = entry,
        current_input  = input,
        original_input = input,
        trace          = list(),
        steps_taken    = 0L
      )
      if (!is.null(checkpoint)) private$.save_checkpoint(checkpoint, "running", state)

      private$.execute(state, on_event = on_event, checkpoint = checkpoint)
    },

    # -- resume_from -------------------------------------------------------

    #' @description Go on with a run saved in a checkpoint file.
    #'
    #' A run started with \code{$run(input, checkpoint = "run.rds")} is saved
    #' after every step. If it failed, was interrupted or R was restarted,
    #' rebuild the workflow (with the same Stations), then call
    #' \code{$resume_from("run.rds")}: the run goes on from the first Station
    #' that did not finish, with the output of the last one that did. The
    #' Stations' agents start with the conversation they have in this
    #' session, not the one they had before the restart.
    #'
    #' A run paused at an HITL step (\code{hitl_mode = "pause"}) is saved
    #' too: give `action` (and `value`) to answer it, as with
    #' \code{$resume()}; without `action`, the pending request is returned
    #' again.
    #'
    #' @param checkpoint `[character(1)]` The checkpoint file.
    #' @param action `[character(1) | NULL]` For a run paused at an HITL step:
    #'   `"continue"`, `"edit"` or `"abort"`, as in \code{$resume()}.
    #' @param value `[character(1) | NULL]` With \code{action = "edit"}: the
    #'   replacement output.
    #' @param stream `[logical(1)]` Whether to stream the rest of the run.
    #' @param on_event `[function | NULL]` Callback receiving each
    #'   `mini007_event`. Supplying it implies \code{stream = TRUE}.
    #'
    #' @return The output of the run (for a run that had already finished,
    #'   the saved output), or a `mini007_pending` object.
    #' @examples
    #' wf <- Workflow$new("guide")
    #' wf$add_station("draft", function(x) paste("Draft about", x))
    #' wf$add_station("polish", function(x) paste("Polished:", x))
    #' wf$add_route("draft", "polish")
    #' checkpoint <- tempfile(fileext = ".rds")
    #' wf$run("Tlemcen", checkpoint = checkpoint)
    #' wf$resume_from(checkpoint)
    resume_from = function(checkpoint, action = NULL, value = NULL,
                           stream = FALSE, on_event = NULL) {
      checkmate::assert_string(checkpoint)
      if (!is.null(action)) action <- match.arg(action, c("continue", "edit", "abort"))
      if (identical(action, "edit")) checkmate::assert_string(value)
      on_event <- resolve_on_event(stream, on_event)

      if (!file.exists(checkpoint)) {
        cli::cli_abort("There is no checkpoint file {.file {checkpoint}}.")
      }
      saved <- read_checkpoint(checkpoint)
      if (!identical(saved$workflow, self$name)) {
        cli::cli_abort(c(
          "The checkpoint {.file {checkpoint}} is a run of workflow {.val {saved$workflow}}, not {.val {self$name}}."
        ))
      }
      if (identical(saved$status, "complete")) {
        cli::cli_alert_info("The run saved in {.file {checkpoint}} is already complete.")
        return(saved$output)
      }
      private$.continue_checkpoint(saved, checkpoint, action, value, on_event)
    },

    # -- resume ------------------------------------------------------------

    #' @description Resume a Workflow paused at an HITL step.
    #'
    #' Only relevant when \code{hitl_mode = "pause"} (see \code{$set_hitl()}).
    #' \code{$run()} returns a `mini007_pending` object when it reaches a
    #' paused HITL step; call \code{$resume()} with that object's
    #' `request_id` and a chosen `action` to continue execution from that
    #' point.
    #'
    #' @param request_id `[character(1)]` The `request_id` from the
    #'   `mini007_pending` object returned by \code{$run()}.
    #' @param action `[character(1)]` One of `"continue"` (use the proposed
    #'   output as-is), `"edit"` (replace it with `value`), or `"abort"`
    #'   (raise an error, stopping the workflow).
    #' @param value `[character(1) | NULL]` Required when
    #'   \code{action = "edit"}: the replacement output.
    #' @param stream `[logical(1)]` Whether to stream the remaining execution
    #'   (see \code{$run()}).
    #' @param on_event `[function | NULL]` Callback receiving each
    #'   `mini007_event`. Supplying it implies \code{stream = TRUE}.
    #'
    #' @return `[character(1)]` The final output, or another `mini007_pending`
    #'   object if a further HITL step is reached.
    resume = function(request_id, action = c("continue", "edit", "abort"), value = NULL,
                      stream = FALSE, on_event = NULL) {
      checkmate::assert_string(request_id)
      action <- match.arg(action)
      if (identical(action, "edit")) checkmate::assert_string(value)
      on_event <- resolve_on_event(stream, on_event)

      pending <- private$.pending[[request_id]]
      if (is.null(pending)) {
        cli::cli_abort(
          "No pending HITL request found with id {.val {request_id}} on workflow {.val {self$name}}."
        )
      }
      private$.pending[[request_id]] <- NULL

      private$.execute(
        pending$state,
        resume_response = list(action = action, value = value),
        on_event = on_event,
        checkpoint = pending$checkpoint
      )
    },

    # -- set_daemons -----------------------------------------------------------

    #' @description Configure parallel execution daemons using mirai.
    #'
    #' Sets up persistent daemon processes for parallel station execution.
    #' When `n > 0`, daemons are created via \code{mirai::daemons()}.
    #' Call with `n = 0` to shut down all daemons.
    #'
    #' The daemons belong to the R session: every `Workflow` and `LeadAgent`
    #' shares the same pool, and the last call sets its size. Each parallel
    #' station runs on a copy of its agents; once it finishes, their
    #' conversation, cost and traces are copied back to the original agents
    #' (also for agents that a function handler, a `LeadAgent` or a wrapped
    #' `Workflow` runs). A station that fails makes the workflow fail, with
    #' the errors of every failed station.
    #'
    #' @param n `[integerish(1)]` Number of daemon processes (default `0`).
    #'   Use number of cores for optimal CPU parallelism.
    #'
    #' @return Invisibly returns `self` for method chaining.
    set_daemons = function(n = 0L) {
      checkmate::assert_integerish(n, lower = 0L, len = 1L, any.missing = FALSE)
      n <- as.integer(n)

      before <- running_daemons()
      configure_daemons(n)
      self$n_daemons <- n
      if (n == 0L) {
        if (before > 0L) cli::cli_alert_success("Parallel daemons shut down.")
      } else if (before == 0L) {
        cli::cli_alert_success("Parallel daemons initialized: {n} worker(s).")
      } else if (before != n) {
        cli::cli_alert_success("Parallel daemons resized to {n} worker(s).")
      }

      invisible(self)
    },

    # -- add_parallel_group ----------------------------------------------------

    #' @description Define a group of Stations to execute in parallel.
    #'
    #' All specified Stations receive the same input and execute concurrently
    #' via mirai daemons. Their outputs are collected and merged by the
    #' `merge_fn` before passing to the next Station(s).
    #'
    #' Requires `$set_daemons(n > 0)` to be called first.
    #'
    #' @param from `[character(1)]` Name of the predecessor Station whose
    #'   output feeds into the parallel group. It runs first, in the same
    #'   step as the group (so a HITL pause at that step reviews the group's
    #'   merged result), and its own Routes are not followed: the run goes on
    #'   to `to`.
    #' @param stations `[character]` Names of Stations to run in parallel.
    #'   All must exist and not be the `from` Station.
    #' @param to `[character(1)]` Name of the successor Station that receives
    #'   the merged result (optional).
    #' @param merge_fn `[function]` A function \code{function(results)} that
    #'   takes a named list of results (names are station names) and returns
    #'   a single character string. Default concatenates results with newlines.
    #'
    #' @return Invisibly returns `self` for method chaining.
    add_parallel_group = function(from, stations, to = NULL,
                                   merge_fn = NULL) {
      checkmate::assert_string(from)
      checkmate::assert_character(stations, min.len = 1L)
      if (!is.null(to)) checkmate::assert_string(to)
      if (!is.null(merge_fn) && !is.function(merge_fn)) {
        cli::cli_abort("{.arg merge_fn} must be a {.cls function} or {.val NULL}.")
      }

      if (!from %in% names(private$.stations)) {
        cli::cli_abort("Station {.val {from}} not found.")
      }
      for (s in stations) {
        if (!s %in% names(private$.stations)) {
          cli::cli_abort("Station {.val {s}} not found.")
        }
        if (s == from) {
          cli::cli_abort("Parallel stations cannot include the predecessor {.val {from}}.")
        }
      }
      if (!is.null(to) && !to %in% names(private$.stations)) {
        cli::cli_abort("Successor Station {.val {to}} not found.")
      }

      if (is.null(merge_fn)) {
        merge_fn <- function(results) {
          paste(unlist(results), collapse = "\n")
        }
      }

      private$.parallel_groups <- c(
        private$.parallel_groups,
        list(list(from = from, stations = stations, to = to, merge_fn = merge_fn))
      )

      cli::cli_alert_success(
        "Parallel group registered: {.val {from}} -> {.str {stations}} {if (!is.null(to)) paste0('-> ', to)}"
      )
      invisible(self)
    },

    # -- set_hitl --------------------------------------------------------------

    #' @description Set Human-In-The-Loop (HITL) pause points.
    #'
    #' When execution reaches a step whose number is listed in `steps`, it
    #' pauses and presents the human with three choices:
    #' \enumerate{
    #'   \item Continue with the Station's original output.
    #'   \item Edit the output manually before the next Station receives it.
    #'   \item Stop the workflow immediately (raises an error).
    #' }
    #' HITL only fires on fresh Station executions - cache hits are skipped.
    #' Steps are numbered from 1 in execution order, matching the step counter
    #' shown in \code{$run()} output. You can set multiple steps at once:
    #' \code{wf$set_hitl(c(1, 3))}.
    #'
    #' With \code{mode = "console"} (default), a paused step blocks on
    #' \code{readline()} right there in \code{$run()} - unchanged from
    #' previous behavior. With \code{mode = "pause"}, \code{$run()} instead
    #' returns immediately with a `mini007_pending` object describing the
    #' paused step; call \code{$resume()} with the chosen action to continue.
    #' This allows HITL to work outside an interactive console (e.g. Shiny,
    #' Plumber, or a batch job resuming later) and lets workflow state be
    #' inspected/persisted between steps.
    #'
    #' @param steps `[integerish]` One or more step numbers (>= 1).
    #' @param mode `[character(1)]` `"console"` (default) or `"pause"`.
    #'
    #' @return Invisibly returns `self` for method chaining.
    set_hitl = function(steps, mode = c("console", "pause")) {
      checkmate::assert_integerish(steps, lower = 1L, any.missing = FALSE)
      mode <- match.arg(mode)
      self$hitl_steps <- unique(as.integer(steps))
      self$hitl_mode  <- mode
      cli::cli_alert_success(
        "HITL enabled at step(s): {.val {toString(self$hitl_steps)}} (mode: {.val {mode}})."
      )
      invisible(self)
    },

    # -- clear_cache -----------------------------------------------------------

    #' @description Remove all cached Station results.
    #'
    #' @return Invisibly returns `self`.
    clear_cache = function() {
      cached <- ls(self$cache)
      if (length(cached) > 0L) rm(list = cached, envir = self$cache)
      cli::cli_alert_success("Cache cleared for workflow {.val {self$name}}.")
      invisible(self)
    },

    # -- as_agent --------------------------------------------------------------

    #' @description Wrap this Workflow as a `WorkflowAgent`.
    #'
    #' The returned `WorkflowAgent` exposes \code{$invoke(prompt)} and holds an
    #' `agent_id`, making it compatible with `LeadAgent$register_agents()` and
    #' usable as a Station handler inside another `Workflow`.
    #'
    #' @param name `[character(1)]` Name for the `WorkflowAgent`. Defaults to
    #'   \code{"\{workflow name\} (agent)"}.
    #' @param instruction `[character(1)]` Instruction string describing the
    #'   agent's role. Used by `LeadAgent` for task-agent matching.
    #'
    #' @return A `WorkflowAgent` object.
    as_agent = function(name = NULL, instruction = NULL) {
      agent_name <- if (!is.null(name)) {
        name
      } else {
        paste0(self$name, " (agent)")
      }

      agent_instruction <- if (!is.null(instruction)) {
        instruction
      } else {
        desc_part <- if (!is.null(self$description) && nchar(self$description) > 0L) {
          paste0(" ", self$description, ".")
        } else {
          ""
        }
        paste0(
          "You are a workflow agent named '", self$name, "'.",
          desc_part,
          " When invoked with a prompt, you run a sequential pipeline of",
          " specialized Stations and return the final result."
        )
      }

      wa <- WorkflowAgent$new(
        name        = agent_name,
        instruction = agent_instruction,
        workflow    = self
      )

      cli::cli_alert_success(
        "Workflow {.val {self$name}} wrapped as agent {.val {agent_name}}."
      )

      wa
    },

    # -- visualize -------------------------------------------------------------

    #' @description Draw the workflow as a graph.
    #'
    #' Each Station is a card showing its name, what runs it (an Agent and its
    #' model, a wrapped Workflow, or a function), its description, and its
    #' retries and fallback. The graph follows the rules of \code{$run()}:
    #'
    #' - **Start** leads to the entry Station, and **End** is reached from
    #'   every Station where the run can stop.
    #' - Conditional Routes are dashed and labelled with the condition's code
    #'   (or the `label` given to \code{$add_route()}); the Route taken when
    #'   no condition matches is labelled "otherwise".
    #' - Parallel groups are drawn in a box, and their results meet at a
    #'   merge point before going on.
    #' - The issues \code{$validate()} reports are shown: Stations that never
    #'   run are faded, loops the run can never leave are red, and Routes
    #'   that are never followed are dotted and labelled "ignored".
    #'
    #' Hover over a Station to see its description and, for an Agent, its
    #' instruction.
    #'
    #' @param direction `[character(1)]` `"LR"` (left to right, the default)
    #'   or `"TB"` (top to bottom).
    #' @return A `grViz` htmlwidget. Its DOT code is in `$x$diagram`.
    #' @examples
    #' wf <- Workflow$new("casbah_guide")
    #' wf$add_station("draft", function(x) paste("A guide to", x),
    #'                description = "Draft a guide to the Casbah")
    #' wf$add_station("review", function(x) x)
    #' wf$add_station("translate", function(x) x)
    #' wf$add_route("draft", "review")
    #' wf$add_route("review", "draft", condition = function(x) grepl("TODO", x))
    #' wf$add_route("review", "translate")
    #' wf$visualize()
    visualize = function(direction = c("LR", "TB")) {
      direction <- match.arg(direction)
      if (length(private$.stations) == 0L) {
        cli::cli_abort("Nothing to visualize - no Stations have been added.")
      }
      DiagrammeR::grViz(workflow_dot(
        private$.stations, private$.routes, private$.parallel_groups, private$.entry,
        name = self$name, description = self$description, direction = direction
      ), allow_subst = FALSE)
    }
  ),

  # -- private ----------------------------------------------------------------
  private = list(
    # The issues $validate() reports.
    .issues = function() {
      workflow_issues(
        private$.stations, private$.routes, private$.parallel_groups, private$.entry
      )
    },

    .stations         = list(),
    .routes           = list(),
    .entry            = NULL,
    .parallel_groups  = list(),
    .pending          = list(),

    # Saves the run to the checkpoint file: its status ("running",
    # "awaiting_input", "complete" or "failed") and its state. The state is
    # plain data: a parallel group is saved as the name of the Station it
    # starts from, never as the group itself, whose merge function could
    # carry agents (and their credentials) with it.
    .save_checkpoint = function(path, status, state, output = NULL,
                                error = NULL, pending = NULL) {
      if (is.list(state$context) && identical(state$context$kind, "parallel")) {
        state$context <- list(
          kind = "parallel", from = state$context$parallel_group$from,
          group_input = state$context$group_input
        )
      }
      write_checkpoint(path, structure(list(
        workflow = self$name, status = status, state = state,
        output = output, error = error, pending = pending,
        saved_at = Sys.time(),
        mini007 = as.character(utils::packageVersion("mini007"))
      ), class = "mini007_checkpoint"))
    },

    # Goes on with a saved run: answers its HITL request, gives the request
    # back, or runs on from the first Station that did not finish.
    .continue_checkpoint = function(saved, checkpoint, action, value, on_event) {
      state <- saved$state
      missing_stations <- setdiff(
        c(state$current, vapply(state$trace, function(t) t$station, character(1))),
        c(names(private$.stations), "parallel_group")
      )
      if (length(missing_stations)) {
        cli::cli_abort(c(
          "The checkpoint {.file {checkpoint}} does not match workflow {.val {self$name}}.",
          "x" = "Unknown Station{?s}: {.val {missing_stations}}."
        ))
      }
      if (is.list(state$context) && identical(state$context$kind, "parallel")) {
        state$context$parallel_group <- private$.find_parallel_group(state$context$from)
      }

      if (identical(saved$status, "awaiting_input")) {
        pending <- saved$pending
        private$.pending[[pending$request_id]] <- list(state = state, checkpoint = checkpoint)
        if (is.null(action)) {
          cli::cli_alert_info("The saved run is waiting for a human's answer at step {pending$step}.")
          return(pending)
        }
        return(self$resume(pending$request_id, action = action, value = value,
                           on_event = on_event))
      }

      if (!is.null(saved$error)) {
        cli::cli_alert_info("The saved run had stopped: {saved$error}")
      }
      cli::cli_rule(left = glue::glue("Workflow: {self$name} (resumed after step {state$steps_taken})"))
      emit_event(on_event, new_event(
        "workflow_resumed", self$name, step = state$steps_taken, station = state$current
      ))
      private$.execute(state, on_event = on_event, checkpoint = checkpoint)
    },

    # Resolve the next Station given the current one and its output.
    # Conditional Routes are tried first (in insertion order); the first
    # whose condition returns TRUE wins. If none match, the first
    # unconditional Route is used as default. Returns NULL if the workflow
    # should stop.
    .get_next_station = function(current, result) {
      from_here <- Filter(function(r) r$from == current, private$.routes)

      if (length(from_here) == 0L) return(NULL)

      cond_routes   <- Filter(function(r) !is.null(r$condition), from_here)
      uncond_routes <- Filter(function(r)  is.null(r$condition), from_here)

      for (route in cond_routes) {
        ok <- tryCatch(
          isTRUE(route$condition(result)),
          error = function(e) {
            cli::cli_alert_warning(
              "Condition on route {.val {route$from}} -> {.val {route$to}} errored: {e$message}"
            )
            FALSE
          }
        )
        if (ok) return(route$to)
      }

      if (length(uncond_routes) > 0L) return(uncond_routes[[1L]]$to)

      NULL
    },

    # Dispatch a handler call: Agent/WorkflowAgent use $invoke(); plain
    # functions are called directly and their output coerced to character.
    # `on_event` is forwarded to agents that support streaming.
    .invoke_handler = function(handler, input, on_event = NULL) {
      if (inherits(handler, c("Agent", "WorkflowAgent"))) {
        invoke_with_events(handler, input, on_event)
      } else {
        out <- handler(input)
        if (!is.character(out)) as.character(out) else out
      }
    },

    # Invoke a station handler with retry and fallback support.
    # Wraps .invoke_handler, retrying up to max_retries additional times with
    # retry_delay seconds between attempts. If all attempts fail and a fallback
    # is defined, calls fallback(input, error); otherwise re-raises the last error.
    # A cancellation raised by `on_event` is never retried nor sent to the
    # fallback - it propagates immediately.
    # Runs one Station (or takes its output from the cache), with its
    # retries and fallback, and emits its start and completion events.
    # Returns list(result, cache_key, from_cache); caching the result is
    # left to the caller, after any HITL review.
    .run_station = function(name, input, step, on_event = NULL) {
      station   <- private$.stations[[name]]
      cache_key <- private$.cache_key(name, input)
      from_cache <- self$use_cache &&
        exists(cache_key, envir = self$cache, inherits = FALSE)

      emit_event(on_event, new_event(
        "station_started", self$name,
        station = name, step = step, input = input
      ))

      if (from_cache) {
        cli::cli_alert_info("[cache] Station {.val {name}}.")
        result <- get(cache_key, envir = self$cache, inherits = FALSE)
      } else {
        cli::cli_text("  {cli::col_blue('->')} Station {.val {name}}")
        result <- private$.invoke_handler_safe(
          station, input,
          on_event = forward_events(on_event, station = name, step = step)
        )
      }

      emit_event(on_event, new_event(
        "station_completed", self$name, text = result,
        station = name, step = step, from_cache = from_cache
      ))

      list(result = result, cache_key = cache_key, from_cache = from_cache)
    },

    .invoke_handler_safe = function(station, input, on_event = NULL) {
      max_retries <- station$max_retries
      retry_delay <- station$retry_delay
      fallback    <- station$fallback

      last_err <- NULL

      for (attempt in seq_len(max_retries + 1L)) {
        out <- tryCatch(
          list(ok = TRUE,
               value = private$.invoke_handler(station$handler, input, on_event)),
          error = function(e) {
            if (inherits(e, "mini007_stream_cancelled")) stop(e)
            list(ok = FALSE, error = e)
          }
        )

        if (isTRUE(out$ok)) return(out$value)

        last_err <- out$error

        if (attempt <= max_retries) {
          cli::cli_alert_warning(
            "Station {.val {station$name}} failed (attempt {attempt}/{max_retries + 1L}): {last_err$message}. Retrying in {retry_delay}s."
          )
          emit_event(on_event, new_event(
            "station_retry", self$name,
            attempt = attempt, max_attempts = max_retries + 1L,
            error = conditionMessage(last_err)
          ))
          Sys.sleep(retry_delay)
        }
      }

      if (!is.null(fallback)) {
        cli::cli_alert_warning(
          "Station {.val {station$name}}: all {max_retries + 1L} attempt(s) failed. Invoking fallback."
        )
        emit_event(on_event, new_event(
          "station_fallback", self$name, error = conditionMessage(last_err)
        ))
        return(fallback(input, last_err))
      }

      stop(last_err)
    },

    # Pause execution, show the station's input and output, then ask the human
    # what to do. Returns the result to continue with (original or edited).
    .human_confirm = function(step_index, station_name, input, result) {
      cli::cli_rule(left = glue::glue("HITL - Step {step_index}"))
      cli::cli_text("Station: {.strong {station_name}}")
      cli::cli_alert_info("Input:")
      cli::cli_verbatim(input)
      cli::cli_alert_info("Output:")
      cli::cli_verbatim(result)

      cli::cli_text(cli::cli_ul(c(
        "[1] Continue with this output",
        "[2] Edit the output",
        "[3] Stop the workflow"
      )))

      repeat {
        answer <- readline("Your choice [1/2/3]: ")
        if (nzchar(answer) && answer %in% c("1", "2", "3")) break
        cli::cli_alert_warning("Invalid input. Please enter 1, 2, or 3.")
      }

      if (answer == "2") {
        new_result <- readline("(->) Enter edited output: ")
        cli::cli_alert_success("Output updated.")
        return(new_result)
      } else if (answer == "3") {
        cli::cli_alert_danger("Workflow stopped by user at step {step_index}.")
        cli::cli_abort("HITL: Execution stopped by user.")
      } else {
        cli::cli_alert_success("Continuing with original output.")
        return(result)
      }
    },

    # Resolve an HITL pause point. In "console" mode this blocks on
    # readline() via .human_confirm() exactly as before. In "pause" mode it
    # instead throws a `mini007_workflow_pause` condition carrying everything
    # needed to resume later; .execute() catches it and returns a
    # mini007_pending object to the caller instead of blocking.
    .request_confirmation = function(step_index, station_name, input, proposed_result, state_snapshot) {
      if (identical(self$hitl_mode, "pause")) {
        request_id <- uuid::UUIDgenerate()
        state_snapshot$proposed_result <- proposed_result

        private$.pending[[request_id]] <- list(state = state_snapshot)

        pending_obj <- new_pending(
          request_id      = request_id,
          step            = step_index,
          station         = station_name,
          input           = input,
          proposed_output = proposed_result
        )

        cond <- structure(
          class   = c("mini007_workflow_pause", "condition"),
          list(
            message = glue::glue(
              "Workflow '{self$name}' paused at step {step_index} awaiting human input."
            ),
            pending = pending_obj
          )
        )
        stop(cond)
      }

      private$.human_confirm(step_index, station_name, input, proposed_result)
    },

    # Turn a $resume() response into the result to continue with.
    .apply_response = function(response, proposed_result, step_index) {
      if (identical(response$action, "abort")) {
        cli::cli_alert_danger("Workflow stopped by user at step {step_index}.")
        cli::cli_abort("HITL: Execution stopped by user.")
      } else if (identical(response$action, "edit")) {
        cli::cli_alert_success("Output updated.")
        return(response$value)
      }

      cli::cli_alert_success("Continuing with original output.")
      proposed_result
    },

    # Build a deterministic cache key from a Station name and its input.
    # The fixed separator is unlikely to appear in normal station names or prompts.
    .cache_key = function(station_name, input) {
      paste0(station_name, "|||", substr(input, 1L, 1024L))
    },

    # Find a parallel group that starts from the given station.
    # Returns the group definition or NULL if none exists.
    .find_parallel_group = function(station_name) {
      for (group in private$.parallel_groups) {
        if (group$from == station_name) return(group)
      }
      NULL
    },

    # Execute a parallel group of stations using mirai.
    # All stations in the group receive the same input and run concurrently.
    # Results are merged and returned (HITL confirmation, if any, happens in
    # the caller so it can be paused/resumed uniformly with regular stations).
    # `on_event` is only ever called from this (main) process: it is never
    # shipped to the mirai daemons, so parallel stations emit start/completion
    # events but no token deltas.
    .execute_parallel_group_compute = function(group, input, step = NA_integer_,
                                               on_event = NULL) {
      station_names <- group$stations

      cli::cli_text("{cli::col_cyan('\u250c Parallel Group')} ({length(station_names)} station{?s})")

      from_cache <- vapply(station_names, function(name) {
        self$use_cache &&
          exists(private$.cache_key(name, input), envir = self$cache, inherits = FALSE)
      }, logical(1))

      tasks <- lapply(station_names, function(name) {
        station <- private$.stations[[name]]
        cache_key <- private$.cache_key(name, input)

        emit_event(on_event, new_event(
          "station_started", self$name,
          station = name, step = step, input = input, parallel = TRUE
        ))

        if (from_cache[[name]]) {
          cli::cli_alert_info("[cache] Parallel station {.val {name}}.")
          return(get(cache_key, envir = self$cache, inherits = FALSE))
        }

        cli::cli_text("  {cli::col_blue('\u2192')} {name}")

        # The daemon gets a copy of the station: its agents' conversation,
        # cost and traces are copied back by collect_parallel().
        parallel_task(station, function(station) private$.invoke_handler_safe(station, input))
      })

      names(tasks) <- station_names

      cli::cli_alert_info("Waiting for {length(station_names)} parallel task{?s}...")

      handlers <- lapply(station_names, function(name) private$.stations[[name]]$handler)
      results <- tryCatch(
        collect_parallel(tasks, handlers, what = "station"),
        error = function(e) {
          cli::cli_alert_danger("Parallel execution failed: {conditionMessage(e)}")
          stop(e)
        }
      )

      cli::cli_text("{cli::col_cyan('\u2514 Parallel Group')} complete.")

      for (name in station_names) {
        emit_event(on_event, new_event(
          "station_completed", self$name, text = results[[name]],
          station = name, step = step, from_cache = from_cache[[name]],
          parallel = TRUE
        ))
      }

      if (self$use_cache) {
        for (name in station_names) {
          cache_key <- private$.cache_key(name, input)
          assign(cache_key, results[[name]], envir = self$cache)
        }
      }

      group$merge_fn(results)
    },

    # The resumable execution loop shared by $run() and $resume(). `state`
    # holds the loop's mutable variables (current station, its input, the
    # trace so far, step counter, and the original input for run_history).
    # On a fresh $run() call, `resume_response` is NULL and the loop starts
    # by computing the current step from scratch. On $resume(), `state` is a
    # snapshot captured right before the paused step's HITL confirmation, and
    # `resume_response` is applied instead of recomputing that step.
    # `on_event` is the streaming callback of the current $run()/$resume()
    # call (NULL when not streaming); it is deliberately not part of `state`
    # so a resumed run streams to the callback given to $resume().
    .execute = function(state, resume_response = NULL, on_event = NULL,
                        checkpoint = NULL) {
      # What the checkpoint holds: the state after the last finished step.
      last_state <- state[c("current", "current_input", "original_input", "trace", "steps_taken")]
      current        <- state$current
      current_input  <- state$current_input
      original_input <- state$original_input
      trace          <- state$trace
      steps_taken    <- state$steps_taken
      max_steps      <- 500L

      first_iteration <- TRUE
      result          <- NULL

      pause_result <- tryCatch(withCallingHandlers({
        repeat {
          if (first_iteration && !is.null(resume_response)) {
            context <- state$context
            result  <- private$.apply_response(
              resume_response, state$proposed_result, steps_taken
            )
          } else {
            steps_taken <- steps_taken + 1L

            if (steps_taken > max_steps) {
              cli::cli_abort(
                "Workflow exceeded {max_steps} steps. Possible cycle in Routes."
              )
            }

            parallel_group <- private$.find_parallel_group(current)

            if (!is.null(parallel_group)) {
              # The Station the group starts from runs first, in the same
              # step, and the group gets its output.
              start <- private$.run_station(current, current_input, steps_taken, on_event)
              if (!start$from_cache && self$use_cache) {
                assign(start$cache_key, start$result, envir = self$cache)
              }
              trace[[length(trace) + 1L]] <- list(
                step    = steps_taken,
                station = current,
                input   = current_input,
                output  = start$result
              )
              group_input <- start$result
              proposed_result <- private$.execute_parallel_group_compute(
                parallel_group, group_input,
                step = steps_taken, on_event = on_event
              )
              context <- list(
                kind = "parallel", parallel_group = parallel_group,
                group_input = group_input
              )
              station_label <- "parallel_group"
            } else {
              ran <- private$.run_station(current, current_input, steps_taken, on_event)
              proposed_result <- ran$result
              context <- list(
                kind = "station", cache_key = ran$cache_key, from_cache = ran$from_cache
              )
              station_label <- current
            }

            needs_hitl <- !is.null(self$hitl_steps) &&
              steps_taken %in% self$hitl_steps &&
              !(context$kind == "station" && context$from_cache)

            if (needs_hitl) {
              state_snapshot <- list(
                current = current, current_input = current_input,
                original_input = original_input, trace = trace,
                steps_taken = steps_taken, context = context
              )
              result <- private$.request_confirmation(
                steps_taken, station_label,
                if (context$kind == "parallel") context$group_input %||% current_input else current_input,
                proposed_result, state_snapshot
              )
            } else {
              result <- proposed_result
            }
          }

          first_iteration <- FALSE

          if (context$kind == "station" && !context$from_cache && self$use_cache) {
            assign(context$cache_key, result, envir = self$cache)
          }

          next_station <- if (context$kind == "parallel") {
            context$parallel_group$to
          } else {
            private$.get_next_station(current, result)
          }

          trace[[length(trace) + 1L]] <- list(
            step    = steps_taken,
            station = if (context$kind == "parallel") "parallel_group" else current,
            input   = if (context$kind == "parallel") context$group_input %||% current_input else current_input,
            output  = result
          )

          last_state <- list(
            current = next_station, current_input = result,
            original_input = original_input, trace = trace,
            steps_taken = steps_taken
          )
          if (!is.null(checkpoint)) {
            private$.save_checkpoint(
              checkpoint, if (is.null(next_station)) "complete" else "running",
              last_state, output = if (is.null(next_station)) result
            )
          }

          if (is.null(next_station)) break

          current       <- next_station
          current_input <- result
        }

        list(status = "complete")
      }, error = function(e) {
        if (!is.null(checkpoint)) {
          try(private$.save_checkpoint(
            checkpoint, "failed", last_state, error = conditionMessage(e)
          ), silent = TRUE)
        }
        if (!inherits(e, "mini007_stream_cancelled")) {
          emit_event(on_event, new_event(
            "workflow_failed", self$name,
            error = conditionMessage(e), step = steps_taken
          ))
        }
      }, interrupt = function(e) {
        if (!is.null(checkpoint)) {
          try(private$.save_checkpoint(checkpoint, "failed", last_state,
                                       error = "Interrupted."), silent = TRUE)
        }
      }), mini007_workflow_pause = function(e) {
        id <- e$pending$request_id
        private$.pending[[id]]$checkpoint <- checkpoint
        if (!is.null(checkpoint)) {
          private$.save_checkpoint(
            checkpoint, "awaiting_input", private$.pending[[id]]$state,
            pending = e$pending
          )
        }
        list(status = "awaiting_input", pending = e$pending)
      })

      if (identical(pause_result$status, "awaiting_input")) {
        emit_event(on_event, new_event(
          "hitl_request", self$name,
          pending = pause_result$pending,
          station = pause_result$pending$station,
          step = pause_result$pending$step
        ))
        return(pause_result$pending)
      }

      cli::cli_alert_success(
        "Workflow {.val {self$name}} completed in {steps_taken} step(s)."
      )

      self$run_history[[length(self$run_history) + 1L]] <- list(
        input  = original_input,
        output = result,
        steps  = steps_taken,
        trace  = trace
      )

      emit_event(on_event, new_event(
        "workflow_output", self$name, text = result, steps = steps_taken
      ))

      result
    }
  )
)


# ==============================================================================

#' @title WorkflowAgent
#'
#' @description
#' A lightweight, Agent-compatible wrapper around a `Workflow`. Created via
#' \code{Workflow$as_agent()}.
#'
#' `WorkflowAgent` exposes the same interface that `LeadAgent` expects from
#' any agent (\code{name}, \code{instruction}, \code{agent_id},
#' \code{$invoke()}), so it can be:
#' \itemize{
#'   \item Registered with \code{LeadAgent$register_agents()}.
#'   \item Used as a Station handler inside another `Workflow`.
#' }
#'
#' Do not instantiate `WorkflowAgent` directly - use \code{Workflow$as_agent()}.
#'
#' @export
WorkflowAgent <- R6::R6Class(
  "WorkflowAgent",
  cloneable = FALSE,

  public = list(

    #' @field name Agent name (visible to `LeadAgent` for task matching).
    name = NULL,

    #' @field instruction System instruction describing the agent's role.
    instruction = NULL,

    #' @field agent_id Unique identifier (UUID).
    agent_id = NULL,

    #' @field workflow The underlying `Workflow` object.
    workflow = NULL,

    #' @field messages Conversation history as a list of
    #'   \code{list(role, content)} entries.
    messages = NULL,

    #' @description Create a new `WorkflowAgent`. Prefer \code{Workflow$as_agent()}.
    #'
    #' @param name `[character(1)]` Agent name.
    #' @param instruction `[character(1)]` Instruction / system prompt.
    #' @param workflow A `Workflow` object.
    initialize = function(name, instruction, workflow) {
      checkmate::assert_string(name)
      checkmate::assert_string(instruction)

      if (!inherits(workflow, "Workflow")) {
        cli::cli_abort("{.arg workflow} must be a {.cls Workflow} object.")
      }

      self$name        <- name
      self$instruction <- instruction
      self$agent_id    <- uuid::UUIDgenerate()
      self$workflow    <- workflow
      self$messages    <- list()
    },

    #' @description Run the underlying workflow with `prompt` as input.
    #'
    #' Not compatible with a wrapped `Workflow` whose \code{hitl_mode} is
    #' `"pause"`: a `WorkflowAgent` is invoked synchronously from a `Workflow`
    #' Station or a `LeadAgent` step, both of which expect a single character
    #' result back, not a `mini007_pending` object to resume later. Use
    #' \code{hitl_mode = "console"} (the default), or drive the wrapped
    #' workflow directly with \code{$workflow$run()} / \code{$resume()} if you
    #' need pause/resume HITL.
    #'
    #' @param prompt `[character(1)]` The user prompt / input payload.
    #' @param stream `[logical(1)]` Whether to stream the wrapped workflow's
    #'   progress (see \code{Workflow$run()}).
    #' @param on_event `[function | NULL]` Callback receiving each
    #'   `mini007_event` emitted by the wrapped workflow and its Agents.
    #'   Supplying it implies \code{stream = TRUE}.
    #'
    #' @return `[character(1)]` The final output of the workflow.
    invoke = function(prompt, stream = FALSE, on_event = NULL) {
      checkmate::assert_string(prompt)
      on_event <- resolve_on_event(stream, on_event)

      self$messages <- c(
        self$messages,
        list(list(role = "user", content = prompt))
      )

      result <- self$workflow$run(prompt, on_event = on_event)

      if (is_pending(result)) {
        cli::cli_abort(c(
          "Workflow {.val {self$workflow$name}} paused for HITL input (pause mode) while running as a WorkflowAgent.",
          "i" = "A WorkflowAgent must return a single result synchronously - it cannot be resumed later.",
          "i" = "Use {.code hitl_mode = \"console\"} on the wrapped Workflow, or drive it directly via {.code $workflow$run()} / {.code $workflow$resume()} instead of {.code $as_agent()}."
        ))
      }

      self$messages <- c(
        self$messages,
        list(list(role = "assistant", content = result))
      )

      result
    },

    #' @description
    #' Wraps the workflow in an ellmer tool, so that an agent can run it.
    #' See \code{Agent$as_tool()}: the tool's `request` is the workflow's
    #' input, and it returns the workflow's output.
    #'
    #' @param description `[character(1) | NULL]` What the workflow does.
    #'   Defaults to a description made from the name and instruction.
    #' @param name `[character(1) | NULL]` The tool name. Defaults to the
    #'   agent's name.
    #' @param fresh `[logical(1)]` If `TRUE`, \code{$messages} is cleared
    #'   before each run.
    #' @return An ellmer tool.
    as_tool = function(description = NULL, name = NULL, fresh = FALSE) {
      if (is.null(name)) name <- self$name
      if (is.null(description)) {
        description <- default_tool_description(self$name, self$instruction)
      }
      agent_as_tool(self, name, description, fresh)
    },

    #' @description Clear the conversation history stored in \code{$messages}.
    #'
    #' @return Invisibly returns `self`.
    reset_conversation_history = function() {
      self$messages <- list()
      invisible(self)
    }
  )
)

# Checkpoint files of Workflow runs. Written to a temporary file first, then
# renamed, so that a crash while writing never leaves half a file.
write_checkpoint <- function(path, checkpoint) {
  dir <- dirname(path)
  if (!dir.exists(dir)) dir.create(dir, recursive = TRUE)
  tmp <- tempfile(".checkpoint-", tmpdir = dir, fileext = ".rds")
  saveRDS(checkpoint, tmp)
  if (!file.rename(tmp, path)) {
    unlink(tmp)
    cli::cli_abort("Could not write the checkpoint file {.file {path}}.")
  }
  invisible(path)
}

read_checkpoint <- function(path) {
  checkpoint <- tryCatch(readRDS(path), error = function(e) NULL)
  if (!inherits(checkpoint, "mini007_checkpoint")) {
    cli::cli_abort("{.file {path}} is not a mini007 Workflow checkpoint.")
  }
  checkpoint
}

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.