@aragon-agent/cli 0.5.2 → 0.5.4

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 (87) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +193 -3
  3. package/dist/agent/controller.d.ts +51 -1
  4. package/dist/agent/controller.js +177 -2
  5. package/dist/agent/headless.d.ts +12 -0
  6. package/dist/agent/headless.js +41 -1
  7. package/dist/agent/reducer.d.ts +48 -0
  8. package/dist/agent/reducer.js +91 -2
  9. package/dist/agent/system-prompt.d.ts +17 -0
  10. package/dist/agent/system-prompt.js +4 -0
  11. package/dist/cli.js +98 -7
  12. package/dist/commands/builtins.d.ts +2 -2
  13. package/dist/commands/builtins.js +133 -3
  14. package/dist/config/app-paths.d.ts +17 -0
  15. package/dist/config/app-paths.js +21 -0
  16. package/dist/config/cli-commands.d.ts +26 -2
  17. package/dist/config/cli-commands.js +83 -6
  18. package/dist/config/env.d.ts +3 -2
  19. package/dist/config/env.js +44 -6
  20. package/dist/config/history-commands.d.ts +20 -0
  21. package/dist/config/history-commands.js +71 -0
  22. package/dist/config/load.d.ts +13 -0
  23. package/dist/config/load.js +107 -6
  24. package/dist/config/migrate-state-out-of-config.d.ts +32 -0
  25. package/dist/config/migrate-state-out-of-config.js +85 -0
  26. package/dist/config/prompt-history.d.ts +86 -0
  27. package/dist/config/prompt-history.js +332 -0
  28. package/dist/config/schema.d.ts +176 -18
  29. package/dist/config/schema.js +162 -8
  30. package/dist/config/store.js +40 -4
  31. package/dist/config/ui-state.d.ts +52 -0
  32. package/dist/config/ui-state.js +149 -0
  33. package/dist/logging/install.d.ts +85 -0
  34. package/dist/logging/install.js +94 -0
  35. package/dist/logging/logger.d.ts +1 -1
  36. package/dist/session/persist.d.ts +16 -0
  37. package/dist/session/persist.js +19 -1
  38. package/dist/team/activity.d.ts +67 -0
  39. package/dist/team/activity.js +130 -0
  40. package/dist/team/bus.d.ts +190 -0
  41. package/dist/team/bus.js +366 -0
  42. package/dist/team/comm-tools.d.ts +61 -0
  43. package/dist/team/comm-tools.js +221 -0
  44. package/dist/team/human-queue.d.ts +55 -0
  45. package/dist/team/human-queue.js +72 -0
  46. package/dist/team/limits.d.ts +123 -0
  47. package/dist/team/limits.js +128 -0
  48. package/dist/team/normalize.d.ts +39 -0
  49. package/dist/team/normalize.js +106 -0
  50. package/dist/team/panel-rows.d.ts +48 -0
  51. package/dist/team/panel-rows.js +75 -0
  52. package/dist/team/prompt.d.ts +49 -0
  53. package/dist/team/prompt.js +87 -0
  54. package/dist/team/report.d.ts +58 -0
  55. package/dist/team/report.js +205 -0
  56. package/dist/team/retry.d.ts +48 -0
  57. package/dist/team/retry.js +56 -0
  58. package/dist/team/runtime.d.ts +122 -0
  59. package/dist/team/runtime.js +406 -0
  60. package/dist/team/subagent.d.ts +90 -0
  61. package/dist/team/subagent.js +294 -0
  62. package/dist/team/task-tool.d.ts +47 -0
  63. package/dist/team/task-tool.js +118 -0
  64. package/dist/team/types.d.ts +172 -0
  65. package/dist/team/types.js +13 -0
  66. package/dist/tools/index.d.ts +48 -2
  67. package/dist/tools/index.js +26 -1
  68. package/dist/ui/App.d.ts +22 -1
  69. package/dist/ui/App.js +144 -18
  70. package/dist/ui/StatusBar.d.ts +21 -0
  71. package/dist/ui/StatusBar.js +5 -2
  72. package/dist/ui/TeamPanel.d.ts +57 -0
  73. package/dist/ui/TeamPanel.js +134 -0
  74. package/dist/ui/Transcript.js +10 -0
  75. package/dist/ui/entries/TeamCard.d.ts +31 -0
  76. package/dist/ui/entries/TeamCard.js +39 -0
  77. package/dist/ui/glyphs.d.ts +10 -0
  78. package/dist/ui/glyphs.js +6 -0
  79. package/dist/ui/layout/AppShell.d.ts +11 -1
  80. package/dist/ui/layout/AppShell.js +3 -3
  81. package/dist/ui/overlays/HelpOverlay.js +13 -0
  82. package/dist/ui/overlays/SettingsScreen.d.ts +12 -1
  83. package/dist/ui/overlays/SettingsScreen.js +38 -1
  84. package/dist/ui/transcript-text.js +20 -0
  85. package/dist/ui/use-startup-notices.d.ts +1 -1
  86. package/dist/ui/use-startup-notices.js +2 -1
  87. package/package.json +2 -2
@@ -300,3 +300,97 @@ export function attachAgentEvents(logger, controller) {
300
300
  }
301
301
  });
302
302
  }
303
+ /**
304
+ * Record a dispatch's lifecycle.
305
+ *
306
+ * WITHOUT THIS, A DISPATCH LEAVES NO TRACE IN THE LOG AT ALL (P1-2 / R-19).
307
+ * `TeamEvent` is deliberately CLI-local (D-10), so `attachAgentEvents` cannot
308
+ * see it — which is the wrong outcome for the one feature in this CLI that runs
309
+ * five agents the user cannot watch, and whose only other artefact is a report
310
+ * written by the thing that failed. A separate function rather than a branch in
311
+ * `attachAgentEvents` (D-19): the two consume different unions and want
312
+ * different level policies.
313
+ *
314
+ * TWO RULES, BOTH ABOUT NOT TURNING A LOG INTO A LIABILITY:
315
+ *
316
+ * - A subagent's PROMPT and its SUMMARY are `trace` only, and go through the
317
+ * same redaction every other record does. A `prompt` is up to 8 000
318
+ * characters of whatever the lead decided to say; at `debug` it would
319
+ * dominate the file.
320
+ * - A `team_send` BODY is never recorded at any level. The subject is enough to
321
+ * reconstruct who talked to whom and when, which is the diagnostic question;
322
+ * the body is user content that reached no other sink.
323
+ *
324
+ * `agent_update` is recorded on PHASE TRANSITIONS ONLY, not on the 120 ms
325
+ * coalescer tick: that throttle exists to protect React, and five children at
326
+ * eight events a second each is 40 lines a second of noise that would push the
327
+ * retention window down to minutes.
328
+ */
329
+ export function attachTeamEvents(logger, controller) {
330
+ if (!controller.subscribeTeam)
331
+ return () => { };
332
+ const lastPhase = new Map();
333
+ return controller.subscribeTeam((event) => {
334
+ switch (event.type) {
335
+ case 'dispatch_start': {
336
+ const specs = event.specs ?? [];
337
+ logger.info('agent', 'team_dispatch_start', {
338
+ dispatchId: event.dispatchId,
339
+ requested: event.requested,
340
+ accepted: specs.length,
341
+ labels: specs.map((s) => s.label ?? '?'),
342
+ });
343
+ for (const spec of specs) {
344
+ logger.trace('agent', 'team_subagent_brief', {
345
+ dispatchId: event.dispatchId,
346
+ label: spec.label,
347
+ description: spec.description,
348
+ prompt: spec.prompt,
349
+ });
350
+ }
351
+ break;
352
+ }
353
+ case 'agent_update': {
354
+ const key = `${event.dispatchId}:${event.run?.label ?? '?'}`;
355
+ const phase = event.run?.phase ?? 'unknown';
356
+ if (lastPhase.get(key) === phase)
357
+ break;
358
+ lastPhase.set(key, phase);
359
+ logger.debug('agent', 'team_agent_update', {
360
+ dispatchId: event.dispatchId,
361
+ label: event.run?.label,
362
+ phase,
363
+ lastTool: event.run?.lastTool,
364
+ });
365
+ break;
366
+ }
367
+ case 'message':
368
+ logger.debug('agent', 'team_message', {
369
+ dispatchId: event.dispatchId,
370
+ from: event.message?.from,
371
+ to: event.message?.to,
372
+ // SUBJECT ONLY. See the rule above; the body never leaves the process.
373
+ subject: event.message?.subject,
374
+ });
375
+ break;
376
+ case 'dispatch_end': {
377
+ const outcome = event.outcome;
378
+ const runs = outcome?.runs ?? [];
379
+ const ok = runs.filter((r) => r.phase === 'done' && !r.error).length;
380
+ logger.info('agent', 'team_dispatch_end', {
381
+ dispatchId: event.dispatchId,
382
+ durationMs: Math.max(0, (outcome?.endedAt ?? 0) - (outcome?.startedAt ?? 0)),
383
+ ok,
384
+ failed: runs.length - ok,
385
+ aborted: outcome?.aborted === true,
386
+ in: outcome?.usage?.inputTokens ?? 0,
387
+ out: outcome?.usage?.outputTokens ?? 0,
388
+ filesTouched: [...new Set(runs.flatMap((r) => r.filesTouched ?? []))],
389
+ });
390
+ break;
391
+ }
392
+ default:
393
+ break;
394
+ }
395
+ });
396
+ }
@@ -23,7 +23,7 @@
23
23
  import type { LogConfig } from '../config/schema.js';
24
24
  import { type LogLevelName } from './levels.js';
25
25
  /** Closed set, not free text: a typo'd scope is a record nobody can filter on. */
26
- export type LogScope = 'cli' | 'config' | 'agent' | 'tool' | 'skills' | 'llm' | 'migrate' | 'log';
26
+ export type LogScope = 'cli' | 'config' | 'agent' | 'tool' | 'skills' | 'llm' | 'migrate' | 'log' | 'history';
27
27
  export interface LogRecord {
28
28
  ts: string;
29
29
  lv: LogLevelName;
@@ -21,4 +21,20 @@ export declare function saveSession(filePath: string, data: {
21
21
  messages: Message[];
22
22
  entries: Entry[];
23
23
  }): void;
24
+ /**
25
+ * Settle any team entry that was saved mid-dispatch (team-subagents §5.3 / P1-5).
26
+ *
27
+ * `saveSession` writes `entries` verbatim and `loadSession` validates only
28
+ * array-ness, so a session saved while a dispatch was in flight resumes with a
29
+ * `kind: 'team'` entry claiming `active: true` while nothing is running. TWO
30
+ * things then go wrong at once: the card spins forever, and `Transcript`'s
31
+ * settled boundary is MONOTONIC — an entry that never settles never reaches
32
+ * `<Static>` and is re-rendered on every frame for the rest of the session.
33
+ *
34
+ * `aborted: true` is also simply TRUE: the children died with the process.
35
+ *
36
+ * This belongs in the LOAD path rather than the reducer because the reducer
37
+ * never legitimately sees a stale-active entry — only the file does.
38
+ */
39
+ export declare function normalizeLoadedEntries(entries: Entry[]): Entry[];
24
40
  export declare function loadSession(filePath: string): SavedSession;
@@ -41,11 +41,29 @@ export function saveSession(filePath, data) {
41
41
  };
42
42
  writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf-8');
43
43
  }
44
+ /**
45
+ * Settle any team entry that was saved mid-dispatch (team-subagents §5.3 / P1-5).
46
+ *
47
+ * `saveSession` writes `entries` verbatim and `loadSession` validates only
48
+ * array-ness, so a session saved while a dispatch was in flight resumes with a
49
+ * `kind: 'team'` entry claiming `active: true` while nothing is running. TWO
50
+ * things then go wrong at once: the card spins forever, and `Transcript`'s
51
+ * settled boundary is MONOTONIC — an entry that never settles never reaches
52
+ * `<Static>` and is re-rendered on every frame for the rest of the session.
53
+ *
54
+ * `aborted: true` is also simply TRUE: the children died with the process.
55
+ *
56
+ * This belongs in the LOAD path rather than the reducer because the reducer
57
+ * never legitimately sees a stale-active entry — only the file does.
58
+ */
59
+ export function normalizeLoadedEntries(entries) {
60
+ return entries.map((entry) => entry.kind === 'team' && entry.active ? { ...entry, active: false, aborted: true } : entry);
61
+ }
44
62
  export function loadSession(filePath) {
45
63
  const raw = readFileSync(filePath, 'utf-8');
46
64
  const parsed = JSON.parse(raw);
47
65
  if (!parsed || !Array.isArray(parsed.messages) || !Array.isArray(parsed.entries)) {
48
66
  throw new Error('Invalid session file (missing messages/entries).');
49
67
  }
50
- return parsed;
68
+ return { ...parsed, entries: normalizeLoadedEntries(parsed.entries) };
51
69
  }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Activity strings for the live roster (team-live-activity F-1).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside the glyph scanner's scope. That rule binds
5
+ * the LITERALS IN THIS FILE, not the runtime data flowing through it - a child
6
+ * may well be reading a CJK path, and `run.description` already carries model
7
+ * text into the same row.
8
+ */
9
+ /**
10
+ * The only part of a tool call this module will ever render (P1-4).
11
+ *
12
+ * A PICKED SUBSET, NOT THE ARGS OBJECT. Storing `event.args` whole would put
13
+ * `write_file`'s `content` - a whole file - on the run, and `TeamRuntime.publish`
14
+ * shallow-copies the run into the live snapshot AND into every `agent_update`
15
+ * event, and `dispatch()` copies it again into `DispatchOutcome.runs`, which
16
+ * `TeamCard` holds in the transcript for the rest of the session. Two facts make
17
+ * that unacceptable rather than merely wasteful: the retention is unbounded in
18
+ * the file's size, and one `JSON.stringify` anywhere downstream would put a file
19
+ * body into a log - the exact liability the logging section spends a paragraph
20
+ * avoiding.
21
+ *
22
+ * This costs nothing in maintenance: the switch below is ALREADY a per-tool
23
+ * table, so a new tool is one entry either way.
24
+ */
25
+ export interface ActivityArgs {
26
+ path?: string;
27
+ pattern?: string;
28
+ command?: string;
29
+ to?: string;
30
+ from?: string;
31
+ }
32
+ /** Pick at capture time. Called once per `tool_execution_start`. */
33
+ export declare function pickActivityArgs(args: unknown): ActivityArgs;
34
+ /**
35
+ * Strip anything that could corrupt the frame, collapse whitespace, and clamp.
36
+ *
37
+ * THE CONTROL-CHARACTER STRIP IS A CORRECTNESS BOUNDARY, NOT TIDINESS. This
38
+ * string is model-chosen and reaches an Ink <Text> unescaped. A child running
39
+ * `bash` with an ANSI escape in the command line would otherwise write that
40
+ * escape into the roster: at best a mangled row, at worst a cleared screen or a
41
+ * moved cursor in the middle of someone's transcript. `bash`'s own output never
42
+ * reaches the panel; its ARGUMENTS now do.
43
+ *
44
+ * SURROGATES ARE GUARDED AT BOTH ENDS (P2-3). The trailing guard is the obvious
45
+ * one. The LEADING one is needed because the caller feeds this a rolling tail
46
+ * built with `String.slice(-n)`, which cuts on a UTF-16 code-unit boundary and
47
+ * can therefore hand us a lone LOW surrogate at index 0. Either half of a split
48
+ * pair renders as a replacement character - the same failure `truncateBytes`
49
+ * guards one layer down (report.ts).
50
+ */
51
+ export declare function sanitizeActivity(raw: string, maxChars: number): string;
52
+ /**
53
+ * One short phrase describing a tool call.
54
+ *
55
+ * `wide` false is the narrow-terminal form (D-4). For a path-valued argument
56
+ * that is the basename; for `bash` it is the PROGRAM NAME (P1-6). Running the
57
+ * command line through `basename` is wrong twice over: `basename` splits on `/`,
58
+ * so `npm test -w cli` comes back whole and `./scripts/build.sh --prod` comes
59
+ * back as `build.sh --prod`. Neither is shorter and the second is a lie about
60
+ * what ran.
61
+ *
62
+ * Anything not in the table renders as its own name. That is the correct
63
+ * degradation for `skill_find` and for any tool a later round registers on a
64
+ * child: a name is always true, and inventing an argument mapping for a tool
65
+ * this module has not been taught is how a formatter starts lying.
66
+ */
67
+ export declare function describeToolActivity(toolName: string, args: ActivityArgs | undefined, wide: boolean): string;
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Activity strings for the live roster (team-live-activity F-1).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside the glyph scanner's scope. That rule binds
5
+ * the LITERALS IN THIS FILE, not the runtime data flowing through it - a child
6
+ * may well be reading a CJK path, and `run.description` already carries model
7
+ * text into the same row.
8
+ */
9
+ import { TEAM_LIMITS } from './limits.js';
10
+ /** Pick at capture time. Called once per `tool_execution_start`. */
11
+ export function pickActivityArgs(args) {
12
+ const a = (args ?? {});
13
+ const str = (v) => typeof v === 'string' && v.length > 0 ? v.slice(0, TEAM_LIMITS.activityArgChars) : undefined;
14
+ const picked = {};
15
+ const path = str(a.path);
16
+ const pattern = str(a.pattern);
17
+ const command = str(a.command);
18
+ const to = str(a.to);
19
+ const from = str(a.from);
20
+ if (path !== undefined)
21
+ picked.path = path;
22
+ if (pattern !== undefined)
23
+ picked.pattern = pattern;
24
+ if (command !== undefined)
25
+ picked.command = command;
26
+ if (to !== undefined)
27
+ picked.to = to;
28
+ if (from !== undefined)
29
+ picked.from = from;
30
+ return picked;
31
+ }
32
+ /**
33
+ * Strip anything that could corrupt the frame, collapse whitespace, and clamp.
34
+ *
35
+ * THE CONTROL-CHARACTER STRIP IS A CORRECTNESS BOUNDARY, NOT TIDINESS. This
36
+ * string is model-chosen and reaches an Ink <Text> unescaped. A child running
37
+ * `bash` with an ANSI escape in the command line would otherwise write that
38
+ * escape into the roster: at best a mangled row, at worst a cleared screen or a
39
+ * moved cursor in the middle of someone's transcript. `bash`'s own output never
40
+ * reaches the panel; its ARGUMENTS now do.
41
+ *
42
+ * SURROGATES ARE GUARDED AT BOTH ENDS (P2-3). The trailing guard is the obvious
43
+ * one. The LEADING one is needed because the caller feeds this a rolling tail
44
+ * built with `String.slice(-n)`, which cuts on a UTF-16 code-unit boundary and
45
+ * can therefore hand us a lone LOW surrogate at index 0. Either half of a split
46
+ * pair renders as a replacement character - the same failure `truncateBytes`
47
+ * guards one layer down (report.ts).
48
+ */
49
+ export function sanitizeActivity(raw, maxChars) {
50
+ let src = raw;
51
+ const head = src.charCodeAt(0);
52
+ if (head >= 0xdc00 && head <= 0xdfff)
53
+ src = src.slice(1);
54
+ const flat = src
55
+ // eslint-disable-next-line no-control-regex
56
+ .replace(/[\x00-\x1f\x7f]/g, ' ')
57
+ .replace(/\s+/g, ' ')
58
+ .trim();
59
+ if (maxChars <= 0)
60
+ return '';
61
+ if (flat.length <= maxChars)
62
+ return flat;
63
+ if (maxChars <= 3)
64
+ return flat.slice(0, maxChars);
65
+ let cut = maxChars - 3;
66
+ const code = flat.charCodeAt(cut - 1);
67
+ if (code >= 0xd800 && code <= 0xdbff)
68
+ cut -= 1;
69
+ return `${flat.slice(0, cut)}...`;
70
+ }
71
+ /** The basename of a path, for the narrow form. Pure string work: no `path`. */
72
+ function basename(p) {
73
+ const parts = p.split(/[\\/]/);
74
+ return parts[parts.length - 1] || p;
75
+ }
76
+ /** The program name of a command line, for the narrow form. */
77
+ function program(commandLine) {
78
+ const first = commandLine.trim().split(/\s+/)[0] ?? '';
79
+ return basename(first) || commandLine;
80
+ }
81
+ /**
82
+ * One short phrase describing a tool call.
83
+ *
84
+ * `wide` false is the narrow-terminal form (D-4). For a path-valued argument
85
+ * that is the basename; for `bash` it is the PROGRAM NAME (P1-6). Running the
86
+ * command line through `basename` is wrong twice over: `basename` splits on `/`,
87
+ * so `npm test -w cli` comes back whole and `./scripts/build.sh --prod` comes
88
+ * back as `build.sh --prod`. Neither is shorter and the second is a lie about
89
+ * what ran.
90
+ *
91
+ * Anything not in the table renders as its own name. That is the correct
92
+ * degradation for `skill_find` and for any tool a later round registers on a
93
+ * child: a name is always true, and inventing an argument mapping for a tool
94
+ * this module has not been taught is how a formatter starts lying.
95
+ */
96
+ export function describeToolActivity(toolName, args, wide) {
97
+ const a = args ?? {};
98
+ switch (toolName) {
99
+ case 'read_file':
100
+ return detail('read', a.path, wide, basename);
101
+ case 'write_file':
102
+ return detail('write', a.path, wide, basename);
103
+ case 'edit_file':
104
+ return detail('edit', a.path, wide, basename);
105
+ case 'list_dir':
106
+ return detail('list', a.path ?? '.', wide, basename);
107
+ case 'glob':
108
+ return detail('glob', a.pattern, wide, basename);
109
+ case 'grep':
110
+ return detail('grep', a.pattern, wide, basename);
111
+ case 'bash':
112
+ return detail('bash', a.command, wide, program);
113
+ case 'team_send': {
114
+ const to = (a.to ?? '').trim();
115
+ return to ? `messaging ${to}` : 'messaging';
116
+ }
117
+ case 'team_wait': {
118
+ const from = (a.from ?? '').trim();
119
+ return from ? `waiting for ${from}` : 'waiting for mail';
120
+ }
121
+ default:
122
+ return toolName;
123
+ }
124
+ }
125
+ function detail(verb, value, wide, narrow) {
126
+ const v = (value ?? '').trim();
127
+ if (v.length === 0)
128
+ return verb;
129
+ return `${verb}: ${wide ? v : narrow(v)}`;
130
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * TeamBus — the subagent message channel (team-subagents §3.6).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside the glyph scanner's scope.
5
+ *
6
+ * The requirement asks for "lei si ren lei jiao liu de dian hua ji zhi, dan bu
7
+ * neng tai pin fan" — a real telephone, used sparingly. This module takes both
8
+ * halves literally: there IS a channel, and it is expensive on purpose. The rate
9
+ * limits in `TEAM_LIMITS` are the requirement, not a compromise (R-9).
10
+ *
11
+ * DELIVERY IS PIGGY-BACKED, NEVER PUSHED (D-4). A message for child B is
12
+ * appended to B's NEXT TOOL RESULT by `withMailboxTail`. `Agent.steer()` looks
13
+ * like the natural push channel and is the wrong answer: the core agent loop
14
+ * treats steering that arrives mid-batch by pushing "Tool execution skipped due
15
+ * to steering interrupt." for EVERY REMAINING TOOL CALL in that batch, so a
16
+ * chatty peer would cancel its colleague's work as a side effect of saying
17
+ * hello. Piggy-backing costs zero extra turns, cannot interfere with the loop,
18
+ * and is guaranteed to be seen by any child that is doing anything at all.
19
+ *
20
+ * EVERY REFUSAL IS A NON-ERROR (D-7). An `errorResult` reads to a model as a
21
+ * malfunction and invites an immediate retry, which is precisely the "tai pin
22
+ * fan" behaviour being designed out. The verdicts below carry a `reason` the
23
+ * caller renders as ordinary text.
24
+ */
25
+ import type { TeamMessage } from './types.js';
26
+ /** The lead's stable address. Subagents are addressed by their `label`. */
27
+ export declare const LEAD_KEY = "lead";
28
+ /** Broadcast address: every other participant, the lead included. */
29
+ export declare const ALL_KEY = "all";
30
+ export type SendVerdict = {
31
+ ok: true;
32
+ delivered: string[];
33
+ spent: number;
34
+ remaining: number;
35
+ } | {
36
+ ok: false;
37
+ reason: 'unknown_recipient';
38
+ recipients: string[];
39
+ } | {
40
+ ok: false;
41
+ reason: 'agent_quota';
42
+ used: number;
43
+ max: number;
44
+ } | {
45
+ ok: false;
46
+ reason: 'dispatch_quota';
47
+ used: number;
48
+ max: number;
49
+ } | {
50
+ ok: false;
51
+ reason: 'too_soon';
52
+ retryInSeconds: number;
53
+ };
54
+ /** Why `team_wait` was refused before it ever blocked (F-3). */
55
+ export type WaitRefusal = {
56
+ reason: 'no_peers';
57
+ } | {
58
+ reason: 'unknown_sender';
59
+ asked: string;
60
+ peers: string[];
61
+ } | {
62
+ reason: 'all_finished';
63
+ who: string[];
64
+ } | {
65
+ reason: 'all_blocked';
66
+ who: string[];
67
+ };
68
+ export interface TeamBusOptions {
69
+ /** Injectable clock so the interval rule is testable without real waiting. */
70
+ now?: () => number;
71
+ /** Called once per delivered message, for the `TeamEvent` stream and the log. */
72
+ onMessage?: (message: TeamMessage) => void;
73
+ /**
74
+ * Whether `label` still has a loop that could call `team_send`.
75
+ *
76
+ * Optional and defaulting to `() => true`, so every existing construction site
77
+ * and every existing test keeps its current behaviour exactly. `TeamRuntime`
78
+ * supplies the real answer from its live handles, and it is a NEGATIVE
79
+ * predicate over TERMINAL phases: a `queued` child has not started yet and
80
+ * will, so "the phase is running" - the obvious implementation - would refuse
81
+ * a wait on children 4 and 5 of a five-way dispatch at the shipped defaults.
82
+ */
83
+ canSend?: (label: string) => boolean;
84
+ }
85
+ export declare class TeamBus {
86
+ private readonly labels;
87
+ private readonly mailboxes;
88
+ private readonly waiters;
89
+ private readonly sentBy;
90
+ private readonly lastSentAt;
91
+ private readonly blocked;
92
+ private readonly lead;
93
+ private readonly now;
94
+ private readonly onMessage?;
95
+ private readonly canSend;
96
+ private total;
97
+ private last?;
98
+ constructor(labels: string[], options?: TeamBusOptions);
99
+ /** Every addressable participant, in dispatch order, with the lead last. */
100
+ participants(): string[];
101
+ /** Sibling labels for the `<subagent_role>` block. */
102
+ peersOf(label: string): string[];
103
+ /** Messages addressed to `lead`, for the report's own section (§3.7). */
104
+ leadMail(): TeamMessage[];
105
+ messageCount(): number;
106
+ lastMessage(): TeamMessage | undefined;
107
+ sentCount(label: string): number;
108
+ /**
109
+ * Canonical label for a model-supplied `from`, or `undefined` (P1-3).
110
+ *
111
+ * PUBLIC, because `makeTeamWait` has to hand the SAME string to
112
+ * `checkWaitable` and to `wait()`. `wait()` and `deliverToWaiter` compare
113
+ * `m.from === opts.from` EXACTLY, so a caller that gate-checks `"A2"`
114
+ * case-insensitively and then passes `"A2"` down would wait the full timeout
115
+ * for a message the delivery filter can never match.
116
+ */
117
+ resolveLabel(raw: string): string | undefined;
118
+ /** `team_wait` calls refused as unanswerable, per label (F-3). */
119
+ recordBlockedWait(label: string): void;
120
+ blockedWaitCount(label: string): number;
121
+ /**
122
+ * Spend quota and deliver.
123
+ *
124
+ * Refusal ORDER is deliberate: the permanent conditions are reported before
125
+ * the temporary one. Telling a child to "try again in 9s" when its quota is
126
+ * already spent sends it back for a second refusal it cannot act on.
127
+ */
128
+ send(from: string, to: string, subjectRaw: string, bodyRaw: string): SendVerdict;
129
+ private resolveRecipients;
130
+ private waiterFor;
131
+ /**
132
+ * Decide whether waiting could possibly pay off (F-3).
133
+ *
134
+ * TAKES `timeoutMs`, NOT `deadlineAt` (P1-1). The deadline is derived here,
135
+ * from the one clock this class has, so it is comparable with every registered
136
+ * `Waiter.deadlineAt`.
137
+ *
138
+ * PURE: no counters, no mutation, no waiter registration. `makeTeamWait`
139
+ * records the refusal, because a predicate with a counter inside it is a
140
+ * predicate people stop trusting (D-6).
141
+ *
142
+ * BIASED TOWARD PERMITTING (D-16). Every branch that cannot be decided returns
143
+ * `null`. A wait that should have been refused costs the child seconds it can
144
+ * see; a refusal that should have been a wait destroys a result the child
145
+ * cannot see was ever possible. The asymmetry is total, so the bias is total.
146
+ */
147
+ checkWaitable(key: string, opts: {
148
+ from?: string;
149
+ timeoutMs: number;
150
+ }): WaitRefusal | null;
151
+ /**
152
+ * Shrink `cannotAct` to its fixpoint, in place (P0-3).
153
+ *
154
+ * Everyone acceptable being stuck is NOT yet a deadlock proof, because a
155
+ * blocked peer can be released EARLY by a third party: `a` waits on `b`, `b`
156
+ * waits on `c`, `c` messages `b` at t=10, `b` resumes and messages `a`. A
157
+ * deadline comparison alone refuses `a` at t=0 and throws that outcome away.
158
+ *
159
+ * So a blocked peer stays in the set only while everyone who could wake it is
160
+ * also in it (or is the caller, who is about to block). If growth stops with
161
+ * an acceptable peer outside the set, that peer can still be woken and the
162
+ * wait must be permitted.
163
+ *
164
+ * Terminates because each pass either removes at least one member or stops. At
165
+ * ten participants the worst case is a hundred set lookups, once per
166
+ * `team_wait`, and `team_wait` is itself rate-limited by the message budget.
167
+ */
168
+ private closeCannotAct;
169
+ /** Take everything queued for `key`. Called by `withMailboxTail` (§3.6). */
170
+ drain(key: string): TeamMessage[];
171
+ /**
172
+ * Block until a matching message arrives, the signal aborts, or the deadline
173
+ * elapses. Resolves `null` on both non-delivery paths — from the model's point
174
+ * of view an abandoned wait and an expired one want the same guidance.
175
+ *
176
+ * THE CALLER PAUSES THE CHILD'S IDLE WATCHDOG around this (see
177
+ * `comm-tools.ts`). A deliberate wait is not a wedged agent, and the child
178
+ * emits nothing while it is here.
179
+ */
180
+ wait(key: string, opts: {
181
+ from?: string;
182
+ timeoutMs: number;
183
+ signal?: AbortSignal;
184
+ }): Promise<TeamMessage | null>;
185
+ /** Settle every outstanding wait with `null`. Called on abort and dispose. */
186
+ cancelAllWaits(): void;
187
+ private deliverToWaiter;
188
+ }
189
+ /** Render queued mail as the `<team_mail>` block appended to a tool result. */
190
+ export declare function renderMailBlock(messages: TeamMessage[]): string;