pi-crew 0.9.50 → 0.9.52

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