Title: AI Agent Runtime
Version: 0.6.3
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 with managed workspace state. Tools execute as R function calls with provenance tracking, and a deterministic retrieval system keeps relevant objects in context across turns. Three entry points: 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, codetools, curl, jsonlite, llm.api, printify, processx, saber
Suggests: fortunes, mx.api, 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-04-30 00:11:49 UTC; troy
Author: Troy Hernandez ORCID iD [aut, cre], cornball.ai [cph]
Maintainer: Troy Hernandez <troy@cornball.ai>
Repository: CRAN
Date/Publication: 2026-05-04 19:00:13 UTC

corteza: AI Agent Runtime in R

Description

corteza: AI Agent Runtime in R

Author(s)

Maintainer: Troy Hernandez troy@cornball.ai


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:

Errors raised inside an observer are swallowed.

Usage

add_observer(session, observer)

Arguments

session

A session environment from new_session.

observer

A function of one argument (the event list).

Value

The session, invisibly.


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)

Arguments

provider

LLM provider: "anthropic", "openai", "moonshot", or "ollama". Defaults to config value or "anthropic".

model

Model name. Defaults to 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, or a character session key to resume a specific session.

max_turns

Integer or NULL. Maximum LLM turns per user prompt before the loop stops with [Max turns reached]. NULL (default) reads getOption("corteza.max_turns"), then falls back to the session_setup default (50).

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")
}

Drain structured events the worker wrote to stderr while a tool ran. When 'trace' is TRUE each event is pretty-printed via [printify::print_step()] / [printify::print_message()]; otherwise the events are still read (to keep the stderr buffer from growing) but not displayed.

Description

Drain structured events the worker wrote to stderr while a tool ran. When 'trace' is TRUE each event is pretty-printed via [printify::print_step()] / [printify::print_message()]; otherwise the events are still read (to keep the stderr buffer from growing) but not displayed.

Usage

cli_worker_drain_events(session, trace = FALSE)

Arguments

session

A 'callr::r_session'.

trace

Pretty-print events if TRUE.

Value

Invisible NULL.


Spawn and initialize a CLI worker session.

Description

Starts a fresh 'callr::r_session', loads corteza inside it, and runs 'worker_init()' so skills are registered in the session. Returns an opaque handle the CLI uses for tool dispatch. Schema production is CLI-side. The worker registers skills only so it can execute them; the CLI builds the LLM 'tools' payload from its own registry via 'schema_from_registry()'. Nothing about schema shape travels over the worker pipe.

Usage

cli_worker_spawn(cwd = getwd())

Arguments

cwd

Working directory for the worker.

Value

A list with 'session' (the 'callr::r_session' instance) and 'cwd', with class 'corteza_cli_worker'.


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)

Ensure skills are registered.

Description

Registers built-in skills if not already registered. Exported with '@keywords internal' so the CLI (which runs in its own R process, separate from the callr worker) can register skills in its own namespace before calling 'schema_from_registry()'.

Usage

ensure_skills()

Value

Invisible character vector of skill names.


Install corteza CLI

Description

Install the corteza command-line tool to a directory in your PATH. 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 ~/bin on Unix, tools::R_user_dir("corteza", "data")/bin on Windows.

force

Overwrite existing installation.

Details

Requires:

After installation, run corteza from any terminal (you may need to add the install directory to PATH; the function prints the PATH hint if it isn't already there).

Value

The installed script path, invisibly.

Examples

## Not run: 
install_cli()
install_cli("/usr/local/bin")

## End(Not run)

Flush all in-memory matrix sessions to the pensar vault

Description

Walks the per-room session registry and archives any turns that haven't been ingested yet via the pensar archive ingest. Each session tracks an ingested_through watermark so repeated calls only write new turns. Silent no-op when pensar is not installed.

Usage

matrix_archive_all(sessions, mx_sess = NULL)

Arguments

sessions

A registry environment built by matrix_run/matrix_poll. Keys are room IDs, values are session lists carrying $history.

mx_sess

Optional Matrix session for room-name lookups. When NULL, the room ID is used as the source identifier.

Value

Integer count of rooms ingested, invisibly.


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. Pre-CRAN releases stored the file at ~/.corteza/matrix.json; that path is still read for backward compatibility, but the next matrix_configure() call writes to the new location.

Usage

matrix_configure(server, user, password, room, model = NULL,
                 provider = c("anthropic", "openai", "moonshot", "ollama"),
                 tools_filter = NULL, auto_approve_asks = FALSE)

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", "openai", "moonshot", or "ollama".

tools_filter

Character vector or NULL. Passed to get_tools() to restrict which tools the bot can invoke. NULL allows all registered tools.

auto_approve_asks

Logical. When TRUE, tool calls that policy returns "ask" for are auto-approved. Suitable for a personal bot on a trusted tailnet. When FALSE (default) asks are declined until the thumbs-up reaction protocol lands.

Value

The saved configuration, invisibly.


One iteration of sync-and-reply

Description

Fetches new messages across all joined rooms and runs turn against each. Auto-joins any pending invites the bot has received. 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. Pass sessions = NULL (the default) for a stateless one-shot — each incoming message builds a fresh session. Pass a registry created by matrix_new_session_registry() so a long-running matrix_run keeps a separate history per room (conversations in different rooms don't cross-contaminate).

Usage

matrix_poll(system = NULL, model = NULL, provider = NULL, tools_filter = NULL,
            timeout = 0L, sessions = 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 matrix_new_session_registry() keyed by room_id, or NULL to build fresh sessions each call.

Value

An integer count of messages replied to, invisibly.


Ask the running matrix bot to archive sessions to pensar

Description

Drops an archive.signal file in the corteza state directory. The next iteration of the long-poll loop in matrix_run picks it up, runs matrix_archive_all, 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

matrix_request_flush()

Value

The signal file path, invisibly.


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.

Usage

matrix_run(timeout = 30000L, system = NULL, model = NULL, provider = NULL,
           tools_filter = 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.

Value

Never returns under normal operation. Crashes on fatal error so systemd can restart.


Send a message to a Matrix room

Description

Send a message to a Matrix room

Usage

matrix_send(text, room_id = NULL, msgtype = "m.text")

Arguments

text

Character. Plain text body.

room_id

Character. Matrix room id. Defaults to cfg$room_id from the saved Matrix config (see matrix_configure).

msgtype

Character. Matrix msgtype, default "m.text".

Value

The event ID of the sent message.


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 llm.api::mcp_connect).

Value

A function with signature function(name, args) that returns an MCP-format result list.


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)

Arguments

channel

Character, one of "cli", "console", "matrix".

history

List of prior messages, or NULL.

model_map

Named list with cloud and local model names. Defaults to configured defaults.

provider

LLM provider passed to llm.api::agent.

tools_filter

Character vector passed to get_tools().

system

System prompt override (NULL for built-in default).

approval_cb

Function called when policy returns "ask". Signature: function(call, decision) -> TRUE|FALSE. Default denies (safe fallback).

max_turns

Maximum LLM turns per call.

verbose

Print tool call progress.

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.


Evaluate policy for a tool call

Description

Returns a decision list(model, approval, reason). model is "cloud" or "local"; approval is "allow", "ask", or "deny".

Usage

policy(call)

Arguments

call

A list describing the tool call. See the file header in R/policy.R for the expected fields.

Value

A decision list with fields model, approval, reason.


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)

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.

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). Used by the CLI to avoid round-tripping schemas through the worker. Exported with '@keywords internal': the CLI calls this directly, but it is not part of the public user-facing API.

Usage

schema_from_registry(filter = NULL)

Arguments

filter

Optional tool-name or category filter; see 'get_tools()'.

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)

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).

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)

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:

  1. Loads project + global corteza config from cwd.

  2. Resolves provider, model, and verifies the required API environment variable is set.

  3. Registers built-in skills and loads user/project skills and skill docs from tools::R_user_dir("corteza", "data")/skills and <cwd>/.corteza/skills.

  4. Loads skill packages declared in the config.

  5. Optionally builds the system prompt via load_context(cwd).

  6. Returns a new_session() built from the above.

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)

Arguments

channel

Character, one of "cli", "console", "matrix".

cwd

Working directory. Defaults to the current directory.

provider

Character or NULL. LLM provider override. NULL falls back to config$provider, then "anthropic".

model

Character or NULL. Model override. NULL falls back to config$model, then the provider default.

tools

Character vector, NULL, or the string "all". Tool filter passed through to get_tools(). NULL is treated as "all".

system

Character or NULL. System prompt. NULL auto-builds via load_context(cwd) when load_project_context = TRUE, otherwise left NULL (channel supplies its own).

approval_cb

Function or NULL. Approval callback for "ask" verdicts; see new_session.

history

List or NULL. Prior conversation messages to seed the session with (each entry a list with role and content).

load_project_context

Logical. When TRUE, auto-call load_context(cwd) to assemble the system prompt. Channels with their own short system prompt (like matrix) 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 new_session.

max_turns

Integer. Passed through to new_session. Defaults to 50, a safety net for interactive channels where a multi-step request (read + edit + verify several files) can easily exceed the new_session() default of 10.

Value

A session environment from new_session, with an extra cwd field set.


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 tools::R_user_dir("corteza", "data")/skills.

force

Overwrite if exists

Value

Installed skill name


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


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


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


Kill a subagent.

Description

Kill a subagent.

Usage

subagent_kill(id)

Arguments

id

Subagent ID.

Value

Invisible TRUE if killed, FALSE if not found.


List active subagents.

Description

List active subagents.

Usage

subagent_list()

Value

List of subagent info objects.


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, timeout = 60L)

Arguments

id

Subagent ID.

prompt

Prompt to send.

timeout

Timeout in seconds (currently advisory; callr-level hard timeouts are future work).

Value

Reply text (character).


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, parent_session = NULL,
               config = NULL)

Arguments

task

Task description (stored for bookkeeping; not yet fed into an agent loop — see TODO on subagent_query).

model

Optional model override (reserved for later use).

tools

Optional tool filter (character vector).

parent_session

Parent session object; read for nested-spawning control and session-key derivation.

config

Config list.

Value

Subagent ID (character).


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. Subagents deny all tool approvals by default so a subagent can't run bash without the parent opting in.

Usage

subagent_turn_init(provider = "anthropic", model = NULL, tools_filter = NULL,
                   system = NULL, max_turns = 10L)

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.

Value

Invisible TRUE.


Forward a prompt to the child-side turn session.

Description

Forward a prompt to the child-side turn session.

Usage

subagent_turn_prompt(prompt)

Arguments

prompt

User prompt (character).

Value

Reply text (character).


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.


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 file contents with regex pattern.

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.


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.


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 and get the response.

Description

Send a prompt to a running subagent and get the response.

Usage

tool_query_subagent(id, prompt)

Arguments

id

(character) Subagent ID.

prompt

(character) Prompt to send.

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).

Usage

tool_read_handle(handle, op = "str")

Arguments

handle

(character) Handle id, e.g. '.h_001'.

op

(character; one of: str, head, summary, print) Inspection operation.

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 the session's global environment.

Description

New bindings are auto-captured into the workspace cache. Large result values (data frames, matrices, long vectors, objects over ~10 KB) are stashed via 'with_handle()' and returned as a 'str()' summary plus a short '.h_NNN' handle the LLM can reference in a later 'run_r' call or inspect with 'read_handle'.

Usage

tool_run_r(code)

Arguments

code

(character) R code to execute.

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.


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, ctx = list())

Arguments

task

(character) Task description for the subagent.

model

(character) Optional model override.

tools

(character vector) Optional tool filter (list of tool names).

Value

An MCP tool-result list.


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. Tool dispatch is pluggable via tool_executor. The default is an in-process dispatcher that calls the local skill registry — suitable for chat() and matrix adapters running in the same R process as their skills. Pass mcp_tool_executor (or any function(name, args) -> MCP-format result) to run tools in a separate process, which is how the CLI talks to serve().

Usage

turn(prompt, session, tool_executor = NULL, tools = NULL)

Arguments

prompt

Character. User prompt.

session

A session environment created by new_session.

tool_executor

Function or NULL. Dispatcher with signature function(name, args) -> list. NULL uses the in-process call_skill path.

tools

List or NULL. Tool schemas to pass the LLM. NULL uses the in-process skill registry (filtered by session$tools_filter). Pass explicit schemas when running against a remote skill source.

Value

A list with reply (character) and session (the updated session environment; also mutated in place).


Uninstall corteza CLI

Description

Remove the corteza command-line tool.

Usage

uninstall_cli(path = NULL)

Arguments

path

Directory where corteza is installed. Default matches install_cli(): ~/bin on Unix, tools::R_user_dir("corteza", "data")/bin on Windows.

Value

TRUE if removed, FALSE if not found, invisibly.

Examples

## Not run: 
uninstall_cli()

## End(Not run)

Worker-side tool dispatch.

Description

Called from the CLI over 'callr::r_session$run()'. Looks up the skill in the registry, runs it, and normalizes any dispatch-level failures as a 'corteza_tool_error' condition. Tool-body failures that are already caught by 'skill_run()' remain as 'err()' envelopes. Exported (with '@keywords internal') because it runs inside a 'callr::r_session' child process, where 'corteza:::' would otherwise trip the R CMD check "calls to the package's namespace" NOTE.

Usage

worker_dispatch(name, args, ctx = list(), timeout = 30L, dry_run = FALSE)

Arguments

name

Tool name.

args

Named list of arguments.

ctx

Optional context (cwd, session metadata).

timeout

Timeout in seconds.

dry_run

If TRUE, preview only.

Value

MCP-shaped tool result list (content, isError).


Worker-side initialization.

Description

Called once after the callr session starts. Sets up cwd, loads the package, registers skills. Separate from worker_dispatch so session init is explicit and inspectable. Exported (with '@keywords internal') for the same reason as 'worker_dispatch()'.

Usage

worker_init(cwd = getwd())

Arguments

cwd

Working directory for the worker.

Value

Invisible TRUE on success.


Worker-side tool listing.

Description

Returns the full tool definition list the CLI needs to build its LLM API 'tools' payload. Ensures built-in skills and user skills are loaded before listing. Exported (with '@keywords internal') for the same reason as 'worker_dispatch()'.

Usage

worker_tool_list(filter = NULL, cwd = getwd())

Arguments

filter

Optional tool-name or category filter; see get_tools().

cwd

Project root for project-local skill discovery.

Value

List of tool definitions.