| Title: | AI Agent Runtime |
| Version: | 0.8.1 |
| Description: | An agent runtime that gives Large Language Models (LLMs) from 'Anthropic' https://www.anthropic.com/, 'OpenAI' https://openai.com/, 'Moonshot' https://www.moonshot.ai/, and 'Ollama' https://ollama.com/ direct access to a live R session. Tools execute as R function calls and record their results. Interfaces include a shell command-line interface (CLI), a console read-eval-print-loop via chat(), and a Model Context Protocol (MCP) server via serve() for external clients. |
| License: | Apache License (≥ 2) |
| URL: | https://github.com/cornball-ai/corteza |
| BugReports: | https://github.com/cornball-ai/corteza/issues |
| Depends: | R (≥ 4.4.0) |
| Imports: | callr, curl, digest, jsonlite, llm.api (≥ 0.2.0), printify, processx, saber (≥ 0.8.0), utils |
| Suggests: | chat.api (≥ 0.2.0), clipr, fortunes, rgrpc (≥ 0.1.0), mx.client (≥ 0.3.0), pensar, RProtoBuf (≥ 0.4.24), rstudioapi, simplermarkdown, tinytest |
| VignetteBuilder: | simplermarkdown |
| SystemRequirements: | On Windows, Rtools45 (R 4.5.x) or Rtools44 (R 4.4.x) is recommended so the 'bash' shell tool is available; minimal installs fall back to a 'cmd' tool. 'git' is required for the git_status, git_diff, and git_log tools (install Git for Windows, or 'pacman -Sy git' from an Rtools shell). |
| Encoding: | UTF-8 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-26 21:56:26 UTC; troy |
| Author: | Troy Hernandez |
| Maintainer: | Troy Hernandez <troy@cornball.ai> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-27 01:00:09 UTC |
AI Agent Runtime
Description
An agent runtime that gives Large Language Models (LLMs) from 'Anthropic' <https://www.anthropic.com/>, 'OpenAI' <https://openai.com/>, 'Moonshot' <https://www.moonshot.ai/>, and 'Ollama' <https://ollama.com/> direct access to a live R session. Tools execute as R function calls and record their results. Interfaces include a shell command-line interface (CLI), a console read-eval-print-loop via chat(), and a Model Context Protocol (MCP) server via serve() for external clients.
Package Content
Index of help topics:
add_observer Add a tool-call observer to a session
audit_payload_expire Expire unpinned audit payloads explicitly
audit_payload_pin Pin or unpin an audit payload
audit_payload_read Read an immutable audit payload
audit_read Read an audit event stream
bot_archive_all Hand each room's new conversation to the host
bot_configure Configure the Matrix channel for this host
bot_poll One iteration of sync-and-reply
bot_request_flush Ask the running matrix bot to archive its
sessions
bot_run Run the Matrix adapter as a long-poll loop
bot_run_init Initialize the Matrix long-poll state
bot_run_step One Matrix long-poll iteration
bot_send Send a message to a Matrix room
chat Start Interactive Chat
default_local_model Detect the preferred local Ollama model
install_cli Install corteza CLI
matrix_archive_all Deprecated: use bot_archive_all()
matrix_configure Deprecated: use bot_configure()
matrix_poll Deprecated: use bot_poll()
matrix_request_flush Deprecated: use bot_request_flush()
matrix_run Deprecated: use bot_run()
matrix_run_init Deprecated: use bot_run_init()
matrix_run_step Deprecated: use bot_run_step()
matrix_send Deprecated: use bot_send()
mcp_tool_executor Build a tool executor that routes through an
MCP connection
new_session Create a new turn session
observer_progress Built-in progress observer that prints to
stdout
policy Evaluate policy for a tool call
serve Start MCP Server
session_setup Configure and construct a session for any
channel
sessions_prune Remove what old sessions no longer need
skill_install Install a skill from a path or URL
skill_list_installed List installed skills
skill_remove Remove an installed skill
skill_test Run skill tests
subagent_collect Collect the result of a previously-fired async
subagent query.
subagent_kill Kill a subagent.
subagent_list List active subagents.
subagent_query Query a subagent.
subagent_spawn Spawn a subagent.
turn Run one agent turn
uninstall_cli Uninstall corteza CLI
voice_serve Serve AgentVoice for live voice clients
Maintainer
Troy Hernandez <troy@cornball.ai>
Author(s)
Troy Hernandez [aut, cre] (ORCID: <https://orcid.org/0009-0005-4248-604X>), Grant McDermott [ctb] (ORCID: <https://orcid.org/0000-0001-7883-8573>), Jorge Krzyzaniak [ctb], cornball.ai [cph]
Model context limits in tokens.
Description
The largest input each known model takes: the provider's published input limit where it has one, else its context window. Used by [context_limit_for_model()]. Each group names the page its numbers were read from and the day. A model that is not here gets the fallback, 128,000, and compacts early, so add a row when a provider ships a model. 'test_compact_trigger.R' fails when a default model of llm.api has no row.
Usage
MODEL_CONTEXT_LIMITS
Format
An object of class list of length 55.
Add a tool-call observer to a session
Description
Observers run after every tool call (run, denied, or declined). They
receive a single event list with fields:
Usage
add_observer(session, observer)
Arguments
session |
A session environment from |
observer |
A function of one argument (the event list). |
Details
-
call— the call list passed topolicy(). -
decision— the policy decision for the call. -
outcome— one of"ran","deny","declined". -
result— the string returned to the LLM. -
success— logical; TRUE only for"ran"with no tool error. -
elapsed_ms— wall time including policy overhead. -
turn_number— the session's tool-call counter.
Errors raised inside an observer are swallowed.
Value
The session, invisibly.
Examples
s <- new_session(provider = "anthropic")
add_observer(s, function(event) {
# An observer is just a function of one argument; record the
# outcome for inspection.
message(event$outcome)
})
length(s$on_tool)
Expire unpinned audit payloads explicitly
Description
Automatic expiry requires a positive retention.audit_payload_days
in the user's configuration. Only files in the named writer's payload store are
eligible; event metadata and other writers' stores are left intact. Expiry
decisions append to a separate maintenance stream before deletion. Event
retention is a planning value until an explicit event-retention tool is used.
Usage
audit_payload_expire(store, days = 30, now = Sys.time(), dry_run = TRUE)
Arguments
store |
A writer's payload store path from a payload reference. |
days |
Retain this many days, default 30. |
now |
Comparison time, default Sys.time(). |
dry_run |
Report eligible hashes without deleting, default TRUE. |
Value
Character vector of eligible (or deleted) hashes.
Examples
# A payload as an audit event records it: bytes named by their SHA-256
# in a writer's store, under a folder called "payloads".
store <- file.path(tempfile("audit"), "payloads", "example")
dir.create(store, recursive = TRUE)
text <- "the full output of a tool call"
hash <- digest::digest(charToRaw(text), algo = "sha256", serialize = FALSE)
writeBin(charToRaw(text), file.path(store, hash))
ref <- list(store = store, hash = hash, format = "text", status = "stored")
audit_payload_read(ref)
audit_payload_pin(ref)
audit_payload_pin(ref, pin = FALSE)
# A dry run lists what is older than 30 days and unpinned: nothing here.
audit_payload_expire(store)
unlink(dirname(dirname(store)), recursive = TRUE)
Pin or unpin an audit payload
Description
Pins keep incident/evaluation evidence through explicit expiry. Pinned bytes still count toward the store quota; capture reports quota omissions when full.
Usage
audit_payload_pin(ref, pin = TRUE)
Arguments
ref |
Payload reference from an audit event. |
pin |
TRUE to pin, FALSE to remove the pin. |
Value
The payload reference, invisibly.
Examples
# A payload as an audit event records it: bytes named by their SHA-256
# in a writer's store, under a folder called "payloads".
store <- file.path(tempfile("audit"), "payloads", "example")
dir.create(store, recursive = TRUE)
text <- "the full output of a tool call"
hash <- digest::digest(charToRaw(text), algo = "sha256", serialize = FALSE)
writeBin(charToRaw(text), file.path(store, hash))
ref <- list(store = store, hash = hash, format = "text", status = "stored")
audit_payload_read(ref)
audit_payload_pin(ref)
audit_payload_pin(ref, pin = FALSE)
# A dry run lists what is older than 30 days and unpinned: nothing here.
audit_payload_expire(store)
unlink(dirname(dirname(store)), recursive = TRUE)
Read an immutable audit payload
Description
Reads only a payload whose bytes still match its recorded SHA-256. Redaction affects the returned view, never the stored record. An omitted, expired, missing or damaged payload is an error, not an empty successful read.
Usage
audit_payload_read(ref, redact = TRUE, secrets = character())
Arguments
ref |
Payload reference from an audit event or request manifest. |
redact |
Apply display redaction. Defaults to TRUE. |
secrets |
Additional known credential values to hide in the view. |
Value
The decoded JSON object or UTF-8 text, as recorded.
Examples
# A payload as an audit event records it: bytes named by their SHA-256
# in a writer's store, under a folder called "payloads".
store <- file.path(tempfile("audit"), "payloads", "example")
dir.create(store, recursive = TRUE)
text <- "the full output of a tool call"
hash <- digest::digest(charToRaw(text), algo = "sha256", serialize = FALSE)
writeBin(charToRaw(text), file.path(store, hash))
ref <- list(store = store, hash = hash, format = "text", status = "stored")
audit_payload_read(ref)
audit_payload_pin(ref)
audit_payload_pin(ref, pin = FALSE)
# A dry run lists what is older than 30 days and unpinned: nothing here.
audit_payload_expire(store)
unlink(dirname(dirname(store)), recursive = TRUE)
Read an audit event stream
Description
Uses the auto-log decoder, retaining malformed-line locations and separating a torn final line from interior damage. A missing terminal turn record means unresolved completion. Redaction changes this returned view only; callers can supply additional known credential values. It cannot detect all secrets.
Usage
audit_read(path, redact = TRUE, secrets = character())
Arguments
path |
Path to a writer's JSONL stream. |
redact |
Apply display redaction, default TRUE. |
secrets |
Additional known credential values to hide. |
Value
List with records, auto-run start/end compatibility fields and malformed-record diagnostics. Turn endings remain in records.
Examples
audit_read(tempfile())
History marker written when an unattended run escalates to a human.
Description
Carries the same "stop and ask" directive as its siblings, for the same reason: whatever the worker does next, it must not be another attempt at the thing that just got escalated.
Usage
auto_escalate_marker(reason = "")
Arguments
reason |
Character. Why a human is needed. |
Value
Character scalar.
Hand each room's new conversation to the host
Description
Offers what every room and thread session said since its last
archive to the host's on_archive hook (see
bot_run_init), and again whatever the hook did not take
before. A range the host took is consumed from the session's ledger
and its Matrix event ids are kept per room under
CORTEZA_STATE_DIR, so a restart's backfill is recognized
rather than offered again. A range it did not take waits there for
the next flush. With no hook nothing is filed.
Usage
bot_archive_all(sessions, chat = NULL, on_archive = NULL, cfg = NULL)
Arguments
sessions |
A registry environment built by
|
chat |
Optional chat.api client, handed to the hook. |
on_archive |
The host's |
cfg |
The bot config, which names the bot. NULL reads the saved one when there is a hook. |
Value
Integer count of ranges the host took, invisibly.
Examples
## Not run:
# Requires a running Matrix session registry and a host's hook.
reg <- new.env(parent = emptyenv())
bot_archive_all(reg, on_archive = function(chat, cfg, room_id, archive) {
list(archived = TRUE, ref = NULL)
})
## End(Not run)
Configure the Matrix channel for this host
Description
Logs in to a Matrix homeserver as the bot account, joins (or records)
the target room, and writes credentials to
tools::R_user_dir("corteza", "config")/matrix.json with file
mode 0600. Call once per host. Model, provider, tools_filter, and
auto_approve_asks are defaults the poll loop uses unless overridden
at call time.
Usage
bot_configure(
server,
user,
password,
room,
model = NULL,
provider = "anthropic",
tools_filter = NULL,
auto_approve_asks = FALSE,
bots = NULL,
models = NULL,
model_badge = c("never", "non_default", "always"),
display_name = NULL,
fallback = NULL,
cwd = NULL,
operators = NULL,
project_roots = NULL
)
Arguments
server |
Character. Homeserver base URL. |
user |
Character. Bot localpart or full Matrix ID. |
password |
Character. Bot password. Stored locally so the bot can re-authenticate if its access token is invalidated. |
room |
Character. Room ID or alias the bot should read and post to. If the bot has been invited but not joined, it will be joined. |
model |
Character or NULL. Default model name. |
provider |
Character. LLM provider: "anthropic", "anthropic_claude", "openai", "openai_codex", "moonshot", or "ollama". |
tools_filter |
Character vector or NULL. Passed to
|
auto_approve_asks |
Logical. Who rules on a tool call that
needs approval. Rules in code read every call first, and what they
catch (credentials, writes outside the project, elevated
privileges, other machines, publishing, discarded work) is always
put to a person by reaction in the room. When TRUE, the rest goes
to a monitor: a read-only model in its own process that approves,
refuses, or passes the call on to a person. When FALSE (default) a
person is asked for the rest as well. Nothing is approved unseen.
The monitor's model is set under |
bots |
Character vector or NULL. Full Matrix IDs of other known bot accounts. Their messages only get a reply when they mention this bot, and they are not counted as humans when deciding whether a room gets ungated replies (a room whose only non-bot member is one human is answered without a mention). |
models |
Character vector or NULL. Extra entries for the
|
model_badge |
Character. When to show which model is answering:
|
display_name |
Character or NULL. Base display name the badge rename builds on. Defaults to the localpart of the bot's user id. |
fallback |
Character vector or NULL. What |
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one with |
operators |
Character vector or NULL. The people the bot answers
to, each a full Matrix id such as |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Details
Pre-CRAN releases stored the file at ~/.corteza/matrix.json;
that path is still read for backward compatibility, but the next
bot_configure() call writes to the new location.
Value
The saved configuration, invisibly.
Examples
## Not run:
# Requires a real Matrix server and bot credentials. Configuration
# is written under tools::R_user_dir("corteza", "config").
bot_configure(
server = "https://matrix.example.org",
user = "bot",
password = "secret",
room = "!roomid:example.org"
)
## End(Not run)
One iteration of sync-and-reply
Description
Fetches new messages across all joined rooms and runs turn
against each. Joins a room the bot is invited to when one of its
operators sent the invite (see bot_configure); every
other invite is refused and reported.
Replies are sent back to the originating room. On first run there is
no saved sync token, so this call establishes a baseline and returns
without processing history.
Usage
bot_poll(
system = NULL,
model = NULL,
provider = NULL,
tools_filter = NULL,
timeout = 0L,
sessions = NULL,
hooks = NULL,
cwd = NULL,
project_roots = NULL
)
Arguments
system |
Character or NULL. System prompt override. |
model |
Character or NULL. Model override. |
provider |
Character or NULL. Provider override. |
tools_filter |
Character vector or NULL. Tool filter override. |
timeout |
Integer. Long-poll timeout in milliseconds. 0 returns immediately. |
sessions |
Environment from |
hooks |
Named list of functions or NULL, as validated by
|
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one with |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Details
Pass sessions = NULL (the default) for a stateless one-shot —
each incoming message builds a fresh session. Pass a registry created
by bot_new_session_registry() so a long-running
bot_run keeps a separate history per room (conversations
in different rooms don't cross-contaminate).
Value
An integer count of messages replied to, invisibly.
Examples
## Not run:
# Single poll cycle against the configured Matrix homeserver.
bot_poll(timeout = 5000L)
## End(Not run)
Ask the running matrix bot to archive its sessions
Description
Drops an archive.signal file in the corteza state directory.
The next iteration of the long-poll loop in bot_run
picks it up, runs bot_archive_all with the host's
on_archive hook, and removes the file. Safe to call from any
process or scheduler — systemd, Task
Scheduler, launchd, cron, or a separate R session — without needing
to know the bot's PID or share its memory.
Usage
bot_request_flush()
Value
The signal file path, invisibly.
Examples
# Writes a sentinel file under CORTEZA_STATE_DIR (or the package's
# R_user_dir data path). Redirect to a tempdir for the example so
# we don't touch persistent state.
old <- Sys.getenv("CORTEZA_STATE_DIR", unset = NA)
Sys.setenv(CORTEZA_STATE_DIR = file.path(tempdir(), "state"))
sig <- bot_request_flush()
file.exists(sig)
unlink(Sys.getenv("CORTEZA_STATE_DIR"), recursive = TRUE)
if (is.na(old)) {
Sys.unsetenv("CORTEZA_STATE_DIR")
} else {
Sys.setenv(CORTEZA_STATE_DIR = old)
}
Run the Matrix adapter as a long-poll loop
Description
Creates one session up front and reuses it across polls so conversation
history accumulates within the process lifetime. Intended as the entry
point for a systemd user unit. A thin wrapper over
bot_run_init plus a bot_run_step
loop; call those two directly when an external scheduler needs to own
the main process.
Usage
bot_run(
timeout = 30000L,
system = NULL,
model = NULL,
provider = NULL,
tools_filter = NULL,
cwd = NULL,
project_roots = NULL
)
Arguments
timeout |
Integer. Long-poll timeout in milliseconds. |
system |
Character or NULL. System prompt override. |
model |
Character or NULL. Model override. |
provider |
Character or NULL. Provider override. |
tools_filter |
Character vector or NULL. Tool filter override. |
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one; see |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Value
Never returns under normal operation. Crashes on fatal error so systemd can restart.
This is a bare bot: it runs with no hooks, so /clear
archives and resets without filing the conversation anywhere, and a
thread reply starts from the thread's own history. A host that wants
segment rooms and rehydration drives the loop itself through
bot_run_init and supplies them.
See Also
Examples
## Not run:
# Run the Matrix bot loop -- typically launched by a systemd unit
# rather than from an interactive R session.
bot_run()
## End(Not run)
Initialize the Matrix long-poll state
Description
Performs everything bot_run does before its loop:
builds the per-room session registry, catches up on invites that
predate the saved sync token, and backfills recent room history into
the registry. Returns an opaque state object to drive with
bot_run_step.
Usage
bot_run_init(
system = NULL,
model = NULL,
provider = NULL,
tools_filter = NULL,
hooks = NULL,
cwd = NULL,
project_roots = NULL
)
Arguments
system |
Character or NULL. System prompt override. |
model |
Character or NULL. Model override. |
provider |
Character or NULL. Provider override. |
tools_filter |
Character vector or NULL. Tool filter override. |
hooks |
Named list of functions or NULL. Policy the loop asks
the host about; see Hooks. NULL, the default, means a bare bot:
|
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one with |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Details
End-to-end encryption is not set up here. When the config sets
e2ee, the chat.api Matrix adapter owns the Olm account and
Megolm sessions and both directions of encrypted traffic, so there is
no crypto state for this package to build or carry.
Use this with bot_run_step() when an external loop owns the
main process and needs to interleave the Matrix poll with other work
(a scheduler, a multiplexer, an embedding host). For a standalone bot,
call bot_run, which wraps both.
Value
A list holding the session registry, startup session handle,
archive-flush signal path, and the saved poll options. Pass it to
bot_run_step.
Hooks
corteza runs a conversation. What becomes of one once it ends, where a thread's earlier context comes from, and which rooms' messages the host answers itself, belong to the host that runs the bot over time (a host might file segments and fold them into topic rooms). Four slots, all optional:
on_archive(chat, cfg, room_id, archive)Called with each range of a room's or thread's conversation that nothing has filed yet: at
/clear, at a flush (bot_request_flush), and again for every range the hook did not take before.archiveis a list:id, the same however often the range is offered;bot, the bot's Matrix id;room_id;thread, the thread's root event or NULL;session, the session's id;first_eventandlast_event, the Matrix events that bound the range;entries, oldest first, eachlist(event_id, role, content)with the text as posted; andreason,"clear"or"flush". Returnslist(archived = TRUE, ref)once the host has filed the range or chosen not to;ref, a string or NULL, is whaton_clearreceives. Anything else, or an error, which is reported, and the range waits underCORTEZA_STATE_DIRfor the next/clearor flush, through a restart. When it cannot be written there either,/clearkeeps the session that holds it, and says so in the room. A range from a flush takes the conversation's later entries under the sameid, so a host that filed one before replaces it. With no hook nothing is filed.on_clear(chat, cfg, room_id, title, vault_ref)Called from the
/clearhandler onceon_archivetook the conversation, when the user said something in it and the clear was not inside a thread.chatis the live chat.api client,cfgthe bot config,titlethe segment title corteza derived from the transcript's opening line,vault_reftherefthe archive hook returned (or NULL). Returnslist(id, name)for a room it filed the conversation into, which the acknowledgement names, or NULL for none. An error is reported and treated as none: archive-and-reset is the critical path.thread_context(chat, room_id, thread_root)Called once per thread session before its first reply. Returns
list(segment, vault, kind)naming the archived conversation the thread continues, or NULL when it continues nothing;vaultis the file's path, vault-relative or absolute. Withkind = "summary"the file is a summary, and the session is seeded with its start, said to be one; otherwise it is a transcript, and the session is seeded with its tail.on_message(chat, cfg, room_id, message, session, backfill)The host's first refusal on each message from someone else, for a host that answers some rooms itself. Called once per event, after remote control and delegation take theirs and before anything else: the read receipt, the media step, the reply rules, commands and the turn.
messageis the transport'schat_messageas received,rawincluded;sessionis the room's or the thread's session, where the host may keep state of its own. Returnslist(handled = TRUE)when the host took the message: corteza marks it seen and does nothing more with it, not even a read receipt, and from then on records none of the bot's own messages in that room. Anything else, or an error, which is reported, and the message goes on as if there were no hook. In a restart's backfillbackfillis TRUE: the hook answers from the room's own state and drives nothing, and a message it takes stays out of the session's history.
See Also
Examples
## Not run:
# Drive the loop yourself instead of calling bot_run():
state <- bot_run_init()
repeat bot_run_step(state, timeout = 30000L)
## End(Not run)
One Matrix long-poll iteration
Description
Polls /sync once (blocking up to timeout ms, returning
early when a message arrives), runs the agent against any new messages
and posts the replies, then services a pending archive-flush signal.
Mutates the session registry held in state in place, so
successive calls accumulate conversation history.
Usage
bot_run_step(state, timeout = 30000L)
Arguments
state |
A state object from |
timeout |
Integer. Long-poll timeout in milliseconds. |
Value
Invisibly, the integer count of messages replied to this poll.
See Also
Examples
## Not run:
state <- bot_run_init()
bot_run_step(state, timeout = 5000L)
## End(Not run)
Send a message to a Matrix room
Description
Send a message to a Matrix room
Usage
bot_send(text, room_id = NULL, msgtype = "m.text", markdown = FALSE)
Arguments
text |
Character. Plain text body. |
room_id |
Character. Matrix room id. Defaults to |
msgtype |
Character. Matrix msgtype, default "m.text". |
markdown |
Logical. If TRUE, also send Matrix custom HTML derived from a conservative markdown subset. |
Value
The event ID of the sent message.
Examples
## Not run:
# Requires bot_configure() to have run.
bot_send("hello from corteza")
## End(Not run)
Start Interactive Chat
Description
Run a conversational agent inside your R session. Tools execute as direct function calls, no MCP server needed.
Usage
chat(
provider = NULL,
model = NULL,
tools = NULL,
session = NULL,
max_turns = NULL,
web_search = NULL
)
Arguments
provider |
LLM provider: "anthropic", "openai", "moonshot", or "ollama". Defaults to the saved provider when resuming, otherwise the config value or "anthropic". |
model |
Model name. Defaults to the saved model when resuming with the same provider, otherwise the matching config value or provider default. |
tools |
Character vector of tool names or categories to enable. Categories: file, code, r, data, web, git, chat, memory. Use "core" for file+code+git, "all" for everything (default). |
session |
Session resume control. NULL (default) starts fresh, TRUE resumes the latest session started in the current directory, or a character session key to resume a specific session from any directory. |
max_turns |
Integer or NULL. Maximum LLM turns per user prompt
before the loop stops with |
web_search |
Logical or NULL. Enable provider-native (server-side) web search for the conversation. NULL uses the config default (on for supported providers); the model searches inside its own turn with no Tavily key required. |
Details
A project's own files (its .corteza/ folder, AGENTS.md or
CLAUDE.md, and the briefing built from it) load only from a
directory you have trusted. Where the working directory is not trusted
and holds such files, chat() lists them and asks once before it
starts; /trust shows the same later. See "Trusted projects" in
vignette("configuration").
Value
The session object (invisibly).
Examples
if (interactive()) {
# Start chatting with defaults from config
chat()
# Use a specific provider/model
chat(provider = "ollama", model = "llama3.2")
# Minimal tools for focused work
chat(tools = "core")
}
Find the largest cut point in ‘history' that doesn’t split a tool_use / tool_result pair.
Description
Returns the number of entries that can safely be summarized (entries '1..cut'). Entries 'cut+1..end' are preserved verbatim. Returns 0 when no safe cut is available.
Usage
compact_find_cut(history, keep_recent_turns = 1L, keep_recent_tokens = 20000L)
Arguments
history |
Live in-memory history list. |
keep_recent_turns |
Number of recent user→assistant turns to keep verbatim (a turn starts at a user message). |
keep_recent_tokens |
Approximate recent-history tokens to retain when one user prompt has grown into a long tool trajectory. The cut still lands only at a complete tool-call/result boundary. |
Details
Strategy: start from the maximum cut that leaves 'keep_recent_turns' user-prompt boundaries intact, then walk back as needed so the cut doesn't land between a tool_use and the tool_result that satisfies it.
Replace the compacted prefix of a session's history with a single assistant summary message.
Description
Pure function: returns the new history list, doesn't mutate anything. The summary is prefixed with a '[compacted history]' tag (followed by a blank line) so it's visually distinct in the transcript.
Usage
compact_rewrite_history(history, cut, summary)
Summarize the prefix of a history slice via the LLM.
Description
Returns the summary text on success or NULL on any error (including timeout). Caller leaves history intact on NULL.
Usage
compact_summarize_slice(
slice,
provider = "anthropic",
model = NULL,
timeout_seconds = 60L,
summary_prompt = NULL,
error_callback = NULL,
session = NULL,
max_total_chars = .compact_max_total_chars,
max_request_bytes = NA_real_
)
Arguments
slice |
List of history entries to summarize (the part being compacted; the recent tail is excluded). |
provider |
Provider name. |
model |
Model name. |
timeout_seconds |
Hard wall on the summarizer call. |
summary_prompt |
Optional caller-supplied summarization instructions. NULL uses corteza's general coding-agent brief. |
error_callback |
Optional function called with a caught summarizer error before NULL is returned. |
session |
Optional session supplying audit settings, identity and the parent turn reference. |
max_total_chars |
How many characters of the rendered slice the request may hold. Past it the oldest entries are left out and the summarizer is told how many. The compactor passes a budget that follows the model's window. |
max_request_bytes |
The most bytes the serialized request may take, its framing included, or NA for no limit. Past it the oldest entries are left out as well. A request that cannot fit is not sent, nor one with room for no entry of the slice. |
Look up the context window for a given model.
Description
Tries the model's own row, then the longest row name the id starts with (so a dated or suffixed id resolves to its family), then the rows whose names start with the id (so '"claude-3-haiku"' resolves to the dated entry). An id cut short can mean several rows, and it gets the smallest limit among them.
Usage
context_limit_for_model(model, provider = NULL)
Arguments
model |
Model name (character). |
provider |
Optional provider/product endpoint. Provider-specific limits take precedence over the public model limit. |
Value
Context limit in tokens (integer). Returns 128000L when no entry matches.
Percent of a model's context window used by a session.
Description
Convenience wrapper around [estimate_live_context_tokens()] and [context_limit_for_model()]. Returns 0 when the limit is 0 or negative (defensive — shouldn't happen with a real model).
Usage
context_usage_pct(
session,
model,
system_prompt = NULL,
tools = NULL,
provider = NULL
)
Arguments
session |
Session-like object with '$messages'. |
model |
Model name used to look up the context limit. |
system_prompt |
Optional system prompt. |
tools |
Optional tools list. |
provider |
Optional provider/product endpoint passed to [context_limit_for_model()]. |
Value
Numeric percentage in '[0, +Inf)'.
Execute current line or selection in 'corteza::chat()'
Description
RStudio addin. Reads the line or selection under the cursor in the active source editor, prepends '/r' for '.R' files (or '! ' for '.sh' / '.bash' files) when 'corteza::chat()' is the active console REPL, and sends the result to the console via 'rstudioapi::sendToConsole()'. After sending, the editor cursor advances to the next line (mirroring RStudio's pre-assigned Ctrl+Enter / Cmd+Return behavior).
Usage
corteza_execute_in_chat()
Details
When 'chat()' is not running, no prefix is added – the addin is a superset of RStudio's default "execute line" behavior, so you can bind it to Ctrl+Enter without losing normal R script execution.
**Setup:** bind Ctrl+Enter to "Execute in corteza::chat()" under RStudio's Tools -> Modify Keyboard Shortcuts. Choose "Addins" in the dropdown to find the binding.
Value
Invisible NULL. Side effect: sends a line to the console.
Execute current line or selection in 'corteza::chat()' (retain cursor)
Description
Same routing logic as [corteza_execute_in_chat()] but the editor cursor stays in place after sending, mirroring RStudio's pre-assigned Alt+Enter / Option+Return behavior.
Usage
corteza_execute_in_chat_retain()
Details
**Setup:** bind Alt+Enter to "Execute in corteza::chat() (retain cursor)" under RStudio's Tools -> Modify Keyboard Shortcuts.
Value
Invisible NULL.
Detect the preferred local Ollama model
Description
Walks getOption("corteza.local_models") (default
c("gpt-oss:120b", "gpt-oss:20b")) and returns the first one that
is currently installed in the local Ollama server. Returns NULL if
Ollama is unreachable or none of the candidates are installed.
Cached per R process.
Usage
default_local_model()
Value
Character scalar model name, or NULL.
Examples
# NULL when Ollama isn't running locally; a model name otherwise.
model <- default_local_model()
is.null(model) || is.character(model)
Provider-specific default model name.
Description
Resolves the actual model a subagent (or chat session) will run
with when no explicit model is set, so /agents, compaction,
and the CLI all show the same model identity. Delegates to
llm.api::provider_default_model() – the canonical table –
rather than keeping a parallel one that drifts. Returns NULL for an
unknown or empty provider (llm.api errors there; we map it to NULL).
Usage
default_provider_model(provider)
Arguments
provider |
Provider name. |
Value
Model name (character) or NULL.
Ensure skills are registered.
Description
Registers built-in skills if not already registered. Exported with ‘@keywords internal' so a subagent’s 'callr::r_session' child can register skills in its own namespace (via 'worker_init()') before dispatching tools.
Usage
ensure_skills()
Value
Invisible character vector of skill names.
Token estimate for a list of messages (history).
Description
Sums text tokens for each message and adds a small framing overhead (6 tokens / message) that the chars/4 estimate misses.
Usage
estimate_history_tokens(messages)
Arguments
messages |
List of message lists, each with '$role' and '$content'. |
Value
Integer.
Token estimate for an entire live model-context.
Description
Sum of system prompt + tool schema + message history, plus framing overheads. Used to drive auto-compaction triggers.
Usage
estimate_live_context_tokens(session, system_prompt = NULL, tools = NULL)
Arguments
session |
Session-like object with '$messages' list. |
system_prompt |
Character or NULL. |
tools |
List of tool definitions or NULL. |
Value
Integer.
Rough token estimate from raw text.
Description
Returns 'ceil(nchar(text) / 4)'. Good enough for budget decisions but not a substitute for the provider's real usage count.
Usage
estimate_text_tokens(text)
Arguments
text |
Character (length 1 or vector; collapsed with newlines). |
Value
Integer.
Token estimate for the tool schema payload.
Description
Serializes the tool list as JSON and counts tokens, plus a 12- token overhead per tool for the schema framing.
Usage
estimate_tool_tokens(tools)
Arguments
tools |
List of tool definitions (or NULL). |
Value
Integer.
Format an age in seconds as a compact string (e.g. "12s", "3m", "2h").
Description
Format an age in seconds as a compact string (e.g. "12s", "3m", "2h").
Usage
format_age(seconds)
Arguments
seconds |
Age in seconds. |
Value
A character string.
Format a live-context display like "4.2K/200K" or "?".
Description
Used by /agents to summarize live tokens versus model limit.
Usage
format_live_ctx(tokens, limit)
Arguments
tokens |
Live context, in tokens. |
limit |
The model's context window, in tokens. |
Value
A character string: "tokens/limit", or "?" when either value is NA.
Format a token count for display (K / M suffixes).
Description
Format a token count for display (K / M suffixes).
Usage
format_tokens(n)
Arguments
n |
Token count. |
Value
Character.
Install corteza CLI
Description
Install the corteza command-line tool. On Unix (Linux, macOS)
installs the Rscript shebang binary. On Windows installs a
.cmd wrapper alongside the script so corteza works from
cmd.exe / PowerShell.
Usage
install_cli(path = NULL, force = FALSE)
Arguments
path |
Directory to install to. Default is
|
force |
Overwrite existing installation. |
Details
Requires:
-
r(littler) for fast R script execution (Unix only — Windows usesRscript). The
llm.apipackage for LLM connectivityThe
cortezapackage itself
After installation, run corteza from any terminal. The
default directory is not in PATH, and the function prints the line
that adds it.
An install made by 0.8.0 or earlier stays in ~/bin until you
replace it (install_cli("~/bin", force = TRUE)) or remove it
(uninstall_cli("~/bin")). A shell that finds that copy first
keeps running it, so both functions say when one is there.
Value
The installed script path, invisibly.
Examples
# Into a directory of your choosing, here a throwaway one. With no
# argument the command goes to R's user data directory.
bin <- file.path(tempdir(), "corteza-bin")
install_cli(bin)
uninstall_cli(bin)
unlink(bin, recursive = TRUE)
Deprecated: use bot_archive_all()
Description
Deprecated: use bot_archive_all()
Usage
matrix_archive_all(
sessions,
mx_sess = NULL,
chat = NULL,
on_archive = NULL,
cfg = NULL
)
Arguments
sessions |
A registry environment built by
|
mx_sess |
Ignored. Kept so calls written for corteza 0.7.1 still run. |
chat |
Optional chat.api client, handed to the hook. |
on_archive |
The host's |
cfg |
The bot config, which names the bot. NULL reads the saved one when there is a hook. |
Value
See bot_archive_all.
See Also
Examples
## Not run:
matrix_archive_all(sessions) # use bot_archive_all()
## End(Not run)
Deprecated: use bot_configure()
Description
Deprecated: use bot_configure()
Usage
matrix_configure(
server,
user,
password,
room,
model = NULL,
provider = "anthropic",
tools_filter = NULL,
auto_approve_asks = FALSE,
bots = NULL,
models = NULL,
model_badge = c("never", "non_default", "always"),
display_name = NULL,
fallback = NULL,
cwd = NULL,
operators = NULL,
project_roots = NULL
)
Arguments
server |
Character. Homeserver base URL. |
user |
Character. Bot localpart or full Matrix ID. |
password |
Character. Bot password. Stored locally so the bot can re-authenticate if its access token is invalidated. |
room |
Character. Room ID or alias the bot should read and post to. If the bot has been invited but not joined, it will be joined. |
model |
Character or NULL. Default model name. |
provider |
Character. LLM provider: "anthropic", "anthropic_claude", "openai", "openai_codex", "moonshot", or "ollama". |
tools_filter |
Character vector or NULL. Passed to
|
auto_approve_asks |
Logical. Who rules on a tool call that
needs approval. Rules in code read every call first, and what they
catch (credentials, writes outside the project, elevated
privileges, other machines, publishing, discarded work) is always
put to a person by reaction in the room. When TRUE, the rest goes
to a monitor: a read-only model in its own process that approves,
refuses, or passes the call on to a person. When FALSE (default) a
person is asked for the rest as well. Nothing is approved unseen.
The monitor's model is set under |
bots |
Character vector or NULL. Full Matrix IDs of other known bot accounts. Their messages only get a reply when they mention this bot, and they are not counted as humans when deciding whether a room gets ungated replies (a room whose only non-bot member is one human is answered without a mention). |
models |
Character vector or NULL. Extra entries for the
|
model_badge |
Character. When to show which model is answering:
|
display_name |
Character or NULL. Base display name the badge rename builds on. Defaults to the localpart of the bot's user id. |
fallback |
Character vector or NULL. What |
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one with |
operators |
Character vector or NULL. The people the bot answers
to, each a full Matrix id such as |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Value
See bot_configure.
See Also
Examples
## Not run:
matrix_configure(server, user, password, room) # use bot_configure()
## End(Not run)
Deprecated: use bot_poll()
Description
Deprecated: use bot_poll()
Usage
matrix_poll(
system = NULL,
model = NULL,
provider = NULL,
tools_filter = NULL,
timeout = 0L,
sessions = NULL,
crypto = NULL,
hooks = NULL,
cwd = NULL,
project_roots = NULL
)
Arguments
system |
Character or NULL. System prompt override. |
model |
Character or NULL. Model override. |
provider |
Character or NULL. Provider override. |
tools_filter |
Character vector or NULL. Tool filter override. |
timeout |
Integer. Long-poll timeout in milliseconds. 0 returns immediately. |
sessions |
Environment from |
crypto |
Ignored. Kept so calls written for corteza 0.7.1 still run; the chat transport handles encryption now. |
hooks |
Named list of functions or NULL, as validated by
|
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one with |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Value
See bot_poll.
See Also
Examples
## Not run:
matrix_poll() # use bot_poll()
## End(Not run)
Deprecated: use bot_request_flush()
Description
Deprecated: use bot_request_flush()
Usage
matrix_request_flush()
Value
See bot_request_flush.
See Also
Examples
# Use bot_request_flush(). Like it, this writes a sentinel file under
# CORTEZA_STATE_DIR, sent to a temporary folder here.
old <- Sys.getenv("CORTEZA_STATE_DIR", unset = NA)
Sys.setenv(CORTEZA_STATE_DIR = file.path(tempdir(), "state"))
sig <- matrix_request_flush() # warns that it is deprecated
file.exists(sig)
unlink(Sys.getenv("CORTEZA_STATE_DIR"), recursive = TRUE)
if (is.na(old)) {
Sys.unsetenv("CORTEZA_STATE_DIR")
} else {
Sys.setenv(CORTEZA_STATE_DIR = old)
}
Deprecated: use bot_run()
Description
Deprecated: use bot_run()
Usage
matrix_run(
timeout = 30000L,
system = NULL,
model = NULL,
provider = NULL,
tools_filter = NULL,
cwd = NULL,
project_roots = NULL
)
Arguments
timeout |
Integer. Long-poll timeout in milliseconds. |
system |
Character or NULL. System prompt override. |
model |
Character or NULL. Model override. |
provider |
Character or NULL. Provider override. |
tools_filter |
Character vector or NULL. Tool filter override. |
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one; see |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Value
See bot_run.
See Also
Examples
## Not run:
matrix_run() # use bot_run()
## End(Not run)
Deprecated: use bot_run_init()
Description
Deprecated: use bot_run_init()
Usage
matrix_run_init(
system = NULL,
model = NULL,
provider = NULL,
tools_filter = NULL,
hooks = NULL,
cwd = NULL,
project_roots = NULL
)
Arguments
system |
Character or NULL. System prompt override. |
model |
Character or NULL. Model override. |
provider |
Character or NULL. Provider override. |
tools_filter |
Character vector or NULL. Tool filter override. |
hooks |
Named list of functions or NULL. Policy the loop asks
the host about; see Hooks. NULL, the default, means a bare bot:
|
cwd |
Character or NULL. The directory a room works in when no
operator has bound it to one with |
project_roots |
Character vector or NULL. The directories inside
which an operator may bind a room with |
Value
See bot_run_init.
See Also
Examples
## Not run:
matrix_run_init() # use bot_run_init()
## End(Not run)
Deprecated: use bot_run_step()
Description
Deprecated: use bot_run_step()
Usage
matrix_run_step(state, timeout = 30000L)
Arguments
state |
A state object from |
timeout |
Integer. Long-poll timeout in milliseconds. |
Value
See bot_run_step.
See Also
Examples
## Not run:
matrix_run_step(state) # use bot_run_step()
## End(Not run)
Deprecated: use bot_send()
Description
Deprecated: use bot_send()
Usage
matrix_send(text, room_id = NULL, msgtype = "m.text", markdown = FALSE)
Arguments
text |
Character. Plain text body. |
room_id |
Character. Matrix room id. Defaults to |
msgtype |
Character. Matrix msgtype, default "m.text". |
markdown |
Logical. If TRUE, also send Matrix custom HTML derived from a conservative markdown subset. |
Value
See bot_send.
See Also
Examples
## Not run:
matrix_send("hello") # use bot_send()
## End(Not run)
Maybe compact a turn_session's in-memory history.
Description
Decision points: - Compaction mode off → return invisibly without checking. - History shorter than 'min_messages' → skip (nothing to gain). - Live token usage and serialized request size below thresholds → skip. The token threshold is the smaller of 'context_compact_pct' of the window and ‘context_compact_tokens'. Ahead of a turn’s first request, a session idle for 'context_idle_minutes' with 'context_idle_tokens' of context compacts below it (R/compact-trigger.R). - No safe cut available (e.g. open tool_use) → skip. - Summarizer fails → log and leave history intact. The session's next summary then reads the smaller budget of 120,000 characters, until one succeeds. So does a summary made after the provider refused a request for its size (R/compact-trigger.R).
Usage
maybe_compact_turn_session(
session,
config,
kind = NULL,
tools = NULL,
system = NULL,
threshold,
byte_limit,
min_messages,
reason = "threshold",
now = Sys.time()
)
Arguments
session |
A turn_session ('new_session()'). |
config |
Full corteza config (post-defaults). |
kind |
Optional marker. "archive_holder" skips compaction entirely so seeded transcript history is preserved. |
tools |
Optional exact model-facing tool schema. Direct 'turn()' callers with custom tools should pass it; otherwise tools are resolved from 'session$tools_filter' as before. |
system |
Optional exact model-facing system prompt. |
threshold |
Optional explicit percentage. When omitted, parent/direct sessions use 'config$context_compact_pct' and subagents use their stricter inherited policy. Explicit NULL disables compaction. |
byte_limit |
Optional serialized-request threshold. When omitted, 'config$context_compact_bytes' applies to 'openai_codex'; other providers have no byte threshold. Explicit 'Inf' disables the byte guard. |
min_messages |
Optional minimum history entries. The ordinary policy uses its configured value; forced overflow recovery may lower this because a few individual entries can themselves exceed the context window. |
reason |
Short lifecycle marker recorded in the compaction event. ‘"preflight"', the check ahead of a turn’s first request, is also where a session back from an idle gap compacts; the event then carries the reason '"idle"'. |
now |
The time the idle gap is measured to. A test passes its own. |
Details
On success, mutates 'session$history' in place. Returns invisibly TRUE if compaction ran successfully, FALSE otherwise.
Build a tool executor that routes through an MCP connection
Description
Returns a closure suitable for the tool_executor argument of
turn. Each tool call is forwarded to the connected MCP
server via llm.api::mcp_call.
Usage
mcp_tool_executor(conn)
Arguments
conn |
An open MCP connection (from |
Value
A function with signature function(name, args) that
returns an MCP-format result list.
Examples
## Not run:
# Needs an open MCP connection to a running corteza::serve().
conn <- llm.api::mcp_connect("tcp://localhost:7850")
executor <- mcp_tool_executor(conn)
s <- new_session(provider = "anthropic")
turn("Hello", s, tool_executor = executor)
## End(Not run)
Best-effort flatten of a message's 'content' field into one string.
Description
Messages may have content as a plain string or a list of typed blocks (text / tool_use / tool_result). For budget math we just want the textual surface area.
Usage
message_text(message)
Arguments
message |
Single message list. |
Value
Character.
Create a new turn session
Description
Returns an environment with sensible defaults. Adapters set channel-
specific fields (e.g. approval_cb, tools_filter) before
calling turn.
Usage
new_session(
channel = c("cli", "console", "matrix"),
history = NULL,
model_map = NULL,
provider = "anthropic",
tools_filter = NULL,
system = NULL,
approval_cb = NULL,
max_turns = 10L,
verbose = FALSE,
plan_mode = FALSE,
web_search = NULL,
base_url = NULL,
max_tokens = NULL,
reasoning_effort = NULL,
thinking_budget_tokens = NULL,
cache = NULL,
compaction_prompt = NULL,
context_edit = NULL
)
Arguments
channel |
Character, one of "cli", "console", "matrix". |
history |
List of prior messages, or NULL. Thinking blocks are removed from it: a provider accepts one only in the conversation that produced it. |
model_map |
Named list with |
provider |
LLM provider passed to |
tools_filter |
Character vector passed to |
system |
System prompt override (NULL for built-in default). |
approval_cb |
Function called when policy returns |
max_turns |
Maximum LLM turns per call. |
verbose |
Print tool call progress. |
plan_mode |
Logical. When TRUE, the session is in plan mode:
the next prompt opens with a note telling the LLM to research and
propose without acting, and the policy engine denies write/exec
tool calls. |
web_search |
Logical or NULL. When TRUE and the provider
supports it, |
base_url |
Character or NULL. Endpoint for the
|
max_tokens |
Integer or NULL. Per-response output-token budget,
forwarded to |
reasoning_effort |
Character or NULL. How hard a reasoning
model should think before answering, e.g. |
thinking_budget_tokens |
Integer or NULL. Extended-thinking
budget for Anthropic models, forwarded to |
cache |
Character or NULL. Anthropic prompt-cache TTL:
|
compaction_prompt |
Character or NULL. Optional domain-specific instructions for summarizing older history during context compaction. NULL uses corteza's general coding-agent summary brief. The prompt affects only the summarizer; the main agent system prompt is unchanged. |
context_edit |
NULL to inherit configuration, a logical enable switch, or a list with 'enabled' and 'cadence' ('"pressure"' or '"always"'). Context editing requires the session journal and a supported history shape. |
Value
An environment holding the session state.
Examples
# Build a stateless session for the CLI channel without making any
# network calls. The returned environment carries history, the
# active provider/model, and the approval callback.
s <- new_session(channel = "cli", provider = "anthropic")
is.environment(s)
identical(s$provider, "anthropic")
Built-in progress observer that prints to stdout
Description
Prints one line per tool call suitable for an interactive REPL:
" [tool] hint (N lines)\n". The hint is a short summary of
the call (file path, code snippet, search pattern) computed by
tool_hint().
Usage
observer_progress()
Value
A function to pass to add_observer.
Examples
obs <- observer_progress()
s <- new_session(provider = "anthropic")
add_observer(s, obs)
Evaluate policy for a tool call
Description
Returns a decision list(model, approval, reason). model is
"cloud" or "local"; nothing routes on it yet.
approval is "allow", "ask", or "deny". A
verdict from the credential rule also carries
rule = "credential", one that asks before leaving plan mode
rule = "plan_exit", one from plan mode
rule = "plan_mode", and one from a room with no directory
rule = "unbound_room". A person answers the first two each
time: a saved "always" does not, and a prompt offers none.
Usage
policy(call, config = NULL)
Arguments
call |
A list describing the tool call. See the file header in
|
config |
Optional config list from |
Details
Every tool has a class, declared where it is registered:
"read", "write", "exec", "control" (acts on
the session's own work) or "continue" (runs work in a child, a
worker or another room). A tool that declares none is
"unknown". By default read, control and
continue are allowed, and write, exec and
unknown ask. Plan mode refuses write, exec,
continue and unknown. A Matrix room with no directory
(context$unbound) refuses everything but read and a few
named control tools. Nothing lifts a mode's refusal. A path
under a credential store asks next, whatever follows.
When config is supplied, the user's settings are overlaid on
the table: a permissions entry replaces the verdict for its
tool, a tool named in dangerous_tools asks, and
approval_mode says what "ask" means for a tool with no
permissions entry. None of them lifts a deny.
Both corteza::chat() and the CLI tool dispatch loop pass
their session's config through here so the /permissions
contract advertised by both surfaces is enforced consistently.
serve() does not: an MCP client asks its own user.
Value
A decision list with fields model, approval,
reason.
Examples
# A bare-environment read_file call resolves under the default
# built-in policy without needing any session config.
decision <- policy(list(tool = "read_file",
args = list(path = "DESCRIPTION")))
decision$approval
Register a skill whose schema is derived from its function.
Description
Register a skill whose schema is derived from its function.
Usage
register_skill_from_fn(tool_name, fn, available = NULL, class = NULL)
Arguments
tool_name |
Name the LLM sees. |
fn |
The R function to introspect and execute. |
available |
Optional zero-argument predicate. When it returns 'FALSE', [schema_from_registry()] omits the tool from the LLM payload. Used for context-aware pruning (e.g. git tools gated on a real git repo, web tools on an API key being set). The tool stays registered and callable regardless. |
class |
What the tool does, which decides who approves a call: '"read"', '"write"', '"exec"', '"control"' or '"continue"'. 'NULL' leaves the tool '"unknown"', so a call to it asks, and plan mode refuses it. See [policy()]. |
Value
Invisible tool name.
Derive an LLM tool schema from an R function's signature and docs.
Description
Derive an LLM tool schema from an R function's signature and docs.
Usage
schema_from_fn(fn_name, pkg = "corteza", max_desc_chars = 200L)
Arguments
fn_name |
Name of the function to introspect (must be in 'pkg'). |
pkg |
Package that owns the function. |
max_desc_chars |
Cap on the generated description length. |
Value
A tool-definition list with 'name', 'description', and 'input_schema' ready for the Anthropic chat-API 'tools' parameter.
Build the LLM API 'tools' payload from the tool registry.
Description
Returns a list of tool definitions in the shape Anthropic's chat completion API expects (name, description, input_schema). Built in-process from the shared registry.
Usage
schema_from_registry(filter = NULL)
Arguments
filter |
Optional tool-name or category filter; see 'get_tools()'. |
Details
Exported with '@keywords internal': the CLI calls this directly, but it is not part of the public user-facing API.
Value
List of tool definitions.
Start MCP Server
Description
Start the corteza MCP server. This exposes R tools to MCP clients like Claude Desktop, VS Code, or the corteza CLI.
Usage
serve(port = NULL, cwd = NULL, tools = NULL, expose_subagents = NULL)
Arguments
port |
Port number for socket transport. If NULL, uses stdio transport. |
cwd |
Working directory for the server. Defaults to current directory. |
tools |
Character vector of tools or categories to enable. Categories: file, code, r, data, web, git, chat. Use "core" for file+code+git, "all" for everything (default). |
expose_subagents |
Whether MCP clients may call the subagent tools ('spawn_subagent', 'query_subagent', 'collect_subagent', 'list_subagents', 'kill_subagent'). 'NULL' (default) defers to the 'subagents$expose_over_mcp' config flag (itself FALSE by default); 'TRUE'/'FALSE' overrides it. Off by default because a spawned subagent runs its own agent loop and spends autonomously on the host's LLM credentials – an unattended MCP client could otherwise trigger unbounded cost the client never sees. When on, cumulative subagent spend is capped by 'subagents$mcp_spend_cap_usd' (default $5.00). |
Details
The server supports two transport modes:
- **stdio** (default): For Claude Desktop and other MCP clients. Communication happens via stdin/stdout.
- **socket**: For the corteza CLI and R clients. Listens on a TCP port.
## Tools Provided
- 'read_file', 'write_file', 'replace_in_file', 'list_files', 'grep_files' - File operations - 'run_r' - Execute R code in the server session - 'bash' - Run shell commands - 'r_help' - Query package docs via saber (exports, function help) - 'installed_packages' - List installed packages - 'web_search' - Search the web via Tavily (requires TAVILY_API_KEY) - 'fetch_url' - Fetch web content - 'git_status', 'git_diff', 'git_log' - Git operations - 'chat', 'chat_models' - LLM chat (requires llm.api)
## Approval
A call from an MCP client runs without [policy()] and without an approval prompt: the client asks its own user, and a server has nobody to ask. What the server decides is which tools it offers. 'tools' sets that list, a call to a tool outside it is refused, and the subagent tools are refused unless 'expose_subagents' allows them.
Value
NULL (runs until interrupted or client disconnects)
Examples
## Not run:
# For Claude Desktop (stdio)
serve()
# For corteza CLI (socket) with all tools
serve(port = 7850)
# Minimal tools for small context models
serve(port = 7850, tools = "core")
# Specific categories
serve(port = 7850, tools = c("file", "git"))
## End(Not run)
Configure and construct a session for any channel
Description
Performs pre-turn setup common to all channels:
Usage
session_setup(
channel = c("cli", "console", "matrix"),
cwd = getwd(),
provider = NULL,
model = NULL,
tools = NULL,
system = NULL,
approval_cb = NULL,
history = NULL,
load_project_context = TRUE,
validate_api_key = TRUE,
verbose = FALSE,
max_turns = 50L,
web_search = NULL
)
Arguments
channel |
Character, one of |
cwd |
Working directory. Defaults to the current directory. |
provider |
Character or NULL. LLM provider override. NULL falls
back to |
model |
Character or NULL. Model override. NULL falls back to
|
tools |
Character vector, NULL, or the string |
system |
Character or NULL. System prompt. NULL auto-builds via the
saber-backed context manifest when |
approval_cb |
Function or NULL. Approval callback for
|
history |
List or NULL. Prior conversation messages to seed
the session with (each entry a list with |
load_project_context |
Logical. When TRUE, auto-call the saber manifest and rendered system prompt. Channels that supply their own system prompt pass FALSE. |
validate_api_key |
Logical. When TRUE, error if the provider's API key env var is unset or empty. |
verbose |
Logical. Passed through to |
max_turns |
Integer. Passed through to |
web_search |
Logical or NULL. Provider-native web search toggle
passed through to |
Details
Loads project + global corteza config from
cwd. The project's files (its config, skills, instructions, lessons and briefing) are read only where the user has trusted the directory: see "Trusted projects" invignette("configuration").Resolves provider, model, and verifies the required API environment variable is set.
Builds the session's own tool table: the built-in tools, the user's skills from
tools::R_user_dir("corteza", "data")/skills, the package functions the config lists and, in a trusted directory, the skills in<cwd>/.corteza/skills. The session offers and runs these, whatever another session in the process loads; a skill whose name is already taken is skipped with a message. Loads the skill docs from the same folders.Optionally builds the system prompt and source manifest via
load_context_bundle(cwd).Returns a
new_session()built from the above.
Value
A session environment from new_session, with
extra cwd, config and tool_table fields and, for
an auto-built system prompt, a context_manifest field.
Examples
# Reads the user's config and builds the tool table; sends nothing.
s <- session_setup("console", cwd = tempdir(), provider = "anthropic",
load_project_context = FALSE, validate_api_key = FALSE)
s$provider
Remove what old sessions no longer need
Description
corteza keeps its sessions under
tools::R_user_dir("corteza", "data"). For every session that
has not been used for days, this removes its journal (in
<id>.journal/: the provider-native record of the live history
and of every history a compaction replaced), its tool trace
(<id>_trace.jsonl), and the files a chat room's session kept of
what people sent it (<id>.attachments/).
Usage
sessions_prune(dry_run = FALSE, days = NULL)
Arguments
dry_run |
If |
days |
Sessions unused for at least this many days lose their
journal, trace and attachments, and job records, worker folders and
remote-control sessions unchanged for as long go. Default:
|
Details
It also removes, from corteza's state folder (state/ in the
same place, or CORTEZA_STATE_DIR) and its remote-control folder
(remote-control/, or CORTEZA_REMOTE_DIR):
a delegated job's records, with every job linked to it as a resume, a review or a delegation, once all of them have ended and none has changed for
days. While one of them is queued or running, all stay. A job that ended incomplete and was never resumed keeps the snapshot a resume starts from, so its chain waits forretention$incomplete_daysin the user's config (default 180; never fewer thandays; 0 keeps it);a worker process's folder that holds no checkpoint, unchanged for
days: its journal, less its audit records;a worker's folder with a checkpoint (the R objects and history a delegated job's worker left), once both the folder and the session it belongs to have gone unused for
days: at the terminal the conversation's session, in a chat room the room's or thread's session, judged by its journal. The checkpoint goes first, then the rest, less the journal's audit records;a remote-control session unchanged for
daysthat was closed, or whose process on this machine has ended.
A worker's folder stays, whatever its age, while its worker process is alive, while its session is open in the process doing the removing, and while a job is open in its directory.
Transcripts, session stores, configuration, audit events and crypto state are kept. A session whose journal is gone still resumes from its transcript. A chat room that restores its context from its journal starts its next conversation fresh.
A session's audit records are kept in its journal folder, under
audit/, and a job's in its own folder. Separate personal retention
settings opt into expiring unpinned payloads (audit_payload_days),
old journal segments (journal_segment_days) and legacy R workspace
snapshots beside a transcript (workspace_snapshot_days). Each
defaults to zero. The latest committed segment and live history stay.
A session was last used when its journal, its trace, its transcript or
its attachments last changed, whichever is newest. A symbolic link is
never removed, nor anything reached through one. A folder in the state
or remote-control folder whose name and record are not of the form
corteza writes stays whole; once it is days old it is listed
with kind "unknown", so it can be looked at.
corteza runs this itself at most once a day: when a terminal session
starts, and while a chat bot runs. The session a terminal has open, and
the rooms a bot has open, are left alone. The number of days is
retention$session_days in
the user's config file (default 90; 0 keeps everything). A project's
config cannot change either setting.
Value
A data frame with one row per journal, trace, attachments
folder, job folder, worker folder, remote-control session or unknown
folder, or file eligible under a separate lifetime, invisibly:
agent (NA outside a session's
files), session (for a job, its chain's newest job),
kind ("journal", "trace", "attachments",
"job", "worker", "checkpoint", "remote",
"segment", "entry", "payload", "workspace snapshot"
or "unknown"), path, last_use, idle_days,
bytes, incomplete (a job chain kept longer for its
resume snapshot) and removed.
Examples
# A data directory under tempdir(), so that nothing of yours is read
# or removed.
old <- Sys.getenv("R_USER_DATA_DIR", unset = NA)
Sys.setenv(R_USER_DATA_DIR = file.path(tempdir(), "corteza-data"))
# A session last used 100 days ago: a journal and a transcript.
sessions <- file.path(tools::R_user_dir("corteza", "data"), "agents",
"main", "sessions")
journal <- file.path(sessions, "example.journal")
transcript <- file.path(sessions, "example.jsonl")
dir.create(journal, recursive = TRUE)
writeLines("{}", file.path(journal, "live.json"))
writeLines("{}", transcript)
long_ago <- Sys.time() - 100 * 24 * 60 * 60
Sys.setFileTime(c(file.path(journal, "live.json"), journal, transcript),
long_ago)
sessions_prune(dry_run = TRUE, days = 90)
sessions_prune(days = 90)
list.files(sessions)
unlink(file.path(tempdir(), "corteza-data"), recursive = TRUE)
if (is.na(old)) {
Sys.unsetenv("R_USER_DATA_DIR")
} else {
Sys.setenv(R_USER_DATA_DIR = old)
}
Install a skill from a path or URL
Description
Install a skill from a path or URL
Usage
skill_install(source, target_dir = NULL, force = FALSE)
Arguments
source |
Path to skill directory or URL |
target_dir |
Installation directory. Default is
|
force |
Overwrite if exists |
Value
Installed skill name
Examples
# Install into a throwaway directory rather than the user's
# R_user_dir, so this example doesn't mutate state.
src <- file.path(tempdir(), "demo_skill")
dir.create(src, showWarnings = FALSE)
writeLines(c(
"---",
"name: demo",
"description: A demo skill",
"---",
"Demo body."
),
file.path(src, "SKILL.md"))
dest <- file.path(tempdir(), "skills_lib")
skill_install(src, target_dir = dest)
unlink(src, recursive = TRUE)
unlink(dest, recursive = TRUE)
List installed skills
Description
List installed skills
Usage
skill_list_installed(skill_dir = NULL)
Arguments
skill_dir |
Skills directory |
Value
Data frame with skill info
Examples
# List skills from an empty tempdir; returns a zero-row data frame
# with the documented columns.
empty <- file.path(tempdir(), "empty_skills")
dir.create(empty, showWarnings = FALSE)
skill_list_installed(skill_dir = empty)
unlink(empty, recursive = TRUE)
Remove an installed skill
Description
Remove an installed skill
Usage
skill_remove(name, skill_dir = NULL)
Arguments
name |
Skill name |
skill_dir |
Skills directory |
Value
Invisible TRUE on success
Examples
# Install a demo skill into a tempdir, then remove it. The
# installed name is the source directory's basename.
src <- file.path(tempdir(), "demo_skill")
dir.create(src, showWarnings = FALSE)
writeLines(c("---", "name: demo_skill",
"description: A demo skill", "---"),
file.path(src, "SKILL.md"))
dest <- file.path(tempdir(), "skills_lib")
name <- skill_install(src, target_dir = dest)
skill_remove(name, skill_dir = dest)
unlink(src, recursive = TRUE)
unlink(dest, recursive = TRUE)
Run skill tests
Description
Executes test_*.R files in a skill directory.
Usage
skill_test(path, verbose = TRUE)
Arguments
path |
Path to skill directory |
verbose |
Print test output |
Value
List with passed, failed, errors
Examples
# A skill directory with no test_*.R files returns a zero-result
# summary rather than erroring.
p <- file.path(tempdir(), "skill_no_tests")
dir.create(p, showWarnings = FALSE)
skill_test(p, verbose = FALSE)
unlink(p, recursive = TRUE)
Collect the result of a previously-fired async subagent query.
Description
Pairs with 'subagent_query(..., wait = FALSE)'. Returns the reply text once the child finishes its turn, or NULL while the query is still running. Result is read exactly once: after a successful collect the pending slot is cleared, so the next async query can fire.
Usage
subagent_collect(id, wait = TRUE, timeout = 60L)
Arguments
id |
Subagent identifier (UUID, prefix, or sequence number). |
wait |
If TRUE (default), block up to 'timeout' seconds waiting for the child to finish. If FALSE, poll once and return immediately. |
timeout |
Maximum seconds to block when 'wait = TRUE'; 'Inf' waits until the child replies. On timeout the child is left running; caller may collect again later or kill explicitly. |
Value
Reply text (character) when ready; NULL when still running.
Examples
## Not run:
# Requires LLM credentials in the child's environment.
id <- subagent_spawn("background research")
subagent_query(id, "what's in DESCRIPTION?", wait = FALSE)
# ... do other work ...
subagent_collect(id, wait = TRUE, timeout = 30)
subagent_kill(id)
## End(Not run)
Resolve the effective compaction threshold for a subagent.
Description
Returns a numeric percent. NULL means "compaction off for this child" — caller skips entirely.
Usage
subagent_compact_threshold(config)
Arguments
config |
Full corteza config (post-defaults). |
Value
Numeric percent in (0, 100], or NULL.
Kill a subagent.
Description
Kill a subagent.
Usage
subagent_kill(id)
Arguments
id |
Subagent identifier (UUID, prefix, or sequence number). |
Value
Invisible TRUE if killed, FALSE if not found.
Examples
# Unknown id is a silent no-op (returns FALSE), so this is safe to
# run during R CMD check without a live subagent.
subagent_kill("no-such-id")
List active subagents.
Description
Returns a list of info objects per agent: id/seq/task/started_at/ time_remaining/pending plus model/age/cumulative usage and a best-effort live token count for idle agents ('NA' for busy).
Usage
subagent_list()
Value
List of subagent info objects.
Examples
# Empty when no subagent has been spawned yet -- safe to call any time.
subagent_list()
Query a subagent.
Description
Sends a prompt to a running subagent. Inside the child it runs through [turn()] with the child's persistent turn session: the LLM replies, any tool calls it makes resolve against the child's in-process skill registry, and history accumulates across queries.
Usage
subagent_query(
id,
prompt,
wait = TRUE,
timeout = 60L,
return_name = NULL,
report = FALSE
)
Arguments
id |
Subagent identifier. Accepts the canonical UUID, a unique UUID prefix, or the per-session sequence number printed by 'subagent_list()' / '/agents'. |
prompt |
Prompt to send. |
wait |
If TRUE (default), block up to 'timeout' seconds for the child's reply and return the reply text. If FALSE, fire the prompt and return the canonical id invisibly; caller must collect via [subagent_collect()]. |
timeout |
Maximum seconds to block when 'wait = TRUE'; 'Inf' waits until the child replies. On timeout the query stays pending: collect it later with [subagent_collect()] or end it with [subagent_kill()]. |
return_name |
Optional single name or '.h_NNN' handle for a value the child should hand back. When set, the child must have left the result bound under that name (e.g. via 'run_r'); the resolved value is stashed in the parent handle store and the reply gains a '[stored as .h_NNN]' block referencing it. Requires a subagent with 'run_r' (the 'work' preset). For 'wait = FALSE' the name is captured now and applied when collected. |
report |
Logical. When TRUE, require a structured handoff with status, notes, findings, concerns, deviations, open questions, and feedback. The ordinary character reply remains the return value; the report is rendered into it for model callers and retained in its 'corteza_report' attribute for R callers. |
Details
Both paths fire the prompt the same way, as a one-shot call on the child's 'callr::r_session'. With 'wait = FALSE' the call returns immediately and the parent collects the reply later with [subagent_collect()]. With 'wait = TRUE' the call collects on the parent's behalf, but only up to 'timeout' seconds: a child that has not replied by then is left running with the query pending, and the call returns NULL, so the wait is bounded by default ('Inf' opts out). A subagent can only carry one in-flight query at a time: firing a second one while the first is pending raises an error.
Value
Reply text (character) when 'wait = TRUE' and the child replied within 'timeout', with a handle block appended when 'return_name' resolved; NULL (invisibly) when the timeout elapsed and the query is still pending. Canonical id (character, invisibly) when 'wait = FALSE'.
Examples
## Not run:
# Requires LLM credentials in the child's environment.
id <- subagent_spawn("read R/skill.R and summarize", preset = "minimal")
subagent_query(id, "what does this file do?", wait = TRUE)
subagent_kill(id)
## End(Not run)
Seed the child's turn-session history with an externally-built slice.
Description
Used by the archival runtime: the parent spawns a holder subagent, then ships the just-finished turn's history into the holder via this function so the holder owns the full transcript while the parent keeps only '{summary, subagent_id}'.
Usage
subagent_seed_history(history)
Arguments
history |
List of message entries. |
Value
Invisible TRUE.
Spawn a subagent.
Description
Starts a fresh 'callr::r_session' with corteza loaded and its tool registry set up. Stores the handle in the package-level registry keyed by subagent id.
Usage
subagent_spawn(
task,
model = NULL,
tools = NULL,
preset = NULL,
parent_session = NULL,
config = NULL
)
Arguments
task |
Task description (stored for bookkeeping; not yet fed into an agent loop). |
model |
Optional model override (reserved for later use). |
tools |
Optional explicit tool filter (character vector). Overrides 'preset' when provided. Fixed for the lifetime of the child – cannot be expanded after spawn. |
preset |
Preset name (fixed for the lifetime of the child). '"investigate"' (default): 'read_file', 'grep_files', 'r_help', 'web_search', 'fetch_url'. '"work"': investigate + 'bash', 'write_file', 'replace_in_file', 'list_files', 'git_status', 'git_diff', 'git_log', 'run_r'. '"minimal"': 'read_file', 'grep_files'. '"monitor"': the read-only hall monitor used to supervise unattended auto runs – 'read_file', 'grep_files', 'list_files', 'git_status', 'git_diff', 'git_log', and provider-native web search explicitly off. |
parent_session |
Parent session object; read for nested-spawning control and session-key derivation. |
config |
Config list. |
Details
Permissions: subagents have no interactive approval channel back to the parent or user. The child's 'approval_cb' denies by default and there is no mid-run escalation path. Whatever capability the child needs must be granted at spawn time through 'preset' or 'tools'. If a task may need shell, write, or network capability, pick a preset that includes it (or pass an explicit 'tools' list); otherwise the child should report that it is blocked rather than retry.
Value
Subagent ID (character).
Examples
if (interactive()) {
# Spawns a callr::r_session child loaded with corteza; the
# registry is in-memory and dies with the parent R session, so
# we wrap in interactive() to keep R CMD check from leaving
# children behind.
id <- subagent_spawn("look up the package version",
preset = "minimal")
subagent_kill(id)
}
Initialize the child-side turn session.
Description
Called once per child just after [worker_init()]. Creates a ‘new_session()' configured with the subagent’s provider/model/tools and stores it where [subagent_turn_prompt()] can find it. The child's 'approval_cb' denies by default: subagents have no interactive approval channel back to the parent or user, and tool permissions are fixed at spawn time via 'tools_filter' (derived from the parent's 'preset' or explicit 'tools' argument to [subagent_spawn()]). There is no way to grant additional capability mid-run.
Usage
subagent_turn_init(
provider = "anthropic",
model = NULL,
tools_filter = NULL,
system = NULL,
max_turns = 10L,
depth = 0L,
plan_mode = FALSE,
web_search = NULL,
allowed_paths = NULL,
channel = "console",
reasoning_effort = NULL,
thinking_budget_tokens = NULL,
thinking = NULL,
context_edit = NULL
)
Arguments
provider |
LLM provider name (see [new_session()]). |
model |
Optional model override. |
tools_filter |
Optional character vector of tool names to expose. NULL uses the subagent config defaults. |
system |
Optional system prompt string. |
max_turns |
Max tool-use turns per query. |
depth |
Archival depth this child sits at (0 means a direct child of the CLI parent). Used by recursion in [subagent_turn_prompt()] to avoid archiving past the configured depth_cap. |
web_search |
Logical or NULL. Provider-native (server-side) web search for the child. NULL (default) preserves the historical behavior: [new_session()] leaves it unset and [turn()] enables it for providers that support it. Pass FALSE for a child that must have no outbound channel – dropping 'web_search' from 'tools_filter' does not achieve that on its own, because the provider's own search tool is injected by 'llm.api::agent', not drawn from the skill registry. |
allowed_paths |
Character or NULL. Confines this child's file tools to the given roots for the life of the process. NULL (default) leaves it unrestricted, as before. A read-only 'tools_filter' is not a filesystem sandbox on its own – 'read_file' reaches anything the process can – so a child that should only see its project needs this as well. |
channel |
Policy channel for the child's tool calls: "console" (default, the historical behavior), "cli", or "matrix". A job worker passes its originating session's channel so work delegated from a Matrix room is judged by the Matrix column of the policy tensor, not the looser console one. |
thinking |
Character or NULL. The Anthropic 'thinking.type' the child's requests carry, such as '"adaptive"' or '"between_tools"'. NULL (default) sends no 'thinking' field. |
context_edit |
Context editing override, as in [new_session()]. |
reasoning_effort, thinking_budget_tokens |
Reasoning settings for the child's session, as in [new_session()]. NULL (default) leaves them to the child's config and the provider's defaults, as before. A job worker passes the ones configured for its model. |
Value
Invisible TRUE.
Forward a prompt to the child-side turn session.
Description
Captures the pre-turn history length so that, if archival is enabled and this query qualifies, the child can recursively archive its own turn into a sub-subagent (capped by depth_cap).
Usage
subagent_turn_prompt(prompt, return_name = NULL, report = FALSE)
Arguments
prompt |
User prompt (character). |
return_name |
Optional single name or '.h_NNN' handle. When set, after the turn the child resolves it (handle store, then globalenv) and ships the value back as '$final' so the parent can stash it by handle. A bad or unresolved name yields '$final_note'. |
report |
Logical. Ask the child for a structured completion handoff containing status, findings, concerns, deviations, questions, and feedback. |
Value
A list with '$reply' (character, the LLM reply text), '$usage' (list with 'input_tokens', 'output_tokens', 'total_tokens', and optionally 'cost' – provider-dependent). '$termination' records whether the turn finished, stopped incomplete, or was cancelled, with a machine-readable reason. When 'return_name' is set, '$final' (the resolved value) or '$final_note' (why nothing was returned). When 'report = TRUE', '$report' is the validated structured handoff or '$report_error' explains why the child did not provide one. Callers extract the reply and accumulate usage into the parent-side registry.
Set this child's subagent id post-spawn.
Description
Called from [subagent_spawn()] right after [subagent_turn_init()] so the child knows its own id when archival inside the child needs to pass 'parent_session_id'.
Usage
subagent_turn_set_id(id)
Arguments
id |
Subagent id assigned by the parent. |
Value
Invisible TRUE.
Run a bash shell command.
Description
Use background=true for long-running servers or processes.
Usage
tool_bash(command, timeout = 30L, background = FALSE)
Arguments
command |
(character) Shell command to execute. |
timeout |
(integer) Timeout in seconds. |
background |
(logical) Run in background and return immediately. |
Value
An MCP tool-result list.
Kill a background process by id.
Description
Kill a background process by id.
Usage
tool_bg_kill(id)
Arguments
id |
(character) Process id (e.g. bg_1). |
Value
An MCP tool-result list.
Check status and output of background processes.
Description
Check status and output of background processes.
Usage
tool_bg_status()
Value
An MCP tool-result list.
Run a Windows cmd.exe command.
Description
Use background=true for long-running processes.
Usage
tool_cmd(command, timeout = 30L, background = FALSE)
Arguments
command |
(character) cmd.exe command to execute. |
timeout |
(integer) Timeout in seconds. |
background |
(logical) Run in background and return immediately. |
Value
An MCP tool-result list.
Collect the result of a previously-fired async subagent query.
Description
Collect the result of a previously-fired async subagent query.
Usage
tool_collect_subagent(id, wait = TRUE, timeout = 60)
Arguments
id |
(character) Subagent ID. |
wait |
(logical) If TRUE (default), block up to 'timeout' seconds. If FALSE, poll once and return immediately. |
timeout |
(numeric) Maximum seconds to block when 'wait = TRUE'. Default 60. |
Value
An MCP tool-result list. On timeout returns a note that the query is still running.
Hand a task to this session's doer.
Description
Queues a job for the session's persistent worker and returns at once. The result arrives later as its own message. The doer does not see this conversation, so the task must be self-contained.
Usage
tool_delegate(
task,
review = NULL,
room = NULL,
attach_context = NULL,
ctx = list()
)
Arguments
task |
(character) Complete description of the work: files, goal, constraints, and how to check the result. |
review |
(logical) Have a read-only reviewer check the work when the doer finishes. The checkout stays locked until the review ends, and the review arrives as a second message. Omit to use the configured default. |
room |
(character) Hand the task to another room's doer instead of this one's: the room's name, its id, or its project directory. The work then runs in that room's project, that room is told, and the result is posted in both rooms. Omit for this room. Only where the bot serves several rooms. |
attach_context |
(logical) Attach the message this turn is answering to the task, so the doer can read it without the task repeating it. Use it when the work is about something the user just provided here (an article, a document, a log): the content is written beside the job and the task points the doer at it, instead of being copied into the task text and through the model's output budget. This session's doer only; not for a 'room' hand-off. |
ctx |
Server-side context; supplies the session. |
Value
An MCP tool-result list.
Submit a plan and exit plan mode.
Description
Called by the LLM after it has finished research in plan mode. The plan text is shown to the user; on approval the session leaves plan mode and the LLM proceeds with the work. On decline the session stays in plan mode and the LLM iterates.
Usage
tool_exit_plan_mode(plan)
Arguments
plan |
(character) Markdown-formatted implementation plan. State what will change, in which files, and why. Be concrete. |
Details
Every session that can be in plan mode is offered this tool, so its tool list stays the same when plan mode starts or ends. Outside plan mode the call is refused.
Value
An MCP tool-result list.
Fetch the contents of a URL and return the response body.
Description
Fetch the contents of a URL and return the response body.
Usage
tool_fetch_url(url, max_chars = 8000L)
Arguments
url |
(character) URL to fetch. |
max_chars |
(integer) Maximum number of characters to return. |
Value
An MCP tool-result list.
Show git diff for the current repository.
Description
Show git diff for the current repository.
Usage
tool_git_diff(
ref = "HEAD",
path = ".",
file_path = "",
staged = FALSE,
context_lines = 3L
)
Arguments
ref |
(character) Diff against this ref. |
path |
(character) Repository path or file path filter when combined with file_path. |
file_path |
(character) Optional file path filter within the repository. |
staged |
(logical) Diff staged changes instead of the worktree. |
context_lines |
(integer) Number of context lines around changes. |
Value
An MCP tool-result list.
Show recent git commits.
Description
Show recent git commits.
Usage
tool_git_log(n = 10L, ref = "HEAD", path = ".")
Arguments
n |
(integer) Number of commits to return. |
ref |
(character) Optional ref to log from. |
path |
(character) Repository path. |
Value
An MCP tool-result list.
Show git working tree status.
Description
Show git working tree status.
Usage
tool_git_status(path = ".")
Arguments
path |
(character) Repository path. |
Value
An MCP tool-result list.
Search file contents with regex pattern.
Description
Search the files the glob 'file_pattern' matches in 'path' (no recursion) for a regex. Skips binary files and files over 10 MB; stops at 500 matches or 20 s and says so.
Usage
tool_grep_files(pattern, path = ".", file_pattern = "*.R")
Arguments
pattern |
(character) Regex pattern to search. |
path |
(character) Directory to search. |
file_pattern |
(character) File glob pattern. |
Value
An MCP tool-result list.
Record a one-line lesson in the continual harness store
Description
Stores one durable, verified fact learned during the session, as a single exact line. It will be shown in future sessions' context. Use it the moment a fact is verified – including negative results ("X does NOT do Y"). Approval is asked per note by default.
Usage
tool_harness_note(
title,
fact,
evidence = NULL,
scope = "project",
ctx = list()
)
Arguments
title |
Short title for the fact; becomes the entry id (slug). |
fact |
The fact itself: one exact line, at most 300 characters. |
evidence |
Where this was established: a test, a run id, an issue URL, a file. Optional but strongly encouraged. |
scope |
Where to store it: "project" (default; travels with this repo) or "global" (all projects). |
ctx |
Server-injected context (session, cwd); not model-facing. |
Value
Confirmation string with the entry id.
List installed R packages, optionally filtered by name.
Description
List installed R packages, optionally filtered by name.
Usage
tool_installed_packages(pattern = NULL, limit = 100L)
Arguments
pattern |
(character) Case-insensitive package-name filter. |
limit |
(integer) Maximum number of packages to return. |
Value
An MCP tool-result list.
Cancel one of this session's jobs.
Description
Cancel one of this session's jobs.
Usage
tool_job_cancel(id, ctx = list())
Arguments
id |
(character) Job id. |
ctx |
Server-side context; supplies the session. |
Value
An MCP tool-result list.
Resume an incomplete delegated job after an explicit user request.
Description
Resume an incomplete delegated job after an explicit user request.
Usage
tool_job_resume(id, ctx = list())
Arguments
id |
(character) Incomplete job id. |
ctx |
Server-side context; supplies requester authorization. |
Value
An MCP tool-result list.
Show this session's recent jobs.
Description
Show this session's recent jobs.
Usage
tool_job_status(id = NULL, ctx = list())
Arguments
id |
(character) Optional job id for one job's full record. |
ctx |
Server-side context; supplies the session. |
Value
An MCP tool-result list.
Terminate a running subagent.
Description
Terminate a running subagent.
Usage
tool_kill_subagent(id)
Arguments
id |
(character) Subagent ID to terminate. |
Value
An MCP tool-result list.
List files in a directory.
Description
List files in a directory.
Usage
tool_list_files(
path = ".",
pattern = NULL,
recursive = FALSE,
all_files = FALSE,
limit = 200L
)
Arguments
path |
(character) Directory to inspect. |
pattern |
(character) Regex pattern to filter file names. |
recursive |
(logical) Recurse into subdirectories. |
all_files |
(logical) Include hidden files. |
limit |
(integer) Maximum number of entries to return. |
Value
An MCP tool-result list.
List all active subagents.
Description
List all active subagents.
Usage
tool_list_subagents()
Value
An MCP tool-result list.
Send a prompt to a running subagent.
Description
Fires the prompt and returns at once; collect the reply later with collect_subagent, so several subagents can run in parallel. wait = TRUE for a quick answer.
Usage
tool_query_subagent(
id,
prompt,
wait = FALSE,
return_name = NULL,
timeout = 60,
report = FALSE
)
Arguments
id |
(character) Subagent ID. |
prompt |
(character) Prompt to send. |
wait |
(logical) If FALSE (default), fire the prompt and return immediately; collect the reply with 'collect_subagent'. If TRUE, block up to 'timeout' seconds for the reply; on timeout the query stays pending and 'collect_subagent' fetches it later. |
return_name |
(string) Optional name or '.h_NNN' handle for a value the subagent should hand back. Tell the subagent to leave its result bound under this name (it needs 'run_r'); the value is returned as a handle you can reference in a later 'run_r', instead of being inlined into the reply text. |
timeout |
(numeric) Maximum seconds to block when 'wait = TRUE'. Default 60. |
report |
(logical) Request a structured completion handoff containing findings, concerns, deviations, open questions, and feedback. Default FALSE preserves the plain-reply behavior. |
Value
An MCP tool-result list.
Get R package documentation via saber (exports, function help).
Description
Get R package documentation via saber (exports, function help).
Usage
tool_r_help(topic, package = NULL)
Arguments
topic |
(character) Package or function name. |
package |
(character) Package to search in (optional). |
Value
An MCP tool-result list.
Read file contents, optionally with line numbers.
Description
Read file contents, optionally with line numbers.
Usage
tool_read_file(path, from = 1L, lines = NULL, line_numbers = TRUE)
Arguments
path |
(character) Path to the file. |
from |
(integer) Starting line number (1-based). |
lines |
(integer) Number of lines to read. |
line_numbers |
(logical) Prefix each line with its line number. |
Value
An MCP tool-result list.
Read / inspect a stashed handle.
Description
The LLM's only window onto large stashed objects. Supports a few common ops: 'str' (structure), 'head' (first six rows / elements), ‘summary' (R’s summary()), 'print' (full print of the object), 'grep' (the lines matching 'pattern', numbered), and 'lines' (a range of lines, 'start' to 'end'). The last two are how a tool result that was cut for length is searched and paged; each returns few enough lines not to be cut again.
Usage
tool_read_handle(handle, op = "str", pattern = NULL, start = NULL, end = NULL)
Arguments
handle |
(character) Handle id, e.g. '.h_001'. |
op |
(character; one of: str, head, summary, print, grep, lines) Inspection operation. |
pattern |
(character) For 'op = "grep"': a regular expression, matched without regard to case. Text that is not a valid expression is matched as written. |
start |
(integer) For 'op = "lines"': the first line wanted. Defaults to 1. |
end |
(integer) For 'op = "lines"': the last line wanted. At most 40 lines come back. |
Value
An MCP tool-result list.
Replace exact text in a file without rewriting the whole file manually.
Description
Replace exact text in a file without rewriting the whole file manually.
Usage
tool_replace_in_file(
path,
old_text,
new_text,
all = FALSE,
expected_count = NULL
)
Arguments
path |
(character) Path to the file. |
old_text |
(character) Exact text to replace. |
new_text |
(character) Replacement text. |
all |
(logical) Replace all matches instead of exactly one. |
expected_count |
(integer) Fail unless this many matches are found. |
Value
An MCP tool-result list.
Execute R code in a persistent environment.
Description
By default, code runs in the host's global environment, preserving the
original run_r contract. Pass a private persistent environment to
give an agent or capability its own R scope. Assignments and handles
persist in the selected scope.
Usage
tool_run_r(code, envir = globalenv())
Arguments
code |
(character) R code to execute. |
envir |
(environment) Persistent environment in which assignments
should land. Defaults to |
Value
An MCP tool-result list.
Execute R code in a clean subprocess via littler.
Description
Use for scripts that modify packages, run tests, or need isolation from the server.
Usage
tool_run_r_script(code, timeout = 30L)
Arguments
code |
(character) R code to execute. |
timeout |
(integer) Timeout in seconds. |
Value
An MCP tool-result list.
Read a session-scoped instruction or supporting resource.
Description
Resolves an exact instruction identifier against the immutable catalog captured for the current agent session. Supporting resources are confined to the same snapshotted instruction directory and checked for drift.
Usage
tool_skill_instructions(id, resource = NULL, ctx = list())
Arguments
id |
(character) Exact instruction identifier shown in the session catalog. |
resource |
(character) Optional relative supporting-resource path. Omit to read SKILL.md. |
ctx |
(list) Host-owned tool execution context containing the session. |
Value
An MCP tool-result list.
Spawn a specialized subagent for a task.
Description
Use for parallel work or tasks requiring focused attention. Parent session is read from 'ctx$session', which the skill handler injects from the invoking context; not from LLM-provided args.
Usage
tool_spawn_subagent(
task,
model = NULL,
tools = NULL,
preset = NULL,
ctx = list()
)
Arguments
task |
(character) Task description for the subagent. |
model |
(character) Optional model override. |
tools |
(character vector) Optional explicit tool filter. |
preset |
(character) Preset name: "investigate" (default, read-only), "work" (read + write + bash), or "minimal" (read_file + grep_files only). |
Value
An MCP tool-result list.
Create a list of tasks to track for the current request.
Description
Call this at the start of any multi-step user request (3+ steps) to commit to a visible plan. The list persists across turns and replaces any prior list. After creating, update each task's status with 'task_update' as you work: mark a task 'in_progress' when you start it, 'completed' when done, 'cancelled' if the user redirects.
Usage
tool_task_create(tasks)
Arguments
tasks |
(character vector) One task description per element. Order matters; task_update references tasks by 1-based index. |
Value
Confirmation string.
Update one task's status in the current session task list.
Description
Update one task's status in the current session task list.
Usage
tool_task_update(index, status)
Arguments
index |
(integer) 1-based position of the task to update. |
status |
(character) New status. One of 'pending', 'in_progress', 'completed', 'cancelled'. Promoting a task to 'in_progress' automatically demotes any other 'in_progress' task to 'pending', so there is at most one active task at a time. |
Value
Confirmation string.
Search the web using Tavily API.
Description
Search the web using Tavily API.
Usage
tool_web_search(query, max_results = 5L)
Arguments
query |
(character) Search query. |
max_results |
(integer) Max results to return. |
Value
An MCP tool-result list.
Write text to a file.
Description
Creates parent directories by default.
Usage
tool_write_file(path, content, append = FALSE, create_dirs = TRUE)
Arguments
path |
(character) Path to the file. |
content |
(character) Text to write. |
append |
(logical) Append instead of overwrite. |
create_dirs |
(logical) Create parent directories if needed. |
Value
An MCP tool-result list.
Run one agent turn
Description
Sends prompt to the configured LLM with tool use enabled. Every
tool call the LLM makes is routed through policy before
being dispatched.
Usage
turn(prompt, session, tool_executor = NULL, tools = NULL)
Arguments
prompt |
Character. User prompt. |
session |
A session environment created by |
tool_executor |
Function or NULL. Dispatcher with signature
|
tools |
List or NULL. Tool schemas to pass the LLM. NULL uses
the in-process skill registry (filtered by |
Details
Tool dispatch is pluggable via tool_executor, but the CLI and
chat() both leave it NULL: tools run in-process through the
default call_skill dispatcher against the local skill registry.
serve() is a separate MCP server for external clients only; it
is not part of the CLI's tool path. Pass an explicit
function(name, args) -> list executor only when dispatching
tools somewhere other than the in-process registry.
When the provider refuses the request with a limit error (HTTP 429,
503, or 529, or a body naming a rate, usage, or quota limit) and the
session has a fallback chain, the turn is retried on the next
"model provider" entry in that chain. The chain comes from
session$fallback (the Matrix config's fallback key, see
bot_configure) or the cwd config's fallback
key. A provider that hit a limit is skipped process-wide for
fallback_cooldown_minutes (default 30); a configured
fallback_primary_retry_at can hold the primary until a weekly
reset boundary. Provider-native histories are bridged when the wire
changes, and a partially completed tool run resumes from its captured
results so no completed tool call runs twice. Fallback replies identify
their actual model/provider; API-key fallbacks carry a prominent billable
usage warning. Errors that are not limits are rethrown untouched.
A program that runs turns for someone else can let them stop one. It
sets session$stop_requested to a function of no arguments that
returns TRUE once a stop is asked for. The turn asks it before
each request to the model, before each tool call, again just before the
call runs (a call can wait for an approval or a review in between) and,
when the turn streams (session$on_delta), before each piece of
the reply goes out. A stop ends the turn with status
cancelled: a tool call that got no result is given a
placeholder, and the history ends on a note that the turn was stopped,
so the next turn can go on from it. A stop cannot cut short a request
already waiting for its first word, nor the reply of a provider that
does not stream.
A turn that ends on an error leaves a history the next request can
use. Before the error leaves turn(), each tool call the model
made that has no result gets a placeholder result, and a note says
the turn stopped on that error. A turn also closes, before its first
request, any call that an earlier turn or an earlier process left
without a result.
Value
A list with reply (character), session (the
updated session environment; also mutated in place), route
(the actual model/provider and fallback credential mode), and
termination (status done, incomplete, or
cancelled, with a machine-readable reason), and audit
(the stream path and canonical turn ID, or NULL when recording is disabled).
Examples
## Not run:
# Requires ANTHROPIC_API_KEY (or the configured provider's key) and
# a network connection to the LLM.
s <- new_session(provider = "anthropic")
out <- turn("Say hello", s)
out$reply
## End(Not run)
Uninstall corteza CLI
Description
Remove the corteza command-line tool.
Usage
uninstall_cli(path = NULL)
Arguments
path |
Directory where corteza is installed. Default matches
|
Value
TRUE if removed, FALSE if not found, invisibly.
Examples
bin <- file.path(tempdir(), "corteza-bin")
install_cli(bin)
uninstall_cli(bin)
unlink(bin, recursive = TRUE)
Build a condition object representing "user denied this tool call".
Description
Raised by [chat_approval_cb()] (and the CLI's 'cli_approval_cb') when the user picks "3. Deny". The class deliberately excludes '"error"' so the defensive 'tryCatch(error = function(e) FALSE)' wrapper around approval_cb in [.make_tool_handler()] does not swallow it. The '"interrupt"' class lets the existing chat()/CLI interrupt-marker machinery fall through cleanly if a surface forgets to register a 'corteza_user_deny' handler.
Usage
user_deny_condition(tool = "?")
Arguments
tool |
Character. Name of the denied tool (for the history marker). Defaults to '"?"' when unavailable. |
Value
A condition object with class 'c("corteza_user_deny", "interrupt", "condition")'.
History marker written when a turn is aborted by a user deny.
Description
Format chosen so the LLM, reading the marker on the next turn, knows to stop and ask the user how to proceed instead of retrying the same tool or planning a workaround.
Usage
user_deny_marker(tool = "?")
Arguments
tool |
Character. Name of the denied tool. |
Value
Character scalar.
History marker written when a turn is interrupted (Ctrl+C / Esc).
Description
Carries the same "stop and ask the user" directive as [user_deny_marker()] so an interrupt and a deny leave the LLM with the same next-turn instruction – matching the (Esc)/(Ctrl+C) hint on the approval prompt, which converges on this interrupt path.
Usage
user_interrupt_marker()
Value
Character scalar.
Serve AgentVoice for live voice clients
Description
Runs the gRPC service a fluffychat live-voice client talks to
(AllocateVoice, Converse, ReportTurn). Blocks
until interrupted. Run it as its own R process, next to – not inside
– the room poll loop.
Usage
voice_serve(
config = NULL,
address = NULL,
hooks = list(),
poll_ms = 200L,
max_events = Inf
)
Arguments
config |
Config list as from |
address |
|
hooks |
Named list overriding side effects (tests/harnesses
only): |
poll_ms |
Milliseconds each poll waits for events. |
max_events |
Stop after handling this many events (tests only; the default never stops). |
Details
Requires the rgrpc and RProtoBuf packages (Suggests),
and a media allocator named in the config: voice.allocator
(the gpu.ctl base URL) plus voice.allocator_token (the
service credential its front requires on every mint). Without
either, AllocateVoice refuses and names the missing key.
Voice sessions generate in spoken register: their system prompt
carries an instruction to write plain speakable prose (no markdown,
numbers said aloud), because the reply is synthesized verbatim.
voice.speech_style in the config replaces that instruction's
text; typed room chat is unaffected either way.
Value
Invisibly, the number of events handled.
Examples
## Not run:
# Needs rgrpc and RProtoBuf, a bot config naming voice.allocator and
# voice.allocator_token, and a running allocator. Blocks until
# interrupted.
voice_serve(address = "127.0.0.1:7851")
## End(Not run)
Subagent session initialization.
Description
Runs inside a subagent's private 'callr::r_session' subprocess
(invoked via 'corteza::worker_init()' across the callr boundary).
Sets the subprocess cwd and ensures the built-in skills are
registered. The child's session takes its own tools when
subagent_turn_init makes it: the user's skills, the config's
package tools, and the project's skills where cwd is a trusted
directory.
Usage
worker_init(cwd = getwd())
Arguments
cwd |
Working directory for the subagent session. |
Details
Exported (with '@keywords internal') because it is called as 'corteza::worker_init()' from inside the 'callr::r_session' child, where ‘corteza:::' would trip the R CMD check "calls to the package’s namespace" NOTE.
Value
Invisible TRUE on success.