docs/pkg/service/agent.md
pkg/service/agent
Purpose. This package is the process-local coordinator for one session leaf. It admits work, owns its run queue and model-cycle clock, publishes streaming progress, and cleans up terminal runs.
Wrong page?
- Daemon/socket command routing: service
- Durable turns, context, and SQLite: session
- Model/provider configuration: config
- Frame types and wire/API details: protocol, JSONL API
- Tool, plugin, and macro implementations: tools, the builtin
What does an agent own?
| Role | Primary source |
|---|---|
| Leaf state, execution ownership, and safe tip mutation | agent.go, agent_execution.go, agent_lifecycle.go |
| Prompt/steer/abort admission and queue clock | agent_run.go |
| Pre-plugin gate and pending-set release | preplugin_gate.go, pending_set*.go |
| Model cycle and terminal transition | agent_cycle.go, loop.go |
| Model-facing projection (attachments and turn IDs) | convert.go |
| Tool, plugin, macro, and provider boundaries | agent_tools.go, pipeline.go, provider*.go |
Agent delegates durable roots, leaves, turns, and context to pkg/service/session; injected callers perform external tool, plugin, and macro work. The server creates/resumes agents and translates client requests; it also owns subscriptions and event routing.
Provider host exports
ProviderExports is a daemon-lifetime provider owner in this package, separate
from leaf execution. It automatically publishes one internal macro per eligible
local provider and owns host request admission, upstream HTTP/WebSocket policy,
and withdrawal cancellation. The service supplies config snapshots and exact
caller connection identities. See provider-owned exports
for the macro payloads, catalog validation and per-type policies. External
exports launch one host bridge per execution stream, validate protocol-1 hello
and model admission, and join child cleanup when the stream retires. The local
Agent keeps tools, context finalization, result storage and the same protocol
client used for local external processes. The resident Agent holds a client and a separate close/wait lifetime, supplied
by either a child or a remote stream. Successful executions leave that runtime
parked for compatible subsequent executions; completion callbacks and
cancellation remain bound to the active execution. Failures, history rewrites,
rewind, identity changes and shutdown retire it. Remote construction never resolves consumer bridge credentials or
imposes a shorter startup deadline than the host. Stopped clients and clients
bound to an older destination connection are not reused. A subsequent step
opens a fresh bridge with replacement context; this does not replay a failed
active request.
Remote consumer routing
provider_remote.go owns RemoteProviders, shared by the service's Agents.
Construction is lazy. The service publishes user config on startup and config/auth
reload, and closes the owner at shutdown. Destination changes cancel and join
their streams. Published descriptors are authoritative, so an older run config
cannot reopen a removed or replaced destination. Project-localized configs and
credential-only reloads keep saved model selections separate from availability.
Aliases may share a destination connection and SSH forward; retiring one alias
closes its own streams without cancelling another alias's active work.
Config.ConfiguredModelRoute selects one route for dispatch and metadata lookup.
An exact local provider/model entry wins. Otherwise a configured default remote
source serves ordinary provider/model refs, even when a same-name local provider
exists. Explicit source/provider/model refs bypass that default and all local
overrides. No source requires a saved model list for explicit references. Saved
entries are browser favorites, and changing the default source does not invalidate
explicit refs. Missing models, unavailable sources, and local adapter failures
never cause failover.
Resolve(ctx, cfg, ref) resolves the configured remote route, discovers the exact
provider macro, validates IFO and the bounded LIST catalog, and returns a
RemoteProviderRoute. llmCycle.resolveModel does this before local endpoint
validation and adapter dispatch. Saved refs and assistant identities retain the
selected form, either provider/model or explicit source/provider/model, while
the adapter receives the host's model ID and literal alias target. Further
slashes within that ID are preserved.
Remote construction branches before consumer key, environment, OAuth, or subscription-admission lookup. The existing Responses, Chat Completions, Anthropic, Ollama and Wafer builders and stream parsers use a per-provider client over the tunnel, never a replacement package-global client. Subscription request semantics remain on the Responses adapter; admission, token refresh, identity, and authorization watching remain on the host. No consumer OAuth session is fabricated. Tools, context construction, sessions, and native persistence stay on the consumer.
HTTP uses one stream per request. Successful WebSocket setup detaches its
lifetime from the handshake context, leaving closure to the local Responses
session or destination retirement. Synthetic endpoint identity includes the
destination alias, descriptor and exported provider, isolating local/remote and
different remote routes. Continuation, reconnect with full context, handshake
fallback, watchdogs, and cooldown remain in ResponsesTransportSession.
WebSocket failures and HTTP fallback emit WARN diagnostics independently of the
incident recorder's budget, correlated with leaf and turn IDs when available.
Failure records identify the stage, attempt, duration, encoded payload size,
image count, and safe error classification, including close codes and system
error numbers when available. DEBUG upload-start records identify full replay
versus continuation before a potentially blocked write. Payload sizes include
encoded image data; image counts describe only the transmitted payload. Error
messages, close reasons, credentials, response IDs, and message contents are
omitted. Extensible provider error-code identifiers are retained when they
contain at most 64 ASCII letters, digits, or underscores; this is metadata
format validation, not secret redaction of arbitrary provider-supplied codes.
Uploads use bounded WebSocket fragments with one response read active during
the write, allowing control frames and early provider rejections to be received.
An early rejection interrupts an unfinished upload and preserves the structured
provider error instead of replacing it with a secondary write failure. The
same reducer recovery policy handles early errors: a missing continuation gets
one full-history replay on a fresh socket if the interrupted upload closed its
connection, while connection-expiry errors retain their reconnect policy. The
reader is joined before retry or connection reuse; no speculative response
content reaches callbacks before the normal reducer consumes it.
Continuation safety is checked against the sanitized request projection, so an
old dangling tool call omitted from that projection does not force full replay
on every turn. Duplicate and empty paired tool IDs still disable continuation.
DEBUG upload progress and completion records distinguish local upload duration
from waiting for the provider after the upload finishes.
Ping/pong traffic resets the active operation's watchdog, and an upstream normal
close reaches the consumer with its close status. Orderly tunnel closure drains
already-written bytes through consumption ACKs for up to two seconds, preserving
the consumer's close reply. Cancellation, authorization withdrawal and broken
transports still abort rather than waiting for an application close handshake.
Discovery caches at most 32 connection catalogs, each with at most 128 providers
and 4 MiB combined LIST data. Individual LIST objects retain their 256 KiB limit.
Successful metadata expires after one minute; errors expire after one second.
Shared discovery has a service/connection-owned ten-second deadline, independent
of any waiting leaf's deadline or abort. Every caller, including the initiator,
waits with its own context. Cancelling a waiter does not fail other leaves or
cache caller-induced unavailability. Shutdown cancels and joins discovery owners;
connection retirement also cancels discovery on that exact connection.
Refresh(ctx, cfg, host) explicitly refreshes inventory and catalogs without
opening INIT or selecting models. CachedModel uses the same configured route
for nonblocking context-budget metadata, including ordinary refs from the default
source. Thinking normalization preserves remote intent until catalog resolution;
access-source metadata never consults a same-name local credential profile for a
remote route. The optional catalog access_source supplies the host's known
label to active run snapshots, including default-source routes. Explicit model
selection and admitted execution save the effective maximum context and access
source in ordinary leaf properties. Discovery and snapshot reads remain
read-only, including during CLI preflight, but discovery publishes the newly
known source to subscribed clients. Valid external-provider observations update the same
record. Idle/unloaded snapshots can use these remembered values without
connecting to the host; absent catalog values do not erase prior information.
See remembered model properties. A refreshed missing provider/model fails not found; connection
failure is unavailable, never deletion or fallback. The service model-list handler
calls Refresh and projects configured refs plus the default source's dynamic
catalog from that request's returned snapshot, so another refresh cannot replace
its metadata mid-projection. Exact local entries keep local capabilities and
selected main/small/audit refs remain visible when unavailable. It uses four destination workers under
one ten-second request budget, canceled on client disconnect. A failed host
refresh marks its saved entries unavailable; a successful refresh missing a
provider/model marks them not-found in the existing model flags. Healthy local
and remote entries still return. No new outer JSONL fields are needed. TUI model
menus and the session editor retain full refs and show these status labels;
opening the draft model menu also fetches current availability. Unknown
capabilities on flagged entries do not erase draft thinking intent; CLI launch
preflight reports the route condition before thinking validation. Pending draft
picker replies are retired when another page or popup takes ownership. The configurator
uses a separate temporary owner for its name-only model checklist, never the
daemon's runtime connection.
How does queued work reach a model boundary?
Configured model aliases retain provider/name throughout model selection and
the response loop. Provider constructors resolve the optional base_model
only for request IDs. OpenAI Responses uses this ID on API-key and subscription
routes, as do the OpenAI-compatible, Anthropic, Wafer, and Ollama adapters.
Anthropic thinking and refusal-fallback policy use the real model ID; aliases
still report their selected name to the response loop, including after a
fallback hop. Entries without base_model keep existing serving-model reporting.
See provider-local aliases for metadata
inheritance and YAML configuration.
- Admission. A prompt reserves an idle leaf, stores a draft, and starts its run. A steer queues during a run; an idle follow-up must name a valid parent. Another prompt on a running leaf is rejected.
- Gate. The generic pre-plugin gate receives the held draft. Macros run by priority; a trimmed, exact
HOLDresponse is a poll condition, errors warn and fail open, and cancellation stops the gate. - Sealing. Releasing the gate seals the current queue prefix. Each source passes through the plugin pipeline, then one aggregate is persisted for the provider call. Steers arriving after sealing wait for a later cycle.
Plugin failures, empty results, and invalid results do not replace already good input. Do not bypass lifecycle serialization for durable mutations: external tip changes use MutateTip, which preserves the held-draft anchor while the callback runs.
Agent.Rewind is the stricter idle-only operation. It shares the lifecycle
lock with prompt admission, resume, close, and other tip mutations; a separate
State() preflight is not sufficient. It rejects running, aborting,
terminalizing, or reserved agents. A replay admission has no new input or held
draft, so it skips pre-plugin macros and the plugin preprocessing pipeline and
calls the provider from retained canonical context. Later tool results and
user input use their ordinary pipelines.
The returned *ReplayRun remains reserved until the service has enqueued
leaf_rewound and leaf_updated; only then does Start launch the normal run
loop. Replay uses the current model/config and clears this Agent's opaque
continuation state; provider-native thinking follows the durable turns. Once provider streaming starts it emits the ordinary
agent, turn, and message events. Every terminal path still emits agent_end and
prompt_completed; setup failures become durable error turns even though no
input was newly sent. The acknowledgement means admission, not generation
success.
Execution ownership and lifetimes
Agent remains resident while idle. It owns accepted queues, conversation state, provider transport sessions, and learned provider capabilities. One activation of its processing loop consumes work across model cycles, retries, and tool continuations. Each model cycle owns its own input and assistant placement.
Activation, retirement, and service-owned background-presence changes persist
the idle-alert lifecycle under Agent.mu.
Prompt and steer admission do not arm or clear Inbox alerts. Clients own that
policy through the leaf metadata API; see session.md.
Provisional reservations and rejected prompts or steers do not create activity
markers. Reservations only defer an existing marker's idle transition, including
across Agent replacement. Accepted input, tool results, replay, and recovered
drafts record real activity; the next fully idle transition consumes any
explicitly armed alert. Alert storage failures are logged without rejecting
already-admitted input.
The service updates background ownership within that same critical section,
then releases its registry lock before storage I/O. This prevents another run
from hiding an idle transition and keeps background work from firing an alert
prematurely. Close leaves activity markers for startup recovery.
Every activation receives a private execution identity before launch. Attached
request generations identify the originating request for terminal routing, not
connection lifetime. Detached work must also be protected from an earlier loop's
delayed cleanup. Detached activations do not increment the public generation.
AbortRun checks attached ownership, generation, and the abort transition
atomically.
leafOperations checks requester liveness before recovery or mutation. Once it
accepts prompt or replay work, later requester disconnects do not cancel the run.
The Agent executes from its daemon-owned shutdown context, so accepted work can
finish with no client connected. This does not change resident Agent lifetime, lazy
recovery, or accepted-steer processing after a prompt append failure.
Subscription authorization shutdown
Subscription authorization readers register before their first protected session
check. BeginClose closes registration and cancels each watcher directly, so a
run-loop defer blocked by unrelated work cannot keep polling credentials.
Initial admission checks reject stale selection before network work.
Shutdown cancels all leaves before
joining their owned credential resolutions and bounded authorization-reader
drains concurrently. It does not join unrelated tools or entire run loops.
An in-progress protected read may outlast the two-second watcher drain bound,
but will not poll again after cancellation. Caller cancellation still cannot
discard an admitted rotating replacement before protected saving.
Entry paths
Preparation reserves clean processing state without launching the loop, changing history, discarding accepted work, or resetting warm resources. Entry paths then perform their distinct admission work:
| Entry | Input and ownership |
|---|---|
| Prompt | Appends a draft and installs its gate with attached requester ownership. Provisional admission retains the previous outcome until the append succeeds. |
| Idle steer | Queues input and starts detached processing. A steer arriving during processing joins the existing activation. |
| Recovery | Starts detached processing for a recoverable draft with its gate skipped once. Recovery without pending input stays idle. |
| Replay | Reconciles the idle database history cut and resident caches, then reserves attached processing without appending input. The service releases it through the publication barrier described above. Reconciliation alone does not activate processing. |
If a prompt append fails after steers were accepted during its reservation, detached processing consumes that queue using the reserved configuration. The requester still receives the append error and does not own that processing. Without accepted steers, the failed reservation retires. Detached tool results use ordinary steer admission without requiring an origin connection; their acknowledgement follows admission.
Retirement and failure guarantees
An activation retires once. Applicable terminal and idle callbacks finish before admission reopens, and steers cannot join during retirement. The idle transition atomically commits ownership cleanup and captures the tip after idle callbacks. Terminal publication uses those captured facts: another activation may start before publication or deferred cleanup returns. The old loop must not install cancellation, claim a terminal outcome, clear cycle state, or retire the new one. External callbacks and publication do not run under the admission mutex.
Accepted work cannot disappear at a processing boundary. Draft-read failures, pending-set release failures, and queue-head persistence failures end the owning activation through error cleanup rather than proceeding to a provider request that omits the input. Abort or Close already selected takes precedence. When appending a new durable error, cleanup rolls back unsent input first so the error's parent remains in canonical history. Existing sent-assistant error markers and translations retain persistence-before-cleanup ordering.
Cancellation during a pre-plugin macro, HOLD poll, or queue operation still
completes a selected public abort exactly once, including rollback, queue/gate
cleanup, and terminal notification. Close is distinct: it permanently cancels
the resident Agent, and reserved or delayed launches cannot reopen it.
BeginClose performs that cancellation without a renewal wait; ordinary Close
then drains owned subscription resolutions. Registration shares the closed-state
lock, so draining cannot race a new registration. Daemon shutdown cancels every
Agent before waiting on any resolution. The wait excludes tools, plugins, and
whole run loops.
Lazy recovery uses ResumeFromDBWithRegistration to accept or reject publication
before launching recovered work. A rejected registration returns with the
lifecycle lock released, so its caller can close the provisional Agent without
deadlocking or submitting a renewal. The existing void-callback resume API is
unchanged.
Streaming and retained resources
Stream snapshots belong to the activation, not the attached request generation.
Detached processing therefore supports accumulated text/reasoning replay for
joining clients and periodic partial-content persistence. Snapshot mutation and
live enqueue share streamEventMu with the service replay barrier. Checkpoints
match both activation and assistant turn; stale cleanup cannot clear a newer
activation's snapshot.
Ordinary retirement clears processing state, not reusable conversation resources.
Rewind invalidates conversation-history caches while retaining warm transport
and learned provider capabilities. The implementation lives in
agent_execution.go, agent_run.go, and agent_lifecycle.go; deterministic
ownership regressions include execution_handoff_test.go.
What happens in a model cycle?
The agent first commits and publishes sent input, creates the streaming assistant turn, and invokes a prepared provider cycle. Providers own transport and provider-specific routing; the agent owns retries, stream publication, continuation, tools, and terminal state. Failure placement uses facts owned by that one cycle (whether this cycle sent input and created a placeholder), never the previous tool-call cycle's assistant/input snapshot. Retryable transport failures may retry only before user-relevant output reaches the provider-neutral turn stream: emitted text, emitted/displayable reasoning, or a complete delivered tool call. The semantic-output bit is sticky even when emitted reasoning later resets. Headers, usage-only events, retries, informational notices, opaque encrypted/signature/redacted-thinking data, incomplete parser fragments, and watchdog phase flags do not set it. An empty success is an error unless context already has a tool result.
Tool calls naming a tool that was not offered are rejected before execution. For the production resolver, each model-visible definition is cached with a private caller bound to the exact provider connection selected during resolution. A cached model cycle captures both under the Agent lock. A missing binding or changed tool owner produces an ordinary tool error. If a daemon-launched configured direct service loses its connection before dispatch, its caller can recover that same service once, verify the offered description and parameter schema under the run's admitted overrides, and bind to the new connection. Unrelated providers and changed service definitions cannot take over the call. Calls already sent are never replayed automatically, including send failures with uncertain delivery. Provider identity is not sent to the model or stored in history.
Tool calls run sequentially unless their handle explicitly permits parallel work; results retain source-call order, re-enter through Steer, and form the next pending set. See tools for capability implementation and the builtin for bundled behavior.
Streaming providers have no absolute generation cutoff. A provider-specific
first-output inactivity window covers connection establishment, headers, and
waiting for text, reasoning, or tool-call information; headers and incoming
body data reset it. First semantic output switches to a rolling stream-idle
window, which every subsequent transport read or keepalive resets. Connection
and TLS setup remain independently bounded. Provider inactivity has a
phase-specific error, while parent/user cancellation retains its original
identity. OpenAI Responses excludes queueing, request encoding, and upload from
its response clock. HTTP arms it at successful WroteRequest; WebSocket arms it
after response.create finishes writing and pauses it again for a resend or HTTP
fallback. An upgrade's header wait is timed after the handshake request is sent.
These are local transport send boundaries, not proof of upstream model receipt.
Each remote tunnel dial has a separate 30-second setup deadline, which is
disarmed before upload and does not own the connected socket's lifetime.
Parent cancellation still interrupts uploads. Wafer derives its Wafer-ZDR: required
header solely from the selected model record's zdr_supported: true; the
legacy global ZDR default does not participate at runtime.
OpenAI-compatible Chat Completions and OpenAI Responses inference requests send
X_OSS_AGENT_CODE: https://git.cafe/ezterry/ez-agent alongside EzAgent's
User-Agent. This includes API-key and ChatGPT subscription requests over
HTTP/SSE and the Responses WebSocket handshake. The source header is applied
after configured extra headers so they cannot replace it. Other provider
adapters do not add it automatically. It is public project-identification
metadata, not authorization, and does not guarantee that a remote provider or
proxy retains or logs it.
Provider HTTP requests and OpenAI Responses WebSocket handshakes never follow redirects, including credential-free Ollama and OpenAI-compatible requests. This keeps the configured destination authoritative, prevents 307/308 prompt-body replay, and stops standard or configured credential headers from reaching a redirect target. Provider TLS uses Go's ordinary system roots and hostname verification; there is no insecure mode. Connection diagnostics log the destination authority and status but omit configurable URL paths, queries, and fragments.
OpenAI Responses accepts only local function and custom tool definitions,
projected as functions with strict: false so authored optional parameters remain
optional. Hosted tool types are rejected before network I/O, including web search, file
search, Code Interpreter, image generation, native computer use, hosted
MCP/connectors, tool_search, and programmatic_tool_calling. The internal tool
shape has no nested namespace or hosted-tool fields.
Both authentication modes omit background, conversation, max_tool_calls,
metadata, moderation, multi_agent, prompt, prompt_cache_retention,
safety_identifier, temperature, top_logprobs, top_p, truncation, and
user. This is EzAgent's shared minimal policy, not a claim that API-key access
rejects every field. Output-token limits follow the auth-specific policy
described below. Access-program selections apply to both modes.
Both authentication modes use one public Responses encoder. Local tools use
documented additional_tools input items, and system instructions become developer
messages without changing their order or content. Images retain their detail.
Every transport sends store: false. HTTP always sends complete canonical context, including function
calls and outputs, and never sends previous_response_id.
Canonical first-party API-key and subscription routes prefer WebSocket unless
responses.websocket: false explicitly selects HTTP/SSE. Unsupported upgrades
and pre-output connection failures can fall back to HTTP with the same full
history and no-storage policy. The Agent retains full history on every cycle.
Only the same authenticated socket may use connection-local previous_response_id
with a proven strict input extension and unchanged request settings. New sockets,
invalid cache state, branch changes, or changed settings send full context.
WebSocket omits the HTTP-only stream field. A recognized missing-context error
retries once with full context, only before semantic output. A reasoning item ID
without text or encrypted content is a placeholder, not semantic output, and does
not block recovery. A retryable
pre-output provider error clears cached ancestry so the outer retry also resends
full context. Neither path replays after semantic output.
max_output_tokens is sent only for non-subscription requests when
responses.send_max_output_tokens permits it, defaulting to true. Endpoint
overrides do not silently disable it. prompt_cache_key remains independent of
response storage and routes matching prefixes toward warm KV caches. Explicit
responses.prompt_cache_key: false is respected for both authentication modes.
reasoning.context is sent only when configured, never forced. The encoder follows
the public create reference.
OpenAI authentication never falls back between API-key and subscription credentials.
For API-key and subscription models, the model's access_programs mapping is
sent on both HTTP and WebSocket requests. Empty or absent configuration omits
the entire object. Changing a selection invalidates WebSocket continuation
through the request-settings fingerprint. OpenAI owns model eligibility and
access checks; the adapter preserves access-program errors without retrying
under a different program. See configuration for
values and layer semantics.
Response-reported access programs are separate from request selections. The shared
HTTP/SSE and WebSocket event reducer maps response.access_programs.cyber values
daybreak_blue and daybreak_red to friendly Blue and Red response labels.
It captures metadata throughout the stream, including the final response. Later
reported values replace earlier ones; standard and explicit null clear the
label. An omitted field leaves earlier reported metadata unchanged. Unknown
values produce no special label. Pre-output labels from abandoned transport
attempts do not carry into a replacement response. The adapter never infers a
label from the requested alias or access program, and keeps the chosen model
identity unchanged.
The provider-neutral loop carries friendly labels into assistant
other_meta.response_labels alongside archived tool metadata. It retains neither
the raw access-program object nor the raw response. Other providers may supply
friendly labels through the same internal path; no Wafer ZDR label is produced.
See session storage and
TUI badges.
Reasoning summaries remain enabled by default when the selected model allows
them. If OpenAI rejects a summary request because the account, organization, or
model lacks access, the provider sends OpenAI's error message to the leaf as a
warning without rewriting it. Before semantic output, it retries once with only
reasoning.summary omitted. The leaf's process-local OpenAI runtime then omits
summaries for later cycles and runs until the leaf unloads. Loading the leaf
again permits a fresh attempt. A rejection after semantic output still disables
later summaries but does not replay the current response. Other authentication
failures and unrelated unsupported_value errors keep their normal behavior.
An explicit responses.reasoning_summary: false setting skips the probe and
warning.
How is Anthropic thinking configured?
The adapter uses thinking.type: adaptive and output_config.effort for
Claude Opus 4.6 and later, Sonnet 4.6 and later, Haiku 5.5, Fable 5, and
Mythos 5/Preview. Adaptive requests do not send budget_tokens. Older 4.5
models retain thinking.type: enabled with bounded token budgets. Enabled
thinking requests ask for display: summarized so reasoning remains visible.
The known-model effort choices live in pkg/service/config/provider_defaults.yaml.
off omits thinking configuration for older models whose API default is off.
For Opus 5, Sonnet 5, and Haiku 5.5, whose default is on, it explicitly sends
thinking.type: disabled with effort: low. Sonnet 5.5 instead sends
thinking.type: between_tools with effort: low: this stops up-front thinking,
not thinking between tool calls. Opus 5.5, Fable, and Mythos cannot disable
thinking, so their catalog choices exclude off. An old saved off on those
models leaves the API's adaptive default in effect. Disabled thinking requests
do not add thinking block-binding controls or their required beta header.
These mappings follow Anthropic's thinking configuration table and effort levels.
How does Anthropic preserved thinking recover?
Anthropic thinking and redacted_thinking blocks are saved with the assistant
turn that produced them (see session storage)
and loaded with the provider context. Signatures and redacted data are never
added to readable turn fields or public projections. Thinking-enabled requests opt
into Anthropic's binding controls with
prefix_mismatch_behavior: "drop_block", merging the required beta token with
configured anthropic-beta values. Known model- or prefix-binding drops are
logged from the response's input_transformations diagnostics.
For local routes, selection is by native format family and the destination adapter, not provider
name, model, thinking level, credentials, or endpoint URL. An Anthropic Messages
request encodes the anthropic.thinking.v1 batches of the assistant turns in its
context and sends the readable <previous_thoughts> text only for turns without
one; a turn never gets both. OpenAI Responses batches stay stored for later
Responses requests. A rename, key rotation, restart, model alias, or thinking-level
change does not suppress same-family replay; Anthropic validates what it receives.
Remote captures additionally store a non-secret remote_route tag on every
native payload item in the existing JSON column. Replay requires the matching
destination/provider identity. Local routes do not replay tagged remote batches,
and remote routes do not replay untagged local batches. The tag survives restart
and fork but is stripped by the native decoder before any upstream request.
The only capture gates are successful completion and payload integrity: a
response naming a different model (an alias or refusal fallback) is still a
complete capture, and the turn records the model through the ordinary turn path.
If Anthropic rejects the replayed state with a signature/modified-thinking HTTP 400 and the attempt actually submitted native batches, the provider compare-and-deletes exactly the stored rows that attempt submitted (separately per model attempt, in one short transaction) and retries the same turn once with cold reconstructed context, after sending the original error to the leaf as a warning. If the deletion fails, the rejection is returned with a bounded storage error and no retry. Once the deletion commits, those entries are also removed from the request-local selection, so a later generic retry (such as a cold HTTP 429) or refusal-fallback hop in the same request never resends them. A second classified rejection keeps the provider diagnostic and appends advice to switch models and compact before returning to Anthropic. A request that already loaded an earlier snapshot can still submit a batch deleted afterward; its rejection is handled the same way. OpenAI Responses has no dedicated rejection classifier, so generic errors never delete saved batches. Rejected OpenAI batches may fail again on later requests until the user changes context or compacts; there is no native-specific cold retry.
Classified pre-output refusals follow a fallback chain. Each model names one
fallback, and chains form transitively: Opus 5.5 → Opus 5 → Opus 4.8. Sonnet
5.5 falls back to Sonnet 5, while Fable 5.1, Fable 5, and Opus 5 fall back
directly to Opus 4.8. A hop that refuses before any output moves to the next
model. A hop that fails any other way, or refuses after output, is terminal.
Only the terminal hop's done event reaches the loop. Fallback output is stored
under the model actually used.
A successful assistant finalization saves its staged batch in the same transaction (tool-call and stop completions alike). Failed, interrupted, and aborted attempts save no partial native data. Only the new turn's own capture is written; a request never writes its input batches back.
How do terminal and restart paths stay safe?
- Terminal outcomes are exclusive. Normal completion requires no queued steer; errors clean queued and in-flight work.
- A terminal provider error before semantic output atomically changes the sent empty assistant placeholder into a sent service-owned
errorturn without changing its ID or placement. A setup error after input publication but before placeholder creation appends anerrorturn. Partial assistants instead retain their content and receive the normalized error in service-ownedother_meta.exit_message. - Successful durable failure writes publish refreshed canonical
turn_contentand suppress the ordinary leaf-wide error informational, avoiding duplicate live warnings. Persistence failure leaves the listener informational fallback;agent_endand prompt completion still carry the terminal details. - Abort cancels the run, finalizes any streaming assistant turn as interrupted, rolls back unsent turns, and appends the durable
Abortedturn. It does not fire success or error triggers. Retirement selectson_idleonce true quiescence is reached, including after background-only cancellation. - On resume, a reachable accepted held draft is rescheduled with the gate skipped once (
SkipOnce), bypassing pre-plugin macros for that draft. Other incomplete shapes roll back to the last ready/sent chain; process-local gate state is not durable restart state.
How are history mutations coordinated?
Agent.MutateTip serializes tip mutations with the Agent lifecycle. It rejects
aborting work and running work outside the active pre-plugin gate with
ErrLeafBusy. A draft held at that gate remains the
canonical tip and is reparented rather than cloned during virtual-root creation.
Outcome macros may mutate history during terminalization. Idle/background macros
run after execution retirement, outside service gates and Agent mutexes. Their
history changes use ordinary idle-operation admission and are separate from the
finishing run's frozen terminal tip.
After a successful mutation, the Agent invalidates history-dependent provider continuation state and retires any loaded external owner. The next provider call uses the canonical rewritten history through a fresh owner. As with retirement, access evidence reported by the detached owner is cleared, and a run shown as subscription access reverts to unknown until the fresh owner reports. A failed mutation keeps the existing owner and continuation state. This invalidation preserves the active execution, held draft, pre-plugin gate and terminal lifecycle state.
For an unloaded leaf, the service holds the existing per-leaf gate across its
no-Agent check and virtual-root storage mutation. Lazy prompt initialization
uses that same gate, so it cannot accept a draft between those steps. A prompt
whose parent became stale receives the existing turn_conflict response and
must retry. If an Agent already exists, the service releases the leaf gate
before entering Agent.MutateTip to avoid lock-order inversion. Other leaves
remain independent. This coordinates the final mutation, not earlier history
reads or arbitrary external history writers.
Where does compaction fit?
The agent recognizes no compaction-specific protocol or database ledger. Automatic compaction is a bundled pre-plugin macro that returns ordinary HOLD or ready behavior; its run-start anchoring, selection policy, temporary summary work, and transient generic leaf_config metadata belong to the builtin documentation. Completion uses the same held-draft-safe MutateTip/virtual-root boundary; interrupted temporary work is abandoned and cleaned rather than resumed.
Where is behavior authoritative?
Read the role files above with pending_set_test.go, preplugin_gate_test.go, loop_test.go, and lifecycle/abort tests for executable behavior. Durable state transitions live in pkg/service/session/storage.go; command translation and agent lookup live in pkg/service/server.go. Provider transport details live in provider*.go and their tests.
OpenAI subscription routing
openai_oauth profiles select the distinct openai_chatgpt auth mode. Legacy
Codex records remain untouched but are ignored for discovery, renewal, and
inference. No model-name allowlist admits subscription requests. The configurator
owns current account-specific discovery; the daemon consumes configured slugs.
An unknown discovered slug can be selected without a new release.
Preparation calls Config.ResolveSubscriptionAdmission, which owns protected
fresh reads, session-scoped cross-process renewal, and short auth mutation locks.
The admission captures the provider's account-selection generation with its
credentials. Pre-request checks and the active watcher reject any later selection
change, including a switch away and back between polls. Renewal of an unchanged
session preserves admitted work. Canceled renewal still saves validated rotating
tokens before refusing admission. There is no leaf-local refreshed-token cache.
The Agent tracks preparation's credential resolution through validation and
persistence through Agent.ResolveSubscriptionAdmission, so graceful close
cannot abandon its owned rotation. Refresh runs
under the config resolver's bounded independent context after its cancellable
lock wait and cancellation check. This does not recover a lost provider response
or survive a hard process kill.
Usable sign-in requires verified
registration identity, direct-plan and resource scopes, and versioned affirmative
local background authorization. A failure stays on the selected profile. API-key
credentials are independent and never used as fallback. Active inference observes
local withdrawal, replacement, and sign-out and cancels only the affected session.
Subscription admission decides whether a request may run; it does not select
saved encrypted reasoning, which follows the Responses native format.
OpenAI Responses requests (API-key and subscription) replay the stored
openai.responses.reasoning.v1 batch of each assistant turn at that turn in place
of its readable summary, sending only items that carry encrypted content;
Anthropic batches and unusable rows fall back to readable history. Chat
Completions providers gain no encrypted-reasoning support.
Subscription requests use https://api.openai.com/v1/responses, preferring
WebSocket with HTTP/SSE fallback or explicit opt-out. Both auth modes send
store:false, array-form history, developer instructions, and tools through
additional_tools input items. HTTP sends complete history with stream:true;
the same authenticated WebSocket may send incremental follow-ups.
Both auth modes omit HTTP continuation. Subscriptions also omit
max_output_tokens, even if an endpoint override is cleared or the output-token
capability is enabled.
The shared field/tool policy above follows the
subscription preview restrictions.
The WebSocket guide
describes connection-local continuation compatible with store:false and ZDR. The inference bearer belongs
to the selected validated account. Extra headers cannot override it, add a Codex
account identity, or add private endpoint markers. EzAgent
keeps its honest User-Agent.
HTTP, SSE, and WebSocket use shared structured error classification. Only
subscription admission and usage-stop actions differ. Temporary Responses
HTTP/availability failures allow three normal provider invocations, followed by
one final pre-output invocation after a 30-second wait. Responses allows six
outbound requests for the normal invocations, leaving room for socket fallback
and request corrections, and adds three request slots for that final invocation.
The final invocation is not a fresh retry round. Responses has no total
wall-clock recovery cap: an active slow upload, response wait, or cooldown does
not lose its remaining attempt allowance to an absolute deadline. Attempt and
request limits still apply, and exhaustion preserves credentials. Integer HTTP Retry-After
values retain precedence; HTTP-date values keep the existing ignored-date policy.
All provider-directed delays, including duration prose in terminal stream errors,
are clamped to two hours, as is jittered backoff. Before semantic output,
Responses allows 60, 120, and 180 seconds of response inactivity on its three
normal invocations, then 180 seconds on the delayed final invocation. The response
windows use the configured first_output_timeout as their base when overridden,
with multipliers of 1, 2, 3, and 3. The response
wait starts only after the request has been sent, not during connection setup,
queueing, or upload. Response activity resets the inactivity wait. Timeout
notices report the elapsed idle duration, the sent request with no response
activity, the resend attempt, and its next silence allowance. The final timeout
notice also explains the cooldown and final attempt. Successful streams retain
rolling inactivity protection, not an absolute generation cutoff. An SSE EOF or [DONE]
without response.completed uses the same bounded recovery only before semantic
output. After text, reasoning, or tool-call data, it remains a terminal incomplete
stream; partial calls are not executed. Parent cancellation and
no-retry-after-semantic-output remain unchanged. Inactivity timeouts retain
their typed recovery, including the single delayed final invocation, within the
same attempt allowance. Ineligible users, unsupported capabilities
or routes, and invalid permission contexts are terminal. Admission prose such as
{"detail":"..."} is diagnostic, not a stable code. Errors preserve actual HTTP
status, structured code/parameter, and request ID, with credential redaction.
Relevant terminal SSE errors use the same recovery classification. Their accepted
stream's actual HTTP status is retained separately from any status supplied in
the terminal event; a generation failure does not rewrite an HTTP 200 into a
guessed HTTP rejection. Summary-access
rejection retains the existing single retry without reasoning.summary, but
explicit subscription permission-context failures remain terminal.
subscription_sharing_usage_limit_exceeded stops the failed activation and pauses
that registration/session in all activations already admitted in the daemon,
including unprepared siblings, retries, tool follow-ups, and accepted queues.
The ordinary failure path cancels queued steers and rolls back unsent turns;
paused work is never automatically replayed. Pause records live only until their
activation retires. The action is Manage usage at
https://chatgpt.com/settings/usage. Do not infer plan-wide exhaustion or a reset
time. A later idle prompt, idle steer, or explicit replay starts a new activation
and can ask OpenAI again with the existing valid login. Refresh, sign-out, and
daemon restart are not quota controls. A new admission does not resume older
paused work. There is no automatic account rotation or billing fallback.
The existing admission API does not distinguish a human request from an addon
submitting a new request; addons must not use fresh admissions to retry unchanged
quota failures automatically.
Success still requires response.completed; failed, incomplete, interrupted,
or partial streams cannot execute incomplete calls. Cancellation immediately after
successful completion does not replace that success with an error. Cancellation
causes override only failed attempts, including an explicit retry-policy recovery-window expiry.
Admitted inference checks protected authorization immediately and once per second,
without trusting file modification times. Sign-out, withdrawal, replacement, and
protected-read failures cancel affected requests. The unused LeafUpdateRuntime
and LeafStatsRuntime helpers were removed; service projections use the single
LeafRuntime snapshot. OpenAIResponsesProvider.AccountID, its legacy HTTP/WS
header-setting paths, empty run-reset hooks, and the redundant native-cache route
generation wrapper were also removed. Unsafe custom auth headers remain stripped.
OpenAI subscription acceptance
Offline regression tests cover request projections and multi-call assembly, not service acceptance. Before release, complete fresh SIWC browser sign-in and pick a currently discovered model. Never inspect, copy, or paste tokens for the test.
- In a dedicated subscription profile, check WebSocket first,
then explicit
responses.websocket: falseHTTP/SSE with a small harmless prompt and two independent local read-only tools. responses.parallel_tool_callsdefaults totrue. Check that no explicit provider or model override disables it, and use at most one initial request plus one matching-results follow-up for each transport. Temporary failures can use three normal invocations and one delayed final pre-output invocation, subject to the shared attempt and request limits. Stop after an invalid-body rejection.- Check several returned call IDs, interleaved argument assembly, source order,
local results, and a follow-up containing every matching result. A model
choosing one call is inconclusive, not a route-rejection result. Do not use
max_tool_callsto force it. Existing tools execute sequentially unless their own handles permit parallel execution. - Record only sanitized status, exact error code/parameter, and request ID on a
rejection. Set explicit
parallel_tool_calls: falseif compatibility requires it. Do not claim a batching fix merely from the endpoint move. - Check the one-line title and read-only
/usagepage at ordinary and narrow widths, including during an active run. Verify selected-account recognition, local withdrawal cancelling admitted work, and sign-out/revocation behavior.
Offline tests cover paid/subscription payload parity, marker-free requests, prompt-cache opt-out, no-storage policy, and safe socket continuation/recovery. They do not establish live model or account acceptance.
A bounded live public WebSocket trial completed on paid gpt-5.4-nano,
gpt-5.6-luna, and gpt-6-luna, and subscription gpt-6-astra, gpt-6-luna,
gpt-6.1-sol, and gpt-daybreak-blue-latest. Each returned multi-call batches
and completed matching-result follow-ups. Paid and subscription gpt-6-luna
also completed full-history requests after reconnect. The Sol run exercised
pre-output availability retries and full-history recovery after missing context.
Models can make additional tool rounds; exact prompt compliance is separate from
protocol acceptance. Other model/account combinations still need live checks.
Prompt admission's existing agent is running rejection now unwraps to
ErrLeafBusy without changing its public message. Service audit classification
uses that typed cause, not a later Agent state snapshot: a storage append can
fail while another queued activation still leaves the Agent running. That later
state must not hide the storage failure as an expected busy rejection.
Agent.Prompt also validates the parent before reserving an activation. Immediately
before the draft append, it re-reads the durable leaf tip while holding
lifecycleMu and keeps that lock through append and launch. A preliminary
ensureAgent or ValidateAndLock check can become stale after an intervening
completed prompt and cannot authorize the append. Missing follow-up parents and
mismatched parents return turn_conflict without appending input and unwrap to
ErrPromptParentConflict, including through final reservation-failure wrapping.
Service callers can classify that expected rejection without inspecting text. A final
revalidation failure retires the reservation through the existing append-failure
path, preserving detached ownership of any steers accepted during reservation.
Regressions are in prompt_parent_test.go.
Provider classification and bounded temporary recovery
provider_errors.go exposes ClassifyProviderError(error) ProviderErrorCategory.
The fixed internal categories are success, cancelled, deadline, temporary,
exhausted, rejected, protocol, transport, and unexpected. Classification
uses typed causes through errors.Is and errors.As, never error presentation
or provider prose. It does not authorize replay of a prompt, assistant turn, or
tool effect.
RetryableErroris adapter evidence for temporary handling. Chat-compatible HTTP adapters use the existing HTTP 429/5xx policy. Responses also recognizes its existing structured code allowlist and subscription-specific rejection policy. Anthropic HTTP uses 429/5xx; SSE recognizes onlyoverloaded_error,api_error, andrate_limit_error. Chat-compatible SSE recognizes onlyrate_limit_exceeded,server_error, andservice_unavailablecodes. Other explicit SSE error frames are typed rejections, not successful output.- Initial Responses inactivity timeouts retain their existing bounded retry behavior. Other adapters' inactivity timeouts are classified as deadlines but are not newly made retryable. Transport errors, malformed JSON, unknown codes, and premature streams do not acquire transient status from their text.
ProviderRetryExhaustedErrorcontainsAttempts, fixedReasonofattemptsorwindow, andCause.Unwrappreserves the last available typed cause. Public error text includes the attempt count and distinguishes attempt-limit exhaustion from recovery-window expiry without exposing arbitrary reason text. The shared budget retains one latest adapter-local cause, including failures recovered within the current outer invocation. Retained causes have fixed presentation before window or attempt exhaustion joins, without formatting raw diagnostics;Unwrapstill exposes their original typed evidence. Responses exhaustion redacts ordinary presentation without erasing that concrete cause. Nested diagnostic causes can still contain private provider data and must never be formatted into audit records. Exhaustion takes precedence over a nestedRetryableError. Callers must use classification first, not grant another retry layer merely becauseerrors.Asstill finds that diagnostic cause.
By default, RunLoopWithOptions has at most three outer invocations and three
outbound model requests; a provider's attempt-limit policy can tighten that
allowance, disabling both extensions below. Responses otherwise opts into a
larger request allowance of six for adapter-local repairs, plus one final
invocation after exhaustion with three additional request slots. That final invocation waits 30 seconds, or a longer
provider-directed cooldown, and can run only before semantic output. It does not
reset the attempt count or start a new agent
run. Other providers keep the default bounds. Foreign exhaustion and errors
that suppress retries remain terminal.
HTTP requests and WebSocket response.create writes share the context-carried
request counter, including adapter-local thinking/summary/continuation corrections
and existing configured refusal handling. Failed writes count; TCP connection
setup is not a model request. Direct adapter calls outside RunLoop retain their
single-call adapter behavior and do not install this cycle budget. The transient
recovery window defaults to five minutes from the first retryable failure and covers
later waits and attempts. An explicit zero from a provider's retry-window policy
disables that window; a positive override can only shorten the default, and a
negative override is ignored. Responses disables the absolute window and uses
the bounded invocation and request allowances instead. Wrappers with explicit
short positive windows still enforce them, including during cooldowns and active
attempts. Semantic output disarms any absolute timer and stops retrying,
preserving normal rolling streaming inactivity protection. Alternating
timeouts and HTTP failures cannot reset the attempt allowance. Existing model
selection is unchanged; there is no added fallback model or outer replay loop.
Here semantic output means output delivered to the loop. The provider's
AfterOutput flag alone does not veto the supported timeout retry when no text,
reasoning, or complete tool call reached the loop.
ProviderAudit shares the service's process recorder through the optional
EventRouter.ProviderAudit() *ProviderAudit hook. Headless callers may provide
LoopOptions.Audit. Static registered boundary/category sites provide bounded
provenance without dynamic stacks, panic values, exception text, provider bodies,
model names, or native thinking. Healthy execution and ordinary cancellation
remain cold breadcrumbs. Preparation failures, unexpected results, transient
failures, retry decisions, exhaustion, and panic boundaries can create incidents.
The optional observer also follows request contexts into adapters. Fixed sites
record recovered WebSocket connect/write/read/decode failures and local retry
or HTTP transport fallback decisions. Expected summary, thinking, continuation,
and configured refusal corrections use cold breadcrumbs; failed thinking-state
cleanup is an incident. A later incident retains those breadcrumbs, while a
recovered unexpected transport failure retains its failure, decision, and final
successful outcome even when the outer loop only sees success. Adapter sites
receive only validated leaf/turn IDs and the shared numeric attempt count.
Panics are recorded and rethrown unchanged. Audit delivery never decides provider
or durable terminal success. See the incident writer contract.
Fixed persistence sites also record failed input sent-state publication, streaming
assistant append, success exit marker, unsent rollback, abort rollback, and synthetic
ABORT append. These incidents contain only validated leaf/turn IDs, never error
presentation, input, credentials, or model output. Wrapped context.Canceled and
ErrAgentClosed causes are excluded by type; a deadline is still a failure.
Persistence auditing adds no retry. Input publication or streaming append failure
stops before provider execution, and a success-marker failure retains error
completion rather than claiming success. Abort remains best-effort: rollback and
ABORT append fail independently, cleanup still retires the run with one abort
completion, and an incident does not imply either write committed. Private
per-agent fault hooks in persistence_audit_test.go exercise these boundaries
without changing storage schema or the wire API.
Classification limits for recovery owners
Go typed categories are internal only. Existing agent_end, prompt_completed,
error turns, and exit_message do not carry provider retry authorization. Ruby
must not infer it from their terminal reason or diagnostic text. The standalone
Ruby error classification helper
separates transient evidence, explicit retry authorization, and ambiguous
admission. No JSONL fields or durable terminal meanings changed here.
HTTP status policy is coarse: a generic 429 may represent a permanent quota
condition unless that adapter has an explicit structured rejection rule. Unknown
provider extensions and network failures remain fail-closed for retry policy.
Responses redaction and Anthropic's one-shot refusal-fallback failure wrapper
preserve concrete diagnostic causes through Unwrap. Public error presentation
redacts the configured API key; nested causes can still contain private provider
data and must not be formatted into audit records. Previously untyped Responses
wrappers and transient failures from a one-shot Anthropic fallback explicitly
suppress generic retries. A suppressed Responses wrapper also cannot authorize
an adapter-local summary correction. Categories still reflect typed evidence,
including cancellation and timeouts, but a nested RetryableError or Responses
timeout cannot override that suppression. Direct supported Responses timeouts
and typed temporary errors keep their existing retry policy. Exhaustion still
takes precedence over every nested cause. Existing semantic correction detectors
may inspect provider prose, including continuation and preserved-thinking
rejection advice; these are not
new transient classification rules and now consume the same outbound budget.
Existing semantic-disconnect reconciliation is separate Agent policy, not an
extra temporary-provider retry allowance. This change does not implement durable
Workflow recovery or authorize another provider cycle after an error terminal.
Focused regressions live in provider_errors_test.go and
provider_audit_corrections_test.go, with existing provider,
streaming, timeout, and subscription suites covering adapter-specific behavior.
Provider-owned background activity
The daemon keeps generic leaf_id → task_id → provider connection ownership in
memory, independently of pending tool calls. Add/remove are correlated RPCs;
kill is a one-way notification routed by task ID with an informative reason.
The approved frames are documented in the JSONL catalog.
For correlated command tasks, registration preserves the interpreter independently
of the pending call, including unrecognized interpreters. For Bash and Ruby,
leaf-abort records use meta:<interpreter>-<task_id>/state and
<interpreter>:<task_id> references even after the initial tool result retires the
pending call. Generic tasks and unknown interpreters do not receive inferred
buffer references.
Registration loads an existing unloaded leaf and adds ownership under one leaf gate, without model generation. Missing leaves are not recreated. Add, remove, eviction and deletion share the gate; no provider wait holds it. Same-owner add is idempotent, another owner's live ID conflicts, and absent removal is an acknowledged no-op that never loads a leaf. Provider loss releases only that connection's contributions and publishes affected snapshots. For any correlated command task whose non-error initial result entered the Agent queue, loss also admits an ordinary user input reporting an unknown outcome and possible effects, without implying rollback, unless its correlated completion was already admitted. A claimed initial result is settled before that decision; a provisional completion check is not a queue admission. Generic ownership and foreground tool errors do not generate this input. Abort, fatal agent/storage cleanup and shutdown cancel it before admission. A provider invocation or provider-setup failure leaves unadmitted input alive to use the post-retirement tip. A pending admission blocks deletion; a rejected busy delete does not cancel it. Deletion that wins before the handoff suppresses the input. The handoff waits for terminal retirement and uses the current parent tip; it is not replayed after admission or rejection. Invalid configuration can prevent idle activation. Configuration resolution belongs to the pending worker and its reload-lock wait observes cancellation; shutdown joins that worker, so ordinary filesystem work that does not respond to cancellation can delay shutdown. Cleanup joins independent per-leaf workers, so a held leaf gate or lifecycle macro on one leaf cannot delay another leaf's ownership retirement. Lost-provider cleanup still removes task entries if storage already deleted the leaf; error and vacuum cleanup likewise retire owners rather than depending on a live DB leaf.
The service serializes leaf lifecycle selection with those ownership changes.
on_success and on_error remain per-model-run triggers, even when owners remain.
on_background, resolved through active_background_triggers, fires when model
processing has retired with owners remaining, or an idle leaf acquires ownership.
on_idle fires only when execution, queued/in-flight input, terminalization,
pending admission and ownership have all drained. Both use a selected transition,
not every snapshot. Removing the last generic task or losing a provider without
an eligible command loss input can deliver idle without another turn. New leaves and forks persist configured
background trigger defaults alongside idle defaults.
Canonical state is published before the selected lifecycle macro is invoked.
Invocation holds no leaf gate or service/Agent mutex; a macro can reenter its leaf,
and completion admission need not wait for a background macro to return. Per-run
agent_end and requester completion follow the outcome chain. Lifecycle callbacks execute in selection order per leaf, including background
rejection before a later idle callback. A busy callback queues later notifications
without blocking their callers, so a callback can remove ownership or await a
follow-up run without deadlocking. Terminal frames from that follow-up may arrive
before the queued lifecycle callback runs. Without an earlier callback in flight,
a retirement-selected macro chain precedes that run's terminal frames.
Ownership-only or deferred reservation-release transitions add no model terminal
frame. A follower must not treat success or background
as final leaf quiescence.
Agent LeafState stays idle when only background work remains. Existing
snapshots, statistics and listings derive background; running and aborting
retain precedence. Background prevents eviction, not ordinary prompts, steers,
rewinds or configuration edits. Completion admission is covered by ownership
until completion admission precedes removal. Bash retries known terminalization
and stale-tip rejections while retaining ownership; abort and missing-leaf
rejections drop completion. Uncertain admission fails the provider connection
rather than retrying and risking a duplicate.
Pending prompt/steer admissions and initial-result completion waits reserve the
handoff interval. They prevent idle selection and eviction and project running
even before a lazy Agent exists. Reservation release re-evaluates lifecycle state,
so rejection cannot strand a leaf in a false busy or background state. Idle age is
reset when true quiescence begins, not when the model initially stops.
For accepted user-kind steers, the daemon generates boolean
background_progress:true in advanced.other_meta only if the sending connection
still owns background work for that leaf at queue admission. Untrusted claims are
removed from prompts, steers, tool results and virtual-root input. The plugin
pipeline preserves the admitted flag on user-kind descendants but cannot mint it
for ordinary input. Source trust is captured once at pipeline entry and survives
intermediate role changes, such as user to system to user. System-kind output
carries no progress flag, but does not erase the source's trust for a later
user-kind descendant. Unrelated metadata is retained. Stored turn_content.other_meta
carries the flag so Workflow can distinguish owned progress from external steering
without broadening its external-steer admission policy. Bash completion additionally
retains background_bash.task_id, connection/leaf ownership validation, cancellation
checks and the initial tool-result admission barrier. Ordinary ingress and plugin
outputs cannot mint or replace legacy background_bash claims either. Verified
same-root content-reference copies retain the stored source's Bash correlation,
but explicit replacement content cannot inherit it.
Ownership RPCs run in tracked workers outside the connection's serialized callback lane. Their five-second request context bounds leaf-gate acquisition and database reads through acknowledgement enqueue. The selected lifecycle notification is returned from leaf admission rather than invoked there. After acknowledgement, the worker cancels and joins the deadline watcher, then invokes the notification outside that request budget. Slow macros cannot time out a successful ownership acknowledgement or close the shared provider connection. Notification execution stays tracked. Disconnect and shutdown join those workers; admission rechecks cancellation and connection identity before publishing ownership. Registration remains atomic against deletion and eviction. A blocked leaf therefore cannot hold the shared provider lane needed by another leaf.
Abort commits aborting before routing cancellation and records only facts
available at the existing abort boundary. Bash-associated task IDs include state
and output references; generic tasks do not imply bash buffers. Cancellation is
remembered by both provider and daemon so a late completion cannot restart the
model after idle. Deletion drops ownership and later missing-leaf completion.
Terminal provider status and output buffers are not active daemon ownership.
Tool-result queue admission happens as the scheduler receives each result, including parallel results while a later foreground call is blocked. The model still waits for the complete tool batch. This gives the background completion barrier a per-call admission point rather than a batch-duration wait, without extending provider RPC deadlines or allowing completion to precede its initial result.
Abort captures task identities, provider owners and known bash references with the Agent's abort decision under one leaf gate. That immutable snapshot supplies both the record and cancellation routing; registration/removal cannot enter between capture and retirement. Provider delivery and abort finalization occur outside the gate. If the model is already terminalizing, background work remains cancellable without replacing the claimed model outcome or launching another run. The existing abort record writer records cancellation facts, and the model terminalizer cannot expose idle before that record is finished. No process-exit wait or additional outcome turn is introduced.
Provider invocation and provider-setup errors end the current model run but keep
independently owned background tasks alive. Remaining owners select background
after retirement, and a later task completion can admit a fresh run without user
input. Unadmitted daemon continuations also survive and wait for retirement as
usual. This does not retry the failed invocation or replay tool calls: error
cleanup still discards that run's queued/in-flight input and rolls back unsent
turns. The original error remains in history, runtime outcome and requester
completion until a new run is admitted. Registration is rejected during error
terminalization, and explicit abort/delete/shutdown still cancel owned work.
Fatal agent/storage errors, including context-storage reads during provider
preparation, retain a separate ownership cleanup path. Failure to save a provider
error turn or its assistant exit message also takes this path, while clients
still receive the original provider error. It retires and kills the owned-task
snapshot with reason error, without calling public abort or appending an ABORT
turn. Retiring an owner also wakes its unresolved initial-result barrier with
failure.
Shutdown closes admission before provider teardown, retires remaining owners with
reason shutdown, and suppresses new lifecycle work or owned continuations.
Continuous elapsed time with background tasks
The service's background ownership registry mirrors task presence to the agent
through SetBackgroundTiming. This retains the original run start when model
processing ends with background tasks still active, and reuses it when another
turn resumes processing. Registering a task on an idle leaf starts a clock without
activating the model. Removing the last task clears the clock only when the model
is idle; otherwise normal model completion clears it. Provider loss and abort
retirement update the same timing flag. This flag owns no tasks and does not
change prompt/steer admission. Existing leaf_updated timing fields report this
continuous interval, including in background snapshots.
Cancellation during healthy capability waits
Execution cancellation is installed at activation, before on-demand tool
discovery, and reused by the run loop. Abort or close can interrupt renewable
metadata waits during prompt/idle-steer admission; retired discovery cannot
publish a tool cache. Replay defers discovery to normal model-cycle preparation
after ReplayRun.Start, following rewind reply/snapshot publication. Discovery
holds neither the lifecycle admission locks nor the service rewind gate, so
close and abort can reach the execution's cancellation. Post-response triggers
still detach from the completed LLM
request, but remain bound to leaf shutdown and any active execution's cancellation.
Healthy heartbeats do not extend those lifetimes. These changes do not alter
LLM provider retries or wait for remote rollback or graceful completion.