@ulm0/gonogo 0.1.1 → 0.1.2

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.
@@ -1,7 +1,8 @@
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';
1
+ import { DOING_MAX_CHARS, HISTORY_MAX, HISTORY_WINDOW_MS, HOLD_REASON, HOOK_EVENTS, MODEL_PATTERN, PERMISSION_MODES, POLL_VOTES, PROVIDERS, providerInfo, RESERVED_NAMES, STATIC_FIRE_POSITIONS, STATION_NAME_PATTERN, } from '../shared/protocol.js';
2
2
  import { POSITION_IDS } from '../shared/positions.js';
3
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
4
  import { parseCleanRoom } from './cleanroom.js';
5
+ import { checkKeys } from './clearance.js';
5
6
  import { parsePayload, payloadRefusal } from './payload.js';
6
7
  /** Every request the hub rejects is one of these; web.ts maps `code` to the HTTP status (contract 3.3). */
7
8
  export class HubError extends Error {
@@ -24,6 +25,9 @@ const STATION_RE = new RegExp(STATION_NAME_PATTERN);
24
25
  const payloadKey = (record) => (record.payload === undefined ? null : JSON.stringify(record.payload));
25
26
  /** The Clean Room setting of a record as text, for comparing: null when the agent runs on the host. */
26
27
  const cleanRoomKey = (record) => (record.cleanRoom === undefined ? null : JSON.stringify(record.cleanRoom));
28
+ /** The model and the keys (names and times) of a record as text, for comparing: a key set again has a new time, so a changed value shows as dirty too. */
29
+ const engineKey = (record) => JSON.stringify([record.model ?? null, record.keys ?? null]);
30
+ const MODEL_RE = new RegExp(MODEL_PATTERN);
27
31
  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
32
  const REPLY_ID_RE = /^m\d+$/;
29
33
  const REPLY_ID_MAX_CHARS = 40;
@@ -378,7 +382,8 @@ export function createHub(io, options) {
378
382
  running.mode !== record.mode ||
379
383
  running.command !== (record.command ?? null) ||
380
384
  running.payload !== payloadKey(record) ||
381
- running.cleanRoom !== cleanRoomKey(record)),
385
+ running.cleanRoom !== cleanRoomKey(record) ||
386
+ running.engine !== engineKey(record)),
382
387
  generation: rt.generation,
383
388
  exit: rt.exit ? { ...rt.exit } : null,
384
389
  position: record.position ?? null,
@@ -386,6 +391,8 @@ export function createHub(io, options) {
386
391
  command: record.command ?? null,
387
392
  payload: record.payload ?? null,
388
393
  cleanRoom: record.cleanRoom ?? null,
394
+ model: record.model ?? null,
395
+ keys: { ...record.keys },
389
396
  doing: rt.doing,
390
397
  history: trimHistory(rt.history, io.now()),
391
398
  };
@@ -584,7 +591,7 @@ export function createHub(io, options) {
584
591
  return `held: text in ${rt.record.name}'s input`;
585
592
  }
586
593
  function redlineNote(rt) {
587
- return `held: redline on ${rt.record.name}`;
594
+ return rt.redline === HOLD_REASON ? `held: ${rt.record.name} is on hold` : `held: redline on ${rt.record.name}`;
588
595
  }
589
596
  function holdNote(rt) {
590
597
  if (rt.redline !== null)
@@ -798,19 +805,23 @@ export function createHub(io, options) {
798
805
  rt.apiErrorAt = [];
799
806
  rt.sentTo.clear();
800
807
  }
801
- /** Trips the breaker: Escape interrupts a turn in progress, the state reads needs_you and the mail waits. */
802
- function tripRt(rt, reason) {
808
+ /** Trips the breaker: Escape interrupts a turn in progress, the state reads needs_you and the mail waits. A Hold is a trip the Director asked for. */
809
+ function tripRt(rt, reason, byHand = false) {
803
810
  if (rt.redline !== null || rt.removed || !hooked(rt) || rt.state === 'stopped' || rt.transition !== null)
804
811
  return;
805
812
  const wasWorking = rt.state === 'working';
806
- rt.redline = `redline: ${reason}`;
807
- log.warn(`${rt.record.name} tripped the redline: ${reason}`);
813
+ rt.redline = byHand ? HOLD_REASON : `redline: ${reason}`;
814
+ if (byHand)
815
+ log.info(`${rt.record.name} is on hold`);
816
+ else
817
+ log.warn(`${rt.record.name} tripped the redline: ${reason}`);
808
818
  if (wasWorking && !io.press?.(rt.record.name, rt.generation, ESC)) {
809
819
  log.warn(`could not interrupt ${rt.record.name}`);
810
820
  }
811
821
  setState(rt, 'needs_you');
812
822
  syncHolds(rt);
813
- io.notify?.('redline', `${rt.record.name}: ${reason}`);
823
+ if (!byHand)
824
+ io.notify?.('redline', `${rt.record.name}: ${reason}`);
814
825
  }
815
826
  /** The automatic detectors trip only when they are on; a Propellant limit trips through Hub.trip either way. */
816
827
  function detect(rt, reason) {
@@ -834,6 +845,22 @@ export function createHub(io, options) {
834
845
  tripRt(rt, reason);
835
846
  flush(rt);
836
847
  }
848
+ function hold(name) {
849
+ assertOpen();
850
+ const rt = lookup(name);
851
+ const who = rt.record.name;
852
+ if (!hooked(rt))
853
+ throw new HubError('conflict', `${who} reports no hooks, so gonogo cannot hold it`);
854
+ if (rt.redline !== null)
855
+ throw new HubError('conflict', rt.redline === HOLD_REASON ? `${who} is already on hold` : `${who} has tripped the redline: resume or stop it`);
856
+ if (rt.state === 'needs_you' && rt.transition === null)
857
+ throw new HubError('conflict', `${who} needs you: answer it first`);
858
+ if ((rt.state !== 'idle' && rt.state !== 'working') || rt.transition !== null)
859
+ throw new HubError('conflict', `${who} is not running`);
860
+ tripRt(rt, HOLD_REASON, true);
861
+ flush(rt);
862
+ return buildView(rt);
863
+ }
837
864
  function resume(name) {
838
865
  assertOpen();
839
866
  const rt = lookup(name);
@@ -848,6 +875,15 @@ export function createHub(io, options) {
848
875
  flush(rt);
849
876
  return buildView(rt);
850
877
  }
878
+ /** Telemetry: every tool hook goes to the recorder; a failure there never touches the hub's own handling. */
879
+ function toolHook(rt, event, payload) {
880
+ try {
881
+ io.toolHook?.(rt.record.name, event, payload);
882
+ }
883
+ catch (error) {
884
+ log.warn('telemetry failed', error);
885
+ }
886
+ }
851
887
  /** Propellant reads the transcript at most every METER_INTERVAL_MS on a tool hook, and at every Stop. */
852
888
  function meter(rt, payload, force) {
853
889
  const path = payload.transcript_path;
@@ -985,15 +1021,18 @@ export function createHub(io, options) {
985
1021
  onPromptSubmit(rt, payload);
986
1022
  break;
987
1023
  case 'PreToolUse':
1024
+ toolHook(rt, input.event, payload);
988
1025
  rt.doing = describeDoing(payload.tool_name, payload.tool_input);
989
1026
  onToolHook(rt);
990
1027
  detect(rt, repeatReason(rt, payload));
991
1028
  meter(rt, payload, false);
992
1029
  break;
993
1030
  case 'PostToolUse':
1031
+ toolHook(rt, input.event, payload);
994
1032
  onToolHook(rt);
995
1033
  break;
996
1034
  case 'PostToolUseFailure':
1035
+ toolHook(rt, input.event, payload);
997
1036
  onToolHook(rt);
998
1037
  if (countRecent(rt.toolFailAt, io.now(), REDLINE_TOOL_FAILURE_WINDOW_MS) >= REDLINE_TOOL_FAILURES) {
999
1038
  detect(rt, `error storm: ${rt.toolFailAt.length} failed tool calls in 2 min`);
@@ -1404,7 +1443,7 @@ export function createHub(io, options) {
1404
1443
  rt.pointed.clear();
1405
1444
  rt.screenClearSince = null;
1406
1445
  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) };
1446
+ 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), engine: engineKey(rt.record) };
1408
1447
  rt.flag = flag;
1409
1448
  // The browser reacts to a new generation by attaching, so the frame waits until the process exists in the terminal host.
1410
1449
  rt.frameHold = true;
@@ -1522,6 +1561,12 @@ export function createHub(io, options) {
1522
1561
  settlePoll();
1523
1562
  publishPoll();
1524
1563
  }
1564
+ try {
1565
+ await io.keys?.remove(rt.record.name);
1566
+ }
1567
+ catch (error) {
1568
+ log.warn(`could not remove the keys of ${rt.record.name}`, error);
1569
+ }
1525
1570
  // The process is gone (stopped above, or never ran): the terminal's mirror and scrollback can go too.
1526
1571
  try {
1527
1572
  io.forget?.(rt.record.name);
@@ -1612,6 +1657,40 @@ export function createHub(io, options) {
1612
1657
  delete target.cleanRoom;
1613
1658
  else
1614
1659
  target.cleanRoom = from.cleanRoom;
1660
+ if (from.model === undefined)
1661
+ delete target.model;
1662
+ else
1663
+ target.model = from.model;
1664
+ if (from.keys === undefined)
1665
+ delete target.keys;
1666
+ else
1667
+ target.keys = from.keys;
1668
+ }
1669
+ /** The model for `--model`: empty text is none. Only an engine that takes one (PROVIDER_INFO.model). A bad value is 400, field model. */
1670
+ function checkModel(provider, value) {
1671
+ if (value === undefined || value === null)
1672
+ return undefined;
1673
+ if (typeof value !== 'string')
1674
+ throw new HubError('bad_request', 'model must be text', 'model');
1675
+ const model = value.trim();
1676
+ if (model === '')
1677
+ return undefined;
1678
+ if (providerInfo(provider).model === null) {
1679
+ throw new HubError('bad_request', `${providerInfo(provider).label} takes no model setting`, 'model');
1680
+ }
1681
+ if (!MODEL_RE.test(model)) {
1682
+ throw new HubError('bad_request', 'model must be 1 to 100 letters, digits or . _ : / @ + -, starting with a letter or digit', 'model');
1683
+ }
1684
+ return model;
1685
+ }
1686
+ /** The keys of a request: their values to the key store and their names with times for the record. A bad one is 400, field keys. */
1687
+ function checkKeysOf(value, current, hireRequest) {
1688
+ const checked = checkKeys(value, current, io.now(), hireRequest);
1689
+ if (!checked.ok)
1690
+ throw new HubError('bad_request', checked.error, 'keys');
1691
+ if (io.keys === undefined && Object.keys(checked.patch).length > 0)
1692
+ throw new HubError('bad_request', 'this server cannot keep keys', 'keys');
1693
+ return { patch: checked.patch, names: Object.keys(checked.names).length === 0 ? undefined : checked.names };
1615
1694
  }
1616
1695
  /** The shape of a payload and whether the engine takes it (no disk). A bad value is 400 with the field it names. */
1617
1696
  function checkPayload(provider, value) {
@@ -1703,6 +1782,8 @@ export function createHub(io, options) {
1703
1782
  }
1704
1783
  const command = custom ? checkCommand(req.command) : undefined;
1705
1784
  const payload = checkPayload(provider, req.payload);
1785
+ const model = checkModel(provider, req.model);
1786
+ const kept = req.keys === undefined ? undefined : checkKeysOf(req.keys, undefined, true);
1706
1787
  // A CLI without permission modes (a custom command among them): the mode and confirmBypass of the request are ignored.
1707
1788
  const mode = providerInfo(provider).modes ? checkMode(req.mode) : 'default';
1708
1789
  // The name is claimed while the checks and the save await, so two hires cannot take the same name or the same desk.
@@ -1735,8 +1816,20 @@ export function createHub(io, options) {
1735
1816
  record.payload = payload;
1736
1817
  if (cleanRoom)
1737
1818
  record.cleanRoom = cleanRoom;
1819
+ if (model)
1820
+ record.model = model;
1821
+ if (kept?.names)
1822
+ record.keys = kept.names;
1738
1823
  hiring.set(name, record);
1739
- await saveRecords(rosterRecords());
1824
+ // The values first, from none (a removed agent of this name may have left some), then the roster; a roster that cannot be saved takes them back.
1825
+ await io.keys?.apply(name, kept?.patch ?? {}, true);
1826
+ try {
1827
+ await saveRecords(rosterRecords());
1828
+ }
1829
+ catch (error) {
1830
+ await io.keys?.remove(name).catch(() => undefined);
1831
+ throw error;
1832
+ }
1740
1833
  hired = makeRt(record);
1741
1834
  agents.set(name, hired);
1742
1835
  }
@@ -1755,13 +1848,14 @@ export function createHub(io, options) {
1755
1848
  if (rt.removed)
1756
1849
  throw new HubError('not_found', 'unknown agent');
1757
1850
  const req = asObject(request, 'the request');
1758
- const fields = ['name', 'role', 'dir', 'mode', 'confirmBypass', 'position', 'command', 'payload', 'cleanRoom'];
1851
+ const fields = ['name', 'role', 'dir', 'mode', 'confirmBypass', 'position', 'command', 'payload', 'cleanRoom', 'model', 'keys'];
1759
1852
  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');
1853
+ throw new HubError('bad_request', 'nothing to change: send at least one of name, role, dir, mode, position, command, payload, cleanRoom, model, keys');
1761
1854
  }
1762
1855
  const current = rt.record;
1763
1856
  const next = { ...current };
1764
1857
  let newName = null;
1858
+ let keyPatch = null;
1765
1859
  try {
1766
1860
  if (req.name !== undefined) {
1767
1861
  const name = checkName(req.name);
@@ -1805,6 +1899,21 @@ export function createHub(io, options) {
1805
1899
  else
1806
1900
  next.cleanRoom = await checkCleanRoom(current.provider ?? 'claude', req.cleanRoom, next.dir);
1807
1901
  }
1902
+ if (req.model !== undefined) {
1903
+ const model = checkModel(current.provider ?? 'claude', req.model);
1904
+ if (model)
1905
+ next.model = model;
1906
+ else
1907
+ delete next.model;
1908
+ }
1909
+ if (req.keys !== undefined) {
1910
+ const kept = checkKeysOf(req.keys, current.keys, false);
1911
+ keyPatch = kept.patch;
1912
+ if (kept.names)
1913
+ next.keys = kept.names;
1914
+ else
1915
+ delete next.keys;
1916
+ }
1808
1917
  if (next.mode === 'bypassPermissions' && next.mode !== current.mode && req.confirmBypass !== true) {
1809
1918
  throw new HubError('bad_request', 'bypassPermissions needs confirmBypass: true', 'confirmBypass');
1810
1919
  }
@@ -1822,7 +1931,8 @@ export function createHub(io, options) {
1822
1931
  next.position !== current.position ||
1823
1932
  next.command !== current.command ||
1824
1933
  payloadKey(next) !== payloadKey(current) ||
1825
- cleanRoomKey(next) !== cleanRoomKey(current);
1934
+ cleanRoomKey(next) !== cleanRoomKey(current) ||
1935
+ engineKey(next) !== engineKey(current);
1826
1936
  if (!changed)
1827
1937
  return buildView(rt);
1828
1938
  const oldName = current.name;
@@ -1843,10 +1953,19 @@ export function createHub(io, options) {
1843
1953
  agents.set(newName, rt);
1844
1954
  renamePollEntry(oldName, newName);
1845
1955
  }
1956
+ // What the keys the edit touches hold now, as a patch that puts them back: a key that was not there goes again (null).
1957
+ const held = io.keys?.values(next.name) ?? {};
1958
+ const putBack = Object.fromEntries(Object.keys(keyPatch ?? {}).map((key) => [key, held[key] ?? null]));
1846
1959
  try {
1960
+ if (keyPatch !== null && Object.keys(keyPatch).length > 0)
1961
+ await io.keys?.apply(next.name, keyPatch);
1847
1962
  await saveRecords(rosterRecords());
1848
1963
  }
1849
1964
  catch (error) {
1965
+ // The values were written before the roster; they go back first, while the keys are still under the new name.
1966
+ // shortcut: when this write fails as well, the new values stay and the log says so; upgrade if disk errors matter.
1967
+ if (Object.keys(putBack).length > 0)
1968
+ await io.keys?.apply(next.name, putBack).catch((undo) => log.error('could not put the keys back', undo));
1850
1969
  assignFields(current, previous);
1851
1970
  if (newName !== null) {
1852
1971
  agents.delete(newName);
@@ -2183,25 +2302,35 @@ export function createHub(io, options) {
2183
2302
  emit({ t: 'poll', poll: pollView() });
2184
2303
  // The inbox hears each result once: a later vote that leaves the status as it is says nothing new.
2185
2304
  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}`);
2305
+ if (pollState !== null && result !== '' && result !== pollResult) {
2306
+ const line = `${pollState.status.toUpperCase()}: ${pollState.note}`;
2307
+ // A static fire is about the answers: they go to the inbox with the result.
2308
+ const answers = pollState.entries.flatMap((entry) => (entry.reason !== '' ? [`${entry.agent}: ${entry.reason}`] : []));
2309
+ io.notify?.('tminus', pollState.subject === undefined ? line : [`Static fire on ${pollState.subject}: ${line}`, ...answers].join(' · '));
2310
+ }
2188
2311
  pollResult = result;
2189
2312
  }
2190
2313
  function tellFromUser(to, subject, body) {
2191
2314
  sendFromUser({ to, subject, body });
2192
2315
  }
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). */
2316
+ /**
2317
+ * An open poll ends in hold at the first no-go and in go when everybody voted go (and then the boss is told). A static fire
2318
+ * waits for every answer (the break report and the rollback plan both matter) and tells nobody: the Director reads the result.
2319
+ */
2194
2320
  function settlePoll() {
2195
2321
  const poll = pollState;
2196
2322
  if (!poll || (poll.status !== 'open' && !(poll.status === 'hold' && holdBy === 'vote')))
2197
2323
  return;
2198
- if (poll.entries.some((entry) => entry.vote === 'no-go')) {
2324
+ if (poll.subject !== undefined && poll.entries.some((entry) => entry.vote === null)) {
2325
+ poll.status = 'open';
2326
+ }
2327
+ else if (poll.entries.some((entry) => entry.vote === 'no-go')) {
2199
2328
  poll.status = 'hold';
2200
2329
  holdBy = 'vote';
2201
2330
  }
2202
2331
  else if (poll.entries.length > 0 && poll.entries.every((entry) => entry.vote === 'go')) {
2203
2332
  poll.status = 'go';
2204
- const boss = bossRt();
2333
+ const boss = poll.subject === undefined ? bossRt() : undefined;
2205
2334
  if (boss)
2206
2335
  tellFromUser(boss.record.name, 'T-minus: all go', 'Every polled position is go. Proceed.');
2207
2336
  }
@@ -2255,9 +2384,12 @@ export function createHub(io, options) {
2255
2384
  const req = asObject(request, 'the request');
2256
2385
  if (pollState !== null)
2257
2386
  throw new HubError('conflict', 'clear the poll first');
2258
- const targets = pollTargets(req.agents);
2387
+ const subject = staticFireSubject(req);
2388
+ const targets = subject === undefined
2389
+ ? pollTargets(req.agents)
2390
+ : pollTargets(undefined).filter((rt) => STATIC_FIRE_POSITIONS.includes(rt.record.position ?? ''));
2259
2391
  if (targets.length === 0)
2260
- throw new HubError('bad_request', 'nobody to poll');
2392
+ throw new HubError('bad_request', subject === undefined ? 'nobody to poll' : 'no SIMSUP or RETRO is running');
2261
2393
  pollSeq += 1;
2262
2394
  pollState = {
2263
2395
  id: pollSeq,
@@ -2265,13 +2397,34 @@ export function createHub(io, options) {
2265
2397
  status: 'open',
2266
2398
  entries: targets.map((rt) => ({ agent: rt.record.name, vote: null, reason: '', at: null })),
2267
2399
  note: '',
2400
+ ...(subject === undefined ? {} : { subject }),
2268
2401
  };
2269
2402
  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.');
2403
+ if (subject === undefined) {
2404
+ 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.');
2405
+ }
2406
+ else if (rt.record.position === 'simsup') {
2407
+ tellFromUser(rt.record.name, `Static fire: ${subject}`, `Before this ships, try to break it: ${subject}. Then call go_nogo: go if it held, no-go with what broke in one sentence (write the steps to reproduce to the Mission Log).`);
2408
+ }
2409
+ else {
2410
+ tellFromUser(rt.record.name, `Static fire: ${subject}`, `Before this ships, write the rollback plan for: ${subject}. Put the plan in the Mission Log with log_write, then call go_nogo: go when it can be rolled back, no-go if it cannot, with a one-sentence reason.`);
2411
+ }
2271
2412
  }
2272
2413
  publishPoll();
2273
2414
  return pollView();
2274
2415
  }
2416
+ /** The subject of a static fire, one clean line; undefined for a T-minus poll. */
2417
+ function staticFireSubject(req) {
2418
+ if (req.subject === undefined)
2419
+ return undefined;
2420
+ if (req.agents !== undefined)
2421
+ throw new HubError('bad_request', 'a static fire picks SIMSUP and RETRO itself', 'agents');
2422
+ const max = SUBJECT_MAX_CHARS - 'Static fire: '.length;
2423
+ const subject = typeof req.subject === 'string' ? collapseWhitespace(req.subject.replace(UNSAFE_IN_REASON, ' ')) : '';
2424
+ if (subject === '' || subject.length > max)
2425
+ throw new HubError('bad_request', `subject must be text of 1 to ${max} characters`, 'subject');
2426
+ return subject;
2427
+ }
2275
2428
  function holdPoll() {
2276
2429
  assertOpen();
2277
2430
  if (pollState === null || pollState.status !== 'open')
@@ -2288,8 +2441,12 @@ export function createHub(io, options) {
2288
2441
  if (pollState.status !== 'aborted') {
2289
2442
  pollState.status = 'aborted';
2290
2443
  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.');
2444
+ if (entry.vote !== 'no-go') {
2445
+ if (pollState.subject === undefined)
2446
+ tellFromUser(entry.agent, 'T-minus: aborted', 'The Director aborted the poll. Stand by.');
2447
+ else
2448
+ tellFromUser(entry.agent, 'Static fire: aborted', 'The Director aborted the static fire. Stand by.');
2449
+ }
2293
2450
  }
2294
2451
  publishPoll();
2295
2452
  }
@@ -2465,6 +2622,7 @@ export function createHub(io, options) {
2465
2622
  sendFromStation,
2466
2623
  sendFromAgent,
2467
2624
  trip,
2625
+ hold,
2468
2626
  resume,
2469
2627
  readMessages,
2470
2628
  rosterFor,
@@ -98,6 +98,7 @@ export function buildArgv(input) {
98
98
  '--mcp-config',
99
99
  input.mcpPath,
100
100
  ...(input.pluginDir ? ['--plugin-dir', input.pluginDir] : []),
101
+ ...(input.model ? ['--model', input.model] : []),
101
102
  '--append-system-prompt',
102
103
  input.roleText,
103
104
  '--system-prompt-snapshot',
@@ -147,6 +148,7 @@ export function buildChildEnv(input) {
147
148
  continue;
148
149
  env[key] = value;
149
150
  }
151
+ Object.assign(env, input.keys);
150
152
  if (input.seed) {
151
153
  env.IS_DEMO = '1';
152
154
  // A plain ANTHROPIC_API_KEY triggers a dialog whose default is "No" (or "Not logged in" under IS_DEMO)
@@ -391,7 +393,7 @@ export function createLauncher(options) {
391
393
  const dirInfo = await stat(agent.dir).catch(() => null);
392
394
  if (!dirInfo?.isDirectory())
393
395
  throw new Error(`working directory does not exist: ${agent.dir}`);
394
- return { spec: { file, args, env: buildChildEnv({ base: options.env ?? process.env, token: null, seed: false }), cwd: agent.dir }, flag: 'session-id', token: '' };
396
+ return { spec: { file, args, env: buildChildEnv({ base: options.env ?? process.env, token: null, seed: false, keys: options.keys?.(name) }), cwd: agent.dir }, flag: 'session-id', token: '' };
395
397
  };
396
398
  /** Engine Bay: another agent CLI, started by its program name with the files and flags of its adapter (providers.ts). */
397
399
  const prepareOther = async (agent, provider, base, hubUrl, memoryPath, token) => {
@@ -406,11 +408,12 @@ export function createLauncher(options) {
406
408
  tokenFile: join(base, AGENT_TOKEN_FILE),
407
409
  token,
408
410
  seed: options.seed,
411
+ model: agent.model,
409
412
  };
410
413
  const start = buildProviderStart(provider, ctx);
411
414
  for (const [file, content] of Object.entries(start.files))
412
415
  await writeFileAtomic(join(base, file), content, FILE_MODE);
413
- const env = { ...buildChildEnv({ base: options.env ?? process.env, token, seed: false }), ...start.env };
416
+ const env = { ...buildChildEnv({ base: options.env ?? process.env, token, seed: false, keys: options.keys?.(agent.name) }), ...start.env };
414
417
  log.debug(`prepared ${agent.name} to run ${provider}`);
415
418
  return { spec: { file: PROVIDER_INFO[provider].bin, args: start.args, env, cwd: agent.dir }, flag: 'session-id', token };
416
419
  };
@@ -459,7 +462,8 @@ export function createLauncher(options) {
459
462
  const agentUrl = clean === null ? hubUrl : containerUrl(hubUrl);
460
463
  const settingsPath = join(base, SETTINGS_FILE);
461
464
  const mcpPath = join(base, MCP_FILE);
462
- const moveApiKey = seed && hasText(env.ANTHROPIC_API_KEY);
465
+ const keys = options.keys?.(name) ?? {};
466
+ const moveApiKey = seed && hasText(keys.ANTHROPIC_API_KEY ?? env.ANTHROPIC_API_KEY);
463
467
  const settings = buildSettings({ hubUrl: agentUrl, name, mode: agent.mode, memoryPath, apiKeyHelper: moveApiKey });
464
468
  await writeFileAtomic(settingsPath, JSON.stringify(settings, null, 2), FILE_MODE);
465
469
  await writeFileAtomic(mcpPath, JSON.stringify(buildMcpConfig(agentUrl, agent.payload?.mcpServers), null, 2), FILE_MODE);
@@ -489,9 +493,9 @@ export function createLauncher(options) {
489
493
  const projectsRoot = join(clean === null ? configDir ?? join(homedir(), '.claude') : clean.home, 'projects');
490
494
  const flag = opts.flag ?? ((await transcriptExists(projectsRoot, clean === null ? [dir, realDir] : [clean.cwd], agent.sessionId)) ? 'resume' : 'session-id');
491
495
  const roleText = buildRoleText(name, agent.role, memoryPath) + (clean === null ? '' : `\n${CLEAN_ROOM_NOTE.replace('{branch}', cleanRoomBranch(name))}`);
492
- const claudeArgs = buildArgv({ flag, sessionId: agent.sessionId, mode: agent.mode, settingsPath, mcpPath, roleText, pluginDir });
496
+ const claudeArgs = buildArgv({ flag, sessionId: agent.sessionId, mode: agent.mode, settingsPath, mcpPath, roleText, pluginDir, model: agent.model });
493
497
  const [file, ...leading] = options.agentCmd?.length ? options.agentCmd : [options.claudeBin ?? CLAUDE_BIN];
494
- const childEnv = buildChildEnv({ base: env, token, seed });
498
+ const childEnv = buildChildEnv({ base: env, token, seed, keys });
495
499
  let spec;
496
500
  if (clean === null) {
497
501
  spec = { file, args: [...leading, ...claudeArgs], env: childEnv, cwd: agent.dir };
@@ -502,7 +506,8 @@ export function createLauncher(options) {
502
506
  if (uid === undefined || gid === undefined)
503
507
  throw new Error('Clean Room needs a user id: it runs on macOS and Linux only');
504
508
  // by name: docker reads the values from its own environment, so no secret is on the command line
505
- const names = [...CLEAN_ROOM_ENV, ...CLEAN_ROOM_CREDENTIALS].filter((variable) => hasText(childEnv[variable]));
509
+ // The agent's own keys go the same way: the container gets their names, and nothing else of the host's environment.
510
+ const names = [...new Set([...CLEAN_ROOM_ENV, ...CLEAN_ROOM_CREDENTIALS, ...Object.keys(keys)])].filter((variable) => hasText(childEnv[variable]));
506
511
  const command = [file, ...leading, ...claudeArgs];
507
512
  const args = buildDockerArgs({ image: cleanRoomImage(agent.cleanRoom ?? {}, env), uid, gid, place: clean, agentDir: base, names, command });
508
513
  spec = { file: DOCKER_BIN, args, env: childEnv, cwd: clean.worktree };
@@ -0,0 +1,58 @@
1
+ export const CHART_ENTRIES_MAX = 150;
2
+ export const CHART_TAGS_MAX = 40;
3
+ /** Two tags are joined by a co-occurrence edge when this many entries hold both. */
4
+ export const COOCCUR_MIN = 2;
5
+ /** An entry id as a word of its own: `l12`, `(l12)`, `l12.`; not `cl12`, `l12x` or `l12-b`. */
6
+ const MENTION = /(?<![\p{L}\p{N}_-])l([1-9]\d{0,5})(?![\p{L}\p{N}_-])/gu;
7
+ /** The ids of other entries named in a text, each once, in order of appearance. */
8
+ export function mentions(text, self) {
9
+ const found = new Set();
10
+ for (const match of text.matchAll(MENTION))
11
+ if (`l${match[1]}` !== self)
12
+ found.add(`l${match[1]}`);
13
+ return [...found];
14
+ }
15
+ export function buildChart(all) {
16
+ const shown = [...all].sort((a, b) => b.updatedAt - a.updatedAt || b.createdAt - a.createdAt || a.id.localeCompare(b.id)).slice(0, CHART_ENTRIES_MAX);
17
+ const ids = new Set(shown.map((e) => e.id));
18
+ const uses = new Map();
19
+ for (const entry of shown)
20
+ for (const tag of entry.tags)
21
+ uses.set(tag, (uses.get(tag) ?? 0) + 1);
22
+ const tags = [...uses].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, CHART_TAGS_MAX);
23
+ const tagged = new Set(tags.map(([tag]) => tag));
24
+ const authors = new Map();
25
+ for (const entry of shown)
26
+ authors.set(entry.author, (authors.get(entry.author) ?? 0) + 1);
27
+ const edges = [];
28
+ const named = new Map();
29
+ const together = new Map();
30
+ for (const entry of shown) {
31
+ const from = `entry:${entry.id}`;
32
+ for (const tag of entry.tags)
33
+ if (tagged.has(tag))
34
+ edges.push({ from, to: `tag:${tag}`, kind: 'tag', weight: 1 });
35
+ edges.push({ from, to: `author:${entry.author}`, kind: 'author', weight: 1 });
36
+ for (const id of mentions(`${entry.title}\n${entry.body}`, entry.id)) {
37
+ if (!ids.has(id))
38
+ continue;
39
+ edges.push({ from, to: `entry:${id}`, kind: 'mention', weight: 1 });
40
+ named.set(id, (named.get(id) ?? 0) + 1);
41
+ }
42
+ const own = entry.tags.filter((t) => tagged.has(t)).sort();
43
+ for (let i = 0; i < own.length; i += 1)
44
+ for (let j = i + 1; j < own.length; j += 1)
45
+ together.set(`${own[i]}\n${own[j]}`, (together.get(`${own[i]}\n${own[j]}`) ?? 0) + 1);
46
+ }
47
+ for (const [pair, weight] of [...together].sort((a, b) => a[0].localeCompare(b[0]))) {
48
+ const [a = '', b = ''] = pair.split('\n');
49
+ if (weight >= COOCCUR_MIN)
50
+ edges.push({ from: `tag:${a}`, to: `tag:${b}`, kind: 'cooccur', weight });
51
+ }
52
+ const nodes = [
53
+ ...shown.map((e) => ({ id: `entry:${e.id}`, kind: 'entry', ref: e.id, label: e.title, weight: 1 + (named.get(e.id) ?? 0) })),
54
+ ...tags.map(([tag, weight]) => ({ id: `tag:${tag}`, kind: 'tag', ref: tag, label: tag, weight })),
55
+ ...[...authors].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([name, weight]) => ({ id: `author:${name}`, kind: 'author', ref: name, label: name, weight })),
56
+ ];
57
+ return { total: all.length, shown: shown.length, nodes, edges };
58
+ }