@chankov/agent-fleet 0.0.4 → 0.0.5

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