Skip to main content
A session_agent_harness section is designed so that a clean restart picks up exactly where it left off. The authoritative state is split between server-side envelopes (handoff) and local YAML files (local recovery), and the worker writes the local file before any externally observable side-effect.

Worker restart

A graceful shutdown (SIGINT, SIGTERM, q in the TUI) leaves:
  • instance.yaml removed.
  • Each active thread’s local thread.yaml snapshotted at the last completed turn boundary.
The worker object is left in place (its instance.status only ever holds attached; last_seen_at goes stale) and is refreshed on the next attach. An ungraceful exit (SIGKILL, OS crash) skips those steps. The next start handles both cases. On the next start, for each section:
  1. The instance lock check accepts a dead-PID instance.yaml and replaces it.
  2. Credentials and identity are re-verified against /v1/users/me.
  3. The worker session object is read; if metadata.user.user_id matches, the section re-attaches (overwriting instance with our fresh block). If it differs, the section refuses with SESSION_OWNED_BY_DIFFERENT_USER (see Worker object).
  4. The section opens its event feed and resumes from the persisted events.cursor: the first sweep lists the stream from 60 seconds before it, drops the ids held in events.seen, and handles the rest. Nothing that happened while the worker was down is lost, and nothing is handled twice.

Per-thread recovery

A thread is recoverable only when both views agree it was running: the persisted local thread.yaml shows agent.state == "active" and the server envelope shows instance.state == "active". (The local thread.yaml keeps the agent state under agent.state; the wire envelope keeps it under instance.state — see Job Session Object.) For each such thread, the worker runs:
  1. Re-validate workspace.work_folder, agent.permissions, and — for a guarded thread — its policy block, re-read fresh from the envelope (the same checks as initial activation; see Job Session Object → Policy). A policy failure here fails recovery with the same code activation would have raised (POLICY_MISSING, POLICY_INVALID, or POLICY_AUTONOMOUS_FORBIDDEN).
  2. Re-derive the artifacts block from the envelope and re-create the outbox if it carries one. artifacts (like policy) is never mirrored into thread.yaml — it is in-memory only for the life of the turn loop, so a freshly reconstructed agent after a restart must re-read it or a thread that was publishing before the restart would silently stop after one turn.
  3. Acquire a concurrency slot.
  4. Resume the agent session via the codeagents SDK using the persisted agent_session_id. If the resume fails, the thread transitions to failed with AGENT_CRASHED (a failed resume is reported the same way as any other agent crash; there is no separate resume error code).
  5. Cancel any leftover pending_prompt by posting pending_prompt_resolved with reason: worker_restart (see Interactive prompts).
  6. Replay thread items posted while the worker was down: fetch list_session_thread_items(created_since = items.last_consumed.created_at, ascending=true), drop self items, feed remaining user items as the first post-recovery turn’s prompt. An item is the worker’s own when it carries the tree’s client tag, however it is posted.
  7. Post a thread_recovered activity-log item on the worker thread.
  8. Resume normal active behavior — including posting a policy_applied item before the next turn, for a guarded thread.
Recovery runs before activation of any new pending threads on the same section, so threads already running keep their concurrency slots; new pending work waits if the configured concurrency.max_agents ceiling is full.

If max_agents was lowered across restart

If you reduced concurrency.max_agents and there are more recoverable active threads than slots, the overflow are logged as thread_recover_deferred and remain inert until a future restart with enough slots. They aren’t transitioned to failed.

Agent crash (worker still running)

An agent process that exits unexpectedly transitions its thread to failed with AGENT_CRASHED. The worker writes instance.state = "failed" on the envelope and records the error code and message in the local thread.yaml; the error is not placed on the envelope. The failure surfaces server-side through a thread_failed activity item (carrying the code and message) on the worker thread. The worker does not auto-retry. To resume, the user updates the envelope to instance.state = "pending" (see Handoff).

Network blips

Transient errors from api.blobhub.io (429, 5xx, connection failures and timeouts) are classified as API_RATE_LIMITED / API_TRANSIENT_ERROR / API_NETWORK_ERROR and logged. In the TUI they surface as a warning ribbon; in headless mode they appear in the JSON log. What happens next depends on the call:
  • Reads and periodic calls — event sweeps, attachment downloads, the keepalive — are retried, a sweep with exponential backoff up to polling.backoff_max_ms (default 30 s), or simply run again on the next tick. They do not change any state machine. A sweep whose confirming read fails transiently stops at that event, leaves the cursor where it was, and lists the event again next time.
  • Posting a thread item is a write the API cannot de-duplicate, so it is repeated only where that is safe. A 429 or a failed connect never ran, and is retried up to three times, after 0.5 s, 1 s and 2 s. Any other failure may have stored the item: the worker waits 2 s, reads the thread’s 25 newest items back, and posts again only if none carries the item’s post_id.
An agent’s item that still cannot be posted — its retries spent, or a read-back that could not complete — fails the thread as THREAD_POST_FAILED, and the full item is still in the local thread.log. A prompt that cannot be posted is denied instead. An unknown outcome is logged twice: post_outcome_unknown (a warning) when a post fails in a way that may have stored it, then post_read_back with result found, not_found or unreadable. Both carry the thread alias, the post_id and the failed post’s code.

What does not survive a restart

  • The in-memory inbound queue beyond items.last_consumed (replayed from the server).
  • In-flight agent turn state beyond the resumable agent_session_id (recovered by the SDK).
  • Agent stdout that hadn’t yet been posted — only present in the local thread.log (not on BlobHub).
  • An unresolved interactive prompt — cancelled on recovery.

A lost connection

The section listens over a WebSocket, and losing it does not stop the section. A connection that API Gateway ends cleanly (after two hours, or ten idle minutes) is reopened at once if it had been live for at least 5 seconds. Any other failure is retried after a random wait of up to min(60, 2^attempt) seconds. The wait resets once a connection has stayed live for 60 seconds. While the connection is down the section is polling: it sweeps at the polling cadence, and after the connection returns it sweeps once to catch up. A connection that the host’s sleep left half-open is noticed within 40 seconds, or at once when the worker sees the host wake. The worker never detaches a section because of the socket; a refused listener or a 405 leaves the section polling, and only the REST answers below decide whether it detaches.

Detachment while running

If someone deletes the worker session object (e.g. via delete_session_object from the API or playground), the worker observes the object.deleted event for the worker alias, reads the object to confirm it is gone, and stops that section with SESSION_DETACHED_EXTERNALLY. If the object is back (a re-create can be listed before the delete), the event is ignored. Other sections continue running. All ThreadAgents for that section shut down cleanly (the codeagents SDK is asked to cancel each session); their threads remain in whatever state they were in on the server and the worker reattaches if you re-create the worker marker.

Session closed or deleted

A section also stops when the session itself reaches the end of its lifecycle. The worker watches for the session lifecycle events on the same event stream it listens to. An event says what happened, not what holds now, so the worker reads the session before acting: “Gone” is a not-found or a 403, which is how the platform answers a deleted session. An event the session’s status does not agree with is a replay (a close that a reopen has since undone, for instance): the worker ignores it and logs lifecycle_event_stale at debug. session.deleting is treated as terminal rather than waiting for session.deleted: a session deleted directly from open never emits session.closed, and its data is about to disappear. session.deleted is read by id from the stream like any other event, so a worker that was down when the session was deleted still finds it on its first sweep, or is told by the 403 below. On detach every ThreadAgent in the section is torn down and its concurrency slot released. This is a cancellation, not a drain — a closed or deleting session rejects every write, so an in-flight turn could not post its result even if it were allowed to finish. Other sections keep running.
The worker does not release its worker object on this path. Once the session leaves open it rejects writes, so the marker cannot be updated; a deleted session takes it with everything else. A closed session that is later reopened still carries the marker, and the worker reattaches on its next start.
If the session becomes unreadable altogether — a sweep starts getting 403, which is what a deleted session answers — the section detaches with SESSION_UNREACHABLE rather than failing silently.

See also