@aragon-agent/cli 0.6.56 → 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 (97) hide show
  1. package/CHANGELOG.md +94 -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/recheck.js +2 -1
  28. package/dist/gene/curator/task-runner.js +4 -1
  29. package/dist/gene/curator/tool-support.js +16 -7
  30. package/dist/gene/curator/tools-verify.js +54 -1
  31. package/dist/gene/curator/tools-write.js +41 -1
  32. package/dist/gene/curator/validate/evidence-tokens.d.ts +7 -19
  33. package/dist/gene/curator/validate/evidence-tokens.js +174 -17
  34. package/dist/gene/curator/validate/knowledge.d.ts +22 -1
  35. package/dist/gene/curator/validate/knowledge.js +108 -25
  36. package/dist/gene/curator/validate/live-check.js +7 -1
  37. package/dist/gene/curator/validate/prompts.js +7 -3
  38. package/dist/gene/curator/validate/types.d.ts +6 -1
  39. package/dist/gene/learn/learn-call.d.ts +58 -5
  40. package/dist/gene/learn/learn-call.js +38 -30
  41. package/dist/gene/learn/learn-prompt.d.ts +18 -2
  42. package/dist/gene/learn/learn-prompt.js +29 -11
  43. package/dist/gene/learn/learner.d.ts +6 -0
  44. package/dist/gene/learn/learner.js +31 -9
  45. package/dist/gene/learn/proposal-build.js +2 -6
  46. package/dist/gene/wiring-models.js +4 -1
  47. package/dist/governance/engine/lifecycle.js +1 -1
  48. package/dist/governance/store/run-lock.d.ts +9 -2
  49. package/dist/governance/store/run-lock.js +91 -7
  50. package/dist/host/controller-factory.d.ts +13 -0
  51. package/dist/host/controller-factory.js +7 -0
  52. package/dist/host/index.d.ts +1 -0
  53. package/dist/host/index.js +1 -0
  54. package/dist/host/interaction.d.ts +19 -0
  55. package/dist/host/interaction.js +75 -0
  56. package/dist/host/team-control.d.ts +83 -0
  57. package/dist/host/team-control.js +55 -0
  58. package/dist/logging/install.d.ts +32 -1
  59. package/dist/logging/install.js +21 -0
  60. package/dist/proc/output-streams.d.ts +11 -0
  61. package/dist/proc/output-streams.js +11 -0
  62. package/dist/redteam/prompt-resolve.d.ts +61 -0
  63. package/dist/redteam/prompt-resolve.js +303 -0
  64. package/dist/redteam/prompt-store.d.ts +96 -0
  65. package/dist/redteam/prompt-store.js +156 -0
  66. package/dist/redteam/prompt-template.d.ts +22 -0
  67. package/dist/redteam/prompt-template.js +72 -0
  68. package/dist/team/bus.d.ts +18 -0
  69. package/dist/team/bus.js +70 -18
  70. package/dist/team/console-tools.d.ts +54 -0
  71. package/dist/team/console-tools.js +333 -0
  72. package/dist/team/console-view.d.ts +88 -0
  73. package/dist/team/console-view.js +173 -0
  74. package/dist/team/forced-mode.d.ts +61 -1
  75. package/dist/team/forced-mode.js +75 -0
  76. package/dist/team/normalize.d.ts +31 -0
  77. package/dist/team/normalize.js +49 -5
  78. package/dist/team/notices.d.ts +95 -0
  79. package/dist/team/notices.js +121 -0
  80. package/dist/team/pause-gate.d.ts +79 -0
  81. package/dist/team/pause-gate.js +127 -0
  82. package/dist/team/prompt.d.ts +25 -9
  83. package/dist/team/prompt.js +29 -29
  84. package/dist/team/report.js +33 -0
  85. package/dist/team/runtime.d.ts +270 -5
  86. package/dist/team/runtime.js +732 -64
  87. package/dist/team/settled.d.ts +5 -2
  88. package/dist/team/settled.js +12 -2
  89. package/dist/team/subagent.d.ts +7 -0
  90. package/dist/team/subagent.js +12 -1
  91. package/dist/team/task-tool.d.ts +39 -1
  92. package/dist/team/task-tool.js +75 -18
  93. package/dist/tools/bash-tool.d.ts +11 -8
  94. package/dist/tools/bash-tool.js +37 -9
  95. package/dist/tools/index.d.ts +2 -2
  96. package/dist/tools/index.js +30 -0
  97. package/package.json +3 -3
@@ -28,6 +28,7 @@
28
28
  * the first `-n=6` someone tried.
29
29
  */
30
30
  import { parseSubagentArgs } from './forced-dispatch.js';
31
+ import { TEAM_LIMITS } from '@aragon-agent/tui/model/team/limits';
31
32
  /**
32
33
  * The default count when the user names none (D-7).
33
34
  *
@@ -37,6 +38,80 @@ import { parseSubagentArgs } from './forced-dispatch.js';
37
38
  * user who wants the widest fan-out knows which flag to add.
38
39
  */
39
40
  export const DEFAULT_FORCED_COUNT = 4;
41
+ /**
42
+ * Parse a line as a control verb, or `null` when it is (still) a brief.
43
+ *
44
+ * THE AMBIGUITY RULE IS THE WHOLE FUNCTION (REV-14 / AC-24). Every one of these
45
+ * verbs is a perfectly good English word, and `/team stop the leak hunt` dispatches
46
+ * a team TODAY. Turning that sentence into "stop the team and never work on the
47
+ * leak hunt" would be a silent breaking change, so a verb only becomes a control
48
+ * when the token after it PROVES the intent:
49
+ *
50
+ * - the second token is `all`, or a label that exists in the LIVE dispatch;
51
+ * - or, for `wait` / `spawn`, it is a number (and for `wait`, absent is fine).
52
+ *
53
+ * Everything else falls through to the brief grammar, unchanged - which is why
54
+ * `/team stop the leak hunt` still dispatches, and `/team "stop all"` still works
55
+ * through the existing quote escape (checked by the caller BEFORE this function).
56
+ *
57
+ * `liveLabels` is passed in rather than read from the controller here: this is a
58
+ * pure parser, and a parser that reads global state is a parser nobody can test.
59
+ */
60
+ export function readTeamControlIntent(raw, liveLabels) {
61
+ const trimmed = raw.trim();
62
+ if (trimmed.length === 0)
63
+ return null;
64
+ const tokens = trimmed.split(/\s+/);
65
+ const verb = tokens[0].toLowerCase();
66
+ const rest = tokens.slice(1);
67
+ const isTarget = (token) => token.toLowerCase() === 'all' || liveLabels.some((label) => label.toLowerCase() === token.toLowerCase());
68
+ if (verb === 'wait') {
69
+ if (rest.length === 0)
70
+ return { kind: 'control', action: 'wait' };
71
+ if (rest.length === 1 && /^[0-9]+$/.test(rest[0])) {
72
+ return { kind: 'control', action: 'wait', seconds: Math.min(Number(rest[0]), 1_000_000) };
73
+ }
74
+ // NO DIGITS -> A BRIEF. `/team wait for the build` is a request, not a pause.
75
+ return null;
76
+ }
77
+ if (verb === 'spawn') {
78
+ const count = rest[0];
79
+ if (count === undefined || !/^[1-9][0-9]*$/.test(count))
80
+ return null;
81
+ const brief = rest.slice(1).join(' ').trim().slice(0, TEAM_LIMITS.forcedBriefChars);
82
+ if (brief.length === 0)
83
+ return null;
84
+ return { kind: 'control', action: 'spawn', count: Number(count), brief };
85
+ }
86
+ if (verb === 'send') {
87
+ const target = rest[0];
88
+ if (target === undefined || !isTarget(target))
89
+ return null;
90
+ const text = rest.slice(1).join(' ').trim().slice(0, TEAM_LIMITS.bodyChars);
91
+ if (text.length === 0)
92
+ return null;
93
+ return { kind: 'control', action: 'send', target, text };
94
+ }
95
+ if (verb === 'pause' || verb === 'resume' || verb === 'stop') {
96
+ const target = rest[0];
97
+ if (target === undefined)
98
+ return null;
99
+ // `stop all` and `pause <live label>` only; anything else stays a brief.
100
+ if (!isTarget(target))
101
+ return null;
102
+ // `pause all` / `resume all` mean nothing (holding every child is `stop`), so
103
+ // they are refused as briefs rather than silently widening the grammar.
104
+ if (verb !== 'stop' && target.toLowerCase() === 'all')
105
+ return null;
106
+ const words = rest.slice(1).join(' ').trim();
107
+ if (verb === 'stop')
108
+ return { kind: 'control', action: 'stop', target, reason: words };
109
+ if (verb === 'pause')
110
+ return { kind: 'control', action: 'pause', label: target, reason: words };
111
+ return { kind: 'control', action: 'resume', label: target, message: words };
112
+ }
113
+ return null;
114
+ }
40
115
  /** The three words that command the session rather than describe work. */
41
116
  const CONTROL_WORDS = new Set(['on', 'off', 'status']);
42
117
  /**
@@ -45,6 +45,20 @@ export interface NormalizedSpecs {
45
45
  * this function stays a pure transformation.
46
46
  */
47
47
  export declare function toSlug(raw: unknown): string;
48
+ /**
49
+ * Make `label` unique within the dispatch, case-insensitively, by appending
50
+ * `-2`, `-3`, ...
51
+ *
52
+ * EXPORTED for `team_spawn` (team-detached-dispatch section 5.2.6): a child added
53
+ * mid-dispatch must not collide with a live one, and `normalizeSubagentSpecs` can
54
+ * only dedupe inside the batch it is given. One suffixer, two callers - a copy
55
+ * here would drift the first time either side gained a rule.
56
+ *
57
+ * Two agents the user cannot tell apart in the panel is worse than an ugly label,
58
+ * and the bus addresses children BY label: a duplicate makes `team_send`
59
+ * ambiguous, which is a correctness problem rather than a cosmetic one.
60
+ */
61
+ export declare function dedupeLabel(label: string, taken: Set<string>): string;
48
62
  /**
49
63
  * Repair and bound a raw `subagents` array.
50
64
  *
@@ -57,4 +71,21 @@ export declare function toSlug(raw: unknown): string;
57
71
  * `TEAM_LIMITS.hardMaxSubagents` here so a hand-edited config file
58
72
  * cannot raise the requirement's ceiling (R-g).
59
73
  */
74
+ /**
75
+ * Turn ONE sentence plus a count into that many subagent specs, for
76
+ * `/team spawn <n> <brief>` and the desktop control surface
77
+ * (team-detached-dispatch section 5.8).
78
+ *
79
+ * WHY A SHARED HELPER RATHER THAN ELEVEN LINES IN EACH CALLER. The split is a
80
+ * POLICY ("who owns which part"), and the package already has one: a brief fanned
81
+ * out over N children without any of them being told which slice is theirs
82
+ * produces N agents reading the same repository. So every slice gets a distinct
83
+ * ordinal and an explicit instruction to stay inside its own part, and the caller
84
+ * keeps the count and the clamp this file is responsible for.
85
+ *
86
+ * Deterministic, no model call, never throws. `count` is clamped to the structural
87
+ * ceiling for the same reason `normalizeSubagentSpecs` clamps: a hand-typed
88
+ * `/team spawn 40 ...` must not be able to exceed `hardMaxSubagents`.
89
+ */
90
+ export declare function splitBriefIntoSpecs(brief: string, count: number): SubagentSpec[];
60
91
  export declare function normalizeSubagentSpecs(raw: unknown, max: number): NormalizedSpecs;
@@ -66,12 +66,16 @@ function slugLabel(raw, index) {
66
66
  * Make `label` unique within the dispatch, case-insensitively, by appending
67
67
  * `-2`, `-3`, ...
68
68
  *
69
- * Two agents the user cannot tell apart in the panel is worse than an ugly
70
- * label, and the bus addresses children BY label — a duplicate would make
71
- * `team_send` ambiguous, which is a correctness problem rather than a cosmetic
72
- * one.
69
+ * EXPORTED for `team_spawn` (team-detached-dispatch section 5.2.6): a child added
70
+ * mid-dispatch must not collide with a live one, and `normalizeSubagentSpecs` can
71
+ * only dedupe inside the batch it is given. One suffixer, two callers - a copy
72
+ * here would drift the first time either side gained a rule.
73
+ *
74
+ * Two agents the user cannot tell apart in the panel is worse than an ugly label,
75
+ * and the bus addresses children BY label: a duplicate makes `team_send`
76
+ * ambiguous, which is a correctness problem rather than a cosmetic one.
73
77
  */
74
- function dedupeLabel(label, taken) {
78
+ export function dedupeLabel(label, taken) {
75
79
  const base = label.toLowerCase();
76
80
  if (!taken.has(base)) {
77
81
  taken.add(base);
@@ -100,6 +104,46 @@ function dedupeLabel(label, taken) {
100
104
  * `TEAM_LIMITS.hardMaxSubagents` here so a hand-edited config file
101
105
  * cannot raise the requirement's ceiling (R-g).
102
106
  */
107
+ /**
108
+ * Turn ONE sentence plus a count into that many subagent specs, for
109
+ * `/team spawn <n> <brief>` and the desktop control surface
110
+ * (team-detached-dispatch section 5.8).
111
+ *
112
+ * WHY A SHARED HELPER RATHER THAN ELEVEN LINES IN EACH CALLER. The split is a
113
+ * POLICY ("who owns which part"), and the package already has one: a brief fanned
114
+ * out over N children without any of them being told which slice is theirs
115
+ * produces N agents reading the same repository. So every slice gets a distinct
116
+ * ordinal and an explicit instruction to stay inside its own part, and the caller
117
+ * keeps the count and the clamp this file is responsible for.
118
+ *
119
+ * Deterministic, no model call, never throws. `count` is clamped to the structural
120
+ * ceiling for the same reason `normalizeSubagentSpecs` clamps: a hand-typed
121
+ * `/team spawn 40 ...` must not be able to exceed `hardMaxSubagents`.
122
+ */
123
+ export function splitBriefIntoSpecs(brief, count) {
124
+ const text = brief.trim();
125
+ if (text.length === 0)
126
+ return [];
127
+ const wanted = Math.max(1, Math.min(Math.floor(count) || 1, TEAM_LIMITS.hardMaxSubagents));
128
+ const head = text.slice(0, TEAM_LIMITS.descriptionChars);
129
+ const specs = [];
130
+ for (let index = 0; index < wanted; index += 1) {
131
+ const ordinal = index + 1;
132
+ const label = `part-${ordinal}`;
133
+ specs.push({
134
+ label,
135
+ description: `${head} (part ${ordinal} of ${wanted})`.slice(0, TEAM_LIMITS.descriptionChars),
136
+ prompt: `${text}\n\n` +
137
+ `You are part ${ordinal} of ${wanted} working on the request above. Take an ` +
138
+ 'independent slice of it, name the files or areas that slice owns in your first ' +
139
+ 'sentence, and do not edit anything another part is likely to own - if you need a ' +
140
+ 'shared file changed, say so in your report instead of changing it. Your final ' +
141
+ 'message is the only thing the lead sees.',
142
+ readOnly: false,
143
+ });
144
+ }
145
+ return specs;
146
+ }
103
147
  export function normalizeSubagentSpecs(raw, max) {
104
148
  if (!Array.isArray(raw))
105
149
  return { specs: [], requested: 0 };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * TeamNoticeQueue - "a dispatch did something the lead must be told about,
3
+ * exactly once" (team-detached-dispatch section 5.3.1).
4
+ *
5
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
6
+ *
7
+ * STRUCTURALLY THE SAME OBJECT AS `proc/notices.ts`, AND DELIBERATELY NOT THE
8
+ * SAME CLASS. Both are idempotent-by-id bounded queues behind three mutually
9
+ * exclusive delivery channels; they differ in every policy that matters. A job
10
+ * notice is "the thing you started has ended"; these are one CHILD settling, the
11
+ * whole DISPATCH settling (carrying the report), and a child writing to the lead.
12
+ * Merging them would put the "never inject while a tool batch is open" rule (job
13
+ * I-5) and the "the settle report must always arrive" rule in one object and let
14
+ * either win.
15
+ *
16
+ * THREE KINDS, THREE LIFETIMES:
17
+ *
18
+ * - `child_settled` is CHATTER. It is dropped the moment the `dispatch_settled`
19
+ * report arrives, because the report already contains every row - five child
20
+ * lines plus a report that repeats them is the duplicate noise this feature
21
+ * would otherwise add to every dispatch.
22
+ * - `dispatch_settled` is THE FACT. Its body is `session.reportText`, generated
23
+ * once by the runtime (spec REV-05), so the notice, `team_collect` and
24
+ * `/team wait` show the same string rather than three renderings of the same
25
+ * outcome.
26
+ * - `lead_mail` is a REMINDER, bounded by `leadNoticesPerDispatch`; the full mail
27
+ * is always in the report as well, so losing one of these loses nothing.
28
+ */
29
+ export type TeamNotice = {
30
+ kind: 'child_settled';
31
+ /** `${dispatchId}:${label}:${phase}` - a child settles once. */
32
+ id: string;
33
+ dispatchId: string;
34
+ label: string;
35
+ phase: string;
36
+ elapsedMs: number;
37
+ turns: number;
38
+ toolCalls: number;
39
+ /** First line of the error, when there was one. */
40
+ error?: string;
41
+ at: number;
42
+ } | {
43
+ kind: 'dispatch_settled';
44
+ /** `${dispatchId}:end`. */
45
+ id: string;
46
+ dispatchId: string;
47
+ /** `session.reportText`, verbatim. */
48
+ report: string;
49
+ aborted: boolean;
50
+ at: number;
51
+ } | {
52
+ kind: 'lead_mail';
53
+ /** `${dispatchId}:mail:${at}:${from}`. */
54
+ id: string;
55
+ dispatchId: string;
56
+ from: string;
57
+ subject: string;
58
+ /** Body head, already clamped by the producer. */
59
+ bodyHead: string;
60
+ at: number;
61
+ };
62
+ export declare class TeamNoticeQueue {
63
+ private readonly entries;
64
+ /**
65
+ * `lead_mail` notices already admitted, PER DISPATCH.
66
+ *
67
+ * PER DISPATCH, not per drain: the relay drains at every safe point, so a plain
68
+ * counter that `drain()` reset would have allowed `leadNoticesPerDispatch` mails
69
+ * per DRAIN - an unbounded number for a long dispatch, which is the opposite of
70
+ * what the bound is for.
71
+ */
72
+ private readonly leadMails;
73
+ /**
74
+ * Same id twice keeps ONE entry. That is what makes the relay's re-queue after a
75
+ * queue wipe idempotent: a notice that was delivered and re-queued can only be
76
+ * rendered again, never duplicated (job I-11's argument, same mechanism).
77
+ */
78
+ push(notice: TeamNotice): void;
79
+ /** Take everything and reset. The one way a notice leaves this object. */
80
+ drain(): TeamNotice[];
81
+ peek(): TeamNotice[];
82
+ pending(): number;
83
+ clear(): void;
84
+ }
85
+ /**
86
+ * Render the `<team_notices>` block, or `''` when there is nothing to say.
87
+ *
88
+ * EMPTY IN, EMPTY OUT, for the same reason `renderJobNotices` is: an unconditional
89
+ * block would add lines to every tool call in every session.
90
+ *
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.
94
+ */
95
+ export declare function renderTeamNotices(notices: readonly TeamNotice[]): string;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * TeamNoticeQueue - "a dispatch did something the lead must be told about,
3
+ * exactly once" (team-detached-dispatch section 5.3.1).
4
+ *
5
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
6
+ *
7
+ * STRUCTURALLY THE SAME OBJECT AS `proc/notices.ts`, AND DELIBERATELY NOT THE
8
+ * SAME CLASS. Both are idempotent-by-id bounded queues behind three mutually
9
+ * exclusive delivery channels; they differ in every policy that matters. A job
10
+ * notice is "the thing you started has ended"; these are one CHILD settling, the
11
+ * whole DISPATCH settling (carrying the report), and a child writing to the lead.
12
+ * Merging them would put the "never inject while a tool batch is open" rule (job
13
+ * I-5) and the "the settle report must always arrive" rule in one object and let
14
+ * either win.
15
+ *
16
+ * THREE KINDS, THREE LIFETIMES:
17
+ *
18
+ * - `child_settled` is CHATTER. It is dropped the moment the `dispatch_settled`
19
+ * report arrives, because the report already contains every row - five child
20
+ * lines plus a report that repeats them is the duplicate noise this feature
21
+ * would otherwise add to every dispatch.
22
+ * - `dispatch_settled` is THE FACT. Its body is `session.reportText`, generated
23
+ * once by the runtime (spec REV-05), so the notice, `team_collect` and
24
+ * `/team wait` show the same string rather than three renderings of the same
25
+ * outcome.
26
+ * - `lead_mail` is a REMINDER, bounded by `leadNoticesPerDispatch`; the full mail
27
+ * is always in the report as well, so losing one of these loses nothing.
28
+ */
29
+ import { TEAM_LIMITS } from '@aragon-agent/tui/model/team/limits';
30
+ export class TeamNoticeQueue {
31
+ entries = new Map();
32
+ /**
33
+ * `lead_mail` notices already admitted, PER DISPATCH.
34
+ *
35
+ * PER DISPATCH, not per drain: the relay drains at every safe point, so a plain
36
+ * counter that `drain()` reset would have allowed `leadNoticesPerDispatch` mails
37
+ * per DRAIN - an unbounded number for a long dispatch, which is the opposite of
38
+ * what the bound is for.
39
+ */
40
+ leadMails = new Map();
41
+ /**
42
+ * Same id twice keeps ONE entry. That is what makes the relay's re-queue after a
43
+ * queue wipe idempotent: a notice that was delivered and re-queued can only be
44
+ * rendered again, never duplicated (job I-11's argument, same mechanism).
45
+ */
46
+ push(notice) {
47
+ if (this.entries.has(notice.id))
48
+ return;
49
+ if (notice.kind === 'lead_mail') {
50
+ const used = this.leadMails.get(notice.dispatchId) ?? 0;
51
+ if (used >= TEAM_LIMITS.leadNoticesPerDispatch)
52
+ return;
53
+ this.leadMails.set(notice.dispatchId, used + 1);
54
+ }
55
+ if (notice.kind === 'dispatch_settled') {
56
+ // THE REPORT REPLACES THE CHILD LINES. Dropping them here rather than in the
57
+ // renderer keeps the queue's own bound honest: what is in the map is what
58
+ // will be delivered.
59
+ for (const [id, held] of [...this.entries]) {
60
+ if (held.dispatchId === notice.dispatchId && held.kind === 'child_settled') {
61
+ this.entries.delete(id);
62
+ }
63
+ }
64
+ // The dispatch is over, so its mail allowance goes with it.
65
+ this.leadMails.delete(notice.dispatchId);
66
+ }
67
+ this.entries.set(notice.id, notice);
68
+ }
69
+ /** Take everything and reset. The one way a notice leaves this object. */
70
+ drain() {
71
+ if (this.entries.size === 0)
72
+ return [];
73
+ const out = [...this.entries.values()];
74
+ this.entries.clear();
75
+ return out;
76
+ }
77
+ peek() {
78
+ return [...this.entries.values()];
79
+ }
80
+ pending() {
81
+ return this.entries.size;
82
+ }
83
+ clear() {
84
+ this.entries.clear();
85
+ this.leadMails.clear();
86
+ }
87
+ }
88
+ /**
89
+ * Render the `<team_notices>` block, or `''` when there is nothing to say.
90
+ *
91
+ * EMPTY IN, EMPTY OUT, for the same reason `renderJobNotices` is: an unconditional
92
+ * block would add lines to every tool call in every session.
93
+ *
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.
97
+ */
98
+ export function renderTeamNotices(notices) {
99
+ if (notices.length === 0)
100
+ 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));
103
+ const lines = ['<team_notices>'];
104
+ for (const notice of sorted) {
105
+ if (notice.kind === 'dispatch_settled') {
106
+ lines.push(notice.report);
107
+ continue;
108
+ }
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;
114
+ }
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
+ }
119
+ lines.push('</team_notices>');
120
+ return lines.join('\n');
121
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The cooperative pause gate for subagents (team-detached-dispatch section 5.2.4).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
5
+ *
6
+ * "PAUSED" IS COOPERATIVE AND THE WORDING SAYS SO. There is no way to freeze a
7
+ * child mid-request: the only places a child can be held are (a) between two tool
8
+ * calls and (b) at the top of its own loop, before the next `prompt()`. This file
9
+ * owns (a), `TeamRuntime.runOne` owns (b). Anything that promises more - "frozen
10
+ * instantly" - is a promise the mechanism cannot keep, so `team_pause`'s result
11
+ * text is written to match this reality instead.
12
+ *
13
+ * WHY A SEPARATE FILE. `team/subagent.ts` is already 1 032 lines and
14
+ * `team/runtime.ts` 1 631 (both recorded in `.claude-index/config.md`); the gate
15
+ * is a self-contained little scheduler (a resolve queue per label), so it lives
16
+ * here and those two only wire it.
17
+ *
18
+ * THE GATE WRAPS *OUTSIDE* `withMailboxTail` (spec REV-12). The order matters
19
+ * twice over: a held child must not be handed a mailbox tail (that would be a
20
+ * delivery to an agent that is not running), and the existing wrapper stack
21
+ * (`withToolPolicy` / `withPlanModeGate` / `withMailboxTail`) keeps the order it
22
+ * was designed with.
23
+ */
24
+ import type { AgentTool } from '@aragon-agent/core';
25
+ import type { TeamControlBy } from '@aragon-agent/tui/model/team/types';
26
+ /**
27
+ * One gate per dispatch: the pause state for every label plus the accounting the
28
+ * report and the child's own timeout budget need.
29
+ */
30
+ export declare class PauseGate {
31
+ private readonly held;
32
+ /** Milliseconds spent held, closed out at each resume. */
33
+ private readonly total;
34
+ /** How many times each label was held. */
35
+ private readonly holds;
36
+ private readonly now;
37
+ constructor(now?: () => number);
38
+ /**
39
+ * Hold `label`. Idempotent: a second pause of an already held child only
40
+ * restates WHO holds it, so a supervisor's hold can be taken over by the lead
41
+ * without restarting the accounting.
42
+ */
43
+ pause(label: string, by: TeamControlBy): boolean;
44
+ /** Release `label`, waking everything that waited on it. `false` when it was not held. */
45
+ resume(label: string): boolean;
46
+ /**
47
+ * Release everything. Used by abort and by dispose: a held child that nobody
48
+ * releases would leave a promise (and therefore a worker slot) dangling, and
49
+ * `finally` in the runtime could never run.
50
+ */
51
+ releaseAll(): void;
52
+ isPaused(label: string): boolean;
53
+ /** Who holds it, for the status line and the run's `controlBy` fact. */
54
+ holderOf(label: string): TeamControlBy | undefined;
55
+ /** When the current hold started (epoch ms), or `undefined` when not held. */
56
+ pausedSince(label: string): number | undefined;
57
+ /**
58
+ * Total milliseconds `label` has spent held, INCLUDING the hold that is open
59
+ * right now. This is the number settlement credits back to the child's own
60
+ * `subagentTimeoutMs` - and the one it must never add to the dispatch ceiling.
61
+ */
62
+ pausedMs(label: string): number;
63
+ /** How many times `label` was held. */
64
+ pauseCount(label: string): number;
65
+ /**
66
+ * Resolve when `label` may run. Resolves IMMEDIATELY when it is not held, which
67
+ * keeps an unpaused dispatch free of an extra await on the hot path.
68
+ */
69
+ waitIfPaused(label: string): Promise<void>;
70
+ }
71
+ /**
72
+ * Wrap one tool so a held child cannot execute it.
73
+ *
74
+ * CHECKS THEN DELEGATES: arguments, results and errors are untouched, and on
75
+ * release the original `execute` runs exactly once with the arguments it was
76
+ * called with - so the model's tool-call id, and therefore the conversation,
77
+ * is unchanged.
78
+ */
79
+ export declare function withPauseGate(tool: AgentTool, gate: PauseGate, label: string): AgentTool;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The cooperative pause gate for subagents (team-detached-dispatch section 5.2.4).
3
+ *
4
+ * ASCII ONLY: `src/team/**` is inside `glyphs.test.ts`'s static scan.
5
+ *
6
+ * "PAUSED" IS COOPERATIVE AND THE WORDING SAYS SO. There is no way to freeze a
7
+ * child mid-request: the only places a child can be held are (a) between two tool
8
+ * calls and (b) at the top of its own loop, before the next `prompt()`. This file
9
+ * owns (a), `TeamRuntime.runOne` owns (b). Anything that promises more - "frozen
10
+ * instantly" - is a promise the mechanism cannot keep, so `team_pause`'s result
11
+ * text is written to match this reality instead.
12
+ *
13
+ * WHY A SEPARATE FILE. `team/subagent.ts` is already 1 032 lines and
14
+ * `team/runtime.ts` 1 631 (both recorded in `.claude-index/config.md`); the gate
15
+ * is a self-contained little scheduler (a resolve queue per label), so it lives
16
+ * here and those two only wire it.
17
+ *
18
+ * THE GATE WRAPS *OUTSIDE* `withMailboxTail` (spec REV-12). The order matters
19
+ * twice over: a held child must not be handed a mailbox tail (that would be a
20
+ * delivery to an agent that is not running), and the existing wrapper stack
21
+ * (`withToolPolicy` / `withPlanModeGate` / `withMailboxTail`) keeps the order it
22
+ * was designed with.
23
+ */
24
+ /**
25
+ * One gate per dispatch: the pause state for every label plus the accounting the
26
+ * report and the child's own timeout budget need.
27
+ */
28
+ export class PauseGate {
29
+ held = new Map();
30
+ /** Milliseconds spent held, closed out at each resume. */
31
+ total = new Map();
32
+ /** How many times each label was held. */
33
+ holds = new Map();
34
+ now;
35
+ constructor(now = () => Date.now()) {
36
+ this.now = now;
37
+ }
38
+ /**
39
+ * Hold `label`. Idempotent: a second pause of an already held child only
40
+ * restates WHO holds it, so a supervisor's hold can be taken over by the lead
41
+ * without restarting the accounting.
42
+ */
43
+ pause(label, by) {
44
+ const existing = this.held.get(label);
45
+ if (existing !== undefined) {
46
+ existing.by = by;
47
+ return false;
48
+ }
49
+ this.held.set(label, { by, since: this.now(), waiters: [] });
50
+ this.holds.set(label, (this.holds.get(label) ?? 0) + 1);
51
+ return true;
52
+ }
53
+ /** Release `label`, waking everything that waited on it. `false` when it was not held. */
54
+ resume(label) {
55
+ const held = this.held.get(label);
56
+ if (held === undefined)
57
+ return false;
58
+ this.total.set(label, this.pausedMs(label));
59
+ this.held.delete(label);
60
+ for (const wake of held.waiters.splice(0, held.waiters.length))
61
+ wake();
62
+ return true;
63
+ }
64
+ /**
65
+ * Release everything. Used by abort and by dispose: a held child that nobody
66
+ * releases would leave a promise (and therefore a worker slot) dangling, and
67
+ * `finally` in the runtime could never run.
68
+ */
69
+ releaseAll() {
70
+ for (const label of [...this.held.keys()])
71
+ this.resume(label);
72
+ }
73
+ isPaused(label) {
74
+ return this.held.has(label);
75
+ }
76
+ /** Who holds it, for the status line and the run's `controlBy` fact. */
77
+ holderOf(label) {
78
+ return this.held.get(label)?.by;
79
+ }
80
+ /** When the current hold started (epoch ms), or `undefined` when not held. */
81
+ pausedSince(label) {
82
+ return this.held.get(label)?.since;
83
+ }
84
+ /**
85
+ * Total milliseconds `label` has spent held, INCLUDING the hold that is open
86
+ * right now. This is the number settlement credits back to the child's own
87
+ * `subagentTimeoutMs` - and the one it must never add to the dispatch ceiling.
88
+ */
89
+ pausedMs(label) {
90
+ const closed = this.total.get(label) ?? 0;
91
+ const held = this.held.get(label);
92
+ return held === undefined ? closed : closed + (this.now() - held.since);
93
+ }
94
+ /** How many times `label` was held. */
95
+ pauseCount(label) {
96
+ return this.holds.get(label) ?? 0;
97
+ }
98
+ /**
99
+ * Resolve when `label` may run. Resolves IMMEDIATELY when it is not held, which
100
+ * keeps an unpaused dispatch free of an extra await on the hot path.
101
+ */
102
+ waitIfPaused(label) {
103
+ const held = this.held.get(label);
104
+ if (held === undefined)
105
+ return Promise.resolve();
106
+ return new Promise((resolve) => {
107
+ held.waiters.push(resolve);
108
+ });
109
+ }
110
+ }
111
+ /**
112
+ * Wrap one tool so a held child cannot execute it.
113
+ *
114
+ * CHECKS THEN DELEGATES: arguments, results and errors are untouched, and on
115
+ * release the original `execute` runs exactly once with the arguments it was
116
+ * called with - so the model's tool-call id, and therefore the conversation,
117
+ * is unchanged.
118
+ */
119
+ export function withPauseGate(tool, gate, label) {
120
+ return {
121
+ ...tool,
122
+ async execute(id, params, ctx) {
123
+ await gate.waitIfPaused(label);
124
+ return tool.execute(id, params, ctx);
125
+ },
126
+ };
127
+ }
@@ -18,19 +18,35 @@ export { TEAM_BLOCK_VERSION };
18
18
  export interface TeamBlockParams {
19
19
  maxSubagents: number;
20
20
  maxConcurrent: number;
21
+ /**
22
+ * Whether a dispatch outlives the `task` call (`team.detachDispatch`).
23
+ *
24
+ * THE ONLY CONDITIONAL IN THIS BLOCK, AND IT IS THE ONE THAT CARRIES I-DD8: with
25
+ * the key false the only paragraph that differs is the one describing a free lead,
26
+ * which would be a lie in a session where `task` still blocks. The rest of the
27
+ * block is the compressed text below - byte-identical between the two modes, and
28
+ * NOT byte-identical to v3: the compression the 1 200-character budget forced
29
+ * applies to both (spec 'implementation findings', IF-14).
30
+ * `task`'s own description is NOT conditional (it cannot be: the tool array is
31
+ * frozen at construction), which is why the detach contract lives here.
32
+ */
33
+ detachDispatch?: boolean;
21
34
  }
22
35
  /**
23
- * The lead's `<team_mode>` block. Under 1200 characters on purpose: it is paid
24
- * for on EVERY turn of every team-enabled session, so anything that does not
25
- * change a delegation decision does not belong in it.
36
+ * The lead's `<team_mode>` block.
37
+ *
38
+ * UNDER 1200 CHARACTERS, AND NOW ASSERTED BY A TEST (`team-prompt.test.ts`), which
39
+ * is a change of kind rather than of number: v3 measured 1 204 and the budget had
40
+ * never been enforced, so every later addition was free money. The detach
41
+ * paragraph costs ~600 characters, so the prose below was compressed by more than
42
+ * that rather than by "roughly enough": what went is everything that repeated
43
+ * `task`'s own description (the whole "do not delegate when" list, the second
44
+ * "cannot ask the user anything", the duplicate "one combined report" sentence)
45
+ * and the second copy of a maximum that is already in the first line.
26
46
  *
27
47
  * "Two to four is usually enough" is where the requirement's "shu liang zi shi
28
- * ying" (adaptive count) actually lives. The ceiling is mechanical and enforced
29
- * elsewhere (`team.maxSubagents`, quoted in the first paragraph); the CHOICE is
30
- * the model's, and this paragraph is the only thing that informs it. It names a
31
- * USUAL size rather than the maximum on purpose: the default fan-out moved to 8
32
- * (subagent-fanout D-1), and a block that told the model "eight is normal"
33
- * would turn every two-part job into an eight-agent bill.
48
+ * ying" (adaptive count) actually lives: the ceiling is mechanical and enforced
49
+ * elsewhere, this paragraph is the only thing that informs the CHOICE.
34
50
  */
35
51
  export declare function buildTeamBlock(params: TeamBlockParams): string;
36
52
  export interface SubagentBlockParams {