@aragon-agent/cli 0.6.62 → 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 (93) hide show
  1. package/CHANGELOG.md +70 -2
  2. package/README.md +143 -27
  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 +62 -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/commands/builtins.js +2 -1
  12. package/dist/commands/catalog.js +1 -1
  13. package/dist/compaction/archive.d.ts +27 -1
  14. package/dist/compaction/archive.js +8 -0
  15. package/dist/compaction/budget.d.ts +73 -0
  16. package/dist/compaction/budget.js +89 -0
  17. package/dist/compaction/child.js +6 -1
  18. package/dist/compaction/command.js +147 -1
  19. package/dist/compaction/compactor.d.ts +132 -15
  20. package/dist/compaction/compactor.js +288 -95
  21. package/dist/compaction/context-command.js +21 -0
  22. package/dist/compaction/memory-agent-prompt.d.ts +32 -0
  23. package/dist/compaction/memory-agent-prompt.js +76 -0
  24. package/dist/compaction/memory-agent-tools.d.ts +88 -0
  25. package/dist/compaction/memory-agent-tools.js +338 -0
  26. package/dist/compaction/memory-agent.d.ts +114 -0
  27. package/dist/compaction/memory-agent.js +220 -0
  28. package/dist/compaction/prune.d.ts +129 -0
  29. package/dist/compaction/prune.js +386 -0
  30. package/dist/compaction/retry-plan.d.ts +103 -0
  31. package/dist/compaction/retry-plan.js +136 -0
  32. package/dist/compaction/summarize-ladder.d.ts +149 -0
  33. package/dist/compaction/summarize-ladder.js +273 -0
  34. package/dist/compaction/wiring.d.ts +19 -0
  35. package/dist/compaction/wiring.js +65 -1
  36. package/dist/config/cli-commands.d.ts +2 -2
  37. package/dist/config/cli-commands.js +27 -0
  38. package/dist/config/env.d.ts +3 -1
  39. package/dist/config/env.js +44 -2
  40. package/dist/exec/events.d.ts +30 -0
  41. package/dist/exec/index.js +2 -0
  42. package/dist/exec/runner.js +16 -1
  43. package/dist/gene/commit-prepare.js +27 -1
  44. package/dist/gene/curator/curator.d.ts +15 -0
  45. package/dist/gene/curator/curator.js +26 -2
  46. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  47. package/dist/gene/curator/scripted-lane.js +101 -0
  48. package/dist/gene/curator/task-context.d.ts +21 -0
  49. package/dist/gene/curator/task-context.js +33 -0
  50. package/dist/gene/curator/task-runner.d.ts +10 -1
  51. package/dist/gene/curator/task-runner.js +39 -4
  52. package/dist/gene/curator/tool-support.js +11 -4
  53. package/dist/gene/curator/toolkit.d.ts +13 -0
  54. package/dist/gene/curator/toolkit.js +23 -1
  55. package/dist/gene/curator/tools-verify.js +2 -2
  56. package/dist/gene/curator/tools-write.js +6 -1
  57. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  58. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  59. package/dist/gene/curator/validate/knowledge.js +74 -11
  60. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  61. package/dist/gene/curator/validate/prompts.js +2 -2
  62. package/dist/gene/learn/draft-guard.d.ts +17 -0
  63. package/dist/gene/learn/draft-guard.js +113 -0
  64. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  65. package/dist/gene/learn/learn-prompt.js +27 -2
  66. package/dist/gene/learn/learner.js +20 -2
  67. package/dist/gene/queue.d.ts +16 -0
  68. package/dist/gene/queue.js +44 -1
  69. package/dist/governance/store/run-store.d.ts +20 -0
  70. package/dist/governance/store/run-store.js +54 -8
  71. package/dist/host/index.d.ts +1 -0
  72. package/dist/host/index.js +1 -0
  73. package/dist/host/interaction.d.ts +8 -17
  74. package/dist/host/interaction.js +50 -72
  75. package/dist/host/team-wake-driver.d.ts +90 -0
  76. package/dist/host/team-wake-driver.js +114 -0
  77. package/dist/logging/install.d.ts +59 -1
  78. package/dist/logging/install.js +15 -0
  79. package/dist/session/validate-session.js +11 -0
  80. package/dist/team/console-tools.d.ts +12 -0
  81. package/dist/team/console-tools.js +20 -3
  82. package/dist/team/console-view.js +11 -1
  83. package/dist/team/notices.d.ts +81 -4
  84. package/dist/team/notices.js +187 -22
  85. package/dist/team/prompt.js +1 -1
  86. package/dist/team/runtime.d.ts +67 -24
  87. package/dist/team/runtime.js +250 -31
  88. package/dist/team/stall-watch.d.ts +54 -0
  89. package/dist/team/stall-watch.js +119 -0
  90. package/dist/team/task-tool.js +2 -2
  91. package/dist/team/wake.d.ts +176 -0
  92. package/dist/team/wake.js +444 -0
  93. package/package.json +81 -81
@@ -13,7 +13,7 @@
13
13
  * I-5) and the "the settle report must always arrive" rule in one object and let
14
14
  * either win.
15
15
  *
16
- * THREE KINDS, THREE LIFETIMES:
16
+ * FIVE KINDS, THREE LIFETIMES:
17
17
  *
18
18
  * - `child_settled` is CHATTER. It is dropped the moment the `dispatch_settled`
19
19
  * report arrives, because the report already contains every row - five child
@@ -25,7 +25,17 @@
25
25
  * outcome.
26
26
  * - `lead_mail` is a REMINDER, bounded by `leadNoticesPerDispatch`; the full mail
27
27
  * is always in the report as well, so losing one of these loses nothing.
28
+ * - `child_failed` and `team_stalled` (team-lead-wake-signals) are SIGNALS: the
29
+ * team needs the lead BEFORE the dispatch ends. Like `child_settled` they are
30
+ * chatter once the report exists, and the queue remembers which dispatches have
31
+ * settled so a stranded one that is re-queued later cannot come back to life.
32
+ *
33
+ * `isAttention()` is the one predicate that says which notices the lead is OWED a
34
+ * wake for. It is a property of the notice, not a second queue.
28
35
  */
36
+ import { type AttentionFact, type SettleFacts } from '@aragon-agent/tui/model/team/wake-plan';
37
+ import type { DispatchOutcome, StallBlocker } from '@aragon-agent/tui/model/team/types';
38
+ export type { SettleFacts };
29
39
  export type TeamNotice = {
30
40
  kind: 'child_settled';
31
41
  /** `${dispatchId}:${label}:${phase}` - a child settles once. */
@@ -47,6 +57,36 @@ export type TeamNotice = {
47
57
  /** `session.reportText`, verbatim. */
48
58
  report: string;
49
59
  aborted: boolean;
60
+ /**
61
+ * Whether the lead is OWED a wake for this end. False for a stop the user or the
62
+ * lead ordered themselves (I-WK11): the actor already knows. The notice is still
63
+ * queued and still delivered with the next turn.
64
+ */
65
+ attention: boolean;
66
+ /** Counted from the outcome; what `<team_signal>` states. */
67
+ facts: SettleFacts;
68
+ at: number;
69
+ } | {
70
+ kind: 'child_failed';
71
+ /** `${dispatchId}:fail:${label}` - a child fails finally once. */
72
+ id: string;
73
+ dispatchId: string;
74
+ label: string;
75
+ /** First line of the error, already cut. */
76
+ error: string;
77
+ elapsedMs: number;
78
+ turns: number;
79
+ toolCalls: number;
80
+ stillRunning: number;
81
+ at: number;
82
+ } | {
83
+ kind: 'team_stalled';
84
+ /** `${dispatchId}:stall:${episode}`. */
85
+ id: string;
86
+ dispatchId: string;
87
+ episode: number;
88
+ quietMs: number;
89
+ blockers: StallBlocker[];
50
90
  at: number;
51
91
  } | {
52
92
  kind: 'lead_mail';
@@ -59,6 +99,14 @@ export type TeamNotice = {
59
99
  bodyHead: string;
60
100
  at: number;
61
101
  };
102
+ /** Notices that mean "the lead is owed a wake". `dispatch_settled` decides per notice. */
103
+ export declare function isAttention(notice: TeamNotice): boolean;
104
+ /**
105
+ * The wake governor's view of one notice: the facts and nothing else, or `null` for a
106
+ * notice the lead is not owed a wake for. The governor lives in a different layer
107
+ * than the notice shapes and reads only this.
108
+ */
109
+ export declare function attentionFactOf(notice: TeamNotice): AttentionFact | null;
62
110
  export declare class TeamNoticeQueue {
63
111
  private readonly entries;
64
112
  /**
@@ -70,6 +118,16 @@ export declare class TeamNoticeQueue {
70
118
  * what the bound is for.
71
119
  */
72
120
  private readonly leadMails;
121
+ /**
122
+ * Dispatches whose report has been queued, in arrival order.
123
+ *
124
+ * WHY THE QUEUE REMEMBERS (RV-P2-11). Swallowing chatter when the report arrives
125
+ * only touches what is IN the queue at that moment. A `child_failed` that had
126
+ * already been steered sits in the relay's ledger, and when the ledger gives it back
127
+ * (`requeueUndelivered`) it would re-enter a queue whose report is already there
128
+ * and be delivered a second time, as a fact the report already contains.
129
+ */
130
+ private readonly settledDispatches;
73
131
  /**
74
132
  * Same id twice keeps ONE entry. That is what makes the relay's re-queue after a
75
133
  * queue wipe idempotent: a notice that was delivered and re-queued can only be
@@ -79,17 +137,36 @@ export declare class TeamNoticeQueue {
79
137
  /** Take everything and reset. The one way a notice leaves this object. */
80
138
  drain(): TeamNotice[];
81
139
  peek(): TeamNotice[];
140
+ /** The queued notices the lead is owed a wake for. */
141
+ attention(): TeamNotice[];
142
+ /**
143
+ * Remove one notice without delivering it. The one caller is `team_collect`: it has
144
+ * just handed the lead the same report in a tool result, so delivering it again
145
+ * would be the duplicate RC-8 describes.
146
+ */
147
+ dropById(id: string): boolean;
82
148
  pending(): number;
83
149
  clear(): void;
150
+ private rememberSettled;
84
151
  }
152
+ /**
153
+ * Count one outcome into the facts `<team_signal>` states.
154
+ *
155
+ * DERIVED FROM THE OUTCOME ALONE, like the report's own header, so the two cannot
156
+ * disagree about how many children failed. "Stopped by" comes from the interventions
157
+ * ledger, which is where `recordControl` already writes who stopped whom.
158
+ */
159
+ export declare function settleFactsOf(outcome: DispatchOutcome): SettleFacts;
160
+ /** First line of an error, cut to the signal's own bound. */
161
+ export declare function firstLine(text: string): string;
85
162
  /**
86
163
  * Render the `<team_notices>` block, or `''` when there is nothing to say.
87
164
  *
88
165
  * EMPTY IN, EMPTY OUT, for the same reason `renderJobNotices` is: an unconditional
89
166
  * block would add lines to every tool call in every session.
90
167
  *
91
- * ORDER: the settle report FIRST, then mail, then child lines. The report is the
92
- * fact; the rest is context for it, and a model that reads only the first two
93
- * lines of a block should still see the thing that ended.
168
+ * ORDER: the settle report FIRST, then the live signals, then mail, then child
169
+ * lines. The report is the fact; the rest is context for it, and a model that reads
170
+ * only the first two lines of a block should still see the thing that ended.
94
171
  */
95
172
  export declare function renderTeamNotices(notices: readonly TeamNotice[]): string;
@@ -13,7 +13,7 @@
13
13
  * I-5) and the "the settle report must always arrive" rule in one object and let
14
14
  * either win.
15
15
  *
16
- * THREE KINDS, THREE LIFETIMES:
16
+ * FIVE KINDS, THREE LIFETIMES:
17
17
  *
18
18
  * - `child_settled` is CHATTER. It is dropped the moment the `dispatch_settled`
19
19
  * report arrives, because the report already contains every row - five child
@@ -25,8 +25,69 @@
25
25
  * outcome.
26
26
  * - `lead_mail` is a REMINDER, bounded by `leadNoticesPerDispatch`; the full mail
27
27
  * is always in the report as well, so losing one of these loses nothing.
28
+ * - `child_failed` and `team_stalled` (team-lead-wake-signals) are SIGNALS: the
29
+ * team needs the lead BEFORE the dispatch ends. Like `child_settled` they are
30
+ * chatter once the report exists, and the queue remembers which dispatches have
31
+ * settled so a stranded one that is re-queued later cannot come back to life.
32
+ *
33
+ * `isAttention()` is the one predicate that says which notices the lead is OWED a
34
+ * wake for. It is a property of the notice, not a second queue.
28
35
  */
29
36
  import { TEAM_LIMITS } from '@aragon-agent/tui/model/team/limits';
37
+ import { formatDuration, sanitizeFact, } from '@aragon-agent/tui/model/team/wake-plan';
38
+ /** Notices that mean "the lead is owed a wake". `dispatch_settled` decides per notice. */
39
+ export function isAttention(notice) {
40
+ switch (notice.kind) {
41
+ case 'dispatch_settled':
42
+ return notice.attention;
43
+ case 'child_failed':
44
+ case 'team_stalled':
45
+ return true;
46
+ default:
47
+ return false;
48
+ }
49
+ }
50
+ /**
51
+ * The wake governor's view of one notice: the facts and nothing else, or `null` for a
52
+ * notice the lead is not owed a wake for. The governor lives in a different layer
53
+ * than the notice shapes and reads only this.
54
+ */
55
+ export function attentionFactOf(notice) {
56
+ if (!isAttention(notice))
57
+ return null;
58
+ const base = { id: notice.id, dispatchId: notice.dispatchId, at: notice.at };
59
+ switch (notice.kind) {
60
+ case 'dispatch_settled':
61
+ return { ...base, kind: 'settled', settled: notice.facts };
62
+ case 'child_failed':
63
+ return {
64
+ ...base,
65
+ kind: 'child_failed',
66
+ failed: {
67
+ label: notice.label,
68
+ error: notice.error,
69
+ elapsedMs: notice.elapsedMs,
70
+ stillRunning: notice.stillRunning,
71
+ },
72
+ };
73
+ case 'team_stalled':
74
+ return {
75
+ ...base,
76
+ kind: 'stalled',
77
+ stalled: { quietMs: notice.quietMs, blockers: notice.blockers },
78
+ };
79
+ default:
80
+ return null;
81
+ }
82
+ }
83
+ /** Notices the report makes redundant once its dispatch has ended. */
84
+ function isChatter(notice) {
85
+ return (notice.kind === 'child_settled' ||
86
+ notice.kind === 'child_failed' ||
87
+ notice.kind === 'team_stalled');
88
+ }
89
+ /** How many settled dispatch ids the queue remembers. Same order as one dispatch's allowance. */
90
+ const SETTLED_MEMORY = 64;
30
91
  export class TeamNoticeQueue {
31
92
  entries = new Map();
32
93
  /**
@@ -38,6 +99,16 @@ export class TeamNoticeQueue {
38
99
  * what the bound is for.
39
100
  */
40
101
  leadMails = new Map();
102
+ /**
103
+ * Dispatches whose report has been queued, in arrival order.
104
+ *
105
+ * WHY THE QUEUE REMEMBERS (RV-P2-11). Swallowing chatter when the report arrives
106
+ * only touches what is IN the queue at that moment. A `child_failed` that had
107
+ * already been steered sits in the relay's ledger, and when the ledger gives it back
108
+ * (`requeueUndelivered`) it would re-enter a queue whose report is already there
109
+ * and be delivered a second time, as a fact the report already contains.
110
+ */
111
+ settledDispatches = new Set();
41
112
  /**
42
113
  * Same id twice keeps ONE entry. That is what makes the relay's re-queue after a
43
114
  * queue wipe idempotent: a notice that was delivered and re-queued can only be
@@ -46,6 +117,8 @@ export class TeamNoticeQueue {
46
117
  push(notice) {
47
118
  if (this.entries.has(notice.id))
48
119
  return;
120
+ if (isChatter(notice) && this.settledDispatches.has(notice.dispatchId))
121
+ return;
49
122
  if (notice.kind === 'lead_mail') {
50
123
  const used = this.leadMails.get(notice.dispatchId) ?? 0;
51
124
  if (used >= TEAM_LIMITS.leadNoticesPerDispatch)
@@ -57,10 +130,10 @@ export class TeamNoticeQueue {
57
130
  // renderer keeps the queue's own bound honest: what is in the map is what
58
131
  // will be delivered.
59
132
  for (const [id, held] of [...this.entries]) {
60
- if (held.dispatchId === notice.dispatchId && held.kind === 'child_settled') {
133
+ if (held.dispatchId === notice.dispatchId && isChatter(held))
61
134
  this.entries.delete(id);
62
- }
63
135
  }
136
+ this.rememberSettled(notice.dispatchId);
64
137
  // The dispatch is over, so its mail allowance goes with it.
65
138
  this.leadMails.delete(notice.dispatchId);
66
139
  }
@@ -77,13 +150,77 @@ export class TeamNoticeQueue {
77
150
  peek() {
78
151
  return [...this.entries.values()];
79
152
  }
153
+ /** The queued notices the lead is owed a wake for. */
154
+ attention() {
155
+ return this.peek().filter(isAttention);
156
+ }
157
+ /**
158
+ * Remove one notice without delivering it. The one caller is `team_collect`: it has
159
+ * just handed the lead the same report in a tool result, so delivering it again
160
+ * would be the duplicate RC-8 describes.
161
+ */
162
+ dropById(id) {
163
+ return this.entries.delete(id);
164
+ }
80
165
  pending() {
81
166
  return this.entries.size;
82
167
  }
83
168
  clear() {
84
169
  this.entries.clear();
85
170
  this.leadMails.clear();
171
+ this.settledDispatches.clear();
172
+ }
173
+ rememberSettled(dispatchId) {
174
+ this.settledDispatches.delete(dispatchId);
175
+ this.settledDispatches.add(dispatchId);
176
+ if (this.settledDispatches.size <= SETTLED_MEMORY)
177
+ return;
178
+ const oldest = this.settledDispatches.values().next().value;
179
+ if (oldest !== undefined)
180
+ this.settledDispatches.delete(oldest);
181
+ }
182
+ }
183
+ /**
184
+ * Count one outcome into the facts `<team_signal>` states.
185
+ *
186
+ * DERIVED FROM THE OUTCOME ALONE, like the report's own header, so the two cannot
187
+ * disagree about how many children failed. "Stopped by" comes from the interventions
188
+ * ledger, which is where `recordControl` already writes who stopped whom.
189
+ */
190
+ export function settleFactsOf(outcome) {
191
+ const count = (phase) => outcome.runs.filter((run) => run.phase === phase).length;
192
+ const failures = outcome.runs.filter((run) => run.phase === 'failed');
193
+ const stopped = { lead: [], user: [] };
194
+ for (const entry of outcome.interventions ?? []) {
195
+ if (entry.action !== 'abandon')
196
+ continue;
197
+ if (entry.trigger !== 'lead' && entry.trigger !== 'user')
198
+ continue;
199
+ stopped[entry.trigger].push(describeStop(entry.label, entry.reason, entry.trigger));
86
200
  }
201
+ return {
202
+ ok: count('done'),
203
+ failed: failures.length,
204
+ aborted: count('aborted'),
205
+ paused: count('paused'),
206
+ firstFailures: failures.slice(0, TEAM_LIMITS.signalFailedLabelsMax).map((run) => ({
207
+ label: run.label,
208
+ error: firstLine(run.error ?? ''),
209
+ })),
210
+ stopped,
211
+ };
212
+ }
213
+ /** `label` or `label (reason: ...)`; the default reason (`stopped by lead`) says nothing new. */
214
+ function describeStop(label, reason, by) {
215
+ const prefix = `stop by ${by}: `;
216
+ const bare = reason.startsWith(prefix) ? reason.slice(prefix.length) : reason;
217
+ if (bare === '' || bare === `stopped by ${by}`)
218
+ return label;
219
+ return `${label} (reason: ${sanitizeFact(bare, 60)})`;
220
+ }
221
+ /** First line of an error, cut to the signal's own bound. */
222
+ export function firstLine(text) {
223
+ return sanitizeFact(text.split('\n')[0] ?? '', TEAM_LIMITS.signalErrorChars);
87
224
  }
88
225
  /**
89
226
  * Render the `<team_notices>` block, or `''` when there is nothing to say.
@@ -91,31 +228,59 @@ export class TeamNoticeQueue {
91
228
  * EMPTY IN, EMPTY OUT, for the same reason `renderJobNotices` is: an unconditional
92
229
  * block would add lines to every tool call in every session.
93
230
  *
94
- * ORDER: the settle report FIRST, then mail, then child lines. The report is the
95
- * fact; the rest is context for it, and a model that reads only the first two
96
- * lines of a block should still see the thing that ended.
231
+ * ORDER: the settle report FIRST, then the live signals, then mail, then child
232
+ * lines. The report is the fact; the rest is context for it, and a model that reads
233
+ * only the first two lines of a block should still see the thing that ended.
97
234
  */
98
235
  export function renderTeamNotices(notices) {
99
236
  if (notices.length === 0)
100
237
  return '';
101
- const rank = (notice) => notice.kind === 'dispatch_settled' ? 0 : notice.kind === 'lead_mail' ? 1 : 2;
102
- const sorted = [...notices].sort((a, b) => rank(a) - rank(b));
238
+ const sorted = [...notices].sort((a, b) => noticeRank(a) - noticeRank(b));
103
239
  const lines = ['<team_notices>'];
104
- for (const notice of sorted) {
105
- if (notice.kind === 'dispatch_settled') {
106
- lines.push(notice.report);
107
- continue;
240
+ for (const notice of sorted)
241
+ lines.push(...noticeLines(notice));
242
+ lines.push('</team_notices>');
243
+ return lines.join('\n');
244
+ }
245
+ /** settled, then the signals, then mail, then child chatter. */
246
+ function noticeRank(notice) {
247
+ switch (notice.kind) {
248
+ case 'dispatch_settled':
249
+ return 0;
250
+ case 'child_failed':
251
+ case 'team_stalled':
252
+ return 1;
253
+ case 'lead_mail':
254
+ return 2;
255
+ default:
256
+ return 3;
257
+ }
258
+ }
259
+ function noticeLines(notice) {
260
+ switch (notice.kind) {
261
+ case 'dispatch_settled':
262
+ return [notice.report];
263
+ case 'lead_mail': {
264
+ const head = `${notice.from} -> lead: ${notice.subject}`;
265
+ return notice.bodyHead.length > 0 ? [head, ` ${notice.bodyHead}`] : [head];
108
266
  }
109
- if (notice.kind === 'lead_mail') {
110
- lines.push(`${notice.from} -> lead: ${notice.subject}`);
111
- if (notice.bodyHead.length > 0)
112
- lines.push(` ${notice.bodyHead}`);
113
- continue;
267
+ case 'child_failed': {
268
+ const error = notice.error === '' ? '' : `: ${notice.error}`;
269
+ return [
270
+ `${notice.label} failed after ${formatDuration(notice.elapsedMs)}` +
271
+ ` (${notice.turns} turns / ${notice.toolCalls} tools)${error}`,
272
+ ];
273
+ }
274
+ case 'team_stalled': {
275
+ const who = notice.blockers
276
+ .map((b) => `${sanitizeFact(b.label, 24)} ${b.state} ${formatDuration(b.ms)}`)
277
+ .join(', ');
278
+ return [`no progress for ${formatDuration(notice.quietMs)}${who === '' ? '' : `: ${who}`}`];
279
+ }
280
+ default: {
281
+ const detail = `${notice.label} ${notice.phase} after ${Math.round(notice.elapsedMs / 1000)}s` +
282
+ ` (${notice.turns} turns / ${notice.toolCalls} tools)`;
283
+ return [notice.error !== undefined ? `${detail}: ${notice.error}` : detail];
114
284
  }
115
- const detail = `${notice.label} ${notice.phase} after ${Math.round(notice.elapsedMs / 1000)}s` +
116
- ` (${notice.turns} turns / ${notice.toolCalls} tools)`;
117
- lines.push(notice.error !== undefined ? `${detail}: ${notice.error}` : detail);
118
285
  }
119
- lines.push('</team_notices>');
120
- return lines.join('\n');
121
286
  }
@@ -49,7 +49,7 @@ export function buildTeamBlock(params) {
49
49
  'yours), and none may delegate further.',
50
50
  ];
51
51
  if (params.detachDispatch === true) {
52
- lines.push('', 'While a dispatch runs you are FREE, not waiting: a new user message is your', 'own turn - answer it, do not route it to the team. team_status shows the', 'roster and partial results; team_message corrects a child; team_pause /', 'team_resume hold one; team_stop ends one; team_spawn adds one; team_collect', 'only when you cannot answer without results. If the user changes the goal', 'mid-flight, propagate it with team_message (and pause what no longer matters)', 'before you answer. The report arrives when the team finishes; summarise it', 'then, in your own words.');
52
+ lines.push('', 'While a dispatch runs you are FREE, not waiting: a new user message is your', 'own turn - answer it, do not route it to the team. team_status shows the', 'roster and partial results; team_message corrects a child; team_pause /', 'team_resume hold one; team_stop ends one; team_spawn adds one; team_collect', 'only when you cannot answer without results. If the user changes the goal', 'mid-flight, propagate it with team_message (and pause what no longer matters)', 'before you answer. A <team_signal> wakes you when the team ends, a child', 'fails or it stalls; the rest is yours.');
53
53
  }
54
54
  else {
55
55
  lines.push('', 'You get one combined report when they all finish. Read it before deciding', 'what to do next, and tell the user what the team found in your own words.');
@@ -140,12 +140,6 @@ export interface TeamRuntimeDeps {
140
140
  * default, because a host that cannot answer must not be assumed free).
141
141
  */
142
142
  currentTurnId?: () => number;
143
- /**
144
- * Whether the lead is inside a turn right now. Paired with `currentTurnId()`
145
- * to derive `settledInsideTurn`; a dispatch cannot have "settled inside its own
146
- * turn" if no turn is running.
147
- */
148
- isLeadRunning?: () => boolean;
149
143
  /**
150
144
  * The report's price and model closures, read AT SETTLEMENT (REV-05).
151
145
  *
@@ -209,6 +203,16 @@ export interface DispatchInspection {
209
203
  mail: TeamMessage[];
210
204
  controls: TeamControlRecord[];
211
205
  reportText?: string;
206
+ /**
207
+ * Present only while the team is stalled right now (team-lead-wake-signals 4.6):
208
+ * somebody is blocked, nobody is working, and it has been quiet for at least
209
+ * `team.stallSignalMs`. Absent when the signal is off.
210
+ */
211
+ stalled?: {
212
+ since: number;
213
+ quietMs: number;
214
+ blockers: string[];
215
+ };
212
216
  }
213
217
  export declare class TeamRuntime {
214
218
  private readonly deps;
@@ -293,6 +297,8 @@ export declare class TeamRuntime {
293
297
  snapshot(): TeamSnapshot | null;
294
298
  /** Everything `team_status`, `team_collect` and `/team status` render. */
295
299
  inspect(): DispatchInspection | null;
300
+ /** `{ stalled }` while the watch currently judges the team stalled, else nothing. */
301
+ private stalledInspection;
296
302
  /**
297
303
  * Hold one child (section 5.2.4). The RESULT says what will actually happen,
298
304
  * because "paused" is cooperative: `paused` when the child is between tools,
@@ -395,6 +401,23 @@ export declare class TeamRuntime {
395
401
  * reads it.
396
402
  */
397
403
  start(specs: SubagentSpec[], requested: number): DispatchHandle;
404
+ /**
405
+ * EXACTLY ONE `dispatch_end` PER DETACHED DISPATCH (I-WK15), including the ones
406
+ * that never got to emit their own.
407
+ *
408
+ * `runDispatch` can throw before `dispatch_start` (a child cannot be constructed)
409
+ * or, in principle, afterwards. The `session.outcome` guard is what makes "exactly
410
+ * one" a property of this method rather than of `runDispatch`'s shape: a dispatch
411
+ * that already settled has its outcome and its `dispatch_end`, and this returns.
412
+ *
413
+ * THE OUTCOME IS SYNTHESISED FROM FIELDS THAT ALREADY EXIST, every run `failed`
414
+ * with the reason: no new `DispatchOutcome` member (it is persisted), and the real
415
+ * `buildDispatchReport` can render it, so the lead reads a report in the format it
416
+ * knows. If even synthesis throws it degrades to one line per spec - a rough report
417
+ * beats no signal.
418
+ */
419
+ private failDetached;
420
+ private synthesizeFailedOutcome;
398
421
  /** The live dispatch handle, or `null`. The read surface behind `team_status`. */
399
422
  live(): DispatchHandle | null;
400
423
  /** The settled outcome for `dispatchId`, when it is the one on record. */
@@ -402,25 +425,19 @@ export declare class TeamRuntime {
402
425
  /** The report text produced AT SETTLEMENT, or `undefined` while live (REV-05). */
403
426
  reportText(dispatchId: string): string | undefined;
404
427
  /**
405
- * The settle facts the host needs to decide whether the lead gets a follow-up
406
- * turn (`planSettleContinuation`, section 5.3.3).
428
+ * Who ended dispatch `dispatchId` as a whole, if anybody did (I-WK11).
407
429
  *
408
- * `settledInsideTurn` is COMPUTED AT SETTLEMENT from `turnId` equality plus
409
- * `isLeadRunning()` (REV-04), never from a signal or a wall clock: both of those
410
- * give the wrong answer in the case that most needs reporting - a dispatch that
411
- * failed fast inside the very turn that started it, where the report has
412
- * already arrived as a steering message.
413
- */
414
- settleFacts(dispatchId: string): {
415
- settled: boolean;
416
- settledInsideTurn: boolean;
417
- continuedThisDispatch: boolean;
418
- aborted: boolean;
419
- errored: boolean;
420
- outcome: DispatchOutcome | null;
421
- } | null;
422
- /** Record that the follow-up turn was spent. At most one per dispatch. */
423
- markContinued(dispatchId: string): void;
430
+ * READ BY THE CONTROLLER INSIDE ITS `dispatch_end` LISTENER, where it decides
431
+ * whether the settle notice is a wake-worthy signal: a stop the user or the lead
432
+ * ordered is a fact the ordering party already has.
433
+ */
434
+ abortedBy(dispatchId: string): 'user' | 'lead' | 'ceiling' | 'dispose' | undefined;
435
+ /**
436
+ * Record that the LIVE dispatch is being ended on purpose by `by`. First writer
437
+ * wins: an Esc followed by `team_stop all` is still one decision. A narrow method
438
+ * rather than a setter so `controller.stopEngine()` cannot reach the session.
439
+ */
440
+ noteAbortedBy(by: 'user' | 'lead' | 'ceiling' | 'dispose'): void;
424
441
  /** The id of the dispatch on record, live or settled. */
425
442
  currentDispatchId(): string | null;
426
443
  /** Whether the live dispatch was started by the turn identified by `turnId`. */
@@ -458,6 +475,21 @@ export declare class TeamRuntime {
458
475
  * a handle swapped anywhere else would never be (I-OV1).
459
476
  */
460
477
  private runOne;
478
+ /**
479
+ * Say, once, that a child FINALLY failed (team-lead-wake-signals 4.4.1).
480
+ *
481
+ * `agent_update` with `phase: 'failed'` is not that: the supervisor's post-mortem may
482
+ * rebuild the child a moment later. So the signal is raised from the three places
483
+ * where the child's fate is settled - the terminal branch of `runOne` AFTER its
484
+ * post-mortem, and the two early returns where `replaceChild` could not build a body.
485
+ *
486
+ * THE SINGLE `!==` IS THE DEDUPLICATION. `maybePostMortem` recurses into `runOne`,
487
+ * and the inner frame reaches its own `noteChildFinal` first, with the fresh handle;
488
+ * when control returns to the outer frame `handles[index]` is no longer ITS handle,
489
+ * so it stays silent and only the successor reports. `aborted` is not a failure: it
490
+ * is what a `team_stop` by the lead or the user, and an `abortAll`, produce.
491
+ */
492
+ private noteChildFinal;
461
493
  /**
462
494
  * One post-mortem inspection, and possibly ONE replacement driven by a
463
495
  * recursive `runOne` — the worker that called us has already moved on to the
@@ -563,5 +595,16 @@ export declare class TeamRuntime {
563
595
  /** Process-exit path: abort everything and clear timers (R-15). */
564
596
  dispose(): void;
565
597
  private publish;
598
+ /** Arm the watch. `quietMs <= 0` is the documented off switch: nothing is created. */
599
+ private startStallWatch;
600
+ private stopStallWatch;
601
+ /**
602
+ * Real progress closes the current stall episode, so the NEXT quiet spell can raise
603
+ * its own signal. `touched` is the lead's own activity, which the ledger has to be
604
+ * told about directly (nothing is published for it).
605
+ */
606
+ private noteProgress;
607
+ private tickStall;
608
+ private stallVerdict;
566
609
  private emit;
567
610
  }