Documentation
¶
Overview ¶
Package tools holds the built-in tools. Each tool lives in its own file and declares its effect; the input shape and the handler are settled in M0, the effect is fixed now because the invariants depend on it (AGENTS.md, invariants 3 and 4).
Index ¶
- Constants
- Variables
- func DraftOf(env Env, name string) ([]byte, error)
- func Escalates(input json.RawMessage) bool
- func Hash(b []byte) string
- func Loopback(input json.RawMessage) bool
- type BashInput
- type Def
- type Effect
- type Env
- type HostAuth
- type JobArgs
- type JobSpec
- type JobView
- type Jobs
- type Net
- type Planned
- type Result
- type Todo
Constants ¶
const ( // BashWaitName is the tool the workflow turns into a wait. BashWaitName = "bash_wait" // JobMaxTimeout is how long a command in the background may run, and // bash_wait wait. JobMaxTimeout = 24 * time.Hour // JobDefaultTimeout is how long one runs unless timeout_ms says. JobDefaultTimeout = 2 * time.Hour )
const Absent = "absent"
Absent is the hash of a file that does not exist.
Variables ¶
var AfterGitCommit func(commit string)
AfterGitCommit, if set, is called once a commit is in place and before the tool returns: a crash test stops the process there.
var AfterWrite func(path string)
AfterWrite, if set, is called once a write is in place and before Apply returns: a crash test stops the process there.
var AskUserTool = Def{ Name: "ask_user", Description: "Ask the user a question when you need their choice or a fact only they know, and wait for the answer, " + "instead of ending your reply with the question. Give 2 to 6 short answers to choose from; the user may also " + "answer in their own words. The turn goes on with the answer.", Schema: json.RawMessage(`{"properties":{ "question":{"type":"string","description":"The question, on its own: what you need to know and why"}, "options":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":6,"description":"The answers to choose from, each short"}}, "required":["question","options"]}`), Effect: Read, Run: func(context.Context, Env, json.RawMessage) Result { return failed("ask_user is asked by a turn, not run as a tool: in a flow, use ask()") }, }
AskUserTool asks the user a question and has the answer (ADR 0018, 7): the turn waits for it (the process may stop meanwhile), and goes on with it, its checks at its end coming after. It is not run as a tool: the turn's workflow asks and waits; Run is reached only from a flow's tool("ask_user"), and says to use ask() there.
var BashKillTool = Def{ Name: "bash_kill", Description: "Stop a command started with bash's background, and what it started.", Schema: json.RawMessage(`{"properties":{ "id":{"type":"string","description":"The command's id (bg_…)"}}, "required":["id"]}`), Effect: Real, Run: func(ctx context.Context, env Env, input json.RawMessage) Result { var in JobArgs if err := json.Unmarshal(input, &in); err != nil || in.ID == "" { return failed("invalid input: want {id}") } if env.Jobs == nil { return failed("commands in the background are not available here") } if err := env.Jobs.Kill(in.ID); err != nil { return failed("%v", err) } v, err := env.Jobs.View(in.ID, 0) if err != nil { return Result{Output: in.ID + ": stopped"} } return Result{Output: v.Text()} }, }
var BashOutputTool = Def{ Name: "bash_output", Description: "Read what a command started with bash's background wrote, and whether it still runs. since: the byte to " + "read from (the size the last read gave), to read only what is new.", Schema: json.RawMessage(`{"properties":{ "id":{"type":"string","description":"The command's id (bg_…)"}, "since":{"type":"integer","description":"Read from this byte on (default 0: from the start; a long output gives its end)"}}, "required":["id"]}`), Effect: Read, Run: func(ctx context.Context, env Env, input json.RawMessage) Result { var in JobArgs if err := json.Unmarshal(input, &in); err != nil || in.ID == "" { return failed("invalid input: want {id}") } if env.Jobs == nil { return failed("commands in the background are not available here") } v, err := env.Jobs.View(in.ID, in.Since) if err != nil { return failed("%v", err) } return Result{Output: v.Text()} }, }
var BashTool = Def{ Name: "bash", Description: "Run a shell command (sh -c) in the working directory. It runs in a sandbox: it may write only " + "inside the working directory and the temporary directories, not to .git or the agents' settings, and has " + "no network. A command that needs only this machine's network (tests that listen on 127.0.0.1 or on a Unix socket, " + "a local server) runs with sandbox set to \"loopback\": localhost, and Unix sockets in its own TMPDIR, still in the sandbox. " + "If the sandbox stops something else the task needs, call again with sandbox set to \"escalate\" " + "and a justification: the user is asked, and the command runs outside the sandbox only if they approve. " + "A command that may take long (a build, the tests, a server): background true starts it and returns its id at once; " + "bash_output reads what it writes, bash_wait waits for its end, bash_kill stops it.", Schema: json.RawMessage(`{"properties":{ "command":{"type":"string","description":"The command"}, "cwd":{"type":"string","description":"Directory to run in, inside the working directory (default: the working directory)"}, "timeout_ms":{"type":"integer","description":"Stop the command after this long (default 120000, at most 600000; in the background: default 7200000, at most 86400000)"}, "background":{"type":"boolean","description":"Start it in the background and return at once with its id"}, "sandbox":{"type":"string","enum":["default","loopback","escalate"],"description":"loopback: in the sandbox, with localhost and Unix sockets in its own TMPDIR; escalate: run outside the sandbox, if the user approves"}, "justification":{"type":"string","description":"Shown to the user, who decides: in their language and plain words, what the command does, what it reads or changes, and why the task needs it"}}, "required":["command"]}`), Effect: Real, Run: runBash, }
var BashWaitTool = Def{ Name: BashWaitName, Description: "Wait for a command started with bash's background to end, and read its output. Waiting holds nothing: it " + "may be hours, and survives restarts. With timeout_ms (at most 24 hours), it waits at most that long, and says so " + "with what the command wrote if it has not ended: to do other work meanwhile, and wait again later.", Schema: json.RawMessage(`{"properties":{ "id":{"type":"string","description":"The command's id (bg_…)"}, "timeout_ms":{"type":"integer","description":"How long to wait at most (default: until it ends)"}}, "required":["id"]}`), Effect: Read, Run: func(ctx context.Context, env Env, input json.RawMessage) Result { return BashOutputTool.Run(ctx, env, input) }, }
var EditTool = Def{ Name: "edit", Description: "Replace text in a file of the working directory. old_string must appear exactly once " + "(include enough surrounding lines to make it unique), unless replace_all is true. Read the file first.", Schema: json.RawMessage(`{"properties":{ "path":{"type":"string","description":"File path, relative to the working directory"}, "old_string":{"type":"string","description":"The exact text to replace"}, "new_string":{"type":"string","description":"The text to put in its place"}, "replace_all":{"type":"boolean","description":"Replace every occurrence (default false)"}}, "required":["path","old_string","new_string"]}`), Effect: Idempotent, Plan: planEdit, }
var FetchTool = Def{ Name: "fetch", Description: "Fetch a URL with GET and return its content: an HTML page as Markdown (format \"markdown\", the default), " + "as plain text (\"text\"), or as it is (\"html\"). Large content is cut. To send data, use the http tool.", Schema: json.RawMessage(`{"properties":{ "url":{"type":"string","description":"The http or https URL"}, "format":{"type":"string","enum":["markdown","text","html"],"description":"How to return an HTML page (default: markdown)"}, "headers":{"type":"object","additionalProperties":{"type":"string"},"description":"Request headers (Accept, say)"}}, "required":["url"]}`), Effect: Read, Run: runFetch, }
FetchTool reads a URL with GET (ADR 0013). It only reads, so a resumed turn may fetch again. It follows redirects within the same host; one to another host is handed to the model, whose call for it is checked like any other.
var FlowCheckTool = Def{ Name: "flow_check", Description: "Check a flow's Starlark script (.kairocode/workflows/<name>.star) without running it: parse errors, " + "names that are not there, a missing main(input). Call it after writing or changing a flow, and fix what it reports " + "until it says the flow is ready. It also shows the flow's shape.", Schema: json.RawMessage(`{"properties":{ "name":{"type":"string","description":"The flow's name: the file's name without .star"}}, "required":["name"]}`), Effect: Read, Run: runFlowCheck, }
FlowCheckTool checks a flow's script without running it (ADR 0003): the model calls it after it writes or changes .kairocode/workflows/<name>.star, and puts right what it reports.
var FlowPublishTool = Def{ Name: "flow_publish", Description: "Publish a flow's draft: make .kairocode/workflows/drafts/<name>.star the flow that runs with /flow <name>, " + "hooks and kairocode run. The user is shown the flow to review (and may try it) before it is. Give what the user asked " + "for, as for flow_write.", Schema: json.RawMessage(`{"properties":{ "name":{"type":"string","description":"The flow's name"}, "asked":{"type":"array","description":"What the user asked for, one thing at a time, as you took it, each with the phase(\"name\") of the flow that does it: shown to the user to check against the flow", "items":{"type":"object","properties":{"need":{"type":"string"},"phase":{"type":"string"}},"required":["need","phase"]}}}, "required":["name"]}`), Effect: Idempotent, Plan: planFlowPublish, Apply: applyFlowWrite, }
FlowPublishTool makes a flow's draft the flow that runs (ADR 0030): it puts .kairocode/workflows/drafts/<name>.star, as it is, at .kairocode/workflows/<name>.star. Its content comes from the draft's file, not from the model. The user is asked (the flow's review and its try, ADR 0003, 0017); the write is planned and then made by comparing and replacing, as flow_write's.
var FlowWriteTool = Def{ Name: "flow_write", Description: "Write a flow's draft: the whole Starlark script of .kairocode/workflows/drafts/<name>.star, new or changed. " + "It is checked first (parse errors, names that are not there, a missing main(input)); a script with problems is not " + "written, and the problems come back to fix. It shows the flow's shape when it is written. A draft does not run " + "(only as a try: /flow <name> --draft); flow_publish makes it the flow that runs, once the user allows it.", Schema: json.RawMessage(`{"properties":{ "name":{"type":"string","description":"The flow's name: lowercase letters, digits and - (not new, graph or runs)"}, "source":{"type":"string","description":"The flow's whole Starlark script"}, "asked":{"type":"array","description":"What the user asked for, one thing at a time, as you took it, each with the phase(\"name\") of the flow that does it: shown to the user to check against the flow", "items":{"type":"object","properties":{"need":{"type":"string"},"phase":{"type":"string"}},"required":["need","phase"]}}}, "required":["name","source"]}`), Effect: Idempotent, Plan: planFlowWrite, Apply: applyFlowWrite, }
FlowWriteTool writes a flow's draft (ADR 0003, 0030): with flow_publish, the one way into .kairocode, which the other tools may not write (ADR 0005), as the git tools are into .git. It writes only .kairocode/workflows/drafts/<name>.star, and only a script that flowchart.Check finds nothing wrong with; the write is planned and then made by comparing and replacing (design 3.1), as write's is. A draft runs only as a try: by default it is written without asking.
var GitCommitTool = Def{ Name: "git_commit", Description: "Commit every change in the working directory (like git add -A && git commit) with a message.", Schema: json.RawMessage(`{"properties":{ "message":{"type":"string","description":"The commit message"}}, "required":["message"]}`), Effect: Idempotent, Plan: planCommit, Apply: applyCommit, }
var GitPushTool = Def{ Name: "git_push", Description: "Push the current branch's commit to a remote branch (no force). The user is asked every time: " + "it reaches outside the machine.", Schema: json.RawMessage(`{"properties":{ "remote":{"type":"string","description":"Remote (default origin)"}, "branch":{"type":"string","description":"Branch (default: the current one)"}}}`), Effect: Idempotent, Plan: planPush, Apply: applyPush, }
var GlobTool = Def{ Name: "glob", Description: "Find files in the working directory whose path matches a glob pattern. * and ? match within one path segment; ** matches any number of segments (e.g. \"**/*.go\"). Results are sorted.", Schema: json.RawMessage(`{"properties":{ "pattern":{"type":"string","description":"Glob pattern, relative to path"}, "path":{"type":"string","description":"Directory to search from (default: the working directory)"}}, "required":["pattern"]}`), Effect: Read, Run: runGlob, }
var GrepTool = Def{ Name: "grep", Description: "Search file contents in the working directory with a regular expression (RE2 syntax). Prints path:line: text for each matching line. Binary files, .git and node_modules are skipped.", Schema: json.RawMessage(`{"properties":{ "pattern":{"type":"string","description":"Regular expression (RE2)"}, "path":{"type":"string","description":"File or directory to search (default: the working directory)"}, "include":{"type":"string","description":"Only files whose name matches this glob, e.g. \"*.go\""}}, "required":["pattern"]}`), Effect: Read, Run: runGrep, }
var HTTPTool = Def{ Name: "http", Description: "Send a POST request (an API call: a comment, a CI run, a GraphQL query) and return the response's status, " + "main headers and body. It is not sent again by itself: if it may have reached the server without an answer, " + "a person is asked whether it took effect. To read a page, use fetch.", Schema: json.RawMessage(`{"properties":{ "url":{"type":"string","description":"The http or https URL"}, "headers":{"type":"object","additionalProperties":{"type":"string"},"description":"Request headers (Content-Type, Idempotency-Key, say)"}, "body":{"type":"string","description":"The request body"}}, "required":["url"]}`), Effect: Real, Run: runHTTP, }
HTTPTool sends a POST (ADR 0013). It acts on the world: a request that may have reached the server, its answer not had, is not sent again unasked (invariant 4) but stops for a person to say whether it took effect. It follows no redirect. A POST that only reads (a GraphQL query) is a POST all the same.
var ListTool = Def{ Name: "list", Description: "List the files and directories under a directory of the working directory, as a tree. .git and node_modules are skipped.", Schema: json.RawMessage(`{"properties":{ "path":{"type":"string","description":"Directory, relative to the working directory (default: the working directory)"}}}`), Effect: Read, Run: runList, }
var ReadTool = Def{ Name: "read", Description: "Read a text file in the working directory. Lines are numbered from 1. Use offset and limit to read part of a long file.", Schema: json.RawMessage(`{"properties":{ "path":{"type":"string","description":"File path, relative to the working directory"}, "offset":{"type":"integer","description":"First line to read (1-based)"}, "limit":{"type":"integer","description":"Number of lines to read (default 2000)"}}, "required":["path"]}`), Effect: Read, Run: runRead, }
var SkillTool = Def{ Name: "skill", Description: "Load a skill: specialized instructions and workflows for a task. Call it with the name of a skill " + "listed in <available_skills> when a task matches its description, then follow what it says.", Schema: json.RawMessage(`{"properties":{ "name":{"type":"string","description":"The skill's name, as listed"}}, "required":["name"]}`), Effect: Read, Run: runSkill, }
SkillTool loads a skill (opencode's skill tool): the instructions of a SKILL.md the system prompt lists, where it lives and its other files.
var TaskTool = Def{ Name: "task", Description: "Hand a self-contained task to a subagent: another agent that starts with no history, does it with its own " + "tools, and answers. Use it for work that can be done apart (looking through code, a review, a change in one place), " + "several at once if they are independent. Say in the prompt all it needs to know.", Schema: json.RawMessage(`{"properties":{ "prompt":{"type":"string","description":"The whole task: what to do, where, and what to answer with"}, "agent":{"type":"string","description":"The agent to do it: build (can change files, the default), plan (only reads), or one of .opencode/agents"}}, "required":["prompt"]}`), Effect: Read, Run: func(context.Context, Env, json.RawMessage) Result { return failed("task runs as a subagent of a turn, not as a tool: in a flow, use agent()") }, }
TaskTool hands a task to a subagent (FR-13): another agent, with its own prompt and tools, does it from the start and answers. It is not run as a tool: the turn's workflow runs the subagent as a turn of its own, a child that survives restarts and stops with its parent, and gives its reply as the call's result. Run is reached only from a flow's tool("task"), and says to use agent() there.
var TodoTool = Def{ Name: "todo", Description: "Keep a list of what is to be done in a task of several steps, and show it to the user: give the whole list each time, " + "each item pending, in_progress (one at a time) or completed. Use it for work of three steps or more; mark an item completed as soon as it is done.", Schema: json.RawMessage(`{"properties":{ "todos":{"type":"array","items":{"type":"object","properties":{ "content":{"type":"string","description":"What is to be done"}, "status":{"type":"string","enum":["pending","in_progress","completed"]}}, "required":["content","status"]}}}, "required":["todos"]}`), Effect: Read, Run: runTodo, }
TodoTool keeps the model's list of what to do (FR-5, ADR 0022). It is given the whole list each time and gives it back: the list lives in the conversation (the latest call holds it), not in a store, so it only reads.
var WriteTool = Def{ Name: "write", Description: "Write a whole file in the working directory, creating it (and its directories) if needed. To change part of an existing file, use edit instead.", Schema: json.RawMessage(`{"properties":{ "path":{"type":"string","description":"File path, relative to the working directory"}, "content":{"type":"string","description":"The file's full new content"}}, "required":["path","content"]}`), Effect: Idempotent, Plan: planWrite, }
Functions ¶
func Escalates ¶
func Escalates(input json.RawMessage) bool
Escalates says whether a bash call asks to run outside the sandbox.
func Loopback ¶
func Loopback(input json.RawMessage) bool
Loopback says whether a bash call asks for this machine's network in the sandbox (ADR 0031).
Types ¶
type BashInput ¶
type BashInput struct {
Command string `json:"command"`
Cwd string `json:"cwd"`
TimeoutMS int `json:"timeout_ms"`
Background bool `json:"background"`
Sandbox string `json:"sandbox"`
Justification string `json:"justification"`
}
BashInput is bash's input.
type Def ¶
type Def struct {
Name string
Description string
// Schema is the JSON schema of the input: {"properties": ..., "required": [...]}.
Schema json.RawMessage
Effect Effect
// Run does the work in the session's working directory. A failure the
// model should see (a missing file, a path outside the directory) is a
// Result with IsError, not an error.
Run func(ctx context.Context, env Env, input json.RawMessage) Result
// Plan, for a tool that writes a file, works out the write without
// making it (design 3.1). The plan is recorded, and Apply makes it,
// comparing the file with what the plan saw: done again, it does not
// write twice. A tool with Plan has no Run.
Plan func(ctx context.Context, env Env, input json.RawMessage) Planned
// Apply makes what Plan worked out, from its Data, when it is not a file
// write. Done again it must not act twice.
Apply func(ctx context.Context, env Env, data json.RawMessage) Result
}
Def describes a tool. Every Def literal must set Effect explicitly (checked by internal/invariants), even when it is Real.
type Effect ¶
type Effect int
Effect is what a tool does to the world. The zero value is Real, so a tool that forgets to declare one is treated as acting on the world (the same rule as kairo's ir.Effect).
const ( // Real must not happen twice; an unknown outcome stops for review. // kairo: EffectReal. Real Effect = iota // Idempotent acts, but running it again with the same input gives the // same result; an unknown outcome is checked, then retried. // kairo: EffectReal with IdempotentRetry. Idempotent // Read only reads and may run again freely. kairo: EffectUnprotected. Read )
type Env ¶
type Env struct {
// Root is the working directory. Every file a tool touches is reached
// through it, so no path, symbolic link or race leads outside it.
Root *os.Root
// Dir is the working directory's absolute path, to read the absolute
// paths a model may give.
Dir string
// Net is how fetch and http reach the network (ADR 0013).
Net Net
// Jobs are the session's commands in the background (ADR 0028).
Jobs Jobs
}
Env is where a tool works.
type HostAuth ¶
type HostAuth struct {
Header string `json:"header"`
Env string `json:"env"`
Prefix string `json:"prefix,omitempty"`
}
HostAuth: Header is Prefix and the value of the environment variable Env.
type JobArgs ¶
type JobArgs struct {
ID string `json:"id"`
Since int64 `json:"since"`
TimeoutMS int64 `json:"timeout_ms"`
}
JobArgs are bash_output's, bash_wait's and bash_kill's input.
type JobSpec ¶
type JobSpec struct {
Command string `json:"command"`
Cwd string `json:"cwd,omitempty"`
Escape bool `json:"escape,omitempty"` // outside the sandbox (approved: escalate)
// Loopback: in the sandbox, with this machine's network (ADR 0031).
Loopback bool `json:"loopback,omitempty"`
Timeout time.Duration `json:"timeout"`
}
JobSpec is a command to run in the background.
type JobView ¶
type JobView struct {
ID string `json:"id"`
Command string `json:"command"`
Running bool `json:"running"`
// Status, once it ended: "exit N", "timed out", "stopped", or "lost"
// (its runner went, with the machine say: how it ended is not known).
Status string `json:"status,omitempty"`
// Output is what it wrote from Since on (its end, if that is long);
// Size, all it wrote.
Output string `json:"output"`
Since int64 `json:"since"`
Size int64 `json:"size"`
}
JobView is a command's state and output.
type Jobs ¶
type Jobs interface {
// Start starts a command in the background: its ID.
Start(spec JobSpec) (string, error)
// View is a command's state, and what it wrote from byte since on.
View(id string, since int64) (JobView, error)
// Kill stops a command (and what it started).
Kill(id string) error
}
Jobs are the session's commands in the background, as a tool call sees them (Env.Jobs).
type Net ¶
type Net struct {
// AllowPrivate lets a request reach loopback, private and link-local
// addresses.
AllowPrivate bool
// Auth is a header to send to a host (by its name, lower case), its
// value read from an environment variable when the request is made.
Auth map[string]HostAuth
// contains filtered or unexported fields
}
Net is the user's settings for fetch and http ("http" in their kairocode.json; a project's are not read).
type Planned ¶
type Planned struct {
Data json.RawMessage
Path string
// Before is the file's hash when it was planned (Absent: no file).
Before string
// Content is the file after the write; After its hash.
Content []byte
After string
// Summary says what the write does, for the model.
Summary string
Fail *Result
}
Planned is a write worked out by Plan, or the failure to give the model (Fail) when there is nothing to write. A file write fills Path, Before, Content, After; a tool with an Apply of its own fills Data instead.
type Result ¶
type Result struct {
Output string
IsError bool
// Unknown: the tool may have acted on the world but cannot say whether
// it did (it was cut off after it began). Such a result is never taken
// for success (invariant 4): a real tool stops for review, an idempotent
// one is checked and tried again.
Unknown bool
}
func Apply ¶
Apply makes a planned write by comparing and replacing (design 3.1): the file as the plan expected it is written; the file as the plan would leave it is already done; anything else is a conflict, given to the model. The new content goes to a temporary file that is then renamed over the old, so no half-written file is ever seen. Done again, Apply does not write twice.