@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
@@ -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
+ }
@@ -0,0 +1,114 @@
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 { TEAM_SIGNAL_NEXT_MESSAGE } from '@aragon-agent/tui/model/team/wake-plan';
36
+ export class TeamWakeDriver {
37
+ ports;
38
+ /** The countdown this driver is holding, if any. The only thing `cancel()` acts on. */
39
+ outstandingId = null;
40
+ constructor(ports) {
41
+ this.ports = ports;
42
+ }
43
+ /** Subscribe to the controller. Returns the detach function. */
44
+ attach() {
45
+ // A controller double or an older host has no team surface: nothing to subscribe to,
46
+ // and nothing that could ever ask this driver for a wake.
47
+ if (typeof this.ports.controller.subscribeTeamWake !== 'function')
48
+ return () => { };
49
+ const unsubscribe = this.ports.controller.subscribeTeamWake((request) => this.onRequest(request));
50
+ return () => {
51
+ unsubscribe();
52
+ if (this.outstandingId !== null) {
53
+ this.outstandingId = null;
54
+ this.ports.timer.clear();
55
+ }
56
+ };
57
+ }
58
+ /** Whether a countdown is running right now. Hosts use it to avoid a second toast. */
59
+ isCounting() {
60
+ return this.outstandingId !== null;
61
+ }
62
+ /**
63
+ * The user typed or pressed Esc: stop the countdown. Called by the host from its own
64
+ * "cancel any pending continuation" point. A no-op unless this driver holds a request.
65
+ */
66
+ cancel() {
67
+ const id = this.outstandingId;
68
+ if (id === null)
69
+ return;
70
+ this.outstandingId = null;
71
+ this.ports.timer.clear();
72
+ this.ports.controller.ackTeamWake(id, 'cancelled');
73
+ (this.ports.toast ?? this.ports.announce)('info', `Wake cancelled. ${TEAM_SIGNAL_NEXT_MESSAGE}`);
74
+ }
75
+ onRequest(request) {
76
+ if (request.action === 'announce') {
77
+ this.ports.announce(request.announce.level, request.announce.text);
78
+ return;
79
+ }
80
+ // Another continuation holds the slot, or a turn is in flight: say "later", do not
81
+ // drop it and do not take the slot from the one that has it.
82
+ if (this.ports.timer.armed() || this.ports.leadBusy()) {
83
+ this.ports.controller.ackTeamWake(request.id, 'busy');
84
+ return;
85
+ }
86
+ const seconds = Math.max(1, Math.ceil(request.graceMs / 1000));
87
+ const hint = this.ports.cancelHint?.() ?? '';
88
+ const suffix = hint === '' ? '' : ` (${hint})`;
89
+ this.ports.announce(request.announce.level, `${request.announce.text} Waking the lead in ${seconds}s${suffix}`);
90
+ this.outstandingId = request.id;
91
+ this.ports.timer.set(() => this.fire(), request.graceMs);
92
+ }
93
+ /** The countdown ended. One synchronous block (I-WK10). */
94
+ fire() {
95
+ const id = this.outstandingId;
96
+ if (id === null)
97
+ return;
98
+ // BEFORE the submit: the host's submit begins by cancelling "any pending
99
+ // continuation", and this must find nothing left to cancel.
100
+ this.outstandingId = null;
101
+ const { controller } = this.ports;
102
+ const begun = controller.confirmTeamWake(id);
103
+ if (!begun.ok) {
104
+ controller.ackTeamWake(id, begun.why === 'obsolete' ? 'obsolete' : 'busy');
105
+ return;
106
+ }
107
+ if (this.ports.leadBusy()) {
108
+ controller.ackTeamWake(id, 'busy');
109
+ return;
110
+ }
111
+ const accepted = this.ports.submit(begun.text, begun.invocation);
112
+ controller.ackTeamWake(id, accepted ? 'started' : 'busy');
113
+ }
114
+ }
@@ -160,6 +160,20 @@ export type AgentLogEvent = {
160
160
  errorType?: string;
161
161
  retryable?: boolean;
162
162
  reason?: string;
163
+ /**
164
+ * Core's `AgentStallInfo`, present only on an `idle_watchdog` end. Spelled out
165
+ * rather than `Record<string, unknown>`: an interface has no index signature,
166
+ * so the loose type would make `AgentController` incompatible with this source.
167
+ */
168
+ stall?: {
169
+ phase?: string;
170
+ lastEvent?: string;
171
+ msSinceLastEvent?: number;
172
+ wallMsSinceLastEvent?: number;
173
+ eventsSeen?: number;
174
+ idleTimeoutMs?: number;
175
+ toolName?: string;
176
+ };
163
177
  } | {
164
178
  type: 'turn_start';
165
179
  } | {
@@ -298,7 +312,7 @@ export declare function attachAgentEvents(logger: Logger, controller: AgentEvent
298
312
  export interface TeamEventSource {
299
313
  subscribeTeam?(listener: (event: TeamLogEvent) => void): () => void;
300
314
  }
301
- /** The seven members of the CLI-local `TeamEvent` union, as this module reads them. */
315
+ /** The nine members of the CLI-local `TeamEvent` union, as this module reads them. */
302
316
  export type TeamLogEvent = {
303
317
  type: 'dispatch_start';
304
318
  dispatchId: string;
@@ -370,9 +384,26 @@ export type TeamLogEvent = {
370
384
  reason?: string;
371
385
  };
372
386
  trigger?: string;
387
+ } | {
388
+ /** A subagent FINALLY failed (team-lead-wake-signals). Logged as label only. */
389
+ type: 'child_failed';
390
+ dispatchId: string;
391
+ run?: {
392
+ label?: string;
393
+ phase?: string;
394
+ };
395
+ } | {
396
+ /** Nobody is doing real work and somebody is blocked (team-lead-wake-signals). */
397
+ type: 'stalled';
398
+ dispatchId: string;
399
+ episode?: number;
400
+ quietMs?: number;
401
+ blockers?: unknown[];
373
402
  } | {
374
403
  type: 'dispatch_end';
375
404
  dispatchId: string;
405
+ /** True for every detached dispatch (team-lead-wake-signals I-WK15). */
406
+ detached?: boolean;
376
407
  outcome?: {
377
408
  startedAt?: number;
378
409
  endedAt?: number;
@@ -447,6 +447,10 @@ export function attachAgentEvents(logger, controller) {
447
447
  ...(event.errorType !== undefined ? { errorType: event.errorType } : {}),
448
448
  ...(event.retryable !== undefined ? { retryable: event.retryable } : {}),
449
449
  ...(event.reason !== undefined ? { reason: event.reason } : {}),
450
+ // WHERE THE WATCHDOG'S SILENCE BEGAN (team-idle-watchdog-dead-run F0): the
451
+ // phase, the last event, and the silence on BOTH clocks, so the next death
452
+ // can be attributed without inferring it from the gap to the previous row.
453
+ ...(event.stall !== undefined ? { stall: event.stall } : {}),
450
454
  });
451
455
  break;
452
456
  }
@@ -516,6 +520,17 @@ export function attachTeamEvents(logger, controller) {
516
520
  });
517
521
  break;
518
522
  }
523
+ case 'child_failed':
524
+ // COUNTS AND NAMES ONLY: the error text is a provider's or a tool's prose, and
525
+ // the controller's `team_signal_raised` line already records the signal itself.
526
+ logger.info('agent', 'team_child_failed', {
527
+ dispatchId: event.dispatchId,
528
+ label: event.run?.label,
529
+ });
530
+ break;
531
+ case 'stalled':
532
+ // Logged by the controller as `team_stall_detected`, next to the notice it queues.
533
+ break;
519
534
  case 'message':
520
535
  logger.debug('agent', 'team_message', {
521
536
  dispatchId: event.dispatchId,
@@ -33,6 +33,18 @@ export interface ConsoleToolDeps {
33
33
  * must never miss: the lead waiting is acceptable, the USER waiting is not.
34
34
  */
35
35
  hasPendingUserInput: () => boolean;
36
+ /**
37
+ * `controller.acknowledgeTeamSettle(dispatchId)`: the report is about to be handed
38
+ * over in a tool result, so the settle notice must not deliver it a second time
39
+ * (team-lead-wake-signals RC-8). Optional so a host without notices stays unchanged.
40
+ */
41
+ acknowledgeSettle?: (dispatchId: string) => void;
42
+ /**
43
+ * `controller.hasPendingTeamAttention()`: the runtime has something to tell the lead
44
+ * (a child failed, the team stalled). `team_collect` stops waiting on it - the notice
45
+ * reaches the lead on its own the moment this tool returns.
46
+ */
47
+ hasPendingTeamAttention?: () => boolean;
36
48
  /** Who is acting. `'lead'` for these tools; `'user'` for `/team` verbs. */
37
49
  by?: TeamControlBy;
38
50
  }
@@ -269,11 +269,13 @@ export function makeTeamCollectTool(deps) {
269
269
  const report = deps.runtime.reportText(startId);
270
270
  if (report === undefined)
271
271
  return textResult(NO_DISPATCH);
272
+ deps.acknowledgeSettle?.(startId);
272
273
  return textResult(`settled: true\n\n${report}`);
273
274
  }
274
275
  const waited = await waitForSettle(deps, startId, seconds * 1000);
275
276
  const report = deps.runtime.reportText(startId);
276
277
  if (waited === 'settled' && report !== undefined) {
278
+ deps.acknowledgeSettle?.(startId);
277
279
  return textResult(`settled: true\n\n${report}`);
278
280
  }
279
281
  const inspection = deps.runtime.inspect();
@@ -282,9 +284,7 @@ export function makeTeamCollectTool(deps) {
282
284
  ? 'the dispatch is no longer live'
283
285
  : `${counts.running} running, ${counts.queued} waiting, ${counts.paused} paused, ` +
284
286
  `${counts.done} done, ${counts.failed} failed`;
285
- const why = waited === 'user_message'
286
- ? 'stopped waiting: the user sent you a message. Answer it first; the report will arrive on its own.'
287
- : `still live after ${seconds}s; ${state}. Do not wait again - answer the user, or use team_status.`;
287
+ const why = describeUnsettled(waited, seconds, state);
288
288
  return textResult(`settled: false\n${why}`);
289
289
  },
290
290
  };
@@ -309,6 +309,13 @@ function waitForSettle(deps, dispatchId, budgetMs) {
309
309
  resolve('settled');
310
310
  return;
311
311
  }
312
+ // A signal for the lead (a child failed, the team stalled) ends the wait: it is
313
+ // steered in the moment this tool returns, and holding the lead here would only
314
+ // delay the one thing it most needs to read (team-lead-wake-signals 4.8).
315
+ if (deps.hasPendingTeamAttention?.() === true) {
316
+ resolve('signal');
317
+ return;
318
+ }
312
319
  if (Date.now() - startedAt >= budgetMs) {
313
320
  resolve('timeout');
314
321
  return;
@@ -319,6 +326,16 @@ function waitForSettle(deps, dispatchId, budgetMs) {
319
326
  tick();
320
327
  });
321
328
  }
329
+ /** The sentence a `settled: false` result gives for why the wait ended. */
330
+ function describeUnsettled(waited, seconds, state) {
331
+ if (waited === 'user_message') {
332
+ return 'stopped waiting: the user sent you a message. Answer it first; the report will arrive on its own.';
333
+ }
334
+ if (waited === 'signal') {
335
+ return 'stopped waiting: a team signal arrived (a subagent failed or the team stalled). It will reach you on its own - read it first.';
336
+ }
337
+ return `still live after ${seconds}s; ${state}. Do not wait again - answer the user, or use team_status.`;
338
+ }
322
339
  /** The seven tools, in the order the prompt block lists them. */
323
340
  export function createConsoleTools(deps) {
324
341
  return [
@@ -95,7 +95,17 @@ export function renderTeamStatus(inspection, options = {}) {
95
95
  (mailDetail.length > 0 ? ` (${mailDetail})` : '') +
96
96
  ` interventions: ${inspection.controls.length}` +
97
97
  (controlDetail.length > 0 ? ` (${controlDetail})` : '');
98
- const parts = [head, ...roster, footer];
98
+ // One line under the header when the watch says nobody is working: the lead and the
99
+ // user can both read "no progress for 3m" without having to infer it from phases.
100
+ const stalled = inspection.stalled === undefined
101
+ ? []
102
+ : [
103
+ `no progress for ${formatElapsed(inspection.stalled.quietMs)}` +
104
+ (inspection.stalled.blockers.length > 0
105
+ ? ` (blocked: ${inspection.stalled.blockers.join(', ')})`
106
+ : ''),
107
+ ];
108
+ const parts = [head, ...stalled, ...roster, footer];
99
109
  if (options.includeSummary === true) {
100
110
  for (const child of rows) {
101
111
  if (child.summary === undefined || child.summary.length === 0)