@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
@@ -26,14 +26,16 @@
26
26
  * FAILURE POLICY. A transient provider error (rate limit, overload) costs nothing and is retried
27
27
  * at the next trigger. A real failure or a timeout is a strike; three in a row disable learning
28
28
  * for the session (`learner_failing`) and the status chip says so. A cancelled call (`/clear`,
29
- * exit) is dropped without a trace: no strike, no enqueue.
29
+ * exit) is dropped without a trace: no strike, no enqueue. A reply that stopped at the output
30
+ * ceiling and did not parse is a truncation, not a model failure: it costs no strike and rolls the
31
+ * watermark back, so the next trigger pays for that run again instead of losing the experience.
30
32
  */
31
33
  import { collectSignals, shouldLearn, } from '@aragon-agent/tui/model/gene/signals';
32
34
  import { normalizeLearningOutput } from '@aragon-agent/tui/model/gene/proposal';
33
35
  import { EvidenceLedger, } from './ledger.js';
34
36
  import { factsFromLedger } from './signals-port.js';
35
37
  import { buildLearningInput, LEARN_SYSTEM_PROMPT } from './learn-prompt.js';
36
- import { runLearnCall, } from './learn-call.js';
38
+ import { isTruncated, runLearnCall, } from './learn-call.js';
37
39
  import { guardProposal } from './proposal-guard.js';
38
40
  import { adjustAttributions, buildProposal, outcomeEvents, } from './proposal-build.js';
39
41
  export const LEARNER_STRIKES_MAX = 3;
@@ -280,8 +282,9 @@ export class GeneLearner {
280
282
  return;
281
283
  }
282
284
  this.deps.onUsage?.(result.usage);
283
- if (result.ok)
284
- await this.settleReply(result.text, { job, prepared, usage: result.usage });
285
+ if (result.ok) {
286
+ await this.settleReply(result.text, { job, prepared, usage: result.usage, truncated: isTruncated(result), replyChars: result.replyChars }, before);
287
+ }
285
288
  else
286
289
  await this.settleFailure(result, before);
287
290
  this.deps.notify?.();
@@ -300,10 +303,18 @@ export class GeneLearner {
300
303
  const used = [...snapshot.reads.keys()].map((id) => ({ id, line: this.deps.describeGene(id) ?? '' }));
301
304
  return { input: buildLearningInput({ snapshot, signals: job.signals, used, existing }), snapshot };
302
305
  }
303
- undoFire(before) {
306
+ /**
307
+ * Un-spend one attempt: the run's signals become learnable again and the session count goes
308
+ * back. The cooldown (`lastLearnAt`) is NOT part of it - a busy provider, a truncation and a
309
+ * cancellation all keep it, and only a cancellation gives it back (`undoFire`).
310
+ */
311
+ giveBack(before) {
304
312
  this.watermark = before.watermark;
305
- this.lastLearnAt = before.lastLearnAt;
306
313
  this.sessionCount = Math.max(0, this.sessionCount - 1);
314
+ }
315
+ undoFire(before) {
316
+ this.giveBack(before);
317
+ this.lastLearnAt = before.lastLearnAt;
307
318
  this.deps.notify?.();
308
319
  }
309
320
  setReviewing(value) {
@@ -311,10 +322,12 @@ export class GeneLearner {
311
322
  this.deps.notify?.();
312
323
  }
313
324
  async settleFailure(result, before) {
325
+ // The spend of a FAILED call is still spend: without this the run log said `tokens: null` for
326
+ // every truncation and the budget could never see the wasted calls (RV-14).
327
+ this.pendingTokens = { in: result.usage.inTok, out: result.usage.outTok, component: 'reviewer' };
314
328
  if (result.kind === 'transient') {
315
329
  // Busy provider: not our fault and not a strike. Keep the cooldown, forget the attempt.
316
- this.watermark = before.watermark;
317
- this.sessionCount = Math.max(0, this.sessionCount - 1);
330
+ this.giveBack(before);
318
331
  await this.record({ ev: 'skipped', detail: `transient:${result.errorType}` });
319
332
  return;
320
333
  }
@@ -327,7 +340,7 @@ export class GeneLearner {
327
340
  this.selfDisabled = true;
328
341
  }
329
342
  // ---- the reply -------------------------------------------------------------------------
330
- async settleReply(text, ctx) {
343
+ async settleReply(text, ctx, before) {
331
344
  const { snapshot, input } = ctx.prepared;
332
345
  const normalized = normalizeLearningOutput(text, {
333
346
  readGeneIds: input.usedIds,
@@ -335,6 +348,15 @@ export class GeneLearner {
335
348
  });
336
349
  this.pendingTokens = { in: ctx.usage.inTok, out: ctx.usage.outTok, component: 'reviewer' };
337
350
  if (normalized.parseFailed === true) {
351
+ // PARSE FIRST, THEN BLAME (RV-18). A reply cut at OUR ceiling is not the tier's fault and not
352
+ // the run's fault: no strike, the watermark rolls back so the next trigger tries again, and
353
+ // the cooldown stays. Without this, three truncations in a row disabled learning for the
354
+ // whole session and the signals they covered were dropped forever (RC-1).
355
+ if (ctx.truncated) {
356
+ this.giveBack(before);
357
+ await this.record({ ev: 'skipped', detail: `truncated:reply=${ctx.replyChars}` });
358
+ return;
359
+ }
338
360
  this.noteStrike();
339
361
  await this.record({ ev: 'error', detail: 'unparseable_reply' });
340
362
  return;
@@ -1,4 +1,4 @@
1
- import { escapeGeneText } from '@aragon-agent/tui/model/gene/escape';
1
+ import { escapeGeneText, unescapeGeneEntities } from '@aragon-agent/tui/model/gene/escape';
2
2
  import { isValidScope, mintProposalId, scopeId } from '@aragon-agent/tui/model/gene/ids';
3
3
  import { GENE_LIMITS, GENE_SCORE } from '@aragon-agent/tui/model/gene/limits';
4
4
  import { dedupeKeyOf, priorityOf } from '@aragon-agent/tui/model/gene/proposal';
@@ -26,10 +26,6 @@ export function resolveScope(kind, session) {
26
26
  function quoteKey(text) {
27
27
  return escapeGeneText(text, 'line');
28
28
  }
29
- /** The model read an entity-escaped prompt and may quote the entities back; undo them once. */
30
- function unescapeEntities(text) {
31
- return text.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
32
- }
33
29
  /** Check quotes against the ledger, scrub secrets, clip. */
34
30
  export function verifyEvidence(list, snapshot, knownSecrets) {
35
31
  const users = snapshot.users.map((u) => ({ key: quoteKey(u.text), raw: u.text }));
@@ -37,7 +33,7 @@ export function verifyEvidence(list, snapshot, knownSecrets) {
37
33
  let text = entry.text;
38
34
  let trust = entry.trust;
39
35
  if (entry.kind === 'user_statement') {
40
- const keys = [quoteKey(entry.text), quoteKey(unescapeEntities(entry.text))].filter((k) => k.length > 0);
36
+ const keys = [quoteKey(entry.text), quoteKey(unescapeGeneEntities(entry.text))].filter((k) => k.length > 0);
41
37
  const hit = users.find((u) => keys.some((key) => u.key.includes(key)));
42
38
  text = hit ? hit.raw : text;
43
39
  trust = hit ? 'user' : 'untrusted';
@@ -76,6 +76,9 @@ export function createLearnComplete(deps) {
76
76
  const inTok = reply.usage?.inputTokens ?? 0;
77
77
  const outTok = reply.usage?.outputTokens ?? 0;
78
78
  deps.onSpend?.({ inTok, outTok, usd: reply.usage?.cost });
79
- return { text, usage: { inTok, outTok } };
79
+ // The stop reason is the ONLY way to tell "the model wrote a short answer" from "we cut its
80
+ // answer at our own ceiling": every provider fills it and it used to be dropped right here.
81
+ const stop = reply.stopReason === undefined ? {} : { stopReason: reply.stopReason };
82
+ return { text, usage: { inTok, outTok }, ...stop };
80
83
  };
81
84
  }
@@ -291,7 +291,7 @@ async function createRun(core, c) {
291
291
  : null;
292
292
  const flushNote = await core.flush();
293
293
  const digest = startDigest(core, c.notes, chunkNote);
294
- return flushNote === null ? digest : `${digest}
294
+ return flushNote === null ? digest : `${digest}
295
295
  ${flushNote}`;
296
296
  }
297
297
  /** DEV per WP in WP order, REV / TEST by `rosterSizes` (5.2). Logged as ledger ops. */
@@ -47,9 +47,16 @@ export declare function defaultIsPidAlive(pid: number): boolean;
47
47
  export declare function readLock(path: string, fs?: GovFs): Promise<LockInfo | null>;
48
48
  /** True when a lock must be honoured: fresh heartbeat AND a living holder. */
49
49
  export declare function isLockLive(info: LockInfo | null, deps: LockDeps): boolean;
50
- /** Take the lock, or explain who holds it. Never throws for contention. */
50
+ /**
51
+ * Take the lock, or explain who holds it. Never throws for contention.
52
+ *
53
+ * THE WINNER IS THE ONE WHO CREATES, NOT THE ONE WHO READS LAST. Between `open(wx)` and the
54
+ * `write` that follows it the file exists and is empty, and that empty file must not be readable
55
+ * as "nobody has it": `readLockState` distinguishes it, and `TORN_LOCK_GRACE_MS` bounds how long
56
+ * a genuinely abandoned one may block a takeover.
57
+ */
51
58
  export declare function acquireLock(path: string, deps: LockDeps): Promise<AcquireResult>;
52
59
  /** Refresh `heartbeatAt`. Returns false when the lock is no longer ours (lost or removed). */
53
60
  export declare function refreshLock(path: string, deps: LockDeps): Promise<boolean>;
54
- /** Remove the lock only if it is ours; a foreign lock is left untouched. */
61
+ /** Remove the lock only if it is ours; a foreign - or not-yet-written - lock is left untouched. */
55
62
  export declare function removeLock(path: string, deps: LockDeps): Promise<void>;
@@ -45,6 +45,64 @@ export async function readLock(path, fs = nodeGovFs) {
45
45
  return null;
46
46
  }
47
47
  }
48
+ /**
49
+ * Longest a lock file may stay UNPARSABLE before it is judged a crash rather than a write
50
+ * already in progress.
51
+ *
52
+ * A lock is born empty: `tryExclusiveCreate` succeeds on `open(wx)` and the JSON arrives a
53
+ * moment later with `write` + `sync`. Any process that reads the file inside that window gets
54
+ * `JSON.parse('')`. Calling that "no lock" is how TWO processes end up holding one lock - the
55
+ * second overwrites the file on Windows (POSIX replaces it even while the handle is open) and
56
+ * both enter the critical section, which is a lost update rather than an error
57
+ * (`policy.test.ts` AC-59: 11 of 12 exclusions survived, only under load).
58
+ *
59
+ * 2 s is ~1000x the cost of the write it is waiting for, and still short enough that a process
60
+ * that crashed between create and write cannot wedge a lock forever.
61
+ */
62
+ const TORN_LOCK_GRACE_MS = 2_000;
63
+ async function readLockState(path, fs) {
64
+ let text;
65
+ try {
66
+ text = await fs.readFile(path);
67
+ }
68
+ catch {
69
+ return { state: 'absent' };
70
+ }
71
+ try {
72
+ const parsed = JSON.parse(text);
73
+ if (isLockInfo(parsed))
74
+ return { state: 'held', info: parsed };
75
+ }
76
+ catch {
77
+ // Fall through: the file is there but holds no record.
78
+ }
79
+ const state = text.trim().length === 0 ? 'empty' : 'corrupt';
80
+ try {
81
+ return { state, mtimeMs: (await fs.stat(path)).mtimeMs };
82
+ }
83
+ catch {
84
+ return { state, mtimeMs: null };
85
+ }
86
+ }
87
+ /**
88
+ * True when an unparsable lock file has been that way long enough to be a crash. An
89
+ * unreadable `mtimeMs` is treated as recent: we cannot prove it is old, and taking over a
90
+ * lock somebody is writing is the failure this whole check exists to prevent.
91
+ */
92
+ function tornLockIsAbandoned(mtimeMs, deps) {
93
+ if (mtimeMs === null)
94
+ return false;
95
+ return deps.now() - mtimeMs >= TORN_LOCK_GRACE_MS;
96
+ }
97
+ function tornRefusal() {
98
+ return {
99
+ ok: false,
100
+ // No process can be named: the file does not hold a record yet. Callers that display the
101
+ // holder treat 0 as "unknown", and every caller already handles `ok: false` by waiting.
102
+ holderPid: 0,
103
+ message: 'NOT ACCEPTED: another process is taking this lock right now. Try again in a moment.',
104
+ };
105
+ }
48
106
  /** True when a lock must be honoured: fresh heartbeat AND a living holder. */
49
107
  export function isLockLive(info, deps) {
50
108
  if (!info)
@@ -91,19 +149,40 @@ async function tryExclusiveCreate(path, deps) {
91
149
  }
92
150
  return true;
93
151
  }
94
- /** Take the lock, or explain who holds it. Never throws for contention. */
152
+ /**
153
+ * Take the lock, or explain who holds it. Never throws for contention.
154
+ *
155
+ * THE WINNER IS THE ONE WHO CREATES, NOT THE ONE WHO READS LAST. Between `open(wx)` and the
156
+ * `write` that follows it the file exists and is empty, and that empty file must not be readable
157
+ * as "nobody has it": `readLockState` distinguishes it, and `TORN_LOCK_GRACE_MS` bounds how long
158
+ * a genuinely abandoned one may block a takeover.
159
+ */
95
160
  export async function acquireLock(path, deps) {
96
161
  const fs = deps.fs ?? nodeGovFs;
97
162
  if (await tryExclusiveCreate(path, deps))
98
163
  return { ok: true, takenOver: false };
99
- const existing = await readLock(path, fs);
164
+ const read = await readLockState(path, fs);
165
+ if (read.state === 'empty' && !tornLockIsAbandoned(read.mtimeMs, deps)) {
166
+ return tornRefusal();
167
+ }
168
+ const existing = read.state === 'held' ? read.info : null;
100
169
  if (isLockLive(existing, deps))
101
170
  return refusal(existing, deps);
102
- await atomicWriteFile(path, freshLockText(deps), { fs });
171
+ try {
172
+ await atomicWriteFile(path, freshLockText(deps), { fs });
173
+ }
174
+ catch {
175
+ // A replace that the platform refuses (Windows reports EPERM while the winner still holds
176
+ // its `wx` handle open) is contention, not a failure: the caller's contract is `ok: false`,
177
+ // and a thrown EPERM out of here reads as an application bug to every caller.
178
+ return tornRefusal();
179
+ }
103
180
  const confirmed = await readLock(path, fs);
104
181
  if (confirmed && confirmed.pid !== deps.pid)
105
182
  return refusal(confirmed, deps);
106
- return { ok: true, takenOver: existing !== null };
183
+ // A file we found `held` - or an empty one we waited out - was replaced, which is a takeover
184
+ // even when it held no record to read (the crashed-writer case).
185
+ return { ok: true, takenOver: read.state !== 'absent' };
107
186
  }
108
187
  /** Refresh `heartbeatAt`. Returns false when the lock is no longer ours (lost or removed). */
109
188
  export async function refreshLock(path, deps) {
@@ -114,11 +193,16 @@ export async function refreshLock(path, deps) {
114
193
  await atomicWriteFile(path, freshLockText(deps, existing.startedAt), { fs });
115
194
  return true;
116
195
  }
117
- /** Remove the lock only if it is ours; a foreign lock is left untouched. */
196
+ /** Remove the lock only if it is ours; a foreign - or not-yet-written - lock is left untouched. */
118
197
  export async function removeLock(path, deps) {
119
198
  const fs = deps.fs ?? nodeGovFs;
120
- const existing = await readLock(path, fs);
121
- if (existing && existing.pid !== deps.pid)
199
+ // `absent` is nothing to remove and `empty` is a lock being born by somebody else: unlinking
200
+ // it would delete a lock we do not own - the same double-owner window `acquireLock` refuses.
201
+ // `corrupt` is unowned garbage and has always been removable.
202
+ const read = await readLockState(path, fs);
203
+ if (read.state === 'held' && read.info.pid !== deps.pid)
204
+ return;
205
+ if (read.state === 'absent' || read.state === 'empty')
122
206
  return;
123
207
  await fs.unlink(path).catch(() => undefined);
124
208
  }
@@ -95,6 +95,19 @@ export declare function makeController(flags: CliFlags, opts?: {
95
95
  * sessions' prompts and tools byte-identical (I-1).
96
96
  */
97
97
  redTeamArmed?: boolean;
98
+ /**
99
+ * `--redteam-prompt <path>`: this session's prompt profile (redteam-prompt-profile S-12).
100
+ *
101
+ * THE SAME CHANNEL AS `redTeamArmed`, and for the same reason: the flag has to reach
102
+ * `RedTeamWiring`, and `validateRedTeamLaunch`'s `decision` is discarded at its only call
103
+ * site, so a field added there would never be read. An unreadable path is a WARNING at the
104
+ * first assembly, never a launch refusal (AC-22).
105
+ *
106
+ * THIS BAG IS SPREAD, NOT PASSED WHOLE (see the note above the deps literal): a key that is
107
+ * declared here but not spread below is dropped in silence, which is what made this flag
108
+ * inert once already.
109
+ */
110
+ redTeamPromptPath?: string;
98
111
  }): {
99
112
  controller: AgentController;
100
113
  confirmBridge: ConfirmBridge;
@@ -124,6 +124,13 @@ export function makeController(flags, opts = { interactive: true }) {
124
124
  // deps bag it always did; the value is already the output of `validateRedTeamLaunch`, which
125
125
  // is the only place allowed to refuse it.
126
126
  ...(opts.redTeamArmed === true ? { redTeamArmed: true } : {}),
127
+ // `--redteam-prompt` (redteam-prompt-profile S-12 / IF-4). THE SAME TRAP AS THE R3 PAIR
128
+ // ABOVE: this factory forwards only what is named here, so the flag's only route to
129
+ // `RedTeamWiring.promptPath` is this spread. Absent stays absent, keeping a launch without
130
+ // the flag byte-identical to the pre-feature build.
131
+ ...(opts.redTeamPromptPath === undefined
132
+ ? {}
133
+ : { redTeamPromptPath: opts.redTeamPromptPath }),
127
134
  });
128
135
  return { controller, confirmBridge, humanInputBridge };
129
136
  }
@@ -23,3 +23,4 @@ export * from './settings.js';
23
23
  export * from './commands.js';
24
24
  export * from './skills.js';
25
25
  export * from './index-build.js';
26
+ export * from './team-control.js';
@@ -23,3 +23,4 @@ export * from './settings.js';
23
23
  export * from './commands.js';
24
24
  export * from './skills.js';
25
25
  export * from './index-build.js';
26
+ export * from './team-control.js';
@@ -37,6 +37,14 @@ export declare class InteractionCoordinator {
37
37
  private sequence;
38
38
  private gesture;
39
39
  private disposed;
40
+ /**
41
+ * The team settle timer (team-detached-dispatch section 5.3.3).
42
+ *
43
+ * THIS HOST'S OWN, exactly like the TUI's `followTimer`, and armed from the SAME
44
+ * pure decision table: that is what makes the two front ends answer one sentence
45
+ * identically (R9) without either owning the policy.
46
+ */
47
+ private settleTimer;
40
48
  constructor(ports: InteractionPorts);
41
49
  get phase(): InteractionPhase;
42
50
  /** Feed `agent_start` / `agent_end` here so `phase` follows the engine. */
@@ -47,6 +55,17 @@ export declare class InteractionCoordinator {
47
55
  * else.
48
56
  */
49
57
  onAgentEnd(): void;
58
+ /**
59
+ * Arm, announce, or skip the settle continuation (5.3.3).
60
+ *
61
+ * THE SAME TRUTH TABLE THE TERMINAL RUNS (`planSettleContinuation`), fed this
62
+ * host's facts. `followThroughArmed` is false here because this host has no todo
63
+ * follow-through and no forced-dispatch nudge: the flag exists for the hosts
64
+ * that do, and passing `false` is the honest answer rather than a guess.
65
+ */
66
+ private armTeamSettle;
67
+ /** Release the settle timer. Called from `dispose()` so it cannot fire into a dead host. */
68
+ private clearSettleTimer;
50
69
  /** Land the team-mode change that was asked for during the turn, and say what happened. */
51
70
  private landTeamMode;
52
71
  /** Send a message to the agent, bypassing slash parsing. */
@@ -23,12 +23,21 @@ import { teamModeToast, teamRefusalText } from '@aragon-agent/tui/model/team/tea
23
23
  import { buildInvocationCard, invocationCardsEnabled } from '@aragon-agent/tui/model/agent/invocation-card';
24
24
  import { getSecrets } from '@aragon-agent/tui/model/logging/secret-registry';
25
25
  import { redactText } from '../logging/redact.js';
26
+ import { planSettleContinuation } from '@aragon-agent/tui/model/team/settle-plan';
26
27
  export class InteractionCoordinator {
27
28
  ports;
28
29
  phaseValue = 'idle';
29
30
  sequence = 0;
30
31
  gesture = { phase: 'ready' };
31
32
  disposed = false;
33
+ /**
34
+ * The team settle timer (team-detached-dispatch section 5.3.3).
35
+ *
36
+ * THIS HOST'S OWN, exactly like the TUI's `followTimer`, and armed from the SAME
37
+ * pure decision table: that is what makes the two front ends answer one sentence
38
+ * identically (R9) without either owning the policy.
39
+ */
40
+ settleTimer = null;
32
41
  constructor(ports) {
33
42
  this.ports = ports;
34
43
  }
@@ -53,6 +62,12 @@ export class InteractionCoordinator {
53
62
  // otherwise be skipped by the `if (!applied) return` below and sit pending until the next
54
63
  // `prompt()` safety net (team-mode-toggle-keys R-10).
55
64
  this.landTeamMode();
65
+ // THE TEAM SETTLE, BEFORE THE POSTURE'S EARLY RETURN (5.3.3): the decision has
66
+ // to be made once per `agent_end`, and the posture returns early for almost
67
+ // every turn. A dispatch that settled during this turn announces or continues
68
+ // here; one that settled inside the turn itself is `none` by the table's own
69
+ // rule, because its report already arrived as a steering message.
70
+ this.armTeamSettle();
56
71
  const applied = controller.applyPendingPosture();
57
72
  if (!applied)
58
73
  return;
@@ -66,6 +81,63 @@ export class InteractionCoordinator {
66
81
  });
67
82
  dispatch({ type: 'pushToast', level: 'info', text: postureAppliedToast(applied.effective) });
68
83
  }
84
+ /**
85
+ * Arm, announce, or skip the settle continuation (5.3.3).
86
+ *
87
+ * THE SAME TRUTH TABLE THE TERMINAL RUNS (`planSettleContinuation`), fed this
88
+ * host's facts. `followThroughArmed` is false here because this host has no todo
89
+ * follow-through and no forced-dispatch nudge: the flag exists for the hosts
90
+ * that do, and passing `false` is the honest answer rather than a guess.
91
+ */
92
+ armTeamSettle() {
93
+ const { controller, dispatch } = this.ports;
94
+ const facts = controller.teamSettleFacts?.() ?? null;
95
+ if (facts === null)
96
+ return;
97
+ const team = controller.getTeamConfig();
98
+ const decision = planSettleContinuation({
99
+ mode: team.autoResume,
100
+ settled: facts.settled,
101
+ settledInsideTurn: facts.settledInsideTurn,
102
+ runEnd: { aborted: facts.aborted, errored: facts.errored },
103
+ continuedThisDispatch: facts.continuedThisDispatch,
104
+ userPending: controller.hasPendingUserMessages(),
105
+ followThroughArmed: false,
106
+ graceMs: team.settleGraceMs,
107
+ outcome: facts.outcome,
108
+ });
109
+ if (decision.kind === 'notice') {
110
+ this.ports.notify(decision.level, decision.text);
111
+ return;
112
+ }
113
+ if (decision.kind !== 'continue')
114
+ return;
115
+ this.ports.notify(decision.level, decision.notice);
116
+ if (this.settleTimer !== null)
117
+ clearTimeout(this.settleTimer);
118
+ this.settleTimer = setTimeout(() => {
119
+ this.settleTimer = null;
120
+ // Re-read at fire time: the user may have typed in the grace window, and a
121
+ // continuation that starts over their message is the one promise this table
122
+ // must never break.
123
+ if (this.disposed)
124
+ return;
125
+ if (controller.isRunning() || controller.isCompactionBusy?.())
126
+ return;
127
+ if (controller.hasPendingUserMessages())
128
+ return;
129
+ // The id comes from the facts: the dispatch has settled, so `live()` is null.
130
+ controller.markTeamContinued(facts.dispatchId);
131
+ void controller.prompt(decision.message, { todoPolicy: 'continue' });
132
+ }, decision.graceMs);
133
+ this.settleTimer.unref?.();
134
+ }
135
+ /** Release the settle timer. Called from `dispose()` so it cannot fire into a dead host. */
136
+ clearSettleTimer() {
137
+ if (this.settleTimer !== null)
138
+ clearTimeout(this.settleTimer);
139
+ this.settleTimer = null;
140
+ }
69
141
  /** Land the team-mode change that was asked for during the turn, and say what happened. */
70
142
  landTeamMode() {
71
143
  const { controller, dispatch } = this.ports;
@@ -195,6 +267,9 @@ export class InteractionCoordinator {
195
267
  }
196
268
  dispose() {
197
269
  this.disposed = true;
270
+ // An armed continuation must not fire into a disposed host: the timer would
271
+ // call `controller.prompt()` for a coordinator nobody is listening to.
272
+ this.clearSettleTimer();
198
273
  this.sequence += 1;
199
274
  if (this.phaseValue === 'starting' || this.ports.controller.isCompactionBusy?.()) {
200
275
  this.ports.controller.abort();
@@ -0,0 +1,83 @@
1
+ /**
2
+ * `host/team-control.ts` - the desktop control surface for a live dispatch
3
+ * (team-detached-dispatch section 7.3).
4
+ *
5
+ * ASCII ONLY, and NO INK, NO REACT: this file is inside the `host/**` import
6
+ * closure that layering rule L9 keeps free of the UI packages, because the Electron
7
+ * main process evaluates it.
8
+ *
9
+ * THE POINT OF THIS FILE IS THE BOUNDARY. A renderer panel gets a handful of
10
+ * strings and sends a handful of verbs; it never sees a `TeamRuntime`, a handle or
11
+ * a phase enum of its own. That is what keeps the desktop honest about the same
12
+ * facts the terminal shows - both read `TeamRuntime.inspect()`, and the panel
13
+ * renders what it is given rather than re-deriving it.
14
+ *
15
+ * NO NEW STREAM. The live roster keeps arriving over the existing team channel
16
+ * (`attachTeamChannel`); this only answers "what is true now" and "do this".
17
+ */
18
+ import type { SubagentPhase } from '@aragon-agent/tui/model/team/types';
19
+ import type { DispatchInspection, TeamRuntime } from '../team/runtime.js';
20
+ import type { TeamControlRequest } from '../team/console-view.js';
21
+ /**
22
+ * What a control surface may read. A STRUCTURAL subset of the controller, so this
23
+ * file compiles without importing the 4 500-line controller and a test can pass a
24
+ * two-line stub.
25
+ */
26
+ export interface TeamControlSource {
27
+ readTeamControl(): {
28
+ inspection: DispatchInspection | null;
29
+ live: {
30
+ dispatchId: string;
31
+ } | null;
32
+ };
33
+ sendTeamControl(request: TeamControlRequest, by?: 'lead' | 'user'): {
34
+ ok: boolean;
35
+ detail: string;
36
+ };
37
+ stopTeam(by: 'lead' | 'user', reason?: string): {
38
+ stopped: string[];
39
+ live: string[];
40
+ };
41
+ }
42
+ /** One row of the roster, as the panel draws it. */
43
+ export interface TeamControlRow {
44
+ label: string;
45
+ description: string;
46
+ phase: SubagentPhase;
47
+ /** Who holds it, when it is paused. */
48
+ by?: 'lead' | 'user' | 'supervisor';
49
+ elapsedMs: number;
50
+ turns: number;
51
+ toolCalls: number;
52
+ lastTool?: string;
53
+ pausedMs?: number;
54
+ error?: string;
55
+ }
56
+ /** Everything the panel needs for one render. */
57
+ export interface TeamControlView {
58
+ dispatch: {
59
+ id: string;
60
+ live: boolean;
61
+ startedAt: number;
62
+ requested: number;
63
+ } | null;
64
+ rows: TeamControlRow[];
65
+ /** Messages the children addressed to the lead, for the "mail" badge. */
66
+ mail: number;
67
+ }
68
+ /** Project the runtime's inspection into the panel's shape. Pure. */
69
+ export declare function readTeamControl(source: TeamControlSource): TeamControlView;
70
+ /**
71
+ * Run one control verb.
72
+ *
73
+ * `by: 'user'` ALWAYS, and not a parameter: this surface is a human pressing a
74
+ * button. A lead-initiated action reaches the runtime through its own tool, and
75
+ * conflating the two would make the report's Control section attribute a button
76
+ * press to the model.
77
+ */
78
+ export declare function controlTeam(source: TeamControlSource, request: TeamControlRequest): {
79
+ ok: boolean;
80
+ detail: string;
81
+ };
82
+ /** Exported for the tests' convenience: the runtime type this file must never leak. */
83
+ export type { TeamRuntime };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `host/team-control.ts` - the desktop control surface for a live dispatch
3
+ * (team-detached-dispatch section 7.3).
4
+ *
5
+ * ASCII ONLY, and NO INK, NO REACT: this file is inside the `host/**` import
6
+ * closure that layering rule L9 keeps free of the UI packages, because the Electron
7
+ * main process evaluates it.
8
+ *
9
+ * THE POINT OF THIS FILE IS THE BOUNDARY. A renderer panel gets a handful of
10
+ * strings and sends a handful of verbs; it never sees a `TeamRuntime`, a handle or
11
+ * a phase enum of its own. That is what keeps the desktop honest about the same
12
+ * facts the terminal shows - both read `TeamRuntime.inspect()`, and the panel
13
+ * renders what it is given rather than re-deriving it.
14
+ *
15
+ * NO NEW STREAM. The live roster keeps arriving over the existing team channel
16
+ * (`attachTeamChannel`); this only answers "what is true now" and "do this".
17
+ */
18
+ /** Project the runtime's inspection into the panel's shape. Pure. */
19
+ export function readTeamControl(source) {
20
+ const { inspection } = source.readTeamControl();
21
+ if (inspection === null)
22
+ return { dispatch: null, rows: [], mail: 0 };
23
+ return {
24
+ dispatch: {
25
+ id: inspection.dispatchId,
26
+ live: inspection.live,
27
+ startedAt: inspection.startedAt,
28
+ requested: inspection.requested,
29
+ },
30
+ rows: inspection.children.map((child) => ({
31
+ label: child.label,
32
+ description: child.description,
33
+ phase: child.phase,
34
+ ...(child.pausedBy !== undefined ? { by: child.pausedBy } : {}),
35
+ elapsedMs: child.elapsedMs,
36
+ turns: child.turns,
37
+ toolCalls: child.toolCalls,
38
+ ...(child.lastTool !== undefined ? { lastTool: child.lastTool } : {}),
39
+ ...(child.pausedMs !== undefined ? { pausedMs: child.pausedMs } : {}),
40
+ ...(child.error !== undefined ? { error: child.error } : {}),
41
+ })),
42
+ mail: inspection.mail.length,
43
+ };
44
+ }
45
+ /**
46
+ * Run one control verb.
47
+ *
48
+ * `by: 'user'` ALWAYS, and not a parameter: this surface is a human pressing a
49
+ * button. A lead-initiated action reaches the runtime through its own tool, and
50
+ * conflating the two would make the report's Control section attribute a button
51
+ * press to the model.
52
+ */
53
+ export function controlTeam(source, request) {
54
+ return source.sendTeamControl(request, 'user');
55
+ }