@chankov/agent-fleet 2.0.6 → 2.0.8

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 (1050) hide show
  1. package/.pi/agent-fleet/hermes/README.md +347 -0
  2. package/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +773 -0
  3. package/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  4. package/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  5. package/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  6. package/.pi/agent-fleet/hermes/skills/hub-conductor/SKILL.md +84 -0
  7. package/.pi/agent-fleet/hermes/skills/hub-watchdog/SKILL.md +76 -0
  8. package/.pi/agent-fleet/hooks/coms-stop-hook.mjs +84 -0
  9. package/.pi/agent-fleet/scripts/claude-code-preflight.ts +70 -0
  10. package/.pi/agent-fleet/scripts/coms-claude-bridge.ts +411 -0
  11. package/.pi/agent-fleet/scripts/coms-cli.ts +425 -0
  12. package/.pi/agent-fleet/scripts/coms-hermes-bridge.ts +413 -0
  13. package/.pi/agent-fleet/scripts/fleet-codex-read.py +148 -0
  14. package/.pi/agent-fleet/scripts/fleet.ts +216 -0
  15. package/.pi/agent-fleet/scripts/flow.ts +137 -0
  16. package/.pi/agent-fleet/scripts/lib/claude-bridge-core.ts +210 -0
  17. package/.pi/agent-fleet/scripts/lib/coms-envelope.ts +582 -0
  18. package/.pi/agent-fleet/scripts/lib/fleet-codex-transport.ts +124 -0
  19. package/.pi/agent-fleet/scripts/lib/herdr-layout.ts +281 -0
  20. package/.pi/agent-fleet/scripts/lib/hermes-bridge-core.ts +241 -0
  21. package/.pi/agent-fleet/scripts/lib/hermes-monitor-events.ts +1 -0
  22. package/.pi/agent-fleet/scripts/lib/hermes-monitor-herdr.ts +2 -0
  23. package/.pi/agent-fleet/scripts/lib/hermes-monitor-model.ts +3 -0
  24. package/.pi/agent-fleet/scripts/lib/hermes-monitor-registry.ts +2 -0
  25. package/.pi/agent-fleet/scripts/lib/hermes-monitor-socket.ts +2 -0
  26. package/.pi/agent-fleet/scripts/lib/hermes-monitor-store.ts +2 -0
  27. package/.pi/agent-fleet/scripts/lib/monitor-env.ts +146 -0
  28. package/.pi/agent-fleet/scripts/lib/peer-launch.ts +318 -0
  29. package/.pi/agent-fleet/scripts/lib/persona-banner.ts +62 -0
  30. package/.pi/agent-fleet/scripts/lib/persona-dirs.ts +25 -0
  31. package/.pi/agent-fleet/scripts/lib/runtime-dependencies.js +124 -0
  32. package/.pi/agent-fleet/scripts/lib/spawn-stagger.ts +101 -0
  33. package/.pi/agent-fleet/scripts/lib/team-project.ts +178 -0
  34. package/.pi/agent-fleet/scripts/lib/team-snapshot.ts +147 -0
  35. package/.pi/agent-fleet/scripts/peer-banner.ts +41 -0
  36. package/.pi/agent-fleet/scripts/peer-launch.ts +283 -0
  37. package/.pi/agent-fleet/scripts/team-snapshot.ts +237 -0
  38. package/.pi/agent-fleet/scripts/team-up.ts +378 -0
  39. package/.pi/agent-fleet/scripts/workflows/lib/agent-phase.ts +133 -0
  40. package/.pi/agent-fleet/scripts/workflows/lib/envelopes.ts +169 -0
  41. package/.pi/agent-fleet/scripts/workflows/lib/model-profile.ts +22 -0
  42. package/.pi/agent-fleet/scripts/workflows/lib/personas.ts +57 -0
  43. package/.pi/agent-fleet/scripts/workflows/lib/trace.ts +34 -0
  44. package/.pi/agents/peers.yaml +3 -1
  45. package/.pi/harnesses/agent-hub/README.md +1 -1
  46. package/.pi/harnesses/agent-hub/config/agents.ts +5 -1
  47. package/.pi/harnesses/agent-hub/debate-command.ts +1 -1
  48. package/.pi/harnesses/agent-hub/index.ts +19 -19
  49. package/.pi/harnesses/agent-hub/package.json +1 -1
  50. package/.pi/harnesses/agent-hub/peer-spawn-plan.ts +1 -1
  51. package/.pi/harnesses/agent-hub/tools/fleet-tools.ts +3 -5
  52. package/.pi/harnesses/agent-hub/tools/herdr-executors.ts +2 -2
  53. package/.pi/harnesses/ask-user-remote/index.ts +2 -2
  54. package/.pi/harnesses/coms/package.json +1 -1
  55. package/.pi/harnesses/damage-control-continue/README.md +11 -0
  56. package/.pi/harnesses/damage-control-continue/index.ts +5 -0
  57. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  58. package/.pi/harnesses/lib/spawned-peers.js +1 -1
  59. package/.pi/harnesses/lib/update-check.ts +222 -0
  60. package/.pi/prompts/af-constraints.md +31 -0
  61. package/.versions/2.0.7/.pi/agents/dispatch-policy.yaml +32 -0
  62. package/.versions/2.0.7/.pi/agents/model-profiles.yaml +83 -0
  63. package/.versions/2.0.7/.pi/agents/peers.yaml +145 -0
  64. package/.versions/2.0.7/.pi/agents/teams.yaml +41 -0
  65. package/.versions/2.0.7/.pi/agents/voices.yaml +13 -0
  66. package/.versions/2.0.7/.pi/damage-control-rules.yaml +297 -0
  67. package/.versions/2.0.7/.pi/extensions/btw/README.md +120 -0
  68. package/.versions/2.0.7/.pi/extensions/btw/index.ts +914 -0
  69. package/{.pi/extensions/agent-fleet-update-check → .versions/2.0.7/.pi/extensions/btw}/package.json +1 -1
  70. package/.versions/2.0.7/.pi/extensions/btw/state.js +179 -0
  71. package/.versions/2.0.7/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  72. package/.versions/2.0.7/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  73. package/.versions/2.0.7/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  74. package/.versions/2.0.7/.pi/extensions/compact-and-continue/README.md +42 -0
  75. package/.versions/2.0.7/.pi/extensions/compact-and-continue/index.ts +120 -0
  76. package/.versions/2.0.7/.pi/extensions/compact-and-continue/package.json +6 -0
  77. package/.versions/2.0.7/.pi/extensions/mcp-bridge/README.md +46 -0
  78. package/.versions/2.0.7/.pi/extensions/mcp-bridge/index.ts +206 -0
  79. package/.versions/2.0.7/.pi/extensions/mcp-bridge/package.json +6 -0
  80. package/.versions/2.0.7/.pi/extensions/package-lock.json +1175 -0
  81. package/.versions/2.0.7/.pi/extensions/package.json +9 -0
  82. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/README.md +205 -0
  83. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/config.ts +198 -0
  84. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  85. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/index.ts +248 -0
  86. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/package.json +6 -0
  87. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  88. package/.versions/2.0.7/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  89. package/.versions/2.0.7/.pi/harnesses/agent-hub/README.md +1203 -0
  90. package/.versions/2.0.7/.pi/harnesses/agent-hub/acceptance.ts +62 -0
  91. package/.versions/2.0.7/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  92. package/.versions/2.0.7/.pi/harnesses/agent-hub/artifacts.js +146 -0
  93. package/.versions/2.0.7/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  94. package/.versions/2.0.7/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  95. package/.versions/2.0.7/.pi/harnesses/agent-hub/budget-continuation.ts +13 -0
  96. package/.versions/2.0.7/.pi/harnesses/agent-hub/budget-recovery.ts +97 -0
  97. package/.versions/2.0.7/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  98. package/.versions/2.0.7/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  99. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agent-model-thinking.ts +10 -0
  100. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agent-model.ts +10 -0
  101. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agent-models-substitute.ts +10 -0
  102. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-add.ts +9 -0
  103. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-drop.ts +9 -0
  104. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-history.ts +9 -0
  105. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-kill.ts +10 -0
  106. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-list.ts +9 -0
  107. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-restart.ts +10 -0
  108. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-save.ts +9 -0
  109. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/agents-team.ts +9 -0
  110. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/budget-continue.ts +10 -0
  111. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/compound.ts +9 -0
  112. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/coms.ts +9 -0
  113. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/context-command.ts +9 -0
  114. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/context.ts +43 -0
  115. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/debate.ts +9 -0
  116. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/dispatch-policy.ts +9 -0
  117. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/handoff.ts +10 -0
  118. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/hub-report.ts +9 -0
  119. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/models.ts +10 -0
  120. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/poll.ts +9 -0
  121. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/retry.ts +10 -0
  122. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/watchdog.ts +9 -0
  123. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/work-mode.ts +29 -0
  124. package/.versions/2.0.7/.pi/harnesses/agent-hub/commands/zoom.ts +10 -0
  125. package/.versions/2.0.7/.pi/harnesses/agent-hub/config/agents.ts +173 -0
  126. package/.versions/2.0.7/.pi/harnesses/agent-hub/config/model-profiles.ts +216 -0
  127. package/.versions/2.0.7/.pi/harnesses/agent-hub/config/overrides.ts +153 -0
  128. package/.versions/2.0.7/.pi/harnesses/agent-hub/context/agent-state.ts +30 -0
  129. package/.versions/2.0.7/.pi/harnesses/agent-hub/context/assertions-artifacts.ts +213 -0
  130. package/.versions/2.0.7/.pi/harnesses/agent-hub/context/budgets.ts +202 -0
  131. package/.versions/2.0.7/.pi/harnesses/agent-hub/context/hub-state.ts +40 -0
  132. package/.versions/2.0.7/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  133. package/.versions/2.0.7/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  134. package/.versions/2.0.7/.pi/harnesses/agent-hub/context-window.js +106 -0
  135. package/.versions/2.0.7/.pi/harnesses/agent-hub/debate-command.ts +176 -0
  136. package/.versions/2.0.7/.pi/harnesses/agent-hub/delegate.ts +446 -0
  137. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-coms.ts +237 -0
  138. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-core.ts +27 -0
  139. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-native-complete.ts +154 -0
  140. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-native-prepare.ts +156 -0
  141. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-native-spawn.ts +193 -0
  142. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-native-types.ts +230 -0
  143. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-native.ts +213 -0
  144. package/.versions/2.0.7/.pi/harnesses/agent-hub/dispatch-observability.ts +225 -0
  145. package/.versions/2.0.7/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  146. package/.versions/2.0.7/.pi/harnesses/agent-hub/drift-watchdog.js +218 -0
  147. package/.versions/2.0.7/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  148. package/.versions/2.0.7/.pi/harnesses/agent-hub/execution-evidence.ts +80 -0
  149. package/.versions/2.0.7/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  150. package/.versions/2.0.7/.pi/harnesses/agent-hub/fixtures/registration-surface.json +57 -0
  151. package/.versions/2.0.7/.pi/harnesses/agent-hub/footer.ts +30 -0
  152. package/.versions/2.0.7/.pi/harnesses/agent-hub/helpers.ts +266 -0
  153. package/.versions/2.0.7/.pi/harnesses/agent-hub/hub-state-audit.js +64 -0
  154. package/.versions/2.0.7/.pi/harnesses/agent-hub/index.ts +2151 -0
  155. package/.versions/2.0.7/.pi/harnesses/agent-hub/input/completions.ts +76 -0
  156. package/.versions/2.0.7/.pi/harnesses/agent-hub/input/shortcuts.ts +18 -0
  157. package/.versions/2.0.7/.pi/harnesses/agent-hub/lifecycle/context-pressure.ts +123 -0
  158. package/.versions/2.0.7/.pi/harnesses/agent-hub/lifecycle/monitor-session.ts +104 -0
  159. package/.versions/2.0.7/.pi/harnesses/agent-hub/lifecycle/session-orchestration.ts +143 -0
  160. package/.versions/2.0.7/.pi/harnesses/agent-hub/lifecycle/turn-handlers.ts +74 -0
  161. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  162. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  163. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  164. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  165. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  166. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  167. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  168. package/.versions/2.0.7/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  169. package/.versions/2.0.7/.pi/harnesses/agent-hub/no-progress.ts +76 -0
  170. package/.versions/2.0.7/.pi/harnesses/agent-hub/package.json +7 -0
  171. package/.versions/2.0.7/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  172. package/.versions/2.0.7/.pi/harnesses/agent-hub/policy/models.ts +153 -0
  173. package/.versions/2.0.7/.pi/harnesses/agent-hub/policy/profile-activation.ts +62 -0
  174. package/.versions/2.0.7/.pi/harnesses/agent-hub/policy/profile-runtime.ts +120 -0
  175. package/.versions/2.0.7/.pi/harnesses/agent-hub/policy/roster.ts +94 -0
  176. package/.versions/2.0.7/.pi/harnesses/agent-hub/policy/work-mode.ts +119 -0
  177. package/.versions/2.0.7/.pi/harnesses/agent-hub/poll-command.ts +176 -0
  178. package/.versions/2.0.7/.pi/harnesses/agent-hub/presentation.ts +48 -0
  179. package/.versions/2.0.7/.pi/harnesses/agent-hub/prompts/context.ts +47 -0
  180. package/.versions/2.0.7/.pi/harnesses/agent-hub/prompts/fragments.ts +115 -0
  181. package/.versions/2.0.7/.pi/harnesses/agent-hub/prompts/session-start.ts +90 -0
  182. package/.versions/2.0.7/.pi/harnesses/agent-hub/prompts/system-prompt.ts +112 -0
  183. package/.versions/2.0.7/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  184. package/.versions/2.0.7/.pi/harnesses/agent-hub/research/controls.ts +74 -0
  185. package/.versions/2.0.7/.pi/harnesses/agent-hub/research/runtime.ts +192 -0
  186. package/.versions/2.0.7/.pi/harnesses/agent-hub/research/spawn-run.ts +156 -0
  187. package/.versions/2.0.7/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  188. package/.versions/2.0.7/.pi/harnesses/agent-hub/return-contract.js +293 -0
  189. package/.versions/2.0.7/.pi/harnesses/agent-hub/return-extract.js +75 -0
  190. package/.versions/2.0.7/.pi/harnesses/agent-hub/review-findings.js +102 -0
  191. package/.versions/2.0.7/.pi/harnesses/agent-hub/run-budget.js +537 -0
  192. package/.versions/2.0.7/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  193. package/.versions/2.0.7/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  194. package/.versions/2.0.7/.pi/harnesses/agent-hub/scope-gate.js +123 -0
  195. package/.versions/2.0.7/.pi/harnesses/agent-hub/session-health.js +110 -0
  196. package/.versions/2.0.7/.pi/harnesses/agent-hub/session-start.ts +42 -0
  197. package/.versions/2.0.7/.pi/harnesses/agent-hub/spawn.ts +404 -0
  198. package/.versions/2.0.7/.pi/harnesses/agent-hub/timeline.ts +54 -0
  199. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/action-executors.ts +149 -0
  200. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/coms-tools.ts +139 -0
  201. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/context.ts +134 -0
  202. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/dispatch-agent.ts +82 -0
  203. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/dispatch-execution.ts +273 -0
  204. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/execution-orchestration.ts +22 -0
  205. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/fleet-tools.ts +202 -0
  206. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/herdr-executors.ts +86 -0
  207. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/set-task-tier.ts +29 -0
  208. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/spawn-research.ts +62 -0
  209. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/team-adjust.ts +29 -0
  210. package/.versions/2.0.7/.pi/harnesses/agent-hub/tools/verification-contract.ts +77 -0
  211. package/.versions/2.0.7/.pi/harnesses/agent-hub/types.ts +63 -0
  212. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/activity-dots.ts +16 -0
  213. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/context-budget.ts +86 -0
  214. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/detail-panel.ts +178 -0
  215. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/fleet-dashboard.ts +125 -0
  216. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/grid.ts +42 -0
  217. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/history-store.ts +137 -0
  218. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/history.ts +234 -0
  219. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/pool.ts +103 -0
  220. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/running-strip.ts +139 -0
  221. package/.versions/2.0.7/.pi/harnesses/agent-hub/ui/zoom.ts +204 -0
  222. package/.versions/2.0.7/.pi/harnesses/agent-hub/version.ts +42 -0
  223. package/.versions/2.0.7/.pi/harnesses/agent-hub/work-mode-controls.ts +56 -0
  224. package/.versions/2.0.7/.pi/harnesses/agent-hub/work-mode.ts +167 -0
  225. package/.versions/2.0.7/.pi/harnesses/ask-user-remote/README.md +59 -0
  226. package/.versions/2.0.7/.pi/harnesses/ask-user-remote/index.ts +558 -0
  227. package/.versions/2.0.7/.pi/harnesses/ask-user-remote/questions.ts +161 -0
  228. package/.versions/2.0.7/.pi/harnesses/ask-user-remote/race-core.js +124 -0
  229. package/.versions/2.0.7/.pi/harnesses/ask-user-remote/runtime-ask.ts +43 -0
  230. package/.versions/2.0.7/.pi/harnesses/coms/README.md +100 -0
  231. package/.versions/2.0.7/.pi/harnesses/coms/index.ts +282 -0
  232. package/.versions/2.0.7/.pi/harnesses/coms/package.json +7 -0
  233. package/.versions/2.0.7/.pi/harnesses/coms/version.ts +42 -0
  234. package/.versions/2.0.7/.pi/harnesses/damage-control-continue/README.md +135 -0
  235. package/.versions/2.0.7/.pi/harnesses/damage-control-continue/index.ts +541 -0
  236. package/.versions/2.0.7/.pi/harnesses/damage-control-continue/package.json +7 -0
  237. package/.versions/2.0.7/.pi/harnesses/damage-control-continue/version.ts +42 -0
  238. package/.versions/2.0.7/.pi/harnesses/lib/coms-core-io.ts +385 -0
  239. package/.versions/2.0.7/.pi/harnesses/lib/coms-core.ts +577 -0
  240. package/.versions/2.0.7/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  241. package/.versions/2.0.7/.pi/harnesses/lib/context-budget-child-prompt.ts +180 -0
  242. package/.versions/2.0.7/.pi/harnesses/lib/context-budget-hub-prompt.ts +114 -0
  243. package/.versions/2.0.7/.pi/harnesses/lib/context-budget-view.ts +107 -0
  244. package/.versions/2.0.7/.pi/harnesses/lib/context-budget.ts +114 -0
  245. package/.versions/2.0.7/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  246. package/.versions/2.0.7/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  247. package/.versions/2.0.7/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  248. package/.versions/2.0.7/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  249. package/.versions/2.0.7/.pi/harnesses/lib/fleet-dashboard-ops.ts +161 -0
  250. package/.versions/2.0.7/.pi/harnesses/lib/fleet-dashboard-view.ts +148 -0
  251. package/.versions/2.0.7/.pi/harnesses/lib/fleet-detail-view.ts +247 -0
  252. package/.versions/2.0.7/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  253. package/.versions/2.0.7/.pi/harnesses/lib/fleet-panel.ts +34 -0
  254. package/.versions/2.0.7/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  255. package/.versions/2.0.7/.pi/harnesses/lib/fleet-selection.ts +24 -0
  256. package/.versions/2.0.7/.pi/harnesses/lib/fleet-transcript-store.ts +244 -0
  257. package/.versions/2.0.7/.pi/harnesses/lib/herdr-client.ts +472 -0
  258. package/.versions/2.0.7/.pi/harnesses/lib/herdr-presence.ts +399 -0
  259. package/.versions/2.0.7/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  260. package/.versions/2.0.7/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  261. package/.versions/2.0.7/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  262. package/.versions/2.0.7/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  263. package/.versions/2.0.7/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  264. package/.versions/2.0.7/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  265. package/.versions/2.0.7/.pi/harnesses/lib/spawned-peers.js +190 -0
  266. package/.versions/2.0.7/.pi/harnesses/lib/update-check.ts +222 -0
  267. package/.versions/2.0.7/.pi/harnesses/package-lock.json +2039 -0
  268. package/.versions/2.0.7/.pi/harnesses/package.json +10 -0
  269. package/.versions/2.0.7/.pi/prompts/af-build.md +24 -0
  270. package/.versions/2.0.7/.pi/prompts/af-code-simplify.md +22 -0
  271. package/.versions/2.0.7/.pi/prompts/af-plan.md +17 -0
  272. package/.versions/2.0.7/.pi/prompts/af-review.md +16 -0
  273. package/.versions/2.0.7/.pi/prompts/af-set-hermes-telegram.md +15 -0
  274. package/.versions/2.0.7/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  275. package/.versions/2.0.7/.pi/prompts/af-ship.md +17 -0
  276. package/.versions/2.0.7/.pi/prompts/af-spec.md +15 -0
  277. package/.versions/2.0.7/.pi/prompts/af-test.md +19 -0
  278. package/.versions/2.0.7/.pi/skills/bowser/SKILL.md +145 -0
  279. package/.versions/2.0.7/.version +1 -0
  280. package/.versions/2.0.7/agents/architect.md +25 -0
  281. package/.versions/2.0.7/agents/bowser.md +28 -0
  282. package/.versions/2.0.7/agents/builder.md +56 -0
  283. package/.versions/2.0.7/agents/code-reviewer.md +210 -0
  284. package/.versions/2.0.7/agents/deep-researcher.md +33 -0
  285. package/.versions/2.0.7/agents/documenter.md +23 -0
  286. package/.versions/2.0.7/agents/orchestrator.md +23 -0
  287. package/.versions/2.0.7/agents/plan-reviewer.md +84 -0
  288. package/.versions/2.0.7/agents/planner.md +106 -0
  289. package/.versions/2.0.7/agents/releaser.md +25 -0
  290. package/.versions/2.0.7/agents/researcher.md +31 -0
  291. package/.versions/2.0.7/agents/security-auditor.md +168 -0
  292. package/.versions/2.0.7/agents/test-engineer.md +154 -0
  293. package/.versions/2.0.7/agents/web-debugger.md +44 -0
  294. package/.versions/2.0.7/agents/web-performance-auditor.md +194 -0
  295. package/.versions/2.0.7/bin/catalog/harness-runtime-closure.json +31 -0
  296. package/.versions/2.0.7/codex/fleet-session-client/SKILL.md +34 -0
  297. package/.versions/2.0.7/codex/fleet-session-client.zip +0 -0
  298. package/.versions/2.0.7/docs/ARCHITECTURE.md +407 -0
  299. package/.versions/2.0.7/docs/agent-fleet-setup.md +561 -0
  300. package/.versions/2.0.7/docs/claude-code-coms-bridge.md +133 -0
  301. package/.versions/2.0.7/docs/codex-session-bridge.md +219 -0
  302. package/.versions/2.0.7/docs/coms-hermes-bridge.md +188 -0
  303. package/.versions/2.0.7/docs/getting-started.md +126 -0
  304. package/.versions/2.0.7/docs/npm-install.md +327 -0
  305. package/.versions/2.0.7/docs/pi-extensions.md +446 -0
  306. package/.versions/2.0.7/docs/pi-setup.md +76 -0
  307. package/.versions/2.0.7/docs/skill-anatomy.md +150 -0
  308. package/.versions/2.0.7/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  309. package/.versions/2.0.7/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  310. package/.versions/2.0.7/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  311. package/.versions/2.0.7/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  312. package/.versions/2.0.7/hermes/gates/gate-o-capability.md +8 -0
  313. package/.versions/2.0.7/hermes/gates/gate-o-validator-fixtures.json +1 -0
  314. package/.versions/2.0.7/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  315. package/.versions/2.0.7/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  316. package/.versions/2.0.7/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  317. package/.versions/2.0.7/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  318. package/.versions/2.0.7/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  319. package/.versions/2.0.7/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  320. package/.versions/2.0.7/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  321. package/.versions/2.0.7/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  322. package/.versions/2.0.7/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  323. package/.versions/2.0.7/hermes/skills/hub-liaison/SKILL.md +84 -0
  324. package/.versions/2.0.7/hermes/skills/hub-watchdog/manifest.json +1 -0
  325. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  326. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  327. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  328. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  329. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  330. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  331. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  332. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  333. package/.versions/2.0.7/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  334. package/.versions/2.0.7/hermes/watchdog-tests/__init__.py +0 -0
  335. package/.versions/2.0.7/install-manifest.json +2886 -0
  336. package/.versions/2.0.7/justfile +247 -0
  337. package/.versions/2.0.7/manifest-meta.json +958 -0
  338. package/.versions/2.0.7/references/accessibility-checklist.md +160 -0
  339. package/.versions/2.0.7/references/communication-contract.md +26 -0
  340. package/.versions/2.0.7/references/definition-of-done.md +67 -0
  341. package/.versions/2.0.7/references/fleet-coordination-patterns.md +171 -0
  342. package/.versions/2.0.7/references/observability-checklist.md +91 -0
  343. package/.versions/2.0.7/references/orchestration-patterns.md +370 -0
  344. package/.versions/2.0.7/references/performance-checklist.md +153 -0
  345. package/.versions/2.0.7/references/prompting-patterns.md +380 -0
  346. package/.versions/2.0.7/references/security-checklist.md +179 -0
  347. package/.versions/2.0.7/references/testing-patterns.md +236 -0
  348. package/.versions/2.0.7/references/workflow-authoring.md +304 -0
  349. package/.versions/2.0.7/scripts/fleet-codex-client.ts +69 -0
  350. package/{scripts → .versions/2.0.7/scripts}/fleet.ts +1 -1
  351. package/.versions/2.0.7/scripts/hermes-monitor-capability-runner.ts +25 -0
  352. package/.versions/2.0.7/scripts/hermes-monitor-scenario.ts +474 -0
  353. package/.versions/2.0.7/scripts/hermes-watchdog-capability-probe.ts +45 -0
  354. package/.versions/2.0.7/scripts/install-hermes-plugin.sh +180 -0
  355. package/.versions/2.0.7/scripts/lib/fake-herdr-server.ts +88 -0
  356. package/.versions/2.0.7/scripts/lib/fleet-codex-catalog.ts +63 -0
  357. package/.versions/2.0.7/scripts/lib/fleet-codex-operations.ts +190 -0
  358. package/.versions/2.0.7/scripts/lib/fleet-codex-session.ts +166 -0
  359. package/.versions/2.0.7/scripts/lib/fleet-command.ts +252 -0
  360. package/.versions/2.0.7/scripts/lib/flow-command.ts +93 -0
  361. package/.versions/2.0.7/scripts/lib/flow-maintenance.ts +230 -0
  362. package/.versions/2.0.7/scripts/package-lock.json +35 -0
  363. package/.versions/2.0.7/scripts/package.json +9 -0
  364. package/.versions/2.0.7/scripts/workflows/lib/changes.ts +61 -0
  365. package/.versions/2.0.7/scripts/workflows/lib/debate.ts +149 -0
  366. package/.versions/2.0.7/scripts/workflows/lib/env.ts +34 -0
  367. package/.versions/2.0.7/scripts/workflows/lib/gates.ts +81 -0
  368. package/.versions/2.0.7/scripts/workflows/lib/git.ts +96 -0
  369. package/.versions/2.0.7/scripts/workflows/lib/merge.ts +95 -0
  370. package/.versions/2.0.7/scripts/workflows/lib/model-visibility.ts +92 -0
  371. package/.versions/2.0.7/scripts/workflows/lib/permissions.ts +130 -0
  372. package/.versions/2.0.7/scripts/workflows/lib/poll.ts +86 -0
  373. package/.versions/2.0.7/scripts/workflows/lib/quality.ts +64 -0
  374. package/.versions/2.0.7/scripts/workflows/lib/run.ts +108 -0
  375. package/.versions/2.0.7/scripts/workflows/lib/voices.ts +128 -0
  376. package/.versions/2.0.7/scripts/workflows/lib/writer-lease.ts +112 -0
  377. package/.versions/2.0.7/scripts/workflows/tsconfig.json +22 -0
  378. package/.versions/2.0.7/scripts/workflows/wf-build-test.ts +61 -0
  379. package/.versions/2.0.7/scripts/workflows/wf-debate.ts +87 -0
  380. package/.versions/2.0.7/scripts/workflows/wf-document.ts +50 -0
  381. package/.versions/2.0.7/scripts/workflows/wf-poll.ts +95 -0
  382. package/.versions/2.0.7/scripts/workflows/wf-quality.ts +20 -0
  383. package/.versions/2.0.7/scripts/workflows/wf-scout.ts +38 -0
  384. package/.versions/2.0.7/skills/_internal/grilling.md +59 -0
  385. package/.versions/2.0.7/skills/browser-testing-with-devtools/SKILL.md +351 -0
  386. package/.versions/2.0.7/skills/code-review-and-quality/SKILL.md +381 -0
  387. package/.versions/2.0.7/skills/compound-learning/SKILL.md +137 -0
  388. package/.versions/2.0.7/skills/context-engineering/SKILL.md +291 -0
  389. package/.versions/2.0.7/skills/deprecation-and-migration/SKILL.md +206 -0
  390. package/.versions/2.0.7/skills/designing-agents/SKILL.md +394 -0
  391. package/.versions/2.0.7/skills/designing-agents/pi-harness-authoring.md +222 -0
  392. package/.versions/2.0.7/skills/drafting-workflows/SKILL.md +143 -0
  393. package/.versions/2.0.7/skills/drafting-workflows/scripts/make-workflow.ts +177 -0
  394. package/.versions/2.0.7/skills/frontend-ui-engineering/SKILL.md +328 -0
  395. package/.versions/2.0.7/skills/git-workflow-and-versioning/SKILL.md +316 -0
  396. package/.versions/2.0.7/skills/idea-refine/SKILL.md +182 -0
  397. package/.versions/2.0.7/skills/idea-refine/examples.md +238 -0
  398. package/.versions/2.0.7/skills/idea-refine/frameworks.md +99 -0
  399. package/.versions/2.0.7/skills/idea-refine/refinement-criteria.md +113 -0
  400. package/.versions/2.0.7/skills/idea-refine/scripts/idea-refine.sh +15 -0
  401. package/.versions/2.0.7/skills/incremental-implementation/SKILL.md +298 -0
  402. package/.versions/2.0.7/skills/interview-me/SKILL.md +226 -0
  403. package/.versions/2.0.7/skills/orchestration-verification/SKILL.md +181 -0
  404. package/.versions/2.0.7/skills/peer-coms/SKILL.md +90 -0
  405. package/.versions/2.0.7/skills/performance-optimization/SKILL.md +350 -0
  406. package/.versions/2.0.7/skills/planning-and-task-breakdown/SKILL.md +265 -0
  407. package/.versions/2.0.7/skills/security-and-hardening/SKILL.md +461 -0
  408. package/.versions/2.0.7/skills/spec-driven-development/SKILL.md +256 -0
  409. package/.versions/2.0.7/skills/using-agent-skills/SKILL.md +197 -0
  410. package/.versions/2.0.7/vendor/agent-skills-upstream/LICENSE +21 -0
  411. package/.versions/2.0.7/vendor/agent-skills-upstream/README.md +11 -0
  412. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  413. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  414. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  415. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  416. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  417. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  418. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  419. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  420. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  421. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  422. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  423. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  424. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  425. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  426. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  427. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  428. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  429. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  430. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  431. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  432. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  433. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  434. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  435. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  436. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  437. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  438. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  439. package/.versions/2.0.7/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  440. package/.versions/2.0.8/.pi/agent-fleet/hermes/README.md +347 -0
  441. package/.versions/2.0.8/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  442. package/.versions/2.0.8/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  443. package/.versions/2.0.8/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  444. package/.versions/2.0.8/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  445. package/.versions/2.0.8/.pi/agent-fleet/hermes/gates/gate-o-capability.md +8 -0
  446. package/.versions/2.0.8/.pi/agent-fleet/hermes/gates/gate-o-validator-fixtures.json +1 -0
  447. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +773 -0
  448. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  449. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  450. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  451. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  452. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  453. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  454. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  455. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  456. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  457. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  458. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  459. package/.versions/2.0.8/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  460. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-conductor/SKILL.md +84 -0
  461. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-liaison/SKILL.md +84 -0
  462. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/SKILL.md +76 -0
  463. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/manifest.json +1 -0
  464. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  465. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  466. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  467. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  468. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  469. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  470. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  471. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  472. package/.versions/2.0.8/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  473. package/.versions/2.0.8/.pi/agent-fleet/hermes/watchdog-tests/__init__.py +0 -0
  474. package/.versions/2.0.8/.pi/agent-fleet/hooks/coms-stop-hook.mjs +84 -0
  475. package/.versions/2.0.8/.pi/agent-fleet/scripts/claude-code-preflight.ts +70 -0
  476. package/.versions/2.0.8/.pi/agent-fleet/scripts/coms-claude-bridge.ts +411 -0
  477. package/.versions/2.0.8/.pi/agent-fleet/scripts/coms-cli.ts +425 -0
  478. package/.versions/2.0.8/.pi/agent-fleet/scripts/coms-hermes-bridge.ts +413 -0
  479. package/.versions/2.0.8/.pi/agent-fleet/scripts/fleet-codex-client.ts +69 -0
  480. package/.versions/2.0.8/.pi/agent-fleet/scripts/fleet-codex-read.py +148 -0
  481. package/.versions/2.0.8/.pi/agent-fleet/scripts/fleet.ts +216 -0
  482. package/.versions/2.0.8/.pi/agent-fleet/scripts/flow.ts +137 -0
  483. package/.versions/2.0.8/.pi/agent-fleet/scripts/hermes-monitor-capability-runner.ts +25 -0
  484. package/.versions/2.0.8/.pi/agent-fleet/scripts/hermes-monitor-scenario.ts +474 -0
  485. package/.versions/2.0.8/.pi/agent-fleet/scripts/hermes-watchdog-capability-probe.ts +45 -0
  486. package/.versions/2.0.8/.pi/agent-fleet/scripts/install-hermes-plugin.sh +180 -0
  487. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/claude-bridge-core.ts +210 -0
  488. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/coms-envelope.ts +582 -0
  489. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/fake-herdr-server.ts +88 -0
  490. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/fleet-codex-catalog.ts +63 -0
  491. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/fleet-codex-operations.ts +190 -0
  492. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/fleet-codex-session.ts +166 -0
  493. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/fleet-codex-transport.ts +124 -0
  494. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/fleet-command.ts +252 -0
  495. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/flow-command.ts +93 -0
  496. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/flow-maintenance.ts +230 -0
  497. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/herdr-layout.ts +281 -0
  498. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-bridge-core.ts +241 -0
  499. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-monitor-events.ts +1 -0
  500. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-monitor-herdr.ts +2 -0
  501. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-monitor-model.ts +3 -0
  502. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-monitor-registry.ts +2 -0
  503. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-monitor-socket.ts +2 -0
  504. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/hermes-monitor-store.ts +2 -0
  505. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/monitor-env.ts +146 -0
  506. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/peer-launch.ts +318 -0
  507. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/persona-banner.ts +62 -0
  508. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/persona-dirs.ts +25 -0
  509. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/runtime-dependencies.js +124 -0
  510. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/spawn-stagger.ts +101 -0
  511. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/team-project.ts +178 -0
  512. package/.versions/2.0.8/.pi/agent-fleet/scripts/lib/team-snapshot.ts +147 -0
  513. package/.versions/2.0.8/.pi/agent-fleet/scripts/package-lock.json +35 -0
  514. package/.versions/2.0.8/.pi/agent-fleet/scripts/package.json +9 -0
  515. package/.versions/2.0.8/.pi/agent-fleet/scripts/peer-banner.ts +41 -0
  516. package/.versions/2.0.8/.pi/agent-fleet/scripts/peer-launch.ts +283 -0
  517. package/.versions/2.0.8/.pi/agent-fleet/scripts/team-snapshot.ts +237 -0
  518. package/.versions/2.0.8/.pi/agent-fleet/scripts/team-up.ts +378 -0
  519. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/agent-phase.ts +133 -0
  520. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/changes.ts +61 -0
  521. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/debate.ts +149 -0
  522. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/env.ts +34 -0
  523. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/envelopes.ts +169 -0
  524. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/gates.ts +81 -0
  525. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/git.ts +96 -0
  526. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/merge.ts +95 -0
  527. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/model-profile.ts +22 -0
  528. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/model-visibility.ts +92 -0
  529. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/permissions.ts +130 -0
  530. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/personas.ts +57 -0
  531. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/poll.ts +86 -0
  532. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/quality.ts +64 -0
  533. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/run.ts +108 -0
  534. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/trace.ts +34 -0
  535. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/voices.ts +128 -0
  536. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/lib/writer-lease.ts +112 -0
  537. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/tsconfig.json +22 -0
  538. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/wf-build-test.ts +61 -0
  539. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/wf-debate.ts +87 -0
  540. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/wf-document.ts +50 -0
  541. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/wf-poll.ts +95 -0
  542. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/wf-quality.ts +20 -0
  543. package/.versions/2.0.8/.pi/agent-fleet/scripts/workflows/wf-scout.ts +38 -0
  544. package/.versions/2.0.8/.pi/agents/dispatch-policy.yaml +32 -0
  545. package/.versions/2.0.8/.pi/agents/model-profiles.yaml +83 -0
  546. package/.versions/2.0.8/.pi/agents/peers.yaml +147 -0
  547. package/.versions/2.0.8/.pi/agents/teams.yaml +41 -0
  548. package/.versions/2.0.8/.pi/agents/voices.yaml +13 -0
  549. package/.versions/2.0.8/.pi/damage-control-rules.yaml +297 -0
  550. package/.versions/2.0.8/.pi/extensions/btw/README.md +120 -0
  551. package/.versions/2.0.8/.pi/extensions/btw/index.ts +914 -0
  552. package/.versions/2.0.8/.pi/extensions/btw/package.json +6 -0
  553. package/.versions/2.0.8/.pi/extensions/btw/state.js +179 -0
  554. package/.versions/2.0.8/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  555. package/.versions/2.0.8/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  556. package/.versions/2.0.8/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  557. package/.versions/2.0.8/.pi/extensions/compact-and-continue/README.md +42 -0
  558. package/.versions/2.0.8/.pi/extensions/compact-and-continue/index.ts +120 -0
  559. package/.versions/2.0.8/.pi/extensions/compact-and-continue/package.json +6 -0
  560. package/.versions/2.0.8/.pi/extensions/mcp-bridge/README.md +46 -0
  561. package/.versions/2.0.8/.pi/extensions/mcp-bridge/index.ts +206 -0
  562. package/.versions/2.0.8/.pi/extensions/mcp-bridge/package.json +6 -0
  563. package/.versions/2.0.8/.pi/extensions/package-lock.json +1175 -0
  564. package/.versions/2.0.8/.pi/extensions/package.json +9 -0
  565. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/README.md +205 -0
  566. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/config.ts +198 -0
  567. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  568. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/index.ts +248 -0
  569. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/package.json +6 -0
  570. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  571. package/.versions/2.0.8/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  572. package/.versions/2.0.8/.pi/harnesses/agent-hub/README.md +1203 -0
  573. package/.versions/2.0.8/.pi/harnesses/agent-hub/acceptance.ts +62 -0
  574. package/.versions/2.0.8/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  575. package/.versions/2.0.8/.pi/harnesses/agent-hub/artifacts.js +146 -0
  576. package/.versions/2.0.8/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  577. package/.versions/2.0.8/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  578. package/.versions/2.0.8/.pi/harnesses/agent-hub/budget-continuation.ts +13 -0
  579. package/.versions/2.0.8/.pi/harnesses/agent-hub/budget-recovery.ts +97 -0
  580. package/.versions/2.0.8/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  581. package/.versions/2.0.8/.pi/harnesses/agent-hub/capability-packs.ts +180 -0
  582. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agent-model-thinking.ts +10 -0
  583. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agent-model.ts +10 -0
  584. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agent-models-substitute.ts +10 -0
  585. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-add.ts +9 -0
  586. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-drop.ts +9 -0
  587. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-history.ts +9 -0
  588. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-kill.ts +10 -0
  589. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-list.ts +9 -0
  590. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-restart.ts +10 -0
  591. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-save.ts +9 -0
  592. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/agents-team.ts +9 -0
  593. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/budget-continue.ts +10 -0
  594. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/compound.ts +9 -0
  595. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/coms.ts +9 -0
  596. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/context-command.ts +9 -0
  597. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/context.ts +43 -0
  598. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/debate.ts +9 -0
  599. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/dispatch-policy.ts +9 -0
  600. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/handoff.ts +10 -0
  601. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/hub-report.ts +9 -0
  602. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/models.ts +10 -0
  603. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/poll.ts +9 -0
  604. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/retry.ts +10 -0
  605. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/watchdog.ts +9 -0
  606. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/work-mode.ts +29 -0
  607. package/.versions/2.0.8/.pi/harnesses/agent-hub/commands/zoom.ts +10 -0
  608. package/.versions/2.0.8/.pi/harnesses/agent-hub/config/agents.ts +177 -0
  609. package/.versions/2.0.8/.pi/harnesses/agent-hub/config/model-profiles.ts +216 -0
  610. package/.versions/2.0.8/.pi/harnesses/agent-hub/config/overrides.ts +153 -0
  611. package/.versions/2.0.8/.pi/harnesses/agent-hub/context/agent-state.ts +30 -0
  612. package/.versions/2.0.8/.pi/harnesses/agent-hub/context/assertions-artifacts.ts +213 -0
  613. package/.versions/2.0.8/.pi/harnesses/agent-hub/context/budgets.ts +202 -0
  614. package/.versions/2.0.8/.pi/harnesses/agent-hub/context/hub-state.ts +40 -0
  615. package/.versions/2.0.8/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  616. package/.versions/2.0.8/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  617. package/.versions/2.0.8/.pi/harnesses/agent-hub/context-window.js +106 -0
  618. package/.versions/2.0.8/.pi/harnesses/agent-hub/debate-command.ts +176 -0
  619. package/.versions/2.0.8/.pi/harnesses/agent-hub/delegate.ts +446 -0
  620. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-coms.ts +237 -0
  621. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-core.ts +27 -0
  622. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-native-complete.ts +154 -0
  623. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-native-prepare.ts +156 -0
  624. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-native-spawn.ts +193 -0
  625. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-native-types.ts +230 -0
  626. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-native.ts +213 -0
  627. package/.versions/2.0.8/.pi/harnesses/agent-hub/dispatch-observability.ts +225 -0
  628. package/.versions/2.0.8/.pi/harnesses/agent-hub/docs-lane.js +122 -0
  629. package/.versions/2.0.8/.pi/harnesses/agent-hub/drift-watchdog.js +218 -0
  630. package/.versions/2.0.8/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  631. package/.versions/2.0.8/.pi/harnesses/agent-hub/execution-evidence.ts +80 -0
  632. package/.versions/2.0.8/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  633. package/.versions/2.0.8/.pi/harnesses/agent-hub/fixtures/registration-surface.json +57 -0
  634. package/.versions/2.0.8/.pi/harnesses/agent-hub/footer.ts +30 -0
  635. package/.versions/2.0.8/.pi/harnesses/agent-hub/helpers.ts +266 -0
  636. package/.versions/2.0.8/.pi/harnesses/agent-hub/hub-state-audit.js +64 -0
  637. package/.versions/2.0.8/.pi/harnesses/agent-hub/index.ts +2151 -0
  638. package/.versions/2.0.8/.pi/harnesses/agent-hub/input/completions.ts +76 -0
  639. package/.versions/2.0.8/.pi/harnesses/agent-hub/input/shortcuts.ts +18 -0
  640. package/.versions/2.0.8/.pi/harnesses/agent-hub/lifecycle/context-pressure.ts +123 -0
  641. package/.versions/2.0.8/.pi/harnesses/agent-hub/lifecycle/monitor-session.ts +104 -0
  642. package/.versions/2.0.8/.pi/harnesses/agent-hub/lifecycle/session-orchestration.ts +143 -0
  643. package/.versions/2.0.8/.pi/harnesses/agent-hub/lifecycle/turn-handlers.ts +74 -0
  644. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  645. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  646. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  647. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  648. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  649. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  650. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  651. package/.versions/2.0.8/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  652. package/.versions/2.0.8/.pi/harnesses/agent-hub/no-progress.ts +76 -0
  653. package/.versions/2.0.8/.pi/harnesses/agent-hub/package.json +7 -0
  654. package/.versions/2.0.8/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  655. package/.versions/2.0.8/.pi/harnesses/agent-hub/policy/models.ts +153 -0
  656. package/.versions/2.0.8/.pi/harnesses/agent-hub/policy/profile-activation.ts +62 -0
  657. package/.versions/2.0.8/.pi/harnesses/agent-hub/policy/profile-runtime.ts +120 -0
  658. package/.versions/2.0.8/.pi/harnesses/agent-hub/policy/roster.ts +94 -0
  659. package/.versions/2.0.8/.pi/harnesses/agent-hub/policy/work-mode.ts +119 -0
  660. package/.versions/2.0.8/.pi/harnesses/agent-hub/poll-command.ts +176 -0
  661. package/.versions/2.0.8/.pi/harnesses/agent-hub/presentation.ts +48 -0
  662. package/.versions/2.0.8/.pi/harnesses/agent-hub/prompts/context.ts +47 -0
  663. package/.versions/2.0.8/.pi/harnesses/agent-hub/prompts/fragments.ts +115 -0
  664. package/.versions/2.0.8/.pi/harnesses/agent-hub/prompts/session-start.ts +90 -0
  665. package/.versions/2.0.8/.pi/harnesses/agent-hub/prompts/system-prompt.ts +112 -0
  666. package/.versions/2.0.8/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  667. package/.versions/2.0.8/.pi/harnesses/agent-hub/research/controls.ts +74 -0
  668. package/.versions/2.0.8/.pi/harnesses/agent-hub/research/runtime.ts +192 -0
  669. package/.versions/2.0.8/.pi/harnesses/agent-hub/research/spawn-run.ts +156 -0
  670. package/.versions/2.0.8/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  671. package/.versions/2.0.8/.pi/harnesses/agent-hub/return-contract.js +293 -0
  672. package/.versions/2.0.8/.pi/harnesses/agent-hub/return-extract.js +75 -0
  673. package/.versions/2.0.8/.pi/harnesses/agent-hub/review-findings.js +102 -0
  674. package/.versions/2.0.8/.pi/harnesses/agent-hub/run-budget.js +537 -0
  675. package/.versions/2.0.8/.pi/harnesses/agent-hub/run-namespace.js +87 -0
  676. package/.versions/2.0.8/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  677. package/.versions/2.0.8/.pi/harnesses/agent-hub/scope-gate.js +123 -0
  678. package/.versions/2.0.8/.pi/harnesses/agent-hub/session-health.js +110 -0
  679. package/.versions/2.0.8/.pi/harnesses/agent-hub/session-start.ts +42 -0
  680. package/.versions/2.0.8/.pi/harnesses/agent-hub/spawn.ts +404 -0
  681. package/.versions/2.0.8/.pi/harnesses/agent-hub/timeline.ts +54 -0
  682. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/action-executors.ts +149 -0
  683. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/coms-tools.ts +139 -0
  684. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/context.ts +134 -0
  685. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/dispatch-agent.ts +82 -0
  686. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/dispatch-execution.ts +273 -0
  687. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/execution-orchestration.ts +22 -0
  688. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/fleet-tools.ts +200 -0
  689. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/herdr-executors.ts +86 -0
  690. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/set-task-tier.ts +29 -0
  691. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/spawn-research.ts +62 -0
  692. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/team-adjust.ts +29 -0
  693. package/.versions/2.0.8/.pi/harnesses/agent-hub/tools/verification-contract.ts +77 -0
  694. package/.versions/2.0.8/.pi/harnesses/agent-hub/types.ts +63 -0
  695. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/activity-dots.ts +16 -0
  696. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/context-budget.ts +86 -0
  697. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/detail-panel.ts +178 -0
  698. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/fleet-dashboard.ts +125 -0
  699. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/grid.ts +42 -0
  700. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/history-store.ts +137 -0
  701. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/history.ts +234 -0
  702. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/pool.ts +103 -0
  703. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/running-strip.ts +139 -0
  704. package/.versions/2.0.8/.pi/harnesses/agent-hub/ui/zoom.ts +204 -0
  705. package/.versions/2.0.8/.pi/harnesses/agent-hub/version.ts +42 -0
  706. package/.versions/2.0.8/.pi/harnesses/agent-hub/work-mode-controls.ts +56 -0
  707. package/.versions/2.0.8/.pi/harnesses/agent-hub/work-mode.ts +167 -0
  708. package/.versions/2.0.8/.pi/harnesses/ask-user-remote/README.md +59 -0
  709. package/.versions/2.0.8/.pi/harnesses/ask-user-remote/index.ts +558 -0
  710. package/.versions/2.0.8/.pi/harnesses/ask-user-remote/questions.ts +161 -0
  711. package/.versions/2.0.8/.pi/harnesses/ask-user-remote/race-core.js +124 -0
  712. package/.versions/2.0.8/.pi/harnesses/ask-user-remote/runtime-ask.ts +43 -0
  713. package/.versions/2.0.8/.pi/harnesses/coms/README.md +100 -0
  714. package/.versions/2.0.8/.pi/harnesses/coms/index.ts +282 -0
  715. package/.versions/2.0.8/.pi/harnesses/coms/package.json +7 -0
  716. package/.versions/2.0.8/.pi/harnesses/coms/version.ts +42 -0
  717. package/.versions/2.0.8/.pi/harnesses/damage-control-continue/README.md +135 -0
  718. package/.versions/2.0.8/.pi/harnesses/damage-control-continue/index.ts +541 -0
  719. package/.versions/2.0.8/.pi/harnesses/damage-control-continue/package.json +7 -0
  720. package/.versions/2.0.8/.pi/harnesses/damage-control-continue/version.ts +42 -0
  721. package/.versions/2.0.8/.pi/harnesses/lib/coms-core-io.ts +385 -0
  722. package/.versions/2.0.8/.pi/harnesses/lib/coms-core.ts +577 -0
  723. package/.versions/2.0.8/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  724. package/.versions/2.0.8/.pi/harnesses/lib/context-budget-child-prompt.ts +180 -0
  725. package/.versions/2.0.8/.pi/harnesses/lib/context-budget-hub-prompt.ts +114 -0
  726. package/.versions/2.0.8/.pi/harnesses/lib/context-budget-view.ts +107 -0
  727. package/.versions/2.0.8/.pi/harnesses/lib/context-budget.ts +114 -0
  728. package/.versions/2.0.8/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  729. package/.versions/2.0.8/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  730. package/.versions/2.0.8/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  731. package/.versions/2.0.8/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  732. package/.versions/2.0.8/.pi/harnesses/lib/fleet-dashboard-ops.ts +161 -0
  733. package/.versions/2.0.8/.pi/harnesses/lib/fleet-dashboard-view.ts +148 -0
  734. package/.versions/2.0.8/.pi/harnesses/lib/fleet-detail-view.ts +247 -0
  735. package/.versions/2.0.8/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  736. package/.versions/2.0.8/.pi/harnesses/lib/fleet-panel.ts +34 -0
  737. package/.versions/2.0.8/.pi/harnesses/lib/fleet-read-model.ts +131 -0
  738. package/.versions/2.0.8/.pi/harnesses/lib/fleet-selection.ts +24 -0
  739. package/.versions/2.0.8/.pi/harnesses/lib/fleet-transcript-store.ts +244 -0
  740. package/.versions/2.0.8/.pi/harnesses/lib/herdr-client.ts +472 -0
  741. package/.versions/2.0.8/.pi/harnesses/lib/herdr-presence.ts +399 -0
  742. package/.versions/2.0.8/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  743. package/.versions/2.0.8/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  744. package/.versions/2.0.8/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  745. package/.versions/2.0.8/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  746. package/.versions/2.0.8/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  747. package/.versions/2.0.8/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  748. package/.versions/2.0.8/.pi/harnesses/lib/spawned-peers.js +190 -0
  749. package/.versions/2.0.8/.pi/harnesses/lib/update-check.ts +222 -0
  750. package/.versions/2.0.8/.pi/harnesses/package-lock.json +2039 -0
  751. package/.versions/2.0.8/.pi/harnesses/package.json +10 -0
  752. package/.versions/2.0.8/.pi/prompts/af-build.md +24 -0
  753. package/.versions/2.0.8/.pi/prompts/af-code-simplify.md +22 -0
  754. package/.versions/2.0.8/.pi/prompts/af-constraints.md +31 -0
  755. package/.versions/2.0.8/.pi/prompts/af-plan.md +17 -0
  756. package/.versions/2.0.8/.pi/prompts/af-review.md +16 -0
  757. package/.versions/2.0.8/.pi/prompts/af-set-hermes-telegram.md +15 -0
  758. package/.versions/2.0.8/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  759. package/.versions/2.0.8/.pi/prompts/af-ship.md +17 -0
  760. package/.versions/2.0.8/.pi/prompts/af-spec.md +15 -0
  761. package/.versions/2.0.8/.pi/prompts/af-test.md +19 -0
  762. package/.versions/2.0.8/.pi/skills/bowser/SKILL.md +145 -0
  763. package/.versions/2.0.8/.version +1 -0
  764. package/.versions/2.0.8/agents/architect.md +25 -0
  765. package/.versions/2.0.8/agents/bowser.md +28 -0
  766. package/.versions/2.0.8/agents/builder.md +56 -0
  767. package/.versions/2.0.8/agents/code-reviewer.md +210 -0
  768. package/.versions/2.0.8/agents/deep-researcher.md +33 -0
  769. package/.versions/2.0.8/agents/documenter.md +23 -0
  770. package/.versions/2.0.8/agents/orchestrator.md +23 -0
  771. package/.versions/2.0.8/agents/plan-reviewer.md +84 -0
  772. package/.versions/2.0.8/agents/planner.md +106 -0
  773. package/.versions/2.0.8/agents/releaser.md +25 -0
  774. package/.versions/2.0.8/agents/researcher.md +31 -0
  775. package/.versions/2.0.8/agents/security-auditor.md +168 -0
  776. package/.versions/2.0.8/agents/test-engineer.md +154 -0
  777. package/.versions/2.0.8/agents/web-debugger.md +44 -0
  778. package/.versions/2.0.8/agents/web-performance-auditor.md +194 -0
  779. package/.versions/2.0.8/bin/catalog/harness-runtime-closure.json +32 -0
  780. package/.versions/2.0.8/codex/fleet-session-client/SKILL.md +34 -0
  781. package/.versions/2.0.8/codex/fleet-session-client.zip +0 -0
  782. package/.versions/2.0.8/docs/ARCHITECTURE.md +416 -0
  783. package/.versions/2.0.8/docs/agent-fleet-setup.md +568 -0
  784. package/.versions/2.0.8/docs/claude-code-coms-bridge.md +134 -0
  785. package/.versions/2.0.8/docs/codex-session-bridge.md +219 -0
  786. package/.versions/2.0.8/docs/coms-hermes-bridge.md +188 -0
  787. package/.versions/2.0.8/docs/getting-started.md +126 -0
  788. package/.versions/2.0.8/docs/npm-install.md +356 -0
  789. package/.versions/2.0.8/docs/pi-extensions.md +446 -0
  790. package/.versions/2.0.8/docs/pi-setup.md +76 -0
  791. package/.versions/2.0.8/docs/skill-anatomy.md +150 -0
  792. package/.versions/2.0.8/install-manifest.json +2991 -0
  793. package/.versions/2.0.8/justfile +247 -0
  794. package/.versions/2.0.8/manifest-meta.json +970 -0
  795. package/.versions/2.0.8/references/accessibility-checklist.md +160 -0
  796. package/.versions/2.0.8/references/communication-contract.md +26 -0
  797. package/.versions/2.0.8/references/definition-of-done.md +67 -0
  798. package/.versions/2.0.8/references/fleet-coordination-patterns.md +171 -0
  799. package/.versions/2.0.8/references/observability-checklist.md +92 -0
  800. package/.versions/2.0.8/references/orchestration-patterns.md +370 -0
  801. package/.versions/2.0.8/references/performance-checklist.md +236 -0
  802. package/.versions/2.0.8/references/prompting-patterns.md +380 -0
  803. package/.versions/2.0.8/references/security-checklist.md +245 -0
  804. package/.versions/2.0.8/references/testing-patterns.md +235 -0
  805. package/.versions/2.0.8/references/workflow-authoring.md +304 -0
  806. package/.versions/2.0.8/skills/_internal/grilling.md +59 -0
  807. package/.versions/2.0.8/skills/browser-testing-with-devtools/SKILL.md +351 -0
  808. package/.versions/2.0.8/skills/code-review-and-quality/SKILL.md +396 -0
  809. package/.versions/2.0.8/skills/compound-learning/SKILL.md +137 -0
  810. package/.versions/2.0.8/skills/constraint-driven-development/SKILL.md +338 -0
  811. package/.versions/2.0.8/skills/constraint-driven-development/references/floor-guard.md +99 -0
  812. package/.versions/2.0.8/skills/context-engineering/SKILL.md +341 -0
  813. package/.versions/2.0.8/skills/deprecation-and-migration/SKILL.md +247 -0
  814. package/.versions/2.0.8/skills/designing-agents/SKILL.md +394 -0
  815. package/.versions/2.0.8/skills/designing-agents/pi-harness-authoring.md +222 -0
  816. package/.versions/2.0.8/skills/drafting-workflows/SKILL.md +143 -0
  817. package/.versions/2.0.8/skills/drafting-workflows/scripts/make-workflow.ts +177 -0
  818. package/.versions/2.0.8/skills/frontend-ui-engineering/SKILL.md +328 -0
  819. package/.versions/2.0.8/skills/git-workflow-and-versioning/SKILL.md +316 -0
  820. package/.versions/2.0.8/skills/idea-refine/SKILL.md +182 -0
  821. package/.versions/2.0.8/skills/idea-refine/examples.md +238 -0
  822. package/.versions/2.0.8/skills/idea-refine/frameworks.md +99 -0
  823. package/.versions/2.0.8/skills/idea-refine/refinement-criteria.md +113 -0
  824. package/.versions/2.0.8/skills/idea-refine/scripts/idea-refine.sh +15 -0
  825. package/.versions/2.0.8/skills/incremental-implementation/SKILL.md +302 -0
  826. package/.versions/2.0.8/skills/interview-me/SKILL.md +226 -0
  827. package/.versions/2.0.8/skills/orchestration-verification/SKILL.md +181 -0
  828. package/.versions/2.0.8/skills/peer-coms/SKILL.md +90 -0
  829. package/.versions/2.0.8/skills/performance-optimization/SKILL.md +496 -0
  830. package/.versions/2.0.8/skills/planning-and-task-breakdown/SKILL.md +289 -0
  831. package/.versions/2.0.8/skills/security-and-hardening/SKILL.md +524 -0
  832. package/.versions/2.0.8/skills/spec-driven-development/SKILL.md +295 -0
  833. package/.versions/2.0.8/skills/using-agent-skills/SKILL.md +198 -0
  834. package/.versions/2.0.8/vendor/agent-skills-upstream/LICENSE +21 -0
  835. package/.versions/2.0.8/vendor/agent-skills-upstream/README.md +430 -0
  836. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +367 -0
  837. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  838. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  839. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  840. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  841. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/constraint-driven-development/SKILL.md +311 -0
  842. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/constraint-driven-development/references/floor-guard.md +99 -0
  843. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +337 -0
  844. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  845. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  846. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +288 -0
  847. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  848. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  849. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  850. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  851. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  852. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  853. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  854. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  855. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  856. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  857. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +238 -0
  858. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +496 -0
  859. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +257 -0
  860. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +524 -0
  861. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +330 -0
  862. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +216 -0
  863. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +245 -0
  864. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +398 -0
  865. package/.versions/2.0.8/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +192 -0
  866. package/CHANGELOG.md +47 -0
  867. package/README.md +24 -16
  868. package/bin/catalog/harness-runtime-closure.json +23 -22
  869. package/bin/cli.js +173 -79
  870. package/bin/lib/apply.js +59 -64
  871. package/bin/lib/detect-agent.js +1 -1
  872. package/bin/lib/doctor.js +3 -3
  873. package/bin/lib/features.js +2 -2
  874. package/bin/lib/manifest.js +23 -16
  875. package/bin/lib/path-boundaries.js +96 -0
  876. package/bin/lib/personas.js +15 -2
  877. package/bin/lib/public-plan.js +17 -0
  878. package/bin/lib/purge.js +9 -3
  879. package/bin/lib/reconcile.js +4 -10
  880. package/bin/lib/repair-desired.js +73 -0
  881. package/bin/lib/set-hermes-telegram.js +2 -2
  882. package/bin/lib/set-hermes-watchdog.js +1 -1
  883. package/bin/lib/state.js +5 -1
  884. package/bin/lib/stt-wizard.js +25 -11
  885. package/bin/lib/transaction.js +118 -108
  886. package/bin/lib/tui.js +70 -65
  887. package/bin/lib/update-notifier.js +2 -2
  888. package/bin/lib/verify.js +43 -5
  889. package/bin/lib/workspace-safety.js +72 -0
  890. package/bin/snapshot-version.js +6 -6
  891. package/codex/fleet-session-client/SKILL.md +3 -3
  892. package/docs/ARCHITECTURE.md +29 -20
  893. package/docs/MIGRATION-agent-fleet.md +11 -7
  894. package/docs/agent-fleet-setup.md +9 -2
  895. package/docs/claude-code-coms-bridge.md +10 -9
  896. package/docs/codex-session-bridge.md +18 -18
  897. package/docs/coms-hermes-bridge.md +6 -6
  898. package/docs/hermes-watchdog-supervisor.md +1 -1
  899. package/docs/npm-install.md +71 -16
  900. package/docs/pi-extensions.md +9 -9
  901. package/docs/pi-setup.md +2 -2
  902. package/docs/workflows.md +9 -5
  903. package/install-manifest.json +202 -135
  904. package/justfile +22 -22
  905. package/manifest-meta.json +51 -57
  906. package/package.json +26 -26
  907. package/references/observability-checklist.md +1 -0
  908. package/references/performance-checklist.md +83 -0
  909. package/references/prompting-patterns.md +1 -1
  910. package/references/security-checklist.md +85 -19
  911. package/references/testing-patterns.md +12 -13
  912. package/references/workflow-authoring.md +5 -5
  913. package/skills/code-review-and-quality/SKILL.md +17 -2
  914. package/skills/constraint-driven-development/SKILL.md +338 -0
  915. package/skills/constraint-driven-development/references/floor-guard.md +99 -0
  916. package/skills/context-engineering/SKILL.md +52 -2
  917. package/skills/deprecation-and-migration/SKILL.md +42 -1
  918. package/skills/designing-agents/SKILL.md +12 -12
  919. package/skills/drafting-workflows/SKILL.md +6 -6
  920. package/skills/drafting-workflows/scripts/make-workflow.ts +3 -3
  921. package/skills/frontend-ui-engineering/SKILL.md +2 -2
  922. package/skills/git-workflow-and-versioning/SKILL.md +1 -1
  923. package/skills/incremental-implementation/SKILL.md +13 -9
  924. package/skills/peer-coms/SKILL.md +4 -4
  925. package/skills/performance-optimization/SKILL.md +152 -6
  926. package/skills/planning-and-task-breakdown/SKILL.md +32 -8
  927. package/skills/security-and-hardening/SKILL.md +84 -21
  928. package/skills/spec-driven-development/SKILL.md +41 -2
  929. package/skills/using-agent-skills/SKILL.md +3 -2
  930. package/vendor/agent-skills-upstream/README.md +427 -8
  931. package/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +73 -0
  932. package/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +2 -2
  933. package/vendor/agent-skills-upstream/skills/constraint-driven-development/SKILL.md +311 -0
  934. package/vendor/agent-skills-upstream/skills/constraint-driven-development/references/floor-guard.md +99 -0
  935. package/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +49 -1
  936. package/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +4 -4
  937. package/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +1 -1
  938. package/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +12 -2
  939. package/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +3 -3
  940. package/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +1 -1
  941. package/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +1 -1
  942. package/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +9 -9
  943. package/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +36 -1
  944. package/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +151 -5
  945. package/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +32 -9
  946. package/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +64 -7
  947. package/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +26 -6
  948. package/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +23 -1
  949. package/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +42 -3
  950. package/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +18 -3
  951. package/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +3 -2
  952. package/.pi/extensions/agent-fleet-update-check/README.md +0 -57
  953. package/.pi/extensions/agent-fleet-update-check/index.ts +0 -161
  954. /package/{hermes → .pi/agent-fleet/hermes}/desktop-plugins/agent-fleet-herdr/plugin.js +0 -0
  955. /package/{hermes → .pi/agent-fleet/hermes}/desktop-plugins/agent-fleet-herdr/presentation.js +0 -0
  956. /package/{hermes → .pi/agent-fleet/hermes}/desktop-plugins/agent-fleet-monitor/plugin.js +0 -0
  957. /package/{hermes → .pi/agent-fleet/hermes}/desktop-plugins/agent-fleet-monitor/state.js +0 -0
  958. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-herdr/dashboard/herdr_source.py +0 -0
  959. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-herdr/dashboard/manifest.json +0 -0
  960. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-herdr/dashboard/plugin_api.py +0 -0
  961. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-herdr/dashboard/sessions.py +0 -0
  962. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-herdr/dashboard/tasks.py +0 -0
  963. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-herdr/plugin.yaml +0 -0
  964. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-monitor/dashboard/adapter.py +0 -0
  965. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-monitor/dashboard/dist/index.js +0 -0
  966. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-monitor/dashboard/manifest.json +0 -0
  967. /package/{hermes → .pi/agent-fleet/hermes}/plugins/agent-fleet-monitor/dashboard/plugin_api.py +0 -0
  968. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-liaison/SKILL.md +0 -0
  969. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/manifest.json +0 -0
  970. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog.py +0 -0
  971. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_actions.py +0 -0
  972. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_contract.py +0 -0
  973. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_delivery.py +0 -0
  974. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_engine.py +0 -0
  975. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_judgment.py +0 -0
  976. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_recovery.py +0 -0
  977. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_state.py +0 -0
  978. /package/{hermes → .pi/agent-fleet/hermes}/skills/hub-watchdog/scripts/watchdog_transport.py +0 -0
  979. /package/{scripts → .pi/agent-fleet/scripts}/fleet-codex-client.ts +0 -0
  980. /package/{scripts → .pi/agent-fleet/scripts}/hermes-watchdog-capability-probe.ts +0 -0
  981. /package/{scripts → .pi/agent-fleet/scripts}/lib/fake-herdr-server.ts +0 -0
  982. /package/{scripts → .pi/agent-fleet/scripts}/lib/fleet-codex-catalog.ts +0 -0
  983. /package/{scripts → .pi/agent-fleet/scripts}/lib/fleet-codex-operations.ts +0 -0
  984. /package/{scripts → .pi/agent-fleet/scripts}/lib/fleet-codex-session.ts +0 -0
  985. /package/{scripts → .pi/agent-fleet/scripts}/lib/fleet-command.ts +0 -0
  986. /package/{scripts → .pi/agent-fleet/scripts}/lib/flow-command.ts +0 -0
  987. /package/{scripts → .pi/agent-fleet/scripts}/lib/flow-maintenance.ts +0 -0
  988. /package/{scripts → .pi/agent-fleet/scripts}/package-lock.json +0 -0
  989. /package/{scripts → .pi/agent-fleet/scripts}/package.json +0 -0
  990. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/changes.ts +0 -0
  991. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/debate.ts +0 -0
  992. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/env.ts +0 -0
  993. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/gates.ts +0 -0
  994. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/git.ts +0 -0
  995. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/merge.ts +0 -0
  996. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/model-visibility.ts +0 -0
  997. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/permissions.ts +0 -0
  998. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/poll.ts +0 -0
  999. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/quality.ts +0 -0
  1000. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/run.ts +0 -0
  1001. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/voices.ts +0 -0
  1002. /package/{scripts → .pi/agent-fleet/scripts}/workflows/lib/writer-lease.ts +0 -0
  1003. /package/{scripts → .pi/agent-fleet/scripts}/workflows/tsconfig.json +0 -0
  1004. /package/{scripts → .pi/agent-fleet/scripts}/workflows/wf-build-test.ts +0 -0
  1005. /package/{scripts → .pi/agent-fleet/scripts}/workflows/wf-debate.ts +0 -0
  1006. /package/{scripts → .pi/agent-fleet/scripts}/workflows/wf-document.ts +0 -0
  1007. /package/{scripts → .pi/agent-fleet/scripts}/workflows/wf-poll.ts +0 -0
  1008. /package/{scripts → .pi/agent-fleet/scripts}/workflows/wf-quality.ts +0 -0
  1009. /package/{scripts → .pi/agent-fleet/scripts}/workflows/wf-scout.ts +0 -0
  1010. /package/{hermes → .versions/2.0.7/hermes}/README.md +0 -0
  1011. /package/{hermes → .versions/2.0.7/hermes}/plugins/agent-fleet-herdr/dashboard/activity.py +0 -0
  1012. /package/{hermes → .versions/2.0.7/hermes}/plugins/agent-fleet-herdr/dashboard/coms_registry.py +0 -0
  1013. /package/{hermes → .versions/2.0.7/hermes}/plugins/agent-fleet-herdr/dashboard/coms_send.py +0 -0
  1014. /package/{hermes → .versions/2.0.7/hermes}/plugins/agent-fleet-herdr/dashboard/watch.py +0 -0
  1015. /package/{hermes → .versions/2.0.7/hermes}/skills/hub-conductor/SKILL.md +0 -0
  1016. /package/{hermes → .versions/2.0.7/hermes}/skills/hub-watchdog/SKILL.md +0 -0
  1017. /package/{hooks → .versions/2.0.7/hooks}/coms-stop-hook.mjs +0 -0
  1018. /package/{scripts → .versions/2.0.7/scripts}/claude-code-preflight.ts +0 -0
  1019. /package/{scripts → .versions/2.0.7/scripts}/coms-claude-bridge.ts +0 -0
  1020. /package/{scripts → .versions/2.0.7/scripts}/coms-cli.ts +0 -0
  1021. /package/{scripts → .versions/2.0.7/scripts}/coms-hermes-bridge.ts +0 -0
  1022. /package/{scripts → .versions/2.0.7/scripts}/fleet-codex-read.py +0 -0
  1023. /package/{scripts → .versions/2.0.7/scripts}/flow.ts +0 -0
  1024. /package/{scripts → .versions/2.0.7/scripts}/lib/claude-bridge-core.ts +0 -0
  1025. /package/{scripts → .versions/2.0.7/scripts}/lib/coms-envelope.ts +0 -0
  1026. /package/{scripts → .versions/2.0.7/scripts}/lib/fleet-codex-transport.ts +0 -0
  1027. /package/{scripts → .versions/2.0.7/scripts}/lib/herdr-layout.ts +0 -0
  1028. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-bridge-core.ts +0 -0
  1029. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-monitor-events.ts +0 -0
  1030. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-monitor-herdr.ts +0 -0
  1031. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-monitor-model.ts +0 -0
  1032. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-monitor-registry.ts +0 -0
  1033. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-monitor-socket.ts +0 -0
  1034. /package/{scripts → .versions/2.0.7/scripts}/lib/hermes-monitor-store.ts +0 -0
  1035. /package/{scripts → .versions/2.0.7/scripts}/lib/monitor-env.ts +0 -0
  1036. /package/{scripts → .versions/2.0.7/scripts}/lib/peer-launch.ts +0 -0
  1037. /package/{scripts → .versions/2.0.7/scripts}/lib/persona-banner.ts +0 -0
  1038. /package/{scripts → .versions/2.0.7/scripts}/lib/runtime-dependencies.js +0 -0
  1039. /package/{scripts → .versions/2.0.7/scripts}/lib/spawn-stagger.ts +0 -0
  1040. /package/{scripts → .versions/2.0.7/scripts}/lib/team-project.ts +0 -0
  1041. /package/{scripts → .versions/2.0.7/scripts}/lib/team-snapshot.ts +0 -0
  1042. /package/{scripts → .versions/2.0.7/scripts}/peer-banner.ts +0 -0
  1043. /package/{scripts → .versions/2.0.7/scripts}/peer-launch.ts +0 -0
  1044. /package/{scripts → .versions/2.0.7/scripts}/team-snapshot.ts +0 -0
  1045. /package/{scripts → .versions/2.0.7/scripts}/team-up.ts +0 -0
  1046. /package/{scripts → .versions/2.0.7/scripts}/workflows/lib/agent-phase.ts +0 -0
  1047. /package/{scripts → .versions/2.0.7/scripts}/workflows/lib/envelopes.ts +0 -0
  1048. /package/{scripts → .versions/2.0.7/scripts}/workflows/lib/model-profile.ts +0 -0
  1049. /package/{scripts → .versions/2.0.7/scripts}/workflows/lib/personas.ts +0 -0
  1050. /package/{scripts → .versions/2.0.7/scripts}/workflows/lib/trace.ts +0 -0
@@ -0,0 +1,2151 @@
1
+ import { registerRetry } from "./commands/retry.ts";
2
+ import { createNoProgressGuard } from "./no-progress.ts";
3
+ import { closeEvidenceSession, pruneEvidenceSessions } from "./execution-evidence.ts";
4
+ import { isCompleteProfile, dispatcherSelection, type ModelProfiles } from './config/model-profiles.ts';
5
+ import { createProfileActivation } from './policy/profile-activation.ts';
6
+ import { readActiveProfile, profileWorkInFlight, withProfileWork, assertProfileModel, profilePeerGate } from './policy/profile-runtime.ts';
7
+ /** Agent Hub composition root: constructs mutable state, contexts, registrars, and ordered lifecycle ports. */
8
+
9
+ import type { AgentDef, AgentState, ResearchState } from "./types.ts";
10
+ import { DEFAULT_OVERRIDES, THINKING_LEVELS, parseAgentTeamOverrides } from "./config/overrides.ts";
11
+ import { loadAgentConfiguration } from "./config/agents.ts";
12
+ import { abbrevThinking, displayName, extractAskUserQuestions, extractNeedsResearch, resolveDelegateExtension, resolveThinkingLevel } from "./presentation.ts";
13
+ import { MAX_LIVE_ENTRY_CHARS, appendTimelineEvent, appendTimelineText, flushTimelineStore } from "./timeline.ts";
14
+ import type { ExtensionAPI, ExtensionContext, ImageContent, Theme } from "@mariozechner/pi-coding-agent";
15
+ import { DynamicBorder, getMarkdownTheme as getPiMdTheme, copyToClipboard } from "@mariozechner/pi-coding-agent";
16
+ import {
17
+ Text, Box, Container, Spacer, Markdown, matchesKey, Key,
18
+ type AutocompleteItem, truncateToWidth, visibleWidth,
19
+ } from "@mariozechner/pi-tui";
20
+ import { spawn, type ChildProcess } from "child_process";
21
+ import { spawnPiAgent, spawnPiAgentWithModelFallback, killPiTree, type Termination } from "./spawn.ts";
22
+ import { researchTerminationOutcome, researchWatchdogSpawnOptions } from "./research-watchdog.ts";
23
+ import { composeFleetFooterHint, renderHubFooterLeft } from "./footer.ts";
24
+ import { HARNESS_VERSION, registerVersionStatus } from "./version.ts";
25
+ import { cancelLocalOwnedProcess, cancelLocalWaitOnly, monitorKeyForAgent } from "./monitor-control.ts";
26
+ import { createMonitorLifecycle } from "./monitor-lifecycle.ts";
27
+ import { createMonitorSessionBridge } from "./monitor-session-bridge.ts";
28
+ import {
29
+ AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
30
+ exemptionsFilePath, type AccessRequest,
31
+ } from "../lib/damage-control-shared.ts";
32
+ import { applyModelOverride, clampDelegateDepth, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
33
+ import { DEFAULT_TASK_TIER, addTaskClockWait, applyTierChange, blockingFindingCap, checkReviewRoundCap, checkTaskBudget, checkTierPersonaGate, checkTurnBudget, createTaskClock, isReviewPersona, openTaskClock, remainingTaskResearch, reviewBudgetClause, reviewRoundCap } from "./run-budget.js";
34
+ import { countReviewFindings, findingBudgetNotice } from "./review-findings.js";
35
+ import { checkDocsLane, docsLaneNotice } from "./docs-lane.js";
36
+ import { checkExternalBlockerGate, extractExternalBlockers } from "./external-blocker.js";
37
+ import { DEFAULT_RUN_HISTORY_KEEP, normalizeRunHistoryKeep } from "./run-namespace.js";
38
+ import { validateAssertionBatch } from "./assertion-ledger.js";
39
+ import { DEFAULT_PROVIDER_LIMITS, createProviderSemaphore, parseProviderLimits } from "./provider-semaphore.js";
40
+ import {
41
+ PANE_PROMPT_TIMEOUT_MS,
42
+ launchPeerInPane,
43
+ peerReadyVerdict,
44
+ unaddressedPeerSweep,
45
+ } from "../lib/spawned-peers.js";
46
+ import { contextPct, estimatePromptTokens, resolveContextWindow } from "./context-window.js";
47
+ import { DEFAULT_WATCHDOG_SETTING, WATCHDOG_SETTINGS, normalizeWatchdogSetting, resolveWatchdogActive } from "./drift-watchdog.js";
48
+ import { shouldExtractReturn } from "./return-extract.js";
49
+ import { crossCheck, deliveryDisposition, extractAssertionIds, parseDeliveredReturn } from "./return-contract.js";
50
+ import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
51
+ import { validateEvidence } from "./evidence-rules.js";
52
+ import { comsRequiredRefusal, explicitComsRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
53
+ import { NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState, resolveSessionWorkMode, resolveSessionRoster } from "./work-mode.ts";
54
+ import { compactWorkMode } from "./work-mode-controls.ts";
55
+ import { registerWorkMode } from "./commands/work-mode.ts";
56
+ import { registerAgentsTeam } from "./commands/agents-team.ts";
57
+ import { registerAgentsList } from "./commands/agents-list.ts";
58
+ import { registerAgentsHistory } from "./commands/agents-history.ts";
59
+ import { registerAgentsAdd } from "./commands/agents-add.ts";
60
+ import { registerAgentsDrop } from "./commands/agents-drop.ts";
61
+ import { registerAgentsSave } from "./commands/agents-save.ts";
62
+ import { registerAgentsKill } from "./commands/agents-kill.ts";
63
+ import { registerAgentsRestart } from "./commands/agents-restart.ts";
64
+ import { registerContextCommand } from "./commands/context-command.ts";
65
+ import { registerHubReport } from "./commands/hub-report.ts";
66
+ import { registerZoom } from "./commands/zoom.ts";
67
+ import { registerDispatchPolicy } from "./commands/dispatch-policy.ts";
68
+ import { registerAgentModel } from "./commands/agent-model.ts";
69
+ import { registerAgentModelThinking } from "./commands/agent-model-thinking.ts";
70
+ import { registerModels } from "./commands/models.ts";
71
+ import { registerAgentModelsSubstitute } from "./commands/agent-models-substitute.ts";
72
+ import { registerWatchdog } from "./commands/watchdog.ts";
73
+ import { registerComs } from "./commands/coms.ts";
74
+ import { registerHandoff } from "./commands/handoff.ts";
75
+ import { registerCompound } from "./commands/compound.ts";
76
+ import { registerPoll } from "./commands/poll.ts";
77
+ import { registerDebate } from "./commands/debate.ts";
78
+ import type { CommandContext } from "./commands/context.ts";
79
+ import { formatAfPollStarted, formatAfPollVoiceProgress, handleAfPoll } from "./poll-command.ts";
80
+ import { formatAfDebateStarted, formatAfDebateVoiceProgress, handleAfDebate } from "./debate-command.ts";
81
+ import { registerDispatchAgent } from "./tools/dispatch-agent.ts";
82
+ import { registerSpawnResearch } from "./tools/spawn-research.ts";
83
+ import { registerSetTaskTier } from "./tools/set-task-tier.ts";
84
+ import { registerTeamAdjust } from "./tools/team-adjust.ts";
85
+ import { registerVerificationContract } from "./tools/verification-contract.ts";
86
+ import { registerComsTools } from "./tools/coms-tools.ts";
87
+ import { paneTail, peerManifest, peerPersonaExists, registerFleetTools, spawnDelaySeconds, STAGGER_ENV_VAR, waitForPeerRegistration } from "./tools/fleet-tools.ts";
88
+ import type { ToolContext } from "./tools/context.ts";
89
+ import { createToolExecutionOrchestration } from "./tools/execution-orchestration.ts";
90
+ import { latestPersistedCapabilityState, type ContextState, type PendingOperation } from "./capability-packs.ts";
91
+ import { contextPressureDiagnostic, createContextPressureState, transitionContextPressure, type ContextPressureState } from "./context-pressure.ts";
92
+ import { confirmationOutcome, capabilityConfirmationPack, capabilityConfirmationQuestion, type ConfirmableCapabilityPack } from "./capability-confirmation.ts";
93
+ import { createBudgetRecovery } from "./budget-recovery.ts";
94
+ import { requestRuntimeAsk } from "../ask-user-remote/runtime-ask.ts";
95
+ import { registerBudgetContinue } from "./commands/budget-continue.ts";
96
+ import { observeAskUserResults } from "../ask-user-remote/index.ts";
97
+ import { handleQuestionEnvelope, registerQuestionPeer } from "../ask-user-remote/questions.ts";
98
+ import { buildHubPeerSpawnPlan, launchHubPeerInPane } from "./peer-spawn-plan.ts";
99
+ import { RESEARCH_TOOLS, createResearchRuntime, parseResearchHandle } from "./research/runtime.ts";
100
+ import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
101
+ import { createAccessApprovalRouter } from "./access-approval.ts";
102
+ import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
103
+ import { herdrPaneId } from "../lib/herdr-presence.ts";
104
+ import { herdr as herdrApi, herdrAvailable } from "../lib/herdr-client.ts";
105
+ import {
106
+ abbreviateModel,
107
+ createComsPeer,
108
+ hexFg,
109
+ nowIso,
110
+ readAllRegistryEntries,
111
+ readAllRegistryEntriesAcrossProjects,
112
+ type ComsIdentity,
113
+ type RegistryEntry as ComsRegistryEntry,
114
+ TIMEOUT_MS,
115
+ } from "../lib/coms-core.ts";
116
+ import { createGridUI } from "./ui/grid.ts";
117
+ import { collectRunningStripItems } from "./ui/running-strip.ts";
118
+ import { createDetailPanel } from "./ui/detail-panel.ts";
119
+ import { createFleetDashboard } from "./ui/fleet-dashboard.ts";
120
+ import { createContextBudgetUi } from "./ui/context-budget.ts";
121
+ import { createPoolPresentation } from "./ui/pool.ts";
122
+ import { registerInputShortcuts } from "./input/shortcuts.ts";
123
+ import { createCompletionPresentation } from "./input/completions.ts";
124
+ import { createResearchControls } from "./research/controls.ts";
125
+ import { createContextPressureLifecycle, createContextPressureRootState } from "./lifecycle/context-pressure.ts";
126
+ import { createTurnLifecycleHandlers, registerTurnPresence } from "./lifecycle/turn-handlers.ts";
127
+ import { createMonitorSession } from "./lifecycle/monitor-session.ts";
128
+ import { applySessionOverrides, registerSessionOrchestration, resetHubSession } from "./lifecycle/session-orchestration.ts";
129
+ import { openZoom, type TimelineEntry, type Zoomable } from "./ui/zoom.ts";
130
+ import { openHistory } from "./ui/history.ts";
131
+ import { createExecutionHistoryStore, type HistoryEntry } from "./ui/history-store.ts";
132
+ import { createDispatchComs, createDispatchNative, createDispatchObservability, type DelegationChild } from "./dispatch-core.ts";
133
+ import { buildFleetRows, type PeerInput } from "../lib/fleet-read-model.ts";
134
+ import { gridColumnsForSize } from "../lib/fleet-dashboard-ops.ts";
135
+ import { createFleetTranscriptStore } from "../lib/fleet-transcript-store.ts";
136
+ import type { ContextBudgetComponent } from "../lib/context-budget.ts";
137
+ import { buildHubSystemPrompt as assembleHubPrompt } from "./prompts/system-prompt.ts";
138
+ import type { HubPromptContext } from "./prompts/context.ts";
139
+ import { buildSessionStartNotice, createSessionFooter } from "./prompts/session-start.ts";
140
+ import { registerSessionStart } from "./session-start.ts";
141
+ import { createHubStateContext } from "./context/hub-state.ts";
142
+ import { createAgentStateFactory } from "./context/agent-state.ts";
143
+ import { createBudgetContext, createSessionTotals, freshTurnReport, type PendingBudgetContinuation, type TurnReport } from "./context/budgets.ts";
144
+ import { createAssertionsArtifactsContext, type Assertion, type InputArtifactPreview } from "./context/assertions-artifacts.ts";
145
+ import { createModelPolicy } from "./policy/models.ts";
146
+ import { createRosterPolicy } from "./policy/roster.ts";
147
+ import { createWorkModePolicy } from "./policy/work-mode.ts";
148
+ import { nativeResearchSystemPrompt } from "../lib/context-budget-child-prompt.ts";
149
+ import { parseEnvFile, resolveEnvFilePath } from "../../../scripts/lib/herdr-layout.ts";
150
+ import { worktreeTag } from "../../../scripts/lib/team-project.ts";
151
+ import { join, resolve } from "path";
152
+ import * as fs from "node:fs";
153
+ import * as path from "node:path";
154
+ import * as crypto from "node:crypto";
155
+
156
+ // ── Extension ────────────────────────────────────
157
+
158
+ const CONTEXT_WARN_THRESHOLD = 70;
159
+ const RESEARCHER_PERSONAS = new Set(["researcher", "deep-researcher"]);
160
+
161
+ export default function (pi: ExtensionAPI) {
162
+ // ── Embedded coms: identity CLI flags ──
163
+ // Registered here (factory load time) so pi's CLI parser accepts them. Because
164
+ // coms is EMBEDDED (one extension, not a second `-e`), these register exactly once.
165
+ pi.registerFlag("name", { description: "Coms: override agent name (else frontmatter or auto-generated)", type: "string", default: undefined });
166
+ pi.registerFlag("purpose", { description: "Coms: override agent purpose (else frontmatter description)", type: "string", default: undefined });
167
+ pi.registerFlag("project", { description: "Coms: project namespace for peer discovery", type: "string", default: "default" });
168
+ pi.registerFlag("color", { description: "Coms: hex color #RRGGBB (else frontmatter or palette fallback)", type: "string", default: undefined });
169
+ pi.registerFlag("explicit", { description: "Coms: hide from auto-discovery; addressable only by exact name", type: "boolean", default: false });
170
+ pi.registerFlag("solo", { description: "Run without the coms layer (fixed specialists + research only — `just fleet hub --solo`)", type: "boolean", default: false });
171
+ pi.registerFlag("work-mode", { description: "Fleet main-agent work mode: operator|orchestrator", type: "string", default: undefined });
172
+ pi.registerFlag("agent-team", { description: "Internal: activate a named native roster from .pi/agents/teams.yaml", type: "string", default: undefined });
173
+
174
+ // ── Embedded coms: shared peer state ──
175
+ let currentCtx: ExtensionContext | null = null;
176
+ const coms = createComsPeer({
177
+ pi,
178
+ getContext: () => currentCtx,
179
+ onPeersChanged: () => {},
180
+ acceptInbound: () => currentCtx && modelWorkBlockedByRosterRecovery(currentCtx)
181
+ ? "orchestrator roster recovery required"
182
+ : null,
183
+ handleCustomEnvelope: (socket, envelope) => {
184
+ if (handleQuestionEnvelope(socket, envelope)) return true;
185
+ if (envelope.type !== "access_request") return false;
186
+ void accessApprovalRouter.handle(socket, envelope as AccessRequest);
187
+ return true;
188
+ },
189
+ });
190
+ const unregisterQuestions = registerQuestionPeer(() => coms.ready && coms.identity ? {
191
+ project: coms.identity.project, peer: coms.identity.name,
192
+ sessionId: coms.identity.session_id, startedAt: coms.identity.started_at,
193
+ } : null);
194
+ let identity: ComsIdentity | null = null;
195
+ const peerCards = coms.peerCards;
196
+ const pendingReplies = coms.pendingReplies;
197
+ const inboundQueue = coms.inboundQueue;
198
+ let comsReady = false;
199
+ let monitorLifecycle: ReturnType<typeof createMonitorLifecycle> | null = null;
200
+ let monitorHubId: string | null = null;
201
+ let monitorTurnId: string | null = null;
202
+ let monitorBridge: ReturnType<typeof createMonitorSessionBridge> | null = null;
203
+ let monitorOwnerId: string | undefined;
204
+
205
+ // ── Damage-control exemptions + access escalation state ──
206
+ // exemptionsFile is the session-scoped shared exemptions file: /af-allow
207
+ // session grants (via the co-loaded damage-control-continue) and approved
208
+ // escalations land here, and spawned children read it through the
209
+ // AGENT_HUB_EXEMPTIONS_FILE env plumbing.
210
+ let exemptionsFile: string | null = null;
211
+ const accessApprovalRouter = createAccessApprovalRouter({
212
+ getContext: () => currentCtx,
213
+ getExemptionsFile: () => exemptionsFile,
214
+ appendLog: (entry) => { try { pi.appendEntry("damage-control-log", entry); } catch { /* best-effort */ } },
215
+ now: nowIso,
216
+ });
217
+
218
+ const agentStates: Map<string, AgentState> = new Map();
219
+ // Live-only research helpers, keyed by numeric id (handle `rN`). Visible in the
220
+ // Fleet Dashboard (Alt+A) while running; evicted from this map on every terminal
221
+ // outcome. Session/transcript/findings files and /af-agents-history survive.
222
+ let researchStates: Map<number, ResearchState> = new Map();
223
+ // Metadata only: prompt text is never retained by this ledger.
224
+ let lastHubLedger: ContextBudgetComponent[] = [];
225
+ let nextResearchId = 1;
226
+
227
+ // ── Execution history (/af-agents-history) ──────────
228
+ // The typed store owns entries and turn/ask_user bookkeeping; index.ts owns
229
+ // composition and wires lifecycle events to its explicit API.
230
+ const executionHistory = createExecutionHistoryStore();
231
+
232
+ let researchPersonas: AgentDef[] = [];
233
+ let allAgentDefs: AgentDef[] = [];
234
+ let teams: Record<string, string[]> = {};
235
+ // Named model profiles from .pi/agents/model-profiles.yaml (validated at
236
+ // session start) and the session-lifetime per-persona model overrides set by
237
+ // /af-agent-model and /af-models (lowercase persona name → pi model spec). Overrides
238
+ // reset on session_start; profiles make re-applying cheap.
239
+ let modelProfiles: ModelProfiles = {};
240
+ let modelProfileErrors: string[] = [];
241
+ // Backend routing policy (.pi/agents/dispatch-policy.yaml): per dispatch, a
242
+ // member preferring coms is served by a live same-name pool peer instead of a
243
+ // native subagent spawn. Missing file → everything native (status quo).
244
+ let dispatchPolicy: {
245
+ default: string;
246
+ grace_s: number;
247
+ substitutions: Record<string, { prefer: string; fallback: string; timeout_s?: number }>;
248
+ } = { default: "native", grace_s: 30, substitutions: {} };
249
+ let dispatchPolicyWarnings: string[] = [];
250
+ // One "coms peer missing → native" notice per member per team activation.
251
+ const comsMissNotified = new Set<string>();
252
+
253
+ let activeTeamName = "";
254
+ let gridCols = 2;
255
+ let widgetCtx: any;
256
+ let sessionDir = "";
257
+ let contextWindow = 0;
258
+ // Per-provider in-flight cap for the hub's OWN spawns (specialists and
259
+ // research helpers, which the dispatcher can start in parallel). Delegate
260
+ // children are gated by the same policy inside their parent's process. The
261
+ // drift judge and the return extractor are deliberately NOT gated: both run
262
+ // while a specialist holds a permit, so queueing them behind that specialist
263
+ // would stall the very watchdog that is supposed to stop it.
264
+ const providerSemaphore = createProviderSemaphore({
265
+ ...DEFAULT_PROVIDER_LIMITS,
266
+ ...parseProviderLimits(process.env.AGENT_HUB_PROVIDER_LIMITS),
267
+ });
268
+ /**
269
+ * pi's model registry as a plain lookup — the documented source for every
270
+ * model's window, and the same one the dispatcher's own window comes from.
271
+ */
272
+ function modelWindowLookup(ctx: any): (provider: string, modelId: string) => any {
273
+ return (provider, modelId) => ctx?.modelRegistry?.find?.(provider, modelId);
274
+ }
275
+
276
+ /** Say so when a run is about to wait on a provider permit, not just hang. */
277
+ function notifyProviderQueue(model: string, label: string, ctx: any): void {
278
+ const cap = providerSemaphore.limitFor(model);
279
+ if (cap == null || providerSemaphore.inFlight(model) < cap) return;
280
+ const ahead = providerSemaphore.queued(model) + 1;
281
+ ctx?.ui?.notify(
282
+ `${label}: queued — ${cap} requests already in flight on this provider (${ahead} waiting). ` +
283
+ "Raise or disable the cap with AGENT_HUB_PROVIDER_LIMITS (e.g. custom=4, custom=off).",
284
+ "info",
285
+ );
286
+ }
287
+
288
+ let activeWritableDispatches = 0;
289
+ let writableOverlapCounter = 0;
290
+ let pendingHandoff: { target: string; token: string } | null = null;
291
+ const hubStateCtx = createHubStateContext({
292
+ getCurrentContext: () => currentCtx, setCurrentContext: value => { currentCtx = value; },
293
+ getExemptionsFile: () => exemptionsFile, setExemptionsFile: value => { exemptionsFile = value; },
294
+ getSessionDir: () => sessionDir, setSessionDir: value => { sessionDir = value; },
295
+ getWidgetContext: () => widgetCtx, setWidgetContext: value => { widgetCtx = value; },
296
+ getPendingHandoff: () => pendingHandoff, setPendingHandoff: value => { pendingHandoff = value; },
297
+ });
298
+ let userLanguage: string = DEFAULT_OVERRIDES.language;
299
+ // Project rule folders from the overrides file's `rules:` key (repo-relative,
300
+ // validated at session_start). Non-empty → every dispatched specialist gets a
301
+ // "Project rules" prompt block; personas resolve the folders index-first (a
302
+ // top-level README.md/index.md is a loading manifest) with recursive discovery
303
+ // as the no-index fallback.
304
+ let projectRulesDirs: string[] = [];
305
+ // Project documentation entry points from the overrides file's `docs:` key
306
+ // (repo-relative files or folders, validated at session_start). Non-empty →
307
+ // dispatched specialists and research helpers get a "Project docs" prompt block.
308
+ let projectDocsPaths: string[] = [];
309
+
310
+ // Prompt blocks for the project's own rules (HOW — compliance) and docs
311
+ // (WHAT/WHY — orientation). Rules discovery is index-first so a curated rule
312
+ // tree (README manifest + session bundles) is honored instead of bulk-read;
313
+ // the blind recursive find is only the no-index fallback. The validation duty
314
+ // itself is written into the planner/code-reviewer personas.
315
+ function buildRulesProtocol(): string {
316
+ if (projectRulesDirs.length === 0) return "";
317
+ return `
318
+
319
+ ## Project rules
320
+ This project keeps its own rules in: ${projectRulesDirs.join(", ")} (repo-relative).
321
+ Rules are HOW constraints — read the ones relevant to your task and comply with them.
322
+ Resolve them index-first: when a listed folder has a top-level README.md or index.md,
323
+ read that first and follow its loading manifest (session bundles, "load X when Y"
324
+ lists) to select the rule files that apply to your task; do not bulk-read the tree.
325
+ Only when a folder has no such index, discover rule files recursively
326
+ (\`find <dir> -type f\`) and read the relevant ones. If you plan or review work,
327
+ validate your subject against the rules; when delegating, pass the relevant rule
328
+ file paths and the specific points to check on to the child.`;
329
+ }
330
+
331
+ function buildDocsProtocol(): string {
332
+ if (projectDocsPaths.length === 0) return "";
333
+ return `
334
+
335
+ ## Project docs
336
+ This project's canonical documentation entry points are: ${projectDocsPaths.join(", ")}
337
+ (repo-relative). Docs carry WHAT/WHY context — architecture, standards, decisions.
338
+ They orient you; they are not compliance rules. Before working in an unfamiliar area,
339
+ read the entry points relevant to your task and follow the links they contain rather
340
+ than bulk-reading doc trees; when an entry point is a folder, start from its README.md
341
+ or index file. If your work changes something the docs describe (architecture, public
342
+ APIs, commands, structure), say so in your final response so the docs can be updated.`;
343
+ }
344
+
345
+ /** One canonical repository context file plus explicitly configured rule roots. */
346
+ function specialistProjectPolicyPaths(cwd: string): string[] {
347
+ const canonical = ["AGENTS.md", "CLAUDE.md"].find(candidate => existsSync(path.join(cwd, candidate)));
348
+ return [...new Set([...(canonical ? [canonical] : []), ...projectRulesDirs])];
349
+ }
350
+ // The one supported safety harness. Every native specialist, researcher, and
351
+ // nested delegate receives it; a missing harness refuses child dispatch.
352
+ let safetyHarnessPath: string | null = null;
353
+ // Resolved once at session_start: the delegate extension injected into
354
+ // specialists that declare `subagents:` (null → delegation disabled).
355
+ let delegateExtPath: string | null = null;
356
+ // Per-tool deadline for read/grep/find/ls in research helpers/delegates. The
357
+ // whole-run bound is separate: the turn budget's agentTurnMs (run-budget.js).
358
+ let reconSearchTimeoutMs: number | null = 120_000;
359
+ // ── Per-turn budgets (run-budget.js) ──
360
+ // Envelopes follow task tier. Override keys are a ceiling (min with the tier).
361
+ // Counters reset in before_agent_start, or after an explicit one-click
362
+ // continuation. executionHistory.turnStartedAt() is the active-time base; ask_user
363
+ // waits are subtracted.
364
+ let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
365
+ let turnDispatchCount = 0;
366
+ let turnResearchCount = 0;
367
+ // Human wait time is not fleet work. Track it separately from history UI
368
+ // intervals so a continuation can rebase the budget without erasing history.
369
+ let turnBudgetAskUserWaitMs = 0;
370
+ let taskContinuationCount = 0;
371
+ let turnContinuationCount = 0;
372
+ // ── Task-scoped budget & tier (run-budget.js) ──
373
+ // A per-message allowance cannot bound a task: every steering message opened a
374
+ // fresh turn window, so a run could spend 8 dispatches and 60 minutes again and
375
+ // again without any counter ever binding. These counters span the whole TASK
376
+ // and are cleared only by an explicit new task (`set_task_tier` with
377
+ // `new_task: true`) or an approved task-budget continuation — never by an
378
+ // ordinary user message.
379
+ let taskDispatchCount = 0;
380
+ let taskResearchCount = 0;
381
+ let taskLabel: string | null = null;
382
+ // The task clock charges ACTIVE time only — turns that ran, minus the time the
383
+ // dispatcher spent blocked on ask_user. Raw wall clock would bill the human's
384
+ // lunch break, an overnight pause, and every long answer against the task, and
385
+ // at small tier's 45-minute envelope that hard-stops a task with two dispatches
386
+ // spent. A false stop is worse than no stop: it teaches people to reset the
387
+ // task window reflexively, which is the one thing that must stay deliberate.
388
+ // The explicit clock state makes `active` authoritative: a stale timestamp can
389
+ // never turn inter-turn idle time into task work.
390
+ let taskClock = createTaskClock();
391
+ // Review dispatches spent on this task (review-round cap).
392
+ let taskReviewRounds = 0;
393
+ // Task tier (complexity triage): declared by the dispatcher via set_task_tier.
394
+ // TASK-scoped, not turn-scoped, and it moves by ratchet — down freely, up only
395
+ // with a stated reason (applyTierChange). Null until declared; the first
396
+ // dispatch assumes DEFAULT_TASK_TIER. Caps come from the tier envelope.
397
+ let taskTier: string | null = null;
398
+ // Was the tier ASSUMED by the hub rather than declared by the dispatcher? The
399
+ // distinction matters to the ratchet: an assumed tier must not turn the
400
+ // dispatcher's own first triage call into an "escalation" that needs a reason.
401
+ let taskTierAssumed = false;
402
+ // Duplicate-dispatch guard: fingerprints of (agent, task) already dispatched
403
+ // THIS turn. Auto-research resumes and /af-agents-restart call dispatchAgent
404
+ // directly, so only real dispatcher tool calls are guarded.
405
+ const turnDispatchFingerprints = new Set<string>();
406
+ // ── External-blocker circuit breaker (external-blocker.js) ──
407
+ // Set when a specialist reports it needs something outside the fleet's reach;
408
+ // gates the next dispatch until the human has been addressed. Cleared by an
409
+ // ask_user call, by a new user turn (the human spoke), and by a new task.
410
+ let externalBlockers: { agent: string; what: string }[] = [];
411
+ let externalBlockerAcknowledged = false;
412
+ let externalBlockerRefusedOnce = false;
413
+ // Per-run artifact archive retention (run-namespace.js).
414
+ let runHistoryKeep: number | null = DEFAULT_RUN_HISTORY_KEEP;
415
+ // ── Drift watchdog (drift-watchdog.js) ──
416
+ // Hub-wide setting from the overrides file, live-switchable via /af-watchdog;
417
+ // per-agent overrides ("on"/"off") win over it. In operator work mode a
418
+ // dispatch_agent `watchdog` param wins over both. In orchestrator work mode the
419
+ // watchdog auto-arms unless hub or per-agent is explicitly off; dispatch
420
+ // `watchdog: false` cannot disarm it.
421
+ let watchdogSetting: string = DEFAULT_WATCHDOG_SETTING;
422
+ let watchdogJudgeModel: string | null = null;
423
+ const watchdogAgentOverrides = new Map<string, "on" | "off">();
424
+ // ── Per-turn cost report (/af-hub-report) ──
425
+ let turnReport: TurnReport = freshTurnReport();
426
+ let lastTurnReport: TurnReport | null = null;
427
+ const sessionTotals = createSessionTotals();
428
+ // Session-wide delegated-spend counter (tokens across all delegate children),
429
+ // surfaced in the status line. Resets on session_start.
430
+ let delegatedTokens = 0;
431
+
432
+ const noProgress = createNoProgressGuard();
433
+ const budgetCtx = createBudgetContext({
434
+ getBudgetOverrides: () => budgetOverrides,
435
+ getTurnDispatchCount: () => turnDispatchCount, setTurnDispatchCount: value => { turnDispatchCount = value; },
436
+ getTurnResearchCount: () => turnResearchCount, setTurnResearchCount: value => { turnResearchCount = value; },
437
+ getTurnBudgetAskUserWaitMs: () => turnBudgetAskUserWaitMs, setTurnBudgetAskUserWaitMs: value => { turnBudgetAskUserWaitMs = value; },
438
+ resetBudgetRecovery: () => budgetRecovery.reset(),
439
+ resetNoProgress: () => noProgress.reset(),
440
+ getTaskContinuationCount: () => taskContinuationCount, setTaskContinuationCount: value => { taskContinuationCount = value; },
441
+ getTurnContinuationCount: () => turnContinuationCount, setTurnContinuationCount: value => { turnContinuationCount = value; },
442
+ getTaskDispatchCount: () => taskDispatchCount, setTaskDispatchCount: value => { taskDispatchCount = value; },
443
+ getTaskResearchCount: () => taskResearchCount, setTaskResearchCount: value => { taskResearchCount = value; },
444
+ getTaskLabel: () => taskLabel, setTaskLabel: value => { taskLabel = value; },
445
+ getTaskClock: () => taskClock, setTaskClock: value => { taskClock = value; },
446
+ getTaskReviewRounds: () => taskReviewRounds, setTaskReviewRounds: value => { taskReviewRounds = value; },
447
+ getTaskTier: () => taskTier, setTaskTier: value => { taskTier = value; },
448
+ getTaskTierAssumed: () => taskTierAssumed, setTaskTierAssumed: value => { taskTierAssumed = value; },
449
+ clearTurnDispatchFingerprints: () => turnDispatchFingerprints.clear(),
450
+ clearTaskCapabilities: () => workModePolicy.resetCapabilities(),
451
+ clearExternalBlockers: () => { externalBlockers = []; externalBlockerAcknowledged = false; externalBlockerRefusedOnce = false; },
452
+ resolveIncomingCapabilities: () => { resolveIncomingCapabilities("", true); }, applyWorkModeTools: () => { applyWorkModeTools(); },
453
+ getTurnReport: () => turnReport,
454
+ setStatus: (key, value) => { widgetCtx?.ui?.setStatus(key, value); },
455
+ getAuditContext: () => ({ cwd: identity?.cwd ?? currentCtx?.cwd, sessionId: identity?.session_id, project: identity?.project }),
456
+ appendEntry: (type, data) => { pi.appendEntry(type, data); },
457
+ executionHistory,
458
+ });
459
+ const {
460
+ currentBudget, currentTaskBudget, taskCounters, taskActiveElapsedMs, turnBudgetActiveElapsedMs,
461
+ renewTurnBudgetWindow, continueTaskBudgetWindow, closeTurnActiveTime, resetTaskWindow,
462
+ hubAuditIdentity, hubLocationSuffix, taskResetSnapshot, budgetContinuationSnapshot,
463
+ appendTaskResetEntry, appendBudgetContinuationEntry, updateModeStatus, ensureTaskTier,
464
+ } = budgetCtx;
465
+ const budgetRecovery = createBudgetRecovery({
466
+ check: operation => {
467
+ const task = checkTaskBudget(operation, taskCounters(), currentTaskBudget(), taskActiveElapsedMs(), taskTier);
468
+ if (task) return { ...task, kind: "task" };
469
+ const turn = checkTurnBudget(operation, { dispatches: turnDispatchCount, research: turnResearchCount }, currentBudget(), turnBudgetActiveElapsedMs(), taskTier);
470
+ return turn ? { ...turn, kind: "turn" } : null;
471
+ },
472
+ language: () => userLanguage,
473
+ ask: (id, params, ctx, signal) => requestRuntimeAsk(pi.events, id, params, ctx, signal),
474
+ startWait: id => executionHistory.startAskUser(id),
475
+ endWait: (id, sameTask) => {
476
+ const wait = executionHistory.endAskUser(id, Date.now());
477
+ if (!sameTask) return;
478
+ if (wait > 0) taskClock = addTaskClockWait(taskClock, wait);
479
+ turnBudgetAskUserWaitMs += wait;
480
+ },
481
+ renew: (refusal, correlation, ctx) => {
482
+ const at = Date.now(), prior = budgetContinuationSnapshot(refusal.kind, at);
483
+ if (refusal.kind === "task") continueTaskBudgetWindow(at); else renewTurnBudgetWindow(at);
484
+ appendBudgetContinuationEntry(refusal.kind, refusal.reason, prior, ctx, correlation);
485
+ },
486
+ });
487
+
488
+ // ── Verification Contract: assertion ledger (advisory) ──
489
+ // Mutable ownership remains here; the extracted runtime receives explicit ports.
490
+ let assertions: Assertion[] = [];
491
+ const assertionsArtifactsCtx = createAssertionsArtifactsContext({
492
+ getAssertions: () => assertions,
493
+ getSessionDir: () => sessionDir,
494
+ getRunHistoryKeep: () => runHistoryKeep,
495
+ setStatus: (key, value) => { widgetCtx?.ui?.setStatus(key, value); },
496
+ });
497
+ const {
498
+ persistAssertions, assertionStatusLine, renderAssertionLedgerLines, renderAssertionLedgerText,
499
+ updateAssertionStatus, artifactsRoot, ensureArtifactsLayout, archivePreviousRun,
500
+ loadInputArtifacts, appendInputArtifacts, writeRunArtifact, evidencePathExists,
501
+ listArtifactFiles, renderArtifactIndexText, appendMachineHandoffSections,
502
+ } = assertionsArtifactsCtx;
503
+
504
+ const modelPolicy = createModelPolicy<AgentDef>({
505
+ getAllDefs: () => allAgentDefs,
506
+ getActiveDef: name => agentStates.get(name)?.def,
507
+ getResearchDefs: () => researchPersonas,
508
+ refreshUi: () => updateWidget(),
509
+ });
510
+ const {
511
+ allowedModels, substitutedModel, resolvedModel, resolvedSubagentModel,
512
+ resolvedThinking, switchablePersonaDef, allKnownModels,
513
+ } = modelPolicy;
514
+
515
+ let profileCommandContext: any;
516
+ const profileActivation = createProfileActivation({
517
+ busy: () => !profileCommandContext?.isIdle?.() || profileWorkInFlight()>0 ||
518
+ Array.from(agentStates.values()).some(state=>state.status==='running') ||
519
+ Array.from(researchStates.values()).some(state=>state.status==='running'),
520
+ defs: () => allAgentDefs,
521
+ available: async () => {
522
+ await profileCommandContext.modelRegistry.refresh?.();
523
+ return (profileCommandContext.modelRegistry.getAvailable?.()??[]).map((m:any)=>`${m.provider}/${m.id}`);
524
+ },
525
+ dispatcher: () => profileCommandContext?.model ? {model:`${profileCommandContext.model.provider}/${profileCommandContext.model.id}`,thinking:pi.getThinkingLevel()} : undefined,
526
+ setDispatcher: async selection => {
527
+ const slash=selection.model.indexOf('/');
528
+ const model=profileCommandContext.modelRegistry.find(selection.model.slice(0,slash),selection.model.slice(slash+1));
529
+ if(!model || !await pi.setModel(model)) return false;
530
+ if(selection.thinking) pi.setThinkingLevel(selection.thinking as any);
531
+ return true;
532
+ },
533
+ apply: profile => modelPolicy.applyProfile(profile),
534
+ });
535
+ pi.on('model_select', async (event,ctx) => {
536
+ contextWindow=event.model.contextWindow||0;
537
+ if(profileActivation.switching()) return;
538
+ const active=readActiveProfile();if(!active) return;
539
+ try { assertProfileModel(`${event.model.provider}/${event.model.id}`,active); }
540
+ catch(error) {
541
+ ctx.abort();ctx.ui.notify(String(error),'error');
542
+ const target=dispatcherSelection(active.profile).model, slash=target.indexOf('/');
543
+ const model=ctx.modelRegistry.find(target.slice(0,slash),target.slice(slash+1));
544
+ if(model) await pi.setModel(model);
545
+ }
546
+ });
547
+ pi.on('before_provider_request', async (_event,ctx) => {
548
+ if(!ctx.model) return;
549
+ try { assertProfileModel(`${ctx.model.provider}/${ctx.model.id}`); }
550
+ catch(error) {ctx.abort();ctx.ui.notify(String(error),'error');}
551
+ });
552
+
553
+ function appendDeclaredScope(task: string, scopeGlobs: string[]): string {
554
+ if (!scopeGlobs || scopeGlobs.length === 0) return task;
555
+ return task + `\n\n## Declared scope — advisory guardrail\nStay within these paths/globs when changing files; changes outside them will be flagged to the dispatcher for a human decision, not auto-reverted.\n${scopeGlobs.map(s => `- ${s}`).join("\n")}`;
556
+ }
557
+
558
+ function loadAgents(cwd: string): void {
559
+ if (sessionDir) closeEvidenceSession(sessionDir);
560
+ loadAgentConfiguration(cwd, {
561
+ setSessionDir: hubStateCtx.setSessionDir, getSessionDir: hubStateCtx.getSessionDir,
562
+ archivePreviousRun, ensureArtifactsLayout, resetAssertions: () => { assertions = []; },
563
+ setAgentDefs: value => { allAgentDefs = value; }, setTeams: value => { teams = value; },
564
+ setModelProfiles: value => { modelProfiles = value; }, setModelProfileErrors: errors => { modelProfileErrors=errors; }, setDispatchPolicy: value => { dispatchPolicy = value; },
565
+ setDispatchPolicyWarnings: value => { dispatchPolicyWarnings = value; },
566
+ });
567
+ pruneEvidenceSessions(sessionDir, runHistoryKeep);
568
+ }
569
+
570
+ const agentStateFactory = createAgentStateFactory(() => sessionDir);
571
+ const { sessionHealthIo, adoptableSessionFile, freshAgentState } = agentStateFactory;
572
+
573
+ // Auto-size grid columns based on team size
574
+ function recomputeGrid() {
575
+ gridCols = gridColumnsForSize(agentStates.size);
576
+ }
577
+
578
+ const rosterPolicy = createRosterPolicy<AgentDef, AgentState>({
579
+ getTeams: () => teams, getAllDefs: () => allAgentDefs, getStates: () => agentStates,
580
+ getActiveTeamName: () => activeTeamName, setActiveTeamName: value => { activeTeamName = value; },
581
+ clearBackendNotices: () => comsMissNotified.clear(), createFreshState: freshAgentState,
582
+ adoptSession: adoptableSessionFile,
583
+ quarantineSession: agentStateFactory.quarantine,
584
+ persist: team => pi.appendEntry(NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState(team)),
585
+ recompute: recomputeGrid, refreshUi: () => updateWidget(), displayName,
586
+ orchestratorNeedsRosterAfterDrop: size => orchestratorNeedsRoster(getWorkMode(), size),
587
+ });
588
+ const { activateTeam, persistActiveRoster, add: rosterAdd, drop: rosterDrop } = rosterPolicy;
589
+
590
+ // ── Shared model presentation ─────────────────
591
+ // These formatters serve the extracted grid and the remaining composition-root
592
+ // call sites. Keep one implementation so cards, fleet rows, menus, fallback
593
+ // notices, and the footer retain the same presentation semantics.
594
+ function shortModel(model: string | undefined): string {
595
+ return model ? model.split("/").pop()! : "default";
596
+ }
597
+
598
+ // A " (code)" thinking badge for display, or "" when the level is off.
599
+ function thinkingSuffix(rawThinking: string | undefined): string {
600
+ const code = abbrevThinking(resolveThinkingLevel(rawThinking));
601
+ return code ? ` (${code})` : "";
602
+ }
603
+
604
+ // The model + thinking badge a persona would dispatch with: "gpt-5.5 (xh)".
605
+ function modelWithThinking(def: AgentDef): string {
606
+ return shortModel(resolvedModel(def)) + thinkingSuffix(resolvedThinking(def));
607
+ }
608
+
609
+ // ── Grid Rendering ───────────────────────────
610
+ const gridUI = createGridUI({
611
+ getWidgetContext: () => widgetCtx,
612
+ getRunningItems: () => {
613
+ const specialists = Array.from(agentStates.values()).map(state => ({
614
+ name: displayName(state.def.name),
615
+ status: state.status,
616
+ model: state.lastBackend === "coms" ? `⇄coms ${shortModel(state.comsPeerModel)}` : modelWithThinking(state.def),
617
+ elapsed: state.elapsed,
618
+ toolCount: state.toolCount,
619
+ messageCount: state.messageCount ?? 0,
620
+ delegations: Array.from(state.delegations?.values() ?? []).map(child => ({
621
+ role: child.role || child.id,
622
+ id: child.id,
623
+ status: child.status,
624
+ model: shortModel(child.model),
625
+ elapsed: child.elapsed,
626
+ startedAt: child.startedAt,
627
+ toolCount: child.toolCount,
628
+ messageCount: child.messageCount ?? 0,
629
+ })),
630
+ }));
631
+ const research = Array.from(researchStates.values()).map(state => ({
632
+ id: state.id,
633
+ persona: state.persona,
634
+ displayName: displayName(state.def.name),
635
+ status: state.status,
636
+ model: shortModel(state.model) + thinkingSuffix(resolvedThinking(state.def)),
637
+ elapsed: state.elapsed,
638
+ toolCount: state.toolCount,
639
+ messageCount: state.messageCount ?? 0,
640
+ }));
641
+ const pendingByName = new Map<string, { count: number; oldest: number }>();
642
+ for (const pending of coms.pendingReplies.values()) {
643
+ if (pending.result || !pending.target_name) continue;
644
+ const started = Date.parse(pending.created_at) || Date.now();
645
+ const prev = pendingByName.get(pending.target_name);
646
+ if (!prev) pendingByName.set(pending.target_name, { count: 1, oldest: started });
647
+ else pendingByName.set(pending.target_name, { count: prev.count + 1, oldest: Math.min(prev.oldest, started) });
648
+ }
649
+ const now = Date.now();
650
+ const comsRows = [];
651
+ const seen = new Set<string>();
652
+ for (const card of peerCards.values()) {
653
+ const pending = pendingByName.get(card.name);
654
+ const running = card.status === "working" || (card.queue_depth ?? 0) > 0 || !!pending;
655
+ if (!running) continue;
656
+ seen.add(card.name);
657
+ comsRows.push({
658
+ name: card.name,
659
+ model: abbreviateModel(card.model),
660
+ elapsed: pending ? now - pending.oldest : 0,
661
+ eventCount: (pending?.count ?? 0) + (card.queue_depth ?? 0),
662
+ running: true,
663
+ });
664
+ }
665
+ for (const [name, pending] of pendingByName) {
666
+ if (seen.has(name)) continue;
667
+ comsRows.push({ name, model: "", elapsed: now - pending.oldest, eventCount: pending.count, running: true });
668
+ }
669
+ return collectRunningStripItems({ specialists, research, coms: comsRows }, now);
670
+ },
671
+ });
672
+ const { updateWidget } = gridUI;
673
+
674
+ // ── Delegation observability ─────────────────
675
+ const dispatchObservability = createDispatchObservability({
676
+ getSessionDir: () => sessionDir,
677
+ getDelegatedTokens: () => delegatedTokens,
678
+ setDelegatedTokens: value => { delegatedTokens = value; },
679
+ getWidgetContext: () => widgetCtx,
680
+ executionHistory,
681
+ displayName,
682
+ safeAgentKey,
683
+ safePathWithin,
684
+ createTranscriptStore: createFleetTranscriptStore,
685
+ appendTimelineText,
686
+ appendTimelineEvent,
687
+ updateWidget,
688
+ });
689
+ const { startDelegationWatch } = dispatchObservability;
690
+
691
+ // ── Dispatch Agent (returns Promise) ─────────
692
+
693
+ // ── Extracted coms dispatch, drift judge, and return extraction ──
694
+ const dispatchComs = createDispatchComs({
695
+ getIdentity: () => identity,
696
+ resolveTarget: target => coms.resolveTarget(target),
697
+ send: (params, auditExtra) => coms.send(params, auditExtra),
698
+ getPendingReply: msgId => pendingReplies.get(msgId),
699
+ deletePendingReply: msgId => { pendingReplies.delete(msgId); },
700
+ getSessionDir: () => sessionDir,
701
+ getWatchdogJudgeModel: () => watchdogJudgeModel,
702
+ getResearcherModel: () => {
703
+ const researcherDef = allAgentDefs.find(def => def.name.toLowerCase() === "researcher");
704
+ return researcherDef ? resolvedModel(researcherDef) ?? null : null;
705
+ },
706
+ displayName,
707
+ safeAgentKey,
708
+ safePathWithin,
709
+ appendInputArtifacts,
710
+ appendDeclaredScope,
711
+ buildRulesProtocol,
712
+ buildDocsProtocol,
713
+ updateWidget,
714
+ spawnPiAgent,
715
+ });
716
+ const { dispatchViaComs, runDriftJudge, runReturnExtraction } = dispatchComs;
717
+
718
+ const nativeDispatch = createDispatchNative({
719
+ getAgentState: key => agentStates.get(key),
720
+ listAgentStates: () => Array.from(agentStates.values()),
721
+ getSessionDir: () => sessionDir,
722
+ getDispatchPolicy: () => dispatchPolicy,
723
+ isComsReady: () => comsReady,
724
+ getIdentity: () => identity,
725
+ peersInScope: () => peersInScope(),
726
+ wasComsMissNotified: personaKey => comsMissNotified.has(personaKey),
727
+ markComsMissNotified: personaKey => { comsMissNotified.add(personaKey); },
728
+ startMonitorChild: (input, env) => {
729
+ const monitorStart = monitorTurnId;
730
+ return monitorStart ? monitorBridge?.startChild({ ...input, parentId: monitorStart }, env) : undefined;
731
+ },
732
+ finalizeMonitorChild: (task, output, status) => monitorBridge?.finalizeChildFor(task, output, status),
733
+ registerMonitorWaitOnly: (monitorKey, state) => monitorBridge?.registerWaitOnly(monitorKey, () => state.comsAbort?.()),
734
+ registerMonitorProcess: (task, proc) => monitorBridge?.registerOwnedProcessFor(task, proc),
735
+ appendMonitorOutput: (task, delta) => monitorBridge?.appendOutputFor(task, delta),
736
+ getContextWindow: () => contextWindow,
737
+ currentBudget,
738
+ bumpRecycle: () => { turnReport.recycles++; sessionTotals.recycles++; },
739
+ bumpDriftStop: () => { turnReport.driftStops++; sessionTotals.driftStops++; },
740
+ getSessionHealthIo: () => sessionHealthIo,
741
+ getSafetyHarnessPath: () => safetyHarnessPath,
742
+ getDelegateExtensionPath: () => delegateExtPath,
743
+ getReconSearchTimeoutMs: () => reconSearchTimeoutMs,
744
+ getProjectDocsPaths: () => projectDocsPaths,
745
+ getUserLanguage: () => userLanguage,
746
+ getWatchdogSetting: () => watchdogSetting,
747
+ getWatchdogAgentOverride: key => watchdogAgentOverrides.get(key),
748
+ getWorkMode: () => getWorkMode(),
749
+ providerSemaphore,
750
+ executionHistory,
751
+ displayName,
752
+ shortModel: model => shortModel(model),
753
+ resolvedModel,
754
+ resolvedThinking,
755
+ resolveThinkingLevel,
756
+ resolvedSubagentModel,
757
+ substitutedModel,
758
+ modelWindowLookup,
759
+ specialistProjectPolicyPaths,
760
+ guardrailEnv,
761
+ appendInputArtifacts,
762
+ appendDeclaredScope,
763
+ flushTimelineStore,
764
+ appendTimelineText,
765
+ appendTimelineEvent,
766
+ createTranscriptStore: createFleetTranscriptStore,
767
+ updateWidget,
768
+ startDelegationWatch,
769
+ dispatchViaComs,
770
+ runDriftJudge,
771
+ notifyProviderQueue,
772
+ spawnPiAgentWithModelFallback,
773
+ });
774
+ const { dispatchAgent } = nativeDispatch;
775
+
776
+ // Shared child guardrail environment. Dispatch-native and research use the
777
+ // same root-owned exemptions and coms escalation endpoint.
778
+ function guardrailEnv(agentId: string): Record<string, string> {
779
+ const env: Record<string, string> = { [AGENT_ID_ENV]: agentId };
780
+ if (exemptionsFile) env[EXEMPTIONS_FILE_ENV] = exemptionsFile;
781
+ if (comsReady && identity) env[ASK_ENDPOINT_ENV] = identity.endpoint;
782
+ return env;
783
+ }
784
+
785
+ // ── Research helper runtime ────────────────────
786
+ // The composition root owns the mutable bindings; the runtime reaches them only
787
+ // through these explicit ports so later controls can keep stable handles.
788
+ const researchRuntime = createResearchRuntime<AgentDef>({
789
+ getResearchStates: () => researchStates,
790
+ setResearchStates: value => { researchStates = value; },
791
+ getNextResearchId: () => nextResearchId,
792
+ setNextResearchId: value => { nextResearchId = value; },
793
+ hubState: hubStateCtx, budget: budgetCtx, artifacts: assertionsArtifactsCtx,
794
+ executionHistory, providerSemaphore,
795
+ getSafetyHarnessPath: () => safetyHarnessPath,
796
+ getReconSearchTimeoutMs: () => reconSearchTimeoutMs,
797
+ getContextWindow: () => contextWindow,
798
+ resolvedModel, resolvedThinking, resolveThinkingLevel, fallbackModelFor, substitutedModel,
799
+ modelWindowLookup, guardrailEnv, notifyProviderQueue, spawnPiAgentWithModelFallback,
800
+ nativeResearchSystemPrompt, requireSafetyHarness, shortModel, displayName,
801
+ flushTimelineStore, appendTimelineText, appendTimelineEvent,
802
+ createTranscriptStore: createFleetTranscriptStore,
803
+ onElapsed: () => updateWidget(),
804
+ });
805
+
806
+ // ── Embedded coms: shared registry, transport, and pool core ──
807
+ const peersInScope = () => coms.peersInScope();
808
+ const resolveTarget = (target: string) => coms.resolveTarget(target);
809
+
810
+ const poolPresentation = createPoolPresentation({
811
+ getIdentity: () => identity,
812
+ getDisplayProject: () => coms.scope.displayProject,
813
+ includeExplicitPeers: () => coms.scope.includeExplicit,
814
+ getPeerCards: () => peerCards,
815
+ readProjectEntries: readAllRegistryEntries,
816
+ readAllEntries: readAllRegistryEntriesAcrossProjects,
817
+ truncate: truncateToWidth,
818
+ });
819
+ const fleetPeerInputs = poolPresentation.peerInputs;
820
+
821
+ // ── Extracted tool execution wiring ──
822
+ // Mutable fleet state remains composition-owned; executor modules receive ports.
823
+ let herdrFleetReady = false;
824
+ const hubSpawnedPeers = new Map<string, { name: string; paneId: string | null; addressed: boolean }>();
825
+ const markPeerAddressed = (name: string) => {
826
+ const entry = hubSpawnedPeers.get(String(name || "").toLowerCase());
827
+ if (entry) entry.addressed = true;
828
+ };
829
+ let lastHubPiSpawnAt: number | null = null;
830
+
831
+ let askUserAvailable = false;
832
+ let baselineTools: string[] = [];
833
+ let contextPressureState: ContextPressureState = createContextPressureState();
834
+ const pressureRootState = createContextPressureRootState();
835
+
836
+ function pendingCapabilityOperations(): PendingOperation[] {
837
+ const pending: PendingOperation[] = [];
838
+ if (Array.from(agentStates.values()).some(state => state.status === "running") || Array.from(researchStates.values()).some(state => state.status === "running")) pending.push({ pack: "fleet", kind: "child" });
839
+ if (pendingReplies.size > 0 || pendingHandoff) pending.push({ pack: "peer", kind: "message" });
840
+ if (hubSpawnedPeers.size > 0) pending.push({ pack: "workspace", kind: "pane" });
841
+ return pending;
842
+ }
843
+ function capabilityContextState(): ContextState {
844
+ if (contextPressureState.phase === "warning") return "approaching-compaction";
845
+ if (contextPressureState.phase !== "normal" || contextPressureState.pressure === "imminent") return "imminent-compaction";
846
+ if (contextPressureState.pressure === "approaching") return "approaching-compaction";
847
+ const percent = currentCtx?.getContextUsage?.()?.percent;
848
+ if (typeof percent === "number" && percent >= 90) return "imminent-compaction";
849
+ if (typeof percent === "number" && percent >= 80) return "approaching-compaction";
850
+ return "normal";
851
+ }
852
+ const workModePolicy = createWorkModePolicy({
853
+ getBaselineTools: () => baselineTools, getRosterSize: () => agentStates.size,
854
+ activateFallbackRoster: ctx => {
855
+ if (!rosterPolicy.activateFirstValidTeam()) return;
856
+ workModePolicy.clearRosterRecovery();
857
+ persistActiveRoster();
858
+ setTimeout(replayDeferredRecoveryInputs, 0);
859
+ updateWidget();
860
+ ctx.ui.setStatus("agent-team", `Team: ${activeTeamName} (${agentStates.size})`);
861
+ },
862
+ getActiveTeamName: () => activeTeamName, getComsReady: () => comsReady,
863
+ getHerdrReady: () => herdrFleetReady, getAskUserAvailable: () => askUserAvailable,
864
+ getIdentityLabel: () => identity ? `${identity.name}@${identity.project}` : null,
865
+ getTaskTier: () => taskTier, getPendingOperations: pendingCapabilityOperations,
866
+ getContextState: capabilityContextState, setActiveTools: tools => pi.setActiveTools(tools),
867
+ persist: (type, data) => pi.appendEntry(type, data), replayDeferredInputs: replayDeferredRecoveryInputs,
868
+ watchdogArmed: mode => resolveWatchdogActive(undefined, undefined, watchdogSetting, mode),
869
+ });
870
+ const {
871
+ getWorkMode, getCapabilityResolution, resolveIncomingCapabilities, provisionalCapabilityRefusal,
872
+ applyWorkModeTools, modelWorkBlockedByRosterRecovery,
873
+ statusText: workModeStatusText, applySelection: applyWorkModeSelection, openPicker: openWorkModePicker,
874
+ } = workModePolicy;
875
+
876
+
877
+ const toolCtx: ToolContext = createToolExecutionOrchestration({
878
+ dispatch: {
879
+ state: {
880
+ getTurnDispatchCount: () => turnDispatchCount, setTurnDispatchCount: value => { turnDispatchCount = value; },
881
+ getTurnResearchCount: () => turnResearchCount, setTurnResearchCount: value => { turnResearchCount = value; },
882
+ getTaskDispatchCount: () => taskDispatchCount, setTaskDispatchCount: value => { taskDispatchCount = value; },
883
+ getTaskResearchCount: () => taskResearchCount, setTaskResearchCount: value => { taskResearchCount = value; },
884
+ getTaskReviewRounds: () => taskReviewRounds, setTaskReviewRounds: value => { taskReviewRounds = value; },
885
+ getTaskTier: () => taskTier, getTurnReport: () => turnReport, getSessionTotals: () => sessionTotals,
886
+ getTurnDispatchFingerprints: () => turnDispatchFingerprints,
887
+ getExternalBlockers: () => externalBlockers,
888
+ getExternalBlockerAcknowledged: () => externalBlockerAcknowledged, setExternalBlockerAcknowledged: value => { externalBlockerAcknowledged = value; },
889
+ getExternalBlockerRefusedOnce: () => externalBlockerRefusedOnce, setExternalBlockerRefusedOnce: value => { externalBlockerRefusedOnce = value; },
890
+ isAskUserAvailable: () => askUserAvailable, getUserLanguage: () => userLanguage, getSessionDir: () => sessionDir,
891
+ getAgentStates: () => agentStates as any, getResearchPersonas: () => researchPersonas,
892
+ getActiveWritableDispatches: () => activeWritableDispatches, setActiveWritableDispatches: value => { activeWritableDispatches = value; },
893
+ getWritableOverlapCounter: () => writableOverlapCounter, setWritableOverlapCounter: value => { writableOverlapCounter = value; },
894
+ },
895
+ budget: budgetCtx, budgetRecovery, noProgress, artifacts: assertionsArtifactsCtx, research: researchRuntime,
896
+ provisionalCapabilityRefusal, dispatchAgent, runReturnExtraction,
897
+ extractNeedsResearch, extractAskUserQuestions, contextPressure: percent => percent >= CONTEXT_WARN_THRESHOLD, displayName,
898
+ },
899
+ actions: {
900
+ budget: budgetCtx, artifacts: assertionsArtifactsCtx, hubState: hubStateCtx,
901
+ provisionalCapabilityRefusal,
902
+ getTaskTier: () => taskTier, setTaskTier: value => { taskTier = value; },
903
+ getTaskTierAssumed: () => taskTierAssumed, setTaskTierAssumed: value => { taskTierAssumed = value; },
904
+ getTaskDispatchCount: () => taskDispatchCount, getTaskResearchCount: () => taskResearchCount,
905
+ getTurnReport: () => turnReport, getAssertions: () => assertions, setAssertions: value => { assertions = value; },
906
+ getAgentStates: () => agentStates, rosterAdd, rosterDrop,
907
+ getIdentity: () => identity, getComs: () => coms, resolveTarget,
908
+ appendMachineHandoffSections, markPeerAddressed,
909
+ },
910
+ herdr: {
911
+ provisionalCapabilityRefusal, isFleetReady: () => herdrFleetReady, isComsReady: () => comsReady,
912
+ getIdentity: () => identity, getCurrentContext: () => currentCtx, peersInScope,
913
+ getComsPeerNames: () => peersInScope().map(peer => peer.name), herdr: herdrApi,
914
+ readEnvFile: file => fs.readFileSync(file, "utf-8"), envFileExists: file => fs.existsSync(file),
915
+ getLastPiSpawnAt: () => lastHubPiSpawnAt, setLastPiSpawnAt: value => { lastHubPiSpawnAt = value; },
916
+ recordSpawnedPeer: (name, paneId) => { hubSpawnedPeers.set(name.toLowerCase(), { name, paneId, addressed: false }); },
917
+ },
918
+ });
919
+
920
+ // Keep the extracted tool surface flat and greppable in this composition root.
921
+ registerDispatchAgent(pi, toolCtx);
922
+ registerSpawnResearch(pi, toolCtx);
923
+ registerSetTaskTier(pi, toolCtx);
924
+ registerTeamAdjust(pi, toolCtx);
925
+ registerVerificationContract(pi, toolCtx);
926
+ registerComsTools(pi, toolCtx);
927
+ registerFleetTools(pi, toolCtx);
928
+
929
+ const researchControls = createResearchControls({
930
+ runtime: researchRuntime,
931
+ refresh: () => {},
932
+ getAgents: () => agentStates, displayName, modelWorkBlocked: modelWorkBlockedByRosterRecovery,
933
+ cancelWait: (state, kind) => cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), event: { kind } }),
934
+ cancelOwned: state => cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), treeKill: killPiTree }),
935
+ restartSpecialist: async (state: AgentState, ctx) => {
936
+ if (state.status === "running" && (state.proc || state.comsAbort)) {
937
+ let resolveTermination!: () => void;
938
+ const terminated = new Promise<void>(resolve => { resolveTermination = resolve; });
939
+ state.onTerminate = resolveTermination;
940
+ if (state.proc) { state.killedByOperator = true; state.restarting = true; killPiTree(state.proc); }
941
+ else await cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), event: { kind: "restart" } });
942
+ await terminated;
943
+ }
944
+ state.sessionFile = null;
945
+ const result = await dispatchAgent(state.def.name, state.task, ctx);
946
+ pi.sendMessage({ customType: "agent-restart-result", content: `[${displayName(state.def.name)}] restarted by operator and ${result.exitCode === 0 ? "completed" : "failed"} in ${Math.round(result.elapsed / 1000)}s.`, display: true }, { deliverAs: "followUp", triggerTurn: true });
947
+ },
948
+ });
949
+
950
+ // ── ask_user Tool (dispatcher → human) ──
951
+ //
952
+ // We do NOT register `ask_user` here. The recommended companion package
953
+ // `pi-ask-user` (see docs/pi-setup.md) owns that tool name with a richer
954
+ // implementation. Registering our own conflicts regardless of load order:
955
+ // - if we register first, pi-ask-user fails to load
956
+ // - if pi-ask-user registers first, our registration fails
957
+ // and pi has no synchronous probe at load time — `pi.getAllTools()` is
958
+ // a runtime action method that throws when called from the factory.
959
+ //
960
+ // Instead, in `session_start` (where action methods ARE allowed) we check
961
+ // `pi.getAllTools()`, gate `ask_user` into `setActiveTools` only if present,
962
+ // and warn the user to `pi install npm:pi-ask-user` if it's missing.
963
+
964
+
965
+ // ── Commands ─────────────────────────────────
966
+
967
+ const commandCtx: CommandContext = {
968
+ setWidgetContext: ctx => { widgetCtx = ctx; },
969
+ applyWorkModeSelection,
970
+ getWorkModeStatusText: workModeStatusText,
971
+ openWorkModePicker,
972
+ handleBudgetContinue: async ctx => { await budgetRecovery.resume(ctx); },
973
+ handleRetry: async (args, ctx) => {
974
+ const dispatchId = args?.trim();
975
+ if (!dispatchId || !noProgress.authorize(dispatchId)) { ctx.ui.notify("Unknown, stale or already authorized failure. Use /af-retry <dispatchId> from the no-progress refusal.", "error"); return; }
976
+ pi.appendEntry("agent-hub-retry-authorized", { dispatchId, identity: hubAuditIdentity(ctx) });
977
+ ctx.ui.notify(`One retry authorized for ${dispatchId}. Budget and safety gates still apply; no operation was dispatched.`, "info");
978
+ },
979
+ handleAgentsTeam: async (_args, ctx) => {
980
+ widgetCtx = ctx;
981
+ const teamNames = Object.keys(teams);
982
+ if (teamNames.length === 0) {
983
+ ctx.ui.notify("No teams defined in .pi/agents/teams.yaml", "warning");
984
+ return;
985
+ }
986
+
987
+ const options = teamNames.map(name => {
988
+ const members = teams[name].map(m => displayName(m));
989
+ return `${name} — ${members.join(", ")}`;
990
+ });
991
+
992
+ const choice = await ctx.ui.select("Select Team", options);
993
+ if (choice === undefined) return;
994
+
995
+ const idx = options.indexOf(choice);
996
+ const name = teamNames[idx];
997
+ const selected = resolveSessionRoster({
998
+ teams,
999
+ entries: [],
1000
+ explicitRoster: name,
1001
+ availablePersonas: allAgentDefs.map(def => def.name),
1002
+ });
1003
+ if (!selected.roster) {
1004
+ ctx.ui.notify(`${selected.diagnostic} Fix .pi/agents/teams.yaml or select another team.`, "error");
1005
+ return;
1006
+ }
1007
+ activateTeam(selected.roster.name);
1008
+ workModePolicy.clearRosterRecovery();
1009
+ persistActiveRoster();
1010
+ resolveIncomingCapabilities("");
1011
+ applyWorkModeTools();
1012
+ setTimeout(replayDeferredRecoveryInputs, 0);
1013
+ updateWidget();
1014
+ ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
1015
+ ctx.ui.notify(`Team: ${name} — ${Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ")}`, "info");
1016
+ },
1017
+ handleAgentsList: async (_args, _ctx) => {
1018
+ widgetCtx = _ctx;
1019
+ await openFleetDashboard(_ctx);
1020
+ },
1021
+ handleAgentsHistory: async (_args, ctx) => {
1022
+ widgetCtx = ctx;
1023
+ await openHistory(ctx, executionHistory, () => (activeTeamName ? `Team: ${activeTeamName}` : "Agent Hub"));
1024
+ },
1025
+ handleAgentsAdd: async (args, ctx) => {
1026
+ widgetCtx = ctx;
1027
+ const names = (args || "").trim().split(/\s+/).filter(Boolean);
1028
+ if (names.length === 0) {
1029
+ const available = allAgentDefs
1030
+ .filter(d => !agentStates.has(d.name.toLowerCase()))
1031
+ .map(d => d.name).sort().join(", ") || "(all personas are already in the team)";
1032
+ ctx.ui.notify(`Usage: /af-agents-add <persona> [<persona>…]\nNot in the team yet: ${available}`, "info");
1033
+ return;
1034
+ }
1035
+ const results = names.map(n => rosterAdd(n));
1036
+ const level = results.some(r => r.ok) ? "success" : "error";
1037
+ ctx.ui.notify(results.map(r => r.message).join("\n"), level as any);
1038
+ ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"}* (${agentStates.size})`);
1039
+ },
1040
+ handleAgentsDrop: async (args, ctx) => {
1041
+ widgetCtx = ctx;
1042
+ const names = (args || "").trim().split(/\s+/).filter(Boolean);
1043
+ if (names.length === 0) {
1044
+ ctx.ui.notify(`Usage: /af-agents-drop <persona> [<persona>…]\nActive team: ${Array.from(agentStates.values()).map(s => s.def.name).join(", ")}`, "info");
1045
+ return;
1046
+ }
1047
+ const results = names.map(n => rosterDrop(n));
1048
+ const level = results.some(r => r.ok) ? "success" : "error";
1049
+ ctx.ui.notify(results.map(r => r.message).join("\n"), level as any);
1050
+ ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"}* (${agentStates.size})`);
1051
+ },
1052
+ handleAgentsSave: async (args, ctx) => {
1053
+ widgetCtx = ctx;
1054
+ const name = (args || "").trim();
1055
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) {
1056
+ ctx.ui.notify("Usage: /af-agents-save <team-name> (letters, digits, hyphens, underscores)", "error");
1057
+ return;
1058
+ }
1059
+ const members = Array.from(agentStates.values()).map(s => s.def.name);
1060
+ if (members.length === 0) {
1061
+ ctx.ui.notify("The active team is empty — nothing to save.", "error");
1062
+ return;
1063
+ }
1064
+ const teamsPath = join(ctx.cwd || process.cwd(), ".pi", "agents", "teams.yaml");
1065
+ let raw = "";
1066
+ try { raw = existsSync(teamsPath) ? readFileSync(teamsPath, "utf-8") : ""; } catch {}
1067
+ try {
1068
+ mkdirSync(join(ctx.cwd || process.cwd(), ".pi", "agents"), { recursive: true });
1069
+ writeFileSync(teamsPath, upsertTeamInYaml(raw, name, members), "utf-8");
1070
+ } catch (err) {
1071
+ ctx.ui.notify(`Could not write ${teamsPath}: ${err instanceof Error ? err.message : String(err)}`, "error");
1072
+ return;
1073
+ }
1074
+ teams[name] = members;
1075
+ activeTeamName = name;
1076
+ persistActiveRoster();
1077
+ ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
1078
+ ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "success");
1079
+ },
1080
+ handleAgentsKill: async (args, ctx) => { widgetCtx = ctx; await researchControls.handleKill(args, ctx); },
1081
+ handleAgentsRestart: async (args, ctx) => { widgetCtx = ctx; await researchControls.handleRestart(args, ctx); },
1082
+ handleContext: async (_args, ctx) => {
1083
+ widgetCtx = ctx;
1084
+ await openContextBudget(ctx);
1085
+ },
1086
+ handleHubReport: async (_args, ctx) => {
1087
+ widgetCtx = ctx;
1088
+ const fmtTok = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
1089
+ const renderReport = (label: string, r: TurnReport): string => {
1090
+ const billed = r.dispatches.reduce((n, d) => n + d.billed, 0);
1091
+ const out = r.dispatches.reduce((n, d) => n + d.out, 0);
1092
+ const rows = r.dispatches.map(d => ` ${d.agent}: ${d.status} in ${Math.round(d.elapsed / 1000)}s · ${fmtTok(d.billed)} billed / ${fmtTok(d.out)} out`);
1093
+ return [
1094
+ `${label} — tier ${r.tier ?? "(unset)"} · ${r.dispatches.length} dispatch(es) · ${r.research} research · ` +
1095
+ `${fmtTok(billed)} billed / ${fmtTok(out)} out · ${r.recycles} recycle(s) · ${r.driftStops} drift stop(s) · ${r.refusals} refusal(s)`,
1096
+ ...rows,
1097
+ ].join("\n");
1098
+ };
1099
+ const lines: string[] = [];
1100
+ if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) {
1101
+ lines.push(renderReport("Current turn", turnReport));
1102
+ }
1103
+ if (lastTurnReport) lines.push(renderReport("Last turn", lastTurnReport));
1104
+ lines.push(
1105
+ `Session — ${sessionTotals.turns} dispatching turn(s) · ${sessionTotals.dispatches} dispatch(es) · ${sessionTotals.research} research · ` +
1106
+ `${fmtTok(sessionTotals.billed)} billed / ${fmtTok(sessionTotals.out)} out · ${sessionTotals.recycles} recycle(s) · ` +
1107
+ `${sessionTotals.driftStops} drift stop(s) · ${sessionTotals.refusals} refusal(s)`,
1108
+ );
1109
+ const sweep = unaddressedPeerSweep(Array.from(hubSpawnedPeers.values()));
1110
+ if (sweep) lines.push(sweep.message);
1111
+ ctx.ui.notify(lines.join("\n\n"), "info");
1112
+ },
1113
+ handleZoom: async (args, ctx) => {
1114
+ widgetCtx = ctx;
1115
+ const arg = args?.trim() || "";
1116
+ const rid = parseResearchHandle(arg);
1117
+ const target: Zoomable | undefined = rid != null
1118
+ ? researchStates.get(rid)
1119
+ : arg
1120
+ ? agentStates.get(arg.toLowerCase()) ?? findDelegationChild(arg)?.child
1121
+ : undefined;
1122
+ if (!target) {
1123
+ const teamKnown = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
1124
+ const researchKnown = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
1125
+ const childKnown = Array.from(agentStates.values())
1126
+ .flatMap(s => Array.from(s.delegations?.keys() || [])).join(", ");
1127
+ const known = [teamKnown, researchKnown, childKnown].filter(Boolean).join(", ");
1128
+ ctx.ui.notify(`Usage: /af-zoom <name|rN|child-id>. Known: ${known || "none"}`, "error");
1129
+ return;
1130
+ }
1131
+ const rowKey = (rid != null ? `r${rid}` : arg).toLowerCase();
1132
+ const row = fleetRows(true).find(r => r.key.toLowerCase() === rowKey);
1133
+ if (row) await openFleetDetail(row, ctx);
1134
+ else await openZoom(target, ctx);
1135
+ },
1136
+ handleDispatchPolicy: async (_args, ctx) => {
1137
+ widgetCtx = ctx;
1138
+ const live = new Set(comsReady && identity ? peersInScope().map(e => e.name.toLowerCase()) : []);
1139
+ const lines = Array.from(agentStates.values()).map(s => {
1140
+ const key = s.def.name.toLowerCase();
1141
+ const sub = dispatchPolicy.substitutions[key];
1142
+ const prefer = sub ? sub.prefer : dispatchPolicy.default === "coms" ? "coms" : "native";
1143
+ if (prefer !== "coms") return `${displayName(s.def.name)}: native`;
1144
+ const fb = sub?.fallback === "none" ? "coms-required" : "coms, fallback native";
1145
+ return `${displayName(s.def.name)}: ${fb} — peer ${live.has(key) ? "LIVE" : "not in pool"}`;
1146
+ });
1147
+ const policyPath = join(ctx.cwd || process.cwd(), ".pi", "agents", "dispatch-policy.yaml");
1148
+ const src = existsSync(policyPath) ? ".pi/agents/dispatch-policy.yaml" : "(no dispatch-policy.yaml — all native)";
1149
+ ctx.ui.notify(
1150
+ `Dispatch backends — ${src}, default: ${dispatchPolicy.default}\n${lines.join("\n") || "(no active team)"}\n` +
1151
+ `Routing is decided per dispatch against the live coms pool (/af-coms to refresh).`,
1152
+ "info",
1153
+ );
1154
+ },
1155
+ handleAgentModel: async (args, ctx) => {
1156
+ widgetCtx = ctx;
1157
+ const arg = (args || "").trim().toLowerCase();
1158
+
1159
+ // Dot form: <persona>.<role> targets a delegate sub-role. Candidates are
1160
+ // the role's declared model (default) + the parent's candidate list.
1161
+ if (arg.includes(".")) {
1162
+ const dot = arg.indexOf(".");
1163
+ const personaName = arg.slice(0, dot);
1164
+ const roleName = arg.slice(dot + 1);
1165
+ const parent = agentStates.get(personaName);
1166
+ const roles = parent?.def.subagents || {};
1167
+ const roleKey = Object.keys(roles).find(r => r.toLowerCase() === roleName);
1168
+ if (!parent || !roleKey) {
1169
+ const valid = Array.from(agentStates.values()).flatMap(s =>
1170
+ Object.keys(s.def.subagents || {}).map(r => `${s.def.name}.${r}`));
1171
+ ctx.ui.notify(
1172
+ `No sub-role "${arg}". Valid targets: ${valid.join(", ") || "none (no persona declares subagents:)"}`,
1173
+ "error",
1174
+ );
1175
+ return;
1176
+ }
1177
+ const role = roles[roleKey];
1178
+ const overrideKey = `${personaName}.${roleKey.toLowerCase()}`;
1179
+ const candidates: string[] = [];
1180
+ for (const m of [role.model, ...allowedModels(parent.def)]) {
1181
+ if (m && !candidates.includes(m)) candidates.push(m);
1182
+ }
1183
+ const current = resolvedSubagentModel(parent.def.name, roleKey, role.model);
1184
+ const options = candidates.map(m => {
1185
+ const tags = [m === role.model ? "default" : "", m === current ? "current" : ""].filter(Boolean);
1186
+ return tags.length ? `${m} (${tags.join(", ")})` : m;
1187
+ });
1188
+ const label = `${displayName(parent.def.name)}.${roleKey}`;
1189
+ const choice = await ctx.ui.select(`Model for ${label}`, options);
1190
+ if (choice === undefined) return;
1191
+ const picked = candidates[options.indexOf(choice)];
1192
+ const effectivePicked = substitutedModel(picked) ?? picked;
1193
+ if (effectivePicked === current) {
1194
+ ctx.ui.notify(`${label} is already on ${effectivePicked}`, "info");
1195
+ return;
1196
+ }
1197
+ if (picked === role.model) {
1198
+ modelPolicy.setSubagentOverride(personaName, roleKey, undefined);
1199
+ } else {
1200
+ modelPolicy.setSubagentOverride(personaName, roleKey, picked);
1201
+ }
1202
+ updateWidget();
1203
+ ctx.ui.notify(
1204
+ `${label} → ${effectivePicked} (applies on next dispatch of ${parent.def.name})`,
1205
+ "success",
1206
+ );
1207
+ return;
1208
+ }
1209
+
1210
+ const name = arg;
1211
+ // Team member (live state) OR a research persona — both switchable.
1212
+ const def = name ? switchablePersonaDef(name) : undefined;
1213
+ if (!def) {
1214
+ const known = [
1215
+ ...Array.from(agentStates.values()).map(s => s.def.name),
1216
+ ...researchPersonas.map(d => d.name),
1217
+ ].join(", ");
1218
+ ctx.ui.notify(`Usage: /af-agent-model <persona>[.<role>]. Known: ${known || "none"}`, "error");
1219
+ return;
1220
+ }
1221
+ if (!def.models || def.models.length === 0) {
1222
+ ctx.ui.notify(
1223
+ `${displayName(def.name)} declares no model candidates — add a \`models:\` list to ${def.file} or a \`models.${def.name}:\` override in .ai/agent-fleet-overrides.md.`,
1224
+ "warning",
1225
+ );
1226
+ return;
1227
+ }
1228
+ const candidates = allowedModels(def);
1229
+ const current = resolvedModel(def);
1230
+ // A persona without a frontmatter default runs on the dispatcher's model —
1231
+ // offer that as an explicit candidate so the override can be cleared.
1232
+ const DISPATCHER_DEFAULT = "(dispatcher's model)";
1233
+ if (!def.model) candidates.unshift(DISPATCHER_DEFAULT);
1234
+ const options = candidates.map(m => {
1235
+ const isDefault = def.model ? m === def.model : m === DISPATCHER_DEFAULT;
1236
+ const isCurrent = current ? m === current : m === DISPATCHER_DEFAULT;
1237
+ const tags = [isDefault ? "default" : "", isCurrent ? "current" : ""].filter(Boolean);
1238
+ return tags.length ? `${m} (${tags.join(", ")})` : m;
1239
+ });
1240
+ const choice = await ctx.ui.select(`Model for ${displayName(def.name)}`, options);
1241
+ if (choice === undefined) return;
1242
+ const picked = candidates[options.indexOf(choice)];
1243
+ const effectivePicked = picked === DISPATCHER_DEFAULT ? picked : (substitutedModel(picked) ?? picked);
1244
+ const pickedIsCurrent = current ? effectivePicked === current : picked === DISPATCHER_DEFAULT;
1245
+ if (pickedIsCurrent) {
1246
+ ctx.ui.notify(`${displayName(def.name)} is already on ${effectivePicked}`, "info");
1247
+ return;
1248
+ }
1249
+ if (picked === def.model || picked === DISPATCHER_DEFAULT) {
1250
+ modelPolicy.setPersonaOverride(name, undefined);
1251
+ } else {
1252
+ modelPolicy.setPersonaOverride(name, picked);
1253
+ }
1254
+ updateWidget();
1255
+ // Research helpers spawn fresh each time, so the switch lands on their
1256
+ // next spawn; team members apply on next dispatch (restartable now).
1257
+ const applyHint = (def.kind || "").toLowerCase() === "research"
1258
+ ? "applies on next spawn_research"
1259
+ : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
1260
+ ctx.ui.notify(`${displayName(def.name)} → ${effectivePicked} (${applyHint})`, "success");
1261
+ if ((dispatchPolicy.substitutions[name]?.prefer ?? dispatchPolicy.default) === "coms") {
1262
+ ctx.ui.notify(
1263
+ `Note: ${displayName(def.name)} prefers a coms peer (dispatch-policy.yaml) — this model override only applies to native(-fallback) runs; the peer keeps its own model.`,
1264
+ "info",
1265
+ );
1266
+ }
1267
+ },
1268
+ handleAgentModelThinking: async (args, ctx) => {
1269
+ widgetCtx = ctx;
1270
+ const name = (args || "").trim().toLowerCase();
1271
+ // Team member (live state) OR a research persona — both switchable.
1272
+ const def = name ? switchablePersonaDef(name) : undefined;
1273
+ if (!def) {
1274
+ const known = [
1275
+ ...Array.from(agentStates.values()).map(s => s.def.name),
1276
+ ...researchPersonas.map(d => d.name),
1277
+ ].join(", ");
1278
+ ctx.ui.notify(`Usage: /af-agent-model-thinking <persona>. Known: ${known || "none"}`, "error");
1279
+ return;
1280
+ }
1281
+ const defaultLevel = resolveThinkingLevel(def.thinking);
1282
+ const current = resolveThinkingLevel(resolvedThinking(def));
1283
+ const levels = [...THINKING_LEVELS];
1284
+ const options = levels.map(l => {
1285
+ const tags = [l === defaultLevel ? "default" : "", l === current ? "current" : ""].filter(Boolean);
1286
+ return tags.length ? `${l} (${tags.join(", ")})` : l;
1287
+ });
1288
+ const choice = await ctx.ui.select(`Thinking level for ${displayName(def.name)}`, options);
1289
+ if (choice === undefined) return;
1290
+ const picked = levels[options.indexOf(choice)];
1291
+ if (picked === current) {
1292
+ ctx.ui.notify(`${displayName(def.name)} is already on thinking: ${picked}`, "info");
1293
+ return;
1294
+ }
1295
+ if (picked === defaultLevel) {
1296
+ modelPolicy.setThinkingOverride(name, undefined);
1297
+ } else {
1298
+ modelPolicy.setThinkingOverride(name, picked);
1299
+ }
1300
+ updateWidget();
1301
+ // Research helpers spawn fresh each time, so the switch lands on their
1302
+ // next spawn; team members apply on next dispatch (restartable now).
1303
+ const applyHint = (def.kind || "").toLowerCase() === "research"
1304
+ ? "applies on next spawn_research"
1305
+ : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
1306
+ ctx.ui.notify(`${displayName(def.name)} thinking → ${picked} (${applyHint})`, "success");
1307
+ },
1308
+ handleModels: async (args, ctx) => {
1309
+ widgetCtx = ctx;
1310
+ const names = Object.keys(modelProfiles);
1311
+ if (names.length === 0) {
1312
+ ctx.ui.notify("No model profiles loaded — define .pi/agents/model-profiles.yaml (invalid profiles are dropped at session start).", "warning");
1313
+ return;
1314
+ }
1315
+ let profileName = (args || "").trim();
1316
+ if (!profileName) {
1317
+ const options = names.map(n =>
1318
+ isCompleteProfile(modelProfiles[n])
1319
+ ? `${n} — complete fleet (${shortModel((modelProfiles[n] as any).defaults.model)} default)`
1320
+ : `${n} — ${Object.entries(modelProfiles[n]).map(([p, m]) => `${p}: ${shortModel(m)}`).join(", ")}`,
1321
+ );
1322
+ const choice = await ctx.ui.select("Select model profile", options);
1323
+ if (choice === undefined) return;
1324
+ profileName = names[options.indexOf(choice)];
1325
+ }
1326
+ const profile = modelProfiles[profileName];
1327
+ if (!profile) {
1328
+ ctx.ui.notify(`No profile "${profileName}". Known: ${names.join(", ")}`, "error");
1329
+ return;
1330
+ }
1331
+ profileCommandContext=ctx;
1332
+ try {
1333
+ const applied=await profileActivation.activate(profileName,profile);
1334
+ ctx.ui.setStatus('hub-model-profile',isCompleteProfile(profile)?`Models: ${profileName}`:undefined);
1335
+ ctx.ui.notify(`Profile "${profileName}": ${applied.length} personas${isCompleteProfile(profile)?', all children, dispatcher and auxiliary models':''} switched.`, 'success');
1336
+ } catch(error) {ctx.ui.notify(String(error),'error');}
1337
+ },
1338
+ handleAgentModelsSubstitute: async (args, ctx) => {
1339
+ widgetCtx = ctx;
1340
+ const tokens = (args || "").trim().split(/\s+/).filter(Boolean);
1341
+ if (tokens.length === 0) {
1342
+ if (allKnownModels().length === 0) {
1343
+ ctx.ui.notify("No configured persona or sub-role models are available as substitution sources.", "warning");
1344
+ return;
1345
+ }
1346
+ await openFleetDashboard(ctx, true);
1347
+ return;
1348
+ }
1349
+ if (tokens.length !== 2) {
1350
+ ctx.ui.notify("Usage: /af-agent-models-substitute [<source> <target>]", "error");
1351
+ return;
1352
+ }
1353
+ await applySessionModelSubstitution(tokens[0], tokens[1], ctx);
1354
+ },
1355
+ handleWatchdog: async (args, ctx) => {
1356
+ widgetCtx = ctx;
1357
+ const parts = (args || "").trim().split(/\s+/).filter(Boolean);
1358
+ if (parts.length === 0) {
1359
+ const perAgent = watchdogAgentOverrides.size > 0
1360
+ ? Array.from(watchdogAgentOverrides.entries()).map(([k, v]) => `${k}: ${v}`).join(", ")
1361
+ : "(none)";
1362
+ ctx.ui.notify(
1363
+ `Drift watchdog: ${watchdogSetting} (hub-wide)\nPer-agent overrides: ${perAgent}\n` +
1364
+ `Judge model: ${watchdogJudgeModel || "(researcher persona's, else dispatcher's)"}\n` +
1365
+ `Usage: /af-watchdog on|off|auto — or /af-watchdog <agent> on|off|clear`,
1366
+ "info",
1367
+ );
1368
+ return;
1369
+ }
1370
+ if (parts.length === 1) {
1371
+ const setting = normalizeWatchdogSetting(parts[0]);
1372
+ if (!setting) {
1373
+ ctx.ui.notify(`Unknown setting "${parts[0]}" — expected one of: ${WATCHDOG_SETTINGS.join(", ")} (or /af-watchdog <agent> on|off|clear)`, "error");
1374
+ return;
1375
+ }
1376
+ watchdogSetting = setting;
1377
+ ctx.ui.notify(`Drift watchdog → ${setting} (applies from the next dispatch)`, "success");
1378
+ return;
1379
+ }
1380
+ const agentKey = normalizeAgentInput(parts[0]);
1381
+ const value = parts[1].toLowerCase();
1382
+ if (!agentStates.has(agentKey)) {
1383
+ ctx.ui.notify(`"${parts[0]}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ")})`, "error");
1384
+ return;
1385
+ }
1386
+ if (value === "clear") {
1387
+ watchdogAgentOverrides.delete(agentKey);
1388
+ ctx.ui.notify(`Drift watchdog override cleared for ${agentKey} (hub-wide setting "${watchdogSetting}" applies)`, "success");
1389
+ return;
1390
+ }
1391
+ if (value !== "on" && value !== "off") {
1392
+ ctx.ui.notify(`Per-agent watchdog must be on, off, or clear — got "${parts[1]}"`, "error");
1393
+ return;
1394
+ }
1395
+ watchdogAgentOverrides.set(agentKey, value);
1396
+ ctx.ui.notify(`Drift watchdog for ${agentKey} → ${value} (overrides the hub-wide "${watchdogSetting}")`, "success");
1397
+ },
1398
+ handleComs: async (args, ctx) => {
1399
+ if (!comsReady) { ctx.ui.notify("coms is not active in this session.", "warning"); return; }
1400
+ await coms.updateScope((args ?? "").trim(), ctx);
1401
+ },
1402
+ handleHandoff: async (args, ctx) => {
1403
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1404
+ if (!comsReady) { ctx.ui.notify("coms is not active in this session — /af-handoff unavailable.", "warning"); return; }
1405
+ const target = (args ?? "").trim();
1406
+ if (!target) {
1407
+ ctx.ui.notify("Usage: /af-handoff <peer>. See the coms pool for live peer names.", "error");
1408
+ return;
1409
+ }
1410
+ const peer = resolveTarget(target);
1411
+ if (!peer) {
1412
+ ctx.ui.notify(`coms: no live peer "${target}". Use /af-coms to refresh the pool.`, "error");
1413
+ return;
1414
+ }
1415
+ const refusal=profilePeerGate({ peerModel: peer.model, targetResolved: true });if(refusal){ctx.ui.notify(refusal.content[0].text,"error");return;}
1416
+ const handoffToken = crypto.randomBytes(8).toString("hex");
1417
+ hubStateCtx.setPendingHandoff({ target: peer.name, token: handoffToken });
1418
+ pi.sendMessage({
1419
+ customType: "coms-handoff",
1420
+ content:
1421
+ `HANDOFF REQUEST → peer "${peer.name}".\n\n` +
1422
+ `Compose a SELF-CONTAINED handoff brief (the peer does NOT share your context): state the ` +
1423
+ `overall goal, what's been done so far, key decisions and constraints, the current status, ` +
1424
+ `and the concrete next steps you want the peer to take. Then call ` +
1425
+ `coms_send(target: "${peer.name}", handoff_token: "${handoffToken}", prompt: <the brief only; the hub appends the verification ledger and artifact index in code only when this token matches>), coms_await its msg_id, and relay ` +
1426
+ `the peer's reply to me in ${userLanguage}.`,
1427
+ display: true,
1428
+ }, { deliverAs: "followUp", triggerTurn: true });
1429
+ ctx.ui.notify(`Handoff to ${peer.name}: asking the dispatcher to compose a brief…`, "info");
1430
+ },
1431
+ handleCompound: async (args, ctx) => {
1432
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1433
+ if (!agentStates.has("documenter")) {
1434
+ ctx.ui.notify(
1435
+ "compound: the documenter persona is not in the active team — switch with /af-agents-team (e.g. default or release), then re-run /af-compound.",
1436
+ "warning",
1437
+ );
1438
+ return;
1439
+ }
1440
+ const focus = (args ?? "").trim();
1441
+ const rulesLine = projectRulesDirs.length > 0
1442
+ ? projectRulesDirs.join(", ")
1443
+ : "(none declared in .ai/agent-fleet-overrides.md — the documenter must locate an existing rules tree or, failing that, propose lessons without writing)";
1444
+ const docsLine = projectDocsPaths.length > 0
1445
+ ? projectDocsPaths.join(", ")
1446
+ : "(none declared)";
1447
+ pi.sendMessage({
1448
+ customType: "compound-learning",
1449
+ content:
1450
+ `COMPOUND REQUEST — capture this session's lessons into the project's rules and docs (compound-learning pass).\n\n` +
1451
+ `1. From THIS session's context, compose a candidate-lessons brief: user corrections, review findings that recurred, ` +
1452
+ `wrong assumptions that cost rework, debugging root causes, and changes that invalidated existing docs. At most 5 lessons; ` +
1453
+ `each is one imperative sentence plus a one-line Why (the failure it prevents) and a one-line Evidence (what happened this session). ` +
1454
+ `${focus ? `Focus especially on: ${focus}. ` : ""}` +
1455
+ `If nothing rises to a lesson, tell the user there is nothing worth compounding and stop.\n` +
1456
+ `2. Confirm the list with the user in ${userLanguage} (ask_user when available) — they approve, trim, or reword. Do not dispatch before this confirmation.\n` +
1457
+ `3. Dispatch the documenter with a SELF-CONTAINED task (it shares none of your context) containing: the approved lessons verbatim ` +
1458
+ `(with Why + Evidence); the project rule folders: ${rulesLine}; the docs entry points: ${docsLine}; the assertion ledger path ` +
1459
+ `.pi/agent-sessions/assertions.json (when it exists); and the instruction to read skills/compound-learning/SKILL.md and follow it exactly — ` +
1460
+ `dedupe index-first against the existing rule tree, minimal diffs on existing files, caps of 5 lessons / 1 new file. State that the user ` +
1461
+ `already approved this lesson list, so it may apply without a second gate. Pass the relevant review/return/evidence artifact paths via the ` +
1462
+ `dispatch's artifacts array — paths only, never pasted bodies.\n` +
1463
+ `4. Relay the documenter's file-by-file result to me in ${userLanguage}.`,
1464
+ display: true,
1465
+ }, { deliverAs: "followUp", triggerTurn: true });
1466
+ ctx.ui.notify("Compound: asking the dispatcher to compose the candidate-lessons brief…", "info");
1467
+ },
1468
+ handlePoll: async (args, ctx) => {
1469
+ return withProfileWork(async () => {
1470
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1471
+ const cwd = ctx.cwd || process.cwd();
1472
+ const result = await handleAfPoll({
1473
+ args: args ?? "",
1474
+ cwd,
1475
+ pollPanelOverride: readActiveProfile()?.name ?? parseAgentTeamOverrides(cwd).pollPanel,
1476
+ listPanels: async dir => {
1477
+ const { listPanelNames } = await import("../../../scripts/workflows/lib/voices.ts");
1478
+ return listPanelNames(dir);
1479
+ },
1480
+ preflight: async ({ panel, persona, cwd: root }) => {
1481
+ const [{ resolvePersona }, { resolvePanel }, { checkChildVisibility }] = await Promise.all([
1482
+ import("../../../scripts/workflows/lib/personas.ts"),
1483
+ import("../../../scripts/workflows/lib/voices.ts"),
1484
+ import("../../../scripts/workflows/lib/model-visibility.ts"),
1485
+ ]);
1486
+ try { resolvePersona(persona, root); }
1487
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1488
+ let voices;
1489
+ try { voices = resolvePanel(panel, root); }
1490
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1491
+ const report = checkChildVisibility(voices.map(voice => voice.model));
1492
+ if (report.diagnostic) return `could not verify clean-room model visibility (${report.diagnostic})`;
1493
+ const hidden = report.models.filter(model => !model.ok);
1494
+ if (hidden.length) {
1495
+ return `panel "${panel}" has models not visible to a clean-room child: ${hidden.map(model => model.reasons[0] ?? model.model).join("; ")}`;
1496
+ }
1497
+ return null;
1498
+ },
1499
+ checkBudget: async () => {
1500
+ ensureTaskTier();
1501
+ const blocked = await budgetRecovery.ensure("dispatch", args ?? "model panel", ctx);
1502
+ return blocked?.message ?? null;
1503
+ },
1504
+ chargeBudget: () => {
1505
+ turnDispatchCount += 1;
1506
+ taskDispatchCount += 1;
1507
+ sessionTotals.dispatches += 1;
1508
+ updateModeStatus();
1509
+ },
1510
+ onAccepted: async ({ panel, persona, question }) => {
1511
+ let voices: { name: string; model: string }[] = [];
1512
+ try {
1513
+ const { resolvePanel } = await import("../../../scripts/workflows/lib/voices.ts");
1514
+ voices = resolvePanel(panel, cwd).map(voice => ({ name: voice.name, model: voice.model }));
1515
+ } catch { /* names are decorative */ }
1516
+ const started = formatAfPollStarted({ panel, persona, question, voices });
1517
+ ctx.ui.setStatus("hub-poll", `Poll: ${panel} (${voices.length || "?"} voices) running…`);
1518
+ ctx.ui.notify(`Poll started — panel ${panel}. This can take a minute.`, "info");
1519
+ pi.sendMessage({ customType: "af-poll-started", content: started, display: true }, { deliverAs: "followUp", triggerTurn: false });
1520
+ },
1521
+ execute: async ({ panel, persona, question }) => {
1522
+ const [{ Run }, { runPoll }, { runMerge }, { resolvePersona }] = await Promise.all([
1523
+ import("../../../scripts/workflows/lib/run.ts"),
1524
+ import("../../../scripts/workflows/lib/poll.ts"),
1525
+ import("../../../scripts/workflows/lib/merge.ts"),
1526
+ import("../../../scripts/workflows/lib/personas.ts"),
1527
+ ]);
1528
+ const run = new Run({ cwd, command: ["/af-poll", "--panel", panel, question] });
1529
+ const personaDef = resolvePersona(persona, cwd);
1530
+ const poll = await runPoll({
1531
+ run, cwd, persona: personaDef, panel, task: question,
1532
+ onVoice: result => {
1533
+ const voice = result.ok
1534
+ ? { name: result.voice.name, model: result.voice.model, ok: true as const, position: result.report.position, confidence: result.report.confidence }
1535
+ : { name: result.voice.name, model: result.voice.model, ok: false as const, reason: result.reason };
1536
+ pi.sendMessage({ customType: "af-poll-voice", content: formatAfPollVoiceProgress(voice), display: true }, { deliverAs: "followUp", triggerTurn: false });
1537
+ },
1538
+ });
1539
+ ctx.ui.setStatus("hub-poll", `Poll: ${panel} merging…`);
1540
+ const merge = await runMerge({ run, cwd, persona: personaDef, panel, task: question, opinions: poll.results });
1541
+ const directory = path.relative(cwd, poll.directory) || poll.directory;
1542
+ return {
1543
+ panel,
1544
+ directory: directory.endsWith(path.sep) ? directory : `${directory}${path.sep}`,
1545
+ voices: poll.results.map(item => item.ok
1546
+ ? { name: item.voice.name, model: item.voice.model, ok: true as const, position: item.report.position, confidence: item.report.confidence }
1547
+ : { name: item.voice.name, model: item.voice.model, ok: false as const, reason: item.reason }),
1548
+ recommendation: merge.report.recommendation,
1549
+ integrator: merge.integrator.name,
1550
+ };
1551
+ },
1552
+ });
1553
+ ctx.ui.setStatus("hub-poll", "");
1554
+ if (!result.ok) {
1555
+ ctx.ui.notify(result.message, "error");
1556
+ pi.sendMessage({ customType: "af-poll-failed", content: `POLL FAILED\n\n${result.message}`, display: true }, { deliverAs: "followUp", triggerTurn: false });
1557
+ return;
1558
+ }
1559
+ ctx.ui.notify(result.digest ?? result.message, "info");
1560
+ pi.sendMessage({
1561
+ customType: "af-poll",
1562
+ content: result.dispatcherNote ?? result.message,
1563
+ display: true,
1564
+ }, { deliverAs: "followUp", triggerTurn: true });
1565
+ });
1566
+ },
1567
+ handleDebate: async (args, ctx) => {
1568
+ return withProfileWork(async () => {
1569
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1570
+ const cwd = ctx.cwd || process.cwd();
1571
+ const result = await handleAfDebate({
1572
+ args: args ?? "",
1573
+ cwd,
1574
+ pollPanelOverride: readActiveProfile()?.name ?? parseAgentTeamOverrides(cwd).pollPanel,
1575
+ listPanels: async dir => {
1576
+ const { listPanelNames } = await import("../../../scripts/workflows/lib/voices.ts");
1577
+ return listPanelNames(dir);
1578
+ },
1579
+ preflight: async ({ panel, persona, cwd: root }) => {
1580
+ const [{ resolvePersona }, { resolvePanel }, { checkChildVisibility }] = await Promise.all([
1581
+ import("../../../scripts/workflows/lib/personas.ts"),
1582
+ import("../../../scripts/workflows/lib/voices.ts"),
1583
+ import("../../../scripts/workflows/lib/model-visibility.ts"),
1584
+ ]);
1585
+ try { resolvePersona(persona, root); }
1586
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1587
+ let voices;
1588
+ try { voices = resolvePanel(panel, root); }
1589
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1590
+ const report = checkChildVisibility(voices.map(voice => voice.model));
1591
+ if (report.diagnostic) return `could not verify clean-room model visibility (${report.diagnostic})`;
1592
+ const hidden = report.models.filter(model => !model.ok);
1593
+ if (hidden.length) {
1594
+ return `panel "${panel}" has models not visible to a clean-room child: ${hidden.map(model => model.reasons[0] ?? model.model).join("; ")}`;
1595
+ }
1596
+ return null;
1597
+ },
1598
+ checkBudget: async () => {
1599
+ ensureTaskTier();
1600
+ const blocked = await budgetRecovery.ensure("dispatch", args ?? "model panel", ctx);
1601
+ return blocked?.message ?? null;
1602
+ },
1603
+ chargeBudget: () => {
1604
+ turnDispatchCount += 1;
1605
+ taskDispatchCount += 1;
1606
+ sessionTotals.dispatches += 1;
1607
+ updateModeStatus();
1608
+ },
1609
+ onAccepted: async ({ panel, persona, question, rounds }) => {
1610
+ let voices: { name: string; model: string }[] = [];
1611
+ try {
1612
+ const { resolvePanel } = await import("../../../scripts/workflows/lib/voices.ts");
1613
+ voices = resolvePanel(panel, cwd).map(voice => ({ name: voice.name, model: voice.model }));
1614
+ } catch { /* names are decorative */ }
1615
+ const started = formatAfDebateStarted({ panel, persona, question, rounds, voices });
1616
+ ctx.ui.setStatus("hub-poll", `Debate: ${panel} (${rounds} rounds) running…`);
1617
+ ctx.ui.notify(`Debate started — panel ${panel}, ${rounds} rounds.`, "info");
1618
+ pi.sendMessage({ customType: "af-debate-started", content: started, display: true }, { deliverAs: "followUp", triggerTurn: false });
1619
+ },
1620
+ execute: async ({ panel, persona, question, rounds }) => {
1621
+ const [{ Run }, { runDebate }, { resolvePersona }] = await Promise.all([
1622
+ import("../../../scripts/workflows/lib/run.ts"),
1623
+ import("../../../scripts/workflows/lib/debate.ts"),
1624
+ import("../../../scripts/workflows/lib/personas.ts"),
1625
+ ]);
1626
+ const run = new Run({ cwd, command: ["/af-debate", "--panel", panel, "--rounds", String(rounds), question] });
1627
+ const personaDef = resolvePersona(persona, cwd);
1628
+ const debate = await runDebate({
1629
+ run, cwd, persona: personaDef, panel, task: question, rounds,
1630
+ onVoice: (result, round) => {
1631
+ const voice = result.ok
1632
+ ? { name: result.voice.name, model: result.voice.model, ok: true as const, round, position: result.report.position, changed: result.report.changed }
1633
+ : { name: result.voice.name, model: result.voice.model, ok: false as const, round, reason: result.reason };
1634
+ ctx.ui.setStatus("hub-poll", `Debate: ${panel} round ${round}…`);
1635
+ pi.sendMessage({ customType: "af-debate-voice", content: formatAfDebateVoiceProgress(voice), display: true }, { deliverAs: "followUp", triggerTurn: false });
1636
+ },
1637
+ });
1638
+ const last = debate.roundsRun.at(-1)?.results ?? [];
1639
+ const directory = path.relative(cwd, debate.directory) || debate.directory;
1640
+ return {
1641
+ panel, rounds: debate.rounds,
1642
+ directory: directory.endsWith(path.sep) ? directory : `${directory}${path.sep}`,
1643
+ voices: last.map(item => item.ok
1644
+ ? { name: item.voice.name, model: item.voice.model, ok: true as const, round: item.round, position: item.report.position, changed: item.report.changed }
1645
+ : { name: item.voice.name, model: item.voice.model, ok: false as const, round: item.round, reason: item.reason }),
1646
+ };
1647
+ },
1648
+ });
1649
+ ctx.ui.setStatus("hub-poll", "");
1650
+ if (!result.ok) {
1651
+ ctx.ui.notify(result.message, "error");
1652
+ pi.sendMessage({ customType: "af-debate-failed", content: `DEBATE FAILED\n\n${result.message}`, display: true }, { deliverAs: "followUp", triggerTurn: false });
1653
+ return;
1654
+ }
1655
+ ctx.ui.notify(result.digest ?? result.message, "info");
1656
+ pi.sendMessage({
1657
+ customType: "af-debate",
1658
+ content: result.dispatcherNote ?? result.message,
1659
+ display: true,
1660
+ }, { deliverAs: "followUp", triggerTurn: true });
1661
+ });
1662
+ },
1663
+ getAgentsKillCompletions: prefix => completions.agentsKill(prefix),
1664
+ getZoomCompletions: prefix => completions.zoom(prefix),
1665
+ getAgentModelCompletions: prefix => completions.agentModels(prefix),
1666
+ getAgentModelThinkingCompletions: prefix => completions.agentThinking(prefix),
1667
+ getModelProfileCompletions: prefix => completions.modelProfiles(prefix),
1668
+ getSubstituteCompletions: prefix => completions.substitutions(prefix),
1669
+ getComsPeerCompletions: prefix => completions.comsPeers(prefix),
1670
+ getSubagentTargetCompletions: prefix => completions.subagentTargets(prefix),
1671
+ };
1672
+
1673
+ // Keep the complete command surface flat and greppable in this composition root.
1674
+ registerAgentsTeam(pi, commandCtx);
1675
+ registerAgentsList(pi, commandCtx);
1676
+ registerAgentsHistory(pi, commandCtx);
1677
+ registerContextCommand(pi, commandCtx);
1678
+ registerWorkMode(pi, commandCtx);
1679
+ registerWatchdog(pi, commandCtx);
1680
+ registerAgentsAdd(pi, commandCtx);
1681
+ registerAgentsDrop(pi, commandCtx);
1682
+ registerAgentsSave(pi, commandCtx);
1683
+ registerHubReport(pi, commandCtx);
1684
+ registerZoom(pi, commandCtx);
1685
+ registerAgentModel(pi, commandCtx);
1686
+ registerAgentModelThinking(pi, commandCtx);
1687
+ registerModels(pi, commandCtx);
1688
+ registerAgentModelsSubstitute(pi, commandCtx);
1689
+ registerDispatchPolicy(pi, commandCtx);
1690
+ registerAgentsKill(pi, commandCtx);
1691
+ registerAgentsRestart(pi, commandCtx);
1692
+ registerComs(pi, commandCtx);
1693
+ registerHandoff(pi, commandCtx);
1694
+ registerCompound(pi, commandCtx);
1695
+ registerPoll(pi, commandCtx);
1696
+ registerBudgetContinue(pi, commandCtx);
1697
+ registerRetry(pi, commandCtx);
1698
+ registerDebate(pi, commandCtx);
1699
+
1700
+ const detailPanel = createDetailPanel<AgentDef, AgentState, ResearchState>({
1701
+ getAgent: key => agentStates.get(key),
1702
+ getResearch: id => researchStates.get(id),
1703
+ parseResearchHandle,
1704
+ findDelegationChild,
1705
+ modelPolicy,
1706
+ displayName,
1707
+ shortModel,
1708
+ refreshUi: updateWidget,
1709
+ getDispatchPreference: name => dispatchPolicy.substitutions[name.toLowerCase()]?.prefer ?? dispatchPolicy.default,
1710
+ maxLiveEntryChars: MAX_LIVE_ENTRY_CHARS,
1711
+ });
1712
+ const { openFleetDetail, loadAvailableModelChoices } = detailPanel;
1713
+ const applySessionModelSubstitution = (source: string, target: string, ctx: any) => modelPolicy.applySessionSubstitution(source, target, {
1714
+ loadAvailable: current => loadAvailableModelChoices(ctx, current),
1715
+ notify: (message, level) => ctx.ui.notify(message, level),
1716
+ });
1717
+
1718
+ let fleetShowFinished = false;
1719
+ let fleetFilter = "";
1720
+ const fleetDashboard = createFleetDashboard<AgentDef, AgentState, ResearchState>({
1721
+ getAgents: () => agentStates,
1722
+ getResearch: () => researchStates,
1723
+ getShowFinished: () => fleetShowFinished,
1724
+ setShowFinished: value => { fleetShowFinished = value; },
1725
+ getFilter: () => fleetFilter,
1726
+ setFilter: value => { fleetFilter = value; },
1727
+ getPeerInputs: fleetPeerInputs,
1728
+ parseResearchHandle,
1729
+ displayName,
1730
+ shortModel,
1731
+ thinkingSuffix,
1732
+ modelWithThinking,
1733
+ resolvedThinking,
1734
+ abbreviatePeerModel: abbreviateModel,
1735
+ modelPolicy,
1736
+ loadAvailableModels: loadAvailableModelChoices,
1737
+ openDetail: openFleetDetail,
1738
+ openHistory: ctx => openHistory(ctx, executionHistory, () => (activeTeamName ? `Team: ${activeTeamName}` : "Agent Hub")),
1739
+ modelWorkBlocked: modelWorkBlockedByRosterRecovery,
1740
+ restartSpecialist: researchControls.restartSpecialist,
1741
+ removeResearch: researchControls.remove,
1742
+ killSpecialistProcess: state => cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), treeKill: killPiTree }),
1743
+ abortComs: state => { state.comsAbort?.(); },
1744
+ getComsLines: (width, theme) => poolPresentation.render(width, theme),
1745
+ });
1746
+ const { fleetRows, openFleetDashboard } = fleetDashboard;
1747
+
1748
+ const contextBudgetUi = createContextBudgetUi<AgentDef, AgentState, ResearchState>({
1749
+ getAgents: () => agentStates,
1750
+ getResearch: () => researchStates,
1751
+ getAllDefs: () => allAgentDefs,
1752
+ getResearchPersonas: () => researchPersonas,
1753
+ getPeers: () => peerCards.values(),
1754
+ modelPolicy,
1755
+ displayName,
1756
+ getProjectDocsPaths: () => projectDocsPaths,
1757
+ getUserLanguage: () => userLanguage,
1758
+ getDelegateExtensionPath: () => delegateExtPath,
1759
+ safeAgentKey,
1760
+ projectPolicyPaths: specialistProjectPolicyPaths,
1761
+ modelWindowLookup,
1762
+ getResearchTools: () => RESEARCH_TOOLS,
1763
+ getPromptLedger: () => lastHubLedger,
1764
+ getPressureState: () => contextPressureState,
1765
+ buildHubSystemPrompt: () => { buildHubSystemPrompt(); },
1766
+ getAllTools: () => typeof pi.getAllTools === "function" ? pi.getAllTools() : [],
1767
+ getActiveTools: () => typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [],
1768
+ getCommands: () => typeof pi.getCommands === "function" ? pi.getCommands() : [],
1769
+ });
1770
+ const { openContextBudget } = contextBudgetUi;
1771
+
1772
+ // A delegate child anywhere in the team, by its id (e.g. "quality-1").
1773
+ function findDelegationChild(arg: string): { child: DelegationChild; owner: AgentState } | null {
1774
+ const lower = arg.toLowerCase();
1775
+ for (const state of agentStates.values()) {
1776
+ const child = Array.from(state.delegations?.values() ?? []).find(candidate => candidate.id.toLowerCase() === lower);
1777
+ if (child) return { child, owner: state };
1778
+ }
1779
+ return null;
1780
+ }
1781
+
1782
+ const completions = createCompletionPresentation({
1783
+ getAgents: () => agentStates.values(), getResearch: () => researchStates.values(),
1784
+ getResearchPersonas: () => researchPersonas, getModelProfiles: () => modelProfiles,
1785
+ getPeers: peersInScope, displayName, shortModel, resolvedModel, resolvedThinking,
1786
+ resolveThinkingLevel, resolvedSubagentModel,
1787
+ getSubagentOverride: (persona, role) => modelPolicy.getSubagentOverride(persona, role),
1788
+ getSubstitutionSources: () => modelPolicy.allKnownModels().map(spec => {
1789
+ const target = modelPolicy.getSubstitution(spec);
1790
+ return { spec, label: target ? `${spec} → ${target} (active this session)` : spec };
1791
+ }),
1792
+ });
1793
+
1794
+ registerInputShortcuts(pi, {
1795
+ setWidgetContext: ctx => { widgetCtx = ctx; }, openFleetDashboard,
1796
+ workModeStatusText, openWorkModePicker,
1797
+ });
1798
+
1799
+ // Root owns subscription order; lifecycle modules own handler bodies.
1800
+ registerTurnPresence(pi, {
1801
+ beforeAgentPresence: () => turnHandlers.beforeAgentPresence(),
1802
+ agentEndPresence: () => turnHandlers.agentEndPresence(),
1803
+ });
1804
+
1805
+ // /af-handoff <peer> — hand the session off to a coms peer. Per decision G1 we do NOT
1806
+ // extract the compaction summary; instead we ask the dispatcher LLM (next turn) to
1807
+ // compose a SELF-CONTAINED brief and coms_send it, then await + relay the reply.
1808
+ // /af-compound [focus] — end-of-session compound-learning pass. Mirrors /af-handoff's
1809
+ // shape: the dispatcher LLM (which saw the whole session) composes the
1810
+ // candidate-lessons brief itself, gates it on the user, then dispatches the
1811
+ // documenter to land the approved lessons per skills/compound-learning/SKILL.md.
1812
+ // The rules/docs targets come from the overrides file; artifacts travel as
1813
+ // paths through the dispatch's `artifacts` array, never as pasted bodies.
1814
+ // ── ask_user wait tracking (for /af-agents-history real-work) ──
1815
+ // pi-ask-user blocks the dispatcher turn while the human answers. Bracket each
1816
+ // ask_user call with its tool_execution start/end so /af-agents-history can subtract
1817
+ // that "away from keyboard" time from the dispatcher's real work.
1818
+ pi.on("tool_execution_start", async event => turnHandlers.toolStart(event));
1819
+ observeAskUserResults(({ params, result, phase }) => {
1820
+ const pack = capabilityConfirmationPack(params.context);
1821
+ if (!pack) return;
1822
+ if (phase === "start") workModePolicy.setCapabilityConfirmation(pack, "pending");
1823
+ else {
1824
+ const outcome = confirmationOutcome(result);
1825
+ if (!outcome) return;
1826
+ workModePolicy.setCapabilityConfirmation(pack, outcome);
1827
+ resolveIncomingCapabilities("");
1828
+ applyWorkModeTools();
1829
+ }
1830
+ });
1831
+
1832
+ pi.on("tool_execution_end", async event => turnHandlers.toolEnd(event));
1833
+
1834
+ // ── System Prompt Override ───────────────────
1835
+
1836
+
1837
+ const hubPromptCtx: HubPromptContext = {
1838
+ getArtifactRoot: () => sessionDir ? artifactsRoot() : null,
1839
+ getCapabilityResolution,
1840
+ getActiveTools: () => pi.getActiveTools(),
1841
+ getAgents: () => Array.from(agentStates.values()).map(state => ({
1842
+ name: state.def.name,
1843
+ displayName: displayName(state.def.name),
1844
+ description: state.def.description,
1845
+ tools: state.def.tools,
1846
+ })),
1847
+ getResearchPersonas: () => researchPersonas.map(def => ({
1848
+ name: def.name,
1849
+ displayName: displayName(def.name),
1850
+ description: def.description,
1851
+ model: resolvedModel(def),
1852
+ thinking: resolveThinkingLevel(resolvedThinking(def)),
1853
+ })),
1854
+ getPromptState: () => ({
1855
+ taskTier: taskTier ?? DEFAULT_TASK_TIER,
1856
+ taskTierAssumed,
1857
+ turnDispatchCount,
1858
+ turnResearchCount,
1859
+ taskDispatchCount,
1860
+ taskResearchCount,
1861
+ taskReviewRounds,
1862
+ turnBudget: currentBudget(),
1863
+ taskBudget: currentTaskBudget(),
1864
+ provisionalConfirmations: getCapabilityResolution().provisional
1865
+ .filter(pack => workModePolicy.getCapabilityConfirmation()[pack as ConfirmableCapabilityPack] !== "declined")
1866
+ .map(pack => ({
1867
+ pack,
1868
+ reason: getCapabilityResolution().reasons[pack],
1869
+ question: capabilityConfirmationQuestion(pack as ConfirmableCapabilityPack),
1870
+ })),
1871
+ }),
1872
+ getWorkMode,
1873
+ getActiveTeamName: () => activeTeamName,
1874
+ getUserLanguage: () => userLanguage,
1875
+ isAskUserAvailable: () => askUserAvailable,
1876
+ isComsReady: () => comsReady,
1877
+ getIdentity: () => identity,
1878
+ isHerdrFleetReady: () => herdrFleetReady,
1879
+ };
1880
+
1881
+ // This is also called by /af-context before the first turn. Keep prompt assembly
1882
+ // in this one production path so its ledger describes the exact next replacement.
1883
+ function buildHubSystemPrompt(): { systemPrompt: string } {
1884
+ const built = assembleHubPrompt(hubPromptCtx);
1885
+ lastHubLedger = built.ledger;
1886
+ return { systemPrompt: built.systemPrompt };
1887
+ }
1888
+
1889
+ const turnHandlers = createTurnLifecycleHandlers({
1890
+ setTurnState: state => coms.setTurnState(state),
1891
+ finishMonitorTurn: () => { if (monitorBridge && monitorTurnId) { monitorBridge.finishParent(monitorTurnId, "completed"); monitorTurnId = null; } },
1892
+ startMonitorTurn: () => { if (monitorBridge && monitorHubId) { monitorTurnId = `hub-turn-${monitorHubId}-${crypto.randomUUID()}`; monitorBridge.startParent({ id: monitorTurnId, hubInstanceId: monitorHubId, checkoutId: currentCtx?.cwd || process.cwd() }); } },
1893
+ startAskUser: id => executionHistory.startAskUser(id), endAskUser: (id, at) => executionHistory.endAskUser(id, at),
1894
+ acknowledgeExternalBlocker: () => { externalBlockerAcknowledged = true; externalBlockerRefusedOnce = false; },
1895
+ addAskUserWait: waitMs => { if (waitMs > 0) taskClock = addTaskClockWait(taskClock, waitMs); turnBudgetAskUserWaitMs += waitMs; },
1896
+ applyWorkMode: applyWorkModeTools, closeTurnActiveTime, openTaskClock: at => { taskClock = openTaskClock(taskClock, at); }, startHistoryTurn: at => executionHistory.startTurn(at),
1897
+ resetTurnBudgetState: () => {
1898
+ turnBudgetAskUserWaitMs = 0; // budgetRecovery is task-scoped: prose/new turns cannot clear a declined confirmation.
1899
+ turnDispatchCount = 0; turnResearchCount = 0; turnDispatchFingerprints.clear(); externalBlockerAcknowledged = true; externalBlockerRefusedOnce = false;
1900
+ if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) { lastTurnReport = turnReport; sessionTotals.turns++; }
1901
+ turnReport = freshTurnReport();
1902
+ },
1903
+ updateModeStatus, buildPrompt: buildHubSystemPrompt, endHistoryTurn: at => executionHistory.endTurn(at),
1904
+ unaddressedPeerWarning: () => unaddressedPeerSweep(Array.from(hubSpawnedPeers.values()))?.message ?? null,
1905
+ respondToPeer: ctx => coms.respond(ctx),
1906
+ });
1907
+ pi.on("before_agent_start", async () => turnHandlers.beforeAgentStart());
1908
+
1909
+ const pressureLifecycle = createContextPressureLifecycle({
1910
+ getState: () => pressureRootState,
1911
+ setPressure: value => { contextPressureState = value; pressureRootState.pressure = value; },
1912
+ getCurrentContext: () => currentCtx,
1913
+ appendEntry: (type, data) => pi.appendEntry(type, data),
1914
+ sendUserMessage: (content, options) => pi.sendUserMessage(content as any, options),
1915
+ resolveCapabilities: resolveIncomingCapabilities, applyWorkMode: applyWorkModeTools,
1916
+ modelWorkBlocked: modelWorkBlockedByRosterRecovery,
1917
+ });
1918
+ function replayDeferredRecoveryInputs(): void { pressureLifecycle.replayDeferred(); }
1919
+ pi.on("message_end", async (event, ctx) => pressureLifecycle.messageEnd(event, ctx));
1920
+ pi.on("turn_end", async (_event, ctx) => pressureLifecycle.turnEnd(ctx));
1921
+ pi.on("context", async (_event, ctx) => pressureLifecycle.context(ctx));
1922
+ pi.on("agent_settled", async (_event, ctx) => pressureLifecycle.agentSettled(ctx));
1923
+ pi.on("session_compact", async () => pressureLifecycle.sessionCompact());
1924
+ pi.on("input", async (event, ctx) => pressureLifecycle.input(event, ctx));
1925
+
1926
+ // ── Session Start ────────────────────────────
1927
+
1928
+ let sessionOverrides: ReturnType<typeof parseAgentTeamOverrides> | undefined;
1929
+ let sessionSoloMode = false;
1930
+ const monitorSession = createMonitorSession({
1931
+ pi,
1932
+ getBridge: () => monitorBridge, setBridge: value => { monitorBridge = value; },
1933
+ getLifecycle: () => monitorLifecycle, setLifecycle: value => { monitorLifecycle = value; },
1934
+ setHubId: value => { monitorHubId = value; },
1935
+ getOwnerId: () => monitorOwnerId, setOwnerId: value => { monitorOwnerId = value; },
1936
+ queueDepth: () => inboundQueue.size,
1937
+ });
1938
+ registerSessionOrchestration(pi, {
1939
+ resetSession: (_ctx) => resetHubSession(_ctx, {
1940
+ registerVersion: registerVersionStatus, resetPressure: pressureLifecycle.reset,
1941
+ clearRosterRecovery: workModePolicy.clearRosterRecovery, captureBaselineTools: () => { baselineTools = pi.getActiveTools(); },
1942
+ resetAccessApproval: accessApprovalRouter.reset,
1943
+ terminateResearch: () => { for (const st of researchStates.values()) if (st.proc && st.status === "running") { st.killedByOperator = true; st.proc.kill("SIGTERM"); } },
1944
+ resetResearch: researchRuntime.reset, resetHistory: executionHistory.reset,
1945
+ resetBudgets: () => { taskClock = createTaskClock(); turnBudgetAskUserWaitMs = 0; turnContinuationCount = 0; taskContinuationCount = 0; budgetRecovery.reset(); noProgress.reset(); },
1946
+ clearWidgets: ctx => { if (widgetCtx) { ctx.ui.setWidget("agent-team", undefined); } },
1947
+ closeDelegationWatchers: () => { for (const st of agentStates.values()) { st.delegationsWatcher?.close(); st.delegationsWatcher = undefined; } },
1948
+ resetSessionState: ctx => { delegatedTokens = 0; hubSpawnedPeers.clear(); widgetCtx = ctx; contextWindow = ctx.model?.contextWindow || 0; },
1949
+ resolveSafety: cwd => Boolean(safetyHarnessPath = resolveSafetyHarness(cwd)), resolveDelegate: cwd => { delegateExtPath = resolveDelegateExtension(cwd); },
1950
+ }),
1951
+ restartMonitor: _ctx => monitorSession.restart(_ctx),
1952
+ initializeComs: async (_ctx) => {
1953
+ // ── Embedded coms init ──
1954
+ // Always refresh the ctx the coms handlers use. Bind the endpoint + register
1955
+ // in the pool exactly once per process (guard on comsReady), so a /new session
1956
+ // keeps the same peer identity rather than leaking a second socket. On any
1957
+ // failure we degrade: comsReady stays false and the coms_* tools are withheld.
1958
+ hubStateCtx.setCurrentContext(_ctx);
1959
+ sessionSoloMode = pi.getFlag("solo") === true;
1960
+ if (!comsReady && !sessionSoloMode) {
1961
+ try {
1962
+ identity = await coms.connect({ ctx: _ctx, defaultNamePrefix: "hub", defaultPurpose: "agent-hub dispatcher" });
1963
+ comsReady = true;
1964
+ try {
1965
+ _ctx.ui.setStatus("coms", `📡 ${identity.name}@${identity.project}`);
1966
+ } catch { /* hasUI may be false — non-fatal */ }
1967
+ } catch (err) {
1968
+ comsReady = false;
1969
+ try { _ctx.ui?.notify?.(`📡 coms: init failed — ${err instanceof Error ? err.message : String(err)} (coms tools disabled)`, "error"); } catch { /* ignore */ }
1970
+ }
1971
+ }
1972
+ },
1973
+ initializeExemptions: (_ctx) => {
1974
+ // ── Damage-control shared exemptions file ──
1975
+ // One per hub session (solo mode included). Exporting the path on our own
1976
+ // process.env lets the co-loaded damage-control-continue mirror /af-allow
1977
+ // session grants into the same file the spawned children read.
1978
+ if (!exemptionsFile) {
1979
+ hubStateCtx.setExemptionsFile(exemptionsFilePath(identity?.session_id ?? `hub-solo-${process.pid}`));
1980
+ process.env[EXEMPTIONS_FILE_ENV] = exemptionsFile!;
1981
+ }
1982
+ },
1983
+ loadAgents: (_ctx) => {
1984
+ // Allocate a fresh namespace; shared legacy files belong to prior/live sessions.
1985
+ sessionOverrides = parseAgentTeamOverrides(_ctx.cwd);
1986
+ runHistoryKeep = sessionOverrides.runHistoryKeep;
1987
+
1988
+ loadAgents(_ctx.cwd);
1989
+
1990
+ // Surface non-fatal persona frontmatter warnings (skipped subagents roles,
1991
+ // bad delegate_depth) once per session.
1992
+ const fmWarnings = allAgentDefs.flatMap(d => (d.warnings || []).map(w => `${d.name}: ${w}`));
1993
+ if (fmWarnings.length > 0) {
1994
+ _ctx.ui.notify(`Persona frontmatter warnings:\n${fmWarnings.join("\n")}`, "warning");
1995
+ }
1996
+ if (!delegateExtPath && allAgentDefs.some(d => d.subagents)) {
1997
+ _ctx.ui.notify(
1998
+ "delegate.ts not found next to agent-hub — `subagents:` declarations are inert (specialists dispatch without a delegate tool).",
1999
+ "warning",
2000
+ );
2001
+ }
2002
+ },
2003
+ applyOverrides: (_ctx) => {
2004
+ if (!sessionOverrides) throw new Error("session_start applyOverrides ran before loadAgents");
2005
+ applySessionOverrides(_ctx, sessionOverrides, {
2006
+ setLanguage: value => { userLanguage = value; },
2007
+ setReconTimeout: value => { reconSearchTimeoutMs = value; }, setBudgetOverrides: value => { budgetOverrides = value; },
2008
+ setWatchdog: (setting, judge) => { watchdogSetting = setting; watchdogJudgeModel = judge; },
2009
+ resetTurnCounts: () => { turnDispatchCount = 0; turnResearchCount = 0; }, resetTaskWindow: () => resetTaskWindow(null), updateModeStatus,
2010
+ setProjectRules: value => { projectRulesDirs = value; }, setProjectDocs: value => { projectDocsPaths = value; },
2011
+ resetModelPolicy: () => {modelPolicy.reset();profileActivation.reset();}, getModelProfileErrors: () => modelProfileErrors, getAgentDefs: () => allAgentDefs, getModelProfiles: () => modelProfiles,
2012
+ deleteModelProfile: name => { delete modelProfiles[name]; }, allowedModels,
2013
+ getDispatchPolicyWarnings: () => dispatchPolicyWarnings, setResearchPersonas: value => { researchPersonas = value; },
2014
+ });
2015
+ },
2016
+ restoreRoster: (_ctx) => {
2017
+ // Explicit CLI selection wins; otherwise restore only the canonical team name
2018
+ // and re-resolve it against current teams.yaml/persona files. An explicit
2019
+ // Operator work mode suppresses an ambient persisted roster unless --agent-team
2020
+ // was also supplied.
2021
+ agentStates.clear();
2022
+ activeTeamName = "";
2023
+ comsMissNotified.clear();
2024
+ recomputeGrid();
2025
+ const sessionEntries = _ctx.sessionManager.getEntries();
2026
+ const explicitWorkMode = pi.getFlag("work-mode");
2027
+ const explicitRoster = pi.getFlag("agent-team");
2028
+ const hasExplicitRoster = typeof explicitRoster === "string" && explicitRoster.trim() !== "";
2029
+ const startupRoster = resolveSessionRoster({
2030
+ teams,
2031
+ entries: sessionEntries,
2032
+ explicitRoster,
2033
+ availablePersonas: allAgentDefs.map(def => def.name),
2034
+ includePersisted: !(explicitWorkMode === "operator" && !hasExplicitRoster),
2035
+ });
2036
+ workModePolicy.setRestoredWorkMode(resolveSessionWorkMode({
2037
+ entries: sessionEntries,
2038
+ explicitWorkMode,
2039
+ hasExplicitRoster: startupRoster.source === "explicit",
2040
+ }));
2041
+ if (startupRoster.roster) {
2042
+ activateTeam(startupRoster.roster.name);
2043
+ persistActiveRoster();
2044
+ }
2045
+ const rosterRecoveryRequired = orchestratorNeedsRoster(getWorkMode(), agentStates.size);
2046
+ const rosterRecoveryDiagnostic = rosterRecoveryRequired
2047
+ ? startupRoster.diagnostic || "Persisted orchestrator work mode has no native roster."
2048
+ : "";
2049
+ workModePolicy.setRosterRecovery(rosterRecoveryRequired, rosterRecoveryDiagnostic);
2050
+ if (startupRoster.diagnostic) {
2051
+ _ctx.ui.notify(
2052
+ `${startupRoster.diagnostic} ${rosterRecoveryRequired ? "Model input is blocked until you select /af-agents-team, restart with --agent-team <name>, or switch explicitly with --work-mode operator." : "Continuing without that roster."}`,
2053
+ rosterRecoveryRequired ? "error" : "warning",
2054
+ );
2055
+ } else if (rosterRecoveryRequired) {
2056
+ _ctx.ui.notify(
2057
+ `${rosterRecoveryDiagnostic} Model input is blocked until you select /af-agents-team, restart with --agent-team <name>, or switch explicitly with --work-mode operator.`,
2058
+ "error",
2059
+ );
2060
+ }
2061
+ },
2062
+ resolveCapabilities: async (_ctx) => {
2063
+ // Probe for `ask_user` (registered by the `pi-ask-user` companion package
2064
+ // when installed). Action methods like getAllTools are runtime-only, so
2065
+ // this MUST happen at session_start, not at extension load.
2066
+ askUserAvailable = pi.getAllTools().some(t => t.name === "ask_user");
2067
+
2068
+ // Fleet tools are available only inside a herdr pane with a live server.
2069
+ // The work mode policy adds gated groups without activating unavailable tools.
2070
+ herdrFleetReady = herdrPaneId() !== null && (await herdrAvailable()) !== null;
2071
+ const persistedCapabilities = latestPersistedCapabilityState(_ctx.sessionManager.getEntries());
2072
+ workModePolicy.restoreCapabilities({ taskPacks: persistedCapabilities?.taskPacks ?? [], provisional: persistedCapabilities?.provisional ?? [], confirmation: persistedCapabilities?.confirmation ?? {} });
2073
+ resolveIncomingCapabilities("");
2074
+ applyWorkModeTools();
2075
+ if (pressureLifecycle.observe(_ctx, "session_start") === "compact-now") {
2076
+ setTimeout(() => pressureLifecycle.runCompaction(_ctx, "session_start"), 0);
2077
+ }
2078
+ workModePolicy.updateStatus(_ctx);
2079
+ },
2080
+ notifyStartup: (_ctx) => {
2081
+ _ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"} (${agentStates.size})`);
2082
+ const members = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
2083
+ const askUserLabel = askUserAvailable
2084
+ ? "available (via pi-ask-user)"
2085
+ : "NOT AVAILABLE — run `pi install npm:pi-ask-user`";
2086
+ const comsLabel = comsReady && identity
2087
+ ? `📡 ${identity.name}@${identity.project} — peers via coms_list; /af-handoff <peer> to delegate`
2088
+ : sessionSoloMode
2089
+ ? "off (--solo: fixed specialists + research only)"
2090
+ : "off (endpoint bind failed — coms tools disabled)";
2091
+ const fleetLabel = herdrFleetReady
2092
+ ? "herdr — spawn/read/close panes + notify (herdr_* tools active)"
2093
+ : "off (not inside a herdr pane, or no herdr server)";
2094
+ const comsPreferred = Object.entries(dispatchPolicy.substitutions)
2095
+ .filter(([, s]) => s.prefer === "coms")
2096
+ .map(([n]) => n);
2097
+ const dispatchLabel = dispatchPolicy.default === "coms"
2098
+ ? "coms default — any member with a live same-name pool peer is served by it (/af-dispatch-policy)"
2099
+ : comsPreferred.length > 0
2100
+ ? `coms-preferred: ${comsPreferred.join(", ")} (live peer wins, /af-dispatch-policy for status)`
2101
+ : "all native (no substitutions in .pi/agents/dispatch-policy.yaml)";
2102
+ _ctx.ui.notify(buildSessionStartNotice({
2103
+ workMode: getWorkMode(),
2104
+ activeTeamName,
2105
+ agentCount: agentStates.size,
2106
+ members,
2107
+ dispatchLabel,
2108
+ userLanguage,
2109
+ askUserLabel,
2110
+ comsLabel,
2111
+ fleetLabel,
2112
+ }), "info");
2113
+ },
2114
+ updateWidget: (_ctx) => {
2115
+ updateWidget();
2116
+ },
2117
+ installFooter: (_ctx) => {
2118
+ _ctx.ui.setFooter(createSessionFooter({
2119
+ ctx: _ctx,
2120
+ version: HARNESS_VERSION,
2121
+ getModel: () => _ctx.model?.id || "no-model",
2122
+ getThinkingLevel: () => pi.getThinkingLevel?.(),
2123
+ thinkingSuffix,
2124
+ getHint: () => composeFleetFooterHint(compactWorkMode(getWorkMode())),
2125
+ renderLeft: renderHubFooterLeft,
2126
+ truncateToWidth,
2127
+ visibleWidth,
2128
+ }));
2129
+ },
2130
+ }, {
2131
+ finishEvidence: () => { if (sessionDir) closeEvidenceSession(sessionDir); },
2132
+ shutdownComs: () => { unregisterQuestions(); return coms.shutdown(); }, shutdownMonitor: () => monitorSession.shutdown(),
2133
+ removeExemptions: () => {
2134
+ if (!exemptionsFile) return;
2135
+ try { fs.unlinkSync(exemptionsFile); } catch {}
2136
+ hubStateCtx.setExemptionsFile(null);
2137
+ },
2138
+ terminateChildren: () => {
2139
+ for (const st of [...agentStates.values(), ...researchStates.values()]) {
2140
+ if (st.proc && st.status === "running") try { st.killedByOperator = true; st.proc.kill("SIGTERM"); } catch {}
2141
+ }
2142
+ },
2143
+ clearPoolWidget: () => {
2144
+ if (currentCtx?.hasUI) try { currentCtx.ui.setWidget("coms-pool", undefined); } catch {}
2145
+ },
2146
+ });
2147
+
2148
+ // Ordered end-turn peer response remains after session-start registration.
2149
+ pi.on("agent_end", async (_event, ctx) => turnHandlers.agentEnd(ctx));
2150
+
2151
+ }