@ulm0/gonogo 0.1.2 → 0.2.0

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.
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
  import { PROTOCOL_VERSION } from '../shared/protocol.js';
8
8
  import { MAX_AGENTS } from '../shared/protocol.js';
9
9
  import { CLAUDE_BIN, DEFAULT_HOME_DIRNAME, DEFAULT_HOST, DEFAULT_MAX_HOPS, DEFAULT_PORT, DOWNLINK_HISTORY, MAX_HOPS_LIMIT, MAX_WORKING_ENV, REDLINE_ENV, ROSTER_ROLE_CHARS, SHUTDOWN_MAX_MS, STATION_ENV, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_PREFIXES, createLogger, nullLogger, } from './constants.js';
10
- import { audited, BOARD_AUDIT, DOCKING_AUDIT, HUB_AUDIT, LIVERIES_AUDIT, pollText, PROPELLANT_AUDIT, RELAY_AUDIT, SCHEDULES_AUDIT, TASKS_AUDIT, tripText, UPLINKS_AUDIT } from './audited.js';
10
+ import { audited, BOARD_AUDIT, DOCKING_AUDIT, HUB_AUDIT, LIVERIES_AUDIT, MISSIONS_AUDIT, pollText, PRICES_AUDIT, PROPELLANT_AUDIT, RELAY_AUDIT, RELIEF_AUDIT, SCHEDULES_AUDIT, TASKS_AUDIT, tripText, UPLINKS_AUDIT } from './audited.js';
11
11
  import { createBlackBox } from './blackbox.js';
12
12
  import { createBoard } from './board.js';
13
13
  import { createDocking, stationName } from './docking.js';
@@ -16,22 +16,27 @@ import { createHub } from './hub.js';
16
16
  import { createHangar, createRoots } from './hangar.js';
17
17
  import { createRecorder } from './recorder.js';
18
18
  import { checkCleanRoom } from './cleanroom.js';
19
+ import { checkWorktree, removeWorktree, worktreeBranch, worktreePath, worktreeStatus } from './worktree.js';
19
20
  import { openHome } from './home.js';
20
21
  import { createLauncher, parseAgentCmd } from './launcher.js';
21
22
  import { createTerminalHost } from './terminal.js';
22
23
  import { createWebServer } from './web.js';
23
24
  import { createPropellant } from './propellant.js';
25
+ import { createPrices } from './prices.js';
24
26
  import { createTelemetry } from './telemetry.js';
25
27
  import { createRelay } from './relay.js';
26
28
  import { createSchedules } from './schedules.js';
27
29
  import { createLiveries } from './livery.js';
30
+ import { createPhone } from './phone.js';
28
31
  import { createRelief } from './relief.js';
29
32
  import { createMassBudget } from './massbudget.js';
30
33
  import { createMissionLog } from './missionlog.js';
34
+ import { createMissions } from './missions.js';
31
35
  import { createTasks } from './tasks.js';
32
36
  import { createUplinks } from './uplinks.js';
33
37
  import { checkEngines, formatDoctor, installedProviders, onPath } from './providers.js';
34
38
  import { createClearance } from './clearance.js';
39
+ import { createModelDefaults } from './models.js';
35
40
  import { cachedLatest, createRollout, isNewer, updateCheckOff, updateCommand, updateText } from './rollout.js';
36
41
  /* ---------------------------------------------------------------- arguments */
37
42
  export const USAGE = `Usage: gonogo [options]
@@ -259,6 +264,8 @@ export async function startGonogo(options = {}) {
259
264
  }
260
265
  const clearance = createClearance({ dir: home.dir, log: log.child('clearance') });
261
266
  await clearance.load();
267
+ const modelDefaults = createModelDefaults({ dir: home.dir, log: log.child('models') });
268
+ await modelDefaults.load();
262
269
  const launcher = createLauncher({
263
270
  homeDir: home.dir,
264
271
  hubUrl: () => baseUrl,
@@ -266,10 +273,19 @@ export async function startGonogo(options = {}) {
266
273
  env,
267
274
  agentCmd,
268
275
  keys: (name) => clearance.values(name),
276
+ defaultModel: (provider) => modelDefaults.get(provider),
269
277
  log: log.child('launcher'),
270
278
  });
279
+ const prices = createPrices({ dir: home.dir, log: log.child('prices') });
280
+ await prices.load();
271
281
  const propellant = createPropellant({
272
282
  dir: home.dir,
283
+ prices: () => prices.table(),
284
+ // the 80 % budget warning: the inbox and Relay, not the Black Box (it is not a trip)
285
+ notify: (kind, text) => {
286
+ downlink.post(kind, text);
287
+ relay.event(kind, text);
288
+ },
273
289
  projectsRoot: join(env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude'), 'projects'),
274
290
  now: () => Date.now(),
275
291
  log: log.child('propellant'),
@@ -302,14 +318,32 @@ export async function startGonogo(options = {}) {
302
318
  log: log.child('black box'),
303
319
  });
304
320
  /** What the parts of the server tell the Director's inbox goes to the targets of Relay too; a trip and a poll result go to the Black Box. */
305
- const tell = (kind, text) => {
321
+ let phone = null;
322
+ const tell = (kind, text, ref) => {
306
323
  downlink.post(kind, text);
307
324
  relay.event(kind, text);
325
+ if (ref !== undefined)
326
+ phone?.approval(ref, text);
308
327
  if (kind === 'redline')
309
328
  blackBox.record('redline', tripText(text));
310
329
  else if (kind === 'tminus')
311
330
  blackBox.record('poll', pollText(text));
312
331
  };
332
+ /** Stops what Propellant says is over its limit or budget: a room limit every Claude agent, an agent's own only that agent. */
333
+ const enforce = (name) => {
334
+ const over = propellant.over(name);
335
+ if (over === null || !hub)
336
+ return;
337
+ const names = over.scope === 'room' ? hub.views().filter((v) => v.provider === 'claude').map((v) => v.name) : [name];
338
+ for (const n of names) {
339
+ try {
340
+ hub.trip(n, over.reason);
341
+ }
342
+ catch (e) {
343
+ log.debug(`could not trip ${n}`, e);
344
+ }
345
+ }
346
+ };
313
347
  let seq = home.lastMessageSeq();
314
348
  // arrow functions on purpose: nothing here relies on `this` of the object it came from
315
349
  const io = {
@@ -333,6 +367,7 @@ export async function startGonogo(options = {}) {
333
367
  return { ok: true, path: resolve(p) };
334
368
  },
335
369
  checkCleanRoom: (dir) => checkCleanRoom(dir, env),
370
+ checkWorktree: (dir) => checkWorktree(dir, env),
336
371
  loadRoster: async () => home.loadRoster(),
337
372
  saveRoster: (r) => home.saveRoster(r),
338
373
  loadHistory: async (n) => home.loadRecentMessages(n),
@@ -368,23 +403,11 @@ export async function startGonogo(options = {}) {
368
403
  return info !== null && info.running && info.generation === generation && terminalHost.write(name, data);
369
404
  },
370
405
  meter: (name, _generation, transcriptPath) => {
371
- void propellant.record(name, transcriptPath).then((tokens) => {
372
- if (tokens === 0 || !hub)
406
+ void propellant.record(name, transcriptPath).then((used) => {
407
+ if (used === 0 || !hub)
373
408
  return;
374
409
  web?.broadcast({ t: 'propellant', propellant: propellant.view() });
375
- const over = propellant.over(name);
376
- if (over === null)
377
- return;
378
- // a room limit stops every Claude agent that runs, an agent's own limit only that agent
379
- const names = over.scope === 'room' ? hub.views().filter((v) => v.provider === 'claude').map((v) => v.name) : [name];
380
- for (const n of names) {
381
- try {
382
- hub.trip(n, over.reason);
383
- }
384
- catch (e) {
385
- log.debug(`could not trip ${n}`, e);
386
- }
387
- }
410
+ enforce(name);
388
411
  });
389
412
  },
390
413
  toolHook: (name, event, payload) => telemetry.hook(name, event, payload),
@@ -439,11 +462,16 @@ export async function startGonogo(options = {}) {
439
462
  emit: (list) => web?.broadcast({ t: 'uplinks', uplinks: list }),
440
463
  notify: tell,
441
464
  inbound: relay,
465
+ press: (secret, pressed) => void phone?.press(secret, pressed).catch((error) => log.warn('phone approvals: a button failed', error instanceof Error ? error.message : String(error))),
442
466
  log: log.child('uplink'),
443
467
  });
468
+ // tasks and missions know each other: a task checks its missionId, a mission counts and unlinks its tasks
469
+ let missionsRef = null;
444
470
  const tasks = audited(createTasks({
445
471
  dir: home.dir,
446
472
  now: io.now,
473
+ hasMission: (id) => missionsRef?.has(id) ?? false,
474
+ afterChange: (list) => missionsRef?.observe(list),
447
475
  isAgent: (name) => hubInstance.views().some((v) => v.name === name),
448
476
  send: (actor, request) => actor.kind === 'user'
449
477
  ? hubInstance.sendFromUser(request)
@@ -454,6 +482,19 @@ export async function startGonogo(options = {}) {
454
482
  notify: tell,
455
483
  log: log.child('flight plan'),
456
484
  }), blackBox.record, TASKS_AUDIT);
485
+ const missions = audited(createMissions({
486
+ dir: home.dir,
487
+ now: io.now,
488
+ isAgent: (name) => hubInstance.views().some((v) => v.name === name),
489
+ boss: () => hubInstance.views().find((v) => v.boss)?.name ?? null,
490
+ tasks: () => tasks.list(),
491
+ unlink: (id) => tasks.unlinkMission(id),
492
+ send: (actor, request) => (actor.kind === 'user' ? hubInstance.sendFromUser(request) : hubInstance.sendFromAgent(actor.name, actor.generation, request)),
493
+ emit: (list) => web?.broadcast({ t: 'missions', missions: list }),
494
+ notify: tell,
495
+ log: log.child('missions'),
496
+ }), blackBox.record, MISSIONS_AUDIT);
497
+ missionsRef = missions;
457
498
  const docking = createDocking({
458
499
  dir: home.dir,
459
500
  name: stationName(env[STATION_ENV], hostname()),
@@ -490,7 +531,7 @@ export async function startGonogo(options = {}) {
490
531
  home: home.dir,
491
532
  agent: (name) => {
492
533
  const view = hubInstance.views().find((v) => v.name === name);
493
- return view === undefined ? null : { dir: view.dir, cleanRoom: view.cleanRoom !== null };
534
+ return view === undefined ? null : { dir: view.dir, cleanRoom: view.cleanRoom !== null, worktree: view.worktree !== null };
494
535
  },
495
536
  });
496
537
  const relief = createRelief({
@@ -503,6 +544,7 @@ export async function startGonogo(options = {}) {
503
544
  notify: tell,
504
545
  log: log.child('relief'),
505
546
  });
547
+ phone = createPhone({ hub: audited(hubInstance, blackBox.record, HUB_AUDIT), relief, relay, secret: () => uplinks.secretOf('telegram'), now: io.now, log: log.child('phone') });
506
548
  const rollout = createRollout({
507
549
  dir: home.dir,
508
550
  now: io.now,
@@ -527,10 +569,19 @@ export async function startGonogo(options = {}) {
527
569
  info,
528
570
  isReady: () => ready,
529
571
  propellant: audited(propellant, blackBox.record, PROPELLANT_AUDIT),
572
+ prices: audited(prices, blackBox.record, PRICES_AUDIT),
573
+ // a changed price or budget is checked at once, not at the next reply
574
+ spendChanged: () => {
575
+ propellant.recheck();
576
+ for (const v of hub?.views() ?? [])
577
+ if (v.provider === 'claude')
578
+ enforce(v.name);
579
+ },
530
580
  telemetry,
531
581
  schedules: audited(schedules, blackBox.record, SCHEDULES_AUDIT),
532
582
  uplinks: audited(uplinks, blackBox.record, UPLINKS_AUDIT),
533
583
  tasks,
584
+ missions,
534
585
  downlink,
535
586
  missionLog,
536
587
  massBudget,
@@ -538,11 +589,22 @@ export async function startGonogo(options = {}) {
538
589
  blackBox,
539
590
  liveries: audited(liveries, blackBox.record, LIVERIES_AUDIT),
540
591
  relay: audited(relay, blackBox.record, RELAY_AUDIT),
592
+ models: modelDefaults,
541
593
  docking: audited(docking, blackBox.record, DOCKING_AUDIT),
542
- relief,
594
+ relief: audited(relief, blackBox.record, RELIEF_AUDIT),
543
595
  rollout,
544
596
  engines: () => checkEngines(env),
545
597
  hangar: createHangar(roots),
598
+ worktrees: {
599
+ has: (name) => hubInstance.views().some((v) => v.name === name && v.worktree !== null),
600
+ status: (name) => worktreeStatus(worktreePath(home.dir, name), worktreeBranch(name), env),
601
+ discard: async (name) => {
602
+ const done = await removeWorktree(worktreePath(home.dir, name), worktreeBranch(name), env);
603
+ if (done.reason !== undefined)
604
+ log.warn(`worktree of ${name} kept: ${done.reason}`);
605
+ return done;
606
+ },
607
+ },
546
608
  recorder: createRecorder(roots, env),
547
609
  log: log.child('web'),
548
610
  });
@@ -560,6 +622,9 @@ export async function startGonogo(options = {}) {
560
622
  baseUrl = `http://${host === '::1' ? '[::1]' : '127.0.0.1'}:${addr.port}`;
561
623
  // before the hub starts any agent: a task_create that came first would take an id of the file and lose that task
562
624
  await tasks.load();
625
+ await missions.load();
626
+ // the open count of each active mission is seeded here, so the last task done after a restart is announced
627
+ missions.observe(tasks.list());
563
628
  await missionLog.load();
564
629
  await board.load();
565
630
  await blackBox.load();
@@ -592,6 +657,7 @@ export async function startGonogo(options = {}) {
592
657
  await step('docking close', () => docking.close());
593
658
  await step('uplinks close', () => uplinks.close());
594
659
  await step('tasks close', () => tasks.close());
660
+ await step('missions close', () => missions.close());
595
661
  await step('mission log close', () => missionLog.close());
596
662
  await step('board close', () => board.close());
597
663
  blackBox.record('audit', 'gonogo stopped');
@@ -599,8 +665,10 @@ export async function startGonogo(options = {}) {
599
665
  await step('livery close', () => liveries.close());
600
666
  await step('relief close', async () => relief.close());
601
667
  await step('relay close', () => relay.close());
668
+ await step('models close', () => modelDefaults.close());
602
669
  await step('downlink close', () => downlink.close());
603
670
  await step('propellant close', () => propellant.close());
671
+ await step('prices close', () => prices.close());
604
672
  await step('telemetry close', () => telemetry.close());
605
673
  await step('rollout close', () => rollout.close());
606
674
  await step('clearance close', () => clearance.close());
@@ -280,6 +280,7 @@ export const CLEAN_ROOM_ENV = ['GONOGO_TOKEN', 'TERM', 'COLORTERM', 'IS_DEMO'];
280
280
  export const CLEAN_ROOM_COMMAND_MS = 30_000;
281
281
  /** Added to the role of a Clean Room agent: git cannot reach the repository from the container. {branch} is its branch. */
282
282
  export const CLEAN_ROOM_NOTE = 'You run in a sandbox: a container that holds only a copy of the project (a git worktree on the branch "{branch}") and your own files. git cannot reach the repository from there, so do not try to commit: edit the files, and the owner commits and merges the branch from outside.';
283
+ export const WORKTREE_NOTE = 'Your files are a git worktree on the branch "{branch}". Commit there; the Director merges the branch.';
283
284
  export const MAX_WORKING_ENV = 'GONOGO_MAX_WORKING';
284
285
  /** A custom command counts as working while it printed something in the last CUSTOM_ACTIVE_MS, and as starting until it prints or CUSTOM_START_MS pass. */
285
286
  export const CUSTOM_ACTIVE_MS = 2000;
@@ -332,6 +333,10 @@ export const DOCK_UNDOCK_TIMEOUT_MS = 3000;
332
333
  export const DOCK_PULL_MS = 30_000;
333
334
  /** Flight Plan (docs/flight-plan-spec.md): the file, the history lines one task keeps, and how many done tasks are kept. */
334
335
  export const TASKS_FILE = 'tasks.json';
336
+ /** Missions (docs/missions-spec.md): the file, the history lines one mission keeps, and how many finished missions are kept. */
337
+ export const MISSIONS_FILE = 'missions.json';
338
+ export const MISSION_NOTES_MAX = 100;
339
+ export const MISSIONS_DONE_KEEP = 20;
335
340
  export const TASK_NOTES_MAX = 20;
336
341
  export const TASKS_DONE_KEEP = 100;
337
342
  /**
@@ -377,8 +382,13 @@ export const RELIEF_RATE_WINDOW_MS = 10 * 60_000;
377
382
  export const RELIEF_TTL_MS = 30 * 60_000;
378
383
  /** Propellant (docs/redline-propellant-spec.md): the limits and cursors file; the ledger fuel.jsonl is a log and has no version. */
379
384
  export const PROPELLANT_FILE = 'propellant.json';
385
+ /** Cost (docs/cost-spec.md): the owner's model prices, mode 0600, and the largest budget in dollars. */
386
+ export const PRICES_FILE = 'prices.json';
387
+ export const BUDGET_MAX_USD = 1_000_000;
380
388
  /** Clearance (docs/engine-bay-spec.md): the values of the keys set for each agent, mode 0600. The roster keeps their names only. */
381
389
  export const KEYS_FILE = 'keys.json';
390
+ /** Default models (docs/engine-bay-spec.md): the room's model for each engine, `{ version: 1, models: { claude: 'sonnet' } }`. */
391
+ export const MODELS_FILE = 'models.json';
382
392
  /** Pad Check: `<bin> --version` gets this long, and its first line is cut to this many characters. */
383
393
  export const ENGINE_VERSION_MS = 5_000;
384
394
  export const ENGINE_VERSION_CHARS = 80;
@@ -410,8 +420,11 @@ export const MCP_DESCRIPTIONS = {
410
420
  list_roster: 'List every agent in the operations room with its name, role and current state, and say which one is the boss. Agents of docked stations are listed too, under docked.',
411
421
  read_messages: 'Return the messages waiting for you (each message is returned once) and mark them read. Call it when a line starting with "gonogo:" says messages are waiting.',
412
422
  task_list: 'List the tasks of the Flight Plan, the team task board, most recently changed first. Optional filters: mine (only the tasks assigned to you) and status (todo, doing, review, done or blocked).',
413
- task_create: 'Add a task to the Flight Plan. It starts as todo. Give a short title, a detail with what done means, and optionally the name of the agent it is assigned to; that agent gets a message.',
414
- task_update: 'Change a task of the Flight Plan by its id: its status (todo, doing, review, done, blocked), its assignee (an agent name, or null to unassign) and a short note for the history. Assigning it to another agent sends that agent a message.',
423
+ task_create: 'Add a task to the Flight Plan. It starts as todo. Give a short title, a detail with what done means, and optionally the name of the agent it is assigned to; that agent gets a message. Optionally missionId, the id of the mission it serves (see mission_list).',
424
+ task_update: 'Change a task of the Flight Plan by its id: its status (todo, doing, review, done, blocked), its assignee (an agent name, or null to unassign) and a short note for the history. Assigning it to another agent sends that agent a message. missionId links it to a mission (null unlinks it).',
425
+ mission_list: 'List the missions of the room, newest change first: a named goal, its status (planned, active, paused, done, aborted), its lead and the tasks that serve it. Optional filter: status. The current mission is the active one that started last.',
426
+ mission_create: 'Boss only. Make a mission: a short name, an optional goal (what done means) and optionally its lead (an agent name; default you). It starts as planned; the Director starts it. Link tasks to it with the missionId field of task_create and task_update.',
427
+ mission_update: 'Boss only. Change a mission by its id: its status (planned, active, paused, done, aborted) and a short note for the history. Becoming active briefs you with the goal and the open tasks. Only the Director edits a name or a goal or removes a mission.',
415
428
  log_write: 'Write to the Mission Log, the memory shared by every agent: a title, a body in plain markdown and optional tags. Give an id to change an entry you wrote earlier (any of title, body, tags). Keep an entry to one finding.',
416
429
  log_search: 'Search the Mission Log. Returns up to limit entries (at most 20), best first, each with its id, title, author, tags and a snippet around the best match. Read the whole entry with log_read.',
417
430
  log_read: 'Read one entry of the Mission Log by its id: the title, tags, author, times and the whole body.',
@@ -10,7 +10,7 @@ import { createHash, randomBytes } from 'node:crypto';
10
10
  import { constants as fs } from 'node:fs';
11
11
  import { access, lstat, open, opendir, realpath, rename, unlink } from 'node:fs/promises';
12
12
  import { isAbsolute, join, relative, sep } from 'node:path';
13
- import { CLEAN_ROOM_DIR, HANGAR_FILE_MAX_BYTES } from '../shared/protocol.js';
13
+ import { CLEAN_ROOM_DIR, HANGAR_FILE_MAX_BYTES, WORKTREE_DIR } from '../shared/protocol.js';
14
14
  import { HubError } from './hub.js';
15
15
  /** A save body: the text, in the worst case a `\u0000` escape for each byte, plus the path and the etag. */
16
16
  export const HANGAR_BODY_MAX_BYTES = 6 * HANGAR_FILE_MAX_BYTES + 8192;
@@ -116,13 +116,13 @@ export function createRoots(deps) {
116
116
  const place = deps.agent(name);
117
117
  if (place === null)
118
118
  throw new HubError('not_found', 'unknown agent');
119
- const wanted = place.cleanRoom ? join(deps.home, CLEAN_ROOM_DIR, name) : place.dir;
119
+ const wanted = place.cleanRoom ? join(deps.home, CLEAN_ROOM_DIR, name) : place.worktree === true ? join(deps.home, WORKTREE_DIR, name) : place.dir;
120
120
  try {
121
121
  return { root: await realpath(wanted), home: await realpath(deps.home) };
122
122
  }
123
123
  catch (e) {
124
124
  if (e.code === 'ENOENT') {
125
- throw new HubError('not_found', place.cleanRoom ? 'the Clean Room has no worktree yet: start the agent once' : 'the agent\'s folder is gone');
125
+ throw new HubError('not_found', place.cleanRoom ? 'the Clean Room has no worktree yet: start the agent once' : place.worktree === true ? 'the worktree is not made yet: start the agent once' : 'the agent\'s folder is gone');
126
126
  }
127
127
  throw e;
128
128
  }
@@ -144,7 +144,7 @@ export function createHangar(roots) {
144
144
  }
145
145
  }
146
146
  /** gonogo's home is out of reach, except the Clean Room worktrees below it (an agent's own files). */
147
- const ownState = (at, real) => inside(at.home, real) && !inside(join(at.home, CLEAN_ROOM_DIR), real);
147
+ const ownState = (at, real) => inside(at.home, real) && !inside(join(at.home, CLEAN_ROOM_DIR), real) && !inside(join(at.home, WORKTREE_DIR), real);
148
148
  const guard = (at, real) => {
149
149
  if (!inside(at.root, real))
150
150
  throw forbidden('that path leads outside the agent\'s folder');
@@ -8,6 +8,8 @@ import { AGENT_NAME_PATTERN, AGENTS_DIR, AGENTS_FILE, BROWSER_TOKEN_FILE, COMMAN
8
8
  import { readCustomCommand } from './command.js';
9
9
  import { migrateHome } from './migrate.js';
10
10
  import { parseCleanRoom } from './cleanroom.js';
11
+ import { parseWorktree } from './worktree.js';
12
+ import { parseRemoteControl } from './remotecontrol.js';
11
13
  import { keyNameProblem } from './clearance.js';
12
14
  import { parsePayload, payloadRefusal } from './payload.js';
13
15
  const MODEL_RE = new RegExp(MODEL_PATTERN);
@@ -152,7 +154,7 @@ function parseAgent(a) {
152
154
  if (typeof createdAt !== 'number' || !Number.isFinite(createdAt))
153
155
  return `${name}: createdAt must be a number`;
154
156
  const record = { name, role, dir, mode, sessionId, desk, boss, createdAt };
155
- const { position, provider, command, payload, cleanRoom } = a;
157
+ const { position, provider, command, payload, cleanRoom, worktree, remoteControl } = a;
156
158
  if (position !== undefined) {
157
159
  if (typeof position !== 'string' || !POSITION_IDS.includes(position))
158
160
  return `${name}: unknown position`;
@@ -197,6 +199,20 @@ function parseAgent(a) {
197
199
  return `${name}: ${checked.error}`;
198
200
  record.cleanRoom = checked.cleanRoom;
199
201
  }
202
+ if (worktree !== undefined) {
203
+ const checked = parseWorktree(worktree);
204
+ if (!checked.ok)
205
+ return `${name}: ${checked.error}`;
206
+ if (cleanRoom !== undefined)
207
+ return `${name}: a Clean Room agent has a worktree already`;
208
+ record.worktree = checked.worktree;
209
+ }
210
+ if (remoteControl !== undefined) {
211
+ const checked = parseRemoteControl(remoteControl, record.provider, record.cleanRoom !== undefined);
212
+ if (!checked.ok)
213
+ return `${name}: ${checked.error}`;
214
+ record.remoteControl = checked.remoteControl;
215
+ }
200
216
  const { model, keys } = a;
201
217
  if (model !== undefined) {
202
218
  if (typeof model !== 'string' || !MODEL_RE.test(model))
@@ -2,6 +2,8 @@ import { DOING_MAX_CHARS, HISTORY_MAX, HISTORY_WINDOW_MS, HOLD_REASON, HOOK_EVEN
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 { parseWorktree } from './worktree.js';
6
+ import { parseRemoteControl } from './remotecontrol.js';
5
7
  import { checkKeys } from './clearance.js';
6
8
  import { parsePayload, payloadRefusal } from './payload.js';
7
9
  /** Every request the hub rejects is one of these; web.ts maps `code` to the HTTP status (contract 3.3). */
@@ -23,8 +25,12 @@ const NAME_RE = new RegExp(AGENT_NAME_PATTERN);
23
25
  const STATION_RE = new RegExp(STATION_NAME_PATTERN);
24
26
  /** The payload of a record as text, for comparing: null when it has none. */
25
27
  const payloadKey = (record) => (record.payload === undefined ? null : JSON.stringify(record.payload));
28
+ /** The Remote Control setting of a record as text, for comparing. */
29
+ const remoteKey = (record) => (record.remoteControl === undefined ? null : JSON.stringify(record.remoteControl));
26
30
  /** The Clean Room setting of a record as text, for comparing: null when the agent runs on the host. */
27
31
  const cleanRoomKey = (record) => (record.cleanRoom === undefined ? null : JSON.stringify(record.cleanRoom));
32
+ /** The worktree setting of a record as text, for comparing: null when the agent starts in its own folder. */
33
+ const worktreeKey = (record) => (record.worktree === undefined ? null : JSON.stringify(record.worktree));
28
34
  /** 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
35
  const engineKey = (record) => JSON.stringify([record.model ?? null, record.keys ?? null]);
30
36
  const MODEL_RE = new RegExp(MODEL_PATTERN);
@@ -300,6 +306,7 @@ export function createHub(io, options) {
300
306
  doing: null,
301
307
  needsKind: null,
302
308
  needsReason: null,
309
+ needSeq: 0,
303
310
  generation: 0,
304
311
  ready: false,
305
312
  transition: null,
@@ -371,6 +378,7 @@ export function createHub(io, options) {
371
378
  stateSince: rt.stateSince,
372
379
  needsKind: rt.needsKind,
373
380
  needsReason: rt.needsReason,
381
+ needSeq: rt.needsKind === 'permission' ? rt.needSeq : null,
374
382
  transition: rt.transition,
375
383
  draft: rt.draft !== null,
376
384
  held: heldInfo(rt),
@@ -383,6 +391,8 @@ export function createHub(io, options) {
383
391
  running.command !== (record.command ?? null) ||
384
392
  running.payload !== payloadKey(record) ||
385
393
  running.cleanRoom !== cleanRoomKey(record) ||
394
+ running.worktree !== worktreeKey(record) ||
395
+ running.remoteControl !== remoteKey(record) ||
386
396
  running.engine !== engineKey(record)),
387
397
  generation: rt.generation,
388
398
  exit: rt.exit ? { ...rt.exit } : null,
@@ -391,6 +401,8 @@ export function createHub(io, options) {
391
401
  command: record.command ?? null,
392
402
  payload: record.payload ?? null,
393
403
  cleanRoom: record.cleanRoom ?? null,
404
+ worktree: record.worktree ?? null,
405
+ remoteControl: record.remoteControl ?? null,
394
406
  model: record.model ?? null,
395
407
  keys: { ...record.keys },
396
408
  doing: rt.doing,
@@ -777,12 +789,21 @@ export function createHub(io, options) {
777
789
  function answer(name, request) {
778
790
  assertOpen();
779
791
  const rt = lookup(name);
780
- const go = asObject(request, 'the request').go;
792
+ const asked = asObject(request, 'the request');
793
+ const go = asked.go;
781
794
  if (typeof go !== 'boolean')
782
795
  throw new HubError('bad_request', 'go must be true or false', 'go');
796
+ const { needSeq } = asked;
797
+ if (needSeq !== undefined && (typeof needSeq !== 'number' || !Number.isSafeInteger(needSeq) || needSeq < 0)) {
798
+ throw new HubError('bad_request', 'needSeq must be a whole number', 'needSeq');
799
+ }
783
800
  if (rt.state !== 'needs_you' || rt.needsKind !== 'permission' || rt.transition !== null) {
784
801
  throw new HubError('conflict', `${rt.record.name} is not asking for a go`);
785
802
  }
803
+ // an answer from a phone for a dialog that was answered or replaced since: nothing is typed
804
+ if (needSeq !== undefined && needSeq !== rt.needSeq) {
805
+ throw new HubError('conflict', `${rt.record.name} is asking about something else now: that dialog was answered or replaced`, 'needSeq');
806
+ }
786
807
  if (!io.press?.(rt.record.name, rt.generation, go ? '\r' : '\x1b')) {
787
808
  throw new HubError('conflict', `could not reach the terminal of ${rt.record.name}`);
788
809
  }
@@ -1038,12 +1059,18 @@ export function createHub(io, options) {
1038
1059
  detect(rt, `error storm: ${rt.toolFailAt.length} failed tool calls in 2 min`);
1039
1060
  }
1040
1061
  break;
1041
- case 'PermissionRequest':
1042
- setState(rt, 'needs_you', {
1043
- kind: 'permission',
1044
- reason: describePermission(payload.tool_name, payload.tool_input),
1045
- });
1062
+ case 'PermissionRequest': {
1063
+ const reason = describePermission(payload.tool_name, payload.tool_input);
1064
+ // the same dialog twice (a repeated hook) is one dialog: no new number, no new event
1065
+ const repeated = rt.state === 'needs_you' && rt.needsKind === 'permission' && rt.needsReason === reason;
1066
+ if (!repeated)
1067
+ rt.needSeq += 1;
1068
+ setState(rt, 'needs_you', { kind: 'permission', reason });
1069
+ // one event for each dialog, unless a Hold or a trip has taken over the state (that one is not a dialog the Director can answer)
1070
+ if (!repeated && rt.needsKind === 'permission')
1071
+ io.notify?.('permission', `${rt.record.name} asks: ${reason.slice(PERMISSION_PREFIX.length)}`, { kind: 'permission', agent: rt.record.name, seq: rt.needSeq });
1046
1072
  break;
1073
+ }
1047
1074
  case 'Notification':
1048
1075
  onNotification(rt, payload);
1049
1076
  break;
@@ -1443,7 +1470,7 @@ export function createHub(io, options) {
1443
1470
  rt.pointed.clear();
1444
1471
  rt.screenClearSince = null;
1445
1472
  rt.lastBlockAt = null;
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) };
1473
+ 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), worktree: worktreeKey(rt.record), remoteControl: remoteKey(rt.record), engine: engineKey(rt.record) };
1447
1474
  rt.flag = flag;
1448
1475
  // The browser reacts to a new generation by attaching, so the frame waits until the process exists in the terminal host.
1449
1476
  rt.frameHold = true;
@@ -1657,6 +1684,14 @@ export function createHub(io, options) {
1657
1684
  delete target.cleanRoom;
1658
1685
  else
1659
1686
  target.cleanRoom = from.cleanRoom;
1687
+ if (from.worktree === undefined)
1688
+ delete target.worktree;
1689
+ else
1690
+ target.worktree = from.worktree;
1691
+ if (from.remoteControl === undefined)
1692
+ delete target.remoteControl;
1693
+ else
1694
+ target.remoteControl = from.remoteControl;
1660
1695
  if (from.model === undefined)
1661
1696
  delete target.model;
1662
1697
  else
@@ -1702,6 +1737,32 @@ export function createHub(io, options) {
1702
1737
  throw new HubError('bad_request', refused.error, refused.field);
1703
1738
  return checked.payload;
1704
1739
  }
1740
+ /** A Remote Control setting: an object, Claude Code only, not with a Clean Room. A bad one is 400, field remoteControl. */
1741
+ function checkRemoteControl(provider, value, cleanRoom) {
1742
+ const checked = parseRemoteControl(value, provider, cleanRoom);
1743
+ if (!checked.ok)
1744
+ throw new HubError('bad_request', checked.error, 'remoteControl');
1745
+ return checked.remoteControl;
1746
+ }
1747
+ /** A worktree setting: an object, not together with a Clean Room (which has one), and `dir` in a git repository. A bad one is 400, field worktree. */
1748
+ async function checkWorktree(value, dir, cleanRoom) {
1749
+ const checked = parseWorktree(value);
1750
+ if (!checked.ok)
1751
+ throw new HubError('bad_request', checked.error, 'worktree');
1752
+ if (cleanRoom !== undefined && cleanRoom !== null)
1753
+ throw new HubError('bad_request', 'a Clean Room agent has a worktree already: use one of the two', 'worktree');
1754
+ let problem;
1755
+ try {
1756
+ problem = (await io.checkWorktree?.(dir)) ?? null;
1757
+ }
1758
+ catch (error) {
1759
+ log.error('worktree check failed', error);
1760
+ problem = errorMessage(error);
1761
+ }
1762
+ if (problem !== null)
1763
+ throw new HubError('bad_request', problem, 'worktree');
1764
+ return checked.worktree;
1765
+ }
1705
1766
  /** 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. */
1706
1767
  async function checkCleanRoom(provider, value, dir) {
1707
1768
  const checked = parseCleanRoom(value, provider);
@@ -1797,6 +1858,8 @@ export function createHub(io, options) {
1797
1858
  }
1798
1859
  await checkSkills(payload);
1799
1860
  const cleanRoom = req.cleanRoom === undefined ? undefined : await checkCleanRoom(provider, req.cleanRoom, dir);
1861
+ const worktree = req.worktree === undefined ? undefined : await checkWorktree(req.worktree, dir, req.cleanRoom);
1862
+ const remoteControl = req.remoteControl === undefined ? undefined : checkRemoteControl(provider, req.remoteControl, cleanRoom !== undefined);
1800
1863
  assertOpen();
1801
1864
  const record = {
1802
1865
  name,
@@ -1816,6 +1879,10 @@ export function createHub(io, options) {
1816
1879
  record.payload = payload;
1817
1880
  if (cleanRoom)
1818
1881
  record.cleanRoom = cleanRoom;
1882
+ if (worktree)
1883
+ record.worktree = worktree;
1884
+ if (remoteControl)
1885
+ record.remoteControl = remoteControl;
1819
1886
  if (model)
1820
1887
  record.model = model;
1821
1888
  if (kept?.names)
@@ -1848,9 +1915,9 @@ export function createHub(io, options) {
1848
1915
  if (rt.removed)
1849
1916
  throw new HubError('not_found', 'unknown agent');
1850
1917
  const req = asObject(request, 'the request');
1851
- const fields = ['name', 'role', 'dir', 'mode', 'confirmBypass', 'position', 'command', 'payload', 'cleanRoom', 'model', 'keys'];
1918
+ const fields = ['name', 'role', 'dir', 'mode', 'confirmBypass', 'position', 'command', 'payload', 'cleanRoom', 'worktree', 'remoteControl', 'model', 'keys'];
1852
1919
  if (!fields.some((field) => req[field] !== undefined)) {
1853
- throw new HubError('bad_request', 'nothing to change: send at least one of name, role, dir, mode, position, command, payload, cleanRoom, model, keys');
1920
+ throw new HubError('bad_request', 'nothing to change: send at least one of name, role, dir, mode, position, command, payload, cleanRoom, worktree, remoteControl, model, keys');
1854
1921
  }
1855
1922
  const current = rt.record;
1856
1923
  const next = { ...current };
@@ -1863,6 +1930,9 @@ export function createHub(io, options) {
1863
1930
  if (current.cleanRoom !== undefined && req.cleanRoom !== null) {
1864
1931
  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');
1865
1932
  }
1933
+ if (current.worktree !== undefined && req.worktree !== null) {
1934
+ throw new HubError('conflict', 'a console with a worktree cannot be renamed: its worktree and branch carry its name (turn the worktree off to rename it)', 'name');
1935
+ }
1866
1936
  if (agents.has(name) || claimedNames.has(name)) {
1867
1937
  throw new HubError('conflict', `an agent named "${name}" already exists`, 'name');
1868
1938
  }
@@ -1899,6 +1969,25 @@ export function createHub(io, options) {
1899
1969
  else
1900
1970
  next.cleanRoom = await checkCleanRoom(current.provider ?? 'claude', req.cleanRoom, next.dir);
1901
1971
  }
1972
+ if (req.worktree !== undefined) {
1973
+ if (req.worktree === null)
1974
+ delete next.worktree;
1975
+ else
1976
+ next.worktree = await checkWorktree(req.worktree, next.dir, next.cleanRoom);
1977
+ }
1978
+ else if (next.worktree !== undefined && (req.dir !== undefined || req.cleanRoom !== undefined)) {
1979
+ // a new folder must be in a repository, and a Clean Room has a worktree of its own
1980
+ next.worktree = await checkWorktree(next.worktree, next.dir, next.cleanRoom);
1981
+ }
1982
+ if (req.remoteControl !== undefined) {
1983
+ if (req.remoteControl === null)
1984
+ delete next.remoteControl;
1985
+ else
1986
+ next.remoteControl = checkRemoteControl(current.provider ?? 'claude', req.remoteControl, next.cleanRoom !== undefined);
1987
+ }
1988
+ else if (next.remoteControl !== undefined && next.cleanRoom !== undefined && req.cleanRoom !== undefined) {
1989
+ throw new HubError('bad_request', 'a Clean Room agent cannot use Remote Control: turn Remote Control off first', 'cleanRoom');
1990
+ }
1902
1991
  if (req.model !== undefined) {
1903
1992
  const model = checkModel(current.provider ?? 'claude', req.model);
1904
1993
  if (model)
@@ -1932,6 +2021,8 @@ export function createHub(io, options) {
1932
2021
  next.command !== current.command ||
1933
2022
  payloadKey(next) !== payloadKey(current) ||
1934
2023
  cleanRoomKey(next) !== cleanRoomKey(current) ||
2024
+ worktreeKey(next) !== worktreeKey(current) ||
2025
+ remoteKey(next) !== remoteKey(current) ||
1935
2026
  engineKey(next) !== engineKey(current);
1936
2027
  if (!changed)
1937
2028
  return buildView(rt);
@@ -2427,6 +2518,8 @@ export function createHub(io, options) {
2427
2518
  }
2428
2519
  function holdPoll() {
2429
2520
  assertOpen();
2521
+ if (pollState !== null && pollState.status === 'hold')
2522
+ throw new HubError('conflict', 'the poll is already on hold');
2430
2523
  if (pollState === null || pollState.status !== 'open')
2431
2524
  throw new HubError('conflict', 'no poll is open');
2432
2525
  pollState.status = 'hold';