@ulm0/gonogo 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -2
  3. package/bin/gonogo.js +18 -0
  4. package/dist/client/THIRD-PARTY-NOTICES.md +409 -0
  5. package/dist/client/apple-touch-icon.png +0 -0
  6. package/dist/client/assets/doto-latin-900-normal-D1bF_x6I.woff +0 -0
  7. package/dist/client/assets/geist-latin-400-normal-B40WzpMT.woff2 +0 -0
  8. package/dist/client/assets/geist-latin-400-normal-akEymXtG.woff +0 -0
  9. package/dist/client/assets/geist-latin-500-normal-BDXIbFrL.woff +0 -0
  10. package/dist/client/assets/geist-latin-500-normal-CTWBw9NS.woff2 +0 -0
  11. package/dist/client/assets/geist-latin-600-normal-CSETrqM2.woff2 +0 -0
  12. package/dist/client/assets/geist-latin-600-normal-DsPlZH-9.woff +0 -0
  13. package/dist/client/assets/geist-mono-latin-400-normal-B2yvC1Cq.woff +0 -0
  14. package/dist/client/assets/geist-mono-latin-400-normal-DTRLJnHl.woff2 +0 -0
  15. package/dist/client/assets/geist-mono-latin-500-normal-D-GG86Jb.woff +0 -0
  16. package/dist/client/assets/geist-mono-latin-500-normal-YINYabwD.woff2 +0 -0
  17. package/dist/client/assets/geist-mono-latin-600-normal-V-KvD_pi.woff2 +0 -0
  18. package/dist/client/assets/geist-mono-latin-600-normal-bZn07FKM.woff +0 -0
  19. package/dist/client/assets/index-B6MsSoeo.css +1 -0
  20. package/dist/client/assets/index-DRtiRh1Y.js +31 -0
  21. package/dist/client/favicon.ico +0 -0
  22. package/dist/client/favicon.svg +1 -0
  23. package/dist/client/index.html +19 -0
  24. package/dist/server/cleanroom.js +214 -0
  25. package/dist/server/cli.js +630 -0
  26. package/dist/server/command.js +44 -0
  27. package/dist/server/constants.js +427 -0
  28. package/dist/server/docking.js +541 -0
  29. package/dist/server/downlink.js +191 -0
  30. package/dist/server/home.js +497 -0
  31. package/dist/server/hooks.js +166 -0
  32. package/dist/server/hub.js +2484 -0
  33. package/dist/server/launcher.js +542 -0
  34. package/dist/server/livery.js +210 -0
  35. package/dist/server/logsearch.js +112 -0
  36. package/dist/server/mcp.js +196 -0
  37. package/dist/server/migrate.js +119 -0
  38. package/dist/server/missionlog.js +209 -0
  39. package/dist/server/payload.js +168 -0
  40. package/dist/server/propellant.js +314 -0
  41. package/dist/server/providers.js +137 -0
  42. package/dist/server/relay.js +300 -0
  43. package/dist/server/relaykinds.js +182 -0
  44. package/dist/server/schedules.js +277 -0
  45. package/dist/server/tasks.js +272 -0
  46. package/dist/server/terminal.js +635 -0
  47. package/dist/server/uplinks.js +356 -0
  48. package/dist/server/web.js +1466 -0
  49. package/dist/shared/cron.js +149 -0
  50. package/dist/shared/fuel.js +18 -0
  51. package/dist/shared/livery.js +348 -0
  52. package/dist/shared/positions.js +132 -0
  53. package/dist/shared/protocol.js +212 -0
  54. package/package.json +84 -3
@@ -0,0 +1,2484 @@
1
+ import { DOING_MAX_CHARS, HISTORY_MAX, HISTORY_WINDOW_MS, HOOK_EVENTS, PERMISSION_MODES, POLL_VOTES, PROVIDERS, providerInfo, RESERVED_NAMES, STATION_NAME_PATTERN, } from '../shared/protocol.js';
2
+ import { POSITION_IDS } from '../shared/positions.js';
3
+ import { ACTIVITY_BACKLOG, ACTIVITY_HUB_MAX, ACTIVITY_WIRE_BODY_CHARS, AGENT_NAME_PATTERN, BODY_MAX_CHARS, BOSS_DEFAULT_NAME, BOSS_ROLE, COMMAND_MAX_CHARS, CUSTOM_ACTIVE_MS, CUSTOM_START_MS, DELIVERY_COALESCE_MS, DELIVERY_SETTLE_MS, DIR_MAX_CHARS, DRAFT_EXPIRY_MS, DRAFT_SCREEN_CLEAR_MS, MAILBOX_MAX_BODY_CHARS, MAILBOX_MAX_MESSAGES, MAX_AGENTS, MAX_STOP_BLOCKS, METER_INTERVAL_MS, NEEDS_YOU_CLEAR_MS, PASTE_END, PERMISSION_SUMMARY_CHARS, POINTER_MAX_ATTEMPTS, POINTER_MAX_SENDERS, POLL_REASON_MAX_CHARS, PROMPT_SUBMIT_CONFIRM_MS, READ_MAX_CHARS, READ_MAX_MESSAGES, RECONCILE_TICK_MS, REDLINE_API_ERROR_WINDOW_MS, REDLINE_API_ERRORS, REDLINE_REPEATS, REDLINE_SEND_WINDOW_MS, REDLINE_SENDS_TO_ONE, REDLINE_TOOL_FAILURE_WINDOW_MS, REDLINE_TOOL_FAILURES, ROLE_MAX_CHARS, ROSTER_ROLE_CHARS, SCREEN_DIALOG_REASON, SEND_RATE_MAX, SEND_RATE_WINDOW_MS, SESSION_FLIP_WINDOW_MS, SESSION_IN_USE_TEXT, SESSION_MISSING_TEXT, STARTUP_DIALOG_REASON, STARTUP_READY_TIMEOUT_MS, STARTUP_RECHECK_MS, SUBJECT_MAX_CHARS, TITLE_IDLE_RECONCILE_MS, TITLE_WORKING_CONFIRM_MS, } from './constants.js';
4
+ import { parseCleanRoom } from './cleanroom.js';
5
+ import { parsePayload, payloadRefusal } from './payload.js';
6
+ /** Every request the hub rejects is one of these; web.ts maps `code` to the HTTP status (contract 3.3). */
7
+ export class HubError extends Error {
8
+ code;
9
+ field;
10
+ constructor(code, message, field) {
11
+ super(message);
12
+ this.name = 'HubError';
13
+ this.code = code;
14
+ if (field !== undefined)
15
+ this.field = field;
16
+ }
17
+ }
18
+ /* ------------------------------------------------------------------------------------------------------------
19
+ * Pure helpers (exported ones are what the unit tests call directly)
20
+ * ---------------------------------------------------------------------------------------------------------- */
21
+ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
22
+ const STATION_RE = new RegExp(STATION_NAME_PATTERN);
23
+ /** The payload of a record as text, for comparing: null when it has none. */
24
+ const payloadKey = (record) => (record.payload === undefined ? null : JSON.stringify(record.payload));
25
+ /** The Clean Room setting of a record as text, for comparing: null when the agent runs on the host. */
26
+ const cleanRoomKey = (record) => (record.cleanRoom === undefined ? null : JSON.stringify(record.cleanRoom));
27
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
28
+ const REPLY_ID_RE = /^m\d+$/;
29
+ const REPLY_ID_MAX_CHARS = 40;
30
+ const RECIPIENT_MAX_CHARS = 64;
31
+ const ESC = '\x1b';
32
+ const PERMISSION_INPUT_KEYS = ['command', 'file_path', 'path', 'url'];
33
+ /** `input requested: <message>` shows at most this much of the message (contract 4.2). */
34
+ const INPUT_REASON_CHARS = 100;
35
+ const UNREAD_STATUSES = new Set(['queued', 'held', 'delivered']);
36
+ /** Waiting to be read. A message to another station that it accepted is `delivered` for good: nobody here will read it. */
37
+ const waiting = (record) => UNREAD_STATUSES.has(record.status) && !(record.status === 'delivered' && record.to.includes('@'));
38
+ const SERVER_RESTARTED_NOTE = 'server restarted before it was read; the message went to the user';
39
+ const LOAD_LIMIT_NOTE = 'waiting: load limit';
40
+ const READ_MORE_NOTE = 'More messages are waiting: call read_messages again to read them.';
41
+ /** A tool call's input is compared up to this many characters for the loop detector. */
42
+ const REPEAT_SIG_CHARS = 2000;
43
+ /** Drops the times older than `windowMs`, adds `now`, and says how many are left. */
44
+ function countRecent(times, now, windowMs) {
45
+ while (times.length > 0 && now - (times[0] ?? now) >= windowMs)
46
+ times.shift();
47
+ times.push(now);
48
+ return times.length;
49
+ }
50
+ function isRecord(value) {
51
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
52
+ }
53
+ function errorMessage(error) {
54
+ return error instanceof Error ? error.message : String(error);
55
+ }
56
+ function isHighSurrogate(code) {
57
+ return code >= 0xd800 && code <= 0xdbff;
58
+ }
59
+ /** Cuts to `max` UTF-16 units without leaving half of a surrogate pair at the end. */
60
+ export function cutText(text, max) {
61
+ if (text.length <= max)
62
+ return text;
63
+ return text.slice(0, isHighSurrogate(text.charCodeAt(max - 1)) ? max - 1 : max);
64
+ }
65
+ // C0, DEL, C1 and bidi controls: a vote reason is shown to the Director and typed nowhere, but must stay one clean line.
66
+ const UNSAFE_IN_REASON = /[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
67
+ function collapseWhitespace(text) {
68
+ return text.replace(/\s+/g, ' ').trim();
69
+ }
70
+ /**
71
+ * The only text gonogo types into a terminal or hands to a Stop hook (contract 5.1). Callers pass at least one message.
72
+ */
73
+ export function pointerText(messages) {
74
+ const senders = [];
75
+ for (const message of messages) {
76
+ if (!senders.includes(message.from))
77
+ senders.push(message.from);
78
+ }
79
+ const names = senders.slice(0, POINTER_MAX_SENDERS).join(', ') + (senders.length > POINTER_MAX_SENDERS ? ' and others' : '');
80
+ const count = messages.length;
81
+ return `gonogo: ${count} new message${count === 1 ? '' : 's'} from ${names}. Call read_messages.`;
82
+ }
83
+ /**
84
+ * The `needs_you` reason of a permission request (contract 4.2): the tool, then the first of command, file_path, path and
85
+ * url from the tool input with whitespace collapsed. A summary longer than PERMISSION_SUMMARY_CHARS is cut and ends in `…`.
86
+ */
87
+ export function describePermission(toolName, toolInput) {
88
+ const named = typeof toolName === 'string' ? collapseWhitespace(toolName) : '';
89
+ const tool = named === '' ? 'unknown tool' : cutText(named, PERMISSION_SUMMARY_CHARS);
90
+ if (isRecord(toolInput)) {
91
+ for (const key of PERMISSION_INPUT_KEYS) {
92
+ const value = toolInput[key];
93
+ if (typeof value !== 'string')
94
+ continue;
95
+ const summary = collapseWhitespace(value);
96
+ if (summary === '')
97
+ continue;
98
+ const shown = summary.length > PERMISSION_SUMMARY_CHARS ? `${cutText(summary, PERMISSION_SUMMARY_CHARS)}…` : summary;
99
+ return `permission request: ${tool}: ${shown}`;
100
+ }
101
+ }
102
+ return `permission request: ${tool}`;
103
+ }
104
+ const PERMISSION_PREFIX = 'permission request: ';
105
+ /** `AgentView.doing`: the permission text of a tool call without its prefix, on one clean line of at most DOING_MAX_CHARS. */
106
+ export function describeDoing(toolName, toolInput) {
107
+ const text = describePermission(toolName, toolInput).slice(PERMISSION_PREFIX.length);
108
+ return cutText(collapseWhitespace(text.replace(UNSAFE_IN_REASON, ' ')), DOING_MAX_CHARS);
109
+ }
110
+ /** The changes of the last HISTORY_WINDOW_MS plus the one before them, at most HISTORY_MAX (the newest), as a copy. */
111
+ function trimHistory(history, now) {
112
+ const cutoff = now - HISTORY_WINDOW_MS;
113
+ const inside = history.findIndex((change) => change.at >= cutoff);
114
+ // Nothing inside the window: the last entry is the state at its left edge.
115
+ const first = inside === -1 ? history.length - 1 : Math.max(0, inside - 1);
116
+ return history.slice(Math.max(first, history.length - HISTORY_MAX)).map((change) => ({ ...change }));
117
+ }
118
+ function isParameterOrIntermediate(code) {
119
+ return code >= 0x20 && code <= 0x3f;
120
+ }
121
+ /**
122
+ * Reads one escape sequence that starts at `start` (a data[start] === ESC). `effect` is non-null only for a bracketed
123
+ * paste that carried text; every other sequence is something a terminal sends on its own or a key that edits nothing.
124
+ */
125
+ function scanEscape(data, start) {
126
+ const length = data.length;
127
+ if (start + 1 >= length)
128
+ return { next: length, effect: null };
129
+ const kind = data[start + 1];
130
+ if (kind === '[') {
131
+ let index = start + 2;
132
+ // X10 mouse report: ESC [ M followed by three raw bytes, which may be any printable-looking characters.
133
+ if (data[index] === 'M')
134
+ return { next: Math.min(length, index + 4), effect: null };
135
+ while (index < length && isParameterOrIntermediate(data.charCodeAt(index)))
136
+ index += 1;
137
+ if (index >= length)
138
+ return { next: length, effect: null };
139
+ const final = data.charCodeAt(index);
140
+ // A malformed sequence ends where it went wrong; the next character is read as a normal one.
141
+ if (final < 0x40 || final > 0x7e)
142
+ return { next: index, effect: null };
143
+ if (data[index] === '~' && data.slice(start + 2, index) === '200') {
144
+ const end = data.indexOf(PASTE_END, index + 1);
145
+ const content = data.slice(index + 1, end < 0 ? length : end);
146
+ return { next: end < 0 ? length : end + PASTE_END.length, effect: /\S/.test(content) ? 'set' : null };
147
+ }
148
+ return { next: index + 1, effect: null };
149
+ }
150
+ if (kind === 'O')
151
+ return { next: Math.min(length, start + 3), effect: null };
152
+ if (kind === ']') {
153
+ const bell = data.indexOf('\x07', start + 2);
154
+ const terminator = data.indexOf(`${ESC}\\`, start + 2);
155
+ if (bell >= 0 && (terminator < 0 || bell < terminator))
156
+ return { next: bell + 1, effect: null };
157
+ return { next: terminator < 0 ? length : terminator + 2, effect: null };
158
+ }
159
+ if (kind === 'P' || kind === '_' || kind === '^' || kind === 'X') {
160
+ const terminator = data.indexOf(`${ESC}\\`, start + 2);
161
+ return { next: terminator < 0 ? length : terminator + 2, effect: null };
162
+ }
163
+ // Alt-key, or ESC CR (a newline in some terminals): the pair is skipped. An astral character is one unit of input.
164
+ const code = data.codePointAt(start + 1) ?? 0;
165
+ return { next: start + 1 + (code > 0xffff ? 2 : 1), effect: null };
166
+ }
167
+ /**
168
+ * What one chunk of browser input does to the draft latch (contract 4.6): `set` for text, `clear` for Enter or Ctrl-C,
169
+ * `none` for everything a terminal or a navigation key sends. A lone Escape is `none` on purpose: it leaves the text in
170
+ * claude's box.
171
+ */
172
+ export function classifyInput(data) {
173
+ let effect = 'none';
174
+ let index = 0;
175
+ while (index < data.length) {
176
+ const char = data[index];
177
+ if (char === ESC) {
178
+ const scanned = scanEscape(data, index);
179
+ if (scanned.effect !== null)
180
+ effect = scanned.effect;
181
+ index = scanned.next;
182
+ continue;
183
+ }
184
+ const code = data.codePointAt(index) ?? 0;
185
+ index += code > 0xffff ? 2 : 1;
186
+ if (code === 0x0d || code === 0x03)
187
+ effect = 'clear';
188
+ else if (code >= 0x20 && code !== 0x7f && !(code >= 0x80 && code <= 0x9f))
189
+ effect = 'set';
190
+ }
191
+ return effect;
192
+ }
193
+ export function createHub(io, options) {
194
+ const log = io.log;
195
+ const agents = new Map();
196
+ /** Every message the hub still needs: the unread ones always, the newest ACTIVITY_HUB_MAX in any case. */
197
+ const messages = new Map();
198
+ /** Message ids, oldest first: what activity() shows. */
199
+ const order = [];
200
+ /** Names that a hire or a rename has claimed but not yet stored (their checks await the file system). */
201
+ const claimedNames = new Set();
202
+ /** Hires in flight; the record exists once the directory was checked and is saved with the roster from then on. */
203
+ const hiring = new Map();
204
+ let closing = false;
205
+ let started = null;
206
+ let shutdownPromise = null;
207
+ let sweepTimer = null;
208
+ /** T-minus and Max Q live in memory only; the signatures make a frame go out once per change. */
209
+ let pollState = null;
210
+ // Why the poll is on hold: only a hold by vote follows later votes.
211
+ let holdBy = 'vote';
212
+ let pollSeq = 0;
213
+ let pollSig = 'null';
214
+ let pollResult = '';
215
+ let limit = options.maxWorking ?? null;
216
+ let governorSig = JSON.stringify(governorView());
217
+ /* ---- small utilities ---- */
218
+ function guarded(what, fn) {
219
+ try {
220
+ fn();
221
+ }
222
+ catch (error) {
223
+ log.error(`${what} failed`, error);
224
+ }
225
+ }
226
+ function isCustom(rt) {
227
+ return rt.record.provider === 'custom';
228
+ }
229
+ /** Engine Bay: working, idle and needs_you come from hooks (Claude Code, Gemini CLI); the rest are read from output activity. */
230
+ function hooked(rt) {
231
+ return providerInfo(rt.record.provider).hooks;
232
+ }
233
+ /** Has the gonogo MCP tools, so it can be handed mail and asked to vote. */
234
+ function mailable(rt) {
235
+ return providerInfo(rt.record.provider).mcp;
236
+ }
237
+ /** The screen and title rules (prompt box, dialogs, title glyphs) are Claude Code's own. */
238
+ function isClaude(rt) {
239
+ return (rt.record.provider ?? 'claude') === 'claude';
240
+ }
241
+ function assertOpen() {
242
+ if (closing)
243
+ throw new HubError('conflict', 'the server is shutting down');
244
+ }
245
+ function screenOf(rt) {
246
+ try {
247
+ return io.screen(rt.record.name) ?? null;
248
+ }
249
+ catch (error) {
250
+ log.debug('screen probe failed', error);
251
+ return null;
252
+ }
253
+ }
254
+ function titleOf(rt) {
255
+ try {
256
+ return io.title(rt.record.name) ?? null;
257
+ }
258
+ catch (error) {
259
+ log.debug('title probe failed', error);
260
+ return null;
261
+ }
262
+ }
263
+ function outputBytesOf(rt) {
264
+ try {
265
+ return io.outputBytes(rt.record.name);
266
+ }
267
+ catch (error) {
268
+ log.debug('output probe failed', error);
269
+ return 0;
270
+ }
271
+ }
272
+ function lookup(name) {
273
+ const rt = typeof name === 'string' ? agents.get(name) : undefined;
274
+ if (!rt || rt.removed)
275
+ throw new HubError('not_found', 'unknown agent');
276
+ return rt;
277
+ }
278
+ function bossRt() {
279
+ let boss = null;
280
+ for (const rt of agents.values()) {
281
+ if (rt.record.boss && (boss === null || rt.record.desk < boss.record.desk))
282
+ boss = rt;
283
+ }
284
+ return boss;
285
+ }
286
+ function sortedAgents() {
287
+ return [...agents.values()].sort((a, b) => a.record.desk - b.record.desk || (a.record.name < b.record.name ? -1 : 1));
288
+ }
289
+ function makeRt(record) {
290
+ const now = io.now();
291
+ return {
292
+ record,
293
+ state: 'stopped',
294
+ stateSince: now,
295
+ history: [{ state: 'stopped', at: now }],
296
+ doing: null,
297
+ needsKind: null,
298
+ needsReason: null,
299
+ generation: 0,
300
+ ready: false,
301
+ transition: null,
302
+ lastBlockAt: null,
303
+ running: null,
304
+ custom: { bytes: 0, activeAt: null, since: io.now() },
305
+ flag: null,
306
+ flipAvailable: false,
307
+ draft: null,
308
+ unconfirmed: null,
309
+ pendingConfirm: null,
310
+ stopBlocks: 0,
311
+ trigger: null,
312
+ screenClearSince: null,
313
+ hooksSeen: false,
314
+ lastInputAt: 0,
315
+ pointed: new Map(),
316
+ exit: null,
317
+ exitSeen: 0,
318
+ queue: [],
319
+ sentAt: [],
320
+ limitNoted: false,
321
+ startupTimer: null,
322
+ deliveryTimer: null,
323
+ ops: [],
324
+ current: null,
325
+ draining: false,
326
+ frameHold: false,
327
+ lastSig: null,
328
+ removed: false,
329
+ redline: null,
330
+ repeat: null,
331
+ toolFailAt: [],
332
+ apiErrorAt: [],
333
+ sentTo: new Map(),
334
+ meteredAt: 0,
335
+ };
336
+ }
337
+ /* ---- frames ---- */
338
+ function emit(event) {
339
+ try {
340
+ io.emit(event);
341
+ }
342
+ catch (error) {
343
+ log.warn('emit failed', error);
344
+ }
345
+ }
346
+ function heldInfo(rt) {
347
+ if (rt.queue.length === 0)
348
+ return null;
349
+ if (rt.redline !== null)
350
+ return { kind: 'redline', text: redlineNote(rt) };
351
+ if (rt.draft)
352
+ return { kind: 'draft', text: draftNote(rt) };
353
+ if (rt.unconfirmed)
354
+ return { kind: 'unconfirmed', text: rt.unconfirmed.note };
355
+ return null;
356
+ }
357
+ function buildView(rt) {
358
+ const { record, running } = rt;
359
+ return {
360
+ name: record.name,
361
+ role: record.role,
362
+ dir: record.dir,
363
+ mode: record.mode,
364
+ desk: record.desk,
365
+ boss: record.boss,
366
+ state: rt.state,
367
+ stateSince: rt.stateSince,
368
+ needsKind: rt.needsKind,
369
+ needsReason: rt.needsReason,
370
+ transition: rt.transition,
371
+ draft: rt.draft !== null,
372
+ held: heldInfo(rt),
373
+ queued: rt.queue.length,
374
+ dirty: rt.state !== 'stopped' &&
375
+ running !== null &&
376
+ (running.role !== record.role ||
377
+ running.dir !== record.dir ||
378
+ running.mode !== record.mode ||
379
+ running.command !== (record.command ?? null) ||
380
+ running.payload !== payloadKey(record) ||
381
+ running.cleanRoom !== cleanRoomKey(record)),
382
+ generation: rt.generation,
383
+ exit: rt.exit ? { ...rt.exit } : null,
384
+ position: record.position ?? null,
385
+ provider: record.provider ?? 'claude',
386
+ command: record.command ?? null,
387
+ payload: record.payload ?? null,
388
+ cleanRoom: record.cleanRoom ?? null,
389
+ doing: rt.doing,
390
+ history: trimHistory(rt.history, io.now()),
391
+ };
392
+ }
393
+ /** Emits the agent's view when it changed since the last frame, unless a restart or spawn holds the frames back. */
394
+ function flush(rt) {
395
+ publishGovernor();
396
+ if (rt.removed || rt.frameHold)
397
+ return;
398
+ const view = buildView(rt);
399
+ const signature = JSON.stringify(view);
400
+ if (signature === rt.lastSig)
401
+ return;
402
+ rt.lastSig = signature;
403
+ emit({ t: 'agent', agent: view });
404
+ }
405
+ function toItem(record) {
406
+ const body = cutText(record.body, ACTIVITY_WIRE_BODY_CHARS);
407
+ return { ...record, body, truncated: body.length < record.body.length };
408
+ }
409
+ function persistMessage(record) {
410
+ try {
411
+ io.logMessage({ ...record });
412
+ }
413
+ catch (error) {
414
+ log.warn('could not log a message', error);
415
+ }
416
+ }
417
+ function announce(record) {
418
+ persistMessage(record);
419
+ emit({ t: 'activity', item: toItem(record) });
420
+ }
421
+ /** Changes a message's status and note; a write that changes nothing is neither logged nor emitted (contract 5.8). */
422
+ function setMessage(record, status, note) {
423
+ if (record.status === status && record.note === note)
424
+ return;
425
+ record.status = status;
426
+ record.note = note;
427
+ record.updatedAt = io.now();
428
+ announce(record);
429
+ }
430
+ function remember(record) {
431
+ messages.set(record.id, record);
432
+ order.push(record.id);
433
+ if (order.length <= ACTIVITY_HUB_MAX * 2)
434
+ return;
435
+ // Older terminal messages stay in the log only. Unread ones stay listed, because a read still needs them and, once it
436
+ // has happened, this is the only place that drops them from the map (an id that left `order` was never looked at again).
437
+ const unread = [];
438
+ for (const id of order.splice(0, order.length - ACTIVITY_HUB_MAX)) {
439
+ const old = messages.get(id);
440
+ if (old && waiting(old))
441
+ unread.push(id);
442
+ else
443
+ messages.delete(id);
444
+ }
445
+ order.unshift(...unread);
446
+ }
447
+ function sanitizeHistory(value) {
448
+ if (!isRecord(value))
449
+ return null;
450
+ const { id, from, to, subject, body, inReplyTo, hops, at, status, note, updatedAt } = value;
451
+ if (typeof id !== 'string' || typeof from !== 'string' || typeof to !== 'string')
452
+ return null;
453
+ if (typeof body !== 'string' || typeof status !== 'string')
454
+ return null;
455
+ const known = ['queued', 'held', 'delivered', 'read', 'undelivered', 'to_user'];
456
+ if (!known.includes(status))
457
+ return null;
458
+ const time = typeof at === 'number' && Number.isFinite(at) ? at : 0;
459
+ return {
460
+ id,
461
+ from,
462
+ to,
463
+ subject: typeof subject === 'string' ? subject : '',
464
+ body,
465
+ inReplyTo: typeof inReplyTo === 'string' ? inReplyTo : null,
466
+ hops: typeof hops === 'number' && Number.isFinite(hops) ? hops : 0,
467
+ at: time,
468
+ status: status,
469
+ note: typeof note === 'string' ? note : null,
470
+ updatedAt: typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? updatedAt : time,
471
+ };
472
+ }
473
+ /* ---- roster persistence ---- */
474
+ /**
475
+ * Every record, hires in flight included: two hires that overlap each save the roster, and the one saved last must not
476
+ * drop the other's agent.
477
+ */
478
+ function rosterRecords() {
479
+ const records = new Map();
480
+ for (const rt of agents.values())
481
+ records.set(rt.record.name, { ...rt.record });
482
+ for (const [name, record] of hiring) {
483
+ if (record && !records.has(name))
484
+ records.set(name, { ...record });
485
+ }
486
+ return [...records.values()].sort((a, b) => a.desk - b.desk || (a.name < b.name ? -1 : 1));
487
+ }
488
+ async function saveRecords(records) {
489
+ const file = { version: 1, agents: records.map((record) => ({ ...record })) };
490
+ try {
491
+ await io.saveRoster(file);
492
+ }
493
+ catch (error) {
494
+ log.error('could not save the roster', error);
495
+ throw new HubError('internal', `could not save the roster: ${errorMessage(error)}`);
496
+ }
497
+ }
498
+ /* ---- timers ---- */
499
+ /** A timer that does nothing once the agent has a newer generation or is gone (contract 2.1 rule 4). */
500
+ function armTimer(rt, ms, fn) {
501
+ const generation = rt.generation;
502
+ const box = { handle: undefined };
503
+ box.handle = io.setTimer(() => {
504
+ if (rt.removed || rt.generation !== generation)
505
+ return;
506
+ guarded('timer callback', () => {
507
+ fn();
508
+ flush(rt);
509
+ });
510
+ }, ms);
511
+ return box;
512
+ }
513
+ function disarm(box) {
514
+ if (box)
515
+ io.clearTimer(box.handle);
516
+ }
517
+ function armStartup(rt, ms) {
518
+ disarm(rt.startupTimer);
519
+ rt.startupTimer = armTimer(rt, ms, () => {
520
+ rt.startupTimer = null;
521
+ if (rt.ready || rt.state !== 'starting')
522
+ return;
523
+ if (outputBytesOf(rt) > 0) {
524
+ setState(rt, 'needs_you', { kind: 'startup_dialog', reason: STARTUP_DIALOG_REASON });
525
+ }
526
+ else {
527
+ armStartup(rt, STARTUP_RECHECK_MS);
528
+ }
529
+ });
530
+ }
531
+ /** The delivery check runs no later than `ms` from now; an earlier pending one is kept (contract 4.10 rule 3). */
532
+ function scheduleDelivery(rt, ms) {
533
+ const due = io.now() + ms;
534
+ if (rt.deliveryTimer && rt.deliveryTimer.due <= due)
535
+ return;
536
+ disarm(rt.deliveryTimer);
537
+ const box = armTimer(rt, ms, () => {
538
+ rt.deliveryTimer = null;
539
+ deliveryCheck(rt);
540
+ });
541
+ rt.deliveryTimer = { handle: box.handle, due };
542
+ }
543
+ function cancelConfirm(rt) {
544
+ if (rt.pendingConfirm)
545
+ disarm(rt.pendingConfirm.timer);
546
+ rt.pendingConfirm = null;
547
+ }
548
+ function cancelTimers(rt) {
549
+ disarm(rt.startupTimer);
550
+ rt.startupTimer = null;
551
+ disarm(rt.deliveryTimer);
552
+ rt.deliveryTimer = null;
553
+ cancelConfirm(rt);
554
+ }
555
+ /* ---- state ---- */
556
+ /** The one way a state changes: `stateSince` moves only when the state value does (contract 4.4). */
557
+ function setState(rt, state, needs) {
558
+ // A trip outlives whatever the hooks and the screen say, until the Director resumes or the process ends.
559
+ if (rt.redline !== null && state === 'stopped')
560
+ rt.redline = null;
561
+ if (rt.redline !== null) {
562
+ state = 'needs_you';
563
+ needs = { kind: 'redline', reason: rt.redline };
564
+ }
565
+ if (rt.state !== state) {
566
+ rt.state = state;
567
+ rt.stateSince = io.now();
568
+ rt.history = trimHistory([...rt.history, { state, at: rt.stateSince }], rt.stateSince);
569
+ rt.screenClearSince = null;
570
+ }
571
+ rt.needsKind = state === 'needs_you' && needs ? needs.kind : null;
572
+ rt.needsReason = state === 'needs_you' && needs ? needs.reason : null;
573
+ }
574
+ function markReady(rt) {
575
+ rt.ready = true;
576
+ disarm(rt.startupTimer);
577
+ rt.startupTimer = null;
578
+ setState(rt, 'idle');
579
+ if (rt.queue.length > 0)
580
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
581
+ }
582
+ /* ---- queue, notes and latches ---- */
583
+ function draftNote(rt) {
584
+ return `held: text in ${rt.record.name}'s input`;
585
+ }
586
+ function redlineNote(rt) {
587
+ return `held: redline on ${rt.record.name}`;
588
+ }
589
+ function holdNote(rt) {
590
+ if (rt.redline !== null)
591
+ return redlineNote(rt);
592
+ if (rt.draft)
593
+ return draftNote(rt);
594
+ if (rt.unconfirmed)
595
+ return rt.unconfirmed.note;
596
+ return null;
597
+ }
598
+ /** The note of a queued message for the recipient's state (contract 5.8). */
599
+ function waitNote(rt) {
600
+ const name = rt.record.name;
601
+ if (rt.transition === 'restarting')
602
+ return `waiting: ${name} is restarting`;
603
+ switch (rt.state) {
604
+ case 'working':
605
+ return `waiting: ${name} is working`;
606
+ case 'needs_you':
607
+ return `waiting: ${name} needs you`;
608
+ case 'idle':
609
+ return 'waiting: about to type the pointer';
610
+ case 'starting':
611
+ case 'stopped':
612
+ return `waiting: ${name} is starting`;
613
+ }
614
+ }
615
+ function inFlight(rt, id) {
616
+ return rt.pendingConfirm !== null && rt.pendingConfirm.ids.includes(id);
617
+ }
618
+ function queued(rt) {
619
+ const records = [];
620
+ for (const id of rt.queue) {
621
+ const record = messages.get(id);
622
+ if (record)
623
+ records.push(record);
624
+ }
625
+ return records;
626
+ }
627
+ function unreadFor(name) {
628
+ const records = [];
629
+ for (const record of messages.values()) {
630
+ if (record.to === name && UNREAD_STATUSES.has(record.status))
631
+ records.push(record);
632
+ }
633
+ return records;
634
+ }
635
+ /**
636
+ * Brings the queued messages in line with the latches: held while a latch is set, back to queued with the wait note when
637
+ * none is (contract 4.6: at once, not at the next delivery check). Messages whose pointer is already in the box are left
638
+ * alone, their pointer is on its way.
639
+ */
640
+ function syncHolds(rt) {
641
+ const hold = holdNote(rt);
642
+ for (const record of queued(rt)) {
643
+ if (inFlight(rt, record.id))
644
+ continue;
645
+ if (hold !== null)
646
+ setMessage(record, 'held', hold);
647
+ else if (record.status === 'held')
648
+ setMessage(record, 'queued', waitNote(rt));
649
+ }
650
+ }
651
+ function setWaitNotes(rt, note) {
652
+ for (const record of queued(rt)) {
653
+ if (!inFlight(rt, record.id) && record.status === 'queued')
654
+ setMessage(record, 'queued', note);
655
+ }
656
+ }
657
+ function endDraft(rt) {
658
+ rt.draft = null;
659
+ syncHolds(rt);
660
+ if (rt.queue.length > 0)
661
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
662
+ }
663
+ function expireDraft(rt, now) {
664
+ if (rt.draft && now - rt.draft.lastKeyAt >= DRAFT_EXPIRY_MS)
665
+ endDraft(rt);
666
+ }
667
+ /** The screen may end a draft latch (an emptied box) but never start one (contract 4.6). */
668
+ function screenProof(rt, now, probe) {
669
+ if (!rt.draft || !probe || !probe.promptBox || probe.promptText !== '')
670
+ return;
671
+ if (now - Math.max(rt.draft.lastKeyAt, rt.lastInputAt) >= DRAFT_SCREEN_CLEAR_MS)
672
+ endDraft(rt);
673
+ }
674
+ function undeliverUnread(rt, note) {
675
+ for (const record of unreadFor(rt.record.name))
676
+ setMessage(record, 'undelivered', note);
677
+ rt.queue = [];
678
+ rt.pointed.clear();
679
+ }
680
+ /** `delivered` messages whose turn ended unread: one more pointer, then a visible `not read` note (contract 5.5). */
681
+ function redeliver(rt) {
682
+ const name = rt.record.name;
683
+ const again = [];
684
+ for (const record of unreadFor(name)) {
685
+ if (record.status !== 'delivered')
686
+ continue;
687
+ if ((rt.pointed.get(record.id) ?? 0) < POINTER_MAX_ATTEMPTS) {
688
+ setMessage(record, 'queued', `waiting: ${name} has not read it yet`);
689
+ again.push(record.id);
690
+ }
691
+ else {
692
+ setMessage(record, 'delivered', `not read: ${name} did not read it after two pointers`);
693
+ }
694
+ }
695
+ if (again.length > 0)
696
+ rt.queue = [...again, ...rt.queue.filter((id) => !again.includes(id))];
697
+ syncHolds(rt);
698
+ }
699
+ function markDelivered(rt, ids, note) {
700
+ for (const id of ids) {
701
+ const index = rt.queue.indexOf(id);
702
+ const record = messages.get(id);
703
+ if (index < 0 || !record)
704
+ continue;
705
+ rt.queue.splice(index, 1);
706
+ rt.pointed.set(id, (rt.pointed.get(id) ?? 0) + 1);
707
+ setMessage(record, 'delivered', note);
708
+ }
709
+ }
710
+ /* ---- Max Q ---- */
711
+ function workingCount() {
712
+ let working = 0;
713
+ for (const rt of agents.values()) {
714
+ // An unconfirmed pointer is a slot taken; an agent without hooks never takes one (its output says too little).
715
+ if (!hooked(rt) || rt.state === 'stopped')
716
+ continue;
717
+ if (rt.state === 'working' || rt.pendingConfirm)
718
+ working += 1;
719
+ }
720
+ return working;
721
+ }
722
+ /** Messages that wait only for the limit: their note is the one loadLimitNote wrote. */
723
+ function holdingCount() {
724
+ let holding = 0;
725
+ for (const rt of agents.values()) {
726
+ for (const record of queued(rt)) {
727
+ if (record.status === 'queued' && record.note?.startsWith(LOAD_LIMIT_NOTE))
728
+ holding += 1;
729
+ }
730
+ }
731
+ return holding;
732
+ }
733
+ function governorView() {
734
+ return { limit, working: workingCount(), holding: holdingCount() };
735
+ }
736
+ function publishGovernor() {
737
+ const view = governorView();
738
+ const signature = JSON.stringify(view);
739
+ if (signature === governorSig)
740
+ return;
741
+ governorSig = signature;
742
+ emit({ t: 'governor', governor: view });
743
+ }
744
+ /** The wait note when the load limit keeps this idle recipient's pointer back; Director messages (and polls) always pass. */
745
+ function loadLimitNote(rt) {
746
+ if (limit === null)
747
+ return null;
748
+ const working = workingCount();
749
+ if (working < limit || queued(rt).some((record) => record.from === 'user'))
750
+ return null;
751
+ return `${LOAD_LIMIT_NOTE} (${working} of ${limit} agents working)`;
752
+ }
753
+ function setGovernor(request) {
754
+ assertOpen();
755
+ const req = asObject(request, 'the request');
756
+ const value = req.limit;
757
+ if (value !== null && !(typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= MAX_AGENTS)) {
758
+ throw new HubError('bad_request', `limit must be a whole number from 1 to ${MAX_AGENTS}, or null`, 'limit');
759
+ }
760
+ limit = value;
761
+ // Held messages re-read the new limit now instead of at the next sweep.
762
+ for (const rt of agents.values()) {
763
+ if (rt.queue.length > 0)
764
+ scheduleDelivery(rt, DELIVERY_COALESCE_MS);
765
+ }
766
+ publishGovernor();
767
+ return governorView();
768
+ }
769
+ /** Hub.answer: the Director's go or no-go for an open permission dialog, typed as Enter or Escape; the hooks move the state. */
770
+ function answer(name, request) {
771
+ assertOpen();
772
+ const rt = lookup(name);
773
+ const go = asObject(request, 'the request').go;
774
+ if (typeof go !== 'boolean')
775
+ throw new HubError('bad_request', 'go must be true or false', 'go');
776
+ if (rt.state !== 'needs_you' || rt.needsKind !== 'permission' || rt.transition !== null) {
777
+ throw new HubError('conflict', `${rt.record.name} is not asking for a go`);
778
+ }
779
+ if (!io.press?.(rt.record.name, rt.generation, go ? '\r' : '\x1b')) {
780
+ throw new HubError('conflict', `could not reach the terminal of ${rt.record.name}`);
781
+ }
782
+ if (!go && !isClaude(rt)) {
783
+ // Gemini CLI ends the turn on Escape and no hook says so, and its screen is not read (Claude has R2 for this).
784
+ // shortcut: an Escape typed in the terminal itself still leaves needs_you until the next prompt, upgrade when its screen is read.
785
+ setState(rt, 'idle');
786
+ endTurnUnseen(rt);
787
+ if (rt.queue.length > 0)
788
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
789
+ flush(rt);
790
+ }
791
+ return buildView(rt);
792
+ }
793
+ /* ---- Redline ---- */
794
+ function clearRedline(rt) {
795
+ rt.redline = null;
796
+ rt.repeat = null;
797
+ rt.toolFailAt = [];
798
+ rt.apiErrorAt = [];
799
+ rt.sentTo.clear();
800
+ }
801
+ /** Trips the breaker: Escape interrupts a turn in progress, the state reads needs_you and the mail waits. */
802
+ function tripRt(rt, reason) {
803
+ if (rt.redline !== null || rt.removed || !hooked(rt) || rt.state === 'stopped' || rt.transition !== null)
804
+ return;
805
+ const wasWorking = rt.state === 'working';
806
+ rt.redline = `redline: ${reason}`;
807
+ log.warn(`${rt.record.name} tripped the redline: ${reason}`);
808
+ if (wasWorking && !io.press?.(rt.record.name, rt.generation, ESC)) {
809
+ log.warn(`could not interrupt ${rt.record.name}`);
810
+ }
811
+ setState(rt, 'needs_you');
812
+ syncHolds(rt);
813
+ io.notify?.('redline', `${rt.record.name}: ${reason}`);
814
+ }
815
+ /** The automatic detectors trip only when they are on; a Propellant limit trips through Hub.trip either way. */
816
+ function detect(rt, reason) {
817
+ if (reason !== null && options.redline !== false)
818
+ tripRt(rt, reason);
819
+ }
820
+ function repeatReason(rt, payload) {
821
+ let input = '';
822
+ try {
823
+ input = JSON.stringify(payload.tool_input) ?? '';
824
+ }
825
+ catch {
826
+ input = '';
827
+ }
828
+ const sig = `${String(payload.tool_name)}\n${input.slice(0, REPEAT_SIG_CHARS)}`;
829
+ rt.repeat = rt.repeat?.sig === sig ? { sig, count: rt.repeat.count + 1 } : { sig, count: 1 };
830
+ return rt.repeat.count >= REDLINE_REPEATS ? `loop: ${rt.doing ?? 'the same tool'} ${rt.repeat.count} times in a row` : null;
831
+ }
832
+ function trip(name, reason) {
833
+ const rt = lookup(name);
834
+ tripRt(rt, reason);
835
+ flush(rt);
836
+ }
837
+ function resume(name) {
838
+ assertOpen();
839
+ const rt = lookup(name);
840
+ if (rt.redline === null)
841
+ throw new HubError('conflict', `${rt.record.name} has not tripped the redline`);
842
+ clearRedline(rt);
843
+ // Escape left claude at its prompt; the hooks and the sweep correct this if it is not.
844
+ setState(rt, 'idle');
845
+ syncHolds(rt);
846
+ if (rt.queue.length > 0)
847
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
848
+ flush(rt);
849
+ return buildView(rt);
850
+ }
851
+ /** Propellant reads the transcript at most every METER_INTERVAL_MS on a tool hook, and at every Stop. */
852
+ function meter(rt, payload, force) {
853
+ const path = payload.transcript_path;
854
+ // Propellant reads Claude Code transcripts only.
855
+ if (!io.meter || !isClaude(rt) || typeof path !== 'string' || path === '')
856
+ return;
857
+ const now = io.now();
858
+ if (!force && now - rt.meteredAt < METER_INTERVAL_MS)
859
+ return;
860
+ rt.meteredAt = now;
861
+ try {
862
+ io.meter(rt.record.name, rt.generation, path);
863
+ }
864
+ catch (error) {
865
+ log.warn('meter failed', error);
866
+ }
867
+ }
868
+ /* ---- the delivery check (contract 5.3) ---- */
869
+ function deliveryCheck(rt) {
870
+ if (rt.removed || rt.transition !== null || rt.state === 'stopped' || rt.queue.length === 0)
871
+ return;
872
+ const name = rt.record.name;
873
+ expireDraft(rt, io.now());
874
+ // Latches first, whatever the state: a working recipient with a draft must read `held`, not `is working`.
875
+ if (holdNote(rt) !== null) {
876
+ syncHolds(rt);
877
+ return;
878
+ }
879
+ if (rt.state === 'starting' || rt.state === 'needs_you' || rt.state === 'working') {
880
+ setWaitNotes(rt, waitNote(rt));
881
+ return;
882
+ }
883
+ if (rt.pendingConfirm)
884
+ return;
885
+ const loadNote = loadLimitNote(rt);
886
+ if (loadNote !== null) {
887
+ setWaitNotes(rt, loadNote);
888
+ return;
889
+ }
890
+ // Another CLI's screen is not read: its idle state (from a hook, or from quiet output) is the only gate.
891
+ if (isClaude(rt)) {
892
+ const probe = screenOf(rt);
893
+ if (probe === null)
894
+ return;
895
+ const notReady = `waiting: ${name} is not ready for input`;
896
+ if (!probe.promptBox || probe.dialog !== null) {
897
+ setWaitNotes(rt, notReady);
898
+ return;
899
+ }
900
+ if (titleOf(rt)?.glyph === 'working') {
901
+ setWaitNotes(rt, notReady);
902
+ return;
903
+ }
904
+ }
905
+ const records = queued(rt);
906
+ if (records.length === 0)
907
+ return;
908
+ const text = pointerText(records);
909
+ let typed = false;
910
+ try {
911
+ typed = io.typePointer(name, rt.generation, text);
912
+ }
913
+ catch (error) {
914
+ log.warn(`could not type the pointer into ${name}`, error);
915
+ }
916
+ if (!typed) {
917
+ log.debug(`the pointer for ${name} was not written; the next sweep tries again`);
918
+ return;
919
+ }
920
+ if (!hooked(rt)) {
921
+ // No hook can confirm it: typed is delivered. shortcut: an unread pointer is not typed again, upgrade when such a CLI gets hooks.
922
+ markDelivered(rt, [...rt.queue], 'pointer typed');
923
+ return;
924
+ }
925
+ const confirm = { text, ids: [...rt.queue], at: io.now(), timer: { handle: undefined } };
926
+ confirm.timer = armTimer(rt, PROMPT_SUBMIT_CONFIRM_MS, () => confirmTimedOut(rt, confirm));
927
+ rt.pendingConfirm = confirm;
928
+ for (const id of confirm.ids) {
929
+ const record = messages.get(id);
930
+ if (record)
931
+ setMessage(record, 'queued', 'waiting: confirming the pointer');
932
+ }
933
+ }
934
+ /** The 2 s rule: no UserPromptSubmit for the typed pointer. The message is held and nothing is typed again (5.4). */
935
+ function confirmTimedOut(rt, confirm) {
936
+ if (rt.pendingConfirm !== confirm)
937
+ return;
938
+ rt.pendingConfirm = null;
939
+ const ids = confirm.ids.filter((id) => rt.queue.includes(id));
940
+ if (ids.length === 0)
941
+ return;
942
+ const name = rt.record.name;
943
+ const info = titleOf(rt);
944
+ let note = 'held: pointer not confirmed within 2 s';
945
+ if (!rt.hooksSeen && info !== null && info.glyph === 'working' && info.since >= confirm.at) {
946
+ note = `held: no hook has reached gonogo from ${name}; is its folder trusted?`;
947
+ log.warn(`no hook has reached gonogo from ${name}; is its folder trusted?`);
948
+ }
949
+ rt.unconfirmed = { text: confirm.text, ids, since: io.now(), note };
950
+ syncHolds(rt);
951
+ }
952
+ /** The UserPromptSubmit of the typed pointer (or of a late one): its messages are delivered (contract 5.4). */
953
+ function confirmPointer(rt, ids) {
954
+ cancelConfirm(rt);
955
+ rt.unconfirmed = null;
956
+ markDelivered(rt, ids, 'pointer typed');
957
+ }
958
+ /* ---- hooks (contract 4.4, 5.5) ---- */
959
+ function onHook(input) {
960
+ try {
961
+ return handleHook(input);
962
+ }
963
+ catch (error) {
964
+ log.error('hook handler failed', error);
965
+ return {};
966
+ }
967
+ }
968
+ function handleHook(input) {
969
+ const rt = agents.get(input.agent);
970
+ if (!rt || input.generation !== rt.generation || !hooked(rt))
971
+ return {};
972
+ if (!HOOK_EVENTS.includes(input.event))
973
+ return {};
974
+ rt.hooksSeen = true;
975
+ // P1 and P2: a process that is going away, or gone, says nothing that matters.
976
+ if (rt.transition !== null || rt.state === 'stopped')
977
+ return {};
978
+ // P3: a hook proves the REPL is up (claude holds hooks back until the dialogs are answered).
979
+ if (rt.state === 'starting' || (rt.state === 'needs_you' && rt.needsKind === 'startup_dialog'))
980
+ markReady(rt);
981
+ const payload = isRecord(input.payload) ? input.payload : {};
982
+ let reply = {};
983
+ switch (input.event) {
984
+ case 'UserPromptSubmit':
985
+ onPromptSubmit(rt, payload);
986
+ break;
987
+ case 'PreToolUse':
988
+ rt.doing = describeDoing(payload.tool_name, payload.tool_input);
989
+ onToolHook(rt);
990
+ detect(rt, repeatReason(rt, payload));
991
+ meter(rt, payload, false);
992
+ break;
993
+ case 'PostToolUse':
994
+ onToolHook(rt);
995
+ break;
996
+ case 'PostToolUseFailure':
997
+ onToolHook(rt);
998
+ if (countRecent(rt.toolFailAt, io.now(), REDLINE_TOOL_FAILURE_WINDOW_MS) >= REDLINE_TOOL_FAILURES) {
999
+ detect(rt, `error storm: ${rt.toolFailAt.length} failed tool calls in 2 min`);
1000
+ }
1001
+ break;
1002
+ case 'PermissionRequest':
1003
+ setState(rt, 'needs_you', {
1004
+ kind: 'permission',
1005
+ reason: describePermission(payload.tool_name, payload.tool_input),
1006
+ });
1007
+ break;
1008
+ case 'Notification':
1009
+ onNotification(rt, payload);
1010
+ break;
1011
+ case 'Stop':
1012
+ reply = onStop(rt);
1013
+ meter(rt, payload, true);
1014
+ break;
1015
+ case 'StopFailure':
1016
+ onStopFailure(rt);
1017
+ if (countRecent(rt.apiErrorAt, io.now(), REDLINE_API_ERROR_WINDOW_MS) >= REDLINE_API_ERRORS) {
1018
+ detect(rt, `error storm: ${rt.apiErrorAt.length} API errors in 10 min`);
1019
+ }
1020
+ meter(rt, payload, true);
1021
+ break;
1022
+ }
1023
+ flush(rt);
1024
+ return reply;
1025
+ }
1026
+ function onPromptSubmit(rt, payload) {
1027
+ const prompt = (typeof payload.prompt === 'string' ? payload.prompt : '').replace(/\r\n?/g, '\n').trim();
1028
+ let ours = false;
1029
+ // `ends with`, not `equals`: a pointer pasted after text that was still in the box is delivered all the same.
1030
+ if (rt.pendingConfirm && prompt.endsWith(rt.pendingConfirm.text)) {
1031
+ confirmPointer(rt, rt.pendingConfirm.ids);
1032
+ ours = true;
1033
+ }
1034
+ else if (rt.unconfirmed && prompt.endsWith(rt.unconfirmed.text)) {
1035
+ confirmPointer(rt, rt.unconfirmed.ids);
1036
+ ours = true;
1037
+ }
1038
+ if (!ours) {
1039
+ // The Director typed into the terminal of a tripped agent: they took over, so the trip is over.
1040
+ if (rt.redline !== null)
1041
+ clearRedline(rt);
1042
+ // A person submitted something else: the old trigger no longer says what this turn is about, and a pointer
1043
+ // that sat in the box was either submitted with it or is gone.
1044
+ rt.trigger = null;
1045
+ rt.unconfirmed = null;
1046
+ }
1047
+ setState(rt, 'working');
1048
+ rt.stopBlocks = 0;
1049
+ // After the state change, so a released message gets the wait note of the state it will really wait in.
1050
+ syncHolds(rt);
1051
+ if (rt.queue.length > 0)
1052
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
1053
+ const session = payload.session_id;
1054
+ if (isClaude(rt) && typeof session === 'string' && UUID_RE.test(session) && session !== rt.record.sessionId) {
1055
+ // claude started a new session (/clear): the next resume must name it.
1056
+ rt.record.sessionId = session;
1057
+ void saveRecords(rosterRecords()).catch((error) => log.error('could not save the new session id', error));
1058
+ }
1059
+ }
1060
+ function onToolHook(rt) {
1061
+ rt.stopBlocks = 0;
1062
+ if (rt.state === 'idle' || rt.state === 'working') {
1063
+ setState(rt, 'working');
1064
+ }
1065
+ else if (rt.state === 'needs_you') {
1066
+ // A sibling tool of the same batch ended while the dialog is still open: stay. A tool the user allowed shows no
1067
+ // hook until it ends, so R4 is the way out for that case.
1068
+ const probe = isClaude(rt) ? screenOf(rt) : null;
1069
+ if (probe === null || probe.dialog === null)
1070
+ setState(rt, 'working');
1071
+ }
1072
+ }
1073
+ function onNotification(rt, payload) {
1074
+ const type = payload.notification_type;
1075
+ if (type === 'permission_prompt') {
1076
+ // The Notification comes about 6 s after the dialog opened: one that arrives after the user answered it, or while
1077
+ // the screen cannot be read, must not bring needs_you back.
1078
+ if (rt.state !== 'needs_you' && screenOf(rt)?.dialog) {
1079
+ setState(rt, 'needs_you', { kind: 'permission', reason: 'permission request: waiting for approval' });
1080
+ }
1081
+ }
1082
+ else if (type === 'ToolPermission') {
1083
+ // Gemini CLI sends this when its confirmation opens, with a message instead of the tool call.
1084
+ const message = typeof payload.message === 'string' ? cutText(collapseWhitespace(payload.message), PERMISSION_SUMMARY_CHARS) : '';
1085
+ setState(rt, 'needs_you', { kind: 'permission', reason: message === '' ? 'permission request: waiting for approval' : `permission request: ${message}` });
1086
+ }
1087
+ else if (type === 'elicitation_dialog' || type === 'agent_needs_input') {
1088
+ const message = typeof payload.message === 'string' ? cutText(payload.message, INPUT_REASON_CHARS) : '';
1089
+ setState(rt, 'needs_you', {
1090
+ kind: 'input',
1091
+ reason: message === '' ? 'input requested' : `input requested: ${message}`,
1092
+ });
1093
+ }
1094
+ }
1095
+ function onStop(rt) {
1096
+ const now = io.now();
1097
+ rt.trigger = null;
1098
+ redeliver(rt);
1099
+ // The state is written once, at the end, so a block never shows a transient idle.
1100
+ const candidates = rt.queue.filter((id) => !inFlight(rt, id));
1101
+ if (candidates.length === 0 || rt.redline !== null) {
1102
+ syncHolds(rt);
1103
+ setState(rt, 'idle');
1104
+ return {};
1105
+ }
1106
+ expireDraft(rt, now);
1107
+ if (rt.draft) {
1108
+ syncHolds(rt);
1109
+ setState(rt, 'idle');
1110
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
1111
+ return {};
1112
+ }
1113
+ if (rt.unconfirmed) {
1114
+ setState(rt, 'idle');
1115
+ return {};
1116
+ }
1117
+ if (rt.stopBlocks >= MAX_STOP_BLOCKS) {
1118
+ // Claude Code ignores the ninth consecutive block: let the agent go idle and type the pointer instead.
1119
+ setState(rt, 'idle');
1120
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
1121
+ return {};
1122
+ }
1123
+ const records = candidates.map((id) => messages.get(id)).filter((record) => !!record);
1124
+ const text = pointerText(records);
1125
+ markDelivered(rt, candidates, 'handed over when its turn ended');
1126
+ rt.stopBlocks += 1;
1127
+ rt.lastBlockAt = now;
1128
+ setState(rt, 'working');
1129
+ return { decision: 'block', reason: text };
1130
+ }
1131
+ function onStopFailure(rt) {
1132
+ rt.trigger = null;
1133
+ rt.stopBlocks = 0;
1134
+ setState(rt, 'idle');
1135
+ redeliver(rt);
1136
+ if (rt.queue.length > 0)
1137
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
1138
+ }
1139
+ /* ---- reconciliation (contract 4.7) ---- */
1140
+ function endTurnUnseen(rt) {
1141
+ rt.trigger = null;
1142
+ rt.stopBlocks = 0;
1143
+ redeliver(rt);
1144
+ }
1145
+ function reconcile(rt, now) {
1146
+ const info = titleOf(rt);
1147
+ const probe = screenOf(rt);
1148
+ // How long the glyph has disagreed with the state, not how long the glyph class has existed: a Stop sets idle at
1149
+ // once while the title still shows the working glyph for 10 to 30 ms, and the glyph's age is the whole turn.
1150
+ const since = info ? Math.max(info.since, rt.stateSince) : now;
1151
+ if (rt.state === 'working') {
1152
+ const blockedRecently = rt.lastBlockAt !== null && now - rt.lastBlockAt < TITLE_IDLE_RECONCILE_MS;
1153
+ if (probe && info?.glyph === 'idle' && now - since >= TITLE_IDLE_RECONCILE_MS && !blockedRecently) {
1154
+ if (probe.dialog !== null)
1155
+ setState(rt, 'needs_you', { kind: 'dialog', reason: SCREEN_DIALOG_REASON });
1156
+ else
1157
+ setState(rt, 'idle');
1158
+ endTurnUnseen(rt);
1159
+ }
1160
+ }
1161
+ else if (rt.state === 'idle') {
1162
+ if (info?.glyph === 'working' && now - since >= TITLE_WORKING_CONFIRM_MS)
1163
+ setState(rt, 'working');
1164
+ }
1165
+ else if (rt.state === 'needs_you' && rt.needsKind !== 'startup_dialog') {
1166
+ if (probe && info && probe.promptBox && probe.dialog === null && info.glyph === 'idle') {
1167
+ // R2: the dialog was answered without a hook (denied, Esc). The title alone proves nothing, it shows the idle
1168
+ // glyph while a permission dialog is open; the screen says the dialog is gone.
1169
+ if (rt.screenClearSince === null)
1170
+ rt.screenClearSince = now;
1171
+ if (now - rt.screenClearSince >= NEEDS_YOU_CLEAR_MS) {
1172
+ setState(rt, 'idle');
1173
+ endTurnUnseen(rt);
1174
+ }
1175
+ }
1176
+ else {
1177
+ rt.screenClearSince = null;
1178
+ if (rt.needsKind !== 'input' &&
1179
+ probe &&
1180
+ probe.dialog === null &&
1181
+ info?.glyph === 'working' &&
1182
+ now - since >= TITLE_WORKING_CONFIRM_MS) {
1183
+ // R4: the user allowed the tool. The turn resumes, but no hook fires until the tool ends.
1184
+ setState(rt, 'working');
1185
+ }
1186
+ }
1187
+ }
1188
+ expireDraft(rt, now);
1189
+ screenProof(rt, now, probe);
1190
+ if (rt.queue.length > 0)
1191
+ deliveryCheck(rt);
1192
+ }
1193
+ /** A custom command has no hooks: its output counter is the only sign of life (more output = working, quiet = idle). */
1194
+ function reconcileCustom(rt, now) {
1195
+ const bytes = outputBytesOf(rt);
1196
+ const sample = rt.custom;
1197
+ if (bytes > sample.bytes)
1198
+ sample.activeAt = now;
1199
+ sample.bytes = bytes;
1200
+ if (sample.activeAt !== null)
1201
+ setState(rt, now - sample.activeAt < CUSTOM_ACTIVE_MS ? 'working' : 'idle');
1202
+ else if (now - sample.since >= CUSTOM_START_MS)
1203
+ setState(rt, 'idle');
1204
+ }
1205
+ function sweep() {
1206
+ const now = io.now();
1207
+ for (const rt of [...agents.values()]) {
1208
+ if (rt.removed || rt.transition !== null || rt.state === 'stopped')
1209
+ continue;
1210
+ guarded(`sweep of ${rt.record.name}`, () => {
1211
+ if (!hooked(rt)) {
1212
+ reconcileCustom(rt, now);
1213
+ if (mailable(rt) && rt.queue.length > 0)
1214
+ deliveryCheck(rt);
1215
+ }
1216
+ else if (isClaude(rt))
1217
+ reconcile(rt, now);
1218
+ else {
1219
+ // Gemini CLI: its hooks alone move the state; the sweep ends a stale draft and retries the mail.
1220
+ expireDraft(rt, now);
1221
+ if (rt.queue.length > 0)
1222
+ deliveryCheck(rt);
1223
+ }
1224
+ flush(rt);
1225
+ });
1226
+ }
1227
+ }
1228
+ function armSweep() {
1229
+ if (closing)
1230
+ return;
1231
+ sweepTimer = { handle: undefined };
1232
+ sweepTimer.handle = io.setTimer(() => {
1233
+ sweepTimer = null;
1234
+ guarded('sweep', sweep);
1235
+ armSweep();
1236
+ }, RECONCILE_TICK_MS);
1237
+ }
1238
+ /* ---- terminal events (contract 4.3, 4.9) ---- */
1239
+ function onTerminalEvent(event) {
1240
+ guarded('terminal event', () => {
1241
+ const rt = isRecord(event) ? agents.get(event.name) : undefined;
1242
+ if (!rt || event.generation !== rt.generation)
1243
+ return;
1244
+ if (event.kind === 'ready') {
1245
+ if (!isClaude(rt) || rt.transition !== null || rt.state === 'stopped')
1246
+ return;
1247
+ rt.ready = true;
1248
+ if (rt.state === 'starting' || (rt.state === 'needs_you' && rt.needsKind === 'startup_dialog'))
1249
+ markReady(rt);
1250
+ }
1251
+ else if (event.kind === 'exit') {
1252
+ handleExit(rt, event.info);
1253
+ }
1254
+ // `title` carries nothing the sweep does not read from io.title itself.
1255
+ flush(rt);
1256
+ });
1257
+ }
1258
+ function lastLine(text) {
1259
+ const lines = text.split('\n').map((line) => line.trim());
1260
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
1261
+ if (lines[index] !== '')
1262
+ return lines[index] ?? '';
1263
+ }
1264
+ return '';
1265
+ }
1266
+ function exitText(info) {
1267
+ if (info.requested)
1268
+ return 'stopped';
1269
+ const base = info.signal !== null
1270
+ ? `killed by signal ${info.signal}`
1271
+ : info.code !== null
1272
+ ? `exited with code ${info.code}`
1273
+ : 'exited';
1274
+ const detail = lastLine(info.tail);
1275
+ return detail === '' ? base : `${base}: ${detail}`;
1276
+ }
1277
+ /** The flag to retry with, when this exit is the one wrong-flag failure the hub corrects (contract 4.9 step 1). */
1278
+ function flipFlag(rt, info) {
1279
+ if (closing || rt.transition !== null || info.requested || info.code !== 1)
1280
+ return null;
1281
+ if (!(info.durationMs < SESSION_FLIP_WINDOW_MS) || !rt.flipAvailable || rt.flag === null)
1282
+ return null;
1283
+ // Exit 1 within 3 s is also what a refused flag, root refusing bypassPermissions or a bad cwd look like: only
1284
+ // claude's own message for the flag that was used says the session id was the problem.
1285
+ const message = rt.flag === 'session-id' ? SESSION_IN_USE_TEXT : SESSION_MISSING_TEXT;
1286
+ if (!info.tail.includes(message))
1287
+ return null;
1288
+ return rt.flag === 'session-id' ? 'resume' : 'session-id';
1289
+ }
1290
+ function handleExit(rt, raw) {
1291
+ const generation = rt.generation;
1292
+ if (rt.exitSeen === generation)
1293
+ return;
1294
+ rt.exitSeen = generation;
1295
+ const info = {
1296
+ code: typeof raw?.code === 'number' ? raw.code : null,
1297
+ signal: typeof raw?.signal === 'number' ? raw.signal : null,
1298
+ durationMs: typeof raw?.durationMs === 'number' ? raw.durationMs : Number.POSITIVE_INFINITY,
1299
+ requested: raw?.requested === true,
1300
+ tail: typeof raw?.tail === 'string' ? raw.tail : '',
1301
+ };
1302
+ const name = rt.record.name;
1303
+ cancelTimers(rt);
1304
+ rt.ready = false;
1305
+ rt.draft = null;
1306
+ rt.unconfirmed = null;
1307
+ rt.trigger = null;
1308
+ rt.stopBlocks = 0;
1309
+ rt.screenClearSince = null;
1310
+ const retry = flipFlag(rt, info);
1311
+ if (retry !== null) {
1312
+ // Nothing else changes: no stopped flash, the queue stays, the retry runs on the agent's own lifecycle queue.
1313
+ rt.flipAvailable = false;
1314
+ log.info(`${name}: the session flag was wrong, trying ${retry}`);
1315
+ void enqueue(rt, 'flip', () => spawnOp(rt, retry, false)).catch((error) => log.error(`the flag retry of ${name} failed`, error));
1316
+ return;
1317
+ }
1318
+ setState(rt, 'stopped');
1319
+ pollEntryStopped(name);
1320
+ rt.exit = { code: info.code, signal: info.signal, at: io.now(), requested: info.requested, text: exitText(info) };
1321
+ if (!closing) {
1322
+ if (rt.transition === 'restarting') {
1323
+ keepQueueForRestart(rt);
1324
+ }
1325
+ else {
1326
+ const gone = rt.transition === 'removing' ? 'was removed before reading it' : 'stopped before reading it';
1327
+ undeliverUnread(rt, `${name} ${gone}; the message went to the user`);
1328
+ }
1329
+ }
1330
+ // The stop operation resolves on this; removing and restarting carry on with their own steps.
1331
+ if (rt.transition === 'stopping')
1332
+ rt.transition = null;
1333
+ }
1334
+ /** A restart keeps every unread message for the new process; the ones it had already pointed at start over. */
1335
+ function keepQueueForRestart(rt) {
1336
+ const name = rt.record.name;
1337
+ const unread = unreadFor(name);
1338
+ rt.pointed.clear();
1339
+ for (const record of unread) {
1340
+ if (record.status === 'delivered')
1341
+ setMessage(record, 'queued', 'restarted before it was read');
1342
+ else
1343
+ setMessage(record, 'queued', `waiting: ${name} is restarting`);
1344
+ }
1345
+ rt.queue = unread.map((record) => record.id);
1346
+ }
1347
+ /* ---- lifecycle: the per-agent queue ---- */
1348
+ function enqueue(rt, kind, run, dedupe = false) {
1349
+ if (dedupe) {
1350
+ // A double-clicked Restart or Stop resolves with the pending one instead of running twice.
1351
+ const tail = rt.ops.length > 0 ? rt.ops[rt.ops.length - 1] : rt.current;
1352
+ if (tail && tail.kind === kind)
1353
+ return tail.promise;
1354
+ }
1355
+ let resolve = () => undefined;
1356
+ let reject = () => undefined;
1357
+ const promise = new Promise((onResolve, onReject) => {
1358
+ resolve = onResolve;
1359
+ reject = onReject;
1360
+ });
1361
+ rt.ops.push({ kind, run, resolve, reject, promise });
1362
+ if (!rt.draining)
1363
+ void drain(rt);
1364
+ return promise;
1365
+ }
1366
+ /** Runs the queue; the first operation of an idle agent starts synchronously, so its first step is visible at once. */
1367
+ async function drain(rt) {
1368
+ rt.draining = true;
1369
+ try {
1370
+ for (let op = rt.ops.shift(); op; op = rt.ops.shift()) {
1371
+ rt.current = op;
1372
+ try {
1373
+ op.resolve(await op.run());
1374
+ }
1375
+ catch (error) {
1376
+ op.reject(error);
1377
+ }
1378
+ }
1379
+ }
1380
+ finally {
1381
+ rt.current = null;
1382
+ rt.draining = false;
1383
+ }
1384
+ }
1385
+ /** Prepares the new generation and returns it. Synchronous: routing sees the new state from the first line (4.9). */
1386
+ function beginSpawn(rt, flag, userInitiated) {
1387
+ rt.generation += 1;
1388
+ clearRedline(rt);
1389
+ if (rt.transition === 'restarting')
1390
+ rt.transition = null;
1391
+ // The first spawn of an agent that never ran: its history starts at `starting`, not at a `stopped` that lasted no time.
1392
+ if (rt.generation === 1)
1393
+ rt.history = [];
1394
+ setState(rt, 'starting');
1395
+ rt.ready = false;
1396
+ rt.draft = null;
1397
+ rt.unconfirmed = null;
1398
+ cancelConfirm(rt);
1399
+ rt.trigger = null;
1400
+ rt.stopBlocks = 0;
1401
+ rt.doing = null;
1402
+ rt.exit = null;
1403
+ rt.hooksSeen = false;
1404
+ rt.pointed.clear();
1405
+ rt.screenClearSince = null;
1406
+ rt.lastBlockAt = null;
1407
+ rt.running = { role: rt.record.role, dir: rt.record.dir, mode: rt.record.mode, command: rt.record.command ?? null, payload: payloadKey(rt.record), cleanRoom: cleanRoomKey(rt.record) };
1408
+ rt.flag = flag;
1409
+ // The browser reacts to a new generation by attaching, so the frame waits until the process exists in the terminal host.
1410
+ rt.frameHold = true;
1411
+ if (!hooked(rt)) {
1412
+ // No startup dialog and no session flag to correct: the first output (or CUSTOM_START_MS) ends `starting`.
1413
+ // The terminal host counts every spawn from 0.
1414
+ rt.custom = { bytes: 0, activeAt: null, since: io.now() };
1415
+ return rt.generation;
1416
+ }
1417
+ if (userInitiated)
1418
+ rt.flipAvailable = true;
1419
+ armStartup(rt, STARTUP_READY_TIMEOUT_MS);
1420
+ return rt.generation;
1421
+ }
1422
+ async function spawnOp(rt, flag, userInitiated) {
1423
+ assertOpen();
1424
+ const name = rt.record.name;
1425
+ const generation = beginSpawn(rt, flag, userInitiated);
1426
+ let failure = null;
1427
+ try {
1428
+ const spawned = await io.spawn({ agent: { ...rt.record }, generation, flag });
1429
+ rt.flag = spawned.flag;
1430
+ log.debug(`${name}: started generation ${generation} (pid ${spawned.pid})`);
1431
+ }
1432
+ catch (error) {
1433
+ failure = errorMessage(error);
1434
+ }
1435
+ rt.frameHold = false;
1436
+ if (failure !== null && rt.generation === generation) {
1437
+ log.warn(`${name} could not start: ${failure}`);
1438
+ cancelTimers(rt);
1439
+ rt.ready = false;
1440
+ setState(rt, 'stopped');
1441
+ rt.exit = { code: null, signal: null, at: io.now(), requested: false, text: `could not start: ${failure}` };
1442
+ undeliverUnread(rt, `${name} could not start; the message went to the user`);
1443
+ }
1444
+ flush(rt);
1445
+ }
1446
+ /** Asks the terminal host to stop the process of the current generation and makes sure the hub has seen it exit. */
1447
+ async function stopProcess(rt) {
1448
+ const generation = rt.generation;
1449
+ try {
1450
+ await io.stop(rt.record.name, generation);
1451
+ }
1452
+ catch (error) {
1453
+ log.warn(`stopping ${rt.record.name} failed`, error);
1454
+ }
1455
+ // The host delivers the exit event before stop() resolves; if it did not, the agent must not stay running here.
1456
+ if (rt.generation === generation && rt.state !== 'stopped' && rt.exitSeen !== generation) {
1457
+ handleExit(rt, { code: null, signal: null, durationMs: 0, requested: true, tail: '' });
1458
+ }
1459
+ }
1460
+ async function restartOp(rt) {
1461
+ assertOpen();
1462
+ if (rt.removed)
1463
+ throw new HubError('not_found', 'unknown agent');
1464
+ if (rt.state !== 'stopped') {
1465
+ rt.transition = 'restarting';
1466
+ flush(rt);
1467
+ // From here until the new process exists the agent shows no frame: the exit would otherwise flash `stopped`.
1468
+ rt.frameHold = true;
1469
+ await stopProcess(rt);
1470
+ if (closing) {
1471
+ if (rt.transition === 'restarting')
1472
+ rt.transition = null;
1473
+ rt.frameHold = false;
1474
+ flush(rt);
1475
+ return buildView(rt);
1476
+ }
1477
+ }
1478
+ await spawnOp(rt, null, true);
1479
+ return buildView(rt);
1480
+ }
1481
+ async function stopOp(rt) {
1482
+ assertOpen();
1483
+ if (rt.removed)
1484
+ throw new HubError('not_found', 'unknown agent');
1485
+ if (rt.state === 'stopped')
1486
+ return buildView(rt);
1487
+ rt.transition = 'stopping';
1488
+ flush(rt);
1489
+ await stopProcess(rt);
1490
+ if (rt.transition === 'stopping')
1491
+ rt.transition = null;
1492
+ flush(rt);
1493
+ return buildView(rt);
1494
+ }
1495
+ async function removeOp(rt) {
1496
+ assertOpen();
1497
+ if (rt.removed)
1498
+ throw new HubError('not_found', 'unknown agent');
1499
+ if (rt.state !== 'stopped') {
1500
+ rt.transition = 'removing';
1501
+ flush(rt);
1502
+ await stopProcess(rt);
1503
+ }
1504
+ try {
1505
+ await saveRecords(rosterRecords().filter((record) => record.name !== rt.record.name));
1506
+ }
1507
+ catch (error) {
1508
+ rt.transition = null;
1509
+ flush(rt);
1510
+ throw error;
1511
+ }
1512
+ cancelTimers(rt);
1513
+ rt.removed = true;
1514
+ agents.delete(rt.record.name);
1515
+ emit({ t: 'agent-removed', name: rt.record.name });
1516
+ publishGovernor();
1517
+ if (pollState !== null) {
1518
+ pollState.entries = pollState.entries.filter((entry) => entry.agent !== rt.record.name);
1519
+ if (pollState.entries.length === 0)
1520
+ pollState = null;
1521
+ else
1522
+ settlePoll();
1523
+ publishPoll();
1524
+ }
1525
+ // The process is gone (stopped above, or never ran): the terminal's mirror and scrollback can go too.
1526
+ try {
1527
+ io.forget?.(rt.record.name);
1528
+ }
1529
+ catch (error) {
1530
+ log.warn(`could not free the terminal of ${rt.record.name}`, error);
1531
+ }
1532
+ }
1533
+ /** Stops what runs when the server shuts down. It queues behind a running operation, so a spawn finishes first. */
1534
+ async function terminateOp(rt) {
1535
+ if (rt.removed || rt.state === 'stopped')
1536
+ return;
1537
+ rt.transition = 'stopping';
1538
+ flush(rt);
1539
+ await stopProcess(rt);
1540
+ if (rt.transition === 'stopping')
1541
+ rt.transition = null;
1542
+ flush(rt);
1543
+ }
1544
+ /* ---- hire and edit ---- */
1545
+ function asObject(value, what) {
1546
+ if (!isRecord(value))
1547
+ throw new HubError('bad_request', `${what} must be a JSON object`);
1548
+ return value;
1549
+ }
1550
+ function checkName(value) {
1551
+ if (typeof value !== 'string' || !NAME_RE.test(value)) {
1552
+ throw new HubError('bad_request', 'name must be 1 to 32 lowercase letters, digits or hyphens, and start with a letter or digit', 'name');
1553
+ }
1554
+ if (RESERVED_NAMES.includes(value)) {
1555
+ throw new HubError('bad_request', `"${value}" is a reserved name`, 'name');
1556
+ }
1557
+ return value;
1558
+ }
1559
+ function checkRole(value) {
1560
+ const role = typeof value === 'string' ? value.trim() : '';
1561
+ if (role.length === 0 || role.length > ROLE_MAX_CHARS) {
1562
+ throw new HubError('bad_request', `role must be 1 to ${ROLE_MAX_CHARS} characters`, 'role');
1563
+ }
1564
+ return role;
1565
+ }
1566
+ function checkMode(value) {
1567
+ if (typeof value !== 'string' || !PERMISSION_MODES.includes(value)) {
1568
+ throw new HubError('bad_request', `mode must be one of ${PERMISSION_MODES.join(', ')}`, 'mode');
1569
+ }
1570
+ return value;
1571
+ }
1572
+ function checkPosition(value) {
1573
+ if (typeof value !== 'string' || !POSITION_IDS.includes(value)) {
1574
+ throw new HubError('bad_request', 'unknown position', 'position');
1575
+ }
1576
+ return value;
1577
+ }
1578
+ function checkProvider(value) {
1579
+ if (value === undefined)
1580
+ return 'claude';
1581
+ if (typeof value !== 'string' || !PROVIDERS.includes(value)) {
1582
+ throw new HubError('bad_request', `provider must be one of ${PROVIDERS.join(', ')}`, 'provider');
1583
+ }
1584
+ return value;
1585
+ }
1586
+ function checkCommand(value) {
1587
+ const command = typeof value === 'string' ? value.trim() : '';
1588
+ if (command.length === 0 || command.length > COMMAND_MAX_CHARS) {
1589
+ throw new HubError('bad_request', `command must be 1 to ${COMMAND_MAX_CHARS} characters`, 'command');
1590
+ }
1591
+ return command;
1592
+ }
1593
+ /** The optional record fields are removed, not set to undefined, so that the roster file stays as it was for old agents. */
1594
+ function setOptional(record, key, value) {
1595
+ if (value === undefined)
1596
+ delete record[key];
1597
+ else
1598
+ record[key] = value;
1599
+ }
1600
+ function assignFields(target, from) {
1601
+ target.name = from.name;
1602
+ target.role = from.role;
1603
+ target.dir = from.dir;
1604
+ target.mode = from.mode;
1605
+ setOptional(target, 'position', from.position);
1606
+ setOptional(target, 'command', from.command);
1607
+ if (from.payload === undefined)
1608
+ delete target.payload;
1609
+ else
1610
+ target.payload = from.payload;
1611
+ if (from.cleanRoom === undefined)
1612
+ delete target.cleanRoom;
1613
+ else
1614
+ target.cleanRoom = from.cleanRoom;
1615
+ }
1616
+ /** The shape of a payload and whether the engine takes it (no disk). A bad value is 400 with the field it names. */
1617
+ function checkPayload(provider, value) {
1618
+ const checked = parsePayload(value);
1619
+ if (!checked.ok)
1620
+ throw new HubError('bad_request', checked.error, checked.field);
1621
+ const refused = checked.payload && payloadRefusal(provider, checked.payload);
1622
+ if (refused)
1623
+ throw new HubError('bad_request', refused.error, refused.field);
1624
+ return checked.payload;
1625
+ }
1626
+ /** A Clean Room setting: Claude Code only, a good image, and (when the check exists) Docker answers and `dir` is in a git repository. A bad one is 400, field cleanRoom. */
1627
+ async function checkCleanRoom(provider, value, dir) {
1628
+ const checked = parseCleanRoom(value, provider);
1629
+ if (!checked.ok)
1630
+ throw new HubError('bad_request', checked.error, 'cleanRoom');
1631
+ let problem;
1632
+ try {
1633
+ problem = (await io.checkCleanRoom?.(dir)) ?? null;
1634
+ }
1635
+ catch (error) {
1636
+ log.error('clean room check failed', error);
1637
+ problem = errorMessage(error);
1638
+ }
1639
+ if (problem !== null)
1640
+ throw new HubError('bad_request', problem, 'cleanRoom');
1641
+ return checked.cleanRoom;
1642
+ }
1643
+ /** Every skill folder must exist (the launcher looks for the SKILL.md at the start). */
1644
+ async function checkSkills(payload) {
1645
+ for (const folder of payload?.skills ?? []) {
1646
+ let verdict;
1647
+ try {
1648
+ verdict = await io.checkDirectory(folder);
1649
+ }
1650
+ catch (error) {
1651
+ log.error('skill folder check failed', error);
1652
+ throw new HubError('internal', `could not check the skill folder: ${errorMessage(error)}`, 'payload.skills');
1653
+ }
1654
+ if (!verdict.ok)
1655
+ throw new HubError('bad_request', `skill folder: ${verdict.error}`, 'payload.skills');
1656
+ }
1657
+ }
1658
+ async function checkDir(value) {
1659
+ if (typeof value !== 'string' || value.length === 0 || value.length > DIR_MAX_CHARS) {
1660
+ throw new HubError('bad_request', `dir must be a path of 1 to ${DIR_MAX_CHARS} characters`, 'dir');
1661
+ }
1662
+ let verdict;
1663
+ try {
1664
+ verdict = await io.checkDirectory(value);
1665
+ }
1666
+ catch (error) {
1667
+ log.error('directory check failed', error);
1668
+ throw new HubError('internal', `could not check the directory: ${errorMessage(error)}`, 'dir');
1669
+ }
1670
+ if (!verdict.ok)
1671
+ throw new HubError('bad_request', verdict.error, 'dir');
1672
+ return verdict.path;
1673
+ }
1674
+ function lowestFreeDesk() {
1675
+ const used = new Set();
1676
+ for (const rt of agents.values())
1677
+ used.add(rt.record.desk);
1678
+ for (const record of hiring.values()) {
1679
+ if (record)
1680
+ used.add(record.desk);
1681
+ }
1682
+ let desk = 1;
1683
+ while (used.has(desk))
1684
+ desk += 1;
1685
+ return desk;
1686
+ }
1687
+ async function hire(request) {
1688
+ assertOpen();
1689
+ const req = asObject(request, 'the request');
1690
+ const name = checkName(req.name);
1691
+ if (agents.has(name) || claimedNames.has(name)) {
1692
+ throw new HubError('conflict', `an agent named "${name}" already exists`, 'name');
1693
+ }
1694
+ if (agents.size + hiring.size >= MAX_AGENTS) {
1695
+ throw new HubError('conflict', `the operations room is full (${MAX_AGENTS} agents)`);
1696
+ }
1697
+ const role = checkRole(req.role);
1698
+ const provider = checkProvider(req.provider);
1699
+ const custom = provider === 'custom';
1700
+ const position = req.position === undefined ? undefined : checkPosition(req.position);
1701
+ if (!custom && req.command !== undefined) {
1702
+ throw new HubError('bad_request', 'only a custom agent has a command', 'command');
1703
+ }
1704
+ const command = custom ? checkCommand(req.command) : undefined;
1705
+ const payload = checkPayload(provider, req.payload);
1706
+ // A CLI without permission modes (a custom command among them): the mode and confirmBypass of the request are ignored.
1707
+ const mode = providerInfo(provider).modes ? checkMode(req.mode) : 'default';
1708
+ // The name is claimed while the checks and the save await, so two hires cannot take the same name or the same desk.
1709
+ claimedNames.add(name);
1710
+ hiring.set(name, null);
1711
+ let hired;
1712
+ try {
1713
+ const dir = await checkDir(req.dir);
1714
+ if (mode === 'bypassPermissions' && req.confirmBypass !== true) {
1715
+ throw new HubError('bad_request', 'bypassPermissions needs confirmBypass: true', 'confirmBypass');
1716
+ }
1717
+ await checkSkills(payload);
1718
+ const cleanRoom = req.cleanRoom === undefined ? undefined : await checkCleanRoom(provider, req.cleanRoom, dir);
1719
+ assertOpen();
1720
+ const record = {
1721
+ name,
1722
+ role,
1723
+ dir,
1724
+ mode,
1725
+ sessionId: io.newSessionId(),
1726
+ desk: lowestFreeDesk(),
1727
+ boss: false,
1728
+ createdAt: io.now(),
1729
+ };
1730
+ setOptional(record, 'position', position);
1731
+ if (provider !== 'claude')
1732
+ record.provider = provider;
1733
+ setOptional(record, 'command', command);
1734
+ if (payload)
1735
+ record.payload = payload;
1736
+ if (cleanRoom)
1737
+ record.cleanRoom = cleanRoom;
1738
+ hiring.set(name, record);
1739
+ await saveRecords(rosterRecords());
1740
+ hired = makeRt(record);
1741
+ agents.set(name, hired);
1742
+ }
1743
+ finally {
1744
+ claimedNames.delete(name);
1745
+ hiring.delete(name);
1746
+ }
1747
+ const rt = hired;
1748
+ return enqueue(rt, 'hire', async () => {
1749
+ await spawnOp(rt, null, true);
1750
+ return buildView(rt);
1751
+ });
1752
+ }
1753
+ async function editOp(rt, request) {
1754
+ assertOpen();
1755
+ if (rt.removed)
1756
+ throw new HubError('not_found', 'unknown agent');
1757
+ const req = asObject(request, 'the request');
1758
+ const fields = ['name', 'role', 'dir', 'mode', 'confirmBypass', 'position', 'command', 'payload', 'cleanRoom'];
1759
+ if (!fields.some((field) => req[field] !== undefined)) {
1760
+ throw new HubError('bad_request', 'nothing to change: send at least one of name, role, dir, mode, position, command, payload, cleanRoom');
1761
+ }
1762
+ const current = rt.record;
1763
+ const next = { ...current };
1764
+ let newName = null;
1765
+ try {
1766
+ if (req.name !== undefined) {
1767
+ const name = checkName(req.name);
1768
+ if (name !== current.name) {
1769
+ if (current.cleanRoom !== undefined && req.cleanRoom !== null) {
1770
+ throw new HubError('conflict', 'a Clean Room console cannot be renamed: its worktree and branch carry its name (turn Clean Room off to rename it)', 'name');
1771
+ }
1772
+ if (agents.has(name) || claimedNames.has(name)) {
1773
+ throw new HubError('conflict', `an agent named "${name}" already exists`, 'name');
1774
+ }
1775
+ // Claimed until the end, so that a hire cannot take the name while the checks below await.
1776
+ claimedNames.add(name);
1777
+ newName = name;
1778
+ }
1779
+ }
1780
+ if (req.role !== undefined)
1781
+ next.role = checkRole(req.role);
1782
+ // A CLI without permission modes keeps mode 'default' whatever the request says.
1783
+ if (req.mode !== undefined && providerInfo(rt.record.provider).modes)
1784
+ next.mode = checkMode(req.mode);
1785
+ if (req.position !== undefined)
1786
+ setOptional(next, 'position', req.position === null ? undefined : checkPosition(req.position));
1787
+ if (req.command !== undefined) {
1788
+ if (!isCustom(rt))
1789
+ throw new HubError('bad_request', 'only a custom agent has a command', 'command');
1790
+ next.command = checkCommand(req.command);
1791
+ }
1792
+ if (req.dir !== undefined)
1793
+ next.dir = await checkDir(req.dir);
1794
+ if (req.payload !== undefined) {
1795
+ const payload = checkPayload(current.provider ?? 'claude', req.payload);
1796
+ await checkSkills(payload);
1797
+ if (payload)
1798
+ next.payload = payload;
1799
+ else
1800
+ delete next.payload;
1801
+ }
1802
+ if (req.cleanRoom !== undefined) {
1803
+ if (req.cleanRoom === null)
1804
+ delete next.cleanRoom;
1805
+ else
1806
+ next.cleanRoom = await checkCleanRoom(current.provider ?? 'claude', req.cleanRoom, next.dir);
1807
+ }
1808
+ if (next.mode === 'bypassPermissions' && next.mode !== current.mode && req.confirmBypass !== true) {
1809
+ throw new HubError('bad_request', 'bypassPermissions needs confirmBypass: true', 'confirmBypass');
1810
+ }
1811
+ if (newName !== null) {
1812
+ // The state may have changed during the directory check: look at it now.
1813
+ if (rt.state !== 'stopped' || rt.transition !== null) {
1814
+ throw new HubError('conflict', 'an agent can only be renamed while it is stopped', 'name');
1815
+ }
1816
+ next.name = newName;
1817
+ }
1818
+ const changed = next.name !== current.name ||
1819
+ next.role !== current.role ||
1820
+ next.dir !== current.dir ||
1821
+ next.mode !== current.mode ||
1822
+ next.position !== current.position ||
1823
+ next.command !== current.command ||
1824
+ payloadKey(next) !== payloadKey(current) ||
1825
+ cleanRoomKey(next) !== cleanRoomKey(current);
1826
+ if (!changed)
1827
+ return buildView(rt);
1828
+ const oldName = current.name;
1829
+ const previous = { ...current };
1830
+ if (newName !== null) {
1831
+ try {
1832
+ await io.renameAgentFiles(oldName, newName);
1833
+ }
1834
+ catch (error) {
1835
+ throw new HubError('conflict', errorMessage(error), 'name');
1836
+ }
1837
+ }
1838
+ // Apply, then save: an operation queued for the agent from now on finds it under its new name, and the frame
1839
+ // waits until the roster is on disk. A failed save puts everything back, the files included.
1840
+ assignFields(current, next);
1841
+ if (newName !== null) {
1842
+ agents.delete(oldName);
1843
+ agents.set(newName, rt);
1844
+ renamePollEntry(oldName, newName);
1845
+ }
1846
+ try {
1847
+ await saveRecords(rosterRecords());
1848
+ }
1849
+ catch (error) {
1850
+ assignFields(current, previous);
1851
+ if (newName !== null) {
1852
+ agents.delete(newName);
1853
+ agents.set(oldName, rt);
1854
+ renamePollEntry(newName, oldName);
1855
+ await io
1856
+ .renameAgentFiles(newName, oldName)
1857
+ .catch((undo) => log.error('could not undo the rename', undo));
1858
+ }
1859
+ throw error;
1860
+ }
1861
+ if (newName !== null) {
1862
+ emit({ t: 'agent-removed', name: oldName });
1863
+ }
1864
+ flush(rt);
1865
+ return buildView(rt);
1866
+ }
1867
+ finally {
1868
+ if (newName !== null)
1869
+ claimedNames.delete(newName);
1870
+ }
1871
+ }
1872
+ function knownRecipients() {
1873
+ return [...sortedAgents().map((rt) => rt.record.name), ...['boss', 'user']].join(', ');
1874
+ }
1875
+ function send(sender, input) {
1876
+ const req = asObject(input, 'the message');
1877
+ const to = req.to;
1878
+ if (typeof to !== 'string' || to.length === 0 || to.length > RECIPIENT_MAX_CHARS) {
1879
+ throw new HubError('bad_request', 'to must be an agent name, "boss" or "user"', 'to');
1880
+ }
1881
+ const subject = req.subject === undefined || req.subject === null ? '' : req.subject;
1882
+ if (typeof subject !== 'string' || subject.length > SUBJECT_MAX_CHARS) {
1883
+ throw new HubError('bad_request', `subject must be text of at most ${SUBJECT_MAX_CHARS} characters`, 'subject');
1884
+ }
1885
+ const body = req.body;
1886
+ if (typeof body !== 'string' || body.trim() === '') {
1887
+ throw new HubError('bad_request', 'body must not be empty', 'body');
1888
+ }
1889
+ if (body.length > BODY_MAX_CHARS) {
1890
+ throw new HubError('bad_request', `body must be at most ${BODY_MAX_CHARS} characters`, 'body');
1891
+ }
1892
+ const inReplyTo = typeof req.inReplyTo === 'string' && req.inReplyTo.length <= REPLY_ID_MAX_CHARS && REPLY_ID_RE.test(req.inReplyTo)
1893
+ ? req.inReplyTo
1894
+ : null;
1895
+ let recipient = null;
1896
+ let recipientName = 'user';
1897
+ const docked = to.includes('@');
1898
+ if (docked) {
1899
+ checkStationAddress(sender, to);
1900
+ recipientName = to;
1901
+ }
1902
+ else if (to === 'user') {
1903
+ if (sender.kind === 'user')
1904
+ throw new HubError('bad_request', 'a message from you cannot be addressed to user', 'to');
1905
+ if (sender.kind === 'station')
1906
+ throw new HubError('bad_request', 'a message from another station cannot be addressed to user: write to an agent', 'to');
1907
+ }
1908
+ else if (to === 'boss') {
1909
+ recipient = bossRt();
1910
+ if (!recipient)
1911
+ throw new HubError('bad_request', 'there is no boss agent', 'to');
1912
+ recipientName = recipient.record.name;
1913
+ }
1914
+ else {
1915
+ recipient = agents.get(to) ?? null;
1916
+ if (!recipient || recipient.removed) {
1917
+ throw new HubError('not_found', `unknown recipient "${to}". Known: ${knownRecipients()}`, 'to');
1918
+ }
1919
+ recipientName = recipient.record.name;
1920
+ }
1921
+ let senderRt = null;
1922
+ if (sender.kind === 'agent') {
1923
+ senderRt = agents.get(sender.name) ?? null;
1924
+ if (!senderRt || senderRt.removed)
1925
+ throw new HubError('bad_request', 'unknown sender');
1926
+ if (sender.generation !== senderRt.generation || senderRt.transition !== null) {
1927
+ throw new HubError('conflict', 'this session has ended');
1928
+ }
1929
+ if (recipient === senderRt) {
1930
+ throw new HubError('bad_request', 'you cannot send a message to yourself', 'to');
1931
+ }
1932
+ }
1933
+ const hops = sender.kind === 'station' ? sender.hops : senderRt === null ? 0 : senderRt.trigger ? senderRt.trigger.maxHops + 1 : 1;
1934
+ const at = io.now();
1935
+ const record = {
1936
+ id: io.newMessageId(),
1937
+ from: sender.kind === 'user' ? 'user' : sender.name,
1938
+ to: recipientName,
1939
+ subject,
1940
+ body,
1941
+ inReplyTo,
1942
+ hops,
1943
+ at,
1944
+ status: 'to_user',
1945
+ note: null,
1946
+ updatedAt: at,
1947
+ };
1948
+ const result = () => ({ ok: record.status !== 'undelivered', id: record.id, to: record.to, status: record.status, note: record.note });
1949
+ // Before the recipient is looked at: a flood to the user or to a stopped agent grows the log all the same.
1950
+ if (senderRt !== null && !takeSendSlot(senderRt, at)) {
1951
+ record.status = 'undelivered';
1952
+ record.note = `rate limit: ${senderRt.record.name} sent too many messages this minute`;
1953
+ // The sender hears it at every send, but the log, the strip and the browsers only once: a refusal that is stored
1954
+ // and broadcast as often as the flood sends would be the flood again.
1955
+ if (senderRt.limitNoted)
1956
+ return result();
1957
+ senderRt.limitNoted = true;
1958
+ }
1959
+ else if (docked) {
1960
+ routeDocked(record);
1961
+ }
1962
+ else {
1963
+ route(record, recipient);
1964
+ }
1965
+ if (senderRt !== null && record.status !== 'undelivered') {
1966
+ const times = senderRt.sentTo.get(recipientName) ?? [];
1967
+ senderRt.sentTo.set(recipientName, times);
1968
+ if (countRecent(times, at, REDLINE_SEND_WINDOW_MS) > REDLINE_SENDS_TO_ONE) {
1969
+ detect(senderRt, `ping-pong: ${times.length} messages to ${recipientName} in 10 min`);
1970
+ flush(senderRt);
1971
+ }
1972
+ }
1973
+ remember(record);
1974
+ announce(record);
1975
+ if (recipient)
1976
+ flush(recipient);
1977
+ return result();
1978
+ }
1979
+ /** `name@station` from an agent, to a station that is docked and a name that can be an agent there. Throws a HubError otherwise. */
1980
+ function checkStationAddress(sender, to) {
1981
+ const at = to.indexOf('@');
1982
+ const name = to.slice(0, at);
1983
+ const station = to.slice(at + 1);
1984
+ if (sender.kind === 'station')
1985
+ throw new HubError('bad_request', 'a message from another station cannot be passed on to a third one', 'to');
1986
+ if (sender.kind === 'user')
1987
+ throw new HubError('bad_request', 'only an agent writes to another station: ask one to', 'to');
1988
+ if (!io.dock)
1989
+ throw new HubError('bad_request', 'docking is not available', 'to');
1990
+ if (!(name === 'boss' || NAME_RE.test(name)) || !STATION_RE.test(station)) {
1991
+ throw new HubError('bad_request', 'to must be name@station, the name of an agent or "boss" and a docked station', 'to');
1992
+ }
1993
+ const stations = io.dock.stations();
1994
+ if (!stations.includes(station)) {
1995
+ throw new HubError('not_found', `unknown station "${station}". ${stations.length === 0 ? 'No station is docked' : `Docked: ${stations.join(', ')}`}`, 'to');
1996
+ }
1997
+ }
1998
+ /** The message goes to the other station in the background: it is queued until that answers, then delivered or undelivered with its reason. */
1999
+ function routeDocked(record) {
2000
+ const at = record.to.indexOf('@');
2001
+ const station = record.to.slice(at + 1);
2002
+ if (record.hops > options.maxHops) {
2003
+ record.status = 'undelivered';
2004
+ record.note = `hop limit ${options.maxHops} reached; the message went to the user`;
2005
+ return;
2006
+ }
2007
+ record.status = 'queued';
2008
+ record.note = `sending to ${station}`;
2009
+ const message = { from: record.from, to: record.to.slice(0, at), subject: record.subject, body: record.body, hops: record.hops };
2010
+ const done = (ok, note) => setMessage(record, ok ? 'delivered' : 'undelivered', note);
2011
+ void io.dock?.send(station, message).then((result) => done(result.ok, result.note), (error) => {
2012
+ log.warn('a docked send failed', error);
2013
+ done(false, `could not send to ${station}`);
2014
+ });
2015
+ }
2016
+ /** One send of an agent against its rolling window. false when the window is full: the message is refused and not counted. */
2017
+ function takeSendSlot(rt, now) {
2018
+ while (rt.sentAt.length > 0 && now - rt.sentAt[0] >= SEND_RATE_WINDOW_MS)
2019
+ rt.sentAt.shift();
2020
+ if (rt.sentAt.length >= SEND_RATE_MAX)
2021
+ return false;
2022
+ rt.sentAt.push(now);
2023
+ rt.limitNoted = false;
2024
+ return true;
2025
+ }
2026
+ /** Decides where a new message goes and writes the outcome into the record; first match wins (contract 5.2 step 6). */
2027
+ function route(record, recipient) {
2028
+ if (recipient === null)
2029
+ return;
2030
+ const name = recipient.record.name;
2031
+ if (!mailable(recipient)) {
2032
+ record.status = 'undelivered';
2033
+ record.note = isCustom(recipient)
2034
+ ? `${name} runs a custom command and cannot receive messages`
2035
+ : `${name} runs ${providerInfo(recipient.record.provider).label} without the gonogo tools and cannot receive messages`;
2036
+ return;
2037
+ }
2038
+ if (record.hops > options.maxHops) {
2039
+ record.status = 'undelivered';
2040
+ record.note = `hop limit ${options.maxHops} reached; the message went to the user`;
2041
+ return;
2042
+ }
2043
+ // A restarting agent is treated like a running one even though its old process may be gone already: the new
2044
+ // process will get the message. This test comes before the `stopped` one (contract 0.5 item 6).
2045
+ const restarting = recipient.transition === 'restarting';
2046
+ if (!restarting && (recipient.state === 'stopped' || recipient.transition !== null)) {
2047
+ record.status = 'undelivered';
2048
+ record.note =
2049
+ recipient.transition === 'removing'
2050
+ ? `${name} is being removed; the message went to the user`
2051
+ : `${name} is stopped; the message went to the user`;
2052
+ return;
2053
+ }
2054
+ // Unread mail is the one thing the hub keeps in memory without a bound of its own: cap what one recipient can pile up.
2055
+ const unread = unreadFor(name);
2056
+ const unreadChars = unread.reduce((total, other) => total + other.body.length, 0);
2057
+ if (unread.length >= MAILBOX_MAX_MESSAGES || unreadChars + record.body.length > MAILBOX_MAX_BODY_CHARS) {
2058
+ record.status = 'undelivered';
2059
+ record.note = `mailbox full: ${name} has too many unread messages`;
2060
+ return;
2061
+ }
2062
+ recipient.queue.push(record.id);
2063
+ const hold = holdNote(recipient);
2064
+ record.status = hold === null ? 'queued' : 'held';
2065
+ record.note = hold ?? waitNote(recipient);
2066
+ scheduleDelivery(recipient, DELIVERY_COALESCE_MS);
2067
+ }
2068
+ function sessionEnded(rt, generation) {
2069
+ return generation !== rt.generation || rt.transition !== null;
2070
+ }
2071
+ function sendFromUser(request) {
2072
+ return send({ kind: 'user' }, request);
2073
+ }
2074
+ function sendFromStation(station, request) {
2075
+ const req = asObject(request, 'the message');
2076
+ if (typeof req.from !== 'string' || !NAME_RE.test(req.from))
2077
+ throw new HubError('bad_request', 'from must be an agent name', 'from');
2078
+ if (typeof req.hops !== 'number' || !Number.isSafeInteger(req.hops) || req.hops < 0)
2079
+ throw new HubError('bad_request', 'hops must be a whole number', 'hops');
2080
+ // only these fields cross: an id another station names (inReplyTo) is not one of this station's
2081
+ return send({ kind: 'station', name: `${req.from}@${station}`, hops: req.hops }, { to: req.to, subject: req.subject, body: req.body });
2082
+ }
2083
+ function sendFromAgent(from, generation, request) {
2084
+ return send({ kind: 'agent', name: from, generation }, request);
2085
+ }
2086
+ function readMessages(agent, generation) {
2087
+ const rt = agents.get(agent);
2088
+ if (!rt || rt.removed)
2089
+ return { count: 0, messages: [] };
2090
+ if (sessionEnded(rt, generation))
2091
+ throw new HubError('conflict', 'this session has ended');
2092
+ const unread = unreadFor(agent);
2093
+ // Claude Code refuses an MCP result of more than 25,000 tokens, and mail it refused would already be marked read.
2094
+ // The first message always goes (a single one is far below the cap); the rest waits for the next call.
2095
+ const result = [];
2096
+ let chars = 0;
2097
+ for (const record of unread) {
2098
+ const message = {
2099
+ id: record.id,
2100
+ from: record.from,
2101
+ subject: record.subject,
2102
+ body: record.body,
2103
+ inReplyTo: record.inReplyTo,
2104
+ at: record.at,
2105
+ };
2106
+ chars += JSON.stringify(message).length;
2107
+ if (result.length >= READ_MAX_MESSAGES || (result.length > 0 && chars > READ_MAX_CHARS))
2108
+ break;
2109
+ result.push(message);
2110
+ }
2111
+ const returned = unread.slice(0, result.length);
2112
+ const left = unread.slice(result.length);
2113
+ for (const record of returned) {
2114
+ setMessage(record, 'read', null);
2115
+ rt.pointed.delete(record.id);
2116
+ }
2117
+ rt.queue = left.map((record) => record.id);
2118
+ // A pointer in flight has nothing left to confirm: the agent is reading. The hook that should have confirmed it may
2119
+ // never come (silent hooks, a lost POST), and without this the 2 s timer would then leave a latch that makes every
2120
+ // later message wait until the user presses a key.
2121
+ if (rt.pendingConfirm || rt.unconfirmed)
2122
+ log.debug(`pointer confirmed by read_messages (${agent})`);
2123
+ cancelConfirm(rt);
2124
+ rt.unconfirmed = null;
2125
+ // What was left over is unread again, even when it had been pointed at or was waiting on the pointer just cancelled:
2126
+ // the usual paths (delivery check, Stop hook, draft latch, pointer counters) take it from here.
2127
+ for (const record of left) {
2128
+ if (record.status !== 'held')
2129
+ setMessage(record, 'queued', waitNote(rt));
2130
+ }
2131
+ syncHolds(rt);
2132
+ if (returned.length > 0) {
2133
+ rt.trigger = { ids: result.map((message) => message.id), maxHops: Math.max(...returned.map((record) => record.hops)) };
2134
+ }
2135
+ flush(rt);
2136
+ if (left.length === 0)
2137
+ return { count: result.length, messages: result };
2138
+ return { count: result.length, messages: result, remaining: left.length, note: READ_MORE_NOTE };
2139
+ }
2140
+ function rosterFor(agent, generation) {
2141
+ const rt = agents.get(agent);
2142
+ if (!rt || rt.removed)
2143
+ throw new HubError('not_found', 'unknown agent');
2144
+ if (sessionEnded(rt, generation))
2145
+ throw new HubError('conflict', 'this session has ended');
2146
+ const boss = bossRt();
2147
+ const entries = sortedAgents().map((other) => ({
2148
+ name: other.record.name,
2149
+ role: cutText(other.record.role, ROSTER_ROLE_CHARS),
2150
+ state: other.state,
2151
+ boss: other.record.boss,
2152
+ position: other.record.position ?? null,
2153
+ }));
2154
+ const docked = io.dock?.rosters() ?? [];
2155
+ return { you: agent, boss: boss ? boss.record.name : null, agents: entries, specialRecipients: ['boss', 'user'], ...(docked.length > 0 ? { docked } : {}) };
2156
+ }
2157
+ /* ---- T-minus ---- */
2158
+ function pollView() {
2159
+ return pollState === null ? null : { ...pollState, entries: pollState.entries.map((entry) => ({ ...entry })) };
2160
+ }
2161
+ function pollNote(poll) {
2162
+ switch (poll.status) {
2163
+ case 'open':
2164
+ return `waiting for ${poll.entries.filter((entry) => entry.vote === null).map((entry) => entry.agent).join(', ')}`;
2165
+ case 'go':
2166
+ return 'all go';
2167
+ case 'aborted':
2168
+ return 'aborted by the Director';
2169
+ case 'hold': {
2170
+ const refusing = poll.entries.filter((entry) => entry.vote === 'no-go').map((entry) => entry.agent);
2171
+ return holdBy === 'vote' && refusing.length > 0 ? `no-go: ${refusing.join(', ')}` : 'held by the Director';
2172
+ }
2173
+ }
2174
+ }
2175
+ /** Refreshes the note and emits a PollFrame when anything in the poll changed. */
2176
+ function publishPoll() {
2177
+ if (pollState)
2178
+ pollState.note = pollNote(pollState);
2179
+ const signature = JSON.stringify(pollState);
2180
+ if (signature === pollSig)
2181
+ return;
2182
+ pollSig = signature;
2183
+ emit({ t: 'poll', poll: pollView() });
2184
+ // The inbox hears each result once: a later vote that leaves the status as it is says nothing new.
2185
+ const result = pollState === null || pollState.status === 'open' ? '' : `${pollState.id}:${pollState.status}`;
2186
+ if (pollState !== null && result !== '' && result !== pollResult)
2187
+ io.notify?.('tminus', `${pollState.status.toUpperCase()}: ${pollState.note}`);
2188
+ pollResult = result;
2189
+ }
2190
+ function tellFromUser(to, subject, body) {
2191
+ sendFromUser({ to, subject, body });
2192
+ }
2193
+ /** An open poll ends in hold at the first no-go and in go when everybody voted go (and then the boss is told). */
2194
+ function settlePoll() {
2195
+ const poll = pollState;
2196
+ if (!poll || (poll.status !== 'open' && !(poll.status === 'hold' && holdBy === 'vote')))
2197
+ return;
2198
+ if (poll.entries.some((entry) => entry.vote === 'no-go')) {
2199
+ poll.status = 'hold';
2200
+ holdBy = 'vote';
2201
+ }
2202
+ else if (poll.entries.length > 0 && poll.entries.every((entry) => entry.vote === 'go')) {
2203
+ poll.status = 'go';
2204
+ const boss = bossRt();
2205
+ if (boss)
2206
+ tellFromUser(boss.record.name, 'T-minus: all go', 'Every polled position is go. Proceed.');
2207
+ }
2208
+ else {
2209
+ poll.status = 'open';
2210
+ }
2211
+ }
2212
+ /** The process of an entry ended (stop, restart, removal or crash): it counts as no-go for as long as the poll is live. */
2213
+ function pollEntryStopped(name) {
2214
+ const poll = pollState;
2215
+ if (!poll || (poll.status !== 'open' && poll.status !== 'hold'))
2216
+ return;
2217
+ const entry = poll.entries.find((candidate) => candidate.agent === name);
2218
+ if (!entry || entry.vote === 'no-go')
2219
+ return;
2220
+ entry.vote = 'no-go';
2221
+ entry.reason = 'stopped';
2222
+ entry.at = io.now();
2223
+ settlePoll();
2224
+ publishPoll();
2225
+ }
2226
+ function renamePollEntry(from, to) {
2227
+ const entry = pollState?.entries.find((candidate) => candidate.agent === from);
2228
+ if (!entry)
2229
+ return;
2230
+ entry.agent = to;
2231
+ publishPoll();
2232
+ }
2233
+ function pollTargets(value) {
2234
+ const running = (rt) => rt.state !== 'stopped' && rt.transition === null && mailable(rt);
2235
+ if (value === undefined)
2236
+ return sortedAgents().filter((rt) => running(rt) && !rt.record.boss);
2237
+ if (!Array.isArray(value) || value.some((name) => typeof name !== 'string')) {
2238
+ throw new HubError('bad_request', 'agents must be a list of agent names', 'agents');
2239
+ }
2240
+ return [...new Set(value)].map((name) => {
2241
+ const rt = agents.get(name);
2242
+ if (!rt || rt.removed)
2243
+ throw new HubError('bad_request', `unknown agent "${name}"`, 'agents');
2244
+ if (!mailable(rt)) {
2245
+ const what = isCustom(rt) ? 'a custom command' : `${providerInfo(rt.record.provider).label} without the gonogo tools`;
2246
+ throw new HubError('bad_request', `${name} runs ${what} and cannot vote`, 'agents');
2247
+ }
2248
+ if (!running(rt))
2249
+ throw new HubError('bad_request', `${name} is not running`, 'agents');
2250
+ return rt;
2251
+ });
2252
+ }
2253
+ function startPoll(request) {
2254
+ assertOpen();
2255
+ const req = asObject(request, 'the request');
2256
+ if (pollState !== null)
2257
+ throw new HubError('conflict', 'clear the poll first');
2258
+ const targets = pollTargets(req.agents);
2259
+ if (targets.length === 0)
2260
+ throw new HubError('bad_request', 'nobody to poll');
2261
+ pollSeq += 1;
2262
+ pollState = {
2263
+ id: pollSeq,
2264
+ startedAt: io.now(),
2265
+ status: 'open',
2266
+ entries: targets.map((rt) => ({ agent: rt.record.name, vote: null, reason: '', at: null })),
2267
+ note: '',
2268
+ };
2269
+ for (const rt of targets) {
2270
+ tellFromUser(rt.record.name, 'T-minus: go/no-go poll', 'The Director is polling for go or no-go. Call go_nogo with your vote and a one-sentence reason.');
2271
+ }
2272
+ publishPoll();
2273
+ return pollView();
2274
+ }
2275
+ function holdPoll() {
2276
+ assertOpen();
2277
+ if (pollState === null || pollState.status !== 'open')
2278
+ throw new HubError('conflict', 'no poll is open');
2279
+ pollState.status = 'hold';
2280
+ holdBy = 'director';
2281
+ publishPoll();
2282
+ return pollView();
2283
+ }
2284
+ function abortPoll() {
2285
+ assertOpen();
2286
+ if (pollState === null)
2287
+ throw new HubError('conflict', 'there is no poll');
2288
+ if (pollState.status !== 'aborted') {
2289
+ pollState.status = 'aborted';
2290
+ for (const entry of pollState.entries) {
2291
+ if (entry.vote !== 'no-go')
2292
+ tellFromUser(entry.agent, 'T-minus: aborted', 'The Director aborted the poll. Stand by.');
2293
+ }
2294
+ publishPoll();
2295
+ }
2296
+ return pollView();
2297
+ }
2298
+ function clearPoll() {
2299
+ pollState = null;
2300
+ publishPoll();
2301
+ }
2302
+ function vote(agent, generation, choice, reason) {
2303
+ const poll = pollState;
2304
+ if (!poll || poll.status === 'go' || poll.status === 'aborted')
2305
+ return { ok: false, note: 'no poll is open' };
2306
+ const entry = poll.entries.find((candidate) => candidate.agent === agent);
2307
+ if (!entry)
2308
+ return { ok: false, note: 'you are not in this poll' };
2309
+ const rt = agents.get(agent);
2310
+ if (!rt || rt.removed || sessionEnded(rt, generation))
2311
+ return { ok: false, note: 'this session has ended' };
2312
+ if (!POLL_VOTES.includes(choice))
2313
+ return { ok: false, note: 'vote must be go or no-go' };
2314
+ if (!takeSendSlot(rt, io.now()))
2315
+ return { ok: false, note: 'too many requests: wait a moment' };
2316
+ entry.vote = choice;
2317
+ entry.reason = cutText(typeof reason === 'string' ? collapseWhitespace(reason.replace(UNSAFE_IN_REASON, ' ')) : '', POLL_REASON_MAX_CHARS);
2318
+ entry.at = io.now();
2319
+ settlePoll();
2320
+ publishPoll();
2321
+ return { ok: true, note: `vote recorded: ${choice}` };
2322
+ }
2323
+ /* ---- browser input (contract 4.6) ---- */
2324
+ function onUserInput(name, data) {
2325
+ const effect = classifyInput(typeof data === 'string' ? data : '');
2326
+ const rt = typeof name === 'string' ? agents.get(name) : undefined;
2327
+ if (!rt || rt.removed || !mailable(rt))
2328
+ return effect;
2329
+ guarded('user input', () => {
2330
+ const now = io.now();
2331
+ rt.lastInputAt = now;
2332
+ if (rt.state === 'stopped')
2333
+ return;
2334
+ if (effect === 'set') {
2335
+ // Keystrokes that answer a dialog or a permission prompt are not a draft.
2336
+ if (rt.state === 'needs_you' || screenOf(rt)?.dialog)
2337
+ return;
2338
+ rt.draft = { lastKeyAt: now };
2339
+ syncHolds(rt);
2340
+ }
2341
+ else if (effect === 'clear') {
2342
+ rt.draft = null;
2343
+ rt.unconfirmed = null;
2344
+ syncHolds(rt);
2345
+ if (rt.queue.length > 0)
2346
+ scheduleDelivery(rt, DELIVERY_SETTLE_MS);
2347
+ }
2348
+ flush(rt);
2349
+ });
2350
+ return effect;
2351
+ }
2352
+ /* ---- start and shutdown (contract 4.9) ---- */
2353
+ function freeBossName() {
2354
+ if (!agents.has(BOSS_DEFAULT_NAME))
2355
+ return BOSS_DEFAULT_NAME;
2356
+ for (let suffix = 2;; suffix += 1) {
2357
+ const candidate = `${BOSS_DEFAULT_NAME}-${suffix}`;
2358
+ if (!agents.has(candidate))
2359
+ return candidate;
2360
+ }
2361
+ }
2362
+ async function doStart() {
2363
+ assertOpen();
2364
+ const roster = await io.loadRoster();
2365
+ for (const record of Array.isArray(roster?.agents) ? roster.agents : []) {
2366
+ if (!isRecord(record) || typeof record.name !== 'string' || agents.has(record.name)) {
2367
+ log.warn('skipping a roster record that is not usable');
2368
+ continue;
2369
+ }
2370
+ agents.set(record.name, makeRt({ ...record }));
2371
+ }
2372
+ if (bossRt() === null) {
2373
+ const boss = {
2374
+ name: freeBossName(),
2375
+ role: BOSS_ROLE,
2376
+ dir: options.bossDir,
2377
+ mode: 'default',
2378
+ sessionId: io.newSessionId(),
2379
+ desk: 0,
2380
+ boss: true,
2381
+ createdAt: io.now(),
2382
+ position: 'flight',
2383
+ };
2384
+ await saveRecords([...rosterRecords(), boss]);
2385
+ agents.set(boss.name, makeRt(boss));
2386
+ }
2387
+ let history = [];
2388
+ try {
2389
+ const loaded = await io.loadHistory(ACTIVITY_BACKLOG);
2390
+ history = loaded.map(sanitizeHistory).filter((record) => !!record);
2391
+ }
2392
+ catch (error) {
2393
+ log.warn('could not load the message history', error);
2394
+ }
2395
+ for (const record of history) {
2396
+ if (messages.has(record.id))
2397
+ continue;
2398
+ remember(record);
2399
+ // Queues live in memory only: whatever the log still shows as waiting will never be typed.
2400
+ if (waiting(record))
2401
+ setMessage(record, 'undelivered', SERVER_RESTARTED_NOTE);
2402
+ }
2403
+ armSweep();
2404
+ const boss = bossRt();
2405
+ if (boss)
2406
+ await enqueue(boss, 'restart', () => restartOp(boss), true);
2407
+ }
2408
+ function start() {
2409
+ started ??= doStart();
2410
+ return started;
2411
+ }
2412
+ function shutdown() {
2413
+ if (shutdownPromise)
2414
+ return shutdownPromise;
2415
+ closing = true;
2416
+ disarm(sweepTimer);
2417
+ sweepTimer = null;
2418
+ pollState = null;
2419
+ // Queued behind a running operation, so a spawn in flight finishes (and has a process to stop) before it is stopped.
2420
+ const stops = [...agents.values()].map((rt) => enqueue(rt, 'shutdown', () => terminateOp(rt)).catch((error) => log.error(`could not stop ${rt.record.name}`, error)));
2421
+ shutdownPromise = Promise.all(stops).then(() => {
2422
+ for (const rt of agents.values())
2423
+ cancelTimers(rt);
2424
+ });
2425
+ return shutdownPromise;
2426
+ }
2427
+ /* ---- the public API ---- */
2428
+ return {
2429
+ start,
2430
+ shutdown,
2431
+ views: () => sortedAgents().map(buildView),
2432
+ activity: () => {
2433
+ const items = [];
2434
+ for (let index = order.length - 1; index >= 0 && items.length < ACTIVITY_HUB_MAX; index -= 1) {
2435
+ const record = messages.get(order[index] ?? '');
2436
+ if (record)
2437
+ items.push(toItem(record));
2438
+ }
2439
+ return items;
2440
+ },
2441
+ hire,
2442
+ edit: async (name, request) => {
2443
+ assertOpen();
2444
+ const rt = lookup(name);
2445
+ return enqueue(rt, 'edit', () => editOp(rt, request));
2446
+ },
2447
+ restart: async (name) => {
2448
+ assertOpen();
2449
+ const rt = lookup(name);
2450
+ return enqueue(rt, 'restart', () => restartOp(rt), true);
2451
+ },
2452
+ stop: async (name) => {
2453
+ assertOpen();
2454
+ const rt = lookup(name);
2455
+ return enqueue(rt, 'stop', () => stopOp(rt), true);
2456
+ },
2457
+ remove: async (name) => {
2458
+ assertOpen();
2459
+ const rt = lookup(name);
2460
+ if (rt.record.boss)
2461
+ throw new HubError('conflict', 'the boss cannot be removed');
2462
+ return enqueue(rt, 'remove', () => removeOp(rt), true);
2463
+ },
2464
+ sendFromUser,
2465
+ sendFromStation,
2466
+ sendFromAgent,
2467
+ trip,
2468
+ resume,
2469
+ readMessages,
2470
+ rosterFor,
2471
+ onHook,
2472
+ onUserInput,
2473
+ onTerminalEvent,
2474
+ startPoll,
2475
+ holdPoll,
2476
+ abortPoll,
2477
+ clearPoll,
2478
+ vote,
2479
+ setGovernor,
2480
+ answer,
2481
+ governor: governorView,
2482
+ poll: pollView,
2483
+ };
2484
+ }