@chankov/agent-fleet 2.0.17 → 2.0.19

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 (1228) hide show
  1. package/.pi/agent-fleet/scripts/coms-claude-bridge.ts +75 -49
  2. package/.pi/agent-fleet/scripts/lib/claude-bridge-core.ts +18 -20
  3. package/.pi/agent-fleet/scripts/workflows/lib/project-policy.ts +3 -1
  4. package/.pi/agents/model-profiles.yaml +5 -5
  5. package/.pi/agents/peers.yaml +3 -3
  6. package/.pi/agents/voices.yaml +1 -1
  7. package/.pi/harnesses/agent-hub/README.md +35 -8
  8. package/.pi/harnesses/agent-hub/agentic-sources.ts +29 -5
  9. package/.pi/harnesses/agent-hub/config/overrides.ts +13 -3
  10. package/.pi/harnesses/agent-hub/delegate.ts +16 -5
  11. package/.pi/harnesses/agent-hub/deterministic-fs.ts +7 -4
  12. package/.pi/harnesses/agent-hub/dispatch-native-prepare.ts +13 -2
  13. package/.pi/harnesses/agent-hub/dispatch-native-spawn.ts +2 -0
  14. package/.pi/harnesses/agent-hub/dispatch-native-types.ts +7 -0
  15. package/.pi/harnesses/agent-hub/dispatch-native.ts +1 -1
  16. package/.pi/harnesses/agent-hub/file-discovery/adapters.ts +82 -0
  17. package/.pi/harnesses/agent-hub/file-discovery/broker-client.ts +56 -0
  18. package/.pi/harnesses/agent-hub/file-discovery/broker.ts +125 -0
  19. package/.pi/harnesses/agent-hub/file-discovery/child-extension.ts +33 -0
  20. package/.pi/harnesses/agent-hub/file-discovery/descendant.ts +63 -0
  21. package/.pi/harnesses/agent-hub/file-discovery/discovery-worker.mjs +15 -0
  22. package/.pi/harnesses/agent-hub/file-discovery/discovery.ts +126 -0
  23. package/.pi/harnesses/agent-hub/file-discovery/evaluate.ts +48 -0
  24. package/.pi/harnesses/agent-hub/file-discovery/hub.ts +152 -0
  25. package/.pi/harnesses/agent-hub/file-discovery/native-context.ts +8 -0
  26. package/.pi/harnesses/agent-hub/file-discovery/owners.ts +96 -0
  27. package/.pi/harnesses/agent-hub/file-discovery/results.ts +54 -0
  28. package/.pi/harnesses/agent-hub/file-discovery/runtime.ts +120 -0
  29. package/.pi/harnesses/agent-hub/file-discovery/sources.ts +69 -0
  30. package/.pi/harnesses/agent-hub/file-discovery/state.ts +22 -0
  31. package/.pi/harnesses/agent-hub/filesystem-tool.ts +74 -26
  32. package/.pi/harnesses/agent-hub/index.ts +23 -5
  33. package/.pi/harnesses/agent-hub/lifecycle/session-orchestration.ts +3 -2
  34. package/.pi/harnesses/agent-hub/no-progress.ts +45 -15
  35. package/.pi/harnesses/agent-hub/package.json +1 -1
  36. package/.pi/harnesses/agent-hub/policy/work-mode.ts +2 -1
  37. package/.pi/harnesses/agent-hub/proactive-config.ts +8 -3
  38. package/.pi/harnesses/agent-hub/proactive-external-git.ts +82 -0
  39. package/.pi/harnesses/agent-hub/proactive-external.ts +142 -0
  40. package/.pi/harnesses/agent-hub/proactive-local.ts +25 -7
  41. package/.pi/harnesses/agent-hub/proactive-observer.ts +2 -1
  42. package/.pi/harnesses/agent-hub/proactive-rules.ts +39 -11
  43. package/.pi/harnesses/agent-hub/proactive-runtime.ts +8 -6
  44. package/.pi/harnesses/agent-hub/proactive-snapshot.ts +49 -6
  45. package/.pi/harnesses/agent-hub/proactive-types.ts +5 -1
  46. package/.pi/harnesses/agent-hub/prompts/fragments.ts +21 -49
  47. package/.pi/harnesses/agent-hub/prompts/system-prompt.ts +2 -1
  48. package/.pi/harnesses/agent-hub/research/runtime.ts +7 -3
  49. package/.pi/harnesses/agent-hub/research/spawn-run.ts +17 -6
  50. package/.pi/harnesses/agent-hub/spawn.ts +38 -9
  51. package/.pi/harnesses/agent-hub/system1-communication-store.ts +39 -0
  52. package/.pi/harnesses/agent-hub/tools/action-executors.ts +6 -1
  53. package/.pi/harnesses/agent-hub/tools/ask-system1-files.ts +15 -0
  54. package/.pi/harnesses/agent-hub/tools/ask-system1.ts +1 -1
  55. package/.pi/harnesses/agent-hub/tools/dispatch-agent.ts +4 -4
  56. package/.pi/harnesses/agent-hub/tools/dispatch-execution.ts +4 -2
  57. package/.pi/harnesses/agent-hub/tools/set-task-tier.ts +3 -3
  58. package/.pi/harnesses/agent-hub/tools/spawn-research.ts +3 -1
  59. package/.pi/harnesses/agent-hub/ui/system1-communication.ts +1 -1
  60. package/.pi/harnesses/agent-hub/work-mode.ts +3 -0
  61. package/.pi/harnesses/coms/package.json +1 -1
  62. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  63. package/.pi/harnesses/lib/context-budget-child-prompt.ts +3 -2
  64. package/.pi/harnesses/lib/deterministic-handle-path.ts +2 -0
  65. package/.pi/harnesses/lib/policy-roots.js +106 -0
  66. package/.pi/harnesses/lib/policy-roots.ts +31 -0
  67. package/.pi/harnesses/lib/system1/config-agentic.js +2 -1
  68. package/.pi/harnesses/lib/system1/config-file-discovery.js +21 -0
  69. package/.pi/harnesses/lib/system1/config-proactive.js +13 -2
  70. package/.pi/harnesses/lib/system1/config-v2.js +8 -5
  71. package/.versions/2.0.18/.pi/agent-fleet/hermes/README.md +347 -0
  72. package/.versions/2.0.18/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  73. package/.versions/2.0.18/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  74. package/.versions/2.0.18/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  75. package/.versions/2.0.18/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  76. package/.versions/2.0.18/.pi/agent-fleet/hermes/gates/gate-o-capability.md +8 -0
  77. package/.versions/2.0.18/.pi/agent-fleet/hermes/gates/gate-o-validator-fixtures.json +1 -0
  78. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +773 -0
  79. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  80. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  81. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  82. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  83. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  84. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  85. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  86. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  87. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  88. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  89. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  90. package/.versions/2.0.18/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  91. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-conductor/SKILL.md +84 -0
  92. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-liaison/SKILL.md +84 -0
  93. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/SKILL.md +76 -0
  94. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/manifest.json +1 -0
  95. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  96. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  97. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  98. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  99. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  100. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  101. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  102. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  103. package/.versions/2.0.18/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  104. package/.versions/2.0.18/.pi/agent-fleet/hermes/watchdog-tests/__init__.py +0 -0
  105. package/.versions/2.0.18/.pi/agent-fleet/hooks/coms-stop-hook.mjs +84 -0
  106. package/.versions/2.0.18/.pi/agent-fleet/scripts/claude-code-preflight.ts +70 -0
  107. package/.versions/2.0.18/.pi/agent-fleet/scripts/coms-claude-bridge.ts +437 -0
  108. package/.versions/2.0.18/.pi/agent-fleet/scripts/coms-cli.ts +425 -0
  109. package/.versions/2.0.18/.pi/agent-fleet/scripts/coms-hermes-bridge.ts +413 -0
  110. package/.versions/2.0.18/.pi/agent-fleet/scripts/fleet-codex-client.ts +69 -0
  111. package/.versions/2.0.18/.pi/agent-fleet/scripts/fleet-codex-read.py +148 -0
  112. package/.versions/2.0.18/.pi/agent-fleet/scripts/fleet.ts +217 -0
  113. package/.versions/2.0.18/.pi/agent-fleet/scripts/flow.ts +157 -0
  114. package/.versions/2.0.18/.pi/agent-fleet/scripts/hermes-monitor-capability-runner.ts +25 -0
  115. package/.versions/2.0.18/.pi/agent-fleet/scripts/hermes-monitor-scenario.ts +474 -0
  116. package/.versions/2.0.18/.pi/agent-fleet/scripts/hermes-watchdog-capability-probe.ts +45 -0
  117. package/.versions/2.0.18/.pi/agent-fleet/scripts/install-hermes-plugin.sh +180 -0
  118. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/claude-bridge-core.ts +208 -0
  119. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/coms-envelope.ts +582 -0
  120. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/fake-herdr-server.ts +88 -0
  121. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/fleet-codex-catalog.ts +63 -0
  122. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/fleet-codex-operations.ts +190 -0
  123. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/fleet-codex-session.ts +166 -0
  124. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/fleet-codex-transport.ts +124 -0
  125. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/fleet-command.ts +252 -0
  126. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/flow-command.ts +98 -0
  127. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/flow-maintenance.ts +230 -0
  128. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/herdr-layout.ts +281 -0
  129. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-bridge-core.ts +241 -0
  130. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-monitor-events.ts +1 -0
  131. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-monitor-herdr.ts +2 -0
  132. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-monitor-model.ts +3 -0
  133. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-monitor-registry.ts +2 -0
  134. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-monitor-socket.ts +2 -0
  135. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/hermes-monitor-store.ts +2 -0
  136. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/monitor-env.ts +146 -0
  137. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/peer-launch.ts +318 -0
  138. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/persona-banner.ts +62 -0
  139. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/persona-dirs.ts +25 -0
  140. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/runtime-dependencies.js +124 -0
  141. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/spawn-stagger.ts +101 -0
  142. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/team-project.ts +178 -0
  143. package/.versions/2.0.18/.pi/agent-fleet/scripts/lib/team-snapshot.ts +147 -0
  144. package/.versions/2.0.18/.pi/agent-fleet/scripts/package-lock.json +35 -0
  145. package/.versions/2.0.18/.pi/agent-fleet/scripts/package.json +9 -0
  146. package/.versions/2.0.18/.pi/agent-fleet/scripts/peer-banner.ts +41 -0
  147. package/.versions/2.0.18/.pi/agent-fleet/scripts/peer-launch.ts +283 -0
  148. package/.versions/2.0.18/.pi/agent-fleet/scripts/team-snapshot.ts +237 -0
  149. package/.versions/2.0.18/.pi/agent-fleet/scripts/team-up.ts +378 -0
  150. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/agent-phase.ts +179 -0
  151. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/changes.ts +61 -0
  152. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/debate.ts +149 -0
  153. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/env.ts +34 -0
  154. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/envelopes.ts +169 -0
  155. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/gates.ts +81 -0
  156. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/git.ts +96 -0
  157. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/isolated-snapshot.ts +125 -0
  158. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/merge.ts +95 -0
  159. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/model-profile.ts +22 -0
  160. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/model-visibility.ts +92 -0
  161. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/permissions.ts +130 -0
  162. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/personas.ts +57 -0
  163. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/poll.ts +86 -0
  164. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/project-policy.ts +36 -0
  165. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/quality.ts +64 -0
  166. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/run.ts +108 -0
  167. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/scout-data-boundary.ts +55 -0
  168. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/trace.ts +34 -0
  169. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/voices.ts +128 -0
  170. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/lib/writer-lease.ts +112 -0
  171. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/tsconfig.json +22 -0
  172. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/wf-build-test.ts +61 -0
  173. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/wf-debate.ts +87 -0
  174. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/wf-document.ts +50 -0
  175. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/wf-poll.ts +95 -0
  176. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/wf-quality.ts +20 -0
  177. package/.versions/2.0.18/.pi/agent-fleet/scripts/workflows/wf-scout.ts +40 -0
  178. package/.versions/2.0.18/.pi/agents/dispatch-policy.yaml +32 -0
  179. package/.versions/2.0.18/.pi/agents/model-profiles.yaml +134 -0
  180. package/.versions/2.0.18/.pi/agents/peers.yaml +147 -0
  181. package/.versions/2.0.18/.pi/agents/teams.yaml +41 -0
  182. package/.versions/2.0.18/.pi/agents/voices.yaml +13 -0
  183. package/.versions/2.0.18/.pi/damage-control-rules.yaml +297 -0
  184. package/.versions/2.0.18/.pi/extensions/btw/README.md +120 -0
  185. package/.versions/2.0.18/.pi/extensions/btw/index.ts +914 -0
  186. package/.versions/2.0.18/.pi/extensions/btw/package.json +6 -0
  187. package/.versions/2.0.18/.pi/extensions/btw/state.js +179 -0
  188. package/.versions/2.0.18/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  189. package/.versions/2.0.18/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  190. package/.versions/2.0.18/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  191. package/.versions/2.0.18/.pi/extensions/compact-and-continue/README.md +42 -0
  192. package/.versions/2.0.18/.pi/extensions/compact-and-continue/index.ts +120 -0
  193. package/.versions/2.0.18/.pi/extensions/compact-and-continue/package.json +6 -0
  194. package/.versions/2.0.18/.pi/extensions/mcp-bridge/README.md +46 -0
  195. package/.versions/2.0.18/.pi/extensions/mcp-bridge/index.ts +206 -0
  196. package/.versions/2.0.18/.pi/extensions/mcp-bridge/package.json +6 -0
  197. package/.versions/2.0.18/.pi/extensions/package-lock.json +1175 -0
  198. package/.versions/2.0.18/.pi/extensions/package.json +9 -0
  199. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/README.md +224 -0
  200. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/config.ts +198 -0
  201. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  202. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/index.ts +248 -0
  203. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/package.json +6 -0
  204. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  205. package/.versions/2.0.18/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  206. package/.versions/2.0.18/.pi/harnesses/agent-hub/README.md +1483 -0
  207. package/.versions/2.0.18/.pi/harnesses/agent-hub/acceptance.ts +199 -0
  208. package/.versions/2.0.18/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  209. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-contract.ts +43 -0
  210. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-evidence.ts +64 -0
  211. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-hub.ts +54 -0
  212. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-runtime.ts +56 -0
  213. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-sources-worker.mjs +4 -0
  214. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-sources.ts +74 -0
  215. package/.versions/2.0.18/.pi/harnesses/agent-hub/agentic-state.ts +23 -0
  216. package/.versions/2.0.18/.pi/harnesses/agent-hub/artifacts.js +146 -0
  217. package/.versions/2.0.18/.pi/harnesses/agent-hub/assertion-ledger.js +67 -0
  218. package/.versions/2.0.18/.pi/harnesses/agent-hub/assist-profile.ts +16 -0
  219. package/.versions/2.0.18/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  220. package/.versions/2.0.18/.pi/harnesses/agent-hub/bounded-output.ts +26 -0
  221. package/.versions/2.0.18/.pi/harnesses/agent-hub/budget-continuation.ts +13 -0
  222. package/.versions/2.0.18/.pi/harnesses/agent-hub/budget-recovery.ts +214 -0
  223. package/.versions/2.0.18/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  224. package/.versions/2.0.18/.pi/harnesses/agent-hub/capability-packs.ts +184 -0
  225. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agent-model-thinking.ts +10 -0
  226. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agent-model.ts +10 -0
  227. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agent-models-substitute.ts +10 -0
  228. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-add.ts +9 -0
  229. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-drop.ts +9 -0
  230. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-history.ts +9 -0
  231. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-kill.ts +10 -0
  232. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-list.ts +9 -0
  233. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-restart.ts +10 -0
  234. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-save.ts +9 -0
  235. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/agents-team.ts +9 -0
  236. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/audit.ts +9 -0
  237. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/budget-continue.ts +10 -0
  238. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/compound.ts +9 -0
  239. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/coms.ts +9 -0
  240. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/context-command.ts +9 -0
  241. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/context.ts +47 -0
  242. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/debate.ts +9 -0
  243. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/dispatch-policy.ts +9 -0
  244. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/handoff.ts +10 -0
  245. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/hub-report.ts +9 -0
  246. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/models.ts +10 -0
  247. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/poll.ts +9 -0
  248. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/recover.ts +61 -0
  249. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/retry.ts +10 -0
  250. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/task-triage-recover.ts +12 -0
  251. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/task-triage-waive.ts +12 -0
  252. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/watchdog.ts +9 -0
  253. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/work-mode.ts +29 -0
  254. package/.versions/2.0.18/.pi/harnesses/agent-hub/commands/zoom.ts +10 -0
  255. package/.versions/2.0.18/.pi/harnesses/agent-hub/config/agents.ts +178 -0
  256. package/.versions/2.0.18/.pi/harnesses/agent-hub/config/model-profiles.ts +236 -0
  257. package/.versions/2.0.18/.pi/harnesses/agent-hub/config/overrides.ts +165 -0
  258. package/.versions/2.0.18/.pi/harnesses/agent-hub/context/agent-state.ts +30 -0
  259. package/.versions/2.0.18/.pi/harnesses/agent-hub/context/assertions-artifacts.ts +221 -0
  260. package/.versions/2.0.18/.pi/harnesses/agent-hub/context/budgets.ts +206 -0
  261. package/.versions/2.0.18/.pi/harnesses/agent-hub/context/hub-state.ts +40 -0
  262. package/.versions/2.0.18/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  263. package/.versions/2.0.18/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  264. package/.versions/2.0.18/.pi/harnesses/agent-hub/context-window.js +108 -0
  265. package/.versions/2.0.18/.pi/harnesses/agent-hub/debate-command.ts +176 -0
  266. package/.versions/2.0.18/.pi/harnesses/agent-hub/delegate.ts +478 -0
  267. package/.versions/2.0.18/.pi/harnesses/agent-hub/deterministic-fs.ts +169 -0
  268. package/.versions/2.0.18/.pi/harnesses/agent-hub/diagnostic-probe-extension.ts +26 -0
  269. package/.versions/2.0.18/.pi/harnesses/agent-hub/diagnostic-series-budget.ts +178 -0
  270. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-coms.ts +252 -0
  271. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-core.ts +27 -0
  272. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-native-complete.ts +173 -0
  273. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-native-prepare.ts +270 -0
  274. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-native-spawn.ts +233 -0
  275. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-native-types.ts +267 -0
  276. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-native.ts +234 -0
  277. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-observability.ts +225 -0
  278. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-triage-contract.ts +27 -0
  279. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-triage-eval.ts +77 -0
  280. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-triage-policy.ts +29 -0
  281. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-triage-runtime.ts +55 -0
  282. package/.versions/2.0.18/.pi/harnesses/agent-hub/dispatch-triage-state.ts +33 -0
  283. package/.versions/2.0.18/.pi/harnesses/agent-hub/docs-lane.js +123 -0
  284. package/.versions/2.0.18/.pi/harnesses/agent-hub/drift-judge.ts +352 -0
  285. package/.versions/2.0.18/.pi/harnesses/agent-hub/drift-runtime.ts +480 -0
  286. package/.versions/2.0.18/.pi/harnesses/agent-hub/drift-system1-policy.ts +39 -0
  287. package/.versions/2.0.18/.pi/harnesses/agent-hub/drift-system1.ts +469 -0
  288. package/.versions/2.0.18/.pi/harnesses/agent-hub/drift-watchdog.js +349 -0
  289. package/.versions/2.0.18/.pi/harnesses/agent-hub/evidence-manifest.ts +51 -0
  290. package/.versions/2.0.18/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  291. package/.versions/2.0.18/.pi/harnesses/agent-hub/execution-evidence.ts +80 -0
  292. package/.versions/2.0.18/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  293. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/adapters.ts +82 -0
  294. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/broker-client.ts +56 -0
  295. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/broker.ts +125 -0
  296. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/child-extension.ts +33 -0
  297. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/descendant.ts +63 -0
  298. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/discovery-worker.mjs +15 -0
  299. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/discovery.ts +126 -0
  300. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/evaluate.ts +48 -0
  301. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/hub.ts +152 -0
  302. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/native-context.ts +8 -0
  303. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/native-fixture.test-support.ts +99 -0
  304. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/owners.ts +96 -0
  305. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/results.ts +54 -0
  306. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/runtime.ts +120 -0
  307. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/sources.ts +69 -0
  308. package/.versions/2.0.18/.pi/harnesses/agent-hub/file-discovery/state.ts +22 -0
  309. package/.versions/2.0.18/.pi/harnesses/agent-hub/filesystem-tool.ts +185 -0
  310. package/.versions/2.0.18/.pi/harnesses/agent-hub/fixtures/registration-surface.json +65 -0
  311. package/.versions/2.0.18/.pi/harnesses/agent-hub/fixtures/t0a-synthetic/catalog.ts +189 -0
  312. package/.versions/2.0.18/.pi/harnesses/agent-hub/footer.ts +30 -0
  313. package/.versions/2.0.18/.pi/harnesses/agent-hub/helpers.ts +270 -0
  314. package/.versions/2.0.18/.pi/harnesses/agent-hub/hub-state-audit.js +65 -0
  315. package/.versions/2.0.18/.pi/harnesses/agent-hub/index.ts +2625 -0
  316. package/.versions/2.0.18/.pi/harnesses/agent-hub/input/completions.ts +82 -0
  317. package/.versions/2.0.18/.pi/harnesses/agent-hub/input/shortcuts.ts +20 -0
  318. package/.versions/2.0.18/.pi/harnesses/agent-hub/lifecycle/context-pressure.ts +133 -0
  319. package/.versions/2.0.18/.pi/harnesses/agent-hub/lifecycle/monitor-session.ts +104 -0
  320. package/.versions/2.0.18/.pi/harnesses/agent-hub/lifecycle/session-orchestration.ts +144 -0
  321. package/.versions/2.0.18/.pi/harnesses/agent-hub/lifecycle/turn-handlers.ts +74 -0
  322. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  323. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  324. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  325. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  326. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  327. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  328. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  329. package/.versions/2.0.18/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  330. package/.versions/2.0.18/.pi/harnesses/agent-hub/no-progress.ts +593 -0
  331. package/.versions/2.0.18/.pi/harnesses/agent-hub/orchestration-activation.ts +112 -0
  332. package/.versions/2.0.18/.pi/harnesses/agent-hub/orchestration-metrics.ts +78 -0
  333. package/.versions/2.0.18/.pi/harnesses/agent-hub/orchestration-route.ts +76 -0
  334. package/.versions/2.0.18/.pi/harnesses/agent-hub/package.json +7 -0
  335. package/.versions/2.0.18/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  336. package/.versions/2.0.18/.pi/harnesses/agent-hub/policy/models.ts +153 -0
  337. package/.versions/2.0.18/.pi/harnesses/agent-hub/policy/profile-activation.ts +62 -0
  338. package/.versions/2.0.18/.pi/harnesses/agent-hub/policy/profile-runtime.ts +120 -0
  339. package/.versions/2.0.18/.pi/harnesses/agent-hub/policy/roster.ts +94 -0
  340. package/.versions/2.0.18/.pi/harnesses/agent-hub/policy/work-mode.ts +137 -0
  341. package/.versions/2.0.18/.pi/harnesses/agent-hub/poll-command.ts +176 -0
  342. package/.versions/2.0.18/.pi/harnesses/agent-hub/presentation.ts +48 -0
  343. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-config.ts +21 -0
  344. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-evaluate.ts +138 -0
  345. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-external-git.ts +59 -0
  346. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-external.ts +77 -0
  347. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-feedback.ts +104 -0
  348. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-findings.ts +115 -0
  349. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-local.ts +89 -0
  350. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-observer.ts +106 -0
  351. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-rules.ts +171 -0
  352. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-runtime.ts +318 -0
  353. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-selection.ts +68 -0
  354. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-snapshot-worker.mjs +12 -0
  355. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-snapshot.ts +258 -0
  356. package/.versions/2.0.18/.pi/harnesses/agent-hub/proactive-types.ts +67 -0
  357. package/.versions/2.0.18/.pi/harnesses/agent-hub/process-obligations.ts +158 -0
  358. package/.versions/2.0.18/.pi/harnesses/agent-hub/prompts/context.ts +56 -0
  359. package/.versions/2.0.18/.pi/harnesses/agent-hub/prompts/fragments.ts +95 -0
  360. package/.versions/2.0.18/.pi/harnesses/agent-hub/prompts/session-start.ts +90 -0
  361. package/.versions/2.0.18/.pi/harnesses/agent-hub/prompts/system-prompt.ts +125 -0
  362. package/.versions/2.0.18/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  363. package/.versions/2.0.18/.pi/harnesses/agent-hub/reconcile.ts +26 -0
  364. package/.versions/2.0.18/.pi/harnesses/agent-hub/recover-policy.ts +44 -0
  365. package/.versions/2.0.18/.pi/harnesses/agent-hub/recover-state.ts +104 -0
  366. package/.versions/2.0.18/.pi/harnesses/agent-hub/recovery-contract.ts +150 -0
  367. package/.versions/2.0.18/.pi/harnesses/agent-hub/rerun-policy.ts +40 -0
  368. package/.versions/2.0.18/.pi/harnesses/agent-hub/research/controls.ts +74 -0
  369. package/.versions/2.0.18/.pi/harnesses/agent-hub/research/runtime.ts +201 -0
  370. package/.versions/2.0.18/.pi/harnesses/agent-hub/research/spawn-run.ts +194 -0
  371. package/.versions/2.0.18/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  372. package/.versions/2.0.18/.pi/harnesses/agent-hub/return-contract.js +349 -0
  373. package/.versions/2.0.18/.pi/harnesses/agent-hub/return-extract.js +77 -0
  374. package/.versions/2.0.18/.pi/harnesses/agent-hub/review-closure.ts +43 -0
  375. package/.versions/2.0.18/.pi/harnesses/agent-hub/review-findings.js +104 -0
  376. package/.versions/2.0.18/.pi/harnesses/agent-hub/routing-observation.ts +41 -0
  377. package/.versions/2.0.18/.pi/harnesses/agent-hub/routing-proposal.ts +46 -0
  378. package/.versions/2.0.18/.pi/harnesses/agent-hub/run-budget.js +554 -0
  379. package/.versions/2.0.18/.pi/harnesses/agent-hub/run-namespace.js +93 -0
  380. package/.versions/2.0.18/.pi/harnesses/agent-hub/runtime-test-check.ts +54 -0
  381. package/.versions/2.0.18/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  382. package/.versions/2.0.18/.pi/harnesses/agent-hub/scope-gate.js +144 -0
  383. package/.versions/2.0.18/.pi/harnesses/agent-hub/session-audit.ts +313 -0
  384. package/.versions/2.0.18/.pi/harnesses/agent-hub/session-health.js +110 -0
  385. package/.versions/2.0.18/.pi/harnesses/agent-hub/session-start.ts +42 -0
  386. package/.versions/2.0.18/.pi/harnesses/agent-hub/spawn.ts +563 -0
  387. package/.versions/2.0.18/.pi/harnesses/agent-hub/system1-activity.ts +625 -0
  388. package/.versions/2.0.18/.pi/harnesses/agent-hub/system1-communication-store.ts +190 -0
  389. package/.versions/2.0.18/.pi/harnesses/agent-hub/system1-report.ts +275 -0
  390. package/.versions/2.0.18/.pi/harnesses/agent-hub/system1-runtime.ts +258 -0
  391. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-resume-contract.ts +70 -0
  392. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-authorization.ts +122 -0
  393. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-config.ts +29 -0
  394. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-contract.ts +14 -0
  395. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-live-stage-boundary.mjs +49 -0
  396. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-obligations.ts +104 -0
  397. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-policy.ts +16 -0
  398. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-review-contract.mjs +43 -0
  399. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-reviewer-only-contract.mjs +156 -0
  400. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-reviewer-only-diagnostics.mjs +112 -0
  401. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-runtime.ts +125 -0
  402. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-stage-guard.ts +21 -0
  403. package/.versions/2.0.18/.pi/harnesses/agent-hub/task-triage-state.ts +46 -0
  404. package/.versions/2.0.18/.pi/harnesses/agent-hub/timeline.ts +72 -0
  405. package/.versions/2.0.18/.pi/harnesses/agent-hub/tool-catalog-runtime.ts +68 -0
  406. package/.versions/2.0.18/.pi/harnesses/agent-hub/tool-catalog-state.ts +123 -0
  407. package/.versions/2.0.18/.pi/harnesses/agent-hub/tool-protocol.ts +134 -0
  408. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/action-executors.ts +213 -0
  409. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/ask-system1-files.ts +15 -0
  410. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/ask-system1.ts +25 -0
  411. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/coms-tools.ts +139 -0
  412. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/context.ts +144 -0
  413. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/dispatch-agent.ts +88 -0
  414. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/dispatch-execution.ts +560 -0
  415. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/dispatch-triage.ts +16 -0
  416. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/execution-orchestration.ts +22 -0
  417. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/fleet-tools.ts +200 -0
  418. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/herdr-executors.ts +95 -0
  419. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/run-flow.ts +136 -0
  420. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/set-task-tier.ts +31 -0
  421. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/spawn-research.ts +67 -0
  422. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/team-adjust.ts +29 -0
  423. package/.versions/2.0.18/.pi/harnesses/agent-hub/tools/verification-contract.ts +80 -0
  424. package/.versions/2.0.18/.pi/harnesses/agent-hub/tsconfig.json +22 -0
  425. package/.versions/2.0.18/.pi/harnesses/agent-hub/types.ts +66 -0
  426. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/activity-dots.ts +25 -0
  427. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/context-budget.ts +87 -0
  428. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/detail-panel.ts +192 -0
  429. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/fleet-actions.ts +78 -0
  430. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/fleet-dashboard.ts +155 -0
  431. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/fleet-editor.ts +44 -0
  432. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/fleet-source.ts +179 -0
  433. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/grid.ts +159 -0
  434. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/history-store.ts +137 -0
  435. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/history.ts +234 -0
  436. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/pool.ts +103 -0
  437. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/running-strip.ts +2 -0
  438. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/system1-communication.ts +59 -0
  439. package/.versions/2.0.18/.pi/harnesses/agent-hub/ui/zoom.ts +206 -0
  440. package/.versions/2.0.18/.pi/harnesses/agent-hub/unknown-tool-counter.ts +116 -0
  441. package/.versions/2.0.18/.pi/harnesses/agent-hub/version.ts +42 -0
  442. package/.versions/2.0.18/.pi/harnesses/agent-hub/watchdog-evaluation.ts +110 -0
  443. package/.versions/2.0.18/.pi/harnesses/agent-hub/work-mode-controls.ts +56 -0
  444. package/.versions/2.0.18/.pi/harnesses/agent-hub/work-mode.ts +187 -0
  445. package/.versions/2.0.18/.pi/harnesses/agent-hub/write-isolation.ts +187 -0
  446. package/.versions/2.0.18/.pi/harnesses/ask-user-remote/README.md +59 -0
  447. package/.versions/2.0.18/.pi/harnesses/ask-user-remote/index.ts +558 -0
  448. package/.versions/2.0.18/.pi/harnesses/ask-user-remote/questions.ts +161 -0
  449. package/.versions/2.0.18/.pi/harnesses/ask-user-remote/race-core.js +124 -0
  450. package/.versions/2.0.18/.pi/harnesses/ask-user-remote/runtime-ask.ts +68 -0
  451. package/.versions/2.0.18/.pi/harnesses/coms/README.md +100 -0
  452. package/.versions/2.0.18/.pi/harnesses/coms/index.ts +282 -0
  453. package/.versions/2.0.18/.pi/harnesses/coms/package.json +7 -0
  454. package/.versions/2.0.18/.pi/harnesses/coms/version.ts +42 -0
  455. package/.versions/2.0.18/.pi/harnesses/damage-control-continue/README.md +135 -0
  456. package/.versions/2.0.18/.pi/harnesses/damage-control-continue/index.ts +533 -0
  457. package/.versions/2.0.18/.pi/harnesses/damage-control-continue/package.json +7 -0
  458. package/.versions/2.0.18/.pi/harnesses/damage-control-continue/version.ts +42 -0
  459. package/.versions/2.0.18/.pi/harnesses/lib/changed-file-diagnostics.ts +642 -0
  460. package/.versions/2.0.18/.pi/harnesses/lib/coms-core-io.ts +385 -0
  461. package/.versions/2.0.18/.pi/harnesses/lib/coms-core.ts +577 -0
  462. package/.versions/2.0.18/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  463. package/.versions/2.0.18/.pi/harnesses/lib/context-budget-child-prompt.ts +220 -0
  464. package/.versions/2.0.18/.pi/harnesses/lib/context-budget-hub-prompt.ts +121 -0
  465. package/.versions/2.0.18/.pi/harnesses/lib/context-budget-view.ts +107 -0
  466. package/.versions/2.0.18/.pi/harnesses/lib/context-budget.ts +114 -0
  467. package/.versions/2.0.18/.pi/harnesses/lib/damage-control-shared.ts +226 -0
  468. package/.versions/2.0.18/.pi/harnesses/lib/deterministic-handle-path.ts +25 -0
  469. package/.versions/2.0.18/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  470. package/.versions/2.0.18/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  471. package/.versions/2.0.18/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  472. package/.versions/2.0.18/.pi/harnesses/lib/fleet-dashboard-ops.ts +178 -0
  473. package/.versions/2.0.18/.pi/harnesses/lib/fleet-dashboard-view.ts +172 -0
  474. package/.versions/2.0.18/.pi/harnesses/lib/fleet-detail-view.ts +339 -0
  475. package/.versions/2.0.18/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  476. package/.versions/2.0.18/.pi/harnesses/lib/fleet-panel.ts +34 -0
  477. package/.versions/2.0.18/.pi/harnesses/lib/fleet-read-model.ts +609 -0
  478. package/.versions/2.0.18/.pi/harnesses/lib/fleet-selection.ts +24 -0
  479. package/.versions/2.0.18/.pi/harnesses/lib/fleet-strip-controller.ts +75 -0
  480. package/.versions/2.0.18/.pi/harnesses/lib/fleet-strip-view.ts +179 -0
  481. package/.versions/2.0.18/.pi/harnesses/lib/fleet-transcript-store.ts +244 -0
  482. package/.versions/2.0.18/.pi/harnesses/lib/herdr-client.ts +472 -0
  483. package/.versions/2.0.18/.pi/harnesses/lib/herdr-presence.ts +399 -0
  484. package/.versions/2.0.18/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  485. package/.versions/2.0.18/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  486. package/.versions/2.0.18/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  487. package/.versions/2.0.18/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  488. package/.versions/2.0.18/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  489. package/.versions/2.0.18/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  490. package/.versions/2.0.18/.pi/harnesses/lib/policy-roots.ts +142 -0
  491. package/.versions/2.0.18/.pi/harnesses/lib/safe-source-read.js +29 -0
  492. package/.versions/2.0.18/.pi/harnesses/lib/spawned-peers.js +191 -0
  493. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-agentic.js +15 -0
  494. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-file-discovery.js +21 -0
  495. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-json.js +37 -0
  496. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-loader.js +44 -0
  497. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-proactive.js +68 -0
  498. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-triage.js +42 -0
  499. package/.versions/2.0.18/.pi/harnesses/lib/system1/config-v2.js +106 -0
  500. package/.versions/2.0.18/.pi/harnesses/lib/system1/config.js +50 -0
  501. package/.versions/2.0.18/.pi/harnesses/lib/system1/contracts.ts +154 -0
  502. package/.versions/2.0.18/.pi/harnesses/lib/system1/demo.ts +95 -0
  503. package/.versions/2.0.18/.pi/harnesses/lib/system1/jev.ts +503 -0
  504. package/.versions/2.0.18/.pi/harnesses/lib/system1/selection.js +11 -0
  505. package/.versions/2.0.18/.pi/harnesses/lib/system1/service.ts +245 -0
  506. package/.versions/2.0.18/.pi/harnesses/lib/update-check.ts +222 -0
  507. package/.versions/2.0.18/.pi/harnesses/package-lock.json +2039 -0
  508. package/.versions/2.0.18/.pi/harnesses/package.json +10 -0
  509. package/.versions/2.0.18/.pi/prompts/af-build.md +27 -0
  510. package/.versions/2.0.18/.pi/prompts/af-code-simplify.md +22 -0
  511. package/.versions/2.0.18/.pi/prompts/af-constraints.md +31 -0
  512. package/.versions/2.0.18/.pi/prompts/af-plan.md +17 -0
  513. package/.versions/2.0.18/.pi/prompts/af-review.md +16 -0
  514. package/.versions/2.0.18/.pi/prompts/af-set-hermes-telegram.md +15 -0
  515. package/.versions/2.0.18/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  516. package/.versions/2.0.18/.pi/prompts/af-setup-rules.md +20 -0
  517. package/.versions/2.0.18/.pi/prompts/af-ship.md +17 -0
  518. package/.versions/2.0.18/.pi/prompts/af-spec.md +15 -0
  519. package/.versions/2.0.18/.pi/prompts/af-test.md +19 -0
  520. package/.versions/2.0.18/.pi/skills/bowser/SKILL.md +145 -0
  521. package/.versions/2.0.18/.version +1 -0
  522. package/.versions/2.0.18/agents/architect.md +24 -0
  523. package/.versions/2.0.18/agents/bowser.md +28 -0
  524. package/.versions/2.0.18/agents/builder.md +55 -0
  525. package/.versions/2.0.18/agents/code-reviewer.md +209 -0
  526. package/.versions/2.0.18/agents/deep-researcher.md +32 -0
  527. package/.versions/2.0.18/agents/documenter.md +22 -0
  528. package/.versions/2.0.18/agents/orchestrator.md +22 -0
  529. package/.versions/2.0.18/agents/plan-reviewer.md +83 -0
  530. package/.versions/2.0.18/agents/planner.md +105 -0
  531. package/.versions/2.0.18/agents/releaser.md +24 -0
  532. package/.versions/2.0.18/agents/researcher.md +30 -0
  533. package/.versions/2.0.18/agents/security-auditor.md +167 -0
  534. package/.versions/2.0.18/agents/test-engineer.md +153 -0
  535. package/.versions/2.0.18/agents/web-debugger.md +44 -0
  536. package/.versions/2.0.18/agents/web-performance-auditor.md +194 -0
  537. package/.versions/2.0.18/bin/catalog/harness-runtime-closure.json +73 -0
  538. package/.versions/2.0.18/codex/fleet-session-client/SKILL.md +34 -0
  539. package/.versions/2.0.18/codex/fleet-session-client.zip +0 -0
  540. package/.versions/2.0.18/docs/ARCHITECTURE.md +874 -0
  541. package/.versions/2.0.18/docs/agent-fleet-setup.md +1101 -0
  542. package/.versions/2.0.18/docs/claude-code-coms-bridge.md +147 -0
  543. package/.versions/2.0.18/docs/codex-session-bridge.md +219 -0
  544. package/.versions/2.0.18/docs/coms-hermes-bridge.md +188 -0
  545. package/.versions/2.0.18/docs/getting-started.md +126 -0
  546. package/.versions/2.0.18/docs/npm-install.md +535 -0
  547. package/.versions/2.0.18/docs/pi-extensions.md +454 -0
  548. package/.versions/2.0.18/docs/pi-setup.md +92 -0
  549. package/.versions/2.0.18/docs/skill-anatomy.md +150 -0
  550. package/.versions/2.0.18/install-manifest.json +3193 -0
  551. package/.versions/2.0.18/justfile +247 -0
  552. package/.versions/2.0.18/manifest-meta.json +1071 -0
  553. package/.versions/2.0.18/references/accessibility-checklist.md +160 -0
  554. package/.versions/2.0.18/references/communication-contract.md +26 -0
  555. package/.versions/2.0.18/references/definition-of-done.md +67 -0
  556. package/.versions/2.0.18/references/fleet-coordination-patterns.md +171 -0
  557. package/.versions/2.0.18/references/observability-checklist.md +92 -0
  558. package/.versions/2.0.18/references/orchestration-patterns.md +370 -0
  559. package/.versions/2.0.18/references/performance-checklist.md +236 -0
  560. package/.versions/2.0.18/references/prompting-patterns.md +380 -0
  561. package/.versions/2.0.18/references/security-checklist.md +245 -0
  562. package/.versions/2.0.18/references/testing-patterns.md +235 -0
  563. package/.versions/2.0.18/references/workflow-authoring.md +304 -0
  564. package/.versions/2.0.18/skills/_internal/grilling.md +59 -0
  565. package/.versions/2.0.18/skills/browser-testing-with-devtools/SKILL.md +351 -0
  566. package/.versions/2.0.18/skills/code-review-and-quality/SKILL.md +396 -0
  567. package/.versions/2.0.18/skills/compound-learning/SKILL.md +137 -0
  568. package/.versions/2.0.18/skills/constraint-driven-development/SKILL.md +338 -0
  569. package/.versions/2.0.18/skills/constraint-driven-development/references/floor-guard.md +99 -0
  570. package/.versions/2.0.18/skills/context-engineering/SKILL.md +341 -0
  571. package/.versions/2.0.18/skills/deprecation-and-migration/SKILL.md +247 -0
  572. package/.versions/2.0.18/skills/designing-agents/SKILL.md +394 -0
  573. package/.versions/2.0.18/skills/designing-agents/pi-harness-authoring.md +222 -0
  574. package/.versions/2.0.18/skills/drafting-workflows/SKILL.md +143 -0
  575. package/.versions/2.0.18/skills/drafting-workflows/scripts/make-workflow.ts +177 -0
  576. package/.versions/2.0.18/skills/frontend-ui-engineering/SKILL.md +328 -0
  577. package/.versions/2.0.18/skills/git-workflow-and-versioning/SKILL.md +316 -0
  578. package/.versions/2.0.18/skills/idea-refine/SKILL.md +182 -0
  579. package/.versions/2.0.18/skills/idea-refine/examples.md +238 -0
  580. package/.versions/2.0.18/skills/idea-refine/frameworks.md +99 -0
  581. package/.versions/2.0.18/skills/idea-refine/refinement-criteria.md +113 -0
  582. package/.versions/2.0.18/skills/idea-refine/scripts/idea-refine.sh +15 -0
  583. package/.versions/2.0.18/skills/incremental-implementation/SKILL.md +353 -0
  584. package/.versions/2.0.18/skills/interview-me/SKILL.md +226 -0
  585. package/.versions/2.0.18/skills/orchestration-verification/SKILL.md +182 -0
  586. package/.versions/2.0.18/skills/peer-coms/SKILL.md +90 -0
  587. package/.versions/2.0.18/skills/performance-optimization/SKILL.md +496 -0
  588. package/.versions/2.0.18/skills/planning-and-task-breakdown/SKILL.md +318 -0
  589. package/.versions/2.0.18/skills/repository-ai-setup/SKILL.md +135 -0
  590. package/.versions/2.0.18/skills/repository-ai-setup/references/agent-fleet-ai-state.template.json +4 -0
  591. package/.versions/2.0.18/skills/repository-ai-setup/references/apply-contract.md +74 -0
  592. package/.versions/2.0.18/skills/repository-ai-setup/references/provenance-template.md +16 -0
  593. package/.versions/2.0.18/skills/repository-ai-setup/references/setup-flow.md +108 -0
  594. package/.versions/2.0.18/skills/repository-ai-setup/references/verify-setup.md +20 -0
  595. package/.versions/2.0.18/skills/repository-ai-setup.zip +0 -0
  596. package/.versions/2.0.18/skills/security-and-hardening/SKILL.md +524 -0
  597. package/.versions/2.0.18/skills/spec-driven-development/SKILL.md +295 -0
  598. package/.versions/2.0.18/skills/using-agent-skills/SKILL.md +198 -0
  599. package/.versions/2.0.18/vendor/agent-skills-upstream/LICENSE +21 -0
  600. package/.versions/2.0.18/vendor/agent-skills-upstream/README.md +430 -0
  601. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +367 -0
  602. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  603. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  604. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  605. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  606. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/constraint-driven-development/SKILL.md +311 -0
  607. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/constraint-driven-development/references/floor-guard.md +99 -0
  608. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +337 -0
  609. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  610. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  611. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +288 -0
  612. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  613. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  614. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  615. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  616. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  617. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  618. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  619. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  620. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  621. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  622. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +238 -0
  623. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +496 -0
  624. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +257 -0
  625. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +524 -0
  626. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +330 -0
  627. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +216 -0
  628. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +245 -0
  629. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +398 -0
  630. package/.versions/2.0.18/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +192 -0
  631. package/.versions/2.0.19/.pi/agent-fleet/hermes/README.md +347 -0
  632. package/.versions/2.0.19/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  633. package/.versions/2.0.19/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  634. package/.versions/2.0.19/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  635. package/.versions/2.0.19/.pi/agent-fleet/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  636. package/.versions/2.0.19/.pi/agent-fleet/hermes/gates/gate-o-capability.md +8 -0
  637. package/.versions/2.0.19/.pi/agent-fleet/hermes/gates/gate-o-validator-fixtures.json +1 -0
  638. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +773 -0
  639. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  640. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  641. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  642. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  643. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  644. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  645. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  646. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  647. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  648. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  649. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  650. package/.versions/2.0.19/.pi/agent-fleet/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  651. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-conductor/SKILL.md +84 -0
  652. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-liaison/SKILL.md +84 -0
  653. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/SKILL.md +76 -0
  654. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/manifest.json +1 -0
  655. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  656. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  657. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  658. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  659. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  660. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  661. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  662. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  663. package/.versions/2.0.19/.pi/agent-fleet/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  664. package/.versions/2.0.19/.pi/agent-fleet/hermes/watchdog-tests/__init__.py +0 -0
  665. package/.versions/2.0.19/.pi/agent-fleet/hooks/coms-stop-hook.mjs +84 -0
  666. package/.versions/2.0.19/.pi/agent-fleet/scripts/claude-code-preflight.ts +70 -0
  667. package/.versions/2.0.19/.pi/agent-fleet/scripts/coms-claude-bridge.ts +437 -0
  668. package/.versions/2.0.19/.pi/agent-fleet/scripts/coms-cli.ts +425 -0
  669. package/.versions/2.0.19/.pi/agent-fleet/scripts/coms-hermes-bridge.ts +413 -0
  670. package/.versions/2.0.19/.pi/agent-fleet/scripts/fleet-codex-client.ts +69 -0
  671. package/.versions/2.0.19/.pi/agent-fleet/scripts/fleet-codex-read.py +148 -0
  672. package/.versions/2.0.19/.pi/agent-fleet/scripts/fleet.ts +217 -0
  673. package/.versions/2.0.19/.pi/agent-fleet/scripts/flow.ts +157 -0
  674. package/.versions/2.0.19/.pi/agent-fleet/scripts/hermes-monitor-capability-runner.ts +25 -0
  675. package/.versions/2.0.19/.pi/agent-fleet/scripts/hermes-monitor-scenario.ts +474 -0
  676. package/.versions/2.0.19/.pi/agent-fleet/scripts/hermes-watchdog-capability-probe.ts +45 -0
  677. package/.versions/2.0.19/.pi/agent-fleet/scripts/install-hermes-plugin.sh +180 -0
  678. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/claude-bridge-core.ts +208 -0
  679. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/coms-envelope.ts +582 -0
  680. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/fake-herdr-server.ts +88 -0
  681. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/fleet-codex-catalog.ts +63 -0
  682. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/fleet-codex-operations.ts +190 -0
  683. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/fleet-codex-session.ts +166 -0
  684. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/fleet-codex-transport.ts +124 -0
  685. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/fleet-command.ts +252 -0
  686. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/flow-command.ts +98 -0
  687. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/flow-maintenance.ts +230 -0
  688. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/herdr-layout.ts +281 -0
  689. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-bridge-core.ts +241 -0
  690. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-monitor-events.ts +1 -0
  691. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-monitor-herdr.ts +2 -0
  692. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-monitor-model.ts +3 -0
  693. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-monitor-registry.ts +2 -0
  694. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-monitor-socket.ts +2 -0
  695. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/hermes-monitor-store.ts +2 -0
  696. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/monitor-env.ts +146 -0
  697. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/peer-launch.ts +318 -0
  698. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/persona-banner.ts +62 -0
  699. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/persona-dirs.ts +25 -0
  700. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/runtime-dependencies.js +124 -0
  701. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/spawn-stagger.ts +101 -0
  702. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/team-project.ts +178 -0
  703. package/.versions/2.0.19/.pi/agent-fleet/scripts/lib/team-snapshot.ts +147 -0
  704. package/.versions/2.0.19/.pi/agent-fleet/scripts/package-lock.json +35 -0
  705. package/.versions/2.0.19/.pi/agent-fleet/scripts/package.json +9 -0
  706. package/.versions/2.0.19/.pi/agent-fleet/scripts/peer-banner.ts +41 -0
  707. package/.versions/2.0.19/.pi/agent-fleet/scripts/peer-launch.ts +283 -0
  708. package/.versions/2.0.19/.pi/agent-fleet/scripts/team-snapshot.ts +237 -0
  709. package/.versions/2.0.19/.pi/agent-fleet/scripts/team-up.ts +378 -0
  710. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/agent-phase.ts +179 -0
  711. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/changes.ts +61 -0
  712. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/debate.ts +149 -0
  713. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/env.ts +34 -0
  714. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/envelopes.ts +169 -0
  715. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/gates.ts +81 -0
  716. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/git.ts +96 -0
  717. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/isolated-snapshot.ts +125 -0
  718. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/merge.ts +95 -0
  719. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/model-profile.ts +22 -0
  720. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/model-visibility.ts +92 -0
  721. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/permissions.ts +130 -0
  722. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/personas.ts +57 -0
  723. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/poll.ts +86 -0
  724. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/project-policy.ts +36 -0
  725. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/quality.ts +64 -0
  726. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/run.ts +108 -0
  727. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/scout-data-boundary.ts +55 -0
  728. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/trace.ts +34 -0
  729. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/voices.ts +128 -0
  730. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/lib/writer-lease.ts +112 -0
  731. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/tsconfig.json +22 -0
  732. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/wf-build-test.ts +61 -0
  733. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/wf-debate.ts +87 -0
  734. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/wf-document.ts +50 -0
  735. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/wf-poll.ts +95 -0
  736. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/wf-quality.ts +20 -0
  737. package/.versions/2.0.19/.pi/agent-fleet/scripts/workflows/wf-scout.ts +40 -0
  738. package/.versions/2.0.19/.pi/agents/dispatch-policy.yaml +32 -0
  739. package/.versions/2.0.19/.pi/agents/model-profiles.yaml +134 -0
  740. package/.versions/2.0.19/.pi/agents/peers.yaml +147 -0
  741. package/.versions/2.0.19/.pi/agents/teams.yaml +41 -0
  742. package/.versions/2.0.19/.pi/agents/voices.yaml +13 -0
  743. package/.versions/2.0.19/.pi/damage-control-rules.yaml +297 -0
  744. package/.versions/2.0.19/.pi/extensions/btw/README.md +120 -0
  745. package/.versions/2.0.19/.pi/extensions/btw/index.ts +914 -0
  746. package/.versions/2.0.19/.pi/extensions/btw/package.json +6 -0
  747. package/.versions/2.0.19/.pi/extensions/btw/state.js +179 -0
  748. package/.versions/2.0.19/.pi/extensions/chrome-devtools-mcp/README.md +55 -0
  749. package/.versions/2.0.19/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  750. package/.versions/2.0.19/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  751. package/.versions/2.0.19/.pi/extensions/compact-and-continue/README.md +42 -0
  752. package/.versions/2.0.19/.pi/extensions/compact-and-continue/index.ts +120 -0
  753. package/.versions/2.0.19/.pi/extensions/compact-and-continue/package.json +6 -0
  754. package/.versions/2.0.19/.pi/extensions/mcp-bridge/README.md +46 -0
  755. package/.versions/2.0.19/.pi/extensions/mcp-bridge/index.ts +206 -0
  756. package/.versions/2.0.19/.pi/extensions/mcp-bridge/package.json +6 -0
  757. package/.versions/2.0.19/.pi/extensions/package-lock.json +1175 -0
  758. package/.versions/2.0.19/.pi/extensions/package.json +9 -0
  759. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/README.md +224 -0
  760. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/config.ts +198 -0
  761. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  762. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/index.ts +248 -0
  763. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/package.json +6 -0
  764. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  765. package/.versions/2.0.19/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  766. package/.versions/2.0.19/.pi/harnesses/agent-hub/README.md +1483 -0
  767. package/.versions/2.0.19/.pi/harnesses/agent-hub/acceptance.ts +199 -0
  768. package/.versions/2.0.19/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  769. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-contract.ts +43 -0
  770. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-evidence.ts +64 -0
  771. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-hub.ts +54 -0
  772. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-runtime.ts +56 -0
  773. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-sources-worker.mjs +4 -0
  774. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-sources.ts +74 -0
  775. package/.versions/2.0.19/.pi/harnesses/agent-hub/agentic-state.ts +23 -0
  776. package/.versions/2.0.19/.pi/harnesses/agent-hub/artifacts.js +146 -0
  777. package/.versions/2.0.19/.pi/harnesses/agent-hub/assertion-ledger.js +67 -0
  778. package/.versions/2.0.19/.pi/harnesses/agent-hub/assist-profile.ts +16 -0
  779. package/.versions/2.0.19/.pi/harnesses/agent-hub/backend-policy.js +174 -0
  780. package/.versions/2.0.19/.pi/harnesses/agent-hub/bounded-output.ts +26 -0
  781. package/.versions/2.0.19/.pi/harnesses/agent-hub/budget-continuation.ts +13 -0
  782. package/.versions/2.0.19/.pi/harnesses/agent-hub/budget-recovery.ts +214 -0
  783. package/.versions/2.0.19/.pi/harnesses/agent-hub/capability-confirmation.ts +47 -0
  784. package/.versions/2.0.19/.pi/harnesses/agent-hub/capability-packs.ts +184 -0
  785. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agent-model-thinking.ts +10 -0
  786. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agent-model.ts +10 -0
  787. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agent-models-substitute.ts +10 -0
  788. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-add.ts +9 -0
  789. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-drop.ts +9 -0
  790. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-history.ts +9 -0
  791. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-kill.ts +10 -0
  792. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-list.ts +9 -0
  793. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-restart.ts +10 -0
  794. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-save.ts +9 -0
  795. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/agents-team.ts +9 -0
  796. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/audit.ts +9 -0
  797. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/budget-continue.ts +10 -0
  798. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/compound.ts +9 -0
  799. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/coms.ts +9 -0
  800. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/context-command.ts +9 -0
  801. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/context.ts +47 -0
  802. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/debate.ts +9 -0
  803. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/dispatch-policy.ts +9 -0
  804. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/handoff.ts +10 -0
  805. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/hub-report.ts +9 -0
  806. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/models.ts +10 -0
  807. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/poll.ts +9 -0
  808. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/recover.ts +61 -0
  809. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/retry.ts +10 -0
  810. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/task-triage-recover.ts +12 -0
  811. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/task-triage-waive.ts +12 -0
  812. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/watchdog.ts +9 -0
  813. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/work-mode.ts +29 -0
  814. package/.versions/2.0.19/.pi/harnesses/agent-hub/commands/zoom.ts +10 -0
  815. package/.versions/2.0.19/.pi/harnesses/agent-hub/config/agents.ts +178 -0
  816. package/.versions/2.0.19/.pi/harnesses/agent-hub/config/model-profiles.ts +236 -0
  817. package/.versions/2.0.19/.pi/harnesses/agent-hub/config/overrides.ts +165 -0
  818. package/.versions/2.0.19/.pi/harnesses/agent-hub/context/agent-state.ts +30 -0
  819. package/.versions/2.0.19/.pi/harnesses/agent-hub/context/assertions-artifacts.ts +221 -0
  820. package/.versions/2.0.19/.pi/harnesses/agent-hub/context/budgets.ts +206 -0
  821. package/.versions/2.0.19/.pi/harnesses/agent-hub/context/hub-state.ts +40 -0
  822. package/.versions/2.0.19/.pi/harnesses/agent-hub/context-budget-snapshot.ts +105 -0
  823. package/.versions/2.0.19/.pi/harnesses/agent-hub/context-pressure.ts +191 -0
  824. package/.versions/2.0.19/.pi/harnesses/agent-hub/context-window.js +108 -0
  825. package/.versions/2.0.19/.pi/harnesses/agent-hub/debate-command.ts +176 -0
  826. package/.versions/2.0.19/.pi/harnesses/agent-hub/delegate.ts +478 -0
  827. package/.versions/2.0.19/.pi/harnesses/agent-hub/deterministic-fs.ts +169 -0
  828. package/.versions/2.0.19/.pi/harnesses/agent-hub/diagnostic-probe-extension.ts +26 -0
  829. package/.versions/2.0.19/.pi/harnesses/agent-hub/diagnostic-series-budget.ts +178 -0
  830. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-coms.ts +252 -0
  831. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-core.ts +27 -0
  832. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-native-complete.ts +173 -0
  833. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-native-prepare.ts +270 -0
  834. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-native-spawn.ts +233 -0
  835. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-native-types.ts +267 -0
  836. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-native.ts +234 -0
  837. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-observability.ts +225 -0
  838. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-triage-contract.ts +27 -0
  839. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-triage-eval.ts +77 -0
  840. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-triage-policy.ts +29 -0
  841. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-triage-runtime.ts +55 -0
  842. package/.versions/2.0.19/.pi/harnesses/agent-hub/dispatch-triage-state.ts +33 -0
  843. package/.versions/2.0.19/.pi/harnesses/agent-hub/docs-lane.js +123 -0
  844. package/.versions/2.0.19/.pi/harnesses/agent-hub/drift-judge.ts +352 -0
  845. package/.versions/2.0.19/.pi/harnesses/agent-hub/drift-runtime.ts +480 -0
  846. package/.versions/2.0.19/.pi/harnesses/agent-hub/drift-system1-policy.ts +39 -0
  847. package/.versions/2.0.19/.pi/harnesses/agent-hub/drift-system1.ts +469 -0
  848. package/.versions/2.0.19/.pi/harnesses/agent-hub/drift-watchdog.js +349 -0
  849. package/.versions/2.0.19/.pi/harnesses/agent-hub/evidence-manifest.ts +51 -0
  850. package/.versions/2.0.19/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  851. package/.versions/2.0.19/.pi/harnesses/agent-hub/execution-evidence.ts +80 -0
  852. package/.versions/2.0.19/.pi/harnesses/agent-hub/external-blocker.js +85 -0
  853. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/adapters.ts +82 -0
  854. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/broker-client.ts +56 -0
  855. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/broker.ts +125 -0
  856. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/child-extension.ts +33 -0
  857. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/descendant.ts +63 -0
  858. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/discovery-worker.mjs +15 -0
  859. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/discovery.ts +126 -0
  860. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/evaluate.ts +48 -0
  861. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/hub.ts +152 -0
  862. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/native-context.ts +8 -0
  863. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/native-fixture.test-support.ts +99 -0
  864. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/owners.ts +96 -0
  865. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/results.ts +54 -0
  866. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/runtime.ts +120 -0
  867. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/sources.ts +69 -0
  868. package/.versions/2.0.19/.pi/harnesses/agent-hub/file-discovery/state.ts +22 -0
  869. package/.versions/2.0.19/.pi/harnesses/agent-hub/filesystem-tool.ts +185 -0
  870. package/.versions/2.0.19/.pi/harnesses/agent-hub/fixtures/registration-surface.json +66 -0
  871. package/.versions/2.0.19/.pi/harnesses/agent-hub/fixtures/t0a-synthetic/catalog.ts +189 -0
  872. package/.versions/2.0.19/.pi/harnesses/agent-hub/footer.ts +30 -0
  873. package/.versions/2.0.19/.pi/harnesses/agent-hub/helpers.ts +270 -0
  874. package/.versions/2.0.19/.pi/harnesses/agent-hub/hub-state-audit.js +65 -0
  875. package/.versions/2.0.19/.pi/harnesses/agent-hub/index.ts +2625 -0
  876. package/.versions/2.0.19/.pi/harnesses/agent-hub/input/completions.ts +82 -0
  877. package/.versions/2.0.19/.pi/harnesses/agent-hub/input/shortcuts.ts +20 -0
  878. package/.versions/2.0.19/.pi/harnesses/agent-hub/lifecycle/context-pressure.ts +133 -0
  879. package/.versions/2.0.19/.pi/harnesses/agent-hub/lifecycle/monitor-session.ts +104 -0
  880. package/.versions/2.0.19/.pi/harnesses/agent-hub/lifecycle/session-orchestration.ts +144 -0
  881. package/.versions/2.0.19/.pi/harnesses/agent-hub/lifecycle/turn-handlers.ts +74 -0
  882. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  883. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  884. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  885. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  886. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  887. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  888. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  889. package/.versions/2.0.19/.pi/harnesses/agent-hub/monitor-session-bridge.ts +266 -0
  890. package/.versions/2.0.19/.pi/harnesses/agent-hub/no-progress.ts +593 -0
  891. package/.versions/2.0.19/.pi/harnesses/agent-hub/orchestration-activation.ts +112 -0
  892. package/.versions/2.0.19/.pi/harnesses/agent-hub/orchestration-metrics.ts +78 -0
  893. package/.versions/2.0.19/.pi/harnesses/agent-hub/orchestration-route.ts +76 -0
  894. package/.versions/2.0.19/.pi/harnesses/agent-hub/package.json +7 -0
  895. package/.versions/2.0.19/.pi/harnesses/agent-hub/peer-spawn-plan.ts +116 -0
  896. package/.versions/2.0.19/.pi/harnesses/agent-hub/policy/models.ts +153 -0
  897. package/.versions/2.0.19/.pi/harnesses/agent-hub/policy/profile-activation.ts +62 -0
  898. package/.versions/2.0.19/.pi/harnesses/agent-hub/policy/profile-runtime.ts +120 -0
  899. package/.versions/2.0.19/.pi/harnesses/agent-hub/policy/roster.ts +94 -0
  900. package/.versions/2.0.19/.pi/harnesses/agent-hub/policy/work-mode.ts +137 -0
  901. package/.versions/2.0.19/.pi/harnesses/agent-hub/poll-command.ts +176 -0
  902. package/.versions/2.0.19/.pi/harnesses/agent-hub/presentation.ts +48 -0
  903. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-config.ts +21 -0
  904. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-evaluate.ts +138 -0
  905. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-external-git.ts +82 -0
  906. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-external.ts +142 -0
  907. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-feedback.ts +104 -0
  908. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-findings.ts +115 -0
  909. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-local.ts +89 -0
  910. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-observer.ts +106 -0
  911. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-rules.ts +171 -0
  912. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-runtime.ts +318 -0
  913. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-selection.ts +68 -0
  914. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-snapshot-worker.mjs +12 -0
  915. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-snapshot.ts +271 -0
  916. package/.versions/2.0.19/.pi/harnesses/agent-hub/proactive-types.ts +67 -0
  917. package/.versions/2.0.19/.pi/harnesses/agent-hub/process-obligations.ts +158 -0
  918. package/.versions/2.0.19/.pi/harnesses/agent-hub/prompts/context.ts +56 -0
  919. package/.versions/2.0.19/.pi/harnesses/agent-hub/prompts/fragments.ts +95 -0
  920. package/.versions/2.0.19/.pi/harnesses/agent-hub/prompts/session-start.ts +90 -0
  921. package/.versions/2.0.19/.pi/harnesses/agent-hub/prompts/system-prompt.ts +125 -0
  922. package/.versions/2.0.19/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  923. package/.versions/2.0.19/.pi/harnesses/agent-hub/reconcile.ts +26 -0
  924. package/.versions/2.0.19/.pi/harnesses/agent-hub/recover-policy.ts +44 -0
  925. package/.versions/2.0.19/.pi/harnesses/agent-hub/recover-state.ts +104 -0
  926. package/.versions/2.0.19/.pi/harnesses/agent-hub/recovery-contract.ts +150 -0
  927. package/.versions/2.0.19/.pi/harnesses/agent-hub/rerun-policy.ts +40 -0
  928. package/.versions/2.0.19/.pi/harnesses/agent-hub/research/controls.ts +74 -0
  929. package/.versions/2.0.19/.pi/harnesses/agent-hub/research/runtime.ts +201 -0
  930. package/.versions/2.0.19/.pi/harnesses/agent-hub/research/spawn-run.ts +194 -0
  931. package/.versions/2.0.19/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  932. package/.versions/2.0.19/.pi/harnesses/agent-hub/return-contract.js +349 -0
  933. package/.versions/2.0.19/.pi/harnesses/agent-hub/return-extract.js +77 -0
  934. package/.versions/2.0.19/.pi/harnesses/agent-hub/review-closure.ts +43 -0
  935. package/.versions/2.0.19/.pi/harnesses/agent-hub/review-findings.js +104 -0
  936. package/.versions/2.0.19/.pi/harnesses/agent-hub/routing-observation.ts +41 -0
  937. package/.versions/2.0.19/.pi/harnesses/agent-hub/routing-proposal.ts +46 -0
  938. package/.versions/2.0.19/.pi/harnesses/agent-hub/run-budget.js +554 -0
  939. package/.versions/2.0.19/.pi/harnesses/agent-hub/run-namespace.js +93 -0
  940. package/.versions/2.0.19/.pi/harnesses/agent-hub/runtime-test-check.ts +54 -0
  941. package/.versions/2.0.19/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  942. package/.versions/2.0.19/.pi/harnesses/agent-hub/scope-gate.js +144 -0
  943. package/.versions/2.0.19/.pi/harnesses/agent-hub/session-audit.ts +313 -0
  944. package/.versions/2.0.19/.pi/harnesses/agent-hub/session-health.js +110 -0
  945. package/.versions/2.0.19/.pi/harnesses/agent-hub/session-start.ts +42 -0
  946. package/.versions/2.0.19/.pi/harnesses/agent-hub/spawn.ts +563 -0
  947. package/.versions/2.0.19/.pi/harnesses/agent-hub/system1-activity.ts +625 -0
  948. package/.versions/2.0.19/.pi/harnesses/agent-hub/system1-communication-store.ts +190 -0
  949. package/.versions/2.0.19/.pi/harnesses/agent-hub/system1-report.ts +275 -0
  950. package/.versions/2.0.19/.pi/harnesses/agent-hub/system1-runtime.ts +258 -0
  951. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-resume-contract.ts +70 -0
  952. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-authorization.ts +122 -0
  953. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-config.ts +29 -0
  954. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-contract.ts +14 -0
  955. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-live-stage-boundary.mjs +49 -0
  956. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-obligations.ts +104 -0
  957. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-policy.ts +16 -0
  958. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-review-contract.mjs +43 -0
  959. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-reviewer-only-contract.mjs +156 -0
  960. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-reviewer-only-diagnostics.mjs +112 -0
  961. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-runtime.ts +125 -0
  962. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-stage-guard.ts +21 -0
  963. package/.versions/2.0.19/.pi/harnesses/agent-hub/task-triage-state.ts +46 -0
  964. package/.versions/2.0.19/.pi/harnesses/agent-hub/timeline.ts +72 -0
  965. package/.versions/2.0.19/.pi/harnesses/agent-hub/tool-catalog-runtime.ts +68 -0
  966. package/.versions/2.0.19/.pi/harnesses/agent-hub/tool-catalog-state.ts +123 -0
  967. package/.versions/2.0.19/.pi/harnesses/agent-hub/tool-protocol.ts +134 -0
  968. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/action-executors.ts +213 -0
  969. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/ask-system1-files.ts +15 -0
  970. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/ask-system1.ts +25 -0
  971. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/coms-tools.ts +139 -0
  972. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/context.ts +144 -0
  973. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/dispatch-agent.ts +88 -0
  974. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/dispatch-execution.ts +560 -0
  975. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/dispatch-triage.ts +16 -0
  976. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/execution-orchestration.ts +22 -0
  977. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/fleet-tools.ts +200 -0
  978. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/herdr-executors.ts +95 -0
  979. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/run-flow.ts +136 -0
  980. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/set-task-tier.ts +31 -0
  981. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/spawn-research.ts +67 -0
  982. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/team-adjust.ts +29 -0
  983. package/.versions/2.0.19/.pi/harnesses/agent-hub/tools/verification-contract.ts +80 -0
  984. package/.versions/2.0.19/.pi/harnesses/agent-hub/tsconfig.json +22 -0
  985. package/.versions/2.0.19/.pi/harnesses/agent-hub/types.ts +66 -0
  986. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/activity-dots.ts +25 -0
  987. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/context-budget.ts +87 -0
  988. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/detail-panel.ts +192 -0
  989. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/fleet-actions.ts +78 -0
  990. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/fleet-dashboard.ts +155 -0
  991. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/fleet-editor.ts +44 -0
  992. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/fleet-source.ts +179 -0
  993. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/grid.ts +159 -0
  994. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/history-store.ts +137 -0
  995. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/history.ts +234 -0
  996. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/pool.ts +103 -0
  997. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/running-strip.ts +2 -0
  998. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/system1-communication.ts +59 -0
  999. package/.versions/2.0.19/.pi/harnesses/agent-hub/ui/zoom.ts +206 -0
  1000. package/.versions/2.0.19/.pi/harnesses/agent-hub/unknown-tool-counter.ts +116 -0
  1001. package/.versions/2.0.19/.pi/harnesses/agent-hub/version.ts +42 -0
  1002. package/.versions/2.0.19/.pi/harnesses/agent-hub/watchdog-evaluation.ts +110 -0
  1003. package/.versions/2.0.19/.pi/harnesses/agent-hub/work-mode-controls.ts +56 -0
  1004. package/.versions/2.0.19/.pi/harnesses/agent-hub/work-mode.ts +187 -0
  1005. package/.versions/2.0.19/.pi/harnesses/agent-hub/write-isolation.ts +187 -0
  1006. package/.versions/2.0.19/.pi/harnesses/ask-user-remote/README.md +59 -0
  1007. package/.versions/2.0.19/.pi/harnesses/ask-user-remote/index.ts +558 -0
  1008. package/.versions/2.0.19/.pi/harnesses/ask-user-remote/questions.ts +161 -0
  1009. package/.versions/2.0.19/.pi/harnesses/ask-user-remote/race-core.js +124 -0
  1010. package/.versions/2.0.19/.pi/harnesses/ask-user-remote/runtime-ask.ts +68 -0
  1011. package/.versions/2.0.19/.pi/harnesses/coms/README.md +100 -0
  1012. package/.versions/2.0.19/.pi/harnesses/coms/index.ts +282 -0
  1013. package/.versions/2.0.19/.pi/harnesses/coms/package.json +7 -0
  1014. package/.versions/2.0.19/.pi/harnesses/coms/version.ts +42 -0
  1015. package/.versions/2.0.19/.pi/harnesses/damage-control-continue/README.md +135 -0
  1016. package/.versions/2.0.19/.pi/harnesses/damage-control-continue/index.ts +533 -0
  1017. package/.versions/2.0.19/.pi/harnesses/damage-control-continue/package.json +7 -0
  1018. package/.versions/2.0.19/.pi/harnesses/damage-control-continue/version.ts +42 -0
  1019. package/.versions/2.0.19/.pi/harnesses/lib/changed-file-diagnostics.ts +642 -0
  1020. package/.versions/2.0.19/.pi/harnesses/lib/coms-core-io.ts +385 -0
  1021. package/.versions/2.0.19/.pi/harnesses/lib/coms-core.ts +577 -0
  1022. package/.versions/2.0.19/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  1023. package/.versions/2.0.19/.pi/harnesses/lib/context-budget-child-prompt.ts +220 -0
  1024. package/.versions/2.0.19/.pi/harnesses/lib/context-budget-hub-prompt.ts +121 -0
  1025. package/.versions/2.0.19/.pi/harnesses/lib/context-budget-view.ts +107 -0
  1026. package/.versions/2.0.19/.pi/harnesses/lib/context-budget.ts +114 -0
  1027. package/.versions/2.0.19/.pi/harnesses/lib/damage-control-shared.ts +226 -0
  1028. package/.versions/2.0.19/.pi/harnesses/lib/deterministic-handle-path.ts +25 -0
  1029. package/.versions/2.0.19/.pi/harnesses/lib/fixtures/context-budget-profiles.json +11 -0
  1030. package/.versions/2.0.19/.pi/harnesses/lib/fixtures/hub-prompt-operator.legacy.txt +73 -0
  1031. package/.versions/2.0.19/.pi/harnesses/lib/fixtures/hub-prompt-orchestrator.legacy.txt +73 -0
  1032. package/.versions/2.0.19/.pi/harnesses/lib/fleet-dashboard-ops.ts +178 -0
  1033. package/.versions/2.0.19/.pi/harnesses/lib/fleet-dashboard-view.ts +172 -0
  1034. package/.versions/2.0.19/.pi/harnesses/lib/fleet-detail-view.ts +339 -0
  1035. package/.versions/2.0.19/.pi/harnesses/lib/fleet-overlay.ts +26 -0
  1036. package/.versions/2.0.19/.pi/harnesses/lib/fleet-panel.ts +34 -0
  1037. package/.versions/2.0.19/.pi/harnesses/lib/fleet-read-model.ts +609 -0
  1038. package/.versions/2.0.19/.pi/harnesses/lib/fleet-selection.ts +24 -0
  1039. package/.versions/2.0.19/.pi/harnesses/lib/fleet-strip-controller.ts +75 -0
  1040. package/.versions/2.0.19/.pi/harnesses/lib/fleet-strip-view.ts +179 -0
  1041. package/.versions/2.0.19/.pi/harnesses/lib/fleet-transcript-store.ts +244 -0
  1042. package/.versions/2.0.19/.pi/harnesses/lib/herdr-client.ts +472 -0
  1043. package/.versions/2.0.19/.pi/harnesses/lib/herdr-presence.ts +399 -0
  1044. package/.versions/2.0.19/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  1045. package/.versions/2.0.19/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  1046. package/.versions/2.0.19/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  1047. package/.versions/2.0.19/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  1048. package/.versions/2.0.19/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  1049. package/.versions/2.0.19/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  1050. package/.versions/2.0.19/.pi/harnesses/lib/policy-roots.js +106 -0
  1051. package/.versions/2.0.19/.pi/harnesses/lib/policy-roots.ts +31 -0
  1052. package/.versions/2.0.19/.pi/harnesses/lib/safe-source-read.js +29 -0
  1053. package/.versions/2.0.19/.pi/harnesses/lib/spawned-peers.js +191 -0
  1054. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-agentic.js +15 -0
  1055. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-file-discovery.js +21 -0
  1056. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-json.js +37 -0
  1057. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-loader.js +44 -0
  1058. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-proactive.js +68 -0
  1059. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-triage.js +42 -0
  1060. package/.versions/2.0.19/.pi/harnesses/lib/system1/config-v2.js +106 -0
  1061. package/.versions/2.0.19/.pi/harnesses/lib/system1/config.js +50 -0
  1062. package/.versions/2.0.19/.pi/harnesses/lib/system1/contracts.ts +154 -0
  1063. package/.versions/2.0.19/.pi/harnesses/lib/system1/demo.ts +95 -0
  1064. package/.versions/2.0.19/.pi/harnesses/lib/system1/jev.ts +503 -0
  1065. package/.versions/2.0.19/.pi/harnesses/lib/system1/selection.js +11 -0
  1066. package/.versions/2.0.19/.pi/harnesses/lib/system1/service.ts +245 -0
  1067. package/.versions/2.0.19/.pi/harnesses/lib/update-check.ts +222 -0
  1068. package/.versions/2.0.19/.pi/harnesses/package-lock.json +2039 -0
  1069. package/.versions/2.0.19/.pi/harnesses/package.json +10 -0
  1070. package/.versions/2.0.19/.pi/prompts/af-build.md +27 -0
  1071. package/.versions/2.0.19/.pi/prompts/af-code-simplify.md +22 -0
  1072. package/.versions/2.0.19/.pi/prompts/af-constraints.md +31 -0
  1073. package/.versions/2.0.19/.pi/prompts/af-plan.md +17 -0
  1074. package/.versions/2.0.19/.pi/prompts/af-review.md +16 -0
  1075. package/.versions/2.0.19/.pi/prompts/af-set-hermes-telegram.md +15 -0
  1076. package/.versions/2.0.19/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  1077. package/.versions/2.0.19/.pi/prompts/af-setup-rules.md +20 -0
  1078. package/.versions/2.0.19/.pi/prompts/af-ship.md +17 -0
  1079. package/.versions/2.0.19/.pi/prompts/af-spec.md +15 -0
  1080. package/.versions/2.0.19/.pi/prompts/af-test.md +19 -0
  1081. package/.versions/2.0.19/.pi/skills/bowser/SKILL.md +145 -0
  1082. package/.versions/2.0.19/.version +1 -0
  1083. package/.versions/2.0.19/agents/architect.md +24 -0
  1084. package/.versions/2.0.19/agents/bowser.md +28 -0
  1085. package/.versions/2.0.19/agents/builder.md +55 -0
  1086. package/.versions/2.0.19/agents/code-reviewer.md +209 -0
  1087. package/.versions/2.0.19/agents/deep-researcher.md +32 -0
  1088. package/.versions/2.0.19/agents/documenter.md +22 -0
  1089. package/.versions/2.0.19/agents/orchestrator.md +22 -0
  1090. package/.versions/2.0.19/agents/plan-reviewer.md +83 -0
  1091. package/.versions/2.0.19/agents/planner.md +105 -0
  1092. package/.versions/2.0.19/agents/releaser.md +24 -0
  1093. package/.versions/2.0.19/agents/researcher.md +30 -0
  1094. package/.versions/2.0.19/agents/security-auditor.md +167 -0
  1095. package/.versions/2.0.19/agents/test-engineer.md +153 -0
  1096. package/.versions/2.0.19/agents/web-debugger.md +44 -0
  1097. package/.versions/2.0.19/agents/web-performance-auditor.md +194 -0
  1098. package/.versions/2.0.19/bin/catalog/harness-runtime-closure.json +73 -0
  1099. package/.versions/2.0.19/codex/fleet-session-client/SKILL.md +34 -0
  1100. package/.versions/2.0.19/codex/fleet-session-client.zip +0 -0
  1101. package/.versions/2.0.19/docs/ARCHITECTURE.md +874 -0
  1102. package/.versions/2.0.19/docs/agent-fleet-setup.md +1101 -0
  1103. package/.versions/2.0.19/docs/claude-code-coms-bridge.md +147 -0
  1104. package/.versions/2.0.19/docs/codex-session-bridge.md +219 -0
  1105. package/.versions/2.0.19/docs/coms-hermes-bridge.md +188 -0
  1106. package/.versions/2.0.19/docs/getting-started.md +126 -0
  1107. package/.versions/2.0.19/docs/npm-install.md +535 -0
  1108. package/.versions/2.0.19/docs/pi-extensions.md +454 -0
  1109. package/.versions/2.0.19/docs/pi-setup.md +92 -0
  1110. package/.versions/2.0.19/docs/skill-anatomy.md +150 -0
  1111. package/.versions/2.0.19/install-manifest.json +3197 -0
  1112. package/.versions/2.0.19/justfile +247 -0
  1113. package/.versions/2.0.19/manifest-meta.json +1075 -0
  1114. package/.versions/2.0.19/references/accessibility-checklist.md +160 -0
  1115. package/.versions/2.0.19/references/communication-contract.md +26 -0
  1116. package/.versions/2.0.19/references/definition-of-done.md +67 -0
  1117. package/.versions/2.0.19/references/fleet-coordination-patterns.md +171 -0
  1118. package/.versions/2.0.19/references/observability-checklist.md +92 -0
  1119. package/.versions/2.0.19/references/orchestration-patterns.md +370 -0
  1120. package/.versions/2.0.19/references/performance-checklist.md +236 -0
  1121. package/.versions/2.0.19/references/prompting-patterns.md +380 -0
  1122. package/.versions/2.0.19/references/security-checklist.md +245 -0
  1123. package/.versions/2.0.19/references/testing-patterns.md +235 -0
  1124. package/.versions/2.0.19/references/workflow-authoring.md +304 -0
  1125. package/.versions/2.0.19/skills/_internal/grilling.md +59 -0
  1126. package/.versions/2.0.19/skills/browser-testing-with-devtools/SKILL.md +351 -0
  1127. package/.versions/2.0.19/skills/code-review-and-quality/SKILL.md +396 -0
  1128. package/.versions/2.0.19/skills/compound-learning/SKILL.md +137 -0
  1129. package/.versions/2.0.19/skills/constraint-driven-development/SKILL.md +338 -0
  1130. package/.versions/2.0.19/skills/constraint-driven-development/references/floor-guard.md +99 -0
  1131. package/.versions/2.0.19/skills/context-engineering/SKILL.md +341 -0
  1132. package/.versions/2.0.19/skills/deprecation-and-migration/SKILL.md +247 -0
  1133. package/.versions/2.0.19/skills/designing-agents/SKILL.md +394 -0
  1134. package/.versions/2.0.19/skills/designing-agents/pi-harness-authoring.md +222 -0
  1135. package/.versions/2.0.19/skills/drafting-workflows/SKILL.md +143 -0
  1136. package/.versions/2.0.19/skills/drafting-workflows/scripts/make-workflow.ts +177 -0
  1137. package/.versions/2.0.19/skills/frontend-ui-engineering/SKILL.md +328 -0
  1138. package/.versions/2.0.19/skills/git-workflow-and-versioning/SKILL.md +316 -0
  1139. package/.versions/2.0.19/skills/idea-refine/SKILL.md +182 -0
  1140. package/.versions/2.0.19/skills/idea-refine/examples.md +238 -0
  1141. package/.versions/2.0.19/skills/idea-refine/frameworks.md +99 -0
  1142. package/.versions/2.0.19/skills/idea-refine/refinement-criteria.md +113 -0
  1143. package/.versions/2.0.19/skills/idea-refine/scripts/idea-refine.sh +15 -0
  1144. package/.versions/2.0.19/skills/incremental-implementation/SKILL.md +353 -0
  1145. package/.versions/2.0.19/skills/interview-me/SKILL.md +226 -0
  1146. package/.versions/2.0.19/skills/orchestration-verification/SKILL.md +182 -0
  1147. package/.versions/2.0.19/skills/peer-coms/SKILL.md +90 -0
  1148. package/.versions/2.0.19/skills/performance-optimization/SKILL.md +496 -0
  1149. package/.versions/2.0.19/skills/planning-and-task-breakdown/SKILL.md +318 -0
  1150. package/.versions/2.0.19/skills/repository-ai-setup/SKILL.md +135 -0
  1151. package/.versions/2.0.19/skills/repository-ai-setup/references/agent-fleet-ai-state.template.json +4 -0
  1152. package/.versions/2.0.19/skills/repository-ai-setup/references/apply-contract.md +74 -0
  1153. package/.versions/2.0.19/skills/repository-ai-setup/references/provenance-template.md +16 -0
  1154. package/.versions/2.0.19/skills/repository-ai-setup/references/setup-flow.md +108 -0
  1155. package/.versions/2.0.19/skills/repository-ai-setup/references/verify-setup.md +20 -0
  1156. package/.versions/2.0.19/skills/repository-ai-setup.zip +0 -0
  1157. package/.versions/2.0.19/skills/security-and-hardening/SKILL.md +524 -0
  1158. package/.versions/2.0.19/skills/spec-driven-development/SKILL.md +295 -0
  1159. package/.versions/2.0.19/skills/using-agent-skills/SKILL.md +198 -0
  1160. package/.versions/2.0.19/vendor/agent-skills-upstream/LICENSE +21 -0
  1161. package/.versions/2.0.19/vendor/agent-skills-upstream/README.md +430 -0
  1162. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +367 -0
  1163. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  1164. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  1165. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  1166. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  1167. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/constraint-driven-development/SKILL.md +311 -0
  1168. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/constraint-driven-development/references/floor-guard.md +99 -0
  1169. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +337 -0
  1170. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  1171. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  1172. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +288 -0
  1173. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  1174. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  1175. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  1176. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  1177. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  1178. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  1179. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  1180. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  1181. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  1182. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  1183. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +238 -0
  1184. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +496 -0
  1185. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +257 -0
  1186. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +524 -0
  1187. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +330 -0
  1188. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +216 -0
  1189. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +245 -0
  1190. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +398 -0
  1191. package/.versions/2.0.19/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +192 -0
  1192. package/CHANGELOG.md +12 -0
  1193. package/README.md +2 -2
  1194. package/agents/architect.md +2 -2
  1195. package/agents/bowser.md +1 -1
  1196. package/agents/builder.md +5 -5
  1197. package/agents/code-reviewer.md +2 -2
  1198. package/agents/deep-researcher.md +2 -2
  1199. package/agents/documenter.md +3 -3
  1200. package/agents/orchestrator.md +2 -2
  1201. package/agents/plan-reviewer.md +2 -2
  1202. package/agents/planner.md +4 -4
  1203. package/agents/releaser.md +2 -2
  1204. package/agents/researcher.md +2 -2
  1205. package/agents/security-auditor.md +2 -2
  1206. package/agents/test-engineer.md +4 -4
  1207. package/agents/web-debugger.md +2 -2
  1208. package/agents/web-performance-auditor.md +2 -2
  1209. package/bin/cli.js +3 -3
  1210. package/bin/lib/doctor.js +8 -2
  1211. package/bin/lib/external-content.js +33 -0
  1212. package/bin/lib/project-provenance.js +19 -13
  1213. package/bin/lib/system1-migration.js +17 -8
  1214. package/bin/lib/system1-policy-context.js +57 -0
  1215. package/bin/lib/transaction.js +33 -2
  1216. package/docs/ARCHITECTURE.md +42 -2
  1217. package/docs/agent-fleet-setup.md +5 -5
  1218. package/docs/claude-code-coms-bridge.md +17 -4
  1219. package/docs/external-project-ai-content.md +64 -0
  1220. package/docs/npm-install.md +5 -0
  1221. package/docs/system1-agentic.md +27 -0
  1222. package/docs/system1-config.md +23 -1
  1223. package/docs/system1-file-discovery.md +220 -0
  1224. package/install-manifest.json +5 -1
  1225. package/manifest-meta.json +4 -0
  1226. package/package.json +15 -6
  1227. package/skills/repository-ai-setup/SKILL.md +18 -0
  1228. package/skills/repository-ai-setup.zip +0 -0
@@ -0,0 +1,2625 @@
1
+ import { registerDiscoveryHub, configureDiscoveryHub, resetDiscoveryHub, discoveryHubEnabled, discoveryManagedReadbackAllowed, prepareDiscoveryNative } from './file-discovery/hub.ts';
2
+ import { registerAgenticHub, configureAgenticHub, agenticHubEnabled, agenticHubRuntime, resetAgenticHub } from './agentic-hub.ts';
3
+ import { loadSystem1Snapshot } from "../lib/system1/config-loader.js";
4
+ import { normalizeSystem1Config } from "../lib/system1/config-v2.js";
5
+ import { registerDispatchTriage } from "./tools/dispatch-triage.ts";
6
+ import { createTriageRuntime } from "./dispatch-triage-runtime.ts";
7
+ import { type TriageConfig, type TriageInput } from "./dispatch-triage-contract.ts";
8
+ import { loadTaskTriageConfig } from "./task-triage-config.ts";
9
+ import { TASK_TRIAGE_MODEL } from "./task-triage-contract.ts";
10
+ import type { JevTransport } from "../lib/system1/jev.ts";
11
+ import { createTaskTriageRuntime, evaluatedTaskTriageInputChanged, TASK_TRIAGE_RUNTIME_ENTRY } from "./task-triage-runtime.ts";
12
+ import { adoptTaskTriageState, applyTaskTriageAdditions, recoverTaskTriageProcessState } from "./task-triage-obligations.ts";
13
+ import { confirmTaskTriageAction, confirmTaskTriageWaiver, consumeActionGrant, taskTriageActionAuditRecord, type TaskTriageActionObservation } from "./task-triage-authorization.ts";
14
+ import { registerTaskTriageRecover } from "./commands/task-triage-recover.ts";
15
+ import { registerTaskTriageWaiver } from "./commands/task-triage-waive.ts";
16
+ import { createCommunicationStore } from "./system1-communication-store.ts";
17
+ import { openSystem1Communication } from "./ui/system1-communication.ts";
18
+ import { registerRetry } from "./commands/retry.ts";
19
+ import { createHash } from "node:crypto";
20
+ import { loadProactiveConfig, isCaptureEnabled } from "./proactive-config.ts";
21
+ import { createProactiveRuntime, createHubCapture, composeHubProactive } from "./proactive-runtime.ts";
22
+ import type { ProactiveConfig } from "./proactive-types.ts";
23
+ import { registerRecover, runRecoverCommand } from "./commands/recover.ts";
24
+ import { createNoProgressGuard } from "./no-progress.ts";
25
+ import { renderNextInvocation, renderRecoverCommands } from './recover-policy.ts';
26
+ import { closeEvidenceSession, pruneEvidenceSessions } from "./execution-evidence.ts";
27
+ import { hasExplicitDispatcher, isCompleteProfile, dispatcherSelection, type ModelProfiles } from './config/model-profiles.ts';
28
+ import { createProfileActivation } from './policy/profile-activation.ts';
29
+ import { readActiveProfile, profileWorkInFlight, withProfileWork, assertProfileModel, profilePeerGate } from './policy/profile-runtime.ts';
30
+ import { resolveAssist } from './assist-profile.ts';
31
+ import { registerFilesystemTool, FILESYSTEM_POLICY_ROOTS_ENV } from './filesystem-tool.ts';
32
+ /** Agent Hub composition root: constructs mutable state, contexts, registrars, and ordered lifecycle ports. */
33
+
34
+ import type { AgentDef, AgentState, ResearchState } from "./types.ts";
35
+ import { DEFAULT_OVERRIDES, THINKING_LEVELS, parseAgentTeamOverrides, type AgentTeamOverrides } from "./config/overrides.ts";
36
+ import { loadAgentConfiguration } from "./config/agents.ts";
37
+ import { abbrevThinking, displayName, extractAskUserQuestions, extractNeedsResearch, resolveDelegateExtension, resolveThinkingLevel } from "./presentation.ts";
38
+ import { MAX_LIVE_ENTRY_CHARS, appendTimelineEvent, appendTimelineText, flushTimelineStore } from "./timeline.ts";
39
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
40
+ import { DynamicBorder, getMarkdownTheme as getPiMdTheme, copyToClipboard } from "@mariozechner/pi-coding-agent";
41
+ import {
42
+ Text, Box, Container, Spacer, Markdown, matchesKey, Key,
43
+ type AutocompleteItem, truncateToWidth, visibleWidth,
44
+ } from "@mariozechner/pi-tui";
45
+ import { spawn, type ChildProcess } from "child_process";
46
+ import { spawnPiAgent, spawnPiAgentWithModelFallback, killPiTree, type Termination } from "./spawn.ts";
47
+ import { fenceOperatorCancel } from "./drift-runtime.ts";
48
+ import { researchTerminationOutcome, researchWatchdogSpawnOptions } from "./research-watchdog.ts";
49
+ import { composeFleetFooterHint, renderHubFooterLeft } from "./footer.ts";
50
+ import { HARNESS_VERSION, registerVersionStatus } from "./version.ts";
51
+ import { cancelLocalOwnedProcess, cancelLocalWaitOnly, monitorKeyForAgent } from "./monitor-control.ts";
52
+ import { createMonitorLifecycle } from "./monitor-lifecycle.ts";
53
+ import { createMonitorSessionBridge } from "./monitor-session-bridge.ts";
54
+ import {
55
+ AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
56
+ exemptionsFilePath, type AccessRequest,
57
+ } from "../lib/damage-control-shared.ts";
58
+ import { applyModelOverride, clampDelegateDepth, fallbackModelFor, isReadOnlyToolList, MAX_DELEGATE_DEPTH, normalizeAgentInput, orchestratorNeedsRoster, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
59
+ import { DEFAULT_TASK_TIER, addTaskClockWait, applyTierChange, blockingFindingCap, checkReviewRoundCap, checkTaskBudget, checkTierPersonaGate, checkTurnBudget, createTaskClock, isReviewPersona, openTaskClock, remainingTaskResearch, reviewBudgetClause, reviewRoundCap } from "./run-budget.js";
60
+ import { countReviewFindings, findingBudgetNotice } from "./review-findings.js";
61
+ import { checkDocsLane, docsLaneNotice } from "./docs-lane.js";
62
+ import { checkExternalBlockerGate, extractExternalBlockers } from "./external-blocker.js";
63
+ import { DEFAULT_RUN_HISTORY_KEEP, normalizeRunHistoryKeep } from "./run-namespace.js";
64
+ import { validateAssertionBatch } from "./assertion-ledger.js";
65
+ import { DEFAULT_PROVIDER_LIMITS, createProviderSemaphore, parseProviderLimits } from "./provider-semaphore.js";
66
+ import {
67
+ PANE_PROMPT_TIMEOUT_MS,
68
+ launchPeerInPane,
69
+ peerReadyVerdict,
70
+ unaddressedPeerSweep,
71
+ } from "../lib/spawned-peers.js";
72
+ import { contextPct, estimatePromptTokens, resolveContextWindow } from "./context-window.js";
73
+ import { DEFAULT_WATCHDOG_SETTING, WATCHDOG_SETTINGS, normalizeWatchdogSetting, resolveWatchdogActive } from "./drift-watchdog.js";
74
+ import { createWatchdogActivity, createTaskTriageActivity, type WatchdogActivity, type TaskTriageActivity } from "./system1-activity.ts";
75
+ import { createWatchdogSystem1Session, disposeWatchdogSystem1Session, readWatchdogSystem1Snapshot, type WatchdogSystem1Session } from "./system1-runtime.ts";
76
+ import { shouldExtractReturn } from "./return-extract.js";
77
+ import { crossCheck, deliveryDisposition, extractAssertionIds, parseDeliveredReturn } from "./return-contract.js";
78
+ import { checkScope, diffAgainst, snapshotWorktree, worktreeRevision } from "./scope-gate.js";
79
+ import { validateEvidence } from "./evidence-rules.js";
80
+ import { comsRequiredRefusal, explicitComsRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
81
+ import { NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState, resolveSessionWorkMode, resolveSessionRoster, type WorkMode } from "./work-mode.ts";
82
+ import { compactWorkMode } from "./work-mode-controls.ts";
83
+ import { registerWorkMode } from "./commands/work-mode.ts";
84
+ import { registerAgentsTeam } from "./commands/agents-team.ts";
85
+ import { registerAgentsList } from "./commands/agents-list.ts";
86
+ import { registerAgentsHistory } from "./commands/agents-history.ts";
87
+ import { registerAgentsAdd } from "./commands/agents-add.ts";
88
+ import { registerAgentsDrop } from "./commands/agents-drop.ts";
89
+ import { registerAgentsSave } from "./commands/agents-save.ts";
90
+ import { registerAgentsKill } from "./commands/agents-kill.ts";
91
+ import { registerAgentsRestart } from "./commands/agents-restart.ts";
92
+ import { registerContextCommand } from "./commands/context-command.ts";
93
+ import { registerAudit } from "./commands/audit.ts";
94
+ import { showSessionAudit } from "./session-audit.ts";
95
+ import { buildWatchdogReport, buildProactiveReport, commandProactiveLabels, readProactiveReport, formatWatchdogStatus, readWatchdogEvents } from "./system1-report.ts";
96
+ import { createProcessState, processAllowsPersona, processOpenObligations, evaluateProcessObligations, latestProcessState, processAuditRecord, processTaskIdentityConflicts, processPreEffectGate, missingProcessRoleRecoveryHints, activeAdditionRecoveryHints, taskTransitionRecoveryHint, transitionToolDecision, latestPendingTaskTransition, TASK_TRANSITION_ENTRY_TYPE, type ProcessObligationState, type ProcessVerdict } from "./process-obligations.ts";
97
+ import { registerHubReport } from "./commands/hub-report.ts";
98
+ import { registerZoom } from "./commands/zoom.ts";
99
+ import { registerDispatchPolicy } from "./commands/dispatch-policy.ts";
100
+ import { registerAgentModel } from "./commands/agent-model.ts";
101
+ import { registerAgentModelThinking } from "./commands/agent-model-thinking.ts";
102
+ import { registerModels } from "./commands/models.ts";
103
+ import { registerAgentModelsSubstitute } from "./commands/agent-models-substitute.ts";
104
+ import { registerWatchdog } from "./commands/watchdog.ts";
105
+ import { registerComs } from "./commands/coms.ts";
106
+ import { registerHandoff } from "./commands/handoff.ts";
107
+ import { registerCompound } from "./commands/compound.ts";
108
+ import { registerPoll } from "./commands/poll.ts";
109
+ import { registerDebate } from "./commands/debate.ts";
110
+ import type { CommandContext } from "./commands/context.ts";
111
+ import { formatAfPollStarted, formatAfPollVoiceProgress, handleAfPoll } from "./poll-command.ts";
112
+ import { formatAfDebateStarted, formatAfDebateVoiceProgress, handleAfDebate } from "./debate-command.ts";
113
+ import { registerDispatchAgent } from "./tools/dispatch-agent.ts";
114
+ import { registerSpawnResearch } from "./tools/spawn-research.ts";
115
+ import { registerRunFlow } from "./tools/run-flow.ts";
116
+ import { resolvePersona as resolveFlowPersona } from "../../agent-fleet/scripts/workflows/lib/personas.ts";
117
+ import { assertProfileModel as assertFlowProfileModel } from "../../agent-fleet/scripts/workflows/lib/model-profile.ts";
118
+ import { registerSetTaskTier } from "./tools/set-task-tier.ts";
119
+ import { registerTeamAdjust } from "./tools/team-adjust.ts";
120
+ import { registerVerificationContract } from "./tools/verification-contract.ts";
121
+ import { registerComsTools } from "./tools/coms-tools.ts";
122
+ import { paneTail, peerManifest, peerPersonaExists, registerFleetTools, spawnDelaySeconds, STAGGER_ENV_VAR, waitForPeerRegistration } from "./tools/fleet-tools.ts";
123
+ import type { ToolContext } from "./tools/context.ts";
124
+ import { createToolExecutionOrchestration } from "./tools/execution-orchestration.ts";
125
+ import { latestPersistedCapabilityState, type ContextState, type PendingOperation } from "./capability-packs.ts";
126
+ import { contextPressureDiagnostic, createContextPressureState, transitionContextPressure, type ContextPressureState } from "./context-pressure.ts";
127
+ import { confirmationOutcome, capabilityConfirmationPack, capabilityConfirmationQuestion, type ConfirmableCapabilityPack } from "./capability-confirmation.ts";
128
+ import { confirmRecoverAction, confirmTaskSupersession, createBudgetRecovery, createReservedTaskIdentityReset } from "./budget-recovery.ts";
129
+ import { requestRuntimeAsk } from "../ask-user-remote/runtime-ask.ts";
130
+ import { registerBudgetContinue } from "./commands/budget-continue.ts";
131
+ import { observeAskUserResults } from "../ask-user-remote/index.ts";
132
+ import { handleQuestionEnvelope, registerQuestionPeer } from "../ask-user-remote/questions.ts";
133
+ import { buildHubPeerSpawnPlan, launchHubPeerInPane } from "./peer-spawn-plan.ts";
134
+ import { RESEARCH_TOOLS, createResearchRuntime, parseResearchHandle } from "./research/runtime.ts";
135
+ import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
136
+ import { createAccessApprovalRouter } from "./access-approval.ts";
137
+ import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
138
+ import { herdrPaneId } from "../lib/herdr-presence.ts";
139
+ import { herdr as herdrApi, herdrAvailable } from "../lib/herdr-client.ts";
140
+ import {
141
+ abbreviateModel,
142
+ createComsPeer,
143
+ hexFg,
144
+ nowIso,
145
+ readAllRegistryEntries,
146
+ readAllRegistryEntriesAcrossProjects,
147
+ type ComsIdentity,
148
+ type RegistryEntry as ComsRegistryEntry,
149
+ TIMEOUT_MS,
150
+ } from "../lib/coms-core.ts";
151
+ import { createGridUI } from "./ui/grid.ts";
152
+ import { createFleetSource } from "./ui/fleet-source.ts";
153
+ import { buildFleetRows } from "../lib/fleet-read-model.ts";
154
+ import { createFleetActions } from "./ui/fleet-actions.ts";
155
+ import { createDetailPanel } from "./ui/detail-panel.ts";
156
+ import { createFleetDashboard } from "./ui/fleet-dashboard.ts";
157
+ import { createContextBudgetUi } from "./ui/context-budget.ts";
158
+ import { createPoolPresentation } from "./ui/pool.ts";
159
+ import { registerInputShortcuts } from "./input/shortcuts.ts";
160
+ import { createCompletionPresentation } from "./input/completions.ts";
161
+ import { createResearchControls } from "./research/controls.ts";
162
+ import { createContextPressureLifecycle, createContextPressureRootState } from "./lifecycle/context-pressure.ts";
163
+ import { createTurnLifecycleHandlers, registerTurnPresence } from "./lifecycle/turn-handlers.ts";
164
+ import { createMonitorSession } from "./lifecycle/monitor-session.ts";
165
+ import { applySessionOverrides, registerSessionOrchestration, resetHubSession } from "./lifecycle/session-orchestration.ts";
166
+ import { openZoom, type TimelineEntry, type Zoomable } from "./ui/zoom.ts";
167
+ import { openHistory } from "./ui/history.ts";
168
+ import { createExecutionHistoryStore, type HistoryEntry } from "./ui/history-store.ts";
169
+ import { createDispatchComs, createDispatchNative, createDispatchObservability, type DelegationChild } from "./dispatch-core.ts";
170
+ import type { FleetRow } from "../lib/fleet-read-model.ts";
171
+ import { gridColumnsForSize } from "../lib/fleet-dashboard-ops.ts";
172
+ import { createFleetTranscriptStore } from "../lib/fleet-transcript-store.ts";
173
+ import type { ContextBudgetComponent } from "../lib/context-budget.ts";
174
+ import { buildHubSystemPrompt as assembleHubPrompt } from "./prompts/system-prompt.ts";
175
+ import type { HubPromptContext } from "./prompts/context.ts";
176
+ import { buildSessionStartNotice, createSessionFooter } from "./prompts/session-start.ts";
177
+ import { registerSessionStart } from "./session-start.ts";
178
+ import { createHubStateContext } from "./context/hub-state.ts";
179
+ import { createAgentStateFactory } from "./context/agent-state.ts";
180
+ import { createBudgetContext, createSessionTotals, freshTurnReport, type TurnReport } from "./context/budgets.ts";
181
+ import { createAssertionsArtifactsContext, type Assertion, type InputArtifactPreview } from "./context/assertions-artifacts.ts";
182
+ import { createModelPolicy } from "./policy/models.ts";
183
+ import { createRosterPolicy } from "./policy/roster.ts";
184
+ import { createWorkModePolicy } from "./policy/work-mode.ts";
185
+ import { catalogSnapshot, latestPersistedToolCatalog, toolCatalogNotice, TOOL_CATALOG_ENTRY_TYPE, type ToolCatalogDelta } from "./tool-catalog-state.ts";
186
+ import { createToolCatalogRuntime } from "./tool-catalog-runtime.ts";
187
+ import { createUnknownToolCounter, latestPersistedUnknownToolCounter, observeUnknownToolCalls, restoreUnknownToolCounter, unknownToolNotice, UNKNOWN_TOOL_COUNTER_ENTRY_TYPE } from "./unknown-tool-counter.ts";
188
+ import { buildProjectDocsProtocol, buildProjectRulesProtocol, nativeResearchSystemPrompt } from "../lib/context-budget-child-prompt.ts";
189
+ import { parseEnvFile, resolveEnvFilePath } from "../../agent-fleet/scripts/lib/herdr-layout.ts";
190
+ import { worktreeTag } from "../../agent-fleet/scripts/lib/team-project.ts";
191
+ import { join, resolve } from "path";
192
+ import * as fs from "node:fs";
193
+ import * as path from "node:path";
194
+ import * as crypto from "node:crypto";
195
+ import { fileURLToPath } from "node:url";
196
+
197
+ // ── Extension ────────────────────────────────────
198
+
199
+ const CONTEXT_WARN_THRESHOLD = 70;
200
+ const RESEARCHER_PERSONAS = new Set(["researcher", "deep-researcher"]);
201
+
202
+ /**
203
+ * Test-only transport seam for real-Pi acceptance. With the offline guard,
204
+ * the normal shared System 1 service uses deterministic wire responses rather
205
+ * than HTTPS; config, readiness, adapter, deadlines and consumers remain real.
206
+ * A profile alone cannot activate this seam outside the guarded test process.
207
+ */
208
+ let taskTriageFakeInstances = 0;
209
+ function resolveTaskTriageTestTransport(): JevTransport | undefined {
210
+ const profile = process.env.AGENT_HUB_TASK_TRIAGE_FAKE;
211
+ const guard = `--import=${fileURLToPath(new URL("../../../bin/test/helpers/system1-no-network.js", import.meta.url))}`;
212
+ if (!profile || process.env.PI_OFFLINE !== "1" || !process.env.NODE_OPTIONS?.split(/\s+/).includes(guard)) return undefined;
213
+ const hot = profile === "security" ? "security_change" : profile === "wide" ? "wide_change" : profile === "irreversible" ? "irreversible_execution" : null;
214
+ if (!hot && profile !== "plain" && profile !== "timeout") return undefined;
215
+ const instanceId = ++taskTriageFakeInstances;
216
+ return async request => {
217
+ const wire = JSON.parse(request.body.toString("utf8"));
218
+ const recordPath = process.env.AGENT_HUB_TASK_TRIAGE_FAKE_RECORD;
219
+ if (recordPath) {
220
+ try { fs.appendFileSync(recordPath, JSON.stringify({ at: Date.now(), profile, instanceId, pid: process.pid, questions: Object.keys(wire.questions), stateFingerprint: createHash("sha256").update(JSON.stringify(wire.state)).digest("hex"), questionFingerprint: createHash("sha256").update(JSON.stringify(wire.questions)).digest("hex"), stack: (new Error("fake-transport").stack ?? "").split("\n").slice(1, 6) }) + "\n"); } catch { /* evidence best-effort */ }
221
+ }
222
+ if (profile === "timeout") {
223
+ return new Promise((_, reject) => {
224
+ if (request.signal.aborted) return reject(new Error("guarded fake transport deadline"));
225
+ request.signal.addEventListener("abort", () => reject(new Error("guarded fake transport deadline")), { once: true });
226
+ });
227
+ }
228
+ return { status: 200, headers: {}, body: JSON.stringify({ model: TASK_TRIAGE_MODEL,
229
+ answers: Object.fromEntries(Object.keys(wire.questions).map(id => [id, { type: "noul", noul: id === hot ? 0.95 : 0.05 }])),
230
+ usage: { input_tokens: 1, output_tokens: 1 },
231
+ }) };
232
+ };
233
+ }
234
+
235
+ export default function (pi: ExtensionAPI) {
236
+ // ── Embedded coms: identity CLI flags ──
237
+ // Registered here (factory load time) so pi's CLI parser accepts them. Because
238
+ // coms is EMBEDDED (one extension, not a second `-e`), these register exactly once.
239
+ pi.registerFlag("name", { description: "Coms: override agent name (else frontmatter or auto-generated)", type: "string", default: undefined });
240
+ pi.registerFlag("purpose", { description: "Coms: override agent purpose (else frontmatter description)", type: "string", default: undefined });
241
+ pi.registerFlag("project", { description: "Coms: project namespace for peer discovery", type: "string", default: "default" });
242
+ pi.registerFlag("color", { description: "Coms: hex color #RRGGBB (else frontmatter or palette fallback)", type: "string", default: undefined });
243
+ pi.registerFlag("explicit", { description: "Coms: hide from auto-discovery; addressable only by exact name", type: "boolean", default: false });
244
+ pi.registerFlag("solo", { description: "Run without the coms layer (fixed specialists + research only — `just fleet hub --solo`)", type: "boolean", default: false });
245
+ pi.registerFlag("work-mode", { description: "Fleet main-agent work mode: operator|orchestrator", type: "string", default: undefined });
246
+ pi.registerFlag("agent-team", { description: "Internal: activate a named native roster from .pi/agents/teams.yaml", type: "string", default: undefined });
247
+
248
+ // ── Embedded coms: shared peer state ──
249
+ let currentCtx: ExtensionContext | null = null;
250
+ let refreshFleetUi = () => {};
251
+ const coms = createComsPeer({
252
+ pi,
253
+ getContext: () => currentCtx,
254
+ onPeersChanged: () => refreshFleetUi(),
255
+ acceptInbound: () => currentCtx && modelWorkBlockedByRosterRecovery(currentCtx)
256
+ ? "orchestrator roster recovery required"
257
+ : null,
258
+ handleCustomEnvelope: (socket, envelope) => {
259
+ if (handleQuestionEnvelope(socket, envelope)) return true;
260
+ if (envelope.type !== "access_request") return false;
261
+ void accessApprovalRouter.handle(socket, envelope as AccessRequest);
262
+ return true;
263
+ },
264
+ });
265
+ const unregisterQuestions = registerQuestionPeer(() => coms.ready && coms.identity ? {
266
+ project: coms.identity.project, peer: coms.identity.name,
267
+ sessionId: coms.identity.session_id, startedAt: coms.identity.started_at,
268
+ } : null);
269
+ let identity: ComsIdentity | null = null;
270
+ const peerCards = coms.peerCards;
271
+ const pendingReplies = coms.pendingReplies;
272
+ const inboundQueue = coms.inboundQueue;
273
+ let comsReady = false;
274
+ let monitorLifecycle: ReturnType<typeof createMonitorLifecycle> | null = null;
275
+ let monitorHubId: string | null = null;
276
+ let monitorTurnId: string | null = null;
277
+ let monitorBridge: ReturnType<typeof createMonitorSessionBridge> | null = null;
278
+ let monitorOwnerId: string | undefined;
279
+
280
+ // ── Damage-control exemptions + access escalation state ──
281
+ // exemptionsFile is the session-scoped shared exemptions file: /af-allow
282
+ // session grants (via the co-loaded damage-control-continue) and approved
283
+ // escalations land here, and spawned children read it through the
284
+ // AGENT_HUB_EXEMPTIONS_FILE env plumbing.
285
+ let exemptionsFile: string | null = null;
286
+ const accessApprovalRouter = createAccessApprovalRouter({
287
+ getContext: () => currentCtx,
288
+ getExemptionsFile: () => exemptionsFile,
289
+ appendLog: (entry) => { try { pi.appendEntry("damage-control-log", entry); } catch { /* best-effort */ } },
290
+ now: nowIso,
291
+ });
292
+
293
+ const agentStates: Map<string, AgentState> = new Map();
294
+ // Live-only research helpers, keyed by numeric id (handle `rN`). Visible in the
295
+ // Fleet Dashboard (Alt+A) while running; evicted from this map on every terminal
296
+ // outcome. Session/transcript/findings files and /af-agents-history survive.
297
+ let researchStates: Map<number, ResearchState> = new Map();
298
+ // Metadata only: prompt text is never retained by this ledger.
299
+ let lastHubLedger: ContextBudgetComponent[] = [];
300
+ let nextResearchId = 1;
301
+
302
+ // ── Execution history (/af-agents-history) ──────────
303
+ // The typed store owns entries and turn/ask_user bookkeeping; index.ts owns
304
+ // composition and wires lifecycle events to its explicit API.
305
+ const executionHistory = createExecutionHistoryStore();
306
+
307
+ let researchPersonas: AgentDef[] = [];
308
+ let allAgentDefs: AgentDef[] = [];
309
+ let teams: Record<string, string[]> = {};
310
+ // Named model profiles from .pi/agents/model-profiles.yaml (validated at
311
+ // session start) and the session-lifetime per-persona model overrides set by
312
+ // /af-agent-model and /af-models (lowercase persona name → pi model spec). Overrides
313
+ // reset on session_start; profiles make re-applying cheap.
314
+ let modelProfiles: ModelProfiles = {};
315
+ let modelProfileErrors: string[] = [];
316
+ // Backend routing policy (.pi/agents/dispatch-policy.yaml): per dispatch, a
317
+ // member preferring coms is served by a live same-name pool peer instead of a
318
+ // native subagent spawn. Missing file → everything native (status quo).
319
+ let dispatchPolicy: {
320
+ default: string;
321
+ grace_s: number;
322
+ substitutions: Record<string, { prefer: string; fallback: string; timeout_s?: number }>;
323
+ } = { default: "native", grace_s: 30, substitutions: {} };
324
+ let dispatchPolicyWarnings: string[] = [];
325
+ // One "coms peer missing → native" notice per member per team activation.
326
+ const comsMissNotified = new Set<string>();
327
+
328
+ let activeTeamName = "";
329
+ let gridCols = 2;
330
+ let widgetCtx: any;
331
+ let sessionDir = "";
332
+ let contextWindow = 0;
333
+ // Per-provider in-flight cap for the hub's OWN spawns (specialists and
334
+ // research helpers, which the dispatcher can start in parallel). Delegate
335
+ // children are gated by the same policy inside their parent's process. The
336
+ // drift judge and the return extractor are deliberately NOT gated: both run
337
+ // while a specialist holds a permit, so queueing them behind that specialist
338
+ // would stall the very watchdog that is supposed to stop it.
339
+ const providerSemaphore = createProviderSemaphore({
340
+ ...DEFAULT_PROVIDER_LIMITS,
341
+ ...parseProviderLimits(process.env.AGENT_HUB_PROVIDER_LIMITS),
342
+ });
343
+ /**
344
+ * pi's model registry as a plain lookup — the documented source for every
345
+ * model's window, and the same one the dispatcher's own window comes from.
346
+ */
347
+ function modelWindowLookup(ctx: any): (provider: string, modelId: string) => any {
348
+ return (provider, modelId) => ctx?.modelRegistry?.find?.(provider, modelId);
349
+ }
350
+
351
+ /** Say so when a run is about to wait on a provider permit, not just hang. */
352
+ function notifyProviderQueue(model: string, label: string, ctx: any): void {
353
+ const cap = providerSemaphore.limitFor(model);
354
+ if (cap == null || providerSemaphore.inFlight(model) < cap) return;
355
+ const ahead = providerSemaphore.queued(model) + 1;
356
+ ctx?.ui?.notify(
357
+ `${label}: queued — ${cap} requests already in flight on this provider (${ahead} waiting). ` +
358
+ "Raise or disable the cap with AGENT_HUB_PROVIDER_LIMITS (e.g. custom=4, custom=off).",
359
+ "info",
360
+ );
361
+ }
362
+
363
+ let activeWritableDispatches = 0;
364
+ let writableOverlapCounter = 0;
365
+ let pendingHandoff: { target: string; token: string } | null = null;
366
+ const hubStateCtx = createHubStateContext({
367
+ getCurrentContext: () => currentCtx, setCurrentContext: value => { currentCtx = value; },
368
+ getExemptionsFile: () => exemptionsFile, setExemptionsFile: value => { exemptionsFile = value; },
369
+ getSessionDir: () => sessionDir, setSessionDir: value => { sessionDir = value; },
370
+ getWidgetContext: () => widgetCtx, setWidgetContext: value => { widgetCtx = value; },
371
+ getPendingHandoff: () => pendingHandoff, setPendingHandoff: value => { pendingHandoff = value; },
372
+ });
373
+ let userLanguage: string = DEFAULT_OVERRIDES.language;
374
+ // Project rule folders from the overrides file's `rules:` key (repo-relative,
375
+ // validated at session_start). Non-empty → every dispatched specialist gets a
376
+ // "Project rules" prompt block; personas resolve the folders index-first (a
377
+ // top-level README.md/index.md is a loading manifest) with recursive discovery
378
+ // as the no-index fallback.
379
+ let projectRulesDirs: string[] = [];
380
+ // Project documentation entry points from the overrides file's `docs:` key
381
+ // (repo-relative files or folders, validated at session_start). Non-empty →
382
+ // dispatched specialists and research helpers get a "Project docs" prompt block.
383
+ let projectDocsPaths: string[] = [];
384
+
385
+ // Prompt blocks for the project's own rules (HOW — compliance) and docs
386
+ // (WHAT/WHY — orientation). Rules discovery is index-first so a curated rule
387
+ // tree (README manifest + session bundles) is honored instead of bulk-read;
388
+ // the blind recursive find is only the no-index fallback. The validation duty
389
+ // itself is written into the planner/code-reviewer personas.
390
+ function buildRulesProtocol(): string {
391
+ return buildProjectRulesProtocol(projectRulesDirs);
392
+ }
393
+
394
+ function buildDocsProtocol(): string {
395
+ return buildProjectDocsProtocol(projectDocsPaths);
396
+ }
397
+
398
+ /** One canonical repository context file plus explicitly configured rule roots. */
399
+ function specialistProjectPolicyPaths(cwd: string): string[] {
400
+ const canonical = ["AGENTS.md", "CLAUDE.md"].find(candidate => existsSync(path.join(cwd, candidate)));
401
+ return [...new Set([...(canonical ? [canonical] : []), ...projectRulesDirs])];
402
+ }
403
+ // The one supported safety harness. Every native specialist, researcher, and
404
+ // nested delegate receives it; a missing harness refuses child dispatch.
405
+ let safetyHarnessPath: string | null = null;
406
+ // Resolved once at session_start: the delegate extension injected into
407
+ // specialists that declare `subagents:` (null → delegation disabled).
408
+ let delegateExtPath: string | null = null;
409
+ // Per-tool deadline for read/grep/find/ls in research helpers/delegates. The
410
+ // whole-run bound is separate: the turn budget's agentTurnMs (run-budget.js).
411
+ let reconSearchTimeoutMs: number | null = 120_000;
412
+ // ── Per-turn budgets (run-budget.js) ──
413
+ // Envelopes follow task tier. Override keys are a ceiling (min with the tier).
414
+ // Counters reset in before_agent_start, or after an explicit one-click
415
+ // continuation. executionHistory.turnStartedAt() is the active-time base; ask_user
416
+ // waits are subtracted.
417
+ let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
418
+ let turnDispatchCount = 0;
419
+ let turnResearchCount = 0;
420
+ // Human wait time is not fleet work. Track it separately from history UI
421
+ // intervals so a continuation can rebase the budget without erasing history.
422
+ let turnBudgetAskUserWaitMs = 0;
423
+ let taskContinuationCount = 0;
424
+ let turnContinuationCount = 0;
425
+ // ── Task-scoped budget & tier (run-budget.js) ──
426
+ // A per-message allowance cannot bound a task: every steering message opened a
427
+ // fresh turn window, so a run could spend 8 dispatches and 60 minutes again and
428
+ // again without any counter ever binding. These counters span the whole TASK
429
+ // and are cleared only by an explicit new task (`set_task_tier` with
430
+ // `new_task: true`) or an approved task-budget continuation — never by an
431
+ // ordinary user message.
432
+ let taskDispatchCount = 0;
433
+ let taskResearchCount = 0;
434
+ let taskLabel: string | null = null;
435
+ // The task clock charges ACTIVE time only — turns that ran, minus the time the
436
+ // dispatcher spent blocked on ask_user. Raw wall clock would bill the human's
437
+ // lunch break, an overnight pause, and every long answer against the task, and
438
+ // at small tier's 45-minute envelope that hard-stops a task with two dispatches
439
+ // spent. A false stop is worse than no stop: it teaches people to reset the
440
+ // task window reflexively, which is the one thing that must stay deliberate.
441
+ // The explicit clock state makes `active` authoritative: a stale timestamp can
442
+ // never turn inter-turn idle time into task work.
443
+ let taskClock = createTaskClock();
444
+ // Review dispatches spent on this task (review-round cap).
445
+ let taskReviewRounds = 0;
446
+ // Task tier (complexity triage): declared by the dispatcher via set_task_tier.
447
+ // TASK-scoped, not turn-scoped, and it moves by ratchet — down freely, up only
448
+ // with a stated reason (applyTierChange). Null until declared; the first
449
+ // dispatch assumes DEFAULT_TASK_TIER. Caps come from the tier envelope.
450
+ let taskTier: string | null = null;
451
+ // Was the tier ASSUMED by the hub rather than declared by the dispatcher? The
452
+ // distinction matters to the ratchet: an assumed tier must not turn the
453
+ // dispatcher's own first triage call into an "escalation" that needs a reason.
454
+ let taskTierAssumed = false;
455
+ // Correctness obligations are independent of the spend tier. They persist for
456
+ // the current task and reset only through the explicit new-task tool path.
457
+ let processState = createProcessState();
458
+ let taskTriage: ReturnType<typeof createTaskTriageRuntime> | null = null;
459
+ let taskTriageTestTransportActive = false;
460
+ let taskTriageActivity: TaskTriageActivity | null = null;
461
+ let taskTriageConfigStatus: "active" | "off" | "invalid" = "off";
462
+ let taskTriageConfigured = false;
463
+ let processPersistenceBlocked = false;
464
+ let pendingTaskTransition = false;
465
+ let transitionDiversions = 0;
466
+ let transitionHintDelivered = false;
467
+ let transitionBatchRefused = false;
468
+ let orchestratorSelfReadUsed = 0;
469
+ const processBlock = () => processPersistenceBlocked ? { reason: "process_state_corrupt", message: "Process persistence is blocked; dependent effects remain refused. Ask the human to run /af-task-triage-recover for a checked in-session append/readback; if it refuses, inspect or resume a valid session. Never edit session JSONL or reset obligations." } : pendingTaskTransition ? { reason: "task_transition_pending", message: taskTransitionRecoveryHint } : null;
470
+ const persistProcessVerdict = (state: ProcessObligationState, verdict: ProcessVerdict) => {
471
+ try { pi.appendEntry("agent-hub-process-state", processAuditRecord(state, verdict)); }
472
+ catch { processPersistenceBlocked = true; }
473
+ };
474
+ // Duplicate-dispatch guard: fingerprints of (agent, task) already dispatched
475
+ // THIS turn. Auto-research resumes and /af-agents-restart call dispatchAgent
476
+ // directly, so only real dispatcher tool calls are guarded.
477
+ const turnDispatchFingerprints = new Set<string>();
478
+ // ── External-blocker circuit breaker (external-blocker.js) ──
479
+ // Set when a specialist reports it needs something outside the fleet's reach;
480
+ // gates the next dispatch until the human has been addressed. Cleared by an
481
+ // ask_user call, by a new user turn (the human spoke), and by a new task.
482
+ let externalBlockers: { agent: string; what: string }[] = [];
483
+ let externalBlockerAcknowledged = false;
484
+ let externalBlockerRefusedOnce = false;
485
+ // Per-run artifact archive retention (run-namespace.js).
486
+ let runHistoryKeep: number | null = DEFAULT_RUN_HISTORY_KEEP;
487
+ // ── Drift watchdog (drift-watchdog.js) ──
488
+ // Hub-wide setting from the overrides file, live-switchable via /af-watchdog;
489
+ // per-agent overrides ("on"/"off") win over it. In operator work mode a
490
+ // dispatch_agent `watchdog` param wins over both. In orchestrator work mode the
491
+ // watchdog auto-arms unless hub or per-agent is explicitly off; dispatch
492
+ // `watchdog: false` cannot disarm it.
493
+ let watchdogSetting: string = DEFAULT_WATCHDOG_SETTING;
494
+ let watchdogJudgeModel: string | null = null;
495
+ let watchdogSystem1: WatchdogSystem1Session | null = null;
496
+ const communicationStore = createCommunicationStore();
497
+ let triageRuntime: ReturnType<typeof createTriageRuntime> | null = null;
498
+ let proactiveRuntime: ReturnType<typeof createProactiveRuntime> | null = null;
499
+ let system1Snapshot: ReturnType<typeof loadSystem1Snapshot> = normalizeSystem1Config(null);
500
+ let proactiveConfig: ProactiveConfig | null = null;
501
+ let proactiveHubDeliveries = 0;
502
+ const proactiveReportInput = () => proactiveRuntime ? { records: proactiveRuntime.records, history: proactiveRuntime.findings.history, current: proactiveRuntime.findings.current, activity: proactiveRuntime.activity.live(), feedback: { hubDelivered: proactiveHubDeliveries, nativeDelivered: null } } : undefined;
503
+ let hubTaskText: string | undefined;
504
+ const hubCapture = createHubCapture({ root: () => currentCtx?.cwd || process.cwd(), task: () => hubTaskText, policyRoots:()=>sessionOverrides?.policyRoots });
505
+ let watchdogActivity: WatchdogActivity | null = null;
506
+ const watchdogAgentOverrides = new Map<string, "on" | "off">();
507
+ // ── Per-turn cost report (/af-hub-report) ──
508
+ let turnReport: TurnReport = freshTurnReport();
509
+ let lastTurnReport: TurnReport | null = null;
510
+ const sessionTotals = createSessionTotals();
511
+ // Session-wide delegated-spend counter (tokens across all delegate children),
512
+ // surfaced in the status line. Resets on session_start.
513
+ let delegatedTokens = 0;
514
+
515
+ const noProgress = createNoProgressGuard((type, data) => pi.appendEntry(type, data));
516
+ const taskTriageMetadata = () => {
517
+ const current = taskTriage?.current;
518
+ return { taskId: noProgress.taskId(), inputRevision: taskTriage?.inputRevision, configuredStatus: taskTriageConfigStatus,
519
+ runtimeBlocks: [...(processPersistenceBlocked ? ["process_persistence_blocked" as const] : []), ...(pendingTaskTransition ? ["task_transition_pending" as const] : [])],
520
+ assessment: current ? { taskId: current.taskId, evaluationId: current.evaluationId, inputRevision: current.revision, assessment: current.assessment } : undefined };
521
+ };
522
+ let taskIdentityReset: ReturnType<typeof createReservedTaskIdentityReset>;
523
+ let unknownToolCounter = createUnknownToolCounter({ limit: 3 });
524
+ const toolCatalogRuntime = createToolCatalogRuntime(catalogSnapshot("operator", []));
525
+ let latestToolCatalogDelta: ToolCatalogDelta | null = null;
526
+ let latestUnknownToolNotice = "";
527
+ const seenUnknownToolCalls = new Set<string>();
528
+ const resetUnknownToolCounterForCurrentTask = () => {
529
+ unknownToolCounter.resetForNewTask(noProgress.taskId());
530
+ seenUnknownToolCalls.clear();
531
+ latestUnknownToolNotice = "";
532
+ };
533
+ let readWorkMode: () => string = () => "operator";
534
+ const budgetCtx = createBudgetContext({
535
+ getBudgetOverrides: () => budgetOverrides,
536
+ getWorkMode: () => readWorkMode(),
537
+ getTurnDispatchCount: () => turnDispatchCount, setTurnDispatchCount: value => { turnDispatchCount = value; },
538
+ getTurnResearchCount: () => turnResearchCount, setTurnResearchCount: value => { turnResearchCount = value; },
539
+ getTurnBudgetAskUserWaitMs: () => turnBudgetAskUserWaitMs, setTurnBudgetAskUserWaitMs: value => { turnBudgetAskUserWaitMs = value; },
540
+ resetBudgetRecovery: () => budgetRecovery.reset(),
541
+ resetNoProgress: (persistTaskIdentity) => noProgress.reset(persistTaskIdentity), resetUnknownToolCounter: resetUnknownToolCounterForCurrentTask,
542
+ getTaskContinuationCount: () => taskContinuationCount, setTaskContinuationCount: value => { taskContinuationCount = value; },
543
+ getTurnContinuationCount: () => turnContinuationCount, setTurnContinuationCount: value => { turnContinuationCount = value; },
544
+ getTaskDispatchCount: () => taskDispatchCount, setTaskDispatchCount: value => { taskDispatchCount = value; },
545
+ getTaskResearchCount: () => taskResearchCount, setTaskResearchCount: value => { taskResearchCount = value; },
546
+ getTaskLabel: () => taskLabel, setTaskLabel: value => { taskLabel = value; },
547
+ getTaskClock: () => taskClock, setTaskClock: value => { taskClock = value; },
548
+ getTaskReviewRounds: () => taskReviewRounds, setTaskReviewRounds: value => { taskReviewRounds = value; },
549
+ getTaskTier: () => taskTier, setTaskTier: value => { taskTier = value; },
550
+ getTaskTierAssumed: () => taskTierAssumed, setTaskTierAssumed: value => { taskTierAssumed = value; },
551
+ clearTurnDispatchFingerprints: () => turnDispatchFingerprints.clear(),
552
+ clearTaskCapabilities: () => workModePolicy.resetCapabilities(),
553
+ clearExternalBlockers: () => { externalBlockers = []; externalBlockerAcknowledged = false; externalBlockerRefusedOnce = false; },
554
+ resolveIncomingCapabilities: () => { resolveIncomingCapabilities("", true); }, applyWorkModeTools: () => { applyWorkModeTools(); },
555
+ getTurnReport: () => turnReport,
556
+ setStatus: (key, value) => { widgetCtx?.ui?.setStatus(key, value); },
557
+ getAuditContext: () => ({ cwd: identity?.cwd ?? currentCtx?.cwd, sessionId: identity?.session_id, project: identity?.project }),
558
+ appendEntry: (type, data) => { pi.appendEntry(type, data); },
559
+ executionHistory,
560
+ });
561
+ const {
562
+ currentBudget, currentTaskBudget, taskCounters, taskActiveElapsedMs, turnBudgetActiveElapsedMs,
563
+ renewTurnBudgetWindow, continueTaskBudgetWindow, closeTurnActiveTime, resetTaskWindow,
564
+ hubAuditIdentity, hubLocationSuffix, taskResetSnapshot, budgetContinuationSnapshot,
565
+ appendTaskResetEntry, appendBudgetContinuationEntry, updateModeStatus, ensureTaskTier,
566
+ } = budgetCtx;
567
+ const budgetRecovery = createBudgetRecovery({
568
+ check: operation => {
569
+ const task = checkTaskBudget(operation, taskCounters(), currentTaskBudget(), taskActiveElapsedMs(), taskTier);
570
+ if (task) return { ...task, kind: "task" };
571
+ const turn = checkTurnBudget(operation, { dispatches: turnDispatchCount, research: turnResearchCount }, currentBudget(), turnBudgetActiveElapsedMs(), taskTier);
572
+ return turn ? { ...turn, kind: "turn" } : null;
573
+ },
574
+ language: () => userLanguage,
575
+ ask: (id, params, ctx, signal) => requestRuntimeAsk(pi.events, id, params, ctx, signal),
576
+ startWait: id => executionHistory.startAskUser(id),
577
+ endWait: (id, sameTask) => {
578
+ const wait = executionHistory.endAskUser(id, Date.now());
579
+ if (!sameTask) return;
580
+ if (wait > 0) taskClock = addTaskClockWait(taskClock, wait);
581
+ turnBudgetAskUserWaitMs += wait;
582
+ },
583
+ renew: (refusal, correlation, ctx) => {
584
+ const at = Date.now(), prior = budgetContinuationSnapshot(refusal.kind, at);
585
+ if (refusal.kind === "task") continueTaskBudgetWindow(at); else renewTurnBudgetWindow(at);
586
+ appendBudgetContinuationEntry(refusal.kind, refusal.reason, prior, ctx, correlation);
587
+ },
588
+ });
589
+ taskIdentityReset = createReservedTaskIdentityReset(budgetRecovery, noProgress);
590
+
591
+ // ── Verification Contract: assertion ledger (advisory) ──
592
+ // Mutable ownership remains here; the extracted runtime receives explicit ports.
593
+ let assertions: Assertion[] = [];
594
+ const assertionsArtifactsCtx = createAssertionsArtifactsContext({
595
+ getAssertions: () => assertions,
596
+ getSessionDir: () => sessionDir,
597
+ getRunHistoryKeep: () => runHistoryKeep,
598
+ setStatus: (key, value) => { widgetCtx?.ui?.setStatus(key, value); },
599
+ });
600
+ const {
601
+ persistAssertions, assertionStatusLine, renderAssertionLedgerLines, renderAssertionLedgerText,
602
+ updateAssertionStatus, artifactsRoot, ensureArtifactsLayout, archivePreviousRun,
603
+ loadInputArtifacts, appendInputArtifacts, writeRunArtifact, evidencePathExists,
604
+ listArtifactFiles, renderArtifactIndexText, appendMachineHandoffSections,
605
+ } = assertionsArtifactsCtx;
606
+
607
+ const modelPolicy = createModelPolicy<AgentDef>({
608
+ getAllDefs: () => allAgentDefs,
609
+ getActiveDef: name => agentStates.get(name)?.def,
610
+ getResearchDefs: () => researchPersonas,
611
+ refreshUi: () => updateWidget(),
612
+ });
613
+ const {
614
+ allowedModels, substitutedModel, resolvedModel, resolvedSubagentModel,
615
+ resolvedThinking, switchablePersonaDef, allKnownModels,
616
+ } = modelPolicy;
617
+
618
+ let profileCommandContext: any;
619
+ const profileActivation = createProfileActivation({
620
+ busy: () => !profileCommandContext?.isIdle?.() || profileWorkInFlight()>0 ||
621
+ Array.from(agentStates.values()).some(state=>state.status==='running') ||
622
+ Array.from(researchStates.values()).some(state=>state.status==='running'),
623
+ defs: () => allAgentDefs,
624
+ available: async () => {
625
+ await profileCommandContext.modelRegistry.refresh?.();
626
+ return (profileCommandContext.modelRegistry.getAvailable?.()??[]).map((m:any)=>`${m.provider}/${m.id}`);
627
+ },
628
+ dispatcher: () => profileCommandContext?.model ? {model:`${profileCommandContext.model.provider}/${profileCommandContext.model.id}`,thinking:pi.getThinkingLevel()} : undefined,
629
+ setDispatcher: async selection => {
630
+ const slash=selection.model.indexOf('/');
631
+ const model=profileCommandContext.modelRegistry.find(selection.model.slice(0,slash),selection.model.slice(slash+1));
632
+ if(!model || !await pi.setModel(model)) return false;
633
+ if(selection.thinking) pi.setThinkingLevel(selection.thinking as any);
634
+ return true;
635
+ },
636
+ apply: profile => modelPolicy.applyProfile(profile),
637
+ });
638
+ pi.on('model_select', async (event,ctx) => {
639
+ contextWindow=event.model.contextWindow||0;
640
+ if(profileActivation.switching()) return;
641
+ const active=readActiveProfile();if(!active || !hasExplicitDispatcher(active.profile)) return;
642
+ try { assertProfileModel(`${event.model.provider}/${event.model.id}`,active); }
643
+ catch(error) {
644
+ ctx.abort();ctx.ui.notify(String(error),'error');
645
+ if(hasExplicitDispatcher(active.profile)) {
646
+ const target=dispatcherSelection(active.profile).model, slash=target.indexOf('/');
647
+ const model=ctx.modelRegistry.find(target.slice(0,slash),target.slice(slash+1));
648
+ if(model) await pi.setModel(model);
649
+ }
650
+ }
651
+ });
652
+ pi.on('before_provider_request', async (_event,ctx) => {
653
+ const active=readActiveProfile();
654
+ if(!ctx.model || !active || !hasExplicitDispatcher(active.profile)) return;
655
+ try { assertProfileModel(`${ctx.model.provider}/${ctx.model.id}`,active); }
656
+ catch(error) {ctx.abort();ctx.ui.notify(String(error),'error');}
657
+ });
658
+
659
+ function appendDeclaredScope(task: string, scopeGlobs: string[]): string {
660
+ if (!scopeGlobs || scopeGlobs.length === 0) return task;
661
+ 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")}`;
662
+ }
663
+
664
+ function loadAgents(cwd: string): void {
665
+ if (sessionDir) closeEvidenceSession(sessionDir);
666
+ loadAgentConfiguration(cwd, {
667
+ setSessionDir: hubStateCtx.setSessionDir, getSessionDir: hubStateCtx.getSessionDir,
668
+ archivePreviousRun, ensureArtifactsLayout, resetAssertions: () => { assertions = []; },
669
+ setAgentDefs: value => { allAgentDefs = value; }, setTeams: value => { teams = value; },
670
+ setModelProfiles: value => { modelProfiles = value; }, setModelProfileErrors: errors => { modelProfileErrors=errors; }, setDispatchPolicy: value => { dispatchPolicy = value; },
671
+ setDispatchPolicyWarnings: value => { dispatchPolicyWarnings = value; },
672
+ });
673
+ pruneEvidenceSessions(sessionDir, runHistoryKeep);
674
+ }
675
+
676
+ const agentStateFactory = createAgentStateFactory(() => sessionDir);
677
+ const { sessionHealthIo, adoptableSessionFile, freshAgentState } = agentStateFactory;
678
+
679
+ // Auto-size grid columns based on team size
680
+ function recomputeGrid() {
681
+ gridCols = gridColumnsForSize(agentStates.size);
682
+ }
683
+
684
+ const rosterPolicy = createRosterPolicy<AgentDef, AgentState>({
685
+ getTeams: () => teams, getAllDefs: () => allAgentDefs, getStates: () => agentStates,
686
+ getActiveTeamName: () => activeTeamName, setActiveTeamName: value => { activeTeamName = value; },
687
+ clearBackendNotices: () => comsMissNotified.clear(), createFreshState: freshAgentState,
688
+ adoptSession: adoptableSessionFile,
689
+ quarantineSession: agentStateFactory.quarantine,
690
+ persist: team => pi.appendEntry(NATIVE_ROSTER_ENTRY_TYPE, persistedNativeRosterState(team)),
691
+ recompute: recomputeGrid, refreshUi: () => updateWidget(), displayName,
692
+ orchestratorNeedsRosterAfterDrop: size => orchestratorNeedsRoster(getWorkMode(), size),
693
+ });
694
+ const { activateTeam, persistActiveRoster, add: rosterAdd, drop: rosterDrop } = rosterPolicy;
695
+
696
+ // ── Shared model presentation ─────────────────
697
+ // These formatters serve the extracted grid and the remaining composition-root
698
+ // call sites. Keep one implementation so cards, fleet rows, menus, fallback
699
+ // notices, and the footer retain the same presentation semantics.
700
+ function shortModel(model: string | undefined): string {
701
+ return model ? model.split("/").pop()! : "default";
702
+ }
703
+
704
+ // A " (code)" thinking badge for display, or "" when the level is off.
705
+ function thinkingSuffix(rawThinking: string | undefined): string {
706
+ const code = abbrevThinking(resolveThinkingLevel(rawThinking));
707
+ return code ? ` (${code})` : "";
708
+ }
709
+
710
+ // The model + thinking badge a persona would dispatch with: "gpt-5.5 (xh)".
711
+ function modelWithThinking(def: AgentDef): string {
712
+ return shortModel(resolvedModel(def)) + thinkingSuffix(resolvedThinking(def));
713
+ }
714
+
715
+ // ── Shared fleet source + below-editor widget ───────────────────────────
716
+ const fleetSource = createFleetSource({
717
+ getAgents: () => agentStates,
718
+ getResearch: () => researchStates,
719
+ getPeerInputs: format => fleetPeerInputs(format),
720
+ getPeerCards: () => peerCards,
721
+ getPendingReplies: () => pendingReplies.values(),
722
+ displayName,
723
+ modelForAgent: state => state.lastBackend === "coms" ? shortModel(state.comsPeerModel) : modelWithThinking(state.def),
724
+ modelForResearch: state => shortModel(state.model) + thinkingSuffix(resolvedThinking(state.def)),
725
+ modelForPeer: abbreviateModel,
726
+ getSystem1: () => watchdogActivity?.live() ?? null,
727
+ getTaskTriage: () => {
728
+ if (!taskTriageConfigured && !processState.additions?.length) return null;
729
+ try { return { ...taskTriageMetadata(), process: { schema: processState.schema, ...evaluateProcessObligations(processState, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER }) } }; }
730
+ catch { return { ...taskTriageMetadata(), process: { schema: "invalid" } }; }
731
+ },
732
+ getProactive: () => proactiveRuntime ? { records: proactiveRuntime.records, history: proactiveRuntime.findings.history, current: proactiveRuntime.findings.current, activity: proactiveRuntime.activity.live() } : null,
733
+ });
734
+ let fleetActions: ReturnType<typeof createFleetActions<AgentState, ResearchState>> | null = null;
735
+ let fleetUiGeneration = 0;
736
+ const gridUI = createGridUI({
737
+ getWidgetContext: () => widgetCtx,
738
+ getRows: now => fleetSource.rows(now, { showFinished: true }),
739
+ getSnapshot: now => { const source = fleetSource.snapshot(now); return { rows: buildFleetRows(source, { showFinished: true }), proactive: source.proactive }; },
740
+ handleIntent: async intent => {
741
+ if (!fleetActions || !widgetCtx) return;
742
+ if (intent.type === "system1") { await gridUI.withSuspended(() => openSystem1Communication(widgetCtx!, communicationStore)); return; }
743
+ if (intent.type === "open") await gridUI.withSuspended(() => fleetActions!.open(intent.key, intent.runToken, widgetCtx!));
744
+ else await fleetActions.execute(intent.type, intent.key, intent.runToken, widgetCtx);
745
+ },
746
+ });
747
+ const { updateWidget } = gridUI;
748
+ refreshFleetUi = updateWidget;
749
+
750
+ // ── Delegation observability ─────────────────
751
+ const dispatchObservability = createDispatchObservability({
752
+ getSessionDir: () => sessionDir,
753
+ getDelegatedTokens: () => delegatedTokens,
754
+ setDelegatedTokens: value => { delegatedTokens = value; },
755
+ getWidgetContext: () => widgetCtx,
756
+ executionHistory,
757
+ displayName,
758
+ safeAgentKey,
759
+ safePathWithin,
760
+ createTranscriptStore: createFleetTranscriptStore,
761
+ appendTimelineText,
762
+ appendTimelineEvent,
763
+ updateWidget,
764
+ });
765
+ const { startDelegationWatch } = dispatchObservability;
766
+
767
+ // ── Dispatch Agent (returns Promise) ─────────
768
+
769
+ // ── Extracted coms dispatch, drift judge, and return extraction ──
770
+ const dispatchComs = createDispatchComs({
771
+ getIdentity: () => identity,
772
+ resolveTarget: target => coms.resolveTarget(target),
773
+ send: (params, auditExtra) => coms.send(params, auditExtra),
774
+ getPendingReply: msgId => pendingReplies.get(msgId),
775
+ deletePendingReply: msgId => { pendingReplies.delete(msgId); },
776
+ getSessionDir: () => sessionDir,
777
+ getWatchdogJudgeModel: () => watchdogJudgeModel,
778
+ getResearcherModel: () => {
779
+ const researcherDef = allAgentDefs.find(def => def.name.toLowerCase() === "researcher");
780
+ return researcherDef ? resolvedModel(researcherDef) ?? null : null;
781
+ },
782
+ displayName,
783
+ safeAgentKey,
784
+ safePathWithin,
785
+ appendInputArtifacts,
786
+ appendDeclaredScope,
787
+ buildRulesProtocol,
788
+ buildDocsProtocol,
789
+ updateWidget,
790
+ spawnPiAgent,
791
+ });
792
+ const { dispatchViaComs, runDriftJudge, runReturnExtraction } = dispatchComs;
793
+
794
+ const nativeDispatch = createDispatchNative({
795
+ prepareDiscovery:input=>prepareDiscoveryNative(pi,input),
796
+ launchIdentity:()=>noProgress.taskToken(),
797
+ nativeAdmission:persona=>!processBlock()&&!provisionalCapabilityRefusal('fleet')&&!processPreEffectGate(processState,'child',persona)&&!checkTaskBudget('dispatch',{...taskCounters(),dispatches:Math.max(0,taskDispatchCount-1)},currentTaskBudget(),taskActiveElapsedMs(),taskTier)&&!checkTurnBudget('dispatch',{dispatches:Math.max(0,turnDispatchCount-1),research:turnResearchCount},currentBudget(),turnBudgetActiveElapsedMs(),taskTier),
798
+ getAgentState: key => agentStates.get(key),
799
+ getProcessState: () => processState,
800
+ listAgentStates: () => Array.from(agentStates.values()),
801
+ getSessionDir: () => sessionDir,
802
+ getDispatchPolicy: () => dispatchPolicy,
803
+ isComsReady: () => comsReady,
804
+ getIdentity: () => identity,
805
+ peersInScope: () => peersInScope(),
806
+ wasComsMissNotified: personaKey => comsMissNotified.has(personaKey),
807
+ markComsMissNotified: personaKey => { comsMissNotified.add(personaKey); },
808
+ startMonitorChild: (input, env) => {
809
+ const monitorStart = monitorTurnId;
810
+ return monitorStart ? monitorBridge?.startChild({ ...input, parentId: monitorStart }, env) : undefined;
811
+ },
812
+ finalizeMonitorChild: (task, output, status) => monitorBridge?.finalizeChildFor(task, output, status),
813
+ registerMonitorWaitOnly: (monitorKey, state) => monitorBridge?.registerWaitOnly(monitorKey, () => state.comsAbort?.()),
814
+ registerMonitorProcess: (task, proc) => monitorBridge?.registerOwnedProcessFor(task, proc),
815
+ appendMonitorOutput: (task, delta) => monitorBridge?.appendOutputFor(task, delta),
816
+ getContextWindow: () => contextWindow,
817
+ currentBudget,
818
+ bumpRecycle: () => { turnReport.recycles++; sessionTotals.recycles++; },
819
+ bumpDriftStop: () => { turnReport.driftStops++; sessionTotals.driftStops++; },
820
+ getSessionHealthIo: () => sessionHealthIo,
821
+ getSafetyHarnessPath: () => safetyHarnessPath,
822
+ getDelegateExtensionPath: () => delegateExtPath,
823
+ getReconSearchTimeoutMs: () => reconSearchTimeoutMs,
824
+ getProjectDocsPaths: () => projectDocsPaths,
825
+ getUserLanguage: () => userLanguage,
826
+ getWatchdogSetting: () => watchdogSetting,
827
+ getWatchdogAgentOverride: key => watchdogAgentOverrides.get(key),
828
+ getWatchdogSystem1: () => watchdogSystem1,
829
+ getWatchdogActivity: () => watchdogActivity,
830
+ getProactiveRuntime: () => proactiveRuntime,
831
+ getProactiveConfig: () => proactiveConfig,
832
+ getProactiveCapture: () => proactiveRuntime ? hubCapture : null,
833
+ getPolicyRoots: () => sessionOverrides?.policyRoots,
834
+ getWorkMode: () => getWorkMode(),
835
+ providerSemaphore,
836
+ executionHistory,
837
+ displayName,
838
+ shortModel: model => shortModel(model),
839
+ resolvedModel,
840
+ resolvedThinking,
841
+ resolveThinkingLevel,
842
+ resolvedSubagentModel,
843
+ substitutedModel,
844
+ modelWindowLookup,
845
+ specialistProjectPolicyPaths,
846
+ guardrailEnv,
847
+ appendInputArtifacts,
848
+ appendDeclaredScope,
849
+ flushTimelineStore,
850
+ appendTimelineText,
851
+ appendTimelineEvent,
852
+ createTranscriptStore: createFleetTranscriptStore,
853
+ updateWidget,
854
+ startDelegationWatch,
855
+ dispatchViaComs,
856
+ runDriftJudge,
857
+ notifyProviderQueue,
858
+ spawnPiAgentWithModelFallback,
859
+ });
860
+ const { dispatchAgent } = nativeDispatch;
861
+
862
+ // Shared child guardrail environment. Dispatch-native and research use the
863
+ // same root-owned exemptions and coms escalation endpoint.
864
+ function guardrailEnv(agentId: string): Record<string, string> {
865
+ const env: Record<string, string> = { [AGENT_ID_ENV]: agentId };
866
+ if (sessionOverrides?.policyRoots) env[FILESYSTEM_POLICY_ROOTS_ENV]=JSON.stringify(sessionOverrides.policyRoots);
867
+ if (exemptionsFile) env[EXEMPTIONS_FILE_ENV] = exemptionsFile;
868
+ if (comsReady && identity) env[ASK_ENDPOINT_ENV] = identity.endpoint;
869
+ return env;
870
+ }
871
+
872
+ // ── Research helper runtime ────────────────────
873
+ // The composition root owns the mutable bindings; the runtime reaches them only
874
+ // through these explicit ports so later controls can keep stable handles.
875
+ const researchRuntime = createResearchRuntime<AgentDef>({
876
+ prepareDiscovery:input=>prepareDiscoveryNative(pi,input),
877
+ launchIdentity:()=>noProgress.taskToken(),
878
+ researchAdmission:()=>!processBlock(),
879
+ getResearchStates: () => researchStates,
880
+ setResearchStates: value => { researchStates = value; },
881
+ getNextResearchId: () => nextResearchId,
882
+ setNextResearchId: value => { nextResearchId = value; },
883
+ hubState: hubStateCtx, budget: budgetCtx, artifacts: assertionsArtifactsCtx,
884
+ executionHistory, providerSemaphore,
885
+ getSafetyHarnessPath: () => safetyHarnessPath,
886
+ getReconSearchTimeoutMs: () => reconSearchTimeoutMs,
887
+ getContextWindow: () => contextWindow,
888
+ resolvedModel, resolvedThinking, resolveThinkingLevel, fallbackModelFor, substitutedModel,
889
+ modelWindowLookup, guardrailEnv, notifyProviderQueue, spawnPiAgentWithModelFallback,
890
+ getProjectPolicyPaths: specialistProjectPolicyPaths,
891
+ getProjectDocsPaths: () => projectDocsPaths,
892
+ nativeResearchSystemPrompt, requireSafetyHarness, shortModel, displayName,
893
+ flushTimelineStore, appendTimelineText, appendTimelineEvent,
894
+ createTranscriptStore: createFleetTranscriptStore,
895
+ onElapsed: () => updateWidget(),
896
+ });
897
+
898
+ // ── Embedded coms: shared registry, transport, and pool core ──
899
+ const peersInScope = () => coms.peersInScope();
900
+ const resolveTarget = (target: string) => coms.resolveTarget(target);
901
+
902
+ const poolPresentation = createPoolPresentation({
903
+ getIdentity: () => identity,
904
+ getDisplayProject: () => coms.scope.displayProject,
905
+ includeExplicitPeers: () => coms.scope.includeExplicit,
906
+ getPeerCards: () => peerCards,
907
+ readProjectEntries: readAllRegistryEntries,
908
+ readAllEntries: readAllRegistryEntriesAcrossProjects,
909
+ truncate: truncateToWidth,
910
+ });
911
+ const fleetPeerInputs = poolPresentation.peerInputs;
912
+
913
+ // ── Extracted tool execution wiring ──
914
+ // Mutable fleet state remains composition-owned; executor modules receive ports.
915
+ let herdrFleetReady = false;
916
+ const hubSpawnedPeers = new Map<string, { name: string; paneId: string | null; addressed: boolean }>();
917
+ const markPeerAddressed = (name: string) => {
918
+ const entry = hubSpawnedPeers.get(String(name || "").toLowerCase());
919
+ if (entry) entry.addressed = true;
920
+ };
921
+ let lastHubPiSpawnAt: number | null = null;
922
+
923
+ let askUserAvailable = false;
924
+ let baselineTools: string[] = [];
925
+ let contextPressureState: ContextPressureState = createContextPressureState();
926
+ const pressureRootState = createContextPressureRootState();
927
+
928
+ function pendingCapabilityOperations(): PendingOperation[] {
929
+ const pending: PendingOperation[] = [];
930
+ if (pendingTaskTransition) pending.push({ pack: "fleet", kind: "task-transition" });
931
+ if (processOpenObligations(processState).some(stage => stage === "plan" || stage === "review")) pending.push({ pack: "fleet", kind: "process-stage" });
932
+ 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" });
933
+ if (pendingReplies.size > 0 || pendingHandoff) pending.push({ pack: "peer", kind: "message" });
934
+ if (hubSpawnedPeers.size > 0) pending.push({ pack: "workspace", kind: "pane" });
935
+ return pending;
936
+ }
937
+ function recordToolCatalogChange(change: { fromMode: WorkMode; toMode: WorkMode; previous: readonly string[]; next: readonly string[]; reason: "refresh" | "mode_switch" }): void {
938
+ const { snapshot, delta } = toolCatalogRuntime.reconcile(change);
939
+ latestToolCatalogDelta = delta;
940
+ unknownToolCounter.noteCatalogChange(delta.catalogVersion);
941
+ const evidenceRef = `session-entry:${TOOL_CATALOG_ENTRY_TYPE}:${delta.catalogVersion}`;
942
+ let persisted = false;
943
+ try { pi.appendEntry(TOOL_CATALOG_ENTRY_TYPE, { snapshot, delta, reason: change.reason }); persisted = true; } catch {}
944
+ if (persisted && delta.evidence.changed) noProgress.establishToolStateChange(delta.evidence.previousCatalogVersion, delta.evidence.catalogVersion, evidenceRef);
945
+ }
946
+ function capabilityContextState(): ContextState {
947
+ if (contextPressureState.phase === "warning") return "approaching-compaction";
948
+ if (contextPressureState.phase !== "normal" || contextPressureState.pressure === "imminent") return "imminent-compaction";
949
+ if (contextPressureState.pressure === "approaching") return "approaching-compaction";
950
+ const percent = currentCtx?.getContextUsage?.()?.percent;
951
+ if (typeof percent === "number" && percent >= 90) return "imminent-compaction";
952
+ if (typeof percent === "number" && percent >= 80) return "approaching-compaction";
953
+ return "normal";
954
+ }
955
+ const workModePolicy = createWorkModePolicy({
956
+ getBaselineTools: () => baselineTools, getRosterSize: () => agentStates.size,
957
+ getDeterministicToolsEnabled: () => resolveAssist(readActiveProfile()?.profile.assist)['deterministic-tools'],
958
+ getAgenticAskEnabled: () => agenticHubEnabled(pi),
959
+ getFileDiscoveryEnabled: () => discoveryHubEnabled(pi),
960
+ getDispatchTriageEnabled: () => triageRuntime?.available === true,
961
+ activateFallbackRoster: ctx => {
962
+ if (!rosterPolicy.activateFirstValidTeam()) return;
963
+ workModePolicy.clearRosterRecovery();
964
+ persistActiveRoster();
965
+ setTimeout(replayDeferredRecoveryInputs, 0);
966
+ updateWidget();
967
+ ctx.ui.setStatus("agent-team", `Team: ${activeTeamName} (${agentStates.size})`);
968
+ },
969
+ getActiveTeamName: () => activeTeamName, getComsReady: () => comsReady,
970
+ getHerdrReady: () => herdrFleetReady, getAskUserAvailable: () => askUserAvailable,
971
+ getIdentityLabel: () => identity ? `${identity.name}@${identity.project}` : null,
972
+ getTaskTier: () => taskTier, getPendingOperations: pendingCapabilityOperations,
973
+ getContextState: capabilityContextState, getActiveTools: () => pi.getActiveTools(), setActiveTools: tools => pi.setActiveTools(tools),
974
+ recordToolCatalog: recordToolCatalogChange,
975
+ persist: (type, data) => pi.appendEntry(type, data), replayDeferredInputs: replayDeferredRecoveryInputs,
976
+ watchdogArmed: mode => resolveWatchdogActive(undefined, undefined, watchdogSetting, mode),
977
+ });
978
+ const {
979
+ getWorkMode, getCapabilityResolution, resolveIncomingCapabilities, provisionalCapabilityRefusal,
980
+ applyWorkModeTools, modelWorkBlockedByRosterRecovery,
981
+ statusText: workModeStatusText, applySelection: applyWorkModeSelection, openPicker: openWorkModePicker,
982
+ } = workModePolicy;
983
+ readWorkMode = () => getWorkMode();
984
+
985
+
986
+ const toolCtx: ToolContext = createToolExecutionOrchestration({
987
+ dispatch: {
988
+ state: {
989
+ getTurnDispatchCount: () => turnDispatchCount, setTurnDispatchCount: value => { turnDispatchCount = value; },
990
+ getTurnResearchCount: () => turnResearchCount, setTurnResearchCount: value => { turnResearchCount = value; },
991
+ getTaskDispatchCount: () => taskDispatchCount, setTaskDispatchCount: value => { taskDispatchCount = value; },
992
+ getTaskResearchCount: () => taskResearchCount, setTaskResearchCount: value => { taskResearchCount = value; },
993
+ getTaskReviewRounds: () => taskReviewRounds, setTaskReviewRounds: value => { taskReviewRounds = value; },
994
+ getTaskTier: () => taskTier, getTurnReport: () => turnReport, getSessionTotals: () => sessionTotals,
995
+ getProcessState: () => processState, setProcessState: value => { processState = value; }, persistProcessVerdict, processBlock,
996
+ getTurnDispatchFingerprints: () => turnDispatchFingerprints,
997
+ getExternalBlockers: () => externalBlockers,
998
+ getExternalBlockerAcknowledged: () => externalBlockerAcknowledged, setExternalBlockerAcknowledged: value => { externalBlockerAcknowledged = value; },
999
+ getExternalBlockerRefusedOnce: () => externalBlockerRefusedOnce, setExternalBlockerRefusedOnce: value => { externalBlockerRefusedOnce = value; },
1000
+ isAskUserAvailable: () => askUserAvailable, getUserLanguage: () => userLanguage, getSessionDir: () => sessionDir,
1001
+ getAgentStates: () => agentStates as any, getAssertions: () => assertions, getResearchPersonas: () => researchPersonas,
1002
+ getActiveWritableDispatches: () => activeWritableDispatches, setActiveWritableDispatches: value => { activeWritableDispatches = value; },
1003
+ getWritableOverlapCounter: () => writableOverlapCounter, setWritableOverlapCounter: value => { writableOverlapCounter = value; },
1004
+ },
1005
+ budget: budgetCtx, budgetRecovery, noProgress, artifacts: assertionsArtifactsCtx, research: researchRuntime,
1006
+ provisionalCapabilityRefusal, dispatchAgent, runReturnExtraction,
1007
+ extractNeedsResearch, extractAskUserQuestions, contextPressure: percent => percent >= CONTEXT_WARN_THRESHOLD, displayName,
1008
+ resolvedAgentModel: (def, ctx) => resolvedModel(def as AgentDef) ?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined),
1009
+ getToolCatalogVersion: () => toolCatalogRuntime.catalogForMessage().catalogVersion,
1010
+ },
1011
+ actions: {
1012
+ budget: budgetCtx, artifacts: assertionsArtifactsCtx, hubState: hubStateCtx,
1013
+ provisionalCapabilityRefusal,
1014
+ getTaskTier: () => taskTier, setTaskTier: value => { taskTier = value; },
1015
+ getTaskTierAssumed: () => taskTierAssumed, setTaskTierAssumed: value => { taskTierAssumed = value; },
1016
+ getProcessState: () => processState, setProcessState: value => { processState = value; },
1017
+ processBlock, adoptTaskTriage: async (id, newTask, expandedScope) => {
1018
+ if (processPersistenceBlocked) throw new Error("corrupt process state");
1019
+ const next = await adoptTaskTriageState({ runtime: taskTriage, taskId: id, newTask,
1020
+ expandedScope, pendingTransition: pendingTaskTransition, state: processState,
1021
+ persist: state => pi.appendEntry("agent-hub-process-state", processAuditRecord(state, evaluateProcessObligations(state, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER }))),
1022
+ onPostCommitFailure: () => { processPersistenceBlocked = true; },
1023
+ });
1024
+ pendingTaskTransition = false;
1025
+ transitionDiversions = 0;
1026
+ transitionHintDelivered = false;
1027
+ transitionBatchRefused = false;
1028
+ try { pi.appendEntry(TASK_TRANSITION_ENTRY_TYPE, { pending: false }); } catch { processPersistenceBlocked = true; }
1029
+ return next;
1030
+ },
1031
+ persistProcessState: value => persistProcessVerdict(value, evaluateProcessObligations(value, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER })),
1032
+ getTaskDispatchCount: () => taskDispatchCount, getTaskResearchCount: () => taskResearchCount,
1033
+ getTurnReport: () => turnReport, getAssertions: () => assertions, setAssertions: value => { assertions = value; },
1034
+ currentTaskId: () => noProgress.taskId(), currentRevision: ctx => worktreeRevision(ctx.cwd || process.cwd(), []),
1035
+ adoptReservedTaskId: (id, resetTaskWindow) => taskIdentityReset.run(id, resetTaskWindow),
1036
+ confirmTaskSupersession: (input, ctx, signal) => confirmTaskSupersession(input, ctx, { language: () => userLanguage, currentTaskId: () => noProgress.taskId(), ask: (id, params, askCtx, askSignal) => requestRuntimeAsk(pi.events, id, params, askCtx, askSignal), startWait: id => executionHistory.startAskUser(id), endWait: (id, sameTask) => { const wait = executionHistory.endAskUser(id, Date.now()); if (sameTask && wait > 0) { taskClock = addTaskClockWait(taskClock, wait); turnBudgetAskUserWaitMs += wait; } } }, signal),
1037
+ getAgentStates: () => agentStates, rosterAdd, rosterDrop,
1038
+ getIdentity: () => identity, getComs: () => coms, resolveTarget,
1039
+ appendMachineHandoffSections, markPeerAddressed,
1040
+ },
1041
+ herdr: {
1042
+ getProcessState: () => processState, processBlock,
1043
+ provisionalCapabilityRefusal, isFleetReady: () => herdrFleetReady, isComsReady: () => comsReady,
1044
+ getIdentity: () => identity, getCurrentContext: () => currentCtx, peersInScope,
1045
+ getComsPeerNames: () => peersInScope().map(peer => peer.name), herdr: herdrApi,
1046
+ readEnvFile: file => fs.readFileSync(file, "utf-8"), envFileExists: file => fs.existsSync(file),
1047
+ getLastPiSpawnAt: () => lastHubPiSpawnAt, setLastPiSpawnAt: value => { lastHubPiSpawnAt = value; },
1048
+ recordSpawnedPeer: (name, paneId) => { hubSpawnedPeers.set(name.toLowerCase(), { name, paneId, addressed: false }); },
1049
+ },
1050
+ });
1051
+
1052
+ function triageInput(task: string, scope: string[], language: string, domain: string): TriageInput {
1053
+ const taskGate = checkTaskBudget("dispatch", budgetCtx.taskCounters(), budgetCtx.currentTaskBudget(), budgetCtx.taskActiveElapsedMs(), taskTier);
1054
+ const turnGate = checkTurnBudget("dispatch", { dispatches: turnDispatchCount, research: turnResearchCount }, budgetCtx.currentBudget(), budgetCtx.turnBudgetActiveElapsedMs(), taskTier);
1055
+ const candidates = [...agentStates.values()].map(s => {
1056
+ const name = s.def.name.toLowerCase();
1057
+ const research = ["researcher", "deep-researcher", ...researchPersonas.map(p => p.name.toLowerCase())].includes(name);
1058
+ const gate = processBlock() ?? processPreEffectGate(processState, "child", name) ?? (processAllowsPersona(processState,name) ? null : checkTierPersonaGate(taskTier,name)) ?? checkReviewRoundCap(taskTier,name,taskReviewRounds) ?? checkDocsLane(name, scope, undefined) ?? taskGate ?? turnGate;
1059
+ return { name, description: s.def.description, ...(research ? { excluded: "research_persona" } : s.status === "running" ? { excluded: "busy" } : gate ? { excluded: gate.reason } : {}) };
1060
+ });
1061
+ return { taskId: noProgress.taskId(), task, scope, language, domain, candidates, constraints: JSON.stringify({ tier: taskTier, process: { risk: processState.risk, scope: processState.scope }, externalBlocked: externalBlockers.length > 0 && !externalBlockerAcknowledged }), complete: !(externalBlockers.length > 0 && !externalBlockerAcknowledged) };
1062
+ }
1063
+ registerAgenticHub(pi);
1064
+ registerDiscoveryHub(pi);
1065
+ registerDispatchTriage(pi, { runtime: () => triageRuntime, input: triageInput, blocked: () => provisionalCapabilityRefusal("fleet") });
1066
+
1067
+ // Keep the extracted tool surface flat and greppable in this composition root.
1068
+ registerDispatchAgent(pi, toolCtx, { disposition: (id, persona, reason) => triageRuntime?.disposition(id, persona, reason) ?? false, submitted: (id, persona, status) => triageRuntime?.submitted(id, persona, status) });
1069
+ registerSpawnResearch(pi, toolCtx);
1070
+ registerRunFlow(pi, {
1071
+ sessionDir: () => sessionDir,
1072
+ taskId: () => noProgress.taskId(),
1073
+ processObligations: () => evaluateProcessObligations(processState, { writable: false, budgetTier: taskTier ?? DEFAULT_TASK_TIER }),
1074
+ effectiveScoutConfig: cwd => {
1075
+ const persona = resolveFlowPersona("researcher", cwd);
1076
+ const model = persona.model!;
1077
+ assertFlowProfileModel(model);
1078
+ return { model, profile: readActiveProfile()?.name ?? null, tools: persona.tools.split(",").map(value => value.trim()).filter(Boolean), fallback: persona.fallbackModel ?? null, allowlisted: true };
1079
+ },
1080
+ reserveBudget: async (params, ctx, signal) => {
1081
+ ensureTaskTier();
1082
+ const blocked = await budgetRecovery.ensure("research", `flow scout: ${params.request}`, ctx, signal);
1083
+ if (blocked) return { charged: false, operation: "research", owner: "hub", refusal: blocked.message };
1084
+ if (signal?.aborted) return { charged: false, operation: "research", owner: "hub", refusal: "Flow cancelled before budget charge." };
1085
+ const taskBlock = checkTaskBudget("research", budgetCtx.taskCounters(), budgetCtx.currentTaskBudget(), budgetCtx.taskActiveElapsedMs(), taskTier);
1086
+ if (taskBlock) return { charged: false, operation: "research", owner: "hub", refusal: taskBlock.message };
1087
+ const turnBlock = checkTurnBudget("research", { dispatches: turnDispatchCount, research: turnResearchCount }, budgetCtx.currentBudget(), budgetCtx.turnBudgetActiveElapsedMs(), taskTier);
1088
+ if (turnBlock) return { charged: false, operation: "research", owner: "hub", refusal: turnBlock.message };
1089
+ turnResearchCount++; taskResearchCount++; turnReport.research++; sessionTotals.research++; budgetCtx.updateModeStatus();
1090
+ return { charged: true, operation: "research", owner: "hub" };
1091
+ },
1092
+ });
1093
+ registerSetTaskTier(pi, toolCtx);
1094
+ registerTeamAdjust(pi, toolCtx);
1095
+ registerVerificationContract(pi, toolCtx);
1096
+ registerComsTools(pi, toolCtx);
1097
+ registerFleetTools(pi, toolCtx);
1098
+ registerFilesystemTool(pi, {
1099
+ enabled: () => resolveAssist(readActiveProfile()?.profile.assist)['deterministic-tools'],
1100
+ readOnly: () => getWorkMode() === "orchestrator",
1101
+ sessionDir: () => sessionDir,
1102
+ policyRoots: () => sessionOverrides?.policyRoots,
1103
+ managedReadbackAllowed: handle => discoveryManagedReadbackAllowed(pi,handle),
1104
+ remainingSelfReadBytes: () => Math.max(0, 64 * 1024 - orchestratorSelfReadUsed),
1105
+ noteSelfReadBytes: bytes => { orchestratorSelfReadUsed += bytes; },
1106
+ });
1107
+
1108
+ const researchControls = createResearchControls({
1109
+ runtime: researchRuntime,
1110
+ refresh: () => {},
1111
+ getAgents: () => agentStates, displayName, modelWorkBlocked: modelWorkBlockedByRosterRecovery,
1112
+ cancelWait: (state, kind) => cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), event: { kind } }),
1113
+ cancelOwned: state => { fenceOperatorCancel(state); cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), treeKill: killPiTree }); },
1114
+ restartSpecialist: async (state: AgentState, ctx) => {
1115
+ if (state.status === "running" && (state.proc || state.comsAbort)) {
1116
+ let resolveTermination!: () => void;
1117
+ const terminated = new Promise<void>(resolve => { resolveTermination = resolve; });
1118
+ state.onTerminate = resolveTermination;
1119
+ fenceOperatorCancel(state);
1120
+ if (state.proc) { state.killedByOperator = true; state.restarting = true; if (state.dispatchId) proactiveRuntime?.abort(safeAgentKey(state.def.name), state.dispatchId); killPiTree(state.proc); }
1121
+ else await cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), event: { kind: "restart" } });
1122
+ await terminated;
1123
+ }
1124
+ state.sessionFile = null;
1125
+ const result = await dispatchAgent(state.def.name, state.task, ctx);
1126
+ 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 });
1127
+ },
1128
+ });
1129
+
1130
+ // ── ask_user Tool (dispatcher → human) ──
1131
+ //
1132
+ // We do NOT register `ask_user` here. The recommended companion package
1133
+ // `pi-ask-user` (see docs/pi-setup.md) owns that tool name with a richer
1134
+ // implementation. Registering our own conflicts regardless of load order:
1135
+ // - if we register first, pi-ask-user fails to load
1136
+ // - if pi-ask-user registers first, our registration fails
1137
+ // and pi has no synchronous probe at load time — `pi.getAllTools()` is
1138
+ // a runtime action method that throws when called from the factory.
1139
+ //
1140
+ // Instead, in `session_start` (where action methods ARE allowed) we check
1141
+ // `pi.getAllTools()`, gate `ask_user` into `setActiveTools` only if present,
1142
+ // and warn the user to `pi install npm:pi-ask-user` if it's missing.
1143
+
1144
+
1145
+ // ── Commands ─────────────────────────────────
1146
+
1147
+ const commandCtx: CommandContext = {
1148
+ setWidgetContext: ctx => { widgetCtx = ctx; },
1149
+ applyWorkModeSelection,
1150
+ getWorkModeStatusText: workModeStatusText,
1151
+ openWorkModePicker,
1152
+ handleBudgetContinue: async ctx => { await budgetRecovery.resume(ctx); },
1153
+ handleTaskTriageRecover: () => {
1154
+ if (!processPersistenceBlocked) return false;
1155
+ try {
1156
+ const recovered = recoverTaskTriageProcessState({ state: processState, current: taskTriage?.current ? { taskId: taskTriage.current.taskId, evaluationId: taskTriage.current.evaluationId, inputRevision: taskTriage.current.revision, assessment: taskTriage.current.assessment } : null,
1157
+ taskId: noProgress.taskId(), budgetTier: taskTier ?? DEFAULT_TASK_TIER,
1158
+ append: record => pi.appendEntry("agent-hub-process-state", record),
1159
+ entries: () => currentCtx?.sessionManager.getEntries() ?? [],
1160
+ });
1161
+ processState = recovered;
1162
+ processPersistenceBlocked = false;
1163
+ resolveIncomingCapabilities(""); applyWorkModeTools();
1164
+ return true;
1165
+ } catch { return false; }
1166
+ },
1167
+ handleTaskTriageWaive: async (args, ctx) => {
1168
+ const [id, ...words] = args.trim().split(/\s+/);
1169
+ const addition = processState.additions?.find(a => a.id === id && a.status === "active" && a.taskId === noProgress.taskId());
1170
+ if (!addition || !words.length || processBlock()) return false;
1171
+ const next = await confirmTaskTriageWaiver(processState, { taskId: addition.taskId, evaluationId: addition.evaluationId, inputRevision: addition.inputRevision, additionId: id, reason: words.join(" ") }, {
1172
+ taskId: () => noProgress.taskId(), inputRevision: () => taskTriage?.current?.revision ?? "",
1173
+ ask: (nonce, question, askCtx, signal) => requestRuntimeAsk(pi.events, nonce, question, askCtx, signal),
1174
+ startWait: nonce => executionHistory.startAskUser(nonce), endWait: (nonce, sameTask) => { const wait = executionHistory.endAskUser(nonce, Date.now()); if (sameTask && wait > 0) { taskClock = addTaskClockWait(taskClock, wait); turnBudgetAskUserWaitMs += wait; } },
1175
+ persist: value => pi.appendEntry("agent-hub-process-state", processAuditRecord(value, evaluateProcessObligations(value, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER }))),
1176
+ }, ctx);
1177
+ if (next) processState = next;
1178
+ return !!next;
1179
+ },
1180
+ handleAudit: async (ctx, args = "") => {
1181
+ const input = proactiveReportInput();
1182
+ await showSessionAudit(ctx, sessionDir, input && { ...input, labels: commandProactiveLabels(sessionDir, args) }, {
1183
+ ...taskTriageMetadata(), activity: taskTriageActivity?.live(),
1184
+ });
1185
+ },
1186
+ handleRetry: async (args, ctx) => {
1187
+ const dispatchId = args?.trim();
1188
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(dispatchId)) { ctx.ui.notify("Usage: /af-retry <dispatchId>", "error"); return; }
1189
+ const op = noProgress.byDispatch(dispatchId), attempt = op?.attempts.find(a => a.dispatchId === dispatchId);
1190
+ if (!op || !attempt) { ctx.ui.notify("Unknown dispatch ID; no retry authorized.", "error"); return; }
1191
+ await commandCtx.handleRecover(`retry ${op.operationId} ${attempt.attemptId}`, ctx);
1192
+ },
1193
+ handleRecover: async (args, ctx) => {
1194
+ await runRecoverCommand(args, ctx, {
1195
+ noProgress,
1196
+ currentRevision: cwd => worktreeRevision(cwd, []),
1197
+ confirm: confirmRecoverAction,
1198
+ askPorts: (op, attempt, action) => ({
1199
+ taskId: () => noProgress.taskId(), language: () => userLanguage,
1200
+ ask: (id: string, params: any, askCtx: any, signal: AbortSignal) => requestRuntimeAsk(pi.events, id, params, askCtx, signal),
1201
+ startWait: (id: string) => executionHistory.startAskUser(id),
1202
+ endWait: (id: string, sameTask: boolean) => { const wait = executionHistory.endAskUser(id, Date.now()); if (sameTask && wait > 0) { taskClock = addTaskClockWait(taskClock, wait); turnBudgetAskUserWaitMs += wait; } },
1203
+ valid: () => { const current = noProgress.inspect(op.operationId); return current?.attempts.at(-1)?.attemptId === attempt.attemptId && (action === "abandon" ? !current.abandoned && noProgress.isIdle(op.executor) : noProgress.canAuthorize(op.operationId, attempt.attemptId)); },
1204
+ consume: (nonce: string) => action === "abandon" ? noProgress.abandon(op.operationId, attempt.attemptId, nonce) : attempt.category === "indeterminate" ? noProgress.authorizeIndeterminate(op.operationId, attempt.attemptId, nonce) : noProgress.authorize(attempt.dispatchId),
1205
+ }),
1206
+ });
1207
+ },
1208
+
1209
+ handleAgentsTeam: async (_args, ctx) => {
1210
+ widgetCtx = ctx;
1211
+ const teamNames = Object.keys(teams);
1212
+ if (teamNames.length === 0) {
1213
+ ctx.ui.notify("No teams defined in .pi/agents/teams.yaml", "warning");
1214
+ return;
1215
+ }
1216
+
1217
+ const options = teamNames.map(name => {
1218
+ const members = teams[name].map(m => displayName(m));
1219
+ return `${name} — ${members.join(", ")}`;
1220
+ });
1221
+
1222
+ const choice = await ctx.ui.select("Select Team", options);
1223
+ if (choice === undefined) return;
1224
+
1225
+ const idx = options.indexOf(choice);
1226
+ const name = teamNames[idx];
1227
+ const selected = resolveSessionRoster({
1228
+ teams,
1229
+ entries: [],
1230
+ explicitRoster: name,
1231
+ availablePersonas: allAgentDefs.map(def => def.name),
1232
+ });
1233
+ if (!selected.roster) {
1234
+ ctx.ui.notify(`${selected.diagnostic} Fix .pi/agents/teams.yaml or select another team.`, "error");
1235
+ return;
1236
+ }
1237
+ activateTeam(selected.roster.name);
1238
+ workModePolicy.clearRosterRecovery();
1239
+ persistActiveRoster();
1240
+ resolveIncomingCapabilities("");
1241
+ applyWorkModeTools();
1242
+ setTimeout(replayDeferredRecoveryInputs, 0);
1243
+ updateWidget();
1244
+ ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
1245
+ ctx.ui.notify(`Team: ${name} — ${Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ")}`, "info");
1246
+ },
1247
+ handleAgentsList: async (_args, _ctx) => {
1248
+ widgetCtx = _ctx;
1249
+ await openFleetDashboard(_ctx);
1250
+ },
1251
+ handleAgentsHistory: async (_args, ctx) => {
1252
+ widgetCtx = ctx;
1253
+ await openHistory(ctx, executionHistory, () => (activeTeamName ? `Team: ${activeTeamName}` : "Agent Hub"));
1254
+ },
1255
+ handleAgentsAdd: async (args, ctx) => {
1256
+ widgetCtx = ctx;
1257
+ const names = (args || "").trim().split(/\s+/).filter(Boolean);
1258
+ if (names.length === 0) {
1259
+ const available = allAgentDefs
1260
+ .filter(d => !agentStates.has(d.name.toLowerCase()))
1261
+ .map(d => d.name).sort().join(", ") || "(all personas are already in the team)";
1262
+ ctx.ui.notify(`Usage: /af-agents-add <persona> [<persona>…]\nNot in the team yet: ${available}`, "info");
1263
+ return;
1264
+ }
1265
+ const results = names.map(n => rosterAdd(n));
1266
+ const level = results.some(r => r.ok) ? "info" : "error";
1267
+ ctx.ui.notify(results.map(r => r.message).join("\n"), level);
1268
+ ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"}* (${agentStates.size})`);
1269
+ },
1270
+ handleAgentsDrop: async (args, ctx) => {
1271
+ widgetCtx = ctx;
1272
+ const names = (args || "").trim().split(/\s+/).filter(Boolean);
1273
+ if (names.length === 0) {
1274
+ ctx.ui.notify(`Usage: /af-agents-drop <persona> [<persona>…]\nActive team: ${Array.from(agentStates.values()).map(s => s.def.name).join(", ")}`, "info");
1275
+ return;
1276
+ }
1277
+ const results = names.map(n => rosterDrop(n));
1278
+ const level = results.some(r => r.ok) ? "info" : "error";
1279
+ ctx.ui.notify(results.map(r => r.message).join("\n"), level);
1280
+ ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"}* (${agentStates.size})`);
1281
+ },
1282
+ handleAgentsSave: async (args, ctx) => {
1283
+ widgetCtx = ctx;
1284
+ const name = (args || "").trim();
1285
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) {
1286
+ ctx.ui.notify("Usage: /af-agents-save <team-name> (letters, digits, hyphens, underscores)", "error");
1287
+ return;
1288
+ }
1289
+ const members = Array.from(agentStates.values()).map(s => s.def.name);
1290
+ if (members.length === 0) {
1291
+ ctx.ui.notify("The active team is empty — nothing to save.", "error");
1292
+ return;
1293
+ }
1294
+ const teamsPath = join(ctx.cwd || process.cwd(), ".pi", "agents", "teams.yaml");
1295
+ let raw = "";
1296
+ try { raw = existsSync(teamsPath) ? readFileSync(teamsPath, "utf-8") : ""; } catch {}
1297
+ try {
1298
+ mkdirSync(join(ctx.cwd || process.cwd(), ".pi", "agents"), { recursive: true });
1299
+ writeFileSync(teamsPath, upsertTeamInYaml(raw, name, members), "utf-8");
1300
+ } catch (err) {
1301
+ ctx.ui.notify(`Could not write ${teamsPath}: ${err instanceof Error ? err.message : String(err)}`, "error");
1302
+ return;
1303
+ }
1304
+ teams[name] = members;
1305
+ activeTeamName = name;
1306
+ persistActiveRoster();
1307
+ ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
1308
+ ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "info");
1309
+ },
1310
+ handleAgentsKill: async (args, ctx) => { widgetCtx = ctx; await researchControls.handleKill(args, ctx); },
1311
+ handleAgentsRestart: async (args, ctx) => { widgetCtx = ctx; await researchControls.handleRestart(args, ctx); },
1312
+ handleContext: async (_args, ctx) => {
1313
+ widgetCtx = ctx;
1314
+ await openContextBudget(ctx);
1315
+ },
1316
+ handleHubReport: async (args, ctx) => {
1317
+ widgetCtx = ctx;
1318
+ const fmtTok = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
1319
+ const renderReport = (label: string, r: TurnReport): string => {
1320
+ const billed = r.dispatches.reduce((n, d) => n + d.billed, 0);
1321
+ const out = r.dispatches.reduce((n, d) => n + d.out, 0);
1322
+ 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`);
1323
+ return [
1324
+ `${label} — tier ${r.tier ?? "(unset)"} · ${r.dispatches.length} dispatch(es) · ${r.research} research · ` +
1325
+ `${fmtTok(billed)} billed / ${fmtTok(out)} out · ${r.recycles} recycle(s) · ${r.driftStops} drift stop(s) · ${r.refusals} refusal(s)`,
1326
+ ...rows,
1327
+ ].join("\n");
1328
+ };
1329
+ const lines: string[] = [];
1330
+ if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) {
1331
+ lines.push(renderReport("Current turn", turnReport));
1332
+ }
1333
+ if (lastTurnReport) lines.push(renderReport("Last turn", lastTurnReport));
1334
+ lines.push(
1335
+ `Session — ${sessionTotals.turns} dispatching turn(s) · ${sessionTotals.dispatches} dispatch(es) · ${sessionTotals.research} research · ` +
1336
+ `${fmtTok(sessionTotals.billed)} billed / ${fmtTok(sessionTotals.out)} out · ${sessionTotals.recycles} recycle(s) · ` +
1337
+ `${sessionTotals.driftStops} drift stop(s) · ${sessionTotals.refusals} refusal(s)`,
1338
+ );
1339
+ const sweep = unaddressedPeerSweep(Array.from(hubSpawnedPeers.values()));
1340
+ if (sweep) lines.push(sweep.message);
1341
+ const trace = readWatchdogEvents(sessionDir);
1342
+ lines.push(`Watchdog System 1 — ${JSON.stringify(buildWatchdogReport(trace.events, watchdogActivity?.live(), trace.integrity))}`);
1343
+ const proactiveInput = proactiveReportInput();
1344
+ lines.push(`Proactive review — ${JSON.stringify(proactiveInput ? buildProactiveReport({ ...proactiveInput, labels: commandProactiveLabels(sessionDir, args) }) : readProactiveReport(sessionDir))}`);
1345
+ ctx.ui.notify(lines.join("\n\n"), "info");
1346
+ },
1347
+ handleZoom: async (args, ctx) => {
1348
+ widgetCtx = ctx;
1349
+ const arg = args?.trim() || "";
1350
+ const rid = parseResearchHandle(arg);
1351
+ const target: Zoomable | undefined = rid != null
1352
+ ? researchStates.get(rid)
1353
+ : arg
1354
+ ? agentStates.get(arg.toLowerCase()) ?? findDelegationChild(arg)?.child
1355
+ : undefined;
1356
+ if (!target) {
1357
+ const teamKnown = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
1358
+ const researchKnown = Array.from(researchStates.values()).map(s => `r${s.id}`).join(", ");
1359
+ const childKnown = Array.from(agentStates.values())
1360
+ .flatMap(s => Array.from(s.delegations?.keys() || [])).join(", ");
1361
+ const known = [teamKnown, researchKnown, childKnown].filter(Boolean).join(", ");
1362
+ ctx.ui.notify(`Usage: /af-zoom <name|rN|child-id>. Known: ${known || "none"}`, "error");
1363
+ return;
1364
+ }
1365
+ const rowKey = (rid != null ? `r${rid}` : arg).toLowerCase();
1366
+ const row = fleetRows(true).find(r => r.key.toLowerCase() === rowKey);
1367
+ if (row) await openFleetDetail(row, ctx);
1368
+ else await openZoom(target, ctx);
1369
+ },
1370
+ handleDispatchPolicy: async (_args, ctx) => {
1371
+ widgetCtx = ctx;
1372
+ const live = new Set(comsReady && identity ? peersInScope().map(e => e.name.toLowerCase()) : []);
1373
+ const lines = Array.from(agentStates.values()).map(s => {
1374
+ const key = s.def.name.toLowerCase();
1375
+ const sub = dispatchPolicy.substitutions[key];
1376
+ const prefer = sub ? sub.prefer : dispatchPolicy.default === "coms" ? "coms" : "native";
1377
+ if (prefer !== "coms") return `${displayName(s.def.name)}: native`;
1378
+ const fb = sub?.fallback === "none" ? "coms-required" : "coms, fallback native";
1379
+ return `${displayName(s.def.name)}: ${fb} — peer ${live.has(key) ? "LIVE" : "not in pool"}`;
1380
+ });
1381
+ const policyPath = join(ctx.cwd || process.cwd(), ".pi", "agents", "dispatch-policy.yaml");
1382
+ const src = existsSync(policyPath) ? ".pi/agents/dispatch-policy.yaml" : "(no dispatch-policy.yaml — all native)";
1383
+ ctx.ui.notify(
1384
+ `Dispatch backends — ${src}, default: ${dispatchPolicy.default}\n${lines.join("\n") || "(no active team)"}\n` +
1385
+ `Routing is decided per dispatch against the live coms pool (/af-coms to refresh).`,
1386
+ "info",
1387
+ );
1388
+ },
1389
+ handleAgentModel: async (args, ctx) => {
1390
+ widgetCtx = ctx;
1391
+ const arg = (args || "").trim().toLowerCase();
1392
+
1393
+ // Dot form: <persona>.<role> targets a delegate sub-role. Candidates are
1394
+ // the role's declared model (default) + the parent's candidate list.
1395
+ if (arg.includes(".")) {
1396
+ const dot = arg.indexOf(".");
1397
+ const personaName = arg.slice(0, dot);
1398
+ const roleName = arg.slice(dot + 1);
1399
+ const parent = agentStates.get(personaName);
1400
+ const roles = parent?.def.subagents || {};
1401
+ const roleKey = Object.keys(roles).find(r => r.toLowerCase() === roleName);
1402
+ if (!parent || !roleKey) {
1403
+ const valid = Array.from(agentStates.values()).flatMap(s =>
1404
+ Object.keys(s.def.subagents || {}).map(r => `${s.def.name}.${r}`));
1405
+ ctx.ui.notify(
1406
+ `No sub-role "${arg}". Valid targets: ${valid.join(", ") || "none (no persona declares subagents:)"}`,
1407
+ "error",
1408
+ );
1409
+ return;
1410
+ }
1411
+ const role = roles[roleKey];
1412
+ const overrideKey = `${personaName}.${roleKey.toLowerCase()}`;
1413
+ const candidates: string[] = [];
1414
+ for (const m of [role.model, ...allowedModels(parent.def)]) {
1415
+ if (m && !candidates.includes(m)) candidates.push(m);
1416
+ }
1417
+ const current = resolvedSubagentModel(parent.def.name, roleKey, role.model);
1418
+ const options = candidates.map(m => {
1419
+ const tags = [m === role.model ? "default" : "", m === current ? "current" : ""].filter(Boolean);
1420
+ return tags.length ? `${m} (${tags.join(", ")})` : m;
1421
+ });
1422
+ const label = `${displayName(parent.def.name)}.${roleKey}`;
1423
+ const choice = await ctx.ui.select(`Model for ${label}`, options);
1424
+ if (choice === undefined) return;
1425
+ const picked = candidates[options.indexOf(choice)];
1426
+ const effectivePicked = substitutedModel(picked) ?? picked;
1427
+ if (effectivePicked === current) {
1428
+ ctx.ui.notify(`${label} is already on ${effectivePicked}`, "info");
1429
+ return;
1430
+ }
1431
+ if (picked === role.model) {
1432
+ modelPolicy.setSubagentOverride(personaName, roleKey, undefined);
1433
+ } else {
1434
+ modelPolicy.setSubagentOverride(personaName, roleKey, picked);
1435
+ }
1436
+ updateWidget();
1437
+ ctx.ui.notify(
1438
+ `${label} → ${effectivePicked} (applies on next dispatch of ${parent.def.name})`,
1439
+ "info",
1440
+ );
1441
+ return;
1442
+ }
1443
+
1444
+ const name = arg;
1445
+ // Team member (live state) OR a research persona — both switchable.
1446
+ const def = name ? switchablePersonaDef(name) : undefined;
1447
+ if (!def) {
1448
+ const known = [
1449
+ ...Array.from(agentStates.values()).map(s => s.def.name),
1450
+ ...researchPersonas.map(d => d.name),
1451
+ ].join(", ");
1452
+ ctx.ui.notify(`Usage: /af-agent-model <persona>[.<role>]. Known: ${known || "none"}`, "error");
1453
+ return;
1454
+ }
1455
+ if (!def.models || def.models.length === 0) {
1456
+ ctx.ui.notify(
1457
+ `${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.`,
1458
+ "warning",
1459
+ );
1460
+ return;
1461
+ }
1462
+ const candidates = allowedModels(def);
1463
+ const current = resolvedModel(def);
1464
+ // A persona without a frontmatter default runs on the dispatcher's model —
1465
+ // offer that as an explicit candidate so the override can be cleared.
1466
+ const DISPATCHER_DEFAULT = "(dispatcher's model)";
1467
+ if (!def.model) candidates.unshift(DISPATCHER_DEFAULT);
1468
+ const options = candidates.map(m => {
1469
+ const isDefault = def.model ? m === def.model : m === DISPATCHER_DEFAULT;
1470
+ const isCurrent = current ? m === current : m === DISPATCHER_DEFAULT;
1471
+ const tags = [isDefault ? "default" : "", isCurrent ? "current" : ""].filter(Boolean);
1472
+ return tags.length ? `${m} (${tags.join(", ")})` : m;
1473
+ });
1474
+ const choice = await ctx.ui.select(`Model for ${displayName(def.name)}`, options);
1475
+ if (choice === undefined) return;
1476
+ const picked = candidates[options.indexOf(choice)];
1477
+ const effectivePicked = picked === DISPATCHER_DEFAULT ? picked : (substitutedModel(picked) ?? picked);
1478
+ const pickedIsCurrent = current ? effectivePicked === current : picked === DISPATCHER_DEFAULT;
1479
+ if (pickedIsCurrent) {
1480
+ ctx.ui.notify(`${displayName(def.name)} is already on ${effectivePicked}`, "info");
1481
+ return;
1482
+ }
1483
+ if (picked === def.model || picked === DISPATCHER_DEFAULT) {
1484
+ modelPolicy.setPersonaOverride(name, undefined);
1485
+ } else {
1486
+ modelPolicy.setPersonaOverride(name, picked);
1487
+ }
1488
+ updateWidget();
1489
+ // Research helpers spawn fresh each time, so the switch lands on their
1490
+ // next spawn; team members apply on next dispatch (restartable now).
1491
+ const applyHint = (def.kind || "").toLowerCase() === "research"
1492
+ ? "applies on next spawn_research"
1493
+ : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
1494
+ ctx.ui.notify(`${displayName(def.name)} → ${effectivePicked} (${applyHint})`, "info");
1495
+ if ((dispatchPolicy.substitutions[name]?.prefer ?? dispatchPolicy.default) === "coms") {
1496
+ ctx.ui.notify(
1497
+ `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.`,
1498
+ "info",
1499
+ );
1500
+ }
1501
+ },
1502
+ handleAgentModelThinking: async (args, ctx) => {
1503
+ widgetCtx = ctx;
1504
+ const name = (args || "").trim().toLowerCase();
1505
+ // Team member (live state) OR a research persona — both switchable.
1506
+ const def = name ? switchablePersonaDef(name) : undefined;
1507
+ if (!def) {
1508
+ const known = [
1509
+ ...Array.from(agentStates.values()).map(s => s.def.name),
1510
+ ...researchPersonas.map(d => d.name),
1511
+ ].join(", ");
1512
+ ctx.ui.notify(`Usage: /af-agent-model-thinking <persona>. Known: ${known || "none"}`, "error");
1513
+ return;
1514
+ }
1515
+ const defaultLevel = resolveThinkingLevel(def.thinking);
1516
+ const current = resolveThinkingLevel(resolvedThinking(def));
1517
+ const levels = [...THINKING_LEVELS];
1518
+ const options = levels.map(l => {
1519
+ const tags = [l === defaultLevel ? "default" : "", l === current ? "current" : ""].filter(Boolean);
1520
+ return tags.length ? `${l} (${tags.join(", ")})` : l;
1521
+ });
1522
+ const choice = await ctx.ui.select(`Thinking level for ${displayName(def.name)}`, options);
1523
+ if (choice === undefined) return;
1524
+ const picked = levels[options.indexOf(choice)];
1525
+ if (picked === current) {
1526
+ ctx.ui.notify(`${displayName(def.name)} is already on thinking: ${picked}`, "info");
1527
+ return;
1528
+ }
1529
+ if (picked === defaultLevel) {
1530
+ modelPolicy.setThinkingOverride(name, undefined);
1531
+ } else {
1532
+ modelPolicy.setThinkingOverride(name, picked);
1533
+ }
1534
+ updateWidget();
1535
+ // Research helpers spawn fresh each time, so the switch lands on their
1536
+ // next spawn; team members apply on next dispatch (restartable now).
1537
+ const applyHint = (def.kind || "").toLowerCase() === "research"
1538
+ ? "applies on next spawn_research"
1539
+ : `applies on next dispatch; /af-agents-restart ${def.name} to apply now`;
1540
+ ctx.ui.notify(`${displayName(def.name)} thinking → ${picked} (${applyHint})`, "info");
1541
+ },
1542
+ handleModels: async (args, ctx) => {
1543
+ widgetCtx = ctx;
1544
+ const names = Object.keys(modelProfiles);
1545
+ if (names.length === 0) {
1546
+ ctx.ui.notify("No model profiles loaded — define .pi/agents/model-profiles.yaml (invalid profiles are dropped at session start).", "warning");
1547
+ return;
1548
+ }
1549
+ let profileName = (args || "").trim();
1550
+ if (!profileName) {
1551
+ const options = names.map(n =>
1552
+ isCompleteProfile(modelProfiles[n])
1553
+ ? `${n} — complete fleet (${shortModel((modelProfiles[n] as any).defaults.model)} default)`
1554
+ : `${n} — ${Object.entries(modelProfiles[n]).map(([p, m]) => `${p}: ${shortModel(m)}`).join(", ")}`,
1555
+ );
1556
+ const choice = await ctx.ui.select("Select model profile", options);
1557
+ if (choice === undefined) return;
1558
+ profileName = names[options.indexOf(choice)];
1559
+ }
1560
+ const profile = modelProfiles[profileName];
1561
+ if (!profile) {
1562
+ ctx.ui.notify(`No profile "${profileName}". Known: ${names.join(", ")}`, "error");
1563
+ return;
1564
+ }
1565
+ profileCommandContext=ctx;
1566
+ try {
1567
+ const applied=await profileActivation.activate(profileName,profile);
1568
+ applyWorkModeTools();
1569
+ ctx.ui.setStatus('hub-model-profile',isCompleteProfile(profile)?`Models: ${profileName}`:undefined);
1570
+ ctx.ui.notify(`Profile "${profileName}": ${applied.length} personas${isCompleteProfile(profile)?', all children, dispatcher and auxiliary models':''} switched.`, 'info');
1571
+ } catch(error) {ctx.ui.notify(String(error),'error');}
1572
+ },
1573
+ handleAgentModelsSubstitute: async (args, ctx) => {
1574
+ widgetCtx = ctx;
1575
+ const tokens = (args || "").trim().split(/\s+/).filter(Boolean);
1576
+ if (tokens.length === 0) {
1577
+ if (allKnownModels().length === 0) {
1578
+ ctx.ui.notify("No configured persona or sub-role models are available as substitution sources.", "warning");
1579
+ return;
1580
+ }
1581
+ await openFleetDashboard(ctx, true);
1582
+ return;
1583
+ }
1584
+ if (tokens.length !== 2) {
1585
+ ctx.ui.notify("Usage: /af-agent-models-substitute [<source> <target>]", "error");
1586
+ return;
1587
+ }
1588
+ await applySessionModelSubstitution(tokens[0], tokens[1], ctx);
1589
+ },
1590
+ handleWatchdog: async (args, ctx) => {
1591
+ widgetCtx = ctx;
1592
+ const parts = (args || "").trim().split(/\s+/).filter(Boolean);
1593
+ if (parts.length === 0) {
1594
+ const perAgent = watchdogAgentOverrides.size > 0
1595
+ ? Array.from(watchdogAgentOverrides.entries()).map(([k, v]) => `${k}: ${v}`).join(", ")
1596
+ : "(none)";
1597
+ ctx.ui.notify(
1598
+ `Drift watchdog: ${watchdogSetting} (hub-wide)\nPer-agent overrides: ${perAgent}\n` +
1599
+ `Judge model: ${watchdogJudgeModel || "(researcher persona's, else dispatcher's)"}\n` +
1600
+ `${formatWatchdogStatus(watchdogSystem1, watchdogActivity)}\n` +
1601
+ `Usage: /af-watchdog on|off|auto — or /af-watchdog <agent> on|off|clear`,
1602
+ "info",
1603
+ );
1604
+ return;
1605
+ }
1606
+ if (parts.length === 1) {
1607
+ const setting = normalizeWatchdogSetting(parts[0]);
1608
+ if (!setting) {
1609
+ ctx.ui.notify(`Unknown setting "${parts[0]}" — expected one of: ${WATCHDOG_SETTINGS.join(", ")} (or /af-watchdog <agent> on|off|clear)`, "error");
1610
+ return;
1611
+ }
1612
+ watchdogSetting = setting;
1613
+ ctx.ui.notify(`Drift watchdog → ${setting} (applies from the next dispatch)`, "info");
1614
+ return;
1615
+ }
1616
+ const agentKey = normalizeAgentInput(parts[0]);
1617
+ const value = parts[1].toLowerCase();
1618
+ if (!agentStates.has(agentKey)) {
1619
+ ctx.ui.notify(`"${parts[0]}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ")})`, "error");
1620
+ return;
1621
+ }
1622
+ if (value === "clear") {
1623
+ watchdogAgentOverrides.delete(agentKey);
1624
+ ctx.ui.notify(`Drift watchdog override cleared for ${agentKey} (hub-wide setting "${watchdogSetting}" applies)`, "info");
1625
+ return;
1626
+ }
1627
+ if (value !== "on" && value !== "off") {
1628
+ ctx.ui.notify(`Per-agent watchdog must be on, off, or clear — got "${parts[1]}"`, "error");
1629
+ return;
1630
+ }
1631
+ watchdogAgentOverrides.set(agentKey, value);
1632
+ ctx.ui.notify(`Drift watchdog for ${agentKey} → ${value} (overrides the hub-wide "${watchdogSetting}")`, "info");
1633
+ },
1634
+ handleComs: async (args, ctx) => {
1635
+ if (!comsReady) { ctx.ui.notify("coms is not active in this session.", "warning"); return; }
1636
+ await coms.updateScope((args ?? "").trim(), ctx);
1637
+ },
1638
+ handleHandoff: async (args, ctx) => {
1639
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1640
+ if (!comsReady) { ctx.ui.notify("coms is not active in this session — /af-handoff unavailable.", "warning"); return; }
1641
+ const target = (args ?? "").trim();
1642
+ if (!target) {
1643
+ ctx.ui.notify("Usage: /af-handoff <peer>. See the coms pool for live peer names.", "error");
1644
+ return;
1645
+ }
1646
+ const peer = resolveTarget(target);
1647
+ if (!peer) {
1648
+ ctx.ui.notify(`coms: no live peer "${target}". Use /af-coms to refresh the pool.`, "error");
1649
+ return;
1650
+ }
1651
+ const refusal=profilePeerGate({ peerModel: peer.model, targetResolved: true });if(refusal){ctx.ui.notify(refusal.content[0].text,"error");return;}
1652
+ const handoffToken = crypto.randomBytes(8).toString("hex");
1653
+ hubStateCtx.setPendingHandoff({ target: peer.name, token: handoffToken });
1654
+ pi.sendMessage({
1655
+ customType: "coms-handoff",
1656
+ content:
1657
+ `HANDOFF REQUEST → peer "${peer.name}".\n\n` +
1658
+ `Compose a SELF-CONTAINED handoff brief (the peer does NOT share your context): state the ` +
1659
+ `overall goal, what's been done so far, key decisions and constraints, the current status, ` +
1660
+ `and the concrete next steps you want the peer to take. Then call ` +
1661
+ `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 ` +
1662
+ `the peer's reply to me in ${userLanguage}.`,
1663
+ display: true,
1664
+ }, { deliverAs: "followUp", triggerTurn: true });
1665
+ ctx.ui.notify(`Handoff to ${peer.name}: asking the dispatcher to compose a brief…`, "info");
1666
+ },
1667
+ handleCompound: async (args, ctx) => {
1668
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1669
+ if (!agentStates.has("documenter")) {
1670
+ ctx.ui.notify(
1671
+ "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.",
1672
+ "warning",
1673
+ );
1674
+ return;
1675
+ }
1676
+ const focus = (args ?? "").trim();
1677
+ const rulesLine = projectRulesDirs.length > 0
1678
+ ? projectRulesDirs.join(", ")
1679
+ : "(none declared in .ai/agent-fleet-overrides.md — the documenter must locate an existing rules tree or, failing that, propose lessons without writing)";
1680
+ const docsLine = projectDocsPaths.length > 0
1681
+ ? projectDocsPaths.join(", ")
1682
+ : "(none declared)";
1683
+ pi.sendMessage({
1684
+ customType: "compound-learning",
1685
+ content:
1686
+ `COMPOUND REQUEST — capture this session's lessons into the project's rules and docs (compound-learning pass).\n\n` +
1687
+ `1. From THIS session's context, compose a candidate-lessons brief: user corrections, review findings that recurred, ` +
1688
+ `wrong assumptions that cost rework, debugging root causes, and changes that invalidated existing docs. At most 5 lessons; ` +
1689
+ `each is one imperative sentence plus a one-line Why (the failure it prevents) and a one-line Evidence (what happened this session). ` +
1690
+ `${focus ? `Focus especially on: ${focus}. ` : ""}` +
1691
+ `If nothing rises to a lesson, tell the user there is nothing worth compounding and stop.\n` +
1692
+ `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` +
1693
+ `3. Dispatch the documenter with a SELF-CONTAINED task (it shares none of your context) containing: the approved lessons verbatim ` +
1694
+ `(with Why + Evidence); the project rule folders: ${rulesLine}; the docs entry points: ${docsLine}; the assertion ledger path ` +
1695
+ `.pi/agent-sessions/assertions.json (when it exists); and the instruction to read skills/compound-learning/SKILL.md and follow it exactly — ` +
1696
+ `dedupe index-first against the existing rule tree, minimal diffs on existing files, caps of 5 lessons / 1 new file. State that the user ` +
1697
+ `already approved this lesson list, so it may apply without a second gate. Pass the relevant review/return/evidence artifact paths via the ` +
1698
+ `dispatch's artifacts array — paths only, never pasted bodies.\n` +
1699
+ `4. Relay the documenter's file-by-file result to me in ${userLanguage}.`,
1700
+ display: true,
1701
+ }, { deliverAs: "followUp", triggerTurn: true });
1702
+ ctx.ui.notify("Compound: asking the dispatcher to compose the candidate-lessons brief…", "info");
1703
+ },
1704
+ handlePoll: async (args, ctx) => {
1705
+ return withProfileWork(async () => {
1706
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1707
+ const cwd = ctx.cwd || process.cwd();
1708
+ const result = await handleAfPoll({
1709
+ args: args ?? "",
1710
+ cwd,
1711
+ pollPanelOverride: readActiveProfile()?.name ?? parseAgentTeamOverrides(cwd).pollPanel,
1712
+ listPanels: async dir => {
1713
+ const { listPanelNames } = await import("../../agent-fleet/scripts/workflows/lib/voices.ts");
1714
+ return listPanelNames(dir);
1715
+ },
1716
+ preflight: async ({ panel, persona, cwd: root }) => {
1717
+ const [{ resolvePersona }, { resolvePanel }, { checkChildVisibility }] = await Promise.all([
1718
+ import("../../agent-fleet/scripts/workflows/lib/personas.ts"),
1719
+ import("../../agent-fleet/scripts/workflows/lib/voices.ts"),
1720
+ import("../../agent-fleet/scripts/workflows/lib/model-visibility.ts"),
1721
+ ]);
1722
+ try { resolvePersona(persona, root); }
1723
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1724
+ let voices;
1725
+ try { voices = resolvePanel(panel, root); }
1726
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1727
+ const report = checkChildVisibility(voices.map(voice => voice.model));
1728
+ if (report.diagnostic) return `could not verify clean-room model visibility (${report.diagnostic})`;
1729
+ const hidden = report.models.filter(model => !model.ok);
1730
+ if (hidden.length) {
1731
+ return `panel "${panel}" has models not visible to a clean-room child: ${hidden.map(model => model.reasons[0] ?? model.model).join("; ")}`;
1732
+ }
1733
+ return null;
1734
+ },
1735
+ checkBudget: async () => {
1736
+ ensureTaskTier();
1737
+ const blocked = await budgetRecovery.ensure("dispatch", args ?? "model panel", ctx);
1738
+ return blocked?.message ?? null;
1739
+ },
1740
+ chargeBudget: () => {
1741
+ turnDispatchCount += 1;
1742
+ taskDispatchCount += 1;
1743
+ sessionTotals.dispatches += 1;
1744
+ updateModeStatus();
1745
+ },
1746
+ onAccepted: async ({ panel, persona, question }) => {
1747
+ let voices: { name: string; model: string }[] = [];
1748
+ try {
1749
+ const { resolvePanel } = await import("../../agent-fleet/scripts/workflows/lib/voices.ts");
1750
+ voices = resolvePanel(panel, cwd).map(voice => ({ name: voice.name, model: voice.model }));
1751
+ } catch { /* names are decorative */ }
1752
+ const started = formatAfPollStarted({ panel, persona, question, voices });
1753
+ ctx.ui.setStatus("hub-poll", `Poll: ${panel} (${voices.length || "?"} voices) running…`);
1754
+ ctx.ui.notify(`Poll started — panel ${panel}. This can take a minute.`, "info");
1755
+ pi.sendMessage({ customType: "af-poll-started", content: started, display: true }, { deliverAs: "followUp", triggerTurn: false });
1756
+ },
1757
+ execute: async ({ panel, persona, question }) => {
1758
+ const [{ Run }, { runPoll }, { runMerge }, { resolvePersona }] = await Promise.all([
1759
+ import("../../agent-fleet/scripts/workflows/lib/run.ts"),
1760
+ import("../../agent-fleet/scripts/workflows/lib/poll.ts"),
1761
+ import("../../agent-fleet/scripts/workflows/lib/merge.ts"),
1762
+ import("../../agent-fleet/scripts/workflows/lib/personas.ts"),
1763
+ ]);
1764
+ const run = new Run({ cwd, command: ["/af-poll", "--panel", panel, question] });
1765
+ const personaDef = resolvePersona(persona, cwd);
1766
+ const poll = await runPoll({
1767
+ run, cwd, persona: personaDef, panel, task: question,
1768
+ onVoice: result => {
1769
+ const voice = result.ok
1770
+ ? { name: result.voice.name, model: result.voice.model, ok: true as const, position: result.report.position, confidence: result.report.confidence }
1771
+ : { name: result.voice.name, model: result.voice.model, ok: false as const, reason: result.reason };
1772
+ pi.sendMessage({ customType: "af-poll-voice", content: formatAfPollVoiceProgress(voice), display: true }, { deliverAs: "followUp", triggerTurn: false });
1773
+ },
1774
+ });
1775
+ ctx.ui.setStatus("hub-poll", `Poll: ${panel} merging…`);
1776
+ const merge = await runMerge({ run, cwd, persona: personaDef, panel, task: question, opinions: poll.results });
1777
+ const directory = path.relative(cwd, poll.directory) || poll.directory;
1778
+ return {
1779
+ panel,
1780
+ directory: directory.endsWith(path.sep) ? directory : `${directory}${path.sep}`,
1781
+ voices: poll.results.map(item => item.ok
1782
+ ? { name: item.voice.name, model: item.voice.model, ok: true as const, position: item.report.position, confidence: item.report.confidence }
1783
+ : { name: item.voice.name, model: item.voice.model, ok: false as const, reason: item.reason }),
1784
+ recommendation: merge.report.recommendation,
1785
+ integrator: merge.integrator.name,
1786
+ };
1787
+ },
1788
+ });
1789
+ ctx.ui.setStatus("hub-poll", "");
1790
+ if (!result.ok) {
1791
+ ctx.ui.notify(result.message, "error");
1792
+ pi.sendMessage({ customType: "af-poll-failed", content: `POLL FAILED\n\n${result.message}`, display: true }, { deliverAs: "followUp", triggerTurn: false });
1793
+ return;
1794
+ }
1795
+ ctx.ui.notify(result.digest ?? result.message, "info");
1796
+ pi.sendMessage({
1797
+ customType: "af-poll",
1798
+ content: result.dispatcherNote ?? result.message,
1799
+ display: true,
1800
+ }, { deliverAs: "followUp", triggerTurn: true });
1801
+ });
1802
+ },
1803
+ handleDebate: async (args, ctx) => {
1804
+ return withProfileWork(async () => {
1805
+ if (modelWorkBlockedByRosterRecovery(ctx)) return;
1806
+ const cwd = ctx.cwd || process.cwd();
1807
+ const result = await handleAfDebate({
1808
+ args: args ?? "",
1809
+ cwd,
1810
+ pollPanelOverride: readActiveProfile()?.name ?? parseAgentTeamOverrides(cwd).pollPanel,
1811
+ listPanels: async dir => {
1812
+ const { listPanelNames } = await import("../../agent-fleet/scripts/workflows/lib/voices.ts");
1813
+ return listPanelNames(dir);
1814
+ },
1815
+ preflight: async ({ panel, persona, cwd: root }) => {
1816
+ const [{ resolvePersona }, { resolvePanel }, { checkChildVisibility }] = await Promise.all([
1817
+ import("../../agent-fleet/scripts/workflows/lib/personas.ts"),
1818
+ import("../../agent-fleet/scripts/workflows/lib/voices.ts"),
1819
+ import("../../agent-fleet/scripts/workflows/lib/model-visibility.ts"),
1820
+ ]);
1821
+ try { resolvePersona(persona, root); }
1822
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1823
+ let voices;
1824
+ try { voices = resolvePanel(panel, root); }
1825
+ catch (error) { return error instanceof Error ? error.message : String(error); }
1826
+ const report = checkChildVisibility(voices.map(voice => voice.model));
1827
+ if (report.diagnostic) return `could not verify clean-room model visibility (${report.diagnostic})`;
1828
+ const hidden = report.models.filter(model => !model.ok);
1829
+ if (hidden.length) {
1830
+ return `panel "${panel}" has models not visible to a clean-room child: ${hidden.map(model => model.reasons[0] ?? model.model).join("; ")}`;
1831
+ }
1832
+ return null;
1833
+ },
1834
+ checkBudget: async () => {
1835
+ ensureTaskTier();
1836
+ const blocked = await budgetRecovery.ensure("dispatch", args ?? "model panel", ctx);
1837
+ return blocked?.message ?? null;
1838
+ },
1839
+ chargeBudget: () => {
1840
+ turnDispatchCount += 1;
1841
+ taskDispatchCount += 1;
1842
+ sessionTotals.dispatches += 1;
1843
+ updateModeStatus();
1844
+ },
1845
+ onAccepted: async ({ panel, persona, question, rounds }) => {
1846
+ let voices: { name: string; model: string }[] = [];
1847
+ try {
1848
+ const { resolvePanel } = await import("../../agent-fleet/scripts/workflows/lib/voices.ts");
1849
+ voices = resolvePanel(panel, cwd).map(voice => ({ name: voice.name, model: voice.model }));
1850
+ } catch { /* names are decorative */ }
1851
+ const started = formatAfDebateStarted({ panel, persona, question, rounds, voices });
1852
+ ctx.ui.setStatus("hub-poll", `Debate: ${panel} (${rounds} rounds) running…`);
1853
+ ctx.ui.notify(`Debate started — panel ${panel}, ${rounds} rounds.`, "info");
1854
+ pi.sendMessage({ customType: "af-debate-started", content: started, display: true }, { deliverAs: "followUp", triggerTurn: false });
1855
+ },
1856
+ execute: async ({ panel, persona, question, rounds }) => {
1857
+ const [{ Run }, { runDebate }, { resolvePersona }] = await Promise.all([
1858
+ import("../../agent-fleet/scripts/workflows/lib/run.ts"),
1859
+ import("../../agent-fleet/scripts/workflows/lib/debate.ts"),
1860
+ import("../../agent-fleet/scripts/workflows/lib/personas.ts"),
1861
+ ]);
1862
+ const run = new Run({ cwd, command: ["/af-debate", "--panel", panel, "--rounds", String(rounds), question] });
1863
+ const personaDef = resolvePersona(persona, cwd);
1864
+ const debate = await runDebate({
1865
+ run, cwd, persona: personaDef, panel, task: question, rounds,
1866
+ onVoice: (result, round) => {
1867
+ const voice = result.ok
1868
+ ? { name: result.voice.name, model: result.voice.model, ok: true as const, round, position: result.report.position, changed: result.report.changed }
1869
+ : { name: result.voice.name, model: result.voice.model, ok: false as const, round, reason: result.reason };
1870
+ ctx.ui.setStatus("hub-poll", `Debate: ${panel} round ${round}…`);
1871
+ pi.sendMessage({ customType: "af-debate-voice", content: formatAfDebateVoiceProgress(voice), display: true }, { deliverAs: "followUp", triggerTurn: false });
1872
+ },
1873
+ });
1874
+ const last = debate.roundsRun.at(-1)?.results ?? [];
1875
+ const directory = path.relative(cwd, debate.directory) || debate.directory;
1876
+ return {
1877
+ panel, rounds: debate.rounds,
1878
+ directory: directory.endsWith(path.sep) ? directory : `${directory}${path.sep}`,
1879
+ voices: last.map(item => item.ok
1880
+ ? { name: item.voice.name, model: item.voice.model, ok: true as const, round: item.round, position: item.report.position, changed: item.report.changed }
1881
+ : { name: item.voice.name, model: item.voice.model, ok: false as const, round: item.round, reason: item.reason }),
1882
+ };
1883
+ },
1884
+ });
1885
+ ctx.ui.setStatus("hub-poll", "");
1886
+ if (!result.ok) {
1887
+ ctx.ui.notify(result.message, "error");
1888
+ pi.sendMessage({ customType: "af-debate-failed", content: `DEBATE FAILED\n\n${result.message}`, display: true }, { deliverAs: "followUp", triggerTurn: false });
1889
+ return;
1890
+ }
1891
+ ctx.ui.notify(result.digest ?? result.message, "info");
1892
+ pi.sendMessage({
1893
+ customType: "af-debate",
1894
+ content: result.dispatcherNote ?? result.message,
1895
+ display: true,
1896
+ }, { deliverAs: "followUp", triggerTurn: true });
1897
+ });
1898
+ },
1899
+ getAgentsKillCompletions: prefix => completions.agentsKill(prefix),
1900
+ getZoomCompletions: prefix => completions.zoom(prefix),
1901
+ getAgentModelCompletions: prefix => completions.agentModels(prefix),
1902
+ getAgentModelThinkingCompletions: prefix => completions.agentThinking(prefix),
1903
+ getModelProfileCompletions: prefix => completions.modelProfiles(prefix),
1904
+ getSubstituteCompletions: prefix => completions.substitutions(prefix),
1905
+ getComsPeerCompletions: prefix => completions.comsPeers(prefix),
1906
+ getSubagentTargetCompletions: prefix => completions.subagentTargets(prefix),
1907
+ };
1908
+
1909
+ // Keep the complete command surface flat and greppable in this composition root.
1910
+ registerAgentsTeam(pi, commandCtx);
1911
+ registerAgentsList(pi, commandCtx);
1912
+ registerAgentsHistory(pi, commandCtx);
1913
+ registerContextCommand(pi, commandCtx);
1914
+ registerAudit(pi, commandCtx);
1915
+ registerWorkMode(pi, commandCtx);
1916
+ registerWatchdog(pi, commandCtx);
1917
+ registerAgentsAdd(pi, commandCtx);
1918
+ registerAgentsDrop(pi, commandCtx);
1919
+ registerAgentsSave(pi, commandCtx);
1920
+ registerHubReport(pi, commandCtx);
1921
+ registerZoom(pi, commandCtx);
1922
+ registerAgentModel(pi, commandCtx);
1923
+ registerAgentModelThinking(pi, commandCtx);
1924
+ registerModels(pi, commandCtx);
1925
+ registerAgentModelsSubstitute(pi, commandCtx);
1926
+ registerDispatchPolicy(pi, commandCtx);
1927
+ registerAgentsKill(pi, commandCtx);
1928
+ registerAgentsRestart(pi, commandCtx);
1929
+ registerComs(pi, commandCtx);
1930
+ registerHandoff(pi, commandCtx);
1931
+ registerCompound(pi, commandCtx);
1932
+ registerPoll(pi, commandCtx);
1933
+ registerBudgetContinue(pi, commandCtx);
1934
+ registerRetry(pi, commandCtx);
1935
+ registerRecover(pi, commandCtx);
1936
+ registerDebate(pi, commandCtx);
1937
+ registerTaskTriageRecover(pi, commandCtx);
1938
+ registerTaskTriageWaiver(pi, commandCtx);
1939
+
1940
+ const detailPanel = createDetailPanel<AgentDef, AgentState, ResearchState>({
1941
+ getAgent: key => agentStates.get(key),
1942
+ getResearch: id => researchStates.get(id),
1943
+ parseResearchHandle,
1944
+ findDelegationChild,
1945
+ modelPolicy,
1946
+ displayName,
1947
+ shortModel,
1948
+ refreshUi: updateWidget,
1949
+ getDispatchPreference: name => (dispatchPolicy.substitutions[name.toLowerCase()]?.prefer ?? dispatchPolicy.default) === "coms" ? "coms" : "native",
1950
+ maxLiveEntryChars: MAX_LIVE_ENTRY_CHARS,
1951
+ getProactive: () => fleetSource.snapshot(Date.now()).proactive,
1952
+ readProactiveEvidence: (finding) => proactiveRuntime?.findings.readback(finding.snapshotHandle, finding.snapshotHash, finding.snapshotId, finding.unitId, finding.excerptHash) ?? null,
1953
+ currentFleetRow: key => fleetSource.rows(Date.now(), { showFinished: true }).find(row => row.key === key),
1954
+ });
1955
+ const { openFleetDetail, loadAvailableModelChoices } = detailPanel;
1956
+ const applySessionModelSubstitution = (source: string, target: string, ctx: any) => modelPolicy.applySessionSubstitution(source, target, {
1957
+ loadAvailable: current => loadAvailableModelChoices(ctx, current),
1958
+ notify: (message, level) => ctx.ui.notify(message, level),
1959
+ });
1960
+
1961
+ fleetActions = createFleetActions<AgentState, ResearchState>({
1962
+ getRows: () => fleetSource.rows(Date.now(), { showFinished: true }),
1963
+ getAgents: () => agentStates,
1964
+ getResearch: () => researchStates,
1965
+ parseResearchHandle,
1966
+ displayName,
1967
+ modelWorkBlocked: modelWorkBlockedByRosterRecovery,
1968
+ restartSpecialist: researchControls.restartSpecialist,
1969
+ removeResearch: researchControls.remove,
1970
+ killSpecialistProcess: state => { fenceOperatorCancel(state); cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), treeKill: killPiTree }); },
1971
+ abortComs: state => { state.comsAbort?.(); },
1972
+ openDetail: openFleetDetail,
1973
+ generation: () => fleetUiGeneration,
1974
+ });
1975
+ let fleetShowFinished = false;
1976
+ let fleetFilter = "";
1977
+ const fleetDashboard = createFleetDashboard<AgentDef, AgentState, ResearchState>({
1978
+ onThinkingChanged: updateWidget,
1979
+ openSystem1: ctx => openSystem1Communication(ctx, communicationStore),
1980
+ getFleetRows: (now, unfiltered) => fleetSource.rows(now, unfiltered ? { showFinished: true } : { showFinished: fleetShowFinished, query: fleetFilter }),
1981
+ getTaskTriage: () => fleetSource.snapshot(Date.now()).taskTriage,
1982
+ getProactive: () => fleetSource.snapshot(Date.now()).proactive,
1983
+ readProactiveEvidence: (finding) => proactiveRuntime?.findings.readback(finding.snapshotHandle, finding.snapshotHash, finding.snapshotId, finding.unitId, finding.excerptHash) ?? null,
1984
+ actions: fleetActions,
1985
+ getAgents: () => agentStates,
1986
+ getResearch: () => researchStates,
1987
+ getShowFinished: () => fleetShowFinished,
1988
+ setShowFinished: value => { fleetShowFinished = value; },
1989
+ getFilter: () => fleetFilter,
1990
+ setFilter: value => { fleetFilter = value; },
1991
+ parseResearchHandle,
1992
+ displayName,
1993
+ shortModel,
1994
+ thinkingSuffix,
1995
+ modelWithThinking,
1996
+ resolvedThinking,
1997
+ abbreviatePeerModel: abbreviateModel,
1998
+ modelPolicy,
1999
+ loadAvailableModels: loadAvailableModelChoices,
2000
+ openDetail: openFleetDetail,
2001
+ openHistory: ctx => openHistory(ctx, executionHistory, () => (activeTeamName ? `Team: ${activeTeamName}` : "Agent Hub")),
2002
+ modelWorkBlocked: modelWorkBlockedByRosterRecovery,
2003
+ restartSpecialist: researchControls.restartSpecialist,
2004
+ removeResearch: researchControls.remove,
2005
+ killSpecialistProcess: state => { fenceOperatorCancel(state); cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.dispatchId ?? state.runCount), treeKill: killPiTree }); },
2006
+ abortComs: state => { state.comsAbort?.(); },
2007
+ getComsLines: (width, theme) => poolPresentation.render(width, theme),
2008
+ });
2009
+ const { fleetRows, openFleetDashboard: openFleetDashboardRaw } = fleetDashboard;
2010
+ const openFleetDashboard = (ctx: any, startSubstitution = false) => gridUI.withSuspended(() => openFleetDashboardRaw(ctx, startSubstitution));
2011
+
2012
+ const contextBudgetUi = createContextBudgetUi<AgentDef, AgentState, ResearchState>({
2013
+ getAgents: () => agentStates,
2014
+ getResearch: () => researchStates,
2015
+ getAllDefs: () => allAgentDefs,
2016
+ getResearchPersonas: () => researchPersonas,
2017
+ getPeers: () => peerCards.values(),
2018
+ modelPolicy,
2019
+ displayName,
2020
+ getProjectDocsPaths: () => projectDocsPaths,
2021
+ getUserLanguage: () => userLanguage,
2022
+ getDelegateExtensionPath: () => delegateExtPath,
2023
+ safeAgentKey,
2024
+ projectPolicyPaths: specialistProjectPolicyPaths,
2025
+ modelWindowLookup,
2026
+ getResearchTools: () => RESEARCH_TOOLS,
2027
+ getPromptLedger: () => lastHubLedger,
2028
+ getPressureState: () => contextPressureState,
2029
+ buildHubSystemPrompt: () => { buildHubSystemPrompt(); },
2030
+ getAllTools: () => typeof pi.getAllTools === "function" ? pi.getAllTools() : [],
2031
+ getActiveTools: () => typeof pi.getActiveTools === "function" ? pi.getActiveTools() : [],
2032
+ getCommands: () => typeof pi.getCommands === "function" ? pi.getCommands() : [],
2033
+ });
2034
+ const { openContextBudget } = contextBudgetUi;
2035
+
2036
+ // A delegate child anywhere in the team, by its id (e.g. "quality-1").
2037
+ function findDelegationChild(arg: string): { child: DelegationChild; owner: AgentState } | null {
2038
+ const lower = arg.toLowerCase();
2039
+ for (const state of agentStates.values()) {
2040
+ const child = Array.from(state.delegations?.values() ?? []).find(candidate => candidate.id.toLowerCase() === lower);
2041
+ if (child) return { child, owner: state };
2042
+ }
2043
+ return null;
2044
+ }
2045
+
2046
+ const completions = createCompletionPresentation({
2047
+ getAgents: () => agentStates.values(), getResearch: () => researchStates.values(),
2048
+ getResearchPersonas: () => researchPersonas, getModelProfiles: () => modelProfiles,
2049
+ getPeers: peersInScope, displayName, shortModel, resolvedModel, resolvedThinking,
2050
+ resolveThinkingLevel, resolvedSubagentModel,
2051
+ getSubagentOverride: (persona, role) => modelPolicy.getSubagentOverride(persona, role),
2052
+ getSubstitutionSources: () => modelPolicy.allKnownModels().map(spec => {
2053
+ const target = modelPolicy.getSubstitution(spec);
2054
+ return { spec, label: target ? `${spec} → ${target} (active this session)` : spec };
2055
+ }),
2056
+ });
2057
+
2058
+ registerInputShortcuts(pi, {
2059
+ setWidgetContext: ctx => { widgetCtx = ctx; }, openFleetDashboard,
2060
+ toggleFleetWidget: () => gridUI.toggle(),
2061
+ workModeStatusText, openWorkModePicker,
2062
+ });
2063
+
2064
+ // Root owns subscription order; lifecycle modules own handler bodies.
2065
+ registerTurnPresence(pi, {
2066
+ beforeAgentPresence: () => turnHandlers.beforeAgentPresence(),
2067
+ agentEndPresence: () => turnHandlers.agentEndPresence(),
2068
+ });
2069
+
2070
+ // /af-handoff <peer> — hand the session off to a coms peer. Per decision G1 we do NOT
2071
+ // extract the compaction summary; instead we ask the dispatcher LLM (next turn) to
2072
+ // compose a SELF-CONTAINED brief and coms_send it, then await + relay the reply.
2073
+ // /af-compound [focus] — end-of-session compound-learning pass. Mirrors /af-handoff's
2074
+ // shape: the dispatcher LLM (which saw the whole session) composes the
2075
+ // candidate-lessons brief itself, gates it on the user, then dispatches the
2076
+ // documenter to land the approved lessons per skills/compound-learning/SKILL.md.
2077
+ // The rules/docs targets come from the overrides file; artifacts travel as
2078
+ // paths through the dispatch's `artifacts` array, never as pasted bodies.
2079
+ // ── ask_user wait tracking (for /af-agents-history real-work) ──
2080
+ // pi-ask-user blocks the dispatcher turn while the human answers. Bracket each
2081
+ // ask_user call with its tool_execution start/end so /af-agents-history can subtract
2082
+ // that "away from keyboard" time from the dispatcher's real work.
2083
+ // T11 production pre-effect gate: operator direct side effects use the same task-scoped process state as child dispatch.
2084
+ pi.on("tool_call", async (event: any, ctx) => {
2085
+ const toolName = String(event.toolName || "").toLowerCase();
2086
+ const block = processBlock();
2087
+ // set_task_tier binds the fence. ask_user is the human supersession path. Every other tool is a diversion.
2088
+ // The first assistant step may emit several tools together. Refuse that whole step without aborting,
2089
+ // so the model can still call set_task_tier. Abort only a later step that ignores the hint; terminate
2090
+ // alone cannot stop siblings whose calls already returned.
2091
+ if (block && toolName !== "set_task_tier" && toolName !== "ask_user") {
2092
+ const decision = transitionToolDecision(transitionHintDelivered, transitionDiversions, block.message);
2093
+ transitionDiversions = decision.nextCount;
2094
+ transitionBatchRefused = true;
2095
+ if (decision.terminate) ctx?.abort?.();
2096
+ return { block: true, terminate: decision.terminate, reason: decision.reason };
2097
+ }
2098
+ if (!["bash", "edit", "write"].includes(toolName)) return;
2099
+ const gate = processPreEffectGate(processState, "write");
2100
+ if (!gate) return;
2101
+ if (gate.reason !== "action_confirmation_unsupported") return { block: true, reason: gate.message };
2102
+ const bound = taskTriage?.current;
2103
+ // Pi's tool_call contract provides the exact call id and input; absent fields cannot be bound.
2104
+ if (!bound || bound.taskId !== noProgress.taskId() || !event.toolCallId || !event.input || !ctx) return { block: true, reason: gate.message };
2105
+ const action = { taskId: bound.taskId, inputRevision: bound.revision, actionId: String(event.toolCallId), operation: String(event.toolName), target: crypto.createHash("sha256").update(JSON.stringify(event.input)).digest("hex"), cwd: ctx.cwd };
2106
+ const observeAction = (status: TaskTriageActionObservation) => {
2107
+ try { const record = taskTriageActionAuditRecord(action, status); if (record) pi.appendEntry("agent-hub-task-triage-action-observation", record); }
2108
+ catch { /* Diagnostic trace cannot alter effect authorization. */ }
2109
+ };
2110
+ observeAction("requested");
2111
+ const grant = await confirmTaskTriageAction(action, {
2112
+ taskId: () => noProgress.taskId(), inputRevision: () => taskTriage?.current?.revision ?? "",
2113
+ ask: (id, question, askCtx, signal) => requestRuntimeAsk(pi.events, id, question, askCtx, signal),
2114
+ startWait: id => executionHistory.startAskUser(id), endWait: (id, sameTask) => { const wait = executionHistory.endAskUser(id, Date.now()); if (sameTask && wait > 0) { taskClock = addTaskClockWait(taskClock, wait); turnBudgetAskUserWaitMs += wait; } },
2115
+ }, ctx, contract => { pi.appendEntry("agent-hub-task-triage-action-grant", contract); return true; }, undefined, { input: event.input, cwd: ctx.cwd });
2116
+ if (processBlock() || ctx.cwd !== action.cwd || String(event.toolName) !== action.operation || String(event.toolCallId) !== action.actionId
2117
+ || noProgress.taskId() !== action.taskId || taskTriage?.current?.revision !== action.inputRevision
2118
+ || crypto.createHash("sha256").update(JSON.stringify(event.input)).digest("hex") !== action.target) return { block: true, reason: "Action changed while confirmation was pending; effect refused." };
2119
+ if (!grant || !consumeActionGrant(grant, action)) { observeAction("not_granted"); return { block: true, reason: gate.message }; }
2120
+ try { pi.appendEntry("agent-hub-task-triage-action-consumed", action); }
2121
+ catch { observeAction("consumption_failed"); return { block: true, reason: "One-use authorization consumption could not be persisted; effect refused." }; }
2122
+ });
2123
+ pi.on("tool_execution_start", async event => turnHandlers.toolStart(event));
2124
+ observeAskUserResults(({ params, result, phase }) => {
2125
+ const pack = capabilityConfirmationPack(params.context);
2126
+ if (!pack) return;
2127
+ if (phase === "start") workModePolicy.setCapabilityConfirmation(pack, "pending");
2128
+ else {
2129
+ const outcome = confirmationOutcome(result);
2130
+ if (!outcome) return;
2131
+ workModePolicy.setCapabilityConfirmation(pack, outcome);
2132
+ resolveIncomingCapabilities("");
2133
+ applyWorkModeTools();
2134
+ }
2135
+ });
2136
+
2137
+ pi.on("tool_execution_end", async event => turnHandlers.toolEnd(event));
2138
+
2139
+ // ── System Prompt Override ───────────────────
2140
+
2141
+
2142
+ const hubPromptCtx: HubPromptContext = {
2143
+ getTriageBeforeDispatch: () => triageRuntime?.orchestratorBeforeDispatch === true,
2144
+ getAgenticAskMode: () => agenticHubRuntime(pi)?.mode ?? "off",
2145
+ getArtifactRoot: () => sessionDir ? artifactsRoot() : null,
2146
+ getCapabilityResolution,
2147
+ getActiveTools: () => pi.getActiveTools(),
2148
+ getToolCatalogNotice: () => [latestToolCatalogDelta ? toolCatalogNotice(latestToolCatalogDelta) : "", latestUnknownToolNotice].filter(Boolean).join("\n"),
2149
+ getAgents: () => Array.from(agentStates.values()).map(state => ({
2150
+ name: state.def.name,
2151
+ displayName: displayName(state.def.name),
2152
+ description: state.def.description,
2153
+ tools: state.def.tools,
2154
+ })),
2155
+ getResearchPersonas: () => researchPersonas.map(def => ({
2156
+ name: def.name,
2157
+ displayName: displayName(def.name),
2158
+ description: def.description,
2159
+ model: resolvedModel(def),
2160
+ thinking: resolveThinkingLevel(resolvedThinking(def)),
2161
+ })),
2162
+ getPromptState: () => ({
2163
+ taskTier: taskTier ?? DEFAULT_TASK_TIER,
2164
+ taskTierAssumed,
2165
+ processRisk: processState.risk,
2166
+ processScope: processState.scope,
2167
+ processOpen: Object.entries(evaluateProcessObligations(processState, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER }).obligations).filter(([, value]) => value.status === "open").map(([name]) => name),
2168
+ turnDispatchCount,
2169
+ turnResearchCount,
2170
+ taskDispatchCount,
2171
+ taskResearchCount,
2172
+ taskReviewRounds,
2173
+ turnBudget: currentBudget(),
2174
+ taskBudget: currentTaskBudget(),
2175
+ provisionalConfirmations: getCapabilityResolution().provisional
2176
+ .filter(pack => workModePolicy.getCapabilityConfirmation()[pack as ConfirmableCapabilityPack] !== "declined")
2177
+ .map(pack => ({
2178
+ pack,
2179
+ reason: getCapabilityResolution().reasons[pack],
2180
+ question: capabilityConfirmationQuestion(pack as ConfirmableCapabilityPack),
2181
+ })),
2182
+ }),
2183
+ getWorkMode,
2184
+ getActiveTeamName: () => activeTeamName,
2185
+ getUserLanguage: () => userLanguage,
2186
+ getRulesProtocol: buildRulesProtocol,
2187
+ getDocsProtocol: buildDocsProtocol,
2188
+ isAskUserAvailable: () => askUserAvailable,
2189
+ isComsReady: () => comsReady,
2190
+ getIdentity: () => identity,
2191
+ isHerdrFleetReady: () => herdrFleetReady,
2192
+ };
2193
+
2194
+ // This is also called by /af-context before the first turn. Keep prompt assembly
2195
+ // in this one production path so its ledger describes the exact next replacement.
2196
+ function buildHubSystemPrompt(): { systemPrompt: string } {
2197
+ const built = assembleHubPrompt(hubPromptCtx);
2198
+ lastHubLedger = built.ledger;
2199
+ const names = new Set(Array.from(agentStates.values(), s => s.def.name.toLowerCase()));
2200
+ const missingRoles = missingProcessRoleRecoveryHints(processState, names);
2201
+ const additions = activeAdditionRecoveryHints(processState, noProgress.taskId(), taskTriage?.current?.revision);
2202
+ return { systemPrompt: `${built.systemPrompt}\n\nTask-triage (experimental, uncertain): ${JSON.stringify(taskTriage?.status ?? { status: "skipped", detail: "consumer_off" })}. This does not change budget or authorize effects.${processBlock() ? ` BLOCKED: ${processBlock()!.message}` : ""}${missingRoles ? ` ${missingRoles} Never auto-raise tier or substitute an unrelated role.` : ""}${additions ? ` ${additions}` : ""}` };
2203
+ }
2204
+
2205
+ const turnHandlers = createTurnLifecycleHandlers({
2206
+ setTurnState: state => coms.setTurnState(state),
2207
+ finishMonitorTurn: () => { if (monitorBridge && monitorTurnId) { monitorBridge.finishParent(monitorTurnId, "completed"); monitorTurnId = null; } },
2208
+ startMonitorTurn: () => { if (monitorBridge && monitorHubId) { monitorTurnId = `hub-turn-${monitorHubId}-${crypto.randomUUID()}`; monitorBridge.startParent({ id: monitorTurnId, hubInstanceId: monitorHubId, checkoutId: currentCtx?.cwd || process.cwd() }); } },
2209
+ startAskUser: id => executionHistory.startAskUser(id), endAskUser: (id, at) => executionHistory.endAskUser(id, at),
2210
+ acknowledgeExternalBlocker: () => { externalBlockerAcknowledged = true; externalBlockerRefusedOnce = false; },
2211
+ addAskUserWait: waitMs => { if (waitMs > 0) taskClock = addTaskClockWait(taskClock, waitMs); turnBudgetAskUserWaitMs += waitMs; },
2212
+ applyWorkMode: applyWorkModeTools, closeTurnActiveTime, openTaskClock: at => { taskClock = openTaskClock(taskClock, at); }, startHistoryTurn: at => executionHistory.startTurn(at),
2213
+ resetTurnBudgetState: () => {
2214
+ turnBudgetAskUserWaitMs = 0; // budgetRecovery is task-scoped: prose/new turns cannot clear a declined confirmation.
2215
+ turnDispatchCount = 0; turnResearchCount = 0; turnDispatchFingerprints.clear(); externalBlockerAcknowledged = true; externalBlockerRefusedOnce = false;
2216
+ if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) { lastTurnReport = turnReport; sessionTotals.turns++; }
2217
+ turnReport = freshTurnReport();
2218
+ },
2219
+ updateModeStatus, buildPrompt: buildHubSystemPrompt, endHistoryTurn: at => executionHistory.endTurn(at),
2220
+ unaddressedPeerWarning: () => unaddressedPeerSweep(Array.from(hubSpawnedPeers.values()))?.message ?? null,
2221
+ respondToPeer: ctx => coms.respond(ctx),
2222
+ });
2223
+ pi.on("before_agent_start", async () => {
2224
+ if (taskTriageTestTransportActive && process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD) {
2225
+ try { fs.appendFileSync(process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD, JSON.stringify({ pid: process.pid, phase: "before_agent_start", consumerPresent: !!taskTriage, consumerStatus: taskTriage?.status.status ?? null, consumerDetail: taskTriage?.status.detail ?? null, calls: taskTriage?.calls ?? null, processPersistenceBlocked, rosterBlocked: !!currentCtx && modelWorkBlockedByRosterRecovery(currentCtx), pendingTaskTransition }) + "\n"); } catch { /* diagnostic only */ }
2226
+ }
2227
+ // Pressure/roster recovery gates run first; assessment runs before this model input.
2228
+ if (taskTriage && !processPersistenceBlocked && (!currentCtx || !modelWorkBlockedByRosterRecovery(currentCtx))) {
2229
+ // Persist the first task identity before binding a pre-model assessment:
2230
+ // compaction/resume must not mint a new ID for the same cached input.
2231
+ try { noProgress.persistTaskIdentity(); } catch { processPersistenceBlocked = true; }
2232
+ const assessment = processPersistenceBlocked ? null : await taskTriage.evaluate(noProgress.taskId());
2233
+ // Guarded offline fixture diagnostics: metadata only, never task text or provider payload.
2234
+ if (taskTriageTestTransportActive && process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD) {
2235
+ try { fs.appendFileSync(process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD, JSON.stringify({ pid: process.pid, phase: "assessment", inputRevision: assessment?.revision ?? null, fingerprint: assessment?.fingerprint ?? null, taskId: assessment?.taskId ?? null, status: assessment?.assessment.status ?? null, calls: taskTriage.calls, pendingTaskTransition, processPersistenceBlocked }) + "\n"); } catch { /* diagnostic only */ }
2236
+ }
2237
+ if (assessment && !pendingTaskTransition && !processPersistenceBlocked) {
2238
+ try {
2239
+ const next = applyTaskTriageAdditions(processState, assessment.assessment, { taskId: assessment.taskId, evaluationId: assessment.evaluationId, inputRevision: assessment.revision });
2240
+ pi.appendEntry("agent-hub-process-state", processAuditRecord(next, evaluateProcessObligations(next, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER })));
2241
+ processState = next;
2242
+ } catch { processPersistenceBlocked = true; }
2243
+ }
2244
+ }
2245
+ // Assessment can open a plan/review lease after input resolved its original packs.
2246
+ if (taskTriage) workModePolicy.refreshCapabilities();
2247
+ const result = turnHandlers.beforeAgentStart();
2248
+ toolCatalogRuntime.beginTurn();
2249
+ return result;
2250
+ });
2251
+
2252
+ const pressureLifecycle = createContextPressureLifecycle({
2253
+ getState: () => pressureRootState,
2254
+ setPressure: value => { contextPressureState = value; pressureRootState.pressure = value; },
2255
+ getCurrentContext: () => currentCtx,
2256
+ appendEntry: (type, data) => pi.appendEntry(type, data),
2257
+ sendUserMessage: (content, options) => pi.sendUserMessage(content as any, options),
2258
+ resolveCapabilities: resolveIncomingCapabilities, applyWorkMode: applyWorkModeTools,
2259
+ modelWorkBlocked: modelWorkBlockedByRosterRecovery,
2260
+ onAcceptedInput: (text, source, replayed) => {
2261
+ if ((source === "extension" && !replayed) || !text.trim()) return;
2262
+ if (evaluatedTaskTriageInputChanged(taskTriage?.current ?? null, text)) { pendingTaskTransition = true; transitionDiversions = 0; transitionHintDelivered = false; transitionBatchRefused = false; try { pi.appendEntry(TASK_TRANSITION_ENTRY_TYPE, { pending: true }); } catch { processPersistenceBlocked = true; } }
2263
+ hubTaskText = text;
2264
+ taskTriage?.input(text, "interactive");
2265
+ },
2266
+ });
2267
+ function replayDeferredRecoveryInputs(): void { pressureLifecycle.replayDeferred(); }
2268
+ pi.on("message_end", async (event, ctx) => {
2269
+ const diagnostics = observeUnknownToolCalls({ message: event.message, catalog: toolCatalogRuntime.catalogForMessage(), taskId: unknownToolCounter.snapshot().activeTaskId || noProgress.taskId(), counter: unknownToolCounter, seenCallIds: seenUnknownToolCalls });
2270
+ for (const diagnostic of diagnostics) {
2271
+ latestUnknownToolNotice = unknownToolNotice(diagnostic);
2272
+ try { pi.appendEntry(UNKNOWN_TOOL_COUNTER_ENTRY_TYPE, { snapshot: unknownToolCounter.snapshot(), diagnostic }); } catch {}
2273
+ }
2274
+ pressureLifecycle.messageEnd(event, ctx);
2275
+ });
2276
+ pi.on("turn_start", event => { orchestratorSelfReadUsed = 0; hubCapture.start(event.turnIndex); });
2277
+ pi.on("turn_end", async (event, ctx) => {
2278
+ if (transitionBatchRefused && pendingTaskTransition) transitionHintDelivered = true;
2279
+ transitionBatchRefused = false;
2280
+ pressureLifecycle.turnEnd(ctx);
2281
+ const text = event.message.role === "assistant" ? event.message.content.filter(c => c.type === "text").map(c => c.text).join("") : "";
2282
+ hubCapture.end(event.turnIndex, text);
2283
+ });
2284
+ pi.on("context", async (event, ctx) => {
2285
+ pressureLifecycle.context(ctx);
2286
+ const context = hubCapture.hubContext();
2287
+ const text = context && proactiveRuntime?.feedback?.take("hub", "direct", context);
2288
+ if (text) { proactiveHubDeliveries++; return { messages: [...event.messages, { role: "custom" as const, customType: "agent-fleet.proactive-advisory", content: text, display: false, timestamp: Date.now() }] }; }
2289
+ });
2290
+ pi.on("agent_settled", async (_event, ctx) => pressureLifecycle.agentSettled(ctx));
2291
+ pi.on("session_compact", async (_event, ctx) => {
2292
+ noProgress.compact(ctx.sessionManager.getEntries());
2293
+ if (!processPersistenceBlocked) persistProcessVerdict(processState, evaluateProcessObligations(processState, { writable: true, budgetTier: taskTier ?? DEFAULT_TASK_TIER }));
2294
+ const result = toolCatalogRuntime.compact({
2295
+ mode: getWorkMode(), getEffectiveTools: () => pi.getActiveTools(),
2296
+ persist: (type, data) => pi.appendEntry(type, data), counterSnapshot: () => unknownToolCounter.snapshot(),
2297
+ retainCounter: () => unknownToolCounter.noteCompaction(),
2298
+ establishToolStateChange: (previous, next, evidenceRef) => noProgress.establishToolStateChange(previous, next, evidenceRef),
2299
+ settle: () => pressureLifecycle.sessionCompact(),
2300
+ onError: error => { try { pi.appendEntry("agent-hub-tool-catalog-error", { reason: "compaction_restore", error: error instanceof Error ? error.message : String(error) }); } catch {} },
2301
+ });
2302
+ if (result) latestToolCatalogDelta = result.delta;
2303
+ });
2304
+ pi.on("input", async (event, ctx) => {
2305
+ const outcome = pressureLifecycle.input(event, ctx);
2306
+ return { action: outcome.action };
2307
+ });
2308
+
2309
+ // ── Session Start ────────────────────────────
2310
+
2311
+ let sessionOverrides: ReturnType<typeof parseAgentTeamOverrides> | undefined;
2312
+ let sessionSoloMode = false;
2313
+ const monitorSession = createMonitorSession({
2314
+ pi,
2315
+ getBridge: () => monitorBridge, setBridge: value => { monitorBridge = value; },
2316
+ getLifecycle: () => monitorLifecycle, setLifecycle: value => { monitorLifecycle = value; },
2317
+ setHubId: value => { monitorHubId = value; },
2318
+ getOwnerId: () => monitorOwnerId, setOwnerId: value => { monitorOwnerId = value; },
2319
+ queueDepth: () => inboundQueue.size,
2320
+ });
2321
+ registerSessionOrchestration(pi, {
2322
+ resetSession: (_ctx) => resetHubSession(_ctx, {
2323
+ registerVersion: registerVersionStatus, resetPressure: pressureLifecycle.reset,
2324
+ clearRosterRecovery: workModePolicy.clearRosterRecovery, captureBaselineTools: () => { baselineTools = pi.getActiveTools(); },
2325
+ resetAccessApproval: accessApprovalRouter.reset,
2326
+ terminateResearch: () => { for (const st of researchStates.values()) if (st.proc && st.status === "running") { st.killedByOperator = true; st.proc.kill("SIGTERM"); } },
2327
+ resetResearch: researchRuntime.reset, resetHistory: executionHistory.reset,
2328
+ resetBudgets: () => { hubCapture.reset(); hubTaskText = undefined; proactiveRuntime = null; proactiveConfig = null; system1Snapshot = normalizeSystem1Config(null);
2329
+ resetAgenticHub(pi); resetDiscoveryHub(pi); proactiveHubDeliveries = 0; taskClock = createTaskClock(); turnBudgetAskUserWaitMs = 0; turnContinuationCount = 0; taskContinuationCount = 0; budgetRecovery.reset(); noProgress.prepareSessionRestore(); resetUnknownToolCounterForCurrentTask(); toolCatalogRuntime.restore(catalogSnapshot(getWorkMode(), [])); latestToolCatalogDelta = null; },
2330
+ clearWidgets: _ctx => { fleetUiGeneration++; fleetActions?.reset(); gridUI.dispose(); },
2331
+ closeDelegationWatchers: () => { for (const st of agentStates.values()) { st.delegationsWatcher?.close(); st.delegationsWatcher = undefined; } },
2332
+ resetSessionState: ctx => { delegatedTokens = 0; hubSpawnedPeers.clear(); widgetCtx = ctx; contextWindow = ctx.model?.contextWindow || 0; gridUI.reset(); },
2333
+ resolveSafety: cwd => Boolean(safetyHarnessPath = resolveSafetyHarness(cwd)), resolveDelegate: cwd => { delegateExtPath = resolveDelegateExtension(cwd); },
2334
+ }),
2335
+ restartMonitor: _ctx => monitorSession.restart(_ctx),
2336
+ initializeComs: async (_ctx) => {
2337
+ // ── Embedded coms init ──
2338
+ // Always refresh the ctx the coms handlers use. Bind the endpoint + register
2339
+ // in the pool exactly once per process (guard on comsReady), so a /new session
2340
+ // keeps the same peer identity rather than leaking a second socket. On any
2341
+ // failure we degrade: comsReady stays false and the coms_* tools are withheld.
2342
+ hubStateCtx.setCurrentContext(_ctx);
2343
+ sessionSoloMode = pi.getFlag("solo") === true;
2344
+ if (!comsReady && !sessionSoloMode) {
2345
+ try {
2346
+ identity = await coms.connect({ ctx: _ctx, defaultNamePrefix: "hub", defaultPurpose: "agent-hub dispatcher" });
2347
+ comsReady = true;
2348
+ try {
2349
+ _ctx.ui.setStatus("coms", `📡 ${identity.name}@${identity.project}`);
2350
+ } catch { /* hasUI may be false — non-fatal */ }
2351
+ } catch (err) {
2352
+ comsReady = false;
2353
+ try { _ctx.ui?.notify?.(`📡 coms: init failed — ${err instanceof Error ? err.message : String(err)} (coms tools disabled)`, "error"); } catch { /* ignore */ }
2354
+ }
2355
+ }
2356
+ },
2357
+ initializeExemptions: (_ctx) => {
2358
+ try {
2359
+ system1Snapshot = loadSystem1Snapshot(_ctx.cwd || process.cwd());
2360
+ const config = loadProactiveConfig(_ctx.cwd || process.cwd(), system1Snapshot);
2361
+ if (isCaptureEnabled(config)) proactiveConfig = config;
2362
+ } catch { /* invalid config fails closed */ }
2363
+ // ── Damage-control shared exemptions file ──
2364
+ // One per hub session (solo mode included). Exporting the path on our own
2365
+ // process.env lets the co-loaded damage-control-continue mirror /af-allow
2366
+ // session grants into the same file the spawned children read.
2367
+ if (!exemptionsFile) {
2368
+ hubStateCtx.setExemptionsFile(exemptionsFilePath(identity?.session_id ?? `hub-solo-${process.pid}`));
2369
+ process.env[EXEMPTIONS_FILE_ENV] = exemptionsFile!;
2370
+ }
2371
+ },
2372
+ loadAgents: (_ctx) => {
2373
+ // Allocate a fresh namespace; shared legacy files belong to prior/live sessions.
2374
+ sessionOverrides = parseAgentTeamOverrides(_ctx.cwd);
2375
+ try {
2376
+ const config = loadProactiveConfig(_ctx.cwd,system1Snapshot,sessionOverrides.policyRoots);
2377
+ proactiveConfig = isCaptureEnabled(config) ? config : null;
2378
+ } catch { proactiveConfig = null; /* invalid consent fails closed */ }
2379
+ runHistoryKeep = sessionOverrides.runHistoryKeep;
2380
+
2381
+ loadAgents(_ctx.cwd);
2382
+ // Composition follows applyOverrides: approved roots and the shared service do not exist yet.
2383
+
2384
+ // Surface non-fatal persona frontmatter warnings (skipped subagents roles,
2385
+ // bad delegate_depth) once per session.
2386
+ const fmWarnings = allAgentDefs.flatMap(d => (d.warnings || []).map(w => `${d.name}: ${w}`));
2387
+ if (fmWarnings.length > 0) {
2388
+ _ctx.ui.notify(`Persona frontmatter warnings:\n${fmWarnings.join("\n")}`, "warning");
2389
+ }
2390
+ if (!delegateExtPath && allAgentDefs.some(d => d.subagents)) {
2391
+ _ctx.ui.notify(
2392
+ "delegate.ts not found next to agent-hub — `subagents:` declarations are inert (specialists dispatch without a delegate tool).",
2393
+ "warning",
2394
+ );
2395
+ }
2396
+ },
2397
+ applyOverrides: (_ctx) => {
2398
+ if (!sessionOverrides) throw new Error("session_start applyOverrides ran before loadAgents");
2399
+ watchdogSystem1 = disposeWatchdogSystem1Session(watchdogSystem1);
2400
+ communicationStore.dispose();
2401
+ triageRuntime?.dispose(); triageRuntime = null;
2402
+ taskTriage?.dispose(); taskTriage = null;
2403
+ taskTriageActivity?.dispose(); taskTriageActivity = null;
2404
+ try { watchdogActivity?.dispose(); } catch { /* trace disposal must not block the session */ }
2405
+ // Stable for a real session across snapshot replacement; G2 must not split one session into artificial samples.
2406
+ watchdogActivity = sessionDir ? createWatchdogActivity({ directory: `${sessionDir}/artifacts/watchdog`, sessionId: path.basename(sessionDir) }) : null;
2407
+ const taskTriageTestTransport = resolveTaskTriageTestTransport();
2408
+ taskTriageTestTransportActive = !!taskTriageTestTransport;
2409
+ watchdogSystem1 = createWatchdogSystem1Session({ ...readWatchdogSystem1Snapshot({
2410
+ cwd: _ctx.cwd,
2411
+ snapshot: system1Snapshot,
2412
+ configuredMode: sessionOverrides.watchdogSystem1Mode,
2413
+ watchdogSetting: sessionOverrides.watchdogSetting,
2414
+ env: process.env,
2415
+ transport: taskTriageTestTransport,
2416
+ warnings: sessionOverrides.warnings,
2417
+ }), wrapService: service => communicationStore.wrap(service, { provider: "typesafe", model: "jev-1.13.0" }) });
2418
+ const triageConfig = (system1Snapshot?.consumers.dispatchTriage.config ?? null) as TriageConfig | null;
2419
+ const taskTriageConfig = loadTaskTriageConfig(_ctx.cwd || process.cwd(), system1Snapshot);
2420
+ const sharedService = watchdogSystem1?.sharedService;
2421
+ configureAgenticHub(pi, { snapshot: system1Snapshot, service: sharedService, ctx: _ctx, sessionDir, communicationStore, taskId: () => noProgress.taskId() });
2422
+ configureDiscoveryHub(pi, { snapshot: system1Snapshot, service: sharedService, ctx: _ctx, sessionDir, communicationStore, taskId: () => noProgress.taskId() });
2423
+ const serviceUnavailableReason = watchdogSystem1?.readiness.status === "ready" ? "unavailable" : watchdogSystem1?.readiness.reason ?? "unavailable";
2424
+ taskTriageConfigured = taskTriageConfig.status !== "missing";
2425
+ taskTriageConfigStatus = taskTriageConfig.status === "active" ? "active" : taskTriageConfig.status === "invalid" ? "invalid" : "off";
2426
+ taskTriageActivity = taskTriageConfig.status === "active" ? createTaskTriageActivity({ directory: sessionDir ? path.join(sessionDir, "artifacts/task-triage-activity") : undefined }) : null;
2427
+ taskTriage = taskTriageConfig.status === "active" ? createTaskTriageRuntime({ root: _ctx.cwd || process.cwd(), service: sharedService, serviceUnavailableReason, persist: state => pi.appendEntry(TASK_TRIAGE_RUNTIME_ENTRY, state), observer: taskTriageActivity! }) : null;
2428
+ if (taskTriageTestTransportActive && process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD) {
2429
+ try { fs.appendFileSync(process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD, JSON.stringify({ pid: process.pid, phase: "service_init", configStatus: taskTriageConfig.status, consumerPresent: !!taskTriage, fakeTransportActive: taskTriageTestTransportActive, sharedServiceReady: !!sharedService, serviceUnavailableReason }) + "\n"); } catch { /* diagnostic only */ }
2430
+ }
2431
+ if (taskTriage && !sharedService) {
2432
+ try { _ctx.ui.notify(`Task triage is enabled but unavailable (${serviceUnavailableReason}); no inference or new requirements will be added. Existing process obligations remain enforced.`, "warning"); }
2433
+ catch { /* Optional UI must not change process enforcement. The prompt retains the status. */ }
2434
+ }
2435
+ triageRuntime = createTriageRuntime({ config: triageConfig, service: watchdogSystem1?.sharedService,
2436
+ current: input => triageInput(input.task,input.scope,input.language,input.domain),
2437
+ trace: event => pi.appendEntry("agent-hub-triage", event),
2438
+ });
2439
+ applySessionOverrides(_ctx, sessionOverrides, {
2440
+ setLanguage: value => { userLanguage = value; },
2441
+ setReconTimeout: value => { reconSearchTimeoutMs = value; }, setBudgetOverrides: value => { budgetOverrides = value; },
2442
+ setWatchdog: (setting, judge) => { watchdogSetting = setting; watchdogJudgeModel = judge; },
2443
+ resetTurnCounts: () => { turnDispatchCount = 0; turnResearchCount = 0; },
2444
+ // Session setup clears in-memory budgets before restore, not the saved task.
2445
+ // A persisted reset here would append a new task event after the old one.
2446
+ resetTaskWindow: () => resetTaskWindow(null, Date.now(), false), updateModeStatus,
2447
+ setProjectRules: value => { projectRulesDirs = value; }, setProjectDocs: value => { projectDocsPaths = value; },
2448
+ resetModelPolicy: () => {modelPolicy.reset();profileActivation.reset();applyWorkModeTools();}, getModelProfileErrors: () => modelProfileErrors, getAgentDefs: () => allAgentDefs, getModelProfiles: () => modelProfiles,
2449
+ deleteModelProfile: name => { delete modelProfiles[name]; }, allowedModels,
2450
+ getDispatchPolicyWarnings: () => dispatchPolicyWarnings, setResearchPersonas: value => { researchPersonas = value; },
2451
+ });
2452
+ if (proactiveConfig && sessionDir) {
2453
+ try { proactiveRuntime = composeHubProactive({ config: proactiveConfig, root: _ctx.cwd, sessionDir,
2454
+ rulesRoots: sessionOverrides.rulesDirs, policyRoots: sessionOverrides.policyRoots, service: watchdogSystem1?.sharedService, capture: hubCapture, onChange: updateWidget }); }
2455
+ catch { proactiveRuntime = null; proactiveConfig = null; } // unavailable composition never reports reviewed
2456
+ }
2457
+ },
2458
+ restoreRoster: (_ctx) => {
2459
+ // Explicit CLI selection wins; otherwise restore only the canonical team name
2460
+ // and re-resolve it against current teams.yaml/persona files. An explicit
2461
+ // Operator work mode suppresses an ambient persisted roster unless --agent-team
2462
+ // was also supplied.
2463
+ agentStates.clear();
2464
+ activeTeamName = "";
2465
+ comsMissNotified.clear();
2466
+ recomputeGrid();
2467
+ const sessionEntries = _ctx.sessionManager.getEntries();
2468
+ // Resume restores the persisted fence. A missing entry is the legacy clear state.
2469
+ pendingTaskTransition = latestPendingTaskTransition(sessionEntries);
2470
+ transitionDiversions = 0;
2471
+ transitionHintDelivered = false;
2472
+ transitionBatchRefused = false;
2473
+ try { processState = latestProcessState(sessionEntries); processPersistenceBlocked = false; }
2474
+ catch { processState = createProcessState(); processPersistenceBlocked = true; }
2475
+ taskTriage?.restore(sessionEntries);
2476
+ const savedTaskIds = new Set(processState.additions?.map(addition => addition.taskId));
2477
+ noProgress.restore(sessionEntries, savedTaskIds.size === 1 ? [...savedTaskIds][0] : undefined);
2478
+ if (processTaskIdentityConflicts(processState, noProgress.taskId())) processPersistenceBlocked = true;
2479
+ if (taskTriageTestTransportActive && process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD) {
2480
+ try { fs.appendFileSync(process.env.AGENT_HUB_TASK_TRIAGE_FAKE_STATE_RECORD, JSON.stringify({ pid: process.pid, phase: "restore", processPersistenceBlocked, savedTaskIdCount: savedTaskIds.size, taskIdMatchesAddition: savedTaskIds.size === 1 && savedTaskIds.has(noProgress.taskId()), consumerPresent: !!taskTriage, calls: taskTriage?.calls ?? null, consumerStatus: taskTriage?.status.status ?? null }) + "\n"); } catch { /* diagnostic only */ }
2481
+ }
2482
+ const persistedCatalog = latestPersistedToolCatalog(sessionEntries);
2483
+ if (persistedCatalog) toolCatalogRuntime.restore(persistedCatalog);
2484
+ const persistedUnknownTools = latestPersistedUnknownToolCounter(sessionEntries);
2485
+ if (persistedUnknownTools) unknownToolCounter = restoreUnknownToolCounter(persistedUnknownTools, { limit: 3 });
2486
+ const explicitWorkMode = pi.getFlag("work-mode");
2487
+ const explicitRoster = pi.getFlag("agent-team");
2488
+ const hasExplicitRoster = typeof explicitRoster === "string" && explicitRoster.trim() !== "";
2489
+ const startupRoster = resolveSessionRoster({
2490
+ teams,
2491
+ entries: sessionEntries,
2492
+ explicitRoster,
2493
+ availablePersonas: allAgentDefs.map(def => def.name),
2494
+ includePersisted: !(explicitWorkMode === "operator" && !hasExplicitRoster),
2495
+ });
2496
+ workModePolicy.setRestoredWorkMode(resolveSessionWorkMode({
2497
+ entries: sessionEntries,
2498
+ explicitWorkMode,
2499
+ hasExplicitRoster: startupRoster.source === "explicit",
2500
+ }));
2501
+ if (startupRoster.roster) {
2502
+ activateTeam(startupRoster.roster.name);
2503
+ persistActiveRoster();
2504
+ }
2505
+ const rosterRecoveryRequired = orchestratorNeedsRoster(getWorkMode(), agentStates.size);
2506
+ const rosterRecoveryDiagnostic = rosterRecoveryRequired
2507
+ ? startupRoster.diagnostic || "Persisted orchestrator work mode has no native roster."
2508
+ : "";
2509
+ workModePolicy.setRosterRecovery(rosterRecoveryRequired, rosterRecoveryDiagnostic);
2510
+ if (startupRoster.diagnostic) {
2511
+ _ctx.ui.notify(
2512
+ `${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."}`,
2513
+ rosterRecoveryRequired ? "error" : "warning",
2514
+ );
2515
+ } else if (rosterRecoveryRequired) {
2516
+ _ctx.ui.notify(
2517
+ `${rosterRecoveryDiagnostic} Model input is blocked until you select /af-agents-team, restart with --agent-team <name>, or switch explicitly with --work-mode operator.`,
2518
+ "error",
2519
+ );
2520
+ }
2521
+ },
2522
+ resolveCapabilities: async (_ctx) => {
2523
+ // Probe for `ask_user` (registered by the `pi-ask-user` companion package
2524
+ // when installed). Action methods like getAllTools are runtime-only, so
2525
+ // this MUST happen at session_start, not at extension load.
2526
+ askUserAvailable = pi.getAllTools().some(t => t.name === "ask_user");
2527
+
2528
+ // Fleet tools are available only inside a herdr pane with a live server.
2529
+ // The work mode policy adds gated groups without activating unavailable tools.
2530
+ herdrFleetReady = herdrPaneId() !== null && (await herdrAvailable()) !== null;
2531
+ const persistedCapabilities = latestPersistedCapabilityState(_ctx.sessionManager.getEntries());
2532
+ workModePolicy.restoreCapabilities({ taskPacks: persistedCapabilities?.taskPacks ?? [], provisional: persistedCapabilities?.provisional ?? [], confirmation: persistedCapabilities?.confirmation ?? {} });
2533
+ resolveIncomingCapabilities("");
2534
+ applyWorkModeTools();
2535
+ if (pressureLifecycle.observe(_ctx, "session_start") === "compact-now") {
2536
+ setTimeout(() => pressureLifecycle.runCompaction(_ctx, "session_start"), 0);
2537
+ }
2538
+ workModePolicy.updateStatus(_ctx);
2539
+ },
2540
+ notifyStartup: (_ctx) => {
2541
+ _ctx.ui.setStatus("agent-team", `Native roster: ${activeTeamName || "(none)"} (${agentStates.size})`);
2542
+ const members = Array.from(agentStates.values()).map(s => displayName(s.def.name)).join(", ");
2543
+ const askUserLabel = askUserAvailable
2544
+ ? "available (via pi-ask-user)"
2545
+ : "NOT AVAILABLE — run `pi install npm:pi-ask-user`";
2546
+ const comsLabel = comsReady && identity
2547
+ ? `📡 ${identity.name}@${identity.project} — peers via coms_list; /af-handoff <peer> to delegate`
2548
+ : sessionSoloMode
2549
+ ? "off (--solo: fixed specialists + research only)"
2550
+ : "off (endpoint bind failed — coms tools disabled)";
2551
+ const fleetLabel = herdrFleetReady
2552
+ ? "herdr — spawn/read/close panes + notify (herdr_* tools active)"
2553
+ : "off (not inside a herdr pane, or no herdr server)";
2554
+ const comsPreferred = Object.entries(dispatchPolicy.substitutions)
2555
+ .filter(([, s]) => s.prefer === "coms")
2556
+ .map(([n]) => n);
2557
+ const dispatchLabel = dispatchPolicy.default === "coms"
2558
+ ? "coms default — any member with a live same-name pool peer is served by it (/af-dispatch-policy)"
2559
+ : comsPreferred.length > 0
2560
+ ? `coms-preferred: ${comsPreferred.join(", ")} (live peer wins, /af-dispatch-policy for status)`
2561
+ : "all native (no substitutions in .pi/agents/dispatch-policy.yaml)";
2562
+ _ctx.ui.notify(buildSessionStartNotice({
2563
+ workMode: getWorkMode(),
2564
+ activeTeamName,
2565
+ agentCount: agentStates.size,
2566
+ members,
2567
+ dispatchLabel,
2568
+ userLanguage,
2569
+ askUserLabel,
2570
+ comsLabel,
2571
+ fleetLabel,
2572
+ }), "info");
2573
+ },
2574
+ updateWidget: (_ctx) => {
2575
+ updateWidget();
2576
+ },
2577
+ installFooter: (_ctx) => {
2578
+ _ctx.ui.setFooter(createSessionFooter({
2579
+ ctx: _ctx,
2580
+ version: HARNESS_VERSION ?? "unknown",
2581
+ getModel: () => _ctx.model?.id || "no-model",
2582
+ getThinkingLevel: () => pi.getThinkingLevel?.() ?? undefined,
2583
+ thinkingSuffix,
2584
+ getHint: () => composeFleetFooterHint(compactWorkMode(getWorkMode())),
2585
+ renderLeft: renderHubFooterLeft,
2586
+ truncateToWidth,
2587
+ visibleWidth,
2588
+ }));
2589
+ },
2590
+ }, {
2591
+ finishEvidence: () => { if (sessionDir) closeEvidenceSession(sessionDir); },
2592
+ shutdownComs: () => { unregisterQuestions(); return coms.shutdown(); }, shutdownMonitor: () => monitorSession.shutdown(),
2593
+ removeExemptions: () => {
2594
+ if (!exemptionsFile) return;
2595
+ try { fs.unlinkSync(exemptionsFile); } catch {}
2596
+ hubStateCtx.setExemptionsFile(null);
2597
+ },
2598
+ terminateChildren: () => {
2599
+ hubCapture.reset(); proactiveRuntime = null;
2600
+ watchdogSystem1 = disposeWatchdogSystem1Session(watchdogSystem1);
2601
+ communicationStore.dispose();
2602
+ triageRuntime?.dispose(); triageRuntime = null;
2603
+ taskTriage?.dispose(); taskTriage = null;
2604
+ taskTriageActivity?.dispose(); taskTriageActivity = null;
2605
+ taskTriageConfigStatus = "off"; taskTriageConfigured = false;
2606
+ try { watchdogActivity?.dispose(); } catch { /* trace disposal must not block shutdown */ }
2607
+ watchdogActivity = null;
2608
+ for (const st of [...agentStates.values(), ...researchStates.values()]) {
2609
+ fenceOperatorCancel(st);
2610
+ if (st.proc && st.status === "running") try { st.killedByOperator = true; st.proc.kill("SIGTERM"); } catch {}
2611
+ }
2612
+ },
2613
+ clearPoolWidget: () => {
2614
+ gridUI.dispose();
2615
+ if (currentCtx?.hasUI) try { currentCtx.ui.setWidget("coms-pool", undefined); } catch {}
2616
+ },
2617
+ });
2618
+
2619
+ // Ordered end-turn peer response remains after session-start registration.
2620
+ pi.on("agent_end", async (_event, ctx) => {
2621
+ toolCatalogRuntime.endTurn();
2622
+ await turnHandlers.agentEnd(ctx);
2623
+ });
2624
+
2625
+ }