@wrongstack/core 0.296.4 → 0.298.0

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 (820) hide show
  1. package/dist/chronicle/index.js +126 -22
  2. package/dist/chronicle/project-server-client.d.ts +12 -0
  3. package/dist/chronicle/project-server-protocol.d.ts +22 -0
  4. package/dist/chronicle/project-server.js +1076 -283
  5. package/dist/coordination/agents/index.js +136 -1
  6. package/dist/coordination/agents/role-skills.d.ts +3 -2
  7. package/dist/coordination/brain-cache.d.ts +14 -0
  8. package/dist/coordination/brain-trace.d.ts +2 -1
  9. package/dist/coordination/director/director-task-registry.d.ts +12 -0
  10. package/dist/coordination/fleet-supervisor.d.ts +21 -0
  11. package/dist/coordination/index.d.ts +23 -21
  12. package/dist/coordination/index.js +16514 -15945
  13. package/dist/coordination/mail-tools.d.ts +3 -3
  14. package/dist/coordination/mailbox-credential-store.d.ts +22 -2
  15. package/dist/coordination/mailbox-credential-throttle.d.ts +63 -0
  16. package/dist/coordination/mailbox-http-router.d.ts +6 -0
  17. package/dist/coordination/mailbox-project-server-client.d.ts +16 -0
  18. package/dist/coordination/mailbox-project-server-protocol.d.ts +43 -5
  19. package/dist/coordination/mailbox-project-server.js +1270 -289
  20. package/dist/coordination/provider-status-tracker.d.ts +2 -0
  21. package/dist/coordination/remote-mailbox-credential-store.d.ts +5 -5
  22. package/dist/coordination/remote-mailbox.d.ts +30 -4
  23. package/dist/coordination/sqlite-mailbox-credentials.d.ts +11 -0
  24. package/dist/core/context.d.ts +5 -5
  25. package/dist/core/fallback-profile-manager.d.ts +14 -0
  26. package/dist/core/index.js +624 -168
  27. package/dist/core/instruction-bundle.d.ts +12 -0
  28. package/dist/core/system-prompt-builder.d.ts +14 -0
  29. package/dist/core/system-prompt-skill-bodies.d.ts +1 -1
  30. package/dist/core/system-prompt-skill-text.d.ts +1 -2
  31. package/dist/defaults/index.js +2393 -1302
  32. package/dist/design/index.js +47 -8
  33. package/dist/execution/design-materialize.d.ts +22 -0
  34. package/dist/execution/index.js +582 -285
  35. package/dist/execution/skill-loader.d.ts +10 -1
  36. package/dist/execution/tool-error-taxonomy.d.ts +31 -0
  37. package/dist/execution/tool-executor.d.ts +1 -0
  38. package/dist/goal/index.js +71 -17
  39. package/dist/goal/phase-store.d.ts +7 -0
  40. package/dist/hooks/index.js +5 -0
  41. package/dist/hq/auth-audit.d.ts +6 -0
  42. package/dist/hq/auth-store.d.ts +59 -3
  43. package/dist/hq/index.js +680 -163
  44. package/dist/hq/kanban-store.d.ts +3 -0
  45. package/dist/hq/persistence/event-log.d.ts +25 -0
  46. package/dist/hq/persistence.d.ts +1 -1
  47. package/dist/hq/protocol/browser.d.ts +2 -1
  48. package/dist/hq/protocol/client.d.ts +18 -1
  49. package/dist/hq/protocol/core.d.ts +5 -16
  50. package/dist/hq/protocol/envelope.d.ts +29 -0
  51. package/dist/hq/protocol/governance.d.ts +34 -0
  52. package/dist/hq/protocol/peer.d.ts +55 -0
  53. package/dist/hq/protocol/project.d.ts +3 -0
  54. package/dist/hq/protocol/resume.d.ts +56 -0
  55. package/dist/hq/protocol.d.ts +11 -8
  56. package/dist/hq/protocol.js +675 -0
  57. package/dist/hq/publisher.d.ts +31 -2
  58. package/dist/hq/session-bridge.d.ts +8 -0
  59. package/dist/index.js +7197 -4006
  60. package/dist/infrastructure/index.js +198 -101
  61. package/dist/kernel/events/session-events.d.ts +3 -0
  62. package/dist/kernel/events/tool-events.d.ts +3 -1
  63. package/dist/models/index.js +1 -1
  64. package/dist/observability/index.d.ts +1 -1
  65. package/dist/observability/index.js +103 -5
  66. package/dist/observability/metrics.d.ts +37 -0
  67. package/dist/observability/prometheus.d.ts +11 -0
  68. package/dist/plugin/index.d.ts +5 -1
  69. package/dist/plugin/index.js +965 -511
  70. package/dist/plugins/auto-review-plugin.d.ts +6 -0
  71. package/dist/plugins/review-store-maintenance.d.ts +26 -0
  72. package/dist/plugins/review-types.d.ts +6 -0
  73. package/dist/security/capabilities.d.ts +45 -1
  74. package/dist/security/error-sanitize.d.ts +49 -0
  75. package/dist/security/file-permissions.d.ts +41 -0
  76. package/dist/security/index.d.ts +9 -6
  77. package/dist/security/index.js +3007 -2032
  78. package/dist/security/permission-policy.d.ts +55 -3
  79. package/dist/security/secret-vault.d.ts +17 -0
  80. package/dist/security/totp.d.ts +86 -0
  81. package/dist/skills/frontmatter.d.ts +12 -1
  82. package/dist/skills/github-fetcher.d.ts +48 -0
  83. package/dist/skills/index.js +137 -26
  84. package/dist/skills/limits.d.ts +19 -0
  85. package/dist/skills/skill-installer.d.ts +13 -0
  86. package/dist/storage/file-session-writer.d.ts +23 -0
  87. package/dist/storage/index.js +1140 -905
  88. package/dist/storage/provider-config-watcher.d.ts +1 -0
  89. package/dist/storage/session-helpers.d.ts +1 -0
  90. package/dist/storage/session-reader.d.ts +0 -7
  91. package/dist/storage/session-store/types.d.ts +12 -1
  92. package/dist/storage/session-store.d.ts +11 -2
  93. package/dist/storage/session-workspace-checkpoints.d.ts +5 -0
  94. package/dist/tools/fallback-manage-tools.d.ts +6 -0
  95. package/dist/tools/index.js +305 -133
  96. package/dist/tools/mcp-use.d.ts +1 -1
  97. package/dist/types/blocks.d.ts +7 -0
  98. package/dist/types/config/autonomy.d.ts +12 -3
  99. package/dist/types/config/mcp-features.d.ts +15 -1
  100. package/dist/types/config/root.d.ts +10 -4
  101. package/dist/types/context-window.d.ts +15 -0
  102. package/dist/types/index.d.ts +1 -1
  103. package/dist/types/observability.d.ts +13 -0
  104. package/dist/types/secret-vault.d.ts +8 -0
  105. package/dist/types/session.d.ts +42 -0
  106. package/dist/types/skill.d.ts +56 -0
  107. package/dist/types/tool-executor.d.ts +2 -0
  108. package/dist/utils/continuous-memory-profiler.d.ts +35 -0
  109. package/dist/utils/env-typed.d.ts +64 -0
  110. package/dist/utils/glob-match.d.ts +21 -1
  111. package/dist/utils/heap-watchdog-types.d.ts +62 -0
  112. package/dist/utils/heap-watchdog.d.ts +15 -34
  113. package/dist/utils/heap-watchdog.js +592 -18
  114. package/dist/utils/incoming-images.d.ts +19 -0
  115. package/dist/utils/index.d.ts +15 -11
  116. package/dist/utils/index.js +1425 -545
  117. package/dist/utils/memory-flight-recorder.d.ts +47 -0
  118. package/dist/utils/path-segment.d.ts +29 -0
  119. package/dist/utils/tool-name.d.ts +34 -0
  120. package/dist/utils/win32-cmd.d.ts +25 -0
  121. package/dist/worktree/index.js +5 -0
  122. package/package.json +11 -3
  123. package/skills/chimera/SKILL.md +16 -4
  124. package/skills/data-governance/SKILL.md +92 -0
  125. package/skills/wrongstack-kanban/SKILL.md +129 -0
  126. package/skills/wrongstack-kanban/agents/openai.yaml +4 -0
  127. package/skills/wrongstack-mailbox-mcp/SKILL.md +72 -0
  128. package/skills/wrongstack-mailbox-mcp/agents/openai.yaml +4 -0
  129. package/dist/agent-status-helpers.d.ts.map +0 -1
  130. package/dist/agent-status-tracker.d.ts.map +0 -1
  131. package/dist/boot.d.ts.map +0 -1
  132. package/dist/chronicle/context.d.ts.map +0 -1
  133. package/dist/chronicle/decision-adapter.d.ts.map +0 -1
  134. package/dist/chronicle/domain-adapter.d.ts.map +0 -1
  135. package/dist/chronicle/event-hash.d.ts.map +0 -1
  136. package/dist/chronicle/file-observer.d.ts.map +0 -1
  137. package/dist/chronicle/health-monitor.d.ts.map +0 -1
  138. package/dist/chronicle/identity.d.ts.map +0 -1
  139. package/dist/chronicle/index.d.ts.map +0 -1
  140. package/dist/chronicle/index.js.map +0 -7
  141. package/dist/chronicle/journal.d.ts.map +0 -1
  142. package/dist/chronicle/legacy-journal-import.d.ts.map +0 -1
  143. package/dist/chronicle/metrics-store.d.ts.map +0 -1
  144. package/dist/chronicle/partition-filename.d.ts.map +0 -1
  145. package/dist/chronicle/partition-range-cache.d.ts.map +0 -1
  146. package/dist/chronicle/process-adapter.d.ts.map +0 -1
  147. package/dist/chronicle/project-access.d.ts.map +0 -1
  148. package/dist/chronicle/project-server-client.d.ts.map +0 -1
  149. package/dist/chronicle/project-server-endpoint.d.ts.map +0 -1
  150. package/dist/chronicle/project-server-protocol.d.ts.map +0 -1
  151. package/dist/chronicle/project-server.d.ts.map +0 -1
  152. package/dist/chronicle/project-server.js.map +0 -7
  153. package/dist/chronicle/prompt-manifest.d.ts.map +0 -1
  154. package/dist/chronicle/provider-adapter.d.ts.map +0 -1
  155. package/dist/chronicle/query.d.ts.map +0 -1
  156. package/dist/chronicle/review-adapter.d.ts.map +0 -1
  157. package/dist/chronicle/rollup-adapter.d.ts.map +0 -1
  158. package/dist/chronicle/sink.d.ts.map +0 -1
  159. package/dist/chronicle/sqlite-journal.d.ts.map +0 -1
  160. package/dist/chronicle/sqlite-query.d.ts.map +0 -1
  161. package/dist/chronicle/stream-adapter.d.ts.map +0 -1
  162. package/dist/chronicle/tool-adapter.d.ts.map +0 -1
  163. package/dist/chronicle/types.d.ts.map +0 -1
  164. package/dist/coordination/adaptive-concurrency.d.ts.map +0 -1
  165. package/dist/coordination/agent-bridge.d.ts.map +0 -1
  166. package/dist/coordination/agent-monitor.d.ts.map +0 -1
  167. package/dist/coordination/agent-subagent-runner.d.ts.map +0 -1
  168. package/dist/coordination/agents/agent-prompts.d.ts.map +0 -1
  169. package/dist/coordination/agents/index.d.ts.map +0 -1
  170. package/dist/coordination/agents/index.js.map +0 -7
  171. package/dist/coordination/agents/phase1-discovery.d.ts.map +0 -1
  172. package/dist/coordination/agents/phase2-planning.d.ts.map +0 -1
  173. package/dist/coordination/agents/phase3-build.d.ts.map +0 -1
  174. package/dist/coordination/agents/phase3-techstack.d.ts.map +0 -1
  175. package/dist/coordination/agents/phase3-wave1-platform.d.ts.map +0 -1
  176. package/dist/coordination/agents/phase3-wave2-meta.d.ts.map +0 -1
  177. package/dist/coordination/agents/phase4-verify.d.ts.map +0 -1
  178. package/dist/coordination/agents/phase5-review.d.ts.map +0 -1
  179. package/dist/coordination/agents/phase6-domain.d.ts.map +0 -1
  180. package/dist/coordination/agents/phase7-knowledge.d.ts.map +0 -1
  181. package/dist/coordination/agents/phase8-delivery.d.ts.map +0 -1
  182. package/dist/coordination/agents/phase8-wave3-products.d.ts.map +0 -1
  183. package/dist/coordination/agents/phase9-meta.d.ts.map +0 -1
  184. package/dist/coordination/agents/phase9-wave4-platform-meta.d.ts.map +0 -1
  185. package/dist/coordination/agents/project-agent-config-validation.d.ts.map +0 -1
  186. package/dist/coordination/agents/project-agent-consolidation.d.ts.map +0 -1
  187. package/dist/coordination/agents/project-agent-files.d.ts.map +0 -1
  188. package/dist/coordination/agents/project-agent-identity-types.d.ts.map +0 -1
  189. package/dist/coordination/agents/project-agent-identity.d.ts.map +0 -1
  190. package/dist/coordination/agents/project-agent-knowledge-manifests.d.ts.map +0 -1
  191. package/dist/coordination/agents/project-agent-learning-entries.d.ts.map +0 -1
  192. package/dist/coordination/agents/project-agent-learning-normalize.d.ts.map +0 -1
  193. package/dist/coordination/agents/project-agent-learning-policy.d.ts.map +0 -1
  194. package/dist/coordination/agents/project-agent-learning-structured.d.ts.map +0 -1
  195. package/dist/coordination/agents/project-agent-paths.d.ts.map +0 -1
  196. package/dist/coordination/agents/project-agent-profile.d.ts.map +0 -1
  197. package/dist/coordination/agents/role-skills.d.ts.map +0 -1
  198. package/dist/coordination/agents/types.d.ts.map +0 -1
  199. package/dist/coordination/agents.d.ts.map +0 -1
  200. package/dist/coordination/auto-extend.d.ts.map +0 -1
  201. package/dist/coordination/autonomous-brain.d.ts.map +0 -1
  202. package/dist/coordination/autonomous-coordinator.d.ts.map +0 -1
  203. package/dist/coordination/brain-cache.d.ts.map +0 -1
  204. package/dist/coordination/brain-heuristics.d.ts.map +0 -1
  205. package/dist/coordination/brain-ledger.d.ts.map +0 -1
  206. package/dist/coordination/brain-monitor.d.ts.map +0 -1
  207. package/dist/coordination/brain-rules.d.ts.map +0 -1
  208. package/dist/coordination/brain-telemetry.d.ts.map +0 -1
  209. package/dist/coordination/brain-trace.d.ts.map +0 -1
  210. package/dist/coordination/brain.d.ts.map +0 -1
  211. package/dist/coordination/change-manager.d.ts.map +0 -1
  212. package/dist/coordination/checkpoint-wiring.d.ts.map +0 -1
  213. package/dist/coordination/collab-bus.d.ts.map +0 -1
  214. package/dist/coordination/collab-debug-types.d.ts.map +0 -1
  215. package/dist/coordination/collab-debug.d.ts.map +0 -1
  216. package/dist/coordination/collab-director-host.d.ts.map +0 -1
  217. package/dist/coordination/commit-safety.d.ts.map +0 -1
  218. package/dist/coordination/consensus-protocol.d.ts.map +0 -1
  219. package/dist/coordination/coordinator/error-classifier.d.ts.map +0 -1
  220. package/dist/coordination/delegate-tool.d.ts.map +0 -1
  221. package/dist/coordination/dep-watcher-bridge.d.ts.map +0 -1
  222. package/dist/coordination/dep-watcher.d.ts.map +0 -1
  223. package/dist/coordination/director/director-btw-notes.d.ts.map +0 -1
  224. package/dist/coordination/director/director-budget-policy.d.ts.map +0 -1
  225. package/dist/coordination/director/director-collab.d.ts.map +0 -1
  226. package/dist/coordination/director/director-errors.d.ts.map +0 -1
  227. package/dist/coordination/director/director-task-registry.d.ts.map +0 -1
  228. package/dist/coordination/director/director-toolset.d.ts.map +0 -1
  229. package/dist/coordination/director-basic-tools.d.ts.map +0 -1
  230. package/dist/coordination/director-collab-tools.d.ts.map +0 -1
  231. package/dist/coordination/director-host-contracts.d.ts.map +0 -1
  232. package/dist/coordination/director-input-helpers.d.ts.map +0 -1
  233. package/dist/coordination/director-kanban-queue-helpers.d.ts.map +0 -1
  234. package/dist/coordination/director-options.d.ts.map +0 -1
  235. package/dist/coordination/director-prompts.d.ts.map +0 -1
  236. package/dist/coordination/director-quality-gate-tool.d.ts.map +0 -1
  237. package/dist/coordination/director-session.d.ts.map +0 -1
  238. package/dist/coordination/director-spawn-model.d.ts.map +0 -1
  239. package/dist/coordination/director-tools.d.ts.map +0 -1
  240. package/dist/coordination/director.d.ts.map +0 -1
  241. package/dist/coordination/dispatcher.d.ts.map +0 -1
  242. package/dist/coordination/file-author-tracker.d.ts.map +0 -1
  243. package/dist/coordination/fleet-bus.d.ts.map +0 -1
  244. package/dist/coordination/fleet-event-validation.d.ts.map +0 -1
  245. package/dist/coordination/fleet-manager.d.ts.map +0 -1
  246. package/dist/coordination/fleet-spawn.d.ts.map +0 -1
  247. package/dist/coordination/fleet-status-tool.d.ts.map +0 -1
  248. package/dist/coordination/fleet-supervisor.d.ts.map +0 -1
  249. package/dist/coordination/fleet.d.ts.map +0 -1
  250. package/dist/coordination/global-mailbox-completion.d.ts.map +0 -1
  251. package/dist/coordination/global-mailbox-paths.d.ts.map +0 -1
  252. package/dist/coordination/icoordinator.d.ts.map +0 -1
  253. package/dist/coordination/ifleet-manager.d.ts.map +0 -1
  254. package/dist/coordination/in-memory-transport.d.ts.map +0 -1
  255. package/dist/coordination/index.d.ts.map +0 -1
  256. package/dist/coordination/index.js.map +0 -7
  257. package/dist/coordination/knowledge-graph.d.ts.map +0 -1
  258. package/dist/coordination/large-answer-store.d.ts.map +0 -1
  259. package/dist/coordination/mail-tools.d.ts.map +0 -1
  260. package/dist/coordination/mailbox-actions.d.ts.map +0 -1
  261. package/dist/coordination/mailbox-auth-types.d.ts.map +0 -1
  262. package/dist/coordination/mailbox-codecs.d.ts.map +0 -1
  263. package/dist/coordination/mailbox-constants.d.ts.map +0 -1
  264. package/dist/coordination/mailbox-credential-store.d.ts.map +0 -1
  265. package/dist/coordination/mailbox-events.d.ts.map +0 -1
  266. package/dist/coordination/mailbox-health.d.ts.map +0 -1
  267. package/dist/coordination/mailbox-hooks.d.ts.map +0 -1
  268. package/dist/coordination/mailbox-http-auth.d.ts.map +0 -1
  269. package/dist/coordination/mailbox-http-rate-limit.d.ts.map +0 -1
  270. package/dist/coordination/mailbox-http-router.d.ts.map +0 -1
  271. package/dist/coordination/mailbox-http-validation.d.ts.map +0 -1
  272. package/dist/coordination/mailbox-message-codec.d.ts.map +0 -1
  273. package/dist/coordination/mailbox-parse-state.d.ts.map +0 -1
  274. package/dist/coordination/mailbox-project-server-client.d.ts.map +0 -1
  275. package/dist/coordination/mailbox-project-server-endpoint.d.ts.map +0 -1
  276. package/dist/coordination/mailbox-project-server-protocol.d.ts.map +0 -1
  277. package/dist/coordination/mailbox-project-server.d.ts.map +0 -1
  278. package/dist/coordination/mailbox-project-server.js.map +0 -7
  279. package/dist/coordination/mailbox-receipt-folding.d.ts.map +0 -1
  280. package/dist/coordination/mailbox-registry-codec.d.ts.map +0 -1
  281. package/dist/coordination/mailbox-retention-state.d.ts.map +0 -1
  282. package/dist/coordination/mailbox-status-mappers.d.ts.map +0 -1
  283. package/dist/coordination/mailbox-tool.d.ts.map +0 -1
  284. package/dist/coordination/mailbox-type-properties.d.ts.map +0 -1
  285. package/dist/coordination/mailbox-types.d.ts.map +0 -1
  286. package/dist/coordination/model-matrix.d.ts.map +0 -1
  287. package/dist/coordination/multi-agent-coordinator.d.ts.map +0 -1
  288. package/dist/coordination/multi-agent-timeout.d.ts.map +0 -1
  289. package/dist/coordination/null-fleet-bus.d.ts.map +0 -1
  290. package/dist/coordination/package-author-tracker.d.ts.map +0 -1
  291. package/dist/coordination/package-outdated-watcher.d.ts.map +0 -1
  292. package/dist/coordination/provider-status-tracker.d.ts.map +0 -1
  293. package/dist/coordination/remote-mailbox-credential-store.d.ts.map +0 -1
  294. package/dist/coordination/remote-mailbox.d.ts.map +0 -1
  295. package/dist/coordination/single-instance-mailbox.d.ts.map +0 -1
  296. package/dist/coordination/spawn-budget.d.ts.map +0 -1
  297. package/dist/coordination/sqlite-mailbox-compaction.d.ts.map +0 -1
  298. package/dist/coordination/sqlite-mailbox-credentials.d.ts.map +0 -1
  299. package/dist/coordination/sqlite-mailbox-rows.d.ts.map +0 -1
  300. package/dist/coordination/sqlite-mailbox-schema.d.ts.map +0 -1
  301. package/dist/coordination/sqlite-mailbox.d.ts.map +0 -1
  302. package/dist/coordination/subagent-budget.d.ts.map +0 -1
  303. package/dist/coordination/subagent-nicknames.d.ts.map +0 -1
  304. package/dist/coordination/subagent-result-tool.d.ts.map +0 -1
  305. package/dist/coordination/task-auctioneer.d.ts.map +0 -1
  306. package/dist/coordination/task-dag.d.ts.map +0 -1
  307. package/dist/coordination/techstack-mailbox-consumer.d.ts.map +0 -1
  308. package/dist/coordination/transport.d.ts.map +0 -1
  309. package/dist/coordination/worktree-task-runner.d.ts.map +0 -1
  310. package/dist/core/agent-internals.d.ts.map +0 -1
  311. package/dist/core/agent-loop.d.ts.map +0 -1
  312. package/dist/core/agent-response.d.ts.map +0 -1
  313. package/dist/core/agent-tools.d.ts.map +0 -1
  314. package/dist/core/agent-types.d.ts.map +0 -1
  315. package/dist/core/agent.d.ts.map +0 -1
  316. package/dist/core/btw.d.ts.map +0 -1
  317. package/dist/core/context.d.ts.map +0 -1
  318. package/dist/core/continue-intent.d.ts.map +0 -1
  319. package/dist/core/continue-to-next-iteration.d.ts.map +0 -1
  320. package/dist/core/conversation-state.d.ts.map +0 -1
  321. package/dist/core/fallback-model.d.ts.map +0 -1
  322. package/dist/core/fallback-profile-manager.d.ts.map +0 -1
  323. package/dist/core/fleet-pulse.d.ts.map +0 -1
  324. package/dist/core/index.d.ts.map +0 -1
  325. package/dist/core/index.js.map +0 -7
  326. package/dist/core/input-builder.d.ts.map +0 -1
  327. package/dist/core/instruction-bundle.d.ts.map +0 -1
  328. package/dist/core/iteration-limit.d.ts.map +0 -1
  329. package/dist/core/mailbox-loop.d.ts.map +0 -1
  330. package/dist/core/model-availability-calendar.d.ts.map +0 -1
  331. package/dist/core/model-ref.d.ts.map +0 -1
  332. package/dist/core/model-ref.js.map +0 -7
  333. package/dist/core/modes/brief.d.ts.map +0 -1
  334. package/dist/core/modes/default.d.ts.map +0 -1
  335. package/dist/core/modes/teach.d.ts.map +0 -1
  336. package/dist/core/provider-runner.d.ts.map +0 -1
  337. package/dist/core/queued-messages.d.ts.map +0 -1
  338. package/dist/core/request-provider-binding.d.ts.map +0 -1
  339. package/dist/core/run-env.d.ts.map +0 -1
  340. package/dist/core/streaming-response-builder.d.ts.map +0 -1
  341. package/dist/core/system-prompt-blocks.d.ts.map +0 -1
  342. package/dist/core/system-prompt-builder.d.ts.map +0 -1
  343. package/dist/core/system-prompt-environment-probes.d.ts.map +0 -1
  344. package/dist/core/system-prompt-environment.d.ts.map +0 -1
  345. package/dist/core/system-prompt-memory-skills.d.ts.map +0 -1
  346. package/dist/core/system-prompt-plan.d.ts.map +0 -1
  347. package/dist/core/system-prompt-shell.d.ts.map +0 -1
  348. package/dist/core/system-prompt-skill-bodies.d.ts.map +0 -1
  349. package/dist/core/system-prompt-skill-text.d.ts.map +0 -1
  350. package/dist/defaults/index.d.ts.map +0 -1
  351. package/dist/defaults/index.js.map +0 -7
  352. package/dist/design/index.d.ts.map +0 -1
  353. package/dist/design/index.js.map +0 -7
  354. package/dist/execution/auto-compaction-middleware.d.ts.map +0 -1
  355. package/dist/execution/autonomous-runner.d.ts.map +0 -1
  356. package/dist/execution/autonomy-brain.d.ts.map +0 -1
  357. package/dist/execution/autonomy-prompt-contributor.d.ts.map +0 -1
  358. package/dist/execution/brain-chain.d.ts.map +0 -1
  359. package/dist/execution/brain-circuit.d.ts.map +0 -1
  360. package/dist/execution/brain-evaluation.d.ts.map +0 -1
  361. package/dist/execution/brain-runtime-constants.d.ts.map +0 -1
  362. package/dist/execution/brain-runtime.d.ts.map +0 -1
  363. package/dist/execution/compaction-core.d.ts.map +0 -1
  364. package/dist/execution/compaction-scoring.d.ts.map +0 -1
  365. package/dist/execution/compaction-summary-cache.d.ts.map +0 -1
  366. package/dist/execution/compactor.d.ts.map +0 -1
  367. package/dist/execution/council-brain.d.ts.map +0 -1
  368. package/dist/execution/council-orchestrator.d.ts.map +0 -1
  369. package/dist/execution/council-personas.d.ts.map +0 -1
  370. package/dist/execution/council-profiles.d.ts.map +0 -1
  371. package/dist/execution/council-prompts.d.ts.map +0 -1
  372. package/dist/execution/council-resolution.d.ts.map +0 -1
  373. package/dist/execution/design-color.d.ts.map +0 -1
  374. package/dist/execution/design-detect.d.ts.map +0 -1
  375. package/dist/execution/design-kit-loader.d.ts.map +0 -1
  376. package/dist/execution/design-materialize.d.ts.map +0 -1
  377. package/dist/execution/design-project-store.d.ts.map +0 -1
  378. package/dist/execution/design-tune.d.ts.map +0 -1
  379. package/dist/execution/design-verify.d.ts.map +0 -1
  380. package/dist/execution/enhance-recovery.d.ts.map +0 -1
  381. package/dist/execution/error-handler.d.ts.map +0 -1
  382. package/dist/execution/eternal-autonomy-types.d.ts.map +0 -1
  383. package/dist/execution/eternal-autonomy.d.ts.map +0 -1
  384. package/dist/execution/goal-preamble.d.ts.map +0 -1
  385. package/dist/execution/index.d.ts.map +0 -1
  386. package/dist/execution/index.js.map +0 -7
  387. package/dist/execution/intelligent-compactor.d.ts.map +0 -1
  388. package/dist/execution/model-runtime.d.ts.map +0 -1
  389. package/dist/execution/one-shot-llm.d.ts.map +0 -1
  390. package/dist/execution/parallel-eternal-engine.d.ts.map +0 -1
  391. package/dist/execution/prompt-enhancer.d.ts.map +0 -1
  392. package/dist/execution/prompt-enhancer.js.map +0 -7
  393. package/dist/execution/prompt-loader.d.ts.map +0 -1
  394. package/dist/execution/provider-runner-impl.d.ts.map +0 -1
  395. package/dist/execution/regex-patterns.d.ts.map +0 -1
  396. package/dist/execution/retry-policy.d.ts.map +0 -1
  397. package/dist/execution/selective-compactor.d.ts.map +0 -1
  398. package/dist/execution/skill-loader.d.ts.map +0 -1
  399. package/dist/execution/strategy-compactor.d.ts.map +0 -1
  400. package/dist/execution/subagent-compaction.d.ts.map +0 -1
  401. package/dist/execution/tool-executor-logging.d.ts.map +0 -1
  402. package/dist/execution/tool-executor-results.d.ts.map +0 -1
  403. package/dist/execution/tool-executor-stream.d.ts.map +0 -1
  404. package/dist/execution/tool-executor-support.d.ts.map +0 -1
  405. package/dist/execution/tool-executor.d.ts.map +0 -1
  406. package/dist/extension/extension-points.d.ts.map +0 -1
  407. package/dist/extension/index.d.ts.map +0 -1
  408. package/dist/extension/index.js.map +0 -7
  409. package/dist/extension/registry.d.ts.map +0 -1
  410. package/dist/fleet-notifier.d.ts.map +0 -1
  411. package/dist/goal/checkpoint.d.ts.map +0 -1
  412. package/dist/goal/goal-assessor.d.ts.map +0 -1
  413. package/dist/goal/goal-planner.d.ts.map +0 -1
  414. package/dist/goal/goal-runner.d.ts.map +0 -1
  415. package/dist/goal/index.d.ts.map +0 -1
  416. package/dist/goal/index.js.map +0 -7
  417. package/dist/goal/phase-board-mutations.d.ts.map +0 -1
  418. package/dist/goal/phase-graph-builder.d.ts.map +0 -1
  419. package/dist/goal/phase-orchestrator-integration.d.ts.map +0 -1
  420. package/dist/goal/phase-orchestrator-queries.d.ts.map +0 -1
  421. package/dist/goal/phase-orchestrator-runtime.d.ts.map +0 -1
  422. package/dist/goal/phase-orchestrator-types.d.ts.map +0 -1
  423. package/dist/goal/phase-orchestrator.d.ts.map +0 -1
  424. package/dist/goal/phase-store.d.ts.map +0 -1
  425. package/dist/goal/types.d.ts.map +0 -1
  426. package/dist/hooks/http-executor.d.ts.map +0 -1
  427. package/dist/hooks/index.d.ts.map +0 -1
  428. package/dist/hooks/index.js.map +0 -7
  429. package/dist/hooks/registry.d.ts.map +0 -1
  430. package/dist/hooks/runner.d.ts.map +0 -1
  431. package/dist/hooks/shell-executor.d.ts.map +0 -1
  432. package/dist/hooks/shell-hooks-equal.d.ts.map +0 -1
  433. package/dist/hq/alerts.d.ts.map +0 -1
  434. package/dist/hq/auth-audit.d.ts.map +0 -1
  435. package/dist/hq/auth-store.d.ts.map +0 -1
  436. package/dist/hq/bootstrap-store.d.ts.map +0 -1
  437. package/dist/hq/brain-bridge.d.ts.map +0 -1
  438. package/dist/hq/bridge-context.d.ts.map +0 -1
  439. package/dist/hq/commands.d.ts.map +0 -1
  440. package/dist/hq/cost-bridge.d.ts.map +0 -1
  441. package/dist/hq/exposure.d.ts.map +0 -1
  442. package/dist/hq/factory.d.ts.map +0 -1
  443. package/dist/hq/fleet-bridge.d.ts.map +0 -1
  444. package/dist/hq/index.d.ts.map +0 -1
  445. package/dist/hq/index.js.map +0 -7
  446. package/dist/hq/kanban-store.d.ts.map +0 -1
  447. package/dist/hq/mailbox-mapper.d.ts.map +0 -1
  448. package/dist/hq/persistence/event-log.d.ts.map +0 -1
  449. package/dist/hq/persistence/jsonl-io.d.ts.map +0 -1
  450. package/dist/hq/persistence/simple-log.d.ts.map +0 -1
  451. package/dist/hq/persistence/snapshot-store.d.ts.map +0 -1
  452. package/dist/hq/persistence/timeseries-store.d.ts.map +0 -1
  453. package/dist/hq/persistence.d.ts.map +0 -1
  454. package/dist/hq/protocol/brain.d.ts.map +0 -1
  455. package/dist/hq/protocol/browser.d.ts.map +0 -1
  456. package/dist/hq/protocol/client.d.ts.map +0 -1
  457. package/dist/hq/protocol/core.d.ts.map +0 -1
  458. package/dist/hq/protocol/fleet.d.ts.map +0 -1
  459. package/dist/hq/protocol/kanban.d.ts.map +0 -1
  460. package/dist/hq/protocol/mailbox.d.ts.map +0 -1
  461. package/dist/hq/protocol/mcp.d.ts.map +0 -1
  462. package/dist/hq/protocol/project.d.ts.map +0 -1
  463. package/dist/hq/protocol/session.d.ts.map +0 -1
  464. package/dist/hq/protocol/tool.d.ts.map +0 -1
  465. package/dist/hq/protocol.d.ts.map +0 -1
  466. package/dist/hq/publisher.d.ts.map +0 -1
  467. package/dist/hq/redaction.d.ts.map +0 -1
  468. package/dist/hq/session-bridge.d.ts.map +0 -1
  469. package/dist/hq/tool-bridge.d.ts.map +0 -1
  470. package/dist/hq/transcript-mapper.d.ts.map +0 -1
  471. package/dist/hq/worktree-bridge.d.ts.map +0 -1
  472. package/dist/hq/write-queues.d.ts.map +0 -1
  473. package/dist/index.d.ts.map +0 -1
  474. package/dist/index.js.map +0 -7
  475. package/dist/infrastructure/context-manager.d.ts.map +0 -1
  476. package/dist/infrastructure/index.d.ts.map +0 -1
  477. package/dist/infrastructure/index.js.map +0 -7
  478. package/dist/infrastructure/logger.d.ts.map +0 -1
  479. package/dist/infrastructure/mcp-servers.d.ts.map +0 -1
  480. package/dist/infrastructure/path-resolver.d.ts.map +0 -1
  481. package/dist/infrastructure/provider-cache-ledger.d.ts.map +0 -1
  482. package/dist/infrastructure/token-counter.d.ts.map +0 -1
  483. package/dist/kernel/container.d.ts.map +0 -1
  484. package/dist/kernel/events/agent-events.d.ts.map +0 -1
  485. package/dist/kernel/events/brain-events.d.ts.map +0 -1
  486. package/dist/kernel/events/file-events.d.ts.map +0 -1
  487. package/dist/kernel/events/fleet-events.d.ts.map +0 -1
  488. package/dist/kernel/events/memory-events.d.ts.map +0 -1
  489. package/dist/kernel/events/network-events.d.ts.map +0 -1
  490. package/dist/kernel/events/process-events.d.ts.map +0 -1
  491. package/dist/kernel/events/provider-events.d.ts.map +0 -1
  492. package/dist/kernel/events/sdd-events.d.ts.map +0 -1
  493. package/dist/kernel/events/session-events.d.ts.map +0 -1
  494. package/dist/kernel/events/tool-events.d.ts.map +0 -1
  495. package/dist/kernel/events/worktree-events.d.ts.map +0 -1
  496. package/dist/kernel/events.d.ts.map +0 -1
  497. package/dist/kernel/index.d.ts.map +0 -1
  498. package/dist/kernel/index.js.map +0 -7
  499. package/dist/kernel/pipeline.d.ts.map +0 -1
  500. package/dist/kernel/run-controller.d.ts.map +0 -1
  501. package/dist/kernel/tokens.d.ts.map +0 -1
  502. package/dist/mailbox-attach.d.ts.map +0 -1
  503. package/dist/middleware/collab-pause.d.ts.map +0 -1
  504. package/dist/models/alibaba-token-plan-catalog.d.ts.map +0 -1
  505. package/dist/models/codex-catalog.d.ts.map +0 -1
  506. package/dist/models/index.d.ts.map +0 -1
  507. package/dist/models/index.js.map +0 -7
  508. package/dist/models/llm-selector.d.ts.map +0 -1
  509. package/dist/models/mode-store.d.ts.map +0 -1
  510. package/dist/models/model-intelligence.d.ts.map +0 -1
  511. package/dist/models/model-router.d.ts.map +0 -1
  512. package/dist/models/models-registry.d.ts.map +0 -1
  513. package/dist/models/provider-model-resolve.d.ts.map +0 -1
  514. package/dist/notifications/index.d.ts.map +0 -1
  515. package/dist/notifications/index.js.map +0 -7
  516. package/dist/notifications/notifier-impl.d.ts.map +0 -1
  517. package/dist/notifications/notifier.d.ts.map +0 -1
  518. package/dist/notifications/types.d.ts.map +0 -1
  519. package/dist/observability/event-bridge.d.ts.map +0 -1
  520. package/dist/observability/health.d.ts.map +0 -1
  521. package/dist/observability/index.d.ts.map +0 -1
  522. package/dist/observability/index.js.map +0 -7
  523. package/dist/observability/metrics.d.ts.map +0 -1
  524. package/dist/observability/network-telemetry.d.ts.map +0 -1
  525. package/dist/observability/otel-tracer.d.ts.map +0 -1
  526. package/dist/observability/otlp-metrics.d.ts.map +0 -1
  527. package/dist/observability/otlp-traces.d.ts.map +0 -1
  528. package/dist/observability/process-telemetry.d.ts.map +0 -1
  529. package/dist/observability/prometheus.d.ts.map +0 -1
  530. package/dist/observability/redact-command.d.ts.map +0 -1
  531. package/dist/observability/tracer.d.ts.map +0 -1
  532. package/dist/plugin/api.d.ts.map +0 -1
  533. package/dist/plugin/config.d.ts.map +0 -1
  534. package/dist/plugin/index.d.ts.map +0 -1
  535. package/dist/plugin/index.js.map +0 -7
  536. package/dist/plugin/loader.d.ts.map +0 -1
  537. package/dist/plugins/auto-review-plugin.d.ts.map +0 -1
  538. package/dist/plugins/chimera-plugin.d.ts.map +0 -1
  539. package/dist/plugins/prompts-plugin.d.ts.map +0 -1
  540. package/dist/plugins/review-claim-registry.d.ts.map +0 -1
  541. package/dist/plugins/review-context-builder.d.ts.map +0 -1
  542. package/dist/plugins/review-finding-commands.d.ts.map +0 -1
  543. package/dist/plugins/review-finding-integration.d.ts.map +0 -1
  544. package/dist/plugins/review-finding-parser.d.ts.map +0 -1
  545. package/dist/plugins/review-finding-store.d.ts.map +0 -1
  546. package/dist/plugins/review-finding-types.d.ts.map +0 -1
  547. package/dist/plugins/review-report-integration.d.ts.map +0 -1
  548. package/dist/plugins/review-report-store.d.ts.map +0 -1
  549. package/dist/plugins/review-report-types.d.ts.map +0 -1
  550. package/dist/plugins/review-types.d.ts.map +0 -1
  551. package/dist/plugins/skills-plugin.d.ts.map +0 -1
  552. package/dist/plugins/sync-plugin.d.ts.map +0 -1
  553. package/dist/prompts/index.d.ts.map +0 -1
  554. package/dist/prompts/prompt-installer.d.ts.map +0 -1
  555. package/dist/prompts/prompt-manifest-store.d.ts.map +0 -1
  556. package/dist/registry/index.d.ts.map +0 -1
  557. package/dist/registry/index.js.map +0 -7
  558. package/dist/registry/provider-registry.d.ts.map +0 -1
  559. package/dist/registry/slash-command-registry.d.ts.map +0 -1
  560. package/dist/registry/tool-registry.d.ts.map +0 -1
  561. package/dist/replay/hash.d.ts.map +0 -1
  562. package/dist/replay/index.d.ts.map +0 -1
  563. package/dist/replay/index.js.map +0 -7
  564. package/dist/replay/replay-provider-runner.d.ts.map +0 -1
  565. package/dist/security/capabilities.d.ts.map +0 -1
  566. package/dist/security/config-secrets.d.ts.map +0 -1
  567. package/dist/security/directory-permission-policy.d.ts.map +0 -1
  568. package/dist/security/directory-policy-schema.d.ts.map +0 -1
  569. package/dist/security/index.d.ts.map +0 -1
  570. package/dist/security/index.js.map +0 -7
  571. package/dist/security/kanban-boundary.d.ts.map +0 -1
  572. package/dist/security/permission-policy-schema.d.ts.map +0 -1
  573. package/dist/security/permission-policy.d.ts.map +0 -1
  574. package/dist/security/readonly-permission-policy.d.ts.map +0 -1
  575. package/dist/security/secret-scrubber.d.ts.map +0 -1
  576. package/dist/security/secret-vault.d.ts.map +0 -1
  577. package/dist/security/trust-boundary.d.ts.map +0 -1
  578. package/dist/security/yolo-risk.d.ts.map +0 -1
  579. package/dist/session-registry-atomic-file.d.ts.map +0 -1
  580. package/dist/session-registry-types.d.ts.map +0 -1
  581. package/dist/session-registry.d.ts.map +0 -1
  582. package/dist/skills/foreign-sources.d.ts.map +0 -1
  583. package/dist/skills/frontmatter.d.ts.map +0 -1
  584. package/dist/skills/github-fetcher.d.ts.map +0 -1
  585. package/dist/skills/index.d.ts.map +0 -1
  586. package/dist/skills/index.js.map +0 -7
  587. package/dist/skills/limits.d.ts.map +0 -1
  588. package/dist/skills/manifest-store.d.ts.map +0 -1
  589. package/dist/skills/registry/github-direct-adapter.d.ts.map +0 -1
  590. package/dist/skills/registry/registry-adapter.d.ts.map +0 -1
  591. package/dist/skills/registry/skills-sh-adapter.d.ts.map +0 -1
  592. package/dist/skills/skill-generator.d.ts.map +0 -1
  593. package/dist/skills/skill-installer.d.ts.map +0 -1
  594. package/dist/storage/annotations-store.d.ts.map +0 -1
  595. package/dist/storage/attachment-store.d.ts.map +0 -1
  596. package/dist/storage/cloud-sync.d.ts.map +0 -1
  597. package/dist/storage/completed-work-checkpoint.d.ts.map +0 -1
  598. package/dist/storage/config-loader/bootstrap.d.ts.map +0 -1
  599. package/dist/storage/config-loader/default-repair.d.ts.map +0 -1
  600. package/dist/storage/config-loader/defaults.d.ts.map +0 -1
  601. package/dist/storage/config-loader/diagnostics.d.ts.map +0 -1
  602. package/dist/storage/config-loader/env-overrides.d.ts.map +0 -1
  603. package/dist/storage/config-loader/in-project-policy.d.ts.map +0 -1
  604. package/dist/storage/config-loader/inline-provider-models.d.ts.map +0 -1
  605. package/dist/storage/config-loader/legacy-sage-migration.d.ts.map +0 -1
  606. package/dist/storage/config-loader/path-identity.d.ts.map +0 -1
  607. package/dist/storage/config-loader/types.d.ts.map +0 -1
  608. package/dist/storage/config-loader/validation.d.ts.map +0 -1
  609. package/dist/storage/config-loader.d.ts.map +0 -1
  610. package/dist/storage/config-migration.d.ts.map +0 -1
  611. package/dist/storage/config-store.d.ts.map +0 -1
  612. package/dist/storage/director-state.d.ts.map +0 -1
  613. package/dist/storage/file-session-writer.d.ts.map +0 -1
  614. package/dist/storage/goal-coordination.d.ts.map +0 -1
  615. package/dist/storage/goal-kanban.d.ts.map +0 -1
  616. package/dist/storage/goal-store.d.ts.map +0 -1
  617. package/dist/storage/index.d.ts.map +0 -1
  618. package/dist/storage/index.js.map +0 -7
  619. package/dist/storage/input-history-store.d.ts.map +0 -1
  620. package/dist/storage/memory-backend.d.ts.map +0 -1
  621. package/dist/storage/memory-consolidator.d.ts.map +0 -1
  622. package/dist/storage/memory-graph-backend.d.ts.map +0 -1
  623. package/dist/storage/plan-store.d.ts.map +0 -1
  624. package/dist/storage/plan-templates.d.ts.map +0 -1
  625. package/dist/storage/prompt-store.d.ts.map +0 -1
  626. package/dist/storage/prompt-usage-store.d.ts.map +0 -1
  627. package/dist/storage/provider-config-watcher.d.ts.map +0 -1
  628. package/dist/storage/queue-store.d.ts.map +0 -1
  629. package/dist/storage/recovery-lock.d.ts.map +0 -1
  630. package/dist/storage/replay-log-store.d.ts.map +0 -1
  631. package/dist/storage/session-analyzer.d.ts.map +0 -1
  632. package/dist/storage/session-checkpoint-cas.d.ts.map +0 -1
  633. package/dist/storage/session-event-bridge.d.ts.map +0 -1
  634. package/dist/storage/session-helpers.d.ts.map +0 -1
  635. package/dist/storage/session-id-resolver.d.ts.map +0 -1
  636. package/dist/storage/session-id.d.ts.map +0 -1
  637. package/dist/storage/session-read-scrubber.d.ts.map +0 -1
  638. package/dist/storage/session-reader.d.ts.map +0 -1
  639. package/dist/storage/session-recovery.d.ts.map +0 -1
  640. package/dist/storage/session-resume-validation.d.ts.map +0 -1
  641. package/dist/storage/session-rewind-apply.d.ts.map +0 -1
  642. package/dist/storage/session-rewinder.d.ts.map +0 -1
  643. package/dist/storage/session-store/delete-session-artifacts.d.ts.map +0 -1
  644. package/dist/storage/session-store/delete-session-guards.d.ts.map +0 -1
  645. package/dist/storage/session-store/directory-scan.d.ts.map +0 -1
  646. package/dist/storage/session-store/directory-session-files.d.ts.map +0 -1
  647. package/dist/storage/session-store/events.d.ts.map +0 -1
  648. package/dist/storage/session-store/fork-session.d.ts.map +0 -1
  649. package/dist/storage/session-store/index-reader.d.ts.map +0 -1
  650. package/dist/storage/session-store/load-cache.d.ts.map +0 -1
  651. package/dist/storage/session-store/load-session-data.d.ts.map +0 -1
  652. package/dist/storage/session-store/paths.d.ts.map +0 -1
  653. package/dist/storage/session-store/prune-helpers.d.ts.map +0 -1
  654. package/dist/storage/session-store/replay.d.ts.map +0 -1
  655. package/dist/storage/session-store/search-events.d.ts.map +0 -1
  656. package/dist/storage/session-store/shard-manifest.d.ts.map +0 -1
  657. package/dist/storage/session-store/summary-builder.d.ts.map +0 -1
  658. package/dist/storage/session-store/summary-header.d.ts.map +0 -1
  659. package/dist/storage/session-store/types.d.ts.map +0 -1
  660. package/dist/storage/session-store.d.ts.map +0 -1
  661. package/dist/storage/session-summary.d.ts.map +0 -1
  662. package/dist/storage/session-tool-call-ends.d.ts.map +0 -1
  663. package/dist/storage/session-writer-scrubber.d.ts.map +0 -1
  664. package/dist/storage/session-writer-truncate.d.ts.map +0 -1
  665. package/dist/storage/storage-concurrency.d.ts.map +0 -1
  666. package/dist/storage/task-store.d.ts.map +0 -1
  667. package/dist/storage/todos-checkpoint.d.ts.map +0 -1
  668. package/dist/storage/tool-audit-log.d.ts.map +0 -1
  669. package/dist/tasking/index.d.ts.map +0 -1
  670. package/dist/tasking/index.js.map +0 -7
  671. package/dist/tasking/task-store.d.ts.map +0 -1
  672. package/dist/tasking/task-tracker.d.ts.map +0 -1
  673. package/dist/tools/council-tool.d.ts.map +0 -1
  674. package/dist/tools/fallback-chain-manage-tool.d.ts.map +0 -1
  675. package/dist/tools/fallback-favorite-manage-tool.d.ts.map +0 -1
  676. package/dist/tools/fallback-manage-helpers.d.ts.map +0 -1
  677. package/dist/tools/fallback-manage-tool-options.d.ts.map +0 -1
  678. package/dist/tools/fallback-manage-tools.d.ts.map +0 -1
  679. package/dist/tools/fallback-model-ref-parse.d.ts.map +0 -1
  680. package/dist/tools/fallback-provider-key-store.d.ts.map +0 -1
  681. package/dist/tools/fallback-system-config-view-tool.d.ts.map +0 -1
  682. package/dist/tools/index.d.ts.map +0 -1
  683. package/dist/tools/index.js.map +0 -7
  684. package/dist/tools/mcp-control.d.ts.map +0 -1
  685. package/dist/tools/mcp-use.d.ts.map +0 -1
  686. package/dist/tools/one-shot-llm-tool.d.ts.map +0 -1
  687. package/dist/tools/plugin-manager.d.ts.map +0 -1
  688. package/dist/types/agent-bridge.d.ts.map +0 -1
  689. package/dist/types/attachment.d.ts.map +0 -1
  690. package/dist/types/autonomy.d.ts.map +0 -1
  691. package/dist/types/blocks.d.ts.map +0 -1
  692. package/dist/types/compactor.d.ts.map +0 -1
  693. package/dist/types/config/autonomy.d.ts.map +0 -1
  694. package/dist/types/config/context.d.ts.map +0 -1
  695. package/dist/types/config/fleet-chat.d.ts.map +0 -1
  696. package/dist/types/config/mcp-features.d.ts.map +0 -1
  697. package/dist/types/config/providers.d.ts.map +0 -1
  698. package/dist/types/config/root.d.ts.map +0 -1
  699. package/dist/types/config/runtime.d.ts.map +0 -1
  700. package/dist/types/config/skills-fleet-brain.d.ts.map +0 -1
  701. package/dist/types/config/tools.d.ts.map +0 -1
  702. package/dist/types/config.d.ts.map +0 -1
  703. package/dist/types/context-evidence.d.ts.map +0 -1
  704. package/dist/types/context-window.d.ts.map +0 -1
  705. package/dist/types/council.d.ts.map +0 -1
  706. package/dist/types/default-config.d.ts.map +0 -1
  707. package/dist/types/design-kit.d.ts.map +0 -1
  708. package/dist/types/error-handler.d.ts.map +0 -1
  709. package/dist/types/errors.d.ts.map +0 -1
  710. package/dist/types/file-event-record.d.ts.map +0 -1
  711. package/dist/types/hooks.d.ts.map +0 -1
  712. package/dist/types/index.d.ts.map +0 -1
  713. package/dist/types/index.js.map +0 -7
  714. package/dist/types/input-reader.d.ts.map +0 -1
  715. package/dist/types/logger.d.ts.map +0 -1
  716. package/dist/types/memory.d.ts.map +0 -1
  717. package/dist/types/messages.d.ts.map +0 -1
  718. package/dist/types/mode-prompts.d.ts.map +0 -1
  719. package/dist/types/mode.d.ts.map +0 -1
  720. package/dist/types/models-registry.d.ts.map +0 -1
  721. package/dist/types/multi-agent.d.ts.map +0 -1
  722. package/dist/types/observability.d.ts.map +0 -1
  723. package/dist/types/one-shot-llm.d.ts.map +0 -1
  724. package/dist/types/path-resolver.d.ts.map +0 -1
  725. package/dist/types/permission.d.ts.map +0 -1
  726. package/dist/types/plugin.d.ts.map +0 -1
  727. package/dist/types/prompt-registry.d.ts.map +0 -1
  728. package/dist/types/prompt.d.ts.map +0 -1
  729. package/dist/types/provider-runner.d.ts.map +0 -1
  730. package/dist/types/provider.d.ts.map +0 -1
  731. package/dist/types/quota-regex.d.ts.map +0 -1
  732. package/dist/types/renderer.d.ts.map +0 -1
  733. package/dist/types/retry-policy.d.ts.map +0 -1
  734. package/dist/types/secret-scrubber.d.ts.map +0 -1
  735. package/dist/types/secret-vault.d.ts.map +0 -1
  736. package/dist/types/selector.d.ts.map +0 -1
  737. package/dist/types/session-markers.d.ts.map +0 -1
  738. package/dist/types/session-markers.js.map +0 -7
  739. package/dist/types/session-reader.d.ts.map +0 -1
  740. package/dist/types/session-rewinder.d.ts.map +0 -1
  741. package/dist/types/session.d.ts.map +0 -1
  742. package/dist/types/side-effect.d.ts.map +0 -1
  743. package/dist/types/skill.d.ts.map +0 -1
  744. package/dist/types/slash-command.d.ts.map +0 -1
  745. package/dist/types/spec.d.ts.map +0 -1
  746. package/dist/types/system-prompt-contributor.d.ts.map +0 -1
  747. package/dist/types/system-prompt.d.ts.map +0 -1
  748. package/dist/types/task-graph.d.ts.map +0 -1
  749. package/dist/types/token-counter.d.ts.map +0 -1
  750. package/dist/types/tool-executor.d.ts.map +0 -1
  751. package/dist/types/tool-markers.d.ts.map +0 -1
  752. package/dist/types/tool.d.ts.map +0 -1
  753. package/dist/types/utility-types.d.ts.map +0 -1
  754. package/dist/utils/assert-never.d.ts.map +0 -1
  755. package/dist/utils/atomic-write.d.ts.map +0 -1
  756. package/dist/utils/cache-key.d.ts.map +0 -1
  757. package/dist/utils/child-env.d.ts.map +0 -1
  758. package/dist/utils/color.d.ts.map +0 -1
  759. package/dist/utils/compaction-preview.d.ts.map +0 -1
  760. package/dist/utils/config-backup.d.ts.map +0 -1
  761. package/dist/utils/config-json.d.ts.map +0 -1
  762. package/dist/utils/connectivity.d.ts.map +0 -1
  763. package/dist/utils/context-breakdown.d.ts.map +0 -1
  764. package/dist/utils/context-evidence.d.ts.map +0 -1
  765. package/dist/utils/crash-shield.d.ts.map +0 -1
  766. package/dist/utils/deep-merge.d.ts.map +0 -1
  767. package/dist/utils/diff.d.ts.map +0 -1
  768. package/dist/utils/error.d.ts.map +0 -1
  769. package/dist/utils/error.js.map +0 -7
  770. package/dist/utils/expect-defined.d.ts.map +0 -1
  771. package/dist/utils/expect-defined.js.map +0 -7
  772. package/dist/utils/glob-expand.d.ts.map +0 -1
  773. package/dist/utils/glob-match.d.ts.map +0 -1
  774. package/dist/utils/heap-watchdog.d.ts.map +0 -1
  775. package/dist/utils/heap-watchdog.js.map +0 -7
  776. package/dist/utils/incoming-images.d.ts.map +0 -1
  777. package/dist/utils/index.d.ts.map +0 -1
  778. package/dist/utils/index.js.map +0 -7
  779. package/dist/utils/instruction-file.d.ts.map +0 -1
  780. package/dist/utils/ip-guard.d.ts.map +0 -1
  781. package/dist/utils/json-repair.d.ts.map +0 -1
  782. package/dist/utils/json-schema-validate.d.ts.map +0 -1
  783. package/dist/utils/lru-cache.d.ts.map +0 -1
  784. package/dist/utils/merge-custom-models.d.ts.map +0 -1
  785. package/dist/utils/merge-models-payload.d.ts.map +0 -1
  786. package/dist/utils/message-invariants.d.ts.map +0 -1
  787. package/dist/utils/newline-normalize.d.ts.map +0 -1
  788. package/dist/utils/perf-profile.d.ts.map +0 -1
  789. package/dist/utils/pid.d.ts.map +0 -1
  790. package/dist/utils/project-identity.d.ts.map +0 -1
  791. package/dist/utils/project-watch.d.ts.map +0 -1
  792. package/dist/utils/regex-guard.d.ts.map +0 -1
  793. package/dist/utils/safe-json.d.ts.map +0 -1
  794. package/dist/utils/sage-output-block.d.ts.map +0 -1
  795. package/dist/utils/session-scoped-path.d.ts.map +0 -1
  796. package/dist/utils/sleep.d.ts.map +0 -1
  797. package/dist/utils/slug.d.ts.map +0 -1
  798. package/dist/utils/socket-path.d.ts.map +0 -1
  799. package/dist/utils/sqlite-warning.d.ts.map +0 -1
  800. package/dist/utils/string.d.ts.map +0 -1
  801. package/dist/utils/task-format.d.ts.map +0 -1
  802. package/dist/utils/term.d.ts.map +0 -1
  803. package/dist/utils/todos-format.d.ts.map +0 -1
  804. package/dist/utils/token-estimate.d.ts.map +0 -1
  805. package/dist/utils/tool-description-mode.d.ts.map +0 -1
  806. package/dist/utils/tool-output-serializer.d.ts.map +0 -1
  807. package/dist/utils/tool-result-render-mode.d.ts.map +0 -1
  808. package/dist/utils/tool-subject.d.ts.map +0 -1
  809. package/dist/utils/tool-wire-compact.d.ts.map +0 -1
  810. package/dist/utils/tree-kill.d.ts.map +0 -1
  811. package/dist/utils/tree-kill.js.map +0 -7
  812. package/dist/utils/ulid.d.ts.map +0 -1
  813. package/dist/utils/walk-ignore.d.ts.map +0 -1
  814. package/dist/utils/wstack-paths.d.ts.map +0 -1
  815. package/dist/worktree/index.d.ts.map +0 -1
  816. package/dist/worktree/index.js.map +0 -7
  817. package/dist/worktree/worktree-git.d.ts.map +0 -1
  818. package/dist/worktree/worktree-managed-ops.d.ts.map +0 -1
  819. package/dist/worktree/worktree-manager.d.ts.map +0 -1
  820. package/dist/worktree/worktree-types.d.ts.map +0 -1
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/coordination/mailbox-project-server.ts
4
- import * as fs4 from "node:fs";
4
+ import { randomBytes as randomBytes2 } from "node:crypto";
5
+ import * as fs5 from "node:fs";
5
6
  import * as fsPromises from "node:fs/promises";
6
7
  import * as net from "node:net";
7
- import * as path4 from "node:path";
8
+ import * as path7 from "node:path";
8
9
 
9
10
  // src/kernel/events.ts
10
11
  var MAX_WILDCARDS = 500;
@@ -250,12 +251,899 @@ function makePatternMatcher(pattern) {
250
251
  return (e) => e === pattern;
251
252
  }
252
253
 
254
+ // src/utils/atomic-write.ts
255
+ import {
256
+ createPersistencePrimitives
257
+ } from "@wrongstack/persistence";
258
+
259
+ // src/types/errors.ts
260
+ var ERROR_CODES = {
261
+ // Provider
262
+ PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
263
+ PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
264
+ PROVIDER_OVERLOADED: "PROVIDER_OVERLOADED",
265
+ PROVIDER_INVALID_REQUEST: "PROVIDER_INVALID_REQUEST",
266
+ PROVIDER_SERVER_ERROR: "PROVIDER_SERVER_ERROR",
267
+ PROVIDER_NETWORK_ERROR: "PROVIDER_NETWORK_ERROR",
268
+ PROVIDER_CONTEXT_OVERFLOW: "PROVIDER_CONTEXT_OVERFLOW",
269
+ // Tool
270
+ TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
271
+ TOOL_PERMISSION_DENIED: "TOOL_PERMISSION_DENIED",
272
+ TOOL_EXECUTION_FAILED: "TOOL_EXECUTION_FAILED",
273
+ TOOL_TIMEOUT: "TOOL_TIMEOUT",
274
+ TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
275
+ // Config
276
+ CONFIG_INVALID: "CONFIG_INVALID",
277
+ CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND",
278
+ CONFIG_PARSE_FAILED: "CONFIG_PARSE_FAILED",
279
+ CONFIG_MIGRATION_NEEDED: "CONFIG_MIGRATION_NEEDED",
280
+ // Plugin
281
+ PLUGIN_LOAD_FAILED: "PLUGIN_LOAD_FAILED",
282
+ PLUGIN_API_MISMATCH: "PLUGIN_API_MISMATCH",
283
+ PLUGIN_MISSING_DEPENDENCY: "PLUGIN_MISSING_DEPENDENCY",
284
+ // Agent
285
+ AGENT_ITERATION_LIMIT: "AGENT_ITERATION_LIMIT",
286
+ AGENT_CONTEXT_OVERFLOW: "AGENT_CONTEXT_OVERFLOW",
287
+ AGENT_ABORTED: "AGENT_ABORTED",
288
+ AGENT_RUN_FAILED: "AGENT_RUN_FAILED",
289
+ // Session
290
+ SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
291
+ SESSION_CORRUPTED: "SESSION_CORRUPTED",
292
+ SESSION_WRITE_FAILED: "SESSION_WRITE_FAILED",
293
+ // Container / Registry
294
+ CONTAINER_TOKEN_ALREADY_BOUND: "CONTAINER_TOKEN_ALREADY_BOUND",
295
+ CONTAINER_TOKEN_NOT_BOUND: "CONTAINER_TOKEN_NOT_BOUND",
296
+ CONTAINER_CIRCULAR_DEPENDENCY: "CONTAINER_CIRCULAR_DEPENDENCY",
297
+ REGISTRY_DUPLICATE: "REGISTRY_DUPLICATE",
298
+ REGISTRY_NOT_FOUND: "REGISTRY_NOT_FOUND",
299
+ REGISTRY_INVALID: "REGISTRY_INVALID",
300
+ // File system
301
+ FS_READ_FAILED: "FS_READ_FAILED",
302
+ FS_WRITE_FAILED: "FS_WRITE_FAILED",
303
+ FS_MKDIR_FAILED: "FS_MKDIR_FAILED",
304
+ FS_DELETE_FAILED: "FS_DELETE_FAILED",
305
+ FS_ATOMIC_WRITE_FAILED: "FS_ATOMIC_WRITE_FAILED",
306
+ // SDD (Spec-Driven Development)
307
+ SDD_VALIDATION_FAILED: "SDD_VALIDATION_FAILED",
308
+ SDD_PARSE_FAILED: "SDD_PARSE_FAILED",
309
+ SDD_INVALID_STATE: "SDD_INVALID_STATE",
310
+ SDD_NOT_READY: "SDD_NOT_READY",
311
+ // General
312
+ VALIDATION_ERROR: "VALIDATION_ERROR",
313
+ PARSE_FAILED: "PARSE_FAILED",
314
+ UNKNOWN: "UNKNOWN"
315
+ };
316
+ var WrongStackError = class extends Error {
317
+ code;
318
+ subsystem;
319
+ severity;
320
+ recoverable;
321
+ context;
322
+ constructor(opts) {
323
+ super(opts.message, { cause: opts.cause });
324
+ this.name = "WrongStackError";
325
+ this.code = opts.code;
326
+ this.subsystem = opts.subsystem;
327
+ this.severity = opts.severity ?? "error";
328
+ this.recoverable = opts.recoverable ?? false;
329
+ this.context = opts.context;
330
+ }
331
+ /**
332
+ * Render a one-line user-facing description.
333
+ * Subclasses should override for domain-specific formatting.
334
+ */
335
+ describe() {
336
+ const ctx = this.context ? ` ${formatContext(this.context)}` : "";
337
+ return `${this.code}: ${this.message}${ctx}`;
338
+ }
339
+ };
340
+ function formatContext(ctx) {
341
+ const parts = Object.entries(ctx).filter(([, v]) => v !== void 0).slice(0, 3).map(([k, v]) => `${k}=${String(v)}`);
342
+ return parts.length > 0 ? `[${parts.join(" ")}]` : "";
343
+ }
344
+ var FsError = class extends WrongStackError {
345
+ path;
346
+ constructor(opts) {
347
+ super({
348
+ message: opts.message,
349
+ code: opts.code,
350
+ subsystem: "fs",
351
+ severity: "error",
352
+ recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,
353
+ context: { path: opts.path, ...opts.context },
354
+ cause: opts.cause
355
+ });
356
+ this.name = "FsError";
357
+ this.path = opts.path;
358
+ }
359
+ };
360
+
361
+ // src/utils/atomic-write.ts
362
+ var primitives = createPersistencePrimitives({
363
+ createLockTimeoutError: ({ targetPath, timeoutMs }) => new FsError({
364
+ message: `Timed out waiting for file lock: ${targetPath}`,
365
+ code: "FS_ATOMIC_WRITE_FAILED",
366
+ path: targetPath,
367
+ context: { timeoutMs }
368
+ })
369
+ });
370
+ var atomicWrite = primitives.atomicWrite;
371
+ var atomicReplaceWithWriter = primitives.atomicReplaceWithWriter;
372
+ var ensureDir = primitives.ensureDir;
373
+ var withFileLock = primitives.withFileLock;
374
+
375
+ // src/utils/heap-watchdog.ts
376
+ import * as fs from "node:fs";
377
+ import * as fsp2 from "node:fs/promises";
378
+ import * as path3 from "node:path";
379
+ import { PerformanceObserver, constants as performanceConstants } from "node:perf_hooks";
380
+ import * as v8 from "node:v8";
381
+
382
+ // src/utils/memory-flight-recorder.ts
383
+ import * as fsp from "node:fs/promises";
384
+ import * as path2 from "node:path";
385
+
386
+ // src/utils/continuous-memory-profiler.ts
387
+ import { Session } from "node:inspector/promises";
388
+ var DEFAULT_SAMPLE_INTERVAL_BYTES = 512 * 1024;
389
+ var DEFAULT_STACK_DEPTH = 64;
390
+ var MAX_SUMMARY_STACKS = 20;
391
+ var MAX_FRAMES_PER_STACK = 12;
392
+ function errorMessage(error) {
393
+ return error instanceof Error ? error.message : String(error);
394
+ }
395
+ function numeric(value) {
396
+ if (typeof value === "bigint") return Number(value);
397
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
398
+ }
399
+ function summarizePprof(profile) {
400
+ const strings = profile.stringTable.strings;
401
+ const functions = new Map(profile.function.map((entry) => [numeric(entry.id), entry]));
402
+ const locations = new Map(profile.location.map((entry) => [numeric(entry.id), entry]));
403
+ const stacks = /* @__PURE__ */ new Map();
404
+ let sampledBytes = 0;
405
+ let sampledObjects = 0;
406
+ for (const sample of profile.sample) {
407
+ const objects = numeric(sample.value[0]);
408
+ const bytes = numeric(sample.value[1]);
409
+ sampledObjects += objects;
410
+ sampledBytes += bytes;
411
+ const frames = sample.locationId.slice(0, MAX_FRAMES_PER_STACK).flatMap((locationId) => {
412
+ const location = locations.get(numeric(locationId));
413
+ const line = location?.line[0];
414
+ const fn = line ? functions.get(numeric(line.functionId)) : void 0;
415
+ if (!fn) return [];
416
+ const name = strings[numeric(fn.name)] || "(anonymous)";
417
+ const filename = strings[numeric(fn.filename)] || "";
418
+ const lineNumber = numeric(line?.line);
419
+ return [filename ? `${name} (${filename}${lineNumber > 0 ? `:${lineNumber}` : ""})` : name];
420
+ });
421
+ if (frames.length === 0) frames.push("(unknown)");
422
+ const key = frames.join("\n");
423
+ const existing = stacks.get(key);
424
+ if (existing) {
425
+ existing.bytes += bytes;
426
+ existing.objects += objects;
427
+ } else {
428
+ stacks.set(key, { bytes, objects, frames });
429
+ }
430
+ }
431
+ return {
432
+ sampledBytes,
433
+ sampledObjects,
434
+ sampleCount: profile.sample.length,
435
+ topStacks: [...stacks.values()].sort((left, right) => right.bytes - left.bytes).slice(0, MAX_SUMMARY_STACKS)
436
+ };
437
+ }
438
+ async function startDatadogProfiler() {
439
+ const pprof = await import("@datadog/pprof");
440
+ pprof.heap.start(DEFAULT_SAMPLE_INTERVAL_BYTES, DEFAULT_STACK_DEPTH);
441
+ let stopped = false;
442
+ return {
443
+ backend: "datadog-pprof",
444
+ capture: async () => {
445
+ if (stopped) throw new Error("Continuous memory profiler is stopped");
446
+ const profile = pprof.heap.profile();
447
+ return {
448
+ backend: "datadog-pprof",
449
+ data: await pprof.encode(profile),
450
+ extension: ".pb.gz",
451
+ summary: summarizePprof(profile)
452
+ };
453
+ },
454
+ stop: async () => {
455
+ if (stopped) return;
456
+ stopped = true;
457
+ pprof.heap.stop();
458
+ }
459
+ };
460
+ }
461
+ async function startInspectorProfiler() {
462
+ const session = new Session();
463
+ session.connect();
464
+ try {
465
+ await session.post("HeapProfiler.enable");
466
+ await session.post("HeapProfiler.startSampling", {
467
+ samplingInterval: DEFAULT_SAMPLE_INTERVAL_BYTES,
468
+ includeObjectsCollectedByMajorGC: false,
469
+ includeObjectsCollectedByMinorGC: false
470
+ });
471
+ } catch (error) {
472
+ try {
473
+ session.disconnect();
474
+ } catch {
475
+ }
476
+ throw error;
477
+ }
478
+ let stopped = false;
479
+ return {
480
+ backend: "node-inspector",
481
+ capture: async () => {
482
+ if (stopped) throw new Error("Continuous memory profiler is stopped");
483
+ const result = await session.post("HeapProfiler.stopSampling");
484
+ await session.post("HeapProfiler.startSampling", {
485
+ samplingInterval: DEFAULT_SAMPLE_INTERVAL_BYTES,
486
+ includeObjectsCollectedByMajorGC: false,
487
+ includeObjectsCollectedByMinorGC: false
488
+ });
489
+ return {
490
+ backend: "node-inspector",
491
+ data: JSON.stringify(result.profile),
492
+ extension: ".heapprofile"
493
+ };
494
+ },
495
+ stop: async () => {
496
+ if (stopped) return;
497
+ stopped = true;
498
+ try {
499
+ await session.post("HeapProfiler.disable");
500
+ } catch {
501
+ }
502
+ try {
503
+ session.disconnect();
504
+ } catch {
505
+ }
506
+ }
507
+ };
508
+ }
509
+ async function startContinuousMemoryProfiler() {
510
+ try {
511
+ return { profiler: await startDatadogProfiler() };
512
+ } catch (error) {
513
+ const fallbackReason = errorMessage(error);
514
+ return {
515
+ profiler: await startInspectorProfiler(),
516
+ fallbackReason
517
+ };
518
+ }
519
+ }
520
+
521
+ // src/utils/wstack-paths.ts
522
+ import * as os from "node:os";
523
+ import * as path from "node:path";
524
+ function wstackGlobalRoot() {
525
+ const fromEnv = process.env["WRONGSTACK_HOME"];
526
+ if (fromEnv && fromEnv.trim().length > 0) return path.resolve(fromEnv);
527
+ return path.join(os.homedir(), ".wrongstack");
528
+ }
529
+
530
+ // src/utils/memory-flight-recorder.ts
531
+ var MB = 1024 * 1024;
532
+ var HOUR_MS = 60 * 60 * 1e3;
533
+ var DEFAULT_WINDOW_MS = 5 * 60 * 1e3;
534
+ var DEFAULT_MINIMUM_WINDOW_MS = 2 * 60 * 1e3;
535
+ var DEFAULT_COOLDOWN_MS = 15 * 60 * 1e3;
536
+ var DEFAULT_CONTINUOUS_CAPTURE_MS = 5 * 60 * 1e3;
537
+ var MAX_OBSERVATIONS = 24;
538
+ var MAX_CAPTURE_SESSIONS = 12;
539
+ var MAX_CAPTURES_PER_SESSION = 6;
540
+ var SESSION_MAX_AGE_MS = 7 * 24 * HOUR_MS;
541
+ function timestampSlug(date = /* @__PURE__ */ new Date()) {
542
+ return date.toISOString().replaceAll(":", "").replaceAll(".", "-");
543
+ }
544
+ async function pruneCaptureFiles(artifactDir) {
545
+ const entries = await fsp.readdir(artifactDir, { withFileTypes: true });
546
+ const captures = entries.filter(
547
+ (entry) => entry.isFile() && entry.name.startsWith("event-") && entry.name.endsWith(".json")
548
+ ).map((entry) => entry.name).sort();
549
+ const remove = captures.slice(0, Math.max(0, captures.length - MAX_CAPTURES_PER_SESSION));
550
+ await Promise.all(
551
+ remove.flatMap((eventName) => {
552
+ const stem = eventName.slice("event-".length, -".json".length);
553
+ return [
554
+ fsp.rm(path2.join(artifactDir, eventName), { force: true }),
555
+ fsp.rm(path2.join(artifactDir, `allocations-${stem}.heapprofile`), { force: true }),
556
+ fsp.rm(path2.join(artifactDir, `allocations-${stem}.pb.gz`), { force: true })
557
+ ];
558
+ })
559
+ );
560
+ }
561
+ async function pruneOldSessions(root, currentDir) {
562
+ const entries = await fsp.readdir(root, { withFileTypes: true });
563
+ const sessions = await Promise.all(
564
+ entries.filter((entry) => entry.isDirectory() && entry.name !== path2.basename(currentDir)).map(async (entry) => {
565
+ const fullPath = path2.join(root, entry.name);
566
+ const stat2 = await fsp.stat(fullPath);
567
+ return { fullPath, mtimeMs: stat2.mtimeMs };
568
+ })
569
+ );
570
+ sessions.sort((a, b) => b.mtimeMs - a.mtimeMs);
571
+ const now = Date.now();
572
+ await Promise.all(
573
+ sessions.filter(
574
+ (session, index) => now - session.mtimeMs > SESSION_MAX_AGE_MS || index >= MAX_CAPTURE_SESSIONS && now - session.mtimeMs > 24 * HOUR_MS
575
+ ).map((session) => fsp.rm(session.fullPath, { recursive: true, force: true }))
576
+ );
577
+ }
578
+ var ContinuousMemoryCaptureWriter = class {
579
+ artifactDir;
580
+ root;
581
+ ready;
582
+ profiler;
583
+ profilerBackend = "initializing";
584
+ fallbackReason;
585
+ startError;
586
+ lastSummary;
587
+ stopped = false;
588
+ constructor(root) {
589
+ this.root = root;
590
+ this.artifactDir = path2.join(root, `${timestampSlug()}-pid-${process.pid}`);
591
+ this.ready = this.start().catch((error) => {
592
+ this.startError = error instanceof Error ? error.message : String(error);
593
+ this.profilerBackend = "unavailable";
594
+ });
595
+ }
596
+ async start() {
597
+ const started = await startContinuousMemoryProfiler();
598
+ this.profiler = started.profiler;
599
+ this.profilerBackend = started.profiler.backend;
600
+ this.fallbackReason = started.fallbackReason;
601
+ }
602
+ diagnostics() {
603
+ return {
604
+ memoryProfilerBackend: this.profilerBackend,
605
+ ...this.fallbackReason ? { memoryProfilerFallbackReason: this.fallbackReason } : {},
606
+ ...this.startError ? { memoryProfilerStartError: this.startError } : {},
607
+ ...this.lastSummary ? {
608
+ memoryProfileSampledBytes: this.lastSummary.sampledBytes,
609
+ memoryProfileSampledObjects: this.lastSummary.sampledObjects,
610
+ memoryProfileSampleCount: this.lastSummary.sampleCount,
611
+ memoryProfileTopStack: this.lastSummary.topStack,
612
+ memoryProfileTopStackBytes: this.lastSummary.topStackBytes
613
+ } : {}
614
+ };
615
+ }
616
+ async capture(event) {
617
+ await this.ready;
618
+ if (this.stopped) return;
619
+ let profile;
620
+ let captureError = this.startError;
621
+ if (!captureError && this.profiler) {
622
+ try {
623
+ profile = await this.profiler.capture();
624
+ const top = profile.summary?.topStacks[0];
625
+ if (profile.summary) {
626
+ this.lastSummary = {
627
+ sampledBytes: profile.summary.sampledBytes,
628
+ sampledObjects: profile.summary.sampledObjects,
629
+ sampleCount: profile.summary.sampleCount,
630
+ topStack: top?.frames.join(" <- "),
631
+ topStackBytes: top?.bytes
632
+ };
633
+ }
634
+ } catch (error) {
635
+ captureError = error instanceof Error ? error.message : String(error);
636
+ }
637
+ }
638
+ await fsp.mkdir(this.artifactDir, { recursive: true });
639
+ const stem = `${timestampSlug(new Date(event.capturedAt))}-${event.reason}`;
640
+ await fsp.writeFile(
641
+ path2.join(this.artifactDir, `event-${stem}.json`),
642
+ `${JSON.stringify(
643
+ {
644
+ ...event,
645
+ profilerBackend: profile?.backend ?? this.profilerBackend,
646
+ ...profile?.summary ? { allocationSummary: profile.summary } : {},
647
+ ...this.fallbackReason ? { profilerFallbackReason: this.fallbackReason } : {},
648
+ ...captureError ? { captureError } : {}
649
+ },
650
+ null,
651
+ 2
652
+ )}
653
+ `,
654
+ "utf8"
655
+ );
656
+ if (profile) {
657
+ await fsp.writeFile(
658
+ path2.join(this.artifactDir, `allocations-${stem}${profile.extension}`),
659
+ profile.data
660
+ );
661
+ }
662
+ await Promise.all([
663
+ pruneCaptureFiles(this.artifactDir),
664
+ fsp.mkdir(this.root, { recursive: true }).then(() => pruneOldSessions(this.root, this.artifactDir))
665
+ ]);
666
+ }
667
+ async stop() {
668
+ if (this.stopped) return;
669
+ this.stopped = true;
670
+ await this.ready;
671
+ await this.profiler?.stop();
672
+ }
673
+ };
674
+ function disabledWriter(artifactDir) {
675
+ return {
676
+ artifactDir,
677
+ capture: async () => void 0,
678
+ stop: async () => void 0
679
+ };
680
+ }
681
+ function createMemoryFlightRecorder(options = {}) {
682
+ const now = options.now ?? Date.now;
683
+ const startedAt2 = now();
684
+ const root = options.diagnosticsRoot ?? path2.join(wstackGlobalRoot(), "diagnostics", "memory");
685
+ const enabled = options.enabled ?? (process.env["WRONGSTACK_MEMORY_FLIGHT_RECORDER"] !== "0" && process.env["NODE_ENV"] !== "test");
686
+ const writer = options.captureWriter ?? (enabled ? new ContinuousMemoryCaptureWriter(root) : disabledWriter(path2.join(root, `${timestampSlug()}-pid-${process.pid}`)));
687
+ const observations = [];
688
+ const windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
689
+ const minimumWindowMs = options.minimumWindowMs ?? DEFAULT_MINIMUM_WINDOW_MS;
690
+ const cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
691
+ const continuousCaptureMs = options.continuousCaptureMs ?? DEFAULT_CONTINUOUS_CAPTURE_MS;
692
+ const warmupMs = options.warmupMs ?? 6e4;
693
+ let lastSignalCaptureAt = Number.NEGATIVE_INFINITY;
694
+ let lastContinuousCaptureAt = startedAt2;
695
+ let captureInFlight = false;
696
+ let capturePromise;
697
+ const observe = (sample, stats) => {
698
+ const at = now();
699
+ const postGcHeapUsed = typeof stats["postGcHeapUsed"] === "number" ? stats["postGcHeapUsed"] : 0;
700
+ const postMajorGcHeapUsed = typeof stats["postMajorGcHeapUsed"] === "number" ? stats["postMajorGcHeapUsed"] : 0;
701
+ const lastGcAgoMs = typeof stats["lastGcAgoMs"] === "number" ? stats["lastGcAgoMs"] : -1;
702
+ const lastMajorGcAgoMs = typeof stats["lastMajorGcAgoMs"] === "number" ? stats["lastMajorGcAgoMs"] : -1;
703
+ const retainedHeapUsed = postMajorGcHeapUsed > 0 && lastMajorGcAgoMs >= 0 && lastMajorGcAgoMs <= windowMs ? postMajorGcHeapUsed : postGcHeapUsed > 0 && lastGcAgoMs >= 0 && lastGcAgoMs <= minimumWindowMs ? postGcHeapUsed : sample.heapUsed;
704
+ observations.push({
705
+ at,
706
+ heapUsed: retainedHeapUsed,
707
+ rss: sample.rss,
708
+ nativeResidual: sample.nativeResidual ?? 0
709
+ });
710
+ while (observations.length > MAX_OBSERVATIONS || observations.length > 1 && at - (observations[0]?.at ?? at) > windowMs) {
711
+ observations.shift();
712
+ }
713
+ const first = observations[0] ?? observations.at(-1);
714
+ const elapsedMs = first ? Math.max(0, at - first.at) : 0;
715
+ const heapGrowthBytes = first ? retainedHeapUsed - first.heapUsed : 0;
716
+ const rssGrowthBytes = first ? sample.rss - first.rss : 0;
717
+ const nativeGrowthBytes = first ? (sample.nativeResidual ?? 0) - first.nativeResidual : 0;
718
+ const heapGrowthBytesPerHour = elapsedMs > 0 ? Math.round(heapGrowthBytes / elapsedMs * HOUR_MS) : 0;
719
+ const rssGrowthBytesPerHour = elapsedMs > 0 ? Math.round(rssGrowthBytes / elapsedMs * HOUR_MS) : 0;
720
+ const nativeGrowthBytesPerHour = elapsedMs > 0 ? Math.round(nativeGrowthBytes / elapsedMs * HOUR_MS) : 0;
721
+ let signal = "stable";
722
+ if ((sample.detachedContexts ?? 0) > 0) signal = "detached-contexts";
723
+ else if (heapGrowthBytes >= 32 * MB && heapGrowthBytesPerHour > 0) signal = "js-retention";
724
+ else if (nativeGrowthBytes >= 64 * MB && nativeGrowthBytesPerHour > 0) signal = "native-rss";
725
+ const diagnosis = {
726
+ memorySignal: signal,
727
+ memoryWindowMs: elapsedMs,
728
+ retainedHeapUsed,
729
+ transientHeapBytes: Math.max(0, sample.heapUsed - retainedHeapUsed),
730
+ heapGrowthBytes,
731
+ rssGrowthBytes,
732
+ nativeGrowthBytes,
733
+ heapGrowthBytesPerHour,
734
+ rssGrowthBytesPerHour,
735
+ nativeGrowthBytesPerHour,
736
+ memoryArtifactDir: writer.artifactDir,
737
+ ...writer.diagnostics?.() ?? {}
738
+ };
739
+ let reason;
740
+ if (at - startedAt2 >= warmupMs) {
741
+ if ((sample.detachedContexts ?? 0) > 0) reason = "detached-contexts";
742
+ else if (sample.load >= 0.45) reason = "heap-load";
743
+ else if (sample.heapUsed >= (options.absoluteHeapBytes ?? 768 * MB)) {
744
+ reason = "absolute-heap";
745
+ } else if (elapsedMs >= minimumWindowMs && heapGrowthBytes >= (options.heapGrowthBytes ?? 32 * MB) && heapGrowthBytesPerHour >= (options.heapGrowthBytesPerHour ?? 192 * MB)) {
746
+ reason = "heap-growth";
747
+ } else if (elapsedMs >= minimumWindowMs && nativeGrowthBytes >= (options.nativeGrowthBytes ?? 128 * MB) && nativeGrowthBytesPerHour >= (options.nativeGrowthBytesPerHour ?? 256 * MB)) {
748
+ reason = "native-rss-growth";
749
+ }
750
+ }
751
+ const signalCaptureDue = reason !== void 0 && at - lastSignalCaptureAt >= cooldownMs;
752
+ const intervalCaptureDue = at - lastContinuousCaptureAt >= continuousCaptureMs;
753
+ const captureReason = signalCaptureDue ? reason : intervalCaptureDue ? "interval" : void 0;
754
+ if (enabled && captureReason && !captureInFlight) {
755
+ if (captureReason !== "interval") lastSignalCaptureAt = at;
756
+ lastContinuousCaptureAt = at;
757
+ captureInFlight = true;
758
+ diagnosis["memoryCaptureReason"] = captureReason;
759
+ capturePromise = writer.capture({
760
+ reason: captureReason,
761
+ capturedAt: new Date(at).toISOString(),
762
+ pid: process.pid,
763
+ sample,
764
+ stats,
765
+ diagnosis: { ...diagnosis },
766
+ observations: observations.map((observation) => ({ ...observation }))
767
+ }).catch(() => {
768
+ }).finally(() => {
769
+ captureInFlight = false;
770
+ capturePromise = void 0;
771
+ });
772
+ }
773
+ return diagnosis;
774
+ };
775
+ return {
776
+ artifactDir: writer.artifactDir,
777
+ observe,
778
+ stop: async () => {
779
+ await capturePromise;
780
+ await writer.stop();
781
+ }
782
+ };
783
+ }
784
+
785
+ // src/utils/heap-watchdog.ts
786
+ var MB2 = 1024 * 1024;
787
+ function defaultHeapLogPath() {
788
+ const override = process.env["WRONGSTACK_HEAP_LOG_PATH"]?.trim();
789
+ if (override) return path3.resolve(override);
790
+ return path3.join(wstackGlobalRoot(), "logs", "heap.jsonl");
791
+ }
792
+ function takeHeapSample() {
793
+ const m = process.memoryUsage();
794
+ const heap = v8.getHeapStatistics();
795
+ const spaces = v8.getHeapSpaceStatistics();
796
+ const spaceUsed = (name) => spaces.find((space) => space.space_name === name)?.space_used_size ?? 0;
797
+ const limit = heap.heap_size_limit || 0;
798
+ let activeResources = 0;
799
+ let activeResourceTypes = "";
800
+ try {
801
+ const resources = process.getActiveResourcesInfo?.() ?? [];
802
+ activeResources = resources.length;
803
+ const counts = /* @__PURE__ */ new Map();
804
+ for (const resource of resources) counts.set(resource, (counts.get(resource) ?? 0) + 1);
805
+ activeResourceTypes = [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([resource, count]) => `${resource}=${count}`).join(",");
806
+ } catch {
807
+ }
808
+ return {
809
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
810
+ rss: m.rss,
811
+ heapUsed: m.heapUsed,
812
+ heapTotal: m.heapTotal,
813
+ external: m.external,
814
+ arrayBuffers: m.arrayBuffers,
815
+ nativeResidual: Math.max(0, m.rss - m.heapTotal - m.external),
816
+ oldSpaceUsed: spaceUsed("old_space"),
817
+ newSpaceUsed: spaceUsed("new_space"),
818
+ largeObjectSpaceUsed: spaceUsed("large_object_space"),
819
+ codeSpaceUsed: spaceUsed("code_space"),
820
+ mallocedMemory: heap.malloced_memory,
821
+ peakMallocedMemory: heap.peak_malloced_memory,
822
+ nativeContexts: heap.number_of_native_contexts,
823
+ detachedContexts: heap.number_of_detached_contexts,
824
+ activeResources,
825
+ activeResourceTypes,
826
+ heapLimit: limit,
827
+ load: limit > 0 ? m.heapUsed / limit : 0
828
+ };
829
+ }
830
+ function startHeapWatchdog(opts = {}) {
831
+ const profileMode = process.env["WRONGSTACK_MEMORY_PROFILE"] === "1";
832
+ const sampleEveryMs = opts.sampleEveryMs ?? (profileMode ? 5e3 : 3e4);
833
+ const logEveryMs = opts.logEveryMs ?? (profileMode ? 5e3 : 6e4);
834
+ const logPath = opts.logPath ?? defaultHeapLogPath();
835
+ const warnAt = opts.warnAt ?? 0.6;
836
+ const criticalAt = opts.criticalAt ?? 0.85;
837
+ const REARM_MARGIN = 0.05;
838
+ let warnArmed = true;
839
+ let criticalArmed = true;
840
+ let lastLogAt = 0;
841
+ let writeInFlight = false;
842
+ let pendingLine;
843
+ let drainPromise;
844
+ let stopped = false;
845
+ let dirReady = false;
846
+ const flightRecorder = createMemoryFlightRecorder();
847
+ let gcMajorCount = 0;
848
+ let gcMinorCount = 0;
849
+ let gcIncrementalCount = 0;
850
+ let gcWeakCallbackCount = 0;
851
+ let gcDurationMs = 0;
852
+ let postGcHeapUsed = 0;
853
+ let postMajorGcHeapUsed = 0;
854
+ let lastGcAt = 0;
855
+ let lastMajorGcAt = 0;
856
+ const gcObserver = new PerformanceObserver((list) => {
857
+ for (const entry of list.getEntries()) {
858
+ const kind = entry.detail?.kind ?? 0;
859
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_MAJOR) !== 0) gcMajorCount++;
860
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_MINOR) !== 0) gcMinorCount++;
861
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_INCREMENTAL) !== 0) {
862
+ gcIncrementalCount++;
863
+ }
864
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_WEAKCB) !== 0) gcWeakCallbackCount++;
865
+ gcDurationMs += entry.duration;
866
+ postGcHeapUsed = process.memoryUsage().heapUsed;
867
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_MAJOR) !== 0) {
868
+ postMajorGcHeapUsed = postGcHeapUsed;
869
+ lastMajorGcAt = Date.now();
870
+ }
871
+ lastGcAt = Date.now();
872
+ }
873
+ });
874
+ try {
875
+ gcObserver.observe({ entryTypes: ["gc"] });
876
+ } catch {
877
+ }
878
+ const collectRuntimeStats = () => ({
879
+ gcMajorCount,
880
+ gcMinorCount,
881
+ gcIncrementalCount,
882
+ gcWeakCallbackCount,
883
+ gcDurationMs: Math.round(gcDurationMs),
884
+ postGcHeapUsed,
885
+ postMajorGcHeapUsed,
886
+ lastGcAgoMs: lastGcAt > 0 ? Date.now() - lastGcAt : -1,
887
+ lastMajorGcAgoMs: lastMajorGcAt > 0 ? Date.now() - lastMajorGcAt : -1
888
+ });
889
+ const writeDiagnosticLine = opts.writeDiagnosticLine ?? (async (targetPath, line) => {
890
+ if (!dirReady) {
891
+ await fsp2.mkdir(path3.dirname(targetPath), { recursive: true });
892
+ dirReady = true;
893
+ }
894
+ await fsp2.appendFile(targetPath, `${line}
895
+ `, { encoding: "utf8", mode: 384 });
896
+ });
897
+ const drainWrites = async (firstLine) => {
898
+ let line = firstLine;
899
+ while (line !== void 0) {
900
+ try {
901
+ await writeDiagnosticLine(logPath, line);
902
+ } catch {
903
+ }
904
+ line = pendingLine;
905
+ pendingLine = void 0;
906
+ }
907
+ writeInFlight = false;
908
+ };
909
+ const append = (line) => {
910
+ if (stopped) return;
911
+ if (writeInFlight) {
912
+ pendingLine = line;
913
+ return;
914
+ }
915
+ writeInFlight = true;
916
+ drainPromise = drainWrites(line);
917
+ };
918
+ const appendTerminalSample = (event, error, origin) => {
919
+ if (stopped) return;
920
+ let extras = {};
921
+ try {
922
+ extras = opts.collectStats?.() ?? {};
923
+ } catch {
924
+ }
925
+ try {
926
+ const sample = takeHeapSample();
927
+ const runtimeStats = collectRuntimeStats();
928
+ fs.mkdirSync(path3.dirname(logPath), { recursive: true });
929
+ fs.appendFileSync(
930
+ logPath,
931
+ `${JSON.stringify({
932
+ ...extras,
933
+ ...runtimeStats,
934
+ event,
935
+ ...origin ? { crashOrigin: origin } : {},
936
+ ...error instanceof Error ? { errorName: error.name, errorMessage: error.message.slice(0, 1e3) } : {},
937
+ pid: process.pid,
938
+ ...sample,
939
+ exitCode: process.exitCode
940
+ })}
941
+ `,
942
+ "utf8"
943
+ );
944
+ } catch {
945
+ }
946
+ };
947
+ const onUncaughtException = (error, origin) => {
948
+ appendTerminalSample("memory.flight_recorder.crash", error, origin);
949
+ };
950
+ const onProcessExit = () => {
951
+ appendTerminalSample("memory.flight_recorder.exit");
952
+ };
953
+ process.on("uncaughtExceptionMonitor", onUncaughtException);
954
+ process.on("exit", onProcessExit);
955
+ const tick = () => {
956
+ let userTimings = 0;
957
+ try {
958
+ userTimings = performance.getEntriesByType("mark").length + performance.getEntriesByType("measure").length;
959
+ if (userTimings > 0) {
960
+ performance.clearMarks();
961
+ performance.clearMeasures();
962
+ }
963
+ } catch {
964
+ }
965
+ const s = takeHeapSample();
966
+ let extras = {};
967
+ try {
968
+ extras = opts.collectStats?.() ?? {};
969
+ } catch {
970
+ }
971
+ const runtimeStats = collectRuntimeStats();
972
+ const diagnosticStats = { ...extras, ...runtimeStats };
973
+ const memoryDiagnosis = flightRecorder.observe(s, diagnosticStats);
974
+ if (s.load >= criticalAt && criticalArmed) {
975
+ criticalArmed = false;
976
+ warnArmed = false;
977
+ opts.onWarn?.(
978
+ "critical",
979
+ `Heap critical: ${Math.round(s.heapUsed / MB2)} MB of ~${Math.round(s.heapLimit / MB2)} MB V8 limit (${Math.round(s.load * 100)}%). An out-of-memory crash is likely soon \u2014 finish/checkpoint work and restart the session. Diagnostics: ${logPath}`,
980
+ s
981
+ );
982
+ } else if (s.load >= warnAt && warnArmed) {
983
+ warnArmed = false;
984
+ opts.onWarn?.(
985
+ "warn",
986
+ `Heap high: ${Math.round(s.heapUsed / MB2)} MB of ~${Math.round(s.heapLimit / MB2)} MB V8 limit (${Math.round(s.load * 100)}%). Memory diagnostics are being recorded to ${logPath}`,
987
+ s
988
+ );
989
+ }
990
+ if (!warnArmed && s.load < warnAt - REARM_MARGIN) warnArmed = true;
991
+ if (!criticalArmed && s.load < criticalAt - REARM_MARGIN) criticalArmed = true;
992
+ const due = Date.now() - lastLogAt >= logEveryMs;
993
+ const crossed = s.load >= warnAt;
994
+ const captured = typeof memoryDiagnosis["memoryCaptureReason"] === "string";
995
+ if (due || crossed || captured) {
996
+ lastLogAt = Date.now();
997
+ append(
998
+ JSON.stringify({
999
+ ...extras,
1000
+ ...runtimeStats,
1001
+ ...memoryDiagnosis,
1002
+ pid: process.pid,
1003
+ ...s,
1004
+ userTimings
1005
+ })
1006
+ );
1007
+ }
1008
+ };
1009
+ const timer = setInterval(tick, sampleEveryMs);
1010
+ timer.unref?.();
1011
+ tick();
1012
+ return async () => {
1013
+ stopped = true;
1014
+ clearInterval(timer);
1015
+ gcObserver.disconnect();
1016
+ process.removeListener("uncaughtExceptionMonitor", onUncaughtException);
1017
+ process.removeListener("exit", onProcessExit);
1018
+ await drainPromise;
1019
+ await flightRecorder.stop();
1020
+ };
1021
+ }
1022
+ var sharedContributors = /* @__PURE__ */ new Map();
1023
+ var nextSharedContributorId = 1;
1024
+ var sharedSamplerActive = false;
1025
+ var stopSharedSampler;
1026
+ function collectSharedStats() {
1027
+ const merged = {};
1028
+ for (const contributor of sharedContributors.values()) {
1029
+ try {
1030
+ Object.assign(merged, contributor.collectStats?.() ?? {});
1031
+ } catch {
1032
+ }
1033
+ }
1034
+ return merged;
1035
+ }
1036
+ function warnSharedContributors(level, message, sample) {
1037
+ for (const contributor of sharedContributors.values()) {
1038
+ try {
1039
+ contributor.onWarn?.(level, message, sample);
1040
+ } catch {
1041
+ }
1042
+ }
1043
+ }
1044
+ function startSharedHeapWatchdog(opts = {}) {
1045
+ if (process.env["NODE_ENV"] === "test" && !sharedSamplerActive && opts.logPath === void 0 && opts.writeDiagnosticLine === void 0) {
1046
+ return async () => void 0;
1047
+ }
1048
+ const id = nextSharedContributorId++;
1049
+ sharedContributors.set(id, {
1050
+ collectStats: opts.collectStats,
1051
+ onWarn: opts.onWarn
1052
+ });
1053
+ if (!sharedSamplerActive) {
1054
+ sharedSamplerActive = true;
1055
+ stopSharedSampler = startHeapWatchdog({
1056
+ ...opts,
1057
+ collectStats: collectSharedStats,
1058
+ onWarn: warnSharedContributors
1059
+ });
1060
+ }
1061
+ let stopped = false;
1062
+ return async () => {
1063
+ if (stopped) return;
1064
+ stopped = true;
1065
+ sharedContributors.delete(id);
1066
+ if (sharedContributors.size > 0 || !sharedSamplerActive) return;
1067
+ const stop2 = stopSharedSampler;
1068
+ if (!stop2) return;
1069
+ sharedSamplerActive = false;
1070
+ stopSharedSampler = void 0;
1071
+ await stop2();
1072
+ };
1073
+ }
1074
+
253
1075
  // src/utils/perf-profile.ts
254
1076
  var daemonDefaults = false;
255
1077
  function useDaemonPerfDefaults() {
256
1078
  daemonDefaults = true;
257
1079
  }
258
1080
 
1081
+ // src/coordination/mailbox-credential-store.ts
1082
+ import * as crypto from "node:crypto";
1083
+ var CREDENTIAL_STORE_FILE = "_mailbox_credentials.json";
1084
+ var MAX_CREDENTIAL_TTL = {
1085
+ agent: 7 * 24 * 60 * 60 * 1e3,
1086
+ // 7 days
1087
+ operator: 24 * 60 * 60 * 1e3,
1088
+ // 24 hours
1089
+ service: 30 * 24 * 60 * 60 * 1e3
1090
+ // 30 days
1091
+ };
1092
+ var ROTATION_OVERLAP_MS = 60 * 60 * 1e3;
1093
+ function createMailboxCredential(opts, now = Date.now()) {
1094
+ const ttlMs = Math.min(opts.ttlMs, MAX_CREDENTIAL_TTL[opts.kind]);
1095
+ const credentialId = crypto.randomUUID();
1096
+ const secret = crypto.randomBytes(32).toString("hex");
1097
+ const verifierKey = crypto.createHash("sha256").update(secret).digest();
1098
+ const verifier = crypto.createHmac("sha256", verifierKey).update(credentialId).digest("hex");
1099
+ return {
1100
+ credential: {
1101
+ credentialId,
1102
+ verifier,
1103
+ verifierAlgorithm: "hmac-sha256",
1104
+ principalId: opts.principalId,
1105
+ projectId: opts.projectId,
1106
+ capabilities: opts.capabilities,
1107
+ kind: opts.kind,
1108
+ issuedAt: new Date(now).toISOString(),
1109
+ expiresAt: new Date(now + ttlMs).toISOString(),
1110
+ notBefore: opts.notBefore?.toISOString(),
1111
+ status: "active",
1112
+ statusChangedAt: new Date(now).toISOString(),
1113
+ supersedes: opts.supersedes,
1114
+ lastModifiedBy: opts.issuedBy
1115
+ },
1116
+ secret
1117
+ };
1118
+ }
1119
+ function redactMailboxCredential(credential) {
1120
+ const { verifier: _verifier, verifierAlgorithm: _algorithm, ...rest } = credential;
1121
+ return rest;
1122
+ }
1123
+ function verifyMailboxCredential(credential, secret, now = Date.now()) {
1124
+ if (credential === void 0) {
1125
+ return { valid: false, reason: "credential not found" };
1126
+ }
1127
+ const rotationStillValid = credential.status === "rotated_out" && credential.rotationValidUntil !== void 0 && new Date(credential.rotationValidUntil).getTime() >= now;
1128
+ if (credential.status !== "active" && !rotationStillValid) {
1129
+ return { valid: false, reason: `credential is ${credential.status}`, credential };
1130
+ }
1131
+ if (new Date(credential.expiresAt).getTime() <= now) {
1132
+ return { valid: false, reason: "credential expired", credential };
1133
+ }
1134
+ if (credential.notBefore !== void 0 && new Date(credential.notBefore).getTime() > now) {
1135
+ return { valid: false, reason: "credential not yet valid", credential };
1136
+ }
1137
+ const verifierKey = crypto.createHash("sha256").update(secret).digest();
1138
+ const expected = crypto.createHmac("sha256", verifierKey).update(credential.credentialId).digest("hex");
1139
+ const actualBytes = Buffer.from(credential.verifier, "hex");
1140
+ const expectedBytes = Buffer.from(expected, "hex");
1141
+ if (actualBytes.length !== expectedBytes.length || !crypto.timingSafeEqual(actualBytes, expectedBytes)) {
1142
+ return { valid: false, reason: "invalid secret" };
1143
+ }
1144
+ return { valid: true, credential };
1145
+ }
1146
+
259
1147
  // src/coordination/mailbox-events.ts
260
1148
  var MailboxEventEmitter = class {
261
1149
  listeners = /* @__PURE__ */ new Set();
@@ -284,10 +1172,10 @@ var MailboxEventEmitter = class {
284
1172
  };
285
1173
 
286
1174
  // src/coordination/mailbox-project-server-endpoint.ts
287
- import { createHash } from "node:crypto";
288
- import * as fs from "node:fs";
289
- import * as os from "node:os";
290
- import * as path from "node:path";
1175
+ import { createHash as createHash2 } from "node:crypto";
1176
+ import * as fs2 from "node:fs";
1177
+ import * as os2 from "node:os";
1178
+ import * as path4 from "node:path";
291
1179
 
292
1180
  // src/utils/socket-path.ts
293
1181
  import {
@@ -297,7 +1185,7 @@ import {
297
1185
  } from "@wrongstack/persistence";
298
1186
 
299
1187
  // src/coordination/mailbox-project-server-protocol.ts
300
- var MAILBOX_PROJECT_SERVER_PROTOCOL_VERSION = 3;
1188
+ var MAILBOX_PROJECT_SERVER_PROTOCOL_VERSION = 4;
301
1189
  var MAILBOX_PROJECT_SERVER_MAX_FRAME_CHARS = 16 * 1024 * 1024;
302
1190
  var MAILBOX_SERVER_OPERATION_NAMES = {
303
1191
  ping: true,
@@ -409,50 +1297,37 @@ function encodeMailboxProjectServerMessage(message) {
409
1297
  // src/coordination/mailbox-project-server-endpoint.ts
410
1298
  var MAILBOX_PROJECT_SERVER_METADATA_FILE = ".mailbox-server.json";
411
1299
  function normalizeLocalPath(value) {
412
- const resolved = path.resolve(value);
1300
+ const resolved = path4.resolve(value);
413
1301
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
414
1302
  }
415
1303
  function mailboxProjectServerKey(projectDir2) {
416
- return createHash("sha256").update(normalizeLocalPath(projectDir2)).digest("hex").slice(0, 24);
1304
+ return createHash2("sha256").update(normalizeLocalPath(projectDir2)).digest("hex").slice(0, 24);
417
1305
  }
418
1306
  function mailboxProjectServerEndpoint(projectDir2) {
419
1307
  const key = mailboxProjectServerKey(projectDir2);
420
1308
  if (process.platform === "win32") {
421
1309
  return `\\\\.\\pipe\\wrongstack-mailbox-v${MAILBOX_PROJECT_SERVER_PROTOCOL_VERSION}-${key}`;
422
1310
  }
423
- return path.join(
424
- os.tmpdir(),
1311
+ return path4.join(
1312
+ os2.tmpdir(),
425
1313
  `wsmb-v${MAILBOX_PROJECT_SERVER_PROTOCOL_VERSION}`,
426
1314
  `${key}.sock`
427
1315
  );
428
1316
  }
429
1317
  function mailboxProjectServerMetadataPath(projectDir2) {
430
- return path.join(path.resolve(projectDir2), MAILBOX_PROJECT_SERVER_METADATA_FILE);
1318
+ return path4.join(path4.resolve(projectDir2), MAILBOX_PROJECT_SERVER_METADATA_FILE);
431
1319
  }
432
1320
  function ensureMailboxProjectServerSocketDirectory(endpoint2) {
433
1321
  if (process.platform !== "win32") {
434
1322
  assertUnixSocketPathWithinLimit(endpoint2, "mailbox");
435
- fs.mkdirSync(path.dirname(endpoint2), { recursive: true, mode: 448 });
1323
+ fs2.mkdirSync(path4.dirname(endpoint2), { recursive: true, mode: 448 });
436
1324
  }
437
1325
  }
438
1326
 
439
1327
  // src/coordination/sqlite-mailbox.ts
440
1328
  import { randomUUID as randomUUID2 } from "node:crypto";
441
- import * as fs3 from "node:fs";
442
- import * as path3 from "node:path";
443
-
444
- // src/coordination/mailbox-constants.ts
445
- var AGENT_STALE_MS = 6e4;
446
- var CLIENT_STALE_MS = 6e4;
447
- var HEARTBEAT_THROTTLE_MS = 5e3;
448
- var LINE_SEPARATOR = "\n";
449
- var AUTO_COMPACT_INTERVAL_MS = 3e5;
450
- var AUTO_COMPACT_READ_MAX_AGE_MS = 6e5;
451
- var AUTO_COMPACT_DEFAULT_TTL_MS = 864e5;
452
- var AUTO_COMPACT_TYPE_TTL_MS = {
453
- status: 18e5
454
- // 30 min
455
- };
1329
+ import * as fs4 from "node:fs";
1330
+ import * as path6 from "node:path";
456
1331
 
457
1332
  // src/coordination/global-mailbox-completion.ts
458
1333
  function isMailboxMessageProjection(msg) {
@@ -471,6 +1346,19 @@ function isMessageCompletedForActor(msg, actorId) {
471
1346
  return msg.completed === true;
472
1347
  }
473
1348
 
1349
+ // src/coordination/mailbox-constants.ts
1350
+ var AGENT_STALE_MS = 6e4;
1351
+ var CLIENT_STALE_MS = 6e4;
1352
+ var HEARTBEAT_THROTTLE_MS = 5e3;
1353
+ var LINE_SEPARATOR = "\n";
1354
+ var AUTO_COMPACT_INTERVAL_MS = 3e5;
1355
+ var AUTO_COMPACT_READ_MAX_AGE_MS = 6e5;
1356
+ var AUTO_COMPACT_DEFAULT_TTL_MS = 864e5;
1357
+ var AUTO_COMPACT_TYPE_TTL_MS = {
1358
+ status: 18e5
1359
+ // 30 min
1360
+ };
1361
+
474
1362
  // src/coordination/mailbox-types.ts
475
1363
  function mailboxIdentityBase(agentId) {
476
1364
  return agentId.split(/[@#]/, 1)[0].trim().toLowerCase();
@@ -517,169 +1405,14 @@ function normalizeRecipient(to, sessionId) {
517
1405
  function isMailboxReceiptRecordV2(value) {
518
1406
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
519
1407
  const v = value;
520
- if (v["__mailboxReceipt"] !== 2) return false;
521
- if (typeof v["messageId"] !== "string" || v["messageId"].length === 0) return false;
522
- if (typeof v["actorId"] !== "string" || v["actorId"].length === 0) return false;
523
- if (typeof v["timestamp"] !== "string" || v["timestamp"].length === 0) return false;
524
- if ("read" in v && typeof v["read"] !== "boolean") return false;
525
- if ("completed" in v && typeof v["completed"] !== "boolean") return false;
526
- if ("outcome" in v && v["outcome"] !== void 0 && typeof v["outcome"] !== "string") return false;
527
- return true;
528
- }
529
-
530
- // src/coordination/mailbox-receipt-folding.ts
531
- function isFanOutRecipient(to) {
532
- if (to === "*") return true;
533
- if (to.startsWith("@session:")) return true;
534
- return !to.includes("@") && !to.includes("#");
535
- }
536
- function materializeMessage(msg, msgReceipts) {
537
- const recipientState = foldRecipientState(msg, msgReceipts);
538
- const legacyGlobalCompletion = classifyLegacyCompletion(msg, msgReceipts);
539
- return {
540
- ...msg,
541
- recipientState,
542
- ...legacyGlobalCompletion ? { legacyGlobalCompletion: true } : {}
543
- };
544
- }
545
- function foldRecipientState(msg, v2Receipts) {
546
- const state = {};
547
- for (const [actorId, readAt] of Object.entries(msg.readBy)) {
548
- state[actorId] = { actorId, readAt };
549
- }
550
- if (msg.completed && msg.completedBy && !isFanOutRecipient(msg.to)) {
551
- const existing = state[msg.completedBy] ?? { actorId: msg.completedBy };
552
- state[msg.completedBy] = {
553
- ...existing,
554
- completedAt: msg.completedAt ?? msg.timestamp,
555
- completedBy: msg.completedBy,
556
- ...msg.outcome !== void 0 ? { outcome: msg.outcome } : {}
557
- };
558
- }
559
- const sorted = [...v2Receipts].sort((a, b) => a.timestamp.localeCompare(b.timestamp));
560
- for (const receipt of sorted) {
561
- const actorId = receipt.actorId;
562
- const existing = state[actorId] ?? { actorId };
563
- const readAt = existing.readAt ?? (receipt.read === true ? receipt.timestamp : void 0);
564
- let completedAt = existing.completedAt;
565
- let completedBy = existing.completedBy;
566
- if (receipt.completed === true) {
567
- completedAt = receipt.timestamp;
568
- completedBy = actorId;
569
- } else if (receipt.completed === false) {
570
- completedAt = void 0;
571
- completedBy = void 0;
572
- }
573
- const outcome = receipt.outcome !== void 0 ? receipt.outcome : existing.outcome;
574
- state[actorId] = { actorId, readAt, completedAt, completedBy, outcome };
575
- }
576
- return state;
577
- }
578
- function classifyLegacyCompletion(msg, v2Receipts) {
579
- if (!msg.completed) return false;
580
- if (v2Receipts.some((r) => r.completed === true)) return false;
581
- return isFanOutRecipient(msg.to);
582
- }
583
-
584
- // src/coordination/mailbox-retention-state.ts
585
- function resolveMailboxRetentionState(message, agentStatuses) {
586
- const projection = message;
587
- if (projection.legacyGlobalCompletion) {
588
- return { completed: true, completedAt: message.completedAt ?? message.timestamp };
589
- }
590
- const recipientState = projection.recipientState;
591
- if (recipientState === void 0) {
592
- return message.completed ? { completed: true, completedAt: message.completedAt ?? message.timestamp } : { completed: false };
593
- }
594
- const relevantRecipients = resolveRelevantRecipients(message, recipientState, agentStatuses);
595
- if (relevantRecipients.length === 0) return { completed: false };
596
- const completionTimes = [];
597
- for (const actorId of relevantRecipients) {
598
- const completedAt = recipientState[actorId]?.completedAt;
599
- if (completedAt === void 0) return { completed: false };
600
- completionTimes.push(completedAt);
601
- }
602
- return {
603
- completed: true,
604
- // Retention starts only after the last intended recipient completed.
605
- completedAt: completionTimes.reduce((latest, time) => time > latest ? time : latest)
606
- };
607
- }
608
- function projectMailboxCompletion(message, actorId, agentStatuses) {
609
- const projection = message;
610
- let state;
611
- if (actorId === void 0) {
612
- state = resolveMailboxRetentionState(message, agentStatuses);
613
- } else if (projection.legacyGlobalCompletion) {
614
- state = { completed: true, completedAt: message.completedAt ?? message.timestamp };
615
- } else if (projection.recipientState !== void 0) {
616
- const completedAt = projection.recipientState[actorId]?.completedAt;
617
- state = completedAt === void 0 ? { completed: false } : { completed: true, completedAt };
618
- } else {
619
- state = message.completed ? { completed: true, completedAt: message.completedAt ?? message.timestamp } : { completed: false };
620
- }
621
- const result = {
622
- ...projection,
623
- completed: state.completed,
624
- readBy: { ...message.readBy }
625
- };
626
- if (state.completedAt === void 0) delete result.completedAt;
627
- else result.completedAt = state.completedAt;
628
- return result;
629
- }
630
- function resolveRelevantRecipients(message, recipientState, agentStatuses) {
631
- const statuses = agentStatuses ?? [];
632
- const receiptActors = Object.keys(recipientState);
633
- if (message.to === "*") {
634
- if (statuses.length === 0) return [];
635
- const registeredRecipients = statuses.filter((status) => isMailboxMessageVisibleTo(message, status.agentId, status.role)).map((status) => status.agentId);
636
- return [.../* @__PURE__ */ new Set([...registeredRecipients, ...receiptActors])];
637
- }
638
- if (message.to.startsWith("@session:")) {
639
- if (statuses.length === 0) return [];
640
- const sessionId = message.to.slice("@session:".length);
641
- const registeredRecipients = statuses.filter(
642
- (status) => status.sessionId === sessionId && isMailboxMessageVisibleTo(message, status.agentId, status.role)
643
- ).map((status) => status.agentId);
644
- return [.../* @__PURE__ */ new Set([...registeredRecipients, ...receiptActors])];
645
- }
646
- if (message.to.includes("@")) return [message.to];
647
- if (statuses.length === 0) return [];
648
- const aliasRecipients = statuses.filter(
649
- (status) => (status.role?.toLowerCase() === message.to.toLowerCase() || mailboxIdentityBase(status.agentId) === message.to.toLowerCase()) && isMailboxMessageVisibleTo(message, status.agentId, status.role)
650
- ).map((status) => status.agentId);
651
- return [.../* @__PURE__ */ new Set([...aliasRecipients, ...receiptActors])];
652
- }
653
-
654
- // src/coordination/mailbox-status-mappers.ts
655
- function mapRegisteredAgentsToStatuses(registry, now, staleMs) {
656
- return Array.from(registry.values()).map((agent) => ({
657
- agentId: agent.agentId,
658
- name: agent.name,
659
- role: agent.role,
660
- sessionId: agent.sessionId,
661
- status: agent.status,
662
- currentTool: agent.currentTool,
663
- currentTask: agent.currentTask,
664
- iterations: agent.iterations,
665
- toolCalls: agent.toolCalls,
666
- lastActivityAt: agent.lastSeenAt,
667
- lastSeenAt: agent.lastSeenAt,
668
- online: now - new Date(agent.lastSeenAt).getTime() < staleMs,
669
- pid: agent.pid,
670
- source: agent.source
671
- })).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt));
672
- }
673
- function mapRegisteredClientsToStatuses(registry, now, staleMs) {
674
- return Array.from(registry.values()).map((client) => ({
675
- clientId: client.clientId,
676
- name: client.name,
677
- source: client.source,
678
- sessionId: client.sessionId,
679
- lastSeenAt: client.lastSeenAt,
680
- online: now - new Date(client.lastSeenAt).getTime() < staleMs,
681
- pid: client.pid
682
- })).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt));
1408
+ if (v["__mailboxReceipt"] !== 2) return false;
1409
+ if (typeof v["messageId"] !== "string" || v["messageId"].length === 0) return false;
1410
+ if (typeof v["actorId"] !== "string" || v["actorId"].length === 0) return false;
1411
+ if (typeof v["timestamp"] !== "string" || v["timestamp"].length === 0) return false;
1412
+ if ("read" in v && typeof v["read"] !== "boolean") return false;
1413
+ if ("completed" in v && typeof v["completed"] !== "boolean") return false;
1414
+ if ("outcome" in v && v["outcome"] !== void 0 && typeof v["outcome"] !== "string") return false;
1415
+ return true;
683
1416
  }
684
1417
 
685
1418
  // src/coordination/mailbox-message-codec.ts
@@ -844,6 +1577,161 @@ function applyAckToMessage(msg, ack) {
844
1577
  }
845
1578
  }
846
1579
 
1580
+ // src/coordination/mailbox-receipt-folding.ts
1581
+ function isFanOutRecipient(to) {
1582
+ if (to === "*") return true;
1583
+ if (to.startsWith("@session:")) return true;
1584
+ return !to.includes("@") && !to.includes("#");
1585
+ }
1586
+ function materializeMessage(msg, msgReceipts) {
1587
+ const recipientState = foldRecipientState(msg, msgReceipts);
1588
+ const legacyGlobalCompletion = classifyLegacyCompletion(msg, msgReceipts);
1589
+ return {
1590
+ ...msg,
1591
+ recipientState,
1592
+ ...legacyGlobalCompletion ? { legacyGlobalCompletion: true } : {}
1593
+ };
1594
+ }
1595
+ function foldRecipientState(msg, v2Receipts) {
1596
+ const state = {};
1597
+ for (const [actorId, readAt] of Object.entries(msg.readBy)) {
1598
+ state[actorId] = { actorId, readAt };
1599
+ }
1600
+ if (msg.completed && msg.completedBy && !isFanOutRecipient(msg.to)) {
1601
+ const existing = state[msg.completedBy] ?? { actorId: msg.completedBy };
1602
+ state[msg.completedBy] = {
1603
+ ...existing,
1604
+ completedAt: msg.completedAt ?? msg.timestamp,
1605
+ completedBy: msg.completedBy,
1606
+ ...msg.outcome !== void 0 ? { outcome: msg.outcome } : {}
1607
+ };
1608
+ }
1609
+ const sorted = [...v2Receipts].sort((a, b) => a.timestamp.localeCompare(b.timestamp));
1610
+ for (const receipt of sorted) {
1611
+ const actorId = receipt.actorId;
1612
+ const existing = state[actorId] ?? { actorId };
1613
+ const readAt = existing.readAt ?? (receipt.read === true ? receipt.timestamp : void 0);
1614
+ let completedAt = existing.completedAt;
1615
+ let completedBy = existing.completedBy;
1616
+ if (receipt.completed === true) {
1617
+ completedAt = receipt.timestamp;
1618
+ completedBy = actorId;
1619
+ } else if (receipt.completed === false) {
1620
+ completedAt = void 0;
1621
+ completedBy = void 0;
1622
+ }
1623
+ const outcome = receipt.outcome !== void 0 ? receipt.outcome : existing.outcome;
1624
+ state[actorId] = { actorId, readAt, completedAt, completedBy, outcome };
1625
+ }
1626
+ return state;
1627
+ }
1628
+ function classifyLegacyCompletion(msg, v2Receipts) {
1629
+ if (!msg.completed) return false;
1630
+ if (v2Receipts.some((r) => r.completed === true)) return false;
1631
+ return isFanOutRecipient(msg.to);
1632
+ }
1633
+
1634
+ // src/coordination/mailbox-retention-state.ts
1635
+ function resolveMailboxRetentionState(message, agentStatuses) {
1636
+ const projection = message;
1637
+ if (projection.legacyGlobalCompletion) {
1638
+ return { completed: true, completedAt: message.completedAt ?? message.timestamp };
1639
+ }
1640
+ const recipientState = projection.recipientState;
1641
+ if (recipientState === void 0) {
1642
+ return message.completed ? { completed: true, completedAt: message.completedAt ?? message.timestamp } : { completed: false };
1643
+ }
1644
+ const relevantRecipients = resolveRelevantRecipients(message, recipientState, agentStatuses);
1645
+ if (relevantRecipients.length === 0) return { completed: false };
1646
+ const completionTimes = [];
1647
+ for (const actorId of relevantRecipients) {
1648
+ const completedAt = recipientState[actorId]?.completedAt;
1649
+ if (completedAt === void 0) return { completed: false };
1650
+ completionTimes.push(completedAt);
1651
+ }
1652
+ return {
1653
+ completed: true,
1654
+ // Retention starts only after the last intended recipient completed.
1655
+ completedAt: completionTimes.reduce((latest, time) => time > latest ? time : latest)
1656
+ };
1657
+ }
1658
+ function projectMailboxCompletion(message, actorId, agentStatuses) {
1659
+ const projection = message;
1660
+ let state;
1661
+ if (actorId === void 0) {
1662
+ state = resolveMailboxRetentionState(message, agentStatuses);
1663
+ } else if (projection.legacyGlobalCompletion) {
1664
+ state = { completed: true, completedAt: message.completedAt ?? message.timestamp };
1665
+ } else if (projection.recipientState !== void 0) {
1666
+ const completedAt = projection.recipientState[actorId]?.completedAt;
1667
+ state = completedAt === void 0 ? { completed: false } : { completed: true, completedAt };
1668
+ } else {
1669
+ state = message.completed ? { completed: true, completedAt: message.completedAt ?? message.timestamp } : { completed: false };
1670
+ }
1671
+ const result = {
1672
+ ...projection,
1673
+ completed: state.completed,
1674
+ readBy: { ...message.readBy }
1675
+ };
1676
+ if (state.completedAt === void 0) delete result.completedAt;
1677
+ else result.completedAt = state.completedAt;
1678
+ return result;
1679
+ }
1680
+ function resolveRelevantRecipients(message, recipientState, agentStatuses) {
1681
+ const statuses = agentStatuses ?? [];
1682
+ const receiptActors = Object.keys(recipientState);
1683
+ if (message.to === "*") {
1684
+ if (statuses.length === 0) return [];
1685
+ const registeredRecipients = statuses.filter((status) => isMailboxMessageVisibleTo(message, status.agentId, status.role)).map((status) => status.agentId);
1686
+ return [.../* @__PURE__ */ new Set([...registeredRecipients, ...receiptActors])];
1687
+ }
1688
+ if (message.to.startsWith("@session:")) {
1689
+ if (statuses.length === 0) return [];
1690
+ const sessionId = message.to.slice("@session:".length);
1691
+ const registeredRecipients = statuses.filter(
1692
+ (status) => status.sessionId === sessionId && isMailboxMessageVisibleTo(message, status.agentId, status.role)
1693
+ ).map((status) => status.agentId);
1694
+ return [.../* @__PURE__ */ new Set([...registeredRecipients, ...receiptActors])];
1695
+ }
1696
+ if (message.to.includes("@")) return [message.to];
1697
+ if (statuses.length === 0) return [];
1698
+ const aliasRecipients = statuses.filter(
1699
+ (status) => (status.role?.toLowerCase() === message.to.toLowerCase() || mailboxIdentityBase(status.agentId) === message.to.toLowerCase()) && isMailboxMessageVisibleTo(message, status.agentId, status.role)
1700
+ ).map((status) => status.agentId);
1701
+ return [.../* @__PURE__ */ new Set([...aliasRecipients, ...receiptActors])];
1702
+ }
1703
+
1704
+ // src/coordination/mailbox-status-mappers.ts
1705
+ function mapRegisteredAgentsToStatuses(registry, now, staleMs) {
1706
+ return Array.from(registry.values()).map((agent) => ({
1707
+ agentId: agent.agentId,
1708
+ name: agent.name,
1709
+ role: agent.role,
1710
+ sessionId: agent.sessionId,
1711
+ status: agent.status,
1712
+ currentTool: agent.currentTool,
1713
+ currentTask: agent.currentTask,
1714
+ iterations: agent.iterations,
1715
+ toolCalls: agent.toolCalls,
1716
+ lastActivityAt: agent.lastSeenAt,
1717
+ lastSeenAt: agent.lastSeenAt,
1718
+ online: now - new Date(agent.lastSeenAt).getTime() < staleMs,
1719
+ pid: agent.pid,
1720
+ source: agent.source
1721
+ })).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt));
1722
+ }
1723
+ function mapRegisteredClientsToStatuses(registry, now, staleMs) {
1724
+ return Array.from(registry.values()).map((client) => ({
1725
+ clientId: client.clientId,
1726
+ name: client.name,
1727
+ source: client.source,
1728
+ sessionId: client.sessionId,
1729
+ lastSeenAt: client.lastSeenAt,
1730
+ online: now - new Date(client.lastSeenAt).getTime() < staleMs,
1731
+ pid: client.pid
1732
+ })).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt));
1733
+ }
1734
+
847
1735
  // src/coordination/sqlite-mailbox-compaction.ts
848
1736
  async function purgeStale(ctx, options) {
849
1737
  const completedMaxAgeMs = options?.completedMaxAgeMs ?? 864e5;
@@ -927,67 +1815,63 @@ async function autoCompact(ctx, options) {
927
1815
  };
928
1816
  }
929
1817
 
930
- // src/coordination/mailbox-credential-store.ts
931
- import * as crypto from "node:crypto";
932
- var CREDENTIAL_STORE_FILE = "_mailbox_credentials.json";
933
- var MAX_CREDENTIAL_TTL = {
934
- agent: 7 * 24 * 60 * 60 * 1e3,
935
- // 7 days
936
- operator: 24 * 60 * 60 * 1e3,
937
- // 24 hours
938
- service: 30 * 24 * 60 * 60 * 1e3
939
- // 30 days
940
- };
941
- var ROTATION_OVERLAP_MS = 60 * 60 * 1e3;
942
- function createMailboxCredential(opts, now = Date.now()) {
943
- const ttlMs = Math.min(opts.ttlMs, MAX_CREDENTIAL_TTL[opts.kind]);
944
- const credentialId = crypto.randomUUID();
945
- const secret = crypto.randomBytes(32).toString("hex");
946
- const verifierKey = crypto.createHash("sha256").update(secret).digest();
947
- const verifier = crypto.createHmac("sha256", verifierKey).update(credentialId).digest("hex");
948
- return {
949
- credential: {
950
- credentialId,
951
- verifier,
952
- verifierAlgorithm: "hmac-sha256",
953
- principalId: opts.principalId,
954
- projectId: opts.projectId,
955
- capabilities: opts.capabilities,
956
- kind: opts.kind,
957
- issuedAt: new Date(now).toISOString(),
958
- expiresAt: new Date(now + ttlMs).toISOString(),
959
- notBefore: opts.notBefore?.toISOString(),
960
- status: "active",
961
- statusChangedAt: new Date(now).toISOString(),
962
- supersedes: opts.supersedes,
963
- lastModifiedBy: opts.issuedBy
964
- },
965
- secret
966
- };
967
- }
968
- function verifyMailboxCredential(credential, secret, now = Date.now()) {
969
- if (credential === void 0) {
970
- return { valid: false, reason: "credential not found" };
971
- }
972
- const rotationStillValid = credential.status === "rotated_out" && credential.rotationValidUntil !== void 0 && new Date(credential.rotationValidUntil).getTime() >= now;
973
- if (credential.status !== "active" && !rotationStillValid) {
974
- return { valid: false, reason: `credential is ${credential.status}`, credential };
1818
+ // src/coordination/mailbox-credential-throttle.ts
1819
+ var CREDENTIAL_VERIFY_MAX_FAILURES = 10;
1820
+ var CREDENTIAL_VERIFY_WINDOW_MS = 6e4;
1821
+ var CREDENTIAL_VERIFY_COOLDOWN_MS = 6e4;
1822
+ var MAX_TRACKED_IDS = 4096;
1823
+ var CredentialVerifyThrottle = class {
1824
+ constructor(maxFailures = CREDENTIAL_VERIFY_MAX_FAILURES, windowMs = CREDENTIAL_VERIFY_WINDOW_MS, cooldownMs = CREDENTIAL_VERIFY_COOLDOWN_MS) {
1825
+ this.maxFailures = maxFailures;
1826
+ this.windowMs = windowMs;
1827
+ this.cooldownMs = cooldownMs;
1828
+ }
1829
+ maxFailures;
1830
+ windowMs;
1831
+ cooldownMs;
1832
+ records = /* @__PURE__ */ new Map();
1833
+ /** Is this credential id allowed another attempt right now? */
1834
+ check(credentialId, now = Date.now()) {
1835
+ const record = this.records.get(credentialId);
1836
+ if (record === void 0) return { allowed: true, retryAfterMs: 0 };
1837
+ if (record.blockedUntil > now) {
1838
+ return { allowed: false, retryAfterMs: record.blockedUntil - now };
1839
+ }
1840
+ return { allowed: true, retryAfterMs: 0 };
1841
+ }
1842
+ /** Record a failed verification. Starts the cooldown once the limit is hit. */
1843
+ recordFailure(credentialId, now = Date.now()) {
1844
+ const record = this.records.get(credentialId);
1845
+ if (record === void 0 || now - record.windowStartedAt > this.windowMs) {
1846
+ this.evictIfFull();
1847
+ this.records.set(credentialId, { failures: 1, windowStartedAt: now, blockedUntil: 0 });
1848
+ return;
1849
+ }
1850
+ record.failures += 1;
1851
+ if (record.failures >= this.maxFailures) {
1852
+ record.blockedUntil = now + this.cooldownMs;
1853
+ record.failures = 0;
1854
+ record.windowStartedAt = now;
1855
+ }
975
1856
  }
976
- if (new Date(credential.expiresAt).getTime() <= now) {
977
- return { valid: false, reason: "credential expired", credential };
1857
+ /**
1858
+ * Clear the counter after a successful verification. A legitimate holder who
1859
+ * fluffed a few attempts is not left in a cooldown they cannot exit.
1860
+ */
1861
+ recordSuccess(credentialId) {
1862
+ this.records.delete(credentialId);
978
1863
  }
979
- if (credential.notBefore !== void 0 && new Date(credential.notBefore).getTime() > now) {
980
- return { valid: false, reason: "credential not yet valid", credential };
1864
+ /** Test seam. */
1865
+ reset() {
1866
+ this.records.clear();
981
1867
  }
982
- const verifierKey = crypto.createHash("sha256").update(secret).digest();
983
- const expected = crypto.createHmac("sha256", verifierKey).update(credential.credentialId).digest("hex");
984
- const actualBytes = Buffer.from(credential.verifier, "hex");
985
- const expectedBytes = Buffer.from(expected, "hex");
986
- if (actualBytes.length !== expectedBytes.length || !crypto.timingSafeEqual(actualBytes, expectedBytes)) {
987
- return { valid: false, reason: "invalid secret", credential };
1868
+ evictIfFull() {
1869
+ if (this.records.size < MAX_TRACKED_IDS) return;
1870
+ const oldest = this.records.keys().next();
1871
+ if (!oldest.done) this.records.delete(oldest.value);
988
1872
  }
989
- return { valid: true, credential };
990
- }
1873
+ };
1874
+ var credentialVerifyThrottle = new CredentialVerifyThrottle();
991
1875
 
992
1876
  // src/coordination/sqlite-mailbox-rows.ts
993
1877
  var MALFORMED_TIMESTAMP = "last_seen_at NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T*'";
@@ -1267,7 +2151,17 @@ function credentialIssue(db, transaction, options) {
1267
2151
  return issued;
1268
2152
  }
1269
2153
  function credentialVerify(db, credentialId, secret) {
1270
- return verifyMailboxCredential(credentialGet(db, credentialId) ?? void 0, secret);
2154
+ const decision = credentialVerifyThrottle.check(credentialId);
2155
+ if (!decision.allowed) {
2156
+ return {
2157
+ valid: false,
2158
+ reason: `too many failed verification attempts \u2014 retry in ${Math.ceil(decision.retryAfterMs / 1e3)}s`
2159
+ };
2160
+ }
2161
+ const result = verifyMailboxCredential(credentialGet(db, credentialId) ?? void 0, secret);
2162
+ if (result.valid) credentialVerifyThrottle.recordSuccess(credentialId);
2163
+ else credentialVerifyThrottle.recordFailure(credentialId);
2164
+ return result;
1271
2165
  }
1272
2166
  function credentialRevoke(db, credentialId, reason, by) {
1273
2167
  const credential = credentialGet(db, credentialId);
@@ -1288,15 +2182,16 @@ function credentialRotate(db, transaction, credentialId, options) {
1288
2182
  kind: old.kind,
1289
2183
  capabilities: options?.capabilities ?? old.capabilities,
1290
2184
  ttlMs: options?.ttlMs ?? MAX_CREDENTIAL_TTL[old.kind],
2185
+ notBefore: options?.notBefore,
1291
2186
  supersedes: credentialId,
1292
2187
  issuedBy: options?.issuedBy
1293
2188
  });
1294
2189
  }
1295
2190
 
1296
2191
  // src/coordination/sqlite-mailbox-schema.ts
1297
- import * as fs2 from "node:fs";
2192
+ import * as fs3 from "node:fs";
1298
2193
  import { createRequire } from "node:module";
1299
- import * as path2 from "node:path";
2194
+ import * as path5 from "node:path";
1300
2195
 
1301
2196
  // src/utils/sqlite-warning.ts
1302
2197
  var SQLITE_EXPERIMENTAL_WARNING_RE = /sqlite is an experimental feature/i;
@@ -1546,10 +2441,10 @@ function migrateLegacyCredentials(ctx) {
1546
2441
  const { db } = ctx;
1547
2442
  const marker = db.prepare("SELECT value FROM mailbox_meta WHERE key = ?").get("legacy_credentials_imported");
1548
2443
  if (marker !== void 0) return;
1549
- const legacyPath = path2.join(ctx.projectDir, CREDENTIAL_STORE_FILE);
2444
+ const legacyPath = path5.join(ctx.projectDir, CREDENTIAL_STORE_FILE);
1550
2445
  const credentials = [];
1551
2446
  try {
1552
- for (const line of fs2.readFileSync(legacyPath, "utf8").split(/\r?\n/u)) {
2447
+ for (const line of fs3.readFileSync(legacyPath, "utf8").split(/\r?\n/u)) {
1553
2448
  if (!line.trim()) continue;
1554
2449
  try {
1555
2450
  const credential = JSON.parse(line);
@@ -1576,11 +2471,11 @@ function migrateLegacyFiles(ctx) {
1576
2471
  if (marker !== void 0) return;
1577
2472
  const messages = readLegacyMessages(ctx.projectDir);
1578
2473
  const agents = readLegacyRegistry(
1579
- path2.join(ctx.projectDir, "_mailbox.registry.json"),
2474
+ path5.join(ctx.projectDir, "_mailbox.registry.json"),
1580
2475
  parseAgentRegistryEntry
1581
2476
  );
1582
2477
  const clients2 = readLegacyRegistry(
1583
- path2.join(ctx.projectDir, GLOBAL_MAILBOX_CLIENT_REGISTRY_FILE),
2478
+ path5.join(ctx.projectDir, GLOBAL_MAILBOX_CLIENT_REGISTRY_FILE),
1584
2479
  parseClientRegistryEntry
1585
2480
  );
1586
2481
  ctx.transaction(() => {
@@ -1602,7 +2497,7 @@ function migrateLegacyFiles(ctx) {
1602
2497
  function readLegacyMessages(projectDir2) {
1603
2498
  try {
1604
2499
  return parseMailboxFile(
1605
- fs2.readFileSync(path2.join(projectDir2, GLOBAL_MAILBOX_FILE), "utf8")
2500
+ fs3.readFileSync(path5.join(projectDir2, GLOBAL_MAILBOX_FILE), "utf8")
1606
2501
  );
1607
2502
  } catch (error) {
1608
2503
  if (error.code === "ENOENT") return [];
@@ -1611,7 +2506,7 @@ function readLegacyMessages(projectDir2) {
1611
2506
  }
1612
2507
  function readLegacyRegistry(filePath, parseEntry) {
1613
2508
  try {
1614
- const raw = JSON.parse(fs2.readFileSync(filePath, "utf8"));
2509
+ const raw = JSON.parse(fs3.readFileSync(filePath, "utf8"));
1615
2510
  const result = /* @__PURE__ */ new Map();
1616
2511
  for (const [id, value] of Object.entries(raw)) {
1617
2512
  const parsed = parseEntry(value);
@@ -1631,8 +2526,8 @@ var HEARTBEAT_TRACKING_TTL_MS = 30 * 6e4;
1631
2526
  var SqliteMailbox = class {
1632
2527
  constructor(projectDir2, events2, eventEmitter2) {
1633
2528
  this.projectDir = projectDir2;
1634
- fs3.mkdirSync(projectDir2, { recursive: true });
1635
- this.databasePath = path3.join(projectDir2, SQLITE_MAILBOX_FILE);
2529
+ fs4.mkdirSync(projectDir2, { recursive: true });
2530
+ this.databasePath = path6.join(projectDir2, SQLITE_MAILBOX_FILE);
1636
2531
  this.messagePath = this.databasePath;
1637
2532
  this.events = events2;
1638
2533
  this.eventEmitter = eventEmitter2;
@@ -1781,7 +2676,41 @@ var SqliteMailbox = class {
1781
2676
  where.push("reply_to = ?");
1782
2677
  params.push(query.replyTo);
1783
2678
  }
1784
- const canPreLimit = query.unreadBy === void 0 && !query.incompleteOnly;
2679
+ if (query.unreadBy !== void 0) {
2680
+ if (!isMailboxLeader(query.unreadBy, query.readerRole)) {
2681
+ where.push("COALESCE(json_extract(data, '$.audience'), 'all') <> 'leaders'");
2682
+ }
2683
+ if (!query.incompleteOnly) {
2684
+ where.push(`NOT EXISTS (
2685
+ SELECT 1 FROM message_receipts AS unread_receipt
2686
+ WHERE unread_receipt.message_id = messages.id
2687
+ AND unread_receipt.actor_id = ?
2688
+ AND unread_receipt.read_at IS NOT NULL
2689
+ )`);
2690
+ params.push(query.unreadBy);
2691
+ where.push(`NOT EXISTS (
2692
+ SELECT 1 FROM json_each(json_extract(data, '$.readBy')) AS legacy_read
2693
+ WHERE legacy_read.key = ?
2694
+ )`);
2695
+ params.push(query.unreadBy);
2696
+ } else {
2697
+ where.push("legacy_global_completion = 0");
2698
+ where.push(`NOT EXISTS (
2699
+ SELECT 1 FROM message_receipts AS completed_receipt
2700
+ WHERE completed_receipt.message_id = messages.id
2701
+ AND completed_receipt.actor_id = ?
2702
+ AND completed_receipt.completed_at IS NOT NULL
2703
+ )`);
2704
+ params.push(query.unreadBy);
2705
+ where.push(`(
2706
+ completed = 0 OR EXISTS (
2707
+ SELECT 1 FROM message_receipts AS any_receipt
2708
+ WHERE any_receipt.message_id = messages.id
2709
+ )
2710
+ )`);
2711
+ }
2712
+ }
2713
+ const canPreLimit = !query.incompleteOnly || query.unreadBy !== void 0;
1785
2714
  let sql = "SELECT id, data, legacy_global_completion FROM messages";
1786
2715
  if (where.length > 0) sql += ` WHERE ${where.join(" AND ")}`;
1787
2716
  sql += " ORDER BY timestamp DESC, rowid DESC";
@@ -1793,10 +2722,14 @@ var SqliteMailbox = class {
1793
2722
  const messages = this.materializeMessageRows(rows).filter((message) => {
1794
2723
  if (query.to !== void 0 && message.to !== query.to && message.to !== "*") return false;
1795
2724
  if (query.from !== void 0 && message.from !== query.from) return false;
1796
- if (query.sessionId !== void 0 && message.senderSessionId !== query.sessionId) return false;
1797
- if (query.unreadBy !== void 0 && !isMailboxMessageVisibleTo(message, query.unreadBy, query.readerRole)) return false;
1798
- if (!query.incompleteOnly && query.unreadBy !== void 0 && query.unreadBy in message.readBy) return false;
1799
- if (query.incompleteOnly && (query.unreadBy === void 0 ? projectMailboxCompletion(message, void 0, statuses).completed : isMessageCompletedForActor(message, query.unreadBy))) return false;
2725
+ if (query.sessionId !== void 0 && message.senderSessionId !== query.sessionId)
2726
+ return false;
2727
+ if (query.unreadBy !== void 0 && !isMailboxMessageVisibleTo(message, query.unreadBy, query.readerRole))
2728
+ return false;
2729
+ if (!query.incompleteOnly && query.unreadBy !== void 0 && query.unreadBy in message.readBy)
2730
+ return false;
2731
+ if (query.incompleteOnly && (query.unreadBy === void 0 ? projectMailboxCompletion(message, void 0, statuses).completed : isMessageCompletedForActor(message, query.unreadBy)))
2732
+ return false;
1800
2733
  if (type !== void 0 && message.type !== type) return false;
1801
2734
  if (priorityRank[message.priority] < minimumRank) return false;
1802
2735
  if (query.since !== void 0 && message.timestamp <= query.since) return false;
@@ -2161,7 +3094,7 @@ function parseArgs(argv) {
2161
3094
  if (argv[index] === "--project-dir") projectDir2 = argv[++index];
2162
3095
  }
2163
3096
  if (!projectDir2) throw new Error("mailbox project server requires --project-dir");
2164
- return { projectDir: path4.resolve(projectDir2) };
3097
+ return { projectDir: path7.resolve(projectDir2) };
2165
3098
  }
2166
3099
  useDaemonPerfDefaults();
2167
3100
  var { projectDir } = parseArgs(process.argv.slice(2));
@@ -2181,6 +3114,18 @@ var pendingRequests = 0;
2181
3114
  var idleTimer;
2182
3115
  var stopping = false;
2183
3116
  var stopAutoCompact;
3117
+ var stopMemoryWatchdog = startSharedHeapWatchdog({
3118
+ collectStats: () => ({
3119
+ surface: "mailbox-project-server",
3120
+ clients: clients.size,
3121
+ pendingRequests
3122
+ })
3123
+ });
3124
+ var authToken = randomBytes2(16).toString("hex");
3125
+ var markMetadataWritten;
3126
+ var metadataWritten = new Promise((resolve5) => {
3127
+ markMetadataWritten = resolve5;
3128
+ });
2184
3129
  var serverInfo = {
2185
3130
  protocolVersion: MAILBOX_PROJECT_SERVER_PROTOCOL_VERSION,
2186
3131
  pid: process.pid,
@@ -2210,7 +3155,7 @@ events.onAny((event, payload) => {
2210
3155
  });
2211
3156
  eventEmitter.subscribe((event) => broadcast({ type: "mailbox-event", event }));
2212
3157
  function serverStatus() {
2213
- const databasePath = mailbox?.databasePath ?? path4.join(projectDir, SQLITE_MAILBOX_FILE);
3158
+ const databasePath = mailbox?.databasePath ?? path7.join(projectDir, SQLITE_MAILBOX_FILE);
2214
3159
  return {
2215
3160
  ...serverInfo,
2216
3161
  clients: clients.size,
@@ -2220,6 +3165,18 @@ function serverStatus() {
2220
3165
  storageKind: "sqlite"
2221
3166
  };
2222
3167
  }
3168
+ function reviveCredentialOptions(options) {
3169
+ const wireNotBefore = options.notBefore;
3170
+ if (wireNotBefore === void 0 || wireNotBefore instanceof Date) return options;
3171
+ if (typeof wireNotBefore !== "string") {
3172
+ throw new Error("Credential notBefore must be an ISO date-time string");
3173
+ }
3174
+ const notBefore = new Date(wireNotBefore);
3175
+ if (!Number.isFinite(notBefore.getTime())) {
3176
+ throw new Error("Credential notBefore must be an ISO date-time string");
3177
+ }
3178
+ return { ...options, notBefore };
3179
+ }
2223
3180
  async function dispatch(op, rawArgs) {
2224
3181
  const activeMailbox = mailbox;
2225
3182
  if (activeMailbox === void 0) throw new Error("Mailbox SQLite owner is not initialized");
@@ -2306,11 +3263,18 @@ async function dispatch(op, rawArgs) {
2306
3263
  }
2307
3264
  case "credentialIssue": {
2308
3265
  const args = rawArgs;
2309
- return activeMailbox.credentialIssue(args.options);
3266
+ return activeMailbox.credentialIssue(
3267
+ reviveCredentialOptions(args.options)
3268
+ );
2310
3269
  }
2311
3270
  case "credentialVerify": {
2312
3271
  const args = rawArgs;
2313
- return activeMailbox.credentialVerify(args.credentialId, args.secret);
3272
+ return Promise.resolve(activeMailbox.credentialVerify(args.credentialId, args.secret)).then(
3273
+ (result) => result.valid ? {
3274
+ ...result,
3275
+ credential: result.credential ? redactMailboxCredential(result.credential) : void 0
3276
+ } : { valid: false, reason: result.reason }
3277
+ );
2314
3278
  }
2315
3279
  case "credentialRevoke": {
2316
3280
  const args = rawArgs;
@@ -2318,20 +3282,40 @@ async function dispatch(op, rawArgs) {
2318
3282
  }
2319
3283
  case "credentialRotate": {
2320
3284
  const args = rawArgs;
2321
- return activeMailbox.credentialRotate(args.credentialId, args.options);
3285
+ return activeMailbox.credentialRotate(
3286
+ args.credentialId,
3287
+ args.options === void 0 ? void 0 : reviveCredentialOptions(args.options)
3288
+ );
2322
3289
  }
2323
3290
  case "credentialGet": {
2324
3291
  const args = rawArgs;
2325
- return activeMailbox.credentialGet(args.credentialId);
3292
+ return Promise.resolve(activeMailbox.credentialGet(args.credentialId)).then(
3293
+ (credential) => credential ? redactMailboxCredential(credential) : null
3294
+ );
2326
3295
  }
2327
3296
  case "credentialList":
2328
- return activeMailbox.credentialList();
3297
+ return Promise.resolve(activeMailbox.credentialList()).then(
3298
+ (credentials) => credentials.map(redactMailboxCredential)
3299
+ );
2329
3300
  case "credentialStatusCounts":
2330
3301
  return activeMailbox.credentialStatusCounts();
2331
3302
  }
2332
3303
  }
3304
+ function checkAuthToken(state, message) {
3305
+ if (message.type === "heartbeat") return true;
3306
+ if (message.authToken === authToken) return true;
3307
+ send(state, {
3308
+ type: "response",
3309
+ id: message.id,
3310
+ ok: false,
3311
+ error: "Mailbox IPC request rejected: missing or invalid authToken. Reconnect to refresh metadata (.mailbox-server.json#authToken).",
3312
+ errorName: "UnauthorizedMailboxRequest"
3313
+ });
3314
+ return false;
3315
+ }
2333
3316
  function handleMessage(state, message) {
2334
3317
  state.lastSeenAt = Date.now();
3318
+ if (!checkAuthToken(state, message)) return;
2335
3319
  if (message.type === "heartbeat") return;
2336
3320
  if (message.type === "shutdown") {
2337
3321
  send(state, {
@@ -2399,18 +3383,9 @@ function scheduleIdleStop() {
2399
3383
  }
2400
3384
  async function writeMetadata() {
2401
3385
  await fsPromises.mkdir(projectDir, { recursive: true });
2402
- const temporary = `${metadataPath}.${process.pid}.tmp`;
2403
- await fsPromises.writeFile(temporary, `${JSON.stringify(serverStatus(), null, 2)}
2404
- `, {
2405
- encoding: "utf8",
2406
- mode: 384
2407
- });
2408
- try {
2409
- await fsPromises.rename(temporary, metadataPath);
2410
- } catch {
2411
- await fsPromises.rm(metadataPath, { force: true });
2412
- await fsPromises.rename(temporary, metadataPath);
2413
- }
3386
+ const metadata = { ...serverStatus(), authToken };
3387
+ await atomicWrite(metadataPath, `${JSON.stringify(metadata, null, 2)}
3388
+ `, { mode: 384 });
2414
3389
  }
2415
3390
  async function removeOwnedMetadata() {
2416
3391
  try {
@@ -2426,7 +3401,8 @@ async function stop(_reason) {
2426
3401
  idleTimer = void 0;
2427
3402
  clearInterval(leaseSweep);
2428
3403
  stopAutoCompact?.();
2429
- const serverClosed = new Promise((resolve3) => server.close(() => resolve3()));
3404
+ await removeOwnedMetadata();
3405
+ const serverClosed = new Promise((resolve5) => server.close(() => resolve5()));
2430
3406
  for (const state of clients) state.socket.end();
2431
3407
  const forceCloseTimer = setTimeout(() => {
2432
3408
  for (const state of clients) state.socket.destroy();
@@ -2439,11 +3415,11 @@ async function stop(_reason) {
2439
3415
  await mailbox?.close().catch(() => {
2440
3416
  });
2441
3417
  mailbox = void 0;
2442
- await removeOwnedMetadata();
2443
3418
  if (process.platform !== "win32") {
2444
3419
  await fsPromises.rm(endpoint, { force: true }).catch(() => {
2445
3420
  });
2446
3421
  }
3422
+ await stopMemoryWatchdog();
2447
3423
  }
2448
3424
  ensureMailboxProjectServerSocketDirectory(endpoint);
2449
3425
  var server = net.createServer((socket) => {
@@ -2456,7 +3432,9 @@ var server = net.createServer((socket) => {
2456
3432
  socket.setEncoding("utf8");
2457
3433
  const state = { socket, buffer: "", lastSeenAt: Date.now() };
2458
3434
  clients.add(state);
2459
- send(state, { type: "hello", ...serverInfo });
3435
+ void metadataWritten.then(() => {
3436
+ if (!socket.destroyed) send(state, { type: "hello", ...serverInfo });
3437
+ });
2460
3438
  socket.on("data", (chunk) => onData(state, chunk));
2461
3439
  socket.on("error", () => {
2462
3440
  });
@@ -2492,7 +3470,7 @@ server.on("error", (error) => {
2492
3470
  probe.once("error", () => {
2493
3471
  probe.destroy();
2494
3472
  try {
2495
- fs4.rmSync(endpoint, { force: true });
3473
+ fs5.rmSync(endpoint, { force: true });
2496
3474
  } catch {
2497
3475
  }
2498
3476
  probingExistingEndpoint = false;
@@ -2505,7 +3483,7 @@ server.on("error", (error) => {
2505
3483
  server.on("listening", () => {
2506
3484
  if (process.platform !== "win32") {
2507
3485
  try {
2508
- fs4.chmodSync(endpoint, 384);
3486
+ fs5.chmodSync(endpoint, 384);
2509
3487
  } catch {
2510
3488
  }
2511
3489
  }
@@ -2518,7 +3496,10 @@ server.on("listening", () => {
2518
3496
  return;
2519
3497
  }
2520
3498
  stopAutoCompact = mailbox.startAutoCompactTimer();
2521
- void writeMetadata().then(() => scheduleIdleStop()).catch(() => {
3499
+ void writeMetadata().then(() => {
3500
+ markMetadataWritten?.();
3501
+ scheduleIdleStop();
3502
+ }).catch(() => {
2522
3503
  void stop("metadata-write-failed").finally(() => {
2523
3504
  process.exitCode = 1;
2524
3505
  });