Mod (function hooks): reports this session's live state (turn start and end, tool calls by name and input hash, context fill, rate limits, cost) to a local…

A mod (a plugin of function hooks) that reports a Claude Code session's live state to a local swarmery daemon, so the dashboard sees a session's status, context fill, rate limits and cost the moment they change instead of waiting for the transcript tail.
By default it is a sensor only. It never blocks, rewrites or answers anything: every hook passes its event on unchanged, and a failure on the link is logged and swallowed. Only the opt-in approvals option ever answers an event, with a decision a person made in the dashboard (see Approvals), and the opt-in claimConflicts option, which asks or refuses a write to a file another live session holds (see Holding a conflicting write).
Version 0.2 adds an opt-in command channel (control, off by default): the dashboard's Stop and Send-prompt buttons reach the session through the daemon. See Control.
Version 0.3 adds an opt-in turn forecast (forecast, off by default): one small model call per turn predicts what the turn will touch, the turn's own tool calls make the actual, and the daemon scores how surprised the forecast was. See Forecast.
Version 0.4 adds opt-in approvals (approvals, off by default): a permission ask goes to the swarmery approvals queue first, and an AskUserQuestion can be answered from the dashboard. The PermissionRequest hook shim and the native dialog stay as the fallback. See Approvals.
Version 0.5 adds opt-in swarm coordination (swarm, off by default): messages between sessions are reported, the files each session starts editing are claimed in a registry its sessions share, a line beneath the answer flags a file another live session is editing, and the dashboard can message a session. See Swarm.
Version 0.6 adds an opt-in plan band (planBand, off by default): the session's running plan phase above the prompt, /phase for its checklist, a card for interview-style questions, and a line beneath an answer that drifted off the phase. See Plan band.
Version 0.7 adds opt-in conflict holding (claimConflicts, off by default, needs swarm): a write to a file another live session holds is put to the native dialog where a person can answer, and refused where nobody can. See Holding a conflicting write.
Nothing is installed by default. Install it from the swarmery marketplace:
/plugin install swarmery-link@swarmery
Or enable it for one project, in that project's .claude/settings.json:
{ "enabledPlugins": { "swarmery-link@swarmery": true } }
or try it for one session from a checkout:
claude --plugin-dir plugins/swarmery-link
It also needs the daemon's link token (below). Without it the mod does nothing.
| Hook | Sends to POST /api/link/events |
|---|---|
session.start | reads the token; session.start with { surface, isInteractive } |
turn.start | turn.start |
tool.call | tool.call with { tool, inputHash, agentId? }, then lets the call run |
session.measure | session.measure: context, rateLimits, cost, changed |
turn.complete (main loop only) | turn.complete with { durationMs, stopReason }, plus a session.measure snapshot from $.session.usage() |
session.end | session.end with { reason }, and a last flush that waits at most 1.2 s, even behind a request already in flight |
/clear starts a new session in the same process. The engine ends the old one (session.end with reason: "clear") and goes on under a new session id without a session.start. The mod sends that session.end under the old id, queues nothing more, and at the next turn.start reads the id again: if it moved, it sends a session.start for the new id (the same { surface, isInteractive } the real one carried) and reports everything after under it. A session.measure between the clear and that turn is not reported; the turn's turn.complete sends a fresh snapshot. A resume inside the same process (reason: "resume") is followed the same way. Any other session.end reason is final.tool.call carries the tool's name and the first 16 hex digits of a SHA-256 over the input's canonical JSON (FNV-1a where SHA-256 is unavailable). The input itself is already in the transcript.(session, kind, at) dedup never swallows one. A resend carries the same at.rateLimits or a missing context.percent keeps the daemon's last value.The wire format is the daemon's link protocol: tools/swarmery/docs/mods-link-protocol.md.
As claude plugin validate --strict --json plugins/swarmery-link reports it:
./register.ts hooks: session.start, turn.start, tool.call, tool.check, tool.call{tool=AskUserQuestion}, classic.SessionStart, classic.UserPromptSubmit, classic.PostToolUse, classic.PostToolUseFailure, session.measure, turn.complete, session.end, session.send, session.receive, ui.render{component=AbovePrompt}, ui.render{component=Pane, requestId=?}, ui.render{component=AskUserQuestion}, command.run{command=phase}
./register.ts gating hook with .catch: tool.call
./register.ts gating hook with .catch: tool.check
./register.ts gating hook with .catch: tool.call{tool=AskUserQuestion}
./register.ts gating hook with .catch: classic.SessionStart
./register.ts gating hook with .catch: classic.UserPromptSubmit
./register.ts gating hook with .catch: classic.PostToolUse
./register.ts gating hook with .catch: classic.PostToolUseFailure
./register.ts gating hook with .catch: session.send
./register.ts gating hook with .catch: session.receive
./register.ts gating hook with .catch: command.run{command=phase}
./register.ts calls: $.clock.after (via arm, beginForecast, bounded, pause, send, startControl, within), $.clock.every (via startPlanTimer), $.clock.now (via askSwarmery, claimFile, heldElsewhere, newRun, poll, pollDecision, push), $.command.register (via registerPlanCommand), $.env.get (via readToken), $.fs.read (via readToken), $.http.fetch (via cancelRequest, fetchCommand, planFetch, post, request, sendAck), $.model.classify (via checkDrift), $.model.complete (via runForecast), $.prompt.submit (via submitPrompt), $.session.cwd, $.session.id, $.session.send (via sendToSession), $.session.usage, $.store.delete (via releaseClaims), $.store.get (via readOthers), $.store.keys (via readOthers), $.store.set (via claimFile), $.turn.abort (via abortTurn), $.ui.ask (via pressNext, pressTick), $.ui.copy (via pressOpen), $.ui.invalidate (via setView), $.ui.log (via log), $.ui.notice (via showNotice), $.ui.open (via runPlanCommand), $.ui.resolve (via drawBand, drawInterview, drawPane), $.ui.status (via showStatu… [+26 chars]
./register.ts env writes: nothing
./register.ts env reads: HOME
The unmatched tool.call, session.send and session.receive are listed as gating hooks because of where they sit, not what they do: each always calls next(e) with the event unchanged, and its .catch does the same (replay-safe: a send is never made twice). With forecast or planBand on tool.call waits for the call's result to note how a main-loop call ended, and returns that result unchanged. command.run{command=phase} answers /phase itself; its .catch answers with one line if it fails.
tool.check is registered with approvals or claimConflicts on (one hook serves both: the conflict verdict first, then the approvals channel), and tool.call{tool=AskUserQuestion} with approvals on; validate lists them whatever the options say (it reads the source, not the options). Their .catch hands the event on (next(e)), never refuses. The four classic.* hooks are registered with claimConflicts: ask alone: each records the event's permission_mode and hands it on unchanged (validate notes that where an organization manages Claude Code they do not run in a plugin a person installs; the mode then stays unknown and a held write is asked).
$.turn.abort and $.prompt.submit are the command channel's. Validate lists them whatever the options say; with control off they are never called and no request goes to the command endpoints. $.model.complete is the forecast's; with forecast off it is never called. $.ui.status and $.ui.notice are the approvals channel's; with approvals off they are never called. $.store.* and $.session.send are the swarm's; with swarm off they are never called, and session.send / session.receive are not registered at all (validate lists every on it reads, conditional or not). The ui.render and command.run hooks, $.clock.every, $.command.register, $.model.classify and $.ui.ask, $.ui.copy, $.ui.invalidate, $.ui.open, $.ui.resolve, $.ui.toast are the plan band's: with planBand off none of those hooks is registered and none of those calls is made.
~/.swarmery/link-token, mode 0600, minted by the daemon on start (or by swarmery link token). The mod reads ${HOME}/.swarmery/link-token on every session.start and sends it as Authorization: Bearer <token>.
swarmery-link: no token, sensor off, and no request for the rest of the session.link disabled: the link is off for the session.| Option | Default | Effect |
|---|---|---|
daemonUrl | http://127.0.0.1:7777 | the daemon's origin. Only http:// on 127.0.0.1, [::1] or localhost (any port, path ignored) is accepted; anything else is refused with one log line and the default is used, so the token never leaves the machine |
control | false | the command channel: the dashboard can stop the running turn and send prompts (Control) |
forecast | false | the turn forecast: one haiku call per user turn, a turn.forecast and a turn.actual per forecast turn (Forecast) |
approvals | false | routes each permission ask to the Swarmery approvals queue first, ahead of the dialog or auto mode's classifier; the shim/dialog takes over if the daemon is down or does not decide in time. An AskUserQuestion can be answered from the dashboard (Approvals) |
swarm | false | swarm coordination: message events, the file-claims registry, the conflict line, and the dashboard's message command with control on (Swarm) |
claimConflicts | off | with swarm on, a write to a file another live session holds: off only the conflict line; ask the native dialog asks, naming the other session, in default/acceptEdits/plan mode, and the write is refused in auto/dontAsk/bypassPermissions, where no person would see the ask; deny refused in every mode. Bash is never checked (Holding a conflicting write) |
planBand | false | the plan band, /phase, the interview card and the drift line (Plan band) |
Set them in the plugin's config menu (/plugin → swarmery-link → configure), which writes your user settings, or under pluginConfigs in your user settings, ~/.claude/settings.json:
{ "pluginConfigs": { "swarmery-link@swarmery": { "options": { "control": true } } } }
Claude Code reads plugin options from user settings (and from the --settings flag) only. A pluginConfigs block in a project's .claude/settings.json or .claude/settings.local.json is ignored without a warning, so an option set there stays off. enabledPlugins is different: it still goes in the project's settings. Each "Enable it" section below follows that split.
With control on, the dashboard's Stop and Send prompt buttons (and the bulk "continue phase" action) reach this session.
With the plugin enabled (see Opt-in), set the option in your user settings, ~/.claude/settings.json (a project's settings are ignored for options, see Options):
{ "pluginConfigs": { "swarmery-link@swarmery": { "options": { "control": true } } } }
or flip Control from the dashboard in the plugin's config menu (/plugin → swarmery-link → configure), which reloads the mod with the new value. Loaded through --plugin-dir, the key is swarmery-link (or swarmery-link@inline) instead of swarmery-link@swarmery.
On session.start, once the token is read, the mod starts one background loop for the session. It never runs inside a hook, and no hook waits on it.
GET /api/link/commands?session=<session id>&wait=25 with the bearer token. The daemon holds the request up to 25 s; the mod gives up on it at 28 s (raced against a $.clock timer, since $.http.fetch takes no timeout).200 {id, kind, payload}: run the command, then POST /api/link/commands/{id}/ack with { result: "done" | "failed", message? }, then poll again at once.204: poll again (no sooner than 1 s after the last poll started).401: re-read the token file once and retry 1.1 s later; a second 401 stops the loop. 503 (link disabled) stops the loop and the sensor.session.end stops the loop: the pending wait is cancelled and the reply of a poll still open is never acted on. After a /clear or an in-process resume (reason: "clear" or "resume") a new loop starts at the next turn.start, polling under the session id the process now runs as; any other reason stops it for good.| Command | What the mod does | Ack |
|---|---|---|
stop | $.turn.abort({ turnId }) on the main loop's running turn (the id its turn.start carried) | done; done + no turn running when the session is idle; failed + the error when the abort throws |
prompt { text, asUser? } | $.prompt.submit({ text }), or { text, asUser: true } when the payload says asUser: true (default false: the model reads it framed as this plugin's message) | done once its turn starts (done + queued if it has not started within 10 s); failed + turn in progress while a turn runs; failed + a short reason on any other refusal |
message { to, text } | with swarm on, $.session.send({ to: { sessionId: to }, text }), whether or not a turn runs (Swarm) | done once queued at the recipient; failed + undeliverable: <reason> when not; failed + swarm option is off with swarm off |
| anything else | nothing | failed + unknown command kind: … (or prompt without text) |
turn in progress is retried by the daemon, after the session's next turn.complete, up to 3 attempts. That one failure is not remembered, so the re-delivered prompt runs.~/.swarmery/link-token, mode 0600). Without the file there is no loop.daemonUrl origin, which is refused unless it is http:// on 127.0.0.1, [::1] or localhost.409 session has no link. A session without the mod, or with control off, cannot be stopped or prompted from the dashboard.POST /api/sessions/{id}/link/stop|prompt) accepts local-origin requests only.With forecast on, the mod asks a small model before each turn what the turn will do, then records what it did. The daemon compares the two and scores the surprise; the dashboard's Insights shows how well the forecasts are calibrated. It is advisory: nothing is blocked or changed.
With the plugin enabled, in your user settings, ~/.claude/settings.json (see Options):
{ "pluginConfigs": { "swarmery-link@swarmery": { "options": { "forecast": true } } } }
or flip Turn forecast in the plugin's config menu. It needs the token file like the rest of the link: without it no model call is made.
One $.model.complete to haiku per turn the person typed, with maxTokens: 300 and a 20 s time limit. The request is a fixed two-line instruction, at most 2000 characters of the person's text, and the files the last 3 turns edited: about 150–700 input tokens and 30–100 output tokens per forecast. The tokens each call cost ride along as forecastTokens.
Skipped, with no model call: turns without the person's text (a continuation, a slash command, a task notification), a turn that starts while the last forecast is still running, and every turn while the link has no token. The call is started from the turn's hook and never waited on, so a turn never waits for the model.
Two events per forecast turn, through the same queue as the sensor:
| Event | Payload |
|---|---|
turn.forecast | { runId, turnSeq, files, testsPass, steps, confidence, model, forecastTokens }: the model's claims, each null where it made none or its reply was unreadable |
turn.actual | { runId, turnSeq, files, testsRan, testsPass, steps }, at the turn's end |
files entry that is not one path-like token (spaces, quotes, no / or .) is dropped, so a model that echoes the prompt cannot leak it. Paths are made relative to the session's cwd where they are under it; at most 50 entries of at most 300 characters.turnSeq counts the main loop's turns from 1 within a runId. A new run starts at session.start (a --resume too, which keeps the session id), at a session.end with reason clear, and at the first turn after an in-process resume. Its id is the reset's time in ms and 6 random base36 characters (crypto.getRandomValues), the time alone without a random source. The daemon keys a turn on (session, runId, turnSeq), so a resumed session's turn 1 never overwrites an older turn 1.files that Edit, Write, MultiEdit or NotebookEdit wrote without error, steps the number of calls, testsRan when a Bash command matched test, vitest, jest, go test, pytest, cargo test or npm (run) test. testsPass is the last such run's outcome, read from the call's result (an error result, as a non-zero exit is, reads as failing); it stays null for a run in the background and when no test ran./clear, a resume, a new session.start) is dropped: its session and run are gone.With approvals on, a permission the engine would ask the person about goes to the swarmery approvals queue first, and the dashboard decides it. The PermissionRequest hook shim and the native dialog stay as the fallback: the mod first, the shim when the mod cannot decide.
With the plugin enabled, in your user settings, ~/.claude/settings.json (see Options):
{ "pluginConfigs": { "swarmery-link@swarmery": { "options": { "approvals": true } } } }
or flip Approvals in Swarmery in the plugin's config menu. It needs the token file like the rest of the link. With approvals off no tool.check hook and no AskUserQuestion hook is registered, and no request goes to the permission endpoint.
The hook sits on tool.check, which fires after the tool.call and PreToolUse hooks and before the mode settles an ask.
next(e)): the settings rules, the mode, the tool's own check, a PreToolUse decision. An allow or a deny is returned untouched; only an ask goes to Swarmery.$.tool.check query (no tool_use_id) is never sent, and neither is a tool that needs the person (AskUserQuestion, ExitPlanMode: a hook's allow cannot dismiss their dialog) or a call the organization's ceiling keeps at ask or below.POST /api/link/permission with the bearer token and { sessionId, cwd, toolName, toolInput, toolUseId, agentId? }, bounded at 5 s on a $.clock timer.| Reply | What the mod does |
|---|---|
200 {"decision":"allow"} (a person, or a rule: "via":"rule") | allow, reason approved in Swarmery |
200 {"decision":"deny","message":m} | deny, reason m (or denied in Swarmery) |
200 {"decision":"local"} (a production deploy) | the engine's verdict, and the dialog shows production deploy: confirm it here, not in Swarmery |
200 {"decision":"pass"}, 204 (an excluded project) | the engine's verdict |
202 {"id","status":"pending","expiresAt"} | waits for the dashboard (below) |
401 | re-reads the token file once and retries 1.1 s later; a second 401 leaves the engine's verdict |
no answer in 5 s, 429, 5xx, anything else | the engine's verdict |
GET /api/link/permission/{id}?session=<id>&wait=25; the daemon holds each poll up to 25 s and the mod gives up on one at 28 s. A 204 polls again (no sooner than 1 s after the last one started), a 200 decides as above, a 404 (the request is gone) leaves the engine's verdict. The wait ends with the engine's verdict when the person interrupts the call (next.signal), at expiresAt plus 5 s, or after 3 failed polls in a row. Only the interrupt gives the request up: the mod sends DELETE /api/link/permission/{id}?session=<id> fire-and-forget (bounded at 2 s, never awaited), so a later dashboard decision cannot land on a call no hook reads. On every other end the request stays pending, and the shim the engine fires next attaches to it. The time spent inside a long poll does not count against the hook's 10 s budget (tools/swarmery/docs/mods-format.md, M3), so the mod can wait out the daemon's whole approval window. While it waits, the status line reads waiting for Swarmery approval…; it is cleared when the wait ends, however it ends.It fails open to the shim and the dialog. Every failure returns the engine's own verdict, which for an ask means the mode's decider runs as if the mod were not there: the native dialog in the terminal, the PermissionRequest shim where it is installed. The mod never answers ask of its own and never refuses a call because the daemon failed. Its .catch hands the event on.
A production deploy stays local. When the daemon marks a call as a production deploy (local), the mod leaves it to the terminal's dialog and says so there; it is never approved from the dashboard.
An
hooks/register.ts 1195 lines1// swarmery-link 0.2: a sensor, plus an opt-in command channel. It reports this
2// session's live state to a local swarmery daemon over POST /api/link/events
3// (tools/swarmery/docs/mods-link-protocol.md) and changes nothing: every hook
4// passes its event on, a failure is logged and swallowed, and with no token
5// file the whole mod stays silent for the session and makes no request.
6//
7// With `control` on, one background loop long-polls GET /api/link/commands
8// and runs what the dashboard queued for this session: `stop` aborts the
9// running turn, `prompt` submits a prompt once the session is idle. Commands
10// run only from that loop, never from inside a hook. With `control` off none
11// of it is created and no request goes to the command endpoints.
12//
13// With `forecast` on, each main-loop turn that starts with the person's text
14// asks a small model, without waiting on it, what the turn will touch; the
15// turn's own tool calls make the actual. Both go to the daemon as
16// `turn.forecast` and `turn.actual` (paths and numbers only). With `forecast`
17// off no model call is made and neither event is sent.
18//
19// With `approvals` on, a permission `ask` the engine reached for a real call
20// goes to the daemon's approvals queue first (tool.check), and an
21// AskUserQuestion is put to the dashboard (tool.call); every failure leaves
22// the engine's verdict or the question's dialog (./approvals.ts). With
23// `approvals` off neither hook is registered and no request goes to the
24// permission endpoint.
25//
26// With `swarm` on, messages this conversation sends to or receives from other
27// sessions go to the daemon as `session.send` / `session.receive`, each file
28// the session starts editing is claimed in a registry shared through
29// `$.store` (a `claim`, and a `conflict` when another live session holds the
30// same path, shown as a line beneath the answer), claims are released at each
31// turn's end, and with `control` on too the dashboard's `message` command is
32// sent through `$.session.send`. With `swarm` off none of it runs and the
33// send/receive hooks are not registered. With `claimConflicts` set (`ask` or
34// `deny`, `swarm` on), a tool.check beneath the approvals channel's asks or
35// refuses a write whose path another live session holds (`ask` turns into a
36// refusal in a permission mode where no person sees the ask, read off the
37// classic events), and the edit is claimed after the call instead of ahead of it.
38//
39// With `planBand` on, the session's running plan phase is drawn in a band
40// above the prompt from a cache the daemon fills (GET /api/link/plan), `/phase`
41// shows its checklist, an interview-style AskUserQuestion gets a card above
42// the dialog, and a main-loop turn that edited files while a phase runs is
43// classified once; an `off-phase` turn gets a line beneath its answer. With
44// `planBand` off none of those hooks, the command, the timer or the
45// classification exists, and no plan request is made.
46//
47// `$` is handed only to top-level function declarations, as the engine
48// requires: the ones of this file, ./approvals.ts's, ./swarm.ts's, and the
49// band's in ./plan.ts, ./drift.ts and ./ask-render.ts. ./lib/* is pure (data
50// in, data out).
51
52import type { EngineInterface, PromptSubmitArgs, Register, SessionSendInput, SessionSendResult, Timer } from 'claude-code'
53import { type Gate, answerFromSwarmery, checkWithSwarmery } from './approvals'
54import { drawInterview } from './ask-render'
55import { checkDrift } from './drift'
56import { interviewsOf } from './lib/interview'
57import { PLAN_PANE_ID, editedPath, isEditTool, noteEdit } from './lib/plan'
58import {
59 type Planner,
60 drawBand,
61 drawPane,
62 newPlanner,
63 refreshPlan,
64 registerPlanCommand,
65 runPlanCommand,
66 setView,
67 startPlanTimer,
68 stopPlanTimer,
69} from './plan'
70import {
71 AUTH_RETRY_MS,
72 DEFAULT_DAEMON_URL,
73 END_FLUSH_TIMEOUT_MS,
74 FLUSH_EVERY_MS,
75 REQUEST_TIMEOUT_MS,
76 daemonEndpoint,
77 describeFailure,
78 linkRequest,
79 outcome,
80 parseToken,
81} from './lib/client'
82import {
83 type Ack,
84 type Command,
85 type Executed,
86 POLL_TIMEOUT_MS,
87 PROMPT_START_TIMEOUT_MS,
88 ackBody,
89 ackUrl,
90 commandsUrl,
91 decide,
92 done,
93 dropAck,
94 failed,
95 nextPollDelay,
96 parseCommand,
97 pollOutcome,
98 pollRequest,
99 SWARM_OFF,
100 remember,
101 shortError,
102 submitFailure,
103 undeliverable,
104} from './lib/control'
105import {
106 FORECAST_MAX_TOKENS,
107 FORECAST_MODEL,
108 FORECAST_TIMEOUT_MS,
109 type ForecastState,
110 INITIAL_FORECAST,
111 NO_CLAIMS,
112 RUN_ID_RANDOM,
113 type ToolOutcome,
114 closeForecast,
115 endTurn,
116 forecastPayload,
117 forecastRequest,
118 noteToolCall,
119 parseForecast,
120 resetForecast,
121 runIdOf,
122 startTurn,
123 usageTokens,
124} from './lib/forecast'
125import { inputHash, toolInput } from './lib/hash'
126import { type LinkEvent, type LinkKind, type Stamps, drop, enqueue, stamp, takeBatch } from './lib/queue'
127import {
128 type ClaimConflicts,
129 type ConflictVerdict,
130 EMPTY_TURN,
131 type ModeBook,
132 type PendingSend,
133 type SwarmTurn,
134 claimConflictsOf,
135 claimPath,
136 conflictLines,
137 conflictVerdict,
138 isAmbiguousSend,
139 modeOf,
140 noteMode,
141 pendingFor,
142 receiveLine,
143 receivePayload,
144 releasePayload,
145 sendPayload,
146 withBeneath,
147} from './lib/swarm'
148import { measurePayload } from './lib/usage'
149import { signedFetch } from './signed'
150import { claimFile, heldElsewhere, releaseClaims, sendToSession } from './swarm'
151
152const NAME = 'swarmery-link'
153
154/** Options reserved for later releases: each logs once when switched on, and hooks nothing else. */
155const RESERVED: readonly string[] = []
156
157/** A dashboard message's `$.session.send` resolves once queued at the recipient; past this it is reported undeliverable. */
158const MESSAGE_TIMEOUT_MS = 10_000
159
160type Reply = { readonly status?: number; readonly error?: unknown }
161
162/** The link's state for one load of the module (a reload starts it over). */
163type Link = {
164 readonly url: string
165 token: string | undefined
166 sessionId: string
167 cwd: string
168 /** The real session.start's `{ surface, isInteractive }`, sent again for the session a `/clear` starts. */
169 start: Readonly<Record<string, unknown>> | undefined
170 /**
171 * A `/clear` ended the session and the process goes on under a new id with
172 * no session.start: nothing is queued until the next turn.start re-reads it.
173 */
174 isClearing: boolean
175 /** Off for the rest of this load: 503, or a 401 that survived a re-read. */
176 isOff: boolean
177 /** The last request got no answer or a 5xx: turn boundaries leave sending to the timer until one succeeds. */
178 isFailing: boolean
179 /** A 401 was answered with a token re-read; the one retry is pending. */
180 isAuthWait: boolean
181 hasRetriedAuth: boolean
182 queue: readonly LinkEvent[]
183 stamps: Stamps
184 timer: Timer | undefined
185 flushing: Promise<void> | undefined
186 readonly logged: Set<string>
187}
188
189const isActive = (link: Link): boolean => link.token !== undefined && !link.isOff && link.sessionId !== ''
190
191function log($: EngineInterface, text: string, toDebug = false): void {
192 try {
193 $.ui.log(`${NAME}: ${text}`, toDebug ? { to: 'debug' } : undefined)
194 } catch {
195 // a log line is a courtesy
196 }
197}
198
199/** Logs `text` to the transcript the first time `key` is seen, to the debug log after. */
200function logOnce($: EngineInterface, link: Link, key: string, text: string): void {
201 log($, text, link.logged.has(key))
202 link.logged.add(key)
203}
204
205/** The daemon's token (M7: `~` is not expanded, so HOME is read and spelled out). */
206async function readToken($: EngineInterface): Promise<string | undefined> {
207 try {
208 const home = await $.env.get('HOME')
209 return parseToken(await $.fs.read(`${home}/.swarmery/link-token`))
210 } catch {
211 return undefined
212 }
213}
214
215function turnOff($: EngineInterface, link: Link, why: string): void {
216 link.isOff = true
217 link.queue = []
218 link.timer?.cancel()
219 link.timer = undefined
220 log($, `link off for this session: ${why}`)
221}
222
223/** `pending`, or `'timeout'` once `ms` pass on `$.clock`, whichever comes first. */
224async function within<T>($: EngineInterface, pending: Promise<T>, ms: number): Promise<T | 'timeout'> {
225 let guard: Timer | undefined
226 const timeout = new Promise<'timeout'>(resolve => {
227 try {
228 guard = $.clock.after(ms, () => resolve('timeout'))
229 } catch {
230 // no timer: the pending work alone decides
231 }
232 })
233 try {
234 return await Promise.race([pending, timeout])
235 } finally {
236 guard?.cancel()
237 }
238}
239
240/** One POST of `body`, raced against a `$.clock` timer: HttpInit has no timeout or signal. */
241async function post($: EngineInterface, link: Link, body: string, timeoutMs: number): Promise<Reply> {
242 const request = signedFetch($, link.token ?? '', link.url, linkRequest(body)).then(
243 (r): Reply => ({ status: r.status }),
244 (error: unknown): Reply => ({ error }),
245 )
246 const reply = await within($, request, timeoutMs)
247 return reply === 'timeout' ? { error: 'timeout' } : reply
248}
249
250async function send($: EngineInterface, link: Link, timeoutMs: number): Promise<void> {
251 while (isActive(link) && !link.isAuthWait && link.queue.length > 0) {
252 const { batch, body, oversized } = takeBatch(link.queue)
253 if (oversized.length > 0) link.queue = drop(link.queue, oversized)
254 if (batch.length === 0) return
255 const reply = await post($, link, body, timeoutMs)
256 switch (outcome(reply.status)) {
257 case 'sent':
258 link.queue = drop(link.queue, batch)
259 link.isFailing = false
260 link.hasRetriedAuth = false
261 continue
262 case 'discard':
263 link.queue = drop(link.queue, batch)
264 logOnce($, link, `discard-${reply.status}`, `the daemon refused a batch (${describeFailure(reply.status, undefined)}); dropped`)
265 continue
266 case 'off':
267 turnOff($, link, 'the daemon has the link disabled (503)')
268 return
269 case 'auth':
270 if (link.hasRetriedAuth) {
271 turnOff($, link, 'the daemon refused the token after a re-read (401)')
272 return
273 }
274 link.hasRetriedAuth = true
275 link.isAuthWait = true
276 link.token = (await readToken($)) ?? link.token
277 log($, 'token refused (401): re-read it, retrying once', true)
278 try {
279 $.clock.after(AUTH_RETRY_MS, () => {
280 link.isAuthWait = false
281 void flush($, link, REQUEST_TIMEOUT_MS)
282 })
283 } catch {
284 link.isAuthWait = false
285 }
286 return
287 case 'retry':
288 link.isFailing = true
289 logOnce($, link, 'unreachable', `daemon unreachable (${describeFailure(reply.status, reply.error)}); keeping up to 200 events`)
290 return
291 }
292 }
293}
294
295/** Sends what is queued, one flush at a time. Never rejects. */
296function flush($: EngineInterface, link: Link, timeoutMs: number): Promise<void> {
297 if (link.flushing !== undefined) return link.flushing
298 link.flushing = send($, link, timeoutMs)
299 .catch(() => undefined)
300 .finally(() => {
301 link.flushing = undefined
302 })
303 return link.flushing
304}
305
306/** Arms the periodic flush once; it re-arms while events remain. */
307function arm($: EngineInterface, link: Link): void {
308 if (link.timer !== undefined || !isActive(link)) return
309 try {
310 link.timer = $.clock.after(FLUSH_EVERY_MS, () => {
311 link.timer = undefined
312 void flush($, link, REQUEST_TIMEOUT_MS).then(() => {
313 if (link.queue.length > 0) arm($, link)
314 })
315 })
316 } catch {
317 link.timer = undefined
318 }
319}
320
321async function push($: EngineInterface, link: Link, kind: LinkKind, payload?: Readonly<Record<string, unknown>>): Promise<void> {
322 if (!isActive(link) || link.isClearing) return
323 const stamped = stamp(link.stamps, kind, await $.clock.now())
324 link.stamps = stamped.stamps
325 const event: LinkEvent = { sessionId: link.sessionId, cwd: link.cwd, kind, at: stamped.at, ...(payload !== undefined ? { payload } : {}) }
326 link.queue = enqueue(link.queue, event)
327 arm($, link)
328}
329
330/**
331 * At a turn boundary: start a send now while the daemon answers, else leave it
332 * to the timer. Never waited on: a hook never blocks on the daemon.
333 */
334function flushAtTurn($: EngineInterface, link: Link): void {
335 if (isActive(link) && !link.isFailing) void flush($, link, REQUEST_TIMEOUT_MS)
336}
337
338/**
339 * session.end's last send: joins a flush already in flight (which may have
340 * started under the 5 s request timeout), then sends what that one left. The
341 * caller bounds the whole wait.
342 */
343async function flushForEnd($: EngineInterface, link: Link): Promise<void> {
344 await flush($, link, END_FLUSH_TIMEOUT_MS)
345 if (link.queue.length > 0 && !link.isFailing) await flush($, link, END_FLUSH_TIMEOUT_MS)
346}
347
348/**
349 * After a `/clear`, at the first main-loop turn.start: the process goes on
350 * under a new session id and no session.start fires for it (SessionEndInput),
351 * so the id is read again here and, when it moved, the new session is
352 * announced with the real session.start's payload.
353 */
354async function resync($: EngineInterface, link: Link): Promise<void> {
355 const sessionId = await $.session.id()
356 const cwd = (await $.session.cwd()) || link.cwd
357 link.isClearing = false
358 if (sessionId === link.sessionId) return
359 link.sessionId = sessionId
360 link.cwd = cwd
361 await push($, link, 'session.start', link.start)
362}
363
364/** The swarm's state for one load of the module. Exists only with `swarm` on. */
365type Swarm = {
366 turn: SwarmTurn
367 /** Claims and releases run one at a time: parallel tool calls must not lose a claim. */
368 lock: Promise<void>
369 /**
370 * Dashboard messages being sent, by command id, until their send settles —
371 * past the 10 s ack timeout too: the `session.send` a late send raises still
372 * carries the command's id.
373 */
374 readonly pending: Map<string, PendingSend>
375}
376
377/** Runs `work` after every claim or release queued before it. Rejects as `work` does. */
378function serialize<T>(swarm: Swarm, work: () => Promise<T>): Promise<T> {
379 const run = swarm.lock.then(work)
380 swarm.lock = run.then(
381 () => undefined,
382 () => undefined,
383 )
384 return run
385}
386
387/** A tool call that writes a file claims its absolute path: `claim`, plus a `conflict` per other live session holding it. */
388async function claimEdit($: EngineInterface, link: Link, swarm: Swarm, tool: string, fields: Readonly<Record<string, unknown>>): Promise<void> {
389 const path = claimPath(tool, fields, link.cwd)
390 if (path === undefined) return
391 await serialize(swarm, async () => {
392 const outcome = await claimFile($, swarm.turn, link.sessionId, link.cwd, path)
393 swarm.turn = outcome.turn
394 if (!outcome.isNew) return
395 if (outcome.storeError !== undefined) {
396 logOnce($, link, 'swarm-store', `swarm: the claims registry refused (${shortError(outcome.storeError)}); the claim is still reported`)
397 }
398 await push($, link, 'claim', { path })
399 for (const conflict of outcome.conflicts) await push($, link, 'conflict', { path: conflict.path, otherSession: conflict.otherSession })
400 })
401}
402
403/**
404 * tool.check with `claimConflicts` set: the verdict for a write whose path
405 * another live session holds (ask, or deny where no person would see the
406 * ask); undefined for any other call, which keeps the verdict beneath.
407 */
408async function checkClaims(
409 $: EngineInterface,
410 link: Link,
411 setting: ClaimConflicts,
412 modes: ModeBook,
413 call: { readonly tool: string; readonly input: unknown; readonly agentId?: string | undefined },
414): Promise<ConflictVerdict | undefined> {
415 if (typeof call.input !== 'object' || call.input === null) return undefined
416 const path = claimPath(call.tool, call.input as Readonly<Record<string, unknown>>, link.cwd)
417 if (path === undefined) return undefined
418 return conflictVerdict(setting, modeOf(modes, call.agentId), await heldElsewhere($, link.sessionId, path))
419}
420
421/** The main loop's turn ended: its claims are released; returns the lines to show beneath the answer. */
422async function endSwarmTurn($: EngineInterface, link: Link, swarm: Swarm): Promise<readonly string[]> {
423 return serialize(swarm, async () => {
424 const { claimed, conflicts, entry } = swarm.turn
425 swarm.turn = EMPTY_TURN
426 if (entry !== undefined) {
427 try {
428 await releaseClaims($, link.sessionId)
429 } catch (error) {
430 logOnce($, link, 'swarm-store', `swarm: the claims registry refused (${shortError(error)}); the claim lapses in 30 min`)
431 }
432 }
433 if (claimed.length > 0) await push($, link, 'release', releasePayload(claimed))
434 return conflictLines(conflicts)
435 })
436}
437
438/** The session ends: every claim it holds is released. */
439async function endSwarmSession($: EngineInterface, link: Link, swarm: Swarm): Promise<void> {
440 await serialize(swarm, async () => {
441 swarm.turn = EMPTY_TURN
442 try {
443 await releaseClaims($, link.sessionId)
444 } catch {
445 // the entry lapses with its TTL
446 }
447 await push($, link, 'release', { all: true })
448 })
449}
450
451/**
452 * A message this conversation's main loop sent: `session.send`, with the
453 * command's id when the dashboard asked for it. One of this plugin's sends that
454 * matches several pending dashboard messages is not reported here: each
455 * message's own path (deliverMessage) reports it with its own id.
456 */
457async function noteSend($: EngineInterface, link: Link, swarm: Swarm, e: SessionSendInput, result: SessionSendResult): Promise<void> {
458 const name = e.origin.kind === 'plugin' ? e.origin.name : undefined
459 const isOwn = name === NAME || name?.startsWith(`${NAME}@`) === true
460 if (isOwn && isAmbiguousSend(swarm.pending, e.to, e.text)) return
461 const pending = isOwn ? pendingFor(swarm.pending, e.to, e.text) : undefined
462 if (pending !== undefined) pending.isLogged = true
463 await push(
464 $,
465 link,
466 'session.send',
467 sendPayload({ to: e.to, text: e.text, origin: e.origin.kind, isDelivered: result.isDelivered, reason: result.reason, commandId: pending?.commandId }),
468 )
469 flushAtTurn($, link)
470}
471
472/** A delivery to the main conversation: `session.receive`, and one line naming where it came from. */
473async function noteReceive($: EngineInterface, link: Link, text: string, origin: unknown): Promise<void> {
474 if (!isActive(link) || link.isClearing) return
475 await push($, link, 'session.receive', receivePayload(text, origin))
476 log($, receiveLine(text, origin))
477 flushAtTurn($, link)
478}
479
480/**
481 * The dashboard's `message` command: `$.session.send` to the session it names.
482 * `done` once queued at the recipient, else `failed` + `undeliverable: <reason>`.
483 * The send's `session.send` event carries the command's id; when the send hook
484 * did not report it, it is reported here. Both happen once the send settles,
485 * also when that is after the 10 s timeout acked the command failed: the
486 * daemon then takes the send's verdict over the ack's.
487 */
488async function deliverMessage($: EngineInterface, link: Link, swarm: Swarm, commandId: string, to: string, text: string): Promise<Ack> {
489 const pending: PendingSend = { commandId, to, text, isLogged: false }
490 swarm.pending.set(commandId, pending)
491 const sending = sendToSession($, to, text).then(
492 (result): SessionSendResult => result,
493 (error: unknown): SessionSendResult => ({ isDelivered: false, reason: shortError(error) }),
494 )
495 const reported = sending
496 .then(async result => {
497 if (pending.isLogged) return
498 await push($, link, 'session.send', sendPayload({ to, text, origin: 'plugin', isDelivered: result.isDelivered, reason: result.reason, commandId }))
499 flushAtTurn($, link)
500 })
501 .catch(() => undefined) // unreported
502 .finally(() => {
503 if (swarm.pending.get(commandId) === pending) swarm.pending.delete(commandId)
504 })
505 const reply = await within($, sending, MESSAGE_TIMEOUT_MS)
506 if (reply === 'timeout') return undeliverable(`no answer in ${MESSAGE_TIMEOUT_MS / 1000}s`)
507 // on time: the report is queued before the ack goes out
508 await reported
509 return reply.isDelivered ? done() : undeliverable(reply.reason)
510}
511
512/** The command channel's state for one session's loop. Exists only with `control` on. */
513type Control = {
514 readonly origin: string
515 readonly sessionId: string
516 /** Set for good by session.end, a 503, or a 401 that survived a re-read. */
517 isStopped: boolean
518 /** The main loop's running turn: `turn.start`'s id until its `turn.complete`. */
519 turnId: string | undefined
520 executed: Executed
521 hasRetriedAuth: boolean
522 /** The pending wait between polls, cancelled on stop. */
523 pause: Timer | undefined
524 /** Settles every race of the loop the moment it stops. */
525 readonly stopped: Promise<'stopped'>
526 readonly settleStopped: () => void
527 /** The swarm's state, for the `message` command; undefined with `swarm` off. */
528 readonly swarm: Swarm | undefined
529}
530
531/** A command poll's end; `isVerified`: the daemon signed the answer (only a signed command runs). */
532type PollReply = { readonly status?: number; readonly text?: string; readonly error?: unknown; readonly isVerified?: boolean }
533
534const newControl = (origin: string, sessionId: string, previous: Control | undefined, swarm: Swarm | undefined): Control => {
535 let settleStopped: () => void = () => undefined
536 const stopped = new Promise<'stopped'>(resolve => {
537 settleStopped = () => resolve('stopped')
538 })
539 return {
540 origin,
541 sessionId,
542 isStopped: false,
543 turnId: previous?.turnId,
544 // ids are the daemon's, unique across sessions: a new loop keeps what ran
545 executed: previous?.executed ?? new Map(),
546 hasRetriedAuth: false,
547 pause: undefined,
548 stopped,
549 settleStopped,
550 swarm,
551 }
552}
553
554function stopControl($: EngineInterface, control: Control, why: string | undefined): void {
555 if (control.isStopped) return
556 control.isStopped = true
557 control.pause?.cancel()
558 control.pause = undefined
559 control.settleStopped()
560 if (why !== undefined) log($, `control off for this session: ${why}`)
561}
562
563/** Waits `ms` on `$.clock` between polls, or less when the loop stops. A clock that refuses stops the loop. */
564async function pause($: EngineInterface, control: Control, ms: number): Promise<void> {
565 if (ms <= 0 || control.isStopped) return
566 const waited = new Promise<void>(resolve => {
567 try {
568 control.pause = $.clock.after(ms, () => {
569 control.pause = undefined
570 resolve()
571 })
572 } catch {
573 stopControl($, control, 'no timer for the poll loop')
574 resolve()
575 }
576 })
577 await Promise.race([waited, control.stopped])
578}
579
580/** One long poll, raced against its 28 s timer and the loop's stop. */
581async function fetchCommand($: EngineInterface, link: Link, control: Control): Promise<PollReply | 'stopped'> {
582 const request = signedFetch($, link.token ?? '', commandsUrl(control.origin, control.sessionId), pollRequest()).then(
583 (r): PollReply => ({ status: r.status, text: r.text, isVerified: r.isVerified }),
584 (error: unknown): PollReply => ({ error }),
585 )
586 const reply = await Promise.race([within($, request, POLL_TIMEOUT_MS), control.stopped])
587 return reply === 'timeout' ? { error: 'timeout' } : reply
588}
589
590/** Acks a command. A lost ack is not retried: the daemon delivers the command again and the executed set answers it. */
591async function sendAck($: EngineInterface, link: Link, control: Control, id: string, ack: Ack): Promise<void> {
592 try {
593 const request = signedFetch($, link.token ?? '', ackUrl(control.origin, id), linkRequest(ackBody(ack))).then(
594 (r): Reply => ({ status: r.status }),
595 (error: unknown): Reply => ({ error }),
596 )
597 const reply = await within($, request, REQUEST_TIMEOUT_MS)
598 const status = reply === 'timeout' ? undefined : reply.status
599 if (status === undefined || status < 200 || status >= 300) {
600 const error = reply === 'timeout' ? 'timeout' : reply.error
601 logOnce($, link, 'ack-failed', `command ${id}: ack not taken (${describeFailure(status, error)}); the daemon delivers it again`)
602 }
603 } catch {
604 // the daemon re-delivers an unacked command after 30 s
605 }
606}
607
608async function abortTurn($: EngineInterface, turnId: string): Promise<Ack> {
609 try {
610 await $.turn.abort({ turnId })
611 return done()
612 } catch (error) {
613 return failed(shortError(error))
614 }
615}
616
617/** Submits the prompt; it resolves as its turn starts, so a session that stays busy past the bound leaves it queued. */
618async function submitPrompt($: EngineInterface, text: string, asUser: boolean): Promise<Ack> {
619 const args: PromptSubmitArgs = asUser ? { text, asUser: true } : { text }
620 try {
621 const result = await within($, $.prompt.submit(args), PROMPT_START_TIMEOUT_MS)
622 if (result === 'timeout') return done('queued')
623 if (result.drop !== undefined) return dropAck(result.drop)
624 return done()
625 } catch (error) {
626 return submitFailure(error)
627 }
628}
629
630/** Runs one delivered command (or answers a re-delivered one from the executed set) and acks it. */
631async function execute($: EngineInterface, link: Link, control: Control, command: Command): Promise<void> {
632 const action = decide(command, control.executed, control.turnId, control.swarm !== undefined)
633 let ack: Ack
634 switch (action.do) {
635 case 'ack':
636 ack = action.ack
637 break
638 case 'abort':
639 ack = await abortTurn($, action.turnId)
640 break
641 case 'submit':
642 ack = await submitPrompt($, action.text, action.asUser)
643 break
644 case 'message':
645 ack = control.swarm === undefined ? failed(SWARM_OFF) : await deliverMessage($, link, control.swarm, command.id, action.to, action.text)
646 break
647 }
648 // recorded before the ack goes out: a lost ack must not run it twice
649 control.executed = remember(control.executed, command.id, ack)
650 if (!control.isStopped) await sendAck($, link, control, command.id, ack)
651}
652
653/** The command loop: poll, execute, ack, poll again, until it stops. Never rejects. */
654async function poll($: EngineInterface, link: Link, control: Control): Promise<void> {
655 try {
656 while (!control.isStopped && !link.isOff) {
657 const startedAt = await $.clock.now()
658 const reply = await fetchCommand($, link, control)
659 if (reply === 'stopped' || control.isStopped || link.isOff) return
660 switch (pollOutcome(reply.status)) {
661 case 'command': {
662 if (reply.isVerified !== true) {
663 // not the daemon's answer: nothing runs on it
664 logOnce($, link, 'command-unsigned', 'control: a command reply without the daemon\'s signature was ignored')
665 await pause($, control, nextPollDelay('retry', 0))
666 continue
667 }
668 const command = parseCommand(reply.text)
669 control.hasRetriedAuth = false
670 if (command === undefined) {
671 logOnce($, link, 'command-unreadable', 'control: a command reply named no id; skipped')
672 await pause($, control, nextPollDelay('retry', 0))
673 continue
674 }
675 await execute($, link, control, command)
676 continue
677 }
678 case 'idle':
679 control.hasRetriedAuth = false
680 await pause($, control, nextPollDelay('idle', (await $.clock.now()) - startedAt))
681 continue
682 case 'auth':
683 if (control.hasRetriedAuth) {
684 stopControl($, control, 'the daemon refused the token after a re-read (401)')
685 return
686 }
687 control.hasRetriedAuth = true
688 link.token = (await readToken($)) ?? link.token
689 log($, 'control: token refused (401): re-read it, retrying once', true)
690 await pause($, control, AUTH_RETRY_MS)
691 continue
692 case 'off':
693 stopControl($, control, undefined)
694 turnOff($, link, 'the daemon has the link disabled (503)')
695 return
696 case 'retry':
697 logOnce($, link, 'control-unreachable', `control: command poll failed (${describeFailure(reply.status, reply.error)}); retrying every 3s`)
698 await pause($, control, nextPollDelay('retry', 0))
699 continue
700 }
701 }
702 } catch {
703 stopControl($, control, 'the poll loop failed')
704 }
705}
706
707/** Starts the session's one command loop, detached from the hook that starts it. */
708function startControl($: EngineInterface, link: Link, control: Control): void {
709 try {
710 $.clock.after(0, () => {
711 void poll($, link, control)
712 })
713 log($, 'control: polling the daemon for commands', true)
714 } catch {
715 stopControl($, control, 'no timer for the poll loop')
716 }
717}
718
719/** Replaces `previous` (stopped first) with a loop for the link's current session id, and starts it. */
720function openControl($: EngineInterface, link: Link, origin: string, previous: Control | undefined, swarm: Swarm | undefined): Control {
721 if (previous !== undefined) stopControl($, previous, undefined)
722 const control = newControl(origin, link.sessionId, previous, swarm)
723 startControl($, link, control)
724 return control
725}
726
727/** The forecast loop's state for one load of the module. Exists only with `forecast` on. */
728type Forecaster = {
729 state: ForecastState
730 /** An in-process resume ended the session: the next turn.start starts a new run (resync). */
731 isResumed: boolean
732}
733
734/** RUN_ID_RANDOM random bytes from the runtime's `crypto`, or undefined where it has none. */
735const randomBytes = (): Uint8Array | undefined => {
736 try {
737 if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') return undefined
738 return crypto.getRandomValues(new Uint8Array(RUN_ID_RANDOM))
739 } catch {
740 return undefined
741 }
742}
743
744/** Starts the turn counter over under a fresh run id: `<ms of $.clock.now()>-<random base36>`. */
745async function newRun($: EngineInterface, forecaster: Forecaster): Promise<void> {
746 let now = 0
747 try {
748 now = await $.clock.now()
749 } catch {
750 // the random part alone tells the runs apart
751 }
752 forecaster.state = resetForecast(forecaster.state, runIdOf(now, randomBytes()))
753}
754
755/**
756 * Asks the model for turn `turnSeq`'s forecast and queues it as `turn.forecast`,
757 * however the call ended (no readable claim: all-null claims, tokens still
758 * counted). A reset while the call was in flight (`generation` moved) drops
759 * it: the session id and the run it was asked under are gone. Never rejects;
760 * nothing waits on it.
761 */
762async function runForecast(
763 $: EngineInterface,
764 link: Link,
765 forecaster: Forecaster,
766 runId: string,
767 turnSeq: number,
768 generation: number,
769 ask: { readonly system: string; readonly prompt: string },
770): Promise<void> {
771 let claims = NO_CLAIMS
772 let tokens: number | null = null
773 try {
774 const reply = await $.model.complete({
775 model: FORECAST_MODEL,
776 system: ask.system,
777 prompt: ask.prompt,
778 maxTokens: FORECAST_MAX_TOKENS,
779 timeoutMs: FORECAST_TIMEOUT_MS,
780 })
781 tokens = usageTokens(reply.usage)
782 if (reply.isAnswered) claims = parseForecast(reply.text, link.cwd)
783 else logOnce($, link, `forecast-${reply.reason}`, `forecast: no reply (${reply.reason}); sent without claims`)
784 } catch {
785 logOnce($, link, 'forecast-refused', 'forecast: the model call was refused; sent without claims')
786 } finally {
787 forecaster.state = closeForecast(forecaster.state, generation)
788 }
789 if (forecaster.state.generation !== generation) return
790 try {
791 await push($, link, 'turn.forecast', forecastPayload(runId, turnSeq, claims, FORECAST_MODEL, tokens))
792 flushAtTurn($, link)
793 } catch {
794 // unreported
795 }
796}
797
798/**
799 * A main-loop turn starts: count it, and when it carries the person's text and
800 * no forecast is still open, start one detached from the hook, so the turn
801 * never waits on the model.
802 */
803function beginForecast($: EngineInterface, link: Link, forecaster: Forecaster, turnId: string, text: string): void {
804 const { state, shouldAsk } = startTurn(forecaster.state, turnId, text, isActive(link))
805 forecaster.state = state
806 if (!shouldAsk) return
807 const run = (): void => {
808 void runForecast($, link, forecaster, state.runId, state.turnSeq, state.generation, forecastRequest(text, state.history))
809 }
810 try {
811 $.clock.after(0, run)
812 } catch {
813 run()
814 }
815}
816
817/** A main-loop turn ends: queue its actual when the turn was forecast. */
818async function finishForecast($: EngineInterface, link: Link, forecaster: Forecaster, turnId: string): Promise<void> {
819 const { state, actual } = endTurn(forecaster.state, turnId)
820 forecaster.state = state
821 if (actual !== undefined) await push($, link, 'turn.actual', actual)
822}
823
824/** The approvals channel's view of the link for one call: its session as of now, its token, the token re-read. */
825function gateOf($: EngineInterface, link: Link, origin: string, waiting: { count: number }): Gate {
826 return {
827 origin,
828 sessionId: link.sessionId,
829 cwd: link.cwd,
830 token: () => link.token ?? '',
831 reread: async () => {
832 link.token = (await readToken($)) ?? link.token
833 },
834 waiting,
835 }
836}
837
838/** How a tool call ended, from what `next(e)` resolved to. */
839const toolOutcome = (result: unknown): ToolOutcome => {
840 const r = result as { readonly deny?: unknown; readonly isError?: unknown } | undefined
841 if (r?.deny !== undefined) return 'denied'
842 return r?.isError === true ? 'error' : 'ok'
843}
844
845export const register: Register = (on, options) => {
846 const reserved = RESERVED.filter(feature => options[feature] === true)
847 const isControlOn = options.control === true
848 const isApprovalsOn = options.approvals === true
849 const endpoint = daemonEndpoint(options.daemonUrl)
850 /** Calls waiting on the dashboard right now; the status line shows while any does. */
851 const waiting = { count: 0 }
852 /** The command loop; only ever set with `control` on. */
853 let control: Control | undefined
854 /** The forecast loop; undefined with `forecast` off, so none of it runs. */
855 const forecaster: Forecaster | undefined = options.forecast === true ? { state: INITIAL_FORECAST, isResumed: false } : undefined
856 /** The swarm; undefined with `swarm` off, so no store access, no swarm event and no send/receive hook. */
857 const swarm: Swarm | undefined = options.swarm === true ? { turn: EMPTY_TURN, lock: Promise.resolve(), pending: new Map() } : undefined
858 /** How a write another live session holds is met; the registry exists with `swarm` on alone, so `off` without it. */
859 const claimConflicts: ClaimConflicts = swarm !== undefined ? claimConflictsOf(options.claimConflicts) : 'off'
860 /** `claimConflicts` set without `swarm`: said once, at the first session.start. */
861 const isClaimConflictsIdle = swarm === undefined && claimConflictsOf(options.claimConflicts) !== 'off'
862 /** The permission mode per loop, read off the classic events; kept with `claimConflicts: ask` alone. */
863 const modes: ModeBook = new Map()
864 /** The plan band; undefined with `planBand` off, so no band hook, command, timer or plan request exists. */
865 const planner: Planner | undefined = options.planBand === true ? newPlanner(endpoint.origin) : undefined
866 const noted = new Set<string>()
867 const link: Link = {
868 url: endpoint.url,
869 token: undefined,
870 sessionId: '',
871 cwd: '',
872 start: undefined,
873 isClearing: false,
874 isOff: false,
875 isFailing: false,
876 isAuthWait: false,
877 hasRetriedAuth: false,
878 queue: [],
879 stamps: {},
880 timer: undefined,
881 flushing: undefined,
882 logged: new Set<string>(),
883 }
884
885 on('session.start', async ($, e, next) => {
886 const result = await next(e)
887 // also on `--resume`, which keeps the session id: a new run, so turn 1 is a new row
888 if (forecaster !== undefined) {
889 forecaster.isResumed = false
890 await newRun($, forecaster)
891 }
892 for (const feature of reserved) {
893 if (noted.has(feature)) continue
894 noted.add(feature)
895 log($, `${feature}: not implemented yet`)
896 }
897 if (isClaimConflictsIdle && !noted.has('claimConflicts')) {
898 noted.add('claimConflicts')
899 log($, 'claimConflicts needs swarm on: no write is held')
900 }
901 // the command answers with or without a token: it says what is missing
902 if (planner !== undefined) await registerPlanCommand($)
903 if (endpoint.isRefused && !noted.has('daemonUrl')) {
904 // the configured value is not echoed: it may carry credentials
905 noted.add('daemonUrl')
906 log($, `daemonUrl refused: not a loopback http origin (127.0.0.1, [::1], localhost); using ${DEFAULT_DAEMON_URL}`)
907 }
908 try {
909 link.token = await readToken($)
910 if (link.token === undefined) {
911 log($, 'no token, sensor off')
912 return result
913 }
914 link.sessionId = await $.session.id()
915 link.cwd = (await $.session.cwd()) || e.cwd
916 link.start = { surface: e.surface, isInteractive: e.isInteractive }
917 link.isClearing = false
918 await push($, link, 'session.start', link.start)
919 // one loop per session: a second session.start of the same session keeps it
920 if (isControlOn && !link.isOff && (control === undefined || control.isStopped || control.sessionId !== link.sessionId)) {
921 control = openControl($, link, endpoint.origin, control, swarm)
922 }
923 if (planner !== undefined) {
924 startPlanTimer($, planner, link)
925 void refreshPlan($, planner, link)
926 }
927 } catch {
928 // the sensor stays off; the session goes on
929 }
930 return result
931 })
932
933 // turn.start is the main loop's alone (TurnCompleteFields.turnId: "a subagent's run raises no turn.start").
934 on('turn.start', async ($, e, next) => {
935 if (link.isClearing && isActive(link)) {
936 try {
937 await resync($, link)
938 if (isControlOn && !link.isOff) control = openControl($, link, endpoint.origin, control, swarm)
939 // the band follows the new session id: its plan is read again under it
940 if (planner !== undefined) void refreshPlan($, planner, link)
941 } catch {
942 // the id is read again at the next turn.start
943 }
944 }
945 if (control !== undefined) control.turnId = e.turnId
946 if (planner !== undefined) {
947 planner.turn = { turnId: e.turnId, edits: [], isClassified: false }
948 startPlanTimer($, planner, link)
949 }
950 // the resync after an in-process resume: the counter starts over under a new run
951 if (forecaster !== undefined && forecaster.isResumed) {
952 forecaster.isResumed = false
953 await newRun($, forecaster)
954 }
955 try {
956 await push($, link, 'turn.start')
957 flushAtTurn($, link)
958 } catch {
959 // never fail a turn over the sensor
960 }
961 // turn.start is the main loop's alone: a subagent's run raises none
962 if (forecaster !== undefined) beginForecast($, link, forecaster, e.turnId, e.text)
963 return next(e)
964 })
965
966 on('tool.call', async ($, e, next) => {
967 if (isActive(link)) {
968 try {
969 const fields = e as unknown as Readonly<Record<string, unknown>>
970 await push($, link, 'tool.call', {
971 tool: String(e.tool),
972 inputHash: await inputHash(toolInput(fields)),
973 ...(e.agentId !== undefined ? { agentId: e.agentId } : {}),
974 })
975 } catch {
976 // the call goes on unreported
977 }
978 }
979 // With claimConflicts off the edit is claimed ahead of the call, as ever. On,
980 // it is claimed once the call ran: a write the check held back (refused, or
981 // declined at the dialog) must not leave a claim that holds the other session back.
982 const claimsAfter = swarm !== undefined && claimConflicts !== 'off'
983 if (swarm !== undefined && !claimsAfter && isActive(link) && !link.isClearing) {
984 try {
985 await claimEdit($, link, swarm, String(e.tool), e as unknown as Readonly<Record<string, unknown>>)
986 } catch {
987 // the edit goes on unclaimed
988 }
989 }
990 const isMainLoop = e.agentId === undefined
991 const isForecastTurn = forecaster !== undefined && isMainLoop && forecaster.state.turnId !== undefined
992 // the drift check counts the main loop's edits alone
993 const isPlanEdit = planner?.turn !== undefined && isMainLoop && isEditTool(String(e.tool))
994 if (!isForecastTurn && !isPlanEdit && !claimsAfter) return next(e)
995 const result = await next(e)
996 const fields = e as unknown as Readonly<Record<string, unknown>>
997 if (swarm !== undefined && claimsAfter && toolOutcome(result) === 'ok' && isActive(link) && !link.isClearing) {
998 try {
999 await claimEdit($, link, swarm, String(e.tool), fields)
1000 } catch {
1001 // the edit stands unclaimed
1002 }
1003 }
1004 try {
1005 if (forecaster !== undefined && isForecastTurn) {
1006 const facts = { tool: String(e.tool), agentId: e.agentId, fields }
1007 forecaster.state = noteToolCall(forecaster.state, facts, toolOutcome(result), link.cwd)
1008 }
1009 const path = isPlanEdit ? editedPath(String(e.tool), fields, link.cwd) : undefined
1010 if (planner !== undefined && path !== undefined && toolOutcome(result) !== 'denied') planner.turn = noteEdit(planner.turn, path)
1011 } catch {
1012 // the journal misses one call; the call's result stands
1013 }
1014 return result
1015 }).catch(($, e, next) => next(e))
1016
1017 // One tool.check (the engine takes one unmatched hook per event) serves the
1018 // approvals channel and `claimConflicts`: the conflict verdict is reached
1019 // first, then the approvals channel sees it, so a write the conflict check
1020 // refuses never opens a dashboard approval (only an `ask` goes there).
1021 // Registered with either option on.
1022 if (isApprovalsOn || claimConflicts !== 'off') {
1023 on('tool.check', async ($, e, next) => {
1024 const below = await next(e)
1025 if (!isActive(link) || link.isClearing) return below
1026 let verdict = below
1027 if (claimConflicts !== 'off' && below.decision !== 'deny') {
1028 try {
1029 verdict = (await checkClaims($, link, claimConflicts, modes, { tool: String(e.tool), input: e.input, agentId: e.agentId })) ?? below
1030 } catch {
1031 // the registry could not be read: the verdict beneath stands
1032 }
1033 }
1034 if (!isApprovalsOn) return verdict
1035 return checkWithSwarmery($, gateOf($, link, endpoint.origin, waiting), e, verdict, next.signal)
1036 }).catch(($, e, next) => next(e))
1037 }
1038
1039 // Registered after the sensor's tool.call, so the sensor sits above it and
1040 // still reports (and journals) an AskUserQuestion answered from the dashboard.
1041 if (isApprovalsOn) {
1042 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
1043 if (!isActive(link) || link.isClearing) return next(e)
1044 const fields = e as unknown as Readonly<Record<string, unknown>>
1045 // an answer as the call's result, a dashboard deny as its refusal; anything else opens the native dialog
1046 const outcome = await answerFromSwarmery($, gateOf($, link, endpoint.origin, waiting), fields, next.signal)
1047 return outcome ?? next(e)
1048 }).catch(($, e, next) => next(e))
1049 }
1050
1051 // tool.check carries no permission mode; these classic events do. Each only
1052 // records it and hands the event on unchanged. With `ask` alone: `deny`
1053 // refuses in every mode.
1054 if (swarm !== undefined && claimConflicts === 'ask') {
1055 const record = (e: unknown): void => {
1056 try {
1057 noteMode(modes, e)
1058 } catch {
1059 // an unread mode keeps the ask
1060 }
1061 }
1062 on('classic.SessionStart', async ($, e, next) => {
1063 record(e)
1064 return next(e)
1065 }).catch(($, e, next) => next(e))
1066 on('classic.UserPromptSubmit', async ($, e, next) => {
1067 record(e)
1068 return next(e)
1069 }).catch(($, e, next) => next(e))
1070 on('classic.PostToolUse', async ($, e, next) => {
1071 record(e)
1072 return next(e)
1073 }).catch(($, e, next) => next(e))
1074 on('classic.PostToolUseFailure', async ($, e, next) => {
1075 record(e)
1076 return next(e)
1077 }).catch(($, e, next) => next(e))
1078 }
1079
1080 on('session.measure', async ($, e, next) => {
1081 try {
1082 const payload = measurePayload(e)
1083 if (payload !== undefined) await push($, link, 'session.measure', payload)
1084 } catch {
1085 // unreported
1086 }
1087 return next(e)
1088 })
1089
1090 on('turn.complete', async ($, e, next) => {
1091 // A subagent's run ends in a turn.complete too; only the main loop's means the session waits.
1092 if (control !== undefined && e.agentId === undefined && control.turnId === e.turnId) control.turnId = undefined
1093 if (e.agentId !== undefined || !isActive(link)) return next(e)
1094 /** Lines shown beneath the answer: each feature that has one adds it here. */
1095 const beneath: string[] = []
1096 try {
1097 await push($, link, 'turn.complete', { durationMs: e.durationMs, stopReason: e.reason })
1098 if (forecaster !== undefined) await finishForecast($, link, forecaster, e.turnId)
1099 if (swarm !== undefined) beneath.push(...(await endSwarmTurn($, link, swarm)))
1100 const snapshot = measurePayload(await $.session.usage())
1101 if (snapshot !== undefined) await push($, link, 'session.measure', snapshot)
1102 flushAtTurn($, link)
1103 } catch {
1104 // unreported
1105 }
1106 const result = await next(e)
1107 if (planner !== undefined) {
1108 try {
1109 const drift = await checkDrift($, planner, link, e.turnId, e.answer)
1110 if (drift !== undefined) beneath.push(drift)
1111 } catch {
1112 // no line; the answer stands
1113 }
1114 void refreshPlan($, planner, link)
1115 }
1116 // each feature added its own line; they are joined once, beneath the answer
1117 return withBeneath(result, e.answer, beneath)
1118 })
1119
1120 on('session.end', async ($, e, next) => {
1121 if (control !== undefined) stopControl($, control, undefined)
1122 if (planner !== undefined) {
1123 stopPlanTimer(planner)
1124 planner.turn = undefined
1125 // `/clear` or an in-process resume: the old session's plan is not the next one's
1126 if (e.reason === 'clear' || e.reason === 'resume') setView($, planner, undefined)
1127 }
1128 // a /clear goes on in this process with no session.start: the turn count starts over here;
1129 // an in-process resume starts it over at the next turn.start's resync
1130 if (forecaster !== undefined && e.reason === 'clear') await newRun($, forecaster)
1131 if (forecaster !== undefined && e.reason === 'resume') forecaster.isResumed = true
1132 if (!isActive(link)) return next(e)
1133 try {
1134 if (swarm !== undefined) await endSwarmSession($, link, swarm)
1135 await push($, link, 'session.end', { reason: e.reason })
1136 link.timer?.cancel()
1137 link.timer = undefined
1138 // bounded by its own timer: a flush in flight may have a 5 s request timeout
1139 await within($, flushForEnd($, link), END_FLUSH_TIMEOUT_MS)
1140 } catch {
1141 // best effort inside session.end's 1.5 s bound
1142 }
1143 // `/clear` or an in-process resume: the process goes on under another id with no
1144 // session.start (SessionEndInput.sessionId); the next turn.start picks it up
1145 if (e.reason === 'clear' || e.reason === 'resume') link.isClearing = true
1146 return next(e)
1147 })
1148
1149 // Registered with `swarm` on alone: off, no message hook runs at all.
1150 if (swarm !== undefined) {
1151 // The main conversation's messages to other sessions or agents; a subagent's are left out.
1152 on('session.send', async ($, e, next) => {
1153 const result = await next(e)
1154 if (e.agentId !== undefined || !isActive(link)) return result
1155 try {
1156 await noteSend($, link, swarm, e, result)
1157 } catch {
1158 // unreported; the send stands
1159 }
1160 return result
1161 }).catch(($, e, next) => next(e))
1162
1163 // A delivery to the main conversation; one for a subagent is left out. Passed on as received.
1164 on('session.receive', async ($, e, next) => {
1165 if (e.agentId === undefined) {
1166 try {
1167 await noteReceive($, link, e.text, e.origin)
1168 } catch {
1169 // unreported
1170 }
1171 }
1172 return next(e)
1173 }).catch(($, e, next) => next(e))
1174 }
1175
1176 if (planner === undefined) return
1177
1178 // The band draws from the cache alone: a render never fetches.
1179 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => drawBand($, planner, link, e) ?? next(e))
1180
1181 on('ui.render', { component: 'Pane', requestId: PLAN_PANE_ID }, async ($, e) => drawPane($, planner, e))
1182
1183 // An interview-style question gets a card above the engine's own dialog, which still answers it.
1184 on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
1185 const interviews = interviewsOf(e.props.questions)
1186 if (interviews.length === 0) return next(e)
1187 return drawInterview($, e, interviews, await next(e))
1188 })
1189
1190 // `/phase [task-id]`: answered here, so no model turn runs.
1191 on('command.run', { command: 'phase' }, async ($, e) => runPlanCommand($, planner, link, e.args)).catch(() => ({
1192 text: 'swarmery-link: /phase failed; the band shows the cached phase',
1193 }))
1194}
1195hooks/approvals.ts 332 lines1// The approvals channel (option `approvals`, plan decision D3: the mod first,
2// the shim as the fallback). A permission `ask` the engine reached for a real
3// call goes to the daemon's queue, and the mod waits for the dashboard's
4// decision inside server-held long polls (time inside `$.http.fetch` does not
5// count against a hook's 10 s budget; mods-format.md §M3). An AskUserQuestion
6// is put to the dashboard the same way and answered (or refused) from it (§M4).
7//
8// Every failure falls back to the engine's verdict (tool.check) or to the
9// question's own dialog (tool.call): no answer, a timeout, a 5xx, a second
10// 401, the deadline, the person interrupting. The mod never answers `ask` of
11// its own and never refuses on a failure. Only an interrupt mid-wait gives
12// the daemon's request up (a fire-and-forget DELETE); on every other end the
13// request stays pending for the shim to attach to.
14//
15// The `$` calls live in the functions declared at the top of this file;
16// ./lib/approvals.ts holds the pure parts.
17
18import type { Args, EngineInterface, ResultOf, Timer } from 'claude-code'
19import {
20 type Answer,
21 type HttpReply,
22 LOCAL_NOTICE,
23 MAX_POLL_FAILURES,
24 PERMISSION_AUTH_RETRY_MS,
25 PERMISSION_CANCEL_TIMEOUT_MS,
26 PERMISSION_POST_TIMEOUT_MS,
27 type PermissionRequest,
28 type QuestionOutcome,
29 WAITING_STATUS,
30 checkResult,
31 permissionBody,
32 permissionCancel,
33 permissionCancelUrl,
34 permissionPoll,
35 permissionPollUrl,
36 permissionUrl,
37 pollAnswer,
38 pollBound,
39 pollGap,
40 postAnswer,
41 questionOutcome,
42 shouldAsk,
43} from './lib/approvals'
44import { linkRequest } from './lib/client'
45import { toolInput } from './lib/hash'
46import { matchProd } from './lib/prod'
47import { type LinkInit, signedFetch } from './signed'
48
49/** What the channel reads of the link, as of the call it decides. */
50export type Gate = {
51 /** The daemon's loopback origin. */
52 readonly origin: string
53 readonly sessionId: string
54 readonly cwd: string
55 /** The link's current token: the key every request is signed with (never sent). */
56 readonly token: () => string
57 /** Re-reads the token file into the link (after a 401). */
58 readonly reread: () => Promise<void>
59 /** How many calls wait on the dashboard right now: the status line is the plugin's one, shared. */
60 readonly waiting: { count: number }
61}
62
63const PASS: Answer = { kind: 'pass' }
64
65/** Settles `'aborted'` once the dispatch is abandoned (the person interrupted, a hook above settled first). */
66const abortOf = (signal: AbortSignal): Promise<'aborted'> =>
67 new Promise(resolve => {
68 if (signal.aborted) {
69 resolve('aborted')
70 return
71 }
72 signal.addEventListener('abort', () => resolve('aborted'), { once: true })
73 })
74
75/** `pending`, `'timeout'` once `ms` pass on `$.clock`, or `'aborted'`, whichever comes first. No timer: `'timeout'` at once. */
76async function bounded<T>($: EngineInterface, pending: Promise<T>, ms: number, aborted: Promise<'aborted'>): Promise<T | 'timeout' | 'aborted'> {
77 let guard: Timer | undefined
78 const timeout = new Promise<'timeout'>(resolve => {
79 try {
80 guard = $.clock.after(ms, () => resolve('timeout'))
81 } catch {
82 resolve('timeout')
83 }
84 })
85 try {
86 return await Promise.race([pending, timeout, aborted])
87 } finally {
88 guard?.cancel()
89 }
90}
91
92/**
93 * One signed request, bounded by `ms` on `$.clock` (HttpInit has no timeout or
94 * signal) and by the dispatch's abort. The reply says whether the daemon
95 * signed it; only a signed decision counts (lib/approvals.ts postAnswer).
96 */
97async function request(
98 $: EngineInterface,
99 gate: Gate,
100 url: string,
101 init: LinkInit,
102 ms: number,
103 aborted: Promise<'aborted'>,
104): Promise<HttpReply | 'aborted'> {
105 const pending = signedFetch($, gate.token(), url, init).then(
106 (r): HttpReply => ({ status: r.status, text: r.text, isVerified: r.isVerified }),
107 (error: unknown): HttpReply => ({ error }),
108 )
109 const reply = await bounded($, pending, ms, aborted)
110 return reply === 'timeout' ? { error: 'timeout' } : reply
111}
112
113/** Waits `ms` on `$.clock`, or less when the dispatch is abandoned. */
114async function pause($: EngineInterface, ms: number, aborted: Promise<'aborted'>): Promise<'aborted' | undefined> {
115 if (ms <= 0) return undefined
116 // a fresh never-settling promise per wait, so no race's reactions pile up on a shared one
117 const ended = await bounded($, new Promise<never>(() => undefined), ms, aborted)
118 return ended === 'aborted' ? 'aborted' : undefined
119}
120
121/** Sets (or, with undefined, clears) the plugin's status line; a refused one is skipped. */
122function showStatus($: EngineInterface, text: string | undefined): void {
123 try {
124 $.ui.status(text)
125 } catch {
126 // a status line is a courtesy
127 }
128}
129
130/** A line under the call's dialog; refused when no dialog is open for it, which is fine. */
131function showNotice($: EngineInterface, toolUseId: string, text: string): void {
132 try {
133 $.ui.notice(toolUseId, text)
134 } catch {
135 // the dialog says the rest
136 }
137}
138
139/**
140 * Tells the daemon the mod gave up on request `id` (DELETE), so a dashboard
141 * decision no longer lands on a row no hook reads. Fire-and-forget: raced
142 * against a 2 s `$.clock` timer and never awaited, so the hook's return never
143 * waits on it; a lost DELETE only leaves the daemon's lease to lapse.
144 */
145function cancelRequest($: EngineInterface, gate: Gate, id: string): void {
146 try {
147 const sent = signedFetch($, gate.token(), permissionCancelUrl(gate.origin, id, gate.sessionId), permissionCancel()).catch(() => undefined)
148 // the dispatch is already abandoned, so the race runs against a wait that never ends rather than its abort
149 bounded($, sent, PERMISSION_CANCEL_TIMEOUT_MS, new Promise<never>(() => undefined)).catch(() => undefined)
150 } catch {
151 // the lease lapsing says the same, later
152 }
153}
154
155/**
156 * Polls a pending request until the dashboard decides, the deadline passes,
157 * the dispatch is abandoned (`'aborted'`) or the daemon fails (`pass`).
158 */
159async function pollDecision(
160 $: EngineInterface,
161 gate: Gate,
162 id: string,
163 deadline: number,
164 signal: AbortSignal,
165 aborted: Promise<'aborted'>,
166 hasRetriedAuth: boolean,
167): Promise<Answer | 'aborted'> {
168 let failures = 0
169 let isRetried = hasRetriedAuth
170 for (;;) {
171 const startedAt = await $.clock.now()
172 const bound = pollBound(deadline, startedAt)
173 if (signal.aborted) return 'aborted'
174 if (bound <= 0) return PASS
175 const reply = await request($, gate, permissionPollUrl(gate.origin, id, gate.sessionId), permissionPoll(), bound, aborted)
176 if (reply === 'aborted' || signal.aborted) return 'aborted'
177 const answer = pollAnswer(reply)
178 switch (answer.kind) {
179 case 'wait': {
180 failures = 0
181 if ((await pause($, pollGap((await $.clock.now()) - startedAt), aborted)) === 'aborted') return 'aborted'
182 continue
183 }
184 case 'auth': {
185 if (isRetried) return PASS
186 isRetried = true
187 await gate.reread()
188 if ((await pause($, PERMISSION_AUTH_RETRY_MS, aborted)) === 'aborted') return 'aborted'
189 continue
190 }
191 case 'fail': {
192 failures += 1
193 if (failures >= MAX_POLL_FAILURES) return PASS
194 continue
195 }
196 default:
197 return answer
198 }
199 }
200}
201
202/**
203 * Waits on a pending request (pollDecision) with the status line up. An
204 * abandoned dispatch gives the request up with a DELETE; every other end
205 * (the deadline, failed polls, a 404, a second 401) leaves the row pending,
206 * so the shim the engine fires next can attach to it by hash.
207 */
208async function waitForDecision(
209 $: EngineInterface,
210 gate: Gate,
211 id: string,
212 deadline: number,
213 signal: AbortSignal,
214 aborted: Promise<'aborted'>,
215 hasRetriedAuth: boolean,
216): Promise<Answer> {
217 gate.waiting.count += 1
218 if (gate.waiting.count === 1) showStatus($, WAITING_STATUS)
219 try {
220 const answer = await pollDecision($, gate, id, deadline, signal, aborted, hasRetriedAuth)
221 if (answer !== 'aborted') return answer
222 cancelRequest($, gate, id)
223 return PASS
224 } finally {
225 gate.waiting.count -= 1
226 if (gate.waiting.count === 0) showStatus($, undefined)
227 }
228}
229
230/**
231 * Puts one call to the daemon and waits for the decision. Resolves to the
232 * daemon's answer; every failure resolves to `pass` (the caller's fallback
233 * stands). Never rejects.
234 */
235async function askSwarmery($: EngineInterface, gate: Gate, permission: PermissionRequest, signal: AbortSignal): Promise<Answer> {
236 try {
237 const aborted = abortOf(signal)
238 const body = permissionBody(permission)
239 let isRetried = false
240 for (;;) {
241 if (signal.aborted) return PASS
242 const reply = await request($, gate, permissionUrl(gate.origin), linkRequest(body), PERMISSION_POST_TIMEOUT_MS, aborted)
243 if (reply === 'aborted' || signal.aborted) return PASS
244 const answer = postAnswer(reply, await $.clock.now())
245 if (answer.kind === 'auth') {
246 if (isRetried) return PASS
247 isRetried = true
248 await gate.reread()
249 if ((await pause($, PERMISSION_AUTH_RETRY_MS, aborted)) === 'aborted') return PASS
250 continue
251 }
252 if (answer.kind !== 'pending') return answer
253 return await waitForDecision($, gate, answer.id, answer.deadline, signal, aborted, isRetried)
254 }
255 } catch {
256 return PASS
257 }
258}
259
260/**
261 * tool.check: the engine's `ask` for a real call goes to the dashboard first.
262 * An allow or a deny the daemon signed answers; anything else (an excluded
263 * project, a pass, a failure, an unsigned answer, the deadline, an interrupt)
264 * returns the engine's verdict untouched, so the shim or the native dialog
265 * takes over. A production deploy is confirmed in the terminal, and its
266 * dialog says so: one the mod matches itself (lib/prod.ts) never goes to the
267 * daemon at all, and one the daemon matches comes back `local`.
268 */
269export async function checkWithSwarmery(
270 $: EngineInterface,
271 gate: Gate,
272 e: Args<'tool.check'>,
273 verdict: ResultOf['tool.check'],
274 signal: AbortSignal,
275): Promise<ResultOf['tool.check']> {
276 const toolUseId = e.tool_use_id
277 if (!shouldAsk(verdict, e) || toolUseId === undefined) return verdict
278 if (matchProd(e.tool, e.input) !== undefined) {
279 showNotice($, toolUseId, LOCAL_NOTICE)
280 return verdict
281 }
282 const answer = await askSwarmery(
283 $,
284 gate,
285 {
286 sessionId: gate.sessionId,
287 cwd: gate.cwd,
288 toolName: e.tool,
289 toolInput: e.input,
290 toolUseId,
291 ...(e.agentId !== undefined ? { agentId: e.agentId } : {}),
292 },
293 signal,
294 )
295 if (answer.kind === 'local') showNotice($, toolUseId, LOCAL_NOTICE)
296 return checkResult(answer, verdict)
297}
298
299/**
300 * tool.call of AskUserQuestion: the question goes to the dashboard first. The
301 * person's answer there is returned as `{ result: { questions, answers } }`, a
302 * dashboard deny as the call's refusal `{ deny }` (handing the call on would
303 * open the native dialog and fire the shim, and the deny would be lost);
304 * undefined on anything else (an allow without answers, a pass, a failure, the
305 * deadline, an interrupt), so the caller hands the call on to the native
306 * dialog.
307 */
308export async function answerFromSwarmery(
309 $: EngineInterface,
310 gate: Gate,
311 fields: Readonly<Record<string, unknown>>,
312 signal: AbortSignal,
313): Promise<QuestionOutcome | undefined> {
314 const toolUseId = fields.tool_use_id
315 if (typeof toolUseId !== 'string' || toolUseId === '') return undefined
316 const agentId = fields.agentId
317 const answer = await askSwarmery(
318 $,
319 gate,
320 {
321 sessionId: gate.sessionId,
322 cwd: gate.cwd,
323 toolName: 'AskUserQuestion',
324 toolInput: toolInput(fields),
325 toolUseId,
326 ...(typeof agentId === 'string' ? { agentId } : {}),
327 },
328 signal,
329 )
330 return questionOutcome(answer, fields.questions)
331}
332hooks/ask-render.ts 45 lines1// The interview card (option `planBand`): an AskUserQuestion asked in the
2// dashboard interview's shape gets a card above the dialog, with each option's
3// description, pros (+) and cons (−) and the recommended one highlighted.
4//
5// The dialog's props carry no answer callback (RenderPropsOf.AskUserQuestion is
6// `tool`, `questions`, `metadataSource`), so a tree of the plugin's own cannot
7// answer the question. The card is drawn ABOVE the engine's own control
8// (`next(e)`'s element, kept whole), which still takes the answer.
9
10import type { EngineInterface, RenderElement, RenderInput } from 'claude-code'
11import type { Interview, InterviewOption } from './lib/interview'
12
13/** The card for `interviews` above `engine`, the dialog's own drawing. */
14export function drawInterview(
15 $: EngineInterface,
16 e: RenderInput<'AskUserQuestion'>,
17 interviews: readonly Interview[],
18 engine: RenderElement,
19): RenderElement {
20 const { Box, Text } = $.ui.resolve(e)
21 const option = (o: InterviewOption): RenderElement =>
22 Box({
23 flexDirection: 'column',
24 children: [
25 o.isRecommended
26 ? Text({ bold: true, color: 'success', children: `★ ${o.label} (recommended)` })
27 : Text({ children: `• ${o.label}` }),
28 o.description === '' ? null : Text({ dimColor: true, children: ` ${o.description}` }),
29 o.pros.map(p => Text({ color: 'success', children: ` + ${p}` })),
30 o.cons.map(c => Text({ color: 'error', children: ` − ${c}` })),
31 ],
32 })
33 const card = (q: Interview): RenderElement =>
34 Box({
35 flexDirection: 'column',
36 marginBottom: 1,
37 children: [
38 Text({ bold: true, children: q.question }),
39 q.description === '' ? null : Text({ dimColor: true, children: q.description }),
40 q.options.map(option),
41 ],
42 })
43 return Box({ flexDirection: 'column', children: [interviews.map(card), engine] })
44}
45hooks/drift.ts 46 lines1// The drift line (option `planBand`): once per main-loop turn that edited a
2// file while the session's plan phase is In progress (or was picked in the
3// terminal with /phase), one `$.model.classify` asks whether
4// the turn stayed on the phase. `off-phase` is reported to the daemon and
5// drawn as one line beneath the answer. register.ts calls it from its one
6// turn.complete hook; a subagent's turn never reaches it.
7
8import type { EngineInterface } from 'claude-code'
9import { DRIFT_LABELS, DRIFT_TIMEOUT_MS, driftInput, driftLine, driftReason, isDriftWatched } from './lib/plan'
10import { type PlanAccess, type Planner, bounded, postPlan } from './plan'
11
12/**
13 * The drift line for turn `turnId`, or undefined: no plan, a phase that is
14 * neither In progress nor picked in the terminal, no edit, a turn
15 * already classified, a label other than `off-phase`, or a classification
16 * that failed or ran past DRIFT_TIMEOUT_MS. Never rejects.
17 */
18export async function checkDrift($: EngineInterface, planner: Planner, access: PlanAccess, turnId: string, answer: string): Promise<string | undefined> {
19 const turn = planner.turn
20 const view = planner.view
21 if (turn === undefined || turn.turnId !== turnId || turn.isClassified || turn.edits.length === 0) return undefined
22 if (view === undefined || access.token === undefined || !isDriftWatched(view)) return undefined
23 planner.turn = { ...turn, isClassified: true }
24 let label: string | undefined
25 try {
26 const asked = $.model.classify(driftInput(view.phase, answer, turn.edits), DRIFT_LABELS).then(
27 (l): string | undefined => l,
28 (): string | undefined => undefined,
29 )
30 const reply = await bounded($, asked, DRIFT_TIMEOUT_MS)
31 label = reply === 'timeout' ? undefined : reply
32 } catch {
33 return undefined
34 }
35 if (label !== 'off-phase') return undefined
36 const reason = driftReason(turn.edits)
37 void postPlan($, planner, access, 'drift', {
38 session: access.sessionId,
39 taskId: view.taskId,
40 phaseId: view.phase.id,
41 verdict: label,
42 reason,
43 })
44 return driftLine(view.phase.n, reason)
45}
46hooks/lib/interview.ts 73 lines1// Interview-style AskUserQuestion questions. Pure: tells a question asked in
2// the dashboard interview's shape (internal/planning/prompt.go: a JSON
3// `{"type":"question","data":{…}}` as the question's text or description)
4// apart from a plain question, and reads it into what the card draws. Nothing
5// else makes a question an interview: Claude Code's own AskUserQuestion
6// guidance has the model mark an option "(Recommended)" and weigh pros and
7// cons in plain questions too, and those keep the engine's standard dialog.
8
9export type InterviewOption = {
10 readonly label: string
11 readonly description: string
12 readonly pros: readonly string[]
13 readonly cons: readonly string[]
14 readonly isRecommended: boolean
15}
16
17export type Interview = {
18 readonly question: string
19 readonly description: string
20 readonly options: readonly InterviewOption[]
21}
22
23const isRecord = (v: unknown): v is Readonly<Record<string, unknown>> => typeof v === 'object' && v !== null && !Array.isArray(v)
24const str = (v: unknown): string => (typeof v === 'string' ? v.trim() : '')
25const strings = (v: unknown): readonly string[] =>
26 Array.isArray(v) ? v.map(str).filter(s => s !== '') : typeof v === 'string' && v.trim() !== '' ? [v.trim()] : []
27
28/** The dashboard interview's JSON, from a question's text (a ```json fence allowed), or undefined. */
29const interviewJson = (text: string): Readonly<Record<string, unknown>> | undefined => {
30 const body = text
31 .trim()
32 .replace(/^```(?:json)?\s*/i, '')
33 .replace(/```\s*$/, '')
34 .trim()
35 if (!body.startsWith('{')) return undefined
36 try {
37 const raw: unknown = JSON.parse(body)
38 return isRecord(raw) && raw.type === 'question' && isRecord(raw.data) ? raw.data : undefined
39 } catch {
40 return undefined
41 }
42}
43
44const fromJson = (data: Readonly<Record<string, unknown>>): Interview | undefined => {
45 const question = str(data.question)
46 if (question === '') return undefined
47 const options = (Array.isArray(data.options) ? data.options : [])
48 .filter(isRecord)
49 .filter(o => o.isOther !== true)
50 .map(
51 (o): InterviewOption => ({
52 label: str(o.label),
53 description: str(o.description),
54 pros: strings(o.pros),
55 cons: strings(o.cons),
56 isRecommended: o.recommended === true,
57 }),
58 )
59 .filter(o => o.label !== '')
60 return { question, description: str(data.description), options }
61}
62
63/** One AskUserQuestion question read as an interview, or undefined for a plain one. */
64export const parseInterview = (question: unknown): Interview | undefined => {
65 if (!isRecord(question)) return undefined
66 const json = interviewJson(str(question.question)) ?? interviewJson(str(question.description))
67 return json === undefined ? undefined : fromJson(json)
68}
69
70/** The interview questions of a dialog; empty when every one is plain. */
71export const interviewsOf = (questions: readonly unknown[]): readonly Interview[] =>
72 questions.map(parseInterview).filter((q): q is Interview => q !== undefined)
73hooks/lib/plan.ts 279 lines1// The plan band's decisions. Pure: parses the daemon's plan view, builds the
2// plan requests, lays the band and the /phase checklist out, picks what a tick
3// offers, and builds the drift classification's input and its line. The `$`
4// calls are made in ../plan.ts.
5// Contract: GET/POST /api/link/plan* (tools/swarmery, phase 7).
6
7import { FILE_TOOLS, normalizePath } from './forecast'
8
9/** Every plan request gives up after this long (raced against a `$.clock` timer). */
10export const PLAN_TIMEOUT_MS = 5_000
11/** The cache is refreshed this often while the band is on. */
12export const PLAN_REFRESH_MS = 60_000
13/** The drift classification gives up after this long. */
14export const DRIFT_TIMEOUT_MS = 15_000
15/** How much of the turn's answer (its tail, in characters) the classification reads. */
16export const DRIFT_ANSWER_LIMIT = 2_048
17/** The drift line's reason is cut to this many characters. */
18export const DRIFT_REASON_LIMIT = 120
19/** The whole drift line, its `↯ … phase N:` lead included, is cut to this many characters. */
20export const DRIFT_LINE_LIMIT = 120
21/** The view's `phase.status` of a phase that is running (the Plans page's chip). */
22export const PHASE_IN_PROGRESS = 'In progress'
23/** The labels the drift classification picks from. */
24export const DRIFT_LABELS = ['on-phase', 'adjacent', 'off-phase'] as const
25/** At most this many criteria rows in the band. */
26export const BAND_CRITERIA_ROWS = 3
27/** The width the band is laid out in when the surface measured none. */
28export const DEFAULT_COLUMNS = 80
29/** The id of the pane /phase opens. */
30export const PLAN_PANE_ID = 'swarmery-plan'
31/** `$.ui.ask` takes 2-4 option labels. */
32const ASK_OPTIONS_MAX = 4
33/** An ask label keeps this much of a criterion's text. */
34const ASK_LABEL_LIMIT = 60
35
36export type CriterionClass = '' | 'land' | 'manual'
37
38export type PlanCriterion = {
39 readonly idx: number
40 readonly text: string
41 readonly done: boolean
42 readonly class: CriterionClass
43}
44
45export type PlanPhase = {
46 readonly id: string
47 readonly n: number
48 readonly title: string
49 readonly status: string
50 readonly done: number
51 readonly total: number
52 readonly criteria: readonly PlanCriterion[]
53}
54
55export type PlanNext = { readonly id: string; readonly n: number; readonly title: string }
56
57/** The daemon's PlanView: the session's plan and its running phase. */
58export type PlanView = {
59 readonly taskId: string
60 readonly title: string
61 readonly url: string
62 readonly chosenBy: 'terminal' | 'auto'
63 readonly phase: PlanPhase
64 readonly next: PlanNext | null
65}
66
67const isRecord = (v: unknown): v is Readonly<Record<string, unknown>> => typeof v === 'object' && v !== null && !Array.isArray(v)
68const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
69const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
70
71const parseCriterion = (v: unknown): PlanCriterion | undefined => {
72 if (!isRecord(v)) return undefined
73 const idx = num(v.idx)
74 const text = str(v.text)
75 if (idx === undefined || text === undefined) return undefined
76 const cls = v.class === 'land' || v.class === 'manual' ? v.class : ''
77 return { idx, text, done: v.done === true, class: cls }
78}
79
80const parseNext = (v: unknown): PlanNext | null => {
81 if (!isRecord(v)) return null
82 const id = str(v.id)
83 const n = num(v.n)
84 return id === undefined || n === undefined ? null : { id, n, title: str(v.title) ?? '' }
85}
86
87/** A PlanView from the daemon's JSON text, or undefined when it is not one. */
88export const parsePlanView = (text: unknown): PlanView | undefined => {
89 if (typeof text !== 'string' || text.trim() === '') return undefined
90 let raw: unknown
91 try {
92 raw = JSON.parse(text)
93 } catch {
94 return undefined
95 }
96 if (!isRecord(raw) || !isRecord(raw.phase)) return undefined
97 const taskId = str(raw.taskId)
98 const phase = raw.phase
99 const id = str(phase.id)
100 const n = num(phase.n)
101 if (taskId === undefined || id === undefined || n === undefined) return undefined
102 const criteria = (Array.isArray(phase.criteria) ? phase.criteria : [])
103 .map(parseCriterion)
104 .filter((c): c is PlanCriterion => c !== undefined)
105 return {
106 taskId,
107 title: str(raw.title) ?? taskId,
108 url: str(raw.url) ?? '',
109 chosenBy: raw.chosenBy === 'terminal' ? 'terminal' : 'auto',
110 phase: {
111 id,
112 n,
113 title: str(phase.title) ?? '',
114 status: str(phase.status) ?? '',
115 done: num(phase.done) ?? criteria.filter(c => c.done).length,
116 total: num(phase.total) ?? criteria.length,
117 criteria,
118 },
119 next: parseNext(raw.next),
120 }
121}
122
123/** Whether two views draw the same: a refresh that changed nothing redraws nothing. */
124export const isSameView = (a: PlanView | undefined, b: PlanView | undefined): boolean =>
125 JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
126
127/** GET /api/link/plan for this session and cwd. */
128export const planUrl = (origin: string, sessionId: string, cwd: string): string =>
129 `${origin}/api/link/plan?session=${encodeURIComponent(sessionId)}&cwd=${encodeURIComponent(cwd)}`
130
131export type PlanAction = 'select' | 'tick' | 'run' | 'drift'
132
133/** POST /api/link/plan/<action>. */
134export const planActionUrl = (origin: string, action: PlanAction): string => `${origin}/api/link/plan/${action}`
135
136export type PlanGet = { readonly method: 'GET' }
137
138/** The plan read; signedFetch (../signed.ts) adds its signature. */
139export const planGetRequest = (): PlanGet => ({ method: 'GET' })
140
141/** The plan's dashboard URL, absolute: a path the daemon gave is put under its origin. */
142export const absoluteUrl = (url: string, origin: string): string => (url.startsWith('/') ? `${origin}${url}` : url)
143
144/** The daemon's `error` text from a JSON reply body, or the status. */
145export const replyError = (status: number | undefined, text: string | undefined): string => {
146 try {
147 const body: unknown = JSON.parse(text ?? '')
148 if (isRecord(body) && typeof body.error === 'string' && body.error.trim() !== '') return body.error.trim().slice(0, 200)
149 } catch {
150 // not JSON: the status says it
151 }
152 return status === undefined ? 'the daemon did not answer' : `HTTP ${status}`
153}
154
155/** `text` cut to `max` characters, the cut marked with an ellipsis. */
156export const truncate = (text: string, max: number): string => {
157 const one = text.replace(/\s+/g, ' ').trim()
158 if (max <= 0) return ''
159 return one.length <= max ? one : `${one.slice(0, Math.max(0, max - 1))}…`
160}
161
162/** `☑` or `☐`, the mark of a criterion. */
163export const mark = (c: PlanCriterion): string => (c.done ? '☑' : '☐')
164
165/** The band's and the pane's first line. */
166export const headerLine = (phase: PlanPhase): string => `Phase ${phase.n} — ${phase.title} · ${phase.done}/${phase.total}`
167
168export type BandLayout = {
169 readonly header: string
170 readonly rows: readonly string[]
171 readonly hasNext: boolean
172 readonly hasOpen: boolean
173}
174
175/**
176 * What the band draws in `maxRows` rows of `columns` cells: the header, up to
177 * three criteria (the open ones first, the done ones filling what is left)
178 * and the button row. A band of fewer than three rows draws the header and
179 * the buttons alone.
180 */
181export const bandLayout = (view: PlanView, maxRows: number, columns: number): BandLayout => {
182 const width = columns > 0 ? columns : DEFAULT_COLUMNS
183 const room = Math.max(0, Math.min(BAND_CRITERIA_ROWS, Math.floor(maxRows) - 2))
184 const open = view.phase.criteria.filter(c => !c.done)
185 const done = view.phase.criteria.filter(c => c.done)
186 const shown = [...open, ...done].slice(0, room)
187 return {
188 header: truncate(headerLine(view.phase), width),
189 rows: shown.map(c => truncate(`${mark(c)} ${c.text}`, width)),
190 hasNext: view.next !== null,
191 hasOpen: open.length > 0,
192 }
193}
194
195/** The plan's line in the checklist: its title and task id. */
196export const titleLine = (view: PlanView): string => `${view.title} (${view.taskId})`
197
198/** The phase's line in the checklist: the header and the phase's status. */
199export const statusLine = (phase: PlanPhase): string => `${headerLine(phase)}${phase.status === '' ? '' : ` · ${phase.status}`}`
200
201/** One criterion in the checklist, its class (`[LAND]`, `[MANUAL]`) after it. */
202export const criterionLine = (c: PlanCriterion): string => `${mark(c)} ${c.text}${c.class === '' ? '' : ` [${c.class.toUpperCase()}]`}`
203
204export const nextLine = (view: PlanView): string =>
205 view.next === null ? 'next: none (last phase)' : `next: Phase ${view.next.n} — ${view.next.title}`
206
207/** The /phase checklist as text: the command's output where no pane is placed. */
208export const checklistLines = (view: PlanView, origin: string): readonly string[] => [
209 titleLine(view),
210 statusLine(view.phase),
211 ...view.phase.criteria.map(criterionLine),
212 nextLine(view),
213 ...(view.url === '' ? [] : [absoluteUrl(view.url, origin)]),
214]
215
216export const NO_PLAN_TEXT = 'no active plan for this session (pick one with /phase <task-id>)'
217
218/** What a tick offers: the open criteria, each under a label unique within the ask. */
219export type TickChoice = { readonly label: string; readonly idx: number }
220
221export const tickChoices = (view: PlanView): readonly TickChoice[] =>
222 view.phase.criteria
223 .filter(c => !c.done)
224 .slice(0, ASK_OPTIONS_MAX)
225 .map(c => ({ label: `${c.idx}. ${truncate(c.text, ASK_LABEL_LIMIT)}`, idx: c.idx }))
226
227/** Whether a call of `tool` edits a file (Edit, Write, MultiEdit, NotebookEdit). */
228export const isEditTool = (tool: string): boolean => FILE_TOOLS[tool] !== undefined
229
230/** The path a main-loop edit call names, relative to `cwd`, or undefined. */
231export const editedPath = (tool: string, fields: Readonly<Record<string, unknown>>, cwd: string): string | undefined => {
232 const field = FILE_TOOLS[tool]
233 const target = field === undefined ? undefined : fields[field]
234 return typeof target === 'string' && target.trim() !== '' ? normalizePath(target, cwd) : undefined
235}
236
237/** The running turn as the drift check sees it: its id, the files it edited, whether it was classified. */
238export type DriftTurn = {
239 readonly turnId: string
240 readonly edits: readonly string[]
241 readonly isClassified: boolean
242}
243
244export const noteEdit = (turn: DriftTurn | undefined, path: string): DriftTurn | undefined =>
245 turn === undefined || turn.edits.includes(path) ? turn : { ...turn, edits: [...turn.edits, path] }
246
247/**
248 * The classification's input: the phase and its open criteria for context,
249 * the files the turn edited, and the tail of its answer. `$.model.classify`
250 * takes no context of its own, so it rides in the text.
251 */
252export const driftInput = (phase: PlanPhase, answer: string, edits: readonly string[]): string => {
253 const open = phase.criteria.filter(c => !c.done).map(c => `- ${truncate(c.text, 200)}`)
254 return [
255 `Running plan phase ${phase.n}: ${phase.title}`,
256 'Open acceptance criteria:',
257 ...(open.length === 0 ? ['- (none)'] : open.slice(0, 12)),
258 'Files this turn edited:',
259 ...edits.slice(0, 30).map(p => `- ${p}`),
260 'The end of the turn\'s answer:',
261 answer.slice(-DRIFT_ANSWER_LIMIT),
262 'Label whether this turn\'s work is on this phase, adjacent to it, or off it.',
263 ].join('\n')
264}
265
266/** Why the turn looks off-phase: `classify` names a label alone, so the edited files say it. */
267export const driftReason = (edits: readonly string[]): string => truncate(`edited ${edits.join(', ')}`, DRIFT_REASON_LIMIT)
268
269/** The drift line, cut as a whole to DRIFT_LINE_LIMIT characters. */
270export const driftLine = (n: number, reason: string): string => truncate(`↯ this turn looks outside phase ${n}: ${reason}`, DRIFT_LINE_LIMIT)
271
272/**
273 * Whether a turn's edits are held against the view's phase: only a phase that
274 * is running, or one the person picked in the terminal. An automatic view can
275 * land on a Pending or Blocked phase (the first not Done), and no work is
276 * "off" a phase nobody has started.
277 */
278export const isDriftWatched = (view: PlanView): boolean => view.phase.status === PHASE_IN_PROGRESS || view.chosenBy === 'terminal'
279hooks/plan.ts 330 lines1// The plan band (option `planBand`): the session's running plan phase above
2// the prompt, `/phase`, and the requests behind them. Every function here that
3// takes `$` is a top-level declaration, as the engine requires; register.ts
4// wires them to its hooks and nothing here registers a hook.
5//
6// A render never fetches: the band and the pane draw from `planner.view`,
7// which only the refreshes (session.start, each main-loop turn.complete,
8// /phase, a button's request, the 60 s timer) write. A write that changed what
9// is drawn redraws with `$.ui.invalidate('ui.render')`.
10
11import type { CommandRunResult, EngineInterface, RenderElement, RenderInput, Timer, UiPressArgument } from 'claude-code'
12import { linkRequest } from './lib/client'
13import {
14 type DriftTurn,
15 NO_PLAN_TEXT,
16 PLAN_PANE_ID,
17 PLAN_REFRESH_MS,
18 PLAN_TIMEOUT_MS,
19 type PlanAction,
20 type PlanView,
21 absoluteUrl,
22 bandLayout,
23 checklistLines,
24 criterionLine,
25 headerLine,
26 isSameView,
27 nextLine,
28 parsePlanView,
29 planActionUrl,
30 planGetRequest,
31 planUrl,
32 replyError,
33 statusLine,
34 tickChoices,
35 titleLine,
36 truncate,
37} from './lib/plan'
38import { type LinkInit, signedFetch } from './signed'
39
40/** What the plan requests read of the link: its token, session and cwd, and whether it is off. */
41export type PlanAccess = {
42 readonly token: string | undefined
43 readonly sessionId: string
44 readonly cwd: string
45 readonly isOff: boolean
46}
47
48/** The band's state for one load of the module. Exists only with `planBand` on. */
49export type Planner = {
50 readonly origin: string
51 /** The session's plan as the daemon last answered it; undefined: draw nothing. */
52 view: PlanView | undefined
53 /** Bumped by every write of `view`: a GET started under an older one is dropped. */
54 version: number
55 /** The 60 s refresh, while the band has a token. */
56 timer: Timer | undefined
57 /** The running main-loop turn, for the drift check. */
58 turn: DriftTurn | undefined
59}
60
61export const newPlanner = (origin: string): Planner => ({ origin, view: undefined, version: 0, timer: undefined, turn: undefined })
62
63export type PlanReply = { readonly status?: number; readonly text?: string; readonly error?: unknown }
64
65const START_LABEL = 'Start it'
66const TICK_LABEL = 'Tick it'
67
68/** `pending`, or `'timeout'` once `ms` pass on `$.clock` (the same race as register.ts's `within`). */
69export async function bounded<T>($: EngineInterface, pending: Promise<T>, ms: number): Promise<T | 'timeout'> {
70 let guard: Timer | undefined
71 const timeout = new Promise<'timeout'>(resolve => {
72 try {
73 guard = $.clock.after(ms, () => resolve('timeout'))
74 } catch {
75 // no timer: the pending work alone decides
76 }
77 })
78 try {
79 return await Promise.race([pending, timeout])
80 } finally {
81 guard?.cancel()
82 }
83}
84
85/** One signed plan request, bounded by PLAN_TIMEOUT_MS. Never rejects. */
86async function planFetch($: EngineInterface, key: string, url: string, init: LinkInit): Promise<PlanReply> {
87 try {
88 const request = signedFetch($, key, url, init).then(
89 (r): PlanReply => ({ status: r.status, text: r.text }),
90 (error: unknown): PlanReply => ({ error }),
91 )
92 const reply = await bounded($, request, PLAN_TIMEOUT_MS)
93 return reply === 'timeout' ? { error: 'timeout' } : reply
94 } catch (error) {
95 return { error }
96 }
97}
98
99/** Writes the cache; redraws only when what is drawn changed. */
100export function setView($: EngineInterface, planner: Planner, view: PlanView | undefined): void {
101 planner.version += 1
102 if (isSameView(planner.view, view)) return
103 planner.view = view
104 try {
105 $.ui.invalidate('ui.render')
106 } catch {
107 // the next draw picks it up
108 }
109}
110
111const canRequest = (access: PlanAccess): boolean => access.token !== undefined && !access.isOff && access.sessionId !== ''
112
113/**
114 * Reads the session's plan into the cache: a 200 view, else nothing (204, no
115 * token, the daemon down or slow). A reply that lands after another write of
116 * the cache, or after the session id moved, is dropped. Never rejects.
117 */
118export async function refreshPlan($: EngineInterface, planner: Planner, access: PlanAccess): Promise<void> {
119 if (!canRequest(access)) {
120 setView($, planner, undefined)
121 return
122 }
123 const version = planner.version
124 const sessionId = access.sessionId
125 const reply = await planFetch($, access.token ?? '', planUrl(planner.origin, sessionId, access.cwd), planGetRequest())
126 if (planner.version !== version || access.sessionId !== sessionId) return
127 setView($, planner, reply.status === 200 ? parsePlanView(reply.text) : undefined)
128}
129
130/** POSTs `body` to /api/link/plan/<action>. Never rejects. */
131export async function postPlan($: EngineInterface, planner: Planner, access: PlanAccess, action: PlanAction, body: object): Promise<PlanReply> {
132 if (!canRequest(access)) return { error: 'no token' }
133 return planFetch($, access.token ?? '', planActionUrl(planner.origin, action), linkRequest(JSON.stringify(body)))
134}
135
136/** Starts the 60 s refresh once; it runs until stopPlanTimer. */
137export function startPlanTimer($: EngineInterface, planner: Planner, access: PlanAccess): void {
138 if (planner.timer !== undefined || !canRequest(access)) return
139 try {
140 planner.timer = $.clock.every(PLAN_REFRESH_MS, () => {
141 void refreshPlan($, planner, access)
142 })
143 } catch {
144 planner.timer = undefined
145 }
146}
147
148export const stopPlanTimer = (planner: Planner): void => {
149 planner.timer?.cancel()
150 planner.timer = undefined
151}
152
153/** Declares `/phase [task-id]` for the session. */
154export async function registerPlanCommand($: EngineInterface): Promise<void> {
155 try {
156 await $.command.register({
157 name: 'phase',
158 description: 'Show this session\'s swarmery plan phase and its checklist; /phase <task-id> picks the plan',
159 argumentHint: '[task-id]',
160 })
161 } catch {
162 // no command: the band still draws
163 }
164}
165
166function toast($: EngineInterface, text: string): void {
167 try {
168 $.ui.toast(text)
169 } catch {
170 // a toast is a courtesy
171 }
172}
173
174/**
175 * `/phase [task-id]`, answered without a model turn: with an argument the
176 * daemon selects that plan for the session first; then the cache is read
177 * again and the checklist opens in a pane, or is the command's output where
178 * no pane is placed.
179 */
180export async function runPlanCommand($: EngineInterface, planner: Planner, access: PlanAccess, args: string | undefined): Promise<CommandRunResult> {
181 if (access.token === undefined) return { text: 'swarmery-link: no daemon token (~/.swarmery/link-token); /phase needs the swarmery daemon' }
182 const taskId = (args ?? '').trim().split(/\s+/)[0] ?? ''
183 if (taskId !== '') {
184 const reply = await postPlan($, planner, access, 'select', { session: access.sessionId, cwd: access.cwd, taskId })
185 if (reply.status !== 200) return { text: `swarmery-link: could not select ${taskId}: ${replyError(reply.status, reply.text)}` }
186 const selected = parsePlanView(reply.text)
187 if (selected !== undefined) setView($, planner, selected)
188 else await refreshPlan($, planner, access)
189 } else {
190 await refreshPlan($, planner, access)
191 }
192 const view = planner.view
193 if (view === undefined) return { text: NO_PLAN_TEXT }
194 let isPlaced = false
195 try {
196 const opened = await $.ui.open({ id: PLAN_PANE_ID, title: 'Plan', rows: Math.min(20, view.phase.criteria.length + 6) })
197 isPlaced = opened.isPlaced
198 } catch {
199 // no pane: the checklist is the output
200 }
201 return { text: isPlaced ? `${headerLine(view.phase)} (checklist in the Plan pane)` : checklistLines(view, planner.origin).join('\n') }
202}
203
204/** [1] next phase: asks first, then has the daemon start the next phase. */
205export async function pressNext($: EngineInterface, planner: Planner, access: PlanAccess): Promise<void> {
206 const view = planner.view
207 const next = view?.next ?? null
208 if (view === undefined || next === null) return
209 let answer: string
210 try {
211 answer = await $.ui.ask(`Start phase ${next.n} — ${truncate(next.title, 60)} now?`, { options: [START_LABEL, 'Not now'], header: 'Plan' })
212 } catch {
213 return
214 }
215 if (answer !== START_LABEL) return
216 const reply = await postPlan($, planner, access, 'run', { session: access.sessionId, cwd: access.cwd, taskId: view.taskId, phaseId: next.id })
217 const isStarted = reply.status !== undefined && reply.status >= 200 && reply.status < 300
218 toast($, isStarted ? `phase ${next.n} started` : `could not start phase ${next.n}: ${replyError(reply.status, reply.text)}`)
219 await refreshPlan($, planner, access)
220}
221
222/** [2] open in Swarmery: no call opens a browser, so the URL goes to the clipboard of the surface pressed on. */
223export async function pressOpen($: EngineInterface, planner: Planner, press: UiPressArgument): Promise<void> {
224 const view = planner.view
225 if (view === undefined || view.url === '') return
226 const url = absoluteUrl(view.url, planner.origin)
227 let isCopied = false
228 try {
229 isCopied = (await $.ui.copy({ text: url, surface: press.surface })).isCopied
230 } catch {
231 // shown instead
232 }
233 toast($, isCopied ? `copied ${url}` : `open ${url}`)
234}
235
236/** [3] tick: picks an open criterion, then has the daemon tick it in the phase doc. */
237export async function pressTick($: EngineInterface, planner: Planner, access: PlanAccess): Promise<void> {
238 const view = planner.view
239 if (view === undefined) return
240 const choices = tickChoices(view)
241 const only = choices[0]
242 if (only === undefined) {
243 toast($, `phase ${view.phase.n}: nothing left to tick`)
244 return
245 }
246 let idx: number | undefined
247 try {
248 if (choices.length === 1) {
249 const answer = await $.ui.ask(`Tick "${only.label}"?`, { options: [TICK_LABEL, 'Cancel'], header: 'Tick' })
250 idx = answer === TICK_LABEL ? only.idx : undefined
251 } else {
252 const answer = await $.ui.ask(`Which criterion of phase ${view.phase.n} is done?`, { options: choices.map(c => c.label), header: 'Tick' })
253 idx = choices.find(c => c.label === answer)?.idx
254 }
255 } catch {
256 return
257 }
258 if (idx === undefined) return
259 // The drawn text rides along: the daemon answers 409 when the doc's idx-th
260 // criterion no longer reads so, instead of ticking whatever moved there.
261 const text = view.phase.criteria.find(c => c.idx === idx)?.text
262 const reply = await postPlan($, planner, access, 'tick', {
263 session: access.sessionId,
264 cwd: access.cwd,
265 taskId: view.taskId,
266 phaseId: view.phase.id,
267 idx,
268 text,
269 done: true,
270 })
271 if (reply.status === 200) {
272 const ticked = parsePlanView(reply.text)
273 if (ticked !== undefined) setView($, planner, ticked)
274 else await refreshPlan($, planner, access)
275 return
276 }
277 if (reply.status === 409) {
278 await refreshPlan($, planner, access)
279 toast($, 'the phase doc changed since the band drew it: refreshed, tick again')
280 return
281 }
282 toast($, `could not tick: ${replyError(reply.status, reply.text)}`)
283}
284
285/**
286 * The band above the prompt, from the cache alone; undefined (draw the
287 * engine's) with no plan or while a survey holds the band.
288 */
289export function drawBand($: EngineInterface, planner: Planner, access: PlanAccess, e: RenderInput<'AbovePrompt'>): RenderElement | undefined {
290 const view = planner.view
291 if (view === undefined || e.props.hasSurvey) return undefined
292 const layout = bandLayout(view, e.props.maxRows, e.props.bodyColumns || (e.viewport?.columns ?? 0))
293 const { Box, Text, Button } = $.ui.resolve(e)
294 return Box({
295 flexDirection: 'column',
296 children: [
297 Text({ bold: true, wrap: 'truncate-end', children: layout.header }),
298 layout.rows.map(row => Text({ wrap: 'truncate-end', dimColor: row.startsWith('☑'), children: row })),
299 Box({
300 flexDirection: 'row',
301 gap: 2,
302 children: [
303 layout.hasNext
304 ? Button({ key: 'plan-next', label: 'next phase', hotkey: '1', plain: true, onPress: () => void pressNext($, planner, access) })
305 : null,
306 Button({ key: 'plan-open', label: 'open in Swarmery', hotkey: '2', plain: true, onPress: press => void pressOpen($, planner, press) }),
307 Button({ key: 'plan-tick', label: 'tick', hotkey: '3', plain: true, onPress: () => void pressTick($, planner, access) }),
308 ],
309 }),
310 ],
311 })
312}
313
314/** The Plan pane /phase opens: the whole checklist, from the cache alone. */
315export function drawPane($: EngineInterface, planner: Planner, e: RenderInput<'Pane'>): RenderElement {
316 const { Box, Text, Link } = $.ui.resolve(e)
317 const view = planner.view
318 if (view === undefined) return Text({ dimColor: true, children: NO_PLAN_TEXT })
319 return Box({
320 flexDirection: 'column',
321 children: [
322 Text({ bold: true, children: titleLine(view) }),
323 Text({ children: statusLine(view.phase) }),
324 view.phase.criteria.map(c => Text({ dimColor: c.done, children: criterionLine(c) })),
325 Text({ dimColor: true, children: nextLine(view) }),
326 view.url === '' ? null : Link({ href: absoluteUrl(view.url, planner.origin), label: 'open in Swarmery' }),
327 ],
328 })
329}
330hooks/lib/client.ts 95 lines1// The link client's decisions. Pure: builds the request and turns a response
2// into what the queue does next. The `$.http.fetch` call itself is made in
3// register.ts, where every `$` call is spelled.
4// Contract: tools/swarmery/docs/mods-link-protocol.md.
5
6export const DEFAULT_DAEMON_URL = 'http://127.0.0.1:7777'
7export const EVENTS_PATH = '/api/link/events'
8
9/** How long a request may run before the queue treats it as failed. */
10export const REQUEST_TIMEOUT_MS = 5_000
11/** session.end's whole wall-clock bound is 1.5 s; the final flush keeps inside it. */
12export const END_FLUSH_TIMEOUT_MS = 1_200
13/** The periodic flush. */
14export const FLUSH_EVERY_MS = 2_000
15/** After a 401, the one retry waits past the daemon's 1 s token re-read throttle. */
16export const AUTH_RETRY_MS = 1_100
17
18/**
19 * A loopback http origin: scheme, one of the three loopback hosts, an optional
20 * port, then nothing or a path/query/fragment (dropped). No userinfo, no other
21 * host, no https: the signed requests go nowhere else.
22 */
23const LOOPBACK_ORIGIN = /^http:\/\/(127\.0\.0\.1|\[::1\]|localhost)(?::(\d{1,5}))?(?:[/?#].*)?$/i
24
25export type DaemonEndpoint = {
26 /** The daemon's loopback origin, no path: the command channel's URLs hang off it. */
27 readonly origin: string
28 /** Where events are POSTed. */
29 readonly url: string
30 /** A daemonUrl was configured but is not a loopback http origin, so the default is used. */
31 readonly isRefused: boolean
32}
33
34/** The events endpoint under the configured loopback origin; the default origin for anything else. */
35export const daemonEndpoint = (daemonUrl: unknown): DaemonEndpoint => {
36 const fallback: DaemonEndpoint = { origin: DEFAULT_DAEMON_URL, url: `${DEFAULT_DAEMON_URL}${EVENTS_PATH}`, isRefused: false }
37 if (daemonUrl === undefined || daemonUrl === null) return fallback
38 const raw = typeof daemonUrl === 'string' ? daemonUrl.trim() : undefined
39 if (raw === '') return fallback
40 const match = raw === undefined ? null : LOOPBACK_ORIGIN.exec(raw)
41 const host = match?.[1]?.toLowerCase()
42 const port = match?.[2] === undefined ? undefined : Number(match[2])
43 if (host === undefined || (port !== undefined && (port < 1 || port > 65_535))) return { ...fallback, isRefused: true }
44 const origin = `http://${host}${port === undefined ? '' : `:${port}`}`
45 return { origin, url: `${origin}${EVENTS_PATH}`, isRefused: false }
46}
47
48export type LinkRequest = {
49 readonly method: 'POST'
50 readonly headers: Record<string, string>
51 readonly body: string
52}
53
54/** A POST of `body`; signedFetch (../signed.ts) adds its signature, so no credential is in it. */
55export const linkRequest = (body: string): LinkRequest => ({
56 method: 'POST',
57 headers: { 'content-type': 'application/json' },
58 body,
59})
60
61/**
62 * What a response means for the queue:
63 * - `sent`: the batch was processed (202); drop it, rejected events included.
64 * - `auth`: 401; re-read the token once and retry once, past the throttle.
65 * - `off`: 503 link disabled; the link is off for this session.
66 * - `discard`: a request the daemon will never take (400, 403, 413 and other
67 * 4xx); drop the batch, log once.
68 * - `retry`: 5xx, a timeout or no answer; keep the batch for the next flush.
69 */
70export type Outcome = 'sent' | 'auth' | 'off' | 'discard' | 'retry'
71
72export const outcome = (status: number | undefined): Outcome => {
73 if (status === undefined) return 'retry'
74 if (status >= 200 && status < 300) return 'sent'
75 if (status === 401) return 'auth'
76 if (status === 503) return 'off'
77 if (status >= 400 && status < 500) return 'discard'
78 return 'retry'
79}
80
81/** The token file's text as a bearer credential, or undefined when it holds none. */
82export const parseToken = (text: unknown): string | undefined => {
83 if (typeof text !== 'string') return undefined
84 const token = text.trim()
85 return token === '' || /\s/.test(token) ? undefined : token
86}
87
88/** A one-line reason for the log, never the token or a request body. */
89export const describeFailure = (status: number | undefined, error: unknown): string => {
90 if (status !== undefined) return `HTTP ${status}`
91 if (error === 'timeout') return `no answer in ${REQUEST_TIMEOUT_MS / 1000}s`
92 const text = error instanceof Error ? error.message : String(error)
93 return text.split('\n')[0]?.slice(0, 160) ?? 'unknown error'
94}
95hooks/lib/control.ts 186 lines1// The command channel's decisions. Pure: builds the poll and ack requests,
2// reads a command out of a reply, decides what to do with it, and keeps the
3// set of commands already executed. Every `$` call (fetch, clock, turn.abort,
4// prompt.submit) is made in register.ts.
5// Contract: tools/swarmery/docs/mods-link-protocol.md, "Commands".
6
7export const COMMANDS_PATH = '/api/link/commands'
8/** How long the daemon may hold a poll open (it clamps anything above 25). */
9export const POLL_WAIT_S = 25
10/** A poll's own bound, past the daemon's 25 s hold: HttpInit has no timeout. */
11export const POLL_TIMEOUT_MS = 28_000
12/** After a failed poll (no answer, a 5xx, an unreadable reply). */
13export const FAILURE_BACKOFF_MS = 3_000
14/** Two polls that came back empty start at least this far apart. */
15export const MIN_POLL_GAP_MS = 1_000
16/** `$.prompt.submit` resolves as its turn starts; past this, the prompt is left queued. */
17export const PROMPT_START_TIMEOUT_MS = 10_000
18/** The exact ack message the daemon reads as "deliver again after the next turn.complete". */
19export const TURN_IN_PROGRESS = 'turn in progress'
20/** The daemon keeps an ack message up to 500 characters. */
21export const MAX_ACK_MESSAGE = 500
22/** Executed ids remembered for re-delivery, newest kept. */
23export const MAX_REMEMBERED = 200
24
25export const commandsUrl = (origin: string, sessionId: string): string =>
26 `${origin}${COMMANDS_PATH}?session=${encodeURIComponent(sessionId)}&wait=${POLL_WAIT_S}`
27
28export const ackUrl = (origin: string, id: string): string => `${origin}${COMMANDS_PATH}/${encodeURIComponent(id)}/ack`
29
30export type PollRequest = {
31 readonly method: 'GET'
32}
33
34/** A poll; signedFetch (../signed.ts) adds its signature. */
35export const pollRequest = (): PollRequest => ({ method: 'GET' })
36
37/**
38 * What a poll's reply means for the loop (a 200 the daemon did not sign is a
39 * `retry` in register.ts, never a command):
40 * - `command`: 200, a command to execute and ack, then poll again at once.
41 * - `idle`: 204, nothing deliverable; poll again.
42 * - `auth`: 401; re-read the token once, else stop.
43 * - `off`: 503 link disabled; stop.
44 * - `retry`: anything else, a timeout or no answer; back off, then poll again.
45 */
46export type PollOutcome = 'command' | 'idle' | 'auth' | 'off' | 'retry'
47
48export const pollOutcome = (status: number | undefined): PollOutcome => {
49 if (status === 200) return 'command'
50 if (status === 204) return 'idle'
51 if (status === 401) return 'auth'
52 if (status === 503) return 'off'
53 return 'retry'
54}
55
56/** How long to wait before the next poll, given how the last one ended and how long it took. */
57export const nextPollDelay = (outcome: 'command' | 'idle' | 'retry', elapsedMs: number): number => {
58 if (outcome === 'command') return 0
59 if (outcome === 'retry') return FAILURE_BACKOFF_MS
60 return Math.max(0, MIN_POLL_GAP_MS - Math.max(0, elapsedMs))
61}
62
63export type Command =
64 | { readonly id: string; readonly kind: 'stop' }
65 | { readonly id: string; readonly kind: 'prompt'; readonly text: string; readonly asUser: boolean }
66 | { readonly id: string; readonly kind: 'message'; readonly to: string; readonly text: string }
67 | { readonly id: string; readonly kind: 'invalid'; readonly reason: string }
68
69const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
70 typeof value === 'object' && value !== null && !Array.isArray(value)
71
72const commandId = (value: unknown): string | undefined => {
73 if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return String(value)
74 if (typeof value === 'string' && /^[1-9]\d{0,18}$/.test(value)) return value
75 return undefined
76}
77
78/**
79 * The command a 200 carries, or undefined when the reply names no id to ack
80 * (the loop then backs off as on a failure). A command it cannot run comes
81 * back `invalid`, to be acked failed.
82 */
83export const parseCommand = (text: unknown): Command | undefined => {
84 if (typeof text !== 'string') return undefined
85 let body: unknown
86 try {
87 body = JSON.parse(text)
88 } catch {
89 return undefined
90 }
91 if (!isRecord(body)) return undefined
92 const id = commandId(body.id)
93 if (id === undefined) return undefined
94 const payload = isRecord(body.payload) ? body.payload : {}
95 if (body.kind === 'stop') return { id, kind: 'stop' }
96 if (body.kind === 'prompt') {
97 const text = payload.text
98 if (typeof text !== 'string' || text.trim() === '') return { id, kind: 'invalid', reason: 'prompt without text' }
99 return { id, kind: 'prompt', text, asUser: payload.asUser === true }
100 }
101 if (body.kind === 'message') {
102 const { to, text } = payload
103 if (typeof to !== 'string' || to.trim() === '') return { id, kind: 'invalid', reason: 'message without a recipient' }
104 if (typeof text !== 'string' || text.trim() === '') return { id, kind: 'invalid', reason: 'message without text' }
105 return { id, kind: 'message', to: to.trim(), text }
106 }
107 return { id, kind: 'invalid', reason: `unknown command kind: ${String(body.kind).slice(0, 40)}` }
108}
109
110export type Ack = { readonly result: 'done' | 'failed'; readonly message?: string }
111
112export const done = (message?: string): Ack => (message === undefined ? { result: 'done' } : { result: 'done', message })
113export const failed = (message: string): Ack => ({ result: 'failed', message })
114
115export const ackBody = (ack: Ack): string =>
116 JSON.stringify(ack.message === undefined ? { result: ack.result } : { result: ack.result, message: ack.message.slice(0, MAX_ACK_MESSAGE) })
117
118/** The executed commands by id, with the ack each got: a re-delivery is acked the same, never run again. */
119export type Executed = ReadonlyMap<string, Ack>
120
121/**
122 * Records `ack` under `id`, keeping the newest MAX_REMEMBERED. A prompt
123 * refused for a running turn is not recorded: the daemon delivers it again
124 * after the turn, and then it runs.
125 */
126export const remember = (executed: Executed, id: string, ack: Ack): Executed => {
127 if (ack.result === 'failed' && ack.message === TURN_IN_PROGRESS) return executed
128 const next = new Map(executed)
129 next.delete(id)
130 next.set(id, ack)
131 const extra = next.size - MAX_REMEMBERED
132 if (extra > 0) for (const old of [...next.keys()].slice(0, extra)) next.delete(old)
133 return next
134}
135
136export type Action =
137 | { readonly do: 'ack'; readonly ack: Ack }
138 | { readonly do: 'abort'; readonly turnId: string }
139 | { readonly do: 'submit'; readonly text: string; readonly asUser: boolean }
140 | { readonly do: 'message'; readonly to: string; readonly text: string }
141
142/** The ack for a `message` command while the `swarm` option is off. */
143export const SWARM_OFF = 'swarm option is off'
144
145/**
146 * What to do with a delivered command, given the commands already executed,
147 * the main loop's running turn (`turn.start`'s id, until its
148 * `turn.complete`), and whether the `swarm` option is on. A `message` is sent
149 * whether or not a turn runs: it lands in the recipient's queue, not this one.
150 */
151export const decide = (command: Command, executed: Executed, runningTurnId: string | undefined, isSwarmOn = false): Action => {
152 const previous = executed.get(command.id)
153 if (previous !== undefined) return { do: 'ack', ack: previous }
154 switch (command.kind) {
155 case 'invalid':
156 return { do: 'ack', ack: failed(command.reason) }
157 case 'message':
158 return isSwarmOn ? { do: 'message', to: command.to, text: command.text } : { do: 'ack', ack: failed(SWARM_OFF) }
159 case 'stop':
160 return runningTurnId === undefined ? { do: 'ack', ack: done('no turn running') } : { do: 'abort', turnId: runningTurnId }
161 case 'prompt':
162 return runningTurnId === undefined
163 ? { do: 'submit', text: command.text, asUser: command.asUser }
164 : { do: 'ack', ack: failed(TURN_IN_PROGRESS) }
165 }
166}
167
168/** A one-line, bounded reason for an ack or a log line. */
169export const shortError = (error: unknown): string => {
170 const text = error instanceof Error ? error.message : String(error)
171 return (text.split('\n')[0] ?? '').slice(0, 160) || 'unknown error'
172}
173
174/** Whether a rejected `$.prompt.submit` says a turn is running. */
175export const isTurnRunning = (error: unknown): boolean =>
176 /\bturn\b.*\b(running|in progress|active|busy)\b|\bnot idle\b|\bbusy\b/i.test(shortError(error))
177
178/** The ack for a `$.prompt.submit` that rejected. */
179export const submitFailure = (error: unknown): Ack => (isTurnRunning(error) ? failed(TURN_IN_PROGRESS) : failed(shortError(error)))
180
181/** The ack for a `$.session.send` that delivered nothing. */
182export const undeliverable = (reason: string): Ack => failed(`undeliverable: ${shortError(reason)}`)
183
184/** The ack for a `$.prompt.submit` a hook answered with `{ drop }`: the same rule, the reason marked as a drop. */
185export const dropAck = (reason: string): Ack => (isTurnRunning(reason) ? failed(TURN_IN_PROGRESS) : failed(`dropped: ${shortError(reason)}`))
186hooks/lib/forecast.ts 351 lines1// The turn forecast loop (option `forecast`). Pure: every function takes the
2// loop's state or a raw value and returns the next state or a payload. The
3// `$` calls (the model call, the push into the sensor queue) are spelled in
4// register.ts. The wire shapes are the link protocol's `turn.forecast` and
5// `turn.actual` (tools/swarmery/docs/mods-link-protocol.md): paths and numbers
6// only, never prompt text, tool input or model reply text.
7
8/** The model asked: an alias the engine resolves like `--model`. */
9export const FORECAST_MODEL = 'haiku'
10/** The reply's token cap: a forecast is one short JSON object. */
11export const FORECAST_MAX_TOKENS = 300
12/** The model call's own time limit; past it the call resolves `aborted`. */
13export const FORECAST_TIMEOUT_MS = 20_000
14/** The most of the user's text the model is shown. */
15export const PROMPT_TEXT_LIMIT = 2_000
16/** Completed turns whose touched files the model is shown. */
17export const HISTORY_TURNS = 3
18/** The daemon's limits on `files`. */
19export const MAX_FILES = 50
20export const MAX_PATH = 300
21/** Random base36 characters after a run id's time: enough that two loads in the same millisecond differ. */
22export const RUN_ID_RANDOM = 6
23
24/** A Bash command that runs tests (the protocol's pattern). */
25export const TEST_COMMAND = /\b(test|vitest|jest|go test|pytest|cargo test|npm (run )?test)\b/
26
27/** Tools whose input names the file they write, and the field that names it. */
28export const FILE_TOOLS: Readonly<Record<string, string>> = {
29 Edit: 'file_path',
30 Write: 'file_path',
31 MultiEdit: 'file_path',
32 NotebookEdit: 'notebook_path',
33}
34
35/** What the model claimed about the coming turn; null where it made no claim. */
36export type Claims = {
37 readonly files: readonly string[]
38 readonly testsPass: boolean | null
39 readonly steps: number | null
40 readonly confidence: number | null
41}
42
43export const NO_CLAIMS: Claims = { files: [], testsPass: null, steps: null, confidence: null }
44
45/** What the main loop did this turn, from its tool calls. */
46export type Journal = {
47 readonly files: readonly string[]
48 readonly testsRan: boolean
49 readonly testsPass: boolean | null
50 readonly steps: number
51}
52
53export const EMPTY_JOURNAL: Journal = { files: [], testsRan: false, testsPass: null, steps: 0 }
54
55/** The loop's state for one load of the module. */
56export type ForecastState = {
57 /**
58 * Names this run of the turn counter; renewed with every reset (session.start,
59 * a /clear, an in-process resume). A `--resume` keeps the session id and counts
60 * from 1 again, so the daemon keys a turn on (session, runId, turnSeq).
61 * '' before the first reset: no turn is forecast without one.
62 */
63 readonly runId: string
64 /** The main loop's turn count since the run started. */
65 readonly turnSeq: number
66 /** Bumped on every reset, so a forecast in flight from before it does not reopen the gate. */
67 readonly generation: number
68 /** The running main-loop turn's id; undefined between turns. */
69 readonly turnId: string | undefined
70 /** This turn asked the model, so its actual is sent. */
71 readonly isForecasted: boolean
72 /** A forecast call is still in flight: the next turn is not forecast. */
73 readonly isOpen: boolean
74 readonly journal: Journal
75 /** Files touched per completed turn, newest last, at most HISTORY_TURNS. */
76 readonly history: ReadonlyArray<readonly string[]>
77}
78
79export const INITIAL_FORECAST: ForecastState = {
80 runId: '',
81 turnSeq: 0,
82 generation: 0,
83 turnId: undefined,
84 isForecasted: false,
85 isOpen: false,
86 journal: EMPTY_JOURNAL,
87 history: [],
88}
89
90/**
91 * The state after session.start, a session.end with reason `clear`, or the
92 * resync after an in-process resume: numbering starts over under `runId`.
93 */
94export const resetForecast = (state: ForecastState, runId: string): ForecastState => ({
95 ...INITIAL_FORECAST,
96 runId,
97 generation: state.generation + 1,
98})
99
100/**
101 * A run id: the reset's time in ms since the epoch, then `-` and RUN_ID_RANDOM
102 * base36 characters drawn from `random` when there is a random source, the
103 * time alone when there is none. Always within the daemon's
104 * `[A-Za-z0-9._:-]{1,64}`.
105 */
106export const runIdOf = (nowMs: number, random: Uint8Array | undefined): string => {
107 const ms = Number.isFinite(nowMs) && nowMs >= 0 ? Math.floor(nowMs) : 0
108 const time = String(ms)
109 if (random === undefined || random.length < RUN_ID_RANDOM) return time
110 const tail = Array.from(random.subarray(0, RUN_ID_RANDOM), b => (b % 36).toString(36)).join('')
111 return `${time}-${tail}`
112}
113
114/**
115 * Whether a turn's text was typed by the person: empty text (a continuation)
116 * and the forms a command or a notification arrives in are not.
117 */
118export const isUserText = (text: string): boolean => {
119 const t = text.trim()
120 return t !== '' && !/^(\/|<(command-|local-command|task-notification|system-reminder))/.test(t)
121}
122
123/** The state at a main-loop turn.start, and whether to ask the model for this turn. */
124export const startTurn = (
125 state: ForecastState,
126 turnId: string,
127 text: string,
128 canSend: boolean,
129): { readonly state: ForecastState; readonly shouldAsk: boolean } => {
130 const shouldAsk = canSend && state.runId !== '' && !state.isOpen && isUserText(text)
131 return {
132 shouldAsk,
133 state: {
134 ...state,
135 turnSeq: state.turnSeq + 1,
136 turnId,
137 isForecasted: shouldAsk,
138 isOpen: state.isOpen || shouldAsk,
139 journal: EMPTY_JOURNAL,
140 },
141 }
142}
143
144/** The state once the forecast call of `generation` settled. */
145export const closeForecast = (state: ForecastState, generation: number): ForecastState =>
146 state.generation === generation ? { ...state, isOpen: false } : state
147
148/**
149 * The state at the main loop's turn.complete, and the turn.actual payload when
150 * the turn was forecast. The actual carries the run the turn started in: a
151 * reset between start and complete clears `turnId`, so no actual is built
152 * across one.
153 */
154export const endTurn = (
155 state: ForecastState,
156 turnId: string,
157): { readonly state: ForecastState; readonly actual: Readonly<Record<string, unknown>> | undefined } => {
158 if (state.turnId === undefined || state.turnId !== turnId) return { state, actual: undefined }
159 const { journal } = state
160 const actual = state.isForecasted
161 ? { runId: state.runId, turnSeq: state.turnSeq, files: journal.files, testsRan: journal.testsRan, testsPass: journal.testsPass, steps: journal.steps }
162 : undefined
163 return {
164 actual,
165 state: {
166 ...state,
167 turnId: undefined,
168 isForecasted: false,
169 journal: EMPTY_JOURNAL,
170 history: [...state.history, journal.files].slice(-HISTORY_TURNS),
171 },
172 }
173}
174
175/** `path` with `./`, duplicate and trailing separators gone, relative to `cwd` when under it. */
176export const normalizePath = (path: string, cwd: string): string => {
177 const clean = (p: string): string =>
178 p
179 .trim()
180 .replace(/\/{2,}/g, '/')
181 .replace(/^(\.\/)+/, '')
182 .replace(/(.)\/$/, '$1')
183 const p = clean(path)
184 const root = clean(cwd)
185 return root !== '' && root !== '/' && p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p
186}
187
188/**
189 * Whether `p` can stand on the wire as a path: one token of at most MAX_PATH
190 * characters naming a directory or an extension. A model that echoes prose
191 * into `files` has it dropped here, so prompt text never rides along.
192 */
193const isWirePath = (p: string): boolean =>
194 p.length > 0 && p.length <= MAX_PATH && !/[\s\u0000-\u001f<>"'`|;]/.test(p) && /[./]/.test(p)
195
196/** The paths added to `files` in order, each once, valid ones only, at most MAX_FILES. */
197const addFiles = (files: readonly string[], more: readonly string[]): readonly string[] => {
198 const out = [...files]
199 for (const p of more) {
200 if (out.length >= MAX_FILES) break
201 if (isWirePath(p) && !out.includes(p)) out.push(p)
202 }
203 return out
204}
205
206/** A tool call as the journal reads it: the tool, its loop, and the input fields it may name. */
207export type ToolCallFacts = {
208 readonly tool: string
209 readonly agentId?: string | undefined
210 readonly fields: Readonly<Record<string, unknown>>
211}
212
213/** How the call ended, from `next(e)`'s result. */
214export type ToolOutcome = 'ok' | 'error' | 'denied'
215
216/**
217 * The journal after one tool call of the running turn ended with `outcome`.
218 * A subagent's call (agentId present), or a call outside a turn, leaves it as
219 * it was. Every main-loop call is a step; a file counts once its write
220 * succeeded; a test command run in the foreground sets testsRan and testsPass
221 * (the last one wins: a red run fixed later in the turn reads as passing).
222 */
223export const noteToolCall = (state: ForecastState, call: ToolCallFacts, outcome: ToolOutcome, cwd: string): ForecastState => {
224 if (state.turnId === undefined || call.agentId !== undefined) return state
225 let journal: Journal = { ...state.journal, steps: state.journal.steps + 1 }
226 const field = FILE_TOOLS[call.tool]
227 const target = field === undefined ? undefined : call.fields[field]
228 if (typeof target === 'string' && outcome === 'ok') {
229 journal = { ...journal, files: addFiles(journal.files, [normalizePath(target, cwd)]) }
230 }
231 const command = call.tool === 'Bash' ? call.fields.command : undefined
232 if (typeof command === 'string' && TEST_COMMAND.test(command) && outcome !== 'denied') {
233 const isBackground = call.fields.run_in_background === true
234 journal = { ...journal, testsRan: true, testsPass: isBackground ? journal.testsPass : outcome === 'ok' }
235 }
236 return { ...state, journal }
237}
238
239/** The model's request: a short fixed instruction, the user's text and the files of the last turns. */
240export const forecastRequest = (text: string, history: ReadonlyArray<readonly string[]>): { readonly system: string; readonly prompt: string } => {
241 const recent = [...new Set(history.flat())]
242 const shown = text.length > PROMPT_TEXT_LIMIT ? `${text.slice(0, PROMPT_TEXT_LIMIT)}…` : text
243 return {
244 system: [
245 'You forecast what a coding agent will do while it answers the request below.',
246 'Reply with one JSON object and nothing else:',
247 '{"files": [paths it will create or edit, relative to the repository root], "testsPass": true | false | null (null when it will not run tests),',
248 '"steps": number of tool calls it will make, "confidence": 0..1 that the forecast is right}.',
249 ].join(' '),
250 prompt: [
251 'Request:',
252 shown,
253 '',
254 'Files edited in the previous turns:',
255 recent.length > 0 ? recent.map(p => `- ${p}`).join('\n') : '(none)',
256 ].join('\n'),
257 }
258}
259
260/** The first balanced `{...}` in `text`, strings respected; undefined when there is none. */
261const firstObject = (text: string): string | undefined => {
262 const start = text.indexOf('{')
263 if (start < 0) return undefined
264 let depth = 0
265 let inString = false
266 let escaped = false
267 for (let i = start; i < text.length; i += 1) {
268 const c = text[i]
269 if (inString) {
270 if (escaped) escaped = false
271 else if (c === '\\') escaped = true
272 else if (c === '"') inString = false
273 continue
274 }
275 if (c === '"') inString = true
276 else if (c === '{') depth += 1
277 else if (c === '}') {
278 depth -= 1
279 if (depth === 0) return text.slice(start, i + 1)
280 }
281 }
282 return undefined
283}
284
285const isRecord = (v: unknown): v is Readonly<Record<string, unknown>> => typeof v === 'object' && v !== null && !Array.isArray(v)
286
287/**
288 * The claims in a model reply: the first JSON object in it, each field held to
289 * the protocol's limits; a field out of shape is null, a reply with no
290 * readable object is NO_CLAIMS.
291 */
292export const parseForecast = (reply: string | undefined, cwd: string): Claims => {
293 const raw = reply === undefined ? undefined : firstObject(reply)
294 if (raw === undefined) return NO_CLAIMS
295 let value: unknown
296 try {
297 value = JSON.parse(raw)
298 } catch {
299 return NO_CLAIMS
300 }
301 if (!isRecord(value)) return NO_CLAIMS
302 const files = Array.isArray(value.files)
303 ? addFiles(
304 [],
305 value.files.filter((f): f is string => typeof f === 'string').map(f => normalizePath(f, cwd)),
306 )
307 : []
308 const steps = typeof value.steps === 'number' && Number.isFinite(value.steps) ? Math.max(0, Math.round(value.steps)) : null
309 const confidence =
310 typeof value.confidence === 'number' && Number.isFinite(value.confidence) ? Math.min(1, Math.max(0, value.confidence)) : null
311 return {
312 files,
313 testsPass: typeof value.testsPass === 'boolean' ? value.testsPass : null,
314 steps,
315 confidence,
316 }
317}
318
319/** The four token counts of a model call, as ModelUsage spells them. */
320export type TokenUsage = {
321 readonly input_tokens: number
322 readonly output_tokens: number
323 readonly cache_read_input_tokens: number
324 readonly cache_creation_input_tokens: number
325}
326
327/** Every token the call was billed for, input (cached or not) and output; null when the reply carried no usage. */
328export const usageTokens = (usage: TokenUsage | undefined): number | null => {
329 if (usage === undefined) return null
330 const sum = usage.input_tokens + usage.output_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
331 return Number.isFinite(sum) && sum >= 0 ? Math.round(sum) : null
332}
333
334/** The turn.forecast payload; `runId` is the run the forecast turn started in. */
335export const forecastPayload = (
336 runId: string,
337 turnSeq: number,
338 claims: Claims,
339 model: string,
340 forecastTokens: number | null,
341): Readonly<Record<string, unknown>> => ({
342 runId,
343 turnSeq,
344 files: claims.files,
345 testsPass: claims.testsPass,
346 steps: claims.steps,
347 confidence: claims.confidence,
348 model: model.slice(0, 80),
349 forecastTokens,
350})
351hooks/lib/hash.ts 58 lines1// The tool-call input hash. Pure: takes a value, returns its digest. The link
2// sends this in place of the input, which never leaves the session
3// (mods-link-protocol.md, "tool.call carries no input").
4
5/** Hex digits kept of a digest: 64 bits, enough to match two calls, too few to search. */
6export const HASH_HEX = 16
7
8const isRecord = (v: unknown): v is Readonly<Record<string, unknown>> =>
9 typeof v === 'object' && v !== null && !Array.isArray(v)
10
11/** JSON with object keys sorted at every depth, so equal inputs hash equal. */
12export const canonicalJson = (value: unknown): string => {
13 if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
14 if (isRecord(value)) {
15 const fields = Object.keys(value)
16 .filter(k => value[k] !== undefined)
17 .sort()
18 .map(k => `${JSON.stringify(k)}:${canonicalJson(value[k])}`)
19 return `{${fields.join(',')}}`
20 }
21 const text = JSON.stringify(value)
22 return text === undefined ? 'null' : text
23}
24
25const toHex = (bytes: Uint8Array): string => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
26
27/** FNV-1a, 64 bits, as 16 hex digits: the fallback where `crypto.subtle` is missing. */
28export const fnv1a64 = (text: string): string => {
29 const bytes = new TextEncoder().encode(text)
30 let hash = 0xcbf29ce484222325n
31 for (const b of bytes) {
32 hash ^= BigInt(b)
33 hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn
34 }
35 return hash.toString(16).padStart(16, '0')
36}
37
38/** `HASH_HEX` hex digits of SHA-256 over the canonical JSON, FNV-1a where SHA-256 is unavailable. */
39export const inputHash = async (input: unknown): Promise<string> => {
40 const text = canonicalJson(input)
41 try {
42 const subtle = typeof crypto === 'undefined' ? undefined : crypto.subtle
43 if (subtle !== undefined) {
44 const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text))
45 return toHex(new Uint8Array(digest)).slice(0, HASH_HEX)
46 }
47 } catch {
48 // fall through to the pure hash
49 }
50 return fnv1a64(text).slice(0, HASH_HEX)
51}
52
53/** The tool's arguments alone: the envelope fields the engine spreads beside them removed. */
54export const toolInput = (e: Readonly<Record<string, unknown>>): Record<string, unknown> => {
55 const { tool: _tool, tool_use_id: _id, agentId: _agent, requestMeta: _meta, ...args } = e
56 return args
57}
58hooks/lib/queue.ts 94 lines1// The outgoing event queue. Pure: every function takes the queue's state and
2// returns the next one. The wire shape and limits are the link protocol's
3// (tools/swarmery/docs/mods-link-protocol.md, POST /api/link/events).
4
5export type LinkKind =
6 | 'session.start'
7 | 'turn.start'
8 | 'tool.call'
9 | 'session.measure'
10 | 'turn.complete'
11 | 'session.end'
12 | 'turn.forecast'
13 | 'turn.actual'
14 | 'session.send'
15 | 'session.receive'
16 | 'claim'
17 | 'release'
18 | 'conflict'
19
20export type LinkEvent = {
21 readonly sessionId: string
22 readonly cwd: string
23 readonly kind: LinkKind
24 /** RFC 3339, ms, UTC. Never rewritten once stamped: a resend carries the same `at`. */
25 readonly at: string
26 readonly payload?: Readonly<Record<string, unknown>>
27}
28
29/** Events a batch may carry, and the most the queue holds while the daemon is away. */
30export const MAX_EVENTS = 200
31/** The daemon's body limit is 1 MiB; a batch stays under it with room for the envelope. */
32export const MAX_BODY_BYTES = 1_000_000
33
34/** The last `at` (epoch ms) stamped per kind. */
35export type Stamps = Readonly<Partial<Record<LinkKind, number>>>
36
37/**
38 * The event's time: `now`, or one millisecond past the last event of the same
39 * kind when `now` does not move past it. The daemon's dedup key is
40 * (session, kind, at), so two distinct events of a kind must never share an `at`.
41 */
42export const stamp = (stamps: Stamps, kind: LinkKind, now: number): { readonly at: string; readonly stamps: Stamps } => {
43 const last = stamps[kind]
44 const ms = last !== undefined && now <= last ? last + 1 : now
45 return { at: new Date(ms).toISOString(), stamps: { ...stamps, [kind]: ms } }
46}
47
48const key = (e: LinkEvent): string => `${e.kind}\u0000${e.at}`
49
50/**
51 * The queue with `event` appended: an event already queued under the same
52 * (kind, at) is not queued twice, and past `cap` the oldest events are dropped.
53 */
54export const enqueue = (queue: readonly LinkEvent[], event: LinkEvent, cap: number = MAX_EVENTS): readonly LinkEvent[] => {
55 if (queue.some(q => key(q) === key(event))) return queue
56 const next = [...queue, event]
57 return next.length > cap ? next.slice(next.length - cap) : next
58}
59
60/** The queue without the events of `sent` (a batch the daemon answered), matched by (kind, at). */
61export const drop = (queue: readonly LinkEvent[], sent: readonly LinkEvent[]): readonly LinkEvent[] => {
62 const gone = new Set(sent.map(key))
63 return queue.filter(e => !gone.has(key(e)))
64}
65
66const bytes = (text: string): number => new TextEncoder().encode(text).length
67
68/**
69 * The next batch, oldest first: at most `MAX_EVENTS` events and a body under
70 * `MAX_BODY_BYTES`. An event too large to send alone is skipped (it can never
71 * be accepted) and returned in `oversized` so the caller can drop it.
72 */
73export const takeBatch = (
74 queue: readonly LinkEvent[],
75): { readonly batch: readonly LinkEvent[]; readonly body: string; readonly oversized: readonly LinkEvent[] } => {
76 const batch: LinkEvent[] = []
77 const oversized: LinkEvent[] = []
78 const envelope = bytes('{"events":[]}')
79 let size = envelope
80 for (const event of queue) {
81 if (batch.length >= MAX_EVENTS) break
82 const one = bytes(JSON.stringify(event))
83 if (envelope + one > MAX_BODY_BYTES) {
84 oversized.push(event)
85 continue
86 }
87 const added = one + (batch.length > 0 ? 1 : 0)
88 if (size + added > MAX_BODY_BYTES) break
89 batch.push(event)
90 size += added
91 }
92 return { batch, body: JSON.stringify({ events: batch }), oversized }
93}
94