@aragon-agent/cli 0.6.57 → 0.6.58

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 (85) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +159 -3
  3. package/dist/agent/controller.d.ts +112 -1
  4. package/dist/agent/controller.js +350 -7
  5. package/dist/agent/project-guidance-prompt.js +97 -97
  6. package/dist/agent/redteam-prompt.d.ts +29 -11
  7. package/dist/agent/redteam-prompt.js +118 -103
  8. package/dist/agent/redteam-wiring.d.ts +117 -2
  9. package/dist/agent/redteam-wiring.js +204 -1
  10. package/dist/agent/team-notices.d.ts +68 -0
  11. package/dist/agent/team-notices.js +82 -0
  12. package/dist/app/App.js +208 -5
  13. package/dist/app/use-redteam-mode.d.ts +1 -1
  14. package/dist/app/use-redteam-mode.js +14 -1
  15. package/dist/cli.js +13 -0
  16. package/dist/commands/catalog.js +6 -2
  17. package/dist/commands/redteam-command.d.ts +14 -8
  18. package/dist/commands/redteam-command.js +243 -12
  19. package/dist/commands/team-command.js +93 -2
  20. package/dist/config/app-paths.d.ts +19 -0
  21. package/dist/config/app-paths.js +23 -0
  22. package/dist/config/load.d.ts +8 -0
  23. package/dist/gene/catalog-sync.js +37 -16
  24. package/dist/gene/curator/budget.js +1 -1
  25. package/dist/gene/curator/curator.d.ts +6 -0
  26. package/dist/gene/curator/curator.js +8 -0
  27. package/dist/gene/curator/task-runner.js +4 -1
  28. package/dist/gene/curator/tools-verify.js +17 -5
  29. package/dist/gene/curator/validate/evidence-tokens.js +97 -18
  30. package/dist/gene/curator/validate/knowledge.d.ts +5 -0
  31. package/dist/gene/curator/validate/knowledge.js +57 -13
  32. package/dist/gene/curator/validate/types.d.ts +6 -1
  33. package/dist/gene/learn/learn-prompt.d.ts +10 -1
  34. package/dist/gene/learn/learn-prompt.js +11 -2
  35. package/dist/governance/engine/lifecycle.js +1 -1
  36. package/dist/governance/store/run-lock.d.ts +9 -2
  37. package/dist/governance/store/run-lock.js +91 -7
  38. package/dist/host/controller-factory.d.ts +13 -0
  39. package/dist/host/controller-factory.js +7 -0
  40. package/dist/host/index.d.ts +1 -0
  41. package/dist/host/index.js +1 -0
  42. package/dist/host/interaction.d.ts +19 -0
  43. package/dist/host/interaction.js +75 -0
  44. package/dist/host/team-control.d.ts +83 -0
  45. package/dist/host/team-control.js +55 -0
  46. package/dist/logging/install.d.ts +32 -1
  47. package/dist/logging/install.js +21 -0
  48. package/dist/proc/output-streams.d.ts +11 -0
  49. package/dist/proc/output-streams.js +11 -0
  50. package/dist/redteam/prompt-resolve.d.ts +61 -0
  51. package/dist/redteam/prompt-resolve.js +303 -0
  52. package/dist/redteam/prompt-store.d.ts +96 -0
  53. package/dist/redteam/prompt-store.js +156 -0
  54. package/dist/redteam/prompt-template.d.ts +22 -0
  55. package/dist/redteam/prompt-template.js +72 -0
  56. package/dist/team/bus.d.ts +18 -0
  57. package/dist/team/bus.js +70 -18
  58. package/dist/team/console-tools.d.ts +54 -0
  59. package/dist/team/console-tools.js +333 -0
  60. package/dist/team/console-view.d.ts +88 -0
  61. package/dist/team/console-view.js +173 -0
  62. package/dist/team/forced-mode.d.ts +61 -1
  63. package/dist/team/forced-mode.js +75 -0
  64. package/dist/team/normalize.d.ts +31 -0
  65. package/dist/team/normalize.js +49 -5
  66. package/dist/team/notices.d.ts +95 -0
  67. package/dist/team/notices.js +121 -0
  68. package/dist/team/pause-gate.d.ts +79 -0
  69. package/dist/team/pause-gate.js +127 -0
  70. package/dist/team/prompt.d.ts +25 -9
  71. package/dist/team/prompt.js +29 -29
  72. package/dist/team/report.js +33 -0
  73. package/dist/team/runtime.d.ts +270 -5
  74. package/dist/team/runtime.js +732 -64
  75. package/dist/team/settled.d.ts +5 -2
  76. package/dist/team/settled.js +12 -2
  77. package/dist/team/subagent.d.ts +7 -0
  78. package/dist/team/subagent.js +12 -1
  79. package/dist/team/task-tool.d.ts +39 -1
  80. package/dist/team/task-tool.js +75 -18
  81. package/dist/tools/bash-tool.d.ts +11 -8
  82. package/dist/tools/bash-tool.js +37 -9
  83. package/dist/tools/index.d.ts +2 -2
  84. package/dist/tools/index.js +30 -0
  85. package/package.json +3 -3
package/dist/team/bus.js CHANGED
@@ -70,6 +70,33 @@ export class TeamBus {
70
70
  sentCount(label) {
71
71
  return this.sentBy.get(label) ?? 0;
72
72
  }
73
+ /**
74
+ * Add a participant mid-dispatch (team-detached-dispatch section 5.2.6).
75
+ *
76
+ * `team_spawn` creates children after the first batch, and a late child that
77
+ * cannot be addressed would be a subagent its own siblings cannot message and
78
+ * whose mail nobody can send - a silent half-participant. `participants()` keeps
79
+ * the lead LAST, which is the order every bus consumer already assumes.
80
+ */
81
+ addParticipant(label) {
82
+ if (this.labels.includes(label))
83
+ return;
84
+ this.labels.push(label);
85
+ this.mailboxes.set(label, []);
86
+ }
87
+ /**
88
+ * Messages addressed to `lead` from `cursor` onward, for the live reminder path
89
+ * (section 5.2.3). `leadMail()` returns everything, which is what the REPORT
90
+ * wants; a relay that re-reported every message on every event would repeat
91
+ * itself once per notice.
92
+ */
93
+ leadMailSince(cursor) {
94
+ return this.lead.slice(Math.max(0, cursor));
95
+ }
96
+ /** How many messages have been addressed to `lead` so far (the relay's cursor). */
97
+ leadMailCount() {
98
+ return this.lead.length;
99
+ }
73
100
  /**
74
101
  * Canonical label for a model-supplied `from`, or `undefined` (P1-3).
75
102
  *
@@ -118,8 +145,13 @@ export class TeamBus {
118
145
  return { ok: false, reason: 'recipient_finished', who: addressed };
119
146
  }
120
147
  const used = this.sentCount(from);
121
- if (used + cost > TEAM_LIMITS.messagesPerAgent) {
122
- return { ok: false, reason: 'agent_quota', used, max: TEAM_LIMITS.messagesPerAgent };
148
+ // THE LEAD HAS ITS OWN CAP (section 5.2.3): it is the only participant that
149
+ // reacts to the user changing their mind mid-dispatch, and six corrections
150
+ // across a two-hour dispatch is too few. Everything else keeps
151
+ // `messagesPerAgent`.
152
+ const perSenderCap = from === LEAD_KEY ? TEAM_LIMITS.messagesFromLeadPerDispatch : TEAM_LIMITS.messagesPerAgent;
153
+ if (used + cost > perSenderCap) {
154
+ return { ok: false, reason: 'agent_quota', used, max: perSenderCap };
123
155
  }
124
156
  if (this.total + cost > TEAM_LIMITS.messagesPerDispatch) {
125
157
  return {
@@ -129,7 +161,17 @@ export class TeamBus {
129
161
  max: TEAM_LIMITS.messagesPerDispatch,
130
162
  };
131
163
  }
132
- const last = this.lastSentAt.get(from);
164
+ // THE RATE WINDOW IS KEYED DIFFERENTLY FOR THE LEAD (REV-17 / R15).
165
+ //
166
+ // A child's window makes chatter expensive, and its natural key is the sender:
167
+ // one child, one voice, one interval. The lead's window exists for a different
168
+ // reason - to stop it flooding ONE child - and a per-sender key would refuse
169
+ // the second and third message of a single decision the user made ("drop the
170
+ // bundle work, look at render instead"), which is precisely the moment the
171
+ // console exists for. So the lead's key is `lead:<recipient>`; every other
172
+ // sender keeps the plain sender key.
173
+ const windowKey = from === LEAD_KEY ? `${from}:${target}` : from;
174
+ const last = this.lastSentAt.get(windowKey);
133
175
  const now = this.now();
134
176
  if (last !== undefined && now - last < TEAM_LIMITS.minSendIntervalMs) {
135
177
  return {
@@ -143,17 +185,20 @@ export class TeamBus {
143
185
  const subject = subjectRaw.trim().slice(0, TEAM_LIMITS.subjectChars);
144
186
  const body = bodyRaw.trim().slice(0, TEAM_LIMITS.bodyChars);
145
187
  this.sentBy.set(from, used + cost);
146
- this.lastSentAt.set(from, now);
188
+ this.lastSentAt.set(windowKey, now);
147
189
  this.total += cost;
148
190
  for (const recipient of recipients) {
149
191
  const message = { from, to: recipient, subject, body, at: now };
150
192
  this.last = message;
151
193
  this.onMessage?.(message);
152
194
  if (recipient === LEAD_KEY) {
153
- // The lead is blocked inside `task` for the whole dispatch (§1.3), so
154
- // its mail is COLLECTED rather than delivered: it reaches the model in
155
- // the report, and the panel shows it live. Injecting it into the lead's
156
- // history mid-tool is what §1.3 rules out.
195
+ // The lead's mail is COLLECTED here rather than injected into its history
196
+ // mid-tool. That was the pre-feature rule because the lead was blocked
197
+ // inside `task` for the whole dispatch; with a detached dispatch the lead
198
+ // is idle between turns, so the SAME collection now also feeds a live
199
+ // reminder path (`agent/team-notices.ts`) and `team_status`'s mail line.
200
+ // Injection still belongs to the notice/steering machinery, not to this
201
+ // class - one delivery mechanism, not two.
157
202
  this.lead.push(message);
158
203
  continue;
159
204
  }
@@ -165,7 +210,10 @@ export class TeamBus {
165
210
  ok: true,
166
211
  delivered: recipients,
167
212
  spent: cost,
168
- remaining: Math.max(0, TEAM_LIMITS.messagesPerAgent - (used + cost)),
213
+ // THE SAME CAP THAT WAS JUST ENFORCED. A hard-coded `messagesPerAgent` here
214
+ // answered the lead's budget with the child budget (6 instead of 24) - wrong
215
+ // for every caller that reads `remaining` rather than recomputing it.
216
+ remaining: Math.max(0, perSenderCap - (used + cost)),
169
217
  };
170
218
  }
171
219
  resolveRecipients(from, target) {
@@ -210,11 +258,13 @@ export class TeamBus {
210
258
  let acceptable = peers;
211
259
  let want;
212
260
  if (opts.from !== undefined) {
213
- const canonical = this.resolveLabel(opts.from);
214
- // Covers a typo, `lead` (which never sends - its mail is collected for the
215
- // report and there is no `team_send` on a lead), and the caller's own
216
- // label. All three are "this wait can never be satisfied", and none of
217
- // them is "you have no teammates" (P1-2).
261
+ const asked = opts.from.trim().toLowerCase();
262
+ // THE LEAD IS A LEGAL SENDER NOW (team-detached-dispatch section 5.2.3): the
263
+ // console tools let it write to a child, so a child waiting for a lead reply
264
+ // is a wait that can be satisfied. The old reading - "lead never sends, so
265
+ // asking for it can never be satisfied" - was true before this feature and is
266
+ // now exactly wrong.
267
+ const canonical = asked === LEAD_KEY ? LEAD_KEY : this.resolveLabel(opts.from);
218
268
  if (canonical === undefined || canonical === key) {
219
269
  return { reason: 'unknown_sender', asked: opts.from.trim(), peers };
220
270
  }
@@ -281,10 +331,12 @@ export class TeamBus {
281
331
  continue;
282
332
  }
283
333
  // Who could release `p`? Its own acceptable senders - and `peersOf`, NOT
284
- // `participants`, because the lead is never a sender. Using
285
- // `participants` here would put `lead` in every from-less waiter's waker
286
- // set, `lead` is never in `cannotAct`, and `all_blocked` would become
287
- // unreachable for exactly the from-less waits it was written for.
334
+ // `participants`, because `participants` includes `lead`, which would put the
335
+ // lead in every from-less waiter's waker set. The lead is never in
336
+ // `cannotAct` (it runs no loop here), so `all_blocked` would become
337
+ // unreachable for exactly the from-less waits it was written for. The lead
338
+ // CAN send now (`sendFromLead`); that changes which messages arrive, not who
339
+ // counts as a peer for this reachability argument.
288
340
  const wakers = w.from ? [w.from] : this.peersOf(p);
289
341
  if (wakers.some((x) => x !== p && !cannotAct.has(x))) {
290
342
  cannotAct.delete(p);
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The seven LEAD-side control tools (team-detached-dispatch section 5.2).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan. The gate
5
+ * `docs/guide-doc` extracts tool names from THIS file with a line-anchored
6
+ * `name: '<tool>',` pattern, so each `name:` literal stays alone on its line.
7
+ *
8
+ * WHY THE LEAD NEEDS THESE AT ALL. Making the lead idle during a dispatch solves
9
+ * the queue problem and creates a responsibility: an idle lead that cannot look,
10
+ * steer or stop is just a lead that has been told to wait somewhere else. The
11
+ * console is the other half of the feature, and every tool here is a thin call
12
+ * into `TeamRuntime`'s public surface - no tool touches a handle, a bus or a
13
+ * phase. That is what keeps the audit (I-DD5) and the abort path (REV-03) single
14
+ * sourced.
15
+ *
16
+ * EVERY REFUSAL IS A NON-ERROR `textResult` (section 5.2.1). An `errorResult`
17
+ * reads to a model as a malfunction and invites an immediate retry, which is how
18
+ * a console turns into a loop. "No dispatch is running" is an ANSWER, and the
19
+ * wording says what to do instead.
20
+ *
21
+ * `team_collect` IS THE ONLY ONE THAT MAY WAIT, and even it must stop waiting the
22
+ * moment the user is owed an answer (I-DD2). It polls `hasPendingUserInput`, which
23
+ * the controller injects from the queue's own predicate - so "the lead is asleep
24
+ * while the user waits" is structurally impossible rather than merely unlikely.
25
+ */
26
+ import { type AgentTool } from '@aragon-agent/core';
27
+ import type { TeamControlBy } from '@aragon-agent/tui/model/team/types';
28
+ import type { TeamRuntime } from './runtime.js';
29
+ export interface ConsoleToolDeps {
30
+ runtime: TeamRuntime;
31
+ /**
32
+ * `controller.hasPendingUserMessages()` (I-DD2). The one signal `team_collect`
33
+ * must never miss: the lead waiting is acceptable, the USER waiting is not.
34
+ */
35
+ hasPendingUserInput: () => boolean;
36
+ /** Who is acting. `'lead'` for these tools; `'user'` for `/team` verbs. */
37
+ by?: TeamControlBy;
38
+ }
39
+ /** `team_status` - the read surface. */
40
+ export declare function makeTeamStatusTool(deps: ConsoleToolDeps): AgentTool;
41
+ /** `team_message` - steer a child, or all of them. */
42
+ export declare function makeTeamMessageTool(deps: ConsoleToolDeps): AgentTool;
43
+ /** `team_pause` - hold one child. */
44
+ export declare function makeTeamPauseTool(deps: ConsoleToolDeps): AgentTool;
45
+ /** `team_resume` - release one child, optionally with an instruction. */
46
+ export declare function makeTeamResumeTool(deps: ConsoleToolDeps): AgentTool;
47
+ /** `team_stop` - end one child or the whole dispatch. */
48
+ export declare function makeTeamStopTool(deps: ConsoleToolDeps): AgentTool;
49
+ /** `team_spawn` - add subagents to the dispatch that is already running. */
50
+ export declare function makeTeamSpawnTool(deps: ConsoleToolDeps): AgentTool;
51
+ /** `team_collect` - the one bounded wait, and it yields to the user. */
52
+ export declare function makeTeamCollectTool(deps: ConsoleToolDeps): AgentTool;
53
+ /** The seven tools, in the order the prompt block lists them. */
54
+ export declare function createConsoleTools(deps: ConsoleToolDeps): AgentTool[];
@@ -0,0 +1,333 @@
1
+ /**
2
+ * The seven LEAD-side control tools (team-detached-dispatch section 5.2).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan. The gate
5
+ * `docs/guide-doc` extracts tool names from THIS file with a line-anchored
6
+ * `name: '<tool>',` pattern, so each `name:` literal stays alone on its line.
7
+ *
8
+ * WHY THE LEAD NEEDS THESE AT ALL. Making the lead idle during a dispatch solves
9
+ * the queue problem and creates a responsibility: an idle lead that cannot look,
10
+ * steer or stop is just a lead that has been told to wait somewhere else. The
11
+ * console is the other half of the feature, and every tool here is a thin call
12
+ * into `TeamRuntime`'s public surface - no tool touches a handle, a bus or a
13
+ * phase. That is what keeps the audit (I-DD5) and the abort path (REV-03) single
14
+ * sourced.
15
+ *
16
+ * EVERY REFUSAL IS A NON-ERROR `textResult` (section 5.2.1). An `errorResult`
17
+ * reads to a model as a malfunction and invites an immediate retry, which is how
18
+ * a console turns into a loop. "No dispatch is running" is an ANSWER, and the
19
+ * wording says what to do instead.
20
+ *
21
+ * `team_collect` IS THE ONLY ONE THAT MAY WAIT, and even it must stop waiting the
22
+ * moment the user is owed an answer (I-DD2). It polls `hasPendingUserInput`, which
23
+ * the controller injects from the queue's own predicate - so "the lead is asleep
24
+ * while the user waits" is structurally impossible rather than merely unlikely.
25
+ */
26
+ import { textResult } from '@aragon-agent/core';
27
+ import { TEAM_LIMITS } from '@aragon-agent/tui/model/team/limits';
28
+ import { renderPauseResult, renderResumeResult, renderSendResult, renderSpawnResult, renderStopResult, renderTeamStatus, } from './console-view.js';
29
+ const NO_DISPATCH = 'No team dispatch is running. Use task to start one.';
30
+ /** A string field, trimmed, or `''`. Shape repair belongs here, not in the schema. */
31
+ function str(value) {
32
+ return typeof value === 'string' ? value.trim() : '';
33
+ }
34
+ function num(value) {
35
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
36
+ }
37
+ /** `team_status` - the read surface. */
38
+ export function makeTeamStatusTool(deps) {
39
+ return {
40
+ name: 'team_status',
41
+ label: 'Team status',
42
+ description: 'Show the running team: each subagent\'s phase, how long it has run, its turns and ' +
43
+ 'tool calls, who paused it, the dispatch ceiling and any mail the children sent you. ' +
44
+ 'Use it to answer "how is it going" and to decide who needs a message or a pause. ' +
45
+ 'Set includeSummary for the settled children\'s own reports.',
46
+ parameters: {
47
+ type: 'object',
48
+ properties: {
49
+ labels: {
50
+ type: 'array',
51
+ items: { type: 'string' },
52
+ description: 'Only these subagent labels. Omit for the whole roster.',
53
+ },
54
+ includeSummary: {
55
+ type: 'boolean',
56
+ default: false,
57
+ description: 'Also show each settled child\'s summary (bounded).',
58
+ },
59
+ },
60
+ },
61
+ async execute(_id, params) {
62
+ const inspection = deps.runtime.inspect();
63
+ if (inspection === null)
64
+ return textResult(NO_DISPATCH);
65
+ const p = params;
66
+ const labels = Array.isArray(p.labels)
67
+ ? p.labels.filter((label) => typeof label === 'string')
68
+ : undefined;
69
+ return textResult(renderTeamStatus(inspection, {
70
+ ...(labels !== undefined ? { labels } : {}),
71
+ includeSummary: p.includeSummary === true,
72
+ }));
73
+ },
74
+ };
75
+ }
76
+ /** `team_message` - steer a child, or all of them. */
77
+ export function makeTeamMessageTool(deps) {
78
+ return {
79
+ name: 'team_message',
80
+ label: 'Message subagents',
81
+ description: 'Send one short instruction to a subagent (or "all"). Use it when the user changes ' +
82
+ 'the goal, or when a child is heading the wrong way - not for status updates. ' +
83
+ 'The message also reaches a child that is mid-request (interrupt, default on) at its ' +
84
+ 'next safe point. You have ' +
85
+ `${TEAM_LIMITS.messagesFromLeadPerDispatch} messages per dispatch.`,
86
+ parameters: {
87
+ type: 'object',
88
+ required: ['to', 'body'],
89
+ properties: {
90
+ to: { type: 'string', description: 'A subagent label, or "all".' },
91
+ subject: { type: 'string', description: `<= ${TEAM_LIMITS.subjectChars} chars.` },
92
+ body: { type: 'string', description: `<= ${TEAM_LIMITS.bodyChars} chars.` },
93
+ interrupt: {
94
+ type: 'boolean',
95
+ default: true,
96
+ description: 'Also steer the child at its next safe point, not only on its next tool result.',
97
+ },
98
+ },
99
+ },
100
+ async execute(_id, params) {
101
+ const p = params;
102
+ const to = str(p.to);
103
+ const body = str(p.body);
104
+ if (to.length === 0 || body.length === 0) {
105
+ return textResult('Not sent: team_message needs a "to" and a "body".');
106
+ }
107
+ const verdict = deps.runtime.sendFromLead(to, body, {
108
+ ...(str(p.subject).length > 0 ? { subject: str(p.subject) } : {}),
109
+ interrupt: p.interrupt !== false,
110
+ ...(deps.by !== undefined ? { by: deps.by } : {}),
111
+ });
112
+ if (!verdict.ok)
113
+ return textResult(`Not sent: ${verdict.why}.`);
114
+ return textResult(renderSendResult(verdict.delivered, verdict.remaining));
115
+ },
116
+ };
117
+ }
118
+ /** `team_pause` - hold one child. */
119
+ export function makeTeamPauseTool(deps) {
120
+ return {
121
+ name: 'team_pause',
122
+ label: 'Pause subagent',
123
+ description: 'Hold one subagent so its next tool does not start. Pausing is cooperative: a child ' +
124
+ 'that is mid-tool or mid-sentence stops at the next boundary, not instantly. It stays ' +
125
+ 'paused until team_resume or team_stop - nothing resumes it automatically.',
126
+ parameters: {
127
+ type: 'object',
128
+ required: ['label'],
129
+ properties: {
130
+ label: { type: 'string', description: 'The subagent label.' },
131
+ reason: { type: 'string', description: 'Why, for the report. Keep it short.' },
132
+ },
133
+ },
134
+ async execute(_id, params) {
135
+ const p = params;
136
+ const label = str(p.label);
137
+ if (label.length === 0)
138
+ return textResult('team_pause needs a "label".');
139
+ const by = deps.by ?? 'lead';
140
+ const result = deps.runtime.pauseChild(label, by, str(p.reason));
141
+ if ('why' in result)
142
+ return textResult(`Not paused: ${result.why}.`);
143
+ return textResult(renderPauseResult(label, result.effect, by));
144
+ },
145
+ };
146
+ }
147
+ /** `team_resume` - release one child, optionally with an instruction. */
148
+ export function makeTeamResumeTool(deps) {
149
+ return {
150
+ name: 'team_resume',
151
+ label: 'Resume subagent',
152
+ description: 'Release a subagent held by team_pause and let it continue from where it stopped. ' +
153
+ 'A "message" is steered into it as it resumes, which is the cheapest way to redirect ' +
154
+ 'a child you paused earlier.',
155
+ parameters: {
156
+ type: 'object',
157
+ required: ['label'],
158
+ properties: {
159
+ label: { type: 'string' },
160
+ message: { type: 'string', description: 'What to tell it as it resumes.' },
161
+ },
162
+ },
163
+ async execute(_id, params) {
164
+ const p = params;
165
+ const label = str(p.label);
166
+ if (label.length === 0)
167
+ return textResult('team_resume needs a "label".');
168
+ const message = str(p.message);
169
+ const result = deps.runtime.resumeChild(label, deps.by ?? 'lead', message);
170
+ if (!result.ok)
171
+ return textResult(`Not resumed: ${result.why}.`);
172
+ return textResult(renderResumeResult(label, result.effect, message.length > 0));
173
+ },
174
+ };
175
+ }
176
+ /** `team_stop` - end one child or the whole dispatch. */
177
+ export function makeTeamStopTool(deps) {
178
+ return {
179
+ name: 'team_stop',
180
+ label: 'Stop subagents',
181
+ description: 'End one subagent, or the whole dispatch with "all". A stopped child is recorded as ' +
182
+ 'aborted and its partial work stays in the report. This is also the only way to end a ' +
183
+ 'dispatch that someone else started, so it is what you use when the user asks you to stop.',
184
+ parameters: {
185
+ type: 'object',
186
+ required: ['label'],
187
+ properties: {
188
+ label: { type: 'string', description: 'A label, or "all".' },
189
+ reason: { type: 'string' },
190
+ },
191
+ },
192
+ async execute(_id, params) {
193
+ const p = params;
194
+ const label = str(p.label);
195
+ if (label.length === 0)
196
+ return textResult('team_stop needs a "label", or "all".');
197
+ const done = deps.runtime.stopChild(label.toLowerCase() === 'all' ? 'all' : label, deps.by ?? 'lead', str(p.reason));
198
+ if (done.stopped.length === 0 && done.live.length === 0)
199
+ return textResult(NO_DISPATCH);
200
+ return textResult(renderStopResult(done.stopped, done.live, done.unknown === true ? { unknownLabel: label } : {}));
201
+ },
202
+ };
203
+ }
204
+ /** `team_spawn` - add subagents to the dispatch that is already running. */
205
+ export function makeTeamSpawnTool(deps) {
206
+ return {
207
+ name: 'team_spawn',
208
+ label: 'Add subagents',
209
+ description: 'Add one or more subagents to the team that is already running - for work the first ' +
210
+ 'briefs did not cover. The same total ceiling applies (' +
211
+ `${TEAM_LIMITS.hardMaxSubagents} at most), so a full dispatch must free a slot first. ` +
212
+ 'Each spec needs a description and a self-contained prompt, exactly like task.',
213
+ parameters: {
214
+ type: 'object',
215
+ required: ['subagents'],
216
+ properties: {
217
+ subagents: {
218
+ type: 'array',
219
+ items: {
220
+ type: 'object',
221
+ required: ['description', 'prompt'],
222
+ properties: {
223
+ label: { type: 'string', description: `Short id, <= ${TEAM_LIMITS.labelChars} chars.` },
224
+ description: { type: 'string', description: `<= ${TEAM_LIMITS.descriptionChars} chars.` },
225
+ prompt: { type: 'string', description: 'The full brief. Self-contained.' },
226
+ readOnly: { type: 'boolean', default: false },
227
+ },
228
+ },
229
+ },
230
+ reason: { type: 'string' },
231
+ },
232
+ },
233
+ async execute(_id, params) {
234
+ const p = params;
235
+ const result = deps.runtime.addSpecs(p.subagents, deps.by ?? 'lead', str(p.reason));
236
+ if ('why' in result)
237
+ return textResult(`Not added: ${result.why}.`);
238
+ return textResult(renderSpawnResult(result.added, result.dropped, result.requested));
239
+ },
240
+ };
241
+ }
242
+ /** `team_collect` - the one bounded wait, and it yields to the user. */
243
+ export function makeTeamCollectTool(deps) {
244
+ return {
245
+ name: 'team_collect',
246
+ label: 'Collect team report',
247
+ description: 'Wait a bounded moment for the dispatch to finish, then return its report. Use it only ' +
248
+ 'when you cannot answer without the result - the report arrives on its own when the team ' +
249
+ 'finishes. It returns immediately if you already have it, and it stops waiting the moment ' +
250
+ 'the user sends you something.',
251
+ parameters: {
252
+ type: 'object',
253
+ properties: {
254
+ timeoutSeconds: {
255
+ type: 'number',
256
+ description: `${TEAM_LIMITS.waitMinSeconds}..${TEAM_LIMITS.waitMaxSeconds}, default ` +
257
+ `${TEAM_LIMITS.waitDefaultSeconds}.`,
258
+ },
259
+ },
260
+ },
261
+ async execute(_id, params) {
262
+ const p = params;
263
+ const requested = num(p.timeoutSeconds) ?? TEAM_LIMITS.waitDefaultSeconds;
264
+ const seconds = Math.min(TEAM_LIMITS.waitMaxSeconds, Math.max(TEAM_LIMITS.waitMinSeconds, Math.round(requested)));
265
+ const startId = deps.runtime.currentDispatchId();
266
+ if (startId === null)
267
+ return textResult(NO_DISPATCH);
268
+ if (deps.runtime.live() === null) {
269
+ const report = deps.runtime.reportText(startId);
270
+ if (report === undefined)
271
+ return textResult(NO_DISPATCH);
272
+ return textResult(`settled: true\n\n${report}`);
273
+ }
274
+ const waited = await waitForSettle(deps, startId, seconds * 1000);
275
+ const report = deps.runtime.reportText(startId);
276
+ if (waited === 'settled' && report !== undefined) {
277
+ return textResult(`settled: true\n\n${report}`);
278
+ }
279
+ const inspection = deps.runtime.inspect();
280
+ const counts = inspection?.counts;
281
+ const state = counts === undefined
282
+ ? 'the dispatch is no longer live'
283
+ : `${counts.running} running, ${counts.queued} waiting, ${counts.paused} paused, ` +
284
+ `${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.`;
288
+ return textResult(`settled: false\n${why}`);
289
+ },
290
+ };
291
+ }
292
+ /**
293
+ * Poll until the dispatch leaves the live state, the budget elapses, or the user
294
+ * is owed an answer (I-DD2).
295
+ *
296
+ * POLLING IS THE DESIGN, not a shortcut: "did the user type something?" has no
297
+ * subscription point on the controller, and `TEAM_LIMITS.collectPollMs` (250 ms)
298
+ * costs nothing measurable in a tool the model is expected to use rarely.
299
+ */
300
+ function waitForSettle(deps, dispatchId, budgetMs) {
301
+ return new Promise((resolve) => {
302
+ const startedAt = Date.now();
303
+ const tick = () => {
304
+ if (deps.hasPendingUserInput()) {
305
+ resolve('user_message');
306
+ return;
307
+ }
308
+ if (deps.runtime.live() === null || deps.runtime.currentDispatchId() !== dispatchId) {
309
+ resolve('settled');
310
+ return;
311
+ }
312
+ if (Date.now() - startedAt >= budgetMs) {
313
+ resolve('timeout');
314
+ return;
315
+ }
316
+ const timer = setTimeout(tick, TEAM_LIMITS.collectPollMs);
317
+ timer.unref?.();
318
+ };
319
+ tick();
320
+ });
321
+ }
322
+ /** The seven tools, in the order the prompt block lists them. */
323
+ export function createConsoleTools(deps) {
324
+ return [
325
+ makeTeamStatusTool(deps),
326
+ makeTeamMessageTool(deps),
327
+ makeTeamPauseTool(deps),
328
+ makeTeamResumeTool(deps),
329
+ makeTeamStopTool(deps),
330
+ makeTeamSpawnTool(deps),
331
+ makeTeamCollectTool(deps),
332
+ ];
333
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `console-view.ts` - how the lead console renders a dispatch as TEXT
3
+ * (team-detached-dispatch section 5.2, "one question, one formatter").
4
+ *
5
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
6
+ *
7
+ * PURE: it takes the runtime's `DispatchInspection` and returns a string. Both
8
+ * `team_status` (a model-facing tool result), `/team status` (a user-facing
9
+ * command result) and the desktop control surface read THIS file, which is what
10
+ * keeps the three from describing the same dispatch in three different ways - the
11
+ * `childStatus` rule of the UI, applied to text.
12
+ *
13
+ * EVERY BLOCK IS BYTE-BOUNDED at `TEAM_LIMITS.statusMaxBytes`: a status read is
14
+ * paid for on every poll the model chooses to make, and an unbounded roster with
15
+ * ten children each carrying a 6 000-byte summary is a context leak with a
16
+ * helpful name.
17
+ */
18
+ import type { DispatchInspection } from './runtime.js';
19
+ /**
20
+ * The host-facing control contract (team-detached-dispatch section 7.3).
21
+ *
22
+ * DEFINED HERE, IN THE PURE FILE, and not in `host/team-control.ts`, because the
23
+ * controller needs the request type too and `host -> agent -> host` would be a
24
+ * cycle. Nothing here knows what a controller is: it is a request shape and a
25
+ * view shape, which is exactly what a desktop button sends and renders.
26
+ */
27
+ export type TeamControlRequest = {
28
+ action: 'message';
29
+ to: string;
30
+ body: string;
31
+ interrupt?: boolean;
32
+ } | {
33
+ action: 'pause';
34
+ label: string;
35
+ reason?: string;
36
+ } | {
37
+ action: 'resume';
38
+ label: string;
39
+ message?: string;
40
+ } | {
41
+ action: 'stop';
42
+ label: string;
43
+ reason?: string;
44
+ } | {
45
+ action: 'spawn';
46
+ brief: string;
47
+ count: number;
48
+ };
49
+ /** `12m04s` / `41s` - one duration format, the one the panel already uses. */
50
+ export declare function formatElapsed(ms: number): string;
51
+ /**
52
+ * `team_status`: conclusion first, detail after (section 5.2.2).
53
+ *
54
+ * The four blocks are, in order: the header line (which answers "is anything
55
+ * happening, how long, and will anything stop it"), the roster, the mail and
56
+ * control counters, and optionally the settled summaries.
57
+ */
58
+ export declare function renderTeamStatus(inspection: DispatchInspection, options?: {
59
+ labels?: string[];
60
+ includeSummary?: boolean;
61
+ }): string;
62
+ /**
63
+ * The `/team stop`-shaped answer: what happened, to whom, and what is still alive.
64
+ *
65
+ * Non-error on purpose: a control action that found nothing to do ("that child
66
+ * had already finished") is information, and an `errorResult` would invite a
67
+ * retry of an operation that is already complete.
68
+ */
69
+ export declare function renderStopResult(stopped: string[], live: string[], options?: {
70
+ unknownLabel?: string;
71
+ }): string;
72
+ /**
73
+ * The `team_pause` answer, whose whole job is to be HONEST about cooperative
74
+ * pausing (section 5.2.4's table, in words).
75
+ */
76
+ export declare function renderPauseResult(label: string, effect: 'paused' | 'deferred' | 'finished', by: 'lead' | 'user' | 'supervisor'): string;
77
+ /**
78
+ * The `team_message` / `/team send` answer.
79
+ *
80
+ * ONE AUTHOR FOR BOTH SURFACES (section 5.8's last rule): the lead's tool result and
81
+ * the user's command report the same facts in the same words, so a user who saw the
82
+ * model send a message reads the identical receipt when they send one themselves.
83
+ */
84
+ export declare function renderSendResult(delivered: string[], remaining: number): string;
85
+ /** The `team_resume` / `/team resume` answer. */
86
+ export declare function renderResumeResult(label: string, effect: 'resumed' | 'was-running', withMessage: boolean): string;
87
+ /** The `team_spawn` / `/team spawn` answer, truncation included (AC-9). */
88
+ export declare function renderSpawnResult(added: string[], dropped: number, requested: number): string;