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.

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

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.

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 Bash admit and report commands?

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 has a one-second RPC budget and runs outside the shared reporter, 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. While the leaf is running or background, live commands refresh missing rows and follow sent-turn changes without clearing first. The daemon's old-turn expiry remains unchanged.

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. 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 resolves only the sibling physical Ruby launcher. 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.

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 → bash (<id>) tool-result presentation, while storage still records an ordinary user turn. This format is established independently of background command execution.

Background bash

bash 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/deletion makes it inapplicable, then removal is acknowledged. 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.