pi-crew 0.9.53 → 0.9.55

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 (493) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +6 -3
  3. package/scripts/clean-strip-types.mjs +60 -0
  4. package/src/adapters/claude-adapter.ts +23 -0
  5. package/src/adapters/codex-adapter.ts +21 -0
  6. package/src/adapters/cursor-adapter.ts +17 -0
  7. package/src/adapters/export-util.ts +143 -0
  8. package/src/adapters/index.ts +15 -0
  9. package/src/adapters/registry.ts +18 -0
  10. package/src/adapters/types.ts +23 -0
  11. package/src/agents/agent-config.ts +194 -0
  12. package/src/agents/agent-search.ts +98 -0
  13. package/src/agents/agent-serializer.ts +38 -0
  14. package/src/agents/discover-agents.ts +623 -0
  15. package/src/benchmark/benchmark-runner.ts +313 -0
  16. package/src/benchmark/feedback-loop.ts +73 -0
  17. package/src/config/config.ts +1270 -0
  18. package/src/config/defaults.ts +193 -0
  19. package/src/config/drift-detector.ts +290 -0
  20. package/src/config/markers.ts +330 -0
  21. package/src/config/resilient-parser.ts +117 -0
  22. package/src/config/role-tools.ts +118 -0
  23. package/src/config/suggestions.ts +75 -0
  24. package/src/config/types.ts +280 -0
  25. package/src/errors.ts +194 -0
  26. package/src/extension/action-suggestions.ts +117 -0
  27. package/src/extension/async-notifier.ts +179 -0
  28. package/src/extension/autonomous-policy.ts +209 -0
  29. package/src/extension/command-completions.ts +120 -0
  30. package/src/extension/context-status-injection.ts +185 -0
  31. package/src/extension/crew-autocomplete.ts +131 -0
  32. package/src/extension/crew-cleanup.ts +168 -0
  33. package/src/extension/crew-input-router.ts +93 -0
  34. package/src/extension/crew-shortcuts.ts +87 -0
  35. package/src/extension/crew-vibes/cat-frames.ts +18 -0
  36. package/src/extension/crew-vibes/config.ts +195 -0
  37. package/src/extension/crew-vibes/figures.ts +101 -0
  38. package/src/extension/crew-vibes/font-detect.ts +71 -0
  39. package/src/extension/crew-vibes/footer.ts +292 -0
  40. package/src/extension/crew-vibes/index.ts +432 -0
  41. package/src/extension/crew-vibes/provider-usage.ts +396 -0
  42. package/src/extension/crew-vibes/render.ts +206 -0
  43. package/src/extension/crew-vibes/speed.ts +286 -0
  44. package/src/extension/cross-extension-rpc.ts +350 -0
  45. package/src/extension/help.ts +62 -0
  46. package/src/extension/import-index.ts +74 -0
  47. package/src/extension/knowledge-injection.ts +402 -0
  48. package/src/extension/management.ts +571 -0
  49. package/src/extension/message-renderers.ts +108 -0
  50. package/src/extension/notification-router.ts +152 -0
  51. package/src/extension/notification-sink.ts +54 -0
  52. package/src/extension/pi-api.ts +56 -0
  53. package/src/extension/plan-orchestrate.ts +302 -0
  54. package/src/extension/project-init.ts +170 -0
  55. package/src/extension/register.ts +113 -0
  56. package/src/extension/registration/artifact-cleanup.ts +20 -0
  57. package/src/extension/registration/command-registration.ts +58 -0
  58. package/src/extension/registration/command-utils.ts +58 -0
  59. package/src/extension/registration/commands.ts +1228 -0
  60. package/src/extension/registration/compaction-guard.ts +333 -0
  61. package/src/extension/registration/context-builder.ts +135 -0
  62. package/src/extension/registration/crash-recovery-cache.ts +54 -0
  63. package/src/extension/registration/foreground-run-controller.ts +238 -0
  64. package/src/extension/registration/hook-registration.ts +119 -0
  65. package/src/extension/registration/lazy-configurers.ts +124 -0
  66. package/src/extension/registration/lifecycle-handlers.ts +923 -0
  67. package/src/extension/registration/lifecycle.ts +259 -0
  68. package/src/extension/registration/observability.ts +322 -0
  69. package/src/extension/registration/registration-types.ts +158 -0
  70. package/src/extension/registration/runtime-cleanup.ts +230 -0
  71. package/src/extension/registration/subagent-helpers.ts +125 -0
  72. package/src/extension/registration/subagent-manager-setup.ts +330 -0
  73. package/src/extension/registration/subagent-tools.ts +456 -0
  74. package/src/extension/registration/team-tool.ts +225 -0
  75. package/src/extension/registration/tool-registration.ts +50 -0
  76. package/src/extension/registration/ui.ts +172 -0
  77. package/src/extension/registration/viewers.ts +121 -0
  78. package/src/extension/registration/wire-cross-extension.ts +37 -0
  79. package/src/extension/result-watcher.ts +139 -0
  80. package/src/extension/rpc-hmac.ts +256 -0
  81. package/src/extension/run-bundle-schema.ts +104 -0
  82. package/src/extension/run-export.ts +97 -0
  83. package/src/extension/run-import.ts +168 -0
  84. package/src/extension/run-index.ts +131 -0
  85. package/src/extension/run-maintenance.ts +190 -0
  86. package/src/extension/session-summary.ts +18 -0
  87. package/src/extension/team-manager-command.ts +153 -0
  88. package/src/extension/team-onboard.ts +180 -0
  89. package/src/extension/team-recommendation.ts +288 -0
  90. package/src/extension/team-tool/anchor.ts +172 -0
  91. package/src/extension/team-tool/api.ts +1244 -0
  92. package/src/extension/team-tool/auto-summarize.ts +142 -0
  93. package/src/extension/team-tool/cache-control.ts +19 -0
  94. package/src/extension/team-tool/cancel.ts +337 -0
  95. package/src/extension/team-tool/chain-dispatch.ts +95 -0
  96. package/src/extension/team-tool/chain-executor.ts +379 -0
  97. package/src/extension/team-tool/config-patch.ts +50 -0
  98. package/src/extension/team-tool/context.ts +149 -0
  99. package/src/extension/team-tool/destructive-gate.ts +52 -0
  100. package/src/extension/team-tool/dispatch/automate.ts +80 -0
  101. package/src/extension/team-tool/dispatch/control.ts +42 -0
  102. package/src/extension/team-tool/dispatch/index.ts +95 -0
  103. package/src/extension/team-tool/dispatch/manage.ts +161 -0
  104. package/src/extension/team-tool/dispatch/run.ts +53 -0
  105. package/src/extension/team-tool/dispatch/status.ts +187 -0
  106. package/src/extension/team-tool/doctor.ts +431 -0
  107. package/src/extension/team-tool/explain.ts +282 -0
  108. package/src/extension/team-tool/failure-patterns.ts +118 -0
  109. package/src/extension/team-tool/goal-wrap.ts +330 -0
  110. package/src/extension/team-tool/goal.ts +556 -0
  111. package/src/extension/team-tool/handle-schedule.ts +332 -0
  112. package/src/extension/team-tool/handle-settings.ts +520 -0
  113. package/src/extension/team-tool/health-monitor.ts +481 -0
  114. package/src/extension/team-tool/inspect.ts +88 -0
  115. package/src/extension/team-tool/intent-policy.ts +45 -0
  116. package/src/extension/team-tool/lifecycle-actions.ts +615 -0
  117. package/src/extension/team-tool/orchestrate.ts +98 -0
  118. package/src/extension/team-tool/parallel-dispatch.ts +183 -0
  119. package/src/extension/team-tool/plan.ts +50 -0
  120. package/src/extension/team-tool/respond.ts +150 -0
  121. package/src/extension/team-tool/run-deadline.ts +66 -0
  122. package/src/extension/team-tool/run-not-found.ts +49 -0
  123. package/src/extension/team-tool/run.ts +1051 -0
  124. package/src/extension/team-tool/status.ts +260 -0
  125. package/src/extension/team-tool/workflow-manage.ts +261 -0
  126. package/src/extension/team-tool-types.ts +26 -0
  127. package/src/extension/team-tool.ts +750 -0
  128. package/src/extension/tool-result.ts +16 -0
  129. package/src/extension/validate-resources.ts +108 -0
  130. package/src/hooks/registry.ts +200 -0
  131. package/src/hooks/types.ts +69 -0
  132. package/src/i18n.ts +212 -0
  133. package/src/observability/correlation.ts +50 -0
  134. package/src/observability/event-bus.ts +86 -0
  135. package/src/observability/event-to-metric.ts +170 -0
  136. package/src/observability/exporters/adapter.ts +27 -0
  137. package/src/observability/exporters/otlp-exporter.ts +356 -0
  138. package/src/observability/exporters/prometheus-exporter.ts +54 -0
  139. package/src/observability/metric-registry.ts +100 -0
  140. package/src/observability/metric-retention.ts +64 -0
  141. package/src/observability/metric-sink.ts +99 -0
  142. package/src/observability/metrics-primitives.ts +219 -0
  143. package/src/plugins/plugin-define.ts +6 -0
  144. package/src/plugins/plugin-registry.ts +32 -0
  145. package/src/plugins/plugins/index.ts +3 -0
  146. package/src/plugins/plugins/nextjs.ts +19 -0
  147. package/src/plugins/plugins/vite.ts +10 -0
  148. package/src/plugins/plugins/vitest.ts +9 -0
  149. package/src/prompt/prompt-runtime.ts +380 -0
  150. package/src/runtime/adaptive-plan.ts +563 -0
  151. package/src/runtime/agent-control.ts +215 -0
  152. package/src/runtime/agent-memory.ts +81 -0
  153. package/src/runtime/agent-observability.ts +122 -0
  154. package/src/runtime/anchor-manager.ts +475 -0
  155. package/src/runtime/async-marker.ts +32 -0
  156. package/src/runtime/async-runner.ts +381 -0
  157. package/src/runtime/attention-events.ts +28 -0
  158. package/src/runtime/auto-summarize.ts +344 -0
  159. package/src/runtime/background-runner.ts +840 -0
  160. package/src/runtime/batch-barrier.ts +147 -0
  161. package/src/runtime/broker-issuer.ts +39 -0
  162. package/src/runtime/cancellation-token.ts +99 -0
  163. package/src/runtime/cancellation.ts +99 -0
  164. package/src/runtime/capability-inventory.ts +137 -0
  165. package/src/runtime/chain-parser.ts +237 -0
  166. package/src/runtime/chain-runner.ts +606 -0
  167. package/src/runtime/checkpoint.ts +291 -0
  168. package/src/runtime/child-pi-constants.ts +42 -0
  169. package/src/runtime/child-pi-kill.ts +180 -0
  170. package/src/runtime/child-pi-pool.ts +68 -0
  171. package/src/runtime/child-pi-spawn.ts +287 -0
  172. package/src/runtime/child-pi-steering.ts +128 -0
  173. package/src/runtime/child-pi-streams.ts +296 -0
  174. package/src/runtime/child-pi-transcript.ts +169 -0
  175. package/src/runtime/child-pi.ts +1105 -0
  176. package/src/runtime/coalesce-tasks.ts +268 -0
  177. package/src/runtime/code-summary.ts +292 -0
  178. package/src/runtime/command-trace.ts +105 -0
  179. package/src/runtime/compact-pipeline.ts +56 -0
  180. package/src/runtime/compact-stages/ansi-strip-stage.ts +25 -0
  181. package/src/runtime/compact-stages/blank-collapse-stage.ts +31 -0
  182. package/src/runtime/compact-stages/deduplicate-stage.ts +34 -0
  183. package/src/runtime/compact-stages/head-snap-stage.ts +57 -0
  184. package/src/runtime/compact-stages/index.ts +23 -0
  185. package/src/runtime/compact-stages/tail-capture-stage.ts +77 -0
  186. package/src/runtime/compact-stages/truncation-stage.ts +74 -0
  187. package/src/runtime/compaction-summary.ts +278 -0
  188. package/src/runtime/completion-guard.ts +207 -0
  189. package/src/runtime/concurrency.ts +58 -0
  190. package/src/runtime/crash-classification.ts +229 -0
  191. package/src/runtime/crash-recovery.ts +594 -0
  192. package/src/runtime/crew-agent-records.ts +595 -0
  193. package/src/runtime/crew-agent-runtime.ts +62 -0
  194. package/src/runtime/crew-broker-child.ts +88 -0
  195. package/src/runtime/crew-broker-client.ts +673 -0
  196. package/src/runtime/crew-broker-tokens.ts +159 -0
  197. package/src/runtime/crew-broker.ts +1304 -0
  198. package/src/runtime/crew-hooks.ts +227 -0
  199. package/src/runtime/cross-extension-rpc.ts +143 -0
  200. package/src/runtime/custom-tools/irc-tool.ts +282 -0
  201. package/src/runtime/custom-tools/submit-result-tool.ts +102 -0
  202. package/src/runtime/deadletter.ts +47 -0
  203. package/src/runtime/delivery-coordinator.ts +211 -0
  204. package/src/runtime/delta-conflict.ts +348 -0
  205. package/src/runtime/deterministic-ast.ts +161 -0
  206. package/src/runtime/diagnostic-export.ts +171 -0
  207. package/src/runtime/direct-run.ts +45 -0
  208. package/src/runtime/dwf-state-store.ts +102 -0
  209. package/src/runtime/dynamic-workflow-context.ts +1013 -0
  210. package/src/runtime/dynamic-workflow-runner.ts +325 -0
  211. package/src/runtime/effectiveness.ts +90 -0
  212. package/src/runtime/errors/crew-errors.ts +162 -0
  213. package/src/runtime/event-stream-bridge.ts +98 -0
  214. package/src/runtime/foreground-control.ts +193 -0
  215. package/src/runtime/foreground-watchdog.ts +132 -0
  216. package/src/runtime/global-worker-cap.ts +96 -0
  217. package/src/runtime/goal-achievement.ts +148 -0
  218. package/src/runtime/goal-evaluator.ts +365 -0
  219. package/src/runtime/goal-loop-runner.ts +825 -0
  220. package/src/runtime/goal-state-store.ts +219 -0
  221. package/src/runtime/green-contract.ts +55 -0
  222. package/src/runtime/group-join.ts +267 -0
  223. package/src/runtime/handoff-manager.ts +598 -0
  224. package/src/runtime/heartbeat-gradient.ts +36 -0
  225. package/src/runtime/heartbeat-watcher.ts +239 -0
  226. package/src/runtime/hidden-handoff.ts +407 -0
  227. package/src/runtime/important-line-classifier.ts +140 -0
  228. package/src/runtime/intercom-bridge.ts +187 -0
  229. package/src/runtime/iteration-hooks.ts +305 -0
  230. package/src/runtime/live-agent-control.ts +136 -0
  231. package/src/runtime/live-agent-manager.ts +704 -0
  232. package/src/runtime/live-control-realtime.ts +56 -0
  233. package/src/runtime/live-extension-bridge.ts +148 -0
  234. package/src/runtime/live-irc.ts +97 -0
  235. package/src/runtime/live-session-health.ts +108 -0
  236. package/src/runtime/live-session-runtime.ts +1146 -0
  237. package/src/runtime/loop-gates.ts +128 -0
  238. package/src/runtime/manifest-cache.ts +375 -0
  239. package/src/runtime/mcp-proxy.ts +105 -0
  240. package/src/runtime/metric-parser.ts +36 -0
  241. package/src/runtime/model-fallback.ts +409 -0
  242. package/src/runtime/model-resolver.ts +126 -0
  243. package/src/runtime/model-scope.ts +158 -0
  244. package/src/runtime/orphan-worker-registry.ts +465 -0
  245. package/src/runtime/output-validator.ts +202 -0
  246. package/src/runtime/overflow-recovery.ts +206 -0
  247. package/src/runtime/parallel-research.ts +68 -0
  248. package/src/runtime/parallel-utils.ts +160 -0
  249. package/src/runtime/parent-guard.ts +134 -0
  250. package/src/runtime/path-overlap.ts +150 -0
  251. package/src/runtime/peer-dep.ts +292 -0
  252. package/src/runtime/per-write-validator.ts +181 -0
  253. package/src/runtime/phase-progress.ts +217 -0
  254. package/src/runtime/phase-tracker.ts +385 -0
  255. package/src/runtime/pi-args.ts +655 -0
  256. package/src/runtime/pi-json-output.ts +170 -0
  257. package/src/runtime/pi-spawn.ts +273 -0
  258. package/src/runtime/pipeline-runner.ts +523 -0
  259. package/src/runtime/plan-templates.ts +201 -0
  260. package/src/runtime/policy-engine.ts +115 -0
  261. package/src/runtime/post-checks.ts +142 -0
  262. package/src/runtime/post-exit-stdio-guard.ts +109 -0
  263. package/src/runtime/process-lifecycle.ts +491 -0
  264. package/src/runtime/process-status.ts +154 -0
  265. package/src/runtime/progress-event-coalescer.ts +44 -0
  266. package/src/runtime/progress-tracker.ts +124 -0
  267. package/src/runtime/prose-compressor.ts +162 -0
  268. package/src/runtime/recovery-recipes.ts +203 -0
  269. package/src/runtime/replace.ts +570 -0
  270. package/src/runtime/resilient-edit.ts +153 -0
  271. package/src/runtime/result-extractor.ts +217 -0
  272. package/src/runtime/retry-executor.ts +109 -0
  273. package/src/runtime/retry-runner.ts +336 -0
  274. package/src/runtime/role-permission.ts +59 -0
  275. package/src/runtime/run-coalesced-task-group.ts +308 -0
  276. package/src/runtime/run-drift.ts +219 -0
  277. package/src/runtime/run-tracker.ts +116 -0
  278. package/src/runtime/run-worker.ts +78 -0
  279. package/src/runtime/runtime-policy.ts +29 -0
  280. package/src/runtime/runtime-resolver.ts +172 -0
  281. package/src/runtime/runtime-warmup.ts +160 -0
  282. package/src/runtime/scheduler.ts +353 -0
  283. package/src/runtime/semaphore.ts +141 -0
  284. package/src/runtime/sensitive-paths.ts +93 -0
  285. package/src/runtime/session-resources.ts +25 -0
  286. package/src/runtime/session-snapshot.ts +59 -0
  287. package/src/runtime/session-usage.ts +79 -0
  288. package/src/runtime/settings-store.ts +155 -0
  289. package/src/runtime/sidechain-output.ts +35 -0
  290. package/src/runtime/single-agent-compose.ts +84 -0
  291. package/src/runtime/skill-effectiveness.ts +524 -0
  292. package/src/runtime/skill-instructions.ts +394 -0
  293. package/src/runtime/stale-reconciler.ts +680 -0
  294. package/src/runtime/stream-preview.ts +184 -0
  295. package/src/runtime/streaming-output.ts +50 -0
  296. package/src/runtime/subagent-manager.ts +561 -0
  297. package/src/runtime/subprocess-tool-registry.ts +70 -0
  298. package/src/runtime/supervisor-contact.ts +64 -0
  299. package/src/runtime/task-display.ts +52 -0
  300. package/src/runtime/task-graph-scheduler.ts +227 -0
  301. package/src/runtime/task-graph.ts +290 -0
  302. package/src/runtime/task-health.ts +83 -0
  303. package/src/runtime/task-id.ts +161 -0
  304. package/src/runtime/task-output-context.ts +602 -0
  305. package/src/runtime/task-packet.ts +268 -0
  306. package/src/runtime/task-quality.ts +199 -0
  307. package/src/runtime/task-runner/capabilities.ts +78 -0
  308. package/src/runtime/task-runner/child-executor.ts +790 -0
  309. package/src/runtime/task-runner/context-retrieval.ts +163 -0
  310. package/src/runtime/task-runner/live-executor.ts +227 -0
  311. package/src/runtime/task-runner/output-splitter.ts +152 -0
  312. package/src/runtime/task-runner/post-execution.ts +480 -0
  313. package/src/runtime/task-runner/pre-execution.ts +365 -0
  314. package/src/runtime/task-runner/progress.ts +157 -0
  315. package/src/runtime/task-runner/prompt-builder.ts +278 -0
  316. package/src/runtime/task-runner/prompt-pipeline.ts +88 -0
  317. package/src/runtime/task-runner/result-utils.ts +16 -0
  318. package/src/runtime/task-runner/retrieval-orchestrator.ts +310 -0
  319. package/src/runtime/task-runner/run-projection.ts +125 -0
  320. package/src/runtime/task-runner/scaffold-executor.ts +25 -0
  321. package/src/runtime/task-runner/state-helpers.ts +176 -0
  322. package/src/runtime/task-runner/tail-read.ts +34 -0
  323. package/src/runtime/task-runner.ts +216 -0
  324. package/src/runtime/team-runner-artifacts.ts +13 -0
  325. package/src/runtime/team-runner.ts +2396 -0
  326. package/src/runtime/tool-output-pruner.ts +333 -0
  327. package/src/runtime/tool-progress.ts +278 -0
  328. package/src/runtime/usage-tracker.ts +73 -0
  329. package/src/runtime/verification-gates.ts +579 -0
  330. package/src/runtime/verification-integrity.ts +108 -0
  331. package/src/runtime/verification-worktree.ts +186 -0
  332. package/src/runtime/worker-heartbeat.ts +25 -0
  333. package/src/runtime/worker-startup.ts +83 -0
  334. package/src/runtime/workflow-state.ts +195 -0
  335. package/src/runtime/workspace-lock.ts +443 -0
  336. package/src/runtime/workspace-tree.ts +312 -0
  337. package/src/runtime/yield-handler.ts +224 -0
  338. package/src/runtime/zombie-scanner.ts +298 -0
  339. package/src/schema/config-schema.ts +327 -0
  340. package/src/schema/team-tool-schema.ts +492 -0
  341. package/src/schema/validation-types.ts +159 -0
  342. package/src/skills/discover-skills.ts +203 -0
  343. package/src/skills/skill-templates.ts +456 -0
  344. package/src/skills/validate.ts +285 -0
  345. package/src/state/active-run-registry.ts +439 -0
  346. package/src/state/artifact-store.ts +176 -0
  347. package/src/state/atomic-write.ts +970 -0
  348. package/src/state/blob-store.ts +308 -0
  349. package/src/state/contracts.ts +160 -0
  350. package/src/state/crew-init.ts +269 -0
  351. package/src/state/decision-ledger.ts +372 -0
  352. package/src/state/event-log-rotation.ts +399 -0
  353. package/src/state/event-log.ts +1465 -0
  354. package/src/state/event-reconstructor.ts +229 -0
  355. package/src/state/gitignore-manager.ts +46 -0
  356. package/src/state/health-store.ts +79 -0
  357. package/src/state/hook-instinct-bridge.ts +94 -0
  358. package/src/state/hook-integrations.ts +51 -0
  359. package/src/state/instinct-store.ts +275 -0
  360. package/src/state/jsonl-writer.ts +107 -0
  361. package/src/state/locks.ts +562 -0
  362. package/src/state/mailbox.ts +916 -0
  363. package/src/state/observation-store.ts +176 -0
  364. package/src/state/run-cache.ts +193 -0
  365. package/src/state/run-graph.ts +183 -0
  366. package/src/state/run-metrics.ts +165 -0
  367. package/src/state/schedule.ts +166 -0
  368. package/src/state/session-state-map.ts +51 -0
  369. package/src/state/state-store.ts +973 -0
  370. package/src/state/task-claims.ts +61 -0
  371. package/src/state/tiered-eval.ts +480 -0
  372. package/src/state/types-eval.ts +58 -0
  373. package/src/state/types.ts +447 -0
  374. package/src/state/usage.ts +138 -0
  375. package/src/state/worker-atomic-writer.ts +198 -0
  376. package/src/subagents/async-entry.ts +1 -0
  377. package/src/subagents/index.ts +3 -0
  378. package/src/subagents/live/control.ts +1 -0
  379. package/src/subagents/live/manager.ts +1 -0
  380. package/src/subagents/live/realtime.ts +1 -0
  381. package/src/subagents/live/session-runtime.ts +1 -0
  382. package/src/subagents/manager.ts +1 -0
  383. package/src/subagents/spawn.ts +1 -0
  384. package/src/teams/discover-teams.ts +187 -0
  385. package/src/teams/team-config.ts +27 -0
  386. package/src/teams/team-serializer.ts +38 -0
  387. package/src/tools/safe-bash-extension.ts +54 -0
  388. package/src/tools/safe-bash.ts +505 -0
  389. package/src/types/diff.d.ts +18 -0
  390. package/src/types/new-api-types.ts +35 -0
  391. package/src/ui/agent-management-overlay.ts +160 -0
  392. package/src/ui/card-colors.ts +139 -0
  393. package/src/ui/crew-footer.ts +102 -0
  394. package/src/ui/crew-select-list.ts +112 -0
  395. package/src/ui/dashboard-panes/agents-pane.ts +164 -0
  396. package/src/ui/dashboard-panes/cancellation-pane.ts +66 -0
  397. package/src/ui/dashboard-panes/capability-pane.ts +77 -0
  398. package/src/ui/dashboard-panes/health-pane.ts +31 -0
  399. package/src/ui/dashboard-panes/mailbox-pane.ts +35 -0
  400. package/src/ui/dashboard-panes/metrics-pane.ts +37 -0
  401. package/src/ui/dashboard-panes/progress-pane.ts +38 -0
  402. package/src/ui/dashboard-panes/transcript-pane.ts +10 -0
  403. package/src/ui/deploy-bundled-themes.ts +71 -0
  404. package/src/ui/dwf-phase-display.ts +151 -0
  405. package/src/ui/dynamic-border.ts +35 -0
  406. package/src/ui/format-helpers.ts +31 -0
  407. package/src/ui/heartbeat-aggregator.ts +74 -0
  408. package/src/ui/key-utils.ts +42 -0
  409. package/src/ui/keybinding-map.ts +248 -0
  410. package/src/ui/layout-primitives.ts +106 -0
  411. package/src/ui/live-conversation-overlay.ts +183 -0
  412. package/src/ui/live-duration.ts +55 -0
  413. package/src/ui/live-run-sidebar.ts +293 -0
  414. package/src/ui/loaders.ts +6 -0
  415. package/src/ui/mascot.ts +449 -0
  416. package/src/ui/overlays/agent-picker-overlay.ts +66 -0
  417. package/src/ui/overlays/confirm-overlay.ts +60 -0
  418. package/src/ui/overlays/help-overlay.ts +177 -0
  419. package/src/ui/overlays/mailbox-compose-overlay.ts +181 -0
  420. package/src/ui/overlays/mailbox-compose-preview.ts +78 -0
  421. package/src/ui/overlays/mailbox-detail-overlay.ts +155 -0
  422. package/src/ui/pi-ui-compat.ts +68 -0
  423. package/src/ui/powerbar-publisher.ts +459 -0
  424. package/src/ui/render-coalescer.ts +101 -0
  425. package/src/ui/render-diff.ts +160 -0
  426. package/src/ui/render-scheduler.ts +278 -0
  427. package/src/ui/run-action-dispatcher.ts +182 -0
  428. package/src/ui/run-dashboard.ts +910 -0
  429. package/src/ui/run-event-bus.ts +381 -0
  430. package/src/ui/run-snapshot-cache.ts +1057 -0
  431. package/src/ui/settings-overlay.ts +1067 -0
  432. package/src/ui/shared-overlay-scheduler.ts +96 -0
  433. package/src/ui/snapshot-types.ts +90 -0
  434. package/src/ui/spinner.ts +17 -0
  435. package/src/ui/status-colors.ts +143 -0
  436. package/src/ui/syntax-highlight.ts +136 -0
  437. package/src/ui/terminal-status.ts +269 -0
  438. package/src/ui/theme-adapter.ts +271 -0
  439. package/src/ui/theme-discovery.ts +199 -0
  440. package/src/ui/tool-progress-formatter.ts +93 -0
  441. package/src/ui/tool-renderers/brief-mode.ts +225 -0
  442. package/src/ui/tool-renderers/index.ts +726 -0
  443. package/src/ui/transcript-cache.ts +128 -0
  444. package/src/ui/transcript-entries.ts +256 -0
  445. package/src/ui/transcript-viewer.ts +424 -0
  446. package/src/ui/widget/index.ts +418 -0
  447. package/src/ui/widget/widget-formatters.ts +182 -0
  448. package/src/ui/widget/widget-model.ts +110 -0
  449. package/src/ui/widget/widget-renderer.ts +182 -0
  450. package/src/ui/widget/widget-types.ts +36 -0
  451. package/src/utils/bm25-search.ts +235 -0
  452. package/src/utils/completion-dedupe.ts +63 -0
  453. package/src/utils/conflict-detect.ts +668 -0
  454. package/src/utils/env-allowlist.ts +30 -0
  455. package/src/utils/env-filter.ts +155 -0
  456. package/src/utils/file-coalescer.ts +98 -0
  457. package/src/utils/fingerprint.ts +180 -0
  458. package/src/utils/frontmatter.ts +70 -0
  459. package/src/utils/fs-watch.ts +37 -0
  460. package/src/utils/gh-protocol.ts +556 -0
  461. package/src/utils/git.ts +260 -0
  462. package/src/utils/guards.ts +107 -0
  463. package/src/utils/ids.ts +24 -0
  464. package/src/utils/incremental-reader.ts +220 -0
  465. package/src/utils/internal-error.ts +10 -0
  466. package/src/utils/names.ts +36 -0
  467. package/src/utils/ndjson.ts +115 -0
  468. package/src/utils/paths.ts +227 -0
  469. package/src/utils/project-detector.ts +160 -0
  470. package/src/utils/redaction.ts +370 -0
  471. package/src/utils/resolve-shell.ts +36 -0
  472. package/src/utils/run-watcher-registry.ts +152 -0
  473. package/src/utils/safe-paths.ts +393 -0
  474. package/src/utils/scan-cache.ts +144 -0
  475. package/src/utils/session-utils.ts +110 -0
  476. package/src/utils/sleep.ts +54 -0
  477. package/src/utils/socket-path.ts +164 -0
  478. package/src/utils/sse-parser.ts +131 -0
  479. package/src/utils/task-name-generator.ts +337 -0
  480. package/src/utils/timings.ts +33 -0
  481. package/src/utils/token-counter.ts +200 -0
  482. package/src/utils/visual.ts +207 -0
  483. package/src/workflows/cost-estimator.ts +34 -0
  484. package/src/workflows/discover-workflows.ts +308 -0
  485. package/src/workflows/intermediate-store.ts +166 -0
  486. package/src/workflows/preflight-validator.ts +168 -0
  487. package/src/workflows/topology-analyzer.ts +203 -0
  488. package/src/workflows/validate-workflow.ts +50 -0
  489. package/src/workflows/workflow-config.ts +75 -0
  490. package/src/workflows/workflow-serializer.ts +32 -0
  491. package/src/worktree/branch-freshness.ts +112 -0
  492. package/src/worktree/cleanup.ts +341 -0
  493. package/src/worktree/worktree-manager.ts +1204 -0
@@ -0,0 +1,1304 @@
1
+ /**
2
+ * crew-broker.ts — Root-only local socket server for cross-process pi-worker
3
+ * message transport. PHASE 0 skeleton (sub-task 0.4).
4
+ *
5
+ * - Bound to a `node:net` Unix domain socket or Windows named pipe.
6
+ * - One broker per root session; per-run token auth on first `hello`.
7
+ * - NDJSON framing, 256 KiB UTF-8 cap, 1s hello deadline.
8
+ * - Per-connection outbound queue cap (default 256) with drop-newest +
9
+ * `needsResync` marker.
10
+ * - Phase 0 dispatches ONLY `hello` and `ping`. All other methods return
11
+ * a typed `not-implemented` response (preserves forward-compat without
12
+ * pretending Phase 1 methods are live).
13
+ * - Token map is HEAP ONLY; cleared on `stop()`. Never serialized.
14
+ * - `stop()` is idempotent. Never calls `process.kill`.
15
+ * - All log/error scopes use `crew-broker.*` prefix; every diagnostic
16
+ * passes through `redactSecretString` from `src/utils/redaction.ts`.
17
+ *
18
+ * NO outbound TCP. NO persistence. NO children. NO process killing.
19
+ *
20
+ * See `reports/inter-pi-broker-impl-plan-2026-07-21.md` §"0.4" for the
21
+ * full contract and acceptance criteria.
22
+ */
23
+
24
+ import * as fsp from "node:fs/promises";
25
+ import * as net from "node:net";
26
+
27
+ import { readEventsCursor } from "../state/event-log.ts";
28
+ import {
29
+ appendMailboxMessageAsync,
30
+ type MailboxMessage,
31
+ type MailboxMessageKind,
32
+ type MailboxMessagePriority,
33
+ readMailbox,
34
+ registerMailboxAppendObserver,
35
+ } from "../state/mailbox.ts";
36
+ import { loadRunManifestById } from "../state/state-store.ts";
37
+ import { runEventBus } from "../ui/run-event-bus.ts";
38
+ import { logInternalError } from "../utils/internal-error.ts";
39
+ import { BrokerError, encodeBrokerFrame, MAX_BROKER_FRAME_BYTES, NdjsonDecoder } from "../utils/ndjson.ts";
40
+ import { redactSecretString } from "../utils/redaction.ts";
41
+ import { resolveRealContainedPath } from "../utils/safe-paths.ts";
42
+ import { getBrokerSocketPath, prepareBrokerSocketDir, removeStaleBrokerSocket } from "../utils/socket-path.ts";
43
+ import { BrokerTokenRegistry } from "./crew-broker-tokens.ts";
44
+
45
+ /** Protocol version negotiated at `hello` time. Bump on breaking change. */
46
+ const BROKER_PROTOCOL = 1;
47
+
48
+ /** Hard hello deadline (per spec). After 1s, the connection is closed with a
49
+ * generic auth/protocol code. */
50
+ const HELLO_DEADLINE_MS = 1_000;
51
+
52
+ /** Default per-connection outbound queue cap (events). */
53
+ const DEFAULT_OUTBOUND_QUEUE_CAP = 256;
54
+
55
+ export interface CrewBrokerOptions {
56
+ /** Root session ID used to derive the socket path. */
57
+ sessionId: string;
58
+ /** Pre-resolved socket path (skips re-derivation; useful for tests). */
59
+ socketPath?: string;
60
+ /** Frame cap in UTF-8 bytes. Default 256 KiB. */
61
+ maxFrameBytes?: number;
62
+ /** Per-connection outbound queue cap. Default 256. */
63
+ outboundQueueCap?: number;
64
+ /** Required: when false, start() is a no-op and the server never binds.
65
+ * Lets the lifecycle controller install the broker unconditionally and
66
+ * have a single kill switch. */
67
+ enabled: boolean;
68
+ /** CWD for `loadRunManifestById` (Phase 1 msg.send / msg.inbox resolution).
69
+ * When omitted, manifest-touching methods return no-manifest errors. */
70
+ cwd?: string;
71
+ /** Optional test seam: override the `net` module (allows fake-server tests). */
72
+ netModule?: typeof net;
73
+ }
74
+
75
+ /** Per-connection server-side state. */
76
+ interface ServerConnection {
77
+ socket: net.Socket;
78
+ decoder: NdjsonDecoder;
79
+ /** Whether the connection has completed `hello` successfully. */
80
+ authed: boolean;
81
+ /** Run id bound by hello. */
82
+ runId?: string;
83
+ /** Task id bound by hello. */
84
+ taskId?: string;
85
+ /** Role bound by hello: orchestrator can steer/msg-send; workers default. */
86
+ role?: "orchestrator" | "worker";
87
+ /** Outbound queue of encoded frames awaiting drain. */
88
+ outbound: Buffer[];
89
+ /** Set when the queue has hit the cap and a frame was dropped. */
90
+ needsResync: boolean;
91
+ /** Set when the connection is closing (idempotent). */
92
+ closed: boolean;
93
+ /** Timer for the hello deadline. */
94
+ helloTimer: NodeJS.Timeout | null;
95
+ /** Monotonic seq counter for outbound events (diagnostic). */
96
+ outboundSeq: number;
97
+ }
98
+
99
+ export class CrewBroker {
100
+ private readonly options: Required<Pick<CrewBrokerOptions, "sessionId" | "enabled">> &
101
+ Pick<CrewBrokerOptions, "socketPath" | "maxFrameBytes" | "outboundQueueCap" | "cwd" | "netModule">;
102
+ private readonly tokens = new BrokerTokenRegistry();
103
+ private server: net.Server | null = null;
104
+ private resolvedSocketPath: string | null = null;
105
+ private stopped = false;
106
+ private starting = false;
107
+ private startingPromise: Promise<void> | null = null;
108
+ private readonly connections = new Set<ServerConnection>();
109
+ /** Connections indexed by runId for live message fanout (Phase 1.3). */
110
+ private readonly connectionsByRun = new Map<string, Set<ServerConnection>>();
111
+ /** Per-connection event subscription unsubscribers (Phase 2: events.subscribe). */
112
+ private readonly subscriptionUnsubs = new WeakMap<ServerConnection, Set<() => void>>();
113
+ /** Unsubscribe handle for the mailbox append observer (set on start, cleared on stop). */
114
+ private mailboxObserverUnsub: (() => void) | null = null;
115
+ /** A single observable handshake counter (test/observability). */
116
+ private handshakeCount = 0;
117
+
118
+ constructor(options: CrewBrokerOptions) {
119
+ if (!options || typeof options !== "object") {
120
+ throw new Error("CrewBroker: options is required");
121
+ }
122
+ if (typeof options.sessionId !== "string" || options.sessionId.length === 0) {
123
+ throw new Error("CrewBroker: sessionId must be a non-empty string");
124
+ }
125
+ this.options = {
126
+ sessionId: options.sessionId,
127
+ enabled: options.enabled === true,
128
+ socketPath: options.socketPath,
129
+ maxFrameBytes: options.maxFrameBytes,
130
+ outboundQueueCap: options.outboundQueueCap,
131
+ cwd: options.cwd,
132
+ netModule: options.netModule,
133
+ };
134
+ }
135
+
136
+ /** Read the resolved socket path. Available after start() resolves. */
137
+ get socketPath(): string {
138
+ return this.resolvedSocketPath ?? this.options.socketPath ?? getBrokerSocketPath(this.options.sessionId);
139
+ }
140
+
141
+ /** Diagnostic: number of connections currently registered. */
142
+ get connectionCount(): number {
143
+ return this.connections.size;
144
+ }
145
+
146
+ /** Diagnostic: number of completed handshakes since start(). */
147
+ get handshakes(): number {
148
+ return this.handshakeCount;
149
+ }
150
+
151
+ /** Diagnostic: number of registered tokens. */
152
+ get tokenCount(): number {
153
+ return this.tokens.size;
154
+ }
155
+
156
+ /** Issue a fresh token for `runId` (+optional `taskId` for per-task
157
+ * isolation). The token is stored in the heap-only registry and is the
158
+ * only way a child can complete `hello`. Never log the return value;
159
+ * never write it to disk. taskId is optional — when absent, the legacy
160
+ * per-run token model applies. */
161
+ issueRunToken(runId: string, taskId?: string): string {
162
+ if (typeof runId !== "string" || runId.length === 0) {
163
+ throw new Error("CrewBroker.issueRunToken: runId must be a non-empty string");
164
+ }
165
+ return this.tokens.issue(runId, taskId);
166
+ }
167
+
168
+ /** Issue the orchestrator token for `runId` (F-06). Cryptographically
169
+ * distinct from every per-task token — the ONLY token that grants
170
+ * role:'orchestrator' (required for steer.push / msg.send). */
171
+ issueOrchestratorToken(runId: string): string {
172
+ if (typeof runId !== "string" || runId.length === 0) {
173
+ throw new Error("CrewBroker.issueOrchestratorToken: runId must be a non-empty string");
174
+ }
175
+ return this.tokens.issueOrchestratorToken(runId);
176
+ }
177
+
178
+ /** Start the broker. Idempotent (subsequent calls return the same promise).
179
+ * When `enabled=false`, this is a no-op and no socket is created. */
180
+ start(): Promise<void> {
181
+ if (!this.options.enabled) {
182
+ // Disabled path: ensure the server is NOT bound. This is the
183
+ // disabled-path proof — no socket created, no listener installed.
184
+ logInternalError("crew-broker.start.disabled", new Error("broker disabled"), `sessionId=${this.options.sessionId}`);
185
+ return Promise.resolve();
186
+ }
187
+ if (this.server) return Promise.resolve();
188
+ if (this.startingPromise) return this.startingPromise;
189
+ this.starting = true;
190
+ this.startingPromise = this.doStart()
191
+ .then(() => {
192
+ this.starting = false;
193
+ })
194
+ .catch((err) => {
195
+ this.starting = false;
196
+ this.startingPromise = null;
197
+ throw err;
198
+ });
199
+ return this.startingPromise;
200
+ }
201
+
202
+ private async doStart(): Promise<void> {
203
+ // 1. Resolve socket path.
204
+ const sockPath = this.options.socketPath ?? getBrokerSocketPath(this.options.sessionId);
205
+ this.resolvedSocketPath = sockPath;
206
+
207
+ // 2. Ensure parent directory exists (mode 0700 on POSIX).
208
+ await prepareBrokerSocketDir(sockPath);
209
+
210
+ // 3. Connect-then-unlink any stale endpoint. A live listener MUST NOT
211
+ // be replaced (we let EADDRINUSE surface on bind).
212
+ const staleResult = await removeStaleBrokerSocket(sockPath);
213
+ if (staleResult === "refused") {
214
+ // Symlink — refuse to proceed.
215
+ throw new BrokerError("protocol", `refusing to follow symlinked broker socket: ${sockPath}`);
216
+ }
217
+
218
+ // 4. Bind the server. allowHalfOpen:false so the other side's FIN is
219
+ // the only end-of-stream signal; we won't keep reading from a
220
+ // half-closed socket.
221
+ const netModule = this.options.netModule ?? net;
222
+ const server = netModule.createServer({ allowHalfOpen: false }, (sock) => {
223
+ this.handleConnection(sock).catch((err) => {
224
+ logInternalError(
225
+ "crew-broker.connection.crashed",
226
+ err instanceof Error ? err : new Error(String(err)),
227
+ `sessionId=${this.options.sessionId}`,
228
+ );
229
+ });
230
+ });
231
+
232
+ await new Promise<void>((resolve, reject) => {
233
+ const onError = (err: Error) => {
234
+ server.removeListener("listening", onListening);
235
+ reject(err);
236
+ };
237
+ const onListening = () => {
238
+ server.removeListener("error", onError);
239
+ resolve();
240
+ };
241
+ server.once("error", onError);
242
+ server.once("listening", onListening);
243
+ try {
244
+ server.listen(sockPath);
245
+ } catch (err) {
246
+ server.removeListener("error", onError);
247
+ server.removeListener("listening", onListening);
248
+ reject(err as Error);
249
+ }
250
+ });
251
+
252
+ // 5. Tighten socket permissions on POSIX. Node's net module has no
253
+ // `mode` option (unlike `fs`), so we chmod after listen() succeeds.
254
+ if (process.platform !== "win32") {
255
+ try {
256
+ await fsp.chmod(sockPath, 0o600);
257
+ } catch (err) {
258
+ // chmod may fail on filesystems that don't support it; log and
259
+ // continue — the directory mode (0700) is the outer defense.
260
+ logInternalError(
261
+ "crew-broker.start.chmod-failed",
262
+ err instanceof Error ? err : new Error(String(err)),
263
+ `path=${redactSecretString(sockPath)}`,
264
+ );
265
+ }
266
+ }
267
+
268
+ this.server = server;
269
+ // Phase 1.3: register the mailbox append observer for live fanout.
270
+ // When a durable mailbox append completes, push the message to any
271
+ // connected recipient for that run. Best-effort — never blocks the
272
+ // append path (the notifier uses queueMicrotask internally).
273
+ this.mailboxObserverUnsub = registerMailboxAppendObserver((msg) => {
274
+ this.fanoutMailboxMessage(msg);
275
+ });
276
+ // Server-level safety net: any uncaught server error must not crash
277
+ // the parent. We log and let the close handler clean up.
278
+ server.on("error", (err) => {
279
+ logInternalError(
280
+ "crew-broker.server.error",
281
+ err instanceof Error ? err : new Error(String(err)),
282
+ `sessionId=${this.options.sessionId}`,
283
+ );
284
+ });
285
+ }
286
+
287
+ /** Stop the broker. Idempotent. Closes every active connection, unlinks
288
+ * ONLY the recorded socket path (never `process.kill`), and clears the
289
+ * token registry. Safe to call twice. */
290
+ async stop(): Promise<void> {
291
+ if (this.stopped) return;
292
+ this.stopped = true;
293
+ // Phase 1.3: unregister the mailbox observer before closing connections.
294
+ if (this.mailboxObserverUnsub) {
295
+ try {
296
+ this.mailboxObserverUnsub();
297
+ } catch {
298
+ /* ignore */
299
+ }
300
+ this.mailboxObserverUnsub = null;
301
+ }
302
+
303
+ // 1. Close all live connections. We don't surface errors here — stop()
304
+ // must be idempotent and never throw on individual connection faults.
305
+ for (const conn of [...this.connections]) {
306
+ try {
307
+ conn.closed = true;
308
+ if (conn.helloTimer) {
309
+ clearTimeout(conn.helloTimer);
310
+ conn.helloTimer = null;
311
+ }
312
+ conn.socket.end();
313
+ // Give Node a tick to flush; destroy after a short grace if not.
314
+ setTimeout(() => {
315
+ try {
316
+ conn.socket.destroy();
317
+ } catch {
318
+ /* ignore */
319
+ }
320
+ }, 50).unref();
321
+ } catch (err) {
322
+ logInternalError(
323
+ "crew-broker.stop.close-conn-failed",
324
+ err instanceof Error ? err : new Error(String(err)),
325
+ `sessionId=${this.options.sessionId}`,
326
+ );
327
+ }
328
+ }
329
+ this.connections.clear();
330
+
331
+ // 2. Close the server itself.
332
+ if (this.server) {
333
+ await new Promise<void>((resolve) => {
334
+ const srv = this.server;
335
+ if (!srv) return resolve();
336
+ srv.close(() => resolve());
337
+ // If the server is not currently listening, close() resolves
338
+ // synchronously — guard with a hard timeout for safety.
339
+ setTimeout(() => resolve(), 250).unref();
340
+ });
341
+ this.server = null;
342
+ }
343
+
344
+ // 3. Clear the token map. This is the single point where the heap
345
+ // state for runIds is wiped. No persistence to clean up.
346
+ this.tokens.clear();
347
+
348
+ // 4. Unlink the recorded socket file IF we created it. We never
349
+ // touch any other path. We also never `process.kill` anything.
350
+ const sockPath = this.resolvedSocketPath ?? this.options.socketPath;
351
+ if (sockPath && process.platform !== "win32") {
352
+ try {
353
+ await fsp.unlink(sockPath);
354
+ } catch (err) {
355
+ const code = (err as NodeJS.ErrnoException).code;
356
+ if (code !== "ENOENT") {
357
+ logInternalError(
358
+ "crew-broker.stop.unlink-failed",
359
+ err instanceof Error ? err : new Error(String(err)),
360
+ `path=${redactSecretString(sockPath)}`,
361
+ );
362
+ }
363
+ }
364
+ }
365
+ this.resolvedSocketPath = null;
366
+ }
367
+
368
+ /**
369
+ * Non-throwing enqueue entry point for the post-append mailbox observer
370
+ * (Phase 1) or any other in-process producer. Phase 0 accepts `notifyMessage`
371
+ * as a no-op shape so the lifecycle controller can install a single
372
+ * observer regardless of broker state.
373
+ *
374
+ * Fanout goes ONLY to authenticated connections matching the recipient.
375
+ * Phase 0 keeps this as a typed no-op (`not-implemented` would be
376
+ * inappropriate here — the caller is in-process and shouldn't be
377
+ * punished for testing the broker skeleton).
378
+ */
379
+ notifyMessage(_message: unknown): void {
380
+ // Phase 0: no fanout. Phase 1 replaces this with the single
381
+ // post-durable mailbox observer fanout.
382
+ }
383
+
384
+ // ------------------------------------------------------------------------
385
+ // Connection lifecycle
386
+ // ------------------------------------------------------------------------
387
+
388
+ private async handleConnection(sock: net.Socket): Promise<void> {
389
+ const conn: ServerConnection = {
390
+ socket: sock,
391
+ decoder: new NdjsonDecoder(),
392
+ authed: false,
393
+ runId: undefined,
394
+ taskId: undefined,
395
+ role: undefined,
396
+ outbound: [],
397
+ needsResync: false,
398
+ closed: false,
399
+ helloTimer: null,
400
+ outboundSeq: 0,
401
+ };
402
+ this.connections.add(conn);
403
+
404
+ // 1. Hello deadline. Fires after HELLO_DEADLINE_MS if hello has not
405
+ // succeeded. Route through closeConnection so the connection is
406
+ // properly removed from this.connections + the per-run fanout index.
407
+ conn.helloTimer = setTimeout(() => {
408
+ if (!conn.authed && !conn.closed) {
409
+ logInternalError("crew-broker.hello.deadline", new Error("hello deadline"), `sessionId=${this.options.sessionId}`);
410
+ this.closeConnection(conn);
411
+ }
412
+ }, HELLO_DEADLINE_MS);
413
+ conn.helloTimer.unref?.();
414
+
415
+ sock.on("data", (chunk: Buffer) => {
416
+ this.handleData(conn, chunk).catch((err) => {
417
+ logInternalError(
418
+ "crew-broker.connection.data-crashed",
419
+ err instanceof Error ? err : new Error(String(err)),
420
+ `sessionId=${this.options.sessionId}`,
421
+ );
422
+ this.closeConnection(conn);
423
+ });
424
+ });
425
+ sock.on("error", (err) => {
426
+ // socket-level error — log with redaction, then close.
427
+ logInternalError(
428
+ "crew-broker.connection.socket-error",
429
+ err instanceof Error ? err : new Error(String(err)),
430
+ `sessionId=${this.options.sessionId}`,
431
+ );
432
+ this.closeConnection(conn);
433
+ });
434
+ sock.on("close", () => {
435
+ this.closeConnection(conn);
436
+ });
437
+ }
438
+
439
+ private closeConnection(conn: ServerConnection): void {
440
+ if (conn.closed) return;
441
+ conn.closed = true;
442
+ if (conn.helloTimer) {
443
+ clearTimeout(conn.helloTimer);
444
+ conn.helloTimer = null;
445
+ }
446
+ this.connections.delete(conn);
447
+ // Phase 1.3: remove from the per-run fanout index.
448
+ if (conn.runId) {
449
+ const set = this.connectionsByRun.get(conn.runId);
450
+ if (set) {
451
+ set.delete(conn);
452
+ if (set.size === 0) this.connectionsByRun.delete(conn.runId);
453
+ }
454
+ }
455
+ // Phase 2: tear down any per-connection event subscriptions.
456
+ const subs = this.subscriptionUnsubs.get(conn);
457
+ if (subs) {
458
+ for (const unsub of subs) {
459
+ try {
460
+ unsub();
461
+ } catch {
462
+ /* ignore */
463
+ }
464
+ }
465
+ subs.clear();
466
+ this.subscriptionUnsubs.delete(conn);
467
+ }
468
+ try {
469
+ conn.socket.destroy();
470
+ } catch {
471
+ /* ignore */
472
+ }
473
+ }
474
+
475
+ /**
476
+ * Phase 1.3: push a durable-appended mailbox message to any connected
477
+ * recipient for the message's run. Best-effort — silently skips
478
+ * recipients that are offline (they recover via msg.inbox). Never throws.
479
+ */
480
+ private fanoutMailboxMessage(msg: MailboxMessage): void {
481
+ const set = this.connectionsByRun.get(msg.runId);
482
+ if (!set || set.size === 0) return;
483
+ // Recipient delivery dedup lives in src/prompt/prompt-runtime.ts and is
484
+ // keyed by the same message id in this mailbox event and the steering JSONL.
485
+ const eventFrame = encodeBrokerFrame({
486
+ event: "mailbox.message",
487
+ data: { id: msg.id, from: msg.from, to: msg.to, body: msg.body, kind: msg.kind, priority: msg.priority },
488
+ seq: 0, // mailbox messages don't carry a TeamEvent seq; dedup by msg.id
489
+ });
490
+ for (const conn of set) {
491
+ if (conn.closed || !conn.authed) continue;
492
+ // Recipient filter: deliver to the addressed task, or to all if 'all'.
493
+ if (msg.to && msg.to !== "all" && conn.taskId !== msg.to) continue;
494
+ try {
495
+ this.writeOrQueue(conn, eventFrame, false);
496
+ } catch {
497
+ /* a slow/dead recipient must not break fanout to others */
498
+ }
499
+ }
500
+ }
501
+
502
+ private async handleData(conn: ServerConnection, chunk: Buffer): Promise<void> {
503
+ if (conn.closed) return;
504
+ let frames: unknown[];
505
+ try {
506
+ frames = conn.decoder.push(chunk);
507
+ } catch (err) {
508
+ // BrokerError from the decoder — typed close.
509
+ if (err instanceof BrokerError) {
510
+ logInternalError("crew-broker.decoder.error", err, `code=${err.code} sessionId=${this.options.sessionId}`);
511
+ this.sendErrorAndClose(conn, undefined, err.code === "oversize-frame" ? "oversize-frame" : "protocol", err.message);
512
+ return;
513
+ }
514
+ throw err;
515
+ }
516
+ for (const frame of frames) {
517
+ await this.dispatchFrame(conn, frame);
518
+ if (conn.closed) return;
519
+ }
520
+ }
521
+
522
+ private async dispatchFrame(conn: ServerConnection, frame: unknown): Promise<void> {
523
+ // Validate the frame is a request object.
524
+ if (!isRequestObject(frame)) {
525
+ this.sendErrorAndClose(conn, undefined, "protocol", "malformed request");
526
+ return;
527
+ }
528
+ const { id, method, params } = frame;
529
+
530
+ // Hello MUST be the first method. Any other method before hello
531
+ // returns a generic protocol error and closes.
532
+ if (!conn.authed) {
533
+ if (method !== "hello") {
534
+ this.sendErrorAndClose(conn, id, "protocol", "hello required");
535
+ return;
536
+ }
537
+ await this.handleHello(conn, id, params);
538
+ return;
539
+ }
540
+
541
+ // Post-hello: dispatch the known set.
542
+ switch (method) {
543
+ case "ping":
544
+ this.sendResult(conn, id, { pong: true, protocol: BROKER_PROTOCOL });
545
+ return;
546
+ case "hello":
547
+ // Repeat hello on the same connection — generic protocol error.
548
+ this.sendErrorAndClose(conn, id, "protocol", "hello already completed");
549
+ return;
550
+ case "msg.send":
551
+ await this.handleMsgSend(conn, id, params);
552
+ return;
553
+ case "msg.inbox":
554
+ await this.handleMsgInbox(conn, id, params);
555
+ return;
556
+ case "events.since":
557
+ await this.handleEventsSince(conn, id, params);
558
+ return;
559
+ case "events.subscribe":
560
+ await this.handleEventsSubscribe(conn, id, params);
561
+ return;
562
+ case "task.waitStatus":
563
+ await this.handleTaskWaitStatus(conn, id, params);
564
+ return;
565
+ case "steer.push":
566
+ await this.handleSteerPush(conn, id, params);
567
+ return;
568
+ case "escalate":
569
+ await this.handleEscalate(conn, id, params);
570
+ return;
571
+ default:
572
+ // Unhandled method → typed not-implemented.
573
+ this.sendError(conn, id, "not-implemented", `method '${method}' is not implemented`);
574
+ return;
575
+ }
576
+ }
577
+
578
+ private async handleHello(conn: ServerConnection, id: string, params: unknown): Promise<void> {
579
+ // Validate params shape. We deliberately do NOT disclose which field
580
+ // is wrong — return a generic auth/protocol code.
581
+ if (!isHelloParams(params)) {
582
+ this.sendErrorAndClose(conn, id, "auth", "hello rejected");
583
+ return;
584
+ }
585
+ const { protocol, runId, taskId, token } = params;
586
+
587
+ // Protocol must be exactly BROKER_PROTOCOL. Mismatch is a generic
588
+ // auth failure so we don't disclose whether the runId was valid.
589
+ if (protocol !== BROKER_PROTOCOL) {
590
+ this.sendErrorAndClose(conn, id, "auth", "hello rejected");
591
+ return;
592
+ }
593
+
594
+ // Token must match. Role is derived from the TOKEN TYPE (orchestrator
595
+ // vs worker), never from a self-declared hello field (F-06: otherwise a
596
+ // worker could forge role:'orchestrator' and call steer.push/msg.send).
597
+ // Constant-time compare; never include the token in the error path.
598
+ const role = this.tokens.tokenRole(runId, taskId, token);
599
+ if (role === null) {
600
+ this.sendErrorAndClose(conn, id, "auth", "hello rejected");
601
+ return;
602
+ }
603
+
604
+ // Bounded identity checks. taskId must be a non-empty string.
605
+ if (typeof taskId !== "string" || taskId.length === 0 || taskId.length > 256) {
606
+ this.sendErrorAndClose(conn, id, "auth", "hello rejected");
607
+ return;
608
+ }
609
+ if (typeof runId !== "string" || runId.length === 0 || runId.length > 256) {
610
+ this.sendErrorAndClose(conn, id, "auth", "hello rejected");
611
+ return;
612
+ }
613
+
614
+ // Bind connection identity and ack. Ack never includes the token.
615
+ conn.authed = true;
616
+ conn.runId = runId;
617
+ conn.taskId = taskId;
618
+ conn.role = role;
619
+ // Phase 1.3: index by runId for live mailbox fanout.
620
+ let connsForRun = this.connectionsByRun.get(runId);
621
+ if (!connsForRun) {
622
+ connsForRun = new Set();
623
+ this.connectionsByRun.set(runId, connsForRun);
624
+ }
625
+ connsForRun.add(conn);
626
+ if (conn.helloTimer) {
627
+ clearTimeout(conn.helloTimer);
628
+ conn.helloTimer = null;
629
+ }
630
+ this.handshakeCount += 1;
631
+ this.sendResult(conn, id, {
632
+ protocol: BROKER_PROTOCOL,
633
+ session: this.options.sessionId,
634
+ run: runId,
635
+ ok: true,
636
+ });
637
+ }
638
+
639
+ // ------------------------------------------------------------------------
640
+ // Outbound queue + drop-newest + needsResync
641
+ // ------------------------------------------------------------------------
642
+
643
+ private sendResult(conn: ServerConnection, id: string, result: unknown): void {
644
+ this.enqueueFrame(conn, { id, result });
645
+ }
646
+
647
+ private sendError(conn: ServerConnection, id: string, code: string, message: string): void {
648
+ this.enqueueFrame(conn, { id, error: { code, message: redactSecretString(message) } });
649
+ }
650
+
651
+ private sendErrorAndClose(conn: ServerConnection, id: string | undefined, code: string, message: string): void {
652
+ if (id !== undefined) {
653
+ // Best-effort error frame before close. Even if the queue is full
654
+ // we still try to deliver the close reason.
655
+ try {
656
+ const buf = encodeBrokerFrame({ id, error: { code, message: redactSecretString(message) } });
657
+ this.writeOrQueue(conn, buf, /*force*/ true);
658
+ } catch {
659
+ // encodeBrokerFrame may throw oversize-frame; we still want to
660
+ // close, so swallow.
661
+ }
662
+ }
663
+ this.closeConnection(conn);
664
+ }
665
+
666
+ private enqueueFrame(conn: ServerConnection, payload: unknown): void {
667
+ let buf: Buffer;
668
+ try {
669
+ buf = encodeBrokerFrame(payload);
670
+ } catch (err) {
671
+ logInternalError(
672
+ "crew-broker.enqueue.encode-failed",
673
+ err instanceof Error ? err : new Error(String(err)),
674
+ `sessionId=${this.options.sessionId}`,
675
+ );
676
+ return;
677
+ }
678
+ this.writeOrQueue(conn, buf, /*force*/ false);
679
+ }
680
+
681
+ private writeOrQueue(conn: ServerConnection, buf: Buffer, force: boolean): void {
682
+ if (conn.closed) return;
683
+ const cap = this.options.outboundQueueCap ?? DEFAULT_OUTBOUND_QUEUE_CAP;
684
+ if (conn.outbound.length >= cap) {
685
+ if (force) {
686
+ // Forced sends (e.g. close-reason) bypass the cap and attempt
687
+ // to flush directly; if the socket is busy they may still drop.
688
+ try {
689
+ conn.socket.write(buf);
690
+ } catch {
691
+ /* socket may have closed; the close handler will sweep. */
692
+ }
693
+ return;
694
+ }
695
+ // Drop-newest: do NOT add the new frame, mark needsResync, and stop
696
+ // further live fanout for this connection. The client must reconnect
697
+ // and replay (Phase 1: via events.since; Phase 0: protocol error).
698
+ conn.needsResync = true;
699
+ // We do NOT revoke auth — the connection is still authenticated; we
700
+ // simply pause live frame production. The client is expected to
701
+ // notice the queue-depth and resync.
702
+ return;
703
+ }
704
+ conn.outbound.push(buf);
705
+ this.drainOutbound(conn);
706
+ }
707
+
708
+ private drainOutbound(conn: ServerConnection): void {
709
+ while (conn.outbound.length > 0) {
710
+ const buf = conn.outbound[0];
711
+ if (buf === undefined) break;
712
+ // Try the write; if it returns false, wait for drain before pushing more.
713
+ try {
714
+ const ok = conn.socket.write(buf);
715
+ if (!ok) {
716
+ // Backpressure — re-arm on drain event.
717
+ conn.socket.once("drain", () => {
718
+ if (!conn.closed) this.drainOutbound(conn);
719
+ });
720
+ return;
721
+ }
722
+ } catch {
723
+ // Write failed — close the connection (we already had it open).
724
+ this.closeConnection(conn);
725
+ return;
726
+ }
727
+ conn.outbound.shift();
728
+ conn.outboundSeq += 1;
729
+ }
730
+ }
731
+
732
+ // ------------------------------------------------------------------------
733
+ // Phase 1: msg.send + msg.inbox handlers
734
+ // ------------------------------------------------------------------------
735
+
736
+ /** Phase 1.1: direct or broadcast mailbox write via the durable append path. */
737
+ private async handleMsgSend(conn: ServerConnection, id: string, params: unknown): Promise<void> {
738
+ if (conn.role !== "orchestrator") {
739
+ this.sendError(conn, id, "forbidden", "msg.send requires orchestrator role");
740
+ return;
741
+ }
742
+ if (!conn.runId) {
743
+ this.sendError(conn, id, "auth", "not authed");
744
+ return;
745
+ }
746
+ const parsed = parseMsgSendParams(params);
747
+ if (!parsed) {
748
+ this.sendError(conn, id, "bad-params", "msg.send: invalid params");
749
+ return;
750
+ }
751
+ const bodyJson = safeStringify(parsed.body);
752
+ if (bodyJson.length > MAX_BROKER_FRAME_BYTES) {
753
+ this.sendError(conn, id, "oversize-frame", "msg.send: body too large");
754
+ return;
755
+ }
756
+ const cwd = this.options.cwd;
757
+ if (!cwd) {
758
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
759
+ return;
760
+ }
761
+ let manifest: Parameters<typeof appendMailboxMessageAsync>[0];
762
+ let taskIds: string[];
763
+ try {
764
+ const loaded = loadRunManifestById(cwd, conn.runId);
765
+ if (!loaded) {
766
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
767
+ return;
768
+ }
769
+ manifest = loaded.manifest;
770
+ taskIds = (loaded.tasks ?? []).map((t) => t.id);
771
+ } catch (err) {
772
+ this.sendError(conn, id, "no-manifest", (err as Error).message);
773
+ return;
774
+ }
775
+ const recipients: string[] = Array.isArray(parsed.to)
776
+ ? (parsed.to as string[])
777
+ : parsed.to === "all"
778
+ ? taskIds
779
+ : [parsed.to as string];
780
+ if (recipients.length === 0 || recipients.length > 64) {
781
+ this.sendError(conn, id, "bad-params", "msg.send: recipient count out of range");
782
+ return;
783
+ }
784
+ const messageId = `msg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
785
+ const fromField = conn.taskId ?? conn.runId;
786
+ let durable = false;
787
+ try {
788
+ for (const recipient of recipients) {
789
+ await appendMailboxMessageAsync(manifest, {
790
+ id: `${messageId}_${recipient}`,
791
+ direction: "inbox",
792
+ from: fromField,
793
+ to: recipient,
794
+ taskId: recipient,
795
+ body: bodyJson,
796
+ kind: parsed.kind ?? "message",
797
+ priority: parsed.priority ?? "normal",
798
+ deliveryMode: "next_turn",
799
+ replyTo: parsed.replyTo,
800
+ });
801
+ }
802
+ durable = true;
803
+ } catch (err) {
804
+ this.sendError(conn, id, "durable-failed", (err as Error).message);
805
+ return;
806
+ }
807
+ this.sendResult(conn, id, {
808
+ messageId,
809
+ recipientCount: recipients.length,
810
+ durableStatus: durable ? "ok" : "failed",
811
+ liveDeliveryStatus: "ok",
812
+ });
813
+ }
814
+
815
+ /** Phase 1.2: paginated inbox pull for the authenticated run/task. */
816
+ private async handleMsgInbox(conn: ServerConnection, id: string, params: unknown): Promise<void> {
817
+ if (!conn.runId) {
818
+ this.sendError(conn, id, "auth", "not authed");
819
+ return;
820
+ }
821
+ const parsed = parseMsgInboxParams(params);
822
+ if (!parsed) {
823
+ this.sendError(conn, id, "bad-params", "msg.inbox: invalid params");
824
+ return;
825
+ }
826
+ const cwd = this.options.cwd;
827
+ if (!cwd) {
828
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
829
+ return;
830
+ }
831
+ let manifest: Parameters<typeof readMailbox>[0];
832
+ try {
833
+ const loaded = loadRunManifestById(cwd, conn.runId);
834
+ if (!loaded) {
835
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
836
+ return;
837
+ }
838
+ manifest = loaded.manifest;
839
+ } catch (err) {
840
+ this.sendError(conn, id, "no-manifest", (err as Error).message);
841
+ return;
842
+ }
843
+ const limit = Math.min(Math.max(parsed.limit ?? 100, 1), 1000);
844
+ const taskId = conn.taskId ?? undefined;
845
+ const all = readMailbox(manifest, "inbox", taskId);
846
+ const filtered = all.filter((m) => m.status !== "acknowledged");
847
+ const offset = parsed.cursor ? parseInt(parsed.cursor, 10) || 0 : 0;
848
+ const page = filtered.slice(offset, offset + limit);
849
+ const nextOffset = offset + page.length;
850
+ const hasMore = nextOffset < filtered.length;
851
+ this.sendResult(conn, id, {
852
+ messages: page,
853
+ nextCursor: hasMore ? String(nextOffset) : undefined,
854
+ hasMore,
855
+ total: filtered.length,
856
+ });
857
+ }
858
+
859
+ /**
860
+ * Phase 1.5: events.since — bounded replay of structured events with seq >
861
+ * sinceSeq from the durable log. Used by clients to resync after a missed
862
+ * live frame (e.g. after a queue overflow or reconnect). Reuses the same
863
+ * readEventsCursor + seq semantics as runEventBus.onWithReplay.
864
+ */
865
+ private async handleEventsSince(conn: ServerConnection, id: string, params: unknown): Promise<void> {
866
+ if (!conn.runId) {
867
+ this.sendError(conn, id, "auth", "not authed");
868
+ return;
869
+ }
870
+ const cwd = this.options.cwd;
871
+ if (!cwd) {
872
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
873
+ return;
874
+ }
875
+ let eventsPath: string;
876
+ try {
877
+ const loaded = loadRunManifestById(cwd, conn.runId);
878
+ if (!loaded) {
879
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
880
+ return;
881
+ }
882
+ eventsPath = loaded.manifest.eventsPath;
883
+ } catch (err) {
884
+ this.sendError(conn, id, "no-manifest", (err as Error).message);
885
+ return;
886
+ }
887
+ const v = params && typeof params === "object" && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
888
+ const sinceSeq = typeof v.sinceSeq === "number" && Number.isFinite(v.sinceSeq) ? Math.max(0, Math.floor(v.sinceSeq)) : 0;
889
+ const limit = typeof v.limit === "number" && Number.isFinite(v.limit) ? Math.min(Math.max(1, Math.floor(v.limit)), 1000) : 1000;
890
+ try {
891
+ const result = readEventsCursor(eventsPath, { sinceSeq, limit });
892
+ // hasMore is true iff the total filtered count exceeds the page we
893
+ // returned. When `total === events.length` we are at the exact end
894
+ // of the stream (caller will discover this on the next call when
895
+ // `nextSeq` is unchanged from `sinceSeq`).
896
+ const hasMore = result.total > result.events.length;
897
+ this.sendResult(conn, id, {
898
+ events: result.events,
899
+ nextSeq: result.nextSeq,
900
+ hasMore,
901
+ });
902
+ } catch (err) {
903
+ this.sendError(conn, id, "replay-failed", (err as Error).message);
904
+ }
905
+ }
906
+
907
+ /**
908
+ * Phase 2: events.subscribe — live event-stream subscription.
909
+ * Replays events with seq > sinceSeq from the durable log, then pushes
910
+ * live events as they are emitted. Delivery uses the same writeOrQueue
911
+ * path as mailbox fanout (queue-cap 256, drop-newest on overflow).
912
+ */
913
+ private async handleEventsSubscribe(conn: ServerConnection, id: string, params: unknown): Promise<void> {
914
+ if (!conn.runId) {
915
+ this.sendError(conn, id, "auth", "not authed");
916
+ return;
917
+ }
918
+ const cwd = this.options.cwd;
919
+ if (!cwd) {
920
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
921
+ return;
922
+ }
923
+ let eventsPath: string;
924
+ try {
925
+ const loaded = loadRunManifestById(cwd, conn.runId);
926
+ if (!loaded) {
927
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
928
+ return;
929
+ }
930
+ eventsPath = loaded.manifest.eventsPath;
931
+ } catch (err) {
932
+ this.sendError(conn, id, "no-manifest", (err as Error).message);
933
+ return;
934
+ }
935
+ const v = params && typeof params === "object" && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
936
+ const sinceSeq = typeof v.sinceSeq === "number" && Number.isFinite(v.sinceSeq) ? Math.max(0, Math.floor(v.sinceSeq)) : 0;
937
+ // Live callback: enqueue a serialized event frame onto the connection's
938
+ // outbound queue (non-blocking; queue-cap enforces drop-newest).
939
+ const cb = (event: unknown) => {
940
+ if (conn.closed) return;
941
+ const seq =
942
+ event && typeof event === "object" && "seq" in (event as Record<string, unknown>)
943
+ ? ((event as { seq?: unknown }).seq as number | undefined)
944
+ : undefined;
945
+ const eventFrame = encodeBrokerFrame({ event: "team.event", data: event, seq });
946
+ try {
947
+ this.writeOrQueue(conn, eventFrame, false);
948
+ } catch {
949
+ /* a slow/dead client must not break the bus */
950
+ }
951
+ };
952
+ const unsub = runEventBus.onWithReplay(conn.runId, eventsPath, sinceSeq, cb);
953
+ // Track the unsub so closeConnection can tear it down.
954
+ let bucket = this.subscriptionUnsubs.get(conn);
955
+ if (!bucket) {
956
+ bucket = new Set();
957
+ this.subscriptionUnsubs.set(conn, bucket);
958
+ }
959
+ bucket.add(unsub);
960
+ // Auto-cleanup on close.
961
+ const origUnsub = unsub;
962
+ const wrappedUnsub = () => {
963
+ try {
964
+ origUnsub();
965
+ } catch {
966
+ /* ignore */
967
+ }
968
+ const b = this.subscriptionUnsubs.get(conn);
969
+ if (b) b.delete(origUnsub);
970
+ };
971
+ bucket.delete(origUnsub);
972
+ bucket.add(wrappedUnsub);
973
+ this.sendResult(conn, id, { subscribed: true, sinceSeq });
974
+ }
975
+
976
+ /**
977
+ * Phase 2: task.waitStatus — resolve when a task reaches `until` status.
978
+ * Polls loadRunManifestById + tasks.json mtime with a bounded backoff.
979
+ * Returns the current task state if already at the target.
980
+ */
981
+ private async handleTaskWaitStatus(conn: ServerConnection, id: string, params: unknown): Promise<void> {
982
+ if (!conn.runId) {
983
+ this.sendError(conn, id, "auth", "not authed");
984
+ return;
985
+ }
986
+ const cwd = this.options.cwd;
987
+ if (!cwd) {
988
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
989
+ return;
990
+ }
991
+ const v = params && typeof params === "object" && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
992
+ const targetTaskId = typeof v.taskId === "string" ? v.taskId : undefined;
993
+ const targetStatus = typeof v.until === "string" ? v.until : undefined;
994
+ const timeoutMs =
995
+ typeof v.timeoutMs === "number" && Number.isFinite(v.timeoutMs)
996
+ ? Math.min(Math.max(0, Math.floor(v.timeoutMs)), 60_000)
997
+ : 30_000;
998
+ if (!targetTaskId || !targetStatus) {
999
+ this.sendError(conn, id, "bad-params", "task.waitStatus: taskId and until are required");
1000
+ return;
1001
+ }
1002
+ // Reject non-authed identity-supplying params.
1003
+ if (targetTaskId.length === 0 || targetTaskId.length > 256) {
1004
+ this.sendError(conn, id, "bad-params", "task.waitStatus: taskId out of range");
1005
+ return;
1006
+ }
1007
+ const validStatuses = new Set(["queued", "running", "completed", "failed", "blocked", "cancelled"]);
1008
+ if (!validStatuses.has(targetStatus)) {
1009
+ this.sendError(conn, id, "bad-params", `task.waitStatus: invalid until '${targetStatus}'`);
1010
+ return;
1011
+ }
1012
+ const isTerminal = (s: string) => s === "completed" || s === "failed" || s === "cancelled";
1013
+ const start = Date.now();
1014
+ const interval = 200; // 200ms poll; bounded by timeoutMs.
1015
+ // Properly recursive: the promise returned by `pollUntilDone` only
1016
+ // resolves when the task reaches the target status OR the timeout
1017
+ // elapses OR the connection closes. Each iteration schedules the
1018
+ // next via setTimeout to keep the event loop free.
1019
+ const pollUntilDone = (): Promise<void> =>
1020
+ new Promise<void>((resolve) => {
1021
+ const tick = () => {
1022
+ if (conn.closed) {
1023
+ this.sendError(conn, id, "close", "connection closed during wait");
1024
+ resolve();
1025
+ return;
1026
+ }
1027
+ const connRunId = conn.runId;
1028
+ if (!connRunId) {
1029
+ this.sendError(conn, id, "auth", "not authed (post-narrow)");
1030
+ resolve();
1031
+ return;
1032
+ }
1033
+ if (Date.now() - start >= timeoutMs) {
1034
+ this.sendError(conn, id, "wait-timeout", `task did not reach '${targetStatus}' within ${timeoutMs}ms`);
1035
+ resolve();
1036
+ return;
1037
+ }
1038
+ try {
1039
+ const loaded = loadRunManifestById(cwd, connRunId);
1040
+ if (!loaded) {
1041
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
1042
+ resolve();
1043
+ return;
1044
+ }
1045
+ const task = loaded.tasks.find((t) => t.id === targetTaskId);
1046
+ if (!task) {
1047
+ this.sendError(conn, id, "no-task", `task '${targetTaskId}' not found`);
1048
+ resolve();
1049
+ return;
1050
+ }
1051
+ if (task.status === targetStatus || (isTerminal(targetStatus) && isTerminal(task.status))) {
1052
+ this.sendResult(conn, id, { taskId: task.id, status: task.status, waitedMs: Date.now() - start });
1053
+ resolve();
1054
+ return;
1055
+ }
1056
+ } catch (err) {
1057
+ this.sendError(conn, id, "wait-failed", (err as Error).message);
1058
+ resolve();
1059
+ return;
1060
+ }
1061
+ setTimeout(tick, interval);
1062
+ };
1063
+ setTimeout(tick, 0);
1064
+ });
1065
+ await pollUntilDone();
1066
+ }
1067
+
1068
+ /**
1069
+ * Phase 3: steer.push — push steering message to a running worker.
1070
+ *
1071
+ * Dual-write strategy for durability:
1072
+ * 1. Mailbox append (appendMailboxMessageAsync) — feeds the live broker
1073
+ * fanout to connected subscribers AND persists to the mailbox inbox
1074
+ * JSONL for later read.
1075
+ * 2. Steering-file append — writes the steer body to
1076
+ * ${artifactsRoot}/steering/${taskId}.jsonl, the same file the
1077
+ * child's pollSteering() polls via PI_CREW_STEERING_FILE. This is
1078
+ * the durable fallback: even if the recipient child's broker connection is down, the
1079
+ * child picks up the steer on its next poll tick.
1080
+ *
1081
+ * A steering-file write failure does NOT fail the steer push — the
1082
+ * mailbox write (1) has already succeeded.
1083
+ */
1084
+ private async handleSteerPush(conn: ServerConnection, id: string, params: unknown): Promise<void> {
1085
+ if (conn.role !== "orchestrator") {
1086
+ this.sendError(conn, id, "forbidden", "steer.push requires orchestrator role");
1087
+ return;
1088
+ }
1089
+ if (!conn.runId) {
1090
+ this.sendError(conn, id, "auth", "not authed");
1091
+ return;
1092
+ }
1093
+ const v = params && typeof params === "object" && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
1094
+ const targetTaskId = typeof v.taskId === "string" ? v.taskId : undefined;
1095
+ const body = typeof v.body === "string" ? v.body : undefined;
1096
+ if (!targetTaskId || body === undefined) {
1097
+ this.sendError(conn, id, "bad-params", "steer.push: taskId and body are required");
1098
+ return;
1099
+ }
1100
+ if (body.length > MAX_BROKER_FRAME_BYTES) {
1101
+ this.sendError(conn, id, "oversize-frame", "steer.push: body too large");
1102
+ return;
1103
+ }
1104
+ const cwd = this.options.cwd;
1105
+ if (!cwd) {
1106
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
1107
+ return;
1108
+ }
1109
+ try {
1110
+ const loaded = loadRunManifestById(cwd, conn.runId);
1111
+ if (!loaded) {
1112
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
1113
+ return;
1114
+ }
1115
+
1116
+ const messageId = `steer_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
1117
+ // Write 1: mailbox — live broker fanout + persistent inbox read.
1118
+ await appendMailboxMessageAsync(loaded.manifest, {
1119
+ id: messageId,
1120
+ direction: "inbox",
1121
+ from: conn.taskId ?? conn.runId,
1122
+ to: targetTaskId,
1123
+ taskId: targetTaskId,
1124
+ body,
1125
+ kind: "steer",
1126
+ priority: (v.priority as "urgent" | "normal" | "low" | undefined) ?? "urgent",
1127
+ deliveryMode: "interrupt",
1128
+ });
1129
+ // Write 2: steering file — durable fallback so pollSteering() picks
1130
+ // up the steer even when the recipient child's broker connection is down. Matches the
1131
+ // JSONL format of appendSteeringAsync in task-runner.ts.
1132
+ // Best-effort: a failure here must NOT fail the push (mailbox write
1133
+ // already succeeded).
1134
+ try {
1135
+ const steeringDir = `${loaded.manifest.artifactsRoot}/steering`;
1136
+ const steeringPath = resolveRealContainedPath(loaded.manifest.artifactsRoot, `steering/${targetTaskId}.jsonl`);
1137
+ const line =
1138
+ JSON.stringify({
1139
+ type: "steer",
1140
+ message: body,
1141
+ id: messageId,
1142
+ ts: new Date().toISOString(),
1143
+ }) + "\n";
1144
+ await fsp.mkdir(steeringDir, { recursive: true });
1145
+ await fsp.appendFile(steeringPath, line, "utf-8");
1146
+ } catch (fileErr) {
1147
+ const safeMessage = fileErr instanceof Error ? redactSecretString(fileErr.message) : "";
1148
+ logInternalError("crew-broker.steer-file-write-failed", new Error(safeMessage), `taskId=${targetTaskId}`);
1149
+ }
1150
+ this.sendResult(conn, id, { messageId, taskId: targetTaskId, durable: true });
1151
+ } catch (err) {
1152
+ this.sendError(conn, id, "steer-failed", (err as Error).message);
1153
+ }
1154
+ }
1155
+
1156
+ /**
1157
+ * Phase 3: escalate — worker → orchestrator question/block.
1158
+ * For Phase 3, the durable path is via the same mailbox append
1159
+ * (kind = "follow-up" or "response") to the orchestrator's task
1160
+ * (conn.taskId of the SENDER, or runId itself). The live-fanout
1161
+ * via the mailbox observer will push the event frame to any connected
1162
+ * orchestrator.
1163
+ */
1164
+ private async handleEscalate(conn: ServerConnection, id: string, params: unknown): Promise<void> {
1165
+ if (!conn.runId) {
1166
+ this.sendError(conn, id, "auth", "not authed");
1167
+ return;
1168
+ }
1169
+ const v = params && typeof params === "object" && !Array.isArray(params) ? (params as Record<string, unknown>) : {};
1170
+ const body = typeof v.body === "string" ? v.body : undefined;
1171
+ const to = typeof v.to === "string" ? v.to : undefined;
1172
+ if (body === undefined) {
1173
+ this.sendError(conn, id, "bad-params", "escalate: body is required");
1174
+ return;
1175
+ }
1176
+ if (body.length > MAX_BROKER_FRAME_BYTES) {
1177
+ this.sendError(conn, id, "oversize-frame", "escalate: body too large");
1178
+ return;
1179
+ }
1180
+ const cwd = this.options.cwd;
1181
+ if (!cwd) {
1182
+ this.sendError(conn, id, "no-manifest", "broker has no cwd configured");
1183
+ return;
1184
+ }
1185
+ // Default recipient: the sender's taskId (the orchestrator that
1186
+ // spawned this worker). If 'to' is provided, use it instead.
1187
+ const target = to ?? conn.taskId ?? conn.runId;
1188
+ try {
1189
+ const loaded = loadRunManifestById(cwd, conn.runId);
1190
+ if (!loaded) {
1191
+ this.sendError(conn, id, "no-manifest", `run '${conn.runId}' not found`);
1192
+ return;
1193
+ }
1194
+ const messageId = `esc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
1195
+ await appendMailboxMessageAsync(loaded.manifest, {
1196
+ id: messageId,
1197
+ direction: "inbox",
1198
+ from: conn.taskId ?? conn.runId,
1199
+ to: target,
1200
+ taskId: target,
1201
+ body,
1202
+ kind: "follow-up",
1203
+ priority: (v.priority as "urgent" | "normal" | "low" | undefined) ?? "normal",
1204
+ deliveryMode: "next_turn",
1205
+ });
1206
+ this.sendResult(conn, id, { messageId, to: target, durable: true });
1207
+ } catch (err) {
1208
+ this.sendError(conn, id, "escalate-failed", (err as Error).message);
1209
+ }
1210
+ }
1211
+ }
1212
+
1213
+ // ============================================================================
1214
+ // Type guards (no `any`)
1215
+ // ============================================================================
1216
+
1217
+ function isRequestObject(value: unknown): value is { id: string; method: string; params: unknown } {
1218
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1219
+ const v = value as Record<string, unknown>;
1220
+ if (typeof v.id !== "string" || v.id.length === 0 || v.id.length > 256) return false;
1221
+ if (typeof v.method !== "string" || v.method.length === 0 || v.method.length > 64) return false;
1222
+ // Method names are restricted to a small safe charset. This guards against
1223
+ // odd inputs (control chars, very long names) reaching the dispatcher.
1224
+ if (!/^[a-zA-Z][a-zA-Z0-9._-]{0,63}$/.test(v.method)) return false;
1225
+ // params may be anything (validated per-method), but not undefined-shaped.
1226
+ return "params" in v;
1227
+ }
1228
+
1229
+ function isHelloParams(value: unknown): value is {
1230
+ protocol: number;
1231
+ runId: string;
1232
+ taskId: string;
1233
+ token: string;
1234
+ role?: string;
1235
+ } {
1236
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1237
+ const v = value as Record<string, unknown>;
1238
+ if (v.protocol !== BROKER_PROTOCOL) {
1239
+ // Force exact-type comparison (must be the number 1, not "1").
1240
+ if (typeof v.protocol !== "number" || !Number.isInteger(v.protocol)) return false;
1241
+ }
1242
+ if (typeof v.runId !== "string" || v.runId.length === 0 || v.runId.length > 256) return false;
1243
+ if (typeof v.taskId !== "string" || v.taskId.length === 0 || v.taskId.length > 256) return false;
1244
+ if (typeof v.token !== "string" || v.token.length === 0 || v.token.length > 256) return false;
1245
+ return true;
1246
+ }
1247
+
1248
+ // ============================================================================
1249
+ // Phase 1 parameter parsers (module-level; no `any`)
1250
+ // ============================================================================
1251
+
1252
+ interface MsgSendParams {
1253
+ to: string | string[] | "all";
1254
+ body: unknown;
1255
+ kind?: MailboxMessageKind;
1256
+ priority?: MailboxMessagePriority;
1257
+ replyTo?: string;
1258
+ }
1259
+
1260
+ function parseMsgSendParams(value: unknown): MsgSendParams | undefined {
1261
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
1262
+ const v = value as Record<string, unknown>;
1263
+ const to = v.to;
1264
+ if (typeof to !== "string" && !Array.isArray(to)) return undefined;
1265
+ if (Array.isArray(to) && !to.every((s) => typeof s === "string" && s.length > 0)) return undefined;
1266
+ if (typeof to === "string" && to.length === 0) return undefined;
1267
+ if (v.body === undefined) return undefined;
1268
+ const kind = v.kind as MailboxMessageKind | undefined;
1269
+ if (kind !== undefined && !["message", "steer", "follow-up", "response", "group_join"].includes(kind)) {
1270
+ return undefined;
1271
+ }
1272
+ const priority = v.priority as MailboxMessagePriority | undefined;
1273
+ if (priority !== undefined && !["urgent", "normal", "low"].includes(priority)) {
1274
+ return undefined;
1275
+ }
1276
+ const replyTo = typeof v.replyTo === "string" ? v.replyTo : undefined;
1277
+ return { to: to as string | string[] | "all", body: v.body, kind, priority, replyTo };
1278
+ }
1279
+
1280
+ interface MsgInboxParams {
1281
+ limit?: number;
1282
+ cursor?: string;
1283
+ }
1284
+
1285
+ function parseMsgInboxParams(value: unknown): MsgInboxParams | undefined {
1286
+ if (value === undefined || value === null) return { limit: 100, cursor: undefined };
1287
+ if (typeof value !== "object" || Array.isArray(value)) return undefined;
1288
+ const v = value as Record<string, unknown>;
1289
+ const limit = v.limit;
1290
+ if (limit !== undefined && (typeof limit !== "number" || !Number.isFinite(limit) || limit < 1)) {
1291
+ return undefined;
1292
+ }
1293
+ const cursor = v.cursor;
1294
+ if (cursor !== undefined && typeof cursor !== "string") return undefined;
1295
+ return { limit: limit as number | undefined, cursor: cursor as string | undefined };
1296
+ }
1297
+
1298
+ function safeStringify(value: unknown): string {
1299
+ try {
1300
+ return JSON.stringify(value) ?? "{}";
1301
+ } catch {
1302
+ return "{}";
1303
+ }
1304
+ }