docs/cmd/ez-agent-builtin.md
ez-agent-builtin shipped capabilities
The builtin is the direct stdio provider for EzAgent's default tools, plugins,
macros, and embedded skills. Independent providers start with
ez-agent-hello; wire contracts belong to the
JSONL API.
Capability roles
| Need | Type |
|---|---|
| Model-invoked operation with one terminal result | Tool |
| Transformation of pending conversation turns | Plugin |
| User/trigger logic returning text | Macro |
| Separately distributed provider | External addon |
Assembly and routing
| 1 | builtin catalog + handlers |
| 2 | -> one stdio capability provider |
| 3 | -> daemon capability registry |
| 4 | -> model tool calls, plugin pipeline, macro triggers |
| 5 | |
| 6 | embedded skill packages -> discovery/help resources |
Daemon configuration claims builtin capability names for this provider. The provider's metadata describes model-visible behavior. Its handlers execute the call and return the required terminal result. Embedded skills are documentation resources loaded separately from capability invocation.
To add a capability:
- Implement and test it in the matching builtin subpackage.
- Add metadata and dispatch in
main.go. - Add provider routing in
builtin.yaml. - Add default activation or trigger routing only when intended.
- Update its owning documentation and durable behavior tests.
Configured direct-provider names establish routing; builtin announcement is not a
prerequisite. The runcommand package owns the shared command service for Bash
and Ruby execution, including background task lifecycle and output reporting.
Bash-specific execution and audit logic remains in that package.
builtins.ruby_state is routed as an internal macro. Named notifications work
on fresh valid leaves without file registrations. On Linux, file-backed operations
use the daemon's atomic stable-key attachment RPC to register or reuse the state,
lock, and diagnostic files. Registration does not create the state payload.
Other platforms return wait_unavailable for file-backed operations because the
file adapter is currently Linux-only.
Inside Bubblewrap
The daemon passes ruby_max_workers at launch. The builtin does not open
builtin_plugin.yaml or create config or auth files inside the sandbox. It
gets modes, audit settings and Workspace approvals from the daemon over
stdio. The mount policy
shows how to expose user instructions and individual skill packages. Missing
configured skill paths appear in the daemon log and system prompt, and in
buffer errors when a requested skill cannot be found.
Bash and Ruby run in the session workspace. They can read a read-only project;
writes from them or from write_file fail regardless of approval. The bundled
Ruby launcher extracts the payload on demand in its own persistent directory,
outside the file cache, and runs it inside the same sandbox. Worker state is
reusable within a provider process. File-backed state survives provider
recovery through leaf-files/. There is no host Ruby fallback. $AGENTCLI
connects to the restricted socket bound into the sandbox; if that socket is
unavailable, the client fails instead of starting a daemon. Managed Ruby
invoke_tool, including buffers.read and buffers.stat, uses the builtin's
stdio connection and remains available, subject to normal tool dispatch and
Workspace approvals.
Ruby state and notifications
The macro accepts a JSON object in its parameter string. Every request has an
operation field. Successful responses have ok: true and the fields below;
there is no dictionary snapshot or separate compare-and-swap operation.
| Operation | Request fields besides operation | Successful response fields besides ok |
|---|---|---|
get | key | value, revision, key_revision |
set | key, value, optional if_key_revision | revision, key_revision |
delete | key, optional if_key_revision | deleted, revision, key_revision |
wait for any revision | target: "any", after_revision, optional timeout_ms | outcome, and revision when changed |
wait for a key revision | target: "key", key, after_key_revision, optional timeout_ms | outcome, and key_revision when changed |
prepare_wait | name, optional timeout_ms | handle |
wait for a notification | handle | outcome |
cancel_wait | handle | none |
notify | name | none |
Keys and notification names must be nonempty valid UTF-8 and at most 128 bytes. Values are JSON. The sum of compact encoded values, including JSON escaping, is limited to 65,536 bytes. The entire encoded document, including keys and metadata, is limited to 131,072 bytes. There is no separate key-count limit. Reads update each key's recency. A set evicts the least recently used other keys as needed to fit. If the new value cannot fit alone, the existing document stays unchanged.
Document and key revisions are opaque strings. A missing physical data file
returns state_not_found with stable revision and key_revision absence
revisions. An initialized document without the key returns key_not_found with
its current document and key absence revisions. These key revisions can be used
as if_key_revision; a mismatch returns revision_conflict and current
revisions. Deleting a missing key succeeds with deleted: false. Deleting the
last present key writes an initialized empty document, so later reads return
key_not_found, not state_not_found. An absent key's revision incorporates
the document revision and can change when another key changes.
Revision waits return changed, timed_out, reset, or cancelled.
Notification waits return notified, timed_out, or cancelled. A notification
before prepare is lost; a prepared handle retains one outcome until collected
or expired, with no queue or replay. Only one collector may wait on a handle.
Optional timeout_ms is 1 through 30000, default 30000. The monotonic deadline
starts at prepare, and an uncollected handle expires 30 seconds after its original
deadline. Standalone calls share a per-leaf limit of 128 waits, managed
executions have 128 each, and the global limit is 1024.
Domain failures return ok: false and error: {code, message}, with revision
and key_revision when available. The outer macro result is not an error for
these outcomes; outer errors are reserved for provider, transport, or routing
failure.
| Code | Condition |
|---|---|
invalid_input | Invalid JSON, operation, key, name, wait target, or timeout |
state_not_found | get on an absent data file |
key_not_found | get on an initialized document without the key |
revision_conflict | if_key_revision does not match the current key revision |
state_too_large | A value or resulting document cannot fit within the limits |
identity_mismatch | A registration, managed path, file type, or file identity fails verification |
state_corrupt | Successfully read data was malformed or outside document limits and was reset |
io_failure | Registration or file I/O failed, including an uncertain post-replacement sync |
wait_limit | Per-owner or global wait capacity is exhausted |
wait_in_use | Another collector is already waiting on the handle |
wait_unavailable | Platform support is unavailable, the manager stopped, or a handle is unavailable |
Corruption is diagnosed without copying state contents, then replaced with an
initialized empty document. Registered revision waiters receive reset. I/O
and identity failures do not themselves trigger a reset. If replacement
succeeds but directory synchronization fails, the caller receives io_failure
even though the replacement occurred. Do not blindly retry an uncertain write.
The private Manager also provides NewExecution(leaf), whose Call uses the
same JSON operations and whose Retire cancels that execution's waits. When
assembled, the managed Ruby worker uses this execution-bound interface. Ordinary
macro calls contain no client or execution identity, so standalone callers must cancel handles explicitly, collect
them, or let them expire; disconnect or leaf deletion does not immediately retire
them. Direct waits have application deadlines, and process shutdown clears waits.
The daemon's leaf-deleted event goes to the requester and current leaf feed, not
to a multi-leaf capability lifecycle callback. A managed collector must be the
execution that prepared the handle, and a retired execution cannot collect.
Standalone collection remains same-leaf bearer collection: a caller with a
handle can collect it without an execution identity.
The Linux adapter verifies the registration and managed directory, uses a
separate stable lock file, bounded reads, and same-directory replacement.
At each registration checkpoint (before locking, after locking, and before
replacement), it reads one leaf_files snapshot and verifies all three state,
lock, and diagnostic descriptors. Snapshots are not reused across checkpoints.
It assumes the daemon-owned directory and lock registration are not replaced by
outside writers. File locking protects updates across processes, but revision
wakeups and notifications are local to the manager and do not observe another
manager's writes. Local socket callers can invoke this macro directly. This is
not a sandbox or a secrecy boundary.
Cancellation propagates to registration callbacks and prevents queued leaf-gate or file-lock work from starting later. Callbacks must cooperate with the context; an admitted synchronous filesystem operation cannot be forcibly interrupted. Shutdown stops admission and joins outstanding revision-snapshot work, so an uninterruptible callback or filesystem operation can delay that drain. After a successful replacement and sync, later cancellation does not replace the committed result.
Handler boundaries
- Tool metadata is the model contract. Handlers validate semantic arguments and return one terminal result. Parallel acknowledgement is permission, not a replacement for that result.
- Correlation uses the daemon-supplied
tool_call_id, including progress, abort, heartbeat, result, and retained command buffer ownership. - Buffer ranges apply to text. Supported image/PDF reads attach the whole file.
The
meta:namespace accepts exact names, not arbitrary queries.meta:indexlists every endpoint name and relevant skills; the tool description does not catalogue endpoints. Unknown or malformed names fail with a recovery hint: the error points to the official call list inmeta:index; retry with a listed name. File and service failures retain their own diagnostics. meta:leaves/activelists running and aborting leaves across working directories, including temporary leaves, from a filtered leaf-list request and the runtime projection. Older daemons may return all leaves for local filtering. This is a snapshot, not a lifecycle or authorization decision.meta:history/<leaf-id>returns JSON turn summaries through the latest virtual root and the canonical tip; only sent/ready turns appear in the list.meta:last-turn/<leaf-id>reads that tip, including a draft, andmeta:turn/<turn-id>reads any persisted turn.currentidentifies the calling leaf in the first two names. The last-turn tip and content are separate reads. Buffer slicing limits returned text, not the underlying RPC response.- Plugins return nonempty hydratable pending turns. Invalid plugin output keeps the prior pipeline turns. Macros return strings. Both use renewable inactivity watchdogs; explicit caller limits still apply.
write_filehas one target. Create requires a new file; replace/append require an existing text file; substitute requires exactly one match. Patch validates all regions against one snapshot and writes only after a unique complete assignment. Grammar and errors belong tofileedit/patch_parse.go,tool_write_file.go, and tests.write_fileand file-backedbuffercalls use file preflight in Workspace approvals.- Internal macro metadata hides general TUI selection and suggestions without changing discovery, attachment, or explicit invocation.
File preflight
In Workspace approvals, file tools use fixed path rules and never consult the
audit model. write_file checks before opening a file or creating parent
directories. buffer applies the same scope rule to file: reads,
including stat and media attachments. Either the written path or the resolved
target can be in scope. The written path is made absolute against the call's
directory and cleaned, including ... The workspace, EzAgent file cache, and
private scratch directories under /tmp count in both their original and
resolved spellings. An in-scope file needs no question unless the write
targets a protected name. A path written inside the workspace stays in scope
through a link to an outside directory. If neither spelling is in scope and
no grant applies, the builtin asks directly and names the target in the reason.
Links do not change how the file is opened or created.
Outside file operations can offer Allow for this session. The question names the resolved directory the grant will cover: the target itself if it is a directory, or its parent otherwise. A remembered read covers that tree's reads. A remembered write covers both reads and writes there. The filesystem root cannot be remembered. The builtin checks both written and resolved directory ancestors and asks the daemon to match only keys it learned from remembered replies. It forgets a key when the daemon returns no match. If the walk exceeds 64 directories or the 128-key set is full and no key matches, the question offers only Allow once and Cancel. In-scope operations don't look up grants. File grants never apply to commands. See the grant lifetime.
Tagged builtin buffers can read their own backing files, including through links. This does not grant general access to the state directory. If the policy is unknown, direct file reads and writes ask with only Allow once and Cancel, rather than assuming YOLO. Tagged buffers and background Ruby attachments keep their legacy behavior when the policy is unknown.
Edits to .ez-agent/config.yaml, root AGENTS.md, .ez-agent/AGENTS.md,
loaded project or configured skill instruction files, and the user config
always ask when the written path names the file itself, before checking any
grant. They offer only Allow once and Cancel, as do outside reads of those
names. Both spellings of the workspace root count. A differently named link
to a protected file does not inherit its protection. Ordinary files such as
.ez-agent/scratch/notes.txt are not protected.
If the tool detects that an approved destination changed, it stops and needs
a new call. This check also runs after a remembered match. It is best effort;
POSIX permissions and link behavior still apply.
Inline @file references and automatic instruction and skill loads are not
checked: the builtin cannot tell who authored the request. File completion and
the skill: namespace also keep their normal access to user-selected files
and configured skills. A foreground Ruby path attachment is checked on the
Ruby call. If that call has already used its question, use a separate buffer
call for a read that needs another reply. Background Ruby path attachments
have no live call to ask through; under Workspace approvals, an outside read
is refused with a buffer hint. Nested invoke_tool requests and separate
API invocations get their own check and do not inherit approval.
YOLO skips workspace preflight. These checks belong to the builtin handlers: dispatch to a different provider offering the same tool name does not invoke them.
Private Ruby executor
run-cmd accepts interpreter: ruby for foreground or background execution
when the bundled Ruby executable is available. The executor in
internal/builtin/rubyworker uses a leaf-bound private pool and
launches the existing bundled Ruby executable with a defaults-owned embedded
program. Two inherited pipes carry private JSON messages independently of
stdout and stderr: a versioned ready handshake, sequenced execution requests,
and matching completion replies. A private Unix socket passes per-execution
capture pipe and state socket descriptors to the worker. StartWithOptions and
NewPoolWithOptions accept Options{ChannelMode: UnixChannels} to force the
Linux-tested pathname AF_UNIX fallback. That mode starts without inherited extra
descriptors and connects separate request, reply and descriptor sockets in a
temporary directory with mode 0700. Listeners close after connection, and
pathname removal is attempted before the ready handshake completes.
Execution-local state socket pairs also attempt pathname removal before
descriptor transfer. If removal is refused while sockets remain connected,
the owner retains the pathname and retries after closing the handles. State
cleanup that remains blocked by a duplicated peer is retained through worker
shutdown. Stdout and stderr remain separate capture pipes passed with SCM_RIGHTS.
The default prefers inherited channels. It falls back only for unsupported
channel allocation, not resource exhaustion or a failed process launch. No
started worker is retried.
An explicit InheritedChannels selection disables that automatic fallback.
Temporary socket paths must fit the host's AF_UNIX pathname limit; a long
TMPDIR can make fallback allocation fail. Directory cleanup runs on allocation
failure, launch failure, partial connection, cancellation and success. Startup
uses the caller's context rather than a separate internal timeout. Cancellation
also interrupts blocked descriptor writes, and cleanup joins channel readers,
partial startup and execution-local state calls. Private directory permissions
do not isolate the worker from other code running as the same user. Cleanup
after an OS crash is best effort.
A broken channel, cancellation, shutdown or uncertain execution boundary makes the process disposable. On Linux, the worker owner observes exit without reaping the group leader, signals the group while its identity is reserved, drains capture, and disables group signals before reaping. Close joins the worker and kills its group, including ordinary descendants. On other Unix systems it kills only the worker process. Deliberately detached processes are not confined.
The executor uses Unix process groups and inherited control descriptors, matching the existing Bash tool's Unix process model. Native Windows is not supported by this builtin baseline. The bundled Ruby launcher is shipped for Linux/amd64; cross-compilation of the Go executor alone does not establish runtime support.
Each request supplies the leaf, cwd, code and private context. The worker refreshes
its cwd, EZ_AGENT_LEAF_ID, $ez_agent_context, output capture and result slot;
ordinary Ruby process state can persist. Both streams start captured. The
private capture_stdout(boolean) and capture_stderr(boolean) methods switch
capture prospectively; disabled segments are drained. Output is returned as raw
bytes, without cross-stream ordering or a capture size limit. Optional per-request
writers receive output as it is produced, including output before cancellation or
worker failure. With no writer, the corresponding result field holds the captured
bytes, including on errors. Production streams both channels through the Bash
capture and preview machinery, retaining output as ruby:<tool_call_id>.
result(value) appends a labeled JSON value to that output.
result(value, attachments: [...]) also delivers JPEG, PNG, GIF, WebP, or PDF
files from raw Ruby bytes, base64 decoded by the Ruby helper, or cwd-relative
paths. EzAgent's 32 MiB aggregate binary cap and model-specific limits still
apply. Payloads stay out of retained
text. Invalid attachments mark the result as an error without discarding valid
files. See the managed Ruby reference.
Both foreground results and background completions use the existing attachment
fields. A malformed reply discards the worker. A StandardError can leave the
worker reusable after cleanup; fatal exceptions and live script-created threads at completion
cause discard. After completion or termination, capture gets 250 ms to drain,
matching Bash. A retained descriptor past that deadline causes worker and process
group cleanup, closes the capture pipes, and sets CaptureIncomplete; output
still held by a writer at that point can be lost. Capture sink failures also set
that flag. A sink that blocks indefinitely can still block its copy goroutine, as
with Bash capture. These facilities are not a
sandbox against Ruby code running in the worker process.
Inside an execution, invoke_tool(name, arguments = {}) sends a private,
correlated request to the handler supplied for that execution. It returns the
handler's JSON value, including tool errors and attachments, without reducing
it to text. The Go owner binds trusted routing context; the helper does not
choose its authoritative leaf or parent. Callback errors, invalid responses,
broken channels and execution cancellation discard the worker. Callbacks must
honor their context: cancellation stops waiting and closes the worker, but cannot
forcibly stop a callback that ignores it. The production broker invokes tools on
the execution's leaf through the daemon. It preserves the returned turn, including
attachments and error metadata, and explicitly cancels accepted invocations when
the execution ends. A bounded acknowledgement window begins at retirement, so
late accepted IDs can be cancelled without retrying an uncertain start. If an
acknowledgement is lost or cancellation cannot be confirmed, Ruby output warns
that effects may have occurred.
Worker startup failures report the connection or handshake error, include up to 8 KiB of launcher stderr with a truncation marker when needed, and state that the script did not run. Startup diagnostics stay separate from script stdout and stderr. Excess startup stderr is drained without retaining it; shutdown bounds the drain wait if a descendant holds stderr open.
Private pool bookkeeping starts empty, reserves a maximum per leaf,
and rejects acquisition at capacity. A lease is exclusive; its owner releases it
only after execution and marks uncertain workers unhealthy. Surplus idle workers
can be reaped after their individual idle deadlines while one healthy idle worker
is retained. Retirement and shutdown close and join workers, including startup.
The worker limit is ruby_max_workers in builtin_plugin.yaml, defaulting to
four workers per leaf. With Bubblewrap on, the daemon passes the value from its
startup snapshot. Otherwise the builtin reads it when it starts. The pool
checks every minute for surplus workers
idle for five minutes and reads leaf status to discard idle workers for unloaded
or missing leaves. It never closes a busy lease based on that status snapshot.
The pool closes on shutdown.
Ruby commands share the Bash task owner and internal reap controls. Foreground
execution uses the existing timeout, progress, capture and terminal reporting
paths. Each Ruby execution goes through command preflight
before worker acquisition or capture allocation, even when the worker is reused.
Background Ruby runs in a Ruby worker, not a shell. Its task owns the worker,
state execution and capture after the initial result. Completion uses the same
acknowledged background ownership and wakeup path as Bash. Output uses
ruby:<tool_call_id> and state uses meta:ruby-<task-id>/state in initial results,
task listings, reminders, completion turns and saved reports. The
background_bash completion correlation and bash turn-type tag remain unchanged.
Reap, abort,
timeout and shutdown cancel the execution and join its state calls. Output
remains available through the retained buffer.
The state adapter uses a separate per-execution socket and retires its manager
execution after the worker returns. Ruby's state and buffers helpers use
the peer Ruby libraries included in the shipped runtime. Fresh state files
attach through the shared state manager and buffers invokes the buffer tool
through the same leaf-scoped broker. Named notifications also use that manager.
Registered-state timeout and reap cleanup depend on the state manager propagating the execution context through registration lookup and lock admission. Cancellation closes the script's execution-local state connection and stops dispatching further requests. The worker owner joins any admitted state call; it does not abandon it or delete the leaf's persistent state. Cancellation stops pending lookup and lock admission, not filesystem I/O already admitted; such I/O can still block cleanup. Named waits honor their context.
How are capability executions owned?
Transport callbacks hand accepted tools, plugins, and macros to independently tracked goroutines. There are no fixed worker lanes or call-count limits, so a long Bash command or model wait cannot consume the execution capacity needed by another capability or an internal completion macro. Admission and start commits are ordered against shutdown. Accepted work either starts or is discarded, and shutdown joins both paths without invoking handlers under scheduler locks.
The internal commandtask package tracks active command ownership separately
from runtime's general tool-abort registry. Bash and Ruby register before
admission and retain the same task through execution and background completion
reporting. They retire local command ownership before requesting removal of
daemon background ownership. Retained output and historical status records
outlive that active ownership.
The read-only meta:tasks/current buffer lists active command ownership for the
invoking leaf, including available buffer identities and cancellation state. It
requires a leaf context and does not list tasks belonging to other leaves.
The private leaf-scoped reap request is distinct from ordinary tool abort. On
Linux, Bash signals its owned process group, including ordinary descendants,
while retaining its group identity through completion reporting. Processes that
leave that group are not controlled. Safe Bash reap is not yet supported on
other Unix platforms. The shared owner provides synchronous reap and
reap-all controls using the trusted invoking leaf; reap-all includes the
caller if it owns a command task. The command-control dispatcher routes internal
controls to this shared owner.
Without Bubblewrap, the builtin still loads and normalizes max_parallel from
builtin_plugin.yaml for compatibility, with the existing default of 64. The
setting is a legacy no-op. It does not
limit capability execution or Bash commands. Ruby Workflow's separate
max_parallel setting still bounds its model workers.
How does run-cmd admit and report commands?
The model-visible run-cmd tool shares command lifecycle and reporting across
Bash and Ruby, and routes internal task controls to the same owner. It replaces
the bash tool name; there is no alias. Explicit configuration overrides are not rewritten,
and historical calls and bash: buffer references retain their original names.
Retained output uses bash:<tool_call_id> for Bash, ruby:<tool_call_id> for
Ruby, and int:<tool_call_id> for internal controls. All three use the same
line and byte preview limits and retain nonempty output only when it cannot
be shown completely inline. Internal controls use the default preview limits;
short replies remain direct results. Bash and Ruby background captures are
always retained, including empty output.
The backing files remain buffers/<namespace>/<tool_call_id>.txt in service
state. default.unique_buffer reserves bash, ruby, and int against new
dynamic allocations. On Linux, unique-buffer allocation follows deliberate
symlinks at the service-selected application state root and verifies the opened
target again before publishing. Managed buffers and type directories still
reject symlinks, and leaf reservations never follow or replace existing entries.
Existing dynamic ruby: and int: buffers remain readable at their original
names and paths; no migration or alias shadows them.
Command capture publication never replaces an existing file. A name collision
preserves that file and reports a persistence failure rather than pointing to
unrelated content. builtins.buffer_cache applies its existing age-based cleanup
to all three namespaces, including legacy dynamic entries. It does not treat a
namespace reservation as an exemption from cleanup.
The optional interpreter argument defaults to bash. At startup the provider
checks for Bash on PATH and advertises it only when found. If Bash is missing,
omitting interpreter or explicitly selecting bash returns an unavailable
error; choose an advertised interpreter explicitly instead. Availability is a
startup snapshot, so later changes to PATH can still affect execution. With
interpreter set to internal, command accepts only reap <task-id> or reap-all. Read
meta:tasks/current with buffer to find active tasks for the invoking leaf.
The command-tasks skill explains task inspection and these controls to agents.
Controls do not run a shell or worker, cannot address arbitrary PIDs or tasks on
other leaves, and accept background and parallel only when explicitly false;
other tool arguments are rejected. Reaping the invoking task may
prevent its final result from being delivered. Use interpreter: ruby for Ruby
source when the bundled launcher is available at startup. The tool description
and interpreter help advertise Ruby only when its executable and worker pool are
available; workers start lazily and can still fail to launch at execution time.
The dispatcher derives routing and help from the same available interpreter list.
The tool description and interpreter help lead with Ruby when available,
explaining general execution, file I/O, subprocesses, tool calls, per-leaf state,
and direct text, JSON, and media results. Models are directed to select an
interpreter explicitly; the omitted-argument Bash fallback is unchanged.
Description, examples, and interpreter order come from the dispatcher's available
interpreter list. Without Ruby, only the available shell and internal controls
are described; without either execution interpreter, only internal controls remain.
The generated managed-Ruby prompt hint uses that same startup capability snapshot
and directs agents to pass ad hoc Ruby source directly, using another language
when explicitly requested or when bundled Ruby lacks a required library.
Standalone wrapper guidance lives in the Ruby skill, alongside managed helper
details and standalone API connections.
Unavailable interpreters are rejected rather than run as Bash. Bash, Ruby, and
their subprocesses are not sandboxed by the audit.
Bash and Ruby share option parsing and working-directory validation. command
must be a nonempty string; background must be boolean, while a non-boolean
parallel is ignored. A missing, empty, or non-string timeout defaults to ten
minutes. Duration strings at or below zero disable the timeout (including bare
0); other bare numbers report a missing unit. tail_lines accepts a JSON
number, truncated to an integer, or an integer string; unsupported values use
the default and the result is clamped to 0–5000. Internal controls have their
own more restrictive grammar above. Both interpreters validate background task
IDs before allocation; Ruby does so before parallel acknowledgement and Bash
after it. Background registration checks the ID again defensively.
For both interpreters, background ownership is registered with the daemon before the initial task and buffer references are returned. Completion waits for that initial result, even if execution finishes during registration; cancellation or a failed handoff stops the task instead of announcing completion.
Command preflight
Bash and Ruby validate the call before starting a process, acquiring a Ruby
worker, or handing off a background job. Plan's safer_bash audit checks for
filesystem writes, using Ruby-specific rules for Ruby source. A Plan rejection
is final. No approval can override it.
With Workspace approvals, the
working directory uses the same written-or-resolved scope rule as file tools.
An exact foreground pwd in the workspace or designated EzAgent cache can run
without an audit when there are no user audit instructions. A working directory
outside every allowed root in both spellings asks directly.
A plain Bash subagent launch skips both the remembered-grant lookup and the
workspace audit, including when run in the background. Use $AGENTCLI,
"$AGENTCLI", or the client path it names, with -p and a quoted prompt or
"$(cat <file>)". The launch may use -s/--leaf, --model, --thinking,
--mode, --tools, --plugins, --no-parent, and --cwd. It may start with
one cd <directory> &&. The cd and --cwd directories and the prompt file
must be in scope under the same path rule as file tools. Other forms, including
connection selectors, redirects and additional shell commands, follow normal
preflight: check for an exact remembered grant, then let the workspace audit
decide whether to ask.
The workspace audit uses the same temporary, tool-free and plugin-free worker
as the Plan audit, but asks about the command's effects and where they occur.
When both audits need the model, execution_safety.plan_audit: combined
uses one call by default. The worker returns independent writes and ask
verdicts. Choose separate to run Plan first and the workspace audit second
if Plan allows the call. If the workspace side needs no model, Plan runs its
usual audit alone. In combined mode the model-free workspace checks, including
a read-only remembered-grant lookup, can run before Plan's verdict. They do
not ask the user or admit the command until Plan allows it.
User audit instructions apply only to Bash and Ruby evaluations. The worker gets the call as JSON data, not the calling conversation. The audit trusts ordinary development work, including the project's own scripts, builds, and tests, local servers and localhost requests, and ordinary downloads. It asks before a call deletes or changes files outside allowed locations, reads files outside those locations, especially credentials, or sends local data to another machine. It also asks about tunnels, proxies, or relays to outside hosts. Configured audit instructions take precedence for the targets and operations they cover.
If a standalone workspace audit fails, times out, or cannot return a usable verdict, it asks. A combined audit failure, timeout, abort, or unusable answer rejects the call as a Plan audit failure. It never retries as two audits. A call that needs approval waits for a daemon grant until you answer in the Inbox or stop the run. A rejection, cancellation or RPC failure runs nothing. Each command call is checked independently, including Bash and Ruby calls made by Ruby code. This is a best-effort check, not a sandbox. YOLO skips workspace preflight after policy lookup and does not change the Plan check.
A failed policy lookup, an undecodable config, or an invalid approvals or
plan_audit value asks for approval. Other config errors do not change the
policy.
Before checking remembered grants or consulting the workspace auditor, Bash
and Ruby look for literal protected paths that a visible write would change.
Each shell statement is read on its own: redirect targets, the last operand of
cp, ln, and install, and the operands of mv, tee, rm, truncate,
and sed -i count. In Ruby, the literal path arguments of File.write,
File.rename, File.delete, FileUtils calls, and a write-mode open count.
A match asks directly, with only Allow once and Cancel. Reads such as
cp AGENTS.md backup.md, other mentions, and paths assembled at runtime follow
normal command preflight.
Ruby foreground timeout includes worker acquisition after preflight. Ruby background timeout starts after acquisition and local background registration, before daemon handoff. Bash's timeout begins after process startup, as described below.
After preflight, a Bash-local FIFO gate serializes descriptor allocation and process startup only. Command execution, abort control, and output draining remain independent. Queued work holds no capture file, pipe, or subprocess, and waits at most five seconds for descriptor capacity. All pre-start resource retries share that original deadline. Bash checks capacity once more at expiry when it can immediately own the gate, then returns an explicit resource error if capacity is still unavailable. The command timeout starts after successful process startup, not during admission or audit. A command is never retried after a successful start.
Admission refreshes the OS soft RLIMIT_NOFILE and counts existing builtin
process descriptors by number, without reading their contents or resolving their
targets. It never raises the limit. The Go 1.25 Linux startup path needs a normal
peak of nine additional descriptors: one capture file, four for two pipe pairs,
one for nil stdin's /dev/null, two for the fork/exec status pipe, and one
possible pidfd. The first-use pidfd support check peaks at eight instead. The
count probe uses one temporary descriptor, excludes itself, and closes before
allocation. Go's runtime poller is initialized before admission and counted as
existing descriptors. Non-Linux Unix accounting uses its eight-descriptor exec
path and /dev/fd; the reduced-limit regression runs on Linux. These are
startup allocation counts, not universal workload weights or capacity margins.
Bash wakes admission on its own descriptor releases and uses its shared reporting opportunity to notice releases by unrelated operations. Other builtin file operations are not brokered. They can race admission, so actual open/start failures still unwind partial allocations and are reported truthfully. The limit protects descriptor capacity only; CPU, memory, disk load, and child workload policy remain the operator's responsibility.
If the state-directory capture path fails for a non-descriptor reason, Bash falls back to a temporary capture and still executes the command. Its result includes the bounded output preview and warns that full output could not be retained. Descriptor exhaustion instead stays in the bounded admission retry; it is not hidden by the temporary-file fallback.
Direct blocking stdout/stderr readers retain full raw output and a bounded, projected preview. A capture-write lock orders merged streams; a separate preview lock lets status snapshots proceed while disk writes block. One Bash-local reporter scans running references on a shared two-second ticker, checks revisions before copying previews, and publishes visible changes or refreshed targets. Registration publishes the new command promptly without scanning other commands or resetting the ticker. Each tick also wakes FD admission and sends heartbeats to all running pending tool calls, including silent ones. The first post-start heartbeat arrives on the next shared tick, normally within two seconds, well inside the ten-minute watchdog. Staggered starts add no periodic wakes or per-call deadlines.
The same ticker schedules at most one target check per active leaf. Each check runs outside the shared reporter with a shutdown-cancellable context and the client's renewable RPC handling, so a blocked leaf cannot delay another leaf's previews or heartbeats. A current progress snapshot supplies sent authority; otherwise the check selects the latest sent turn from current-branch history, not a draft or ready tip. Live commands on running, background, or idle leaves refresh missing rows and follow sent-turn changes without clearing first. The daemon's old-turn expiry remains unchanged. If a call has no source turn, the reporter uses this sent target without changing the call's source or correlation ID. It sends no progress until a sent target is available, and resumes reporting if one becomes available while the command is still running.
A background handoff stops tool watchdog heartbeats before sending the initial result, but keeps the process's preview until terminal cleanup. Handoff also requests a target check without waiting for the next tick. If the completion report cannot be persisted, the existing completion steer includes the error without referring to a nonexistent report buffer. Cancelled work does not send that completion in place of the abort record. Terminal cleanup orders an explicit clear of the latest reported target before the foreground result or background completion, so an in-flight scan cannot enqueue an update after the clear. Generic progress ingestion uses the existing positive report iteration to reject older updates for the same owner, leaf, turn, and update ID, even after a clear. This ordering is local to progress state; receiver callbacks remain non-FIFO, and independent IDs do not share an iteration cutoff. Shutdown stops and joins the reporter, target checks, and tracked executions. Public abort sends cooperative SIGTERM to the top-level shell; timeout and provider shutdown kill its process group. A blocked filesystem may still stall that command's capture cleanup.
Session metadata lookup
meta:session/current and meta:session/<leaf-id> read ordinary leaf properties
before requesting a model catalog. A positive model_max_context is reused only
when model_info_ref matches the selected reference and model_info_model
matches its resolved route in the destination's effective config. This config
lookup opens no remote connection. A default-source change or new local override
can change the route without changing the short reference; such a mismatch uses
the model-list lookup instead of the previous route's maximum. Missing or
unavailable route information also falls back to model discovery. Matching idle
and unloaded leaves still avoid discovery. Context-token occupancy comes from
leaf stats; the output format is unchanged.
System prompt
The builtin uses its existing daemon effective-config lookup to add a note after
mode guidance when execution_safety.approvals is workspace. It fills in the
resolved workspace root and the prepared file cache used by the approval gate.
The root can differ from the prompt's cwd line when the workspace was opened
through a symlink. The gate accepts both spellings. Without a workspace path,
the builtin omits the note. If the cache is unavailable, the note lists only
the project and private scratch.
Workspace approvals are active. Ordinary builtin file operations inside the project (<workspace root>), the EzAgent cache (<cache dir>), and a private scratch directory you create under /tmp with
mktemp -dproceed without a prompt; Bash and Ruby commands there are checked first and normally proceed if their effects stay in scope. Expect an approval prompt for work outside those locations, for sending local data to another machine (an upload or agit push, for example), or for edits to the project's config, instruction, or loaded skill instruction files or to the user config. Stay inside those locations unless the user asked for something outside them or the task needs it. A declined call did not run: do not repeat it unchanged; continue with what is in scope or tell the user what you need.
The note is guidance for the agent, not an exact description of when a prompt appears. See the known limits.
YOLO, an absent setting, a lookup failure, undecodable config, or an invalid
approval setting adds no Workspace approvals note and does not change existing
prompt error handling. When the builtin runs in Bubblewrap, it adds a separate
sandbox note under either approval policy, after the Workspace approvals note
if present. The note says that an approval does not change which projects
are visible and tells the agent to report when it needs a file outside the
sandbox. In offline, the note says the network is loopback only and tells
the agent to report when it needs an outside host instead of trying to reach
it. In private-localhost, it says outside hosts are reachable but localhost
belongs to the sandbox. In both modes it mentions previewing a sandbox server
through an ez-agent://tunnel/localport/PORT link if client port forwarding
is available. In normal, it says network access is not restricted. If the
mode is unknown, the note describes only project visibility.
With Bubblewrap off, there is no sandbox note. Tool-free audit workers use
their own prompts.
The notes are written when a session's system prompt is generated, so a session resumed after the settings change keeps its earlier note.
Skills and embedded resources
A bundled skill is one immediate skills/<name>/ package with valid frontmatter.
Physical project/configured roots take precedence; a malformed higher-precedence
package blocks fallback for that name. unlisted hides catalog presentation;
disable-model-invocation also blocks the short skill:<name> alias but not
known concrete package resources.
Explicit skill/file mention syntax and completion rules are implemented together
in the skills plugin, completion/macro_complete_skills.go, and TUI completion
tests. Do not duplicate their parser grammar here. requires-ruby: true and
requires-tunnel: true omit a skill unless the corresponding ez-agent-ruby
or ez-agent-tunnel executable is beside the physical builtin executable.
These checks do not search PATH or execute the candidate. Requirements combine,
so a skill declaring both needs both binaries. Missing requirements exclude the
skill from discovery, catalog, completion, resolution and attachment by name.
Embedded resources are read-only
embed:skills/... identities, not writable filesystem paths.
The builtin derives its cache from the acknowledged state directory, checks
non-following paths, and has no fallback. Cache failure disables only features
that require it. Workflow skill design belongs to the
Workflow skill note. The embedded
client-port-forwarding skill requires the tunnel binary and explains how to
offer a client-handled local port link; the TUI's behavior is documented in the
tunnel guide.
Compaction and minify
Automatic compaction is an on_preplugin macro over the held draft. It selects a
retained suffix, summarizes earlier eligible history on temporary work, creates
one virtual-root boundary, and reparents the held draft once. Manual compact and
minify remain distinct operations. Service-owned error turns are excluded from
rebuilt model context but remain durable source history.
The summary copy keeps the worker's answer and omits its readable thinking, regardless of provider. The worker's original turn and readable thinking in the retained suffix are unchanged. Copied turns keep their saved producer identity, but compaction does not copy provider-native captures onto the new turn IDs.
Compaction metadata is the optional JSON object continuation plus inclusive
pivot_turn_id on the boundary only. The daemon's virtual-root contract owns
storage/validation; pkg/service/agent
owns final mutation safety.
Manual minify registers a per-leaf operation so automatic compaction returns
HOLD until it finishes. It admits only idle/unloaded leaves, captures one
source tip, and holds its registration through the final mutation. Other leaves
remain independent. This coordinates builtin operations, not arbitrary external
history writers, and leaves no persistent marker after process exit.
builtin.auto_title, builtin.minify, and manual builtin.compact return the
successful text result NoOp when the leaf has no replayable conversation turns.
Virtual-root boundaries and service-owned error turns alone do not count as
conversation. The macro handlers apply this rule equally to ordinary permanent
leaves and temporary draft helpers, without model requests, worker creation,
metadata changes, or virtual-root creation. Invalid minify arguments and failed
history reads still report errors. Nonempty histories retain their normal
operation requirements, including manual compact's ordinary-leaf restriction.
Automatic compaction keeps its held-draft HOLD/ready lifecycle, and auto-title
worker callbacks, including legacy query-state dispatch, keep their completion
and failure handling.
One-shot temporary workers
Compaction summaries, auto-title requests, and safer-Bash audits are tool-free one-shot workers. Disabling tools does not prevent an inherited macro or generic provider owner from keeping a worker in background. Each operation installs separate idle, background, and error callbacks. Background claims failure and aborts the worker; safer-Bash rejects the command before allocating capture resources or starting a process. Model-error callbacks preserve the original error without adding an explicit abort turn.
Idle completion consumes only a nonempty sent assistant response with a successful
stop_reason: "stop" and the daemon's exit_message: "SUCCESS" outcome marker.
Title completion also checks the title request and response relationship. Audits
require the response to appear in the worker's history and directly follow its
sent user request. That request must match the exact command-audit prompt held by
the pending caller. Audits also validate the JSON answer. Internal macros are
explicitly callable, so a caller-provided response ID alone is not proof that the
answer belongs to an audit.
The daemon supplies the finishing run's frozen tip as the callback parameter. Workers use that response rather than requiring a later live-state
query to return idle, since admission release can still overlap the callback.
Each worker outcome is claimed once. Claiming compaction completion does not
release the parent's HOLD: parent polls continue holding while finalization is
in progress, and cannot stop or delete the summary worker. Completion is marked
finished only after finalization bookkeeping and the macro response. Idle after
rejection cannot consume an abort, partial answer, or later successful-looking
response.
Auto-title requests {"title":"Docker build optimization"}, aiming for roughly
30 characters. Shared JSON extraction tolerates response
wrappers; title validation requires exactly one nonblank string field named
title, rejecting duplicate or unknown fields. Whitespace is normalized and
titles are capped at 80 Unicode code points. Invalid responses leave the existing
session name unchanged.
An owned generation failure, including a sent error turn from a no-output
provider failure, or invalid title response gets one corrective request, at most
two model attempts per trigger. Error-turn content is never interpreted as a
title. The corrective attempt forks a new tool-free
temporary leaf at the frozen response, so the old callback's admission reservation
cannot block it and permanent worker claims remain one-shot. Background outcomes,
setup/request failures, unverified request/response ownership and metadata-write
failures do not cause corrective requests. Legacy workers without an attempt
marker do not retry. Per-parent locking and builtin.auto_title.active_worker
ownership prevent an older callback from writing a title or clearing a newer
run's throttle. Superseded background/error outcomes still fail their own worker
once, without changing the current parent operation or notifying it of failure.
Only background outcomes add an abort. Failed attempts retain their temporary
leaves for inspection. An admitted corrective attempt suppresses the first
attempt's parent error notification; terminal failure still reports an error.
Terminal failure releases that run's pending timestamp and ownership marker so
the next normal trigger can try again, leaving the existing session name and
parent title state unchanged. Only a successful parent metadata write marks the
title set. The five-minute throttle still applies while a request is pending.
Failure releases compaction's parent HOLD and clears progress, including prompt
admission and monitor failures. Successful titles and all finished
compaction/audit workers schedule deletion after the macro response.
Cleanup uses a five-second context and at most eight busy-leaf retries; exhausted
or non-busy failures are logged rather than silently discarded. The provider joins
these cleanup owners during shutdown. Audit timeout or caller cancellation also
aborts and collects the worker under a fresh bounded context, not the cancelled
caller context. Ordinary source and parent leaves may remain in background.
The registry binds failure names to each worker's dispatcher and keeps them
internal. The failure names are builtin.compact-background,
builtin.compact-error, builtin.auto_title_background,
builtin.auto_title_error, builtin.safer_bash_audit_background, and
builtin.safer_bash_audit_error. These distinct names select failure policy
without adding a trigger-type field to macro calls.
First-run authentication template
With Bubblewrap off, the builtin creates a protected commented auth.yaml
template when absent. With Bubblewrap on, it skips this initialization.
The initializer does not read or replace existing credentials. Subscription
setup instructions direct users to create an openai_oauth provider without a
base_url and use Continue with ChatGPT in the configurator. The template
does not teach flat legacy OAuth token records or hand-authored SIWC tokens.
Account/registration storage belongs to the protected configurator workflow.
See subscription configuration.
How does the mode plugin classify user turns?
mode_user_tag emits one leading <mode ... /> text tag. Its mode and
turn-type attributes are independently optional; no tag is added when both
are absent. It fills missing attributes in an existing leading tag rather than
prefixing a second tag. Optional PendingTurn.steer supplies turn-type="steer"
for input drafted during the preceding assistant response or tool call. A bash
completion tag or background bash metadata keeps turn-type="bash", even when
admitted through steer. Neither classification changes the applicable mode.
Background bash completion user turns use the internal free-form
advanced.other_meta object text
{"background_bash":{"task_id":"<trusted originating tool-call ID>"}}.
Merge this marker into existing metadata; preserve unrelated keys and nested
extensions. The TUI reads this metadata for background → command (<id>)
tool-result presentation, while storage still records an ordinary user turn.
This format is established independently of background command execution.
Background bash
run-cmd defaults to background: false. parallel remains a scheduling hint;
only background: true detaches execution. Bash starts the process, registers
its trusted daemon tool-call ID through background_task_add, and awaits the
acknowledgement before returning exactly these references:
| 1 | id: <id> |
| 2 | state_buffer: meta:bash-<id>/state |
| 3 | output_buffer: bash:<id> |
The existing controller still owns timeout, signals, process groups, merged
capture, and output draining. Its detached lifetime survives handler and pending
call retirement. Background uses the same ten-minute default timeout. Set
timeout: "0s" for an intentionally long build or service; there is no additional
background cap. Shutdown cancels and joins detached owners.
bash:<id> is readable live and retained after completion, even for empty output
and tail_lines: 0. Buffer-cache cleanup covers these captures. Foreground
preview and retention behavior is unchanged. Read-only meta:bash-<id>/state
shows lifecycle, historical parent/process-group IDs, elapsed time, timeout,
recent output, and the observed terminal outcome. Status is transient and may
be collected after the calling leaf unloads; output retention is independent.
Completion closes capture and publishes a tmp: report containing outcome,
duration, buffer references, and the last five output lines. The completion user
turn includes the same preview independently of tail_lines, including when it
is zero. The normal Bash preview byte budget still bounds unusually long lines;
the retained output buffer contains the rest. It sends a small user steer to the original leaf,
with background_bash.task_id inside advanced.other_meta and a leading bash
type tag. The leaf's processing-time model and mode apply. There is no second
tool result. An internal daemon admission barrier prevents fast completion from
overtaking the initial result. Ownership remains until completion is admitted,
or abort makes it inapplicable. The builtin retires local command control and
reaps the held Bash leader before requesting ownership removal. Known
terminalization and stale-parent rejections retry after refreshing statistics;
each RPC retains its five-second budget. A held terminal trigger does not impose
a completion deadline. Statistics failures and uncertain steer admission invoke
the provider's connection-failure path rather than silently dropping completion
or risking duplicate admission.
Abort uses the existing cooperative shell signal, records cancellation requested and known bash references in the existing abort turn, and does not send a completion steer or invoke the model. Cancellation remains sticky after idle. Deletion cancels and drops completion while retaining output. The state buffer can still show the actual terminal outcome after abort on a loaded leaf. Compaction appends active bash IDs, commands and buffer references from the live provider registry to its synthetic continuation turn, without a bash turn type.
Authority and tests
Protocol types: pkg/protocol,
pkg/ezagentapi. Routing/lifecycle:
pkg/service/{registry,ipc,server}.go. Focused Go tests and Python builtin,
macro, completion, minify, and background suites own executable detail; see
tests.
Builtin RPC execution defaults do not impose absolute reply deadlines on healthy heartbeating requests. Explicit caller contexts and intentional cleanup bounds remain authoritative. The Go API owns automatic tool/plugin/macro and RPC heartbeats, independently of builtin business logic and existing Bash stop/kill.