@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
@@ -12,11 +12,19 @@ import type { TodoEvent, TodoSnapshot } from '@aragon-agent/tui/model/todo/types
12
12
  import type { FastEvent } from '@aragon-agent/tui/model/fast/types';
13
13
  import type { CompactionEvent } from '@aragon-agent/tui/model/compaction/types';
14
14
  import { type FollowThroughMode } from '@aragon-agent/tui/model/todo/follow-through';
15
+ import type { RunResumePolicy } from '@aragon-agent/tui/model/config/schema';
15
16
  /** The minimal controller surface headless mode needs (real or stubbed). */
16
17
  export interface HeadlessController {
17
18
  preflight(): PreflightResult;
18
19
  subscribe(listener: (event: AgentEvent) => void): () => void;
19
20
  prompt(text: string): Promise<void | PromptOutcome>;
21
+ /**
22
+ * Re-run the loop from the current history WITHOUT adding a message - OPTIONAL,
23
+ * for the identical reason the subscriptions below are (team-idle-watchdog-dead-run
24
+ * F3). ABSENT MEANS A RECOVERY IS NEVER ATTEMPTED, which keeps a stubbed
25
+ * controller's stdout, stderr and exit code byte-identical to today's.
26
+ */
27
+ continue?(): Promise<void | PromptOutcome>;
20
28
  getModelInfo(): ModelInfo;
21
29
  /**
22
30
  * The CLI-local team stream — OPTIONAL, deliberately (team-subagents §3.12 /
@@ -75,6 +83,14 @@ export interface HeadlessOptions {
75
83
  * `getTodoConfig().followThrough` there.
76
84
  */
77
85
  followThrough?: FollowThroughMode;
86
+ /**
87
+ * Whether, and how often, to re-run a run the engine interrupted (idle watchdog,
88
+ * or a retry ladder that gave up on a transport failure). PASSED IN for the reason
89
+ * `followThrough` is: the real entry points hold the real controller and resolve it
90
+ * from `retry.*` with `toRunResumePolicy(..., { headless: true })`, which is where
91
+ * `-p` gets its one-recovery cap. ABSENT = no recovery, exactly as before.
92
+ */
93
+ resume?: RunResumePolicy;
78
94
  }
79
95
  /** Run a single prompt headlessly and resolve with the process exit code. */
80
96
  export declare function runHeadless(controller: HeadlessController, prompt: string, options?: HeadlessOptions): Promise<number>;
@@ -8,7 +8,7 @@ import { formatCost, formatTokens, formatDuration, computeCost } from '@aragon-a
8
8
  import { formatStreamError } from '@aragon-agent/tui/model/agent/reducer';
9
9
  import { runDurationMs } from '../team/report.js';
10
10
  import { derivePlanPhase } from '@aragon-agent/tui/model/todo/acceptance';
11
- import { advanceBudget, decideFollowThrough, emptyBudget, isTransientRunEnd, } from '@aragon-agent/tui/model/todo/follow-through';
11
+ import { advanceBudget, chargeResume, decideFollowThrough, emptyBudget, emptyResumeCounters, isTransientRunEnd, settleResumeCounters, } from '@aragon-agent/tui/model/todo/follow-through';
12
12
  /**
13
13
  * Mark time. The only wait `-p` ever takes, and it exists for one caller: the
14
14
  * recovery grace in the follow-through loop below (`errorGraceMs`).
@@ -16,6 +16,20 @@ import { advanceBudget, decideFollowThrough, emptyBudget, isTransientRunEnd, } f
16
16
  function pauseMs(ms) {
17
17
  return new Promise((resolve) => setTimeout(resolve, ms));
18
18
  }
19
+ /**
20
+ * The wait, as a piped consumer reads it: `8s`, `1m00s`, `5m00s`.
21
+ *
22
+ * Minutes matter now that a wait can be five of them (tiered-reconnect §4.6.7):
23
+ * `waiting 300s` is technically true and useless, and the CLI's other duration
24
+ * formatter is a `Glyphs`-aware UI module this file deliberately does not import.
25
+ */
26
+ function formatWait(ms) {
27
+ const seconds = Math.max(0, Math.round(ms / 1000));
28
+ if (seconds < 60)
29
+ return `${seconds}s`;
30
+ const minutes = Math.floor(seconds / 60);
31
+ return `${minutes}m${String(seconds % 60).padStart(2, '0')}s`;
32
+ }
19
33
  /** Run a single prompt headlessly and resolve with the process exit code. */
20
34
  export async function runHeadless(controller, prompt, options = {}) {
21
35
  const out = options.stdout ?? process.stdout;
@@ -59,12 +73,19 @@ export async function runHeadless(controller, prompt, options = {}) {
59
73
  // `aragon -p | jq`; a retry line on it would corrupt every consumer.
60
74
  // Not `--quiet`-gated, unlike the tool lines: a three-minute pause with
61
75
  // no explanation anywhere is not a "compact" run, it is a hang.
62
- retryCount = se.attempt;
76
+ //
77
+ // THE CUMULATIVE COUNT (tiered-reconnect §4.6.7 / P2-7), not `attempt`:
78
+ // `attempt` restarts at 1 in every tier, so a recovery in tier 2 would
79
+ // otherwise be reported as "2 retries" after eleven minutes of waiting.
80
+ retryCount = se.totalAttempts ?? se.attempt;
81
+ // The tier rides the same line, because `[retry 2/10]` alone cannot say
82
+ // WHICH 2/10 - the fast tier's or the one-minute tier's.
83
+ const tierTag = se.tier !== undefined && se.tier > 1 ? ` tier ${se.tier}` : '';
63
84
  // The em dash is a literal because `agent/headless.ts` is the CLI's one
64
85
  // documented glyph-scanner exemption: `aragon -p` does no capability
65
86
  // probe, so there is no `Glyphs` set to read here.
66
- err.write(`\n[retry ${se.attempt}/${se.maxRetries}] ${se.errorType} — ` +
67
- `waiting ${Math.round(se.delayMs / 1000)}s\n`);
87
+ err.write(`\n[retry ${se.attempt}/${se.maxRetries}${tierTag}] ${se.errorType} — ` +
88
+ `waiting ${formatWait(se.delayMs)}\n`);
68
89
  }
69
90
  else if (se.type === 'stream_restart') {
70
91
  // The partial answer already on stdout is about to be replayed. Saying so
@@ -106,6 +127,9 @@ export async function runHeadless(controller, prompt, options = {}) {
106
127
  ...(event.errorType !== undefined ? { errorType: event.errorType } : {}),
107
128
  ...(event.retryable !== undefined ? { retryable: event.retryable } : {}),
108
129
  ...(event.reason !== undefined ? { reason: event.reason } : {}),
130
+ // For the recovery notice's WORDING only (F3): without it the line says "the
131
+ // model stopped responding" and cannot say for how long or doing what.
132
+ ...(event.stall !== undefined ? { stall: event.stall } : {}),
109
133
  };
110
134
  if (!sawTurnEnd && !errored)
111
135
  errored = true;
@@ -316,6 +340,12 @@ export async function runHeadless(controller, prompt, options = {}) {
316
340
  const followThrough = options.followThrough ?? 'notify';
317
341
  let budget = emptyBudget();
318
342
  let wasAutoContinuation = false;
343
+ // A RECOVERY NEEDS THE CONTROLLER TO BE ABLE TO CONTINUE (F3): without `continue`
344
+ // the only way to "retry" would be to resend the user's prompt, which is a
345
+ // different act (a duplicate message in the history), so the capability is absent.
346
+ const resumePolicy = typeof controller.continue === 'function' ? options.resume : undefined;
347
+ let resumeCounters = emptyResumeCounters();
348
+ let resumeNext = false;
319
349
  try {
320
350
  let message = prompt;
321
351
  for (;;) {
@@ -328,10 +358,19 @@ export async function runHeadless(controller, prompt, options = {}) {
328
358
  // `turn_end`, the only event that proves a recovery happened.
329
359
  sawTurnEnd = false;
330
360
  endFacts = {};
331
- await controller.prompt(message);
361
+ // A RECOVERY RE-RUNS THE HISTORY AS IT STANDS; it submits nothing, so `message`
362
+ // is neither consumed nor replaced.
363
+ if (resumeNext) {
364
+ resumeNext = false;
365
+ await controller.continue?.();
366
+ }
367
+ else {
368
+ await controller.prompt(message);
369
+ }
332
370
  const snapshot = controller.getTodoSnapshot?.() ?? null;
333
371
  budget = advanceBudget(budget, snapshot, wasAutoContinuation);
334
372
  wasAutoContinuation = false;
373
+ resumeCounters = settleResumeCounters(resumeCounters, { aborted: false, errored });
335
374
  const decision = decideFollowThrough({
336
375
  mode: followThrough,
337
376
  snapshot,
@@ -344,14 +383,37 @@ export async function runHeadless(controller, prompt, options = {}) {
344
383
  runEnd: { aborted: false, errored, transient: isTransientRunEnd(endFacts) },
345
384
  budget,
346
385
  interactive: false,
386
+ ...(resumePolicy
387
+ ? {
388
+ resume: {
389
+ ...resumePolicy,
390
+ consecutive: resumeCounters.consecutive,
391
+ total: resumeCounters.total,
392
+ cause: endFacts,
393
+ },
394
+ }
395
+ : {}),
347
396
  });
348
397
  if (decision.kind === 'none')
349
398
  break;
350
399
  if (decision.kind === 'notify') {
400
+ const tag = decision.source === 'resume' ? 'retry' : 'todo';
351
401
  if (!quiet)
352
- err.write(`\n[todo] ${decision.text}\n`);
402
+ err.write(`\n[${tag}] ${decision.text}\n`);
353
403
  break;
354
404
  }
405
+ if (decision.kind === 'resume') {
406
+ // CHARGED BEFORE THE WAIT, like the todo continuation below: headless has no
407
+ // timer to charge it in, and an uncharged counter is an uncapped loop in the
408
+ // one environment with no human to press Esc.
409
+ resumeCounters = chargeResume(resumeCounters);
410
+ if (!quiet)
411
+ err.write(`\n[retry] ${decision.notice}\n`);
412
+ if (decision.graceMs > 0)
413
+ await pauseMs(decision.graceMs);
414
+ resumeNext = true;
415
+ continue;
416
+ }
355
417
  // CHARGED BEFORE THE RE-PROMPT, and this line is the whole of the headless
356
418
  // cap (P1-2 / I-5 / AC-37). The TUI charges `used` in its grace-timer
357
419
  // callback; headless has no timer, so without this `maxAutoContinuesPerList`
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Sticky starting tier — remember the tier a request just recovered in
3
+ * (tiered-reconnect §4.9, step 8 of the implementation order).
4
+ *
5
+ * THE PROBLEM IT SOLVES, in one sentence: on a link that is down for twenty minutes,
6
+ * every NEW request would spend its first four minutes re-learning what the previous
7
+ * request already proved — that the fast ladder does not work right now. A turn can
8
+ * contain five requests, so that is twenty minutes of waiting for a fact we knew.
9
+ *
10
+ * PROCESS-LOCAL BY DESIGN. Nothing here is persisted and nothing is a `ViewState`
11
+ * field: a tier is a property of the network at this moment, and a stale one loaded
12
+ * from disk tomorrow would be worse than no memory at all (the same argument
13
+ * `RetryPolicy` makes about its own, non-persisted state).
14
+ *
15
+ * OFF BY DEFAULT (`retry.stickyRung: false`), and the switch is checked by the
16
+ * caller, so a session that never flips it is byte-identical to one built before
17
+ * this module existed.
18
+ *
19
+ * NO DEPENDENCIES, NO TIMERS, NO I/O: `now` is injected, exactly like `TodoStore`'s
20
+ * clock, so the window can be tested without waiting two minutes.
21
+ */
22
+ import type { RetryTierId } from '@aragon-agent/core';
23
+ /** How long a recovery keeps steering new requests at the slow tier. */
24
+ export declare const RECONNECT_MEMORY: {
25
+ /**
26
+ * TWO MINUTES. Long enough to cover the next request of the same turn and the
27
+ * user reading one answer; short enough that a network which came back from a
28
+ * lunch break does not silently skip the fast ladder.
29
+ */
30
+ readonly stickyMs: 120000;
31
+ };
32
+ /** Which provider/model a memory belongs to; a change invalidates it. */
33
+ export interface ReconnectRef {
34
+ providerId: string;
35
+ modelId: string;
36
+ }
37
+ /**
38
+ * One record, and the two questions asked of it.
39
+ *
40
+ * A CLASS rather than two module-level functions so a test — and, one day, a second
41
+ * controller in one process (the host spawns several) — cannot share state by
42
+ * accident. Mutable on purpose: this is a memo, and a "pure" version would have to
43
+ * thread a value through the request path, which is precisely where the escalation
44
+ * policy travels and where a second source of truth would be born.
45
+ */
46
+ export declare class ReconnectMemory {
47
+ private readonly now;
48
+ private last;
49
+ constructor(now?: () => number);
50
+ /**
51
+ * Record that a request that had retried at least once finally got its answer.
52
+ *
53
+ * `rung === 1` CLEARS the memory rather than storing tier 1: a recovery during the
54
+ * fast ladder is evidence that the network is fine, and leaving an older "we are
55
+ * in the slow tier" record in place would overrule the fresher evidence.
56
+ */
57
+ recordRecovery(ref: ReconnectRef, rung: RetryTierId): void;
58
+ /**
59
+ * The tier a new request should start from, or `undefined` for the default (1).
60
+ *
61
+ * Returns `undefined` for a different provider/model, for a record older than
62
+ * `stickyMs`, and for no record at all — every one of which means "behave exactly
63
+ * as you would without this feature".
64
+ */
65
+ startRungFor(ref: ReconnectRef): RetryTierId | undefined;
66
+ /** Forget everything (a new conversation, or a provider switch the user forced). */
67
+ reset(): void;
68
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Sticky starting tier — remember the tier a request just recovered in
3
+ * (tiered-reconnect §4.9, step 8 of the implementation order).
4
+ *
5
+ * THE PROBLEM IT SOLVES, in one sentence: on a link that is down for twenty minutes,
6
+ * every NEW request would spend its first four minutes re-learning what the previous
7
+ * request already proved — that the fast ladder does not work right now. A turn can
8
+ * contain five requests, so that is twenty minutes of waiting for a fact we knew.
9
+ *
10
+ * PROCESS-LOCAL BY DESIGN. Nothing here is persisted and nothing is a `ViewState`
11
+ * field: a tier is a property of the network at this moment, and a stale one loaded
12
+ * from disk tomorrow would be worse than no memory at all (the same argument
13
+ * `RetryPolicy` makes about its own, non-persisted state).
14
+ *
15
+ * OFF BY DEFAULT (`retry.stickyRung: false`), and the switch is checked by the
16
+ * caller, so a session that never flips it is byte-identical to one built before
17
+ * this module existed.
18
+ *
19
+ * NO DEPENDENCIES, NO TIMERS, NO I/O: `now` is injected, exactly like `TodoStore`'s
20
+ * clock, so the window can be tested without waiting two minutes.
21
+ */
22
+ /** How long a recovery keeps steering new requests at the slow tier. */
23
+ export const RECONNECT_MEMORY = {
24
+ /**
25
+ * TWO MINUTES. Long enough to cover the next request of the same turn and the
26
+ * user reading one answer; short enough that a network which came back from a
27
+ * lunch break does not silently skip the fast ladder.
28
+ */
29
+ stickyMs: 120_000,
30
+ };
31
+ /**
32
+ * One record, and the two questions asked of it.
33
+ *
34
+ * A CLASS rather than two module-level functions so a test — and, one day, a second
35
+ * controller in one process (the host spawns several) — cannot share state by
36
+ * accident. Mutable on purpose: this is a memo, and a "pure" version would have to
37
+ * thread a value through the request path, which is precisely where the escalation
38
+ * policy travels and where a second source of truth would be born.
39
+ */
40
+ export class ReconnectMemory {
41
+ now;
42
+ last = null;
43
+ constructor(now = Date.now) {
44
+ this.now = now;
45
+ }
46
+ /**
47
+ * Record that a request that had retried at least once finally got its answer.
48
+ *
49
+ * `rung === 1` CLEARS the memory rather than storing tier 1: a recovery during the
50
+ * fast ladder is evidence that the network is fine, and leaving an older "we are
51
+ * in the slow tier" record in place would overrule the fresher evidence.
52
+ */
53
+ recordRecovery(ref, rung) {
54
+ if (rung <= 1) {
55
+ this.last = null;
56
+ return;
57
+ }
58
+ this.last = { providerId: ref.providerId, modelId: ref.modelId, rung, at: this.now() };
59
+ }
60
+ /**
61
+ * The tier a new request should start from, or `undefined` for the default (1).
62
+ *
63
+ * Returns `undefined` for a different provider/model, for a record older than
64
+ * `stickyMs`, and for no record at all — every one of which means "behave exactly
65
+ * as you would without this feature".
66
+ */
67
+ startRungFor(ref) {
68
+ const memory = this.last;
69
+ if (!memory)
70
+ return undefined;
71
+ if (memory.providerId !== ref.providerId || memory.modelId !== ref.modelId) {
72
+ return undefined;
73
+ }
74
+ if (this.now() - memory.at > RECONNECT_MEMORY.stickyMs)
75
+ return undefined;
76
+ return memory.rung;
77
+ }
78
+ /** Forget everything (a new conversation, or a provider switch the user forced). */
79
+ reset() {
80
+ this.last = null;
81
+ }
82
+ }
@@ -20,6 +20,14 @@
20
20
  * into the queue. `TeamNoticeQueue.push` is idempotent by id, so a re-queue can
21
21
  * only delay a notice, never duplicate it.
22
22
  *
23
+ * THE RECEIPT IS PER STEER (team-lead-wake-signals I-WK6). Core only echoes a
24
+ * `steering_accepted` for a steer that carried an id (`accept-steering.ts:14`), and
25
+ * the old code steered without one: a notices-only batch never produced a receipt,
26
+ * so the ledger could only be emptied by `requeueUndelivered()` - which re-queued a
27
+ * notice that HAD been delivered, and delivered it again. Now every steer carries a
28
+ * `notice:` id and the ledger is keyed by it, so a receipt releases exactly the
29
+ * notices it carried and nothing else.
30
+ *
23
31
  * WHY NOT ABSTRACTED TOGETHER WITH THE JOB RELAY (spec 5.3.2). The job relay's
24
32
  * channel 1 must never inject while a tool batch is open (its I-5), because a job
25
33
  * notice is a courtesy. A settle report is not a courtesy: the lead was told "you
@@ -27,41 +35,83 @@
27
35
  * One shared class would have to be parameterised into two different policies and
28
36
  * would end up being two classes anyway, one of them hidden.
29
37
  */
30
- import { type TeamNoticeQueue } from '../team/notices.js';
38
+ import { type TeamNotice, type TeamNoticeQueue } from '../team/notices.js';
31
39
  export interface TeamNoticeRelayDeps {
32
40
  queue: TeamNoticeQueue;
33
- /** `enqueueSteering(text, false)` - the receipt-less path. */
34
- steer: (text: string) => void;
41
+ /**
42
+ * `enqueueSteering(text, false, undefined, true)` - the RECEIPT-carrying path for
43
+ * notices. Returns the id Core will echo in `steering_accepted`.
44
+ */
45
+ steer: (text: string) => string;
46
+ /**
47
+ * Take one steer back out of Core's own steering queue (`Agent.removeQueuedSteering`).
48
+ * `true` means it was still waiting there and is now gone.
49
+ *
50
+ * Core's queue SURVIVES a run, and `acceptSteering` returns early on an aborted
51
+ * signal, so a steer can be "sent, not accepted, still queued" when the run ends
52
+ * (RV-P1-1). Re-queueing such a notice without withdrawing it would let the next
53
+ * turn steer a second copy and Core accept both.
54
+ */
55
+ withdraw: (receiptId: string) => boolean;
35
56
  /** `activeToolCalls === 0 && isRunning() && !abortRequested` (push channel). */
36
57
  isAtSafeSteerPoint: () => boolean;
37
58
  /**
38
- * `activeToolCalls === 0 && !abortRequested` - the FILL channel's precondition.
59
+ * The FILL channel's precondition: no tool batch open, and nothing being aborted
60
+ * RIGHT NOW (`activeToolCalls === 0 && (!abortRequested || !isRunning())`).
39
61
  *
40
62
  * NOT `isAtSafeSteerPoint()`, for the reason `job-notices.ts` records at length:
41
63
  * the fill runs immediately before `agent.prompt()`, where `isRunning()` is
42
64
  * FALSE by contract, so the push predicate would make this channel dead.
65
+ *
66
+ * `abortRequested` alone is the wrong half (RV-P1-5): it is set by `stopEngine()`
67
+ * and cleared only at the next `agent_start`, which is AFTER this check. A session
68
+ * whose last turn was interrupted would then refuse the fill for the very next
69
+ * turn - the wake turn included - and the report would miss it.
43
70
  */
44
71
  canSteerBeforeTurn: () => boolean;
45
72
  }
46
73
  export declare class TeamNoticeRelay {
47
74
  private readonly deps;
48
- /** Notices steered but not yet proven delivered, keyed by their queue id. */
75
+ /** Notices steered but not yet proven delivered, keyed by the id their steer carried. */
49
76
  private readonly pendingSteered;
50
77
  constructor(deps: TeamNoticeRelayDeps);
51
78
  /** The push channel: called from the controller's one safe steer point. */
52
79
  tryPush(): boolean;
53
80
  /** The fill channel: just before the next turn starts. */
54
81
  flushForTurn(): boolean;
55
- /** A receipt proves the steering queue was drained, so nothing is stranded. */
56
- onSteeringAccepted(): void;
82
+ /**
83
+ * A receipt proves ONE steer was taken out of Core's queue and into history, so
84
+ * only the notices that steer carried are delivered. Returns their ids.
85
+ */
86
+ onSteeringAccepted(receiptIds: readonly string[]): string[];
57
87
  /**
58
88
  * Put undelivered notices back at `turn_start` and at the end of a run.
59
89
  *
60
90
  * THIS IS WHAT TURNS "swallowed by clearAllQueues()" INTO "delivered one turn
61
91
  * later" - the difference between a report the user gets and a report that
62
92
  * exists only in a file.
93
+ *
94
+ * WITHDRAW FIRST, THEN QUEUE. A receipt-less entry in the ledger is one of two
95
+ * things: Core's queue was wiped (`withdraw` answers false), or Core still holds
96
+ * the steer (`withdraw` answers true and removes it). Either way ours is the only
97
+ * copy afterwards, so queueing it cannot deliver it twice. "Already accepted" is
98
+ * not a third case: that receipt arrives first, synchronously, and the ledger is
99
+ * released before anything here can run.
63
100
  */
64
101
  requeueUndelivered(): void;
102
+ /**
103
+ * Everything the lead has not yet been PROVEN to have: the queue plus the ledger.
104
+ * The wake governor reads this - a notice that was steered but never receipted is
105
+ * still owed.
106
+ */
107
+ undelivered(): TeamNotice[];
108
+ /**
109
+ * Remove one notice from the queue AND the ledger without delivering it (the lead
110
+ * already has it in a tool result - `team_collect`). Returns whether it was held.
111
+ */
112
+ dropById(noticeId: string): boolean;
113
+ /** Forget everything held in the ledger (session reset). Does not touch the queue. */
114
+ reset(): void;
65
115
  /** How many notices are waiting. Used by the tests and the diagnostics path. */
66
116
  pending(): number;
67
117
  private steerQueued;
@@ -20,6 +20,14 @@
20
20
  * into the queue. `TeamNoticeQueue.push` is idempotent by id, so a re-queue can
21
21
  * only delay a notice, never duplicate it.
22
22
  *
23
+ * THE RECEIPT IS PER STEER (team-lead-wake-signals I-WK6). Core only echoes a
24
+ * `steering_accepted` for a steer that carried an id (`accept-steering.ts:14`), and
25
+ * the old code steered without one: a notices-only batch never produced a receipt,
26
+ * so the ledger could only be emptied by `requeueUndelivered()` - which re-queued a
27
+ * notice that HAD been delivered, and delivered it again. Now every steer carries a
28
+ * `notice:` id and the ledger is keyed by it, so a receipt releases exactly the
29
+ * notices it carried and nothing else.
30
+ *
23
31
  * WHY NOT ABSTRACTED TOGETHER WITH THE JOB RELAY (spec 5.3.2). The job relay's
24
32
  * channel 1 must never inject while a tool batch is open (its I-5), because a job
25
33
  * notice is a courtesy. A settle report is not a courtesy: the lead was told "you
@@ -30,7 +38,7 @@
30
38
  import { renderTeamNotices } from '../team/notices.js';
31
39
  export class TeamNoticeRelay {
32
40
  deps;
33
- /** Notices steered but not yet proven delivered, keyed by their queue id. */
41
+ /** Notices steered but not yet proven delivered, keyed by the id their steer carried. */
34
42
  pendingSteered = new Map();
35
43
  constructor(deps) {
36
44
  this.deps = deps;
@@ -47,9 +55,21 @@ export class TeamNoticeRelay {
47
55
  return false;
48
56
  return this.steerQueued();
49
57
  }
50
- /** A receipt proves the steering queue was drained, so nothing is stranded. */
51
- onSteeringAccepted() {
52
- this.pendingSteered.clear();
58
+ /**
59
+ * A receipt proves ONE steer was taken out of Core's queue and into history, so
60
+ * only the notices that steer carried are delivered. Returns their ids.
61
+ */
62
+ onSteeringAccepted(receiptIds) {
63
+ const delivered = [];
64
+ for (const receiptId of receiptIds) {
65
+ const carried = this.pendingSteered.get(receiptId);
66
+ if (carried === undefined)
67
+ continue;
68
+ this.pendingSteered.delete(receiptId);
69
+ for (const notice of carried)
70
+ delivered.push(notice.id);
71
+ }
72
+ return delivered;
53
73
  }
54
74
  /**
55
75
  * Put undelivered notices back at `turn_start` and at the end of a run.
@@ -57,14 +77,69 @@ export class TeamNoticeRelay {
57
77
  * THIS IS WHAT TURNS "swallowed by clearAllQueues()" INTO "delivered one turn
58
78
  * later" - the difference between a report the user gets and a report that
59
79
  * exists only in a file.
80
+ *
81
+ * WITHDRAW FIRST, THEN QUEUE. A receipt-less entry in the ledger is one of two
82
+ * things: Core's queue was wiped (`withdraw` answers false), or Core still holds
83
+ * the steer (`withdraw` answers true and removes it). Either way ours is the only
84
+ * copy afterwards, so queueing it cannot deliver it twice. "Already accepted" is
85
+ * not a third case: that receipt arrives first, synchronously, and the ledger is
86
+ * released before anything here can run.
60
87
  */
61
88
  requeueUndelivered() {
62
89
  if (this.pendingSteered.size === 0)
63
90
  return;
64
- const stranded = [...this.pendingSteered.values()];
91
+ const stranded = [...this.pendingSteered.entries()];
92
+ this.pendingSteered.clear();
93
+ for (const [receiptId, notices] of stranded) {
94
+ try {
95
+ this.deps.withdraw(receiptId);
96
+ }
97
+ catch {
98
+ // A failed withdraw must not cost the notice: the worst case is the old,
99
+ // duplicate-prone behaviour, which is still better than silence.
100
+ }
101
+ for (const notice of notices)
102
+ this.deps.queue.push(notice);
103
+ }
104
+ }
105
+ /**
106
+ * Everything the lead has not yet been PROVEN to have: the queue plus the ledger.
107
+ * The wake governor reads this - a notice that was steered but never receipted is
108
+ * still owed.
109
+ */
110
+ undelivered() {
111
+ const seen = new Set();
112
+ const out = [];
113
+ const all = [...this.deps.queue.peek(), ...[...this.pendingSteered.values()].flat()];
114
+ for (const notice of all) {
115
+ if (seen.has(notice.id))
116
+ continue;
117
+ seen.add(notice.id);
118
+ out.push(notice);
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * Remove one notice from the queue AND the ledger without delivering it (the lead
124
+ * already has it in a tool result - `team_collect`). Returns whether it was held.
125
+ */
126
+ dropById(noticeId) {
127
+ let dropped = this.deps.queue.dropById(noticeId);
128
+ for (const [receiptId, notices] of [...this.pendingSteered]) {
129
+ const kept = notices.filter((notice) => notice.id !== noticeId);
130
+ if (kept.length === notices.length)
131
+ continue;
132
+ dropped = true;
133
+ if (kept.length === 0)
134
+ this.pendingSteered.delete(receiptId);
135
+ else
136
+ this.pendingSteered.set(receiptId, kept);
137
+ }
138
+ return dropped;
139
+ }
140
+ /** Forget everything held in the ledger (session reset). Does not touch the queue. */
141
+ reset() {
65
142
  this.pendingSteered.clear();
66
- for (const notice of stranded)
67
- this.deps.queue.push(notice);
68
143
  }
69
144
  /** How many notices are waiting. Used by the tests and the diagnostics path. */
70
145
  pending() {
@@ -74,9 +149,17 @@ export class TeamNoticeRelay {
74
149
  const notices = this.deps.queue.drain();
75
150
  if (notices.length === 0)
76
151
  return false;
77
- for (const notice of notices)
78
- this.pendingSteered.set(notice.id, notice);
79
- this.deps.steer(renderTeamNotices(notices));
152
+ let receiptId;
153
+ try {
154
+ receiptId = this.deps.steer(renderTeamNotices(notices));
155
+ }
156
+ catch {
157
+ // Nothing was delivered: put them back so the next channel can try.
158
+ for (const notice of notices)
159
+ this.deps.queue.push(notice);
160
+ return false;
161
+ }
162
+ this.pendingSteered.set(receiptId, notices);
80
163
  return true;
81
164
  }
82
165
  }