@chankov/agent-fleet 0.0.8 → 0.0.9

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 (340) hide show
  1. package/.pi/agents/model-profiles.yaml +9 -2
  2. package/.pi/agents/peers.yaml +12 -16
  3. package/.pi/agents/teams.yaml +4 -2
  4. package/.pi/harnesses/agent-hub/README.md +20 -5
  5. package/.pi/harnesses/agent-hub/footer.ts +4 -2
  6. package/.pi/harnesses/agent-hub/index.ts +104 -11
  7. package/.pi/harnesses/agent-hub/package.json +1 -1
  8. package/.pi/harnesses/agent-hub/version.ts +25 -1
  9. package/.pi/harnesses/coms/README.md +8 -1
  10. package/.pi/harnesses/coms/package.json +1 -1
  11. package/.pi/harnesses/coms/version.ts +25 -1
  12. package/.pi/harnesses/damage-control-continue/README.md +8 -1
  13. package/.pi/harnesses/damage-control-continue/package.json +1 -1
  14. package/.pi/harnesses/damage-control-continue/version.ts +25 -1
  15. package/.pi/harnesses/lib/herdr-client.ts +10 -1
  16. package/.pi/harnesses/lib/spawned-peers.js +190 -0
  17. package/.versions/0.0.9/.claude/commands/build.md +44 -0
  18. package/.versions/0.0.9/.claude/commands/code-simplify.md +22 -0
  19. package/.versions/0.0.9/.claude/commands/design-agent.md +14 -0
  20. package/.versions/0.0.9/.claude/commands/doctor-agent-fleet.md +17 -0
  21. package/.versions/0.0.9/.claude/commands/orchestrate.md +112 -0
  22. package/.versions/0.0.9/.claude/commands/plan.md +16 -0
  23. package/.versions/0.0.9/.claude/commands/prime.md +22 -0
  24. package/.versions/0.0.9/.claude/commands/review.md +16 -0
  25. package/.versions/0.0.9/.claude/commands/set-hermes-telegram.md +15 -0
  26. package/.versions/0.0.9/.claude/commands/set-hermes-watchdog.md +6 -0
  27. package/.versions/0.0.9/.claude/commands/setup-agent-fleet.md +25 -0
  28. package/.versions/0.0.9/.claude/commands/ship.md +72 -0
  29. package/.versions/0.0.9/.claude/commands/spec.md +15 -0
  30. package/.versions/0.0.9/.claude/commands/test.md +19 -0
  31. package/.versions/0.0.9/.claude/commands/webperf.md +32 -0
  32. package/.versions/0.0.9/.claude/orchestrate-teams.yaml +24 -0
  33. package/.versions/0.0.9/.opencode/commands/af-build.md +17 -0
  34. package/.versions/0.0.9/.opencode/commands/af-code-simplify.md +16 -0
  35. package/.versions/0.0.9/.opencode/commands/af-compound.md +16 -0
  36. package/.versions/0.0.9/.opencode/commands/af-design-agent.md +15 -0
  37. package/.versions/0.0.9/.opencode/commands/af-doctor-agent-fleet.md +17 -0
  38. package/.versions/0.0.9/.opencode/commands/af-orchestrate.md +112 -0
  39. package/.versions/0.0.9/.opencode/commands/af-plan.md +16 -0
  40. package/.versions/0.0.9/.opencode/commands/af-prime.md +22 -0
  41. package/.versions/0.0.9/.opencode/commands/af-review.md +15 -0
  42. package/.versions/0.0.9/.opencode/commands/af-set-hermes-telegram.md +15 -0
  43. package/.versions/0.0.9/.opencode/commands/af-set-hermes-watchdog.md +6 -0
  44. package/.versions/0.0.9/.opencode/commands/af-setup-agent-fleet.md +15 -0
  45. package/.versions/0.0.9/.opencode/commands/af-ship.md +16 -0
  46. package/.versions/0.0.9/.opencode/commands/af-spec.md +16 -0
  47. package/.versions/0.0.9/.opencode/commands/af-test.md +21 -0
  48. package/.versions/0.0.9/.opencode/commands/af-webperf.md +32 -0
  49. package/.versions/0.0.9/.opencode/orchestrate-teams.yaml +24 -0
  50. package/.versions/0.0.9/.pi/agents/dispatch-policy.yaml +32 -0
  51. package/.versions/0.0.9/.pi/agents/model-profiles.yaml +27 -0
  52. package/.versions/0.0.9/.pi/agents/peers.yaml +142 -0
  53. package/.versions/0.0.9/.pi/agents/teams.yaml +41 -0
  54. package/.versions/0.0.9/.pi/damage-control-rules.yaml +297 -0
  55. package/.versions/0.0.9/.pi/extensions/agent-fleet-update-check/README.md +58 -0
  56. package/.versions/0.0.9/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
  57. package/.versions/0.0.9/.pi/extensions/agent-fleet-update-check/package.json +6 -0
  58. package/.versions/0.0.9/.pi/extensions/btw/README.md +118 -0
  59. package/.versions/0.0.9/.pi/extensions/btw/index.ts +917 -0
  60. package/.versions/0.0.9/.pi/extensions/btw/package.json +6 -0
  61. package/.versions/0.0.9/.pi/extensions/btw/state.js +179 -0
  62. package/.versions/0.0.9/.pi/extensions/chrome-devtools-mcp/README.md +58 -0
  63. package/.versions/0.0.9/.pi/extensions/chrome-devtools-mcp/index.ts +93 -0
  64. package/.versions/0.0.9/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
  65. package/.versions/0.0.9/.pi/extensions/compact-and-continue/README.md +42 -0
  66. package/.versions/0.0.9/.pi/extensions/compact-and-continue/index.ts +120 -0
  67. package/.versions/0.0.9/.pi/extensions/compact-and-continue/package.json +6 -0
  68. package/.versions/0.0.9/.pi/extensions/mcp-bridge/README.md +46 -0
  69. package/.versions/0.0.9/.pi/extensions/mcp-bridge/index.ts +206 -0
  70. package/.versions/0.0.9/.pi/extensions/mcp-bridge/package.json +6 -0
  71. package/.versions/0.0.9/.pi/extensions/package-lock.json +1143 -0
  72. package/.versions/0.0.9/.pi/extensions/package.json +9 -0
  73. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/README.md +201 -0
  74. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/config.ts +198 -0
  75. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
  76. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/index.ts +248 -0
  77. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/package.json +6 -0
  78. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/providers.ts +214 -0
  79. package/.versions/0.0.9/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
  80. package/.versions/0.0.9/.pi/harnesses/agent-hub/README.md +872 -0
  81. package/.versions/0.0.9/.pi/harnesses/agent-hub/access-approval.ts +135 -0
  82. package/.versions/0.0.9/.pi/harnesses/agent-hub/artifacts.js +146 -0
  83. package/.versions/0.0.9/.pi/harnesses/agent-hub/assertion-ledger.js +58 -0
  84. package/.versions/0.0.9/.pi/harnesses/agent-hub/backend-policy.js +153 -0
  85. package/.versions/0.0.9/.pi/harnesses/agent-hub/context-window.js +106 -0
  86. package/.versions/0.0.9/.pi/harnesses/agent-hub/delegate.ts +435 -0
  87. package/.versions/0.0.9/.pi/harnesses/agent-hub/drift-watchdog.js +211 -0
  88. package/.versions/0.0.9/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
  89. package/.versions/0.0.9/.pi/harnesses/agent-hub/footer.ts +31 -0
  90. package/.versions/0.0.9/.pi/harnesses/agent-hub/helpers.ts +248 -0
  91. package/.versions/0.0.9/.pi/harnesses/agent-hub/index.ts +8702 -0
  92. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
  93. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-invoke-journal.ts +131 -0
  94. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-invoke.ts +92 -0
  95. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
  96. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
  97. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
  98. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
  99. package/.versions/0.0.9/.pi/harnesses/agent-hub/monitor-session-bridge.ts +257 -0
  100. package/.versions/0.0.9/.pi/harnesses/agent-hub/package.json +7 -0
  101. package/.versions/0.0.9/.pi/harnesses/agent-hub/provider-semaphore.js +138 -0
  102. package/.versions/0.0.9/.pi/harnesses/agent-hub/research-retention.js +34 -0
  103. package/.versions/0.0.9/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
  104. package/.versions/0.0.9/.pi/harnesses/agent-hub/return-contract.js +293 -0
  105. package/.versions/0.0.9/.pi/harnesses/agent-hub/return-extract.js +75 -0
  106. package/.versions/0.0.9/.pi/harnesses/agent-hub/run-budget.js +181 -0
  107. package/.versions/0.0.9/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
  108. package/.versions/0.0.9/.pi/harnesses/agent-hub/scope-gate.js +103 -0
  109. package/.versions/0.0.9/.pi/harnesses/agent-hub/session-health.js +110 -0
  110. package/.versions/0.0.9/.pi/harnesses/agent-hub/spawn.ts +354 -0
  111. package/.versions/0.0.9/.pi/harnesses/agent-hub/version.ts +42 -0
  112. package/.versions/0.0.9/.pi/harnesses/ask-user-remote/README.md +19 -0
  113. package/.versions/0.0.9/.pi/harnesses/ask-user-remote/index.ts +321 -0
  114. package/.versions/0.0.9/.pi/harnesses/ask-user-remote/race-core.js +106 -0
  115. package/.versions/0.0.9/.pi/harnesses/coms/README.md +100 -0
  116. package/.versions/0.0.9/.pi/harnesses/coms/index.ts +1767 -0
  117. package/.versions/0.0.9/.pi/harnesses/coms/package.json +7 -0
  118. package/.versions/0.0.9/.pi/harnesses/coms/version.ts +42 -0
  119. package/.versions/0.0.9/.pi/harnesses/damage-control-continue/README.md +124 -0
  120. package/.versions/0.0.9/.pi/harnesses/damage-control-continue/index.ts +536 -0
  121. package/.versions/0.0.9/.pi/harnesses/damage-control-continue/package.json +7 -0
  122. package/.versions/0.0.9/.pi/harnesses/damage-control-continue/version.ts +42 -0
  123. package/.versions/0.0.9/.pi/harnesses/lib/coms-registry-entry.ts +94 -0
  124. package/.versions/0.0.9/.pi/harnesses/lib/damage-control-shared.ts +197 -0
  125. package/.versions/0.0.9/.pi/harnesses/lib/herdr-client.ts +472 -0
  126. package/.versions/0.0.9/.pi/harnesses/lib/herdr-presence.ts +399 -0
  127. package/.versions/0.0.9/.pi/harnesses/lib/hermes-monitor-events.ts +136 -0
  128. package/.versions/0.0.9/.pi/harnesses/lib/hermes-monitor-herdr.ts +28 -0
  129. package/.versions/0.0.9/.pi/harnesses/lib/hermes-monitor-model.ts +18 -0
  130. package/.versions/0.0.9/.pi/harnesses/lib/hermes-monitor-registry.ts +6 -0
  131. package/.versions/0.0.9/.pi/harnesses/lib/hermes-monitor-socket.ts +163 -0
  132. package/.versions/0.0.9/.pi/harnesses/lib/hermes-monitor-store.ts +31 -0
  133. package/.versions/0.0.9/.pi/harnesses/lib/spawned-peers.js +190 -0
  134. package/.versions/0.0.9/.pi/harnesses/package-lock.json +35 -0
  135. package/.versions/0.0.9/.pi/harnesses/package.json +9 -0
  136. package/.versions/0.0.9/.pi/prompts/af-build.md +24 -0
  137. package/.versions/0.0.9/.pi/prompts/af-code-simplify.md +22 -0
  138. package/.versions/0.0.9/.pi/prompts/af-doctor-agent-fleet.md +15 -0
  139. package/.versions/0.0.9/.pi/prompts/af-plan.md +16 -0
  140. package/.versions/0.0.9/.pi/prompts/af-review.md +16 -0
  141. package/.versions/0.0.9/.pi/prompts/af-set-hermes-telegram.md +15 -0
  142. package/.versions/0.0.9/.pi/prompts/af-set-hermes-watchdog.md +6 -0
  143. package/.versions/0.0.9/.pi/prompts/af-setup-agent-fleet.md +27 -0
  144. package/.versions/0.0.9/.pi/prompts/af-ship.md +17 -0
  145. package/.versions/0.0.9/.pi/prompts/af-spec.md +15 -0
  146. package/.versions/0.0.9/.pi/prompts/af-test.md +19 -0
  147. package/.versions/0.0.9/.pi/skills/bowser/SKILL.md +145 -0
  148. package/.versions/0.0.9/.version +1 -0
  149. package/.versions/0.0.9/agents/architect.md +24 -0
  150. package/.versions/0.0.9/agents/bowser.md +27 -0
  151. package/.versions/0.0.9/agents/builder.md +54 -0
  152. package/.versions/0.0.9/agents/code-reviewer.md +204 -0
  153. package/.versions/0.0.9/agents/deep-researcher.md +32 -0
  154. package/.versions/0.0.9/agents/documenter.md +18 -0
  155. package/.versions/0.0.9/agents/orchestrator.md +66 -0
  156. package/.versions/0.0.9/agents/plan-reviewer.md +62 -0
  157. package/.versions/0.0.9/agents/planner.md +70 -0
  158. package/.versions/0.0.9/agents/releaser.md +24 -0
  159. package/.versions/0.0.9/agents/researcher.md +28 -0
  160. package/.versions/0.0.9/agents/security-auditor.md +167 -0
  161. package/.versions/0.0.9/agents/test-engineer.md +153 -0
  162. package/.versions/0.0.9/agents/web-debugger.md +43 -0
  163. package/.versions/0.0.9/agents/web-performance-auditor.md +193 -0
  164. package/.versions/0.0.9/codex/CONDUCTOR.md +148 -0
  165. package/.versions/0.0.9/docs/ARCHITECTURE.md +262 -0
  166. package/.versions/0.0.9/docs/agent-fleet-setup.md +366 -0
  167. package/.versions/0.0.9/docs/claude-code-coms-bridge.md +109 -0
  168. package/.versions/0.0.9/docs/codex-remote-conductor.md +170 -0
  169. package/.versions/0.0.9/docs/coms-hermes-bridge.md +189 -0
  170. package/.versions/0.0.9/docs/getting-started.md +231 -0
  171. package/.versions/0.0.9/docs/npm-install.md +337 -0
  172. package/.versions/0.0.9/docs/opencode-setup.md +249 -0
  173. package/.versions/0.0.9/docs/pi-extensions.md +356 -0
  174. package/.versions/0.0.9/docs/pi-setup.md +476 -0
  175. package/.versions/0.0.9/docs/skill-anatomy.md +150 -0
  176. package/.versions/0.0.9/hermes/README.md +347 -0
  177. package/.versions/0.0.9/hermes/desktop-plugins/agent-fleet-herdr/plugin.js +1291 -0
  178. package/.versions/0.0.9/hermes/desktop-plugins/agent-fleet-herdr/presentation.js +672 -0
  179. package/.versions/0.0.9/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
  180. package/.versions/0.0.9/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
  181. package/.versions/0.0.9/hermes/gates/gate-o-capability.md +8 -0
  182. package/.versions/0.0.9/hermes/gates/gate-o-validator-fixtures.json +1 -0
  183. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/activity.py +770 -0
  184. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/coms_registry.py +134 -0
  185. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/coms_send.py +350 -0
  186. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/herdr_source.py +193 -0
  187. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/manifest.json +4 -0
  188. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/plugin_api.py +444 -0
  189. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/sessions.py +205 -0
  190. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/tasks.py +300 -0
  191. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/dashboard/watch.py +819 -0
  192. package/.versions/0.0.9/hermes/plugins/agent-fleet-herdr/plugin.yaml +8 -0
  193. package/.versions/0.0.9/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +139 -0
  194. package/.versions/0.0.9/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
  195. package/.versions/0.0.9/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
  196. package/.versions/0.0.9/hermes/skills/hub-conductor/SKILL.md +84 -0
  197. package/.versions/0.0.9/hermes/skills/hub-liaison/SKILL.md +84 -0
  198. package/.versions/0.0.9/hermes/skills/hub-watchdog/SKILL.md +76 -0
  199. package/.versions/0.0.9/hermes/skills/hub-watchdog/manifest.json +1 -0
  200. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog.py +249 -0
  201. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_actions.py +124 -0
  202. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_contract.py +76 -0
  203. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_delivery.py +10 -0
  204. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_engine.py +128 -0
  205. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_judgment.py +41 -0
  206. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_recovery.py +103 -0
  207. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_state.py +163 -0
  208. package/.versions/0.0.9/hermes/skills/hub-watchdog/scripts/watchdog_transport.py +138 -0
  209. package/.versions/0.0.9/hermes/watchdog-tests/__init__.py +0 -0
  210. package/.versions/0.0.9/hooks/SIMPLIFY-IGNORE.md +90 -0
  211. package/.versions/0.0.9/hooks/coms-stop-hook.mjs +84 -0
  212. package/.versions/0.0.9/hooks/hooks.json +14 -0
  213. package/.versions/0.0.9/hooks/session-start.sh +74 -0
  214. package/.versions/0.0.9/hooks/simplify-ignore.sh +302 -0
  215. package/.versions/0.0.9/justfile +254 -0
  216. package/.versions/0.0.9/references/accessibility-checklist.md +160 -0
  217. package/.versions/0.0.9/references/definition-of-done.md +67 -0
  218. package/.versions/0.0.9/references/fleet-coordination-patterns.md +151 -0
  219. package/.versions/0.0.9/references/observability-checklist.md +91 -0
  220. package/.versions/0.0.9/references/orchestration-patterns.md +370 -0
  221. package/.versions/0.0.9/references/performance-checklist.md +153 -0
  222. package/.versions/0.0.9/references/prompting-patterns.md +380 -0
  223. package/.versions/0.0.9/references/security-checklist.md +179 -0
  224. package/.versions/0.0.9/references/testing-patterns.md +236 -0
  225. package/.versions/0.0.9/scripts/codex-conductor.ts +41 -0
  226. package/.versions/0.0.9/scripts/codex-remote-control.ts +167 -0
  227. package/.versions/0.0.9/scripts/coms-claude-bridge.ts +401 -0
  228. package/.versions/0.0.9/scripts/coms-cli.ts +484 -0
  229. package/.versions/0.0.9/scripts/coms-hermes-bridge.ts +413 -0
  230. package/.versions/0.0.9/scripts/fleet.ts +168 -0
  231. package/.versions/0.0.9/scripts/hermes-monitor-capability-runner.ts +25 -0
  232. package/.versions/0.0.9/scripts/hermes-monitor-scenario.ts +474 -0
  233. package/.versions/0.0.9/scripts/hermes-watchdog-capability-probe.ts +45 -0
  234. package/.versions/0.0.9/scripts/install-hermes-plugin.sh +180 -0
  235. package/.versions/0.0.9/scripts/lib/claude-bridge-core.ts +165 -0
  236. package/.versions/0.0.9/scripts/lib/codex-conductor.ts +88 -0
  237. package/.versions/0.0.9/scripts/lib/codex-remote-control.ts +480 -0
  238. package/.versions/0.0.9/scripts/lib/coms-envelope.ts +582 -0
  239. package/.versions/0.0.9/scripts/lib/fake-herdr-server.ts +88 -0
  240. package/.versions/0.0.9/scripts/lib/fleet-command.ts +111 -0
  241. package/.versions/0.0.9/scripts/lib/herdr-layout.ts +281 -0
  242. package/.versions/0.0.9/scripts/lib/hermes-bridge-core.ts +241 -0
  243. package/.versions/0.0.9/scripts/lib/hermes-monitor-events.ts +1 -0
  244. package/.versions/0.0.9/scripts/lib/hermes-monitor-herdr.ts +2 -0
  245. package/.versions/0.0.9/scripts/lib/hermes-monitor-model.ts +3 -0
  246. package/.versions/0.0.9/scripts/lib/hermes-monitor-registry.ts +2 -0
  247. package/.versions/0.0.9/scripts/lib/hermes-monitor-socket.ts +2 -0
  248. package/.versions/0.0.9/scripts/lib/hermes-monitor-store.ts +2 -0
  249. package/.versions/0.0.9/scripts/lib/monitor-env.ts +120 -0
  250. package/.versions/0.0.9/scripts/lib/peer-launch.ts +314 -0
  251. package/.versions/0.0.9/scripts/lib/persona-banner.ts +62 -0
  252. package/.versions/0.0.9/scripts/lib/spawn-stagger.ts +101 -0
  253. package/.versions/0.0.9/scripts/lib/team-project.ts +193 -0
  254. package/.versions/0.0.9/scripts/lib/team-snapshot.ts +147 -0
  255. package/.versions/0.0.9/scripts/peer-banner.ts +40 -0
  256. package/.versions/0.0.9/scripts/peer-launch.ts +259 -0
  257. package/.versions/0.0.9/scripts/team-snapshot.ts +237 -0
  258. package/.versions/0.0.9/scripts/team-up.ts +360 -0
  259. package/.versions/0.0.9/skills/_internal/grilling.md +11 -0
  260. package/.versions/0.0.9/skills/browser-testing-with-devtools/SKILL.md +352 -0
  261. package/.versions/0.0.9/skills/code-review-and-quality/SKILL.md +381 -0
  262. package/.versions/0.0.9/skills/compound-learning/SKILL.md +137 -0
  263. package/.versions/0.0.9/skills/context-engineering/SKILL.md +291 -0
  264. package/.versions/0.0.9/skills/deprecation-and-migration/SKILL.md +206 -0
  265. package/.versions/0.0.9/skills/designing-agents/SKILL.md +394 -0
  266. package/.versions/0.0.9/skills/designing-agents/pi-harness-authoring.md +222 -0
  267. package/.versions/0.0.9/skills/frontend-ui-engineering/SKILL.md +328 -0
  268. package/.versions/0.0.9/skills/git-workflow-and-versioning/SKILL.md +316 -0
  269. package/.versions/0.0.9/skills/guided-workspace-setup/SKILL.md +544 -0
  270. package/.versions/0.0.9/skills/guided-workspace-setup/companion-manifest.json +38 -0
  271. package/.versions/0.0.9/skills/idea-refine/SKILL.md +182 -0
  272. package/.versions/0.0.9/skills/idea-refine/examples.md +238 -0
  273. package/.versions/0.0.9/skills/idea-refine/frameworks.md +99 -0
  274. package/.versions/0.0.9/skills/idea-refine/refinement-criteria.md +113 -0
  275. package/.versions/0.0.9/skills/idea-refine/scripts/idea-refine.sh +15 -0
  276. package/.versions/0.0.9/skills/incremental-implementation/SKILL.md +287 -0
  277. package/.versions/0.0.9/skills/interview-me/SKILL.md +226 -0
  278. package/.versions/0.0.9/skills/orchestration-verification/SKILL.md +181 -0
  279. package/.versions/0.0.9/skills/peer-coms/SKILL.md +90 -0
  280. package/.versions/0.0.9/skills/performance-optimization/SKILL.md +350 -0
  281. package/.versions/0.0.9/skills/planning-and-task-breakdown/SKILL.md +236 -0
  282. package/.versions/0.0.9/skills/security-and-hardening/SKILL.md +461 -0
  283. package/.versions/0.0.9/skills/spec-driven-development/SKILL.md +245 -0
  284. package/.versions/0.0.9/skills/using-agent-skills/SKILL.md +199 -0
  285. package/.versions/0.0.9/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
  286. package/.versions/0.0.9/vendor/agent-skills-upstream/LICENSE +21 -0
  287. package/.versions/0.0.9/vendor/agent-skills-upstream/README.md +11 -0
  288. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
  289. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
  290. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
  291. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
  292. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
  293. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
  294. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
  295. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
  296. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
  297. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
  298. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
  299. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
  300. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
  301. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
  302. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
  303. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
  304. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
  305. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
  306. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
  307. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
  308. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
  309. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
  310. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
  311. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
  312. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
  313. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
  314. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
  315. package/.versions/0.0.9/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
  316. package/CHANGELOG.md +38 -0
  317. package/agents/architect.md +1 -0
  318. package/agents/bowser.md +1 -0
  319. package/agents/builder.md +1 -0
  320. package/agents/code-reviewer.md +4 -5
  321. package/agents/deep-researcher.md +2 -1
  322. package/agents/orchestrator.md +1 -0
  323. package/agents/plan-reviewer.md +3 -1
  324. package/agents/planner.md +3 -2
  325. package/agents/security-auditor.md +1 -0
  326. package/agents/test-engineer.md +3 -1
  327. package/agents/web-debugger.md +1 -0
  328. package/agents/web-performance-auditor.md +1 -0
  329. package/docs/ARCHITECTURE.md +1 -1
  330. package/docs/pi-extensions.md +66 -3
  331. package/justfile +10 -1
  332. package/package.json +2 -2
  333. package/scripts/fleet.ts +22 -3
  334. package/scripts/lib/fleet-command.ts +5 -3
  335. package/scripts/lib/herdr-layout.ts +18 -0
  336. package/scripts/lib/peer-launch.ts +314 -0
  337. package/scripts/lib/team-project.ts +3 -1
  338. package/scripts/peer-launch.ts +259 -0
  339. package/skills/guided-workspace-setup/companion-manifest.json +2 -0
  340. package/.pi/harnesses/agent-hub/spawned-peers.js +0 -74
@@ -0,0 +1,1767 @@
1
+ /**
2
+ * coms — Peer-to-peer messaging between Pi agents on the same machine
3
+ *
4
+ * Each agent listens on a single endpoint (unix socket on POSIX, named pipe on
5
+ * Windows) and discovers peers through per-project registry files under
6
+ * ~/.pi/coms/projects/<project>/agents/<name>.json.
7
+ *
8
+ * Phase A (foundation): identity resolution, registry I/O, transport bind/send,
9
+ * connection handlers. Phase B: tools (coms_list/send/get/await), agent_end
10
+ * response capture. Phase C: live pool widget, ping + keepalive cycles, /af-coms
11
+ * slash command, clean shutdown lifecycle.
12
+ *
13
+ * Usage: pi -e extensions/coms.ts
14
+ */
15
+
16
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@mariozechner/pi-coding-agent";
17
+ import { DynamicBorder } from "@mariozechner/pi-coding-agent";
18
+ import { Text, Container, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@mariozechner/pi-tui";
19
+ import type { AutocompleteItem } from "@mariozechner/pi-tui";
20
+ import { Type } from "@sinclair/typebox";
21
+ import * as net from "node:net";
22
+ import * as fs from "node:fs";
23
+ import * as path from "node:path";
24
+ import * as os from "node:os";
25
+ import * as crypto from "node:crypto";
26
+ import { registerVersionStatus } from "./version.ts";
27
+
28
+ import { buildLiveRegistryEntry, type ComsRegistryEntry } from "../lib/coms-registry-entry.ts";
29
+ import {
30
+ HerdrAgentWatch,
31
+ HerdrPresence,
32
+ herdrPaneId,
33
+ herdrPresenceAvailable,
34
+ peerNameFrom,
35
+ type HerdrAgentInfo,
36
+ } from "../lib/herdr-presence.ts";
37
+
38
+ // ━━ Constants ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
39
+
40
+ const COMS_DIR = process.env.PI_COMS_DIR || path.join(os.homedir(), ".pi", "coms");
41
+ const MAX_HOPS = Number(process.env.PI_COMS_MAX_HOPS) || 5;
42
+ const TIMEOUT_MS = Number(process.env.PI_COMS_TIMEOUT_MS) || 1_800_000;
43
+ const PING_INTERVAL_MS = Number(process.env.PI_COMS_PING_INTERVAL_MS) || 10_000;
44
+ const KEEPALIVE_INTERVAL_MS = 30_000;
45
+ const LINE_CAP_BYTES = 64 * 1024;
46
+
47
+ const FALLBACK_PALETTE = [
48
+ "#72F1B8", "#36F9F6", "#FF7EDB", "#FEDE5D",
49
+ "#C792EA", "#FF8B39", "#4D9DE0", "#FFAA8B",
50
+ ];
51
+
52
+ // ━━ Types ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
53
+
54
+ type EnvelopeType = "prompt" | "response" | "ping";
55
+
56
+ interface Envelope {
57
+ type: EnvelopeType;
58
+ msg_id: string;
59
+ sender_session: string;
60
+ sender_endpoint: string;
61
+ hops: number;
62
+ timestamp: string;
63
+ }
64
+
65
+ interface PromptEnvelope extends Envelope {
66
+ type: "prompt";
67
+ prompt: string;
68
+ sender_name: string;
69
+ sender_cwd: string;
70
+ conversation_id?: string | null;
71
+ response_schema?: object | null;
72
+ /** How long the sender will wait; receivers driving an interactive agent use it. */
73
+ reply_timeout_ms?: number | null;
74
+ }
75
+
76
+ interface ResponseEnvelope extends Envelope {
77
+ type: "response";
78
+ response: any;
79
+ error?: string | null;
80
+ }
81
+
82
+ interface PingEnvelope extends Envelope {
83
+ type: "ping";
84
+ }
85
+
86
+ /** Addressability of a peer right now — see scripts/lib/coms-envelope.ts. */
87
+ type PeerStatus = "idle" | "working" | "booting";
88
+
89
+ interface AgentCard {
90
+ name: string;
91
+ purpose: string;
92
+ model: string;
93
+ color: string;
94
+ context_used_pct: number;
95
+ queue_depth: number;
96
+ /** herdr pane hosting this peer, when it runs in one. */
97
+ pane_id?: string | null;
98
+ /** idle | working | booting. Absent from peers older than this field. */
99
+ status?: PeerStatus;
100
+ }
101
+
102
+ interface Pong {
103
+ type: "pong";
104
+ msg_id: string;
105
+ agent_card: AgentCard;
106
+ }
107
+
108
+ // The registry shape and the heartbeat builder are shared with agent-hub —
109
+ // see ../lib/coms-registry-entry.ts. Both harnesses used to keep their own
110
+ // copy of this literal, and both refreshed `started_at` every 30 seconds.
111
+ type RegistryEntry = ComsRegistryEntry;
112
+
113
+ interface PendingReply {
114
+ resolve: (value: any) => void;
115
+ reject: (err: Error) => void;
116
+ timer: NodeJS.Timeout | null;
117
+ promise: Promise<{ response?: any; error?: string | null }>;
118
+ result?: { response?: any; error?: string | null };
119
+ target_name?: string;
120
+ created_at: string;
121
+ }
122
+
123
+ interface InboundContext {
124
+ msg_id: string;
125
+ hops: number;
126
+ sender_endpoint: string;
127
+ sender_session: string;
128
+ response_schema?: object | null;
129
+ fulfilled: boolean;
130
+ }
131
+
132
+ // ━━ Helpers ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
133
+
134
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
135
+
136
+ function ulid(): string {
137
+ const time = Date.now();
138
+ const rand = crypto.randomBytes(10);
139
+ let timeStr = "";
140
+ let t = time;
141
+ for (let i = 9; i >= 0; i--) {
142
+ timeStr = CROCKFORD[t % 32] + timeStr;
143
+ t = Math.floor(t / 32);
144
+ }
145
+ let randStr = "";
146
+ let bits = 0;
147
+ let value = 0;
148
+ for (const byte of rand) {
149
+ value = (value << 8) | byte;
150
+ bits += 8;
151
+ while (bits >= 5) {
152
+ bits -= 5;
153
+ randStr += CROCKFORD[(value >> bits) & 31];
154
+ }
155
+ }
156
+ return (timeStr + randStr).slice(0, 26);
157
+ }
158
+
159
+ function hexFg(hex: string, s: string): string {
160
+ const r = parseInt(hex.slice(1, 3), 16);
161
+ const g = parseInt(hex.slice(3, 5), 16);
162
+ const b = parseInt(hex.slice(5, 7), 16);
163
+ return `\x1b[38;2;${r};${g};${b}m${s}\x1b[39m`;
164
+ }
165
+
166
+ function isValidHex(hex: string): boolean {
167
+ return /^#[0-9a-fA-F]{6}$/.test(hex);
168
+ }
169
+
170
+ function fallbackColor(sessionId: string): string {
171
+ const h = crypto.createHash("sha256").update(sessionId).digest("hex").slice(0, 8);
172
+ return FALLBACK_PALETTE[Number(BigInt("0x" + h)) % FALLBACK_PALETTE.length];
173
+ }
174
+
175
+ function parseFrontmatter(raw: string): { name?: string; description?: string; color?: string; body: string } {
176
+ const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
177
+ if (!match) return { body: raw };
178
+ const frontmatter: Record<string, string> = {};
179
+ for (const line of match[1].split("\n")) {
180
+ const idx = line.indexOf(":");
181
+ if (idx > 0) {
182
+ const key = line.slice(0, idx).trim();
183
+ let val = line.slice(idx + 1).trim();
184
+ // strip surrounding quotes for values like color: "#36F9F6"
185
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
186
+ val = val.slice(1, -1);
187
+ }
188
+ frontmatter[key] = val;
189
+ }
190
+ }
191
+ return {
192
+ name: frontmatter.name,
193
+ description: frontmatter.description,
194
+ color: frontmatter.color,
195
+ body: match[2],
196
+ };
197
+ }
198
+
199
+ function makeEndpoint(sessionId: string): string {
200
+ if (process.platform === "win32") {
201
+ return `\\\\.\\pipe\\pi-coms-${sessionId}`;
202
+ }
203
+ return path.join(COMS_DIR, "sockets", `${sessionId}.sock`);
204
+ }
205
+
206
+ function nowIso(): string {
207
+ return new Date().toISOString();
208
+ }
209
+
210
+ function abbreviateModel(model: string): string {
211
+ let m = model || "";
212
+ if (m.startsWith("claude-")) m = m.slice("claude-".length);
213
+ if (m.length > 14) m = m.slice(0, 14);
214
+ return m;
215
+ }
216
+
217
+ // ━━ CLI flag shape (read via pi.registerFlag/pi.getFlag) ━━━━━━━━━━━━━━━━━━━
218
+
219
+ interface CliFlags {
220
+ name?: string;
221
+ purpose?: string;
222
+ project?: string;
223
+ color?: string;
224
+ explicit?: boolean;
225
+ }
226
+
227
+ function readCliFlags(pi: ExtensionAPI): CliFlags {
228
+ // Identity flags are declared via pi.registerFlag at extension load time so
229
+ // pi's CLI parser accepts them; here we just read them back.
230
+ const name = pi.getFlag("name") as string | undefined;
231
+ const purpose = pi.getFlag("purpose") as string | undefined;
232
+ const project = pi.getFlag("project") as string | undefined;
233
+ const color = pi.getFlag("color") as string | undefined;
234
+ const explicit = pi.getFlag("explicit") as boolean | undefined;
235
+ return {
236
+ name: name && name.length > 0 ? name : undefined,
237
+ purpose: purpose && purpose.length > 0 ? purpose : undefined,
238
+ project: project && project.length > 0 ? project : undefined,
239
+ color: color && color.length > 0 ? color : undefined,
240
+ explicit: explicit === true,
241
+ };
242
+ }
243
+
244
+ // ━━ Registry I/O ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
245
+
246
+ function projectAgentsDir(project: string): string {
247
+ return path.join(COMS_DIR, "projects", project, "agents");
248
+ }
249
+
250
+ function registryFilePath(project: string, name: string): string {
251
+ return path.join(projectAgentsDir(project), `${name}.json`);
252
+ }
253
+
254
+ function writeRegistryAtomic(entry: RegistryEntry, project: string): string {
255
+ const dir = projectAgentsDir(project);
256
+ fs.mkdirSync(dir, { recursive: true });
257
+ const final = registryFilePath(project, entry.name);
258
+ const tmp = `${final}.tmp`;
259
+ fs.writeFileSync(tmp, JSON.stringify(entry, null, 2));
260
+ fs.renameSync(tmp, final);
261
+ return final;
262
+ }
263
+
264
+ function readAllRegistryEntries(project: string): RegistryEntry[] {
265
+ const dir = projectAgentsDir(project);
266
+ if (!fs.existsSync(dir)) return [];
267
+ const out: RegistryEntry[] = [];
268
+ let files: string[];
269
+ try {
270
+ files = fs.readdirSync(dir);
271
+ } catch {
272
+ return [];
273
+ }
274
+ for (const f of files) {
275
+ if (!f.endsWith(".json")) continue;
276
+ try {
277
+ const raw = fs.readFileSync(path.join(dir, f), "utf-8");
278
+ const parsed = JSON.parse(raw) as RegistryEntry;
279
+ if (parsed && typeof parsed.session_id === "string") {
280
+ out.push(parsed);
281
+ }
282
+ } catch {
283
+ // skip malformed
284
+ }
285
+ }
286
+ return out;
287
+ }
288
+
289
+ function readAllRegistryEntriesAcrossProjects(): RegistryEntry[] {
290
+ const root = path.join(COMS_DIR, "projects");
291
+ let projects: string[];
292
+ try {
293
+ projects = fs.readdirSync(root);
294
+ } catch {
295
+ return [];
296
+ }
297
+ const out: RegistryEntry[] = [];
298
+ for (const p of projects) {
299
+ try {
300
+ if (!fs.statSync(path.join(root, p)).isDirectory()) continue;
301
+ } catch {
302
+ continue;
303
+ }
304
+ out.push(...readAllRegistryEntries(p));
305
+ }
306
+ return out;
307
+ }
308
+
309
+ function removeRegistryEntry(project: string, name: string): void {
310
+ try {
311
+ fs.unlinkSync(registryFilePath(project, name));
312
+ } catch {
313
+ // best-effort
314
+ }
315
+ }
316
+
317
+ function pruneDeadEntries(project: string): RegistryEntry[] {
318
+ const entries = readAllRegistryEntries(project);
319
+ const live: RegistryEntry[] = [];
320
+ for (const entry of entries) {
321
+ try {
322
+ process.kill(entry.pid, 0);
323
+ live.push(entry);
324
+ } catch (e: any) {
325
+ if (e && e.code === "ESRCH") {
326
+ removeRegistryEntry(project, entry.name);
327
+ } else {
328
+ // EPERM means the process exists but we can't signal it — treat as live.
329
+ live.push(entry);
330
+ }
331
+ }
332
+ }
333
+ return live;
334
+ }
335
+
336
+ function resolveUniqueName(project: string, desiredName: string): string {
337
+ // Returns a name that doesn't collide with any LIVE registered agent.
338
+ // pruneDeadEntries auto-removes ESRCH entries; we only care about live ones.
339
+ const liveEntries = pruneDeadEntries(project);
340
+ const liveNames = new Set(liveEntries.map(e => e.name));
341
+ if (!liveNames.has(desiredName)) return desiredName;
342
+ let n = 2;
343
+ while (liveNames.has(`${desiredName}${n}`)) n++;
344
+ return `${desiredName}${n}`;
345
+ }
346
+
347
+ function pruneDeadEntriesAllProjects(): RegistryEntry[] {
348
+ const root = path.join(COMS_DIR, "projects");
349
+ let projects: string[];
350
+ try {
351
+ projects = fs.readdirSync(root);
352
+ } catch {
353
+ return [];
354
+ }
355
+ const out: RegistryEntry[] = [];
356
+ for (const p of projects) {
357
+ try {
358
+ if (!fs.statSync(path.join(root, p)).isDirectory()) continue;
359
+ } catch {
360
+ continue;
361
+ }
362
+ out.push(...pruneDeadEntries(p));
363
+ }
364
+ return out;
365
+ }
366
+
367
+ function keepaliveTouch(file: string): void {
368
+ try {
369
+ const now = new Date();
370
+ fs.utimesSync(file, now, now);
371
+ } catch {
372
+ // best-effort
373
+ }
374
+ }
375
+
376
+ // ━━ Transport ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
377
+
378
+ function probeStaleSocket(endpoint: string): Promise<"in_use" | "stale"> {
379
+ return new Promise((resolve) => {
380
+ const sock = net.createConnection({ path: endpoint });
381
+ let settled = false;
382
+ const finish = (verdict: "in_use" | "stale") => {
383
+ if (settled) return;
384
+ settled = true;
385
+ try { sock.destroy(); } catch { /* ignore */ }
386
+ resolve(verdict);
387
+ };
388
+ const timer = setTimeout(() => finish("stale"), 250);
389
+ sock.once("connect", () => {
390
+ clearTimeout(timer);
391
+ finish("in_use");
392
+ });
393
+ sock.once("error", (err: any) => {
394
+ clearTimeout(timer);
395
+ if (err && err.code === "ECONNREFUSED") {
396
+ finish("stale");
397
+ } else {
398
+ // ENOENT or other — treat as stale (file may be gone or unusable)
399
+ finish("stale");
400
+ }
401
+ });
402
+ });
403
+ }
404
+
405
+ async function bindEndpoint(
406
+ endpoint: string,
407
+ connHandler: (socket: net.Socket) => void,
408
+ ): Promise<net.Server> {
409
+ if (process.platform !== "win32" && fs.existsSync(endpoint)) {
410
+ const verdict = await probeStaleSocket(endpoint);
411
+ if (verdict === "in_use") {
412
+ throw new Error(`coms: endpoint already in use (${endpoint})`);
413
+ }
414
+ try {
415
+ fs.unlinkSync(endpoint);
416
+ } catch {
417
+ // best-effort
418
+ }
419
+ }
420
+ return await new Promise<net.Server>((resolve, reject) => {
421
+ const server = net.createServer(connHandler);
422
+ server.once("error", reject);
423
+ server.listen(endpoint, () => {
424
+ server.removeListener("error", reject);
425
+ resolve(server);
426
+ });
427
+ });
428
+ }
429
+
430
+ function readOneLine(socket: net.Socket): Promise<string> {
431
+ return new Promise((resolve, reject) => {
432
+ let buf = "";
433
+ let settled = false;
434
+ const onData = (chunk: Buffer) => {
435
+ buf += chunk.toString("utf-8");
436
+ if (buf.length > LINE_CAP_BYTES) {
437
+ if (settled) return;
438
+ settled = true;
439
+ socket.removeListener("data", onData);
440
+ reject(new Error("line too large"));
441
+ return;
442
+ }
443
+ const nl = buf.indexOf("\n");
444
+ if (nl >= 0) {
445
+ if (settled) return;
446
+ settled = true;
447
+ socket.removeListener("data", onData);
448
+ resolve(buf.slice(0, nl));
449
+ }
450
+ };
451
+ socket.on("data", onData);
452
+ socket.once("error", (err) => {
453
+ if (settled) return;
454
+ settled = true;
455
+ reject(err);
456
+ });
457
+ socket.once("close", () => {
458
+ if (settled) return;
459
+ settled = true;
460
+ reject(new Error("connection closed before line received"));
461
+ });
462
+ });
463
+ }
464
+
465
+ function sendEnvelope(endpoint: string, envelope: Envelope | Pong | { type: string; msg_id?: string; [k: string]: any }): Promise<any> {
466
+ return new Promise((resolve, reject) => {
467
+ const sock = net.createConnection({ path: endpoint });
468
+ let settled = false;
469
+ const fail = (err: Error) => {
470
+ if (settled) return;
471
+ settled = true;
472
+ try { sock.destroy(); } catch { /* ignore */ }
473
+ reject(err);
474
+ };
475
+ sock.once("error", fail);
476
+ sock.once("connect", async () => {
477
+ try {
478
+ sock.write(JSON.stringify(envelope) + "\n");
479
+ const line = await readOneLine(sock);
480
+ const parsed = JSON.parse(line);
481
+ try { sock.end(); } catch { /* ignore */ }
482
+ if (settled) return;
483
+ settled = true;
484
+ if (parsed && parsed.type === "nack") {
485
+ reject(new Error(parsed.error || "nack"));
486
+ } else {
487
+ resolve(parsed);
488
+ }
489
+ } catch (err) {
490
+ fail(err instanceof Error ? err : new Error(String(err)));
491
+ }
492
+ });
493
+ });
494
+ }
495
+
496
+ // ━━ System-prompt frontmatter scan ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
497
+
498
+ function findSystemPromptPath(argv: string[]): string | null {
499
+ // Prefer --system-prompt (overwrite). Fall back to --append-system-prompt.
500
+ // These flags are pi-builtin (not extension-registered) so we still scan
501
+ // argv directly. First match wins per preference order.
502
+ const scan = (flag: string): string | null => {
503
+ for (let i = 0; i < argv.length; i++) {
504
+ if (argv[i] === flag && i + 1 < argv.length) {
505
+ const candidate = argv[i + 1];
506
+ if (candidate.endsWith(".md")) {
507
+ try {
508
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
509
+ return candidate;
510
+ }
511
+ } catch {
512
+ // fall through
513
+ }
514
+ }
515
+ }
516
+ }
517
+ return null;
518
+ };
519
+ return scan("--system-prompt") ?? scan("--append-system-prompt");
520
+ }
521
+
522
+ function readFrontmatterFromArgv(argv: string[]): { name?: string; description?: string; color?: string } {
523
+ const p = findSystemPromptPath(argv);
524
+ if (!p) return {};
525
+ try {
526
+ const raw = fs.readFileSync(p, "utf-8");
527
+ const { name, description, color } = parseFrontmatter(raw);
528
+ return { name, description, color };
529
+ } catch {
530
+ return {};
531
+ }
532
+ }
533
+
534
+ // ━━ Default export ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
535
+
536
+ export default function (pi: ExtensionAPI) {
537
+ // ━━ Register identity CLI flags so pi's parser accepts them. ━━━━━━━━━
538
+ // Without these, pi 0.73+ rejects the invocation with "Unknown options:
539
+ // --name, --project, ..." before this extension's hooks ever fire.
540
+ pi.registerFlag("name", {
541
+ description: "Override agent name (otherwise from frontmatter or auto-generated)",
542
+ type: "string",
543
+ default: undefined,
544
+ });
545
+ pi.registerFlag("purpose", {
546
+ description: "Override agent purpose (otherwise from frontmatter description)",
547
+ type: "string",
548
+ default: undefined,
549
+ });
550
+ pi.registerFlag("project", {
551
+ description: "Project namespace for peer discovery",
552
+ type: "string",
553
+ default: "default",
554
+ });
555
+ pi.registerFlag("color", {
556
+ description: "Hex color #RRGGBB (otherwise from frontmatter or palette fallback)",
557
+ type: "string",
558
+ default: undefined,
559
+ });
560
+ pi.registerFlag("explicit", {
561
+ description: "Hide this agent from auto-discovery; only addressable by exact name",
562
+ type: "boolean",
563
+ default: false,
564
+ });
565
+
566
+ // State containers — shared across all hooks for this extension instance.
567
+ let identity: {
568
+ session_id: string;
569
+ name: string;
570
+ purpose: string;
571
+ color: string;
572
+ project: string;
573
+ explicit: boolean;
574
+ cwd: string;
575
+ model: string;
576
+ endpoint: string;
577
+ registryFile: string;
578
+ // Set once, at registration. The heartbeat reads it; nothing rewrites it.
579
+ started_at: string;
580
+ } | null = null;
581
+ const peerCards: Map<string, AgentCard & { staleCount: number }> = new Map();
582
+ const pendingReplies: Map<string, PendingReply> = new Map();
583
+ const inboundQueue: Map<string, InboundContext> = new Map();
584
+ let server: net.Server | null = null;
585
+ let pingTimer: NodeJS.Timeout | null = null;
586
+ let keepaliveTimer: NodeJS.Timeout | null = null;
587
+ // herdr presence backend (active when this session runs inside a herdr
588
+ // pane and the server answers ping). The envelope transport and the file
589
+ // registry are untouched — herdr only replaces the presence/ping layer.
590
+ let herdrPresence: HerdrPresence | null = null;
591
+ let herdrWatch: HerdrAgentWatch | null = null;
592
+ let turnState: "idle" | "working" = "idle";
593
+ let includeExplicit = false;
594
+ let displayProject: string | null = null;
595
+ let currentCtx: ExtensionContext | null = null;
596
+ let currentInbound: InboundContext | null = null;
597
+
598
+ // Phase A stub handlers — each just acks valid envelopes. Phase B replaces these.
599
+ function ackOk(socket: net.Socket, msg_id: string): void {
600
+ try {
601
+ socket.write(JSON.stringify({ type: "ack", msg_id }) + "\n");
602
+ } catch {
603
+ // ignore
604
+ }
605
+ try { socket.end(); } catch { /* ignore */ }
606
+ }
607
+
608
+ function nack(socket: net.Socket, msg_id: string, error: string): void {
609
+ try {
610
+ socket.write(JSON.stringify({ type: "nack", msg_id, error }) + "\n");
611
+ } catch {
612
+ // ignore
613
+ }
614
+ try { socket.end(); } catch { /* ignore */ }
615
+ }
616
+
617
+ function handlePrompt(socket: net.Socket, env: PromptEnvelope): void {
618
+ // 1. Hop limit check
619
+ if (typeof env.hops !== "number" || env.hops >= MAX_HOPS) {
620
+ nack(socket, env.msg_id, "hops exceeded");
621
+ return;
622
+ }
623
+
624
+ // 2. Insert into inbound queue
625
+ const inbound: InboundContext = {
626
+ msg_id: env.msg_id,
627
+ hops: env.hops,
628
+ sender_endpoint: env.sender_endpoint,
629
+ sender_session: env.sender_session,
630
+ response_schema: env.response_schema ?? null,
631
+ fulfilled: false,
632
+ };
633
+ inboundQueue.set(env.msg_id, inbound);
634
+
635
+ // 3. Track the current inbound so that any coms_send issued during the
636
+ // resulting LLM turn inherits the right hop count.
637
+ currentInbound = inbound;
638
+
639
+ // 4. Inject as a follow-up message into the receiver's next turn.
640
+ try {
641
+ pi.sendMessage(
642
+ {
643
+ customType: "coms-inbound",
644
+ content: `[from ${env.sender_name} @ ${env.sender_cwd}]\n\n${env.prompt}`,
645
+ display: true,
646
+ details: {
647
+ msg_id: env.msg_id,
648
+ sender_session: env.sender_session,
649
+ response_schema: env.response_schema ?? null,
650
+ },
651
+ },
652
+ { deliverAs: "followUp", triggerTurn: true },
653
+ );
654
+ } catch (err) {
655
+ // If sendMessage fails, drop the inbound and nack.
656
+ inboundQueue.delete(env.msg_id);
657
+ currentInbound = null;
658
+ nack(socket, env.msg_id, "internal error");
659
+ return;
660
+ }
661
+
662
+ // 5. Ack + audit log
663
+ ackOk(socket, env.msg_id);
664
+ try {
665
+ pi.appendEntry("coms-log", {
666
+ event: "inbound_prompt",
667
+ msg_id: env.msg_id,
668
+ sender: env.sender_session,
669
+ hops: env.hops,
670
+ });
671
+ } catch {
672
+ // best-effort
673
+ }
674
+ }
675
+
676
+ function handleResponse(socket: net.Socket, env: ResponseEnvelope): void {
677
+ const pending = pendingReplies.get(env.msg_id);
678
+ if (pending) {
679
+ if (pending.timer) {
680
+ try { clearTimeout(pending.timer); } catch { /* ignore */ }
681
+ pending.timer = null;
682
+ }
683
+ pending.result = { response: env.response, error: env.error ?? null };
684
+ try {
685
+ pending.resolve(pending.result);
686
+ } catch {
687
+ // ignore
688
+ }
689
+ // Note: do NOT delete the entry here — coms_get poll may still want it.
690
+ } else {
691
+ try {
692
+ pi.appendEntry("coms-log", { event: "orphan_response", msg_id: env.msg_id });
693
+ } catch {
694
+ // best-effort
695
+ }
696
+ }
697
+ ackOk(socket, env.msg_id);
698
+ }
699
+
700
+ function handlePing(socket: net.Socket, env: PingEnvelope): void {
701
+ const ctx = currentCtx;
702
+ const ident = identity;
703
+ const pct = ctx ? Math.round(ctx.getContextUsage()?.percent ?? 0) : 0;
704
+ const card: AgentCard = {
705
+ name: ident?.name ?? "unknown",
706
+ purpose: ident?.purpose ?? "",
707
+ model: ctx?.model?.id ?? ident?.model ?? "unknown",
708
+ color: ident?.color ?? "#36F9F6",
709
+ context_used_pct: pct,
710
+ queue_depth: inboundQueue.size,
711
+ pane_id: herdrPaneId() ?? null,
712
+ // A queued inbound prompt counts as busy even between turns: the peer
713
+ // owes someone an answer before it can take another.
714
+ status: (turnState === "working" || inboundQueue.size > 0 ? "working" : "idle") as PeerStatus,
715
+ };
716
+ const pong: Pong = { type: "pong", msg_id: env.msg_id, agent_card: card };
717
+ try {
718
+ socket.write(JSON.stringify(pong) + "\n");
719
+ } catch {
720
+ // ignore
721
+ }
722
+ try { socket.end(); } catch { /* ignore */ }
723
+ }
724
+
725
+ function isValidEnvelope(obj: any): obj is Envelope {
726
+ return (
727
+ obj &&
728
+ typeof obj === "object" &&
729
+ typeof obj.type === "string" &&
730
+ typeof obj.msg_id === "string" &&
731
+ typeof obj.sender_session === "string" &&
732
+ typeof obj.sender_endpoint === "string"
733
+ );
734
+ }
735
+
736
+ function connHandler(socket: net.Socket): void {
737
+ let buf = "";
738
+ let handled = false;
739
+ const onData = (chunk: Buffer) => {
740
+ if (handled) return;
741
+ buf += chunk.toString("utf-8");
742
+ if (buf.length > LINE_CAP_BYTES) {
743
+ handled = true;
744
+ socket.removeListener("data", onData);
745
+ nack(socket, "", "malformed envelope");
746
+ return;
747
+ }
748
+ const nl = buf.indexOf("\n");
749
+ if (nl < 0) return;
750
+ handled = true;
751
+ socket.removeListener("data", onData);
752
+ const line = buf.slice(0, nl);
753
+ let parsed: any;
754
+ try {
755
+ parsed = JSON.parse(line);
756
+ } catch {
757
+ nack(socket, "", "malformed envelope");
758
+ return;
759
+ }
760
+ if (!isValidEnvelope(parsed)) {
761
+ const mid = parsed && typeof parsed.msg_id === "string" ? parsed.msg_id : "";
762
+ nack(socket, mid, "malformed envelope");
763
+ return;
764
+ }
765
+ try {
766
+ if (parsed.type === "prompt") {
767
+ handlePrompt(socket, parsed as PromptEnvelope);
768
+ } else if (parsed.type === "response") {
769
+ handleResponse(socket, parsed as ResponseEnvelope);
770
+ } else if (parsed.type === "ping") {
771
+ handlePing(socket, parsed as PingEnvelope);
772
+ } else {
773
+ nack(socket, parsed.msg_id, "unknown type");
774
+ }
775
+ } catch {
776
+ nack(socket, parsed.msg_id, "internal error");
777
+ }
778
+ };
779
+ socket.on("data", onData);
780
+ socket.once("error", () => {
781
+ // connection failures during handshake — drop quietly
782
+ try { socket.destroy(); } catch { /* ignore */ }
783
+ });
784
+ }
785
+
786
+ // ━━ session_start ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
787
+ pi.on("session_start", async (_event, ctx) => {
788
+ registerVersionStatus(ctx);
789
+ currentCtx = ctx;
790
+
791
+ // 1. Resolve identity from CLI flags > frontmatter > defaults.
792
+ const flags = readCliFlags(pi);
793
+ const fm = readFrontmatterFromArgv(process.argv);
794
+ const project = flags.project || "default";
795
+ const explicit = flags.explicit === true;
796
+ const session_id = ulid();
797
+
798
+ const defaultName = `agent-${session_id.slice(-6)}`;
799
+ // pi's built-in `--name` (session display name) shadows the `--name` flag this
800
+ // extension registers, so `flags.name` (getFlag) stays empty when a user passes
801
+ // `--name`. Recover it via getSessionName() — it ranks like the CLI flag (above
802
+ // frontmatter), so `--name foo` is honored as the coms identity.
803
+ const sessionName = typeof pi.getSessionName === "function" ? (pi.getSessionName() || undefined) : undefined;
804
+ const desiredName = flags.name || sessionName || fm.name || defaultName;
805
+ const name = resolveUniqueName(project, desiredName);
806
+ if (name !== desiredName) {
807
+ try {
808
+ pi.appendEntry("coms-log", { event: "name_collision", desired: desiredName, assigned: name, project });
809
+ } catch {
810
+ // best-effort
811
+ }
812
+ }
813
+ const purpose = flags.purpose || fm.description || "";
814
+
815
+ // Color: validate at every level; fall through invalid hex to next.
816
+ // Order: --color CLI flag > frontmatter color > deterministic fallback.
817
+ let color = fallbackColor(session_id);
818
+ if (fm.color && isValidHex(fm.color)) {
819
+ color = fm.color;
820
+ }
821
+ if (flags.color && isValidHex(flags.color)) {
822
+ color = flags.color;
823
+ }
824
+
825
+ const endpoint = makeEndpoint(session_id);
826
+ const cwd = ctx.cwd || process.cwd();
827
+ const model = ctx.model?.id ?? "unknown";
828
+
829
+ // 2. Ensure storage dirs exist.
830
+ try {
831
+ fs.mkdirSync(path.join(COMS_DIR, "projects", project, "agents"), { recursive: true });
832
+ if (process.platform !== "win32") {
833
+ fs.mkdirSync(path.join(COMS_DIR, "sockets"), { recursive: true });
834
+ try { fs.chmodSync(COMS_DIR, 0o700); } catch { /* best-effort */ }
835
+ }
836
+ } catch (err) {
837
+ ctx.ui?.notify?.(`📡 coms: failed to create dirs — ${err instanceof Error ? err.message : String(err)}`, "error");
838
+ return;
839
+ }
840
+
841
+ // 3. Bind the endpoint.
842
+ try {
843
+ server = await bindEndpoint(endpoint, connHandler);
844
+ } catch (err) {
845
+ ctx.ui?.notify?.(`📡 coms: bind failed — ${err instanceof Error ? err.message : String(err)}`, "error");
846
+ return;
847
+ }
848
+
849
+ // 4. Build + write registry entry atomically.
850
+ const started_at = nowIso();
851
+ const entry: RegistryEntry = {
852
+ session_id,
853
+ name,
854
+ purpose,
855
+ model,
856
+ color,
857
+ pid: process.pid,
858
+ endpoint,
859
+ cwd,
860
+ started_at,
861
+ explicit,
862
+ version: 1,
863
+ };
864
+ let registryFile: string;
865
+ try {
866
+ registryFile = writeRegistryAtomic(entry, project);
867
+ } catch (err) {
868
+ ctx.ui?.notify?.(`📡 coms: registry write failed — ${err instanceof Error ? err.message : String(err)}`, "error");
869
+ try { server?.close(); } catch { /* ignore */ }
870
+ return;
871
+ }
872
+
873
+ identity = {
874
+ session_id,
875
+ name,
876
+ purpose,
877
+ color,
878
+ project,
879
+ explicit,
880
+ cwd,
881
+ model,
882
+ endpoint,
883
+ registryFile,
884
+ started_at,
885
+ };
886
+ includeExplicit = false;
887
+ displayProject = project;
888
+
889
+ // 5. Audit log: boot.
890
+ try {
891
+ pi.appendEntry("coms-log", { event: "boot", session_id, name, project });
892
+ } catch {
893
+ // best-effort
894
+ }
895
+
896
+ // 6. Surface presence in the UI + install the live pool widget.
897
+ try {
898
+ ctx.ui.setStatus("coms", `📡 ${name}@${project}`);
899
+ installPoolWidget(ctx);
900
+ ctx.ui.notify(
901
+ `📡 coms ready · ${name}@${project} · ${displayProject ?? project} pool`,
902
+ "info",
903
+ );
904
+ } catch {
905
+ // hasUI may be false in some contexts — non-fatal.
906
+ }
907
+
908
+ // 7. Presence backend: herdr (push events, no polling) when this
909
+ // session runs inside a herdr pane with a live server; the files ping
910
+ // loop otherwise. The registry keepalive below runs in BOTH backends —
911
+ // it carries the full agent card (purpose, model, colour) that a pane
912
+ // annotation is no place for, and keeps us discoverable to peers
913
+ // running outside herdr panes.
914
+ const useHerdr = await herdrPresenceAvailable();
915
+ if (useHerdr) {
916
+ const paneId = herdrPaneId()!;
917
+ herdrPresence = new HerdrPresence({
918
+ paneId,
919
+ source: `coms:${session_id}`,
920
+ // A herdr that rejects our annotation dialect used to be
921
+ // invisible: presence swallows errors, so the sidebar simply
922
+ // stayed blank and every watcher saw "detached" forever.
923
+ onError: (err, dialect) => {
924
+ try {
925
+ pi.appendEntry("coms-log", { event: "presence_dialect_rejected", dialect, reason: err?.message ?? String(err) });
926
+ } catch { /* best-effort */ }
927
+ },
928
+ });
929
+ void herdrPresence.report("idle", { name, project, contextUsedPct: 0, queueDepth: 0 });
930
+ herdrWatch = new HerdrAgentWatch({
931
+ ownPaneId: paneId,
932
+ onChange: (agents) => herdrSyncPeerCards(agents),
933
+ });
934
+ void herdrWatch.start();
935
+ try {
936
+ pi.appendEntry("coms-log", { event: "presence_backend", backend: "herdr", pane: paneId });
937
+ } catch { /* best-effort */ }
938
+ } else {
939
+ pingTimer = setInterval(() => { refreshPool().catch(() => {}); }, PING_INTERVAL_MS);
940
+ try { (pingTimer as any).unref?.(); } catch { /* ignore */ }
941
+ }
942
+ keepaliveTimer = setInterval(() => {
943
+ if (!identity) return;
944
+ try {
945
+ const ctx = currentCtx;
946
+ // Detect missing-registry BEFORE writing so the self_heal audit only
947
+ // fires when something actually went wrong (file unlinked under us).
948
+ const missingBeforeWrite = !fs.existsSync(identity.registryFile);
949
+ const live: RegistryEntry = buildLiveRegistryEntry(identity, {
950
+ now: nowIso(),
951
+ pid: process.pid,
952
+ model: ctx?.model?.id,
953
+ contextUsedPct: ctx?.getContextUsage()?.percent,
954
+ queueDepth: inboundQueue.size,
955
+ });
956
+ // Unconditional atomic write: handles BOTH the live-status refresh
957
+ // (file present → overwrite with fresh values) AND self-heal (file
958
+ // missing → re-create entry). The atomic write also bumps mtime, so
959
+ // keepaliveTouch is now redundant.
960
+ writeRegistryAtomic(live, identity.project);
961
+ if (missingBeforeWrite) {
962
+ pi.appendEntry("coms-log", { event: "self_heal", session_id: identity.session_id, reason: "registry file missing" });
963
+ // Edge case: if the file was unlinked again between our write and
964
+ // this check, re-write once to be safe.
965
+ if (!fs.existsSync(identity.registryFile)) {
966
+ writeRegistryAtomic(live, identity.project);
967
+ }
968
+ }
969
+ } catch { /* best-effort */ }
970
+ // herdr backend: refresh our sidebar entry (context % / queue move
971
+ // without a state change) and re-join peer cards against the
972
+ // registry heartbeats just written by the other peers.
973
+ if (herdrPresence && identity) {
974
+ const pct = Math.round(currentCtx?.getContextUsage()?.percent ?? 0);
975
+ void herdrPresence.report(turnState, { name: identity.name, project: identity.project, contextUsedPct: pct, queueDepth: inboundQueue.size });
976
+ }
977
+ if (herdrWatch) herdrSyncPeerCards(herdrWatch.current());
978
+ }, KEEPALIVE_INTERVAL_MS);
979
+ try { (keepaliveTimer as any).unref?.(); } catch { /* ignore */ }
980
+
981
+ // Kick one cycle immediately so the widget populates fast (the herdr
982
+ // backend populates from its initial agent.list snapshot instead).
983
+ if (!useHerdr) refreshPool().catch(() => {});
984
+ });
985
+
986
+ // ━━ herdr presence: turn-state reporting + peer-card sync ━━━━━━━━━━━━━
987
+ // The herdr sidebar mirrors turn state (idle ↔ working) push-style;
988
+ // context % rides the keepalive refresh above.
989
+ pi.on("before_agent_start", async () => {
990
+ turnState = "working";
991
+ if (herdrPresence && identity) {
992
+ const pct = Math.round(currentCtx?.getContextUsage()?.percent ?? 0);
993
+ void herdrPresence.report("working", { name: identity.name, project: identity.project, contextUsedPct: pct, queueDepth: inboundQueue.size });
994
+ }
995
+ });
996
+
997
+ pi.on("agent_end", async () => {
998
+ turnState = "idle";
999
+ if (herdrPresence && identity) {
1000
+ const pct = Math.round(currentCtx?.getContextUsage()?.percent ?? 0);
1001
+ void herdrPresence.report("idle", { name: identity.name, project: identity.project, contextUsedPct: pct, queueDepth: inboundQueue.size });
1002
+ }
1003
+ });
1004
+
1005
+ // Join herdr's live pane states back to the coms registry: a herdr agent
1006
+ // that advertises a coms peer name maps to that peer's registry entry
1007
+ // (which carries the full card a pane annotation has no room for).
1008
+ // Pool-scope semantics are preserved — only entries from peersInScope()
1009
+ // become cards; peers outside herdr panes stay visible as registry-only
1010
+ // "pending" rows exactly like an unpinged peer in the files backend.
1011
+ function herdrSyncPeerCards(agents: HerdrAgentInfo[]): void {
1012
+ if (!identity) return;
1013
+ const liveNames = new Set<string>();
1014
+ for (const a of agents) {
1015
+ const peerName = peerNameFrom(a);
1016
+ if (peerName) liveNames.add(peerName);
1017
+ }
1018
+ let changed = false;
1019
+ const liveSessions = new Set<string>();
1020
+ for (const entry of peersInScope()) {
1021
+ if (!liveNames.has(entry.name)) continue;
1022
+ liveSessions.add(entry.session_id);
1023
+ const next = {
1024
+ name: entry.name,
1025
+ purpose: entry.purpose,
1026
+ model: entry.model,
1027
+ color: entry.color,
1028
+ context_used_pct: entry.context_used_pct ?? 0,
1029
+ queue_depth: entry.queue_depth ?? 0,
1030
+ staleCount: 0,
1031
+ };
1032
+ const prev = peerCards.get(entry.session_id);
1033
+ if (!prev || JSON.stringify(prev) !== JSON.stringify(next)) {
1034
+ peerCards.set(entry.session_id, next);
1035
+ changed = true;
1036
+ }
1037
+ }
1038
+ for (const sid of [...peerCards.keys()]) {
1039
+ if (sid === identity.session_id) continue;
1040
+ if (!liveSessions.has(sid)) {
1041
+ peerCards.delete(sid);
1042
+ changed = true;
1043
+ }
1044
+ }
1045
+ if (changed && currentCtx?.hasUI) {
1046
+ installPoolWidget(currentCtx);
1047
+ }
1048
+ }
1049
+
1050
+ // ━━ Helpers used by tools ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1051
+
1052
+ async function pingPeer(endpoint: string): Promise<AgentCard | null> {
1053
+ if (!identity) return null;
1054
+ const env: PingEnvelope = {
1055
+ type: "ping",
1056
+ msg_id: ulid(),
1057
+ sender_session: identity.session_id,
1058
+ sender_endpoint: identity.endpoint,
1059
+ hops: 0,
1060
+ timestamp: nowIso(),
1061
+ };
1062
+ try {
1063
+ const resp = await sendEnvelope(endpoint, env);
1064
+ if (resp && resp.type === "pong" && resp.agent_card) {
1065
+ return resp.agent_card as AgentCard;
1066
+ }
1067
+ } catch {
1068
+ // ignore — peer unreachable
1069
+ }
1070
+ return null;
1071
+ }
1072
+
1073
+ // ━━ Pool widget rendering ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1074
+ function renderPool(width: number, theme: Theme): string[] {
1075
+ const projectFilter = displayProject ?? identity?.project ?? "default";
1076
+ const registryEntries = projectFilter === "*"
1077
+ ? readAllRegistryEntriesAcrossProjects()
1078
+ : readAllRegistryEntries(projectFilter);
1079
+
1080
+ interface Row {
1081
+ name: string;
1082
+ model: string;
1083
+ color: string;
1084
+ purpose: string;
1085
+ pct: number | null;
1086
+ pending: boolean;
1087
+ stale: boolean;
1088
+ }
1089
+ const rows: Row[] = [];
1090
+ const seenSessions = new Set<string>();
1091
+
1092
+ for (const [sid, card] of peerCards.entries()) {
1093
+ if (identity && sid === identity.session_id) continue;
1094
+ seenSessions.add(sid);
1095
+ rows.push({
1096
+ name: card.name,
1097
+ model: card.model,
1098
+ color: card.color,
1099
+ purpose: card.purpose,
1100
+ pct: card.context_used_pct,
1101
+ pending: false,
1102
+ stale: (card.staleCount ?? 0) >= 3,
1103
+ });
1104
+ }
1105
+
1106
+ // Registry-only entries that aren't yet in peerCards → pending
1107
+ const seenNames = new Set(rows.map((r) => r.name));
1108
+ for (const entry of registryEntries) {
1109
+ if (identity && entry.session_id === identity.session_id) continue;
1110
+ if (!includeExplicit && entry.explicit) continue;
1111
+ if (seenSessions.has(entry.session_id)) continue;
1112
+ if (seenNames.has(entry.name)) continue;
1113
+ rows.push({
1114
+ name: entry.name,
1115
+ model: entry.model,
1116
+ color: entry.color,
1117
+ purpose: entry.purpose,
1118
+ pct: null,
1119
+ pending: true,
1120
+ stale: false,
1121
+ });
1122
+ }
1123
+
1124
+ // Border helpers — sandwich the body with single-line box-drawing rules
1125
+ // so the widget reads as its own block. The top border carries a branded
1126
+ // ` coms ` tag; bottom border stays a plain rule for minimalism.
1127
+ const safeWidth = Math.max(0, width);
1128
+ let topBorder: string;
1129
+ let bottomBorder: string;
1130
+ if (safeWidth < 12) {
1131
+ topBorder = theme.fg("dim", "━".repeat(safeWidth));
1132
+ bottomBorder = theme.fg("dim", "━".repeat(safeWidth));
1133
+ } else {
1134
+ const left = theme.fg("dim", "┏━") + theme.fg("border", " coms ");
1135
+ const leftFill = theme.fg("dim", "━");
1136
+ const nameLen = identity ? identity.name.length : 0;
1137
+ const rightTagVisLen = identity ? nameLen + 4 : 0;
1138
+ const remaining = safeWidth - 9 /* "┏━ coms ━" */ - rightTagVisLen - 1 /* "┓" */;
1139
+ if (identity && remaining >= 1) {
1140
+ const rightTag =
1141
+ theme.fg("dim", " ") +
1142
+ hexFg(identity.color, identity.name) +
1143
+ theme.fg("dim", " ━");
1144
+ const middle = theme.fg("dim", "━".repeat(remaining));
1145
+ const right = theme.fg("dim", "┓");
1146
+ topBorder = left + leftFill + middle + rightTag + right;
1147
+ } else {
1148
+ const fallbackRemaining = Math.max(0, safeWidth - 2 /* "┏━" */ - 6 /* " coms " */ - 1 /* "┓" */);
1149
+ const right = theme.fg("dim", "━".repeat(fallbackRemaining) + "┓");
1150
+ topBorder = left + right;
1151
+ }
1152
+ bottomBorder = theme.fg("dim", "┗" + "━".repeat(safeWidth - 2) + "┛");
1153
+ }
1154
+
1155
+ if (rows.length === 0) {
1156
+ const emptyMsg = theme.fg("muted", "no peers connected");
1157
+ return [
1158
+ topBorder,
1159
+ truncateToWidth(theme.fg("dim", " ") + emptyMsg, width),
1160
+ bottomBorder,
1161
+ ];
1162
+ }
1163
+
1164
+ rows.sort((a, b) => a.name.localeCompare(b.name));
1165
+
1166
+ const out: string[] = [topBorder];
1167
+
1168
+ for (const r of rows) {
1169
+ const pctNum = r.pct ?? 0;
1170
+ const filled = Math.max(0, Math.min(15, Math.round((pctNum / 100) * 15)));
1171
+ const empty = 15 - filled;
1172
+ const pctLabel = r.pct == null ? "--%" : `${r.pct}%`;
1173
+
1174
+ if (r.stale) {
1175
+ const dimRow = `✗ ${r.name.padEnd(12)} ${abbreviateModel(r.model).padEnd(14)} [${"-".repeat(15)}] ${pctLabel.padStart(4)} — ${r.purpose || ""}`;
1176
+ out.push(truncateToWidth(" " + theme.fg("dim", dimRow), width));
1177
+ continue;
1178
+ }
1179
+
1180
+ const swatch = r.pending ? theme.fg("dim", "●") : hexFg(r.color, "●");
1181
+ const namePart = theme.fg("accent", r.name.padEnd(12));
1182
+ const modelPart = theme.fg("dim", abbreviateModel(r.model).padEnd(14));
1183
+ const barFill = r.pending
1184
+ ? theme.fg("dim", "-".repeat(15))
1185
+ : hexFg(r.color, "#".repeat(filled)) + theme.fg("dim", "-".repeat(empty));
1186
+ const bar = theme.fg("warning", "[") + barFill + theme.fg("warning", "]");
1187
+ const pctPart = " " + theme.fg("accent", pctLabel.padStart(4));
1188
+ const sep = theme.fg("dim", " — ");
1189
+ const purposePart = theme.fg("muted", r.purpose || "");
1190
+
1191
+ const line = " " + swatch + " " + namePart + " " + modelPart + " " + bar + pctPart + sep + purposePart;
1192
+ out.push(truncateToWidth(line, width));
1193
+ }
1194
+
1195
+ out.push(bottomBorder);
1196
+ return out;
1197
+ }
1198
+
1199
+ function installPoolWidget(ctx: ExtensionContext): void {
1200
+ if (!ctx.hasUI) return;
1201
+ try {
1202
+ ctx.ui.setWidget("coms-pool", (_tui, theme) => ({
1203
+ invalidate() {},
1204
+ render(width: number): string[] {
1205
+ return renderPool(width, theme);
1206
+ },
1207
+ }), { placement: "belowEditor" });
1208
+ } catch {
1209
+ // non-fatal
1210
+ }
1211
+ }
1212
+
1213
+ // ━━ Ping cycle ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1214
+ async function refreshPool(): Promise<void> {
1215
+ if (!identity) return;
1216
+ const peers = peersInScope();
1217
+
1218
+ const results = await Promise.allSettled(peers.map(async (peer) => {
1219
+ const pingEnv: PingEnvelope = {
1220
+ type: "ping",
1221
+ msg_id: ulid(),
1222
+ sender_session: identity!.session_id,
1223
+ sender_endpoint: identity!.endpoint,
1224
+ hops: 0,
1225
+ timestamp: nowIso(),
1226
+ };
1227
+ const reply = await sendEnvelope(peer.endpoint, pingEnv);
1228
+ return { peer, pong: reply as Pong };
1229
+ }));
1230
+
1231
+ const seenSessions = new Set<string>();
1232
+ let changed = false;
1233
+
1234
+ for (const r of results) {
1235
+ if (r.status === "fulfilled" && r.value.pong && r.value.pong.agent_card) {
1236
+ const { peer, pong } = r.value;
1237
+ seenSessions.add(peer.session_id);
1238
+ const prev = peerCards.get(peer.session_id);
1239
+ const next = { ...pong.agent_card, staleCount: 0 };
1240
+ if (!prev || JSON.stringify({ ...prev, staleCount: 0 }) !== JSON.stringify(next)) {
1241
+ peerCards.set(peer.session_id, next);
1242
+ changed = true;
1243
+ }
1244
+ }
1245
+ }
1246
+
1247
+ for (const [sid, card] of peerCards.entries()) {
1248
+ if (identity && sid === identity.session_id) continue;
1249
+ if (!seenSessions.has(sid)) {
1250
+ card.staleCount = (card.staleCount ?? 0) + 1;
1251
+ if (card.staleCount > 6) {
1252
+ peerCards.delete(sid);
1253
+ }
1254
+ changed = true;
1255
+ }
1256
+ }
1257
+
1258
+ if (changed && currentCtx?.hasUI) {
1259
+ installPoolWidget(currentCtx);
1260
+ }
1261
+ }
1262
+
1263
+ function listProjects(): string[] {
1264
+ const root = path.join(COMS_DIR, "projects");
1265
+ try {
1266
+ return fs.readdirSync(root).filter((d) => {
1267
+ try { return fs.statSync(path.join(root, d)).isDirectory(); } catch { return false; }
1268
+ });
1269
+ } catch {
1270
+ return [];
1271
+ }
1272
+ }
1273
+
1274
+ function peersInScope(): RegistryEntry[] {
1275
+ if (!identity) return [];
1276
+ const filter = displayProject ?? identity.project;
1277
+ const live = filter === "*" ? pruneDeadEntriesAllProjects() : pruneDeadEntries(filter);
1278
+ return live.filter(
1279
+ (e) => e.session_id !== identity!.session_id && (includeExplicit || !e.explicit),
1280
+ );
1281
+ }
1282
+
1283
+ function resolveTarget(target: string): RegistryEntry | null {
1284
+ // Scoped to the connected pool only (peersInScope): you can reach exactly the
1285
+ // peers the widget shows. Match by name first (preferred, human-facing), then by
1286
+ // session_id. A peer outside the current scope is intentionally NOT resolved — the
1287
+ // human must widen scope via /af-coms --project / --all first. This closes the old
1288
+ // cross-project leak where a name match fell through to scanning every project.
1289
+ const scope = peersInScope();
1290
+ const byName = scope.find((e) => e.name === target);
1291
+ if (byName) return byName;
1292
+ return scope.find((e) => e.session_id === target) ?? null;
1293
+ }
1294
+
1295
+ // ━━ Tools ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1296
+
1297
+ pi.registerTool({
1298
+ name: "coms_list",
1299
+ label: "Coms List",
1300
+ description:
1301
+ "List the peer agents in your current coms pool — the ones shown in the pool widget. Returns " +
1302
+ "names, models, live context-window usage, the herdr pane_id, and status (idle | working | " +
1303
+ "booting). CHECK STATUS BEFORE SENDING: `working` means the peer is mid-turn and your send " +
1304
+ "will wait for it; `booting` means it registered but is not addressable yet. Use this instead " +
1305
+ "of reading the peer's pane to guess whether it is busy. Discovery is scoped to what the human " +
1306
+ "displays via /af-coms; you CANNOT widen it to other projects or reveal --explicit peers yourself.",
1307
+ parameters: Type.Object({
1308
+ project: Type.Optional(Type.String({ description: "Narrow to a project WITHIN the current pool scope. Cannot widen beyond what /af-coms displays — a widening request is ignored." })),
1309
+ include_explicit: Type.Optional(Type.Boolean({ description: "Only narrows: pass false to hide explicit peers. Cannot reveal them unless the human ran /af-coms --all." })),
1310
+ }),
1311
+ async execute(_callId, params) {
1312
+ if (!identity) {
1313
+ return {
1314
+ content: [{ type: "text" as const, text: "coms not initialised." }],
1315
+ details: { agents: [], project: null },
1316
+ };
1317
+ }
1318
+ // Clamp discovery to the human-set pool scope (displayProject + includeExplicit,
1319
+ // driven by /af-coms). The LLM's project/include_explicit may NARROW within that
1320
+ // scope but can never widen it — cross-project or explicit discovery requires a
1321
+ // deliberate /af-coms --project / --all from the human. So coms_list returns exactly
1322
+ // the pool, the same boundary coms_send enforces.
1323
+ const scopeProject = displayProject ?? identity.project;
1324
+ let projects: string[];
1325
+ let widened = false;
1326
+ if (scopeProject === "*") {
1327
+ projects = params.project && params.project !== "*" ? [params.project] : listProjects();
1328
+ } else {
1329
+ projects = [scopeProject];
1330
+ if (params.project && params.project !== scopeProject) widened = true;
1331
+ }
1332
+ // include_explicit may only narrow (turn OFF); it cannot reveal explicit peers
1333
+ // unless the human already did via /af-coms --all.
1334
+ const includeExp = includeExplicit && params.include_explicit !== false;
1335
+ if (params.include_explicit === true && !includeExplicit) widened = true;
1336
+
1337
+ const collected: { entry: RegistryEntry; project: string }[] = [];
1338
+ for (const proj of projects) {
1339
+ for (const entry of pruneDeadEntries(proj)) {
1340
+ if (entry.explicit && !includeExp) continue;
1341
+ if (entry.session_id === identity.session_id) continue;
1342
+ collected.push({ entry, project: proj });
1343
+ }
1344
+ }
1345
+
1346
+ // Ping each peer in parallel for live context usage.
1347
+ const pongs = await Promise.allSettled(collected.map((c) => pingPeer(c.entry.endpoint)));
1348
+
1349
+ const agents = collected.map((c, i) => {
1350
+ const r = pongs[i];
1351
+ const pong = r.status === "fulfilled" ? r.value : null;
1352
+ return {
1353
+ name: c.entry.name,
1354
+ session_id: c.entry.session_id,
1355
+ purpose: c.entry.purpose,
1356
+ model: c.entry.model,
1357
+ cwd: c.entry.cwd,
1358
+ project: c.project,
1359
+ alive: pong != null,
1360
+ context_used_pct: pong ? pong.context_used_pct : null,
1361
+ // Check these BEFORE sending: a `working` peer will make the send
1362
+ // wait, and a `booting` one is not addressable yet. Reading the
1363
+ // pane to find this out is the thing they replace.
1364
+ pane_id: pong?.pane_id ?? null,
1365
+ status: pong?.status ?? null,
1366
+ queue_depth: pong ? pong.queue_depth : null,
1367
+ color: c.entry.color,
1368
+ };
1369
+ });
1370
+
1371
+ const notice = widened
1372
+ ? `\n\n(Discovery is scoped to "${scopeProject}"${includeExplicit ? "" : ", explicit peers hidden"}. ` +
1373
+ `Widening to other projects or revealing --explicit peers is a human action via ` +
1374
+ `/af-coms --project <name> or /af-coms --all.)`
1375
+ : "";
1376
+
1377
+ const lines = agents.length === 0
1378
+ ? "No peer agents in your pool."
1379
+ : agents.map((a) => {
1380
+ const ctxStr = a.context_used_pct != null ? ` ${a.context_used_pct}%` : " ?%";
1381
+ const live = a.alive ? "●" : "✗";
1382
+ const state = ` [${a.alive ? (a.status ?? "unknown") : "unreachable"}${a.pane_id ? ` pane ${a.pane_id}` : ""}]`;
1383
+ return `${live} ${a.name} (${a.model})${ctxStr}${state}${a.purpose ? ` — ${a.purpose}` : ""}`;
1384
+ }).join("\n");
1385
+
1386
+ return {
1387
+ content: [{ type: "text" as const, text: `${agents.length} peer(s) in pool (project ${scopeProject}):\n${lines}${notice}` }],
1388
+ details: { agents, project: scopeProject, scoped: true, widenRequested: widened },
1389
+ };
1390
+ },
1391
+ renderCall(args, theme) {
1392
+ const proj = (args as any).project;
1393
+ const filter = proj ? ` ${proj}` : "";
1394
+ return new Text(
1395
+ theme.fg("toolTitle", theme.bold("coms_list")) + theme.fg("dim", filter),
1396
+ 0, 0,
1397
+ );
1398
+ },
1399
+ renderResult(result, options, theme) {
1400
+ const details = result.details as any;
1401
+ const agents: any[] = details?.agents ?? [];
1402
+ const header = theme.fg("accent", `📡 ${agents.length} peer(s)`);
1403
+ if (!options.expanded || agents.length === 0) {
1404
+ return new Text(header, 0, 0);
1405
+ }
1406
+ const rows = agents.map((a) => {
1407
+ const dot = a.alive ? theme.fg("success", "●") : theme.fg("error", "✗");
1408
+ const pct = a.context_used_pct != null ? `${a.context_used_pct}%` : "?%";
1409
+ const state = a.alive ? (a.status ?? "unknown") : "unreachable";
1410
+ const stateFg = state === "idle" ? "success" : state === "working" ? "warning" : "dim";
1411
+ return `${dot} ${theme.fg("accent", a.name)} ${theme.fg("dim", a.model)} ${theme.fg("warning", pct)} ` +
1412
+ `${theme.fg(stateFg as any, state)}${a.pane_id ? theme.fg("dim", ` ${a.pane_id}`) : ""}`;
1413
+ }).join("\n");
1414
+ return new Text(header + "\n" + rows, 0, 0);
1415
+ },
1416
+ });
1417
+
1418
+ pi.registerTool({
1419
+ name: "coms_send",
1420
+ label: "Coms Send",
1421
+ description:
1422
+ "Send a prompt to a peer agent. Returns synchronously with a msg_id once the receiver acks. " +
1423
+ "Use coms_get (non-blocking) or coms_await (blocking) with the msg_id to retrieve the response. " +
1424
+ "Throws if the receiver is unreachable or rejects the envelope.",
1425
+ parameters: Type.Object({
1426
+ target: Type.String({ description: "Peer name (preferred) or session_id — must be a peer currently in your coms pool (shown in the widget). Out-of-pool targets are refused; ask the human to widen scope with /af-coms --project or /af-coms --all." }),
1427
+ prompt: Type.String({ description: "The prompt to send." }),
1428
+ conversation_id: Type.Optional(Type.String()),
1429
+ response_schema: Type.Optional(Type.Any({ description: "Optional JSON Schema describing the expected response shape." })),
1430
+ reply_timeout_ms: Type.Optional(Type.Number({ description: "How long you will wait for the reply (ms). Pass the same value you intend to give coms_await: a receiver that drives an interactive agent (e.g. a Claude Code pane) uses this instead of its own default, so long reviews are not cut short. Clamped to 1 hour." })),
1431
+ }),
1432
+ async execute(_callId, params) {
1433
+ if (!identity) {
1434
+ throw new Error("coms not initialised");
1435
+ }
1436
+ const target = resolveTarget(params.target);
1437
+ if (!target) {
1438
+ // Refuse without confirming whether the peer exists outside the pool — that
1439
+ // existence is itself cross-project metadata. Point at the human-controlled
1440
+ // widening path instead.
1441
+ const scope = displayProject ?? identity.project;
1442
+ throw new Error(
1443
+ `coms: no connected peer "${params.target}" in your pool (project ${scope}). ` +
1444
+ `Only peers shown in the coms pool are reachable. If you expected this peer, ask the ` +
1445
+ `human to widen scope with /af-coms --project <name> or /af-coms --all, then retry.`,
1446
+ );
1447
+ }
1448
+ const hops = currentInbound ? currentInbound.hops + 1 : 0;
1449
+ if (hops >= MAX_HOPS) {
1450
+ throw new Error(`coms: hop limit reached (${hops} >= ${MAX_HOPS})`);
1451
+ }
1452
+ const msg_id = ulid();
1453
+ const env: PromptEnvelope = {
1454
+ type: "prompt",
1455
+ msg_id,
1456
+ sender_session: identity.session_id,
1457
+ sender_endpoint: identity.endpoint,
1458
+ sender_name: identity.name,
1459
+ sender_cwd: identity.cwd,
1460
+ hops,
1461
+ timestamp: nowIso(),
1462
+ prompt: params.prompt,
1463
+ conversation_id: params.conversation_id ?? null,
1464
+ response_schema: (params.response_schema as object | undefined) ?? null,
1465
+ reply_timeout_ms: params.reply_timeout_ms ?? null,
1466
+ };
1467
+
1468
+ // Send the envelope synchronously and wait for the receiver's ack.
1469
+ await sendEnvelope(target.endpoint, env);
1470
+
1471
+ // Register a pending entry whose promise the receiver-side handleResponse
1472
+ // (or the timeout below) will settle.
1473
+ let resolveFn!: (v: { response?: any; error?: string | null }) => void;
1474
+ let rejectFn!: (e: Error) => void;
1475
+ const promise = new Promise<{ response?: any; error?: string | null }>((res, rej) => {
1476
+ resolveFn = res;
1477
+ rejectFn = rej;
1478
+ });
1479
+ const entry: PendingReply = {
1480
+ resolve: resolveFn,
1481
+ reject: rejectFn,
1482
+ timer: null,
1483
+ promise,
1484
+ target_name: target.name,
1485
+ created_at: nowIso(),
1486
+ };
1487
+ // A local wait deadline does not convert unfinished remote work into an
1488
+ // error. Keep the entry pending so a later await can collect the response.
1489
+ pendingReplies.set(msg_id, entry);
1490
+
1491
+ try {
1492
+ pi.appendEntry("coms-log", {
1493
+ event: "outbound_prompt",
1494
+ msg_id,
1495
+ target: target.name,
1496
+ hops,
1497
+ });
1498
+ } catch {
1499
+ // best-effort
1500
+ }
1501
+
1502
+ return {
1503
+ content: [{ type: "text" as const, text: `coms_send → ${target.name}\nmsg_id ${msg_id}\nhops ${hops}` }],
1504
+ details: { msg_id, target: target.name, target_session: target.session_id, hops },
1505
+ };
1506
+ },
1507
+ renderCall(args, theme) {
1508
+ const tgt = (args as any).target ?? "?";
1509
+ const prompt = (args as any).prompt ?? "";
1510
+ const preview = prompt.length > 60 ? prompt.slice(0, 57) + "..." : prompt;
1511
+ return new Text(
1512
+ theme.fg("toolTitle", theme.bold("coms_send ")) +
1513
+ theme.fg("accent", tgt) +
1514
+ theme.fg("dim", " — ") +
1515
+ theme.fg("muted", preview),
1516
+ 0, 0,
1517
+ );
1518
+ },
1519
+ renderResult(result, _options, theme) {
1520
+ const d = result.details as any;
1521
+ if (!d) {
1522
+ const t = result.content[0];
1523
+ return new Text(t?.type === "text" ? t.text : "", 0, 0);
1524
+ }
1525
+ return new Text(
1526
+ theme.fg("success", "→ ") +
1527
+ theme.fg("accent", d.target) +
1528
+ theme.fg("dim", ` msg_id `) +
1529
+ theme.fg("warning", d.msg_id),
1530
+ 0, 0,
1531
+ );
1532
+ },
1533
+ });
1534
+
1535
+ pi.registerTool({
1536
+ name: "coms_get",
1537
+ label: "Coms Get",
1538
+ description:
1539
+ "Non-blocking poll of a pending coms_send reply. Returns status pending|complete|error and (when complete) the response.",
1540
+ parameters: Type.Object({
1541
+ msg_id: Type.String({ description: "msg_id returned by coms_send." }),
1542
+ }),
1543
+ async execute(_callId, params) {
1544
+ const entry = pendingReplies.get(params.msg_id);
1545
+ if (!entry) {
1546
+ return {
1547
+ content: [{ type: "text" as const, text: `coms_get: unknown msg_id ${params.msg_id}` }],
1548
+ details: { status: "error", error: "unknown msg_id" },
1549
+ };
1550
+ }
1551
+ if (entry.result) {
1552
+ const r = entry.result;
1553
+ const text = r.error
1554
+ ? `coms_get: error — ${r.error}`
1555
+ : `coms_get: complete\n${typeof r.response === "string" ? r.response : JSON.stringify(r.response, null, 2)}`;
1556
+ return {
1557
+ content: [{ type: "text" as const, text }],
1558
+ details: { status: "complete", response: r.response, error: r.error ?? null },
1559
+ };
1560
+ }
1561
+ return {
1562
+ content: [{ type: "text" as const, text: `coms_get: pending` }],
1563
+ details: { status: "pending" },
1564
+ };
1565
+ },
1566
+ renderCall(args, theme) {
1567
+ const id = (args as any).msg_id ?? "?";
1568
+ return new Text(
1569
+ theme.fg("toolTitle", theme.bold("coms_get ")) + theme.fg("warning", id),
1570
+ 0, 0,
1571
+ );
1572
+ },
1573
+ renderResult(result, _options, theme) {
1574
+ const d = result.details as any;
1575
+ const status = d?.status ?? "?";
1576
+ const color = status === "complete" ? "success" : status === "pending" ? "warning" : "error";
1577
+ return new Text(theme.fg(color, status), 0, 0);
1578
+ },
1579
+ });
1580
+
1581
+ pi.registerTool({
1582
+ name: "coms_await",
1583
+ label: "Coms Await",
1584
+ description:
1585
+ "Block until a pending coms_send reply lands or the timeout fires. Default timeout 30 minutes (PI_COMS_TIMEOUT_MS).",
1586
+ parameters: Type.Object({
1587
+ msg_id: Type.String({ description: "msg_id returned by coms_send." }),
1588
+ timeout_ms: Type.Optional(Type.Number({ description: "Override the default timeout (ms)." })),
1589
+ }),
1590
+ async execute(_callId, params) {
1591
+ const entry = pendingReplies.get(params.msg_id);
1592
+ if (!entry) {
1593
+ return {
1594
+ content: [{ type: "text" as const, text: `coms_await: unknown msg_id ${params.msg_id}` }],
1595
+ details: { error: "unknown msg_id" },
1596
+ };
1597
+ }
1598
+ const timeoutMs = typeof params.timeout_ms === "number" && params.timeout_ms > 0
1599
+ ? params.timeout_ms
1600
+ : TIMEOUT_MS;
1601
+
1602
+ const timed = new Promise<{ error: string }>((resolve) => {
1603
+ const t = setTimeout(() => resolve({ error: "timeout" }), timeoutMs);
1604
+ try { (t as any).unref?.(); } catch { /* ignore */ }
1605
+ });
1606
+
1607
+ const winner = await Promise.race([entry.promise, timed]);
1608
+ if ((winner as any).error === "timeout") {
1609
+ return {
1610
+ content: [{ type: "text" as const, text: "coms_await: pending — wait budget exhausted; the peer may still complete" }],
1611
+ details: { status: "pending" },
1612
+ };
1613
+ }
1614
+ if ((winner as any).error) {
1615
+ return {
1616
+ content: [{ type: "text" as const, text: `coms_await: error — ${(winner as any).error}` }],
1617
+ details: { status: "error", error: (winner as any).error },
1618
+ };
1619
+ }
1620
+ const resp = (winner as any).response;
1621
+ return {
1622
+ content: [{ type: "text" as const, text: typeof resp === "string" ? resp : JSON.stringify(resp, null, 2) }],
1623
+ details: { response: resp },
1624
+ };
1625
+ },
1626
+ renderCall(args, theme) {
1627
+ const id = (args as any).msg_id ?? "?";
1628
+ return new Text(
1629
+ theme.fg("toolTitle", theme.bold("coms_await ")) + theme.fg("warning", id),
1630
+ 0, 0,
1631
+ );
1632
+ },
1633
+ renderResult(result, _options, theme) {
1634
+ const d = result.details as any;
1635
+ if (d?.error) return new Text(theme.fg("error", `✗ ${d.error}`), 0, 0);
1636
+ if (d?.status === "pending") return new Text(theme.fg("warning", "⏳ pending"), 0, 0);
1637
+ return new Text(theme.fg("success", "✓ response received"), 0, 0);
1638
+ },
1639
+ });
1640
+
1641
+ // ━━ agent_end: capture turn output and dispatch response back ━━━━━━━━
1642
+
1643
+ pi.on("agent_end", async (_event, ctx) => {
1644
+ const inbound = [...inboundQueue.values()].reverse().find((i) => !i.fulfilled);
1645
+ if (!inbound || !identity) return;
1646
+
1647
+ // Walk the session branch for the most recent assistant message text.
1648
+ let lastAssistantText = "";
1649
+ for (const entry of ctx.sessionManager.getBranch()) {
1650
+ if (entry.type === "message" && entry.message.role === "assistant") {
1651
+ const m = entry.message as any;
1652
+ if (typeof m.content === "string") {
1653
+ lastAssistantText = m.content;
1654
+ } else if (Array.isArray(m.content)) {
1655
+ lastAssistantText = m.content
1656
+ .filter((b: any) => b && b.type === "text")
1657
+ .map((b: any) => b.text)
1658
+ .join("\n");
1659
+ }
1660
+ }
1661
+ }
1662
+
1663
+ let payload: any = lastAssistantText;
1664
+ let error: string | null = null;
1665
+ if (inbound.response_schema && typeof inbound.response_schema === "object") {
1666
+ try {
1667
+ payload = JSON.parse(lastAssistantText);
1668
+ } catch {
1669
+ error = "response not valid JSON";
1670
+ payload = null;
1671
+ }
1672
+ }
1673
+
1674
+ const respEnv: ResponseEnvelope = {
1675
+ type: "response",
1676
+ msg_id: inbound.msg_id,
1677
+ sender_session: identity.session_id,
1678
+ sender_endpoint: identity.endpoint,
1679
+ hops: 0,
1680
+ timestamp: nowIso(),
1681
+ response: payload,
1682
+ error,
1683
+ };
1684
+
1685
+ try {
1686
+ await sendEnvelope(inbound.sender_endpoint, respEnv);
1687
+ try {
1688
+ pi.appendEntry("coms-log", {
1689
+ event: "outbound_response",
1690
+ msg_id: inbound.msg_id,
1691
+ error,
1692
+ });
1693
+ } catch {
1694
+ // best-effort
1695
+ }
1696
+ } catch (e: any) {
1697
+ try {
1698
+ pi.appendEntry("coms-log", {
1699
+ event: "outbound_response_failed",
1700
+ msg_id: inbound.msg_id,
1701
+ reason: e?.message ?? String(e),
1702
+ });
1703
+ } catch {
1704
+ // best-effort
1705
+ }
1706
+ }
1707
+
1708
+ inbound.fulfilled = true;
1709
+ inboundQueue.delete(inbound.msg_id);
1710
+ if (currentInbound && currentInbound.msg_id === inbound.msg_id) {
1711
+ currentInbound = null;
1712
+ }
1713
+ });
1714
+
1715
+ // ━━ /af-coms slash command ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1716
+ pi.registerCommand("af-coms", {
1717
+ description: "Force-refresh the coms pool widget (or filter with --all / --project <name>)",
1718
+ handler: async (args, ctx) => {
1719
+ const trimmed = (args ?? "").trim();
1720
+ if (trimmed.includes("--all")) {
1721
+ includeExplicit = !includeExplicit;
1722
+ try { ctx.ui.notify(`coms: include_explicit = ${includeExplicit}`, "info"); } catch { /* ignore */ }
1723
+ }
1724
+ const projectMatch = trimmed.match(/--project\s+(\S+)/);
1725
+ if (projectMatch) {
1726
+ displayProject = projectMatch[1];
1727
+ try { ctx.ui.notify(`coms: displaying project ${displayProject}`, "info"); } catch { /* ignore */ }
1728
+ }
1729
+ if (herdrWatch) {
1730
+ await herdrWatch.start(); // re-list + resubscribe + sync cards
1731
+ } else {
1732
+ await refreshPool();
1733
+ }
1734
+ },
1735
+ });
1736
+
1737
+ // ━━ Clean shutdown ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1738
+ let shuttingDown = false;
1739
+ async function cleanShutdown(): Promise<void> {
1740
+ if (shuttingDown) return;
1741
+ shuttingDown = true;
1742
+ if (pingTimer) { try { clearInterval(pingTimer); } catch { /* ignore */ } pingTimer = null; }
1743
+ if (keepaliveTimer) { try { clearInterval(keepaliveTimer); } catch { /* ignore */ } keepaliveTimer = null; }
1744
+ if (herdrWatch) { try { herdrWatch.stop(); } catch { /* ignore */ } herdrWatch = null; }
1745
+ if (herdrPresence) { try { void herdrPresence.release(); } catch { /* ignore */ } herdrPresence = null; }
1746
+ if (server) {
1747
+ try { server.close(); } catch { /* ignore */ }
1748
+ server = null;
1749
+ }
1750
+ if (identity) {
1751
+ if (process.platform !== "win32") {
1752
+ try { fs.unlinkSync(identity.endpoint); } catch { /* ignore */ }
1753
+ }
1754
+ try { removeRegistryEntry(identity.project, identity.name); } catch { /* ignore */ }
1755
+ try {
1756
+ pi.appendEntry("coms-log", { event: "shutdown", session_id: identity.session_id });
1757
+ } catch { /* best-effort */ }
1758
+ }
1759
+ if (currentCtx?.hasUI) {
1760
+ try { currentCtx.ui.setWidget("coms-pool", undefined); } catch { /* ignore */ }
1761
+ }
1762
+ }
1763
+
1764
+ pi.on("session_shutdown", async () => { await cleanShutdown(); });
1765
+ process.on("SIGINT", () => { void cleanShutdown(); });
1766
+ process.on("SIGTERM", () => { void cleanShutdown(); });
1767
+ }