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

NeedType
Model-invoked operation with one terminal resultTool
Transformation of pending conversation turnsPlugin
User/trigger logic returning textMacro
Separately distributed providerExternal addon

Assembly and routing

text
1builtin catalog + handlers
2 -> one stdio capability provider
3 -> daemon capability registry
4 -> model tool calls, plugin pipeline, macro triggers
5
6embedded 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:

  1. Implement and test it in the matching builtin subpackage.
  2. Add metadata and dispatch in main.go.
  3. Add provider routing in builtin.yaml.
  4. Add default activation or trigger routing only when intended.
  5. 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.

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.

OperationRequest fields besides operationSuccessful response fields besides ok
getkeyvalue, revision, key_revision
setkey, value, optional if_key_revisionrevision, key_revision
deletekey, optional if_key_revisiondeleted, revision, key_revision
wait for any revisiontarget: "any", after_revision, optional timeout_msoutcome, and revision when changed
wait for a key revisiontarget: "key", key, after_key_revision, optional timeout_msoutcome, and key_revision when changed
prepare_waitname, optional timeout_mshandle
wait for a notificationhandleoutcome
cancel_waithandlenone
notifynamenone

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; there can be at most 256 keys, and the entire encoded document is limited to 131,072 bytes. Reads touch each key's independent LRU position. A set evicts the least recently used other keys as needed to fit; if its 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.

CodeCondition
invalid_inputInvalid JSON, operation, key, name, wait target, or timeout
state_not_foundget on an absent data file
key_not_foundget on an initialized document without the key
revision_conflictif_key_revision does not match the current key revision
state_too_largeA value or resulting document cannot fit within the limits
identity_mismatchA registration, managed path, file type, or file identity fails verification
state_corruptSuccessfully read data was malformed or outside document limits and was reset
io_failureRegistration or file I/O failed, including an uncertain post-replacement sync
wait_limitPer-owner or global wait capacity is exhausted
wait_in_useAnother collector is already waiting on the handle
wait_unavailablePlatform 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 bash: 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:index lists every endpoint name; the tool description names the common ones. Unknown or malformed names fail with an instruction: read meta:index, retry with a listed name, and read skill:reflection for the details behind session, model, or mode metadata. File and service failures retain their own diagnostics.
  • 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_file has 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 to fileedit/patch_parse.go, tool_write_file.go, and tests.
  • Internal macro metadata hides general TUI selection and suggestions without changing discovery, attachment, or explicit invocation.

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, preview and bash: buffer machinery. result(value) appends a labeled JSON value to that output. 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 builtin service reads ruby_max_workers from builtin_plugin.yaml, defaulting to four workers per leaf. It 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. In safer_bash mode, Ruby source receives a Ruby-specific audit before worker acquisition or capture allocation.

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. The bash: output and meta:bash- state names and background_bash completion correlation are legacy identifiers; the state and completion text identify Ruby. 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.

builtin_plugin.yaml still loads and normalizes max_parallel for compatibility, with the existing default of 64. The setting is now 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. 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 generated managed-Ruby prompt hint uses that startup capability snapshot; standalone wrapper guidance separately checks launcher availability and requires an installed shell interpreter. The Ruby skill teaches managed tool composition and links to its helper reference, separate from 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.

Both interpreters validate and audit before allocating execution resources. Ruby foreground timeout includes worker acquisition after the audit; Ruby background timeout starts after acquisition and local background registration, before daemon handoff. Bash's timeout begins after process startup, as described below.

Bash validates arguments and the working directory, then runs any safer-Bash audit before allocating a capture file or pipes. 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.

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 TUI-reviewed local port link; its 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.

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

The builtin creates only a protected commented auth.yaml template when absent; existing credentials are never read or replaced by this initializer. 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:

text
1id: <id>
2state_buffer: meta:bash-<id>/state
3output_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.