@aragon-agent/cli 0.6.57 → 0.6.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +159 -3
  3. package/dist/agent/controller.d.ts +112 -1
  4. package/dist/agent/controller.js +350 -7
  5. package/dist/agent/project-guidance-prompt.js +97 -97
  6. package/dist/agent/redteam-prompt.d.ts +29 -11
  7. package/dist/agent/redteam-prompt.js +118 -103
  8. package/dist/agent/redteam-wiring.d.ts +117 -2
  9. package/dist/agent/redteam-wiring.js +204 -1
  10. package/dist/agent/team-notices.d.ts +68 -0
  11. package/dist/agent/team-notices.js +82 -0
  12. package/dist/app/App.js +208 -5
  13. package/dist/app/use-redteam-mode.d.ts +1 -1
  14. package/dist/app/use-redteam-mode.js +14 -1
  15. package/dist/cli.js +13 -0
  16. package/dist/commands/catalog.js +6 -2
  17. package/dist/commands/redteam-command.d.ts +14 -8
  18. package/dist/commands/redteam-command.js +243 -12
  19. package/dist/commands/team-command.js +93 -2
  20. package/dist/config/app-paths.d.ts +19 -0
  21. package/dist/config/app-paths.js +23 -0
  22. package/dist/config/load.d.ts +8 -0
  23. package/dist/gene/catalog-sync.js +37 -16
  24. package/dist/gene/curator/budget.js +1 -1
  25. package/dist/gene/curator/curator.d.ts +6 -0
  26. package/dist/gene/curator/curator.js +8 -0
  27. package/dist/gene/curator/task-runner.js +4 -1
  28. package/dist/gene/curator/tools-verify.js +17 -5
  29. package/dist/gene/curator/validate/evidence-tokens.js +97 -18
  30. package/dist/gene/curator/validate/knowledge.d.ts +5 -0
  31. package/dist/gene/curator/validate/knowledge.js +57 -13
  32. package/dist/gene/curator/validate/types.d.ts +6 -1
  33. package/dist/gene/learn/learn-prompt.d.ts +10 -1
  34. package/dist/gene/learn/learn-prompt.js +11 -2
  35. package/dist/governance/engine/lifecycle.js +1 -1
  36. package/dist/governance/store/run-lock.d.ts +9 -2
  37. package/dist/governance/store/run-lock.js +91 -7
  38. package/dist/host/controller-factory.d.ts +13 -0
  39. package/dist/host/controller-factory.js +7 -0
  40. package/dist/host/index.d.ts +1 -0
  41. package/dist/host/index.js +1 -0
  42. package/dist/host/interaction.d.ts +19 -0
  43. package/dist/host/interaction.js +75 -0
  44. package/dist/host/team-control.d.ts +83 -0
  45. package/dist/host/team-control.js +55 -0
  46. package/dist/logging/install.d.ts +32 -1
  47. package/dist/logging/install.js +21 -0
  48. package/dist/proc/output-streams.d.ts +11 -0
  49. package/dist/proc/output-streams.js +11 -0
  50. package/dist/redteam/prompt-resolve.d.ts +61 -0
  51. package/dist/redteam/prompt-resolve.js +303 -0
  52. package/dist/redteam/prompt-store.d.ts +96 -0
  53. package/dist/redteam/prompt-store.js +156 -0
  54. package/dist/redteam/prompt-template.d.ts +22 -0
  55. package/dist/redteam/prompt-template.js +72 -0
  56. package/dist/team/bus.d.ts +18 -0
  57. package/dist/team/bus.js +70 -18
  58. package/dist/team/console-tools.d.ts +54 -0
  59. package/dist/team/console-tools.js +333 -0
  60. package/dist/team/console-view.d.ts +88 -0
  61. package/dist/team/console-view.js +173 -0
  62. package/dist/team/forced-mode.d.ts +61 -1
  63. package/dist/team/forced-mode.js +75 -0
  64. package/dist/team/normalize.d.ts +31 -0
  65. package/dist/team/normalize.js +49 -5
  66. package/dist/team/notices.d.ts +95 -0
  67. package/dist/team/notices.js +121 -0
  68. package/dist/team/pause-gate.d.ts +79 -0
  69. package/dist/team/pause-gate.js +127 -0
  70. package/dist/team/prompt.d.ts +25 -9
  71. package/dist/team/prompt.js +29 -29
  72. package/dist/team/report.js +33 -0
  73. package/dist/team/runtime.d.ts +270 -5
  74. package/dist/team/runtime.js +732 -64
  75. package/dist/team/settled.d.ts +5 -2
  76. package/dist/team/settled.js +12 -2
  77. package/dist/team/subagent.d.ts +7 -0
  78. package/dist/team/subagent.js +12 -1
  79. package/dist/team/task-tool.d.ts +39 -1
  80. package/dist/team/task-tool.js +75 -18
  81. package/dist/tools/bash-tool.d.ts +11 -8
  82. package/dist/tools/bash-tool.js +37 -9
  83. package/dist/tools/index.d.ts +2 -2
  84. package/dist/tools/index.js +30 -0
  85. package/package.json +3 -3
@@ -23,6 +23,12 @@ import { createChildReviewer } from '../team/child-reviewer.js';
23
23
  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
+ import { createConsoleTools } from '../team/console-tools.js';
27
+ import { TeamNoticeQueue } from '../team/notices.js';
28
+ import { TeamNoticeRelay } from './team-notices.js';
29
+ import { buildDispatchReport } from '../team/report.js';
30
+ import { renderPauseResult, renderResumeResult, renderSendResult, renderSpawnResult, renderStopResult, } from '../team/console-view.js';
31
+ import { splitBriefIntoSpecs } from '../team/normalize.js';
26
32
  import { resolveSubagentModel } from '@aragon-agent/tui/model/team/model';
27
33
  import { buildTeamBlock } from '../team/prompt.js';
28
34
  // THE THIRD LAYER's prompt half (team-command-forced-dispatch §3.6): spliced
@@ -34,6 +40,11 @@ import { TeamModeWiring, effectiveForced } from './team-mode-wiring.js';
34
40
  // permission predicate live in the wiring; this class forwards and composes the prompt.
35
41
  import { RedTeamWiring, bannerConfirmations, readWaiverVersionPort, writeWaiverVersionPort } from './redteam-wiring.js';
36
42
  import { buildRedTeamBanner } from './redteam-prompt.js';
43
+ // THE PROMPT PROFILE (redteam-prompt-profile 6.2): resolution in the CLI's `redteam/` tree,
44
+ // I/O only in the store, so this class keeps forwarding instead of reading files.
45
+ import { resolveRedTeamPrompt } from '../redteam/prompt-resolve.js';
46
+ import { promptProfileScaffold } from '../redteam/prompt-template.js';
47
+ import { clearPromptProfileCache, writePromptScaffold } from '../redteam/prompt-store.js';
37
48
  import { acceptRedTeamWaiver, getRedTeamWaiverVersion, } from '../config/ui-state.js';
38
49
  import { MemoryService, UNAVAILABLE_VIEW } from '../memory/service.js';
39
50
  import { createMemoryTools } from '../memory/tools.js';
@@ -458,6 +469,25 @@ export class AgentController {
458
469
  jobMirror;
459
470
  /** The relay: terminal events in, ledger across `steering_accepted`, safe-point push. */
460
471
  jobRelay;
472
+ /**
473
+ * The team notice queue and its relay (team-detached-dispatch section 5.3).
474
+ *
475
+ * BUILT ALWAYS, even when team mode was off at construction: the relay is inert
476
+ * without events, and a conditionally-constructed one would make `flushForTurn`,
477
+ * `tryPush` and `requeueUndelivered` three more places that need a guard.
478
+ */
479
+ teamNotices = new TeamNoticeQueue();
480
+ teamRelay;
481
+ /**
482
+ * The monotonic turn counter behind `I-DD11`.
483
+ *
484
+ * ONE PER `prompt()` / `continue()`, read by the runtime when a dispatch starts
485
+ * (`DispatchSession.turnId`) and compared by `stopEngine()`. A dispatch that
486
+ * outlives its turn is then distinguishable from one started by the turn the
487
+ * user is stopping - which is the whole difference between "Esc stops what I am
488
+ * doing" and "Esc silently killed a two-hour team".
489
+ */
490
+ turnId = 0;
461
491
  /** `cfg.jobs.enabled` AND `cfg.bash.background`, fixed at construction. */
462
492
  jobsRegistered = false;
463
493
  /**
@@ -584,6 +614,14 @@ export class AgentController {
584
614
  isRunning: () => this.isRunning() || this.isCompactionBusy(),
585
615
  rebuildPrompt: () => this.rebuildSystemPrompt(),
586
616
  log: (event) => this.logRedTeam(event),
617
+ // THE PROFILE PORTS: the wiring stays I/O-free and asks for a resolution; the store is
618
+ // the only module in the chain that touches the disk.
619
+ resolvePrompt: (request) => resolveRedTeamPrompt(request),
620
+ purgePromptCache: () => { clearPromptProfileCache(); },
621
+ writePromptScaffold: (slug) => this.writeRedTeamPromptScaffold(slug),
622
+ getCwd: () => this.cwd,
623
+ ...(deps.notify === undefined ? {} : { notify: deps.notify }),
624
+ ...(deps.redTeamPromptPath === undefined ? {} : { promptPath: deps.redTeamPromptPath }),
587
625
  });
588
626
  // `--redteam`: the launch check already refused the two cases that cannot work (headless,
589
627
  // and no accepted waiver), so this is the ONE place a session may start armed without a
@@ -697,6 +735,19 @@ export class AgentController {
697
735
  // mid-dispatch and abort it at `idleTimeoutMs`. The queue pauses the
698
736
  // CHILD's watchdog instead, which is the one that needs it (P0-4).
699
737
  ...(confirm ? { humanQueue: new TeamHumanQueue(confirm) } : {}),
738
+ // THE DETACHED-DISPATCH WIRING (team-detached-dispatch section 5.1).
739
+ //
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".
744
+ currentTurnId: () => this.turnId,
745
+ isLeadRunning: () => this.agent.state.isRunning,
746
+ // THE REPORT'S ONE PRODUCER (REV-05). The SAME closure is handed to
747
+ // `createTaskTool` below, so the await path and the detach path price a
748
+ // dispatch identically - one table, one disclosure line.
749
+ reportOptions: () => this.teamReportOptions(),
750
+ hasPendingUserInput: () => this.hasPendingUserMessages(),
700
751
  // THE CHILD INHERITS THE LEAD'S RED TEAM PHRASE (4.5 point 6 / D-16 / RV-2).
701
752
  // `buildSubagentTools` builds its OWN confirm closure (`humanQueue.request`), so
702
753
  // "the same closure is inherited" is FALSE - the same PREDICATE has to be passed
@@ -824,6 +875,20 @@ export class AgentController {
824
875
  steerEnabled: () => this.config.jobs.noticeSteer,
825
876
  });
826
877
  this.jobRelay.attach((listener) => this.procs.subscribe(listener));
878
+ // THE TEAM RELAY (team-detached-dispatch section 5.3.2), built on the same
879
+ // three-channel shape for the same reason, with one difference the dep list
880
+ // records: a settle report is not a courtesy, so it does not consult
881
+ // `noticeSteer` and it is not silenced by any config key.
882
+ this.teamRelay = new TeamNoticeRelay({
883
+ queue: this.teamNotices,
884
+ steer: (text) => this.enqueueSteering(text, false),
885
+ isAtSafeSteerPoint: () => this.isAtSafeSteerPoint(),
886
+ canSteerBeforeTurn: () => this.activeToolCalls === 0 && !this.abortRequested,
887
+ });
888
+ // The SOURCE is the runtime's own event stream: `child_settled` /
889
+ // `dispatch_settled` / `lead_mail` are all derived here, once, so the notices
890
+ // cannot disagree with the panel about what happened.
891
+ this.teamRuntime?.subscribe((event) => this.onTeamEvent(event));
827
892
  this.tools = createBuiltinTools({
828
893
  getCwd: () => this.cwd,
829
894
  // `read_file` can show a picture; the answer is read from the controller on every call
@@ -1051,6 +1116,20 @@ export class AgentController {
1051
1116
  // unknown`, never as $0.00 (C-11 / RV-4).
1052
1117
  fastModelCost: () => this.fastTierModelCost(),
1053
1118
  withPausedWatchdog: (fn) => this.withPausedWatchdog(fn),
1119
+ // THE SEPARATION SWITCH (section 5.1.3). `planInteractive` excludes `-p`
1120
+ // and `exec`, whose machine contract must not change; the config key
1121
+ // is the user's escape hatch back to the blocking behaviour.
1122
+ detach: () => this.planInteractive && this.config.team.detachDispatch,
1123
+ // The SAME closure the runtime holds, so both paths price one report
1124
+ // with one table (REV-05).
1125
+ reportOptions: () => this.teamReportOptions(),
1126
+ }),
1127
+ // THE LEAD CONSOLE (section 5.2): seven tools, registered through the
1128
+ // same `teamTools` path as `task` - which is exactly why all seven had
1129
+ // to join `HOST_TOOL_NAMES`.
1130
+ ...createConsoleTools({
1131
+ runtime: this.teamRuntime,
1132
+ hasPendingUserInput: () => this.hasPendingUserMessages(),
1054
1133
  }),
1055
1134
  ]
1056
1135
  : [],
@@ -1314,6 +1393,9 @@ export class AgentController {
1314
1393
  // A receipt means Core took a batch out of the queue, which is the only
1315
1394
  // proof a steered notice has that it was not discarded (§4.6.1).
1316
1395
  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();
1317
1399
  }
1318
1400
  // THE BATCH COUNTER (D-5 / I-5). Decremented BEFORE the push attempt below,
1319
1401
  // because "the batch is empty" is only true after the last one has ended.
@@ -1336,12 +1418,14 @@ export class AgentController {
1336
1418
  // by the next tool result (the pull channel) or by the next user turn
1337
1419
  // (the fill channel), so nothing is lost by declining.
1338
1420
  this.jobRelay?.tryPush();
1421
+ this.teamRelay?.tryPush();
1339
1422
  }
1340
1423
  if (event.type === 'turn_start') {
1341
1424
  // A new turn's first checkpoint is a safe point, and anything still
1342
1425
  // steered-but-unproven must go back in the queue first: `fast`'s
1343
1426
  // `recoverStranded()` may have wiped it at the end of the last run.
1344
1427
  this.jobRelay?.requeueUndelivered();
1428
+ this.teamRelay?.requeueUndelivered();
1345
1429
  }
1346
1430
  if (event.type === 'agent_end') {
1347
1431
  // A mount changed mid-turn lands now (agent-memory D-13): the flag clears and surfaces
@@ -1355,6 +1439,7 @@ export class AgentController {
1355
1439
  // required: `turn_start` covers the next turn of the same run, and this
1356
1440
  // covers a run that ended with a notice stranded in the queue.
1357
1441
  this.jobRelay?.requeueUndelivered();
1442
+ this.teamRelay?.requeueUndelivered();
1358
1443
  // AFTER the requeue, so a turn that ends with a stranded notice still gets
1359
1444
  // its feedback line. Order between the two is otherwise irrelevant.
1360
1445
  this.maybeReportSkillTriage();
@@ -1468,6 +1553,10 @@ export class AgentController {
1468
1553
  ? buildTeamBlock({
1469
1554
  maxSubagents: config.team.maxSubagents,
1470
1555
  maxConcurrent: config.team.maxConcurrent,
1556
+ // THE ONE CONDITIONAL IN THE BLOCK (I-DD8): with the key false the
1557
+ // text is the pre-feature text byte for byte, because a paragraph
1558
+ // about a free lead would be a lie in a session where `task` blocks.
1559
+ detachDispatch: this.planInteractive && config.team.detachDispatch,
1471
1560
  })
1472
1561
  : '',
1473
1562
  // THE THIRD LAYER (team-command-forced-dispatch §3.6): "you MUST dispatch"
@@ -1757,6 +1846,7 @@ export class AgentController {
1757
1846
  return { status: 'not-started', reason: 'cancelled' };
1758
1847
  }
1759
1848
  }
1849
+ this.turnId += 1;
1760
1850
  this.prepareUserTurn(text, { steering: false });
1761
1851
  if (request !== this.startupSequence) {
1762
1852
  return { status: 'not-started', reason: 'cancelled' };
@@ -1785,6 +1875,7 @@ export class AgentController {
1785
1875
  // notice waiting for a tool batch that may never come, which is exactly the
1786
1876
  // failure AC-25 exists to prevent.
1787
1877
  this.jobRelay?.flushForTurn();
1878
+ this.teamRelay?.flushForTurn();
1788
1879
  }
1789
1880
  /**
1790
1881
  * THE BOUNDARY OF ONE TURN — and there are TWO call sites, which is the reason
@@ -1848,13 +1939,25 @@ export class AgentController {
1848
1939
  // than a consequence of the compactor honouring a signal three modules away.
1849
1940
  this.compaction?.abort();
1850
1941
  this.agent.abort();
1851
- // DELIBERATE REDUNDANCY (§3.8). Aborting the lead already aborts the
1852
- // in-flight `task` call's `ctx.signal`, which the runtime listens to — that
1853
- // path is correct today. Calling it directly as well makes "no child
1854
- // survives its dispatch" a property of THIS class rather than a consequence
1855
- // of signal plumbing three modules away, which is the same argument
1856
- // `App.tsx` records for `cancelPendingHuman()` on `agent_end`.
1857
- this.teamRuntime?.abortAll();
1942
+ // ABORT SCOPE IS THE TURN, NOT THE TEAM (team-detached-dispatch I-DD11).
1943
+ //
1944
+ // The old rule was "stopping a run stops its team", and it was true while a
1945
+ // dispatch could not outlive the turn that started it: `task` held the turn
1946
+ // for the whole dispatch. Detaching ends that premise. Two ways the old rule
1947
+ // now hurts the user:
1948
+ //
1949
+ // - the lead is idle and the user presses Esc (to clear the composer, say):
1950
+ // a 100-minute team dies with no turn being stopped at all;
1951
+ // - the lead is running a SHORT unrelated turn (the user asked "how is it
1952
+ // going?") and stops it: the team dies with it.
1953
+ //
1954
+ // So the team is taken along only when the live dispatch was started by the
1955
+ // turn being stopped. Everything else is `team_stop`'s job - which is also
1956
+ // what the Esc ladder's second press and `/team stop all` call.
1957
+ const live = this.teamRuntime?.live() ?? null;
1958
+ if (live === null || live.turnId === this.turnId) {
1959
+ this.teamRuntime?.abortAll();
1960
+ }
1858
1961
  }
1859
1962
  /**
1860
1963
  * Final rung of the Esc ladder: stop the AGENT, whatever it is blocked on
@@ -2578,6 +2681,33 @@ export class AgentController {
2578
2681
  noteRedTeamPosture() {
2579
2682
  this.redTeam.onPostureChange();
2580
2683
  }
2684
+ // -------------------------------------------------------------------
2685
+ // Red team prompt profile - public surface (redteam-prompt-profile 7.5)
2686
+ // -------------------------------------------------------------------
2687
+ //
2688
+ // FIVE FORWARDERS AND NOTHING ELSE (D-17): every one is optional on the command side, so a
2689
+ // host with no profile machinery keeps working, and none of them decides anything.
2690
+ /** What `/redteam prompt` reports. `builtin` when the session has no resolver. */
2691
+ getRedTeamPromptView() {
2692
+ return this.redTeam.getPromptView();
2693
+ }
2694
+ /** Switch this session's profile; the command persists `redteam.profile` separately. */
2695
+ setRedTeamPromptProfile(profile) {
2696
+ return this.redTeam.setPromptProfile(profile);
2697
+ }
2698
+ /** The session-level override; `null` clears it, which is what `builtin` needs (AC-22). */
2699
+ setRedTeamPromptPath(path) {
2700
+ this.redTeam.setPromptPath(path);
2701
+ }
2702
+ /** Purge the read cache and report whether the block changed. */
2703
+ reloadRedTeamPrompt() {
2704
+ return this.redTeam.reloadPrompt();
2705
+ }
2706
+ /** Write the starter profile through the store; the ONLY write in the feature. */
2707
+ writeRedTeamPromptScaffold(slug) {
2708
+ const safe = slug === undefined || slug.length === 0 ? 'custom' : slug;
2709
+ return writePromptScaffold(promptProfileScaffold(safe), safe);
2710
+ }
2581
2711
  /**
2582
2712
  * One log record per mode event, and NONE of them carries a command, a target or a secret:
2583
2713
  * `scope_set` records a length, `confirm_bypass` records a tool name (D-9 / R-12).
@@ -2608,6 +2738,26 @@ export class AgentController {
2608
2738
  getLogger().info('agent', 'redteam_resume_restored', {
2609
2739
  armed: event.armed, reason: event.reason,
2610
2740
  });
2741
+ return;
2742
+ case 'redteam.prompt_profile':
2743
+ // COUNTS AND A DISPLAY NAME, NEVER TEXT (D-11 / PF-6): `profile` is a slug or a
2744
+ // placeholder, and the body, the title and the real path stay out of every log.
2745
+ getLogger().info('agent', 'redteam_prompt_profile', {
2746
+ profile: event.profile,
2747
+ source: event.source,
2748
+ bytes: event.bytes,
2749
+ sections: event.sections,
2750
+ issues: event.issues,
2751
+ fromCache: event.fromCache,
2752
+ });
2753
+ return;
2754
+ case 'redteam.prompt_issue':
2755
+ // THE CODE, NOT THE DETAIL: a detail may hold a file name, and a file name may be a
2756
+ // person (D-11).
2757
+ getLogger().warn('agent', 'redteam_prompt_issue', {
2758
+ code: event.code, severity: event.severity,
2759
+ });
2760
+ return;
2611
2761
  }
2612
2762
  }
2613
2763
  // -----------------------------------------------------------------------
@@ -2739,6 +2889,199 @@ export class AgentController {
2739
2889
  subagentModelResolution() {
2740
2890
  return resolveSubagentModel(this.config, (id, role) => this.hasApiKey(id, role));
2741
2891
  }
2892
+ /**
2893
+ * The report's price and model closures, in ONE object.
2894
+ *
2895
+ * THE SINGLE AUTHOR OF A REPORT'S NUMBERS (spec REV-05). Both `createTaskTool`
2896
+ * (await mode) and `TeamRuntime` (detach mode, at settlement) call this, so a
2897
+ * dispatch is priced by the same table whichever path produced it - and the
2898
+ * `pricing unknown` rule (C-11 / RV-4) holds in both.
2899
+ */
2900
+ teamReportOptions() {
2901
+ const cost = this.teamModelCost();
2902
+ const fastCost = this.fastTierModelCost();
2903
+ const subagentModel = this.subagentModelResolution();
2904
+ return {
2905
+ ...(cost ? { cost } : {}),
2906
+ ...(fastCost ? { fastCost } : {}),
2907
+ ...(subagentModel ? { subagentModel } : {}),
2908
+ };
2909
+ }
2910
+ // ---------------------------------------------------------------------------
2911
+ // The team console, as a facade (team-detached-dispatch sections 5.2 / 7.3)
2912
+ //
2913
+ // `/team` verbs and the desktop host go through these methods rather than
2914
+ // through the runtime directly: the runtime is an implementation detail of the
2915
+ // controller, and handing a command file the `TeamRuntime` would put a
2916
+ // 1 600-line internal one import away from the command line.
2917
+ // ---------------------------------------------------------------------------
2918
+ /** The live dispatch view, or `null`. */
2919
+ readTeamControl() {
2920
+ return {
2921
+ inspection: this.teamRuntime?.inspect() ?? null,
2922
+ live: this.teamRuntime?.live() ?? null,
2923
+ };
2924
+ }
2925
+ /** Pause / resume / stop / spawn / message, from the user or the lead. */
2926
+ sendTeamControl(request, by = 'user') {
2927
+ const runtime = this.teamRuntime;
2928
+ if (runtime === null)
2929
+ return { ok: false, detail: 'Team mode is off for this session.' };
2930
+ switch (request.action) {
2931
+ case 'message': {
2932
+ const done = runtime.sendFromLead(request.to, request.body, {
2933
+ interrupt: request.interrupt !== false,
2934
+ by,
2935
+ });
2936
+ return done.ok
2937
+ ? { ok: true, detail: renderSendResult(done.delivered, done.remaining) }
2938
+ : { ok: false, detail: done.why };
2939
+ }
2940
+ case 'pause': {
2941
+ const done = runtime.pauseChild(request.label, by, request.reason);
2942
+ if ('why' in done)
2943
+ return { ok: false, detail: done.why };
2944
+ return { ok: true, detail: renderPauseResult(request.label, done.effect, by) };
2945
+ }
2946
+ case 'resume': {
2947
+ const done = runtime.resumeChild(request.label, by, request.message);
2948
+ return done.ok
2949
+ ? {
2950
+ ok: true,
2951
+ detail: renderResumeResult(request.label, done.effect, (request.message ?? '').trim().length > 0),
2952
+ }
2953
+ : { ok: false, detail: done.why };
2954
+ }
2955
+ case 'stop': {
2956
+ const done = runtime.stopChild(request.label, by, request.reason);
2957
+ return {
2958
+ ok: true,
2959
+ detail: renderStopResult(done.stopped, done.live, done.unknown === true ? { unknownLabel: request.label } : {}),
2960
+ };
2961
+ }
2962
+ case 'spawn': {
2963
+ // A BRIEF PLUS A COUNT is the user's shape; the split reuses the same
2964
+ // brief-splitting rule `/team <brief>` already uses, so the package keeps
2965
+ // ONE rule for turning a sentence into N subagent briefs.
2966
+ const specs = splitBriefIntoSpecs(request.brief, request.count);
2967
+ if (specs.length === 0)
2968
+ return { ok: false, detail: 'Nothing to spawn: empty brief.' };
2969
+ const done = runtime.addSpecs(specs, by, request.brief.slice(0, 200));
2970
+ if ('why' in done)
2971
+ return { ok: false, detail: done.why };
2972
+ return { ok: true, detail: renderSpawnResult(done.added, done.dropped, done.requested) };
2973
+ }
2974
+ }
2975
+ }
2976
+ /**
2977
+ * Stop the whole team (the `/team stop all` and Esc-ladder entry point).
2978
+ *
2979
+ * THE ONE PATH A NON-OWNER HAS. `stopEngine()` no longer calls `abortAll()`
2980
+ * unconditionally, so this is how a user ends a dispatch that an EARLIER turn
2981
+ * started.
2982
+ */
2983
+ stopTeam(by, reason) {
2984
+ return this.teamRuntime?.stopChild('all', by, reason) ?? { stopped: [], live: [] };
2985
+ }
2986
+ /** The turn id a dispatch started now would record (`I-DD11`). */
2987
+ currentTurnId() {
2988
+ return this.turnId;
2989
+ }
2990
+ /** Whether a dispatch is live AND was started by an earlier turn. */
2991
+ teamOutlivesTurn() {
2992
+ const runtime = this.teamRuntime;
2993
+ if (!runtime)
2994
+ return false;
2995
+ const live = runtime.live();
2996
+ return live !== null && live.turnId !== this.turnId;
2997
+ }
2998
+ /**
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.
3007
+ */
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 };
3017
+ }
3018
+ /** Spend the one follow-up turn of the current dispatch (at most one). */
3019
+ markTeamContinued(dispatchId) {
3020
+ this.teamRuntime?.markContinued(dispatchId);
3021
+ }
3022
+ /**
3023
+ * Turn one runtime event into a notice (section 5.3.1).
3024
+ *
3025
+ * DERIVED HERE, ONCE, rather than by each UI: the panel, the card and the notice
3026
+ * queue must agree about what happened, and the only way to guarantee that is for
3027
+ * all three to read the same event. The queue adds nothing but the "exactly once"
3028
+ * bookkeeping.
3029
+ */
3030
+ onTeamEvent(event) {
3031
+ 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
+ });
3049
+ break;
3050
+ }
3051
+ case 'lead_mail':
3052
+ this.teamNotices.push({
3053
+ kind: 'lead_mail',
3054
+ id: `${event.dispatchId}:mail:${event.message.at}:${event.message.from}`,
3055
+ dispatchId: event.dispatchId,
3056
+ from: event.message.from,
3057
+ subject: event.message.subject,
3058
+ // A CHILD'S PROSE, CLAMPED. The full body is in the report; a notice
3059
+ // carrying 800 characters of it would be a second report.
3060
+ bodyHead: event.message.body.slice(0, 200),
3061
+ at: Date.now(),
3062
+ });
3063
+ 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();
3079
+ break;
3080
+ }
3081
+ default:
3082
+ break;
3083
+ }
3084
+ }
2742
3085
  /** Refused mid-dispatch by `/team`; half a dispatch under two ceilings is not
2743
3086
  * a result anything can afterwards explain (the reasoning `/reload` uses). */
2744
3087
  isTeamBusy() {