small gleam coding and (not yet) persistent agent daemon with a detachable cli forked from okami.mom/albedo
albedo docs http-sessions.md
28 kB · 468 lines
Markdown
at main

Session lifecycle and recovery #

This reference describes session identity, durable input, cancellation, and recovery. OpenAPI owns exact variants and fields. HTTP API behavior defines common authentication, errors, and pagination.

Session representations #

SessionSummary and Session in OpenAPI define the representations. http_session_resource.gleam projects session reads. Session ownership describes the actor behind them.

Each summary captures its live status, progress, activity, and cursor together. A family address stays stable when a display name changes. Configuration has a separate canonical resource and validator, so unrelated live progress does not invalidate an edit.

Pinning assigns a shared order once. Repeating a pinned value does not move the row or increment its visit count. Unpinning clears the order. Visits change only through the identified visit operation.

Activity is a bounded display projection, not a second transcript. It includes the current partial line, generated-output counters, and identity-bearing input and answer observations. Clients derive rates from successive samples and install initial identities without replaying old animations. Argument previews stay in progress rather than being copied into activity lines.

Kernel metadata is observational. A read does not prepare Python or expose executable process handles. Unknown job counts and lists are null. A known empty list is empty, and a bounded job list can be shorter than the reported count.

Pending input summaries omit images and expanded model input. A continuation can consume a durable position without adding a text row. input_order is zero before admission and records the greatest accepted order thereafter.

Optional compaction progress describes the current strategy stage, completed units, and a nullable stage total. It is transient state, not transcript content. A stage count is not an overall percentage. Clients can display elapsed time from the shared start timestamp. Main-request preparation and terminal outcomes clear this state.

Usage timing belongs to the provider call that produced the observation. Missing timing remains null. Estimated token counts and provider-reported counts remain separate. OpenAPI supplies the bounds and optional-field rules for these projections.

Collection reads #

GET /sessions accepts scope=roots|all and optional parent_id, family_id, workspace, search, archived, and needs_reload. The parent and family filters are mutually exclusive. family_id selects the containing root and all descendants. search matches display names and ID prefixes. sort=activity|frequent defaults to activity. Frequent sorts by opens, activity, and ID. Pinned state remains available for client grouping.

The CLI's prompt, read, send, and stop workflows resolve a full lowercase UUIDv7 with GET /sessions/{id}?view=configuration, including child sessions. Only shortened IDs search the root-session collection and require an unambiguous match.

Parent and family queries default to scope=all. Other queries default to roots. An explicitly supplied scope=roots with a parent or family filter returns 400. The result is a page of SessionSummary objects. A family query also returns family: { "root_id": ..., "revision": ... }. Agent trees are drawn from parent_id, address, and depth. There is no second agent identity or graph endpoint. Clients can traverse all pages. A missing requested family returns 404, while an existing parent with no children returns an empty page.

Accept: text/event-stream selects the collection watch.

Creation, forks, and children #

PUT /sessions/{session_id} requires a fresh client-generated UUIDv7 and If-None-Match: *. Its body follows SessionCreationRequest in OpenAPI:

Kind Behavior
new Create an independent session with resolved defaults.
fork Copy a durable prefix into an independent session.
child Create a family member together with its initial durable task.
side_question Continue a captured side-question exchange in an independent session.
acp Create an editor-owned session with its initial MCP overlay.

session/creation.gleam owns canonical intent. OpenAPI defines the required fields of each variant. Do not infer the union from the ordinary new, fork, and child flows alone.

The daemon resolves defaults once at first admission. Child creation, family membership, creation decision, and initial input admission commit together. A rejected task leaves no orphan child. The child task is ordinary identified user input. Forks preserve full durable tool arguments and results, image references, captured execution traces, continuation boundaries, and selected extension overrides. They copy no Python namespace, live jobs, progress, or usage totals. The daemon closes incomplete tool exchanges at the chosen checkpoint using its existing history rules.

POST /sessions/{session_id}/rewind is the in-place counterpart. It takes a checkpoint_id of a user message and an optional summary request. The daemon copies the whole session into a new archived session first, then deletes every row from the checkpoint on, and recomputes what derives from them (preview, tool-call index, captured traces, LCM nodes, image references). The session must be idle. Its actor stops, so attached streams reconnect and reset. input returns the removed message's text for the composer. With summary, the daemon summarises the removed tail before it changes anything and adds the result after the cut as a note from origin rewind. A failed summary leaves the session unchanged. The Python namespace and files on disk are not rewound. Rewind requires capability history_rewind: 1.

Successful session creation returns 201 with Session, its Location, and ETag. A retained rejected creation returns its original problem and admission status on retry. An existing session fails the create precondition with 412. Recovery reads the session and compares creation.submitted structurally with the original intent. The descriptor preserves the canonical submitted intent. String contents stay exact. Clients compare the returned descriptor according to its schema, including optional-field rules. Matching intent proves creation. A different intent is an ID conflict. Resolved workspace and provider defaults appear in creation.resolved and do not change the submitted descriptor. Current model, title, or workspace cannot replace that provenance check. Sessions stored before immutable provenance was recorded return creation: null. They remain readable, editable, and forkable, but cannot prove a matching creation request. Migration never invents submitted intent from their current configuration. Every newly admitted creation has provenance. Conditional creation follows HTTP If-None-Match semantics.

Creation decisions and deletion tombstones remain queryable at the same URI. Rejected creation reads return their original problem with decision metadata. Deleted session reads return 410 session_deleted with creation provenance. An unknown young ID returns 404, which cannot prove an in-flight PUT will never commit. Recovery retains the same intent and identity.

GET /sessions/{session_id} returns Session. tail, default 100 and maximum 200, selects the recent history window. The byte bound can shorten the window. Status, progress, pending ownership, and the cursor share one session-actor capture. History is read through that capture's durable high-water mark. The configuration view does not accept tail or stream cursor parameters.

Changes, visits, and deletion #

GET /sessions/{session_id}?view=configuration returns only editable metadata, preferences, overrides, and revision, with a strong ETag. Family membership is not configuration: the family revision appears only on the session representation (and its summary), so a child spawning, closing, or being deleted never makes a client's observed configuration stale. A workspace move and a subtree deletion send the family revision that read observed alongside the configuration ETag. The full session read embeds this same value and validator for an edit. PATCH /sessions/{session_id}?view=configuration accepts name, provider_profile, model, effort, preferences, and selection. An empty or null name restores the automatic title for a root, or the original family name for a child. A name the model chose with /rename is that automatic title, kept apart from configuration: it never changes the configuration validator, and the person's own name outranks it. Pin and archive changes are shared preferences. Model and composition changes require an idle session. Selection maps accept true, false, or null to clear the override and inherit the global default. A patch enabling one compaction strategy clears competing earlier true overrides to inheritance. Enabling multiple strategies in the same patch returns 400 selection_conflict, and explicit false or null choices keep their meaning. When model or profile changes without an explicit effort, preserve the saved choice. inherit follows the profile override or model default; default bypasses the profile override. New sessions use inherit when effort is omitted or null. In a session PATCH, an explicit null restores legacy unset behavior. Explicit levels and inherited profile overrides unsupported by the selected model fail validation without changing saved state. Selection has extensions, skills, instructions, and mcp maps keyed by their catalog IDs. MCP entries enable or disable installed server definitions. Their IDs are stable definition names. Definitions and secrets belong to shared settings. Skill and instruction choices additionally include the write-only catalog_revision from the discovery read. A stale catalog returns 409 catalog_changed. The session owner prepares a valid candidate before committing the patch. Editable session data and preferences commit together through the store owner. The result contains the captured session and the workspace-move result, move. The session's configuration_resource carries the saved configuration and validator. For ordinary configuration edits, move is null. PATCHes set explicit values. They never toggle or increment preferences.

For example, a session selection patch clears one override and disables a skill:

{
	"selection": {
		"extensions": {"browser": null},
		"skills": {"candidate-123": false}
	},
	"catalog_revision": "observed-discovery-revision"
}

Workspace changes use the same PATCH with workspace as its only change, alongside the observed family_revision as a write-only precondition. The daemon validates the destination and captures following descendants under the family revision. A busy target session returns 409 session_busy before any move. The UI retains its deferred move intent. An idle parent can move while a descendant is busy. Destination metadata and deferred descendant intents commit in one store transaction before kernel cleanup. Busy descendants finish their captured turn in the old workspace and apply the new workspace at idle. Their workspace_change reports desired location, active location, and state deferred or applying. This intent survives client disconnect and daemon restart.

The move preserves transcript and family addresses, resets affected kernels and Python namespaces, and returns applied and deferred counts, bounded ID lists, truncated, and cleanup warnings. When truncated, clients refresh the family rather than repeating a move to discover its result. Cleanup failure cannot be reported as rollback of a committed move. Affected sessions cannot begin a new turn in an old kernel after the commit. A later explicit move supersedes the earlier desired location by revision. A delayed completion cannot restore an older choice. New descendants inherit the parent's desired workspace at their admission.

Model selection does not implicitly change the default for new sessions. The TUI's model picker saves profile defaults only through Ctrl+S and its confirmation. It leaves the starting profile unchanged. A later default or cap failure leaves a confirmed session model change visible.

PUT /sessions/{session_id}/visits/{visit_id} accepts an empty object and counts one deliberate attachment. Repeating the UUIDv7 returns the same count without incrementing it again. Background refreshes do not create visits. Reads never change opens. Deleted sessions cannot be revived by a visit.

DELETE /sessions/{session_id}?view=configuration defaults to scope=leaf. It requires the configuration If-Match, an idle session, and no children. scope=subtree also requires the family_revision query parameter from the session read. The daemon captures exactly that membership, prevents new child admission during this operation, interrupts members, cancels pending inputs, and deletes deepest first.

Deletion returns 200 with state: "complete"|"partial", deleted_count, remaining_count, deleted_ids, and remaining objects containing ID and safe reason. Counts cover the captured operation. Lists contain up to 200 IDs each and can shorten further to meet the byte limit, with truncated: true. Clients refresh the authoritative family or read known deletion tombstones. They never repeat deletion to page its result. Partial deletion is visible. Any successful deletion changes the family revision. A retry with the old revision cannot broaden the operation or delete new descendants. The client refreshes and confirms the remaining membership before a new deletion attempt. This operation has no automatic replay after transport loss.

Input admission and outcomes #

operations.gleam owns durable admission, delivery, retention, and cancellation.

PUT /sessions/{session_id}/inputs/{input_id} uses a client UUIDv7. The body follows the InputRequest union in OpenAPI. Ordinary inputs can carry client_id for echo correlation. ACP prompts instead require the current attachment token and preserve ordered text and resource-link blocks.

Message, continuation, skill, and command inputs share durable admission. Only a catalog command declared for input delivery can use that variant. Field inventories, image limits, and file limits belong to OpenAPI.

A message requires nonblank text, an image, or a file. Images accept PNG, JPEG, GIF, and WebP, subject to decoding, dimension, and selected-provider bounds. The model receives the text, then the images in upload order. The CLI marks where each was attached with [Image #N] in the text, numbered from 1 in upload order. Pastes are marked the same way, [Paste #N, …] for the Nth paste. The model receives a paste under 100 lines and 32 KiB in place of its marker. A longer one is saved to $ALBEDO_HOME/pastes/<session>/<input>-<n>.md and its marker names that file. History shows the text as sent, markers intact. The daemon preserves original upload metadata and the full durable payload. Provider-specific fitting stays daemon-owned and appears in durable history.

A message can also carry generic files, each a name and base64 data. A message with only files needs no text. Files require a local workspace, because the daemon saves them on its own host. A remote workspace rejects them with attachment_workspace_unsupported, and its images keep working. uploads.check checks the workspace, each name, decoding, and the decoded total before preparation saves any paste or file. uploads.expand then saves each file under $ALBEDO_HOME/pastes/<session>/. The saved name combines the input ID and a content hash, with a short alphanumeric extension retained when present. The uploaded filename is never a path component. The model's text gains a system note with each quoted filename and saved path. History keeps the text as sent. The user entry's files lists each file's name and decoded size in upload order, without the path or bytes. Entries recorded without files omit the field. Do not infer attachments from text that looks like a file label.

Checking before writing is not a transaction. Saves happen during preparation, before admission. The session actor checks the workspace again when it admits the input, so a workspace that became remote in between still rejects it. A write failure or that later rejection can leave saved files behind until the age-based sweep removes them. A files entry in history does not mean the saved bytes still exist.

Command inputs prepare a user turn. They do not invoke arbitrary management handlers. Their preparation produces content, runs outside the session actor, and persists the resolved content before transcript consumption. Preparation must be repeatable without external side effects. An extension that performs effects exposes its own domain operation instead.

The first accepted PUT returns 202 with Input. An identical PUT returns the retained admission decision and current delivery state, using the original admission status. Changed intent under the same ID returns 409 input_conflict. Echo-only client_id does not change identity. File names and data are part of intent, and a message without files keeps its earlier intent. To change attachments after a failure, send them under a new input ID. Lookup happens before current workspace, skill, provider, and queue validation. Defaults and skill content resolve once. Rejected decisions are durable, including 429 queue_full.

GET /sessions/{session_id}/inputs/{input_id} returns the known decision even after session deletion. The input resource separates its admission decision, delivery state, and turn outcome. Rejected admission retains the original safe problem and HTTP status. Delivery is pending, committed, or cancelled, and is null for rejection. A continuation has a durable position without a text row.

turn identifies consumed turn membership and any durable terminal outcome: running, completed, interrupted, failed, or abandoned. A restarted daemon marks an unfinished previous run abandoned rather than claiming its external effects completed. One turn can contain several inputs. Its nullable outcome contains separately recorded detail. Null means no detail was recorded. Acceptance means safe storage. Commitment means transcript consumption. Neither means that the assistant answered or a tool effect ran exactly once.

A waiting input is a row in the session's inbox, beside letters, events, and completion notices. The inbox holds at most 1000 waiting rows per session; an input that finds it full is rejected with 429 queue_full. A duplicate consumes no slot. Consumption commits transcript rows, images, input delivery state, turn membership, and the inbox row's delivery in one store transaction. Failure leaves the input pending. Preparation failure exposes a safe blocking reason. It cannot install a successful delivery state. Waiting accepted inputs survive restart. People see, reorder, and drop what waits through the queue page; see the inbox.

Known pending identities and inputs belonging to an unfinished turn never expire. An input becomes terminal only when delivery and its associated turn are terminal. Its admission record remains for seven days after that point. Rejected decisions become terminal at rejection. Live sessions retain creation provenance for their lifetime. Deleted sessions retain tombstones for seven days. Known decisions are checked first. Unknown UUIDv7 identities older than seven days return 410 identity_expired and cannot execute. Identities more than five minutes ahead return 400 identity_future. This prevents recreation after deduplication records expire. These rules also cover visit identities.

Recovery queries the same input URI and may resend the exact same PUT within the caller's deadline. 404 means unknown at the time of the read, not safe to invent another ID. 410 stops automatic recovery and keeps an unresolved UI row. A matching durable event can still reconcile that row later.

ACP sessions and attachments #

ACP input and session creation send an attachment token in the Albedo-Attachment-Token header, in addition to the daemon's auth token. The daemon keeps only a digest of each token, in memory, so a restart clears every attachment. Session creation stores HMAC-SHA256 fingerprints of the editor's MCP servers. A retried creation can match the original request without the daemon storing the editor's credentials.

OpenAPI defines the routes. The ACP reference defines ownership, leases, and recovery.

Targeted cancellation and interruption #

POST /sessions/{session_id}/inputs/{input_id}/cancel accepts an empty object. It returns the current Input and one result:

  • cancelled: a waiting input was removed and its cancellation committed.
  • interrupt_requested: its current turn belongs exclusively to this input.
  • shared_running: other inputs share the active turn. The turn continues.
  • not_pending: no waiting or interruptible exclusive work remains.

Every input kind uses the same identity for admission, membership, and cancel. This operation never interrupts a later unrelated turn. Repeating it reports the current outcome of the same input, without resubmitting that input.

A person's typed message that still waits can be edited in place. POST /sessions/{session_id}/inputs/{input_id}/hold with an empty object holds it and returns lease_ms: until the hold is released, lapses, or the edit is saved, neither it nor any input queued after it is read. Hold again before the lease runs out to keep editing. POST …/edit takes a message body like the PUT, replaces the waiting message under the same id and position, and releases the hold. DELETE …/hold lets the message be read as it was. Both answer 409 input_not_waiting once the session read the message or it was cancelled.

POST /sessions/{session_id}/interrupt requires run_id, nullable, and through_input_order, taken from the session snapshot. It cancels still-waiting inputs at or below that order and requests interruption of exactly that run. Newer queued inputs remain accepted. An already ended run is reported as ended. A later run is never interrupted by retrying this request. Acceptance of an interrupt request does not mean all external tools stopped.

The result contains run_id, state: "requested"|"already_ended", cancelled_input_ids, and warnings. Interruption prevents new inputs joining the captured run. Live status reports interrupting until the run ends.

Human shell commands #

http_shell_commands.gleam adapts the shell-command owner.

The shell resource is separate from inputs and never starts a model turn. PUT /sessions/{session_id}/shell-commands/{command_id} accepts {"command":"..."} with a client-generated UUIDv7. Admission precedes spawn. Replay of the exact same command returns its original resource before mutable checks, different bytes conflict (409). A session permits one running command and 32 uncommitted outcomes. Admission also caps aggregate pending snapshot reservations at 512 KiB (JSON-escaped command bytes plus 12 KiB per record for preview and metadata), so large commands can reach capacity sooner. Commands contain 1-16384 UTF-8 bytes without NUL. Remote workspaces are refused explicitly.

PUT and GET on the command URI, and POST on its /stop resource, return the current shell-command envelope defined in OpenAPI. A nonzero process exit is still a completed command. Exit code, error, and committed history position can be null.

Stop requests process-group cleanup. The response can still report running until cleanup is confirmed. Output reads use UTF-8 byte offsets and return complete code points. An offset inside a code point or outside the captured output is invalid. Reaching the current cutoff does not prove a running command has finished.

Output capture is bounded and reports truncation. Direct reads and session snapshots use smaller previews than retained output. Clients use the output-paging operation for the complete retained prefix rather than assuming a preview is complete.

Session reads, resets, and shell_command events carry uncommitted outcomes. After idle commitment, a history entry of kind shell_command carries the canonical outcome. Reconcile by command identity and history position. Completion does not admit a new model input.

The model receives a labeled human command and outcome with a bounded output excerpt, not a fabricated tool invocation. The read-only output.read_shell binding pages retained output for that session.

Side questions #

http_side_questions.gleam adapts the side-question owner.

Capability side_questions: 2 provides PUT /sessions/{session_id}/side-questions/{question_id} with {question}, PATCH /sessions/{session_id}/side-questions/{question_id} with {dismissed}, and POST /sessions/{session_id}/side-questions/{question_id}/cancel with an empty body. All three return {side_question}. Identity is a client UUIDv7. Replay with the same question returns the current exchange. A changed question conflicts, and another running exchange is busy. An unprepared session with no transcript history refuses admission; an unloaded session with history loads on demand and prepares context. Exchanges persist in session_side_questions across restarts (an in-flight running exchange comes back failed, and rewinding past checkpoint or deleting a continuation clears stale state). PATCH records whether the exchange's card is dismissed across views and reloads. No GET is needed: session resources, reset snapshots and side_question events carry the exchange, including dismissed and nullable answer, error and continuation session id.

Identified session creation accepts {kind: "side_question", source_session_id, side_question_id, name: null}. Continue copies the captured committed prefix and appends the question and answer atomically. It does not invoke a provider. One exchange permits one continuation identity. Existing creation receipts and 412 preconditions keep retries valid after the source exchange is gone.