@aragon-agent/cli 0.6.63 → 0.6.64

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 (64) hide show
  1. package/CHANGELOG.md +70 -2
  2. package/README.md +44 -20
  3. package/dist/agent/controller.d.ts +66 -14
  4. package/dist/agent/controller.js +291 -81
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +44 -3
  7. package/dist/agent/team-notices.d.ts +57 -7
  8. package/dist/agent/team-notices.js +93 -10
  9. package/dist/app/App.js +199 -77
  10. package/dist/cli.js +4 -1
  11. package/dist/config/cli-commands.d.ts +1 -1
  12. package/dist/config/cli-commands.js +11 -0
  13. package/dist/exec/index.js +2 -0
  14. package/dist/exec/runner.js +10 -1
  15. package/dist/gene/commit-prepare.js +27 -1
  16. package/dist/gene/curator/curator.d.ts +15 -0
  17. package/dist/gene/curator/curator.js +26 -2
  18. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  19. package/dist/gene/curator/scripted-lane.js +101 -0
  20. package/dist/gene/curator/task-context.d.ts +21 -0
  21. package/dist/gene/curator/task-context.js +33 -0
  22. package/dist/gene/curator/task-runner.d.ts +10 -1
  23. package/dist/gene/curator/task-runner.js +39 -4
  24. package/dist/gene/curator/tool-support.js +11 -4
  25. package/dist/gene/curator/toolkit.d.ts +13 -0
  26. package/dist/gene/curator/toolkit.js +23 -1
  27. package/dist/gene/curator/tools-verify.js +2 -2
  28. package/dist/gene/curator/tools-write.js +6 -1
  29. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  30. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  31. package/dist/gene/curator/validate/knowledge.js +74 -11
  32. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  33. package/dist/gene/curator/validate/prompts.js +2 -2
  34. package/dist/gene/learn/draft-guard.d.ts +17 -0
  35. package/dist/gene/learn/draft-guard.js +113 -0
  36. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  37. package/dist/gene/learn/learn-prompt.js +27 -2
  38. package/dist/gene/learn/learner.js +20 -2
  39. package/dist/gene/queue.d.ts +16 -0
  40. package/dist/gene/queue.js +44 -1
  41. package/dist/governance/store/run-store.d.ts +20 -0
  42. package/dist/governance/store/run-store.js +54 -8
  43. package/dist/host/index.d.ts +1 -0
  44. package/dist/host/index.js +1 -0
  45. package/dist/host/interaction.d.ts +8 -17
  46. package/dist/host/interaction.js +50 -72
  47. package/dist/host/team-wake-driver.d.ts +90 -0
  48. package/dist/host/team-wake-driver.js +114 -0
  49. package/dist/logging/install.d.ts +32 -1
  50. package/dist/logging/install.js +15 -0
  51. package/dist/team/console-tools.d.ts +12 -0
  52. package/dist/team/console-tools.js +20 -3
  53. package/dist/team/console-view.js +11 -1
  54. package/dist/team/notices.d.ts +81 -4
  55. package/dist/team/notices.js +187 -22
  56. package/dist/team/prompt.js +1 -1
  57. package/dist/team/runtime.d.ts +67 -24
  58. package/dist/team/runtime.js +250 -31
  59. package/dist/team/stall-watch.d.ts +54 -0
  60. package/dist/team/stall-watch.js +119 -0
  61. package/dist/team/task-tool.js +2 -2
  62. package/dist/team/wake.d.ts +176 -0
  63. package/dist/team/wake.js +444 -0
  64. package/package.json +81 -81
@@ -0,0 +1,176 @@
1
+ /**
2
+ * TeamWakeGovernor - "the lead is owed a look at the team; is now the moment?"
3
+ * (team-lead-wake-signals section 4.3).
4
+ *
5
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
6
+ *
7
+ * LEVEL-TRIGGERED, NOT EDGE-TRIGGERED. The bug this replaces judged "does the lead
8
+ * get a turn about the dispatch?" exactly once, on the lead's own `agent_end`; a
9
+ * dispatch that ended while the lead was idle never produced one, so the judgement
10
+ * never ran. Here the debt is a STATE - there is an attention notice no receipt has
11
+ * proved delivered - and `pump()` re-evaluates it at every moment it could become
12
+ * collectable: a signal arrives (T1), the lead goes idle (T2), a retry beat (T3), the
13
+ * host answers (T4). Nothing here knows how a turn is started; that is the host's
14
+ * business (`host/team-wake-driver.ts`), and nothing here knows what the lead should
15
+ * do once it is awake - that is the lead's.
16
+ *
17
+ * BOUNDED AND NEVER SILENT (I-WK7). A settle wake always goes out, but every notice
18
+ * gets at most `wakeMaxAttempts` tries and then a visible give-up; a non-terminal wake
19
+ * is rate-limited per dispatch in `planTeamWake`. A host that stops answering is a
20
+ * failed try after `graceMs + wakeHostSilentMs`, not a hang.
21
+ *
22
+ * ONE LISTENER, AND ASLEEP WITHOUT IT. `exec` / `-p` mount no driver; with nobody to
23
+ * ask, this object builds no timer and does no work.
24
+ *
25
+ * Pure orchestration: every clock, timer and log is injected, so the state machine is
26
+ * tested with a hand-driven clock.
27
+ */
28
+ import type { InvocationCardInput } from '@aragon-agent/tui/model/agent/invocation-card';
29
+ import type { TeamSignalKind } from '@aragon-agent/tui/model/team/types';
30
+ import { type AttentionFact, type WakeMode } from '@aragon-agent/tui/model/team/wake-plan';
31
+ /** What the governor asks a host to do. `announce` needs no answer; `wake` does. */
32
+ export interface TeamWakeRequest {
33
+ /** `w${n}`. */
34
+ id: string;
35
+ dispatchId: string;
36
+ action: 'wake' | 'announce';
37
+ kinds: TeamSignalKind[];
38
+ announce: {
39
+ level: 'info' | 'warn';
40
+ text: string;
41
+ };
42
+ /** Countdown the user may cancel in; meaningful when `action === 'wake'`. */
43
+ graceMs: number;
44
+ }
45
+ /**
46
+ * The host's answer to a `wake` request.
47
+ *
48
+ * - `started` it submitted the turn.
49
+ * - `busy` it could not start one now (a continuation holds the timer, the lead is
50
+ * busy, the submit was refused): retry later, count nothing.
51
+ * - `obsolete` nothing is owed any more (the user's own turn took the notices).
52
+ * - `cancelled` the user typed or pressed Esc during the countdown.
53
+ * - `rejected` the engine refused after the host submitted. In practice produced only
54
+ * by the silence watchdog: the synchronous `submit()` cannot express it.
55
+ */
56
+ export type TeamWakeAck = 'started' | 'busy' | 'obsolete' | 'cancelled' | 'rejected';
57
+ /** The fire-time re-check, with the text to submit when it passes. */
58
+ export type TeamWakeBegin = {
59
+ ok: true;
60
+ text: string;
61
+ invocation: InvocationCardInput;
62
+ } | {
63
+ ok: false;
64
+ why: 'obsolete' | 'lead-busy' | 'user-pending' | 'disposed';
65
+ };
66
+ export interface TeamWakeGovernorDeps {
67
+ /** Every attention fact the lead has not been PROVEN to have, parked ones included. */
68
+ owed(): AttentionFact[];
69
+ /** Give a notice that was steered but never receipted back to the queue (idle only). */
70
+ reclaimStranded(): void;
71
+ config(): {
72
+ autoResume: WakeMode;
73
+ settleGraceMs: number;
74
+ };
75
+ /**
76
+ * `running` is `isRunning() || promptInFlight`: it must cover the window between
77
+ * `prompt()` being entered and the engine's `agent_start` (the gene planning await),
78
+ * where `isRunning()` is still false but a turn is certainly starting.
79
+ */
80
+ leadFacts(): {
81
+ running: boolean;
82
+ compacting: boolean;
83
+ userPending: boolean;
84
+ };
85
+ now(): number;
86
+ /** Must `unref` the timer. Returns its canceller. */
87
+ setTimer(fn: () => void, ms: number): () => void;
88
+ setImmediate(fn: () => void): void;
89
+ log(level: 'info' | 'warn', event: string, fields: Record<string, unknown>): void;
90
+ /** The loud give-up line (`controller.notifyHostFn`). */
91
+ notifyHost(level: 'warn', text: string): void;
92
+ }
93
+ type WakeListener = (request: TeamWakeRequest) => void;
94
+ export declare class TeamWakeGovernor {
95
+ private readonly deps;
96
+ private listener;
97
+ private disposed;
98
+ private sequence;
99
+ private readonly attempts;
100
+ private readonly announced;
101
+ private readonly gaveUp;
102
+ /**
103
+ * Notices the user declined to be woken for (cancelled a countdown, or interrupted
104
+ * the turn). BY ID, never a flag (I-WK16): a global "parked" would also silence the
105
+ * `settled` that arrives an hour later, which is the one signal that must always
106
+ * reach an idle lead. They stay queued and travel with the next turn; a notice that
107
+ * is delivered leaves `owed()` and is forgotten here.
108
+ */
109
+ private readonly parkedIds;
110
+ private nonTerminalWakes;
111
+ private outstanding;
112
+ private cancelRetry;
113
+ private busyStreak;
114
+ private lastDeferWhy;
115
+ private pokeQueued;
116
+ constructor(deps: TeamWakeGovernorDeps);
117
+ /**
118
+ * ONE host at a time. A second subscriber replaces the first (and the first's
119
+ * unsubscribe becomes a no-op): two drivers would each answer the same request by
120
+ * submitting a turn.
121
+ */
122
+ subscribe(listener: WakeListener): () => void;
123
+ /** T1: a signal arrived. Coalesced into ONE `pump()` on the microtask queue (RV-P2-2). */
124
+ poke(): void;
125
+ /** A detached dispatch began: its non-terminal wake budget starts from zero. */
126
+ onDispatchStart(): void;
127
+ /**
128
+ * T2: the lead is idle again. Deferred one `setImmediate`, so the host finishes its
129
+ * own `agent_end` bookkeeping first - the terminal app resets its interaction phase
130
+ * and arms the todo / nudge follow-through in that same dispatch, and the verdict
131
+ * below must be made AFTER those, never before. (Core already flips `isRunning()`
132
+ * to false before it emits `agent_end`, so this is about the host, not the engine.)
133
+ *
134
+ * `aborted`: the user stopped that turn. They are present and have just made an
135
+ * explicit choice; starting a fresh turn three seconds later would override it
136
+ * (I-WK8). So what is owed right now is parked and announced once, and what arrives
137
+ * LATER still wakes the lead.
138
+ */
139
+ onLeadIdle(info: {
140
+ aborted: boolean;
141
+ }): void;
142
+ /** The fire-time check the host runs just before it submits the turn (I-WK10). */
143
+ begin(requestId: string): TeamWakeBegin;
144
+ /** T4: the host's answer. Stale answers (an unknown or already-settled id) are ignored. */
145
+ ack(requestId: string, result: TeamWakeAck): void;
146
+ /** Forget everything (`/clear`, a session switch). The subscription survives. */
147
+ reset(): void;
148
+ dispose(): void;
149
+ /** The ids currently parked. Read by tests and diagnostics. */
150
+ parked(): string[];
151
+ /** Synchronous, idempotent and never throws: it runs from timers and event handlers. */
152
+ pump(): void;
153
+ private evaluate;
154
+ private emitAnnounce;
155
+ private emitWake;
156
+ private request;
157
+ /** Hand a request to the host. `false` when there is no host or it threw. */
158
+ private deliver;
159
+ private onStarted;
160
+ private onHostSilent;
161
+ private countAttempt;
162
+ /** Once per notice: the visible end of a wake that could not be made to work. */
163
+ private reportGivenUp;
164
+ /** Drop per-notice memory for notices that are no longer owed (they were delivered). */
165
+ private forgetDelivered;
166
+ private parkOwedAfterInterrupt;
167
+ private nextId;
168
+ /** 5 s, 10 s, 20 s, then 30 s: a host that keeps saying `busy` is not polled hot. */
169
+ private backoffMs;
170
+ private scheduleRetry;
171
+ private cancelRetryTimer;
172
+ private cancelOutstanding;
173
+ /** One log line per CHANGE of reason, not per beat: a long-busy host would flood it. */
174
+ private noteDeferred;
175
+ }
176
+ export {};
@@ -0,0 +1,444 @@
1
+ /**
2
+ * TeamWakeGovernor - "the lead is owed a look at the team; is now the moment?"
3
+ * (team-lead-wake-signals section 4.3).
4
+ *
5
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
6
+ *
7
+ * LEVEL-TRIGGERED, NOT EDGE-TRIGGERED. The bug this replaces judged "does the lead
8
+ * get a turn about the dispatch?" exactly once, on the lead's own `agent_end`; a
9
+ * dispatch that ended while the lead was idle never produced one, so the judgement
10
+ * never ran. Here the debt is a STATE - there is an attention notice no receipt has
11
+ * proved delivered - and `pump()` re-evaluates it at every moment it could become
12
+ * collectable: a signal arrives (T1), the lead goes idle (T2), a retry beat (T3), the
13
+ * host answers (T4). Nothing here knows how a turn is started; that is the host's
14
+ * business (`host/team-wake-driver.ts`), and nothing here knows what the lead should
15
+ * do once it is awake - that is the lead's.
16
+ *
17
+ * BOUNDED AND NEVER SILENT (I-WK7). A settle wake always goes out, but every notice
18
+ * gets at most `wakeMaxAttempts` tries and then a visible give-up; a non-terminal wake
19
+ * is rate-limited per dispatch in `planTeamWake`. A host that stops answering is a
20
+ * failed try after `graceMs + wakeHostSilentMs`, not a hang.
21
+ *
22
+ * ONE LISTENER, AND ASLEEP WITHOUT IT. `exec` / `-p` mount no driver; with nobody to
23
+ * ask, this object builds no timer and does no work.
24
+ *
25
+ * Pure orchestration: every clock, timer and log is injected, so the state machine is
26
+ * tested with a hand-driven clock.
27
+ */
28
+ import { TEAM_LIMITS } from '@aragon-agent/tui/model/team/limits';
29
+ import { describeHeadline, describeSignalCard, planTeamWake, renderTeamSignal, TEAM_SIGNAL_NEXT_MESSAGE, } from '@aragon-agent/tui/model/team/wake-plan';
30
+ export class TeamWakeGovernor {
31
+ deps;
32
+ listener = null;
33
+ disposed = false;
34
+ sequence = 0;
35
+ attempts = new Map();
36
+ announced = new Set();
37
+ gaveUp = new Set();
38
+ /**
39
+ * Notices the user declined to be woken for (cancelled a countdown, or interrupted
40
+ * the turn). BY ID, never a flag (I-WK16): a global "parked" would also silence the
41
+ * `settled` that arrives an hour later, which is the one signal that must always
42
+ * reach an idle lead. They stay queued and travel with the next turn; a notice that
43
+ * is delivered leaves `owed()` and is forgotten here.
44
+ */
45
+ parkedIds = new Set();
46
+ nonTerminalWakes = { spent: 0, lastAt: null };
47
+ outstanding = null;
48
+ cancelRetry = null;
49
+ busyStreak = 0;
50
+ lastDeferWhy = null;
51
+ pokeQueued = false;
52
+ constructor(deps) {
53
+ this.deps = deps;
54
+ }
55
+ /**
56
+ * ONE host at a time. A second subscriber replaces the first (and the first's
57
+ * unsubscribe becomes a no-op): two drivers would each answer the same request by
58
+ * submitting a turn.
59
+ */
60
+ subscribe(listener) {
61
+ if (this.listener !== null) {
62
+ this.deps.log('warn', 'team_wake_subscriber_replaced', {});
63
+ }
64
+ this.listener = listener;
65
+ this.poke();
66
+ return () => {
67
+ if (this.listener !== listener)
68
+ return;
69
+ this.listener = null;
70
+ this.cancelOutstanding();
71
+ this.cancelRetryTimer();
72
+ };
73
+ }
74
+ /** T1: a signal arrived. Coalesced into ONE `pump()` on the microtask queue (RV-P2-2). */
75
+ poke() {
76
+ if (this.disposed || this.listener === null || this.pokeQueued)
77
+ return;
78
+ this.pokeQueued = true;
79
+ queueMicrotask(() => {
80
+ this.pokeQueued = false;
81
+ this.pump();
82
+ });
83
+ }
84
+ /** A detached dispatch began: its non-terminal wake budget starts from zero. */
85
+ onDispatchStart() {
86
+ this.nonTerminalWakes = { spent: 0, lastAt: null };
87
+ }
88
+ /**
89
+ * T2: the lead is idle again. Deferred one `setImmediate`, so the host finishes its
90
+ * own `agent_end` bookkeeping first - the terminal app resets its interaction phase
91
+ * and arms the todo / nudge follow-through in that same dispatch, and the verdict
92
+ * below must be made AFTER those, never before. (Core already flips `isRunning()`
93
+ * to false before it emits `agent_end`, so this is about the host, not the engine.)
94
+ *
95
+ * `aborted`: the user stopped that turn. They are present and have just made an
96
+ * explicit choice; starting a fresh turn three seconds later would override it
97
+ * (I-WK8). So what is owed right now is parked and announced once, and what arrives
98
+ * LATER still wakes the lead.
99
+ */
100
+ onLeadIdle(info) {
101
+ if (this.disposed)
102
+ return;
103
+ this.deps.setImmediate(() => {
104
+ if (this.disposed)
105
+ return;
106
+ if (info.aborted)
107
+ this.parkOwedAfterInterrupt();
108
+ this.pump();
109
+ });
110
+ }
111
+ /** The fire-time check the host runs just before it submits the turn (I-WK10). */
112
+ begin(requestId) {
113
+ if (this.disposed)
114
+ return { ok: false, why: 'disposed' };
115
+ const outstanding = this.outstanding;
116
+ if (outstanding === null || outstanding.id !== requestId)
117
+ return { ok: false, why: 'obsolete' };
118
+ const lead = this.deps.leadFacts();
119
+ if (lead.running || lead.compacting)
120
+ return { ok: false, why: 'lead-busy' };
121
+ this.deps.reclaimStranded();
122
+ const owed = this.deps.owed();
123
+ if (owed.length === 0)
124
+ return { ok: false, why: 'obsolete' };
125
+ if (lead.userPending)
126
+ return { ok: false, why: 'user-pending' };
127
+ const card = describeSignalCard(owed);
128
+ return {
129
+ ok: true,
130
+ // EVERYTHING owed, parked included: they travel with this turn anyway
131
+ // (`flushForTurn`), so the facts line must not leave them out.
132
+ text: renderTeamSignal(owed),
133
+ invocation: {
134
+ variant: 'team',
135
+ name: '',
136
+ commandLine: card.commandLine,
137
+ facts: card.facts,
138
+ note: 'Automatic - not typed by you.',
139
+ },
140
+ };
141
+ }
142
+ /** T4: the host's answer. Stale answers (an unknown or already-settled id) are ignored. */
143
+ ack(requestId, result) {
144
+ const outstanding = this.outstanding;
145
+ if (outstanding === null || outstanding.id !== requestId)
146
+ return;
147
+ outstanding.cancelWatchdog();
148
+ this.outstanding = null;
149
+ this.deps.log('info', 'team_wake_ack', { requestId, result });
150
+ switch (result) {
151
+ case 'started':
152
+ this.onStarted(outstanding);
153
+ return;
154
+ case 'busy':
155
+ // The delay is read BEFORE the streak grows, so the first `busy` waits the base
156
+ // 5 s and the ladder runs 5 -> 10 -> 20 -> 30 s.
157
+ this.scheduleRetry(this.backoffMs());
158
+ this.busyStreak += 1;
159
+ return;
160
+ case 'obsolete':
161
+ return;
162
+ case 'cancelled':
163
+ for (const id of outstanding.ids)
164
+ this.parkedIds.add(id);
165
+ this.poke();
166
+ return;
167
+ case 'rejected':
168
+ this.countAttempt(outstanding.ids);
169
+ this.scheduleRetry(this.backoffMs());
170
+ return;
171
+ default:
172
+ return assertNever(result);
173
+ }
174
+ }
175
+ /** Forget everything (`/clear`, a session switch). The subscription survives. */
176
+ reset() {
177
+ this.cancelOutstanding();
178
+ this.cancelRetryTimer();
179
+ this.attempts.clear();
180
+ this.announced.clear();
181
+ this.gaveUp.clear();
182
+ this.parkedIds.clear();
183
+ this.nonTerminalWakes = { spent: 0, lastAt: null };
184
+ this.busyStreak = 0;
185
+ this.lastDeferWhy = null;
186
+ }
187
+ dispose() {
188
+ this.reset();
189
+ this.disposed = true;
190
+ this.listener = null;
191
+ }
192
+ /** The ids currently parked. Read by tests and diagnostics. */
193
+ parked() {
194
+ return [...this.parkedIds];
195
+ }
196
+ // -------------------------------------------------------------------------
197
+ // The one evaluation
198
+ // -------------------------------------------------------------------------
199
+ /** Synchronous, idempotent and never throws: it runs from timers and event handlers. */
200
+ pump() {
201
+ if (this.disposed || this.listener === null || this.outstanding !== null)
202
+ return;
203
+ try {
204
+ this.evaluate();
205
+ }
206
+ catch (error) {
207
+ this.deps.log('warn', 'team_wake_pump_failed', {
208
+ reason: error instanceof Error ? error.name : 'unknown',
209
+ });
210
+ }
211
+ }
212
+ evaluate() {
213
+ const lead = this.deps.leadFacts();
214
+ // Idle means nothing is in flight, so anything still in the ledger is stranded
215
+ // (its steer was swallowed). Take it back BEFORE reading what is owed.
216
+ if (!lead.running && !lead.compacting)
217
+ this.deps.reclaimStranded();
218
+ const owed = this.deps.owed();
219
+ this.forgetDelivered(owed);
220
+ const actionable = owed.filter((fact) => !this.parkedIds.has(fact.id));
221
+ this.reportGivenUp(actionable);
222
+ const config = this.deps.config();
223
+ const plan = planTeamWake({
224
+ mode: config.autoResume,
225
+ owed: actionable,
226
+ attempts: this.attempts,
227
+ announced: this.announced,
228
+ lead,
229
+ continuationArmed: false,
230
+ nonTerminalWakes: this.nonTerminalWakes,
231
+ now: this.deps.now(),
232
+ graceMs: config.settleGraceMs,
233
+ limits: {
234
+ maxAttempts: TEAM_LIMITS.wakeMaxAttempts,
235
+ wakesPerDispatch: TEAM_LIMITS.wakesPerDispatch,
236
+ minGapMs: TEAM_LIMITS.wakeMinGapMs,
237
+ },
238
+ });
239
+ switch (plan.kind) {
240
+ case 'none':
241
+ this.lastDeferWhy = null;
242
+ this.cancelRetryTimer();
243
+ return;
244
+ case 'defer':
245
+ this.noteDeferred(plan.why, plan.retryInMs);
246
+ this.scheduleRetry(plan.retryInMs ?? this.backoffMs());
247
+ return;
248
+ case 'announce':
249
+ this.emitAnnounce(plan.ids, plan.level, plan.text, owed);
250
+ return;
251
+ case 'wake':
252
+ this.emitWake(plan.ids, plan.kinds, plan.announce, plan.graceMs, owed);
253
+ return;
254
+ default:
255
+ return assertNever(plan);
256
+ }
257
+ }
258
+ emitAnnounce(ids, level, text, owed) {
259
+ for (const id of ids)
260
+ this.announced.add(id);
261
+ this.cancelRetryTimer();
262
+ const request = this.request('announce', ids, owed, { level, text }, 0);
263
+ this.deliver(request);
264
+ }
265
+ emitWake(ids, kinds, announce, graceMs, owed) {
266
+ this.cancelRetryTimer();
267
+ this.lastDeferWhy = null;
268
+ const request = this.request('wake', ids, owed, announce, graceMs);
269
+ const watchdogMs = graceMs + TEAM_LIMITS.wakeHostSilentMs;
270
+ const cancelWatchdog = this.deps.setTimer(() => this.onHostSilent(request.id, watchdogMs), watchdogMs);
271
+ this.outstanding = { id: request.id, ids, kinds, cancelWatchdog };
272
+ if (!this.deliver(request))
273
+ this.ack(request.id, 'rejected');
274
+ }
275
+ request(action, ids, owed, announce, graceMs) {
276
+ const facts = owed.filter((fact) => ids.includes(fact.id));
277
+ const kinds = [];
278
+ for (const fact of facts)
279
+ if (!kinds.includes(fact.kind))
280
+ kinds.push(fact.kind);
281
+ this.sequence += 1;
282
+ const request = {
283
+ id: `w${this.sequence}`,
284
+ dispatchId: facts[0]?.dispatchId ?? '',
285
+ action,
286
+ kinds,
287
+ announce,
288
+ graceMs,
289
+ };
290
+ const attempt = Math.max(0, ...ids.map((id) => this.attempts.get(id) ?? 0));
291
+ this.deps.log('info', 'team_wake_requested', {
292
+ requestId: request.id,
293
+ dispatchId: request.dispatchId,
294
+ kinds,
295
+ attempt,
296
+ action,
297
+ });
298
+ return request;
299
+ }
300
+ /** Hand a request to the host. `false` when there is no host or it threw. */
301
+ deliver(request) {
302
+ const listener = this.listener;
303
+ if (listener === null)
304
+ return false;
305
+ try {
306
+ listener(request);
307
+ return true;
308
+ }
309
+ catch (error) {
310
+ this.deps.log('warn', 'team_wake_listener_failed', {
311
+ requestId: request.id,
312
+ reason: error instanceof Error ? error.name : 'unknown',
313
+ });
314
+ return false;
315
+ }
316
+ }
317
+ // -------------------------------------------------------------------------
318
+ // Acknowledgements and bookkeeping
319
+ // -------------------------------------------------------------------------
320
+ onStarted(outstanding) {
321
+ this.busyStreak = 0;
322
+ this.countAttempt(outstanding.ids);
323
+ // A wake that carried the settle report is exempt from the per-dispatch budget (it
324
+ // always goes out), so only the live-signal wakes spend it.
325
+ if (!outstanding.kinds.includes('settled')) {
326
+ this.nonTerminalWakes = {
327
+ spent: this.nonTerminalWakes.spent + 1,
328
+ lastAt: this.deps.now(),
329
+ };
330
+ }
331
+ // Nothing more to do here: the turn's own `flushForTurn` carries the notices, the
332
+ // receipt shrinks `owed()`, and `onLeadIdle` re-evaluates whatever is left.
333
+ }
334
+ onHostSilent(requestId, afterMs) {
335
+ if (this.outstanding?.id !== requestId)
336
+ return;
337
+ this.deps.log('warn', 'team_wake_host_silent', { requestId, afterMs });
338
+ this.ack(requestId, 'rejected');
339
+ }
340
+ countAttempt(ids) {
341
+ for (const id of ids)
342
+ this.attempts.set(id, (this.attempts.get(id) ?? 0) + 1);
343
+ }
344
+ /** Once per notice: the visible end of a wake that could not be made to work. */
345
+ reportGivenUp(actionable) {
346
+ const fresh = actionable.filter((fact) => (this.attempts.get(fact.id) ?? 0) >= TEAM_LIMITS.wakeMaxAttempts && !this.gaveUp.has(fact.id));
347
+ if (fresh.length === 0)
348
+ return;
349
+ const dispatches = new Set();
350
+ for (const fact of fresh) {
351
+ this.gaveUp.add(fact.id);
352
+ dispatches.add(fact.dispatchId);
353
+ this.deps.log('warn', 'team_wake_gave_up', {
354
+ noticeId: fact.id,
355
+ attempts: this.attempts.get(fact.id) ?? 0,
356
+ });
357
+ }
358
+ for (const dispatchId of dispatches) {
359
+ this.deps.notifyHost('warn', `team ${dispatchId}: could not wake the lead. Send any message and the report goes with it.`);
360
+ }
361
+ }
362
+ /** Drop per-notice memory for notices that are no longer owed (they were delivered). */
363
+ forgetDelivered(owed) {
364
+ const live = new Set(owed.map((fact) => fact.id));
365
+ for (const set of [this.announced, this.gaveUp, this.parkedIds]) {
366
+ for (const id of [...set])
367
+ if (!live.has(id))
368
+ set.delete(id);
369
+ }
370
+ for (const id of [...this.attempts.keys()])
371
+ if (!live.has(id))
372
+ this.attempts.delete(id);
373
+ }
374
+ parkOwedAfterInterrupt() {
375
+ const owed = this.deps.owed();
376
+ if (owed.length === 0)
377
+ return;
378
+ for (const fact of owed)
379
+ this.parkedIds.add(fact.id);
380
+ const mode = this.deps.config().autoResume;
381
+ const lead = this.deps.leadFacts();
382
+ // Only while the lead is really idle: a user who submitted a message to a running
383
+ // turn aborts it too, and that new turn is about to carry these notices - saying
384
+ // "the report goes with your next message" would then be wrong.
385
+ if (mode === 'off' || lead.running || this.listener === null)
386
+ return;
387
+ const fresh = owed.filter((fact) => !this.announced.has(fact.id));
388
+ if (fresh.length === 0)
389
+ return;
390
+ for (const fact of fresh)
391
+ this.announced.add(fact.id);
392
+ const headline = describeHeadline(fresh);
393
+ this.deliver({
394
+ id: this.nextId(),
395
+ dispatchId: fresh[0].dispatchId,
396
+ action: 'announce',
397
+ kinds: fresh.map((fact) => fact.kind),
398
+ announce: { level: headline.level, text: `${headline.text} ${TEAM_SIGNAL_NEXT_MESSAGE}` },
399
+ graceMs: 0,
400
+ });
401
+ }
402
+ nextId() {
403
+ this.sequence += 1;
404
+ return `w${this.sequence}`;
405
+ }
406
+ // -------------------------------------------------------------------------
407
+ // Retry beat (T3)
408
+ // -------------------------------------------------------------------------
409
+ /** 5 s, 10 s, 20 s, then 30 s: a host that keeps saying `busy` is not polled hot. */
410
+ backoffMs() {
411
+ const grown = TEAM_LIMITS.wakeRetryMs * 2 ** Math.min(this.busyStreak, 4);
412
+ return Math.min(TEAM_LIMITS.wakeRetryMaxMs, grown);
413
+ }
414
+ scheduleRetry(ms) {
415
+ if (this.disposed || this.listener === null)
416
+ return;
417
+ this.cancelRetryTimer();
418
+ this.cancelRetry = this.deps.setTimer(() => {
419
+ this.cancelRetry = null;
420
+ this.pump();
421
+ }, Math.max(1, ms));
422
+ }
423
+ cancelRetryTimer() {
424
+ this.cancelRetry?.();
425
+ this.cancelRetry = null;
426
+ }
427
+ cancelOutstanding() {
428
+ this.outstanding?.cancelWatchdog();
429
+ this.outstanding = null;
430
+ }
431
+ /** One log line per CHANGE of reason, not per beat: a long-busy host would flood it. */
432
+ noteDeferred(why, retryInMs) {
433
+ if (this.lastDeferWhy === why)
434
+ return;
435
+ this.lastDeferWhy = why;
436
+ this.deps.log('info', 'team_wake_deferred', {
437
+ why,
438
+ retryInMs: retryInMs ?? this.backoffMs(),
439
+ });
440
+ }
441
+ }
442
+ function assertNever(value) {
443
+ throw new Error(`unhandled value: ${String(value)}`);
444
+ }