@aragon-agent/cli 0.6.62 → 0.6.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +70 -2
  2. package/README.md +143 -27
  3. package/dist/agent/controller.d.ts +66 -14
  4. package/dist/agent/controller.js +291 -81
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +62 -3
  7. package/dist/agent/team-notices.d.ts +57 -7
  8. package/dist/agent/team-notices.js +93 -10
  9. package/dist/app/App.js +199 -77
  10. package/dist/cli.js +4 -1
  11. package/dist/commands/builtins.js +2 -1
  12. package/dist/commands/catalog.js +1 -1
  13. package/dist/compaction/archive.d.ts +27 -1
  14. package/dist/compaction/archive.js +8 -0
  15. package/dist/compaction/budget.d.ts +73 -0
  16. package/dist/compaction/budget.js +89 -0
  17. package/dist/compaction/child.js +6 -1
  18. package/dist/compaction/command.js +147 -1
  19. package/dist/compaction/compactor.d.ts +132 -15
  20. package/dist/compaction/compactor.js +288 -95
  21. package/dist/compaction/context-command.js +21 -0
  22. package/dist/compaction/memory-agent-prompt.d.ts +32 -0
  23. package/dist/compaction/memory-agent-prompt.js +76 -0
  24. package/dist/compaction/memory-agent-tools.d.ts +88 -0
  25. package/dist/compaction/memory-agent-tools.js +338 -0
  26. package/dist/compaction/memory-agent.d.ts +114 -0
  27. package/dist/compaction/memory-agent.js +220 -0
  28. package/dist/compaction/prune.d.ts +129 -0
  29. package/dist/compaction/prune.js +386 -0
  30. package/dist/compaction/retry-plan.d.ts +103 -0
  31. package/dist/compaction/retry-plan.js +136 -0
  32. package/dist/compaction/summarize-ladder.d.ts +149 -0
  33. package/dist/compaction/summarize-ladder.js +273 -0
  34. package/dist/compaction/wiring.d.ts +19 -0
  35. package/dist/compaction/wiring.js +65 -1
  36. package/dist/config/cli-commands.d.ts +2 -2
  37. package/dist/config/cli-commands.js +27 -0
  38. package/dist/config/env.d.ts +3 -1
  39. package/dist/config/env.js +44 -2
  40. package/dist/exec/events.d.ts +30 -0
  41. package/dist/exec/index.js +2 -0
  42. package/dist/exec/runner.js +16 -1
  43. package/dist/gene/commit-prepare.js +27 -1
  44. package/dist/gene/curator/curator.d.ts +15 -0
  45. package/dist/gene/curator/curator.js +26 -2
  46. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  47. package/dist/gene/curator/scripted-lane.js +101 -0
  48. package/dist/gene/curator/task-context.d.ts +21 -0
  49. package/dist/gene/curator/task-context.js +33 -0
  50. package/dist/gene/curator/task-runner.d.ts +10 -1
  51. package/dist/gene/curator/task-runner.js +39 -4
  52. package/dist/gene/curator/tool-support.js +11 -4
  53. package/dist/gene/curator/toolkit.d.ts +13 -0
  54. package/dist/gene/curator/toolkit.js +23 -1
  55. package/dist/gene/curator/tools-verify.js +2 -2
  56. package/dist/gene/curator/tools-write.js +6 -1
  57. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  58. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  59. package/dist/gene/curator/validate/knowledge.js +74 -11
  60. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  61. package/dist/gene/curator/validate/prompts.js +2 -2
  62. package/dist/gene/learn/draft-guard.d.ts +17 -0
  63. package/dist/gene/learn/draft-guard.js +113 -0
  64. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  65. package/dist/gene/learn/learn-prompt.js +27 -2
  66. package/dist/gene/learn/learner.js +20 -2
  67. package/dist/gene/queue.d.ts +16 -0
  68. package/dist/gene/queue.js +44 -1
  69. package/dist/governance/store/run-store.d.ts +20 -0
  70. package/dist/governance/store/run-store.js +54 -8
  71. package/dist/host/index.d.ts +1 -0
  72. package/dist/host/index.js +1 -0
  73. package/dist/host/interaction.d.ts +8 -17
  74. package/dist/host/interaction.js +50 -72
  75. package/dist/host/team-wake-driver.d.ts +90 -0
  76. package/dist/host/team-wake-driver.js +114 -0
  77. package/dist/logging/install.d.ts +59 -1
  78. package/dist/logging/install.js +15 -0
  79. package/dist/session/validate-session.js +11 -0
  80. package/dist/team/console-tools.d.ts +12 -0
  81. package/dist/team/console-tools.js +20 -3
  82. package/dist/team/console-view.js +11 -1
  83. package/dist/team/notices.d.ts +81 -4
  84. package/dist/team/notices.js +187 -22
  85. package/dist/team/prompt.js +1 -1
  86. package/dist/team/runtime.d.ts +67 -24
  87. package/dist/team/runtime.js +250 -31
  88. package/dist/team/stall-watch.d.ts +54 -0
  89. package/dist/team/stall-watch.js +119 -0
  90. package/dist/team/task-tool.js +2 -2
  91. package/dist/team/wake.d.ts +176 -0
  92. package/dist/team/wake.js +444 -0
  93. package/package.json +81 -81
@@ -24,8 +24,9 @@ import { TeamHumanQueue } from '../team/human-queue.js';
24
24
  import { createFastOverseerProvider } from '../team/overseer.js';
25
25
  import { createTaskTool } from '../team/task-tool.js';
26
26
  import { createConsoleTools } from '../team/console-tools.js';
27
- import { TeamNoticeQueue } from '../team/notices.js';
27
+ import { TeamNoticeQueue, attentionFactOf, firstLine, settleFactsOf, } from '../team/notices.js';
28
28
  import { TeamNoticeRelay } from './team-notices.js';
29
+ import { TeamWakeGovernor, } from '../team/wake.js';
29
30
  import { buildDispatchReport } from '../team/report.js';
30
31
  import { renderPauseResult, renderResumeResult, renderSendResult, renderSpawnResult, renderStopResult, } from '../team/console-view.js';
31
32
  import { splitBriefIntoSpecs } from '../team/normalize.js';
@@ -478,6 +479,22 @@ export class AgentController {
478
479
  */
479
480
  teamNotices = new TeamNoticeQueue();
480
481
  teamRelay;
482
+ /**
483
+ * The wake governor (team-lead-wake-signals): "the team needs the lead - is now the
484
+ * moment to start a turn?". Level-triggered over the relay's ledger, so a dispatch
485
+ * that ends while the lead is idle still wakes it. Built next to the relay.
486
+ */
487
+ teamWake;
488
+ /** Dispatches started DETACHED; only these produce notices and wakes (I-WK3). */
489
+ detachedDispatches = new Set();
490
+ /**
491
+ * `prompt()` / `continue()` calls between entry and exit. The engine's own
492
+ * `isRunning()` is false for the whole `gene.planForTurn` await, but a turn is
493
+ * certainly starting then; the governor must not start a second one (RV-P2-10).
494
+ */
495
+ promptInFlight = 0;
496
+ /** Distinguishes one notice steer's receipt id from the next. */
497
+ noticeSequence = 0;
481
498
  /**
482
499
  * The monotonic turn counter behind `I-DD11`.
483
500
  *
@@ -737,12 +754,10 @@ export class AgentController {
737
754
  ...(confirm ? { humanQueue: new TeamHumanQueue(confirm) } : {}),
738
755
  // THE DETACHED-DISPATCH WIRING (team-detached-dispatch section 5.1).
739
756
  //
740
- // `currentTurnId` + `isLeadRunning` are what make `I-DD11` possible: a
741
- // dispatch remembers the turn that started it, so `stopEngine()` can tell
742
- // "stop my own turn and its team" from "stop an unrelated turn and leave a
743
- // 100-minute dispatch alone".
757
+ // `currentTurnId` is what makes `I-DD11` possible: a dispatch remembers the
758
+ // turn that started it, so `stopEngine()` can tell "stop my own turn and its
759
+ // team" from "stop an unrelated turn and leave a 100-minute dispatch alone".
744
760
  currentTurnId: () => this.turnId,
745
- isLeadRunning: () => this.agent.state.isRunning,
746
761
  // THE REPORT'S ONE PRODUCER (REV-05). The SAME closure is handed to
747
762
  // `createTaskTool` below, so the await path and the detach path price a
748
763
  // dispatch identically - one table, one disclosure line.
@@ -881,9 +896,41 @@ export class AgentController {
881
896
  // `noticeSteer` and it is not silenced by any config key.
882
897
  this.teamRelay = new TeamNoticeRelay({
883
898
  queue: this.teamNotices,
884
- steer: (text) => this.enqueueSteering(text, false),
899
+ // THE RECEIPT-CARRYING STEER (team-lead-wake-signals I-WK6): Core echoes
900
+ // `steering_accepted` only for a steer that has an id, so the ledger can be
901
+ // released per steer instead of "any receipt frees everything".
902
+ steer: (text) => this.enqueueSteering(text, false, undefined, true),
903
+ withdraw: (receiptId) => this.agent.removeQueuedSteering(receiptId),
885
904
  isAtSafeSteerPoint: () => this.isAtSafeSteerPoint(),
886
- canSteerBeforeTurn: () => this.activeToolCalls === 0 && !this.abortRequested,
905
+ // `abortRequested` is set by `stopEngine()` and cleared only at the next
906
+ // `agent_start` - which is AFTER this check runs. Alone it would refuse the
907
+ // fill for the first turn after any Esc, the wake turn included. It only means
908
+ // something while the engine is still running (RV-P1-5).
909
+ canSteerBeforeTurn: () => this.activeToolCalls === 0 && (!this.abortRequested || !this.isRunning()),
910
+ });
911
+ this.teamWake = new TeamWakeGovernor({
912
+ owed: () => this.owedAttention(),
913
+ reclaimStranded: () => this.teamRelay?.requeueUndelivered(),
914
+ config: () => ({
915
+ autoResume: this.config.team.autoResume,
916
+ settleGraceMs: this.config.team.settleGraceMs,
917
+ }),
918
+ leadFacts: () => ({
919
+ running: this.isRunning() || this.promptInFlight > 0,
920
+ compacting: this.isCompactionBusy(),
921
+ userPending: this.hasPendingUserMessages(),
922
+ }),
923
+ now: () => Date.now(),
924
+ setTimer: (fn, ms) => {
925
+ const timer = setTimeout(fn, ms);
926
+ timer.unref?.();
927
+ return () => clearTimeout(timer);
928
+ },
929
+ setImmediate: (fn) => {
930
+ setImmediate(fn);
931
+ },
932
+ log: (level, event, fields) => getLogger()[level]('agent', event, fields),
933
+ notifyHost: (level, text) => this.notifyHostFn?.(level, text),
887
934
  });
888
935
  // The SOURCE is the runtime's own event stream: `child_settled` /
889
936
  // `dispatch_settled` / `lead_mail` are all derived here, once, so the notices
@@ -1130,6 +1177,11 @@ export class AgentController {
1130
1177
  ...createConsoleTools({
1131
1178
  runtime: this.teamRuntime,
1132
1179
  hasPendingUserInput: () => this.hasPendingUserMessages(),
1180
+ // `team_collect` returning the report must not leave a copy to be
1181
+ // delivered again, and a signal that arrives while it waits must end the
1182
+ // wait (team-lead-wake-signals 4.8).
1183
+ acknowledgeSettle: (dispatchId) => this.acknowledgeTeamSettle(dispatchId),
1184
+ hasPendingTeamAttention: () => this.hasPendingTeamAttention(),
1133
1185
  }),
1134
1186
  ]
1135
1187
  : [],
@@ -1393,9 +1445,12 @@ export class AgentController {
1393
1445
  // A receipt means Core took a batch out of the queue, which is the only
1394
1446
  // proof a steered notice has that it was not discarded (§4.6.1).
1395
1447
  this.jobRelay?.onSteeringAccepted();
1396
- // The team relay needs the SAME proof: a settle report steered without a
1397
- // receipt is otherwise invisible to `fast`'s `clearAllQueues()`.
1398
- this.teamRelay?.onSteeringAccepted();
1448
+ // The team relay needs the SAME proof, but per steer: only the notices a
1449
+ // receipted steer carried are delivered. A delivered attention notice shrinks
1450
+ // what the lead is owed, so the governor looks again (and stops its retry beat).
1451
+ const delivered = this.teamRelay?.onSteeringAccepted(event.ids) ?? [];
1452
+ if (delivered.length > 0)
1453
+ this.teamWake?.poke();
1399
1454
  }
1400
1455
  // THE BATCH COUNTER (D-5 / I-5). Decremented BEFORE the push attempt below,
1401
1456
  // because "the batch is empty" is only true after the last one has ended.
@@ -1440,6 +1495,11 @@ export class AgentController {
1440
1495
  // covers a run that ended with a notice stranded in the queue.
1441
1496
  this.jobRelay?.requeueUndelivered();
1442
1497
  this.teamRelay?.requeueUndelivered();
1498
+ // THE LEAD IS IDLE AGAIN: whatever the team still owes it is now collectable.
1499
+ // After the requeue (so stranded notices are back in the queue the governor
1500
+ // reads). `abortRequested` is still in force here - it clears at the NEXT
1501
+ // `agent_start` - and is exactly "the user stopped this turn" (I-WK8).
1502
+ this.teamWake?.onLeadIdle({ aborted: this.abortRequested });
1443
1503
  // AFTER the requeue, so a turn that ends with a stranded notice still gets
1444
1504
  // its feedback line. Order between the two is otherwise irrelevant.
1445
1505
  this.maybeReportSkillTriage();
@@ -1781,6 +1841,7 @@ export class AgentController {
1781
1841
  if (this.modelMetadataEnabled)
1782
1842
  void this.refreshModelMetadata();
1783
1843
  const request = ++this.startupSequence;
1844
+ this.promptInFlight += 1;
1784
1845
  try {
1785
1846
  if (this.agent.state.isRunning) {
1786
1847
  this.stopEngine();
@@ -1809,6 +1870,9 @@ export class AgentController {
1809
1870
  this.notifyHostFn?.('error', `Could not start the run: ${reason}`);
1810
1871
  return { status: 'not-started', reason: 'failed' };
1811
1872
  }
1873
+ finally {
1874
+ this.promptInFlight -= 1;
1875
+ }
1812
1876
  }
1813
1877
  /**
1814
1878
  * Wait for the engine to unwind, bounded.
@@ -1956,6 +2020,10 @@ export class AgentController {
1956
2020
  // what the Esc ladder's second press and `/team stop all` call.
1957
2021
  const live = this.teamRuntime?.live() ?? null;
1958
2022
  if (live === null || live.turnId === this.turnId) {
2023
+ // The user ended this team on purpose; the settle that follows is not news to them
2024
+ // and must not wake the lead for it (I-WK11).
2025
+ if (live !== null)
2026
+ this.teamRuntime?.noteAbortedBy('user');
1959
2027
  this.teamRuntime?.abortAll();
1960
2028
  }
1961
2029
  }
@@ -2076,12 +2144,25 @@ export class AgentController {
2076
2144
  queueUserMessage(text, parts) {
2077
2145
  return this.enqueueSteering(text, true, parts);
2078
2146
  }
2079
- enqueueSteering(text, user, parts) {
2147
+ /**
2148
+ * `receipt` (notices only, team-lead-wake-signals) asks for an id WITHOUT making the
2149
+ * steer a user message: Core echoes `steering_accepted` for any steer that has one,
2150
+ * and the team relay needs that echo. It is deliberately NOT written to
2151
+ * `pendingUserSteering` - `hasPendingUserMessages()`, `withdrawQueuedUserMessage()`,
2152
+ * `continue()` and `fast`'s `userSteerCount` all read that map and mean "the user is
2153
+ * waiting for an answer". The `notice:` prefix keeps every other receipt consumer
2154
+ * treating it as an unknown id.
2155
+ */
2156
+ enqueueSteering(text, user, parts, receipt) {
2080
2157
  // Both reviewer and user guidance can activate queued skill frames.
2081
2158
  if (this.skillsEnabled && this.isRunning())
2082
2159
  this.skills.absorbPendingFrames();
2083
- const id = user ? `${this.steeringPrefix}:${++this.steeringSequence}` : undefined;
2084
- if (id !== undefined)
2160
+ const id = user
2161
+ ? `${this.steeringPrefix}:${++this.steeringSequence}`
2162
+ : receipt === true
2163
+ ? `notice:${this.steeringPrefix}:${++this.noticeSequence}`
2164
+ : undefined;
2165
+ if (user && id !== undefined)
2085
2166
  this.pendingUserSteering.set(id, text);
2086
2167
  try {
2087
2168
  // The legacy two-argument call is kept verbatim when there are no parts.
@@ -2091,7 +2172,7 @@ export class AgentController {
2091
2172
  this.agent.steer(text, id);
2092
2173
  }
2093
2174
  catch (error) {
2094
- if (id !== undefined)
2175
+ if (user && id !== undefined)
2095
2176
  this.pendingUserSteering.delete(id);
2096
2177
  throw error;
2097
2178
  }
@@ -2133,20 +2214,28 @@ export class AgentController {
2133
2214
  if (this.modelSettingsBlocked || this.isRunning()) {
2134
2215
  return { status: 'not-started', reason: 'failed' };
2135
2216
  }
2136
- if (this.pendingUserSteering.size > 0) {
2137
- const request = ++this.startupSequence;
2138
- this.prepareUserTurn([...this.pendingUserSteering.values()].join('\n\n'), { steering: true });
2139
- if (request !== this.startupSequence) {
2140
- return { status: 'not-started', reason: 'cancelled' };
2217
+ this.promptInFlight += 1;
2218
+ try {
2219
+ if (this.pendingUserSteering.size > 0) {
2220
+ const request = ++this.startupSequence;
2221
+ this.prepareUserTurn([...this.pendingUserSteering.values()].join('\n\n'), {
2222
+ steering: true,
2223
+ });
2224
+ if (request !== this.startupSequence) {
2225
+ return { status: 'not-started', reason: 'cancelled' };
2226
+ }
2227
+ this.todos?.beginUserTurn('new-task');
2141
2228
  }
2142
- this.todos?.beginUserTurn('new-task');
2229
+ // The `continue()` path needs its own delivery for the reason RV-P1-7 gives:
2230
+ // a run that ended with a notice still queued resumes through here, and this
2231
+ // is the most common way a stranded notice gets its second chance.
2232
+ this.flushPendingNotices();
2233
+ await this.agent.continue();
2234
+ return { status: 'finished' };
2235
+ }
2236
+ finally {
2237
+ this.promptInFlight -= 1;
2143
2238
  }
2144
- // The `continue()` path needs its own delivery for the reason RV-P1-7 gives:
2145
- // a run that ended with a notice still queued resumes through here, and this
2146
- // is the most common way a stranded notice gets its second chance.
2147
- this.flushPendingNotices();
2148
- await this.agent.continue();
2149
- return { status: 'finished' };
2150
2239
  }
2151
2240
  /** Pending user receipts survive until Core accepts or the host clears them. */
2152
2241
  hasPendingUserMessages() { return this.pendingUserSteering.size > 0; }
@@ -2995,29 +3084,64 @@ export class AgentController {
2995
3084
  const live = runtime.live();
2996
3085
  return live !== null && live.turnId !== this.turnId;
2997
3086
  }
3087
+ // -----------------------------------------------------------------------
3088
+ // The lead wake signals (team-lead-wake-signals)
3089
+ // -----------------------------------------------------------------------
2998
3090
  /**
2999
- * The settle facts for the live-or-last dispatch, for the follow-up decision.
3000
- *
3001
- * THE ID TRAVELS WITH THE FACTS. The host spends the continuation with
3002
- * `markTeamContinued()`, and the facts are by definition read AFTER settlement,
3003
- * when `TeamRuntime.live()` already answers `null` - so an id re-derived from
3004
- * `live()` was always null, `session.continued` was never set, and every later
3005
- * `agent_end` earned the same follow-up turn: an unbounded model loop that
3006
- * never lets the user type.
3091
+ * Every attention notice the lead has not been PROVEN to have: the queue plus the
3092
+ * relay's ledger, oldest first. The governor's one input.
3007
3093
  */
3008
- teamSettleFacts() {
3009
- const runtime = this.teamRuntime;
3010
- if (!runtime)
3011
- return null;
3012
- const id = runtime.currentDispatchId();
3013
- if (id === null)
3014
- return null;
3015
- const facts = runtime.settleFacts(id);
3016
- return facts === null ? null : { ...facts, dispatchId: id };
3094
+ owedAttention() {
3095
+ const facts = [];
3096
+ for (const notice of this.teamRelay?.undelivered() ?? []) {
3097
+ const fact = attentionFactOf(notice);
3098
+ if (fact !== null)
3099
+ facts.push(fact);
3100
+ }
3101
+ return facts.sort((a, b) => a.at - b.at);
3017
3102
  }
3018
- /** Spend the one follow-up turn of the current dispatch (at most one). */
3019
- markTeamContinued(dispatchId) {
3020
- this.teamRuntime?.markContinued(dispatchId);
3103
+ /**
3104
+ * Register THE host of wake requests (one at a time). The terminal app and the
3105
+ * desktop coordinator both do it through `host/team-wake-driver.ts`.
3106
+ */
3107
+ subscribeTeamWake(listener) {
3108
+ return this.teamWake?.subscribe(listener) ?? (() => { });
3109
+ }
3110
+ /**
3111
+ * The fire-time re-check: still owed, lead still idle, no user message waiting - and
3112
+ * the `<team_signal>` text to submit, rendered NOW so anything that arrived during
3113
+ * the countdown is in it. Synchronous and never throws (I-WK10).
3114
+ */
3115
+ confirmTeamWake(requestId) {
3116
+ return this.teamWake?.begin(requestId) ?? { ok: false, why: 'disposed' };
3117
+ }
3118
+ ackTeamWake(requestId, result) {
3119
+ this.teamWake?.ack(requestId, result);
3120
+ }
3121
+ /** Whether any attention notice is undelivered. `team_collect` stops waiting on it. */
3122
+ hasPendingTeamAttention() {
3123
+ return this.owedAttention().length > 0;
3124
+ }
3125
+ /**
3126
+ * `team_collect` has just put this dispatch's report in a tool result, so the settle
3127
+ * notice must not deliver it again (RC-8).
3128
+ */
3129
+ acknowledgeTeamSettle(dispatchId) {
3130
+ this.teamRelay?.dropById(`${dispatchId}:end`);
3131
+ this.teamWake?.poke();
3132
+ }
3133
+ /** The runtime's live roster as `still running` count: queued + running + paused. */
3134
+ stillRunningCount() {
3135
+ const roster = this.teamRuntime?.inspect() ?? null;
3136
+ if (roster === null)
3137
+ return 0;
3138
+ return roster.counts.queued + roster.counts.running + roster.counts.paused;
3139
+ }
3140
+ /** Forget everything the team owed the previous conversation. */
3141
+ resetTeamSignals() {
3142
+ this.teamWake?.reset();
3143
+ this.teamNotices.clear();
3144
+ this.teamRelay?.reset();
3021
3145
  }
3022
3146
  /**
3023
3147
  * Turn one runtime event into a notice (section 5.3.1).
@@ -3026,28 +3150,30 @@ export class AgentController {
3026
3150
  * queue must agree about what happened, and the only way to guarantee that is for
3027
3151
  * all three to read the same event. The queue adds nothing but the "exactly once"
3028
3152
  * bookkeeping.
3153
+ *
3154
+ * ONLY DETACHED DISPATCHES (I-WK3). A blocking dispatch already returns its report
3155
+ * in the `task` result, so a notice about it would deliver the same report twice -
3156
+ * and, now that notices wake the lead, would also start a turn for nothing. The one
3157
+ * exception to "seen `dispatch_start` first" is `dispatch_end.detached`, which the
3158
+ * runtime sets itself so a dispatch that died before it could announce its start
3159
+ * still reaches the lead (I-WK15).
3029
3160
  */
3030
3161
  onTeamEvent(event) {
3162
+ if (event.type === 'dispatch_start') {
3163
+ if (event.detached !== true)
3164
+ return;
3165
+ this.detachedDispatches.add(event.dispatchId);
3166
+ this.teamWake?.onDispatchStart();
3167
+ return;
3168
+ }
3169
+ const detached = this.detachedDispatches.has(event.dispatchId) ||
3170
+ (event.type === 'dispatch_end' && event.detached === true);
3171
+ if (!detached)
3172
+ return;
3031
3173
  switch (event.type) {
3032
- case 'agent_update': {
3033
- const phase = event.run.phase;
3034
- if (phase !== 'done' && phase !== 'failed' && phase !== 'aborted')
3035
- break;
3036
- const elapsedMs = (event.run.endedAt ?? Date.now()) - (event.run.startedAt ?? Date.now());
3037
- this.teamNotices.push({
3038
- kind: 'child_settled',
3039
- id: `${event.dispatchId}:${event.run.label}:${phase}`,
3040
- dispatchId: event.dispatchId,
3041
- label: event.run.label,
3042
- phase,
3043
- elapsedMs,
3044
- turns: event.run.turns,
3045
- toolCalls: event.run.toolCalls,
3046
- ...(event.run.error !== undefined ? { error: event.run.error } : {}),
3047
- at: Date.now(),
3048
- });
3174
+ case 'agent_update':
3175
+ this.noteChildSettled(event);
3049
3176
  break;
3050
- }
3051
3177
  case 'lead_mail':
3052
3178
  this.teamNotices.push({
3053
3179
  kind: 'lead_mail',
@@ -3061,27 +3187,102 @@ export class AgentController {
3061
3187
  at: Date.now(),
3062
3188
  });
3063
3189
  break;
3064
- case 'dispatch_end': {
3065
- const report = this.teamRuntime?.reportText(event.dispatchId) ??
3066
- buildDispatchReport(event.outcome, this.teamReportOptions());
3067
- this.teamNotices.push({
3068
- kind: 'dispatch_settled',
3069
- id: `${event.dispatchId}:end`,
3070
- dispatchId: event.dispatchId,
3071
- report,
3072
- aborted: event.outcome.aborted,
3073
- at: Date.now(),
3074
- });
3075
- // ONE PUSH ATTEMPT. If the lead is not at a safe steer point (it is
3076
- // mid-batch), the notice stays queued and the next boundary, the next turn
3077
- // or the settle follow-up delivers it - the ledger guarantees that.
3078
- this.teamRelay?.tryPush();
3190
+ case 'child_failed':
3191
+ this.noteChildFailed(event);
3192
+ break;
3193
+ case 'stalled':
3194
+ this.noteStalled(event);
3195
+ break;
3196
+ case 'dispatch_end':
3197
+ this.noteDispatchEnd(event);
3079
3198
  break;
3080
- }
3081
3199
  default:
3082
3200
  break;
3083
3201
  }
3084
3202
  }
3203
+ /** `done` / `aborted` are chatter; `failed` is a SIGNAL and arrives as `child_failed`. */
3204
+ noteChildSettled(event) {
3205
+ const phase = event.run.phase;
3206
+ if (phase !== 'done' && phase !== 'aborted')
3207
+ return;
3208
+ const elapsedMs = (event.run.endedAt ?? Date.now()) - (event.run.startedAt ?? Date.now());
3209
+ this.teamNotices.push({
3210
+ kind: 'child_settled',
3211
+ id: `${event.dispatchId}:${event.run.label}:${phase}`,
3212
+ dispatchId: event.dispatchId,
3213
+ label: event.run.label,
3214
+ phase,
3215
+ elapsedMs,
3216
+ turns: event.run.turns,
3217
+ toolCalls: event.run.toolCalls,
3218
+ ...(event.run.error !== undefined ? { error: event.run.error } : {}),
3219
+ at: Date.now(),
3220
+ });
3221
+ }
3222
+ noteChildFailed(event) {
3223
+ const { run } = event;
3224
+ const now = Date.now();
3225
+ this.teamNotices.push({
3226
+ kind: 'child_failed',
3227
+ id: `${event.dispatchId}:fail:${run.label}`,
3228
+ dispatchId: event.dispatchId,
3229
+ label: run.label,
3230
+ error: firstLine(run.error ?? ''),
3231
+ elapsedMs: (run.endedAt ?? now) - (run.startedAt ?? now),
3232
+ turns: run.turns,
3233
+ toolCalls: run.toolCalls,
3234
+ stillRunning: this.stillRunningCount(),
3235
+ at: now,
3236
+ });
3237
+ this.raiseSignal(event.dispatchId, 'child_failed', true);
3238
+ }
3239
+ noteStalled(event) {
3240
+ this.teamNotices.push({
3241
+ kind: 'team_stalled',
3242
+ id: `${event.dispatchId}:stall:${event.episode}`,
3243
+ dispatchId: event.dispatchId,
3244
+ episode: event.episode,
3245
+ quietMs: event.quietMs,
3246
+ blockers: event.blockers,
3247
+ at: Date.now(),
3248
+ });
3249
+ getLogger().info('agent', 'team_stall_detected', {
3250
+ dispatchId: event.dispatchId,
3251
+ episode: event.episode,
3252
+ blockers: event.blockers.length,
3253
+ quietMs: event.quietMs,
3254
+ });
3255
+ this.raiseSignal(event.dispatchId, 'stalled', true);
3256
+ }
3257
+ noteDispatchEnd(event) {
3258
+ const report = this.teamRuntime?.reportText(event.dispatchId) ??
3259
+ buildDispatchReport(event.outcome, this.teamReportOptions());
3260
+ // A stop the user or the lead ordered is news to nobody (I-WK11): the notice still
3261
+ // goes in the queue and still travels with the next turn, but it owes no wake.
3262
+ const stoppedBy = this.teamRuntime?.abortedBy(event.dispatchId);
3263
+ const attention = stoppedBy !== 'user' && stoppedBy !== 'lead';
3264
+ this.teamNotices.push({
3265
+ kind: 'dispatch_settled',
3266
+ id: `${event.dispatchId}:end`,
3267
+ dispatchId: event.dispatchId,
3268
+ report,
3269
+ aborted: event.outcome.aborted,
3270
+ attention,
3271
+ facts: settleFactsOf(event.outcome),
3272
+ at: Date.now(),
3273
+ });
3274
+ this.detachedDispatches.delete(event.dispatchId);
3275
+ // ONE PUSH ATTEMPT. If the lead is not at a safe steer point (it is mid-batch),
3276
+ // the notice stays queued and the next boundary, the next turn or the wake
3277
+ // delivers it - the ledger guarantees that.
3278
+ this.teamRelay?.tryPush();
3279
+ this.raiseSignal(event.dispatchId, 'settled', attention);
3280
+ }
3281
+ raiseSignal(dispatchId, kind, attention) {
3282
+ getLogger().info('agent', 'team_signal_raised', { dispatchId, kind, attention });
3283
+ if (attention)
3284
+ this.teamWake?.poke();
3285
+ }
3085
3286
  /** Refused mid-dispatch by `/team`; half a dispatch under two ceilings is not
3086
3287
  * a result anything can afterwards explain (the reasoning `/reload` uses). */
3087
3288
  isTeamBusy() {
@@ -3107,6 +3308,7 @@ export class AgentController {
3107
3308
  this.disposed = true;
3108
3309
  this.modelMetadataGeneration += 1;
3109
3310
  this.modelMetadataAbort.abort();
3311
+ this.teamWake?.dispose();
3110
3312
  this.teamRuntime?.dispose();
3111
3313
  // Flushes usage, stops the learner / curator / maintenance and releases the lease. Never rejects.
3112
3314
  void this.gene?.dispose();
@@ -3594,6 +3796,8 @@ export class AgentController {
3594
3796
  */
3595
3797
  clearMessages() {
3596
3798
  this.gene?.resetSession('clear');
3799
+ // A new conversation owes nothing to the old one's team (I-WK12).
3800
+ this.resetTeamSignals();
3597
3801
  this.idleCompaction?.abort();
3598
3802
  this.restoredCompactionIdentity = undefined;
3599
3803
  this.agent.clearMessages();
@@ -3685,6 +3889,7 @@ export class AgentController {
3685
3889
  }
3686
3890
  replaceMessages(messages, identity) {
3687
3891
  this.gene?.resetSession('resume');
3892
+ this.resetTeamSignals();
3688
3893
  this.idleCompaction?.abort();
3689
3894
  this.restoredCompactionIdentity = identity;
3690
3895
  this.agent.replaceMessages(messages);
@@ -3729,6 +3934,9 @@ export class AgentController {
3729
3934
  // receipt id. Anything still unproven goes straight back into the notice
3730
3935
  // queue, so the wipe costs a delay instead of a fact the model never learns.
3731
3936
  this.jobRelay?.requeueUndelivered();
3937
+ // THE TEAM RELAY HAS THE SAME EXPOSURE (RC-9) and was simply missing here: a team
3938
+ // notice steered but not yet accepted is invisible to `fast`'s counter too.
3939
+ this.teamRelay?.requeueUndelivered();
3732
3940
  }
3733
3941
  // -----------------------------------------------------------------------
3734
3942
  // Model / provider info
@@ -4180,6 +4388,8 @@ export class AgentController {
4180
4388
  if (this.idleCompaction === controller) {
4181
4389
  this.idleCompaction = undefined;
4182
4390
  this.publishCompactionBusy(false);
4391
+ // The lead was "busy" for the governor while this ran; look again now.
4392
+ this.teamWake?.onLeadIdle({ aborted: false });
4183
4393
  }
4184
4394
  }
4185
4395
  }
@@ -12,11 +12,19 @@ import type { TodoEvent, TodoSnapshot } from '@aragon-agent/tui/model/todo/types
12
12
  import type { FastEvent } from '@aragon-agent/tui/model/fast/types';
13
13
  import type { CompactionEvent } from '@aragon-agent/tui/model/compaction/types';
14
14
  import { type FollowThroughMode } from '@aragon-agent/tui/model/todo/follow-through';
15
+ import type { RunResumePolicy } from '@aragon-agent/tui/model/config/schema';
15
16
  /** The minimal controller surface headless mode needs (real or stubbed). */
16
17
  export interface HeadlessController {
17
18
  preflight(): PreflightResult;
18
19
  subscribe(listener: (event: AgentEvent) => void): () => void;
19
20
  prompt(text: string): Promise<void | PromptOutcome>;
21
+ /**
22
+ * Re-run the loop from the current history WITHOUT adding a message - OPTIONAL,
23
+ * for the identical reason the subscriptions below are (team-idle-watchdog-dead-run
24
+ * F3). ABSENT MEANS A RECOVERY IS NEVER ATTEMPTED, which keeps a stubbed
25
+ * controller's stdout, stderr and exit code byte-identical to today's.
26
+ */
27
+ continue?(): Promise<void | PromptOutcome>;
20
28
  getModelInfo(): ModelInfo;
21
29
  /**
22
30
  * The CLI-local team stream — OPTIONAL, deliberately (team-subagents §3.12 /
@@ -75,6 +83,14 @@ export interface HeadlessOptions {
75
83
  * `getTodoConfig().followThrough` there.
76
84
  */
77
85
  followThrough?: FollowThroughMode;
86
+ /**
87
+ * Whether, and how often, to re-run a run the engine interrupted (idle watchdog,
88
+ * or a retry ladder that gave up on a transport failure). PASSED IN for the reason
89
+ * `followThrough` is: the real entry points hold the real controller and resolve it
90
+ * from `retry.*` with `toRunResumePolicy(..., { headless: true })`, which is where
91
+ * `-p` gets its one-recovery cap. ABSENT = no recovery, exactly as before.
92
+ */
93
+ resume?: RunResumePolicy;
78
94
  }
79
95
  /** Run a single prompt headlessly and resolve with the process exit code. */
80
96
  export declare function runHeadless(controller: HeadlessController, prompt: string, options?: HeadlessOptions): Promise<number>;