@aragon-agent/cli 0.6.63 → 0.6.66

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 (80) hide show
  1. package/CHANGELOG.md +131 -2
  2. package/README.md +98 -21
  3. package/dist/agent/controller.d.ts +119 -14
  4. package/dist/agent/controller.js +385 -82
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +68 -6
  7. package/dist/agent/reconnect-memory.d.ts +68 -0
  8. package/dist/agent/reconnect-memory.js +82 -0
  9. package/dist/agent/team-notices.d.ts +57 -7
  10. package/dist/agent/team-notices.js +93 -10
  11. package/dist/app/App.js +284 -78
  12. package/dist/cli.js +4 -1
  13. package/dist/commands/builtins.js +8 -72
  14. package/dist/commands/catalog.js +1 -1
  15. package/dist/commands/retry-command.d.ts +52 -0
  16. package/dist/commands/retry-command.js +225 -0
  17. package/dist/config/cli-commands.d.ts +1 -1
  18. package/dist/config/cli-commands.js +39 -0
  19. package/dist/exec/events.d.ts +12 -0
  20. package/dist/exec/index.js +2 -0
  21. package/dist/exec/runner.js +16 -1
  22. package/dist/gene/cli-commands.js +30 -1
  23. package/dist/gene/command-report.js +5 -1
  24. package/dist/gene/commit-prepare.js +27 -1
  25. package/dist/gene/curator/budget.d.ts +24 -1
  26. package/dist/gene/curator/budget.js +67 -14
  27. package/dist/gene/curator/curator.d.ts +25 -0
  28. package/dist/gene/curator/curator.js +61 -7
  29. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  30. package/dist/gene/curator/scripted-lane.js +101 -0
  31. package/dist/gene/curator/task-context.d.ts +29 -0
  32. package/dist/gene/curator/task-context.js +43 -0
  33. package/dist/gene/curator/task-runner.d.ts +10 -1
  34. package/dist/gene/curator/task-runner.js +52 -6
  35. package/dist/gene/curator/tool-support.js +11 -4
  36. package/dist/gene/curator/toolkit.d.ts +13 -0
  37. package/dist/gene/curator/toolkit.js +23 -1
  38. package/dist/gene/curator/tools-verify.js +2 -2
  39. package/dist/gene/curator/tools-write.js +6 -1
  40. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  41. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  42. package/dist/gene/curator/validate/knowledge.js +74 -11
  43. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  44. package/dist/gene/curator/validate/prompts.js +2 -2
  45. package/dist/gene/hub.js +5 -0
  46. package/dist/gene/import-plan.js +8 -5
  47. package/dist/gene/learn/draft-guard.d.ts +17 -0
  48. package/dist/gene/learn/draft-guard.js +113 -0
  49. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  50. package/dist/gene/learn/learn-prompt.js +27 -2
  51. package/dist/gene/learn/learner.js +27 -5
  52. package/dist/gene/queue.d.ts +24 -0
  53. package/dist/gene/queue.js +80 -1
  54. package/dist/governance/store/run-store.d.ts +20 -0
  55. package/dist/governance/store/run-store.js +54 -8
  56. package/dist/host/controller-factory.js +6 -0
  57. package/dist/host/index.d.ts +1 -0
  58. package/dist/host/index.js +1 -0
  59. package/dist/host/interaction.d.ts +8 -17
  60. package/dist/host/interaction.js +50 -72
  61. package/dist/host/team-wake-driver.d.ts +90 -0
  62. package/dist/host/team-wake-driver.js +114 -0
  63. package/dist/logging/install.d.ts +35 -1
  64. package/dist/logging/install.js +23 -0
  65. package/dist/session/persist.js +8 -1
  66. package/dist/session/validate-session.js +15 -5
  67. package/dist/team/console-tools.d.ts +12 -0
  68. package/dist/team/console-tools.js +20 -3
  69. package/dist/team/console-view.js +11 -1
  70. package/dist/team/notices.d.ts +81 -4
  71. package/dist/team/notices.js +187 -22
  72. package/dist/team/prompt.js +1 -1
  73. package/dist/team/runtime.d.ts +67 -24
  74. package/dist/team/runtime.js +250 -31
  75. package/dist/team/stall-watch.d.ts +54 -0
  76. package/dist/team/stall-watch.js +119 -0
  77. package/dist/team/task-tool.js +2 -2
  78. package/dist/team/wake.d.ts +176 -0
  79. package/dist/team/wake.js +444 -0
  80. package/package.json +81 -81
@@ -54,8 +54,33 @@ export function versionServiceFence(queue) {
54
54
  };
55
55
  }
56
56
  export const QUEUE_MAX_ATTEMPTS = 4;
57
+ /**
58
+ * Attempts allowed to a proposal whose task keeps OUTGROWING its ceiling (R-4').
59
+ *
60
+ * WHY TWO. A task that ran out of tokens, turns or the chance to finish does it again with the same
61
+ * prompt, the same model and the same ceiling, so a retry is a deterministic second bill - four
62
+ * dead skill proposals cost 145k-205k tokens EACH, a day's budget between them. One retry is
63
+ * kept because the second claim may be a `resume_validation` that costs almost nothing, and the
64
+ * network-class errors (a timeout, a provider fault) keep all four: those are not the item's fault.
65
+ */
66
+ export const QUEUE_MAX_OVERRUN_ATTEMPTS = 2;
67
+ /**
68
+ * The errors `task-runner.ts` records when a task hit a ceiling (`task_wallclock`: the clock ended a task
69
+ * that was working). `task_budget` is the pre-split name. `task_timeout` is NOT here: that is a stall.
70
+ */
71
+ const OVERRUN_ERRORS = new Set([
72
+ 'task_tokens',
73
+ 'task_turns',
74
+ 'task_wallclock',
75
+ 'no_finish',
76
+ 'task_budget',
77
+ ]);
57
78
  /** Backoff after the 1st, 2nd and 3rd transient failure; the 4th goes to `dead/`. */
58
79
  export const QUEUE_BACKOFF_MS = [30_000, 120_000, 600_000];
80
+ /** How many attempts a transient failure of this kind may use before the item is quarantined. */
81
+ function attemptLimitFor(error) {
82
+ return OVERRUN_ERRORS.has(error) ? QUEUE_MAX_OVERRUN_ATTEMPTS : QUEUE_MAX_ATTEMPTS;
83
+ }
59
84
  const CANCEL_SUFFIX = '.cancel';
60
85
  /** A settle waits for a short-lived lock holder (a claim step, a sweep) rather than failing. */
61
86
  const SETTLE_LOCK_ATTEMPTS = 8;
@@ -374,7 +399,7 @@ export class GeneQueue {
374
399
  return { state: 'pending', record: waiting };
375
400
  }
376
401
  const attempt = item.attempt + 1;
377
- if (attempt >= QUEUE_MAX_ATTEMPTS) {
402
+ if (attempt >= attemptLimitFor(failure.error)) {
378
403
  return { state: 'dead', record: { ...item, attempt, lastError: failure.error } };
379
404
  }
380
405
  const delay = QUEUE_BACKOFF_MS[attempt - 1] ?? QUEUE_BACKOFF_MS[QUEUE_BACKOFF_MS.length - 1];
@@ -497,6 +522,60 @@ export class GeneQueue {
497
522
  this.invalidateCounts();
498
523
  return result;
499
524
  }
525
+ /**
526
+ * Move every `pending/` proposal `reasonOf` names to `dead/`, recording the reason in `lastError`
527
+ * (R-3': the stored proposals a draft guard would now refuse). Nothing is deleted and nothing is
528
+ * redacted: `retryDead` puts an item back. Returns the ids moved. `reasonOf` must be PURE and cheap.
529
+ */
530
+ async quarantinePendingWhere(reasonOf) {
531
+ const moved = [];
532
+ for (const parsed of await this.parsedPending()) {
533
+ const from = queueFile('pending', parsed.name, this.ctx);
534
+ const to = queueFile('dead', parsed.name, this.ctx);
535
+ if (from === null || to === null)
536
+ continue;
537
+ const locked = await this.withLock(parsed.name, async () => {
538
+ const record = await this.readRecord(from);
539
+ const reason = record === null ? null : reasonOf(record.proposal);
540
+ if (record === null || reason === null)
541
+ return null;
542
+ await this.rewrite(from, { ...record, lastError: reason });
543
+ return (await this.tryMove(from, to)) ? record.proposal.id : null;
544
+ }, SETTLE_LOCK_ATTEMPTS);
545
+ if (locked.held && locked.value !== null)
546
+ moved.push(locked.value);
547
+ }
548
+ if (moved.length > 0)
549
+ this.invalidateCounts();
550
+ return moved;
551
+ }
552
+ /**
553
+ * Give every `pending/` item `isParked` names a clean `notBefore` (so it is claimable now) and
554
+ * return their ids. Counts nothing against the item: no attempt, no outcome, same file name. This
555
+ * is for waits that no longer have a reason (a budget window that is no longer enforced); the
556
+ * caller owns the policy, `isParked` must be PURE and cheap, and the rewrite is under the item's
557
+ * own lock like every other change to a pending file.
558
+ */
559
+ async thawPendingWhere(isParked) {
560
+ const thawed = [];
561
+ for (const parsed of await this.parsedPending()) {
562
+ const path = queueFile('pending', parsed.name, this.ctx);
563
+ if (path === null)
564
+ continue;
565
+ const locked = await this.withLock(parsed.name, async () => {
566
+ const record = await this.readRecord(path);
567
+ if (record === null || !isParked(record))
568
+ return null;
569
+ await this.rewrite(path, { ...record, notBefore: 0 });
570
+ return record.proposal.id;
571
+ }, SETTLE_LOCK_ATTEMPTS);
572
+ if (locked.held && locked.value !== null)
573
+ thawed.push(locked.value);
574
+ }
575
+ if (thawed.length > 0)
576
+ this.invalidateCounts();
577
+ return thawed;
578
+ }
500
579
  async settlePending(parsed, outcome, redact = false) {
501
580
  const from = queueFile('pending', parsed.name, this.ctx);
502
581
  const to = queueFile('done', parsed.name, this.ctx);
@@ -202,6 +202,26 @@ export declare class RunStore {
202
202
  private measureArtifacts;
203
203
  private get indexPath();
204
204
  private appendIndexUnlocked;
205
+ /**
206
+ * NEWEST FIRST, AND A KNOWN RUN'S OLDER ROWS ARE NEVER PARSED.
207
+ *
208
+ * The index is append-only (`appendIndexUnlocked`), so the row that decides a run's
209
+ * place in the list is the LAST one for that run - which is why this scans backwards
210
+ * and keeps the first row it meets per run id.
211
+ *
212
+ * Why that matters: 10 000 rows for 100 runs is the shape real use produces (one or
213
+ * two rows per dispatch), and `JSON.parse` of 2.5 MB was the whole cost of
214
+ * `listRuns()` - AC-67 budgets 50 ms for it and a loaded Windows host measured
215
+ * 45-58 ms, i.e. the budget was already the machine's floor. Skipping the 9 900
216
+ * rows whose run is known brings the same file to 4-6 ms here, because the cheap
217
+ * `INDEX_ROW_PREFIX` lookahead runs before any parsing.
218
+ *
219
+ * The lookahead can only ever SKIP a row whose run id it read correctly, and it
220
+ * reads it only from the exact prefix `appendIndexUnlocked` writes. Anything else -
221
+ * a legacy row with a different key order, a hand-edited line, a torn write - fails
222
+ * the prefix and takes the full parse below, so the damaged-row and legacy-row rules
223
+ * are unchanged: a torn row is dropped, a row without a digest still lists.
224
+ */
205
225
  private readIndexUnlocked;
206
226
  /** Latest row per run, newest first. */
207
227
  listRuns(): Promise<IndexEntry[]>;
@@ -466,26 +466,52 @@ export class RunStore {
466
466
  cache.indexedDigest = digest === undefined ? null : JSON.stringify(digest);
467
467
  }
468
468
  }
469
+ /**
470
+ * NEWEST FIRST, AND A KNOWN RUN'S OLDER ROWS ARE NEVER PARSED.
471
+ *
472
+ * The index is append-only (`appendIndexUnlocked`), so the row that decides a run's
473
+ * place in the list is the LAST one for that run - which is why this scans backwards
474
+ * and keeps the first row it meets per run id.
475
+ *
476
+ * Why that matters: 10 000 rows for 100 runs is the shape real use produces (one or
477
+ * two rows per dispatch), and `JSON.parse` of 2.5 MB was the whole cost of
478
+ * `listRuns()` - AC-67 budgets 50 ms for it and a loaded Windows host measured
479
+ * 45-58 ms, i.e. the budget was already the machine's floor. Skipping the 9 900
480
+ * rows whose run is known brings the same file to 4-6 ms here, because the cheap
481
+ * `INDEX_ROW_PREFIX` lookahead runs before any parsing.
482
+ *
483
+ * The lookahead can only ever SKIP a row whose run id it read correctly, and it
484
+ * reads it only from the exact prefix `appendIndexUnlocked` writes. Anything else -
485
+ * a legacy row with a different key order, a hand-edited line, a torn write - fails
486
+ * the prefix and takes the full parse below, so the damaged-row and legacy-row rules
487
+ * are unchanged: a torn row is dropped, a row without a digest still lists.
488
+ */
469
489
  async readIndexUnlocked() {
470
490
  const text = await this.fs.readFile(this.indexPath).catch(() => '');
491
+ const lines = text.split('\n');
471
492
  const latest = new Map();
472
- for (const line of text.split('\n')) {
493
+ for (let at = lines.length - 1; at >= 0; at -= 1) {
494
+ const line = lines[at];
473
495
  if (line.trim() === '')
474
496
  continue;
497
+ const known = knownRunId(line);
498
+ if (known !== null && latest.has(known))
499
+ continue;
475
500
  try {
476
501
  const row = JSON.parse(line);
477
- if (typeof row.runId === 'string' && RUN_ID_PATTERN.test(row.runId)) {
478
- const digest = parseRunDigest(row.digest);
479
- // A hand-edited or damaged digest is dropped, never trusted: the row still lists.
480
- const { digest: _raw, ...rest } = row;
481
- latest.set(row.runId, digest === undefined ? rest : { ...rest, digest });
482
- }
502
+ if (typeof row.runId !== 'string' || !RUN_ID_PATTERN.test(row.runId))
503
+ continue;
504
+ const digest = parseRunDigest(row.digest);
505
+ // A hand-edited or damaged digest is dropped, never trusted: the row still lists.
506
+ delete row.digest;
507
+ latest.set(row.runId, digest === undefined ? row : { ...row, digest });
483
508
  }
484
509
  catch {
485
510
  // A torn index row is skipped; the run folder is still on disk.
486
511
  }
487
512
  }
488
- return [...latest.values()];
513
+ // The map is oldest-last; every caller expects the file's own order.
514
+ return [...latest.values()].reverse();
489
515
  }
490
516
  /** Latest row per run, newest first. */
491
517
  async listRuns() {
@@ -612,6 +638,26 @@ export class RunStore {
612
638
  function finiteNumber(value) {
613
639
  return typeof value === 'number' && Number.isFinite(value);
614
640
  }
641
+ /**
642
+ * The exact bytes `appendIndexUnlocked` writes before a run id - nothing else may be
643
+ * read as one, so a legacy row (different key order) or a hand-edited line always takes
644
+ * the slow, full-parse path in `readIndexUnlocked`.
645
+ */
646
+ const INDEX_ROW_PREFIX = '{"runId":"';
647
+ /**
648
+ * A run id taken from the row's own first field WITHOUT parsing the row, or `null` when
649
+ * this line is not shaped like the writer's. Only ever used to recognise an already-known
650
+ * run, never to trust a row's contents.
651
+ */
652
+ function knownRunId(line) {
653
+ if (!line.startsWith(INDEX_ROW_PREFIX))
654
+ return null;
655
+ const end = line.indexOf('"', INDEX_ROW_PREFIX.length);
656
+ if (end < 0)
657
+ return null;
658
+ const runId = line.slice(INDEX_ROW_PREFIX.length, end);
659
+ return RUN_ID_PATTERN.test(runId) ? runId : null;
660
+ }
615
661
  /** Validate an index row's digest field; anything malformed reads as "no digest". */
616
662
  export function parseRunDigest(raw) {
617
663
  if (typeof raw !== 'object' || raw === null)
@@ -67,6 +67,12 @@ export function makeController(flags, opts = { interactive: true }) {
67
67
  const controller = new AgentController(config, {
68
68
  version: VERSION,
69
69
  todoPanelCapable,
70
+ // THE SAME ANSWER `todoPanelCapable` GIVES, for the same reason (tiered-reconnect
71
+ // §4.4 / D-6): a headless host is headless. `-p`, `aragon exec` and every
72
+ // subcommand build with `interactive: false` and therefore get the BOUNDED
73
+ // ladder (two tiers), while the TUI keeps the full three. Derived here rather
74
+ // than threaded through five call sites, so no host can forget it.
75
+ reconnectMode: opts.interactive ? 'interactive' : 'headless',
70
76
  confirm: (req) => confirmBridge.handler ? confirmBridge.handler(req) : Promise.resolve(true),
71
77
  // THE TWO CAN NEVER BOTH BE PRESENT: `interactive: false` is the only path
72
78
  // that supplies a bridge gate, and the interactive branch is the only one that
@@ -24,3 +24,4 @@ export * from './commands.js';
24
24
  export * from './skills.js';
25
25
  export * from './index-build.js';
26
26
  export * from './team-control.js';
27
+ export * from './team-wake-driver.js';
@@ -24,3 +24,4 @@ export * from './commands.js';
24
24
  export * from './skills.js';
25
25
  export * from './index-build.js';
26
26
  export * from './team-control.js';
27
+ export * from './team-wake-driver.js';
@@ -38,13 +38,14 @@ export declare class InteractionCoordinator {
38
38
  private gesture;
39
39
  private disposed;
40
40
  /**
41
- * The team settle timer (team-detached-dispatch section 5.3.3).
42
- *
43
- * THIS HOST'S OWN, exactly like the TUI's `followTimer`, and armed from the SAME
44
- * pure decision table: that is what makes the two front ends answer one sentence
45
- * identically (R9) without either owning the policy.
41
+ * The team wake driver (team-lead-wake-signals 4.10): the SAME class the terminal
42
+ * mounts, with this host's own timer. It subscribes to the controller for the life of
43
+ * the coordinator, so a dispatch that ends while the lead is idle still starts a turn -
44
+ * which no `onAgentEnd` hook could do, because no agent event fires in that state.
46
45
  */
47
- private settleTimer;
46
+ private readonly wakeDriver;
47
+ private wakeTimer;
48
+ private readonly detachWake;
48
49
  constructor(ports: InteractionPorts);
49
50
  get phase(): InteractionPhase;
50
51
  /** Feed `agent_start` / `agent_end` here so `phase` follows the engine. */
@@ -55,17 +56,7 @@ export declare class InteractionCoordinator {
55
56
  * else.
56
57
  */
57
58
  onAgentEnd(): void;
58
- /**
59
- * Arm, announce, or skip the settle continuation (5.3.3).
60
- *
61
- * THE SAME TRUTH TABLE THE TERMINAL RUNS (`planSettleContinuation`), fed this
62
- * host's facts. `followThroughArmed` is false here because this host has no todo
63
- * follow-through and no forced-dispatch nudge: the flag exists for the hosts
64
- * that do, and passing `false` is the honest answer rather than a guess.
65
- */
66
- private armTeamSettle;
67
- /** Release the settle timer. Called from `dispose()` so it cannot fire into a dead host. */
68
- private clearSettleTimer;
59
+ private clearWakeTimer;
69
60
  /** Land the team-mode change that was asked for during the turn, and say what happened. */
70
61
  private landTeamMode;
71
62
  /** Send a message to the agent, bypassing slash parsing. */
@@ -23,7 +23,7 @@ import { teamModeToast, teamRefusalText } from '@aragon-agent/tui/model/team/tea
23
23
  import { buildInvocationCard, invocationCardsEnabled } from '@aragon-agent/tui/model/agent/invocation-card';
24
24
  import { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
25
25
  import { redactText } from '../logging/redact.js';
26
- import { planSettleContinuation } from '@aragon-agent/tui/model/team/settle-plan';
26
+ import { TeamWakeDriver } from './team-wake-driver.js';
27
27
  export class InteractionCoordinator {
28
28
  ports;
29
29
  phaseValue = 'idle';
@@ -31,15 +31,41 @@ export class InteractionCoordinator {
31
31
  gesture = { phase: 'ready' };
32
32
  disposed = false;
33
33
  /**
34
- * The team settle timer (team-detached-dispatch section 5.3.3).
35
- *
36
- * THIS HOST'S OWN, exactly like the TUI's `followTimer`, and armed from the SAME
37
- * pure decision table: that is what makes the two front ends answer one sentence
38
- * identically (R9) without either owning the policy.
34
+ * The team wake driver (team-lead-wake-signals 4.10): the SAME class the terminal
35
+ * mounts, with this host's own timer. It subscribes to the controller for the life of
36
+ * the coordinator, so a dispatch that ends while the lead is idle still starts a turn -
37
+ * which no `onAgentEnd` hook could do, because no agent event fires in that state.
39
38
  */
40
- settleTimer = null;
39
+ wakeDriver;
40
+ wakeTimer = null;
41
+ detachWake;
41
42
  constructor(ports) {
42
43
  this.ports = ports;
44
+ this.wakeDriver = new TeamWakeDriver({
45
+ // Optional on purpose: a controller double or an older host has no team surface.
46
+ controller: ports.controller,
47
+ timer: {
48
+ set: (fn, ms) => {
49
+ this.clearWakeTimer();
50
+ this.wakeTimer = setTimeout(() => {
51
+ this.wakeTimer = null;
52
+ if (!this.disposed)
53
+ fn();
54
+ }, ms);
55
+ this.wakeTimer.unref?.();
56
+ },
57
+ clear: () => this.clearWakeTimer(),
58
+ // This host has no todo follow-through and no forced-dispatch nudge, so nothing
59
+ // else ever holds a continuation slot here.
60
+ armed: () => this.wakeTimer !== null,
61
+ },
62
+ announce: (level, text) => ports.notify(level, text),
63
+ // `'starting'` counts: the user's turn is already inside `prompt()` waiting on its
64
+ // gene planning, where the controller still answers `isRunning() === false`.
65
+ leadBusy: () => this.phaseValue !== 'idle',
66
+ submit: (text, invocation) => this.submit(text, { userInitiated: false, todoPolicy: 'continue', invocation }).accepted,
67
+ });
68
+ this.detachWake = this.wakeDriver.attach();
43
69
  }
44
70
  get phase() {
45
71
  return this.phaseValue;
@@ -62,12 +88,10 @@ export class InteractionCoordinator {
62
88
  // otherwise be skipped by the `if (!applied) return` below and sit pending until the next
63
89
  // `prompt()` safety net (team-mode-toggle-keys R-10).
64
90
  this.landTeamMode();
65
- // THE TEAM SETTLE, BEFORE THE POSTURE'S EARLY RETURN (5.3.3): the decision has
66
- // to be made once per `agent_end`, and the posture returns early for almost
67
- // every turn. A dispatch that settled during this turn announces or continues
68
- // here; one that settled inside the turn itself is `none` by the table's own
69
- // rule, because its report already arrived as a steering message.
70
- this.armTeamSettle();
91
+ // NO TEAM DECISION HERE ANY MORE (team-lead-wake-signals). It used to be made once
92
+ // per `agent_end`, which a dispatch ending while the lead is idle never produces.
93
+ // The controller's governor re-evaluates when the lead goes idle and when a signal
94
+ // arrives, and the wake driver above acts on its requests.
71
95
  const applied = controller.applyPendingPosture();
72
96
  if (!applied)
73
97
  return;
@@ -81,62 +105,10 @@ export class InteractionCoordinator {
81
105
  });
82
106
  dispatch({ type: 'pushToast', level: 'info', text: postureAppliedToast(applied.effective) });
83
107
  }
84
- /**
85
- * Arm, announce, or skip the settle continuation (5.3.3).
86
- *
87
- * THE SAME TRUTH TABLE THE TERMINAL RUNS (`planSettleContinuation`), fed this
88
- * host's facts. `followThroughArmed` is false here because this host has no todo
89
- * follow-through and no forced-dispatch nudge: the flag exists for the hosts
90
- * that do, and passing `false` is the honest answer rather than a guess.
91
- */
92
- armTeamSettle() {
93
- const { controller, dispatch } = this.ports;
94
- const facts = controller.teamSettleFacts?.() ?? null;
95
- if (facts === null)
96
- return;
97
- const team = controller.getTeamConfig();
98
- const decision = planSettleContinuation({
99
- mode: team.autoResume,
100
- settled: facts.settled,
101
- settledInsideTurn: facts.settledInsideTurn,
102
- runEnd: { aborted: facts.aborted, errored: facts.errored },
103
- continuedThisDispatch: facts.continuedThisDispatch,
104
- userPending: controller.hasPendingUserMessages(),
105
- followThroughArmed: false,
106
- graceMs: team.settleGraceMs,
107
- outcome: facts.outcome,
108
- });
109
- if (decision.kind === 'notice') {
110
- this.ports.notify(decision.level, decision.text);
111
- return;
112
- }
113
- if (decision.kind !== 'continue')
114
- return;
115
- this.ports.notify(decision.level, decision.notice);
116
- if (this.settleTimer !== null)
117
- clearTimeout(this.settleTimer);
118
- this.settleTimer = setTimeout(() => {
119
- this.settleTimer = null;
120
- // Re-read at fire time: the user may have typed in the grace window, and a
121
- // continuation that starts over their message is the one promise this table
122
- // must never break.
123
- if (this.disposed)
124
- return;
125
- if (controller.isRunning() || controller.isCompactionBusy?.())
126
- return;
127
- if (controller.hasPendingUserMessages())
128
- return;
129
- // The id comes from the facts: the dispatch has settled, so `live()` is null.
130
- controller.markTeamContinued(facts.dispatchId);
131
- void controller.prompt(decision.message, { todoPolicy: 'continue' });
132
- }, decision.graceMs);
133
- this.settleTimer.unref?.();
134
- }
135
- /** Release the settle timer. Called from `dispose()` so it cannot fire into a dead host. */
136
- clearSettleTimer() {
137
- if (this.settleTimer !== null)
138
- clearTimeout(this.settleTimer);
139
- this.settleTimer = null;
108
+ clearWakeTimer() {
109
+ if (this.wakeTimer !== null)
110
+ clearTimeout(this.wakeTimer);
111
+ this.wakeTimer = null;
140
112
  }
141
113
  /** Land the team-mode change that was asked for during the turn, and say what happened. */
142
114
  landTeamMode() {
@@ -159,6 +131,9 @@ export class InteractionCoordinator {
159
131
  /** Send a message to the agent, bypassing slash parsing. */
160
132
  submit(message, opts = {}) {
161
133
  const { controller, dispatch, notify } = this.ports;
134
+ // A user message outranks a pending wake. The wake driver's OWN submit passes through
135
+ // here too, and finds nothing to cancel: it takes its countdown down before it submits.
136
+ this.wakeDriver.cancel();
162
137
  if (controller.getConfig().modelSettingsRestartRequired) {
163
138
  return { accepted: false, reason: 'Settings require a restart before sending requests.' };
164
139
  }
@@ -239,6 +214,8 @@ export class InteractionCoordinator {
239
214
  */
240
215
  interrupt(now = performance.now()) {
241
216
  const { controller, dispatch } = this.ports;
217
+ // Stop during the wake countdown also cancels the wake (a no-op when there is none).
218
+ this.wakeDriver.cancel();
242
219
  const next = advanceInterruptGesture(this.gesture, now);
243
220
  this.gesture = next.state;
244
221
  if (next.action === 'hint')
@@ -270,9 +247,10 @@ export class InteractionCoordinator {
270
247
  }
271
248
  dispose() {
272
249
  this.disposed = true;
273
- // An armed continuation must not fire into a disposed host: the timer would
274
- // call `controller.prompt()` for a coordinator nobody is listening to.
275
- this.clearSettleTimer();
250
+ // An armed wake must not fire into a disposed host: the timer would call
251
+ // `controller.prompt()` for a coordinator nobody is listening to.
252
+ this.detachWake();
253
+ this.clearWakeTimer();
276
254
  this.sequence += 1;
277
255
  if (this.phaseValue === 'starting' || this.ports.controller.isCompactionBusy?.()) {
278
256
  this.ports.controller.abort();
@@ -0,0 +1,90 @@
1
+ /**
2
+ * TeamWakeDriver - how a HOST starts the turn the team asked for
3
+ * (team-lead-wake-signals section 4.10).
4
+ *
5
+ * THE GOVERNOR DECIDES THAT THE LEAD IS OWED A TURN; THIS DECIDES HOW THIS HOST
6
+ * STARTS ONE. Both the terminal app and the desktop coordinator mount exactly this
7
+ * class with their own ports, so the countdown, the cancel rules and the re-check at
8
+ * fire time are one implementation, not two that drift (AC-24). Everything that
9
+ * differs between hosts - where the timer lives, how a line is shown, how a turn is
10
+ * submitted - is a port.
11
+ *
12
+ * NO INK, NO TTY (layering gate L9): this file is in the import closure of
13
+ * `host/index.ts`, which a GUI process loads.
14
+ *
15
+ * THREE RULES THAT ARE EASY TO BREAK:
16
+ *
17
+ * - FIRE IS ONE SYNCHRONOUS BLOCK (I-WK10). Re-check, `leadBusy()`, submit, ack - no
18
+ * `await`. The controller's `prompt()` STOPS a running engine and the terminal's
19
+ * `submitMessage` turns a submit-while-running into USER steering; a wake that
20
+ * raced either would kill the lead's turn or masquerade as the user. So the busy
21
+ * checks and the submit share a stack frame.
22
+ *
23
+ * - THE DRIVER'S OWN SUBMIT MUST NOT CANCEL ITSELF. The terminal's `submitMessage`
24
+ * begins with `cancelFollowThrough()` ("any user input cancels a pending
25
+ * continuation"), and this driver is wired to that very call. So `fire` takes
26
+ * `outstandingId` down BEFORE it submits, and `cancel()` only acts on a request
27
+ * it still holds: the submit's own cancel finds nothing and does nothing. Without
28
+ * this the user sees "Wake cancelled" over a turn that is in fact running, and
29
+ * the governor parks notices it has just delivered.
30
+ *
31
+ * - A BUSY HOST IS NOT A DROPPED WAKE. Another continuation holding the timer, or the
32
+ * lead being busy, answers `busy`; the governor retries with back-off. Nothing is
33
+ * discarded and nothing steals the other continuation's slot (I-WK9).
34
+ */
35
+ import type { InvocationCardInput } from '@aragon-agent/tui/model/agent/invocation-card';
36
+ import type { TeamWakeAck, TeamWakeBegin, TeamWakeRequest } from '../team/wake.js';
37
+ /** The three controller methods a host needs; a structural subset so tests can fake it. */
38
+ export interface TeamWakeControllerPort {
39
+ subscribeTeamWake(listener: (request: TeamWakeRequest) => void): () => void;
40
+ confirmTeamWake(requestId: string): TeamWakeBegin;
41
+ ackTeamWake(requestId: string, result: TeamWakeAck): void;
42
+ }
43
+ export interface TeamWakePorts {
44
+ controller: TeamWakeControllerPort;
45
+ /**
46
+ * The countdown timer. The terminal binds its single follow-through slot, so "at
47
+ * most one armed continuation" stays true (I-WK9); the desktop owns its own.
48
+ */
49
+ timer: {
50
+ set(fn: () => void, ms: number): void;
51
+ clear(): void;
52
+ armed(): boolean;
53
+ };
54
+ /** One line in the transcript: the countdown, the `notify` line. */
55
+ announce(level: 'info' | 'warn', text: string): void;
56
+ /** A transient message (the cancellation). Falls back to `announce`. */
57
+ toast?(level: 'info' | 'warn', text: string): void;
58
+ /**
59
+ * Begin a turn through THIS host's own submit pipeline (`userInitiated: false`,
60
+ * `todoPolicy: 'continue'`, with the card). Returns whether it was accepted.
61
+ *
62
+ * A synchronous boolean cannot express the engine refusing later (`prompt()`'s
63
+ * `not-started` is asynchronous, and the terminal even answers `accepted` when its
64
+ * preflight fails), so a refusal after a `true` is the governor's silence watchdog's
65
+ * to catch, not this port's.
66
+ */
67
+ submit(text: string, invocation: InvocationCardInput): boolean;
68
+ /** `Esc cancels` in the terminal; a host with no such gesture leaves it out. */
69
+ cancelHint?(): string;
70
+ /** This host's view of "a turn is running or starting" (OR-ed with the controller's). */
71
+ leadBusy(): boolean;
72
+ }
73
+ export declare class TeamWakeDriver {
74
+ private readonly ports;
75
+ /** The countdown this driver is holding, if any. The only thing `cancel()` acts on. */
76
+ private outstandingId;
77
+ constructor(ports: TeamWakePorts);
78
+ /** Subscribe to the controller. Returns the detach function. */
79
+ attach(): () => void;
80
+ /** Whether a countdown is running right now. Hosts use it to avoid a second toast. */
81
+ isCounting(): boolean;
82
+ /**
83
+ * The user typed or pressed Esc: stop the countdown. Called by the host from its own
84
+ * "cancel any pending continuation" point. A no-op unless this driver holds a request.
85
+ */
86
+ cancel(): void;
87
+ private onRequest;
88
+ /** The countdown ended. One synchronous block (I-WK10). */
89
+ private fire;
90
+ }