agentafk
Guides

Tools Reference

Complete reference for all tools available to the agent during a session.

This page lists every tool available to the agent, grouped by category. Each entry shows the tool name, a one-line description, and a table of its parameters.

Required parameters are marked with ✓. All others are optional.


File System

read_file

Read a file from the filesystem with line numbers. Supports partial reads via offset/limit. Binary files are rejected — use extract_document instead.

ParameterTypeRequiredDescription
file_pathstringAbsolute path to the file to read.
offsetnumberLine number to start reading from (1-based). Defaults to 1.
limitnumberMaximum number of lines to read. Defaults to 2000.

write_file

Write content to a file, creating it or overwriting if it exists. Parent directories are created automatically. Prefer edit_file for modifying existing files.

ParameterTypeRequiredDescription
file_pathstringAbsolute path to the file to write.
contentstringThe full content to write.

edit_file

Perform an exact string replacement in a file. Fails if old_string is not found or matches multiple locations (unless replace_all is set). Always read the file first to verify exact content.

ParameterTypeRequiredDescription
file_pathstringAbsolute path to the file to edit.
old_stringstringThe exact string to find and replace.
new_stringstringThe replacement string.
replace_allbooleanIf true, replace all occurrences. Default: fail on multiple matches.

patch_apply

Validate and atomically apply structured multi-file changes with content-hash verification and dry-run preview. Validation runs on all files before any write; a single failure aborts the entire patch.

ParameterTypeRequiredDescription
changesarrayArray of file changes. Each item: path (required), edits (sequential replacements) or content (full replacement), optional expected_hash.
dry_runbooleanIf true, return the unified diff without writing.

glob

Find files matching a glob pattern. Returns up to 500 matching paths. Skips node_modules, .git, .hg, .svn by default.

ParameterTypeRequiredDescription
patternstringGlob pattern (e.g. "src/**/*.ts", "*.json").
pathstringBase directory to search from. Defaults to cwd.

grep

Search file contents for lines matching a pattern using ripgrep. Returns matches as file:line:content. Honors .gitignore; skips .git and binary files.

ParameterTypeRequiredDescription
patternstringRipgrep regex. | + ? ( ) { } are metacharacters — escape with \ for literal match.
pathstringDirectory or file to search. Defaults to cwd.
includestringFile glob to restrict search (e.g. "*.ts").

list_directory

List the contents of a directory. Returns filenames annotated with type (directories end with /).

ParameterTypeRequiredDescription
pathstringAbsolute path to the directory to list.

extract_document

Extract text from binary document formats that read_file rejects. Supports .docx, .xlsx, .pptx, .pdf (requires pdftotext), and .zip. Output is capped at 512 KB.

ParameterTypeRequiredDescription
file_pathstringAbsolute path to the document file.

json_query

Run a bounded jq-subset query on a JSON file without loading it fully into context. Returns { result, type, truncated, source_size }.

Supported syntax: . .field .field.nested .[N] .[N:M] .[] .[] | .field keys length

ParameterTypeRequiredDescription
pathstringAbsolute or relative path to the JSON file.
querystringQuery expression (e.g. .name, .[0], `.[]
max_resultsnumberMax array elements to return (default 100).
max_bytesnumberMax serialized output size in bytes (default 51200).

Shell & Process

bash

Execute a shell command and return stdout and stderr. Commands run through /bin/sh — not bash. Output is capped to ~100 KB head+tail; commands emitting >8 MB are terminated.

ParameterTypeRequiredDescription
commandstringThe shell command to execute.
timeout_msnumberTimeout in milliseconds (default 120000, max 600000).

wait_for

Block on an external condition without consuming model turns. Returns when the condition is met, the timeout elapses (status: timed_out), or the session is cancelled.

ParameterTypeRequiredDescription
typestringWhat to wait for: url, file, process, or command.
urlstring(url type) HTTP/HTTPS endpoint to poll.
methodstring(url type) HTTP method: HEAD or GET. Default: HEAD.
expected_statusnumber(url type) Expected HTTP status code. Default: any 2xx.
body_containsstring(url type) Substring that must appear in the response body.
pathstring(file type) Path to watch for existence.
content_containsstring(file type) Substring the file content must contain.
pidnumber(process type) PID to wait on. Met when the process exits.
commandstring(command type) Shell command to run. Met when it exits 0.
timeout_msnumberMax wait time in ms (default 120000, max 600000).
poll_interval_msnumberDelay between polls in ms (default 5000, min 1000).
backoffstringBackoff strategy: none, linear, or exponential.

test_run

Discover and run the project test suite. Auto-detects the test runner from project config files. Returns structured results with pass/fail counts, per-failure details, duration, and raw output.

ParameterTypeRequiredDescription
filestringNarrow to a specific test file path (relative to project root).
namestringFilter tests by name/pattern (runner-specific syntax applied automatically).
timeout_msnumberTest timeout in ms (default 120000, max 600000).
coveragebooleanRequest a coverage report.

Browser

Browser tools share a single managed session per AFK process. Always start a workflow with browser_open; subsequent calls operate on the same tab.

browser_open

Open a URL in a managed browser tab and return an observation of the page. The observation lists actionable elements with stable IDs for follow-up browser_act calls.

ParameterTypeRequiredDescription
urlstringAbsolute http(s) URL to navigate to.
wait_forstringWhen navigation is complete: load, domcontentloaded, or networkidle. Default: load.
screenshotbooleanCapture a screenshot in the observation. Default: false.
timeout_msnumberNavigation timeout in ms. Default 30000, max 120000.

browser_observe

Refresh the observation of the current page. Use after DOM mutations or dynamic content loads. Element IDs are stable only within one observation — always use IDs from the most recent call.

ParameterTypeRequiredDescription
screenshotbooleanCapture a screenshot. Default: false.
include_hiddenbooleanInclude hidden elements. Default: false.
max_elementsnumberCap on the interactive elements array (default 80, max 300).

browser_act

Perform an action on a target element on the current page. Prefer semantic targets ({ kind: "semantic", text: "...", role: "button" }) over selectors for stability across markup changes.

ParameterTypeRequiredDescription
actionstringclick, fill, press, select, hover, scroll_to, or wait_for.
targetobjectElement target. Required field: kind (semantic, element_id, or selector).
valuestringText for fill, key combo for press, option value for select.
timeout_msnumberPer-action timeout in ms. Default 10000.
screenshotbooleanCapture a screenshot after the action. Default: false.

browser_screenshot

Capture a PNG screenshot of the current page or a specific element and return it as a viewable image. Also written as a sidecar under ~/.afk/state/witness/.

ParameterTypeRequiredDescription
targetobjectElement to screenshot (same shape as browser_act.target). Omit to capture the viewport.
full_pagebooleanCapture the entire scrollable page. Default: false. Mutually exclusive with target.

browser_close

Close the current browser session, freeing cookies and page state. Subsequent browser_open calls create a fresh session. Leaves the underlying browser process alive.

No parameters.


Web

web_scrape

Scrape a web page or run a web search. Three modes: markdown (default — fetches and extracts main content), raw (response body as text), search (web search via Exa; requires EXA_API_KEY). Output is capped at max_bytes.

ParameterTypeRequiredDescription
modestringmarkdown, raw, or search. Default: markdown.
urlstringAbsolute http(s) URL. Required for markdown and raw modes.
querystringSearch query. Required for search mode.
timeout_msnumberRequest timeout in ms (default 30000, max 120000).
max_bytesnumberMax UTF-8 bytes returned (default 100000, max 1000000).

web_request

Make a structured HTTP request with any method. Returns { status, headers, body, timing_ms }. SSRF-guarded: private IP ranges are blocked. Credential injection via env var name keeps secrets out of the model context.

ParameterTypeRequiredDescription
urlstringAbsolute http(s) URL.
methodstringGET, POST, PUT, PATCH, DELETE, HEAD, or OPTIONS.
bodyanyRequest body. Objects/arrays are JSON-serialized; strings sent as text/plain.
headersobjectRequest headers as a string-keyed object.
timeout_msnumberRequest timeout in ms (default 30000, max 120000).
max_response_bytesnumberMax response body bytes (default 100000, max 1000000).
credentialstringEnv var name whose value is injected as a Bearer token.

Delegation

agent

Dispatch an independent subagent with its own context window and tool access. Foreground mode (default) waits for the result; background mode returns a jobId immediately.

ParameterTypeRequiredDescription
promptstringThe task for the subagent to perform.
modestringforeground (default) or background.
modelstringModel override. Short aliases: haiku, sonnet, opus. Append _1m for 1M-context variants.
max_turnsnumberMax conversation turns (default 0 = unlimited).
max_tool_use_iterationsnumberMax tool-use rounds before graceful wind-down (default 0 = unlimited).
cwdstringAbsolute path for the subagent to run in (e.g. a worktree).
isolationstringnone (default) or worktree — creates an isolated git worktree for the subagent.
writeRootsarrayExtra absolute write roots to pre-grant the child.
readRootsarrayExtra absolute read roots to pre-grant the child.
attachmentsarrayImage IDs or absolute image paths to pass as input.
progress_eventsbooleanGrant the child the emit_progress tool for live parent updates.
id_prefixstringLabel prefix for log correlation.

compose

Execute multiple subagent tasks as a DAG. Nodes without dependencies run in parallel; nodes with edges wait for their upstream dependencies. Maximum 20 nodes per call.

ParameterTypeRequiredDescription
nodesarraySubagent tasks. Each item: id (string), prompt (string), optional model.
edgesarrayDependencies between nodes. Each item: from (node id), to (node id).
fail_fastbooleanCancel downstream nodes on first failure. Default: true.
node_timeout_msnumberPer-node max runtime in ms. Disabled when omitted.
max_tool_rounds_per_nodenumberPer-node tool-use round budget. Triggers graceful wind-down when reached.

skill

Invoke a registered skill by name. A skill either forks an isolated subagent or loads its instructions into the current context — the mode is fixed per-skill.

ParameterTypeRequiredDescription
namestringSkill name (e.g. "mint", "diagnose").
argumentsstringArguments to pass to the skill.

cancel_background_job

Cancel a running background subagent job that the model created with agent in mode="background". Refuses to cancel user-backgrounded jobs (those are user-owned).

ParameterTypeRequiredDescription
jobIdstringBackground job ID returned by an earlier agent call.
reasonstringWhy the job is now obsolete or should stop (recorded in the trace).

send_message_to_agent

Deliver a steering message to a running background subagent at its next tool-call boundary. Injects the message as a user turn so the child can adjust mid-execution.

ParameterTypeRequiredDescription
jobIdstringBackground job ID returned by an earlier agent call.
messagestringSteering text to inject into the child at its next tool-call boundary.

Workspace

The workspace is a session-scoped shared scratchpad for sibling agents running in a compose DAG. Entries published by one node are visible to all other nodes in the same session.

workspace_publish

Publish a structured finding to the shared session workspace. Entries are visible to siblings immediately via workspace_query and injected into new siblings' system prompts at fork time.

ParameterTypeRequiredDescription
typestringEntry type: finding, evidence, hypothesis, decision, artifact, or status.
contentstringThe full text of the finding, evidence, or decision.
subjectstringShort label for relevance routing (e.g. "auth refresh").
evidencearrayFile:line references backing this entry (e.g. ["src/auth.ts:141"]).
confidencenumberConfidence level 0–1 (default 1.0).
relates_toarrayIDs of related workspace entries.
relation_typestringRelationship to relates_to entries: supports, contradicts, depends_on, or supersedes.

workspace_query

Query the shared session workspace for findings published by sibling agents. Returns entries matching the search keywords, ordered by recency.

ParameterTypeRequiredDescription
querystringKeywords to match against entry subjects and content.
typestringFilter results to a specific entry type.
limitnumberMax entries to return (default 20, max 50).

Memory

Cross-session memory persists facts and procedures across all sessions. Hot memory is injected into the system prompt; facts are stored in a searchable SQLite archive.

Search cross-session memory for facts and procedures. Returns results ranked by relevance. Supports FTS5 syntax: AND, OR, NOT, "exact phrase", prefix*.

ParameterTypeRequiredDescription
querystringSearch query (FTS5 syntax).
categorystringFilter by category: preference, convention, decision, or learning.
sincestringISO date — only return facts created after this date.
limitnumberMax results (default 10).

memory_update

Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt for all future sessions. Facts (target: "fact") go into the searchable archive.

ParameterTypeRequiredDescription
targetstringhot (HOT.md / system prompt) or fact (searchable archive).
actionstringset (create/overwrite), supersede (replace with history), or remove (delete).
contentstringContent to store (required for set/supersede).
categorystringFact category: preference, convention, decision, or learning. Required for fact target.
evidencestringProvenance citation (file:line, commit SHA). Unlocks verified recall for convention facts.
supersedesnumberFact ID being replaced (required for supersede action).
idnumberFact ID to delete (required for remove action).

procedure_write

Write a reusable procedure to memory as a markdown file. Procedures persist across sessions and are searchable via memory_search.

ParameterTypeRequiredDescription
namestringProcedure name in kebab-case (becomes the filename).
contentstringProcedure content (markdown).

State Store

A namespaced JSON document store that persists across all surfaces and sessions. Backed by a WAL-mode SQLite file at ~/.afk/state/kv/kv.db. Documents have a version counter for optimistic concurrency and optional TTL.

state_get

Retrieve a document from the durable state store. Returns null if the document does not exist or has expired.

ParameterTypeRequiredDescription
namespacestringDocument namespace. Pattern: [A-Za-z0-9_.-]+, max 128 chars.
keystringDocument key. Same pattern/limit as namespace.

state_put

Write or update a document. Creates on first write (version starts at 1) and increments the version on updates.

ParameterTypeRequiredDescription
namespacestringDocument namespace.
keystringDocument key.
valueanyJSON-serializable value to store.
ttl_msnumberTime-to-live in milliseconds. Document is deleted after this duration.
metadataanyOptional metadata object (not returned by state_get — for audit/tagging).

state_cas

Compare-and-swap write. Updates the document only when its current version matches expected_version. Returns { matched: false } on version mismatch.

ParameterTypeRequiredDescription
namespacestringDocument namespace.
keystringDocument key.
expected_versionnumberVersion the document must currently have for the update to succeed.
valueanyNew value to store if the CAS matches.
ttl_msnumberOptional TTL in milliseconds from the write time.
metadataanyOptional metadata object.

state_delete

Delete a document. Returns { deleted: true } if it existed, { deleted: false } if it did not.

ParameterTypeRequiredDescription
namespacestringDocument namespace.
keystringDocument key.

state_query

List documents in a namespace sorted by key. Supports key prefix filtering and pagination. Expired documents are excluded.

ParameterTypeRequiredDescription
namespacestringDocument namespace.
key_prefixstringOnly return documents whose key starts with this string.
limitnumberMax results (default 20, max 100).

Configuration

config_get

Read AFK configuration from ~/.afk/config/. Secret values (API keys, tokens) are always masked.

ParameterTypeRequiredDescription
targetstringconfig (afk.config.json) or env (afk.env).
keystringDotted config path or env var name. Omit to list all values for the target.
allboolean(env only) When true, list every known env var, not just those currently set.

config_set

Edit AFK configuration. Changes persist for future sessions only — the current session is unchanged. Credentials and human-gated keys are refused (use afk config CLI instead).

ParameterTypeRequiredDescription
targetstringconfig (afk.config.json) or env (afk.env).
keystringDotted config path (e.g. "model") or env var name (e.g. "AFK_EFFORT").
actionstringset (default — writes value) or unset (removes the key).
valueanyRequired for set. String, number, boolean, or array where the schema expects one.

terminal_font_size

Get or set the terminal font size in VS Code and Cursor settings. Writes are atomic. Aborts on JSONC settings files to avoid corrupting comments.

ParameterTypeRequiredDescription
actionstringget (read current size) or set (write new size).
sizenumberFont size to set (range 6–60). Required when action is set.
editorstringRestrict to a specific editor: cursor, vscode, or vscodeinsiders.

Scheduling

create_schedule

Create a new scheduled task saved to ~/.afk/config/schedules.json and live-synced to the running daemon.

ParameterTypeRequiredDescription
namestringHuman-readable label (e.g. "Nightly cleanup").
commandstringCommand to run (e.g. "/my-skill --auto").
cronstring5-field cron expression (e.g. "0 2 * * *").
triggerstringcron (default), sessionstart, or both.
notifyOnstringWhen to push Telegram notifications: failure (default), always, or never.
notifyChatstring/numberRoute notifications to a specific chat (id or alias).
enabledbooleanWhether to activate immediately. Default: true.

list_schedules

List all scheduled tasks with their IDs, cron expressions, enabled status, and notify settings. Returns a JSON array of task configs.

No parameters.

get_schedule_history

Retrieve recent execution history for a scheduled task. Returns records in chronological order (oldest first).

ParameterTypeRequiredDescription
taskIdstringThe task ID (slug) to look up.
limitnumberMax records to return (default 10, max 50).

cancel_schedule

Disable, re-enable, or permanently remove a scheduled task. Default (no flags) sets enabled: false.

ParameterTypeRequiredDescription
taskIdstringThe task ID (slug) to operate on.
enablebooleanIf true, re-enable a disabled task and register it with the daemon.
permanentbooleanIf true, remove from the store entirely (takes precedence over enable).

Git

worktree

Manage AFK-managed git worktrees under <repoRoot>/.afk-worktrees/. Prefer this over raw git worktree bash commands — it writes the .afk-worktree-meta.json the background sweep engine needs.

ParameterTypeRequiredDescription
actionstringcreate, keep, release, list, or remove.
namestring(create) Worktree slug (kebab-case). Becomes .afk-worktrees/<name> and branch afk/<name>.
basestring(create) Git ref to base the new branch on. Default: HEAD.
pathstring(keep/release/remove) Worktree slug or repo-relative path.
reasonstring(keep) Why this worktree must survive (stored as the git lock reason).
forceboolean(remove) Also remove when dirty or with commits ahead of base. Branch ref is always preserved.

Communication

ask_question

Ask the operator a question and wait for their answer. This is a last resort — exhaust tools before calling it. On non-interactive surfaces the call returns { action: "decline" } immediately.

ParameterTypeRequiredDescription
questionstringThe question to ask.
typestringtext (default), confirm, choice, multi_choice, or number.
choicesarrayOptions list. Required for choice and multi_choice types.
contextstringBackground context to display above the question.
defaultstring/boolean/numberDefault value shown as a hint.
allow_skipbooleanWhether the user may skip (submit empty). Default: false.
allow_customboolean(choice/multi_choice) Let the operator type a free-form answer.
min_lengthnumber(text) Minimum character length.
max_lengthnumber(text) Maximum character length.
minnumber(number) Minimum value (inclusive).
maxnumber(number) Maximum value (inclusive).

send_telegram

Send a Telegram message to the operator. Use for terminal-state notifications when the user is away. Plain text only, 4096-character limit. Returns an error when Telegram is not configured.

ParameterTypeRequiredDescription
messagestringPlain-text message body. Max 4096 characters.
chatstring/numberTarget a specific chat: numeric chat id or alias name from telegram.chatAliases.
thread_idnumberTopic thread ID for supergroups with topics enabled. Requires chat.

Session

get_runtime_state

Inspect what the runtime knows about the current session: identity, tool affordances, delegation state, and git workspace state. Read-only; does not probe the filesystem or network.

ParameterTypeRequiredDescription
viewstringself, tools, subagents, workspace, or all (default). Use a narrower view to keep the response compact.

get_facet

Read the structured session facet — a validated, consumer-facing summary of what a session did. Includes tool call counts, error categories, subagent invocations, outcome, summary, and cost breakdown.

ParameterTypeRequiredDescription
sessionstringSession ID, name, or "latest" (default).
fieldsarrayAllowlist of top-level fields to include. Omit to return all non-provenance fields.

read_witness

Read and filter events from a session's witness trace — the durable record of everything the agent did. Returns structured trace events in chronological order.

ParameterTypeRequiredDescription
sessionstringSession ID or "latest" (default).
kindsarrayFilter by event kind(s): tool_call, subagent_lifecycle, session_phase, closure, abort, budget, hook_decision, browser_event, claim, compaction, background_agent, queued_user_message, session_sealed.
tool_namestringFilter tool_call events to one tool name.
errors_onlybooleanWhen true, show only error events. Default: false.
limitnumberMax events to return (default 50, max 200).

search_witness

Search across multiple sessions' witness traces for a text pattern. Returns matching trace events grouped by session. Does not contain full conversation text or tool arguments.

ParameterTypeRequiredDescription
querystringText pattern to search for (case-insensitive substring).
sessionsnumberNumber of recent sessions to scan (default 20, max 100).
kindsarrayFilter results to specific event kinds.
sincestringISO date — only search sessions modified after this date.
tool_namestringFilter tool_call events to one tool name.

clipboard_read

Read the current clipboard contents as text. Requires explicit operator confirmation on every call — the clipboard may contain sensitive data. Returned text is run through the secret-redaction pipeline.

No parameters.

clipboard_write

Write a string to the system clipboard. Uses pbcopy on macOS, clip on Windows, wl-copy/xclip/xsel on Linux, with an OSC 52 fallback for SSH sessions.

ParameterTypeRequiredDescription
textstringThe text to copy to the clipboard.

emit_progress

Push a structured progress update from a child subagent to the parent session. Only available on subagents dispatched with progress_events: true. Events are delivered to the parent's next user turn as a <child-progress> XML envelope.

ParameterTypeRequiredDescription
messagestringFree-text description of current status. Capped at 2048 bytes.
phasestringShort label for the current stage (e.g. "scanning", "testing").
metadataobjectArbitrary key/value object for structured data.

On this page