tests/testthat/test-task-agent.R

library(testthat)
library(mini007)

# ── Helpers ───────────────────────────────────────────────────────────────────

# A chat that plays a scripted tool loop the way ellmer does: each $chat()
# plays assistant turns from `script` until one has no tool request; every
# request goes through the on_tool_request callbacks (which may refuse it
# with ellmer::tool_reject()), the tools really run, and their results form
# the next user turn. A request to summarise the conversation is answered
# with `summary`, without using the script.
TaskChat <- R6::R6Class(
  "Chat",
  public = list(
    system_prompt = NULL, turns = list(), tools = list(), callbacks = list(),
    script = NULL, position = 0L, next_id = 0L, prompts = character(),
    summary = "SUMMARY: the Casbah facts were found.",
    provider = NULL,

    initialize = function(script = list()) {
      self$script <- script
      self$provider <- new("Provider", name = "dummy", model = "v0")
    },

    chat = function(prompt) {
      self$prompts <- c(self$prompts, prompt)
      if (grepl("^The conversation is getting long", prompt)) {
        self$turns <- c(self$turns, list(
          ellmer::Turn("user", list(ellmer::ContentText(prompt))),
          ellmer::Turn("assistant", list(ellmer::ContentText(self$summary)))
        ))
        return(self$summary)
      }
      user <- ellmer::Turn("user", list(ellmer::ContentText(prompt)))
      repeat {
        self$position <- self$position + 1L
        if (self$position > length(self$script)) stop("script exhausted")
        assistant <- ellmer::Turn("assistant", self$script[[self$position]])
        self$turns <- c(self$turns, list(user, assistant))
        requests <- Filter(function(ct) inherits(ct, "ellmer::ContentToolRequest"), assistant@contents)
        if (length(requests) == 0) break
        results <- lapply(requests, function(request) {
          refusal <- tryCatch({
            for (callback in self$callbacks) callback(request)
            NULL
          }, ellmer_tool_reject = function(e) conditionMessage(e))
          if (!is.null(refusal)) return(ellmer::ContentToolResult(error = refusal, request = request))
          tryCatch(
            ellmer::ContentToolResult(
              value = do.call(self$tools[[request@name]], request@arguments),
              request = request
            ),
            error = function(e) ellmer::ContentToolResult(error = e, request = request)
          )
        })
        user <- ellmer::Turn("user", results)
      }
      assistant@text
    },
    on_tool_request = function(callback) {
      self$next_id <- self$next_id + 1L
      id <- as.character(self$next_id)
      self$callbacks[[id]] <- callback
      invisible(function() {
        self$callbacks[[id]] <- NULL
        invisible()
      })
    },
    register_tools = function(tools) { self$tools <- tools },
    set_tools = function(tools) { self$tools <- tools },
    get_tools = function() self$tools,
    last_turn = function() self$turns[[length(self$turns)]],
    get_cost = function(include = "all") NA_real_,
    set_system_prompt = function(value) { self$system_prompt <- value },
    get_system_prompt = function() self$system_prompt,
    set_turns = function(turns) {
      self$turns <- Filter(function(turn) !identical(turn@role, "system"), turns)
    },
    get_turns = function(include_system_prompt = FALSE) {
      if (!include_system_prompt) return(self$turns)
      c(list(ellmer::Turn("system", list(ellmer::ContentText(self$system_prompt)))), self$turns)
    },
    get_provider = function() self$provider
  )
)

say <- function(x) list(ellmer::ContentText(x))
use <- function(.id, .tool, ..., .thought = "Working on it.") {
  list(ellmer::ContentText(.thought),
       ellmer::ContentToolRequest(id = .id, name = .tool, arguments = list(...)))
}
todos <- function(...) {
  items <- list(...)
  lapply(seq(1, length(items), by = 2), function(i) list(task = items[[i]], status = items[[i + 1]]))
}

lookups <- new.env()
monument_info <- ellmer::tool(
  function(monument) {
    lookups$monuments <- c(lookups$monuments, monument)
    paste(monument, "is in Algiers.")
  },
  name = "monument_info",
  description = "Facts about a monument of Algeria.",
  arguments = list(monument = ellmer::type_string("The monument."))
)

new_task_agent <- function(script, ...) {
  suppressMessages(TaskAgent$new(
    name = "guide",
    instruction = "You write travel guides about Algeria.",
    llm_object = TaskChat$new(script),
    ...
  ))
}

# ── Creation ──────────────────────────────────────────────────────────────────

test_that("a TaskAgent has the built-in tools, its own tools and the task guidance", {
  agent <- new_task_agent(list(), tools = list(monument_info))
  expect_s3_class(agent, "ReActAgent")
  expect_setequal(names(agent$llm_object$tools),
                  c("monument_info", "write_todos", "save_note", "read_note"))
  expect_equal(agent$list_tools(), "monument_info")
  expect_equal(agent$role, "You write travel guides about Algeria.")
  prompt <- agent$llm_object$get_system_prompt()
  expect_match(prompt, "You write travel guides about Algeria.", fixed = TRUE)
  expect_match(prompt, "write_todos", fixed = TRUE)
  expect_match(prompt, "save_note", fixed = TRUE)

  bare <- new_task_agent(list())
  expect_setequal(names(bare$llm_object$tools), c("write_todos", "save_note", "read_note"))
  expect_equal(nrow(bare$todos), 0L)
})

test_that("TaskAgent$new() checks its arguments", {
  expect_error(new_task_agent(list(), max_rounds = 0))
  expect_error(new_task_agent(list(), keep_recent = 0))
  expect_error(new_task_agent(list(), require_approval = 1))
  expect_error(new_task_agent(list(), approve = "yes"))
})

# ── Todos, notes and rounds ───────────────────────────────────────────────────

test_that("the agent writes its todo list, works through it and saves notes", {
  lookups$monuments <- NULL
  agent <- new_task_agent(list(
    use("1", "write_todos", todos = todos("Find a fact about the Casbah", "in_progress",
                                          "Write the itinerary", "pending")),
    use("2", "monument_info", monument = "Casbah"),
    use("3", "save_note", name = "casbah", content = "The Casbah is in Algiers."),
    use("4", "write_todos", todos = todos("Find a fact about the Casbah", "done",
                                          "Write the itinerary", "done")),
    say("Morning: the Casbah, which is in Algiers.")
  ), tools = list(monument_info))

  answer <- agent$invoke("Plan a morning in Algiers.")

  expect_equal(answer, "Morning: the Casbah, which is in Algiers.")
  expect_equal(lookups$monuments, "Casbah")
  expect_equal(agent$todos$status, c("done", "done"))
  expect_equal(agent$todos$task[[2]], "Write the itinerary")
  expect_equal(agent$notes$casbah, "The Casbah is in Algiers.")
  expect_equal(agent$last_task$rounds, 1L)
  expect_true(agent$last_task$completed)
  expect_equal(agent$last_task$answer, answer)

  expect_output(agent$print_todos(), "[x] Write the itinerary", fixed = TRUE)
})

test_that("the agent is sent back to work while its todo list is not done", {
  agent <- new_task_agent(list(
    use("1", "write_todos", todos = todos("Visit the Casbah", "done", "Visit Tipaza", "pending")),
    say("Here is half of the plan."),
    use("2", "write_todos", todos = todos("Visit the Casbah", "done", "Visit Tipaza", "done")),
    say("Here is the whole plan.")
  ))

  answer <- agent$invoke("Plan two visits.")

  expect_equal(answer, "Here is the whole plan.")
  expect_equal(agent$last_task$rounds, 2L)
  expect_true(agent$last_task$completed)
  second <- agent$llm_object$prompts[[2]]
  expect_match(second, "Your todo list is not finished", fixed = TRUE)
  expect_match(second, "- [pending] Visit Tipaza", fixed = TRUE)
  expect_match(second, "Plan two visits.", fixed = TRUE)
})

test_that("write_todos points out unfinished items that were dropped", {
  agent <- new_task_agent(list(
    use("1", "write_todos", todos = todos("Visit the Casbah", "pending", "Visit Tipaza", "pending")),
    use("2", "write_todos", todos = todos("Plan everything", "done")),
    say("Done.")
  ))
  agent$invoke("Plan two visits.")
  observed <- agent$trace$content[agent$trace$type == "observe"]
  expect_false(grepl("no longer in the list", observed[[1]], fixed = TRUE))
  expect_match(observed[[2]], "'Visit the Casbah', 'Visit Tipaza'. If they still need doing", fixed = TRUE)
})

test_that("the agent stops after max_rounds with a warning", {
  agent <- new_task_agent(list(
    use("1", "write_todos", todos = todos("Visit Djemila", "pending")),
    say("Not yet."),
    say("Still not.")
  ), max_rounds = 2)

  expect_message(answer <- agent$invoke("Plan a visit."), "not done")
  expect_equal(answer, "Still not.")
  expect_equal(agent$last_task$rounds, 2L)
  expect_false(agent$last_task$completed)
})

test_that("a simple question needs a single round and no todo list", {
  agent <- new_task_agent(list(say("Algiers.")))
  expect_equal(agent$invoke("What is the capital of Algeria?"), "Algiers.")
  expect_equal(agent$last_task$rounds, 1L)
  expect_equal(nrow(agent$todos), 0L)
})

test_that("read_note returns a note, or the names of the saved notes", {
  agent <- new_task_agent(list(
    use("1", "save_note", name = "tassili", content = "Rock art."),
    use("2", "read_note", name = "tassili"),
    use("3", "read_note", name = "ahaggar"),
    say("Done.")
  ))
  agent$invoke("Remember Tassili.")
  results <- agent$trace[agent$trace$type == "observe", ]
  expect_equal(results$content[[2]], "Rock art.")
  expect_true(results$is_error[[3]])
  expect_match(results$content[[3]], "Saved notes: tassili", fixed = TRUE)
})

# ── Workspace ─────────────────────────────────────────────────────────────────

test_that("notes are saved in the workspace and loaded by the next agent", {
  workspace <- file.path(tempfile("workspace"), "notes")
  agent <- new_task_agent(list(
    use("1", "save_note", name = "timgad facts", content = "Founded by Trajan."),
    say("Saved.")
  ), workspace = workspace)
  agent$invoke("Note a fact about Timgad.")
  expect_true(file.exists(file.path(workspace, "timgad_facts.md")))

  later <- new_task_agent(list(say("Trajan founded it.")), workspace = workspace)
  expect_equal(later$notes$timgad_facts, "Founded by Trajan.")
  later$invoke("Who founded Timgad?")
  expect_match(later$llm_object$prompts[[1]], "Notes saved earlier", fixed = TRUE)
  expect_match(later$llm_object$prompts[[1]], "timgad_facts", fixed = TRUE)

  later$clear_notes()
  expect_length(later$notes, 0L)
  expect_false(file.exists(file.path(workspace, "timgad_facts.md")))
})

# ── Approval ──────────────────────────────────────────────────────────────────

test_that("calls of tools that need approval wait for it", {
  lookups$monuments <- NULL
  asked <- character()
  answers <- list(FALSE, TRUE, "always")
  approve <- function(tool, arguments) {
    asked <<- c(asked, arguments$monument)
    answer <- answers[[1]]
    answers <<- answers[-1]
    answer
  }
  agent <- new_task_agent(list(
    use("1", "monument_info", monument = "Casbah"),
    use("2", "monument_info", monument = "Tipaza"),
    use("3", "monument_info", monument = "Djemila"),
    use("4", "monument_info", monument = "Timgad"),
    use("5", "write_todos", todos = todos("Look up monuments", "done")),
    say("Done.")
  ), tools = list(monument_info), require_approval = "monument_info", approve = approve)

  agent$invoke("Look up four monuments.")

  # Refused, allowed once, allowed for good, then not asked again.
  expect_equal(asked, c("Casbah", "Tipaza", "Djemila"))
  expect_equal(lookups$monuments, c("Tipaza", "Djemila", "Timgad"))
  expect_equal(agent$approved_tools, "monument_info")
  refused <- agent$trace[agent$trace$type == "observe", ][1, ]
  expect_true(refused$is_error)
  expect_match(refused$content, "did not allow", fixed = TRUE)
  # The guard is removed after the task.
  expect_length(agent$llm_object$callbacks, 0L)
})

test_that("approval is asked in the console by default", {
  local_mocked_bindings(readline = function(prompt) "n", .package = "base")
  agent <- new_task_agent(list(
    use("1", "monument_info", monument = "Casbah"),
    say("I could not look it up.")
  ), tools = list(monument_info), require_approval = "monument_info")
  expect_output(suppressMessages(agent$invoke("Look up the Casbah.")), "Casbah")
  expect_true(agent$trace$is_error[agent$trace$type == "observe"])
})

# ── Compaction ────────────────────────────────────────────────────────────────

test_that("a long conversation is compacted before the next round", {
  agent <- new_task_agent(list(
    use("1", "monument_info", monument = "Casbah"),
    say("The Casbah is in Algiers."),
    say("Tipaza has Roman ruins.")
  ), tools = list(monument_info), max_context_tokens = 10, keep_recent = 2)

  agent$invoke("Tell me about the Casbah.")
  answer <- agent$invoke("And Tipaza?")

  expect_equal(answer, "Tipaza has Roman ruins.")
  expect_equal(agent$last_task$compactions, 1L)
  contents <- vapply(agent$messages, function(m) m$content, character(1))
  expect_match(contents[[2]], "SUMMARY: the Casbah facts were found.", fixed = TRUE)
  expect_false(any(grepl("[tool request id=", contents, fixed = TRUE)))
  expect_false(any(contents == "Tell me about the Casbah."))
  expect_match(contents[[length(contents) - 1L]], "And Tipaza?", fixed = TRUE)
  # The summary was written on a blank copy of the chat.
  expect_false(any(grepl("getting long", agent$llm_object$prompts, fixed = TRUE)))
})

test_that("$compact() summarises on demand, and not a short conversation", {
  agent <- new_task_agent(list(say("One."), say("Two."), say("Three.")), keep_recent = 2)
  expect_message(agent$compact(), "too short")
  agent$invoke("First?")
  agent$invoke("Second?")
  agent$invoke("Third?")
  suppressMessages(agent$compact())
  expect_match(agent$messages[[2]]$content, "SUMMARY", fixed = TRUE)
  expect_equal(agent$messages[[length(agent$messages)]]$content, "Three.")
})

# ── Clones, structured output, code mode ─────────────────────────────────────

test_that("a clone keeps its own todo list", {
  agent <- new_task_agent(list(
    use("1", "write_todos", todos = todos("Visit Oran", "done")),
    say("Done.")
  ))
  copy <- suppressMessages(agent$clone_agent("copy"))
  copy$invoke("Plan Oran.")
  expect_equal(copy$todos$task, "Visit Oran")
  expect_equal(nrow(agent$todos), 0L)
})

test_that("code mode puts the agent's tools in run_r_code and keeps the built-in tools", {
  lookups$monuments <- NULL
  code <- "for (m in c('Casbah', 'Tipaza')) print(monument_info(m))"
  agent <- new_task_agent(list(
    use("1", "run_r_code", code = code),
    say("Both are in Algiers.")
  ), tools = list(monument_info))
  suppressMessages(agent$set_code_mode(timeout = 5))

  expect_setequal(names(agent$llm_object$tools),
                  c("run_r_code", "write_todos", "save_note", "read_note"))
  expect_match(agent$llm_object$tools$run_r_code@description, "monument_info(monument)", fixed = TRUE)

  agent$invoke("Look up the Casbah and Tipaza.")
  expect_equal(lookups$monuments, c("Casbah", "Tipaza"))
  observed <- agent$trace$content[agent$trace$type == "observe"]
  expect_match(observed, "Tipaza is in Algiers.", fixed = TRUE)
})

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.