wire

package
v0.16.355 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 35 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

internal/wire — the v2 contract

schema/frames.json is the source of truth. types.go (Go) and web/app/next/protocol/v2.ts (TS) mirror it; the fixtures in testdata/ are read by both:

  • go test ./internal/wire/... checks every fixture against the schema (a small checker in schema_test.go that fails on any keyword it does not know), decodes it through the Go types, re-encodes it and compares, and checks that every closed list and codec table equals the schema's.
  • pnpm -C web test parses every fixture with the strict parser of v2.ts, compares the result with the fixture, and checks every TS closed list against the schema. The TS decoder tables are tied to those lists by satisfies Record<Kind, …>, so a kind missing on either side fails typecheck.

No generator: a change starts in the schema, then both mirrors, then a fixture; the tests name what is out of step.

A fixture is one document: a socket frame as sent, a command exchange {op, body, result}, or an HTTP answer {http, response}. File names: frame.*, snapshot.*, ev.*, cmd.*, cmd.refused.<code>, http.*.

In Go a union with a few fields (AgentState, MessageState, GateState, Entry, CmdResult) is a flat struct whose JSON carries exactly the fields of its kind — not omitempty, so false, 0 and null survive. Frames, events and commands are interfaces over one struct per kind. Decoders are strict (unknown kind or field is an error) and run Validate().

Stage 0 decisions

Where the spec was silent or two readings were possible, the simpler one:

  1. Results name their channel. accepted/queued carry ch beside seq: the page waits for that seq on that channel (a send shows on conv:<id>, a rename on convs).
  2. Conversation-scoped commands carry conversationId (cancel, retry, promote, answer, decide, bg.stop): the command goes straight to the conversation's actor, no global index of client, question or task ids.
  3. Every body has opId; for send it must equal clientId.
  4. conversation.restore takes only id; force is delete's. conversation.create takes projectId or cwd (exactly one) and model: Model | null (null: the agent's default). conversation.move takes projectId: string | null (null: out of any project).
  5. MessageState on the wire has no draft, uploading, submitting: they live on the page (LocalMessageState in TS). MessageFailure stays one closed list, page-side codes included.
  6. queued.position starts at 1 (the head). Conversation.lastPromptAt is when the person last wrote to the chat (createdAt until then): the last real human message, not the agent's lines, meta lines, compaction summaries, hook or task notifications, tool results or reminders. A send from a client sets it at once. The sidebar orders and groups by it, so the agent's work never moves a chat.
  7. step carries counts: {toolCount, stepCount} | null — the turn's counters after the entry, null outside a turn. conversation_seen carries rev, like conversation_state.
  8. Snapshots. seq is the last seq the snapshot includes, 0 before any event; event seqs start at 1. The machine channel's data is {machine}. conv:<id>: turns are full Turn records (≤ 33, oldest first); entries hold the steps of the last three and, of each older one, the entry that opened it (the turn's own id: the person's message, a teammate's note) and its answer entry, so a folded turn always renders its question and its answerEntryId. The turns page has the same shape: {turns, entries, beforeTurnId}.
  9. PUT /api/v2/uploads answers an AttachmentRef, not only {id}.
  10. Events are bound to their channel (schema, Go and TS): machine events only on machine, and so on.
  11. Invariants beyond the shape: a failed turn has a failure and no other turn does; turn_finished is done/interrupted, turn_failed is failed; permission_requested is kind tool, plan_proposed kind plan; a compaction event carries a compaction entry; afterSeq needs epoch.
  12. Every conversation id matches ^tab-[A-Za-z0-9_-]+$, not only in channel names. Limits are plain numbers; wire.DefaultLimits holds today's values.
  13. Go: AgentState.TurnID is *string (the spec's sketch had string) because working.turnId is nullable.
  14. convo.Service does not serve the machine channel: reach and load come from elsewhere (the agent link, internal/machines).

Stage 0 decisions after §11–12 (no lags, no unclear states)

  1. Every wait on the runtime has a term on the wire: wait: {slowAt, deadlineAt} on starting, queued (null for agent-busy/behind, which wait on the agent, not on us), typing, in-input and the gate's answering. Past slowAt the page shows «дольше обычного» (waitPhase in v2.ts); by deadlineAt the runtime has moved the state on — it does not wait longer. The page derives nothing: both instants come from the runtime. Terms: wire.WaitSlowMs 3 s, typing 12 s, confirm 15 s, answer 10 s, launch 150 s (slow at 15 s), queued TTL 15 min as before.
  2. in-input → failed{unconfirmed} after 15 s, not the 30 s of §4.3, to fit «ошибка за 10–15 с». The exception is a message typed into a working agent (mode steer): Claude holds it in its own queue until the agent's next step (a Bash call or a long answer: minutes), and its prompt-submit hook fires at the Enter, not when the agent reads it. It stays in-input until its transcript entry arrives (accepted → in-turn), with deadlineAt 30 min away (outbox.SteerDeadline); the page says «agent reads it after the current step», not «not confirmed». Steers go to the agent in the order they were sent, ahead of now and queued messages.
  3. Every command ends. limits gives slowMs (3 s), cmdBudgetMs (10 s: the runtime answers every command within it, refused{timeout} at worst) and cmdTimeoutMs (12 s: the page gives up and offers retry or cancel). On the page a command ends in CmdOutcome = the result, or failed{timeout|network|http}; a retry reuses the opId. New refuse code timeout; RetryableRefuseCodes (machine-offline, rate-limited, internal, timeout) get «Повторить», the rest only «Отменить».
  4. Stable entry ids are part of the contract: every entry id must be c:<uuid>#<k>, x:<offset>#<k> or live:<turnId>, and every turn id one of the first two — schema patterns, ValidEntryID/ValidTurnID and the TS parser refuse anything else, so a random id cannot reach the feed. Builders: ClaudeEntryID, OffsetEntryID, LiveEntryID.
  5. A peer entry is what other agents' sessions wrote (Claude Code's <teammate-message>, which reaches the agent as a user line): peers holds each message of the line — from, kind (message, done for an idle notice with a result, idle for one without, event for any other JSON notice, its type in event), color, summary, sentAt and the body as md. A background subagent of the session writing to it (<agent-message from=<hex id>>) has agentId and model, and from is its task as the Agent call named it (empty when unknown). The harness's lead-in and the paragraph after the messages are not carried. It opens a turn like a user entry but is not the person's (no client id, never the outbox's) and is not counted in stepCount of the turn it opens. The body is the sender's words: the page draws it as Markdown text, never as markup.
  6. The harness's own lines are notice entries with code system-note, never user: a <task-notification> of any shape (a goal check-in has only <summary>), <system-reminder> blocks alone, a line under [SYSTEM NOTIFICATION - NOT USER INPUT]. detail is the note's first line, then its other fields one a line. Like a peer entry it opens a turn when none runs and is not counted in that turn's stepCount.

Message states: one road

A message goes one way, and every state is one event, sent only when the state really changes:

queued{position, reason} → typing → in-input → accepted → in-turn → done
                  ↘ failed{code, retryable} (from any step before in-turn)      ↘ cancelled (person, while queued)
  • queued. position 1 is the head. The head's reason is the agent's state alone (agent-busy, launching, resuming, blocked-menu, blocked-text, paused); the others are behind. A message in flight (typing, in-input) or a steer typed ahead of it does not change the head's reason, and a message that waited on agent-busy and is pushed down by one that jumped ahead («now») keeps agent-busy — it never goes agent-busy → behind → agent-busy.
  • typing → in-input. The text is typed into the agent's box; the wait terms (wait.slowAt, wait.deadlineAt) are the runtime's. A steer (mode: steer) is read by the agent only at its next step: it stays in-input up to 30 min and the line is free for the next one.
  • accepted. The agent has it: the hook said so (entryId: null) and then the transcript named the entry (entryId), the second event only adds the name. in-turn: the turn it opened (a queued message opens a new turn), or the running turn it was steered into — the entry is then a user entry among that turn's steps.
  • failed is the runtime's by its deadlines or a refusal on the merits; the page only shows it. The page has no «not confirmed» of its own: a message the runtime has not answered is not failed, see «The road is not a refusal».
  • Where the page draws it: while the agent was busy at the send (or the message is a steer), in the stack over the field from the first moment until accepted; otherwise in the feed on its way. At accepted it is the feed's: the turn's prompt, or a steered message among the steps. The user entry carries the client id, which is how the page tells a message it holds from the entry that is the same message, and why one never stands twice.
  • Delivery to a free agent is event-driven: the send command pumps the queue at once; a screen that still shows the last turn's spinner while the state says idle is looked at again every 100 ms (40 looks), then every 1.5 s.

References: designs, documents, boards, files, MRs, tasks

A message can point the agent at places instead of carrying files: send.refs (and Message.refs, Draft.refs, draft.set.refs), at most 10 MessageRef {kind, id, title, target} of kind design | doc | board | file | mr | task. Nothing is uploaded; id names the place for the page (a design's id, a document's slug, a path, an MR's or a task's URL or key), title is the chip, target the URL or path the agent opens ("" for a design).

  • The runtime writes them into the words. Message.text is the person's text, a blank line and one block (internal/attach), the same block the agent reads:
    <attached>
    Прикреплено к сообщению:
    <ref kind="design" id="landing" title="Лендинг"/> Дизайн «Лендинг» из библиотеки (…): папка …, доски — в …/project. …
    <ref kind="doc" id="pay" title="Разбор оплаты"/> Документ «Разбор оплаты» — https://… (прочитай его, прежде чем отвечать).
    </attached>
    
    The header is in the runtime's language; every place is one line led by its <ref …/> tag, whose attributes are escaped (&amp; &lt; &gt; &quot;), and nothing in a place's words can close the block or start a line of it.
  • A design is named by the machine's library: its folder, its boards and the rules file a design dialog gets; the conversation is linked to the design (designly.json attachedDesigns), so designly/library lists it among the design's convs. A design the library has not is refused{not-found}; a machine without a library unsupported.
  • The page reads the block back: a bubble and a queued row show the person's text and a chip per <ref>, never the block. A repeat of the clientId is the same message: the block is not appended twice.
  • The first message of conversation.create takes no references yet.

The road is not a refusal

Who leads a message's delivery — this runtime, or a cluster's outbox in front of machines — says where it is by an event (prompt_state, message_upsert); the page never decides that a message failed or went.

  • page-side submitting lasts until the first such event or a refusal on the merits. It has no deadline and no red.
  • Of the road, not a refusal (the message stays submitting, the bubble says «waiting for the machine», without red): no connection, a socket that dropped, a restart of the runtime or the machine, a gateway's 502/503/any status with no CmdResult in the body, an answer that did not come in cmdTimeoutMs, and the refusals machine-offline, timeout, internal, rate-limited (RETRYABLE_REFUSE_CODES) — they say «not now», not «no».
  • Sent again by itself, with the same clientId as opId: 1, 2, 4, 8, 15, 30 s (30 s from then on), at once when the machine's socket is live again, after F5 too (the outbox of IndexedDB keeps the message). The runtime answers a repeat with the answer it gave (kept 24 h and across restarts), so a repeat never types twice; timeout and internal are not kept as an answer, so the repeat is tried afresh (convo.TestASendRepeatedByThePageIsTheSameMessage).
  • Refused on the merits (bad-request, text-too-long, queue-full, attachment-*, agent-gone, not-found, forbidden, …): failed{refused}, red, the reason in the person's words (next.refuse.<code>), Delete only — the same clientId would get the same no.
  • Delete of a message the runtime has not shown is the page's own and works offline; a cancel for the same clientId is sent besides, in case a lost answer hid that the runtime has it.
  • A cluster that leads the delivery uses the same road: it answers the command (accepted/queued) once it has taken the message into its outbox, and from then on queued{reason} / typing / … come as events, whoever types.

Closed questions

  1. Machine channel. wire.MachineSource (source.go) serves it: Snapshot(ctx, load) and Subscribe(load, fn) with machine_status and, while asked, machine_load. convo does not know it.
  2. Device. Every HTTP request carries X-Harnessly-Device: <deviceId> (wire.DeviceHeader, DEVICE_HEADER); the socket carries it in hello.device. The page makes the id once and keeps it in localStorage.
  3. Snapshot and seq — a protocol invariant. The hub subscribes the channel before it takes the snapshot, so no event falls between them. The snapshot carries the last seq it includes; the page drops events with seq ≤ that seq. Every event applies idempotently by id and rev: an event already reflected changes nothing.
  4. Turns page. limit defaults to 30 (TurnsPageDefault), at most 100 (TurnsPageMax); below 1 or above 100 the page answers refused{bad-request}. A page that cannot answer sends {r: "refused", code} like a command (Refusal, parseRefusal).
  5. «Сейчас». There is no event that clears now: the page sets it to null on turn_finished and turn_failed of that turn.
  6. conversation.create with first. The accepted result's id is the new conversation's id. The page subscribes to conv:<id> with its epoch and afterSeq: 0 (frame.client.sub-new-conv); the ring holds a new channel from its first event, so the first message's queued{launching} and later states are not lost.
  7. Gate ids. Permission has turnId: string | null like Question. Question and permission ids share one space within a conversation, told apart by prefix — q:<toolUseId>, p:<toolUseId> or p:<tabId>:<eventSeq> — guaranteed by the runtime and checked everywhere an id of either is taken.
  8. answers[].text is the person's own answer instead of a choice: an item has either choices (≥ 1) or text with choices: []. Both or neither is refused{bad-request}.

Stage B — the hub, the socket, commands and pages

  1. Routes (pages.go, under the same base path as Legacy, /agents or none, and the same page session): GET /api/v2/hello, GET /api/v2/socket, POST /api/v2/cmd/<op>, PUT /api/v2/uploads?name=<file> (the body is the file, Content-Type its type; the answer is an AttachmentRef), GET /api/v2/conversations/<id>/ turns|turns/<turnId>/entries|entries/<entryId>/output. Without a session: 401 with {r: "refused", code: "bad-request"}.
  2. HTTP status of a refusal. A command always answers 200 with a CmdResult (refusals included). A page or an upload answers its refusal with a status: 400 bad-request, 404 not-found, 413 attachment-too-large, 415 attachment-type, 503 timeout, 500 internal.
  3. opId. The same opId with the same body is the same command: while it runs a repeat waits for it, after it the repeat gets the stored result (24 h, 5000 ops, kept in <data>/v2/ops.json). The same opId with another body is refused{conflict}. A command past cmdBudgetMs is refused{timeout} and is not stored, so a retry runs again.
  4. Socket. hello within 10 s or the socket closes; ping every 15 s, a socket silent for 90 s closes, and the runtime sends a pong of its own (t 0) every 15 s to a page it has not heard from, which the page answers with a ping (a hidden tab's timers are stretched by the browser, a frame's handler is not); at most 64 channels; a client 8 MB behind is closed with 1008. Each channel keeps 2000 events or 5 minutes for resume (RingSize, RingAge); a cursor of another epoch or past the ring gets a snapshot.
  5. Budgets. FitConvs keeps the convs snapshot within 72 KB per 100 conversations (snippets, then titles, shortened); FitConv keeps a conversation snapshot within 256 KB: outputs shortened, older turns folded to their answers, the last turn's oldest steps, the oldest turns. The user entry, the answer and the live reply of the last turn always stay.
  6. Fake runtime. RUNTIME_V2_FAKE=1 (pace RUNTIME_V2_FAKE_STEP_MS, default 300) serves the fixtures through wirefake on a real hub and socket: messages run a scripted turn, markers in the text steer it ([fake:work], [fake:question], [fake:permission], [fake:plan], [fake:fail], [fake:stuck], [fake:launch-fail]), and POST /api/v2/fake/<action> steers a test (wirefake/control.go: reset, restart, drop, delay, turn.finish, turn.fail, ask, agent). Without the fake there is no v2 yet: hello is 404.

Models

  1. Model choice. machine.agents[].models lists what the CLI takes ({id, label, hint, efforts, defaultEffort}; hint is one short line on what the model is for, "" when the CLI says nothing honest; the efforts are low | medium | high | xhigh | max | ultra (ultra is Codex's, gpt-5.6-sol and terra), those the model takes, the rest of the CLI's levels left out; defaultEffort is what the model runs on when none is asked for: Codex's cache; for Claude CLAUDE_CODE_EFFORT_LEVEL, then the effortLevel saved in its user settings, then the model's own default from Claude Code's bundled model catalog (a project's settings can still override it for one conversation); Haiku has no depth to choose, [] and null; the first model is the one a new conversation offers; [] when the machine does not know them) and canSwitchModel says whether a running conversation takes the model command. A runtime that serves it announces the model feature. conversation.create carries model (the agent starts on it); model {id, model, effort} switches a running one: Claude gets /model <id> (and /effort <level>) typed into its box, and the answer is accepted on convs with the record's rev once the agent said «Set model to» (the «Switch model?» question is answered yes: choosing it was the consent). An agent that is not at its prompt — in a turn, asking, not started (stopped, gone, still starting) — is never refused for it: the answer is accepted at once with the change on the record as pendingModel {id, effort, ultracode?, since, applying}, and the runtime applies it at the first moment the agent is at its prompt, before the next queued message is typed (an agent not started: right after the launch a message brings about, before that message). The latest ask replaces the one waiting; asking for the model the agent runs on takes it back. An applied change moves model and adds {at, from, to} to modelLog (the last 20), which the feed draws where it happened. An effort the model does not take is refused{option-unknown}, a Codex conversation refused{unsupported}; the record keeps the old model on any refusal. A queued change the agent did not take is logged too, as {at, from, to, refused: <code>} with the record left on from: the feed says «модель не сменилась» and why.

33a. Ultracode. Claude Code's ultracode (2.1.310+) is a mode beside the effort, not a level of it: standing dynamic workflows with subagents on every task, at any effort. models[].ultracode: true marks the models that take it (Claude's Fable, Opus, Sonnet; not Haiku, not Codex). Model, pendingModel and model carry an optional ultracode boolean (absent is off; in model, absent keeps the mode the conversation runs). A switch types /model <id>, then /effort <level>, then /effort ultracode on|off, and is applied when Claude says «Ultracode on»/«Ultracode off»; a model that does not take it is refused{option-unknown}. A conversation started on ultracode gets it from --settings (the ultracode key: Claude Code never saves it), and one resumed gets it typed again, since a new process starts without it. Effort ultracode of before is read as {effort: xhigh, ultracode: true}: what --effort ultracode ran. 33b. Fast and permission modes. models[].fast: true marks the models with a fast mode (Claude's Opus while Claude Code runs on an API key — a claude.ai subscription has no /fast —, Codex models with a fast service tier); machine.agents[].defaultPermission is the mode a chat starts in when it names none. Model, pendingModel and model carry fast (absent is off; in model, absent keeps it) and permission: plan, ask or bypass (absent: the machine's default). A new chat starts in them: Claude with --permission-mode plan|default|bypassPermissions and fastMode in its --settings, Codex with sandbox and approval flags and service_tier. A running Claude takes them like ultracode: /fast on|off, then shift+tab round its footer for plan↔ask; a change with bypass on either side, or from a chat that never said its mode, stops the terminal and resumes the agent on its session in the new mode. Fast on a model without it is refused{option-unknown}; Codex chats keep their modes until they are resumed. A vendor profile offers fast on the models its proxy has a fast tier for: the gpt profile's, by Codex's model cache. There nothing is typed: each request of the chat names its tmux pane (ANTHROPIC_CUSTOM_HEADERS, Version: harnessly-pane/…, which CLIProxyAPI passes on), and the runtime's GPT relay takes the header off and, while the pane's tab keeps launch.fast, sends service_tier: "priority" as the Codex CLI does; the change holds from the next request, without a restart.

Background, closing, projects

  1. Background. conv:<id> snapshots list background (a Bash command, a monitor or a subagent: kind, title, status, stoppable); a runtime that serves it announces the background feature. A task is listed while it runs and leaves the list (background_removed) when it ends. bg.stop {conversationId, taskId} stops a command (SIGTERM, SIGKILL after 3 s) and answers accepted on conv:<id>; a task already stopped is accepted again, a subagent or an unknown id is refused{unsupported} / refused{not-found}. Shots. The same snapshot lists shots (newest first, at most 30: id, name, at, and agent, the subagent's description, absent for the agent itself): the pictures the agent and its subagents read or a tool saved, taken from the transcripts. A change goes out whole as shots_set {shots}. GET /api/v2/conversations/{id}/shot?id=<id> sends the bytes of a listed picture only (PNG, JPEG, GIF or WebP by its first bytes, at most 12 MB); any other id, a path in its place, a file gone or not a picture is a 404 not-found. Pictures. The same snapshot lists pictures (at most 60, the latest named last: id, text): the pictures the conversation's own messages (the person's and the agent's answers) name by an absolute path, text being the path as the message writes it. A path is listed only while it is a plain PNG, JPEG, GIF or WebP file of at most 12 MB that, links followed, lies inside the conversation's folder, a Claude scratchpad (/tmp/claude-<uid>) or the uploads; a change goes out whole as pictures_set {pictures}. Its bytes come from the same shot?id=<id>, which checks the roots, the links and the first bytes again at every request; the page never sends a path.

  2. Deleting closes the pane. conversation.delete ends the conversation's tmux session and takes its tab out of the layout; a deleted conversation restored later is gone, as its tab is not there any more.

  3. Projects. A folder of the machine becomes a project with project.create {path} (an absolute path to a directory; else refused{not-found}). The answer is accepted on convs at the seq of project_upsert {project}, with the project's id; the same folder again is the same project, published again. The convs snapshot carries projects (oldest first) and defaultCwd, the folder a conversation starts in when the person names none — conversation.create takes projectId or cwd, never both, so the page offers defaultCwd as the first choice. Projects are kept by the runtime across restarts. project.update {id, path?, name?} (at least one of the two) moves a project to another folder or renames it: its next conversations start in the new folder, the ones it has stay where they started, the id stays. A folder that is not a directory, or an unknown id, is refused{not-found}; else accepted on convs at the seq of the project_upsert it publishes.

  4. Folders for a project. GET /api/v2/dirs answers [{path, name, git, branch, empty}]: the folders one level below the machine's default folder (defaultCwd) and the git folders one level below those that are not git themselves; hidden folders and build outputs are left out, git folders come first, then by name, at most 200. branch is the checked out branch, null for a plain folder or a detached head. project.create takes an optional name (one line, up to 120 characters); without it the project is called by its folder.

  5. Sessions from a terminal. GET /api/v2/sessions answers [{provider, sessionId, title, cwd, updatedAt, turns}]: the sessions Claude Code and Codex kept on the machine, in any folder, that no conversation of the runtime holds (nor a fork answering a side question), the most recently active first, at most 50. title is the agent's own name for the session, else the first thing the person asked, else the folder's name; sessions nobody has written in are left out; Codex's are those of the last 30 days. conversation.resume then has a second form, {opId, provider, sessionId, cwd} (the first, {opId, id}, resumes a stopped conversation; mixing them is bad-request): it opens a new conversation on that session — the agent starts as claude --resume <id> / codex resume <id> in cwd, the conversation shows the session's history and is titled by it — and answers accepted with its id, like conversation.create. cwd must be the session's own folder (bad-request otherwise), an unknown session or a gone folder is not-found, and a session a conversation already holds answers with that conversation's id and starts nothing.

  6. Terminals. The feature terminal is announced by a runtime that serves terminals (the live one and the fake). A conversation has its agent's pane and any number of shells of its own (at most 8).

    • GET /api/v2/terminal?conversation=<id>[&terminal=<tid>][&cols=&rows=&clientId=] is a WebSocket. Without terminal it attaches to the conversation's agent pane, with full access (keystrokes go to the agent, as in the Legacy page; a person typing there while a v2 message is being typed is the person's doing); with terminal, to that shell. A conversation, a terminal or a pane that is not there is answered 404 before any upgrade, a malformed id 400. clientId is the page's: one socket per clientId and terminal, a page that opens the same terminal again replaces its old socket.
    • The socket speaks the Legacy terminal protocol, binary frames of one byte of type and a payload. Page to runtime: 0x00 keystrokes (UTF-8), 0x02 resize (uint16 cols, uint16 rows, big endian), 0x03 heartbeat (every 30 s, the runtime answers 0x03; 90 s without one closes the socket), 0x07 back from the history to the live screen (the pane leaves tmux's copy mode; keys sent after it reach the program). Runtime to page: 0x01 output (UTF-8, whole characters), 0x03 heartbeat answer. The screen of the pane arrives first, as the output a terminal would draw to catch up. The page keeps the socket by reconnecting when it closes; nothing is lost, tmux holds the session. The history lives in tmux: the wheel reaches it as a mouse report and scrolls the pane in copy mode, or goes to a program that asked for the mouse. While the runtime's tmux.conf is in force, the window title is hx-scroll:1 while the pane is scrolled back and hx-scroll:0 at the live screen (the page's "Down").
    • GET /api/v2/conversations/{id}/terminals lists the own terminals [{id, createdAt}], oldest first; POST makes one (a shell in the conversation's folder) and answers {id, createdAt}; DELETE .../{terminalId} ends it (204). A ninth is 409. The shells are tmux sessions, so they outlive a restart of the runtime; deleting the conversation ends them, and so does closing them. There is no push for the list: the page reads it when it opens.
  7. Voice. The feature voice is announced by a runtime whose machine can recognize speech (ffmpeg and the recognition service's socket, checked once at start; the fake always). POST /api/v2/voice?lang=ru|en|auto (ru without it) takes a whole recording as the body (webm/opus, mp4/aac, wav: whatever ffmpeg reads; up to 20 MB, 2 minutes to be recognized) and answers {text}, "" for silence. It is the same decoder and the same recognition service as the Legacy page's dictation socket. An empty body or an unknown lang is bad-request, a recording over 20 MB attachment-too-large, a machine that cannot recognize now unsupported, a recording that failed to decode or recognize internal, one that took over 2 minutes timeout. The text is for the composer's field; nothing is sent.

  8. Other origins. The socket (/api/v2/socket), the terminal socket, POST /api/v2/voice and the writes to .../terminals, PATCH /api/v2/me/settings and PATCH /api/v2/agent-settings/<provider> (item 48) are refused 403 forbidden when a page of another origin asks: the browser sends the session cookie to any site, and these open a shell or take a recording. Sec-Fetch-Site, when the request has it, decides alone (same-origin and none pass; same-site, a sibling subdomain, does not); without it an Origin must name the host asked (or the X-Forwarded-Host a proxy in front was asked as). A request with neither is no browser's and is let through to its own credentials. The rule is internal/sameorigin; the Legacy sockets (the terminal, the dictation, the timeline, the status and sync hubs) take it too. The agent's own socket to the cluster is authenticated by a bearer token, not a cookie, and is left as it is.

  9. Designly. The feature designly is announced by a runtime that can start agents (the fake always). The machine's design library, over four pages:

    • POST /api/v2/designly/create takes {title, brief, kind: site|slides|ds, provider, model|null, effort|null, designSystem|null}, makes a project of the library from its template, opens a v2 conversation in the project's folder (the agent, model and depth as asked; its first message is the new-project task, the pages hint, the kind and the design system; Claude also gets the library's rules as its system prompt, another agent in the message) and answers {id, title, conv}; the conversation carries the project's name. Refusals are {r: "refused", code, message, projectId} with a message worded for the person: 422 bad-request (an empty name or brief, a name or brief too long, an unknown design system), 409 conflict (the id is taken), 500 internal; with projectId set the project was made but the conversation did not start.
    • GET /api/v2/designly/library answers {port, root, artifacts}: port is the library server's on the machine (the boards are served there), and each artifact {id, title, updatedAt, kind, pinned, cover, projectPath, boards: [{title, path}], convs: [conversation ids], touchedBy?: [conversation ids], owner?: {name, me}}; owner is who made the project (me: the person asking), read from <project>/.owner.json that a create writes beside meta/; it is absent for a project made before owners were recorded, and none is guessed. convs are the v2 conversations whose folder is the project's, so a card shows the state of its chat from the conversation's own channel. touchedBy are the other conversations, of any folder, that worked on the project: their agent wrote a file under its folder (Write/Edit/MultiEdit/NotebookEdit, apply_patch, a shell command that writes there) or named it to the design CLI (open design <id>, design <cmd> <id>), the latest activity first. The runtime reads it from the transcripts (an index per transcript that grows with it, kept in v2/designly-chats.json, the transcripts never read before read behind at idle priority), so the chats from before the link count too; an older runtime leaves it out.
    • GET /api/v2/designly/systems answers [{id, label, desc}]: the design systems the library's template carries (project/_ds/*, named by the folder without its uuid, labelled by its README's heading), the projects of kind ds, and the UI kits installed on the machine (kit:<id>). designSystem of a create is one of these ids.
    • POST /api/v2/designly/pin takes and answers {id, pinned}; a project that is not in the library is 404.
    • POST /api/v2/designly/demo copies back the demo projects (a Relay site, deck, video and design system) the library no longer has and answers {restored}, their ids. The library gets them once by itself, on its first listing; an edited demo project is never overwritten. The kind of a project and the pins are kept by the runtime in its data folder (v2/designly.json), not in the project: a project made elsewhere is a site, unpinned. Create and pin are refused to other origins (item 41).
  10. Side chat. POST /api/v2/conversations/{id}/side-chat takes {question, excerpts?, history?, model?} (the Legacy side chat's body without tabId; the conversation is the tab) and answers a server-sent stream: data: {"type":"delta","text"} frames, then one {"type":"done","text","costUsd"?} or {"type":"error","code","message"}, and a : ping comment every 15 s. The answer is a fork of the conversation's Claude session in its folder, never saved; closing the stream stops it; one question runs per conversation. A question that cannot start is a JSON {error, code} with a status, not a stream: 400 bad-request, 404 (the conversation is not here, or the machine has no side chat), 409 no-session (the agent has no saved session yet) or busy (the previous question still runs), 422 unsupported (not a Claude conversation). Refused to other origins (item 41). The fake answers a Claude conversation in a few deltas; a question with "busy" in it is refused busy, one with "fail" ends in an error frame.

  11. Files. The folder of a conversation (its cwd) can be browsed beside the chat:

    • GET /api/v2/conversations/{id}/files?path=<folder> answers {path, entries: [{name, path, kind: file|directory}], truncated}; path is relative to the folder and empty for the folder itself; entries are folders first, then files, by name; links and special files are not listed; at most 2000 entries are looked at (truncated).
    • GET /api/v2/conversations/{id}/file?path=<file> answers {path, content, revision, bytes}: UTF-8 text of at most 1 MB; revision is what a save must name. A picture or other binary is not read here: the page opens it by its absolute path (the platform's file preview).
    • PUT /api/v2/conversations/{id}/file?path=<file> with {content, revision} saves the whole text and answers the file as it is now (a new revision). The file is replaced whole (a temporary file beside it, renamed over, the mode kept); a file that changed since revision was read is refused 409 conflict; a file the person cannot write is 403. Same-origin only (item 41); the body is at most 6 MB (1 MB of text, every byte escaped). A path that leaves the folder by name or through a link, or is absolute, is refused. Refusals are {r: "refused", code, message} with the message worded for the person: 400 bad-request (no path for a file, a path over 4096 bytes or with a NUL), 403 forbidden, 404 not-found (the conversation or the path is gone, a file where a folder was asked), 409 conflict (a save over a file that changed), 415 unsupported (not text, not UTF-8, over 1 MB, not a regular file), 500 internal; 404 as well where the machine has no files. The fake serves one small project to every conversation (src/, docs/, README.md, package.json); the paths forbidden* and binary* are refused as above, readonly* cannot be saved; a save is kept in memory for the conversation.
  12. Tasks. GET /api/v2/conversations/{id}/tasks answers the plan the agent keeps while it works: [{id, subject, status: pending|in_progress|completed|blocked}], in the order the tasks were made, [] for an agent that keeps none. Claude's TaskCreate/TaskUpdate and Codex's plan updates are not steps of a turn (the feed holds no entry for them), so the page asks again when the turn moves (a step, a finished turn). The id is the agent's own: a number for Claude, the line's text for Codex. A TaskUpdate that names a task made before the transcript the runtime has read (older than its last 2000 entries) is not in the list, and one without a status sets pending. The fake gives the first conversation a plan of four tasks, the others none.

  13. Machine tool. The feature machine is announced by a runtime that serves the Machine tool of the page's right pane (the live runtime and the fake). The page asks again every 2 s while the tab is on screen; nothing is pushed.

    • GET /api/v2/machine/stats answers {at, cpu, cores, mem, net, disk, history, procs}. cpu and cores[] are the busy share (0…1) of the processor and of each core since the reading before (/proc/stat, iowait counts as idle); mem is {used, total} in bytes (what a new program cannot have: total − MemAvailable); net is {rx, tx} bytes per second over the machine's own links (loopback, bridges and container pairs are left out, they carry the same bytes twice).
    • history is the last hour, one {at, cpu, mem, rx, tx} per two minutes (at most 30, oldest first), the last being the newest reading, so the chart ends where the figures beside it are. The runtime reads /proc every 5 s into a ring of an hour in memory; a restart starts it empty, and a stretch the runtime was not running has no point.
    • disk is the filesystem of the runtime user's home: {path, total, free, parts, measuredAt, partial}. The filesystem says how much is used, not whose it is, so the runtime adds up the folders it knows by name in the background (every 10 minutes, at low priority, within 45 s): workspace (the workspace folder; when that is the home folder, its hidden entries are left out), caches (the tools' caches: .cache, .npm, .pnpm-store, .gradle, .m2, .cargo, .bun, go/pkg), agents (.claude, .codex and the runtime's own data folder); other is the used part none of them accounts for (Docker images, system files, everything else) and free is what is available. Sizes are blocks on disk, on the same filesystem, links not followed, a file with several names once. measuredAt is null until the first walk ends (all that is used is then other); partial says the last walk ran out of time, so the named parts are lower bounds.
    • procs are the heaviest processes of the runtime's user by memory and processor together, the heaviest first (the Legacy panel's list, internal/machines): {pid, startTime, name, command, cpu, rss, kind, port, stuck, guard}. cpu is the share of one core, like top (a busy multi-threaded process passes 100); rss is bytes; command has secrets hidden and is cut at 160 characters; name is the program and what it runs ("node · vite"). kind is service | agent | dev | other; guard is true for what is shown and never stopped: the runtime and everything above or under it, tmux, a service of the platform, an agent of a chat and its tools. stuck: a dev server on port that did not answer for three looks in a row.
    • POST /api/v2/machine/processes/stop with {pid, startTime} (as listed) sends the process SIGTERM, and SIGKILL when it is still there 5 s later, and answers {stopped: true, signal}. Everything is checked again on a fresh read of /proc: it is the process the page was shown (the start time is its, the pid may have been reused), it is the runtime user's (real and effective uid), it is not guarded, and it is among the heavy processes the list offers now. A refusal is {r: "refused", code, reason, message} with the status of its code: 404 not-found / gone, 409 conflict / changed, 403 forbidden / foreign, protected, not-stoppable or not-listed, 503 timeout / busy (the scan did not end in time), 500 internal / failed; a body that is not {pid ≥ 2, startTime: digits} is 400. A stop is refused to other origins (item 41): it ends a process. A machine without the tool answers 404 to both. The fake serves eight cores on slow waves, an hour of history, a disk of 128 GB and five processes (two guarded); a stop ends a process until POST /api/v2/fake/reset.
  14. Apps. The feature apps is announced by a runtime that serves the Apps screen of «More»; apps-hub by one that serves the screen's present shape (a left list of apps, each a page of its own), and a page that needs it tells an older runtime to be updated instead of failing to decode. GET /api/v2/apps answers {at, staleDays, apps}; the page asks when the screen opens and again every minute while it is on screen. It reads and changes nothing, so it is not refused to other origins. apps has the tracker and GitLab, in the order of the list; each is {id, state, reason, host, me, sections}:

    • state is ready (the sections are the app's answer, any of them may be empty), off (the machine is not set up for it: reason not-configured when no address is named, no-token when the person's token is not on the machine) or failed (it is set up and did not answer: reason denied when the service refused the token, unreachable otherwise). reason is null exactly when state is ready, and an app that is not ready has no sections. host is the service read (null while none is named); me is the person's login there (null when not read).
    • The tracker's sections are epics (every epic assigned to the person, any space, unresolved ones and those resolved in the last 30 days) and tasks (every other issue assigned to the person, the same window). Nothing is filtered by who made it or by the task-card key, so other spaces (OPS-…) are there; an epic is told by its Type. GitLab's only section is mrs: the open merge requests (any author, up to 200) and the last merged and closed ones. The page does the search, filters and sorting over them. A merge request's pipeline and approvals are read per request for the first 40 open ones; a failed read leaves them null. The tokens are the ones the task card and the merge request pane read (YOUTRACK_TOKEN, GITLAB_SELF_TOKEN), and the first of RUNTIME_GITLAB_HOSTS is the GitLab read; an answer that is ready is kept for 30 s, one that is not is asked again at once.
    • A row is {key, id, title, url, state, flag, tone, project, person, target, createdAt, updatedAt, closedAt, author, assignees, reviewers, me, labels, priority, kind, parent, progress, children, mr}. key is unique on the screen, id is what the person reads (ABC-2628, !502), url opens it in the service. state is the service's own name (the tracker's, in the space's own language; a merge request's opened, merged, closed); person is the assignee or the author as the service names them; labels are the tracker's tags or the merge request's labels; me says in which roles the person stands on it (author, assignee, reviewer). A task has a kind (its Type), a priority and a parent {id, title, url} (its epic); an epic has progress {done, total} over its subtasks and children {id, title, url, state, done, person} (at most 60). A merge request has a flag (review, conflict, ci-failed, no-reviewer, open), its project, target, and mr {source, draft, conflicts, needsRebase, ready, unresolved, comments, pipeline, approvals}: pipeline is success|failed|running|pending|canceled|skipped|manual or null, approvals is {given, required} or null. tone is how the status is coloured. Titles are one line, without control characters, cut at 300; every list is an array, never null. The fake gives both apps their rows and, on POST /api/v2/fake/apps {app, state}, turns one of them off (without a token), failed (unreachable) or ready again; POST /api/v2/fake/reset makes both ready.
  15. Settings. The feature settings is announced by a runtime that serves the Settings screen's agent files (the live runtime and the fake). GET /api/v2/agent-settings/<claude|codex> answers the CLI's settings file on the machine (~/.claude/settings.json, ~/.codex/config.toml; $CLAUDE_CONFIG_DIR and $CODEX_HOME move them) as {provider, path, rev, account, options, rules, env, mcp}; any other provider is 404, a file that does not read is 500 internal, a missing file is a CLI with nothing set. PATCH with {rev, patch} changes it and answers the same record; rev is the file's content hash the page read, a file that moved since is 409 conflict and nothing is written. The write is pessimistic: the page shows a value when this answer carries it. Both are read and written whole by the runtime, never by the page, and a write is refused to other origins (item 41).

    • options lists every option the CLI takes, in a fixed order, each {key, value} with value null while the file does not set it (the CLI's own default then applies). The keys and their values (AgentOptionSpecs in agentsettings.go): Claude Code model, effort (low…max), baseUrl (env.ANTHROPIC_BASE_URL), fallbackModel, thinking (alwaysThinkingEnabled), outputStyle, permissionMode (permissions.defaultMode: default, acceptEdits, plan; a file may also hold bypassPermissions, auto or dontAsk, which are shown and not written), sandbox (sandbox.enabled), projectMcp (enableAllProjectMcpServers), compactWindow (autoCompactWindow, 100000…1000000 tokens), memory (autoMemoryEnabled), keepDays (cleanupPeriodDays), hooks (the inverse of disableAllHooks: true while the hooks run), coauthor (includeCoAuthoredBy), updates (autoUpdatesChannel: stable, latest); Codex model, effort (low…xhigh), baseUrl (openai_base_url), summary (model_reasoning_summary), fast (service_tier is fast), sandboxMode (sandbox_mode), network (sandbox_workspace_write.network_access), approval (approval_policy), search (web_search), history (history.persistence is not none). A value the file holds that is not one of these is read as unset.
    • rules (Claude Code only, null for Codex) are permissions.allow, ask and deny; env (Claude Code only, empty for Codex) is the settings' env without ANTHROPIC_BASE_URL, which is the option baseUrl. A variable whose name has KEY, TOKEN, SECRET or PASS comes as bullets and its last four characters (secret: true), never whole.
    • mcp lists the servers the CLI has for the person, not those of a project or a plugin: Claude Code's mcpServers of ~/.claude.json, Codex's [mcp_servers.*]. target is the program's name or the address's host (no arguments, no path, no key). enabled is false when Claude Code has a deny rule mcp__<name> or Codex has enabled = false.
    • account is how the CLI is signed in on this machine: subscription (Claude Code's .credentials.json, Codex's ChatGPT login), key (an API key in the settings' env or the environment), or not signed in. plan and who come from the files the CLI keeps beside its sign-in (oauthAccount, the id token's claims); a token or a key never leaves.
    • A patch names what it changes: options (a null value unsets the option), rules (the three lists whole), envSet, envUnset, mcp {name, enabled} (Claude Code adds or removes the deny rule, Codex sets or removes enabled). What it does not name keeps its place and its bytes: JSON keeps the order of its keys and the keys nobody models; TOML is edited line by line, comments and tables kept, and read again with a parser before it is written — a file this cannot change safely (a dotted key, a key twice) is 400 bad-request, as are a key the CLI does not take, a value out of its set, an address that is not http(s), rules for Codex, and an empty patch. Skills are not here: the page reads them from the command catalog (/api/<platform>/commands). The fake keeps both files in memory, revisions included; POST /api/v2/fake/reset puts them back.
  16. Open. GET /api/v2/conversations/{id}/open?ref=<ref> answers where a chip or a link of the conversation opens in the right pane: {tab, target}, tab one of task (a tracker key, or a task's page on RUNTIME_TRACKER_HOSTS; target is the key), gitlab (a merge request or a commit on RUNTIME_GITLAB_HOSTS; the link), artifacts (a document or a board of the portal; the reader's path or the board's frame) and browser (any other http(s) address). The rules are the agent's own open command (internal/panel), so a click and the command open the same tab. !12 is the merge request of the GitLab project the conversation's folder is a checkout of (the first of its remotes on a GitLab server of the deployment). What opens nothing (an unknown key, !12 outside a GitLab checkout, a link that is not http(s)) is 404 not-found, as is a conversation that is not here; an empty ref or one over 512 bytes is 400. It reads and changes nothing, so it is not refused to other origins. The fake answers by the same rules from the runtime's environment, with no checkout behind any conversation.

    A merge request is named !12, or with its project in front, as the text names it: harnessly !80, group/sub/project !12 (one space; the ref is the word or path before the number and the number). The project is looked for in this order, and the first step that finds the merge request answers: (1) with a project named, the projects the chat knows (the ones its merge request links, its folder's checkout, the repositories one level below its folder, by their path, their last segment or their folder's name; a path with a slash that matches none is asked of the first GitLab of the deployment as it stands, and a bare name is looked up in that GitLab's project search, the projects whose last segment it is) whose GitLab has that merge request; a name that no project has is a word of the sentence and is dropped; (2) the merge request links the agent and the person wrote in the chat (!12 in a link of the text; what tools printed and links to other servers than RUNTIME_GITLAB_HOSTS are not read), the latest first; (3) the GitLab project of the folder's checkout; (4) when the folder is not a checkout, the GitLab projects of the repositories one level below it. Steps (1), (3), (4) ask the GitLab, with the token the merge request tab reads with, whether the merge request exists (at most 10 requests at once, 6 s each, 8 s for the whole ref; yes is kept for 30 minutes, no for 2 minutes), so a ref that answers is a merge request that opens. A ref that fits several projects answers with choices (tab, target, label the project, detail the merge request's title or null), 2 to 8, the best first; tab and target are the first of them. Of the repositories under a folder (the first 64 by name) the merge requests changed last come first.

  17. Open, many at once. GET /api/v2/conversations/{id}/open-refs?ref=<ref>&ref=<ref>… (1 to 32 refs, each as for open) answers {refs: [{ref, open}]}, every ref in the order asked; open is what open would answer, or null where it would answer 404 (so nothing is an error here but the conversation not being here, 404, and a missing or oversized query, 400). The page asks it for the references of the messages on screen and draws as something to click only the ones that open.

  18. The session's goal. goal {opId, id, text} sets the /goal of a Claude conversation: the runtime queues the command message /goal <text> (an empty text queues /goal clear), so it goes into the agent's box at the first moment the agent can take it, like any queued command. The answer is queued on conv:<id>; the new goal shows on the record (goal) when the transcript says it. text is one line of at most 2000 characters (else refused{bad-request}); a Codex conversation is refused{unsupported}.

  19. Background work. A conversation record carries bgAgents (absent when 0): how many pieces of background work the agent waits for — subagents, commands, monitors and its own scheduled wakeup together (the name is from when only subagents counted; a client that knows nothing else still draws the chat as at work). bgWait (absent when 0) says what it is made of: agents, teammates, workflows, commands, monitors (each absent when 0), command (the title, when one command runs) and wakeupAt (epoch ms, absent when none pends; a wakeup whose time has come is no longer waited for). A BackgroundTask of kind command that is a Monitor carries monitor: true; a wakeup is no task. A named teammate (an Agent call with a name, Claude Code's agent teams) is a subagent with teammate: true: its title is the name, its role what it was started for, its id the agent id that names its transcript (so it opens in the pane as a subagent does). It is running from its spawn or from the lead's next SendMessage to it (startedAt is when that stretch began), idle from its idle_notification (endedAt is then; an idle notice written before the last message sent to it is about the work before it) and done once it shut down (shutdown_approved or the system's teammate_terminated) or its agent is gone; only a teammate is ever idle. A teammate at work counts in bgWait as teammates (and in bgAgents); an idle one waits for a message and nothing waits for it. A dynamic workflow (Claude Code's Workflow tool: a script that starts subagents in the background, phase by phase) is a task of kind workflow, its id the task id the launch named; only it carries workflow: the name and description of the script's meta, the toolUseId of the Workflow call (its tool entry in the feed, null when unknown) and its phases in the script's order, each with the agents its journal started in it so far — id (names the agent's transcript), label, status (never idle; one left at work by a run that ended is stopped), startedAt, endedAt, model, last (its last step) and result (the first words of what it returned), the unknown ones null. It is running until its task notification or its final state says how it ended, listed as long as an ended subagent would be, and one at work counts in bgWait as workflows (and in bgAgents). All of it goes only to a page whose socket address names the cap (/api/v2/socket?caps=workflows, a comma list; not in hello, which an older runtime would refuse): to any other page a workflow's background_upsert is a background_removed of its id (same seq), a snapshot leaves workflow tasks out, and bgWait.workflows is taken out of bgAgents. A chat whose prompt is free but waits for any of it is still at work; the sidebar, the rail and the top tab draw it so and say what it waits for, and it becomes finished (and unread, with a notification) only when all of it is over.

  20. Reordering the queue. queue.move {opId, conversationId, clientId, beforeClientId} puts the queued message clientId right before the queued message beforeClientId (null: at the end of the line). The effect shows as a queue_changed on conv:<id> (the new items order, rev up) and the messages' positions that follow; the answer is accepted. Only a queued message moves: one being typed, waiting in the agent's input or past that is refused{too-late}, an unknown clientId is refused{not-found}. The order keeps what the line always had: the messages sent «now» or into the turn stand ahead of the ones that merely wait, so a place that would put a message across them, or before a message that has left the line meanwhile, is refused{conflict}; a move that changes nothing is accepted at once. A runtime that has the command announces the feature queue-move in hello; the page draws no drag handle without it.

  21. Machine health. machine.health (absent where a source does not judge it, as a gateway's own record) is the machine's verdict on its load: {level, since, issues}, level one of ok, warn, critical and the worst of issues, since the epoch ms it came to that level, issues [{metric, level}] with metric one of disk, mem, cpu and level warn or critical, worst first and then in that order (empty when ok). The runtime judges it every 5 s (internal/machines/health.go, one table of lines): disk of the data folder warn under 10 % or 10 GiB free, critical under 5 % or 3 GiB; memory (MemAvailable) warn from 85 %, critical from 95 %, or a swap-in of 50 / 500 pages a second; CPU warn only, busy 90 % over the last two minutes, never one sample. A level is left only past a margin (disk 20 % above the line, memory 3 points below, swap-in at half, CPU under 80 %). A change goes out as a machine_status carrying health to every subscriber of the machine channel, with load or without: the page holds the channel of every machine (without load, the open one with it) so the other machines' dots are live. A machine_status without health leaves the health the page holds. The page draws what the runtime said and keeps no lines of its own: the machine's dot and the header's machine amber or red, a reason under each line of the card past its line, and for critical a banner at the top of the sidebar and a row in the notification centre.

  22. A decision the page could not deliver. An open gate may carry refused (absent otherwise), one of menu-unmatched. The runtime presses an option only when the menu on the agent's screen is the one the person decided on, read by the strict rules of internal/typist/gates.go. When the same call still asks but the screen cannot be matched (an unknown dialog layout, a cut call), no key goes in and the gate opens again with refused: "menu-unmatched". The card then says «decide in the terminal» and offers to open the chat's terminal on the agent's pane. The next state of the gate drops the field. The runtime asks the same of an open tool permission whenever the screen is read, so refused is set as soon as the menu cannot be matched (the card then offers the terminal and no buttons), not only after a press. A dialog too tall for its window has its top off the screen: with no terminal attached the window grows and the dialog is read whole. An open gate may also carry autoDenyAt (epoch ms, absent otherwise): Claude Code 2.1.311 says on the prompt of an unattended session that it denies the request by itself in m:ss, and the card shows that countdown.

  23. Stopping a chat's terminal. terminal.stop {opId, id, force?} ends the conversation's terminal: the agent and everything under its pane get SIGTERM, what stays SIGKILL after 3 s, then the tmux session goes. The conversation and its history stay: the record goes out as a conversation_upsert on convs with state stopped (resumable: true) and terminalStop: {at, by: "person"}, and the answer is accepted from that seq. The next message resumes the agent on its session the way any stopped agent resumes (the resume makes the session again in the tab's folder); once the agent is up again, terminalStop is gone from the record. A terminal that does not run (stopped, gone, launch-failed, starting, or one being stopped) is refused{agent-gone}; a working or asking agent without force: true is refused{agent-working}; a session the runtime does not own (the one it runs in itself, one of no tab) and a conversation with no agent session to resume on are refused{unsupported}; a stop that failed is refused{internal} and the agent keeps running. A runtime that has the command announces terminal-stop in hello; the page offers «Завершить терминал» only then.

  24. Idle terminals stop by themselves. Every 5 minutes the runtime looks at its chats and stops the terminal of one that stood idle for the whole window, as terminal.stop does, with terminalStop: {at, by: "idle", idleMs}. Idle is every one of these at every look of the window: the agent at its prompt (idle, ready) with no gate, nothing queued, typed or waiting to be applied; no background work (bgAgents, a running background task, a scheduled wakeup); nobody holding conv:<id> or attached to the pane; nothing in the pane's process tree but the agent, its helpers (what it started outside a tool shell: MCP servers, the status line) and shells — a tool shell of the agent (Claude's -c … shell-snapshots … eval, Codex's bash -lc) or any other process in the pane is work; the tree's processor time under 2 % of a core for the helpers and 5 % for the agent between two looks; the agent's screen the same (digits aside); no activity on the record (a prompt, a turn's end, the state's change, a read) after the window began. Any of them failing starts the window again. The window is GET /api/v2/runtime-settings {idleStop: "off" | "1h" | "2h" | "6h"} (2h until set), changed by PUT of the same object and kept in <data>/v2/runtime-settings.json; a bad value is 400 bad-request. The runtime logs each stop with the conversation, how long it stood idle and the memory freed.

  25. Naming a chat anew. conversation.retitle {opId, id} asks the cheap model of the chat's agent to name it again from its first message and the agent's latest answer. The answer comes when the title is made (the record's title, titleSource: "agent", replaces even a title the person typed: they asked); a title that takes longer than 8 s is answered accepted all the same and arrives with the record when it is made. A title that could not be made is refused{internal}; a chat already being named is refused{conflict}, one with no answer of the agent yet refused{bad-request}.

  26. One prompt, several models. conversation.create may carry worktree: true and launch {id, prompt}. launch marks the conversation as one of those a prompt started on different models (the same id and prompt, at most 200 characters, on each; it shows on the record as launch). worktree starts it in a git worktree of its own: the runtime adds <repo>/.worktrees/<name> on a new branch agent/<name> off the HEAD of the repository the folder is in (kept out of git status by the repository's exclude file) and the record's cwd is the matching folder in it. A folder that is no repository, or has no commit yet, is used as it is; a worktree that could not be made is refused{internal}.

  27. Forks, handoffs and merges. Features fork and handoff. conversation.fork {opId, id, atTurn?} opens a new conversation that branches off after a finished turn (atTurn, the last finished one when absent; a live turn is refused agent-working, an unknown one not-found). Claude forks its own session: the runtime copies the transcript up to the cut under a new session id and resumes the copy, so the new chat has the history up to there. Codex forks with its CLI, which takes the whole session: at the last turn of an agent at rest; anywhere else the fork starts with an excerpt up to the turn as its first message. conversation.handoff {opId, id, provider, model, mode: "excerpt" | "note", text} opens a conversation on another agent or model in the same folder and project whose first message is text (at most 90 000 characters), the context the person approved. Both answer accepted on convs with the new id; the source is not changed. The new record carries origin {k: "fork" | "handoff", fromId, fromTitle, fromProvider, fromModel, atTurn?, via: "session" | "excerpt" | "note", at}. conversation.merge {opId, id, text} sends a fork's result into the queue of the conversation it came from, as a queued message on that conversation's channel; its result's id is that conversation (unsupported for a conversation with no origin). The texts travel in blocks the page draws as cards: a handoff's first message is <handoff from title agent model mode [kind="fork"]> with instructions for the agent and the text, a merge is <fork-result from title agent>. POST /conversations/{id}/handoff-draft {mode: "excerpt" | "note" | "result", provider?, model?} answers {mode, text, tokens, turns}: an excerpt (the first request, the newest turns whole, the results of key commands, within 16k tokens and a quarter of the target model's window, no reasoning, tool state or attachments), or a note the agent writes from a throwaway fork of its session with no tools that change anything (Claude through the side chat's fork, Codex by codex exec fork --ephemeral read-only); result is a fork's note for its merge. A note takes up to 3 minutes; one is written at a time per conversation (conflict).

  28. Held on the usage limit, going on at the reset. A turn whose last line is the agent's notice of its plan's usage limit — Claude's refusal (error: "rate_limit", the reset in quotaLimits.resetsAt; the words «You've hit your session limit · resets 11:50pm (UTC)» when it has none), Codex's «You've hit your usage limit … try again at 6:05 PM» in its transcript or, the last thing above its composer, on its screen — ends failed{rate-limit} with retryAt the reset, and the record gets limited: {provider, window: "session" | "weekly" | "other", at, resetsAt, continueAt}. resetsAt is the reset the notice names, else the one of the provider's exhausted window in the limits it last reported, else null. The queue is paused limited; its messages have no term while it is (they were sent for after the reset). At continueAt — resetsAt and 22–90 s of the conversation's own jitter, at least 5 min from the hold when resetsAt was already past — the hold ends and the work goes on: the head of the queue if the person queued something, else the runtime's own message «Продолжай с того места, где остановился» (auto: "limit" on the message); either is noted in autoContinues: [{at, why: "limit", clientId, own?}] (the last 20; own when the message was the runtime's). continueAt is null when the runtime will not go on by itself: the runtime setting limitContinue is off, no reset time is known, or the person said no; such a hold ends quietly at resetsAt and the jitter's end, and what was queued goes then. limit {opId, id, action} decides: now goes on at once (the queue's head, else the same words as the person's own message, not auto, and no autoContinues entry), cancel drops continueAt, auto sets it again; a conversation not held is refused{not-found}. queue.resume of a queue paused limited is limit now. A new turn the agent takes by itself (the person typed into its terminal) ends the hold. The record and the pause outlive a restart.

  29. A restart that cut a turn short. A conversation that was working when the runtime went down and whose agent is not running when it comes back (no tmux session, or a shell in the pane) gets the runtime's message «Продолжай — работа была прервана перезапуском» (auto: "restart") once, noted in autoContinues with why: "restart", own. The queue brings the agent back the usual way: a stopped one is resumed on its session; a lost terminal waits for the startup's resume of the tabs that were at work, and after 45 s without it the conversation resumes its agent itself. An agent still running (tmux outlived the runtime) and a conversation that was not at work are left as they are. The runtime setting restartContinue: "off" turns it off. Both switches are in GET/PUT /api/v2/runtime-settings ("on" until set; a PUT that leaves one out keeps it). A runtime that does all this announces auto-continue.

  30. Delegated chats. conversation.create may carry parentId (a conversation of this machine; an unknown one is refused{not_found}) and title (at most 200 characters, the name from the start): an agent's delegate_task starts a chat so, and the record carries parentId for as long as it lives. RuntimeSettings.delegation {maxChildren 1–10, anyChat, delivery?} bounds what agents may delegate (delivery: step, the default — an agent's message goes into the running turn of the chat it is sent to — or turn, after that turn); a PUT without it keeps the saved one. Both go only to a page that names the cap (/api/v2/socket?caps=delegation, and ?caps=delegation on /api/v2/runtime-settings): any other page gets the record without parentId (an event's older form is encoded with the same seq) and the settings without delegation.

  31. Backend profiles (Kimi, GLM, Grok). A profile is another vendor's models behind one of the agent CLIs, not a new Provider: a Kimi or GLM chat is provider: claude, a Grok chat provider: codex. A profile id is ^[a-z][a-z0-9-]{0,31}$ and the runtime owns the list. conversation.create and conversation.handoff may carry profile beside model (a model of the profile; model.profile in a command is refused), and the record carries model.profile for as long as it lives; it cannot be changed in a chat (a handoff starts another one). MachineAgent.profiles lists {id, label, vendor, configured, models} under the CLI the profile runs through; a page draws only the configured ones. All of it goes only to a page that names the cap (/api/v2/socket?caps=profiles, and ?caps=profiles on /api/v2/machines): any other page gets the agents without profiles and the models without profile (an event's older form is encoded with the same seq, a snapshot is cut the same way). The Settings screen reads and writes the keys over HTTP, same origin only for a write: GET /api/v2/providers → {profiles: [{id, label, vendor, via, host, hint, key: {configured, tail}, models}]} (every preset of the runtime); PUT /api/v2/providers/<id>/key {key} → {configured, tail} (the key is 8–512 printable characters without a space); DELETE /api/v2/providers/<id>/key → {configured: false, tail: null}; POST /api/v2/providers/<id>/test → {ok, reason, status, ms}, one minimal request to the vendor with the saved key. An unknown id is not-found, a bad key bad-request. The key never comes back: tail is «…» and its last four characters. The key is not logged, not on the wire and not in a tab's metadata.

  32. A message does not hang. A typed message (not steered, not carried by a launch) that the agent has not taken within ConfirmDeadline (30 s) — no prompt-submit, no transcript entry — is not failed: the transcript is asked once more, and without its entry the message goes back to the head of the queue as queued{position: 1, reason: "stalled", wait: null}. Its text is taken out of the agent's input box at the next look (a late Enter must not send it behind the person's back), it is never typed again by itself, and the messages behind it wait: something beyond this message is wrong. retry types it again (attempts+1, the transcript asked first), promote does the same at its new place, cancel drops it; an entry with its text read later accepts it. A steered message is Claude's to read at its next step and keeps its 30 min. A message left typing 30 s with no try on its way stalls the same way. The stall goes only to a page that names the cap (/api/v2/socket?caps=msgstatus, and ?caps=msgstatus on the status page): any other page gets the same rev as failed{unconfirmed, retryable: true, at} and a queue without its id. GET /api/v2/conversations/{id}/messages?ids=a,b (1–20 client ids, none twice) answers {messages: [...]}, one per id in order: {clientId, k: "known", message, handed?: {at, where, entryId}} — where is input-box (typed, not taken), agent-queue (a steer in the agent's own queue), agent (its hook took it), transcript (entryId), and handed is absent for a message not typed (queued, failed, cancelled); {clientId, k: "unknown"} for an id the runtime never had; {clientId, k: "expired", at} for one whose record it let go (after a day; the ids are kept 7 days, at most 500 a conversation). A send with an id the runtime still has is accepted with its whole record again (message_upsert), so a page that lost the events takes the true state; one of an expired id is refused{too-late} — it was delivered, and is never typed twice.

  33. Signing an agent in from the page. The CLI does the signing in; the runtime drives it through a terminal of its own, and the page sees the vendor's link, the one-time code of a device flow and a state, nothing else the CLI prints. POST /api/v2/agents/{claude|codex}/login {mode} (subscription or console for Claude, device for Codex) starts a flow and answers {flow}: {id, provider, mode, state, input, url, userCode, startedAt, expiresAt, reason}. States: starting (no link yet), awaiting (url is out; input: "code" means paste the code the vendor's site showed, "none" that the person finishes there), checking (the code went to the CLI), then the end: done, failed (with a reason: not-installed, start-failed, code-rejected, refused, timeout), cancelled, expired. GET .../login answers the last flow ({flow: null} if none), POST .../login/code {id, code} hands the code to that flow (a stale id is conflict), DELETE .../login cancels. One flow a CLI at a time (conflict for a second start); starts are limited (rate-limited). PUT /api/v2/agents/codex/key {key} gives the CLI an API key on its standard input, POST .../logout signs it out; both answer {ok: true}. A page reads who is signed in from GET /api/v2/agent-settings/{provider} (account), as before. Writes are same-origin only; no answer carries a code or a key, and the code and the key are not logged. Claude takes no API key this way: console is its sign-in for API billing.

  34. What the chat made. GET /api/v2/conversations/{id}/made answers {items, complete}: the docs, boards and designs the chat made, opened or changed, newest first, at most 60. An item is {kind: doc|board|design, ref, title, op: created|changed, at, cover, designKind}; ref is the page's URL for a doc or a board (a board keeps its ?k= key, which opens it: never draw it) and the design's id for a design; title is "" when unknown; cover and designKind are null unless the item is a design. Designs are only those the person may see. complete: false means the runtime is still reading a long transcript: ask again soon. An unknown conversation is refused{not-found}. A runtime that serves it announces made; without it the route is a 404. Tracker tasks are only sent to a page that asks with ?tasks=1 (a page that does not know the kind is never shown it): {kind: task, ref: the task's URL, title, task: {key, type, state, resolved, parent, children}}, the chat's tracker calls (create, update, comment, read of one task) read with the person's own token. title and task are from the tracker and left off when it could not be read; type is Epic for an epic, whose subtasks are children (at most 50), a task's epic is parent. A page leaves out a kind it does not know.

  35. The agent's hand on the pane's browser. GET /api/v2/pane-act?conversation=<chat> is the page's long poll: it answers 200 with one action {id, op, ref, element, text, key, value, url, dy, ms, submit} (every field present; op one of snapshot, click, type, press, hover, select, scroll, wait, navigate, back) or 204 after 25 s with nothing. While a poll is open, and for 35 s after the last one ended, the chat's page counts as present; without a present page the agent's browser_* tools fail at once. At most 4 polls are open per chat (the fifth is a 429); an action goes to one poll, and waits for the next one when the page is between two. POST /api/v2/pane-act {conversation, id, state: done|failed|asking, text} (body ≤ 96 KiB, text ≤ 64 KiB) answers 204, 404 for an id that is not the chat's action in flight, 400 for a bad body. asking (the person is being asked) settles nothing and extends the agent's wait to 120 s from now; done and failed end the action with text. A chat has one action in flight, and at most 120 a minute. Both are same-origin only. A runtime that serves it leaves PaneAct set; without it the route is a 404.

  36. A chat that is not saved. The runtime writes a conversation to its disk after every change. When the write fails several times in a row (a full or read-only disk), the record carries notSavedSince (epoch ms) and goes out as a conversation_upsert on convs: the messages the person sends are held in memory only, and a restart of the runtime would lose them. The runtime goes on trying with a pause that grows; the first write that succeeds takes the field off the record. The field is never written to the disk itself.

  37. One agent state for both channels. A conversation's agent state changes in one place of the runtime, and every change takes the record's next rev. convs names it as before (conversation_state, or the record itself). conv:<id> carries it too, as agent: {state, rev, epoch}: on queue_changed at every change (the channel has no event of its own for the state, and a page that does not read the field takes the event as the queue it holds) and on the snapshot. rev is the record's revision the state stands at and epoch the runtime's, so the two channels count alike: within an epoch the page keeps the state of the higher rev, whichever channel brought it, and a stamp of another epoch than the welcome's is not applied. A stamp never moves the rev the page holds the record at: the record's other fields come only by convs. A runtime that sends no agent is read as before.

  38. What the right pane reads of a chat. The tools of the page's right pane (links and documents, the files and pictures the chat worked with, its words with other agents, its subagents) read pane, which the runtime gathers from the same read of the transcript that makes the feed; the page opens no other socket on the conversation for them. A conv:<id> snapshot carries pane: {count, links, items} whole: the links of the agent's answers in what the feed has read, newest first (at most 200; {url, label, at, count, kind}, kind as the pane names links: artifact, claude-artifact, mr, issue, gitlab, github, web), and the newest items, oldest first (at most 128, fewer when they weigh more than 48 KiB). An item is a line of the transcript with only what a tool of the pane reads: {id, k, at} and, by k: tool (a call that names a file, runs a shell command, sends files, writes to another agent or starts a subagent: tool, use, path, text its one-line summary, files, peer {to, text}), result (the result of a subagent's call: use), notice (a background task's notice), user (a message with pictures, images, or other agents' words or uploads in its text), answer (an answer that embeds pictures: text is its Markdown), patch (files) and exec (text the command, cwd). A text is cut at 16 KiB. A picture the transcript carries whole (data:) is not sent. After the snapshot, what a read added rides queue_changed as pane: {count, reset?, links?, items?} beside the queue as it is (the channel has no event of its own for it, and a page that does not read the field takes the event as the queue it holds, as with agent): items go after the ones the page holds, links (only when the list changed) take the place of its list, and reset: true (the transcript was read anew, or one read made more items than a snapshot holds) puts links and items in the place of everything it holds. count is how many lines the read has taken so far and moves with every read that found something: the page takes it as «the chat moved» for what it asks elsewhere. A conversation starts gathering when a page first asks for its snapshot. A runtime that does not gather it (an older one, or RUNTIME_PANE_FEED=0) sends no pane; only then does the page read the conversation for its pane by itself, over the Legacy timeline socket. No feature names it: a snapshot with pane is the sign.

  39. Tasks and commits among what a turn made. Turn.outputs may hold {kind: task} (a task of the tracker the agent showed: harnessly open HRN-1 or the task's address; ref is the task's address, title its key) and {kind: commit} (a commit of GitLab or GitHub; ref its address, title «project sha»). Only a page that names the cap (?caps=links on the socket and on GET …/turns) gets them: any other page gets the turn without them. The card's live title and state come from GET /api/platform/link-meta?url=, which reads, besides a task and a merge request (now with pipeline: {status, url} when it has one), a commit ({kind: commit, title, sha, project, pipeline}) and a feature stand under the stands' domain ({kind: stand, up, title}: a redirect to a sign-in is up, no answer or a 5xx is down). Which addresses are stands, the tracker, GitLab, documents and boards is the organization's word when the hub sends it (env.set links, hubproto.LinkSettings), the machine's environment otherwise.

  40. The pictures a turn drew. Turn.pictures lists the paths of the pictures the turn drew (generate_images, wait_images, Codex's image tool), oldest first, at most 24. The page shows them under the answer, so a folded turn still shows what it drew; the steps keep their cards for the unfolded view. A page that does not know the field drops it.

Documentation

Overview

Package wire is the v2 contract between a runtime and its pages: the data model, the socket frames and events, the commands of POST /api/v2/cmd/<op> and their results. schema/frames.json is the source of truth; these types and web/app/next/protocol/v2.ts mirror it, and the fixtures in testdata keep the three in step.

Times in *At fields are unix milliseconds by the machine's clock. A union with a few fields (AgentState, MessageState, GateState, Entry) is one flat struct whose JSON carries exactly the fields of its kind; a union of frames, events or commands is an interface over one struct per kind.

Index

Constants

View Source
const (
	MaxAgentRules        = 200
	MaxAgentRuleLen      = 300
	MaxAgentEnvValueLen  = 2000
	MaxAgentEnvVars      = 100
	MaxAgentSettingsBody = 128 << 10
)

Limits of the agent settings a page may write.

View Source
const (
	OpsKeep = 24 * time.Hour
	OpsMax  = 5000
)

The answers of opIds are kept OpsKeep, at most OpsMax of them (§3, §4.5).

View Source
const (
	ContextWindow     = 200_000
	ContextWindowLong = 1_000_000
)

The agent's window: Claude's usual one, and the long one ([1m]) a model may run with.

View Source
const (
	DesignTitleMax  = 200
	DesignBriefMax  = 20000
	DesignSystemMax = 200
	DesignlyBodyMax = 256 << 10
	DesignBoardsMax = 200
	// DesignPeopleMax is the most people a project names (DesignArtifact.People).
	DesignPeopleMax = 20
)

The bounds of what a person writes for a new project.

View Source
const (
	DesignDeckMinutesMin = 1
	DesignDeckMinutesMax = 180
	DesignDeckSlidesMin  = 2
	DesignDeckSlidesMax  = 40
	DesignDeckLayoutsMax = 200
	DesignDeckVarsMax    = 32
	DesignDeckVarMax     = 64
	DesignAttachmentsMax = 20
)

The bounds of a new deck's settings and of what a new project's first message carries.

View Source
const (
	DesignVideoSecondsMin = 15
	DesignVideoSecondsMax = 300
)

The bounds of a new video's settings.

View Source
const (
	LoginCodeMin = 8
	LoginCodeMax = 512
	// MaxLoginBody is the largest body of a sign-in route.
	MaxLoginBody = 2 << 10
)

The bounds of a code a page may submit: what the vendors' codes are made of (letters, digits and `-_#.~`).

View Source
const (
	NoticeColorContrast = "contrast"
	NoticeColorTheme    = "theme"
)

The colours of what pops up (PersonSettings.NoticeColor).

View Source
const (
	VoiceMascotH    = "h"
	VoiceMascotFace = "face"
)

The voice agent's heads (PersonSettings.VoiceMascot).

View Source
const (
	VoiceEngineLocal   = "local"
	VoiceEngineChatGPT = "chatgpt"
	VoiceEngineOpenAI  = "openai"
	VoiceEngineYandex  = "yandex"
)

VoiceEngines are the recognition models a person may pick for dictation: the machine's own, the ChatGPT plan's, OpenAI's, Yandex's.

View Source
const (
	MaxVoiceWords   = 200
	MaxVoiceWordLen = 64
	MaxVoiceHeard   = 10
)

Limits of the dictionary.

View Source
const (
	MaxQuickPrompts   = 50
	MaxQuickPromptLen = 2000
	MaxNotifyTypes    = 32
	MaxKeyActions     = 200
	MaxKeysPerAction  = 8
	MaxSettingsBody   = 128 << 10
	// DefaultDayStartHour: the day starts at 03:00 in Moscow, 00:00 UTC.
	DefaultDayStartHour = 3
)

Limits of the settings a page may write.

View Source
const (
	OpenReasonConnect = "connect"
	OpenReasonEmbed   = "embed"
)

The reasons of an OpenLink.

View Source
const (
	OpenRefsMax    = 32
	OpenChoicesMax = 8
)

OpenRefsMax is the most refs one GET .../open-refs may ask about; OpenChoicesMax the most candidates one ref gets.

View Source
const (
	ConvsBudget = 72 << 10 // was 64: lastPromptAt is 30 B a record
	ConvBudget  = 256 << 10
)

The budgets of the snapshots (§2), in bytes of raw JSON: a convs snapshot ConvsBudget per 100 conversations (never less than that), a conv snapshot ConvBudget.

View Source
const (
	ProfileKeyMin = 8
	ProfileKeyMax = 512
	// MaxProfileKeyBody is the largest PUT .../key body.
	MaxProfileKeyBody = 2 << 10
)

The bounds of a key a page may save.

View Source
const (
	RingSize = 2000
	RingAge  = 5 * time.Minute
)

The ring of a channel keeps its last events for a page that comes back: RingSize of them, none older than RingAge. A sub whose afterSeq is still in the ring gets the events it missed; past that it gets a snapshot.

View Source
const (
	SearchQueryMax   = 200
	SearchLimitMax   = 100
	SearchLimitUsual = 40
)

The query of a search: at least two letters, at most 200 bytes; a page asks for up to SearchLimitMax hits.

View Source
const (
	DigestBudgetMax   = 60000
	DigestBudgetUsual = 18000
)

DigestBudgetMax is the largest budget a page may ask for, in characters; DigestBudgetUsual is what it gets without.

View Source
const (
	SettingsDocMe      = "me"               // GET me, PATCH me/settings
	SettingsDocRuntime = "runtime-settings" // GET, PUT
	SettingsDocAgent   = "agent-settings"   // GET, PUT agent-settings/<provider>
)

The documents of settings a page reads and writes under /api/v2.

View Source
const (
	PingEvery   = 15 * time.Second
	StaleAfter  = 20 * time.Second
	SocketIdle  = 90 * time.Second
	HelloWithin = 10 * time.Second
)

The heartbeat (§2): the page pings every 15 s and calls a socket stale after 20 s without a frame; the runtime closes one that sent nothing for SocketIdle, and one that did not say hello within HelloWithin.

A browser stretches the timers of a hidden tab to a minute, so the page's own ping cannot be what keeps its socket. The runtime beats by itself: every PingEvery it sends a pong nobody asked for (T is BeatT) to a page it has not heard from lately. A page that knows the beat answers it with a ping at once (a frame's handler is not a timer), which is the frame the idle limit waits for; a page that does not is kept by SocketIdle being longer than the minute between its stretched pings, and the beat is the frame that keeps it from calling the socket dead.

View Source
const (
	NoticeSummaryOff  = "off"
	NoticeSummaryAuto = "auto"
)

NoticeSummaryOff as NoticeSummaryModel.Provider turns the summaries off; NoticeSummaryAuto picks the default (a PUT that leaves the field out keeps the old one, so «back to Авто» has to be said).

View Source
const (
	WaitSlowMs     = 3000
	TypingDeadline = 12_000 // typing → in-input, else queued again or failed{type-failed}
	// ConfirmDeadline: in-input → accepted, else the message goes back to the head of the queue, stalled (a steered
	// one, which may sit in Claude's own queue, fails unconfirmed instead).
	ConfirmDeadline = 30_000
	AnswerDeadline  = 10_000 // answering → answered or back to open
	LaunchSlowMs    = 15_000
	LaunchDeadline  = 150_000 // starting → idle, else launch-failed (prompts/rules.go: 150 s without a prompt box)
)

The terms of the waits of the runtime: §12 of the spec asks for "дольше обычного" at 3 s and an error by 10–15 s.

View Source
const (
	PaneItemsMax = 128
	PaneLinksMax = 200
)

PaneItemsMax is how many pane items a snapshot carries (the newest), PaneLinksMax how many links.

View Source
const (
	TurnsPageDefault = 30
	TurnsPageMax     = 100
)

The turns page: limit defaults to TurnsPageDefault; below 1 or above TurnsPageMax it is refused{bad-request}. A page that cannot answer sends a refusal, {r: "refused", code}, as a command does.

View Source
const (
	RefTitleMax  = 200
	RefTargetMax = 4096
)

RefTitleMax and RefTargetMax bound a reference's words, in characters.

View Source
const AutoContinueMax = 20

AutoContinueMax is how many of its own continuations a conversation keeps.

View Source
const BeatT = 0

BeatT is the T of the pong the runtime sends by itself; a page's ping carries its clock, never 0.

View Source
const CancelledByUser = "user"

CancelledByUser is the only author of a cancel.

View Source
const ChatFromMax = 120

ChatFromMax caps each field of a ChatFrom, in runes.

View Source
const DelegationMaxChildren = 10

DelegationMaxChildren is the most a person may let one conversation delegate; DefaultDelegation the setting nobody set.

View Source
const DeviceHeader = "X-Harnessly-Device"

DeviceHeader carries the device id on every HTTP request of the page, as hello does on the socket: the page makes the id once and keeps it in localStorage. It names the device in answered{byDevice}.

View Source
const DraftAttachmentsMax = 20

DraftAttachmentsMax is how many uploaded files a draft holds, as many as a message takes.

View Source
const DraftNew = "new"

DraftNew is the key of the draft of the new-chat field, which has no conversation yet.

View Source
const DraftTextMax = 20000

DraftTextMax is the longest text a draft keeps on the machine, in characters; a longer one stays on its device.

View Source
const DraftsMax = 500

DraftsMax is how many drafts a machine keeps; past that the least recently written go first.

View Source
const FavGroupNameMax = 60

FavGroupNameMax is the longest name of a group in the favorites, in characters.

View Source
const FavGroupsMax = 50

FavGroupsMax is how many groups the favorites hold.

View Source
const FileSaveBodyMax = 6<<20 + 4096

FileSaveBodyMax is the largest body a save may send: a text of 1 MB whose every byte is escaped, and the envelope.

View Source
const FilesPathMax = 4096

FilesPathMax is the longest path a page may ask for, in bytes.

View Source
const GoalTextMax = 2000

GoalTextMax is the longest goal a page may set, in characters.

View Source
const HandoffDraftBudget = 200 * time.Second

HandoffDraftBudget is how long a draft may take: a note is a whole answer of the agent.

View Source
const HandoffTextMax = 90_000

HandoffTextMax is the longest text a handoff or a merge carries, in characters: the message it goes in, with its wrapping, stays under Limits.MaxText.

View Source
const HomeConv = "tab-_home"

HomeConv names no conversation but the machine's own place, its projects' folder: the start page's pane browses its files and opens shells there without a chat. No conversation has it (a conversation's id never starts with "_").

View Source
const LaunchPromptMax = 200

LaunchPromptMax is the longest prompt a launch keeps, in characters.

View Source
const LimitJitterMax = 90 * time.Second

LimitJitterMax is how far past ResetsAt the runtime goes on at most: chats held on one limit do not all start at once.

View Source
const MachineStopBodyMax = 4 << 10

MachineStopBodyMax is the largest body a stop may send.

View Source
const MadeMax = 60

MadeMax is the most items one answer holds.

View Source
const MadeTaskChildrenMax = 50

MadeTaskChildrenMax is the most subtasks of one epic an item carries.

View Source
const MaxConversationApps = 8

MaxConversationApps is how many apps one chat may have on at once.

View Source
const MaxConversationView = 16 << 10

MaxConversationView is the most a chat's kept view may take, in bytes of JSON.

View Source
const MaxLookImage = 3 << 20

MaxLookImage is the largest picture a look takes; a page shrinks a bigger one before it uploads.

View Source
const (
	MaxNavKeys = 100
)

Limits of the menu's layout.

View Source
const MaxPersonHeader = 48 << 10

MaxPersonHeader bounds the header's value; words that do not fit are left out, last first.

View Source
const MaxPrefLen = 32 << 10

Limit of one value of Prefs.

View Source
const MaxProfileSwitchBody = 256

MaxProfileSwitchBody is the largest PUT .../switch body.

View Source
const MaxRuntimeSettingsBody = 4 << 10

MaxRuntimeSettingsBody is the largest PUT /api/v2/runtime-settings body.

View Source
const (
	MaxSubs = 64
)

The socket's own limits: subscriptions per socket, the largest frame from the page, how much may wait unsent before the socket is closed (the page comes back with its cursor), how long one frame may take to write, and the size from which frames are compressed.

View Source
const MessageStatusMax = 20

MessageStatusMax is how many client ids one GET .../messages asks about.

View Source
const ModelLogMax = 20

ModelLogMax is how many applied changes of model a conversation keeps.

View Source
const OpenRefMax = 512

OpenRefMax is the longest ref the page may ask about, in bytes.

View Source
const PersonHeader = "X-Harnessly-Person-Settings"

PersonHeader carries, from a hub to a runtime, the settings of the person a request is made for that the runtime works by (RuntimePerson, as base64 of its JSON). A runtime on its own gets none and reads its file.

View Source
const PicturesMax = 60

PicturesMax is how many pictures named in messages a conversation lists.

View Source
const Prefix = "/api/v2/"

Prefix is the path of the v2 API; the runtime answers it under /agents as well, like the rest of its API.

View Source
const ProjectNameMax = 120

ProjectNameMax is the longest name of a project, in characters.

View Source
const Proto = 2

Proto is the protocol version of this package.

View Source
const RefsMax = 10

RefsMax is how many references one message or draft carries.

View Source
const RewindChangesMax = 50

RewindChangesMax is how many changed files a plan names.

View Source
const RewindUndoMs = 15_000

RewindUndoMs is how long a rewind can be undone.

View Source
const RewindsMax = 10

RewindsMax is how many rewinds a conversation keeps on its record.

View Source
const SeenAll = "all"

SeenAll is the conversation id of a seen for every conversation.

View Source
const SessionsMax = 50

SessionsMax is how many sessions GET /api/v2/sessions offers.

View Source
const ShotsMax = 30

ShotsMax is how many pictures a conversation lists.

View Source
const SnippetMax = 160

SnippetMax is the longest TurnSummary.Snippet, in characters.

View Source
const SwitchTimeout = 3 * time.Minute

SwitchTimeout bounds a PUT .../switch: the first one downloads the proxy.

View Source
const TerminalsMax = 8

TerminalsMax is how many own terminals a conversation may have at once.

View Source
const ToolOutputMax = 4096

ToolOutputMax is how much of a tool's output a snapshot or an event carries, in bytes.

View Source
const TurnPicturesMax = 24

TurnPicturesMax is how many pictures a turn lists, at most.

View Source
const (
	// UploadChunkBytes is the chunk the page is asked to send: well under every proxy's body limit (the ingress
	// takes 50 MB).
	UploadChunkBytes = 8 << 20
)
View Source
const VoiceBodyMax = 20 << 20

VoiceBodyMax is the largest recording POST /api/v2/voice takes, in bytes: some ten minutes of speech in a compressed container.

View Source
const VoiceBudget = 5 * time.Minute

VoiceBudget is how long a recording may take to come and to be recognized: it is recognized piece by piece, some seconds for each quarter of a minute, so a long one takes minutes on a busy machine.

Variables

View Source
var (
	// ErrAgentSettingsConflict: the file changed since the revision the write quotes.
	ErrAgentSettingsConflict = errors.New("wire: the agent settings are at another revision")
	// ErrAgentSettingsRefused: the file cannot take the change (the CLI is not installed, or it does not read).
	ErrAgentSettingsRefused = errors.New("wire: the agent settings cannot take the change")
)

The errors a source answers a write with.

View Source
var (
	// ErrLoginBusy: a flow of that CLI is on.
	ErrLoginBusy = errors.New("wire: a sign-in is on")
	// ErrLoginRate: too many sign-ins were started lately.
	ErrLoginRate = errors.New("wire: too many sign-ins")
	// ErrLoginUnsupported: the CLI does not take that mode or that way of signing in.
	ErrLoginUnsupported = errors.New("wire: the CLI does not sign in that way")
	// ErrLoginStale: the flow is not the one asked for, or is not at a state that takes the code.
	ErrLoginStale = errors.New("wire: not that sign-in")
	// ErrLoginInput: the CLI rejected the input (a key it did not take).
	ErrLoginInput = errors.New("wire: the CLI did not take it")
	// ErrLoginNotInstalled: the CLI is not on the machine.
	ErrLoginNotInstalled = errors.New("wire: the CLI is not installed")
)

Errors a LoginSource answers with.

View Source
var (
	ErrMeConflict = errors.New("wire: the settings are at another revision")
	ErrMeBadPatch = errors.New("wire: not a settings patch")
)
View Source
var (
	IdleStops       = []IdleStop{IdleStopOff, IdleStop1h, IdleStop2h, IdleStop6h}
	DefaultIdleStop = IdleStop2h
)

IdleStops is every IdleStop, in the schema's order; DefaultIdleStop is the one of a runtime nobody set.

AgentAccountMethods is every AgentAccountMethod, in the schema's order.

AgentInstallStatuses is every AgentInstallStatus, in the schema's order.

View Source
var AgentMcpKinds = []AgentMcpKind{McpStdio, McpHTTP}

AgentMcpKinds is every AgentMcpKind, in the schema's order.

AgentOptionKeys is every AgentOptionKey, in the schema's order.

AgentStateKinds is every AgentStateKind, in the schema's order.

View Source
var AllCaps = Caps{Delegation: true, Workflows: true, Profiles: true, MsgStatus: true, Links: true}

AllCaps reads every optional part.

AppFlags is every AppFlag, in the schema's order.

AppIDs is every AppID, in the schema's order (the order of the apps in the list).

AppPipelines is every AppPipeline, in the schema's order.

AppReasons is every AppReason, in the schema's order.

AppRoles is every AppRole, in the schema's order.

AppSectionIDs is every AppSectionID, in the schema's order.

AppStates is every AppState, in the schema's order.

View Source
var AppTones = []AppTone{ToneAccent, ToneWarn}

AppTones is every AppTone, in the schema's order.

AttachmentKinds is every AttachmentKind, in the schema's order.

AutoContinueWhys is every AutoContinueWhy, in the schema's order.

BackgroundKinds is every BackgroundKind, in the schema's order.

BackgroundStatuses is every BackgroundStatus, in the schema's order.

ClientFrameKinds is every ClientFrameKind, in the schema's order.

CompactionPhases is every CompactionPhase, in the schema's order.

ConvEventTypes is every ConvEventType, in the schema's order.

ConvsEventTypes is every ConvsEventType, in the schema's order.

View Source
var DefaultDelegation = DelegationSettings{MaxChildren: 5}
View Source
var DefaultLimits = Limits{
	MaxQueue: 20, MaxText: 100_000, MaxAttachments: 20, MaxImageBytes: 10 << 20, MaxFileBytes: 0,
	SlowMs: 3000, CmdBudgetMs: 10_000, CmdTimeoutMs: 12_000,
}

DefaultLimits are the limits of prompts.MaxQueuedPerTab, prompts.MaxQueuedText and the mockup's file sizes.

DelegationDeliveries is every DelegationDelivery, in the schema's order.

View Source
var DesignDeckTones = []DesignDeckTone{"talk", "biz", "short"}

DesignDeckTones is every DesignDeckTone, in the schema's order.

DesignKinds is every DesignKind, in the schema's order.

View Source
var DesignRoles = []DesignRole{"view", "comment", "edit", "manage", "owner"}

DesignRoles is every DesignRole, in the schema's order.

View Source
var DesignVideoFormats = []DesignVideoFormat{"16:9", "9:16"}

DesignVideoFormats is every DesignVideoFormat, in the schema's order.

DiskPartIDs is every DiskPartID, in the schema's order (the order the parts are drawn).

DraftModes is every DraftMode, in the schema's order.

Efforts is every Effort, in the schema's order.

EntryKinds is every EntryKind, in the schema's order.

View Source
var ErrDraftBusy = errors.New("a note of this conversation is being written already")

ErrDraftBusy: a note of the conversation is being written already; one is written at a time.

View Source
var ErrDraftUnsupported = errors.New("no draft can be made of this conversation")

ErrDraftUnsupported: the conversation has nothing a draft can be made of yet (no transcript, no agent session), or its agent cannot write the note.

View Source
var ErrNoShot = errors.New("no such shot")

ErrNoShot is what Server.Shot answers for an id the conversation does not list, and for a listed picture that cannot be sent (gone, too big, not a picture).

View Source
var ErrNoTab = errors.New("no legacy tab yet")

ErrNoTab is what Server.Legacy answers for a conversation that has no tmux session yet: it is there, its tab is not.

View Source
var ErrNothingToOpen = errors.New("nothing to open")

ErrNothingToOpen: the ref is neither a task, a merge request, a document nor a site; the page opens nothing.

View Source
var ErrProfileUnknown = errors.New("wire: no such profile")

ErrProfileUnknown: the runtime has no profile of that id.

View Source
var ErrTerminalLimit = errors.New("wire: the conversation has too many terminals")

ErrTerminalLimit is a conversation that already has TerminalsMax own terminals.

View Source
var ErrVoiceUnavailable = errors.New("voice: not available on this machine")

ErrVoiceUnavailable is a machine that cannot recognize speech right now (no decoder, no recognition service); the page is told unsupported. Any other error of Server.Voice is a recording that failed: internal.

Features is every Feature, in the schema's order.

FileChanges is every FileChange, in the schema's order.

FileGits is every FileGit, in the schema's order.

FileKinds is every FileKind, in the schema's order.

FileOps is every FileOp, in the schema's order.

View Source
var Fixtures embed.FS

Fixtures are the shared fixtures of testdata, for the fake runtime (wirefake) a page's end-to-end tests run on.

FrameErrorCodes is every FrameErrorCode, in the schema's order.

GateCloseReasons is every GateCloseReason, in the schema's order.

GateKinds is every GateKind, in the schema's order.

GateRefusals is every GateRefusal, in the schema's order.

GateStateKinds is every GateStateKind, in the schema's order.

GoalStatuses is every GoalStatus, in the schema's order.

GoneReasons is every GoneReason, in the schema's order.

HandedWheres is every HandedWhere, in the schema's order.

HandoffModes is every HandoffMode, in the schema's order.

HealthLevels is every HealthLevel, in the schema's order (worse later).

HealthMetrics is every HealthMetric, in the schema's order.

View Source
var ImageGenStates = []string{"drawing", "done", "failed"}

ImageGenStates are the states of a picture call.

LaunchFailures is every LaunchFailure, in the schema's order.

LaunchSteps is every LaunchStep, in the schema's order.

LimitActions is every LimitAction, in the schema's order.

LimitWindows is every LimitWindow, in the schema's order.

LoginInputs is every LoginInput, in the schema's order.

LoginModes is every LoginMode, in the schema's order.

LoginReasons is every LoginReason, in the schema's order.

LoginStates is every LoginState, in the schema's order.

View Source
var MachineEventTypes = []EventType{EvMachineStatus, EvMachineLoad}

MachineEventTypes is every MachineEventType, in the schema's order.

MachineProcKinds is every MachineProcKind, in the schema's order.

MachineStopReasons is every MachineStopReason, in the schema's order.

MadeFromKinds is every MadeFromKind, in the schema's order.

MadeKinds is every MadeKind, in the schema's order.

MessageFailures is every MessageFailure, in the schema's order.

MessageKinds is every MessageKind, in the schema's order.

MessageModes is every MessageMode, in the schema's order.

MessageRoles is every MessageRole, in the schema's order.

MessageStateKinds is every MessageStateKind, in the schema's order.

MessageStatusKinds is every MessageStatusKind, in the schema's order.

NoticeLevels is every NoticeLevel, in the schema's order.

View Source
var OnOffs = []OnOff{On, Off}

OnOffs is every OnOff, in the schema's order.

OpenReasons is every reason of an OpenLink, in the schema's order.

OpenTabs is every OpenTab, in the schema's order.

Ops is every Op, in the schema's order.

OriginKinds is every OriginKind, in the schema's order.

OriginVias is every OriginVia, in the schema's order.

OutputKinds is every OutputKind, in the schema's order.

OutputOps is every OutputOp, in the schema's order.

PauseReasons is every PauseReason, in the schema's order.

PeerNoteKinds is every PeerNoteKind, in the schema's order.

PermissionKinds is every PermissionKind, in the schema's order.

PermissionModes are the modes in the picker's order.

PermissionScopes is every PermissionScope, in the schema's order.

View Source
var PrefKeys = []string{
	"hl-theme", "hl-palette", "hl:beta", "hl:feed-kinds", "hl:pane-auto-open", "hl:browser-agent",
	"hx-show-test-chats", "voice.lang", "hx-next-new-chat-choice", "hx.next.quickPrompts", "hx-top-tabs",
	"hx-looks",
	"hx-widgets",
}

PrefKeys are the choices Prefs may hold: the browser's storage key of each (voice.lang is the dictation's language out of the voice's record, whose microphone stays the device's).

ProfileSwitchReasons is every ProfileSwitchReason, in the schema's order.

ProfileTestReasons is every ProfileTestReason, in the schema's order.

ProfileVendors is every ProfileVendor, in the schema's order.

PromoteTos is every PromoteTo, in the schema's order.

Providers is every Provider, in the schema's order.

QueueReasons is every QueueReason, in the schema's order.

Reaches is every Reach, in the schema's order.

RefKinds is every RefKind, in the schema's order.

RefuseCodes is every RefuseCode, in the schema's order.

ResultKinds is every ResultKind, in the schema's order.

RetryableRefuseCodes are the refusals a retry of the same command can turn into a success: the page offers "Повторить" for them and only "Отменить" for the rest.

View Source
var (

	// SecretName is an environment variable whose value is shown by its tail only.
	SecretName = regexp.MustCompile(`KEY|TOKEN|SECRET|PASS`)
)

ServerFrameKinds is every ServerFrameKind, in the schema's order.

View Source
var Settings = []Setting{
	{Doc: SettingsDocMe, Key: "uiVersion", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "locale", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "density", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "textSize", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "noticeColor", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "voiceMascot", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "enterSends", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "defaultMachine", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "notify", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "quickPrompts", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "keys", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "voice", Owner: OwnerPerson, Runtime: true},
	{Doc: SettingsDocMe, Key: "dayStartHour", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "nav", Owner: OwnerPerson},
	{Doc: SettingsDocMe, Key: "prefs", Owner: OwnerPerson},

	{Doc: SettingsDocRuntime, Key: "idleStop", Owner: OwnerMachine},
	{Doc: SettingsDocRuntime, Key: "limitContinue", Owner: OwnerMachine},
	{Doc: SettingsDocRuntime, Key: "restartContinue", Owner: OwnerMachine},
	{Doc: SettingsDocRuntime, Key: "delegation", Owner: OwnerMachine},
	{Doc: SettingsDocRuntime, Key: "noticeSummary", Owner: OwnerMachine},

	{Doc: SettingsDocAgent, Key: "provider", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "path", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "rev", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "account", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "options", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "rules", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "env", Owner: OwnerMachine},
	{Doc: SettingsDocAgent, Key: "mcp", Owner: OwnerMachine},
}

Settings is every setting and its owner: the one table the hub and the runtime go by. A key of a settings document that is not here fails the tests.

SnapshotModes is every SnapshotMode, in the schema's order.

SubagentStatuses is every SubagentStatus, in the schema's order.

TaskStatuses is every TaskStatus, in the schema's order.

TerminalAsides is every TerminalAside, in the schema's order.

View Source
var TerminalFailureKinds = []TerminalFailureKind{FailureQuotaExhausted}

TerminalFailureKinds is every TerminalFailureKind, in the schema's order.

TerminalStopBys is every TerminalStopBy, in the schema's order.

TitleSources is every TitleSource, in the schema's order.

TurnFailureCodes is every TurnFailureCode, in the schema's order.

TurnStatuses is every TurnStatus, in the schema's order.

VoiceEngines is every recognition model, in the order Settings lists them.

View Source
var VoiceLangs = []string{"ru", "en", "auto"}

VoiceLangs are the languages a recording may be recognized in; "" is ru.

Functions

func ClaudeEntryID

func ClaudeEntryID(lineUUID string, k int) string

ClaudeEntryID is the id of entry k of a Claude transcript line.

func ConvsBudgetFor

func ConvsBudgetFor(n int) int

ConvsBudgetFor is the budget of a convs snapshot of n conversations.

func EncodePersonHeader

func EncodePersonHeader(p RuntimePerson) string

EncodePersonHeader is the header's value for the settings, within MaxPersonHeader.

func Fingerprint

func Fingerprint(cmd Command) string

Fingerprint is what tells two bodies of one opId apart: the op and the command as it was read.

func LiveEntryID

func LiveEntryID(turnID string) string

LiveEntryID is the id of a turn's live reply read off the screen, until its transcript line replaces it.

func LookPath

func LookPath(v2path string) (hash string, ok bool)

LookPath says whether a path under /api/v2 is one of the looks' pictures: "me/looks" (hash empty) or "me/looks/<hash>".

func MadeWantsTasks added in v0.16.42

func MadeWantsTasks(ctx context.Context) bool

MadeWantsTasks is whether the page asked for tasks among what the chat made (?tasks=1); the runtime's answer to a page that did not ask has none.

func Marshal

func Marshal(v any) ([]byte, error)

Marshal is json.Marshal for everything that goes on the wire: a nil slice leaves as [], never as null. The page's decoders read an array field as an array — one `null` in queue.items once brought a live page down — and Go leaves a slice nil whenever nothing was appended to it, so the guarantee is made here, once, and not by every producer.

The value is copied on the way (the producers' own slices are not touched) and the copy is what is encoded.

What it encodes passes the redactor, if one is set (SetRedactor): a secret an agent printed does not leave the machine.

func Matches

func Matches(r *http.Request) bool

Matches reports whether r is for the v2 API.

func MessageIDs added in v0.15.46

func MessageIDs(r *http.Request) ([]string, bool)

MessageIDs reads ?ids=a,b of a status request: 1–MessageStatusMax ids, none empty, none twice.

func NewEpoch

func NewEpoch() string

NewEpoch is a new epoch: "ep-" and 16 random base32 characters.

func NormalizeSettings

func NormalizeSettings(st *PersonSettings)

NormalizeSettings brings a saved record up to the settings of today: what an older record lacks gets its default, and a retired value is read as its successor.

func OffsetEntryID

func OffsetEntryID(offset int64, k int) string

OffsetEntryID is the id of entry k of a transcript line without a uuid (Codex), by the line's byte offset.

func PermissionID

func PermissionID(toolUseID string) string

PermissionID is the id of the permission asked by a tool use, or "p:<tabId>:<eventSeq>" for one read off the screen.

func QuestionID

func QuestionID(toolUseID string) string

QuestionID is the id of the question asked by a tool use.

func RequestOf added in v0.16.123

func RequestOf(ctx context.Context) *http.Request

RequestOf is the page's request a call was made for; nil when the call came another way.

func ServeLooks

func ServeLooks(w http.ResponseWriter, r *http.Request, blobs LookBlobs, hash string)

ServeLooks answers the two paths of the looks' pictures from a store.

func ServeMe

func ServeMe(w http.ResponseWriter, r *http.Request, st MeStore)

ServeMe answers GET /api/v2/me from a store; the runtime serves its own person with it, and the hub serves a hub user with a store of that user's settings.

func ServeMeSettings

func ServeMeSettings(w http.ResponseWriter, r *http.Request, st MeStore)

ServeMeSettings answers PATCH /api/v2/me/settings {rev, patch} from a store: {r: accepted, me}, or refused with conflict (rev is not the current one) or bad-request.

func SetRedactor added in v0.15.46

func SetRedactor(f func([]byte) []byte)

SetRedactor sets what every frame and page passes on its way out; it must return its argument when there is nothing to change. nil sets none. The runtime sets the mask of its profiles' keys.

func ValidConvID

func ValidConvID(id string) bool

ValidConvID reports whether id is a conversation id: a runtime tabId, "tab-" and [A-Za-z0-9_-].

func ValidDraftKey

func ValidDraftKey(key string) bool

ValidDraftKey reports whether key names a draft: a conversation id or DraftNew.

func ValidEntryID

func ValidEntryID(id string) bool

ValidEntryID reports whether id is an entry id: a transcript one or "live:<turnId>".

func ValidFavGroupID

func ValidFavGroupID(id string) bool

ValidFavGroupID reports whether id has the shape of a favorites group's id.

func ValidFavName

func ValidFavName(name string) bool

ValidFavName reports whether a group's name is one line of at most FavGroupNameMax characters, not blank.

func ValidMachineID

func ValidMachineID(id string) bool

ValidMachineID: a machine id is a short token, not a path or a sentence.

func ValidPermissionID

func ValidPermissionID(id string) bool

func ValidProfileID added in v0.15.46

func ValidProfileID(s string) bool

ValidProfileID says whether s has the shape of a profile id.

func ValidQuestionID

func ValidQuestionID(id string) bool

ValidQuestionID and ValidPermissionID report whether an id carries its kind's prefix.

func ValidTerminalID

func ValidTerminalID(s string) bool

ValidTerminalID says whether s names an own terminal.

func ValidTurnID

func ValidTurnID(id string) bool

ValidTurnID reports whether id is a transcript entry id: "c:<uuid>#<k>" or "x:<offset>#<k>". Turns are opened by such entries, never by a live one.

func WithMadeTasks added in v0.16.42

func WithMadeTasks(ctx context.Context) context.Context

WithMadeTasks is ctx as the made handler gives it for a request with ?tasks=1.

func WithRequest added in v0.16.123

func WithRequest(ctx context.Context, r *http.Request) context.Context

WithRequest carries the page's request into a service call, so the service can tell whose session asked (HRN-675: a design made from the page belongs to that person, not to the one the machine belongs to).

Types

type AgentAccount

type AgentAccount struct {
	SignedIn bool                `json:"signedIn"`
	Method   *AgentAccountMethod `json:"method"`
	Plan     *string             `json:"plan"`
	Who      *string             `json:"who"`
}

AgentAccount is how the CLI is signed in on this machine. `plan` and `who` (an e-mail) are what the CLI itself keeps beside its sign-in, null where it keeps none; a key is never sent.

func (AgentAccount) Validate

func (a AgentAccount) Validate() error

type AgentAccountMethod

type AgentAccountMethod string

AgentAccountMethod is how a CLI is signed in: with the person's subscription or with an API key.

const (
	AccountSubscription AgentAccountMethod = "subscription"
	AccountKey          AgentAccountMethod = "key"
)

type AgentEnvSet

type AgentEnvSet struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

AgentEnvSet sets a variable of the CLI's environment.

type AgentEnvVar

type AgentEnvVar struct {
	Key    string `json:"key"`
	Value  string `json:"value"`
	Secret bool   `json:"secret"`
}

AgentEnvVar is a variable of the CLI's `env`. A value that looks like a secret comes as its last four characters after bullets (`secret`), never whole.

func (AgentEnvVar) Validate

func (e AgentEnvVar) Validate() error

type AgentInstallStatus

type AgentInstallStatus string

AgentInstallStatus is whether an agent CLI can run on a machine.

const (
	InstallReady         AgentInstallStatus = "ready"
	InstallMissing       AgentInstallStatus = "missing"
	InstallLoginRequired AgentInstallStatus = "login-required"
)

type AgentMcp

type AgentMcp struct {
	Name    string       `json:"name"`
	Kind    AgentMcpKind `json:"kind"`
	Target  string       `json:"target"`
	Enabled bool         `json:"enabled"`
}

AgentMcp is an MCP server the machine has set up for the CLI. `target` is what it runs (the program's name) or where it is (the host), never its arguments or a path with a key in it; `enabled` is false when the CLI is told not to use it.

func (AgentMcp) Validate

func (m AgentMcp) Validate() error

type AgentMcpKind

type AgentMcpKind string

AgentMcpKind is how the CLI reaches an MCP server: it starts a command (`stdio`) or calls an address (`http`).

const (
	McpStdio AgentMcpKind = "stdio"
	McpHTTP  AgentMcpKind = "http"
)

type AgentMcpToggle

type AgentMcpToggle struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled"`
}

AgentMcpToggle turns an MCP server on or off for the CLI.

type AgentModel

type AgentModel struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Hint is one short line on what the model is for, "" when the CLI says nothing honest about it.
	Hint          string   `json:"hint"`
	Efforts       []Effort `json:"efforts"`
	DefaultEffort *Effort  `json:"defaultEffort"`
	// Ultracode: the model takes Claude Code's ultracode mode; absent when it does not.
	Ultracode bool `json:"ultracode,omitempty"`
	// Fast: the model runs in its CLI's fast mode (Claude Code's /fast, Codex's fast service tier); absent when not.
	Fast bool `json:"fast,omitempty"`
}

AgentModel is one model of an agent CLI. Efforts are the reasoning efforts it takes, empty when it has no choice; DefaultEffort is the one it runs on when none is asked for.

func (AgentModel) Validate

func (m AgentModel) Validate() error

type AgentOption

type AgentOption struct {
	Key   AgentOptionKey `json:"key"`
	Value any            `json:"value"`
}

AgentOption is one option and its value: a string, a switch, a whole number, or null while the file does not set it.

type AgentOptionKey

type AgentOptionKey string

AgentOptionKey names one option of an agent CLI. `model` and `effort` are both CLIs'; the rest belong to one.

const (
	OptModel          AgentOptionKey = "model"
	OptEffort         AgentOptionKey = "effort"
	OptBaseURL        AgentOptionKey = "baseUrl"
	OptFallbackModel  AgentOptionKey = "fallbackModel"
	OptThinking       AgentOptionKey = "thinking"
	OptOutputStyle    AgentOptionKey = "outputStyle"
	OptPermissionMode AgentOptionKey = "permissionMode"
	OptSandbox        AgentOptionKey = "sandbox"
	OptProjectMcp     AgentOptionKey = "projectMcp"
	OptCompactWindow  AgentOptionKey = "compactWindow"
	OptMemory         AgentOptionKey = "memory"
	OptKeepDays       AgentOptionKey = "keepDays"
	OptHooks          AgentOptionKey = "hooks"
	OptCoauthor       AgentOptionKey = "coauthor"
	OptUpdates        AgentOptionKey = "updates"
	OptSummary        AgentOptionKey = "summary"
	OptFast           AgentOptionKey = "fast"
	OptSandboxMode    AgentOptionKey = "sandboxMode"
	OptNetwork        AgentOptionKey = "network"
	OptApproval       AgentOptionKey = "approval"
	OptSearch         AgentOptionKey = "search"
	OptHistory        AgentOptionKey = "history"
	// OptUltracode is Claude Code's `ultracode` key: new sessions start in ultracode (2.1.310+).
	OptUltracode AgentOptionKey = "ultracode"
)

type AgentOptionKind

type AgentOptionKind string

AgentOptionKind is the type of an option's value.

const (
	OptKindBool AgentOptionKind = "bool"
	OptKindInt  AgentOptionKind = "int"
	OptKindEnum AgentOptionKind = "enum"
	OptKindText AgentOptionKind = "text"
	OptKindURL  AgentOptionKind = "url"
)

type AgentOptionSpec

type AgentOptionSpec struct {
	Key  AgentOptionKey
	Kind AgentOptionKind
	Enum []string
	// ReadExtra are values the file may hold that the page cannot write: it shows them, and lets the person pick
	// another.
	ReadExtra []string
	Min, Max  int64
	// Pattern checks a text.
	Pattern *regexp.Regexp
}

AgentOptionSpec is what an option takes: a switch, a whole number in a range, one of a list, a short name or an address.

func AgentOptionSpecOf

func AgentOptionSpecOf(p Provider, key AgentOptionKey) (AgentOptionSpec, bool)

AgentOptionSpecOf is the spec of a provider's option; false when the CLI has no such option.

func AgentOptionSpecs

func AgentOptionSpecs(p Provider) []AgentOptionSpec

AgentOptionSpecs are the options a provider's CLI takes, in the order the page lists them.

func (AgentOptionSpec) Check

func (s AgentOptionSpec) Check(v any) error

Check says whether v is a value of the option a page may write: nil (the option unset) always is.

func (AgentOptionSpec) CheckRead

func (s AgentOptionSpec) CheckRead(v any) error

CheckRead says whether v is a value of the option the file may hold, the ones a page cannot write included.

type AgentRules

type AgentRules struct {
	Allow []string `json:"allow"`
	Ask   []string `json:"ask"`
	Deny  []string `json:"deny"`
}

AgentRules are Claude Code's permission rules (`permissions.allow`, `ask`, `deny`): a rule is a tool and a pattern, as `Bash(npm run *)` or `mcp__gitlab`.

func (AgentRules) Validate

func (r AgentRules) Validate() error

type AgentSession

type AgentSession struct {
	Provider  Provider `json:"provider"`
	SessionID string   `json:"sessionId"`
	Title     string   `json:"title"`
	Cwd       string   `json:"cwd"`
	UpdatedAt Ms       `json:"updatedAt"`
	Turns     int      `json:"turns"`
}

AgentSession is a session an agent CLI kept on the machine, outside any conversation of the runtime: the person may continue it. Title is the agent's own name for it or the first thing asked; Turns counts the person's messages.

func (AgentSession) Validate

func (s AgentSession) Validate() error

type AgentSessions

type AgentSessions []AgentSession

AgentSessions is the answer of GET /api/v2/sessions: the newest first.

func (AgentSessions) Validate

func (s AgentSessions) Validate() error

type AgentSettings

type AgentSettings struct {
	Provider Provider      `json:"provider"`
	Path     string        `json:"path"`
	Rev      string        `json:"rev"`
	Account  AgentAccount  `json:"account"`
	Options  []AgentOption `json:"options"`
	Rules    *AgentRules   `json:"rules"`
	Env      []AgentEnvVar `json:"env"`
	Mcp      []AgentMcp    `json:"mcp"`
}

AgentSettings is the answer of GET /api/v2/agent-settings/<provider>: every option the CLI takes (null while unset), and for Claude Code its rules and environment (Codex has neither: `rules` is null and `env` empty). `path` is the file with the home shortened to `~`; `rev` is the file's content hash, the value a write has to quote.

func (AgentSettings) Validate

func (a AgentSettings) Validate() error

type AgentSettingsEdit

type AgentSettingsEdit struct {
	Rev   string             `json:"rev"`
	Patch AgentSettingsPatch `json:"patch"`
}

AgentSettingsEdit is the body of PATCH /api/v2/agent-settings/<provider>: the patch and the revision it was made on.

type AgentSettingsPatch

type AgentSettingsPatch struct {
	Options  []AgentOption   `json:"options,omitempty"`
	Rules    *AgentRules     `json:"rules,omitempty"`
	EnvSet   []AgentEnvSet   `json:"envSet,omitempty"`
	EnvUnset []string        `json:"envUnset,omitempty"`
	Mcp      *AgentMcpToggle `json:"mcp,omitempty"`
}

AgentSettingsPatch names what a write changes: options (a null value unsets the option), the whole rules, variables of the environment to set or to remove, one MCP server turned on or off. What it does not name stays as it is.

func (AgentSettingsPatch) ValidateFor

func (p AgentSettingsPatch) ValidateFor(provider Provider) error

ValidateFor checks a patch against what a provider's CLI takes.

type AgentSettingsSource

type AgentSettingsSource interface {
	AgentSettings(ctx context.Context, p Provider) (AgentSettings, error)
	// PatchAgentSettings applies a patch made on rev: ErrAgentSettingsConflict when the file is at another revision,
	// ErrAgentSettingsRefused when it cannot take the change.
	PatchAgentSettings(ctx context.Context, p Provider, rev string, patch AgentSettingsPatch) (AgentSettings, error)
}

AgentSettingsSource reads and writes the agent CLIs' settings files of this machine.

type AgentStamp

type AgentStamp struct {
	State AgentState `json:"state"`
	Rev   int64      `json:"rev"`
	Epoch string     `json:"epoch"`
}

AgentStamp is a conversation's agent state with its version, as the conversation's own channel carries it. Rev is the record's revision the state stands at, the one the convs channel names for the same change, and Epoch is the runtime's (the welcome's): within an epoch the higher rev is the later state, whichever channel brought it.

func (AgentStamp) Validate

func (a AgentStamp) Validate() error

type AgentState

type AgentState struct {
	K            AgentStateKind `json:"k"`
	Since        Ms             `json:"since"`
	Step         LaunchStep     `json:"step"`
	Wait         *Wait          `json:"wait"` // starting: when the launch is slow and when it fails
	TurnID       *string        `json:"turnId"`
	Compacting   bool           `json:"compacting"`
	QuestionID   string         `json:"questionId"`
	PermissionID string         `json:"permissionId"` // a plan waits here too, its kind is in the Permission
	Resumable    bool           `json:"resumable"`
	Reason       string         `json:"reason"` // LaunchFailure for launch-failed, GoneReason for gone
}

AgentState is where a conversation's agent is. Only the fields of K are on the wire:

starting{since, step, wait} · working{since, turnId|null, compacting} · waiting-question{since, questionId} ·
waiting-permission{since, permissionId} · ready{since} · idle{since} · stopped{since, resumable} ·
launch-failed{since, reason: LaunchFailure} · gone{since, reason: GoneReason} · unknown{since}

unknown is "not checked yet": for delivery it is not idle.

func (AgentState) MarshalJSON

func (s AgentState) MarshalJSON() ([]byte, error)

func (*AgentState) UnmarshalJSON

func (s *AgentState) UnmarshalJSON(b []byte) error

func (AgentState) Validate

func (s AgentState) Validate() error

type AgentStateKind

type AgentStateKind string

AgentStateKind is the kind of an AgentState.

const (
	StateStarting          AgentStateKind = "starting"
	StateWorking           AgentStateKind = "working"
	StateWaitingQuestion   AgentStateKind = "waiting-question"
	StateWaitingPermission AgentStateKind = "waiting-permission"
	StateReady             AgentStateKind = "ready"
	StateIdle              AgentStateKind = "idle"
	StateStopped           AgentStateKind = "stopped"
	StateLaunchFailed      AgentStateKind = "launch-failed"
	StateGone              AgentStateKind = "gone"
	StateUnknown           AgentStateKind = "unknown"
)

type AnswerCmd

type AnswerCmd struct {
	OpID           string           `json:"opId"`
	ConversationID string           `json:"conversationId"`
	QuestionID     string           `json:"questionId"`
	Answers        []QuestionAnswer `json:"answers,omitempty"`
	ChatAbout      bool             `json:"chatAbout,omitempty"`
}

AnswerCmd answers a question: Answers, one per item, or ChatAbout to talk it over in words.

func (AnswerCmd) Op

func (AnswerCmd) Op() Op

func (AnswerCmd) OpKey

func (c AnswerCmd) OpKey() string

func (AnswerCmd) Validate

func (c AnswerCmd) Validate() error

type AnswerPair

type AnswerPair struct {
	Q string `json:"q"`
	A string `json:"a"`
}

AnswerPair is one question and its answer in an answers entry.

type AppApprovals

type AppApprovals struct {
	Given    int `json:"given"`
	Required int `json:"required"`
}

AppApprovals is how many of the approvals a merge request needs it has.

type AppChild

type AppChild struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	URL    string  `json:"url"`
	State  *string `json:"state"`
	Done   bool    `json:"done"`
	Person *string `json:"person"`
}

AppChild is a subtask of an epic: enough to list it and to tell whether it is done. `person` is its assignee.

func (AppChild) Validate

func (c AppChild) Validate() error

type AppFeed

type AppFeed struct {
	ID       AppID        `json:"id"`
	State    AppState     `json:"state"`
	Reason   *AppReason   `json:"reason"`
	Host     *string      `json:"host"`
	Me       *string      `json:"me"`
	Sections []AppSection `json:"sections"`
}

AppFeed is one app's answer. `host` is the service the machine reads it from (null while none is named); `reason` is set exactly when the app is not ready, and then there are no sections. `me` is how the service names the person whose token the machine reads with (null when it did not say), so the page can tell "mine" from the others'.

func (AppFeed) Validate

func (f AppFeed) Validate() error

type AppFlag

type AppFlag string

AppFlag is what a merge request is waiting for or is stuck on, the one thing that is worth a tag.

const (
	FlagReview     AppFlag = "review"      // it waits for the person's review
	FlagConflict   AppFlag = "conflict"    // it cannot be merged: conflicts with its target
	FlagCIFailed   AppFlag = "ci-failed"   // its pipeline failed
	FlagNoReviewer AppFlag = "no-reviewer" // open, and nobody is asked to review it
	FlagOpen       AppFlag = "open"        // open and nothing else to say
)

type AppID

type AppID string

AppID names an app of the screen.

const (
	AppTracker AppID = "tracker"
	AppGitLab  AppID = "gitlab"
)

type AppMR

type AppMR struct {
	Source      *string       `json:"source"`
	Draft       bool          `json:"draft"`
	Conflicts   bool          `json:"conflicts"`
	NeedsRebase bool          `json:"needsRebase"`
	Ready       bool          `json:"ready"`
	Unresolved  bool          `json:"unresolved"`
	Comments    int           `json:"comments"`
	Pipeline    *AppPipeline  `json:"pipeline"`
	Approvals   *AppApprovals `json:"approvals"`
}

AppMR is what GitLab says of a merge request beyond what every row has. `source` is its branch; `ready` that GitLab calls it mergeable now; `unresolved` that a discussion that blocks the merge is open; `comments` how many notes people wrote; `pipeline` the state of its latest pipeline (null: it has none, or the machine did not ask); `approvals` the count (null: the instance has no approvals for it, or the machine did not ask).

func (AppMR) Validate

func (m AppMR) Validate() error

type AppPipeline

type AppPipeline string

AppPipeline is the state of a merge request's latest pipeline, as GitLab names it (the ones it has beyond these are `pending`, which is the least wrong word for "has not started or is waiting").

const (
	PipelineSuccess  AppPipeline = "success"
	PipelineFailed   AppPipeline = "failed"
	PipelineRunning  AppPipeline = "running"
	PipelinePending  AppPipeline = "pending"
	PipelineCanceled AppPipeline = "canceled"
	PipelineSkipped  AppPipeline = "skipped"
	PipelineManual   AppPipeline = "manual"
)

type AppProgress

type AppProgress struct {
	Done  int `json:"done"`
	Total int `json:"total"`
}

AppProgress is how many of an epic's tasks are done.

type AppReason

type AppReason string

AppReason says why an app is not ready. `not-configured` and `no-token` go with `off`; `denied` (the service refused the token) and `unreachable` with `failed`.

const (
	AppNotConfigured AppReason = "not-configured"
	AppNoToken       AppReason = "no-token"
	AppDenied        AppReason = "denied"
	AppUnreachable   AppReason = "unreachable"
)

type AppRef

type AppRef struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	URL   string `json:"url"`
}

AppRef is a task named from another: the epic a task belongs to.

func (AppRef) Validate

func (r AppRef) Validate() error

type AppRole

type AppRole string

AppRole is how a row concerns the person: they wrote it, it is assigned to them, they are asked to review it.

const (
	RoleAuthor   AppRole = "author"
	RoleAssignee AppRole = "assignee"
	RoleReviewer AppRole = "reviewer"
)

type AppRow

type AppRow struct {
	Key       string   `json:"key"`
	ID        string   `json:"id"`
	Title     string   `json:"title"`
	URL       string   `json:"url"`
	State     *string  `json:"state"`
	Flag      *AppFlag `json:"flag"`
	Tone      *AppTone `json:"tone"`
	Project   *string  `json:"project"`
	Person    *string  `json:"person"`
	Target    *string  `json:"target"`
	CreatedAt int64    `json:"createdAt"`
	UpdatedAt int64    `json:"updatedAt"`
	ClosedAt  *int64   `json:"closedAt"`
	Author    *string  `json:"author"`
	// Avatar is the author's picture as the page loads it: a route of this runtime, never the code host's address.
	Avatar *string `json:"avatar"`
	// Bot: the author is a bot of the code host (a dependency bot, an access token's user), not a person.
	Bot       bool         `json:"bot"`
	Assignees []string     `json:"assignees"`
	Reviewers []string     `json:"reviewers"`
	Me        []AppRole    `json:"me"`
	Labels    []string     `json:"labels"`
	Priority  *string      `json:"priority"`
	Kind      *string      `json:"kind"`
	Parent    *AppRef      `json:"parent"`
	Progress  *AppProgress `json:"progress"`
	Children  []AppChild   `json:"children"`
	MR        *AppMR       `json:"mr"`
}

AppRow is a task, an epic or a merge request. `key` tells it from every other row of the screen (a merge request's link: `!12` repeats across projects), `id` is what the person reads (`ABC-2628`, `!502`). A task has the tracker's own `state` name (a merge request `opened`, `merged` or `closed`), a merge request a `flag`; `project` is the repository, `person` the assignee or the author, `target` the branch a merge request goes to, `progress` an epic's tasks, `children` the epic's subtasks (empty for the others). `author` wrote it, `assignees` and `reviewers` are the people named on it, `me` how it concerns the person who reads. `labels` are the tracker's tags or the merge request's labels, `priority` and `kind` the tracker's own words, `parent` the epic a task belongs to. `createdAt`, `updatedAt` and `closedAt` (resolved, merged or closed; null while open) are milliseconds.

func (AppRow) Validate

func (r AppRow) Validate() error

type AppSection

type AppSection struct {
	ID   AppSectionID `json:"id"`
	Rows []AppRow     `json:"rows"`
}

AppSection is a titled run of rows; the page words the title by `id`.

func (AppSection) Validate

func (s AppSection) Validate() error

type AppSectionID

type AppSectionID string

AppSectionID names a section of an app's feed: the epics and the tasks on the person (tracker), the merge requests (GitLab).

const (
	SectionEpics AppSectionID = "epics"
	SectionTasks AppSectionID = "tasks"
	SectionMRs   AppSectionID = "mrs"
)

type AppState

type AppState string

AppState is whether the machine could read an app: `ready` (the sections are the app's answer, any of them may be empty), `off` (the machine is not set up for it) or `failed` (it is set up and did not answer).

const (
	AppReady  AppState = "ready"
	AppOff    AppState = "off"
	AppFailed AppState = "failed"
)

type AppTone

type AppTone string

AppTone is how a row's status is coloured: `accent` for what is going on, `warn` for what is stuck.

const (
	ToneAccent AppTone = "accent"
	ToneWarn   AppTone = "warn"
)

type AppsFeed

type AppsFeed struct {
	At        int64     `json:"at"`
	StaleDays int       `json:"staleDays"`
	Apps      []AppFeed `json:"apps"`
}

AppsFeed is the answer of GET /api/v2/apps: every app of the screen, in the order of the list. `staleDays` is how long a task or merge request stands still before the page calls it stale unless the person chose otherwise.

func (AppsFeed) Validate

func (a AppsFeed) Validate() error

type AppsSource

type AppsSource interface {
	Feed(ctx context.Context, only []AppID) (AppsFeed, error)
}

AppsSource reads the apps. It never waits longer than its own budget: an app that does not answer in time is `failed`. `only` names the apps to read; empty: all of them.

type AttachmentKind

type AttachmentKind string

AttachmentKind is an image or another file.

const (
	AttachmentImage AttachmentKind = "image"
	AttachmentFile  AttachmentKind = "file"
)

type AttachmentRef

type AttachmentRef struct {
	ID   string         `json:"id"`
	Name string         `json:"name"`
	Kind AttachmentKind `json:"kind"`
	Mime string         `json:"mime"`
}

AttachmentRef is an uploaded file a message carries.

func (AttachmentRef) Validate

func (a AttachmentRef) Validate() error

type AutoContinue

type AutoContinue struct {
	At       Ms              `json:"at"`
	Why      AutoContinueWhy `json:"why"`
	ClientID string          `json:"clientId"`
	Own      bool            `json:"own,omitempty"`
}

AutoContinue is one time the runtime went on by itself: why, when, and the message that went — its own (Own, the message's Auto set) or the one the person had queued meanwhile.

type AutoContinueWhy

type AutoContinueWhy string

AutoContinueWhy is why the runtime went on: the usage limit reset, or a restart of the runtime cut a turn short.

const (
	AutoAfterLimit   AutoContinueWhy = "limit"
	AutoAfterRestart AutoContinueWhy = "restart"
)

type BackgroundKind

type BackgroundKind string

BackgroundKind is a subagent, a command or a dynamic workflow.

const (
	BgSubagent BackgroundKind = "subagent"
	BgCommand  BackgroundKind = "command"
	// BgWorkflow: a dynamic workflow, a script of the agent that starts subagents in the background phase by phase.
	BgWorkflow BackgroundKind = "workflow"
)

type BackgroundRemovedEv

type BackgroundRemovedEv struct {
	ID string `json:"id"`
}

BackgroundRemovedEv: a background task is gone from the list.

func (BackgroundRemovedEv) EventType

func (BackgroundRemovedEv) EventType() EventType

func (BackgroundRemovedEv) MarshalJSON

func (e BackgroundRemovedEv) MarshalJSON() ([]byte, error)

func (BackgroundRemovedEv) Validate

func (e BackgroundRemovedEv) Validate() error

type BackgroundStatus

type BackgroundStatus string

BackgroundStatus is where a background task is.

const (
	BgStatusRunning BackgroundStatus = "running"
	BgStatusDone    BackgroundStatus = "done"
	BgStatusStopped BackgroundStatus = "stopped"
	BgStatusFailed  BackgroundStatus = "failed"
	// BgStatusIdle: a teammate that finished what it was sent and waits for the next message; no work running.
	BgStatusIdle BackgroundStatus = "idle"
)

type BackgroundTask

type BackgroundTask struct {
	ID             string           `json:"id"`
	ConversationID string           `json:"conversationId"`
	Kind           BackgroundKind   `json:"kind"`
	Title          string           `json:"title"`
	StartedAt      Ms               `json:"startedAt"`
	EndedAt        *Ms              `json:"endedAt"`
	Status         BackgroundStatus `json:"status"`
	DevServer      bool             `json:"devServer"`
	Stoppable      bool             `json:"stoppable"`
	OutputPath     *string          `json:"outputPath"`
	// Monitor: a command kind that is the agent's Monitor, not a shell. Absent for the rest.
	Monitor bool `json:"monitor,omitempty"`
	// Teammate: a subagent that is a named teammate of the agent (its title is the name, its role what it was started
	// for). Only a teammate is ever idle. Absent for the rest.
	Teammate bool `json:"teammate,omitempty"`
	// Subagents only: the model it runs on (the alias or the full id), the effort when the agent says it, its kind
	// («Explore», «general-purpose») and the last thing it did, one line. Absent when unknown.
	Model  *string `json:"model,omitempty"`
	Effort *Effort `json:"effort,omitempty"`
	Role   *string `json:"role,omitempty"`
	Last   *string `json:"last,omitempty"`
	// Workflow: what a workflow's run says — its phases and the agents it started in each. Only a workflow has it.
	Workflow *WorkflowRun `json:"workflow,omitempty"`
}

BackgroundTask is a subagent or a command running beside a conversation's turn.

func (BackgroundTask) Validate

func (b BackgroundTask) Validate() error

type BackgroundUpsertEv

type BackgroundUpsertEv struct {
	Task BackgroundTask `json:"task"`
}

BackgroundUpsertEv is a background task's whole record.

func (BackgroundUpsertEv) EventType

func (BackgroundUpsertEv) EventType() EventType

func (BackgroundUpsertEv) MarshalJSON

func (e BackgroundUpsertEv) MarshalJSON() ([]byte, error)

func (BackgroundUpsertEv) Validate

func (e BackgroundUpsertEv) Validate() error

type BgStopCmd

type BgStopCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
	TaskID         string `json:"taskId"`
}

BgStopCmd stops a background task.

func (BgStopCmd) Op

func (BgStopCmd) Op() Op

func (BgStopCmd) OpKey

func (c BgStopCmd) OpKey() string

func (BgStopCmd) Validate

func (c BgStopCmd) Validate() error

type BgWait

type BgWait struct {
	Agents    int `json:"agents,omitempty"`    // background subagents running
	Teammates int `json:"teammates,omitempty"` // named teammates at work (one idle waits for a message, it is not waited for)
	Commands  int `json:"commands,omitempty"`  // background shell commands running
	Monitors  int `json:"monitors,omitempty"`  // monitors watching
	Workflows int `json:"workflows,omitempty"` // dynamic workflows running
	// Command is the title of the command when it is the only one running; absent otherwise.
	Command string `json:"command,omitempty"`
	// WakeupAt is when the agent's own scheduled wakeup comes (epoch ms); absent when none is pending.
	WakeupAt *Ms `json:"wakeupAt,omitempty"`
}

BgWait is what an agent whose prompt is free still waits for, by kind; the counts that are 0 are absent. Its parts add up to Conversation.BgAgents.

func (BgWait) Total

func (w BgWait) Total() int

Total is how many pieces of work the wait holds.

type CancelCmd

type CancelCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
	ClientID       string `json:"clientId"`
}

CancelCmd takes a queued message out of the queue.

func (CancelCmd) Op

func (CancelCmd) Op() Op

func (CancelCmd) OpKey

func (c CancelCmd) OpKey() string

func (CancelCmd) Validate

func (c CancelCmd) Validate() error

type Cap

type Cap string

Cap is an optional part of the frames that a page says it reads. The page decodes strictly and an open tab keeps its build after a new runtime ships, so the runtime sends a newer field or value only to a page that asked for it. A page asks in the socket's address (?caps=delegation,...), not in hello: a runtime older than the page refuses any field of hello it does not know, and ignores a query it does not read. Its HTTP calls that carry such a part name the caps the same way.

const (
	// CapDelegation: the page reads Conversation.ParentID and RuntimeSettings.Delegation (README 63).
	CapDelegation Cap = "delegation"
	// CapWorkflows: the page reads the workflow kind of a background task, its run (BackgroundTask.Workflow) and
	// BgWait.Workflows (README 52).
	CapWorkflows Cap = "workflows"
	// CapProfiles: the page reads the backend profiles (README 64): MachineAgent.Profiles and Model.Profile.
	CapProfiles Cap = "profiles"
	// CapMsgStatus: the page reads a message queued stalled (QueuedStalled) and lists it in the queue (README 65).
	CapMsgStatus Cap = "msgstatus"
	// CapLinks: the page reads the output kinds task and commit (README 72).
	CapLinks Cap = "links"
)

type Caps

type Caps struct {
	Delegation bool
	Workflows  bool
	Profiles   bool
	MsgStatus  bool
	Links      bool
}

Caps is what a page reads.

func CapsOf

func CapsOf(r *http.Request) Caps

CapsOf reads the caps a page named in its request's address; an unknown one is ignored.

type Channel

type Channel string

Channel is a subscription of the socket: "machine", "convs" or "conv:<convId>".

const (
	ChannelMachine Channel = "machine"
	ChannelConvs   Channel = "convs"
)

func ConvChannel

func ConvChannel(id string) Channel

ConvChannel is the channel of one conversation.

func (Channel) ConvID

func (c Channel) ConvID() (id string, ok bool)

ConvID is the conversation of a conv channel; ok is false for the other channels.

func (Channel) Valid

func (c Channel) Valid() bool

Valid reports whether c is a channel of this protocol.

type ChatDigest added in v0.15.46

type ChatDigest struct {
	ConvID    string `json:"convId"`
	Title     string `json:"title"`
	Text      string `json:"text"`
	Path      string `json:"path"`
	Truncated bool   `json:"truncated"`
}

ChatDigest is the answer of GET /api/v2/conversations/{id}/digest?budget=: what a chat said, cut to the size of a context block for another agent. Text holds the title, the first request, the latest turns and the key results; Path is the whole conversation as a Markdown file on the machine, which the agent may read for more. Truncated: Text leaves out parts of the conversation.

func (ChatDigest) Validate added in v0.15.46

func (c ChatDigest) Validate() error

type ChatFrom

type ChatFrom struct {
	App   string `json:"app"`
	Label string `json:"label"`
	Title string `json:"title,omitempty"`
}

ChatFrom is the app that started a conversation for the person (an inbox, a trigger): App is its id, Label how the sidebar names its folder, Title the chat's name from the start. The person's move of the chat to a project, to the favorites or to the recent chats takes it, and the mark goes.

func (*ChatFrom) Clean

func (f *ChatFrom) Clean() *ChatFrom

Clean is the mark with its fields trimmed and cut to ChatFromMax; nil when it names no app.

type ChatGlance

type ChatGlance struct {
	ConvID    string         `json:"convId"`
	LastUser  *GlanceMessage `json:"lastUser"`
	LastAgent *GlanceMessage `json:"lastAgent"`
	Messages  int            `json:"messages"`
}

ChatGlance is the answer of GET /api/v2/conversations/{id}/glance: what a chat said last, for the search's preview. LastUser and LastAgent are the newest message of each side (null when it has none); Messages is how many the search index holds for the chat.

func (ChatGlance) Validate

func (c ChatGlance) Validate() error

type ChatMade added in v0.16.42

type ChatMade struct {
	Items    []MadeItem `json:"items"`
	Complete bool       `json:"complete"`
}

ChatMade is GET /api/v2/conversations/{id}/made: what the chat made, opened or changed, newest first, at most MadeMax. Complete is false while the runtime is still reading a long transcript behind the answer; ask again.

func (ChatMade) Validate added in v0.16.42

func (c ChatMade) Validate() error

type ClientFrame

type ClientFrame interface {
	ClientFrameKind() FrameKind
	Validate() error
}

ClientFrame is a frame the page sends on the socket: HelloFrame, SubFrame, UnsubFrame or PingFrame.

func DecodeClientFrame

func DecodeClientFrame(b []byte) (ClientFrame, error)

DecodeClientFrame reads and checks one frame from the page; an unknown kind or field is an error.

type CmdResult

type CmdResult struct {
	R    ResultKind `json:"r"`
	Ch   Channel    `json:"ch"`
	Seq  int64      `json:"seq"`
	Rev  *int64     `json:"rev"`
	ID   *string    `json:"id"`
	Code RefuseCode `json:"code"`
}

CmdResult is the answer of a command. Accepted and queued carry the channel and seq from which the effect shows on the socket — the page waits for that seq, not for a timer — and Rev or ID when the command made one; refused carries only Code.

func Accepted

func Accepted(ch Channel, seq int64) CmdResult

Accepted is an accepted result whose effect shows on ch from seq on.

func Queued

func Queued(ch Channel, seq int64) CmdResult

Queued is a queued result whose effect shows on ch from seq on.

func Refused

func Refused(code RefuseCode) CmdResult

Refused is a refused result.

func (CmdResult) MarshalJSON

func (r CmdResult) MarshalJSON() ([]byte, error)

func (*CmdResult) UnmarshalJSON

func (r *CmdResult) UnmarshalJSON(b []byte) error

func (CmdResult) Validate

func (r CmdResult) Validate() error

type Command

type Command interface {
	Op() Op
	OpKey() string
	Validate() error
}

Command is the body of POST /api/v2/cmd/<op>. OpKey is its opId: the same opId with the same body gets the same result, with another body refused{conflict}.

func DecodeCommand

func DecodeCommand(op Op, body []byte) (Command, error)

DecodeCommand reads and checks the body of POST /api/v2/cmd/<op>; an unknown op or field is an error.

type CompactionEv

type CompactionEv struct {
	Phase CompactionPhase `json:"phase"`
	Entry Entry           `json:"entry"`
}

CompactionEv: a compaction started or finished; Entry is its compaction entry.

func (CompactionEv) EventType

func (CompactionEv) EventType() EventType

func (CompactionEv) MarshalJSON

func (e CompactionEv) MarshalJSON() ([]byte, error)

func (CompactionEv) Validate

func (e CompactionEv) Validate() error

type CompactionPhase

type CompactionPhase string

CompactionPhase is the start or the end of a compaction.

const (
	CompactionStarted  CompactionPhase = "started"
	CompactionFinished CompactionPhase = "finished"
)

type ConvContext

type ConvContext struct {
	UsedTokens  int64 `json:"usedTokens"`
	LimitTokens int64 `json:"limitTokens"`
	// CompactAtTokens is where the agent compacts by itself, by its settings; 0 (absent) where the runtime cannot say.
	CompactAtTokens int64 `json:"compactAtTokens,omitempty"`
}

ConvContext is the answer of GET /api/v2/conversations/{id}/context: how full the agent's window is — the tokens its last answer was asked with (0 before the first) of its window.

func (ConvContext) Validate

func (c ConvContext) Validate() error

type ConvSnapshot

type ConvSnapshot struct {
	Turns        []Turn           `json:"turns"`
	Entries      []Entry          `json:"entries"`
	BeforeTurnID *string          `json:"beforeTurnId"`
	Queue        Queue            `json:"queue"`
	Messages     []Message        `json:"messages"` // not final, and final ones of the last 10 minutes
	Questions    []Question       `json:"questions"`
	Permissions  []Permission     `json:"permissions"`
	Background   []BackgroundTask `json:"background"`
	// Shots are the pictures the agent and its subagents looked at lately, newest first (see Shot); absent when none.
	Shots []Shot `json:"shots,omitempty"`
	// Pictures are the pictures the conversation's messages name, the latest named last (see Picture); absent when none.
	Pictures []Picture `json:"pictures,omitempty"`
	Now      *Now      `json:"now"`
	// Agent is the conversation's agent state as the snapshot was taken; absent from a runtime that does not stamp it.
	Agent *AgentStamp `json:"agent,omitempty"`
	// Pane is what the right pane's tools read of the conversation; absent from a runtime that does not send it, and
	// the page then reads the conversation for its pane by itself.
	Pane *Pane `json:"pane,omitempty"`
}

ConvSnapshot is the data of a conv:<id> snapshot. Turns are the last turns, oldest first; Entries are the steps of the last three and the answer entries of the rest. BeforeTurnID is the cursor for older turns, nil at the start. With mode "after" Entries are those after the cursor and Turns the turns they touch.

func FitConv

func FitConv(s ConvSnapshot) ConvSnapshot

FitConv keeps a conv snapshot within ConvBudget. Step by step, until it fits: tool outputs are cut to ToolOutputMax, then shorter; the steps of the older full turns go (their answer entries stay, a folded turn needs only those); the oldest steps of the last turn go while they take more than half the budget; the oldest turns go, and beforeTurnId moves to the oldest kept one; at last the rest of the last turn's steps but its user entry, its answer and its live reply. What went is loaded by the pages: a turn with fewer entries than its stepCount is opened through /turns/{id}/entries.

func (ConvSnapshot) Validate

func (s ConvSnapshot) Validate() error

type Conversation

type Conversation struct {
	ID             string       `json:"id"`
	MachineID      string       `json:"machineId"`
	ProjectID      *string      `json:"projectId"`
	Cwd            string       `json:"cwd"`
	Provider       Provider     `json:"provider"`
	Model          *Model       `json:"model"`
	Title          string       `json:"title"`
	TitleSource    TitleSource  `json:"titleSource"`
	Pinned         bool         `json:"pinned"`
	Test           bool         `json:"test,omitempty"` // a chat an agent made to check something (HRN-842): the sidebar leaves it out unless asked
	From           *ChatFrom    `json:"from,omitempty"` // an app started the chat for the person (HRN-1393): its folder in the sidebar until the person takes it
	CreatedAt      Ms           `json:"createdAt"`
	LastActivityAt Ms           `json:"lastActivityAt"`
	LastPromptAt   Ms           `json:"lastPromptAt"` // the person's last real message (createdAt until then); the sidebar orders by it
	State          AgentState   `json:"state"`
	SeenAt         Ms           `json:"seenAt"` // read up to; unread when LastTurn.EndedAt > SeenAt — not an agent state
	LastTurn       *TurnSummary `json:"lastTurn"`
	Queue          QueueSummary `json:"queue"`
	Gate           *GateRef     `json:"gate"`             // the open gate; its details are in the conv channel
	Goal           *Goal        `json:"goal,omitempty"`   // the agent's /goal; absent when it has none
	Launch         *Launch      `json:"launch,omitempty"` // set on a conversation started with others by one prompt
	// Apps are the ids of the installed apps turned on in this chat (internal/apps): the agent of the chat gets their
	// profiles. Absent when none is on.
	Apps []string `json:"apps,omitempty"`
	// View is how the person left this chat's window — the full screen it was on, where the chat stood by it, the right
	// pane and the place in the feed (web/app/next/stores/chat-view.ts): a JSON object the page writes whole and reads
	// back on any device. The runtime keeps it as it is; absent when none was kept.
	View json.RawMessage `json:"view,omitempty"`
	// PendingModel is a change of model or effort the person asked for that the agent has not taken yet: the runtime
	// holds it and applies it at the first moment the agent can (see PendingModel). Absent when none waits.
	PendingModel *PendingModel `json:"pendingModel,omitempty"`
	// ModelLog is the changes of model the runtime applied, oldest first, the last ModelLogMax of them: the feed shows
	// each where it happened. Absent when there were none.
	ModelLog []ModelSwitch `json:"modelLog,omitempty"`
	Recap    *Recap        `json:"recap,omitempty"` // Claude's latest «while you were away» summary; absent when it has none
	// BgAgents is how many pieces of background work the agent waits for now — subagents, commands, monitors and a
	// scheduled wakeup together: a chat that waits for them is still at work although its prompt is free. Absent when
	// it waits for nothing. The name is from when only subagents counted; a client that knows nothing else still
	// draws the chat as at work. BgWait says what the number is made of.
	BgAgents int     `json:"bgAgents,omitempty"`
	BgWait   *BgWait `json:"bgWait,omitempty"`
	// TerminalStop says the conversation's terminal was stopped — by the person or for standing idle — while the agent
	// is not running again; the feed ends with a quiet row about it. Absent otherwise.
	TerminalStop *TerminalStop `json:"terminalStop,omitempty"`
	// NotSavedSince is since when the runtime has failed to write the conversation to its disk (a full or read-only
	// disk), several writes in a row: what the person sends is held in memory only and a restart of the runtime loses
	// it. The runtime goes on trying; absent while the conversation is saved.
	NotSavedSince Ms `json:"notSavedSince,omitempty"`
	// TerminalFailure is a provider-neutral, non-retryable failure of the last turn. NeedsTarget means the runtime
	// will not retry or move the conversation itself: the person must choose where to continue.
	TerminalFailure *TerminalFailure `json:"terminalFailure,omitempty"`
	// Rewinds are the person's rewinds of the conversation to an earlier message of theirs, oldest first, the last
	// RewindsMax of them: the feed folds what each left behind where it was cut. Absent when there were none.
	Rewinds []RewindMark `json:"rewinds,omitempty"`
	// Origin is the conversation this one came out of: a fork of it, or its context handed to another agent or model.
	// Absent for a conversation started anew.
	Origin *Origin `json:"origin,omitempty"`
	// Limited says the agent's last turn ended on its plan's usage limit: the runtime holds the queue until the limit
	// resets and then goes on by itself (LimitHold). Absent otherwise.
	Limited *LimitHold `json:"limited,omitempty"`
	// AutoContinues are the times the runtime went on by itself — after a limit reset, after a restart cut a turn —
	// oldest first, the last AutoContinueMax of them: the feed draws each at the message it sent. Absent when none.
	AutoContinues []AutoContinue `json:"autoContinues,omitempty"`
	// ParentID is the conversation whose agent delegated this one (an agent's delegate_task): the sidebar nests it under
	// that one, the parent's feed shows it as a card. Absent for a chat the person started.
	ParentID *string `json:"parentId,omitempty"`
	Rev      int64   `json:"rev"`

	// Server only: the tmux session, the transcript and the agent's session id.
	Session        string `json:"-"`
	TranscriptPath string `json:"-"`
	AgentSessionID string `json:"-"`
	// Person is the address of the person the conversation was started for (whose page session asked; a delegated
	// one is its root's person). Server only: the design library names the people who worked on a project by it
	// and no page ever gets another person's address. Empty: the runtime's own person (and every chat
	// from before it was recorded).
	Person string `json:"-"`
}

Conversation is one agent tab: its id is the runtime's tabId ("tab-…").

func (Conversation) Validate

func (c Conversation) Validate() error

type ConversationAppsCmd added in v0.16.42

type ConversationAppsCmd struct {
	OpID string   `json:"opId"`
	ID   string   `json:"id"`
	Apps []string `json:"apps"`
}

ConversationAppsCmd sets the apps turned on in a conversation: the whole list, in the order the person turned them on. An empty list turns them all off.

func (ConversationAppsCmd) Op added in v0.16.42

func (ConversationAppsCmd) Op() Op

func (ConversationAppsCmd) OpKey added in v0.16.42

func (c ConversationAppsCmd) OpKey() string

func (ConversationAppsCmd) Validate added in v0.16.42

func (c ConversationAppsCmd) Validate() error

type ConversationCreateCmd

type ConversationCreateCmd struct {
	OpID      string   `json:"opId"`
	ProjectID string   `json:"projectId,omitempty"`
	Cwd       string   `json:"cwd,omitempty"`
	Provider  Provider `json:"provider"`
	Model     *Model   `json:"model"` // nil: the agent's default
	// Profile starts the conversation on a backend profile (ProfileOffer.ID) of the Provider's CLI, with one of its
	// models; empty: the CLI's own account. The profile needs a saved key and cannot be changed later.
	Profile string        `json:"profile,omitempty"`
	First   *FirstMessage `json:"first,omitempty"`
	// Worktree starts the conversation in a git worktree of its own, on a new branch off the folder's HEAD; a folder
	// that is no git repository is used as it is.
	Worktree bool `json:"worktree,omitempty"`
	// Launch marks the conversation as one of several started by the same prompt on different models.
	Launch *Launch `json:"launch,omitempty"`
	// ParentID makes the new conversation a delegated one of that conversation (see Conversation.ParentID).
	ParentID string `json:"parentId,omitempty"`
	// Title names the conversation from the start (as a rename would); empty takes the first message's line.
	Title string `json:"title,omitempty"`
	// Test starts the conversation as a test chat (see Conversation.Test).
	Test bool `json:"test,omitempty"`
}

ConversationCreateCmd opens a conversation in a project or a folder; First is queued as soon as it launches. The accepted result's ID is the new conversation's id: the page subscribes to its conv channel with afterSeq 0, and the ring holds that channel from its first event, so the first message's states are not lost.

func (ConversationCreateCmd) Op

func (ConversationCreateCmd) OpKey

func (c ConversationCreateCmd) OpKey() string

func (ConversationCreateCmd) Validate

func (c ConversationCreateCmd) Validate() error

type ConversationDeleteCmd

type ConversationDeleteCmd struct {
	OpID  string `json:"opId"`
	ID    string `json:"id"`
	Force *bool  `json:"force,omitempty"`
}

ConversationDeleteCmd hides a conversation for 7 days; Force deletes a working one too.

func (ConversationDeleteCmd) Op

func (ConversationDeleteCmd) OpKey

func (c ConversationDeleteCmd) OpKey() string

func (ConversationDeleteCmd) Validate

func (c ConversationDeleteCmd) Validate() error

type ConversationForkCmd

type ConversationForkCmd struct {
	OpID   string  `json:"opId"`
	ID     string  `json:"id"`
	AtTurn *string `json:"atTurn,omitempty"`
}

ConversationForkCmd branches a conversation off another one after a finished turn (AtTurn; the last finished one when absent). The new conversation keeps the other's folder, project, agent and model, and holds its history up to there; the other stays as it is. The accepted result's ID is the new conversation's id, on convs.

func (ConversationForkCmd) Op

func (ConversationForkCmd) Op() Op

func (ConversationForkCmd) OpKey

func (c ConversationForkCmd) OpKey() string

func (ConversationForkCmd) Validate

func (c ConversationForkCmd) Validate() error

type ConversationHandoffCmd

type ConversationHandoffCmd struct {
	OpID     string   `json:"opId"`
	ID       string   `json:"id"`
	Provider Provider `json:"provider"`
	Model    *Model   `json:"model"`
	// Profile starts the new conversation on a backend profile (see ConversationCreateCmd.Profile); empty: the CLI's
	// own account. A handoff never inherits the profile of the conversation it comes from: it is how a chat moves to
	// another one.
	Profile string      `json:"profile,omitempty"`
	Mode    HandoffMode `json:"mode"`
	Text    string      `json:"text,omitempty"`
	// ArtifactID is the opaque server-owned history artifact. It is present only in history mode.
	ArtifactID string `json:"artifactId,omitempty"`
}

ConversationHandoffCmd opens a conversation on Provider and Model, in the folder and project of conversation ID, with that conversation's context: Text is the excerpt or the note (the draft the page showed, as the person left it), which the runtime wraps into the new conversation's first message. The conversation it came from stays as it is. The accepted result's ID is the new conversation's id, on convs.

func (ConversationHandoffCmd) Op

func (ConversationHandoffCmd) OpKey

func (c ConversationHandoffCmd) OpKey() string

func (ConversationHandoffCmd) Validate

func (c ConversationHandoffCmd) Validate() error

type ConversationMergeCmd

type ConversationMergeCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
	Text string `json:"text"`
}

ConversationMergeCmd sends a fork's result back into the conversation it came from: Text (the note the fork's agent wrote, as the person left it), wrapped with where it comes from, goes into that conversation's queue as a message whose client id is OpID. The answer is that message's, on the other conversation's channel, with its id.

func (ConversationMergeCmd) Op

func (ConversationMergeCmd) Op() Op

func (ConversationMergeCmd) OpKey

func (c ConversationMergeCmd) OpKey() string

func (ConversationMergeCmd) Validate

func (c ConversationMergeCmd) Validate() error

type ConversationMoveCmd

type ConversationMoveCmd struct {
	OpID      string  `json:"opId"`
	ID        string  `json:"id"`
	ProjectID *string `json:"projectId"`
}

ConversationMoveCmd moves a conversation to a project, or out of any (nil).

func (ConversationMoveCmd) Op

func (ConversationMoveCmd) Op() Op

func (ConversationMoveCmd) OpKey

func (c ConversationMoveCmd) OpKey() string

func (ConversationMoveCmd) Validate

func (c ConversationMoveCmd) Validate() error

type ConversationPinCmd

type ConversationPinCmd struct {
	OpID   string `json:"opId"`
	ID     string `json:"id"`
	Pinned bool   `json:"pinned"`
}

ConversationPinCmd pins or unpins a conversation.

func (ConversationPinCmd) Op

func (ConversationPinCmd) Op() Op

func (ConversationPinCmd) OpKey

func (c ConversationPinCmd) OpKey() string

func (ConversationPinCmd) Validate

func (c ConversationPinCmd) Validate() error

type ConversationRemovedEv

type ConversationRemovedEv struct {
	ID string `json:"id"`
}

ConversationRemovedEv: the conversation is deleted or gone from the list.

func (ConversationRemovedEv) EventType

func (ConversationRemovedEv) EventType() EventType

func (ConversationRemovedEv) MarshalJSON

func (e ConversationRemovedEv) MarshalJSON() ([]byte, error)

func (ConversationRemovedEv) Validate

func (e ConversationRemovedEv) Validate() error

type ConversationRenameCmd

type ConversationRenameCmd struct {
	OpID  string `json:"opId"`
	ID    string `json:"id"`
	Title string `json:"title"`
}

ConversationRenameCmd sets a conversation's title.

func (ConversationRenameCmd) Op

func (ConversationRenameCmd) OpKey

func (c ConversationRenameCmd) OpKey() string

func (ConversationRenameCmd) Validate

func (c ConversationRenameCmd) Validate() error

type ConversationRestoreCmd

type ConversationRestoreCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
}

ConversationRestoreCmd brings a deleted conversation back within its 7 days.

func (ConversationRestoreCmd) Op

func (ConversationRestoreCmd) OpKey

func (c ConversationRestoreCmd) OpKey() string

func (ConversationRestoreCmd) Validate

func (c ConversationRestoreCmd) Validate() error

type ConversationResumeCmd

type ConversationResumeCmd struct {
	OpID      string   `json:"opId"`
	ID        string   `json:"id,omitempty"`
	Provider  Provider `json:"provider,omitempty"`
	SessionID string   `json:"sessionId,omitempty"`
	Cwd       string   `json:"cwd,omitempty"`
}

ConversationResumeCmd starts an agent again on a session: a stopped conversation's own (ID), or one the agent CLI kept on the machine that no conversation holds (Provider, SessionID, Cwd), which opens a new conversation. Exactly one of the two forms.

func (ConversationResumeCmd) Op

func (ConversationResumeCmd) OpKey

func (c ConversationResumeCmd) OpKey() string

func (ConversationResumeCmd) Validate

func (c ConversationResumeCmd) Validate() error

type ConversationRetitleCmd

type ConversationRetitleCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
}

ConversationRetitleCmd asks the agent's cheap model to name the conversation anew from what it holds. The title comes back on the record (source «agent»), a name the person typed gives way to it: they asked.

func (ConversationRetitleCmd) Op

func (ConversationRetitleCmd) OpKey

func (c ConversationRetitleCmd) OpKey() string

func (ConversationRetitleCmd) Validate

func (c ConversationRetitleCmd) Validate() error

type ConversationSeenEv

type ConversationSeenEv struct {
	ID     string `json:"id"`
	SeenAt Ms     `json:"seenAt"`
	Rev    int64  `json:"rev"`
}

ConversationSeenEv is a conversation's new seenAt.

func (ConversationSeenEv) EventType

func (ConversationSeenEv) EventType() EventType

func (ConversationSeenEv) MarshalJSON

func (e ConversationSeenEv) MarshalJSON() ([]byte, error)

func (ConversationSeenEv) Validate

func (e ConversationSeenEv) Validate() error

type ConversationStateEv

type ConversationStateEv struct {
	ID    string     `json:"id"`
	State AgentState `json:"state"`
	Rev   int64      `json:"rev"`
}

ConversationStateEv is a conversation's new agent state; Rev is the record's revision after it.

func (ConversationStateEv) EventType

func (ConversationStateEv) EventType() EventType

func (ConversationStateEv) MarshalJSON

func (e ConversationStateEv) MarshalJSON() ([]byte, error)

func (ConversationStateEv) Validate

func (e ConversationStateEv) Validate() error

type ConversationSummarizeCmd

type ConversationSummarizeCmd struct {
	OpID   string `json:"opId"`
	ID     string `json:"id"`
	TurnID string `json:"turnId"`
}

ConversationSummarizeCmd asks the cheap model for a few lines on what the agent did in the conversation's last turn, for the notification that the turn is done. They come back on the record as its recap — unless Claude wrote a recap of its own after the turn ended — and stand, as a recap does, until the person writes again. The model is called once a turn, however many pages ask.

func (ConversationSummarizeCmd) Op

func (ConversationSummarizeCmd) OpKey

func (c ConversationSummarizeCmd) OpKey() string

func (ConversationSummarizeCmd) Validate

func (c ConversationSummarizeCmd) Validate() error

type ConversationTestCmd

type ConversationTestCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
	Test bool   `json:"test"`
}

ConversationTestCmd marks a conversation as a test chat, or takes the mark off (see Conversation.Test).

func (ConversationTestCmd) Op

func (ConversationTestCmd) Op() Op

func (ConversationTestCmd) OpKey

func (c ConversationTestCmd) OpKey() string

func (ConversationTestCmd) Validate

func (c ConversationTestCmd) Validate() error

type ConversationUpsertEv

type ConversationUpsertEv struct {
	Conv Conversation `json:"conv"`
}

ConversationUpsertEv is a conversation's whole record.

func (ConversationUpsertEv) EventType

func (ConversationUpsertEv) EventType() EventType

func (ConversationUpsertEv) MarshalJSON

func (e ConversationUpsertEv) MarshalJSON() ([]byte, error)

func (ConversationUpsertEv) Validate

func (e ConversationUpsertEv) Validate() error

type ConversationViewCmd

type ConversationViewCmd struct {
	OpID string          `json:"opId"`
	ID   string          `json:"id"`
	View json.RawMessage `json:"view"`
}

ConversationViewCmd keeps how the person left a conversation's window (see Conversation.View): the whole object, the last write wins. An empty object clears it.

func (ConversationViewCmd) Op

func (ConversationViewCmd) Op() Op

func (ConversationViewCmd) OpKey

func (c ConversationViewCmd) OpKey() string

func (ConversationViewCmd) Validate

func (c ConversationViewCmd) Validate() error

type ConvsSnapshot

type ConvsSnapshot struct {
	Conversations []Conversation `json:"conversations"`
	Projects      []Project      `json:"projects"`
	DefaultCwd    string         `json:"defaultCwd"`
	Favorites     *Favorites     `json:"favorites,omitempty"` // absent while nothing is grouped or placed
	Drafts        []Draft        `json:"drafts,omitempty"`    // the composers' drafts kept on the machine; absent while none
}

ConvsSnapshot is the data of a convs snapshot. Projects are the folders of the machine made projects, oldest first; DefaultCwd is the folder a conversation starts in when the person names none (the machine's home), empty when the machine has none to offer.

func FitConvs

func FitConvs(s ConvsSnapshot) ConvsSnapshot

FitConvs keeps a convs snapshot within its budget: the turn snippets get shorter (they are one line of the sidebar), then, for records at their largest, the titles. The events that follow carry the whole records.

func (ConvsSnapshot) Validate

func (s ConvsSnapshot) Validate() error

type DecideCmd

type DecideCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
	PermissionID   string `json:"permissionId"`
	OptionID       string `json:"optionId"`
}

DecideCmd picks an option of a permission or a plan.

func (DecideCmd) Op

func (DecideCmd) Op() Op

func (DecideCmd) OpKey

func (c DecideCmd) OpKey() string

func (DecideCmd) Validate

func (c DecideCmd) Validate() error

type DelegationDelivery

type DelegationDelivery string

DelegationDelivery is when a message an agent sends to another chat (send_to_conversation without its own choice, the news that a delegated chat finished) reaches an agent in the middle of a turn.

const (
	// DelegationStep: inside the running turn, at the agent's next step.
	DelegationStep DelegationDelivery = "step"
	// DelegationTurn: when the turn ends, as the head of the queue.
	DelegationTurn DelegationDelivery = "turn"
)

type DelegationSettings

type DelegationSettings struct {
	MaxChildren int                `json:"maxChildren"`
	AnyChat     bool               `json:"anyChat"`
	Delivery    DelegationDelivery `json:"delivery,omitempty"`
}

DelegationSettings bound the agents' delegation: how many chats one conversation may have delegated (not deleted), whether an agent may write to any chat of the machine rather than only to the ones it delegated, and when a message one agent sends another reaches an agent that works (absent: DelegationStep).

func (DelegationSettings) Steers

func (d DelegationSettings) Steers() bool

Steers says whether a message without a choice of its own goes into the running turn.

type DesignAppKind

type DesignAppKind struct {
	ID      string `json:"id"`
	Title   string `json:"title"`
	App     string `json:"app"`
	AppName string `json:"appName"`
}

DesignAppKind is an app's document type as a project of the library carries it.

type DesignArtifact

type DesignArtifact struct {
	ID          string        `json:"id"`
	Title       string        `json:"title"`
	UpdatedAt   Ms            `json:"updatedAt"`
	Kind        DesignKind    `json:"kind"`
	Pinned      bool          `json:"pinned"`
	Cover       *string       `json:"cover"`
	ProjectPath string        `json:"projectPath"`
	Boards      []DesignBoard `json:"boards"`
	Convs       []string      `json:"convs"`
	TouchedBy   []string      `json:"touchedBy,omitempty"`
	// People are the names of who worked on it: the owner, then the people of the chats in Convs and TouchedBy (a
	// chat's person is whose session started it; a delegated chat's, its root's), each once. Names only, never an
	// address or a chat id; absent from an older runtime.
	People []string     `json:"people,omitempty"`
	Owner  *DesignOwner `json:"owner,omitempty"`
	// Role is what the person may do in the project; absent from a runtime that does not restrict access.
	Role DesignRole `json:"role,omitempty"`
	// AppKind is the app's document type the project is (a type made of Sinopia's site): its label in the
	// library and on the project; absent for a project of Sinopia's own.
	AppKind *DesignAppKind `json:"appKind,omitempty"`
}

DesignArtifact is a project of the library. Convs are the v2 conversations started from it (a new project's first chat, a new chat of the design's column: POST /api/v2/designly/chat). TouchedBy are the other conversations that worked on it: their agent wrote its files or named it to a writing command of the design CLI (read from their transcripts, so it holds for the chats from before), the latest activity first; absent from an older runtime. A chat's folder, a design named in its message or opened from it make it neither. Owner is there for a project made after owners were recorded; an older one has none, and none is guessed.

func (DesignArtifact) Validate

func (a DesignArtifact) Validate() error

type DesignBoard

type DesignBoard struct {
	Title string `json:"title"`
	Path  string `json:"path"`
}

DesignBoard is a board of a project: Path is under the project's folder.

func (DesignBoard) Validate

func (b DesignBoard) Validate() error

type DesignDeckTone added in v0.16.5

type DesignDeckTone string

DesignDeckTone is how a deck's speaker notes are written.

type DesignKind

type DesignKind string

DesignKind is what a project is for.

const (
	DesignSite   DesignKind = "site"
	DesignSlides DesignKind = "slides"
	DesignDS     DesignKind = "ds"
	// DesignVideo is a deck folder with meta/video.json: scenes on a time line rendered to MP4.
	DesignVideo DesignKind = "video"
)

type DesignLibrary

type DesignLibrary struct {
	Port      int              `json:"port"`
	Root      string           `json:"root"`
	Artifacts []DesignArtifact `json:"artifacts"`
}

DesignLibrary is the answer of GET /api/v2/designly/library: the library server's port on the machine (the boards are served there), the library's folder, and the projects.

func (DesignLibrary) Validate

func (l DesignLibrary) Validate() error

type DesignOwner

type DesignOwner struct {
	Name string `json:"name"`
	Me   bool   `json:"me"`
}

DesignOwner is who made a project: the person's name, and whether it is the person asking.

func (DesignOwner) Validate

func (o DesignOwner) Validate() error

type DesignRole

type DesignRole string

DesignRole is a person's role in a project, weakest first.

type DesignSystemInfo

type DesignSystemInfo struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Desc  string `json:"desc"`
}

DesignSystemInfo is a design system the machine has: what a new project may be built on.

func (DesignSystemInfo) Validate

func (d DesignSystemInfo) Validate() error

type DesignSystems

type DesignSystems []DesignSystemInfo

DesignSystems is the answer of GET /api/v2/designly/systems.

func (DesignSystems) Validate

func (d DesignSystems) Validate() error

type DesignVideoFormat added in v0.16.42

type DesignVideoFormat string

DesignVideoFormat is a video's aspect.

type DesignlyChat added in v0.16.123

type DesignlyChat struct {
	ID   string `json:"id"`
	Conv string `json:"conv"`
}

DesignlyChat is the body and the answer of POST /api/v2/designly/chat: the person started conversation Conv from the column of design ID, so it is one of the design's chats.

func (DesignlyChat) Validate added in v0.16.123

func (c DesignlyChat) Validate() error

type DesignlyCreate

type DesignlyCreate struct {
	Title         string         `json:"title"`
	Brief         string         `json:"brief"`
	Kind          DesignKind     `json:"kind"`
	Provider      Provider       `json:"provider"`
	Profile       string         `json:"profile,omitempty"`
	Model         *string        `json:"model"`
	Effort        *Effort        `json:"effort"`
	DesignSystem  *string        `json:"designSystem"`
	Deck          *DesignlyDeck  `json:"deck,omitempty"`
	Video         *DesignlyVideo `json:"video,omitempty"`
	AttachmentIDs []string       `json:"attachmentIds,omitempty"`
}

DesignlyCreate is the body of POST /api/v2/designly/create. Model nil: the agent's default; DesignSystem nil: the library's own. Deck is there only for the kind slides and Video only for the kind video, each only from a page that knows it. AttachmentIDs are uploads (POST /api/v2/upload) the first message carries: the brief's files, a company template.

func (DesignlyCreate) Validate

func (c DesignlyCreate) Validate() error

type DesignlyCreated

type DesignlyCreated struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Conv  string `json:"conv"`
}

DesignlyCreated is the answer of POST /api/v2/designly/create: the project and the conversation opened in it.

func (DesignlyCreated) Validate

func (c DesignlyCreated) Validate() error

type DesignlyDeck added in v0.16.5

type DesignlyDeck struct {
	Minutes int                `json:"minutes"`
	Slides  *int               `json:"slides"`
	Tone    DesignDeckTone     `json:"tone"`
	Script  bool               `json:"script"`
	Style   *DesignlyDeckStyle `json:"style"`
}

DesignlyDeck is what a new deck (kind slides) is asked to be: its length in minutes (0 or absent: the agent decides), its slide count (nil: the agent picks), the tone of the notes, whether the agent writes notes at all, and the company template's style.

func (DesignlyDeck) Validate added in v0.16.5

func (d DesignlyDeck) Validate() error

type DesignlyDeckStyle added in v0.16.5

type DesignlyDeckStyle struct {
	Source  string            `json:"source"`
	Vars    map[string]string `json:"vars"`
	Layouts int               `json:"layouts"`
}

DesignlyDeckStyle is the company template a new deck takes its look from: the file's name, the --deck-* variables read from it (POST /design/deck/pptx-style) and its count of slide layouts.

func (DesignlyDeckStyle) Validate added in v0.16.5

func (s DesignlyDeckStyle) Validate() error

type DesignlyDemo

type DesignlyDemo struct {
	Restored []string `json:"restored"`
}

DesignlyDemo is the answer of POST /api/v2/designly/demo: the demo projects copied back into the library.

func (DesignlyDemo) Validate

func (d DesignlyDemo) Validate() error

type DesignlyError

type DesignlyError struct {
	Code      RefuseCode
	Message   string
	ProjectID string
}

DesignlyError is what a DesignlySource refuses with.

func (*DesignlyError) Error

func (e *DesignlyError) Error() string

type DesignlyPin

type DesignlyPin struct {
	ID     string `json:"id"`
	Pinned bool   `json:"pinned"`
}

DesignlyPin is the body and the answer of POST /api/v2/designly/pin.

func (DesignlyPin) Validate

func (p DesignlyPin) Validate() error

type DesignlyRefusal

type DesignlyRefusal struct {
	R         ResultKind `json:"r"`
	Code      RefuseCode `json:"code"`
	Message   string     `json:"message"`
	ProjectID *string    `json:"projectId"`
}

DesignlyRefusal is the answer of a designly page that refuses: the code of the protocol, a message worded for the person, and the project that was made before the failure, if one was.

func (DesignlyRefusal) Validate

func (d DesignlyRefusal) Validate() error

type DesignlySource

type DesignlySource interface {
	Create(ctx context.Context, c DesignlyCreate) (DesignlyCreated, error)
	Library(ctx context.Context) (DesignLibrary, error)
	Systems(ctx context.Context) ([]DesignSystemInfo, error)
	Pin(ctx context.Context, id string, pinned bool) error
	// Chat records that conversation conv was started from the column of design id.
	Chat(ctx context.Context, id, conv string) error
	// Demo copies back the demo projects the library no longer has; the ones it has are left as they are.
	Demo(ctx context.Context) (DesignlyDemo, error)
}

DesignlySource is the design library of the machine.

type DesignlyVideo added in v0.16.42

type DesignlyVideo struct {
	Formats []DesignVideoFormat `json:"formats"`
	Seconds *int                `json:"seconds"`
	Subs    bool                `json:"subs"`
}

DesignlyVideo is what a new video (kind video) is asked to be: its formats (one or both, no repeats), its length in seconds (nil: the agent decides) and whether the scene's text is burned in as subtitles.

func (DesignlyVideo) Validate added in v0.16.42

func (v DesignlyVideo) Validate() error

type Dir

type Dir struct {
	Path   string  `json:"path"`
	Name   string  `json:"name"`
	Git    bool    `json:"git"`
	Branch *string `json:"branch"`
	Empty  bool    `json:"empty"`
}

Dir is a folder the person may make a project: one the machine offers under its default folder. Branch is the checked out branch of a git folder, nil for any other or one on a detached head; Empty: nothing in it.

func (Dir) Validate

func (d Dir) Validate() error

type DirListing

type DirListing struct {
	Path      string      `json:"path"`
	Entries   []FileEntry `json:"entries"`
	Truncated bool        `json:"truncated"`
	// Root is the place of the workspace an absolute folder lies in: the crumbs go up to it, not further.
	Root string `json:"root,omitempty"`
}

DirListing is the answer of GET /api/v2/conversations/{id}/files?path=<folder>: folders first, then files, by name. Truncated: the folder holds more than the machine looks at (2000 entries).

func (DirListing) Validate

func (d DirListing) Validate() error

type Dirs

type Dirs []Dir

Dirs is the answer of GET /api/v2/dirs: the folders offered, git folders first, then by name.

func (Dirs) Validate

func (d Dirs) Validate() error

type DiskPartID

type DiskPartID string

DiskPartID names a part of the disk layout. Other is the used part none of the named folders accounts for.

const (
	DiskPartWorkspace DiskPartID = "workspace"
	DiskPartCaches    DiskPartID = "caches"
	DiskPartAgents    DiskPartID = "agents"
	DiskPartOther     DiskPartID = "other"
	DiskPartFree      DiskPartID = "free"
)

type Draft

type Draft struct {
	Key         string          `json:"key"`
	Text        string          `json:"text"`
	Attachments []AttachmentRef `json:"attachments,omitempty"`
	// Refs are the places the field points at (MessageRef); absent when none.
	Refs     []MessageRef `json:"refs,omitempty"`
	Rev      int64        `json:"rev"`
	DeviceID string       `json:"deviceId"`
	At       int64        `json:"at"`
}

Draft is the field of one composer: of a conversation (Key is its id) or of the new-chat field (DraftNew), its text and the files already uploaded for it (absent when none: a clear after a send empties both). Rev starts at 1 and grows by one with every write; DeviceID is the device that wrote it, At when (ms).

func (Draft) Validate

func (d Draft) Validate() error

type DraftMode

type DraftMode string

DraftMode is the text a handoff draft is: an excerpt or a note for a handoff, or the result note a fork sends back into the conversation it came from.

const (
	DraftExcerpt DraftMode = "excerpt"
	DraftNote    DraftMode = "note"
	DraftResult  DraftMode = "result"
	DraftHistory DraftMode = "history"
)

type DraftSetCmd

type DraftSetCmd struct {
	OpID        string          `json:"opId"`
	Key         string          `json:"key"`
	Text        string          `json:"text"`
	Attachments []AttachmentRef `json:"attachments,omitempty"`
	Refs        []MessageRef    `json:"refs,omitempty"`
	Rev         int64           `json:"rev"`
}

DraftSetCmd writes a draft: Rev must be the draft's current revision + 1 (1 for a draft the machine does not have), else the answer is refused{conflict} and the page waits for the current draft on the convs channel.

func (DraftSetCmd) Op

func (DraftSetCmd) Op() Op

func (DraftSetCmd) OpKey

func (c DraftSetCmd) OpKey() string

func (DraftSetCmd) SameField

func (c DraftSetCmd) SameField(d Draft) bool

SameField reports whether the command writes what d already holds (text and files).

func (DraftSetCmd) Validate

func (c DraftSetCmd) Validate() error

type DraftUpsertEv

type DraftUpsertEv struct {
	Draft Draft `json:"draft"`
}

DraftUpsertEv is a draft after a write of it.

func (DraftUpsertEv) EventType

func (DraftUpsertEv) EventType() EventType

func (DraftUpsertEv) MarshalJSON

func (e DraftUpsertEv) MarshalJSON() ([]byte, error)

func (DraftUpsertEv) Validate

func (e DraftUpsertEv) Validate() error

type Effort

type Effort string

Effort is a model's reasoning effort.

const (
	EffortLow    Effort = "low"
	EffortMedium Effort = "medium"
	EffortHigh   Effort = "high"
	EffortXHigh  Effort = "xhigh"
	EffortMax    Effort = "max"
	// EffortUltra is above max: the deepest level of the Codex models that have it (gpt-5.6-sol, gpt-5.6-terra).
	EffortUltra Effort = "ultra"
	// EffortUltracode is no effort of the wire any more: records and asks from before ultracode became a mode of its
	// own (Model.Ultracode) said it as one. They are read as xhigh with ultracode on: what `--effort ultracode` runs.
	EffortUltracode Effort = "ultracode"
)

func LegacyUltracode

func LegacyUltracode(e *Effort) (*Effort, bool)

LegacyUltracode reads an effort of before: "ultracode" is xhigh with ultracode on; any other is itself, mode off.

type EntriesPage

type EntriesPage struct {
	TurnID  string  `json:"turnId"`
	Entries []Entry `json:"entries"`
}

EntriesPage is the answer of GET .../turns/{turnId}/entries.

func (EntriesPage) Validate

func (p EntriesPage) Validate() error

type Entry

type Entry struct {
	ID     string    `json:"id"`
	TurnID *string   `json:"turnId"`
	At     Ms        `json:"at"`
	Rev    int64     `json:"rev"`
	T      EntryKind `json:"t"`

	Text         string          `json:"text"` // user, think
	Attachments  []AttachmentRef `json:"attachments"`
	ClientID     *string         `json:"clientId"`
	MD           string          `json:"md"`
	ToolUseID    string          `json:"toolUseId"`
	Tool         string          `json:"tool"`
	Summary      string          `json:"summary"`
	OK           *bool           `json:"ok"`
	Output       *ToolOutput     `json:"output"`
	AgentID      string          `json:"agentId"`
	AgentType    string          `json:"agentType"`
	Description  string          `json:"description"`
	Status       SubagentStatus  `json:"status"`
	Model        *string         `json:"model"`      // subagent: the model it was asked to run on
	DurationMs   *int64          `json:"durationMs"` // subagent: how long it ran, once it has finished
	QuestionID   string          `json:"questionId"`
	Pairs        []AnswerPair    `json:"pairs"`
	PermissionID string          `json:"permissionId"`
	TokensBefore *int64          `json:"tokensBefore"`
	TokensAfter  *int64          `json:"tokensAfter"`
	Keep         []string        `json:"keep"`
	Level        NoticeLevel     `json:"level"`
	Code         string          `json:"code"`
	Detail       *string         `json:"detail"`
	Peers        []PeerNote      `json:"peers"`  // peer: what other agents' sessions wrote to this one
	Images       *ImageGen       `json:"images"` // tool: the picture card of a picture-drawing call; left out for any other
	Call         *ToolCall       `json:"call"`   // tool: what the call says of itself and how it ended; left out when nothing is known
}

Entry is one record of the feed. ID, TurnID, At and Rev are on every kind; the rest only on its T:

user{text, attachments, clientId|null} · say{md} · think{text} ·
tool{toolUseId, tool, summary, ok|null, output|null} · subagent{agentId, agentType, description, status} ·
answers{questionId, pairs} · gate{permissionId} · compaction{tokensBefore|null, tokensAfter|null, keep} ·
notice{level, code, detail|null} · interrupt{}

The id is stable: "c:<jsonl uuid>#<k>" for Claude, "x:<byte offset>#<k>" for Codex and lines without a uuid, "live:<turnId>" for the live reply off the screen. Rev grows as the entry is appended to.

func (Entry) MarshalJSON

func (e Entry) MarshalJSON() ([]byte, error)

func (*Entry) UnmarshalJSON

func (e *Entry) UnmarshalJSON(b []byte) error

func (Entry) Validate

func (e Entry) Validate() error

type EntryKind

type EntryKind string

EntryKind is the kind of a feed Entry.

const (
	EntryUser       EntryKind = "user"
	EntrySay        EntryKind = "say"
	EntryThink      EntryKind = "think"
	EntryTool       EntryKind = "tool"
	EntrySubagent   EntryKind = "subagent"
	EntryAnswers    EntryKind = "answers"
	EntryGate       EntryKind = "gate"
	EntryCompaction EntryKind = "compaction"
	EntryNotice     EntryKind = "notice"
	EntryInterrupt  EntryKind = "interrupt"
	EntryPeer       EntryKind = "peer"
)

type EntryReplaceEv

type EntryReplaceEv struct {
	OldID string `json:"oldId"`
	Entry Entry  `json:"entry"`
}

EntryReplaceEv swaps an entry for another id, as the live reply for its transcript line.

func (EntryReplaceEv) EventType

func (EntryReplaceEv) EventType() EventType

func (EntryReplaceEv) MarshalJSON

func (e EntryReplaceEv) MarshalJSON() ([]byte, error)

func (EntryReplaceEv) Validate

func (e EntryReplaceEv) Validate() error

type EntryUpdateEv

type EntryUpdateEv struct {
	Entry Entry `json:"entry"`
}

EntryUpdateEv is an entry with the same id and a higher rev.

func (EntryUpdateEv) EventType

func (EntryUpdateEv) EventType() EventType

func (EntryUpdateEv) MarshalJSON

func (e EntryUpdateEv) MarshalJSON() ([]byte, error)

func (EntryUpdateEv) Validate

func (e EntryUpdateEv) Validate() error

type ErrorFrame

type ErrorFrame struct {
	Ch   Channel        `json:"ch,omitempty"`
	Code FrameErrorCode `json:"code"`
}

ErrorFrame refuses a frame; Ch is the channel it was about, if any.

func (ErrorFrame) MarshalJSON

func (f ErrorFrame) MarshalJSON() ([]byte, error)

func (ErrorFrame) ServerFrameKind

func (ErrorFrame) ServerFrameKind() FrameKind

func (ErrorFrame) Validate

func (f ErrorFrame) Validate() error

type EvFrame

type EvFrame struct {
	Ch  Channel `json:"ch"`
	Seq int64   `json:"seq"`
	E   Event   `json:"e"`
}

EvFrame is one event of a channel; a gap in Seq means a new sub with the cursor.

func (EvFrame) MarshalJSON

func (f EvFrame) MarshalJSON() ([]byte, error)

func (EvFrame) ServerFrameKind

func (EvFrame) ServerFrameKind() FrameKind

func (*EvFrame) UnmarshalJSON

func (f *EvFrame) UnmarshalJSON(b []byte) error

func (EvFrame) Validate

func (f EvFrame) Validate() error

type Event

type Event interface {
	EventType() EventType
	Validate() error
}

Event is one change on a channel. The events of the machine channel are MachineEventTypes, of convs ConvsEventTypes and of conv:<id> ConvEventTypes.

func DecodeEvent

func DecodeEvent(b []byte) (Event, error)

DecodeEvent reads and checks one event; an unknown type or field is an error.

type EventType

type EventType string

EventType is the kind of an Event, in its "type" field.

const (
	EvMachineStatus EventType = "machine_status"
	EvMachineLoad   EventType = "machine_load"
)
const (
	EvConversationUpsert  EventType = "conversation_upsert"
	EvConversationState   EventType = "conversation_state"
	EvConversationSeen    EventType = "conversation_seen"
	EvConversationRemoved EventType = "conversation_removed"
	EvProjectUpsert       EventType = "project_upsert"
	EvFavoritesUpsert     EventType = "favorites_upsert"
	EvDraftUpsert         EventType = "draft_upsert"
)
const (
	EvTurnStarted         EventType = "turn_started"
	EvStep                EventType = "step"
	EvEntryUpdate         EventType = "entry_update"
	EvEntryReplace        EventType = "entry_replace"
	EvNow                 EventType = "now"
	EvQuestionAsked       EventType = "question_asked"
	EvPermissionRequested EventType = "permission_requested"
	EvPlanProposed        EventType = "plan_proposed"
	EvGateUpdated         EventType = "gate_updated"
	EvCompaction          EventType = "compaction"
	EvTurnFinished        EventType = "turn_finished"
	EvTurnFailed          EventType = "turn_failed"
	EvQuotaExhausted      EventType = "quota_exhausted"
	EvQueueChanged        EventType = "queue_changed"
	EvPromptState         EventType = "prompt_state"
	EvMessageUpsert       EventType = "message_upsert"
	EvBackgroundUpsert    EventType = "background_upsert"
	EvBackgroundRemoved   EventType = "background_removed"
	EvShotsSet            EventType = "shots_set"
	EvPicturesSet         EventType = "pictures_set"
	EvFeedReset           EventType = "feed_reset"
)

func ChannelEvents

func ChannelEvents(c Channel) []EventType

ChannelEvents is the event types a channel carries.

type FavGroup

type FavGroup struct {
	ID    string   `json:"id"`
	Name  string   `json:"name"`
	Chats []string `json:"chats"`
}

FavGroup is a named group inside the favorites; Chats are the ids of its conversations in the order shown.

func (FavGroup) Validate

func (g FavGroup) Validate() error

type FavGroupCreateCmd

type FavGroupCreateCmd struct {
	OpID string `json:"opId"`
	Name string `json:"name"`
}

FavGroupCreateCmd makes an empty group in the favorites; the accepted result's ID is the new group's id.

func (FavGroupCreateCmd) Op

func (FavGroupCreateCmd) Op() Op

func (FavGroupCreateCmd) OpKey

func (c FavGroupCreateCmd) OpKey() string

func (FavGroupCreateCmd) Validate

func (c FavGroupCreateCmd) Validate() error

type FavGroupDeleteCmd

type FavGroupDeleteCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
}

FavGroupDeleteCmd removes a group; its chats stay in the favorites, ungrouped.

func (FavGroupDeleteCmd) Op

func (FavGroupDeleteCmd) Op() Op

func (FavGroupDeleteCmd) OpKey

func (c FavGroupDeleteCmd) OpKey() string

func (FavGroupDeleteCmd) Validate

func (c FavGroupDeleteCmd) Validate() error

type FavGroupMoveCmd

type FavGroupMoveCmd struct {
	OpID     string  `json:"opId"`
	ID       string  `json:"id"`
	BeforeID *string `json:"beforeId"`
}

FavGroupMoveCmd puts a group before another one (BeforeID), or last when BeforeID is nil.

func (FavGroupMoveCmd) Op

func (FavGroupMoveCmd) Op() Op

func (FavGroupMoveCmd) OpKey

func (c FavGroupMoveCmd) OpKey() string

func (FavGroupMoveCmd) Validate

func (c FavGroupMoveCmd) Validate() error

type FavGroupRenameCmd

type FavGroupRenameCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
	Name string `json:"name"`
}

FavGroupRenameCmd renames a group of the favorites.

func (FavGroupRenameCmd) Op

func (FavGroupRenameCmd) Op() Op

func (FavGroupRenameCmd) OpKey

func (c FavGroupRenameCmd) OpKey() string

func (FavGroupRenameCmd) Validate

func (c FavGroupRenameCmd) Validate() error

type FavPlaceCmd

type FavPlaceCmd struct {
	OpID     string  `json:"opId"`
	ID       string  `json:"id"`
	GroupID  *string `json:"groupId"`
	BeforeID *string `json:"beforeId"`
}

FavPlaceCmd puts a conversation into the favorites — pinning it when it is not — in a group (GroupID) or ungrouped (nil), before another conversation of that place (BeforeID) or last when BeforeID is nil. A conversation already in the favorites is moved.

func (FavPlaceCmd) Op

func (FavPlaceCmd) Op() Op

func (FavPlaceCmd) OpKey

func (c FavPlaceCmd) OpKey() string

func (FavPlaceCmd) Validate

func (c FavPlaceCmd) Validate() error

type Favorites

type Favorites struct {
	Groups []FavGroup `json:"groups"`
	Loose  []string   `json:"loose"`
}

Favorites is how the pinned conversations are laid out: the groups in their order, then the conversations that belong to none (Loose) in theirs. Whether a conversation is a favorite is its own `pinned`; this is only where it stands. A pinned conversation the layout does not name shows first among the loose, the newest created first, and an id the layout names for a conversation that is not pinned (or gone) is ignored: both ways the pin of an older page stays right without the layout being told.

func EmptyFavorites

func EmptyFavorites() Favorites

EmptyFavorites is a layout with no groups and no one placed, as a machine starts with.

func (Favorites) Clone

func (f Favorites) Clone() Favorites

Clone is a copy that shares nothing with f; its lists are never nil.

func (Favorites) GroupMoved

func (f Favorites) GroupMoved(id string, before *string) (Favorites, bool)

GroupMoved puts a group before another (before), or last when before is nil; false when either is not there.

func (Favorites) HasGroup

func (f Favorites) HasGroup(id string) bool

HasGroup reports whether the layout has the group.

func (Favorites) MarshalJSON

func (f Favorites) MarshalJSON() ([]byte, error)

MarshalJSON writes the lists as arrays even when nil.

func (Favorites) Normalized

func (f Favorites) Normalized(pinned []string) Favorites

Normalized keeps only the conversations of pinned (the newest created first), once each, where the layout had them, and puts the pinned ones it did not name at the front of the loose.

func (Favorites) Placed

func (f Favorites) Placed(id string, group, before *string) (Favorites, bool)

Placed puts the conversation id, which is pinned, into group (nil: the loose) before another of that place or last. It is taken out of the place it had; false when the group is not there.

func (Favorites) Renamed

func (f Favorites) Renamed(id, name string) (Favorites, bool)

Renamed is f with a group's name changed; false when there is no such group.

func (Favorites) Validate

func (f Favorites) Validate() error

func (Favorites) WithGroup

func (f Favorites) WithGroup(g FavGroup) Favorites

WithGroup adds a group last.

func (Favorites) Without

func (f Favorites) Without(id string) (Favorites, bool)

Without removes a group; its conversations become the first of the loose, in their order.

type FavoritesUpsertEv

type FavoritesUpsertEv struct {
	Favorites Favorites `json:"favorites"`
}

FavoritesUpsertEv is the favorites' whole layout, after any change of it.

func (FavoritesUpsertEv) EventType

func (FavoritesUpsertEv) EventType() EventType

func (FavoritesUpsertEv) MarshalJSON

func (e FavoritesUpsertEv) MarshalJSON() ([]byte, error)

func (FavoritesUpsertEv) Validate

func (e FavoritesUpsertEv) Validate() error

type Feature

type Feature string

Feature is a capability a runtime announces in hello and welcome.

const (
	FeatureQueue       Feature = "queue"
	FeatureSteer       Feature = "steer"
	FeatureQuestions   Feature = "questions"
	FeaturePermissions Feature = "permissions"
	FeatureBackground  Feature = "background"
	FeatureModel       Feature = "model"
	FeatureVoice       Feature = "voice"
	FeatureFiles       Feature = "files"
	FeatureCheckpoints Feature = "checkpoints"
	FeatureDesignly    Feature = "designly"
	FeatureSearch      Feature = "search"
	FeatureVault       Feature = "vault"
	FeaturePush        Feature = "push"
	FeatureTerminal    Feature = "terminal"
	FeatureMachine     Feature = "machine"
	FeatureApps        Feature = "apps"
	FeatureSettings    Feature = "settings"
	FeatureDrafts      Feature = "drafts"
	FeatureQueueMove   Feature = "queue-move"
	// FeatureTerminalStop: terminal.stop ends a conversation's terminal, the runtime stops idle ones by itself, and
	// GET/PUT /api/v2/runtime-settings say after how long.
	FeatureTerminalStop Feature = "terminal-stop"
	FeatureAppsHub      Feature = "apps-hub"
	// FeatureChatView: conversation.view keeps how the person left a chat's window (Conversation.View), for any device.
	FeatureChatView Feature = "chat-view"
	// FeatureRewind: rewind and rewind.undo go on from before one of the person's messages, GET .../rewind?entryId=
	// says what that would do and GET .../rewinds/{n}/turns shows what a rewind left behind.
	FeatureRewind Feature = "rewind"
	// FeatureFork: conversation.fork branches a conversation off another one, and conversation.merge sends a fork's
	// result back (POST …/handoff-draft {mode: result} writes it).
	FeatureFork Feature = "fork"
	// FeatureHandoff: conversation.handoff opens a conversation on another agent with this one's context, drafted by
	// POST …/handoff-draft.
	FeatureHandoff Feature = "handoff"
	// FeatureAutoContinue: a chat held on its usage limit (Conversation.Limited) goes on by itself at the reset, limit
	// moves or cancels that, and a turn a restart cut short goes on by itself (runtime settings limitContinue,
	// restartContinue).
	FeatureAutoContinue Feature = "auto-continue"
	// FeatureMade: GET /api/v2/conversations/{id}/made lists what the chat made, opened or changed (docs, boards, designs).
	FeatureMade Feature = "made"
	// FeatureAgentBrowser exposes the conversation browser socket; it does not imply agent tools are installed.
	FeatureAgentBrowser Feature = "agent-browser"
	// FeatureSnapshotAfter: a conversation's snapshot after an entry (SubFrame.AfterEntryID) carries every turn from that
	// entry's own on as it is now, so a page drawn from elsewhere learns the turn's state.
	FeatureSnapshotAfter Feature = "snapshot-after"
)

type FeedResetEv

type FeedResetEv struct {
	Turns        []Turn  `json:"turns"`
	Entries      []Entry `json:"entries"`
	BeforeTurnID *string `json:"beforeTurnId"`
}

FeedResetEv is the feed as it is now, after a rewind or its undo replaced the transcript under it: the page drops the turns and entries it holds and takes these (the newest turns, as a snapshot's), with BeforeTurnID the cursor for older ones.

func (FeedResetEv) EventType

func (FeedResetEv) EventType() EventType

func (FeedResetEv) MarshalJSON

func (e FeedResetEv) MarshalJSON() ([]byte, error)

func (FeedResetEv) Validate

func (e FeedResetEv) Validate() error

type FileChange

type FileChange string

FileChange is what returning to a snapshot does to a file.

const (
	FileRestored FileChange = "restored" // it is not there now, the snapshot had it
	FileChanged  FileChange = "changed"
	FileRemoved  FileChange = "removed" // it is there now, the snapshot did not have it
)

type FileContent

type FileContent struct {
	Path     string `json:"path"`
	Content  string `json:"content"`
	Revision string `json:"revision"`
	Bytes    int    `json:"bytes"`
	// ReadOnly: the file lies outside the conversation's folder and opened only because the agent showed it or it is in
	// the workspace's places; it is read, never saved.
	ReadOnly bool `json:"readOnly,omitempty"`
}

FileContent is the answer of GET /api/v2/conversations/{id}/file?path=<file>: a UTF-8 text file of at most 1 MB, with the revision a save must name; a save answers with the file as it is now.

func (FileContent) Validate

func (f FileContent) Validate() error

type FileEntry

type FileEntry struct {
	Name string   `json:"name"`
	Path string   `json:"path"`
	Kind FileKind `json:"kind"`
	Git  FileGit  `json:"git,omitempty"`
}

FileEntry is one entry of a folder: its name, its path from the conversation's folder.

func (FileEntry) Validate

func (e FileEntry) Validate() error

type FileError

type FileError struct {
	Code    RefuseCode
	Message string
}

FileError is what a FilesSource refuses with: forbidden (outside the folder, no access), not-found (gone, or not a folder), unsupported (not text, not UTF-8, over 1 MB), conflict (a save over a file that changed), internal.

func (*FileError) Error

func (e *FileError) Error() string

type FileGit added in v0.16.123

type FileGit string

FileGit is what git says of an entry: a file or folder git does not have yet, or one with changes not committed. A folder is new when all that changed in it is new. An entry git has nothing to say of has none.

const (
	FileGitNew     FileGit = "new"
	FileGitChanged FileGit = "changed"
)

type FileKind

type FileKind string

FileKind is what a listed entry is. Links and special files are not listed.

const (
	FileFile      FileKind = "file"
	FileDirectory FileKind = "directory"
)

type FileMe

type FileMe struct {
	Path string
	Name string
	// contains filtered or unexported fields
}

FileMe is a MeStore in a file; Name is shown as the person's name.

func (*FileMe) Me

func (f *FileMe) Me() (Me, error)

func (*FileMe) Patch

func (f *FileMe) Patch(rev int64, patch json.RawMessage) (Me, error)

type FileOp

type FileOp string

FileOp is what a turn did to a file.

const (
	FileCreated FileOp = "created"
	FileEdited  FileOp = "edited"
	FileRead    FileOp = "read"
)

type FileRefusal

type FileRefusal struct {
	R       ResultKind `json:"r"`
	Code    RefuseCode `json:"code"`
	Message string     `json:"message"`
}

FileRefusal is the answer of a files page that refuses: the code of the protocol and a message worded for the person.

func (FileRefusal) Validate

func (f FileRefusal) Validate() error

type FileRuntimeSettings

type FileRuntimeSettings struct {
	Path string
	// contains filtered or unexported fields
}

FileRuntimeSettings is a RuntimeSettingsStore in a file. A file that is missing or does not read is the defaults; so is a value it does not know.

func (*FileRuntimeSettings) RuntimeSettings

func (f *FileRuntimeSettings) RuntimeSettings() RuntimeSettings

func (*FileRuntimeSettings) SetRuntimeSettings

func (f *FileRuntimeSettings) SetRuntimeSettings(s RuntimeSettings) (RuntimeSettings, error)

type FileSave

type FileSave struct {
	Content  string `json:"content"`
	Revision string `json:"revision"`
}

FileSave is the body of PUT /api/v2/conversations/{id}/file?path=<file>: the whole new text over the revision the page read. A file that changed since is refused as a conflict.

func (FileSave) Validate

func (f FileSave) Validate() error

type FilesSource

type FilesSource interface {
	Dir(ctx context.Context, conv, path string) (DirListing, error)
	File(ctx context.Context, conv, path string) (FileContent, error)
	Save(ctx context.Context, conv, path, content, revision string) (FileContent, error)
}

FilesSource reads and saves the folder of a conversation. Errors: convo.ErrNotFound (no such conversation), a *FileError.

type FirstMessage

type FirstMessage struct {
	ClientID      string   `json:"clientId"`
	Text          string   `json:"text"`
	AttachmentIDs []string `json:"attachmentIds"`
	// Refs are the places the first message points at (as SendCmd.Refs); absent when none.
	Refs []MessageRef `json:"refs,omitempty"`
}

FirstMessage is the message a new conversation starts with.

type FrameErrorCode

type FrameErrorCode string

FrameErrorCode is why the socket refused a frame.

const (
	FrameErrProto        FrameErrorCode = "proto"
	FrameErrBadChannel   FrameErrorCode = "bad-channel"
	FrameErrNotFound     FrameErrorCode = "not-found"
	FrameErrTooManySubs  FrameErrorCode = "too-many-subs"
	FrameErrUnauthorized FrameErrorCode = "unauthorized"
)

type FrameKind

type FrameKind string

FrameKind is the kind of a socket frame, in its "f" field.

const (
	FrameHello FrameKind = "hello"
	FrameSub   FrameKind = "sub"
	FrameUnsub FrameKind = "unsub"
	FramePing  FrameKind = "ping"
)
const (
	FrameWelcome  FrameKind = "welcome"
	FrameSnapshot FrameKind = "snapshot"
	FrameEv       FrameKind = "ev"
	FramePong     FrameKind = "pong"
	FrameError    FrameKind = "error"
)

type GateCloseReason

type GateCloseReason string

GateCloseReason is why a gate closed without an answer.

const (
	ClosedAgentMovedOn GateCloseReason = "agent-moved-on"
	ClosedChatAbout    GateCloseReason = "chat-about"
	ClosedTurnEnded    GateCloseReason = "turn-ended"
	ClosedAgentGone    GateCloseReason = "agent-gone"
)

type GateKind

type GateKind string

GateKind is the kind of an open gate on a conversation.

const (
	GateQuestion   GateKind = "question"
	GatePermission GateKind = "permission"
	GatePlan       GateKind = "plan"
)

type GateRef

type GateRef struct {
	Kind GateKind `json:"kind"`
	ID   string   `json:"id"`
}

GateRef points at a conversation's open question, permission or plan.

type GateRefusal

type GateRefusal string

GateRefusal is why a decision taken on the page did not reach the agent's menu.

const (
	// GateRefusedMenuUnmatched: the menu on the screen could not be matched with the one decided on.
	GateRefusedMenuUnmatched GateRefusal = "menu-unmatched"
)

type GateState

type GateState struct {
	K        GateStateKind   `json:"k"`
	OpID     string          `json:"opId"`
	Wait     *Wait           `json:"wait"`
	At       Ms              `json:"at"`
	ByDevice string          `json:"byDevice"`
	Reason   GateCloseReason `json:"reason"`
	// Refused: an open gate the page decided on whose menu the machine could not match on the agent's screen; no key
	// went in, the person decides in the terminal. Absent otherwise.
	Refused *GateRefusal `json:"refused"`
	// AutoDenyAt: an open permission whose prompt says Claude denies it by itself (an unattended session) — when it
	// does (epoch ms), read off the screen. Absent otherwise.
	AutoDenyAt *Ms `json:"autoDenyAt"`
}

GateState is where a question or a permission is. Only the fields of K are on the wire:

open{} · answering{opId, wait} · answered{at, byDevice} · closed{reason}

func (GateState) MarshalJSON

func (s GateState) MarshalJSON() ([]byte, error)

func (*GateState) UnmarshalJSON

func (s *GateState) UnmarshalJSON(b []byte) error

func (GateState) Validate

func (s GateState) Validate() error

type GateStateKind

type GateStateKind string

GateStateKind is the kind of a GateState.

const (
	GateStateOpen      GateStateKind = "open"
	GateStateAnswering GateStateKind = "answering"
	GateStateAnswered  GateStateKind = "answered"
	GateStateClosed    GateStateKind = "closed"
)

type GateUpdatedEv

type GateUpdatedEv struct {
	ID    string    `json:"id"`
	State GateState `json:"state"`
}

GateUpdatedEv is a question's or a permission's new state.

func (GateUpdatedEv) EventType

func (GateUpdatedEv) EventType() EventType

func (GateUpdatedEv) MarshalJSON

func (e GateUpdatedEv) MarshalJSON() ([]byte, error)

func (GateUpdatedEv) Validate

func (e GateUpdatedEv) Validate() error

type GlanceMessage

type GlanceMessage struct {
	At   Ms     `json:"at"`
	Text string `json:"text"`
}

GlanceMessage is one message of a chat in its glance: when, and what it said, cut short.

type Goal

type Goal struct {
	Text   string     `json:"text"`
	Status GoalStatus `json:"status"`
	Since  Ms         `json:"since"`
}

Goal is the /goal of an agent's session: the condition it keeps working toward. Since is when the goal was set.

type GoalCmd

type GoalCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
	Text string `json:"text"`
}

GoalCmd sets the session's /goal (Claude only): «/goal text» is typed into the agent, and an empty text clears it («/goal clear»). It queues as a command message; the goal on the record follows what the transcript says.

func (GoalCmd) Op

func (GoalCmd) Op() Op

func (GoalCmd) OpKey

func (c GoalCmd) OpKey() string

func (GoalCmd) Validate

func (c GoalCmd) Validate() error

type GoalStatus

type GoalStatus string

GoalStatus is where a goal is: active, paused (the agent stopped checking until the person writes), or met.

const (
	GoalActive GoalStatus = "active"
	GoalPaused GoalStatus = "paused"
	GoalMet    GoalStatus = "met"
)

type GoneReason

type GoneReason string

GoneReason is why a conversation's tab is gone.

const (
	GoneTabClosed GoneReason = "tab-closed"
	GoneTmuxLost  GoneReason = "tmux-lost"
)

type HandedWhere added in v0.15.46

type HandedWhere string

HandedWhere is where a message handed to the agent is now.

const (
	// HandedInputBox: typed into the agent's input box, not taken yet.
	HandedInputBox HandedWhere = "input-box"
	// HandedAgentQueue: typed into a working agent, which holds it in its own queue until its next step.
	HandedAgentQueue HandedWhere = "agent-queue"
	// HandedAgent: the agent took it (its prompt-submit hook), its transcript entry not read yet.
	HandedAgent HandedWhere = "agent"
	// HandedTranscript: the transcript has its entry (EntryID).
	HandedTranscript HandedWhere = "transcript"
)

type HandoffArtifact added in v0.16.5

type HandoffArtifact struct {
	ID    string `json:"id"`
	Bytes int64  `json:"bytes"`
}

HandoffArtifact is private handoff material held by the runtime. The page receives only its opaque ID and size, never the filesystem path.

func (HandoffArtifact) Validate added in v0.16.5

func (a HandoffArtifact) Validate() error

type HandoffDraft

type HandoffDraft struct {
	Mode     DraftMode        `json:"mode"`
	Text     string           `json:"text,omitempty"`
	Tokens   int              `json:"tokens"`
	Turns    int              `json:"turns"`
	Artifact *HandoffArtifact `json:"artifact,omitempty"`
}

HandoffDraft answers POST /api/v2/conversations/{id}/handoff-draft {mode, provider?, model?}: the text a handoff or a merge would carry, for the page to show and the person to edit before it goes. Tokens is its size as the runtime estimates it (about four characters a token); Turns is how many of the conversation's turns an excerpt holds.

func (HandoffDraft) Validate

func (d HandoffDraft) Validate() error

type HandoffDraftRequest

type HandoffDraftRequest struct {
	Mode     DraftMode `json:"mode"`
	Provider Provider  `json:"provider,omitempty"`
	Model    string    `json:"model,omitempty"`
	// Profile is the backend profile the context goes to (its models have windows of their own).
	Profile string `json:"profile,omitempty"`
}

HandoffDraftRequest is the body of POST /api/v2/conversations/{id}/handoff-draft. Provider and Model name the agent the context goes to: an excerpt is cut to fit its window.

func (HandoffDraftRequest) Validate

func (r HandoffDraftRequest) Validate() error

type HandoffMode

type HandoffMode string

HandoffMode is how a conversation's context goes to a new one on another agent or model: an excerpt of its transcript, or a note its own agent writes for the next one.

const (
	HandoffExcerpt HandoffMode = "excerpt"
	HandoffNote    HandoffMode = "note"
	HandoffHistory HandoffMode = "history"
)

type HealthIssue

type HealthIssue struct {
	Metric HealthMetric `json:"metric"`
	Level  HealthLevel  `json:"level"`
}

HealthIssue is one metric past its line: warn or critical, never ok.

func (HealthIssue) Validate

func (i HealthIssue) Validate() error

type HealthLevel

type HealthLevel string

HealthLevel is how a machine stands: ok, warn (worth a look) or critical (work is about to fail).

const (
	HealthOK       HealthLevel = "ok"
	HealthWarn     HealthLevel = "warn"
	HealthCritical HealthLevel = "critical"
)

type HealthMetric

type HealthMetric string

HealthMetric is what a health issue is about: the data folder's disk, memory (with swap-in), sustained CPU, or tasks that wait for a disk or the network while the CPU is idle.

const (
	HealthDisk HealthMetric = "disk"
	HealthMem  HealthMetric = "mem"
	HealthCPU  HealthMetric = "cpu"
	// HealthIO: the load is high while the processors stand idle, so the tasks wait for a disk or the network.
	HealthIO HealthMetric = "io"
)

type HealthStall

type HealthStall struct {
	Mounts  []string `json:"mounts"`
	Waiting []string `json:"waiting"`
}

HealthStall is what the machine knows of a stall, a load its processors do not explain: the network folders whose server stopped answering (their mount points; empty when none did) and the programs with the most tasks waiting, most first (their short names; empty when none could be read).

type Hello

type Hello struct {
	Proto    int       `json:"proto"`
	Version  string    `json:"version"`
	Features []Feature `json:"features"`
}

Hello is the answer of GET /api/v2/hello; a 404 there is a runtime without v2.

func (Hello) Validate

func (h Hello) Validate() error

type HelloFrame

type HelloFrame struct {
	Proto  int    `json:"proto"`
	Device string `json:"device"`
	App    string `json:"app"`
}

HelloFrame opens the socket; Device is the device's stable id.

func (HelloFrame) ClientFrameKind

func (HelloFrame) ClientFrameKind() FrameKind

func (HelloFrame) MarshalJSON

func (f HelloFrame) MarshalJSON() ([]byte, error)

func (HelloFrame) Validate

func (f HelloFrame) Validate() error

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub numbers the events of every channel, keeps their rings and hands each event to the sockets subscribed to it. It is the Publisher of the conversations (convo.Publisher) and of the machine source.

The order of a subscription is a protocol invariant (README 21): the hub subscribes a socket to the channel before the snapshot is taken, holds the events that arrive meanwhile, and sends them after the snapshot, which carries the seq the channel had when the socket was subscribed. The page drops events at or below that seq and applies the rest idempotently by id and rev.

func NewHub

func NewHub(machine MachineSource) *Hub

NewHub starts a hub with a new epoch; machine may be nil when nothing serves the machine channel.

func (*Hub) Channels

func (h *Hub) Channels() int

Channels is how many channels the hub holds now.

func (*Hub) Close

func (h *Hub) Close()

Close closes every socket, as the runtime stops.

func (*Hub) Drop

func (h *Hub) Drop()

Drop cuts every socket without a close frame, as a network that goes away does.

func (*Hub) Epoch

func (h *Hub) Epoch() string

Epoch is the hub's current epoch.

func (*Hub) Forget

func (h *Hub) Forget(ch Channel) bool

Forget drops a conversation's channel that no socket holds, whatever its ring still keeps: the conversation is deleted. It reports whether the channel is gone.

func (*Hub) Publish

func (h *Hub) Publish(ch Channel, e Event) (seq int64)

Publish gives e the next seq of ch, keeps it in the channel's ring and sends it to the channel's sockets. An event that does not go on ch, or does not encode, is a bug of the caller: it is logged and dropped, and the seq is 0.

func (*Hub) Reset

func (h *Hub) Reset()

Reset starts a new epoch, as a restart of the runtime does: every channel starts again from seq 0 with an empty ring, and every socket is closed so its page comes back with its cursor.

func (*Hub) Seq

func (h *Hub) Seq(ch Channel) int64

Seq is a channel's last seq, 0 before its first event.

func (*Hub) Subscribers

func (h *Hub) Subscribers(ch Channel) int

Subscribers is how many sockets hold ch now: a conv:<id> with any is a chat someone has open.

func (*Hub) Sweep

func (h *Hub) Sweep()

Sweep lets go of what the quiet channels hold: a channel without a socket gives back the events past RingAge, and a conversation's channel that then has neither a socket nor an event is dropped whole. The hub held a channel, and the buffer of its busiest moment, for every conversation that ever published — the stopped and the deleted ones too. A dropped channel starts again past its last seq (floor): a page that comes back with a cursor of it is given a snapshot, as after any gap.

func (*Hub) Tap added in v0.16.5

func (h *Hub) Tap(fn func(ch Channel, seq int64, frame []byte), end func()) (stop func())

Tap calls fn with every event published on `convs` and on the conversations' channels from now on — its channel, its seq and the frame as the newest page reads it — in publish order, and returns the function that ends it. fn runs under the hub's lock: it must not wait. end is called when the hub starts a new epoch or stops: the seqs the tap saw end there.

type IdleStop

type IdleStop string

IdleStop is after how long without work the runtime stops a conversation's terminal by itself; off never.

const (
	IdleStopOff IdleStop = "off"
	IdleStop1h  IdleStop = "1h"
	IdleStop2h  IdleStop = "2h"
	IdleStop6h  IdleStop = "6h"
)

func (IdleStop) After

func (s IdleStop) After() time.Duration

After is the time an IdleStop names; 0 for off or a value it does not know.

type ImageGen added in v0.16.86

type ImageGen struct {
	Count  int      `json:"count"`
	Prompt string   `json:"prompt"`
	Shape  string   `json:"shape"` // square | landscape | portrait, "" when not told
	JobID  string   `json:"jobId"` // harnessly's job, "" for Codex's own tool
	State  string   `json:"state"` // drawing | done | failed
	Done   []string `json:"done"`
	Failed *string  `json:"failed"`
}

ImageGen is the picture card of a tool call that draws pictures (Codex's image_gen, harnessly's generate_images). Done are the files so far, as absolute paths on the machine; Count is how many the call asked for.

type InterruptCmd

type InterruptCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
	PauseQueue     *bool  `json:"pauseQueue,omitempty"`
}

InterruptCmd presses Escape once; the queue pauses unless PauseQueue is false.

func (InterruptCmd) Op

func (InterruptCmd) Op() Op

func (InterruptCmd) OpKey

func (c InterruptCmd) OpKey() string

func (InterruptCmd) Pauses

func (c InterruptCmd) Pauses() bool

Pauses reports whether the interrupt pauses the queue; it does unless the page said false.

func (InterruptCmd) Validate

func (c InterruptCmd) Validate() error

type Launch

type Launch struct {
	ID     string `json:"id"`
	Prompt string `json:"prompt"`
}

Launch is what the conversations of one prompt started on several models share: the id of the launch and the prompt.

type LaunchFailure

type LaunchFailure string

LaunchFailure is why an agent did not come up.

const (
	LaunchFailedNoProcess     LaunchFailure = "no-process"
	LaunchFailedExited        LaunchFailure = "exited"
	LaunchFailedNoPromptBox   LaunchFailure = "no-prompt-box"
	LaunchFailedNoSession     LaunchFailure = "no-session"
	LaunchFailedCliMissing    LaunchFailure = "cli-missing"
	LaunchFailedLoginRequired LaunchFailure = "login-required"
	// LaunchFailedMachineBusy: tmux did not answer in time, the machine is overloaded; the same launch may go later.
	LaunchFailedMachineBusy LaunchFailure = "machine-busy"
)

type LaunchStep

type LaunchStep string

LaunchStep is a step of the launch screen.

const (
	StepMachine LaunchStep = "machine"
	StepCli     LaunchStep = "cli"
	StepProject LaunchStep = "project"
	StepPrompt  LaunchStep = "prompt"
)

type LegacyTab

type LegacyTab struct {
	TabID          string  `json:"tabId"`
	WorkspaceID    string  `json:"workspaceId"`
	SessionName    string  `json:"sessionName"`
	JsonlPath      *string `json:"jsonlPath"`
	AgentSessionID *string `json:"agentSessionId"`
	Cwd            string  `json:"cwd"`
}

LegacyTab is the answer of GET /api/v2/conversations/{id}/legacy: the Legacy tab a conversation runs in, which the right pane's tools of the current interface read (its timeline, diff, merge requests, subagents, spend).

func (LegacyTab) Validate

func (l LegacyTab) Validate() error

type LimitAction

type LimitAction string

LimitAction is what limit asks.

const (
	LimitNow    LimitAction = "now"
	LimitCancel LimitAction = "cancel"
	LimitAuto   LimitAction = "auto"
)

type LimitCmd

type LimitCmd struct {
	OpID   string      `json:"opId"`
	ID     string      `json:"id"`
	Action LimitAction `json:"action"`
}

LimitCmd decides what a conversation held on its usage limit does: now goes on at once (the person's queued message, or the runtime's own word to go on), cancel leaves the chat to wait without going on by itself, auto goes on by itself at the reset again. Refused{not-found} when the conversation is not held.

func (LimitCmd) Op

func (LimitCmd) Op() Op

func (LimitCmd) OpKey

func (c LimitCmd) OpKey() string

func (LimitCmd) Validate

func (c LimitCmd) Validate() error

type LimitHold

type LimitHold struct {
	Provider   Provider    `json:"provider"`
	Window     LimitWindow `json:"window"`
	At         Ms          `json:"at"`
	ResetsAt   *Ms         `json:"resetsAt"`
	ContinueAt *Ms         `json:"continueAt"`
}

LimitHold is a conversation held on its agent's usage limit. At is when the turn ended on it; ResetsAt is when the limit resets, as the agent said or the limits it last reported (nil when neither names a time). ContinueAt is when the runtime goes on by itself — ResetsAt and a short jitter — nil when it will not: the person said no (limit cancel), the setting is off, or no time is known. Until then the queue is paused{limited}: what the person sends waits for it.

type LimitWindow

type LimitWindow string

LimitWindow is which limit an agent hit: the five-hour session, the weekly one, or one it did not name.

const (
	LimitSession LimitWindow = "session"
	LimitWeekly  LimitWindow = "weekly"
	LimitOther   LimitWindow = "other"
)

type Limits

type Limits struct {
	MaxQueue       int   `json:"maxQueue"`
	MaxText        int   `json:"maxText"` // UTF-16 units
	MaxAttachments int   `json:"maxAttachments"`
	MaxImageBytes  int64 `json:"maxImageBytes"`
	MaxFileBytes   int64 `json:"maxFileBytes"` // 0: no limit but the free space of the disk
	SlowMs         int64 `json:"slowMs"`       // a command unanswered this long shows "дольше обычного"
	CmdBudgetMs    int64 `json:"cmdBudgetMs"`  // the runtime answers every command within this, refused{timeout} at worst
	CmdTimeoutMs   int64 `json:"cmdTimeoutMs"` // the page gives up on a command after this and offers retry or cancel
}

Limits are what a runtime accepts; the page checks them before it sends.

type LoginCode added in v0.15.46

type LoginCode struct {
	ID   string `json:"id"`
	Code string `json:"code"`
}

LoginCode is the body of POST /api/v2/agents/<provider>/login/code: the code the vendor's site showed, for the flow the page was shown (a code never goes to another flow than the one it was asked for).

func (LoginCode) Validate added in v0.15.46

func (c LoginCode) Validate() error

type LoginFlow added in v0.15.46

type LoginFlow struct {
	ID        string       `json:"id"`
	Provider  Provider     `json:"provider"`
	Mode      LoginMode    `json:"mode"`
	State     LoginState   `json:"state"`
	Input     LoginInput   `json:"input"`
	URL       *string      `json:"url"`
	UserCode  *string      `json:"userCode"`
	StartedAt Ms           `json:"startedAt"`
	ExpiresAt Ms           `json:"expiresAt"`
	Reason    *LoginReason `json:"reason"`
}

LoginFlow is one sign-in. `url` is the vendor's link to open; `userCode` is the one-time code to type there (device mode only, it is no secret: it opens nothing without the person's own sign-in). `expiresAt` is when the runtime gives the flow up.

func (LoginFlow) Validate added in v0.15.46

func (f LoginFlow) Validate() error

type LoginInput added in v0.15.46

type LoginInput string

LoginInput is what the flow wants from the page: a code to paste back, or nothing (the person finishes at the vendor).

const (
	LoginInputCode LoginInput = "code"
	LoginInputNone LoginInput = "none"
)

type LoginMode added in v0.15.46

type LoginMode string

LoginMode is how the person signs in: with the subscription (a link and a code to paste back), with the console account (the same for API billing), or with a device code (Codex: a link and a code to type at the vendor, nothing to paste).

const (
	LoginSubscription LoginMode = "subscription"
	LoginConsole      LoginMode = "console"
	LoginDevice       LoginMode = "device"
)

func LoginModesOf added in v0.15.46

func LoginModesOf(p Provider) []LoginMode

LoginModesOf are the modes a CLI takes: Claude the first two, Codex the device code.

type LoginOK added in v0.15.46

type LoginOK struct {
	OK bool `json:"ok"`
}

LoginDoneEv is the answer of the routes that end in a state of the CLI's account and nothing else (an API key saved, a sign-out): the page asks the agent's settings for what the account is now.

func (LoginOK) Validate added in v0.15.46

func (LoginOK) Validate() error

type LoginReason added in v0.15.46

type LoginReason string

LoginReason is why a flow failed.

const (
	// LoginNotInstalled: the CLI is not on the machine.
	LoginNotInstalled LoginReason = "not-installed"
	// LoginStartFailed: the CLI did not start or did not give a link.
	LoginStartFailed LoginReason = "start-failed"
	// LoginCodeRejected: the CLI did not take the code.
	LoginCodeRejected LoginReason = "code-rejected"
	// LoginRefused: the CLI ended without a sign-in (the person said no at the vendor, or the code was never entered).
	LoginRefused LoginReason = "refused"
	// LoginTimeout: nobody finished in time.
	LoginTimeout LoginReason = "timeout"
)

type LoginSource added in v0.15.46

type LoginSource interface {
	// Login is the last flow of the CLI (or the one on).
	Login(ctx context.Context, p Provider) (LoginStatus, error)
	StartLogin(ctx context.Context, p Provider, mode LoginMode) (LoginStatus, error)
	SubmitLoginCode(ctx context.Context, p Provider, id, code string) (LoginStatus, error)
	CancelLogin(ctx context.Context, p Provider) (LoginStatus, error)
	// SaveAPIKey gives the CLI an API key on its standard input.
	SaveAPIKey(ctx context.Context, p Provider, key string) error
	// Logout signs the CLI out.
	Logout(ctx context.Context, p Provider) error
}

LoginSource signs the machine's agents in and out.

type LoginStart added in v0.15.46

type LoginStart struct {
	Mode LoginMode `json:"mode"`
}

LoginStart is the body of POST /api/v2/agents/<provider>/login.

func (LoginStart) Validate added in v0.15.46

func (s LoginStart) Validate() error

type LoginState added in v0.15.46

type LoginState string

LoginState is where a sign-in is. `starting`: the CLI is starting and has no link yet. `awaiting`: the link is out (and `input` says whether a code is to be pasted back). `checking`: the code went to the CLI, which is checking it. The last four end the flow.

const (
	LoginStarting  LoginState = "starting"
	LoginAwaiting  LoginState = "awaiting"
	LoginChecking  LoginState = "checking"
	LoginDone      LoginState = "done"
	LoginFailed    LoginState = "failed"
	LoginCancelled LoginState = "cancelled"
	LoginExpired   LoginState = "expired"
)

type LoginStatus added in v0.15.46

type LoginStatus struct {
	Flow *LoginFlow `json:"flow"`
}

LoginStatus is the answer of the sign-in routes: the flow, or null when none was started since the runtime began.

func (LoginStatus) Validate added in v0.15.46

func (s LoginStatus) Validate() error

type LookBlobs

type LookBlobs interface {
	Has(ctx context.Context, hash string) (bool, error)
	Put(ctx context.Context, hash string, r io.Reader, size int64) error
	Open(ctx context.Context, hash string) (io.ReadCloser, int64, error)
}

LookBlobs keeps the pictures by the sha256 of their content (sites.FolderBlobs and sites.S3Blobs fit).

type Machine

type Machine struct {
	ID         string         `json:"id"`
	Name       string         `json:"name"`
	Host       string         `json:"host"`
	Reach      Reach          `json:"reach"`
	LastSeenAt *Ms            `json:"lastSeenAt"`
	Runtime    *RuntimeInfo   `json:"runtime"` // nil: the runtime did not answer /api/v2/hello
	Agents     []MachineAgent `json:"agents"`
	Load       *MachineLoad   `json:"load,omitempty"` // only while a subscriber asked for {load: true}
	// Health is the machine's own judgement of its disk, memory and CPU; absent where the source does not judge it.
	Health *MachineHealth `json:"health,omitempty"`
}

Machine is one machine of the fleet; standalone there is one, "local".

func MachineFor added in v0.15.46

func MachineFor(m Machine, caps Caps) Machine

MachineFor is m as a page with caps gets it; m itself is never changed.

func (Machine) Validate

func (m Machine) Validate() error

type MachineAgent

type MachineAgent struct {
	Provider Provider           `json:"provider"`
	Version  *string            `json:"version"`
	Status   AgentInstallStatus `json:"status"`
	// Models are the models the CLI takes, the first being the one a new conversation offers; empty when the machine
	// does not know them.
	Models []AgentModel `json:"models"`
	// CanSwitchModel: a running conversation of this CLI takes the model command.
	CanSwitchModel bool `json:"canSwitchModel"`
	// DefaultPermission is the permission mode a chat of this CLI starts in when it names none (the runtime's
	// dangerouslySkipPermissions: bypass, else ask); absent where the machine does not say.
	DefaultPermission PermissionMode `json:"defaultPermission,omitempty"`
	// Profiles are the vendor setups (Kimi, GLM, Grok) a conversation can start on through this CLI, each with its own
	// models. Only a page that names the `profiles` cap gets them; absent where there are none.
	Profiles []ProfileOffer `json:"profiles,omitempty"`
}

MachineAgent is one agent CLI on a machine: what it can be started with and whether a running one can change model.

func (MachineAgent) Validate

func (a MachineAgent) Validate() error

type MachineDisk

type MachineDisk struct {
	Path       string            `json:"path"`
	Total      int64             `json:"total"`
	Free       int64             `json:"free"`
	Parts      []MachineDiskPart `json:"parts"`
	MeasuredAt *int64            `json:"measuredAt"`
	Partial    bool              `json:"partial"`
}

MachineDisk is the filesystem of the runtime user's home and what its used part is made of. The folders are measured in the background, so the layout is as old as `measuredAt` (null: not measured yet, all that is used is `other`); `partial`: the walk ran out of time, the named parts are lower bounds.

func (MachineDisk) Validate

func (d MachineDisk) Validate() error

type MachineDiskPart

type MachineDiskPart struct {
	ID    DiskPartID `json:"id"`
	Bytes int64      `json:"bytes"`
}

MachineDiskPart is one part of the disk with its size in bytes.

func (MachineDiskPart) Validate

func (p MachineDiskPart) Validate() error

type MachineHealth

type MachineHealth struct {
	Level  HealthLevel   `json:"level"`
	Since  Ms            `json:"since"`
	Issues []HealthIssue `json:"issues"`
	// Stall says what an "io" issue is made of; absent without one.
	Stall *HealthStall `json:"stall,omitempty"`
}

MachineHealth is how the machine judges its own load (internal/machines/health.go): ok, or what runs short and how badly. Level is the worst of Issues; Issues are worst first, then disk, mem, cpu, and empty when ok. Since is when the machine came to this level.

func (MachineHealth) Validate

func (h MachineHealth) Validate() error

type MachineLoad

type MachineLoad struct {
	At         Ms      `json:"at"`
	CPU        float64 `json:"cpu"`
	MemUsed    int64   `json:"memUsed"`
	MemTotal   int64   `json:"memTotal"`
	DiskFree   int64   `json:"diskFree"`
	DiskTotal  int64   `json:"diskTotal"`
	BusyAgents int     `json:"busyAgents"`
}

MachineLoad is a machine's load at one moment.

type MachineLoadEv

type MachineLoadEv struct {
	Load MachineLoad `json:"load"`
}

MachineLoadEv is the machine's load, every 2 s while a subscriber asked for it.

func (MachineLoadEv) EventType

func (MachineLoadEv) EventType() EventType

func (MachineLoadEv) MarshalJSON

func (e MachineLoadEv) MarshalJSON() ([]byte, error)

func (MachineLoadEv) Validate

func (e MachineLoadEv) Validate() error

type MachineMem

type MachineMem struct {
	Used  int64 `json:"used"`
	Total int64 `json:"total"`
}

MachineMem is the memory in bytes: in use (what a new program cannot have) of the whole.

type MachineNet

type MachineNet struct {
	Rx float64 `json:"rx"`
	Tx float64 `json:"tx"`
}

MachineNet is the bytes per second over the machine's own links, in and out, now.

type MachineProc

type MachineProc struct {
	PID       int             `json:"pid"`
	StartTime string          `json:"startTime"`
	Name      string          `json:"name"`
	Command   string          `json:"command"`
	CPU       float64         `json:"cpu"`
	RSS       int64           `json:"rss"`
	Kind      MachineProcKind `json:"kind"`
	Port      *int            `json:"port"`
	Stuck     bool            `json:"stuck"`
	Guard     bool            `json:"guard"`
}

MachineProc is a heavy process of the runtime's user. `startTime` with `pid` names it for its whole life (a stop names both); `name` is what it is called ("node · vite"), `command` the command line with secrets hidden, cut at 160 characters. `cpu` is the share of one core like top shows it (a busy multi-threaded process passes 100), `rss` the resident memory in bytes. `guard`: the runtime, a service of the platform, tmux or an agent of a chat; it is shown and never stopped. `stuck`: it listens on `port` and has not answered for several looks.

func (MachineProc) Validate

func (p MachineProc) Validate() error

type MachineProcKind

type MachineProcKind string

MachineProcKind is what a listed process is to the platform: a service of the platform or the runtime itself, an agent or its tool, a dev server, any other process of the user.

const (
	ProcService MachineProcKind = "service"
	ProcAgent   MachineProcKind = "agent"
	ProcDev     MachineProcKind = "dev"
	ProcOther   MachineProcKind = "other"
)

type MachineRefusal

type MachineRefusal struct {
	R       ResultKind        `json:"r"`
	Code    RefuseCode        `json:"code"`
	Reason  MachineStopReason `json:"reason"`
	Message string            `json:"message"`
}

MachineRefusal is the answer of a stop that is refused: the code of the protocol, why, and a message worded for the person.

func (MachineRefusal) Validate

func (m MachineRefusal) Validate() error

type MachineSample

type MachineSample struct {
	At  int64   `json:"at"`
	CPU float64 `json:"cpu"`
	Mem float64 `json:"mem"`
	Rx  float64 `json:"rx"`
	Tx  float64 `json:"tx"`
}

MachineSample is the machine at one moment of the last hour: the busy share of the processor and the share of the memory in use (0…1), the bytes over the network per second.

func (MachineSample) Validate

func (s MachineSample) Validate() error

type MachineSnapshot

type MachineSnapshot struct {
	Machine Machine `json:"machine"`
}

MachineSnapshot is the data of a machine snapshot.

func (MachineSnapshot) Validate

func (s MachineSnapshot) Validate() error

type MachineSource

type MachineSource interface {
	// Snapshot is the data of a machine snapshot; Load is set only when load is true.
	Snapshot(ctx context.Context, load bool) (MachineSnapshot, error)

	// Subscribe calls fn with every MachineStatusEv and, while load is true, a MachineLoadEv every 2 s, in order,
	// until cancel is called.
	Subscribe(load bool, fn func(Event)) (cancel func())
}

MachineSource serves the machine channel: the machine's record and its changes. It is not convo's — reach comes from the cluster's heartbeat (standalone always online), runtime and agents from the runtime itself, load from internal/machines — so the hub asks it, not the conversations.

type MachineStats

type MachineStats struct {
	At      int64           `json:"at"`
	CPU     float64         `json:"cpu"`
	Cores   []float64       `json:"cores"`
	Mem     MachineMem      `json:"mem"`
	Net     MachineNet      `json:"net"`
	Disk    MachineDisk     `json:"disk"`
	History []MachineSample `json:"history"`
	Procs   []MachineProc   `json:"procs"`
}

MachineStats is the answer of GET /api/v2/machine/stats. `cpu`, `cores[]` are the busy share (0…1) of the processor and of each core now; `history` is the last hour thinned to a point every two minutes, oldest first, the last one being now; a point is left out for a stretch the runtime was not running. `procs` are the heaviest processes by memory and processor together, the heaviest first.

func (MachineStats) Validate

func (s MachineStats) Validate() error

type MachineStatusEv

type MachineStatusEv struct {
	Reach   Reach          `json:"reach"`
	Runtime *RuntimeInfo   `json:"runtime"`
	Agents  []MachineAgent `json:"agents"`
	Health  *MachineHealth `json:"health,omitempty"`
}

MachineStatusEv: the machine's reach, runtime, agents or health changed. An event without health leaves the health the page holds as it was.

func (MachineStatusEv) EventType

func (MachineStatusEv) EventType() EventType

func (MachineStatusEv) MarshalJSON

func (e MachineStatusEv) MarshalJSON() ([]byte, error)

func (MachineStatusEv) Validate

func (e MachineStatusEv) Validate() error

type MachineStop

type MachineStop struct {
	PID       int    `json:"pid"`
	StartTime string `json:"startTime"`
}

MachineStop is the body of POST /api/v2/machine/processes/stop: the process the page was shown.

func (MachineStop) Validate

func (m MachineStop) Validate() error

type MachineStopError

type MachineStopError struct {
	Reason  MachineStopReason
	Message string
}

MachineStopError is what a MachineToolSource refuses a stop with.

func (*MachineStopError) Error

func (e *MachineStopError) Error() string

type MachineStopReason

type MachineStopReason string

MachineStopReason says why a process was not stopped.

const (
	StopGone         MachineStopReason = "gone"          // it has ended already
	StopChanged      MachineStopReason = "changed"       // the pid is another process now
	StopForeign      MachineStopReason = "foreign"       // it is not the runtime user's
	StopProtected    MachineStopReason = "protected"     // the runtime, tmux, or a service of the platform
	StopNotStoppable MachineStopReason = "not-stoppable" // an agent of a chat or its tool
	StopNotListed    MachineStopReason = "not-listed"    // not among the heavy processes the page was shown
	StopBusy         MachineStopReason = "busy"          // the machine did not answer in time
	StopFailed       MachineStopReason = "failed"        // the signal could not be sent
)

type MachineStopped

type MachineStopped struct {
	Stopped bool   `json:"stopped"`
	Signal  string `json:"signal"`
}

MachineStopped is the answer of a stop: the signal that ended the process (SIGTERM, or SIGKILL when it was still there five seconds later).

func (MachineStopped) Validate

func (m MachineStopped) Validate() error

type MachineToolSource

type MachineToolSource interface {
	Stats(ctx context.Context) (MachineStats, error)
	Stop(ctx context.Context, req MachineStop) (MachineStopped, error)
}

MachineToolSource serves the Machine tool. Stats never waits for a look at the machine longer than its own budget; Stop refuses with a *MachineStopError, and checks again on a fresh look at /proc that the process is the one named, is the runtime user's and is among those Stats lists as stoppable.

type MadeFrom

type MadeFrom struct {
	Kind  MadeFromKind `json:"kind"`
	ID    string       `json:"id"`
	Title string       `json:"title"`
}

MadeFrom is the subagent or delegated chat that made a thing: the chat that started them inherits all they made. ID is the subchat's conversation id or the subagent's id; Title its name, "" when unknown.

func (MadeFrom) Validate

func (f MadeFrom) Validate() error

type MadeFromKind

type MadeFromKind string

MadeFromKind says who made a thing the chat inherits: one of its subagents or one of its delegated chats.

const (
	MadeFromSubagent MadeFromKind = "subagent"
	MadeFromSubchat  MadeFromKind = "subchat"
)

type MadeItem added in v0.16.42

type MadeItem struct {
	Kind       MadeKind    `json:"kind"`
	Ref        string      `json:"ref"`
	Title      string      `json:"title"`
	Op         OutputOp    `json:"op"`
	At         Ms          `json:"at"`
	Cover      *string     `json:"cover"`
	DesignKind *DesignKind `json:"designKind"`
	// Task is set for a task only, and only when the tracker could be read; it is left out otherwise.
	Task *MadeTaskInfo `json:"task,omitempty"`
	// From is set when a subagent or a delegated chat made it, not the chat itself.
	From *MadeFrom `json:"from,omitempty"`
}

MadeItem is one thing the chat made or touched. Ref is the page's URL for a doc or a board (a board keeps its ?k= key, it is what opens it; never show it), the design's id for a design, the task's address for a task. Title is "" when the runtime does not know it. Op is "created" or "changed" (opening counts as changed). Cover and DesignKind are set for a design only.

func (MadeItem) Validate added in v0.16.42

func (m MadeItem) Validate() error

type MadeKind added in v0.16.42

type MadeKind string

MadeKind is what a chat made, opened or changed that the «made in this chat» block lists.

const (
	MadeDoc    MadeKind = "doc"
	MadeBoard  MadeKind = "board"
	MadeDesign MadeKind = "design"
	// MadeTask is a tracker task or epic the chat created or touched. It is only sent to a page that asked for tasks
	// (?tasks=1): a page that does not know the kind is never shown it.
	MadeTask MadeKind = "task"
	// MadeMR is a merge request (pull request) the chat opened. A page that does not know the kind leaves it out.
	MadeMR MadeKind = "mr"
	// MadeStand is a stand or a dev server the chat opened; MadeCommit a commit it pushed (its page on the server);
	// MadeFile a file it handed to the person (Ref is its path). A page that does not know them leaves them out.
	MadeStand  MadeKind = "stand"
	MadeCommit MadeKind = "commit"
	MadeFile   MadeKind = "file"
)

type MadeTaskInfo added in v0.16.42

type MadeTaskInfo struct {
	Key      string        `json:"key"`
	Type     string        `json:"type"`
	State    string        `json:"state"`
	Resolved bool          `json:"resolved"`
	Parent   *MadeTaskRef  `json:"parent"`
	Children []MadeTaskRef `json:"children"`
}

MadeTaskInfo is what the tracker says of a task the chat touched: its kind («Epic»), state, the epic it belongs to and, for an epic, its subtasks. Type and State are "" when the tracker does not say.

type MadeTaskRef added in v0.16.42

type MadeTaskRef struct {
	Key      string `json:"key"`
	Title    string `json:"title"`
	URL      string `json:"url"`
	State    string `json:"state"`
	Resolved bool   `json:"resolved"`
}

MadeTaskRef is a task named by another one: its epic, or a subtask of an epic.

type Me

type Me struct {
	Email    *string        `json:"email"`
	Name     *string        `json:"name"`
	Settings PersonSettings `json:"settings"`
	Rev      int64          `json:"rev"`
}

Me is GET /api/v2/me: the person and their settings at a revision. A runtime on its own has one person, with no e-mail.

type MeStore

type MeStore interface {
	Me() (Me, error)
	// Patch applies a patch to the settings at rev: ErrMeConflict when rev is not the current revision,
	// ErrMeBadPatch when the patch is not settings.
	Patch(rev int64, patch json.RawMessage) (Me, error)
}

MeStore keeps the person of a runtime on its own.

type Message

type Message struct {
	ClientID       string          `json:"clientId"`
	ConversationID string          `json:"conversationId"`
	Text           string          `json:"text"`
	Attachments    []AttachmentRef `json:"attachments"`
	// Refs are the places it points at; Text already ends with their block. Absent when none.
	Refs []MessageRef `json:"refs,omitempty"`
	Mode MessageMode  `json:"mode"`
	Kind MessageKind  `json:"kind"`
	// Auto is set on a message the runtime wrote itself to go on (AutoContinue): the feed draws it as a quiet line,
	// not as the person's words. Absent on the person's messages.
	Auto AutoContinueWhy `json:"auto,omitempty"`
	// Cleared is the screen the person left open in the agent's terminal (their /login, a picker) that was closed
	// before the message went in: the chat says so under it. Absent when nothing was in the way.
	Cleared   TerminalAside `json:"cleared,omitempty"`
	CreatedAt Ms            `json:"createdAt"`
	Attempts  int           `json:"attempts"`
	State     MessageState  `json:"state"`
	Rev       int64         `json:"rev"`

	// Server only: when the text was typed and how long the transcript was then, to find its user entry.
	TypedAt     Ms    `json:"-"`
	TypedOffset int64 `json:"-"`
}

Message is one message to an agent; ClientID, set by the page, is its idempotency key.

func (Message) Validate

func (m Message) Validate() error

type MessageFailure

type MessageFailure string

MessageFailure is why a message failed.

const (
	MsgFailedUploadFailed MessageFailure = "upload-failed"
	MsgFailedRefused      MessageFailure = "refused"
	MsgFailedLaunchFailed MessageFailure = "launch-failed"
	MsgFailedAgentGone    MessageFailure = "agent-gone"
	MsgFailedTypeFailed   MessageFailure = "type-failed"
	MsgFailedStuckInInput MessageFailure = "stuck-in-input"
	MsgFailedUnconfirmed  MessageFailure = "unconfirmed"
	MsgFailedExpired      MessageFailure = "expired"
	// MsgFailedReturned: the turn was interrupted while the message waited in Claude's queue, and Claude put it back
	// into the input box for the person to edit; it is not Entered again by itself.
	MsgFailedReturned MessageFailure = "returned-to-input"
)

type MessageHanded added in v0.15.46

type MessageHanded struct {
	At      Ms          `json:"at"`
	Where   HandedWhere `json:"where"`
	EntryID *string     `json:"entryId"`
}

MessageHanded is when the message was typed into the agent and where it is now.

func (MessageHanded) Validate added in v0.15.46

func (h MessageHanded) Validate() error

type MessageHit added in v0.15.46

type MessageHit struct {
	ConvID  string      `json:"convId"`
	EntryID string      `json:"entryId"`
	TurnID  *string     `json:"turnId"`
	At      Ms          `json:"at"`
	Role    MessageRole `json:"role"`
	Snippet string      `json:"snippet"`
}

MessageHit is one message found: the conversation, the entry of the feed, the turn the entry is in (null for one outside any), and the words around the match.

func (MessageHit) Validate added in v0.15.46

func (h MessageHit) Validate() error

type MessageKind

type MessageKind string

MessageKind tells a prompt from a command ('/model', '/compact', '!cmd').

const (
	KindPrompt  MessageKind = "prompt"
	KindCommand MessageKind = "command"
)

type MessageMode

type MessageMode string

MessageMode is when a message should reach the agent.

const (
	ModeQueue MessageMode = "queue"
	ModeNow   MessageMode = "now"
	ModeSteer MessageMode = "steer"
)

type MessageRef

type MessageRef struct {
	Kind RefKind `json:"kind"`
	// ID names it for the page and the runtime: a design's id, a document's slug or URL, a path, an MR's URL, a task key.
	ID string `json:"id"`
	// Title is what the chip says.
	Title string `json:"title"`
	// Target is where it is for the agent: a URL or a path; "" for a design, which the runtime finds by its id.
	Target string `json:"target"`
}

MessageRef is a place a message points the agent at instead of carrying a file: a design of the library, a document of the catalogue or of the project, a board, a file of the project, a merge request or a task. Nothing is uploaded: the runtime writes a line for each under the person's words (internal/attach), so the agent knows where to look.

func (MessageRef) Validate

func (r MessageRef) Validate() error

type MessageRole added in v0.15.46

type MessageRole string

MessageRole is who wrote a message found.

const (
	MessageUser  MessageRole = "user"
	MessageAgent MessageRole = "agent"
)

type MessageSearch added in v0.15.46

type MessageSearch struct {
	Query    string       `json:"query"`
	Hits     []MessageHit `json:"hits"`
	Indexing bool         `json:"indexing"`
}

MessageSearch is the answer of GET /api/v2/search?q=&limit=: the messages that hold every word of the query (each word may be the beginning of a word), the newest first, at most three of a conversation. Indexing: the runtime is still reading the older conversations, so the answer may lack some.

func (MessageSearch) Validate added in v0.15.46

func (m MessageSearch) Validate() error

type MessageState

type MessageState struct {
	K         MessageStateKind `json:"k"`
	Position  int              `json:"position"` // 1 is the head of the queue
	Reason    QueueReason      `json:"reason"`
	Wait      *Wait            `json:"wait"`    // queued (nil: agent-busy and behind have no term), typing, in-input
	EntryID   *string          `json:"entryId"` // nil: the hook confirmed it, the transcript line is not read yet
	TurnID    string           `json:"turnId"`
	Code      MessageFailure   `json:"code"`
	Retryable bool             `json:"retryable"`
	At        Ms               `json:"at"`
	By        string           `json:"by"`
}

MessageState is where a message is. Only the fields of K are on the wire:

queued{position, reason, wait|null} · typing{wait} · in-input{wait} · accepted{entryId|null} · in-turn{turnId} · done{turnId} ·
failed{code, retryable, at} · cancelled{by: "user"}

draft, uploading and submitting live only on the page and never cross the wire.

func (MessageState) MarshalJSON

func (s MessageState) MarshalJSON() ([]byte, error)

func (*MessageState) UnmarshalJSON

func (s *MessageState) UnmarshalJSON(b []byte) error

func (MessageState) Validate

func (s MessageState) Validate() error

type MessageStateKind

type MessageStateKind string

MessageStateKind is the kind of a MessageState on the wire.

const (
	MsgQueued    MessageStateKind = "queued"
	MsgTyping    MessageStateKind = "typing"
	MsgInInput   MessageStateKind = "in-input"
	MsgAccepted  MessageStateKind = "accepted"
	MsgInTurn    MessageStateKind = "in-turn"
	MsgDone      MessageStateKind = "done"
	MsgFailed    MessageStateKind = "failed"
	MsgCancelled MessageStateKind = "cancelled"
)

type MessageStatus added in v0.15.46

type MessageStatus struct {
	ClientID string            `json:"clientId"`
	K        MessageStatusKind `json:"k"`
	Message  *Message          `json:"message,omitempty"`
	Handed   *MessageHanded    `json:"handed,omitempty"`
	At       Ms                `json:"at,omitempty"`
}

MessageStatus is the runtime's word on one client id: known (with the record and, once typed, where it went), unknown, or expired (when it ended).

func (MessageStatus) Validate added in v0.15.46

func (s MessageStatus) Validate() error

type MessageStatusKind added in v0.15.46

type MessageStatusKind string

MessageStatusKind is what the runtime knows of a client id.

const (
	// StatusKnown: the runtime has the message; Message is its record as the pages get it.
	StatusKnown MessageStatusKind = "known"
	// StatusUnknown: the runtime never had a message with this id (or lost it): it is the page's to send again.
	StatusUnknown MessageStatusKind = "unknown"
	// StatusExpired: the runtime had it and let its finished record go long ago (At is when it ended).
	StatusExpired MessageStatusKind = "expired"
)

type MessageStatuses added in v0.15.46

type MessageStatuses struct {
	Messages []MessageStatus `json:"messages"`
}

MessageStatuses is the answer of GET /api/v2/conversations/{id}/messages?ids=a,b: one status per id asked, in order.

func (MessageStatuses) Validate added in v0.15.46

func (s MessageStatuses) Validate() error

type MessageUpsertEv

type MessageUpsertEv struct {
	Message Message `json:"message"`
}

MessageUpsertEv is a message's whole record.

func (MessageUpsertEv) EventType

func (MessageUpsertEv) EventType() EventType

func (MessageUpsertEv) MarshalJSON

func (e MessageUpsertEv) MarshalJSON() ([]byte, error)

func (MessageUpsertEv) Validate

func (e MessageUpsertEv) Validate() error

type Model

type Model struct {
	ID        string  `json:"id"`
	Effort    *Effort `json:"effort"`
	Ultracode bool    `json:"ultracode,omitempty"`
	// Fast is the CLI's fast mode (Claude Code's `fastMode`, Codex's `service_tier = "fast"`); absent is off.
	Fast bool `json:"fast,omitempty"`
	// Permission is how the agent asks before it acts (PermissionMode); absent: the machine's default, the runtime's
	// dangerouslySkipPermissions.
	Permission PermissionMode `json:"permission,omitempty"`
	// Profile is the backend profile the conversation runs on (ProfileOffer.ID); absent for the CLI's own account. It
	// is set when the conversation starts and does not change. Only a page that names the `profiles` cap gets it. A
	// command never carries it here: it names the profile beside the model (ConversationCreateCmd.Profile).
	Profile string `json:"profile,omitempty"`
}

Model is a conversation's model; a nil Effort is the model's default. Ultracode is Claude Code's mode of working beside the effort: standing dynamic workflows with subagents on every task, at any effort level. Absent is off.

func (*Model) UnmarshalJSON

func (m *Model) UnmarshalJSON(b []byte) error

func (Model) Validate

func (m Model) Validate() error

type ModelCmd

type ModelCmd struct {
	OpID      string  `json:"opId"`
	ID        string  `json:"id"`
	Model     string  `json:"model"`
	Effort    *Effort `json:"effort"`
	Ultracode *bool   `json:"ultracode,omitempty"`
	// Fast and Permission turn the fast mode and the permission mode with the change; absent keeps what runs.
	Fast       *bool           `json:"fast,omitempty"`
	Permission *PermissionMode `json:"permission,omitempty"`
}

ModelCmd switches a conversation's model: at once, or queued after the turn. Ultracode turns the mode on or off with it; absent keeps the mode the conversation runs.

func (ModelCmd) FastAfter

func (c ModelCmd) FastAfter(cur *Model) bool

FastAfter is the fast mode the conversation runs once the ask is taken: the ask's, or the one cur runs.

func (ModelCmd) Op

func (ModelCmd) Op() Op

func (ModelCmd) OpKey

func (c ModelCmd) OpKey() string

func (ModelCmd) PermissionAfter

func (c ModelCmd) PermissionAfter(cur *Model) PermissionMode

PermissionAfter is the permission mode the conversation runs once the ask is taken: the ask's, or the one cur runs ("" for the machine's default).

func (ModelCmd) UltracodeAfter

func (c ModelCmd) UltracodeAfter(cur *Model) bool

UltracodeAfter is the mode the conversation runs once the ask is taken: the ask's, or, when it does not say, the one cur runs.

func (*ModelCmd) UnmarshalJSON

func (c *ModelCmd) UnmarshalJSON(b []byte) error

func (ModelCmd) Validate

func (c ModelCmd) Validate() error

type ModelSwitch

type ModelSwitch struct {
	At      Ms          `json:"at"`
	From    *Model      `json:"from"`
	To      Model       `json:"to"`
	Refused *RefuseCode `json:"refused,omitempty"`
}

ModelSwitch is a change of model the runtime applied: From is nil when the conversation had no model on record. Refused, when set, says the agent did not take the change To asked for (the record kept From): why, in the words of a command's refusal — conflict (the agent kept its model), internal (it never confirmed), option-unknown (the model does not take ultracode), agent-working (its screen was never at the prompt).

type Ms

type Ms = int64

Ms is a unix time in milliseconds.

type NavSettings struct {
	// Order is the top level, in order; an app's key here stands at the top level instead of under «Приложения».
	Order []string `json:"order"`
	// Hidden are the keys not shown, at the top level or under «Приложения».
	Hidden []string `json:"hidden"`
	// Apps is the order of the apps under «Приложения» (ids, no «app:»), above the ones it does not name.
	Apps []string `json:"apps"`
}

NavSettings are the sidebar menu's layout (PersonSettings.Nav). A key is an item of the menu («newChat», «search», «designly», «apps») or an app («app:<id>»).

type NoticeLevel

type NoticeLevel string

NoticeLevel is how loud a notice entry is.

const (
	NoticeInfo  NoticeLevel = "info"
	NoticeWarn  NoticeLevel = "warn"
	NoticeError NoticeLevel = "error"
)

type NoticeSummaryModel

type NoticeSummaryModel struct {
	Provider string `json:"provider"`
	Model    string `json:"model,omitempty"`
}

NoticeSummaryModel picks the model of a turn's summary: Provider is claude, codex, NoticeSummaryOff or NoticeSummaryAuto; Model is one of the provider's models, "" for the provider's cheap one.

func (*NoticeSummaryModel) Auto

func (m *NoticeSummaryModel) Auto() bool

Auto: nothing picked, the chat's provider and its cheap model.

func (*NoticeSummaryModel) Off

func (m *NoticeSummaryModel) Off() bool

Off: the summaries are turned off.

func (NoticeSummaryModel) Validate

func (m NoticeSummaryModel) Validate() error

Validate: a provider the runtime knows (or off), and a model id that is one word of a CLI argument.

type NotifySettings

type NotifySettings struct {
	Types []string `json:"types"`
	Sound bool     `json:"sound"`
	DND   bool     `json:"dnd"`
}

NotifySettings: which events notify, with a sound, and the do-not-disturb switch.

type Now

type Now struct {
	TurnID  string     `json:"turnId"`
	Thought *string    `json:"thought"`
	Action  *NowAction `json:"action"`
	Word    *string    `json:"word"` // the live reply off the screen
	At      Ms         `json:"at"`
}

Now is what a working agent is doing this moment; the page ticks the timer itself.

func (Now) Validate

func (n Now) Validate() error

type NowAction

type NowAction struct {
	Tool    string  `json:"tool"`
	Summary string  `json:"summary"`
	Command *string `json:"command"`
}

NowAction is the tool call in progress.

type NowEv

type NowEv struct {
	Now
}

NowEv is what the agent does this moment, at most twice a second.

func (NowEv) EventType

func (NowEv) EventType() EventType

func (NowEv) MarshalJSON

func (e NowEv) MarshalJSON() ([]byte, error)

func (NowEv) Validate

func (e NowEv) Validate() error

type OnOff

type OnOff string

OnOff is a switch of the runtime's settings.

const (
	On  OnOff = "on"
	Off OnOff = "off"
)

type Op

type Op string

Op is a command of POST /api/v2/cmd/<op>.

const (
	OpSend                  Op = "send"
	OpCancel                Op = "cancel"
	OpRetry                 Op = "retry"
	OpPromote               Op = "promote"
	OpAnswer                Op = "answer"
	OpDecide                Op = "decide"
	OpInterrupt             Op = "interrupt"
	OpQueueResume           Op = "queue.resume"
	OpSeen                  Op = "seen"
	OpConversationCreate    Op = "conversation.create"
	OpConversationRename    Op = "conversation.rename"
	OpConversationPin       Op = "conversation.pin"
	OpConversationApps      Op = "conversation.apps"
	OpConversationTest      Op = "conversation.test"
	OpConversationView      Op = "conversation.view"
	OpConversationRetitle   Op = "conversation.retitle"
	OpConversationSummarize Op = "conversation.summarize"
	OpConversationMove      Op = "conversation.move"
	OpConversationDelete    Op = "conversation.delete"
	OpConversationRestore   Op = "conversation.restore"
	OpConversationResume    Op = "conversation.resume"
	OpModel                 Op = "model"
	OpBgStop                Op = "bg.stop"
	OpProjectCreate         Op = "project.create"
	OpProjectUpdate         Op = "project.update"
	OpFavGroupCreate        Op = "favorites.group.create"
	OpFavGroupRename        Op = "favorites.group.rename"
	OpFavGroupDelete        Op = "favorites.group.delete"
	OpFavGroupMove          Op = "favorites.group.move"
	OpFavPlace              Op = "favorites.place"
	OpGoal                  Op = "goal"
	OpDraftSet              Op = "draft.set"
	OpQueueMove             Op = "queue.move"
	OpTerminalStop          Op = "terminal.stop"
	OpRewind                Op = "rewind"
	OpRewindUndo            Op = "rewind.undo"
	OpConversationFork      Op = "conversation.fork"
	OpConversationHandoff   Op = "conversation.handoff"
	OpConversationMerge     Op = "conversation.merge"
	OpLimit                 Op = "limit"
)

type OpLog

type OpLog struct {
	// contains filtered or unexported fields
}

OpLog makes the commands idempotent by opId: the same opId with the same body gets the same answer, also while the first one still runs (it waits for that one's answer), and with another body refused{conflict}. A refused{timeout} is not kept: the command may still finish, and a retry gets its answer or runs it again.

func NewOpLog

func NewOpLog(path string) *OpLog

NewOpLog reads the answers kept in path ("" for none) and keeps the new ones there.

func (*OpLog) Clear

func (o *OpLog) Clear()

Clear forgets every kept answer, for a fake runtime that starts its fixtures again.

func (*OpLog) Run

func (o *OpLog) Run(ctx context.Context, cmd Command, budget time.Duration, run func(context.Context) CmdResult) CmdResult

Run answers cmd once per opId within budget: run gets a context that ends with the budget, and when it has not answered by then the caller gets refused{timeout} while run goes on.

type OpenChoice

type OpenChoice struct {
	Tab    OpenTab `json:"tab"`
	Target string  `json:"target"`
	Label  string  `json:"label"`
	Detail *string `json:"detail"`
}

OpenChoice is one place a ref may open: what the person picks from, Label the project and Detail what is known of the merge request (its title).

func (OpenChoice) Validate

func (c OpenChoice) Validate() error

type OpenTab

type OpenTab string

OpenTab is the tab of the right pane a link or a name of the chat opens in: a tracker task, a GitLab merge request or commit, a published document or board, or any other site in the browser.

const (
	OpenTask      OpenTab = "task"
	OpenGitLab    OpenTab = "gitlab"
	OpenArtifacts OpenTab = "artifacts"
	OpenBrowser   OpenTab = "browser"
	// OpenDesign is a design of the machine's library (Target its id), on a board of it when Board names one.
	OpenDesign OpenTab = "design"
	// OpenLink is an address that opens in no tab: a connection reads it but has no working sign-in (OpenReasonConnect),
	// or the service it is on cannot be framed (OpenReasonEmbed). Target is the address; the page offers to connect or to
	// open the original link, and never starts the remote browser by itself.
	OpenLink OpenTab = "link"
)

type OpenTarget

type OpenTarget struct {
	Tab     OpenTab      `json:"tab"`
	Target  string       `json:"target"`
	Choices []OpenChoice `json:"choices,omitempty"`
	// Reason is why an OpenLink opens in no tab; set for that tab only.
	Reason string `json:"reason,omitempty"`
	// Board is the page of a design the ref is (relative to its project/), only on the design tab.
	Board string `json:"board,omitempty"`
}

OpenTarget is the answer of GET /api/v2/conversations/{id}/open?ref=<ref>: the tab and what it shows. A ref that fits several places (`!12` is a merge request of two projects the chat touches) lists them all in Choices, the best first, and Tab and Target are the first one's; a client that cannot ask the person opens that.

func (OpenTarget) Validate

func (o OpenTarget) Validate() error

type OpenedRef

type OpenedRef struct {
	Ref  string      `json:"ref"`
	Open *OpenTarget `json:"open"`
}

OpenedRef is where one ref of a batch opens; Open is null for what opens nothing.

type OpenedRefs

type OpenedRefs struct {
	Refs []OpenedRef `json:"refs"`
}

OpenedRefs is the answer of GET /api/v2/conversations/{id}/open-refs?ref=<ref>&ref=<ref>…: every ref asked, in the order asked, with where it opens. It is what the page asks for the merge requests of a message before it draws them as something to click.

func (OpenedRefs) Validate

func (o OpenedRefs) Validate() error

type Origin

type Origin struct {
	K            OriginKind `json:"k"`
	FromID       string     `json:"fromId"`
	FromTitle    string     `json:"fromTitle"`
	FromProvider Provider   `json:"fromProvider"`
	FromModel    *Model     `json:"fromModel"`
	AtTurn       *string    `json:"atTurn,omitempty"`
	Via          OriginVia  `json:"via"`
	At           Ms         `json:"at"`
}

Origin is the conversation another one came out of, as it was then. A fork (K fork) holds the other's history up to AtTurn (its last finished turn when absent): in an agent session of its own (Via session), or, where the agent CLI cannot fork there, as an excerpt of it in its first message (Via excerpt). A handoff (K handoff) runs on another agent or model and starts with the other's context in its first message: an excerpt of the transcript or a note the other's agent wrote (Via). At is when it was made.

type OriginKind

type OriginKind string

OriginKind is how a conversation came out of another one.

const (
	OriginFork    OriginKind = "fork"
	OriginHandoff OriginKind = "handoff"
)

type OriginVia

type OriginVia string

OriginVia is what carried the other conversation's context: the agent's own forked session, an excerpt of the transcript, or a note the agent wrote.

const (
	ViaSession OriginVia = "session"
	ViaExcerpt OriginVia = "excerpt"
	ViaNote    OriginVia = "note"
	ViaHistory OriginVia = "history"
)

type OutputKind

type OutputKind string

OutputKind is what a turn made: a published document or board, a design, a document of the repository, a merge request, a stand (a preview or a dev server).

const (
	OutputArtifact OutputKind = "artifact"
	OutputDesign   OutputKind = "design"
	OutputDoc      OutputKind = "doc"
	OutputMR       OutputKind = "mr"
	OutputStand    OutputKind = "stand"
	// OutputDelivery is a file the agent handed to the person on purpose (harnessly deliver).
	OutputDelivery OutputKind = "delivery"
	// OutputTask is a task of the tracker the agent showed; OutputCommit a commit of the forge. Only a page
	// with CapLinks gets them (README 72).
	OutputTask   OutputKind = "task"
	OutputCommit OutputKind = "commit"
)

type OutputOp

type OutputOp string

OutputOp is whether the turn made the thing or changed one there was.

const (
	OutputCreated OutputOp = "created"
	OutputChanged OutputOp = "changed"
)

type OutputPage

type OutputPage struct {
	EntryID string     `json:"entryId"`
	Output  ToolOutput `json:"output"`
}

OutputPage is the answer of GET .../entries/{entryId}/output: the whole output.

func (OutputPage) Validate

func (p OutputPage) Validate() error

type OutputTrimmed

type OutputTrimmed struct {
	Shown int64 `json:"shown"`
	Total int64 `json:"total"`
}

OutputTrimmed is how much of an output was shown, of how much.

type Pane

type Pane struct {
	Count int64      `json:"count"`
	Reset bool       `json:"reset,omitempty"`
	Links []PaneLink `json:"links,omitempty"`
	Items []PaneItem `json:"items,omitempty"`
}

Pane is what the tools of the page's right pane read of a conversation (its links, the files and pictures it worked with, what it wrote to other agents and heard from them, its subagents), taken from the one read of the transcript that makes the feed. A snapshot carries it whole: the links of what the feed has read, newest first, and the newest items, oldest first. On an event it is what a read added: Items go after the ones the page holds, Links (when the list changed) take the place of the list it holds, and Reset says the transcript was read anew, so both take the place of what the page holds. Count is how many lines of the transcript the read has taken so far: it moves with every read that found something, whatever the items.

func (Pane) Validate

func (p Pane) Validate() error

type PaneItem

type PaneItem struct {
	ID     string    `json:"id"`
	K      string    `json:"k"`
	At     Ms        `json:"at"`
	Tool   string    `json:"tool,omitempty"`
	Use    string    `json:"use,omitempty"`
	Path   string    `json:"path,omitempty"`
	Text   string    `json:"text,omitempty"`
	Cwd    string    `json:"cwd,omitempty"`
	Files  []string  `json:"files,omitempty"`
	Images []string  `json:"images,omitempty"`
	Peer   *PanePeer `json:"peer,omitempty"`
}

PaneItem is one line of the transcript as the pane's tools need it, with nothing of it they do not read. K is tool (a tool call: Tool its name, Use its id, Path the file it names, Text its one-line summary, Files what it sent the person, Peer what it wrote to another agent), result (the result of a subagent's call: Use), notice (a background task's notice), user (a message with pictures, Images, or with other agents' words in its Text), answer (an answer that embeds pictures: Text is its Markdown), patch (Files are the files a patch touched) or exec (a command run: Text, in Cwd). A page leaves out a kind it does not know.

func (PaneItem) Validate

func (i PaneItem) Validate() error
type PaneLink struct {
	URL   string  `json:"url"`
	Label *string `json:"label"`
	At    Ms      `json:"at"`
	Count int     `json:"count"`
	Kind  string  `json:"kind"`
}

PaneLink is a link of the agent's answers: its address as the pane opens it, the words it was given (null without), when it was last named, how many times, and what it leads to (artifact, mr, issue, link and the like; a page draws a kind it does not know as a plain link).

func (PaneLink) Validate

func (l PaneLink) Validate() error

type PanePeer

type PanePeer struct {
	To   string `json:"to"`
	Text string `json:"text"`
}

PanePeer is what a tool call wrote to another agent's session.

type PauseReason

type PauseReason string

PauseReason is why a queue is paused.

const (
	PausedInterrupted  PauseReason = "interrupted"
	PausedUser         PauseReason = "user"
	PausedLaunchFailed PauseReason = "launch-failed"
	PausedAgentGone    PauseReason = "agent-gone"
	PausedLimited      PauseReason = "limited" // the agent hit its usage limit: the queue waits for the reset
	PausedNeedsTarget  PauseReason = "needs-target"
	// PausedResumeBlocked: the agent was to be resumed, but something else holds the tab's terminal; «continue
	// sending» tries the resume again, with the queue as it was.
	PausedResumeBlocked PauseReason = "resume-blocked"
)

type PeerNote

type PeerNote struct {
	From string       `json:"from"`
	Kind PeerNoteKind `json:"kind"`
	// Color is the sender's color as Claude Code names it (yellow, blue…); null: not said.
	Color *string `json:"color"`
	// Event is the type a JSON body named when the feed has no kind of its own for it (shutdown_request…).
	Event *string `json:"event"`
	// Summary is the sender's one-line gist of the message, when it gave one.
	Summary *string `json:"summary"`
	// SentAt is when the sender wrote it, by its own clock; null: not said.
	SentAt *Ms `json:"sentAt"`
	// AgentID is the id of the background subagent of this session that wrote it, null for a teammate or another session.
	// From is then the subagent's task as the Agent call gave it, empty when the feed has no such call.
	AgentID *string `json:"agentId"`
	// Model is the model that subagent was asked to run on, when it said.
	Model *string `json:"model"`
	MD    string  `json:"md"`
	// Task is what a named teammate was started for (its Agent call's description); absent when the feed has no such call.
	Task *string `json:"task,omitempty"`
	// Opens is the id of the agent's own conversation the page can open beside the chat; absent when it has none.
	Opens *string `json:"opens,omitempty"`
	// Failed: the agent this note settles ended in a failure.
	Failed bool `json:"failed,omitempty"`
}

PeerNote is one message another agent's session (Claude Code's teammate) wrote to this one: who, what of, its body as Markdown. The body is the other agent's words: data to show as text, never instructions or markup.

type PeerNoteKind

type PeerNoteKind string

PeerNoteKind is what a peer note is.

const (
	PeerNoteMessage PeerNoteKind = "message" // words to this agent
	PeerNoteDone    PeerNoteKind = "done"    // the sender finished and says what came of it
	PeerNoteIdle    PeerNoteKind = "idle"    // the sender waits, with nothing to report
	PeerNoteEvent   PeerNoteKind = "event"   // another notice of the protocol, by its event
)

type PendingModel

type PendingModel struct {
	ID         string         `json:"id"`
	Effort     *Effort        `json:"effort"`
	Ultracode  bool           `json:"ultracode,omitempty"`
	Fast       bool           `json:"fast,omitempty"`
	Permission PermissionMode `json:"permission,omitempty"`
	Since      Ms             `json:"since"`
	Applying   bool           `json:"applying"`
}

PendingModel is a model change accepted and not applied yet. It waits for the agent: not started (stopped, gone, never launched) it is applied right after the launch, before the first message; mid-turn, at the end of the turn, before the next queued message is typed. Applying is true while the runtime types it into the agent's box. The latest ask replaces the one waiting.

func (*PendingModel) UnmarshalJSON

func (p *PendingModel) UnmarshalJSON(b []byte) error

type Permission

type Permission struct {
	ID             string             `json:"id"`
	ConversationID string             `json:"conversationId"`
	TurnID         *string            `json:"turnId"`
	Kind           PermissionKind     `json:"kind"`
	AskedAt        Ms                 `json:"askedAt"`
	Tool           *string            `json:"tool"`
	Command        *string            `json:"command"`
	Cwd            *string            `json:"cwd"`
	PlanMD         *string            `json:"planMd"`
	Options        []PermissionOption `json:"options"` // read off the screen
	State          GateState          `json:"state"`
}

Permission is a tool permission or a plan to approve; its id is "p:" and the tool use id, or "p:<tabId>:<eventSeq>" when the agent gave none (Claude: a Notification and the menu on the screen). TurnID is nil outside a turn.

func (Permission) Validate

func (p Permission) Validate() error

type PermissionKind

type PermissionKind string

PermissionKind tells a tool permission from a plan.

const (
	PermTool PermissionKind = "tool"
	PermPlan PermissionKind = "plan"
	// PermDialog is any other menu the agent stands on, which no tool call named: its words are in PlanMD.
	PermDialog PermissionKind = "dialog"
)

type PermissionMode

type PermissionMode string

PermissionMode is how an agent asks before it acts, as the chat's picker offers it:

  • plan: it plans and changes nothing until the plan is accepted (Claude Code's `plan`, Codex's Plan mode);
  • ask: it asks before edits and commands (Claude Code's `default`, Codex's `untrusted` approvals);
  • bypass: it asks nothing (Claude Code's `bypassPermissions`, Codex's `--yolo`).
const (
	PermissionPlan   PermissionMode = "plan"
	PermissionAsk    PermissionMode = "ask"
	PermissionBypass PermissionMode = "bypass"
)

func (PermissionMode) Known

func (p PermissionMode) Known() bool

Known: one of PermissionModes.

type PermissionOption

type PermissionOption struct {
	ID    string          `json:"id"`
	Label string          `json:"label"`
	Scope PermissionScope `json:"scope"`
}

PermissionOption is one choice of a permission menu.

type PermissionRequestedEv

type PermissionRequestedEv struct {
	Permission Permission `json:"permission"`
}

PermissionRequestedEv: the agent asks for a tool permission.

func (PermissionRequestedEv) EventType

func (PermissionRequestedEv) EventType() EventType

func (PermissionRequestedEv) MarshalJSON

func (e PermissionRequestedEv) MarshalJSON() ([]byte, error)

func (PermissionRequestedEv) Validate

func (e PermissionRequestedEv) Validate() error

type PermissionScope

type PermissionScope string

PermissionScope is what a permission option grants.

const (
	ScopeOnce     PermissionScope = "once"
	ScopeAlways   PermissionScope = "always"
	ScopeDeny     PermissionScope = "deny"
	ScopePlanAuto PermissionScope = "plan-auto"
	ScopePlanAsk  PermissionScope = "plan-ask"
	ScopeRevise   PermissionScope = "revise"
)

type PersonSettings

type PersonSettings struct {
	UIVersion string `json:"uiVersion"` // legacy | next
	Locale    string `json:"locale"`    // ru | en
	Density   string `json:"density"`   // compact | full
	TextSize  string `json:"textSize"`  // s | m | l
	// NoticeColor is the colour of what pops up (notices, toasts): contrast — the other of the theme (dark on light, light
	// on dark); theme — the theme's own.
	NoticeColor string `json:"noticeColor"`
	// VoiceMascot is the voice agent's head in the field while the voice is on: h — the «h» (the default), face —
	// «Головка».
	VoiceMascot    string         `json:"voiceMascot"`
	EnterSends     bool           `json:"enterSends"`
	DefaultMachine *string        `json:"defaultMachine"`
	Notify         NotifySettings `json:"notify"`
	QuickPrompts   []string       `json:"quickPrompts"`
	// Keys are the shortcuts the person changed: an action's id to its shortcuts («Mod+Shift+KeyO»); an empty list
	// turns the action off.
	Keys  map[string][]string `json:"keys"`
	Voice VoiceSettings       `json:"voice"`
	// DayStartHour is the Moscow hour the person's day starts at (0–23): «today» of the spend is counted from it.
	DayStartHour int `json:"dayStartHour"`
	// Nav is how the person laid out the sidebar's menu: the order of its items, the hidden ones, the apps raised to the
	// top level and the order of the apps under «Приложения». Empty lists are the default layout.
	Nav NavSettings `json:"nav"`
	// Prefs are the person's choices a page keeps in its browser too (the theme, Beta, the feed's cards, the
	// notices…), so every device has the same: the browser's own value of each, by its key.
	Prefs PrefsSettings `json:"prefs"`
}

PersonSettings are a person's settings (spec §5): the cluster keeps them in person_settings, a runtime on its own in <data>/v2/me.json. A patch replaces whole top-level keys.

func ApplySettingsPatch

func ApplySettingsPatch(cur PersonSettings, patch json.RawMessage) (PersonSettings, error)

ApplySettingsPatch applies a patch ({"<setting>": value, …}) to the settings: ErrMeBadPatch when a key is not a setting, or a value is out of its type or its limits (the whole patch is refused).

func DefaultSettings

func DefaultSettings() PersonSettings

DefaultSettings are the settings of a person who changed nothing.

type Picture

type Picture struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

Picture is a picture a message of the conversation names by its path (the agent's «Скриншот: /tmp/…/home.png», a pasted upload's path in the person's words): Text is the path exactly as the message writes it, so the page finds it in the text. Listed only while the file is there, inside the conversation's folder, a Claude scratchpad or the uploads, and a picture by its first bytes. Its bytes are GET /api/v2/conversations/{id}/shot?id=<id>, as a shot's.

func (Picture) Validate

func (p Picture) Validate() error

type PicturesSetEv

type PicturesSetEv struct {
	Pictures []Picture `json:"pictures"`
}

PicturesSetEv is the whole list of pictures the messages name, when it changed.

func (PicturesSetEv) EventType

func (PicturesSetEv) EventType() EventType

func (PicturesSetEv) MarshalJSON

func (e PicturesSetEv) MarshalJSON() ([]byte, error)

func (PicturesSetEv) Validate

func (e PicturesSetEv) Validate() error

type PingFrame

type PingFrame struct {
	T int64 `json:"t"`
}

PingFrame is the page's heartbeat; T comes back in the pong.

func (PingFrame) ClientFrameKind

func (PingFrame) ClientFrameKind() FrameKind

func (PingFrame) MarshalJSON

func (f PingFrame) MarshalJSON() ([]byte, error)

func (PingFrame) Validate

func (f PingFrame) Validate() error

type PlanProposedEv

type PlanProposedEv struct {
	Permission Permission `json:"permission"`
}

PlanProposedEv: the agent proposes a plan; Permission.Kind is plan.

func (PlanProposedEv) EventType

func (PlanProposedEv) EventType() EventType

func (PlanProposedEv) MarshalJSON

func (e PlanProposedEv) MarshalJSON() ([]byte, error)

func (PlanProposedEv) Validate

func (e PlanProposedEv) Validate() error

type PongFrame

type PongFrame struct {
	T int64 `json:"t"`
}

PongFrame answers ping.

func (PongFrame) MarshalJSON

func (f PongFrame) MarshalJSON() ([]byte, error)

func (PongFrame) ServerFrameKind

func (PongFrame) ServerFrameKind() FrameKind

func (PongFrame) Validate

func (f PongFrame) Validate() error

type PrefsSettings

type PrefsSettings struct {
	Synced bool              `json:"synced"`
	Values map[string]string `json:"values"`
}

PrefsSettings are the browser-kept choices of the person (PersonSettings.Prefs). Synced says a page has put its browser's values here once: until then the first page the person opens moves its own ones in.

type ProfileInfo added in v0.15.46

type ProfileInfo struct {
	ID     string        `json:"id"`
	Label  string        `json:"label"`
	Vendor ProfileVendor `json:"vendor"`
	Via    Provider      `json:"via"`
	Host   string        `json:"host"`
	Hint   string        `json:"hint"`
	Key    ProfileKey    `json:"key"`
	Models []AgentModel  `json:"models"`
	// Login is the vendor CLI's own sign-in the profile runs on while no key is saved (the Grok CLI's for xai, the Codex
	// CLI's for gpt); absent while the CLI is not signed in, and from a runtime that does not read it.
	Login *ProfileLogin `json:"login,omitempty"`
	// Switch is present on a profile that takes no key but is turned on and off (gpt: a local proxy over the Codex
	// CLI's ChatGPT sign-in); absent on the others.
	Switch *ProfileSwitch `json:"switch,omitempty"`
	// Account: the profile's key is an account of the person's providers, added and changed there; no key is typed for
	// the profile itself. Absent on a profile that keeps a key of its own.
	Account bool `json:"account,omitempty"`
}

ProfileInfo is one profile of the Settings screen: GET /api/v2/providers lists every preset of the runtime, a key saved or not. Via is the agent CLI it runs through. Host is the vendor's host the requests go to (shown, never typed: the person cannot point a key at another address). Hint is one line on the plan, in the runtime's wording, "" when there is none.

func (ProfileInfo) Validate added in v0.15.46

func (p ProfileInfo) Validate() error

type ProfileKey added in v0.15.46

type ProfileKey struct {
	Configured bool    `json:"configured"`
	Tail       *string `json:"tail"`
}

ProfileKey is whether a key is saved for a profile: Tail is its last four characters after an ellipsis, null while none is saved. It is the whole of what the runtime ever says about a key.

func (ProfileKey) Validate added in v0.15.46

func (k ProfileKey) Validate() error

type ProfileKeyEdit added in v0.15.46

type ProfileKeyEdit struct {
	Key string `json:"key"`
}

ProfileKeyEdit is the body of PUT /api/v2/providers/<id>/key. The key is a token as a vendor issues it: printable characters without a space, at least ProfileKeyMin and at most ProfileKeyMax of them.

func (ProfileKeyEdit) Validate added in v0.15.46

func (e ProfileKeyEdit) Validate() error

type ProfileList added in v0.15.46

type ProfileList struct {
	Profiles []ProfileInfo `json:"profiles"`
}

ProfileList is the answer of GET /api/v2/providers.

func (ProfileList) Validate added in v0.15.46

func (l ProfileList) Validate() error

type ProfileLogin added in v0.15.46

type ProfileLogin struct {
	Account string `json:"account"`
}

ProfileLogin is a sign-in of the vendor's CLI on the machine: whom it is of (an email; "" when the CLI does not say). The credential stays with the CLI.

type ProfileOffer added in v0.15.46

type ProfileOffer struct {
	ID         string        `json:"id"`
	Label      string        `json:"label"`
	Vendor     ProfileVendor `json:"vendor"`
	Configured bool          `json:"configured"`
	Models     []AgentModel  `json:"models"`
}

ProfileOffer is a profile a machine can start a conversation on, as MachineAgent.Profiles lists it under the agent CLI the profile runs through. Models are the profile's own (ids of the vendor), and a conversation of the profile takes only these. A page draws a profile that is not Configured as not offered.

func (ProfileOffer) Validate added in v0.15.46

func (p ProfileOffer) Validate() error

type ProfileSwitch added in v0.16.42

type ProfileSwitch struct {
	On bool `json:"on"`
}

ProfileSwitch is whether the person turned a switched profile on. On says nothing of whether it can run now: the offer's `configured` does (on, the CLI signed in, the proxy up).

type ProfileSwitchEdit added in v0.16.42

type ProfileSwitchEdit struct {
	On *bool `json:"on"`
}

ProfileSwitchEdit is the body of PUT /api/v2/providers/<id>/switch; `on` is required.

func (ProfileSwitchEdit) Validate added in v0.16.42

func (e ProfileSwitchEdit) Validate() error

type ProfileSwitchError added in v0.16.42

type ProfileSwitchError struct {
	Reason  ProfileSwitchReason
	Message string
}

ProfileSwitchError is what a ProfileSwitcher refuses to turn a switch on with; the switch stays off.

func (*ProfileSwitchError) Error added in v0.16.42

func (e *ProfileSwitchError) Error() string

type ProfileSwitchReason added in v0.16.42

type ProfileSwitchReason string

ProfileSwitchReason is why a switch could not be turned on.

const (
	// SwitchNoLogin: the vendor CLI is not signed in by a subscription (gpt: no ChatGPT sign-in of Codex).
	SwitchNoLogin ProfileSwitchReason = "no-login"
	// SwitchDownload: the proxy could not be downloaded or did not match its pinned digest.
	SwitchDownload ProfileSwitchReason = "download"
	// SwitchStart: the proxy did not start or did not answer in time.
	SwitchStart ProfileSwitchReason = "start"
)

type ProfileSwitchRefusal added in v0.16.42

type ProfileSwitchRefusal struct {
	R       ResultKind          `json:"r"`
	Code    RefuseCode          `json:"code"`
	Reason  ProfileSwitchReason `json:"reason"`
	Message string              `json:"message"`
}

ProfileSwitchRefusal is the answer of a switch that did not go on: the code of the protocol, why, and a message in the runtime's words (English, for the log; the page words the reason itself).

func (ProfileSwitchRefusal) Validate added in v0.16.42

func (m ProfileSwitchRefusal) Validate() error

type ProfileSwitcher added in v0.16.42

type ProfileSwitcher interface {
	SwitchProfile(ctx context.Context, id string, on bool) (ProfileInfo, error)
}

ProfileSwitcher is a ProfilesSource whose switched profiles can be turned on and off. SwitchProfile answers the profile as GET lists it once the switch took: turned on, it waits for the proxy to answer (the first time also for its download), so the caller gives it SwitchTimeout. It refuses with a *ProfileSwitchError.

type ProfileTest added in v0.15.46

type ProfileTest struct {
	OK     bool               `json:"ok"`
	Reason *ProfileTestReason `json:"reason"`
	Status *int               `json:"status"`
	Ms     int64              `json:"ms"`
}

ProfileTest is the answer of POST /api/v2/providers/<id>/test: one minimal request to the vendor with the saved key. A pass has no Reason; a failure has one. Status is the vendor's HTTP code, null where it did not answer. Ms is how long the request took. The answer never holds the key or the vendor's body.

func (ProfileTest) Validate added in v0.15.46

func (t ProfileTest) Validate() error

type ProfileTestReason added in v0.15.46

type ProfileTestReason string

ProfileTestReason is why a test of a connection did not pass.

const (
	// TestNoKey: no key is saved for the profile.
	TestNoKey ProfileTestReason = "no-key"
	// TestUnauthorized: the vendor refused the key (401).
	TestUnauthorized ProfileTestReason = "unauthorized"
	// TestForbidden: the key is known but the plan does not allow the model (403), or has no balance.
	TestForbidden ProfileTestReason = "forbidden"
	// TestRateLimited: the vendor answered 429.
	TestRateLimited ProfileTestReason = "rate-limited"
	// TestUnreachable: the vendor's host did not answer.
	TestUnreachable ProfileTestReason = "unreachable"
	// TestTimeout: the vendor did not answer in time.
	TestTimeout ProfileTestReason = "timeout"
	// TestRejected: the vendor answered another error; Status is its code.
	TestRejected ProfileTestReason = "rejected"
)

type ProfileVendor added in v0.15.46

type ProfileVendor string

ProfileVendor is whose models a profile offers; it picks the mark the page draws.

const (
	VendorKimi ProfileVendor = "kimi"
	VendorGLM  ProfileVendor = "glm"
	VendorGrok ProfileVendor = "grok"
	VendorGPT  ProfileVendor = "gpt"
	// VendorAuto is the router over the person's GLM and Kimi Code subscriptions (providers.Router).
	VendorAuto ProfileVendor = "auto"
	// VendorOwn is a provider the person added themselves or got from the team's environment (internal/extproviders):
	// it has no mark of a vendor, the page draws the neutral one.
	VendorOwn ProfileVendor = "own"
)

type ProfilesSource added in v0.15.46

type ProfilesSource interface {
	Profiles(ctx context.Context) (ProfileList, error)
	// SetProfileKey saves the key of a profile, replacing a saved one.
	SetProfileKey(ctx context.Context, id, key string) (ProfileKey, error)
	// RemoveProfileKey deletes the saved key; a profile with none stays as it is.
	RemoveProfileKey(ctx context.Context, id string) (ProfileKey, error)
	// TestProfile makes one minimal request to the vendor with the saved key.
	TestProfile(ctx context.Context, id string) (ProfileTest, error)
}

ProfilesSource keeps the profiles of this machine and their keys.

type Project

type Project struct {
	ID        string `json:"id"`
	MachineID string `json:"machineId"`
	Path      string `json:"path"`
	Name      string `json:"name"`
	Git       bool   `json:"git"`
	CreatedAt Ms     `json:"createdAt"`
}

Project is a folder on a machine made a project; its id is the machine's own and is not to be parsed.

func (Project) Validate

func (p Project) Validate() error

type ProjectCreateCmd

type ProjectCreateCmd struct {
	OpID string `json:"opId"`
	Path string `json:"path,omitempty"`
	Name string `json:"name,omitempty"`
}

ProjectCreateCmd makes a folder of the machine a project. Name is what the person calls it, the folder's own name when empty. Without a path the project is a named group of chats that start in the machine's default folder.

func (ProjectCreateCmd) Op

func (ProjectCreateCmd) Op() Op

func (ProjectCreateCmd) OpKey

func (c ProjectCreateCmd) OpKey() string

func (ProjectCreateCmd) Validate

func (c ProjectCreateCmd) Validate() error

type ProjectUpdateCmd added in v0.16.24

type ProjectUpdateCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
	Path string `json:"path,omitempty"`
	Name string `json:"name,omitempty"`
}

ProjectUpdateCmd changes a project: Path, the folder its new chats start in (chats already made stay where they are); Name, what the person calls it. An empty field is left as it is, one of them is needed.

func (ProjectUpdateCmd) Op added in v0.16.24

func (ProjectUpdateCmd) Op() Op

func (ProjectUpdateCmd) OpKey added in v0.16.24

func (c ProjectUpdateCmd) OpKey() string

func (ProjectUpdateCmd) Validate added in v0.16.24

func (c ProjectUpdateCmd) Validate() error

type ProjectUpsertEv

type ProjectUpsertEv struct {
	Project Project `json:"project"`
}

ProjectUpsertEv is a project's whole record, new or the same again.

func (ProjectUpsertEv) EventType

func (ProjectUpsertEv) EventType() EventType

func (ProjectUpsertEv) MarshalJSON

func (e ProjectUpsertEv) MarshalJSON() ([]byte, error)

func (ProjectUpsertEv) Validate

func (e ProjectUpsertEv) Validate() error

type PromoteCmd

type PromoteCmd struct {
	OpID           string    `json:"opId"`
	ConversationID string    `json:"conversationId"`
	ClientID       string    `json:"clientId"`
	To             PromoteTo `json:"to"`
}

PromoteCmd moves a queued message to now or to steer.

func (PromoteCmd) Op

func (PromoteCmd) Op() Op

func (PromoteCmd) OpKey

func (c PromoteCmd) OpKey() string

func (PromoteCmd) Validate

func (c PromoteCmd) Validate() error

type PromoteTo

type PromoteTo string

PromoteTo is where promote moves a queued message.

const (
	PromoteToNow   PromoteTo = "now"
	PromoteToSteer PromoteTo = "steer"
)

type PromptStateEv

type PromptStateEv struct {
	ClientID string       `json:"clientId"`
	State    MessageState `json:"state"`
	Rev      int64        `json:"rev"`
}

PromptStateEv is a message's new state, on every server-side step of it.

func (PromptStateEv) EventType

func (PromptStateEv) EventType() EventType

func (PromptStateEv) MarshalJSON

func (e PromptStateEv) MarshalJSON() ([]byte, error)

func (PromptStateEv) Validate

func (e PromptStateEv) Validate() error

type Provider

type Provider string

Provider is the agent CLI behind a conversation.

const (
	ProviderClaude Provider = "claude"
	ProviderCodex  Provider = "codex"
)

type Question

type Question struct {
	ID             string         `json:"id"`
	ConversationID string         `json:"conversationId"`
	TurnID         string         `json:"turnId"`
	AskedAt        Ms             `json:"askedAt"`
	Items          []QuestionItem `json:"items"`
	State          GateState      `json:"state"`
}

Question is an AskUserQuestion; its id is "q:" and the tool use id. Question and permission ids share one space within a conversation, told apart by their prefix: the runtime guarantees it.

func (Question) Validate

func (q Question) Validate() error

type QuestionAnswer

type QuestionAnswer struct {
	I       int     `json:"i"`
	Choices []int   `json:"choices"`
	Text    *string `json:"text,omitempty"`
}

QuestionAnswer is the answer to item I: the indexes of the chosen options, or the person's own text instead of them — never both, and never neither.

type QuestionAskedEv

type QuestionAskedEv struct {
	Question Question `json:"question"`
}

QuestionAskedEv: the agent asks a question.

func (QuestionAskedEv) EventType

func (QuestionAskedEv) EventType() EventType

func (QuestionAskedEv) MarshalJSON

func (e QuestionAskedEv) MarshalJSON() ([]byte, error)

func (QuestionAskedEv) Validate

func (e QuestionAskedEv) Validate() error

type QuestionItem

type QuestionItem struct {
	Header   string           `json:"header"`
	Question string           `json:"question"`
	Multi    bool             `json:"multi"`
	Options  []QuestionOption `json:"options"`
}

QuestionItem is one question of an AskUserQuestion.

type QuestionOption

type QuestionOption struct {
	Label       string  `json:"label"`
	Description *string `json:"description"`
	Preview     *string `json:"preview"`
}

QuestionOption is one choice of a question.

type Queue

type Queue struct {
	ConversationID string      `json:"conversationId"`
	Items          []string    `json:"items"`
	Paused         *QueuePause `json:"paused"`
	Rev            int64       `json:"rev"`
	// Stalled are the items that wait stalled, for the older form of the queue (a page without CapMsgStatus does not
	// list them: it holds them as failed). Server only.
	Stalled []string `json:"-"`
}

Queue is a conversation's queue: client ids, the head first.

func (Queue) Validate

func (q Queue) Validate() error

type QueueChangedEv

type QueueChangedEv struct {
	Queue Queue       `json:"queue"`
	Agent *AgentStamp `json:"agent,omitempty"`
	Pane  *Pane       `json:"pane,omitempty"`
}

QueueChangedEv is the conversation's whole queue. Agent, when set, is the agent state that changed with it: the conversation's channel has no event of its own for the state, and a page that does not read the field takes the event as the queue it already holds.

Pane, when set, is what the right pane's tools read of the conversation, as the read of its transcript that made the events before this one left it (see Pane): it rides here for the same reason, a page that does not read it keeps the queue it holds.

func (QueueChangedEv) EventType

func (QueueChangedEv) EventType() EventType

func (QueueChangedEv) MarshalJSON

func (e QueueChangedEv) MarshalJSON() ([]byte, error)

func (QueueChangedEv) Validate

func (e QueueChangedEv) Validate() error

type QueueMoveCmd

type QueueMoveCmd struct {
	OpID           string  `json:"opId"`
	ConversationID string  `json:"conversationId"`
	ClientID       string  `json:"clientId"`
	BeforeClientID *string `json:"beforeClientId"`
}

QueueMoveCmd puts a queued message before another queued one of the same conversation (BeforeClientID null: at the end of the line). Only a message that is queued moves; one being typed, taken or past that stays where it is.

func (QueueMoveCmd) Op

func (QueueMoveCmd) Op() Op

func (QueueMoveCmd) OpKey

func (c QueueMoveCmd) OpKey() string

func (QueueMoveCmd) Validate

func (c QueueMoveCmd) Validate() error

type QueuePause

type QueuePause struct {
	Reason PauseReason `json:"reason"`
	At     Ms          `json:"at"`
}

QueuePause is why and since when a queue is paused.

func (QueuePause) Validate

func (p QueuePause) Validate() error

type QueueReason

type QueueReason string

QueueReason is why a queued message waits.

const (
	QueuedBehind      QueueReason = "behind"
	QueuedAgentBusy   QueueReason = "agent-busy"
	QueuedLaunching   QueueReason = "launching"
	QueuedResuming    QueueReason = "resuming"
	QueuedPaused      QueueReason = "paused"
	QueuedBlockedMenu QueueReason = "blocked-menu"
	QueuedBlockedText QueueReason = "blocked-text"
	// QueuedStalled: typed, and the agent did not take it within ConfirmDeadline — something is wrong beyond this
	// message. It is back at the head of the line, its text out of the agent's input box, and waits for the person
	// (retry or promote) instead of being typed again by itself: it is never typed twice. Only for a page with
	// CapMsgStatus; any other page gets it as failed{unconfirmed}.
	QueuedStalled QueueReason = "stalled"
)

type QueueResumeCmd

type QueueResumeCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
}

QueueResumeCmd lifts a queue's pause.

func (QueueResumeCmd) Op

func (QueueResumeCmd) Op() Op

func (QueueResumeCmd) OpKey

func (c QueueResumeCmd) OpKey() string

func (QueueResumeCmd) Validate

func (c QueueResumeCmd) Validate() error

type QueueSummary

type QueueSummary struct {
	Count  int         `json:"count"`
	Paused *QueuePause `json:"paused"`
}

QueueSummary is a conversation's queue as the sidebar needs it.

func (QueueSummary) Validate

func (q QueueSummary) Validate() error

type QuotaExhaustedEv added in v0.16.5

type QuotaExhaustedEv struct {
	Failure TerminalFailure `json:"failure"`
}

QuotaExhaustedEv says the provider cannot accept another request on the current target. It is emitted once for the failed turn; the conversation record carries the durable marker.

func (QuotaExhaustedEv) EventType added in v0.16.5

func (QuotaExhaustedEv) EventType() EventType

func (QuotaExhaustedEv) MarshalJSON added in v0.16.5

func (e QuotaExhaustedEv) MarshalJSON() ([]byte, error)

func (QuotaExhaustedEv) Validate added in v0.16.5

func (e QuotaExhaustedEv) Validate() error

type Reach

type Reach string

Reach is whether the cluster hears a machine; standalone it is always online.

const (
	ReachOnline      Reach = "online"
	ReachUnreachable Reach = "unreachable"
	ReachUnknown     Reach = "unknown"
)

type Recap

type Recap struct {
	Text string `json:"text"`
	At   Ms     `json:"at"`
}

Recap is the summary Claude Code writes for the person who comes back after being away. At is when it was written.

type RefKind

type RefKind string

RefKind is what a MessageRef points at.

const (
	RefDesign RefKind = "design"
	RefDoc    RefKind = "doc"
	RefBoard  RefKind = "board"
	RefFile   RefKind = "file"
	RefMR     RefKind = "mr"
	RefTask   RefKind = "task"
	// RefChat is another conversation: ID is its id; the runtime hands the agent an excerpt and the path of the whole.
	RefChat RefKind = "chat"
)

type RefuseCode

type RefuseCode string

RefuseCode is why a command was refused.

const (
	RefuseBadRequest         RefuseCode = "bad-request"
	RefuseConflict           RefuseCode = "conflict"
	RefuseUnsupported        RefuseCode = "unsupported"
	RefuseForbidden          RefuseCode = "forbidden"
	RefuseNotFound           RefuseCode = "not-found"
	RefuseMachineRequired    RefuseCode = "machine-required"
	RefuseMachineOffline     RefuseCode = "machine-offline"
	RefuseAgentGone          RefuseCode = "agent-gone"
	RefuseAgentWorking       RefuseCode = "agent-working"
	RefuseNotWorking         RefuseCode = "not-working"
	RefuseQueueFull          RefuseCode = "queue-full"
	RefuseTextTooLong        RefuseCode = "text-too-long"
	RefuseAttachmentMissing  RefuseCode = "attachment-missing"
	RefuseAttachmentTooLarge RefuseCode = "attachment-too-large"
	RefuseAttachmentType     RefuseCode = "attachment-type"
	RefuseTooManyAttachments RefuseCode = "too-many-attachments"
	RefuseTooLate            RefuseCode = "too-late"
	RefuseNotFailed          RefuseCode = "not-failed"
	RefuseGateClosed         RefuseCode = "gate-closed"
	RefuseGateAnswered       RefuseCode = "gate-answered"
	RefuseOptionUnknown      RefuseCode = "option-unknown"
	RefuseRateLimited        RefuseCode = "rate-limited"
	RefuseInternal           RefuseCode = "internal"
	RefuseTimeout            RefuseCode = "timeout"
)

type ResultKind

type ResultKind string

ResultKind is the outcome of a command.

const (
	ResultAccepted ResultKind = "accepted"
	ResultQueued   ResultKind = "queued"
	ResultRefused  ResultKind = "refused"
)

type RetryCmd

type RetryCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
	ClientID       string `json:"clientId"`
}

RetryCmd queues a failed message again, attempts+1.

func (RetryCmd) Op

func (RetryCmd) Op() Op

func (RetryCmd) OpKey

func (c RetryCmd) OpKey() string

func (RetryCmd) Validate

func (c RetryCmd) Validate() error

type RewindChange

type RewindChange struct {
	Path   string     `json:"path"`
	Change FileChange `json:"change"`
}

RewindChange is one file a rewind of the folder changes.

type RewindCmd

type RewindCmd struct {
	OpID    string `json:"opId"`
	ID      string `json:"id"`
	EntryID string `json:"entryId"`
	Text    string `json:"text"`
	Files   bool   `json:"files"`
}

RewindCmd goes on from before one of the person's messages (EntryID, a turn's opening user entry) with Text in its place: the agent starts again on the conversation as it was before that message, and the turns from it on are left behind. Files returns the chat's folder to its snapshot from before the message too. Only while the agent is idle.

func (RewindCmd) Op

func (RewindCmd) Op() Op

func (RewindCmd) OpKey

func (c RewindCmd) OpKey() string

func (RewindCmd) Validate

func (c RewindCmd) Validate() error

type RewindFiles

type RewindFiles struct {
	At Ms `json:"at"`
	// Changes are the files that would change, at most RewindChangesMax of them; More is how many more.
	Changes []RewindChange `json:"changes"`
	More    int            `json:"more"`
}

RewindFiles is the folder's snapshot a rewind can return to.

type RewindMark

type RewindMark struct {
	At Ms `json:"at"`
	// AfterTurnID is the last turn kept, after which the feed draws what was left; null when the cut kept none of the
	// turns the transcript showed (they were before the first one read).
	AfterTurnID *string `json:"afterTurnId"`
	// Turns is how many turns were left behind: the message's own and every one after it.
	Turns int `json:"turns"`
	// Files: the chat's folder was returned to how it was before the message too.
	Files bool `json:"files"`
	// UndoUntil is until when rewind.undo takes the conversation back to where it was.
	UndoUntil Ms `json:"undoUntil"`
}

RewindMark is one rewind: the conversation went on from before one of the person's messages, with other words, and the turns from that message on were left behind (they stay readable: GET .../rewinds/{n}/turns).

func (RewindMark) Validate

func (m RewindMark) Validate() error

type RewindPlan

type RewindPlan struct {
	EntryID string `json:"entryId"`
	// Turns is how many turns the rewind leaves behind.
	Turns int `json:"turns"`
	// Files is the snapshot of the chat's folder from before the message and what returning to it changes; null when
	// there is none (the snapshots are taken when a turn ends).
	Files *RewindFiles `json:"files"`
}

RewindPlan is what a rewind to one of the person's messages would do, before the person chooses: GET /api/v2/conversations/{id}/rewind?entryId=.

func (RewindPlan) Validate

func (p RewindPlan) Validate() error

type RewindSource

type RewindSource interface {
	// Plan is what a rewind to the person's message entryID would do.
	Plan(ctx context.Context, conv, entryID string) (RewindPlan, error)
	// Rewound is the turns the conversation's rewind n (an index into its Rewinds) left behind, oldest first.
	Rewound(ctx context.Context, conv string, n int) (TurnsPage, error)
}

RewindSource is the rewinds of the conversations (convo.Runtime).

type RewindUndoCmd

type RewindUndoCmd struct {
	OpID string `json:"opId"`
	ID   string `json:"id"`
}

RewindUndoCmd takes the conversation back to where the last rewind took it from (and the folder, when that rewind returned it), while the rewind's UndoUntil has not passed.

func (RewindUndoCmd) Op

func (RewindUndoCmd) Op() Op

func (RewindUndoCmd) OpKey

func (c RewindUndoCmd) OpKey() string

func (RewindUndoCmd) Validate

func (c RewindUndoCmd) Validate() error

type RuntimeInfo

type RuntimeInfo struct {
	Version  string    `json:"version"`
	Proto    int       `json:"proto"`
	Features []Feature `json:"features"`
}

RuntimeInfo is what a machine's runtime says of itself.

func (RuntimeInfo) Validate

func (r RuntimeInfo) Validate() error

type RuntimePerson

type RuntimePerson struct {
	Voice VoiceSettings `json:"voice"`
}

RuntimePerson is the part of a person's settings the runtime works by: the keys of Settings marked Runtime.

func RuntimePersonOf

func RuntimePersonOf(st PersonSettings) RuntimePerson

RuntimePersonOf is the part of the settings a runtime is handed.

type RuntimeSettings

type RuntimeSettings struct {
	IdleStop        IdleStop `json:"idleStop"`
	LimitContinue   OnOff    `json:"limitContinue,omitempty"`
	RestartContinue OnOff    `json:"restartContinue,omitempty"`
	// Delegation is what agents may do with the chats they delegate; absent is DefaultDelegation, and a PUT without it
	// keeps what was set.
	Delegation *DelegationSettings `json:"delegation,omitempty"`
	// NoticeSummary is the model that sums up a finished turn for the «готово» notification; absent is
	// «Авто»: the chat's own provider and its cheap model. A PUT without it keeps what was set.
	NoticeSummary *NoticeSummaryModel `json:"noticeSummary,omitempty"`
}

RuntimeSettings are the settings of the runtime itself, the machine's and not the person's: GET and PUT /api/v2/runtime-settings, kept in <data>/v2/runtime-settings.json.

LimitContinue: a chat held on its usage limit goes on by itself when the limit resets. RestartContinue: a chat whose turn a restart of the runtime cut short goes on by itself once its agent is back. A PUT that leaves one out keeps it.

func DefaultRuntimeSettings

func DefaultRuntimeSettings() RuntimeSettings

DefaultRuntimeSettings are the settings of a runtime nobody set.

func RuntimeSettingsFor

func RuntimeSettingsFor(s RuntimeSettings, caps Caps) RuntimeSettings

RuntimeSettingsFor is the runtime's settings as a page with caps reads them.

func (RuntimeSettings) DelegationOf

func (s RuntimeSettings) DelegationOf() DelegationSettings

DelegationOf is the delegation settings in force: s.Delegation, else the defaults.

func (RuntimeSettings) Validate

func (s RuntimeSettings) Validate() error

type RuntimeSettingsStore

type RuntimeSettingsStore interface {
	RuntimeSettings() RuntimeSettings
	SetRuntimeSettings(s RuntimeSettings) (RuntimeSettings, error)
}

RuntimeSettingsStore keeps the settings of the runtime itself (RuntimeSettings).

type SeenCmd

type SeenCmd struct {
	OpID           string `json:"opId"`
	ConversationID string `json:"conversationId"`
	UpTo           Ms     `json:"upTo"`
}

SeenCmd moves seenAt to max(seenAt, UpTo) of one conversation or of all (ConversationID = SeenAll).

func (SeenCmd) Op

func (SeenCmd) Op() Op

func (SeenCmd) OpKey

func (c SeenCmd) OpKey() string

func (SeenCmd) Validate

func (c SeenCmd) Validate() error

type SendCmd

type SendCmd struct {
	OpID           string      `json:"opId"`
	ClientID       string      `json:"clientId"`
	ConversationID string      `json:"conversationId"`
	Text           string      `json:"text"`
	AttachmentIDs  []string    `json:"attachmentIds"`
	Mode           MessageMode `json:"mode"`
	Kind           MessageKind `json:"kind"`
	// Refs are the places the message points at; the runtime appends their block to Text. Absent when none.
	Refs []MessageRef `json:"refs,omitempty"`
}

SendCmd puts a message in the conversation's queue; its opId is its clientId.

func (SendCmd) Op

func (SendCmd) Op() Op

func (SendCmd) OpKey

func (c SendCmd) OpKey() string

func (SendCmd) Validate

func (c SendCmd) Validate() error

type Server

type Server struct {
	Hub     *Hub
	Service Service
	Machine MachineSource
	Ops     *OpLog
	Uploads *Uploads
	// Dirs lists the folders offered for a new project; nil: GET /api/v2/dirs is a 404.
	Dirs func(ctx context.Context) ([]Dir, error)
	// Sessions lists the agent sessions of the machine that no conversation holds, the newest first; nil: GET
	// /api/v2/sessions is a 404.
	Sessions func(ctx context.Context) ([]AgentSession, error)
	// Terminals gives the conversations' terminals; nil: /api/v2/terminal and .../terminals are 404s.
	Terminals TerminalSource
	// Voice recognizes a recording (lang is ru, en or auto) and returns its text; nil: POST /api/v2/voice is a 404.
	// ErrVoiceUnavailable: this machine cannot recognize.
	Voice func(ctx context.Context, audio io.Reader, lang, engine string) (string, error)
	// SideChat answers a question about a conversation with a stream of server-sent frames (delta, done, error) written
	// to w, and the refusals of its own (unsupported, no-session, busy); it returns nil once it has written anything.
	// convo.ErrNotFound: the conversation is not here. nil: POST /api/v2/conversations/{id}/side-chat is a 404.
	SideChat func(w http.ResponseWriter, r *http.Request, conv string) error
	// Rewind says what a rewind to one of the person's messages would do and shows what a rewind left behind; nil:
	// .../rewind and .../rewinds/{n}/turns are 404s.
	Rewind RewindSource
	// HandoffDraft writes the text a handoff or a merge of a conversation carries (an excerpt, a note, a fork's result);
	// ErrDraftUnsupported when there is nothing to make it of. nil: POST …/handoff-draft is a 404.
	HandoffDraft func(ctx context.Context, conv string, req HandoffDraftRequest) (HandoffDraft, error)
	// Move serves /api/v2/move/*: a conversation carried to another machine of the person. It is the cluster's
	// to call, not the page's; nil answers not-found.
	Move http.Handler
	// Tasks is the agent's task list of a conversation; nil: .../tasks is a 404.
	Tasks func(ctx context.Context, conv string) ([]Task, error)
	// Context is how full a conversation's agent window is; nil: .../context is a 404.
	Context func(ctx context.Context, conv string) (ConvContext, error)
	// MessageStatus is the runtime's word on a conversation's messages by their client ids, one per id in order; nil:
	// .../messages is a 404.
	MessageStatus func(ctx context.Context, conv string, ids []string) (MessageStatuses, error)
	// Legacy is the Legacy tab a conversation runs in; nil: .../legacy is a 404.
	Legacy func(ctx context.Context, conv string) (LegacyTab, error)
	// Download hands over files of a conversation to be saved: GET .../download?path=<p>[&path=<p>…][&name=<zip>] sends one
	// file whole or in ranges, a folder or several paths as one zip made while it is sent. It writes the
	// answer itself, with no time budget: a download may take as long as it takes. nil: a 404.
	Download func(w http.ResponseWriter, r *http.Request, conv string)
	// GitSide answers GET .../file-git?path=<p>[&ref=HEAD]: a file as a git revision has it, for the editor's diff
	// nil: a 404.
	GitSide func(w http.ResponseWriter, r *http.Request, conv string)
	// FindText answers GET .../find?q=<text>[&path=<folder>]: the lines of the folder's text files that hold the text,
	// for «Найти в файлах». nil: a 404.
	FindText func(w http.ResponseWriter, r *http.Request, conv string)
	// EntryOp answers POST .../file-op {op, path, name}: a new empty file, a new name or the trash for an entry of
	// «Файлы». nil: a 404.
	EntryOp func(w http.ResponseWriter, r *http.Request, conv string)
	// Files reads the folders of the conversations: .../files lists a folder, .../file reads a text file. nil: both are
	// 404s.
	Files FilesSource
	// PaneSelection hears what is selected in a file open in a chat's pane: POST /api/v2/pane-selection. nil: a 404.
	PaneSelection http.Handler
	// PaneAct is the agent's hand on the page in a chat's pane: GET /api/v2/pane-act?conversation= is the page's long poll
	// for the next action, POST /api/v2/pane-act its outcome. nil: a 404.
	PaneAct http.Handler
	// FileBytes reads a file's revision and saves a file the viewer edits as bytes (a spreadsheet): GET and PUT
	// /api/v2/file-bytes?path=. nil: a 404.
	FileBytes http.Handler
	// Search finds the messages of the conversations that hold the words of a query; nil: GET /api/v2/search is a 404.
	Search func(ctx context.Context, query string, limit int) (MessageSearch, error)
	// Digest cuts a conversation to a block of about budget characters for another agent's context and writes the whole
	// of it to a file; nil: .../digest is a 404.
	Digest func(ctx context.Context, conv string, budget int) (ChatDigest, error)
	// Glance gives what a conversation said last (the newest message of each side), read from the search index and
	// written nowhere; nil: .../glance is a 404.
	Glance func(ctx context.Context, conv string) (ChatGlance, error)
	// Shot opens a picture the conversation lists in its snapshot's shots; ErrNoShot for any other id. nil: .../shot is
	// a 404.
	Shot func(ctx context.Context, conv, id string) (ShotFile, error)
	// Designly is the machine's design library; nil: /api/v2/designly/* are 404s.
	Designly DesignlySource
	// MachineTool serves the Machine tool: GET /api/v2/machine/stats and POST .../machine/processes/stop; nil: both are
	// 404s.
	MachineTool MachineToolSource
	// Open is where a chip or a link of a conversation opens in the right pane; ErrNothingToOpen for what opens nothing.
	// nil: .../open is a 404.
	Open func(ctx context.Context, conv, ref string) (OpenTarget, error)
	// OpenAll is Open for many refs at once (GET .../open-refs), one answer per ref, nil for what opens nothing; nil:
	// the refs are asked of Open one by one. Both nil: .../open-refs is a 404.
	OpenAll func(ctx context.Context, conv string, refs []string) ([]*OpenTarget, error)
	// Made is what a chat made, opened or changed (GET .../made); nil: it is a 404. A runtime that sets it announces
	// FeatureMade.
	Made func(ctx context.Context, conv string) (ChatMade, error)
	// Apps serves the Apps screen: GET /api/v2/apps; nil: it is a 404.
	Apps AppsSource
	// AgentSettings serves the Settings screen: GET and PATCH /api/v2/agent-settings/<provider>; nil: both are 404s.
	AgentSettings AgentSettingsSource
	// Profiles serves the backend profiles: GET /api/v2/providers, PUT and DELETE .../<id>/key, POST .../<id>/test; nil:
	// all are 404s.
	Profiles ProfilesSource
	// Logins signs the agents in and out: GET/POST/DELETE /api/v2/agents/<provider>/login, POST .../login/code, PUT
	// .../key, POST .../logout; nil: no such routes.
	Logins LoginSource
	// AccountLogins gives the sign-in of one more account of a CLI (`?account=<id>` on the sign-in routes): a home of
	// its own beside the main one. nil, or false for an account it does not know, answers «not found».
	AccountLogins func(p Provider, account string) (LoginSource, bool)
	// RuntimeSettings are the runtime's own settings: GET and PUT /api/v2/runtime-settings; nil: both are 404s.
	RuntimeSettings RuntimeSettingsStore
	// Me is the person of a runtime on its own; nil: /api/v2/me is a 404 (the cluster's gateway answers it itself).
	Me MeStore
	// Looks keeps the pictures of the person's looks (POST/GET /api/v2/me/looks, looks.go); nil: 404s.
	Looks    LookBlobs
	Version  string
	Features []Feature
	Limits   Limits
	// NotFound and UnknownCursor report whether an error of the Service is convo.ErrNotFound, convo.ErrUnknownCursor.
	NotFound      func(error) bool
	UnknownCursor func(error) bool

	// Work is the chats' work the replica socket hands the agent ({"k":"work"}); nil sends none.
	Work WorkFeed
}

Server serves /api/v2: hello, the socket, the commands, the pages and the uploads, on a Service and a machine source. Its fields are set before it serves.

func (*Server) Cmd

func (s *Server) Cmd(w http.ResponseWriter, r *http.Request, op Op)

Cmd serves POST /api/v2/cmd/<op>. Every answer is a CmdResult with status 200, a refusal too: a status other than 2xx is the page's failed{http}. It comes within limits.cmdBudgetMs.

func (*Server) Replica added in v0.16.5

func (s *Server) Replica(w http.ResponseWriter, r *http.Request)

Replica serves GET /api/v2/replica.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP routes /api/v2/*. A page that cannot answer sends a Refusal with its status: 400 bad-request, 404 not-found, 413 attachment-too-large, 415 attachment-type, 503 timeout, 500 internal. The machine parameter is the cluster's: a runtime is one machine and does not read it.

func (*Server) Socket

func (s *Server) Socket(w http.ResponseWriter, r *http.Request)

Socket serves GET /api/v2/socket: one socket per machine and page, its channels by subscription.

func (*Server) Upload

func (s *Server) Upload(w http.ResponseWriter, r *http.Request)

Upload serves PUT /api/v2/uploads?name=<file name>: the body is the file, Content-Type its type. It answers the AttachmentRef, or a Refusal: bad-request without a name, attachment-type for a type that does not parse, attachment-too-large past limits.maxImageBytes or maxFileBytes.

func (*Server) UploadCreate

func (s *Server) UploadCreate(w http.ResponseWriter, r *http.Request)

UploadCreate serves POST /api/v2/uploads: opens a session for a file of size bytes.

type ServerFrame

type ServerFrame interface {
	ServerFrameKind() FrameKind
	Validate() error
}

ServerFrame is a frame the runtime sends on the socket: WelcomeFrame, SnapshotFrame, EvFrame, PongFrame or ErrorFrame.

func DecodeServerFrame

func DecodeServerFrame(b []byte) (ServerFrame, error)

DecodeServerFrame reads and checks one frame from the runtime; an unknown kind or field is an error.

type Service

type Service interface {
	Conversations(ctx context.Context) (ConvsSnapshot, error)
	Conversation(ctx context.Context, id string) (ConvSnapshot, error)
	ConversationAfter(ctx context.Context, id, afterEntryID string) (ConvSnapshot, error)
	Turns(ctx context.Context, id, beforeTurnID string, limit int) (TurnsPage, error)
	TurnEntries(ctx context.Context, id, turnID string) (EntriesPage, error)
	EntryOutput(ctx context.Context, id, entryID string) (OutputPage, error)
	Do(ctx context.Context, device string, cmd Command) CmdResult
}

type Setting

type Setting struct {
	Doc   string
	Key   string
	Owner SettingOwner
	// Runtime: the runtime itself works by this personal setting, so a hub hands the asking person's value to it with
	// the request (PersonHeader).
	Runtime bool
}

Setting is one top-level key of a settings document and its owner.

type SettingOwner

type SettingOwner string

SettingOwner is who a setting belongs to, and so where it is kept.

const (
	// OwnerPerson: the setting is the person's. A hub keeps it by its user (person_settings) and answers for it
	// itself; a runtime on its own, with its one person, keeps it in <data>/v2/me.json.
	OwnerPerson SettingOwner = "person"
	// OwnerMachine: the setting is the machine's, the same for everyone who works on it. The machine keeps it; a hub
	// only passes it on, and may keep a copy to show while the machine is away.
	OwnerMachine SettingOwner = "machine"
)

func SettingsDocOf

func SettingsDocOf(v2path string) (doc string, owner SettingOwner, ok bool)

SettingsDocOf tells which settings document a path under /api/v2 is ("me", "me/settings", "runtime-settings", "agent-settings/claude"), and who owns it; ok is false for a path that is no settings document. A document has one owner: every key of it is that owner's.

type Shot

type Shot struct {
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	At    Ms      `json:"at"`
	Agent *string `json:"agent,omitempty"`
}

Shot is a picture an agent looked at: a file it read, or one a tool (a browser's screenshot) saved. Its bytes are GET /api/v2/conversations/{id}/shot?id=<id>, served only for a picture listed here. Agent is the subagent that looked at it (its description); absent when the agent itself did. At is when it did.

func (Shot) Validate

func (s Shot) Validate() error

type ShotFile

type ShotFile struct {
	Body    io.ReadSeekCloser
	Mime    string
	ModTime time.Time
}

ShotFile is a listed picture opened to be sent.

type ShotsSetEv

type ShotsSetEv struct {
	Shots []Shot `json:"shots"`
}

ShotsSetEv is the whole list of pictures, newest first, when it changed.

func (ShotsSetEv) EventType

func (ShotsSetEv) EventType() EventType

func (ShotsSetEv) MarshalJSON

func (e ShotsSetEv) MarshalJSON() ([]byte, error)

func (ShotsSetEv) Validate

func (e ShotsSetEv) Validate() error

type SnapshotFrame

type SnapshotFrame struct {
	Ch      Channel          `json:"ch"`
	Seq     int64            `json:"seq"` // the last seq the snapshot includes; 0 before any event
	Mode    SnapshotMode     `json:"mode"`
	Machine *MachineSnapshot `json:"-"`
	Convs   *ConvsSnapshot   `json:"-"`
	Conv    *ConvSnapshot    `json:"-"`
}

SnapshotFrame is a channel's state up to Seq. The hub subscribes the channel before it takes the snapshot, so no event is lost between them; the page drops the events with seq ≤ Seq that arrive after it, and applies every event idempotently by id and rev, so an event the snapshot already holds changes nothing. Its data is the one of the channel: Machine, Convs or Conv.

func (SnapshotFrame) MarshalJSON

func (f SnapshotFrame) MarshalJSON() ([]byte, error)

func (SnapshotFrame) ServerFrameKind

func (SnapshotFrame) ServerFrameKind() FrameKind

func (*SnapshotFrame) UnmarshalJSON

func (f *SnapshotFrame) UnmarshalJSON(b []byte) error

func (SnapshotFrame) Validate

func (f SnapshotFrame) Validate() error

type SnapshotMode

type SnapshotMode string

SnapshotMode is a whole snapshot or what follows a cursor.

const (
	SnapshotReplace SnapshotMode = "replace"
	SnapshotAfter   SnapshotMode = "after"
)

type StepEv

type StepEv struct {
	Entry  Entry       `json:"entry"`
	Counts *TurnCounts `json:"counts"`
}

StepEv is a new entry; Counts are its turn's counters after it, nil outside a turn.

func (StepEv) EventType

func (StepEv) EventType() EventType

func (StepEv) MarshalJSON

func (e StepEv) MarshalJSON() ([]byte, error)

func (StepEv) Validate

func (e StepEv) Validate() error

type StepsPager

type StepsPager interface {
	TurnsWithSteps(ctx context.Context, id, beforeTurnID string, limit int) (TurnsPage, error)
}

Service is what the protocol asks of the conversations: convo.Service, which imports this package, has exactly these methods (see its comments). NotFound and UnknownCursor on Server tell its errors apart. StepsPager is a Service that gives a page of turns with the steps of every turn in it (`…/turns?steps=all`): the agent backfills the cluster's copy from it, so a folded turn of a backfilled chat opens from the copy. A Service without it answers the plain page.

type SubFrame

type SubFrame struct {
	Ch           Channel  `json:"ch"`
	Epoch        string   `json:"epoch,omitempty"`
	AfterSeq     *int64   `json:"afterSeq,omitempty"`
	AfterEntryID string   `json:"afterEntryId,omitempty"`
	Opts         *SubOpts `json:"opts,omitempty"`
}

SubFrame subscribes to a channel. Epoch and AfterSeq replay the ring; AfterEntryID asks for what follows that entry when the ring cannot.

func (SubFrame) ClientFrameKind

func (SubFrame) ClientFrameKind() FrameKind

func (SubFrame) MarshalJSON

func (f SubFrame) MarshalJSON() ([]byte, error)

func (SubFrame) Validate

func (f SubFrame) Validate() error

type SubOpts

type SubOpts struct {
	Load *bool `json:"load,omitempty"`
}

SubOpts are a subscription's options; Load asks the machine channel for machine_load.

type SubagentStatus

type SubagentStatus string

SubagentStatus is where a subagent entry is.

const (
	SubagentRunning SubagentStatus = "running"
	SubagentDone    SubagentStatus = "done"
	SubagentFailed  SubagentStatus = "failed"
)

type Task

type Task struct {
	ID      string     `json:"id"`
	Subject string     `json:"subject"`
	Status  TaskStatus `json:"status"`
}

Task is one line of the plan an agent keeps while it works (Claude's tasks, Codex's plan): the id the agent gave it (a number, or the line's text), what it is, where it stands.

func (Task) Validate

func (t Task) Validate() error

type TaskStatus

type TaskStatus string

TaskStatus is where a task of the agent's list stands.

const (
	TaskPending    TaskStatus = "pending"
	TaskInProgress TaskStatus = "in_progress"
	TaskCompleted  TaskStatus = "completed"
	TaskBlocked    TaskStatus = "blocked"
)

func (TaskStatus) Known

func (s TaskStatus) Known() bool

Known reports whether s is one of TaskStatuses.

type Tasks

type Tasks []Task

Tasks is the answer of GET /api/v2/conversations/{id}/tasks: the agent's task list, in the order the tasks were made; empty for an agent that keeps none.

func (Tasks) Validate

func (t Tasks) Validate() error

type Terminal

type Terminal struct {
	ID        string `json:"id"`
	CreatedAt Ms     `json:"createdAt"`
}

Terminal is one of a conversation's own terminals: a shell in the conversation's folder, kept by the machine until it is closed. The id is a short lowercase token that carries no meaning to the page; the list is oldest first.

func (Terminal) Validate

func (t Terminal) Validate() error

type TerminalAside added in v0.16.15

type TerminalAside string

TerminalAside is a screen of the agent's terminal over its input box that Esc closes without changing anything.

const (
	AsideLogin  TerminalAside = "login"
	AsideModel  TerminalAside = "model"
	AsideEffort TerminalAside = "effort"
)

type TerminalFailure added in v0.16.5

type TerminalFailure struct {
	Kind        TerminalFailureKind `json:"kind"`
	At          Ms                  `json:"at"`
	Detail      string              `json:"detail"`
	Terminal    bool                `json:"terminal"`
	NeedsTarget bool                `json:"needsTarget"`
}

TerminalFailure is a provider failure which ended a turn and requires an explicit target choice.

func (TerminalFailure) Validate added in v0.16.5

func (f TerminalFailure) Validate() error

type TerminalFailureKind added in v0.16.5

type TerminalFailureKind string

TerminalFailureKind is a stable, provider-neutral terminal outcome.

const (
	FailureQuotaExhausted TerminalFailureKind = "quota_exhausted"
)

type TerminalSource

type TerminalSource interface {
	// Serve runs the terminal socket of the conversation's agent pane (terminal == "") or of one of its own terminals
	// until either side closes it. It checks what it was asked for before it upgrades the request: an error is answered
	// as a refusal, and nothing is written by then.
	Serve(w http.ResponseWriter, r *http.Request, conversation, terminal string) error
	List(ctx context.Context, conversation string) ([]Terminal, error)
	Create(ctx context.Context, conversation string) (Terminal, error)
	// Close ends an own terminal and its shell.
	Close(ctx context.Context, conversation, terminal string) error
}

TerminalSource is what the machine gives the pages that show a conversation's terminals: its agent's pane, and shells of its own. A source reports a conversation or a terminal it does not have as an error the Server's NotFound knows.

type TerminalStop

type TerminalStop struct {
	At     Ms             `json:"at"`
	By     TerminalStopBy `json:"by"`
	IdleMs int64          `json:"idleMs,omitempty"`
}

TerminalStop is when and why a conversation's terminal was stopped. IdleMs is how long it had stood idle when the runtime stopped it (By idle); absent for a stop the person asked for.

type TerminalStopBy

type TerminalStopBy string

TerminalStopBy is who stopped a terminal: the person (terminal.stop) or the runtime, for standing idle.

const (
	TerminalStopPerson TerminalStopBy = "person"
	TerminalStopIdle   TerminalStopBy = "idle"
)

type TerminalStopCmd

type TerminalStopCmd struct {
	OpID  string `json:"opId"`
	ID    string `json:"id"`
	Force *bool  `json:"force,omitempty"`
}

TerminalStopCmd ends the terminal of a conversation: its tmux session and everything that runs in it (the agent and what the agent started). The conversation and its history stay; the next message starts the agent again on its session. Force stops a working agent too.

func (TerminalStopCmd) Op

func (TerminalStopCmd) Op() Op

func (TerminalStopCmd) OpKey

func (c TerminalStopCmd) OpKey() string

func (TerminalStopCmd) Validate

func (c TerminalStopCmd) Validate() error

type Terminals

type Terminals []Terminal

Terminals is the answer of GET /api/v2/conversations/{id}/terminals.

func (Terminals) Validate

func (t Terminals) Validate() error

type TitleSource

type TitleSource string

TitleSource is who named a conversation.

const (
	TitleFromUser         TitleSource = "user"
	TitleFromAgent        TitleSource = "agent"
	TitleFromFirstMessage TitleSource = "first-message"
)

type ToolCall

type ToolCall struct {
	Description string `json:"description,omitempty"` // Claude's Bash `description`: what the command does, in words
	Command     string `json:"command,omitempty"`     // the whole command of a shell call, all its lines
	Offset      int64  `json:"offset,omitempty"`      // Read: the first line asked for (1-based), 0 from the top
	Limit       int64  `json:"limit,omitempty"`       // Read: how many lines were asked for, 0 the whole file
	DurationMs  *int64 `json:"durationMs,omitempty"`  // from the call to its result, once it has one
	Exit        *int64 `json:"exit,omitempty"`        // a shell call's exit code, when the agent told it
	Lines       int64  `json:"lines,omitempty"`       // how many lines the whole output has
	Tail        string `json:"tail,omitempty"`        // the last few non-empty lines of the whole output
}

ToolCall is what a tool step knows beyond its one-line summary, so the feed can say what is done in words: the agent's own description of a command, the whole command, the lines of a file it read, how long it ran, how it ended and the tail of its output (the event's output is cut to its first ToolOutputMax bytes).

type ToolOutput

type ToolOutput struct {
	Text      string         `json:"text"`
	Truncated *OutputTrimmed `json:"truncated"`
}

ToolOutput is a tool's output; past ToolOutputMax bytes it is cut and the rest is fetched on request.

type Transcript

type Transcript struct {
	Text string `json:"text"`
}

Transcript is the answer of POST /api/v2/voice: what was said, empty for silence.

func (Transcript) Validate

func (Transcript) Validate() error

type Turn

type Turn struct {
	ID            string       `json:"id"` // the id of the user entry that opened the turn
	Author        TurnAuthor   `json:"author"`
	StartedAt     Ms           `json:"startedAt"`
	EndedAt       *Ms          `json:"endedAt"`
	DurationMs    *int64       `json:"durationMs"`
	ToolCount     int          `json:"toolCount"`
	StepCount     int          `json:"stepCount"`
	Status        TurnStatus   `json:"status"`
	Failure       *TurnFailure `json:"failure"`
	AnswerEntryID *string      `json:"answerEntryId"` // the last reply, shown in the folded turn
	Files         []TurnFile   `json:"files"`
	// Outputs are the things the turn made that the person opens: a published document, a design, a document of the
	// repository, a merge request, a stand. Absent when there are none.
	Outputs []TurnOutput `json:"outputs,omitempty"`
	// Pictures are the paths of the pictures the turn drew (harnessly's generate_images, Codex's image tool), oldest
	// first, at most TurnPicturesMax: the page shows them under the answer, where the folded work would hide them
	// Absent when there are none.
	Pictures []string `json:"pictures,omitempty"`
}

Turn is one turn: the user entry that opened it and the steps up to its end.

func (Turn) Validate

func (t Turn) Validate() error

type TurnAuthor

type TurnAuthor struct {
	Provider Provider `json:"provider"`
	Role     *string  `json:"role"`
}

TurnAuthor is who answered in a turn.

type TurnCounts

type TurnCounts struct {
	ToolCount int `json:"toolCount"`
	StepCount int `json:"stepCount"`
}

TurnCounts are a turn's counters; they ride inside step events.

type TurnFailedEv

type TurnFailedEv struct {
	Turn Turn `json:"turn"`
}

TurnFailedEv: a turn failed; Turn.Failure says why.

func (TurnFailedEv) EventType

func (TurnFailedEv) EventType() EventType

func (TurnFailedEv) MarshalJSON

func (e TurnFailedEv) MarshalJSON() ([]byte, error)

func (TurnFailedEv) Validate

func (e TurnFailedEv) Validate() error

type TurnFailure

type TurnFailure struct {
	Code    TurnFailureCode `json:"code"`
	Detail  *string         `json:"detail"`
	RetryAt *Ms             `json:"retryAt"`
}

TurnFailure is why a turn failed; Detail is the agent's raw text (data, not a translation).

type TurnFailureCode

type TurnFailureCode string

TurnFailureCode is why a turn failed.

const (
	TurnFailedApiError        TurnFailureCode = "api-error"
	TurnFailedRateLimit       TurnFailureCode = "rate-limit"
	TurnFailedContextOverflow TurnFailureCode = "context-overflow"
	TurnFailedAgentExited     TurnFailureCode = "agent-exited"
	TurnFailedUnknown         TurnFailureCode = "unknown"
)

func FailureCode

func FailureCode(t Turn) TurnFailureCode

FailureCode is the code of t's failure, or "" when it did not fail.

type TurnFile

type TurnFile struct {
	Path string `json:"path"`
	Op   FileOp `json:"op"`
}

TurnFile is a file a turn touched.

type TurnFinishedEv

type TurnFinishedEv struct {
	Turn Turn `json:"turn"`
}

TurnFinishedEv: a turn ended, done or interrupted.

func (TurnFinishedEv) EventType

func (TurnFinishedEv) EventType() EventType

func (TurnFinishedEv) MarshalJSON

func (e TurnFinishedEv) MarshalJSON() ([]byte, error)

func (TurnFinishedEv) Validate

func (e TurnFinishedEv) Validate() error

type TurnOutput

type TurnOutput struct {
	Kind  OutputKind `json:"kind"`
	Op    OutputOp   `json:"op"`
	Title string     `json:"title"`
	Ref   string     `json:"ref"`
	// A delivered file (kind delivery): Ref is its path; its name, type, size in bytes and sha256 as the platform read them.
	Name   string `json:"name,omitempty"`
	Mime   string `json:"mime,omitempty"`
	Size   int64  `json:"size,omitempty"`
	SHA256 string `json:"sha256,omitempty"`
}

TurnOutput is a thing a turn made: what it is, whether it is new, what it is called and what opens it — a link (an artifact, a merge request, a stand), a design's id, or a file's path (a document).

type TurnStartedEv

type TurnStartedEv struct {
	Turn Turn `json:"turn"`
}

TurnStartedEv: a turn opened.

func (TurnStartedEv) EventType

func (TurnStartedEv) EventType() EventType

func (TurnStartedEv) MarshalJSON

func (e TurnStartedEv) MarshalJSON() ([]byte, error)

func (TurnStartedEv) Validate

func (e TurnStartedEv) Validate() error

type TurnStatus

type TurnStatus string

TurnStatus is where a turn is.

const (
	TurnLive        TurnStatus = "live"
	TurnDone        TurnStatus = "done"
	TurnInterrupted TurnStatus = "interrupted"
	TurnFailed      TurnStatus = "failed"
)

type TurnSummary

type TurnSummary struct {
	ID         string     `json:"id"`
	Status     TurnStatus `json:"status"`
	StartedAt  Ms         `json:"startedAt"`
	EndedAt    *Ms        `json:"endedAt"`
	DurationMs *int64     `json:"durationMs"`
	ToolCount  int        `json:"toolCount"`
	Snippet    string     `json:"snippet"` // at most SnippetMax characters
	// Failure is why a failed turn failed, so a notification can tell a limit from an error; absent otherwise.
	// Not filled yet: a page built before this field rejects a record with a field it does not know, and open tabs keep
	// their build for days (the update banner asks, it does not reload). Pages already read it; a later release fills it
	// (FailureCode) once those builds are gone.
	Failure TurnFailureCode `json:"failure,omitempty"`
}

TurnSummary is a turn as the sidebar row and the notifications need it.

func (TurnSummary) Validate

func (t TurnSummary) Validate() error

type TurnsPage

type TurnsPage struct {
	Turns        []Turn  `json:"turns"`
	Entries      []Entry `json:"entries"`
	BeforeTurnID *string `json:"beforeTurnId"`
}

TurnsPage is the answer of GET /api/v2/conversations/{id}/turns?before=&limit=: turns oldest first and their answer entries.

func TurnsPageFor

func TurnsPageFor(p TurnsPage, caps Caps) TurnsPage

TurnsPageFor is p as a page with caps reads it.

func (TurnsPage) Validate

func (p TurnsPage) Validate() error

type UnsubFrame

type UnsubFrame struct {
	Ch Channel `json:"ch"`
}

UnsubFrame ends a subscription.

func (UnsubFrame) ClientFrameKind

func (UnsubFrame) ClientFrameKind() FrameKind

func (UnsubFrame) MarshalJSON

func (f UnsubFrame) MarshalJSON() ([]byte, error)

func (UnsubFrame) Validate

func (f UnsubFrame) Validate() error

type Uploads

type Uploads struct {
	Dir    string
	Limits Limits
	// contains filtered or unexported fields
}

Uploads keeps the files the page uploads before it sends the message that carries them: <dir>/<id> and its AttachmentRef in <dir>/<id>.json.

func (*Uploads) Get

func (u *Uploads) Get(id string) (ref AttachmentRef, path string, ok bool)

Get is an upload by its id and the file that holds it.

func (*Uploads) Put

func (u *Uploads) Put(name, contentType string, size int64, body io.Reader) (AttachmentRef, RefuseCode)

Put stores one upload; size is the declared length, -1 when unknown.

type VoiceSettings added in v0.16.86

type VoiceSettings struct {
	Engine string      `json:"engine"`
	Words  []VoiceWord `json:"words"`
}

VoiceSettings are the dictation's: which model recognizes and the person's own words.

type VoiceWord added in v0.16.86

type VoiceWord struct {
	Word  string   `json:"word"`
	Heard []string `json:"heard"`
}

VoiceWord is a word the recognizer gets wrong: how it is written and, optionally, how it is heard.

type Wait

type Wait struct {
	SlowAt     Ms `json:"slowAt"`
	DeadlineAt Ms `json:"deadlineAt"`
}

Wait is the term of a state that waits on the runtime: past SlowAt the page shows "дольше обычного", and by DeadlineAt the runtime has moved the state on (failed, launch-failed, back to open) — it never waits longer.

type WelcomeFrame

type WelcomeFrame struct {
	Proto      int       `json:"proto"`
	Epoch      string    `json:"epoch"` // new on every start of the runtime
	ServerTime Ms        `json:"serverTime"`
	Machine    Machine   `json:"machine"`
	Features   []Feature `json:"features"`
	Limits     Limits    `json:"limits"`
}

WelcomeFrame answers hello.

func (WelcomeFrame) MarshalJSON

func (f WelcomeFrame) MarshalJSON() ([]byte, error)

func (WelcomeFrame) ServerFrameKind

func (WelcomeFrame) ServerFrameKind() FrameKind

func (WelcomeFrame) Validate

func (f WelcomeFrame) Validate() error

type WorkFeed

type WorkFeed interface {
	WorkFrames() [][]byte
	WatchWork(fn func(frame []byte)) (stop func())
}

WorkFeed is the work of the chats (internal/chatwork) as frames of the replica socket: all of it, and each change.

type WorkflowAgent

type WorkflowAgent struct {
	ID        string           `json:"id"`
	Label     string           `json:"label"`
	Status    BackgroundStatus `json:"status"`
	StartedAt *Ms              `json:"startedAt"`
	EndedAt   *Ms              `json:"endedAt"`
	Model     *string          `json:"model"`
	Last      *string          `json:"last"`
	Result    *string          `json:"result"`
}

WorkflowAgent is an agent a workflow started: its label in the script, the model it runs on, where it is, its last step and the first words of what it returned. Its id names its transcript, so it opens in the pane as a subagent.

type WorkflowPhase

type WorkflowPhase struct {
	Title  string          `json:"title"`
	Agents []WorkflowAgent `json:"agents"`
}

WorkflowPhase is a stage of a workflow; a phase no agent has started in yet has none.

type WorkflowRun

type WorkflowRun struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	ToolUseID   *string         `json:"toolUseId"`
	Phases      []WorkflowPhase `json:"phases"`
}

WorkflowRun is a dynamic workflow as its files tell it: the name and description of its script, the Workflow call that started it (its tool entry in the feed) and its phases in the script's order, each with the agents started in it so far.

func (WorkflowRun) Validate

func (w WorkflowRun) Validate() error

Directories

Path Synopsis
Package wirefake is a runtime without agents: a convo.Service and a wire.MachineSource that serve the shared fixtures of internal/wire/testdata and play a scripted agent on them.
Package wirefake is a runtime without agents: a convo.Service and a wire.MachineSource that serve the shared fixtures of internal/wire/testdata and play a scripted agent on them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL