@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
@@ -133,6 +133,19 @@ var atomicReplaceWithWriter = primitives.atomicReplaceWithWriter;
133
133
  var ensureDir = primitives.ensureDir;
134
134
  var withFileLock = primitives.withFileLock;
135
135
 
136
+ // src/utils/cache-key.ts
137
+ import { createHash } from "node:crypto";
138
+ var keyCache = /* @__PURE__ */ new WeakMap();
139
+ function deriveCachePrefixKey(systemPrompt) {
140
+ const cached2 = keyCache.get(systemPrompt);
141
+ if (cached2 !== void 0) return cached2;
142
+ const h = createHash("sha256");
143
+ for (const block of systemPrompt) h.update(block.text).update("\0");
144
+ const key = `ws-${h.digest("hex").slice(0, 32)}`;
145
+ keyCache.set(systemPrompt, key);
146
+ return key;
147
+ }
148
+
136
149
  // src/utils/child-env.ts
137
150
  var ALLOWED_KEYS = /* @__PURE__ */ new Set([
138
151
  "PATH",
@@ -169,6 +182,11 @@ var SECRET_NAME_PARTS = [
169
182
  "SECRET",
170
183
  "PASSWORD",
171
184
  "PASSWD",
185
+ // WRONGSTACK_VAULT_PASSPHRASE is the vault KEK. Without this entry it matched
186
+ // no rule here and fell through to the `WRONGSTACK_` prefix allow-rule, so the
187
+ // key that protects the credential vault was forwarded to every child process
188
+ // — including the agent's own exec/bash tools and MCP stdio servers (WS-033).
189
+ "PASSPHRASE",
172
190
  "AUTH",
173
191
  "CRED",
174
192
  "BEARER",
@@ -614,52 +632,69 @@ async function backupConfigFile(filePath, paths) {
614
632
  }
615
633
  }
616
634
 
617
- // src/utils/connectivity.ts
618
- var DEFAULT_PROBE_URL = "https://1.1.1.1";
619
- var DEFAULT_TIMEOUT_MS = 5e3;
620
- var DEFAULT_TTL_MS = 3e4;
621
- var cached;
622
- async function checkConnectivity(opts) {
623
- const url = opts?.probeUrl ?? DEFAULT_PROBE_URL;
624
- const timeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
625
- const ttl = opts?.ttlMs ?? DEFAULT_TTL_MS;
626
- if (cached && ttl > 0 && Date.now() - cached.at < ttl) {
627
- return cached.ok;
628
- }
629
- cached = { ok: await probe(url, timeout), at: Date.now() };
630
- return cached.ok;
635
+ // src/utils/config-json.ts
636
+ import * as fs2 from "node:fs/promises";
637
+
638
+ // src/utils/deep-merge.ts
639
+ var FORBIDDEN_PROTO_KEYS = /* @__PURE__ */ new Set([
640
+ "__proto__",
641
+ "constructor",
642
+ "prototype",
643
+ "__defineGetter__",
644
+ "__defineSetter__",
645
+ "__lookupGetter__",
646
+ "__lookupSetter__"
647
+ ]);
648
+ function isPrimitiveArray(a) {
649
+ return a.every((v) => v === null || typeof v !== "object" && typeof v !== "function");
631
650
  }
632
- async function probe(url, timeoutMs) {
633
- const controller = new AbortController();
634
- const timer = setTimeout(() => controller.abort(), timeoutMs);
635
- try {
636
- await fetch(url, { method: "HEAD", signal: controller.signal });
637
- return true;
638
- } catch {
639
- return false;
640
- } finally {
641
- clearTimeout(timer);
651
+ function deepMerge(base, patch, options = {}) {
652
+ const {
653
+ conflictResolution = "prefer-patch",
654
+ arrayMode = "replace",
655
+ protectProto = true,
656
+ onNonPrimitiveArrayReplace
657
+ } = options;
658
+ if (typeof base !== "object" || base === null) {
659
+ return conflictResolution === "prefer-patch" ? patch : base;
642
660
  }
643
- }
644
- function resetConnectivityCache() {
645
- cached = void 0;
646
- }
647
-
648
- // src/utils/cache-key.ts
649
- import { createHash } from "node:crypto";
650
- var keyCache = /* @__PURE__ */ new WeakMap();
651
- function deriveCachePrefixKey(systemPrompt) {
652
- const cached2 = keyCache.get(systemPrompt);
653
- if (cached2 !== void 0) return cached2;
654
- const h = createHash("sha256");
655
- for (const block of systemPrompt) h.update(block.text).update("\0");
656
- const key = `ws-${h.digest("hex").slice(0, 32)}`;
657
- keyCache.set(systemPrompt, key);
658
- return key;
661
+ if (typeof patch !== "object" || patch === null) {
662
+ return conflictResolution === "prefer-patch" ? patch : base;
663
+ }
664
+ if (Array.isArray(base) && Array.isArray(patch)) {
665
+ if (arrayMode === "concat-primitives" && isPrimitiveArray(base) && isPrimitiveArray(patch)) {
666
+ return [.../* @__PURE__ */ new Set([...base, ...patch])];
667
+ }
668
+ return conflictResolution === "prefer-patch" ? patch : base;
669
+ }
670
+ if (Array.isArray(base) || Array.isArray(patch)) {
671
+ return conflictResolution === "prefer-patch" ? patch : base;
672
+ }
673
+ const baseObj = base;
674
+ const patchObj = patch;
675
+ const out = { ...baseObj };
676
+ for (const [k, v] of Object.entries(patchObj)) {
677
+ if (protectProto && FORBIDDEN_PROTO_KEYS.has(k)) continue;
678
+ const existing = out[k];
679
+ if (v !== null && typeof v === "object" && !Array.isArray(v) && existing !== null && typeof existing === "object" && !Array.isArray(existing)) {
680
+ out[k] = deepMerge(existing, v, options);
681
+ } else if (Array.isArray(v) && Array.isArray(existing)) {
682
+ if (onNonPrimitiveArrayReplace && !isPrimitiveArray(v)) {
683
+ onNonPrimitiveArrayReplace(k, existing.length, v.length);
684
+ }
685
+ out[k] = deepMerge(existing, v, options);
686
+ } else if (v !== void 0) {
687
+ if (onNonPrimitiveArrayReplace && Array.isArray(v) && !isPrimitiveArray(v)) {
688
+ const existingLen = Array.isArray(existing) ? existing.length : 0;
689
+ onNonPrimitiveArrayReplace(k, existingLen, v.length);
690
+ }
691
+ out[k] = v;
692
+ }
693
+ }
694
+ return out;
659
695
  }
660
696
 
661
697
  // src/utils/config-json.ts
662
- import * as fs2 from "node:fs/promises";
663
698
  async function readJsonObjectFile(filePath) {
664
699
  try {
665
700
  const parsed = JSON.parse(await fs2.readFile(filePath, "utf8"));
@@ -686,9 +721,20 @@ async function updateJsonObjectFile(filePath, mutator) {
686
721
  await writeJsonObjectFile(filePath, next);
687
722
  return next;
688
723
  }
689
- function getJsonPath(root, path9) {
724
+ function isForbiddenSegment(segment) {
725
+ return typeof segment === "string" && FORBIDDEN_PROTO_KEYS.has(segment);
726
+ }
727
+ function assertSafePath(path11) {
728
+ for (const segment of path11) {
729
+ if (isForbiddenSegment(segment)) {
730
+ throw new Error(`Refusing to use reserved key "${String(segment)}" in a JSON path`);
731
+ }
732
+ }
733
+ }
734
+ function getJsonPath(root, path11) {
735
+ if (path11.some(isForbiddenSegment)) return void 0;
690
736
  let current = root;
691
- for (const segment of path9) {
737
+ for (const segment of path11) {
692
738
  if (typeof segment === "number") {
693
739
  if (!Array.isArray(current)) return void 0;
694
740
  current = current[segment];
@@ -699,15 +745,17 @@ function getJsonPath(root, path9) {
699
745
  }
700
746
  return current;
701
747
  }
702
- function setJsonPath(root, path9, value) {
703
- if (path9.length === 0) {
748
+ function setJsonPath(root, path11, value) {
749
+ assertSafePath(path11);
750
+ if (path11.length === 0) {
704
751
  if (!isJsonObject(value)) throw new Error("Root config value must be an object");
705
752
  return value;
706
753
  }
707
- const parent = ensureJsonParent(root, path9);
708
- const leaf = lastPathSegment(path9);
754
+ const parent = ensureJsonParent(root, path11);
755
+ const leaf = lastPathSegment(path11);
709
756
  if (typeof leaf === "number") {
710
- if (!Array.isArray(parent)) throw new Error(`Cannot set numeric segment ${leaf} on non-array parent`);
757
+ if (!Array.isArray(parent))
758
+ throw new Error(`Cannot set numeric segment ${leaf} on non-array parent`);
711
759
  parent[leaf] = value;
712
760
  } else {
713
761
  if (!isJsonObject(parent)) throw new Error(`Cannot set property ${leaf} on non-object parent`);
@@ -715,10 +763,11 @@ function setJsonPath(root, path9, value) {
715
763
  }
716
764
  return root;
717
765
  }
718
- function removeJsonPath(root, path9) {
719
- if (path9.length === 0) return false;
720
- const parent = getJsonPath(root, path9.slice(0, -1));
721
- const leaf = lastPathSegment(path9);
766
+ function removeJsonPath(root, path11) {
767
+ if (path11.some(isForbiddenSegment)) return false;
768
+ if (path11.length === 0) return false;
769
+ const parent = getJsonPath(root, path11.slice(0, -1));
770
+ const leaf = lastPathSegment(path11);
722
771
  if (typeof leaf === "number") {
723
772
  if (!Array.isArray(parent) || leaf < 0 || leaf >= parent.length) return false;
724
773
  parent.splice(leaf, 1);
@@ -728,42 +777,78 @@ function removeJsonPath(root, path9) {
728
777
  delete parent[leaf];
729
778
  return true;
730
779
  }
731
- async function setJsonPathInFile(filePath, path9, value) {
732
- return updateJsonObjectFile(filePath, (config) => setJsonPath(config, path9, value));
780
+ async function setJsonPathInFile(filePath, path11, value) {
781
+ return updateJsonObjectFile(filePath, (config) => setJsonPath(config, path11, value));
733
782
  }
734
- async function removeJsonPathInFile(filePath, path9) {
783
+ async function removeJsonPathInFile(filePath, path11) {
735
784
  return updateJsonObjectFile(filePath, (config) => {
736
- removeJsonPath(config, path9);
785
+ removeJsonPath(config, path11);
737
786
  });
738
787
  }
739
788
  function isJsonObject(value) {
740
789
  return typeof value === "object" && value !== null && !Array.isArray(value);
741
790
  }
742
- function lastPathSegment(path9) {
743
- const segment = path9[path9.length - 1];
791
+ function lastPathSegment(path11) {
792
+ const segment = path11[path11.length - 1];
744
793
  if (segment === void 0) throw new Error("Invalid empty JSON path");
745
794
  return segment;
746
795
  }
747
- function ensureJsonParent(root, path9) {
796
+ function ensureJsonParent(root, path11) {
797
+ assertSafePath(path11);
748
798
  let current = root;
749
- for (let i = 0; i < path9.length - 1; i += 1) {
750
- const segment = path9[i];
751
- const nextSegment = path9[i + 1];
799
+ for (let i = 0; i < path11.length - 1; i += 1) {
800
+ const segment = path11[i];
801
+ const nextSegment = path11[i + 1];
752
802
  if (segment === void 0) throw new Error("Invalid empty JSON path segment");
753
803
  const nextContainer = typeof nextSegment === "number" ? [] : {};
754
804
  if (typeof segment === "number") {
755
- if (!Array.isArray(current)) throw new Error(`Cannot traverse numeric segment ${segment} on non-array parent`);
756
- if (!isJsonObject(current[segment]) && !Array.isArray(current[segment])) current[segment] = nextContainer;
805
+ if (!Array.isArray(current))
806
+ throw new Error(`Cannot traverse numeric segment ${segment} on non-array parent`);
807
+ if (!isJsonObject(current[segment]) && !Array.isArray(current[segment]))
808
+ current[segment] = nextContainer;
757
809
  current = current[segment];
758
810
  } else {
759
- if (!isJsonObject(current)) throw new Error(`Cannot traverse property ${segment} on non-object parent`);
760
- if (!isJsonObject(current[segment]) && !Array.isArray(current[segment])) current[segment] = nextContainer;
811
+ if (!isJsonObject(current))
812
+ throw new Error(`Cannot traverse property ${segment} on non-object parent`);
813
+ if (!isJsonObject(current[segment]) && !Array.isArray(current[segment]))
814
+ current[segment] = nextContainer;
761
815
  current = current[segment];
762
816
  }
763
817
  }
764
818
  return current;
765
819
  }
766
820
 
821
+ // src/utils/connectivity.ts
822
+ var DEFAULT_PROBE_URL = "https://1.1.1.1";
823
+ var DEFAULT_TIMEOUT_MS = 5e3;
824
+ var DEFAULT_TTL_MS = 3e4;
825
+ var cached;
826
+ async function checkConnectivity(opts) {
827
+ const url = opts?.probeUrl ?? DEFAULT_PROBE_URL;
828
+ const timeout = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
829
+ const ttl = opts?.ttlMs ?? DEFAULT_TTL_MS;
830
+ if (cached && ttl > 0 && Date.now() - cached.at < ttl) {
831
+ return cached.ok;
832
+ }
833
+ cached = { ok: await probe(url, timeout), at: Date.now() };
834
+ return cached.ok;
835
+ }
836
+ async function probe(url, timeoutMs) {
837
+ const controller = new AbortController();
838
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
839
+ try {
840
+ await fetch(url, { method: "HEAD", signal: controller.signal });
841
+ return true;
842
+ } catch {
843
+ return false;
844
+ } finally {
845
+ clearTimeout(timer);
846
+ }
847
+ }
848
+ function resetConnectivityCache() {
849
+ cached = void 0;
850
+ }
851
+
767
852
  // src/utils/context-evidence.ts
768
853
  import * as path2 from "node:path";
769
854
  var MAX_TOOL_CALLS = 80;
@@ -1742,63 +1827,55 @@ function getContextBreakdown(ctx) {
1742
1827
  };
1743
1828
  }
1744
1829
 
1745
- // src/utils/deep-merge.ts
1746
- var FORBIDDEN_PROTO_KEYS = /* @__PURE__ */ new Set([
1747
- "__proto__",
1748
- "constructor",
1749
- "prototype",
1750
- "__defineGetter__",
1751
- "__defineSetter__",
1752
- "__lookupGetter__",
1753
- "__lookupSetter__"
1754
- ]);
1755
- function isPrimitiveArray(a) {
1756
- return a.every((v) => v === null || typeof v !== "object" && typeof v !== "function");
1757
- }
1758
- function deepMerge(base, patch, options = {}) {
1759
- const {
1760
- conflictResolution = "prefer-patch",
1761
- arrayMode = "replace",
1762
- protectProto = true,
1763
- onNonPrimitiveArrayReplace
1764
- } = options;
1765
- if (typeof base !== "object" || base === null) {
1766
- return conflictResolution === "prefer-patch" ? patch : base;
1767
- }
1768
- if (typeof patch !== "object" || patch === null) {
1769
- return conflictResolution === "prefer-patch" ? patch : base;
1770
- }
1771
- if (Array.isArray(base) && Array.isArray(patch)) {
1772
- if (arrayMode === "concat-primitives" && isPrimitiveArray(base) && isPrimitiveArray(patch)) {
1773
- return [.../* @__PURE__ */ new Set([...base, ...patch])];
1830
+ // src/utils/crash-shield.ts
1831
+ var CRASH_STORM_WINDOW_MS = 6e4;
1832
+ var CRASH_STORM_LIMIT = 20;
1833
+ function isBrokenOutputConsumer(error) {
1834
+ if (typeof error !== "object" || error === null || !("code" in error)) return false;
1835
+ return error.code === "EPIPE" || error.code === "ECONNRESET" || error.code === "ECONNABORTED";
1836
+ }
1837
+ function installCrashShield(options = {}) {
1838
+ const target = options.target ?? process;
1839
+ const exit = options.exit ?? ((code) => process.exit(code));
1840
+ const write = options.write ?? ((s) => void writeErr(s));
1841
+ const recent = [];
1842
+ const isStorming = () => {
1843
+ const now = Date.now();
1844
+ recent.push(now);
1845
+ while (recent.length > 0 && now - recent[0] > CRASH_STORM_WINDOW_MS) {
1846
+ recent.shift();
1774
1847
  }
1775
- return conflictResolution === "prefer-patch" ? patch : base;
1776
- }
1777
- if (Array.isArray(base) || Array.isArray(patch)) {
1778
- return conflictResolution === "prefer-patch" ? patch : base;
1779
- }
1780
- const baseObj = base;
1781
- const patchObj = patch;
1782
- const out = { ...baseObj };
1783
- for (const [k, v] of Object.entries(patchObj)) {
1784
- if (protectProto && FORBIDDEN_PROTO_KEYS.has(k)) continue;
1785
- const existing = out[k];
1786
- if (v !== null && typeof v === "object" && !Array.isArray(v) && existing !== null && typeof existing === "object" && !Array.isArray(existing)) {
1787
- out[k] = deepMerge(existing, v, options);
1788
- } else if (Array.isArray(v) && Array.isArray(existing)) {
1789
- if (onNonPrimitiveArrayReplace && !isPrimitiveArray(v)) {
1790
- onNonPrimitiveArrayReplace(k, existing.length, v.length);
1791
- }
1792
- out[k] = deepMerge(existing, v, options);
1793
- } else if (v !== void 0) {
1794
- if (onNonPrimitiveArrayReplace && Array.isArray(v) && !isPrimitiveArray(v)) {
1795
- const existingLen = Array.isArray(existing) ? existing.length : 0;
1796
- onNonPrimitiveArrayReplace(k, existingLen, v.length);
1797
- }
1798
- out[k] = v;
1848
+ return recent.length > CRASH_STORM_LIMIT;
1849
+ };
1850
+ const report = (kind, reason) => {
1851
+ try {
1852
+ const detail = reason instanceof Error ? reason.stack ?? reason.message : String(reason);
1853
+ write(`[wrongstack] ${kind} (recovered \u2014 please report): ${detail}
1854
+ `);
1855
+ } catch {
1799
1856
  }
1800
- }
1801
- return out;
1857
+ };
1858
+ const guard = (kind) => (reason) => {
1859
+ if (isBrokenOutputConsumer(reason)) return;
1860
+ report(kind, reason);
1861
+ if (isStorming()) {
1862
+ report(
1863
+ kind,
1864
+ new Error(
1865
+ `error storm: >${CRASH_STORM_LIMIT} in ${CRASH_STORM_WINDOW_MS / 1e3}s \u2014 exiting`
1866
+ )
1867
+ );
1868
+ exit(1);
1869
+ }
1870
+ };
1871
+ const onRejection = guard("unhandled promise rejection");
1872
+ const onException = guard("uncaught exception");
1873
+ target.on("unhandledRejection", onRejection);
1874
+ target.on("uncaughtException", onException);
1875
+ return () => {
1876
+ target.off("unhandledRejection", onRejection);
1877
+ target.off("uncaughtException", onException);
1878
+ };
1802
1879
  }
1803
1880
 
1804
1881
  // src/utils/diff.ts
@@ -1953,6 +2030,47 @@ function unifiedDiff(oldText, newText, opts = {}) {
1953
2030
  return out;
1954
2031
  }
1955
2032
 
2033
+ // src/utils/env-typed.ts
2034
+ function envBool(key, env = process.env) {
2035
+ const raw = env[key];
2036
+ if (raw === void 0 || raw === "") return false;
2037
+ return !/^(0|false|no|off)$/i.test(raw.trim());
2038
+ }
2039
+ function envBoolOptional(key, env = process.env) {
2040
+ const raw = env[key];
2041
+ if (raw === void 0 || raw === "") return void 0;
2042
+ return !/^(0|false|no|off)$/i.test(raw.trim());
2043
+ }
2044
+ function envInt(key, options = { default: 0 }, env = process.env) {
2045
+ const raw = env[key];
2046
+ if (raw === void 0 || raw === "") return options.default;
2047
+ const parsed = Number.parseInt(raw, 10);
2048
+ if (!Number.isFinite(parsed)) return options.default;
2049
+ if (options.min !== void 0 && parsed < options.min) return options.default;
2050
+ if (options.max !== void 0 && parsed > options.max) return options.default;
2051
+ return parsed;
2052
+ }
2053
+ function envFloat(key, options = { default: 0 }, env = process.env) {
2054
+ const raw = env[key];
2055
+ if (raw === void 0 || raw === "") return options.default;
2056
+ const parsed = Number.parseFloat(raw);
2057
+ if (!Number.isFinite(parsed)) return options.default;
2058
+ if (options.min !== void 0 && parsed < options.min) return options.default;
2059
+ if (options.max !== void 0 && parsed > options.max) return options.default;
2060
+ return parsed;
2061
+ }
2062
+ function envString(key, env = process.env) {
2063
+ const raw = env[key];
2064
+ if (raw === void 0) return void 0;
2065
+ const trimmed = raw.trim();
2066
+ return trimmed === "" ? void 0 : trimmed;
2067
+ }
2068
+ function envEnum(key, allowed, options, env = process.env) {
2069
+ const raw = envString(key, env);
2070
+ if (raw === void 0) return options.default;
2071
+ return allowed.includes(raw) ? raw : options.default;
2072
+ }
2073
+
1956
2074
  // src/utils/glob-expand.ts
1957
2075
  import * as fsp from "node:fs/promises";
1958
2076
  import { isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
@@ -2051,8 +2169,8 @@ async function expandGlob(pattern) {
2051
2169
  for (const e of entries) {
2052
2170
  const full = `${dir}${SEP}${e}`;
2053
2171
  try {
2054
- const stat2 = await fsp.stat(full);
2055
- if (stat2.isDirectory()) await walk2(full, rest);
2172
+ const stat3 = await fsp.stat(full);
2173
+ if (stat3.isDirectory()) await walk2(full, rest);
2056
2174
  } catch {
2057
2175
  }
2058
2176
  }
@@ -2069,8 +2187,8 @@ async function expandGlob(pattern) {
2069
2187
  if (entries.includes(seg)) {
2070
2188
  const full = `${dir}${SEP}${seg}`;
2071
2189
  try {
2072
- const stat2 = await fsp.stat(full);
2073
- if (stat2.isDirectory()) await walk2(full, rest);
2190
+ const stat3 = await fsp.stat(full);
2191
+ if (stat3.isDirectory()) await walk2(full, rest);
2074
2192
  } catch {
2075
2193
  }
2076
2194
  }
@@ -2087,8 +2205,10 @@ function escapeRegex(s) {
2087
2205
  var COMPILED_GLOB_CACHE = /* @__PURE__ */ new Map();
2088
2206
  var CACHE_MAX_SIZE = 2e3;
2089
2207
  var NEVER_MATCH = /[^\s\S]/;
2090
- function getCachedGlob(pattern) {
2091
- const cached2 = COMPILED_GLOB_CACHE.get(pattern);
2208
+ var COMMAND_WILDCARD_STOP = ";&|\\n\\r`$<>";
2209
+ function getCachedGlob(pattern, commandSubject = false) {
2210
+ const cacheKey = commandSubject ? `cmd\0${pattern}` : pattern;
2211
+ const cached2 = COMPILED_GLOB_CACHE.get(cacheKey);
2092
2212
  if (cached2) return cached2;
2093
2213
  if (COMPILED_GLOB_CACHE.size >= CACHE_MAX_SIZE) {
2094
2214
  const keys = [...COMPILED_GLOB_CACHE.keys()];
@@ -2098,33 +2218,35 @@ function getCachedGlob(pattern) {
2098
2218
  }
2099
2219
  let re;
2100
2220
  try {
2101
- re = compileGlob(pattern);
2221
+ re = compileGlob(pattern, commandSubject);
2102
2222
  } catch {
2103
2223
  re = NEVER_MATCH;
2104
2224
  }
2105
- COMPILED_GLOB_CACHE.set(pattern, re);
2225
+ COMPILED_GLOB_CACHE.set(cacheKey, re);
2106
2226
  return re;
2107
2227
  }
2108
2228
  var MAX_GLOB_PATTERN_LEN = 1024;
2109
- function compileGlob(pattern) {
2229
+ function compileGlob(pattern, commandSubject = false) {
2110
2230
  if (pattern.length > MAX_GLOB_PATTERN_LEN) {
2111
2231
  throw new Error(`Glob pattern exceeds ${MAX_GLOB_PATTERN_LEN} characters`);
2112
2232
  }
2233
+ const star = commandSubject ? `[^/${COMMAND_WILDCARD_STOP}]*` : "[^/]*";
2234
+ const question = commandSubject ? `[^/${COMMAND_WILDCARD_STOP}]` : "[^/]";
2113
2235
  let i = 0;
2114
2236
  let re = "^";
2115
2237
  while (i < pattern.length) {
2116
2238
  const c = pattern[i];
2117
2239
  if (c === "*") {
2118
2240
  if (pattern[i + 1] === "*") {
2119
- re += ".*";
2241
+ re += commandSubject ? `[^${COMMAND_WILDCARD_STOP}]*` : ".*";
2120
2242
  i += 2;
2121
2243
  if (pattern[i] === "/") i++;
2122
2244
  } else {
2123
- re += "[^/]*";
2245
+ re += star;
2124
2246
  i++;
2125
2247
  }
2126
2248
  } else if (c === "?") {
2127
- re += "[^/]";
2249
+ re += question;
2128
2250
  i++;
2129
2251
  } else if (c === "[") {
2130
2252
  let cls = "[";
@@ -2161,44 +2283,878 @@ function matchGlob(pattern, input) {
2161
2283
  function matchAny(patterns, input) {
2162
2284
  return patterns.some((p) => matchGlob(p, input));
2163
2285
  }
2286
+ function matchCommandGlob(pattern, input) {
2287
+ return getCachedGlob(pattern, true).test(input);
2288
+ }
2289
+ function matchAnyCommand(patterns, input) {
2290
+ return patterns.some((p) => matchCommandGlob(p, input));
2291
+ }
2164
2292
 
2165
- // src/utils/incoming-images.ts
2166
- var MAX_INCOMING_IMAGES = 8;
2167
- var MAX_INCOMING_IMAGE_BYTES = 8 * 1024 * 1024;
2168
- var ALLOWED_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
2169
- "image/png",
2170
- "image/jpeg",
2171
- "image/webp",
2172
- "image/gif"
2173
- ]);
2174
- var IncomingImageError = class extends Error {
2175
- constructor(message) {
2176
- super(message);
2177
- this.name = "IncomingImageError";
2293
+ // src/utils/heap-watchdog.ts
2294
+ import * as fs4 from "node:fs";
2295
+ import * as fsp3 from "node:fs/promises";
2296
+ import * as path5 from "node:path";
2297
+ import { PerformanceObserver, constants as performanceConstants } from "node:perf_hooks";
2298
+ import * as v8 from "node:v8";
2299
+
2300
+ // src/utils/memory-flight-recorder.ts
2301
+ import * as fsp2 from "node:fs/promises";
2302
+ import * as path4 from "node:path";
2303
+
2304
+ // src/utils/continuous-memory-profiler.ts
2305
+ import { Session } from "node:inspector/promises";
2306
+ var DEFAULT_SAMPLE_INTERVAL_BYTES = 512 * 1024;
2307
+ var DEFAULT_STACK_DEPTH = 64;
2308
+ var MAX_SUMMARY_STACKS = 20;
2309
+ var MAX_FRAMES_PER_STACK = 12;
2310
+ function errorMessage(error) {
2311
+ return error instanceof Error ? error.message : String(error);
2312
+ }
2313
+ function numeric(value) {
2314
+ if (typeof value === "bigint") return Number(value);
2315
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
2316
+ }
2317
+ function summarizePprof(profile) {
2318
+ const strings = profile.stringTable.strings;
2319
+ const functions = new Map(profile.function.map((entry) => [numeric(entry.id), entry]));
2320
+ const locations = new Map(profile.location.map((entry) => [numeric(entry.id), entry]));
2321
+ const stacks = /* @__PURE__ */ new Map();
2322
+ let sampledBytes = 0;
2323
+ let sampledObjects = 0;
2324
+ for (const sample of profile.sample) {
2325
+ const objects = numeric(sample.value[0]);
2326
+ const bytes = numeric(sample.value[1]);
2327
+ sampledObjects += objects;
2328
+ sampledBytes += bytes;
2329
+ const frames = sample.locationId.slice(0, MAX_FRAMES_PER_STACK).flatMap((locationId) => {
2330
+ const location = locations.get(numeric(locationId));
2331
+ const line = location?.line[0];
2332
+ const fn = line ? functions.get(numeric(line.functionId)) : void 0;
2333
+ if (!fn) return [];
2334
+ const name = strings[numeric(fn.name)] || "(anonymous)";
2335
+ const filename = strings[numeric(fn.filename)] || "";
2336
+ const lineNumber = numeric(line?.line);
2337
+ return [filename ? `${name} (${filename}${lineNumber > 0 ? `:${lineNumber}` : ""})` : name];
2338
+ });
2339
+ if (frames.length === 0) frames.push("(unknown)");
2340
+ const key = frames.join("\n");
2341
+ const existing = stacks.get(key);
2342
+ if (existing) {
2343
+ existing.bytes += bytes;
2344
+ existing.objects += objects;
2345
+ } else {
2346
+ stacks.set(key, { bytes, objects, frames });
2347
+ }
2178
2348
  }
2179
- };
2180
- var DATA_URL_RE = /^data:([a-z0-9.+-]+\/[a-z0-9.+-]+)?(?:;[a-z0-9-]+=[^;,]*)*(;base64)?,/i;
2181
- function splitDataUrl(data) {
2182
- const match = DATA_URL_RE.exec(data);
2183
- if (!match) return { base64: data.trim() };
2184
2349
  return {
2185
- base64: data.slice(match[0].length).trim(),
2186
- mediaType: match[1]?.toLowerCase()
2350
+ sampledBytes,
2351
+ sampledObjects,
2352
+ sampleCount: profile.sample.length,
2353
+ topStacks: [...stacks.values()].sort((left, right) => right.bytes - left.bytes).slice(0, MAX_SUMMARY_STACKS)
2187
2354
  };
2188
2355
  }
2189
- function parseIncomingImages(images, legacyImageBase64) {
2190
- const raw = [...images ?? []];
2191
- if (legacyImageBase64) raw.push({ data: legacyImageBase64 });
2192
- if (raw.length === 0) return [];
2193
- if (raw.length > MAX_INCOMING_IMAGES) {
2194
- throw new IncomingImageError(
2195
- `Too many images: ${raw.length} (max ${MAX_INCOMING_IMAGES} per message).`
2356
+ async function startDatadogProfiler() {
2357
+ const pprof = await import("@datadog/pprof");
2358
+ pprof.heap.start(DEFAULT_SAMPLE_INTERVAL_BYTES, DEFAULT_STACK_DEPTH);
2359
+ let stopped = false;
2360
+ return {
2361
+ backend: "datadog-pprof",
2362
+ capture: async () => {
2363
+ if (stopped) throw new Error("Continuous memory profiler is stopped");
2364
+ const profile = pprof.heap.profile();
2365
+ return {
2366
+ backend: "datadog-pprof",
2367
+ data: await pprof.encode(profile),
2368
+ extension: ".pb.gz",
2369
+ summary: summarizePprof(profile)
2370
+ };
2371
+ },
2372
+ stop: async () => {
2373
+ if (stopped) return;
2374
+ stopped = true;
2375
+ pprof.heap.stop();
2376
+ }
2377
+ };
2378
+ }
2379
+ async function startInspectorProfiler() {
2380
+ const session = new Session();
2381
+ session.connect();
2382
+ try {
2383
+ await session.post("HeapProfiler.enable");
2384
+ await session.post("HeapProfiler.startSampling", {
2385
+ samplingInterval: DEFAULT_SAMPLE_INTERVAL_BYTES,
2386
+ includeObjectsCollectedByMajorGC: false,
2387
+ includeObjectsCollectedByMinorGC: false
2388
+ });
2389
+ } catch (error) {
2390
+ try {
2391
+ session.disconnect();
2392
+ } catch {
2393
+ }
2394
+ throw error;
2395
+ }
2396
+ let stopped = false;
2397
+ return {
2398
+ backend: "node-inspector",
2399
+ capture: async () => {
2400
+ if (stopped) throw new Error("Continuous memory profiler is stopped");
2401
+ const result = await session.post("HeapProfiler.stopSampling");
2402
+ await session.post("HeapProfiler.startSampling", {
2403
+ samplingInterval: DEFAULT_SAMPLE_INTERVAL_BYTES,
2404
+ includeObjectsCollectedByMajorGC: false,
2405
+ includeObjectsCollectedByMinorGC: false
2406
+ });
2407
+ return {
2408
+ backend: "node-inspector",
2409
+ data: JSON.stringify(result.profile),
2410
+ extension: ".heapprofile"
2411
+ };
2412
+ },
2413
+ stop: async () => {
2414
+ if (stopped) return;
2415
+ stopped = true;
2416
+ try {
2417
+ await session.post("HeapProfiler.disable");
2418
+ } catch {
2419
+ }
2420
+ try {
2421
+ session.disconnect();
2422
+ } catch {
2423
+ }
2424
+ }
2425
+ };
2426
+ }
2427
+ async function startContinuousMemoryProfiler() {
2428
+ try {
2429
+ return { profiler: await startDatadogProfiler() };
2430
+ } catch (error) {
2431
+ const fallbackReason = errorMessage(error);
2432
+ return {
2433
+ profiler: await startInspectorProfiler(),
2434
+ fallbackReason
2435
+ };
2436
+ }
2437
+ }
2438
+
2439
+ // src/utils/wstack-paths.ts
2440
+ import { createHash as createHash2 } from "node:crypto";
2441
+ import * as fs3 from "node:fs";
2442
+ import * as os from "node:os";
2443
+ import * as path3 from "node:path";
2444
+ function canonicalProjectRoot(absRoot) {
2445
+ const checkoutRoot = path3.resolve(absRoot);
2446
+ const dotGit = path3.join(checkoutRoot, ".git");
2447
+ try {
2448
+ if (!fs3.statSync(dotGit).isFile()) return checkoutRoot;
2449
+ const gitDirLine = fs3.readFileSync(dotGit, "utf8").trim();
2450
+ const match = /^gitdir:\s*(.+)$/i.exec(gitDirLine);
2451
+ if (!match?.[1]) return checkoutRoot;
2452
+ const gitDir = path3.resolve(checkoutRoot, match[1].trim());
2453
+ const commonDirFile = path3.join(gitDir, "commondir");
2454
+ if (!fs3.statSync(commonDirFile).isFile()) return checkoutRoot;
2455
+ const commonDir = path3.resolve(gitDir, fs3.readFileSync(commonDirFile, "utf8").trim());
2456
+ if (path3.basename(commonDir).toLowerCase() !== ".git") return checkoutRoot;
2457
+ return path3.dirname(commonDir);
2458
+ } catch {
2459
+ return checkoutRoot;
2460
+ }
2461
+ }
2462
+ function projectHash(absRoot) {
2463
+ return createHash2("sha256").update(canonicalProjectRoot(absRoot)).digest("hex").slice(0, 12);
2464
+ }
2465
+ function projectSlug(absRoot) {
2466
+ const identityRoot = canonicalProjectRoot(absRoot);
2467
+ const base = slugify(path3.basename(identityRoot));
2468
+ const hash = createHash2("sha256").update(identityRoot).digest("hex").slice(0, 6);
2469
+ return `${base}-${hash}`;
2470
+ }
2471
+ function slugify(name) {
2472
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "project";
2473
+ }
2474
+ function safeProfileName(name) {
2475
+ const safe = (name ?? "").replace(/[/\\:]/g, "_").replace(/\.\./g, "_").trim();
2476
+ return safe || "default";
2477
+ }
2478
+ function activeProfileName(globalRoot) {
2479
+ try {
2480
+ const parsed = JSON.parse(fs3.readFileSync(path3.join(globalRoot, "config.json"), "utf8"));
2481
+ return safeProfileName(typeof parsed.activeProfile === "string" ? parsed.activeProfile : void 0);
2482
+ } catch {
2483
+ return "default";
2484
+ }
2485
+ }
2486
+ function wstackGlobalRoot() {
2487
+ const fromEnv = process.env["WRONGSTACK_HOME"];
2488
+ if (fromEnv && fromEnv.trim().length > 0) return path3.resolve(fromEnv);
2489
+ return path3.join(os.homedir(), ".wrongstack");
2490
+ }
2491
+ function resolveWstackPaths(opts) {
2492
+ const globalRoot = opts.globalRoot ?? (opts.userHome ? path3.join(opts.userHome, ".wrongstack") : wstackGlobalRoot());
2493
+ const homeDir = opts.userHome ?? os.homedir();
2494
+ const profileName = safeProfileName(opts.profileName ?? activeProfileName(globalRoot));
2495
+ const profileDir = path3.join(globalRoot, "profiles", profileName);
2496
+ const hash = projectHash(opts.projectRoot);
2497
+ const slug = projectSlug(opts.projectRoot);
2498
+ const projectDir = path3.join(globalRoot, "projects", slug);
2499
+ return {
2500
+ globalRoot,
2501
+ profileName,
2502
+ profileDir,
2503
+ projectRoot: opts.projectRoot,
2504
+ homeDir,
2505
+ configDir: profileDir,
2506
+ globalConfig: path3.join(globalRoot, "config.json"),
2507
+ profilesDir: path3.join(globalRoot, "profiles"),
2508
+ profileConfig: (name) => {
2509
+ return path3.join(globalRoot, "profiles", safeProfileName(name), "config.json");
2510
+ },
2511
+ profileStatuslineConfig: (name) => {
2512
+ return path3.join(globalRoot, "profiles", safeProfileName(name), "statusline.json");
2513
+ },
2514
+ profileModeConfig: (name) => {
2515
+ return path3.join(globalRoot, "profiles", safeProfileName(name), "mode.json");
2516
+ },
2517
+ profileProviderStatus: (name) => {
2518
+ return path3.join(globalRoot, "profiles", safeProfileName(name), "provider-status.json");
2519
+ },
2520
+ profileUpdateCache: (name) => {
2521
+ return path3.join(globalRoot, "profiles", safeProfileName(name), "update-cache.json");
2522
+ },
2523
+ secretsKey: path3.join(globalRoot, ".key"),
2524
+ globalMemory: path3.join(profileDir, "memory.md"),
2525
+ globalSkills: path3.join(profileDir, "skills"),
2526
+ globalClaudeSkills: path3.join(homeDir, ".claude", "skills"),
2527
+ globalDesignKits: path3.join(profileDir, "design-kits"),
2528
+ globalPrompts: path3.join(profileDir, "prompts"),
2529
+ globalInstructions: path3.join(profileDir, "instructions"),
2530
+ promptUsage: path3.join(profileDir, "prompt-usage.json"),
2531
+ cacheDir: path3.join(globalRoot, "cache"),
2532
+ modelsCache: path3.join(globalRoot, "cache", "models.dev.json"),
2533
+ modelsOverlayCache: path3.join(globalRoot, "cache", "models-overlay.json"),
2534
+ historyFile: path3.join(profileDir, "history"),
2535
+ logFile: path3.join(globalRoot, "logs", "wrongstack.log"),
2536
+ projectDir,
2537
+ projectCodebaseIndex: path3.join(projectDir, "codebase-index"),
2538
+ projectMemory: path3.join(projectDir, "memory.md"),
2539
+ projectSessions: path3.join(projectDir, "sessions"),
2540
+ projectTrust: path3.join(projectDir, "trust.json"),
2541
+ projectMeta: path3.join(projectDir, "meta.json"),
2542
+ projectLocalConfig: path3.join(projectDir, "config.local.json"),
2543
+ inProjectConfig: path3.join(opts.projectRoot, ".wrongstack", "config.json"),
2544
+ inProjectAgentsFile: path3.join(opts.projectRoot, ".wrongstack", "AGENTS.md"),
2545
+ inProjectSkills: path3.join(opts.projectRoot, ".wrongstack", "skills"),
2546
+ inProjectClaudeSkills: path3.join(opts.projectRoot, ".claude", "skills"),
2547
+ inProjectPrompts: path3.join(opts.projectRoot, ".wrongstack", "prompts"),
2548
+ inProjectInstructions: path3.join(opts.projectRoot, ".wrongstack", "instructions"),
2549
+ inProjectDesignKits: path3.join(opts.projectRoot, ".wrongstack", "design-kits"),
2550
+ inProjectWorktrees: path3.join(opts.projectRoot, ".wrongstack", "worktrees"),
2551
+ projectHash: hash,
2552
+ projectSlug: slug,
2553
+ projectGoal: path3.join(projectDir, "goal.json"),
2554
+ projectInputHistory: path3.join(projectDir, "input-history.json"),
2555
+ projectSpecs: path3.join(projectDir, "specs"),
2556
+ projectTaskGraphs: path3.join(projectDir, "task-graphs"),
2557
+ projectSddSession: path3.join(projectDir, "sdd-session.json"),
2558
+ projectPlan: path3.join(projectDir, "plan.json"),
2559
+ projectAutophase: path3.join(projectDir, "autophase"),
2560
+ projectSddBoards: path3.join(projectDir, "sdd-boards"),
2561
+ syncConfig: path3.join(profileDir, "sync.json"),
2562
+ configHistoryDir: path3.join(globalRoot, "config-history"),
2563
+ projectStatus: (projectHash2) => path3.join(globalRoot, "projects", projectHash2, "status.json")
2564
+ };
2565
+ }
2566
+
2567
+ // src/utils/memory-flight-recorder.ts
2568
+ var MB = 1024 * 1024;
2569
+ var HOUR_MS = 60 * 60 * 1e3;
2570
+ var DEFAULT_WINDOW_MS = 5 * 60 * 1e3;
2571
+ var DEFAULT_MINIMUM_WINDOW_MS = 2 * 60 * 1e3;
2572
+ var DEFAULT_COOLDOWN_MS = 15 * 60 * 1e3;
2573
+ var DEFAULT_CONTINUOUS_CAPTURE_MS = 5 * 60 * 1e3;
2574
+ var MAX_OBSERVATIONS = 24;
2575
+ var MAX_CAPTURE_SESSIONS = 12;
2576
+ var MAX_CAPTURES_PER_SESSION = 6;
2577
+ var SESSION_MAX_AGE_MS = 7 * 24 * HOUR_MS;
2578
+ function timestampSlug(date = /* @__PURE__ */ new Date()) {
2579
+ return date.toISOString().replaceAll(":", "").replaceAll(".", "-");
2580
+ }
2581
+ async function pruneCaptureFiles(artifactDir) {
2582
+ const entries = await fsp2.readdir(artifactDir, { withFileTypes: true });
2583
+ const captures = entries.filter(
2584
+ (entry) => entry.isFile() && entry.name.startsWith("event-") && entry.name.endsWith(".json")
2585
+ ).map((entry) => entry.name).sort();
2586
+ const remove = captures.slice(0, Math.max(0, captures.length - MAX_CAPTURES_PER_SESSION));
2587
+ await Promise.all(
2588
+ remove.flatMap((eventName) => {
2589
+ const stem = eventName.slice("event-".length, -".json".length);
2590
+ return [
2591
+ fsp2.rm(path4.join(artifactDir, eventName), { force: true }),
2592
+ fsp2.rm(path4.join(artifactDir, `allocations-${stem}.heapprofile`), { force: true }),
2593
+ fsp2.rm(path4.join(artifactDir, `allocations-${stem}.pb.gz`), { force: true })
2594
+ ];
2595
+ })
2596
+ );
2597
+ }
2598
+ async function pruneOldSessions(root, currentDir) {
2599
+ const entries = await fsp2.readdir(root, { withFileTypes: true });
2600
+ const sessions = await Promise.all(
2601
+ entries.filter((entry) => entry.isDirectory() && entry.name !== path4.basename(currentDir)).map(async (entry) => {
2602
+ const fullPath = path4.join(root, entry.name);
2603
+ const stat3 = await fsp2.stat(fullPath);
2604
+ return { fullPath, mtimeMs: stat3.mtimeMs };
2605
+ })
2606
+ );
2607
+ sessions.sort((a, b) => b.mtimeMs - a.mtimeMs);
2608
+ const now = Date.now();
2609
+ await Promise.all(
2610
+ sessions.filter(
2611
+ (session, index) => now - session.mtimeMs > SESSION_MAX_AGE_MS || index >= MAX_CAPTURE_SESSIONS && now - session.mtimeMs > 24 * HOUR_MS
2612
+ ).map((session) => fsp2.rm(session.fullPath, { recursive: true, force: true }))
2613
+ );
2614
+ }
2615
+ var ContinuousMemoryCaptureWriter = class {
2616
+ artifactDir;
2617
+ root;
2618
+ ready;
2619
+ profiler;
2620
+ profilerBackend = "initializing";
2621
+ fallbackReason;
2622
+ startError;
2623
+ lastSummary;
2624
+ stopped = false;
2625
+ constructor(root) {
2626
+ this.root = root;
2627
+ this.artifactDir = path4.join(root, `${timestampSlug()}-pid-${process.pid}`);
2628
+ this.ready = this.start().catch((error) => {
2629
+ this.startError = error instanceof Error ? error.message : String(error);
2630
+ this.profilerBackend = "unavailable";
2631
+ });
2632
+ }
2633
+ async start() {
2634
+ const started = await startContinuousMemoryProfiler();
2635
+ this.profiler = started.profiler;
2636
+ this.profilerBackend = started.profiler.backend;
2637
+ this.fallbackReason = started.fallbackReason;
2638
+ }
2639
+ diagnostics() {
2640
+ return {
2641
+ memoryProfilerBackend: this.profilerBackend,
2642
+ ...this.fallbackReason ? { memoryProfilerFallbackReason: this.fallbackReason } : {},
2643
+ ...this.startError ? { memoryProfilerStartError: this.startError } : {},
2644
+ ...this.lastSummary ? {
2645
+ memoryProfileSampledBytes: this.lastSummary.sampledBytes,
2646
+ memoryProfileSampledObjects: this.lastSummary.sampledObjects,
2647
+ memoryProfileSampleCount: this.lastSummary.sampleCount,
2648
+ memoryProfileTopStack: this.lastSummary.topStack,
2649
+ memoryProfileTopStackBytes: this.lastSummary.topStackBytes
2650
+ } : {}
2651
+ };
2652
+ }
2653
+ async capture(event) {
2654
+ await this.ready;
2655
+ if (this.stopped) return;
2656
+ let profile;
2657
+ let captureError = this.startError;
2658
+ if (!captureError && this.profiler) {
2659
+ try {
2660
+ profile = await this.profiler.capture();
2661
+ const top = profile.summary?.topStacks[0];
2662
+ if (profile.summary) {
2663
+ this.lastSummary = {
2664
+ sampledBytes: profile.summary.sampledBytes,
2665
+ sampledObjects: profile.summary.sampledObjects,
2666
+ sampleCount: profile.summary.sampleCount,
2667
+ topStack: top?.frames.join(" <- "),
2668
+ topStackBytes: top?.bytes
2669
+ };
2670
+ }
2671
+ } catch (error) {
2672
+ captureError = error instanceof Error ? error.message : String(error);
2673
+ }
2674
+ }
2675
+ await fsp2.mkdir(this.artifactDir, { recursive: true });
2676
+ const stem = `${timestampSlug(new Date(event.capturedAt))}-${event.reason}`;
2677
+ await fsp2.writeFile(
2678
+ path4.join(this.artifactDir, `event-${stem}.json`),
2679
+ `${JSON.stringify(
2680
+ {
2681
+ ...event,
2682
+ profilerBackend: profile?.backend ?? this.profilerBackend,
2683
+ ...profile?.summary ? { allocationSummary: profile.summary } : {},
2684
+ ...this.fallbackReason ? { profilerFallbackReason: this.fallbackReason } : {},
2685
+ ...captureError ? { captureError } : {}
2686
+ },
2687
+ null,
2688
+ 2
2689
+ )}
2690
+ `,
2691
+ "utf8"
2692
+ );
2693
+ if (profile) {
2694
+ await fsp2.writeFile(
2695
+ path4.join(this.artifactDir, `allocations-${stem}${profile.extension}`),
2696
+ profile.data
2697
+ );
2698
+ }
2699
+ await Promise.all([
2700
+ pruneCaptureFiles(this.artifactDir),
2701
+ fsp2.mkdir(this.root, { recursive: true }).then(() => pruneOldSessions(this.root, this.artifactDir))
2702
+ ]);
2703
+ }
2704
+ async stop() {
2705
+ if (this.stopped) return;
2706
+ this.stopped = true;
2707
+ await this.ready;
2708
+ await this.profiler?.stop();
2709
+ }
2710
+ };
2711
+ function disabledWriter(artifactDir) {
2712
+ return {
2713
+ artifactDir,
2714
+ capture: async () => void 0,
2715
+ stop: async () => void 0
2716
+ };
2717
+ }
2718
+ function createMemoryFlightRecorder(options = {}) {
2719
+ const now = options.now ?? Date.now;
2720
+ const startedAt = now();
2721
+ const root = options.diagnosticsRoot ?? path4.join(wstackGlobalRoot(), "diagnostics", "memory");
2722
+ const enabled = options.enabled ?? (process.env["WRONGSTACK_MEMORY_FLIGHT_RECORDER"] !== "0" && process.env["NODE_ENV"] !== "test");
2723
+ const writer = options.captureWriter ?? (enabled ? new ContinuousMemoryCaptureWriter(root) : disabledWriter(path4.join(root, `${timestampSlug()}-pid-${process.pid}`)));
2724
+ const observations = [];
2725
+ const windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
2726
+ const minimumWindowMs = options.minimumWindowMs ?? DEFAULT_MINIMUM_WINDOW_MS;
2727
+ const cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
2728
+ const continuousCaptureMs = options.continuousCaptureMs ?? DEFAULT_CONTINUOUS_CAPTURE_MS;
2729
+ const warmupMs = options.warmupMs ?? 6e4;
2730
+ let lastSignalCaptureAt = Number.NEGATIVE_INFINITY;
2731
+ let lastContinuousCaptureAt = startedAt;
2732
+ let captureInFlight = false;
2733
+ let capturePromise;
2734
+ const observe = (sample, stats) => {
2735
+ const at = now();
2736
+ const postGcHeapUsed = typeof stats["postGcHeapUsed"] === "number" ? stats["postGcHeapUsed"] : 0;
2737
+ const postMajorGcHeapUsed = typeof stats["postMajorGcHeapUsed"] === "number" ? stats["postMajorGcHeapUsed"] : 0;
2738
+ const lastGcAgoMs = typeof stats["lastGcAgoMs"] === "number" ? stats["lastGcAgoMs"] : -1;
2739
+ const lastMajorGcAgoMs = typeof stats["lastMajorGcAgoMs"] === "number" ? stats["lastMajorGcAgoMs"] : -1;
2740
+ const retainedHeapUsed = postMajorGcHeapUsed > 0 && lastMajorGcAgoMs >= 0 && lastMajorGcAgoMs <= windowMs ? postMajorGcHeapUsed : postGcHeapUsed > 0 && lastGcAgoMs >= 0 && lastGcAgoMs <= minimumWindowMs ? postGcHeapUsed : sample.heapUsed;
2741
+ observations.push({
2742
+ at,
2743
+ heapUsed: retainedHeapUsed,
2744
+ rss: sample.rss,
2745
+ nativeResidual: sample.nativeResidual ?? 0
2746
+ });
2747
+ while (observations.length > MAX_OBSERVATIONS || observations.length > 1 && at - (observations[0]?.at ?? at) > windowMs) {
2748
+ observations.shift();
2749
+ }
2750
+ const first = observations[0] ?? observations.at(-1);
2751
+ const elapsedMs = first ? Math.max(0, at - first.at) : 0;
2752
+ const heapGrowthBytes = first ? retainedHeapUsed - first.heapUsed : 0;
2753
+ const rssGrowthBytes = first ? sample.rss - first.rss : 0;
2754
+ const nativeGrowthBytes = first ? (sample.nativeResidual ?? 0) - first.nativeResidual : 0;
2755
+ const heapGrowthBytesPerHour = elapsedMs > 0 ? Math.round(heapGrowthBytes / elapsedMs * HOUR_MS) : 0;
2756
+ const rssGrowthBytesPerHour = elapsedMs > 0 ? Math.round(rssGrowthBytes / elapsedMs * HOUR_MS) : 0;
2757
+ const nativeGrowthBytesPerHour = elapsedMs > 0 ? Math.round(nativeGrowthBytes / elapsedMs * HOUR_MS) : 0;
2758
+ let signal = "stable";
2759
+ if ((sample.detachedContexts ?? 0) > 0) signal = "detached-contexts";
2760
+ else if (heapGrowthBytes >= 32 * MB && heapGrowthBytesPerHour > 0) signal = "js-retention";
2761
+ else if (nativeGrowthBytes >= 64 * MB && nativeGrowthBytesPerHour > 0) signal = "native-rss";
2762
+ const diagnosis = {
2763
+ memorySignal: signal,
2764
+ memoryWindowMs: elapsedMs,
2765
+ retainedHeapUsed,
2766
+ transientHeapBytes: Math.max(0, sample.heapUsed - retainedHeapUsed),
2767
+ heapGrowthBytes,
2768
+ rssGrowthBytes,
2769
+ nativeGrowthBytes,
2770
+ heapGrowthBytesPerHour,
2771
+ rssGrowthBytesPerHour,
2772
+ nativeGrowthBytesPerHour,
2773
+ memoryArtifactDir: writer.artifactDir,
2774
+ ...writer.diagnostics?.() ?? {}
2775
+ };
2776
+ let reason;
2777
+ if (at - startedAt >= warmupMs) {
2778
+ if ((sample.detachedContexts ?? 0) > 0) reason = "detached-contexts";
2779
+ else if (sample.load >= 0.45) reason = "heap-load";
2780
+ else if (sample.heapUsed >= (options.absoluteHeapBytes ?? 768 * MB)) {
2781
+ reason = "absolute-heap";
2782
+ } else if (elapsedMs >= minimumWindowMs && heapGrowthBytes >= (options.heapGrowthBytes ?? 32 * MB) && heapGrowthBytesPerHour >= (options.heapGrowthBytesPerHour ?? 192 * MB)) {
2783
+ reason = "heap-growth";
2784
+ } else if (elapsedMs >= minimumWindowMs && nativeGrowthBytes >= (options.nativeGrowthBytes ?? 128 * MB) && nativeGrowthBytesPerHour >= (options.nativeGrowthBytesPerHour ?? 256 * MB)) {
2785
+ reason = "native-rss-growth";
2786
+ }
2787
+ }
2788
+ const signalCaptureDue = reason !== void 0 && at - lastSignalCaptureAt >= cooldownMs;
2789
+ const intervalCaptureDue = at - lastContinuousCaptureAt >= continuousCaptureMs;
2790
+ const captureReason = signalCaptureDue ? reason : intervalCaptureDue ? "interval" : void 0;
2791
+ if (enabled && captureReason && !captureInFlight) {
2792
+ if (captureReason !== "interval") lastSignalCaptureAt = at;
2793
+ lastContinuousCaptureAt = at;
2794
+ captureInFlight = true;
2795
+ diagnosis["memoryCaptureReason"] = captureReason;
2796
+ capturePromise = writer.capture({
2797
+ reason: captureReason,
2798
+ capturedAt: new Date(at).toISOString(),
2799
+ pid: process.pid,
2800
+ sample,
2801
+ stats,
2802
+ diagnosis: { ...diagnosis },
2803
+ observations: observations.map((observation) => ({ ...observation }))
2804
+ }).catch(() => {
2805
+ }).finally(() => {
2806
+ captureInFlight = false;
2807
+ capturePromise = void 0;
2808
+ });
2809
+ }
2810
+ return diagnosis;
2811
+ };
2812
+ return {
2813
+ artifactDir: writer.artifactDir,
2814
+ observe,
2815
+ stop: async () => {
2816
+ await capturePromise;
2817
+ await writer.stop();
2818
+ }
2819
+ };
2820
+ }
2821
+
2822
+ // src/utils/heap-watchdog.ts
2823
+ var MB2 = 1024 * 1024;
2824
+ function defaultHeapLogPath() {
2825
+ const override = process.env["WRONGSTACK_HEAP_LOG_PATH"]?.trim();
2826
+ if (override) return path5.resolve(override);
2827
+ return path5.join(wstackGlobalRoot(), "logs", "heap.jsonl");
2828
+ }
2829
+ function takeHeapSample() {
2830
+ const m = process.memoryUsage();
2831
+ const heap = v8.getHeapStatistics();
2832
+ const spaces = v8.getHeapSpaceStatistics();
2833
+ const spaceUsed = (name) => spaces.find((space) => space.space_name === name)?.space_used_size ?? 0;
2834
+ const limit = heap.heap_size_limit || 0;
2835
+ let activeResources = 0;
2836
+ let activeResourceTypes = "";
2837
+ try {
2838
+ const resources = process.getActiveResourcesInfo?.() ?? [];
2839
+ activeResources = resources.length;
2840
+ const counts = /* @__PURE__ */ new Map();
2841
+ for (const resource of resources) counts.set(resource, (counts.get(resource) ?? 0) + 1);
2842
+ activeResourceTypes = [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([resource, count]) => `${resource}=${count}`).join(",");
2843
+ } catch {
2844
+ }
2845
+ return {
2846
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
2847
+ rss: m.rss,
2848
+ heapUsed: m.heapUsed,
2849
+ heapTotal: m.heapTotal,
2850
+ external: m.external,
2851
+ arrayBuffers: m.arrayBuffers,
2852
+ nativeResidual: Math.max(0, m.rss - m.heapTotal - m.external),
2853
+ oldSpaceUsed: spaceUsed("old_space"),
2854
+ newSpaceUsed: spaceUsed("new_space"),
2855
+ largeObjectSpaceUsed: spaceUsed("large_object_space"),
2856
+ codeSpaceUsed: spaceUsed("code_space"),
2857
+ mallocedMemory: heap.malloced_memory,
2858
+ peakMallocedMemory: heap.peak_malloced_memory,
2859
+ nativeContexts: heap.number_of_native_contexts,
2860
+ detachedContexts: heap.number_of_detached_contexts,
2861
+ activeResources,
2862
+ activeResourceTypes,
2863
+ heapLimit: limit,
2864
+ load: limit > 0 ? m.heapUsed / limit : 0
2865
+ };
2866
+ }
2867
+ function startHeapWatchdog(opts = {}) {
2868
+ const profileMode = process.env["WRONGSTACK_MEMORY_PROFILE"] === "1";
2869
+ const sampleEveryMs = opts.sampleEveryMs ?? (profileMode ? 5e3 : 3e4);
2870
+ const logEveryMs = opts.logEveryMs ?? (profileMode ? 5e3 : 6e4);
2871
+ const logPath = opts.logPath ?? defaultHeapLogPath();
2872
+ const warnAt = opts.warnAt ?? 0.6;
2873
+ const criticalAt = opts.criticalAt ?? 0.85;
2874
+ const REARM_MARGIN = 0.05;
2875
+ let warnArmed = true;
2876
+ let criticalArmed = true;
2877
+ let lastLogAt = 0;
2878
+ let writeInFlight = false;
2879
+ let pendingLine;
2880
+ let drainPromise;
2881
+ let stopped = false;
2882
+ let dirReady = false;
2883
+ const flightRecorder = createMemoryFlightRecorder();
2884
+ let gcMajorCount = 0;
2885
+ let gcMinorCount = 0;
2886
+ let gcIncrementalCount = 0;
2887
+ let gcWeakCallbackCount = 0;
2888
+ let gcDurationMs = 0;
2889
+ let postGcHeapUsed = 0;
2890
+ let postMajorGcHeapUsed = 0;
2891
+ let lastGcAt = 0;
2892
+ let lastMajorGcAt = 0;
2893
+ const gcObserver = new PerformanceObserver((list) => {
2894
+ for (const entry of list.getEntries()) {
2895
+ const kind = entry.detail?.kind ?? 0;
2896
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_MAJOR) !== 0) gcMajorCount++;
2897
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_MINOR) !== 0) gcMinorCount++;
2898
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_INCREMENTAL) !== 0) {
2899
+ gcIncrementalCount++;
2900
+ }
2901
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_WEAKCB) !== 0) gcWeakCallbackCount++;
2902
+ gcDurationMs += entry.duration;
2903
+ postGcHeapUsed = process.memoryUsage().heapUsed;
2904
+ if ((kind & performanceConstants.NODE_PERFORMANCE_GC_MAJOR) !== 0) {
2905
+ postMajorGcHeapUsed = postGcHeapUsed;
2906
+ lastMajorGcAt = Date.now();
2907
+ }
2908
+ lastGcAt = Date.now();
2909
+ }
2910
+ });
2911
+ try {
2912
+ gcObserver.observe({ entryTypes: ["gc"] });
2913
+ } catch {
2914
+ }
2915
+ const collectRuntimeStats = () => ({
2916
+ gcMajorCount,
2917
+ gcMinorCount,
2918
+ gcIncrementalCount,
2919
+ gcWeakCallbackCount,
2920
+ gcDurationMs: Math.round(gcDurationMs),
2921
+ postGcHeapUsed,
2922
+ postMajorGcHeapUsed,
2923
+ lastGcAgoMs: lastGcAt > 0 ? Date.now() - lastGcAt : -1,
2924
+ lastMajorGcAgoMs: lastMajorGcAt > 0 ? Date.now() - lastMajorGcAt : -1
2925
+ });
2926
+ const writeDiagnosticLine = opts.writeDiagnosticLine ?? (async (targetPath, line) => {
2927
+ if (!dirReady) {
2928
+ await fsp3.mkdir(path5.dirname(targetPath), { recursive: true });
2929
+ dirReady = true;
2930
+ }
2931
+ await fsp3.appendFile(targetPath, `${line}
2932
+ `, { encoding: "utf8", mode: 384 });
2933
+ });
2934
+ const drainWrites = async (firstLine) => {
2935
+ let line = firstLine;
2936
+ while (line !== void 0) {
2937
+ try {
2938
+ await writeDiagnosticLine(logPath, line);
2939
+ } catch {
2940
+ }
2941
+ line = pendingLine;
2942
+ pendingLine = void 0;
2943
+ }
2944
+ writeInFlight = false;
2945
+ };
2946
+ const append = (line) => {
2947
+ if (stopped) return;
2948
+ if (writeInFlight) {
2949
+ pendingLine = line;
2950
+ return;
2951
+ }
2952
+ writeInFlight = true;
2953
+ drainPromise = drainWrites(line);
2954
+ };
2955
+ const appendTerminalSample = (event, error, origin) => {
2956
+ if (stopped) return;
2957
+ let extras = {};
2958
+ try {
2959
+ extras = opts.collectStats?.() ?? {};
2960
+ } catch {
2961
+ }
2962
+ try {
2963
+ const sample = takeHeapSample();
2964
+ const runtimeStats = collectRuntimeStats();
2965
+ fs4.mkdirSync(path5.dirname(logPath), { recursive: true });
2966
+ fs4.appendFileSync(
2967
+ logPath,
2968
+ `${JSON.stringify({
2969
+ ...extras,
2970
+ ...runtimeStats,
2971
+ event,
2972
+ ...origin ? { crashOrigin: origin } : {},
2973
+ ...error instanceof Error ? { errorName: error.name, errorMessage: error.message.slice(0, 1e3) } : {},
2974
+ pid: process.pid,
2975
+ ...sample,
2976
+ exitCode: process.exitCode
2977
+ })}
2978
+ `,
2979
+ "utf8"
2980
+ );
2981
+ } catch {
2982
+ }
2983
+ };
2984
+ const onUncaughtException = (error, origin) => {
2985
+ appendTerminalSample("memory.flight_recorder.crash", error, origin);
2986
+ };
2987
+ const onProcessExit = () => {
2988
+ appendTerminalSample("memory.flight_recorder.exit");
2989
+ };
2990
+ process.on("uncaughtExceptionMonitor", onUncaughtException);
2991
+ process.on("exit", onProcessExit);
2992
+ const tick = () => {
2993
+ let userTimings = 0;
2994
+ try {
2995
+ userTimings = performance.getEntriesByType("mark").length + performance.getEntriesByType("measure").length;
2996
+ if (userTimings > 0) {
2997
+ performance.clearMarks();
2998
+ performance.clearMeasures();
2999
+ }
3000
+ } catch {
3001
+ }
3002
+ const s = takeHeapSample();
3003
+ let extras = {};
3004
+ try {
3005
+ extras = opts.collectStats?.() ?? {};
3006
+ } catch {
3007
+ }
3008
+ const runtimeStats = collectRuntimeStats();
3009
+ const diagnosticStats = { ...extras, ...runtimeStats };
3010
+ const memoryDiagnosis = flightRecorder.observe(s, diagnosticStats);
3011
+ if (s.load >= criticalAt && criticalArmed) {
3012
+ criticalArmed = false;
3013
+ warnArmed = false;
3014
+ opts.onWarn?.(
3015
+ "critical",
3016
+ `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}`,
3017
+ s
3018
+ );
3019
+ } else if (s.load >= warnAt && warnArmed) {
3020
+ warnArmed = false;
3021
+ opts.onWarn?.(
3022
+ "warn",
3023
+ `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}`,
3024
+ s
3025
+ );
3026
+ }
3027
+ if (!warnArmed && s.load < warnAt - REARM_MARGIN) warnArmed = true;
3028
+ if (!criticalArmed && s.load < criticalAt - REARM_MARGIN) criticalArmed = true;
3029
+ const due = Date.now() - lastLogAt >= logEveryMs;
3030
+ const crossed = s.load >= warnAt;
3031
+ const captured = typeof memoryDiagnosis["memoryCaptureReason"] === "string";
3032
+ if (due || crossed || captured) {
3033
+ lastLogAt = Date.now();
3034
+ append(
3035
+ JSON.stringify({
3036
+ ...extras,
3037
+ ...runtimeStats,
3038
+ ...memoryDiagnosis,
3039
+ pid: process.pid,
3040
+ ...s,
3041
+ userTimings
3042
+ })
3043
+ );
3044
+ }
3045
+ };
3046
+ const timer = setInterval(tick, sampleEveryMs);
3047
+ timer.unref?.();
3048
+ tick();
3049
+ return async () => {
3050
+ stopped = true;
3051
+ clearInterval(timer);
3052
+ gcObserver.disconnect();
3053
+ process.removeListener("uncaughtExceptionMonitor", onUncaughtException);
3054
+ process.removeListener("exit", onProcessExit);
3055
+ await drainPromise;
3056
+ await flightRecorder.stop();
3057
+ };
3058
+ }
3059
+ var sharedContributors = /* @__PURE__ */ new Map();
3060
+ var nextSharedContributorId = 1;
3061
+ var sharedSamplerActive = false;
3062
+ var stopSharedSampler;
3063
+ function collectSharedStats() {
3064
+ const merged = {};
3065
+ for (const contributor of sharedContributors.values()) {
3066
+ try {
3067
+ Object.assign(merged, contributor.collectStats?.() ?? {});
3068
+ } catch {
3069
+ }
3070
+ }
3071
+ return merged;
3072
+ }
3073
+ function warnSharedContributors(level, message, sample) {
3074
+ for (const contributor of sharedContributors.values()) {
3075
+ try {
3076
+ contributor.onWarn?.(level, message, sample);
3077
+ } catch {
3078
+ }
3079
+ }
3080
+ }
3081
+ function startSharedHeapWatchdog(opts = {}) {
3082
+ if (process.env["NODE_ENV"] === "test" && !sharedSamplerActive && opts.logPath === void 0 && opts.writeDiagnosticLine === void 0) {
3083
+ return async () => void 0;
3084
+ }
3085
+ const id = nextSharedContributorId++;
3086
+ sharedContributors.set(id, {
3087
+ collectStats: opts.collectStats,
3088
+ onWarn: opts.onWarn
3089
+ });
3090
+ if (!sharedSamplerActive) {
3091
+ sharedSamplerActive = true;
3092
+ stopSharedSampler = startHeapWatchdog({
3093
+ ...opts,
3094
+ collectStats: collectSharedStats,
3095
+ onWarn: warnSharedContributors
3096
+ });
3097
+ }
3098
+ let stopped = false;
3099
+ return async () => {
3100
+ if (stopped) return;
3101
+ stopped = true;
3102
+ sharedContributors.delete(id);
3103
+ if (sharedContributors.size > 0 || !sharedSamplerActive) return;
3104
+ const stop = stopSharedSampler;
3105
+ if (!stop) return;
3106
+ sharedSamplerActive = false;
3107
+ stopSharedSampler = void 0;
3108
+ await stop();
3109
+ };
3110
+ }
3111
+
3112
+ // src/utils/incoming-images.ts
3113
+ var MAX_INCOMING_IMAGES = 8;
3114
+ var MAX_INCOMING_IMAGE_BYTES = 8 * 1024 * 1024;
3115
+ var ALLOWED_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
3116
+ "image/png",
3117
+ "image/jpeg",
3118
+ "image/webp",
3119
+ "image/gif"
3120
+ ]);
3121
+ function isAllowedImageMediaType(mediaType) {
3122
+ return ALLOWED_IMAGE_MEDIA_TYPES.has(mediaType.toLowerCase());
3123
+ }
3124
+ function isValidImageBase64(base64) {
3125
+ return /^[A-Za-z0-9+/]+={0,2}$/.test(base64);
3126
+ }
3127
+ function base64DecodedBytes(base64) {
3128
+ return Math.floor(base64.length * 3 / 4);
3129
+ }
3130
+ var IncomingImageError = class extends Error {
3131
+ constructor(message) {
3132
+ super(message);
3133
+ this.name = "IncomingImageError";
3134
+ }
3135
+ };
3136
+ var DATA_URL_RE = /^data:([a-z0-9.+-]+\/[a-z0-9.+-]+)?(?:;[a-z0-9-]+=[^;,]*)*(;base64)?,/i;
3137
+ function splitDataUrl(data) {
3138
+ const match = DATA_URL_RE.exec(data);
3139
+ if (!match) return { base64: data.trim() };
3140
+ return {
3141
+ base64: data.slice(match[0].length).trim(),
3142
+ mediaType: match[1]?.toLowerCase()
3143
+ };
3144
+ }
3145
+ function parseIncomingImages(images, legacyImageBase64) {
3146
+ const raw = [...images ?? []];
3147
+ if (legacyImageBase64) raw.push({ data: legacyImageBase64 });
3148
+ if (raw.length === 0) return [];
3149
+ if (raw.length > MAX_INCOMING_IMAGES) {
3150
+ throw new IncomingImageError(
3151
+ `Too many images: ${raw.length} (max ${MAX_INCOMING_IMAGES} per message).`
2196
3152
  );
2197
3153
  }
2198
3154
  return raw.map((img, i) => {
2199
3155
  const { base64, mediaType: fromUrl } = splitDataUrl(img.data ?? "");
2200
3156
  const mediaType = (img.mediaType ?? fromUrl ?? "image/png").toLowerCase();
2201
- if (!ALLOWED_IMAGE_MEDIA_TYPES.has(mediaType)) {
3157
+ if (!isAllowedImageMediaType(mediaType)) {
2202
3158
  throw new IncomingImageError(
2203
3159
  `Image ${i + 1}: unsupported media type "${mediaType}" (allowed: ${[...ALLOWED_IMAGE_MEDIA_TYPES].join(", ")}).`
2204
3160
  );
@@ -2206,10 +3162,10 @@ function parseIncomingImages(images, legacyImageBase64) {
2206
3162
  if (!base64) {
2207
3163
  throw new IncomingImageError(`Image ${i + 1}: empty image data.`);
2208
3164
  }
2209
- if (!/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
3165
+ if (!isValidImageBase64(base64)) {
2210
3166
  throw new IncomingImageError(`Image ${i + 1}: data is not valid base64.`);
2211
3167
  }
2212
- const bytes = Math.floor(base64.length * 3 / 4);
3168
+ const bytes = base64DecodedBytes(base64);
2213
3169
  if (bytes > MAX_INCOMING_IMAGE_BYTES) {
2214
3170
  throw new IncomingImageError(
2215
3171
  `Image ${i + 1}: ${(bytes / (1024 * 1024)).toFixed(1)} MB exceeds the ${MAX_INCOMING_IMAGE_BYTES / (1024 * 1024)} MB limit.`
@@ -2227,6 +3183,51 @@ function buildUserContentBlocks(text, images) {
2227
3183
  return blocks;
2228
3184
  }
2229
3185
 
3186
+ // src/utils/instruction-file.ts
3187
+ import { readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
3188
+ import * as path6 from "node:path";
3189
+ import { fileURLToPath } from "node:url";
3190
+ var textCache = /* @__PURE__ */ new Map();
3191
+ var rootCandidates;
3192
+ function readBundledInstructionText(relativePath) {
3193
+ const cached2 = textCache.get(relativePath);
3194
+ if (cached2 !== void 0) return cached2;
3195
+ let resolved = "";
3196
+ for (const root of instructionRootCandidates()) {
3197
+ try {
3198
+ resolved = readFileSync2(path6.join(root, relativePath), "utf8").trimEnd();
3199
+ break;
3200
+ } catch {
3201
+ }
3202
+ }
3203
+ textCache.set(relativePath, resolved);
3204
+ return resolved;
3205
+ }
3206
+ function renderInstructionTemplate(template, values) {
3207
+ return template.replace(
3208
+ /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g,
3209
+ (match, key) => Object.hasOwn(values, key) ? values[key] ?? "" : match
3210
+ );
3211
+ }
3212
+ function instructionRootCandidates() {
3213
+ if (rootCandidates !== void 0) return rootCandidates;
3214
+ const here = path6.dirname(fileURLToPath(import.meta.url));
3215
+ const candidates = [
3216
+ path6.resolve(here, "../../instructions"),
3217
+ path6.resolve(here, "../instructions"),
3218
+ path6.resolve(here, "instructions")
3219
+ ];
3220
+ rootCandidates = candidates.sort((a, b) => Number(!isDirectory(a)) - Number(!isDirectory(b)));
3221
+ return rootCandidates;
3222
+ }
3223
+ function isDirectory(candidate) {
3224
+ try {
3225
+ return statSync2(candidate).isDirectory();
3226
+ } catch {
3227
+ return false;
3228
+ }
3229
+ }
3230
+
2230
3231
  // src/utils/ip-guard.ts
2231
3232
  import * as dns from "node:dns/promises";
2232
3233
  import * as net from "node:net";
@@ -2252,6 +3253,7 @@ function isPrivateIPv6(raw) {
2252
3253
  if (lower === "::" || lower === "::1") return true;
2253
3254
  const groups = expandIPv6(lower);
2254
3255
  if (!groups) return true;
3256
+ if (groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return true;
2255
3257
  if (groups[0] === 0 && groups[1] === 0 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 65535) {
2256
3258
  const a = (groups[6] ?? 0) >> 8;
2257
3259
  const b = (groups[6] ?? 0) & 255;
@@ -2259,12 +3261,36 @@ function isPrivateIPv6(raw) {
2259
3261
  const d = (groups[7] ?? 0) & 255;
2260
3262
  return isPrivateIPv4(`${a}.${b}.${c}.${d}`);
2261
3263
  }
3264
+ const embedded = embeddedIPv4(groups);
3265
+ if (embedded) return isPrivateIPv4(embedded);
2262
3266
  const high = groups[0] ?? 0;
2263
3267
  if ((high & 65024) === 64512) return true;
2264
3268
  if ((high & 65472) === 65152) return true;
2265
3269
  if ((high & 65280) === 65280) return true;
2266
3270
  return false;
2267
3271
  }
3272
+ function quad(hi, lo) {
3273
+ return `${(hi ?? 0) >> 8}.${(hi ?? 0) & 255}.${(lo ?? 0) >> 8}.${(lo ?? 0) & 255}`;
3274
+ }
3275
+ function embeddedIPv4(groups) {
3276
+ const g = (i) => groups[i] ?? 0;
3277
+ if (g(0) === 100 && g(1) === 65435) {
3278
+ if (g(2) === 0 && g(3) === 0 && g(4) === 0 && g(5) === 0) {
3279
+ return quad(g(6), g(7));
3280
+ }
3281
+ }
3282
+ if (g(0) === 8194) return quad(g(1), g(2));
3283
+ if (g(0) === 8193 && g(1) === 0) {
3284
+ return quad(~g(6) & 65535, ~g(7) & 65535);
3285
+ }
3286
+ if ((g(4) === 0 || g(4) === 512) && g(5) === 24318) {
3287
+ return quad(g(6), g(7));
3288
+ }
3289
+ const highZero = g(0) === 0 && g(1) === 0 && g(2) === 0 && g(3) === 0;
3290
+ if (highZero && g(4) === 65535 && g(5) === 0) return quad(g(6), g(7));
3291
+ if (highZero && g(4) === 0 && g(5) === 0) return quad(g(6), g(7));
3292
+ return void 0;
3293
+ }
2268
3294
  function expandIPv6(addr) {
2269
3295
  const parts = addr.split("::");
2270
3296
  if (parts.length > 2) return null;
@@ -2320,51 +3346,6 @@ async function assertNotPrivateHost(hostname) {
2320
3346
  }
2321
3347
  }
2322
3348
 
2323
- // src/utils/instruction-file.ts
2324
- import { readFileSync, statSync } from "node:fs";
2325
- import * as path3 from "node:path";
2326
- import { fileURLToPath } from "node:url";
2327
- var textCache = /* @__PURE__ */ new Map();
2328
- var rootCandidates;
2329
- function readBundledInstructionText(relativePath) {
2330
- const cached2 = textCache.get(relativePath);
2331
- if (cached2 !== void 0) return cached2;
2332
- let resolved = "";
2333
- for (const root of instructionRootCandidates()) {
2334
- try {
2335
- resolved = readFileSync(path3.join(root, relativePath), "utf8").trimEnd();
2336
- break;
2337
- } catch {
2338
- }
2339
- }
2340
- textCache.set(relativePath, resolved);
2341
- return resolved;
2342
- }
2343
- function renderInstructionTemplate(template, values) {
2344
- return template.replace(
2345
- /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g,
2346
- (match, key) => Object.hasOwn(values, key) ? values[key] ?? "" : match
2347
- );
2348
- }
2349
- function instructionRootCandidates() {
2350
- if (rootCandidates !== void 0) return rootCandidates;
2351
- const here = path3.dirname(fileURLToPath(import.meta.url));
2352
- const candidates = [
2353
- path3.resolve(here, "../../instructions"),
2354
- path3.resolve(here, "../instructions"),
2355
- path3.resolve(here, "instructions")
2356
- ];
2357
- rootCandidates = candidates.sort((a, b) => Number(!isDirectory(a)) - Number(!isDirectory(b)));
2358
- return rootCandidates;
2359
- }
2360
- function isDirectory(candidate) {
2361
- try {
2362
- return statSync(candidate).isDirectory();
2363
- } catch {
2364
- return false;
2365
- }
2366
- }
2367
-
2368
3349
  // src/utils/json-repair.ts
2369
3350
  function completePartialObject(s) {
2370
3351
  if (!s.trim().startsWith("{")) return s;
@@ -2464,10 +3445,10 @@ function validateAgainstSchema(value, schema) {
2464
3445
  return { ok: errors.length === 0, errors };
2465
3446
  }
2466
3447
  var MAX_SCHEMA_DEPTH = 64;
2467
- function walk(value, schema, path9, errors, depth) {
3448
+ function walk(value, schema, path11, errors, depth) {
2468
3449
  if (depth > MAX_SCHEMA_DEPTH) {
2469
3450
  errors.push({
2470
- path: path9 || "<root>",
3451
+ path: path11 || "<root>",
2471
3452
  message: `schema nesting exceeds maximum depth (${MAX_SCHEMA_DEPTH})`
2472
3453
  });
2473
3454
  return;
@@ -2475,7 +3456,7 @@ function walk(value, schema, path9, errors, depth) {
2475
3456
  if (schema.enum !== void 0) {
2476
3457
  if (!enumIncludes(schema.enum, value)) {
2477
3458
  errors.push({
2478
- path: path9 || "<root>",
3459
+ path: path11 || "<root>",
2479
3460
  message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`
2480
3461
  });
2481
3462
  return;
@@ -2484,7 +3465,7 @@ function walk(value, schema, path9, errors, depth) {
2484
3465
  if (typeof schema.type === "string") {
2485
3466
  if (!checkType(value, schema.type)) {
2486
3467
  errors.push({
2487
- path: path9 || "<root>",
3468
+ path: path11 || "<root>",
2488
3469
  message: `expected ${schema.type}, got ${describeType(value)} (${previewValue(value)})`
2489
3470
  });
2490
3471
  return;
@@ -2496,7 +3477,7 @@ function walk(value, schema, path9, errors, depth) {
2496
3477
  if (!(req in obj)) {
2497
3478
  const expected = schema.properties?.[req]?.type;
2498
3479
  errors.push({
2499
- path: joinPath(path9, req),
3480
+ path: joinPath(path11, req),
2500
3481
  message: `required property missing${typeof expected === "string" ? ` (expected ${expected})` : ""}`
2501
3482
  });
2502
3483
  }
@@ -2504,14 +3485,14 @@ function walk(value, schema, path9, errors, depth) {
2504
3485
  if (schema.properties) {
2505
3486
  for (const [key, subSchema] of Object.entries(schema.properties)) {
2506
3487
  if (key in obj) {
2507
- walk(obj[key], subSchema, joinPath(path9, key), errors, depth + 1);
3488
+ walk(obj[key], subSchema, joinPath(path11, key), errors, depth + 1);
2508
3489
  }
2509
3490
  }
2510
3491
  }
2511
3492
  }
2512
3493
  if (schema.type === "array" && Array.isArray(value) && schema.items) {
2513
3494
  for (let i = 0; i < value.length; i++) {
2514
- walk(value[i], schema.items, `${path9}[${i}]`, errors, depth + 1);
3495
+ walk(value[i], schema.items, `${path11}[${i}]`, errors, depth + 1);
2515
3496
  }
2516
3497
  }
2517
3498
  }
@@ -2768,6 +3749,29 @@ function normalizeToLf(text) {
2768
3749
  return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
2769
3750
  }
2770
3751
 
3752
+ // src/utils/path-segment.ts
3753
+ import * as path7 from "node:path";
3754
+ var MAX_PATH_SEGMENT_LENGTH = 256;
3755
+ function isSafePathSegment(value) {
3756
+ if (value.length === 0 || value.length > MAX_PATH_SEGMENT_LENGTH) return false;
3757
+ if (value === "." || value === "..") return false;
3758
+ if (value.includes("/") || value.includes("\\")) return false;
3759
+ if (value.includes("\0")) return false;
3760
+ if (value.includes(":")) return false;
3761
+ return true;
3762
+ }
3763
+ function resolveContainedPath(root, ...segments) {
3764
+ if (segments.length === 0) return null;
3765
+ for (const segment of segments) {
3766
+ if (!isSafePathSegment(segment)) return null;
3767
+ }
3768
+ const resolvedRoot = path7.resolve(root);
3769
+ const candidate = path7.resolve(resolvedRoot, ...segments);
3770
+ if (candidate === resolvedRoot) return null;
3771
+ if (!candidate.startsWith(resolvedRoot + path7.sep)) return null;
3772
+ return candidate;
3773
+ }
3774
+
2771
3775
  // src/utils/perf-profile.ts
2772
3776
  var daemonDefaults = false;
2773
3777
  function useDaemonPerfDefaults() {
@@ -2825,9 +3829,9 @@ function isPidAlive(pid) {
2825
3829
  }
2826
3830
 
2827
3831
  // src/utils/project-identity.ts
2828
- import * as fs3 from "node:fs";
3832
+ import * as fs5 from "node:fs";
2829
3833
  import * as fsPromises from "node:fs/promises";
2830
- import * as path4 from "node:path";
3834
+ import * as path8 from "node:path";
2831
3835
 
2832
3836
  // src/utils/ulid.ts
2833
3837
  import { randomBytes } from "node:crypto";
@@ -2867,7 +3871,7 @@ function isUlid(value) {
2867
3871
  // src/utils/project-identity.ts
2868
3872
  var PROJECT_IDENTITY_VERSION = 1;
2869
3873
  var PROJECT_ID_PREFIX = "proj_";
2870
- var PROJECT_IDENTITY_RELATIVE_PATH = path4.join(".wrongstack", "project.json");
3874
+ var PROJECT_IDENTITY_RELATIVE_PATH = path8.join(".wrongstack", "project.json");
2871
3875
  var PROJECT_GITIGNORE_RULES = [
2872
3876
  ".wrongstack/",
2873
3877
  "!/.wrongstack/",
@@ -2875,7 +3879,7 @@ var PROJECT_GITIGNORE_RULES = [
2875
3879
  "!/.wrongstack/project.json"
2876
3880
  ];
2877
3881
  function projectIdentityPath(projectRoot) {
2878
- return path4.join(projectRoot, PROJECT_IDENTITY_RELATIVE_PATH);
3882
+ return path8.join(projectRoot, PROJECT_IDENTITY_RELATIVE_PATH);
2879
3883
  }
2880
3884
  function createProjectId(seedTime = Date.now()) {
2881
3885
  return `${PROJECT_ID_PREFIX}${ulid(seedTime)}`;
@@ -2886,7 +3890,7 @@ function isProjectId(value) {
2886
3890
  function readProjectIdentitySync(projectRoot) {
2887
3891
  const filePath = projectIdentityPath(projectRoot);
2888
3892
  try {
2889
- return parseProjectIdentity(fs3.readFileSync(filePath, "utf8"), filePath);
3893
+ return parseProjectIdentity(fs5.readFileSync(filePath, "utf8"), filePath);
2890
3894
  } catch (error) {
2891
3895
  if (isMissingFileError(error)) return void 0;
2892
3896
  throw error;
@@ -2906,7 +3910,7 @@ async function ensureProjectIdentity(projectRoot, idFactory = createProjectId) {
2906
3910
  if (existing) return { identity: existing, created: false };
2907
3911
  const filePath = projectIdentityPath(projectRoot);
2908
3912
  const identity = makeIdentity(idFactory());
2909
- await fsPromises.mkdir(path4.dirname(filePath), { recursive: true });
3913
+ await fsPromises.mkdir(path8.dirname(filePath), { recursive: true });
2910
3914
  try {
2911
3915
  await fsPromises.writeFile(filePath, serializeProjectIdentity(identity), {
2912
3916
  encoding: "utf8",
@@ -2924,12 +3928,12 @@ async function rekeyProjectIdentity(projectRoot, idFactory = createProjectId) {
2924
3928
  const previous = await readProjectIdentity(projectRoot);
2925
3929
  const identity = makeIdentity(idFactory());
2926
3930
  const filePath = projectIdentityPath(projectRoot);
2927
- await fsPromises.mkdir(path4.dirname(filePath), { recursive: true });
3931
+ await fsPromises.mkdir(path8.dirname(filePath), { recursive: true });
2928
3932
  await atomicWrite(filePath, serializeProjectIdentity(identity));
2929
3933
  return { previous, identity };
2930
3934
  }
2931
3935
  async function ensureProjectGitignore(projectRoot) {
2932
- const filePath = path4.join(projectRoot, ".gitignore");
3936
+ const filePath = path8.join(projectRoot, ".gitignore");
2933
3937
  let content = "";
2934
3938
  try {
2935
3939
  content = await fsPromises.readFile(filePath, "utf8");
@@ -2993,6 +3997,73 @@ function isAlreadyExistsError(error) {
2993
3997
  return error?.code === "EEXIST";
2994
3998
  }
2995
3999
 
4000
+ // src/utils/project-watch.ts
4001
+ import * as fs6 from "node:fs";
4002
+ import * as path9 from "node:path";
4003
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("wrongstack.projectWatchRegistry");
4004
+ var globalScope = globalThis;
4005
+ if (!globalScope[REGISTRY_KEY]) globalScope[REGISTRY_KEY] = /* @__PURE__ */ new Map();
4006
+ var registry = globalScope[REGISTRY_KEY];
4007
+ function registryKey(root) {
4008
+ const resolved = path9.resolve(root);
4009
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
4010
+ }
4011
+ function watchProjectTree(root, listener, opts) {
4012
+ const key = registryKey(root);
4013
+ let entry = registry.get(key);
4014
+ if (!entry || entry.dead) {
4015
+ const subscribers = /* @__PURE__ */ new Set();
4016
+ const watcher = fs6.watch(
4017
+ path9.resolve(root),
4018
+ { recursive: true, persistent: false },
4019
+ (eventType, filename) => {
4020
+ const event = {
4021
+ eventType: eventType === "rename" ? "rename" : "change",
4022
+ filename: filename === null ? null : String(filename)
4023
+ };
4024
+ for (const sub of subscribers) {
4025
+ try {
4026
+ sub.listener(event);
4027
+ } catch (error) {
4028
+ sub.onError?.(error);
4029
+ }
4030
+ }
4031
+ }
4032
+ );
4033
+ const created = { watcher, subscribers, dead: false };
4034
+ const retire = () => {
4035
+ created.dead = true;
4036
+ if (registry.get(key) === created) registry.delete(key);
4037
+ };
4038
+ watcher.on("error", (error) => {
4039
+ retire();
4040
+ for (const sub of subscribers) sub.onError?.(error);
4041
+ });
4042
+ watcher.on("close", retire);
4043
+ registry.set(key, created);
4044
+ entry = created;
4045
+ }
4046
+ const active = entry;
4047
+ const subscriber = { listener, onError: opts?.onError };
4048
+ active.subscribers.add(subscriber);
4049
+ let closed = false;
4050
+ return {
4051
+ close() {
4052
+ if (closed) return;
4053
+ closed = true;
4054
+ active.subscribers.delete(subscriber);
4055
+ if (active.subscribers.size === 0 && !active.dead) {
4056
+ active.dead = true;
4057
+ if (registry.get(key) === active) registry.delete(key);
4058
+ try {
4059
+ active.watcher.close();
4060
+ } catch {
4061
+ }
4062
+ }
4063
+ }
4064
+ };
4065
+ }
4066
+
2996
4067
  // src/utils/regex-guard.ts
2997
4068
  var MAX_PATTERN_LEN = 512;
2998
4069
  var DANGEROUS_PATTERNS = [
@@ -3169,14 +4240,14 @@ function stripJsonComments(s) {
3169
4240
  }
3170
4241
 
3171
4242
  // src/utils/session-scoped-path.ts
3172
- import * as path5 from "node:path";
4243
+ import * as path10 from "node:path";
3173
4244
  function sessionScopedPath(dir, sessionId, suffix) {
3174
4245
  if (!sessionId || sessionId.includes("\\") || sessionId.includes("..")) {
3175
4246
  throw invalid(sessionId);
3176
4247
  }
3177
- const resolved = path5.resolve(dir, `${sessionId}${suffix}`);
3178
- const rel = path5.relative(path5.resolve(dir), resolved);
3179
- if (rel.startsWith("..") || path5.isAbsolute(rel)) {
4248
+ const resolved = path10.resolve(dir, `${sessionId}${suffix}`);
4249
+ const rel = path10.relative(path10.resolve(dir), resolved);
4250
+ if (rel.startsWith("..") || path10.isAbsolute(rel)) {
3180
4251
  throw invalid(sessionId);
3181
4252
  }
3182
4253
  return resolved;
@@ -3190,6 +4261,16 @@ function invalid(sessionId) {
3190
4261
  });
3191
4262
  }
3192
4263
 
4264
+ // src/utils/sleep.ts
4265
+ function sleep(ms) {
4266
+ return new Promise((resolve9) => setTimeout(resolve9, ms));
4267
+ }
4268
+
4269
+ // src/utils/slug.ts
4270
+ function slugify2(name, fallback = "prompt", maxLen = 64) {
4271
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLen).replace(/-+$/g, "") || fallback;
4272
+ }
4273
+
3193
4274
  // src/utils/socket-path.ts
3194
4275
  import {
3195
4276
  assertUnixSocketPathWithinLimit,
@@ -3220,16 +4301,6 @@ function withSqliteExperimentalWarningSuppressed(run) {
3220
4301
  }
3221
4302
  }
3222
4303
 
3223
- // src/utils/sleep.ts
3224
- function sleep(ms) {
3225
- return new Promise((resolve7) => setTimeout(resolve7, ms));
3226
- }
3227
-
3228
- // src/utils/slug.ts
3229
- function slugify(name, fallback = "prompt", maxLen = 64) {
3230
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, maxLen).replace(/-+$/g, "") || fallback;
3231
- }
3232
-
3233
4304
  // src/utils/string.ts
3234
4305
  function truncate(s, max) {
3235
4306
  return s.length <= max ? s : `${s.slice(0, max - 1)}\u2026`;
@@ -3471,6 +4542,23 @@ function findWordBoundary(text, limit) {
3471
4542
  return space > 40 ? space : limit;
3472
4543
  }
3473
4544
 
4545
+ // src/utils/tool-name.ts
4546
+ var WIRE_TOOL_NAME_MAX_LENGTH = 128;
4547
+ var WIRE_TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,128}$/;
4548
+ function sanitizeWireToolName(name) {
4549
+ const replaced = name.replace(/[^a-zA-Z0-9_-]/g, "_");
4550
+ const clamped = replaced.slice(0, WIRE_TOOL_NAME_MAX_LENGTH);
4551
+ return clamped.length > 0 ? clamped : "tool";
4552
+ }
4553
+ function mcpServerToolPrefix(serverName) {
4554
+ return `mcp__${sanitizeWireToolName(serverName)}__`;
4555
+ }
4556
+ function mcpQualifiedToolName(serverName, toolName) {
4557
+ return sanitizeWireToolName(
4558
+ `${mcpServerToolPrefix(serverName)}${sanitizeWireToolName(toolName)}`
4559
+ );
4560
+ }
4561
+
3474
4562
  // src/utils/tool-output-serializer.ts
3475
4563
  var DEFAULT_LIST_LIMIT = 500;
3476
4564
  var LOG_ENTRY_LIMIT = 200;
@@ -3528,12 +4616,38 @@ function createToolOutputSerializer(opts = {}) {
3528
4616
  return { text: "[truncated: iteration output cap exceeded]", newBudget: 0 };
3529
4617
  }
3530
4618
  const half = Math.floor(available / 2);
3531
- const first = text.slice(0, half);
3532
- const second = text.slice(text.length - half);
4619
+ const first = utf8Prefix(text, half);
4620
+ const second = utf8Suffix(text, available - Buffer.byteLength(first, "utf8"));
3533
4621
  return { text: `${first}${marker}${second}`, newBudget: 0 };
3534
4622
  }
3535
4623
  return { serialize, enforceCap, capBytes };
3536
4624
  }
4625
+ function utf8Prefix(text, maxBytes) {
4626
+ if (maxBytes <= 0) return "";
4627
+ let low = 0;
4628
+ let high = text.length;
4629
+ while (low < high) {
4630
+ const mid = Math.ceil((low + high) / 2);
4631
+ if (Buffer.byteLength(text.slice(0, mid), "utf8") <= maxBytes) low = mid;
4632
+ else high = mid - 1;
4633
+ }
4634
+ let end = low;
4635
+ if (end > 0 && /[\uD800-\uDBFF]/.test(text[end - 1])) end--;
4636
+ return text.slice(0, end);
4637
+ }
4638
+ function utf8Suffix(text, maxBytes) {
4639
+ if (maxBytes <= 0) return "";
4640
+ let low = 0;
4641
+ let high = text.length;
4642
+ while (low < high) {
4643
+ const chars = Math.ceil((low + high) / 2);
4644
+ if (Buffer.byteLength(text.slice(text.length - chars), "utf8") <= maxBytes) low = chars;
4645
+ else high = chars - 1;
4646
+ }
4647
+ let start = text.length - low;
4648
+ if (start < text.length && /[\uDC00-\uDFFF]/.test(text[start])) start++;
4649
+ return text.slice(start);
4650
+ }
3537
4651
  function renderToolObject(toolName, obj, input) {
3538
4652
  if (toolName === "read" && typeof obj["text"] === "string") {
3539
4653
  return joinSections([
@@ -4182,13 +5296,43 @@ function normalizePathSubject(value) {
4182
5296
  function isPathSubjectKey(subjectKey) {
4183
5297
  return subjectKey === "path" || subjectKey === "file" || subjectKey === "files";
4184
5298
  }
5299
+ function renderCommandLine(command, args) {
5300
+ if (!Array.isArray(args) || args.length === 0) return command;
5301
+ const rendered = args.map((arg) => {
5302
+ const str = String(arg);
5303
+ return /\s/.test(str) ? `"${str.replace(/"/g, '\\"')}"` : str;
5304
+ });
5305
+ return [command, ...rendered].join(" ");
5306
+ }
4185
5307
  function subjectForToolInput(toolName, input, subjectKey) {
4186
5308
  if (!input || typeof input !== "object") return void 0;
4187
5309
  const obj = input;
4188
5310
  if (subjectKey) {
4189
5311
  const value = obj[subjectKey];
4190
5312
  if (typeof value === "string") {
4191
- return isPathSubjectKey(subjectKey) ? normalizePathSubject(value) : escapeGlobSubject(value);
5313
+ if (isPathSubjectKey(subjectKey)) {
5314
+ const normalized = normalizePathSubject(value);
5315
+ if (subjectKey === "files" && obj["check"] === true) return `${normalized}:check`;
5316
+ if (subjectKey === "files" && obj["dry_run"] === true) return `${normalized}:dry-run`;
5317
+ return normalized;
5318
+ }
5319
+ if (subjectKey === "command") {
5320
+ const rendered = renderCommandLine(value, obj["args"]);
5321
+ if (value === "commit" && obj["dry_run"] === true) {
5322
+ return `${escapeGlobSubject(rendered)}:dry-run`;
5323
+ }
5324
+ return escapeGlobSubject(rendered);
5325
+ }
5326
+ if (subjectKey === "directory" && obj["dry_run"] === true) {
5327
+ return `${escapeGlobSubject(value)}:dry-run`;
5328
+ }
5329
+ if (subjectKey === "packages" && obj["dry_run"] === true) {
5330
+ return `${escapeGlobSubject(value)}:dry-run`;
5331
+ }
5332
+ if (subjectKey === "name" && obj["dry_run"] === true) {
5333
+ return `${escapeGlobSubject(value)}:dry-run`;
5334
+ }
5335
+ return escapeGlobSubject(value);
4192
5336
  }
4193
5337
  }
4194
5338
  if (toolName === "bash" && typeof obj.command === "string") {
@@ -4206,73 +5350,6 @@ function subjectForToolInput(toolName, input, subjectKey) {
4206
5350
  return void 0;
4207
5351
  }
4208
5352
 
4209
- // src/utils/project-watch.ts
4210
- import * as fs4 from "node:fs";
4211
- import * as path6 from "node:path";
4212
- var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("wrongstack.projectWatchRegistry");
4213
- var globalScope = globalThis;
4214
- if (!globalScope[REGISTRY_KEY]) globalScope[REGISTRY_KEY] = /* @__PURE__ */ new Map();
4215
- var registry = globalScope[REGISTRY_KEY];
4216
- function registryKey(root) {
4217
- const resolved = path6.resolve(root);
4218
- return process.platform === "win32" ? resolved.toLowerCase() : resolved;
4219
- }
4220
- function watchProjectTree(root, listener, opts) {
4221
- const key = registryKey(root);
4222
- let entry = registry.get(key);
4223
- if (!entry || entry.dead) {
4224
- const subscribers = /* @__PURE__ */ new Set();
4225
- const watcher = fs4.watch(
4226
- path6.resolve(root),
4227
- { recursive: true, persistent: false },
4228
- (eventType, filename) => {
4229
- const event = {
4230
- eventType: eventType === "rename" ? "rename" : "change",
4231
- filename: filename === null ? null : String(filename)
4232
- };
4233
- for (const sub of subscribers) {
4234
- try {
4235
- sub.listener(event);
4236
- } catch (error) {
4237
- sub.onError?.(error);
4238
- }
4239
- }
4240
- }
4241
- );
4242
- const created = { watcher, subscribers, dead: false };
4243
- const retire = () => {
4244
- created.dead = true;
4245
- if (registry.get(key) === created) registry.delete(key);
4246
- };
4247
- watcher.on("error", (error) => {
4248
- retire();
4249
- for (const sub of subscribers) sub.onError?.(error);
4250
- });
4251
- watcher.on("close", retire);
4252
- registry.set(key, created);
4253
- entry = created;
4254
- }
4255
- const active = entry;
4256
- const subscriber = { listener, onError: opts?.onError };
4257
- active.subscribers.add(subscriber);
4258
- let closed = false;
4259
- return {
4260
- close() {
4261
- if (closed) return;
4262
- closed = true;
4263
- active.subscribers.delete(subscriber);
4264
- if (active.subscribers.size === 0 && !active.dead) {
4265
- active.dead = true;
4266
- if (registry.get(key) === active) registry.delete(key);
4267
- try {
4268
- active.watcher.close();
4269
- } catch {
4270
- }
4271
- }
4272
- }
4273
- };
4274
- }
4275
-
4276
5353
  // src/utils/walk-ignore.ts
4277
5354
  var DEFAULT_WALK_IGNORE_DIRS = Object.freeze([
4278
5355
  "node_modules",
@@ -4296,250 +5373,31 @@ var DEFAULT_WALK_IGNORE_DIRS = Object.freeze([
4296
5373
  ]);
4297
5374
  var DEFAULT_WALK_IGNORE_SET = new Set(DEFAULT_WALK_IGNORE_DIRS);
4298
5375
 
4299
- // src/utils/wstack-paths.ts
4300
- import { createHash as createHash2 } from "node:crypto";
4301
- import * as fs5 from "node:fs";
4302
- import * as os from "node:os";
4303
- import * as path7 from "node:path";
4304
- function canonicalProjectRoot(absRoot) {
4305
- const checkoutRoot = path7.resolve(absRoot);
4306
- const dotGit = path7.join(checkoutRoot, ".git");
4307
- try {
4308
- if (!fs5.statSync(dotGit).isFile()) return checkoutRoot;
4309
- const gitDirLine = fs5.readFileSync(dotGit, "utf8").trim();
4310
- const match = /^gitdir:\s*(.+)$/i.exec(gitDirLine);
4311
- if (!match?.[1]) return checkoutRoot;
4312
- const gitDir = path7.resolve(checkoutRoot, match[1].trim());
4313
- const commonDirFile = path7.join(gitDir, "commondir");
4314
- if (!fs5.statSync(commonDirFile).isFile()) return checkoutRoot;
4315
- const commonDir = path7.resolve(gitDir, fs5.readFileSync(commonDirFile, "utf8").trim());
4316
- if (path7.basename(commonDir).toLowerCase() !== ".git") return checkoutRoot;
4317
- return path7.dirname(commonDir);
4318
- } catch {
4319
- return checkoutRoot;
4320
- }
4321
- }
4322
- function projectHash(absRoot) {
4323
- return createHash2("sha256").update(canonicalProjectRoot(absRoot)).digest("hex").slice(0, 12);
4324
- }
4325
- function projectSlug(absRoot) {
4326
- const identityRoot = canonicalProjectRoot(absRoot);
4327
- const base = slugify2(path7.basename(identityRoot));
4328
- const hash = createHash2("sha256").update(identityRoot).digest("hex").slice(0, 6);
4329
- return `${base}-${hash}`;
4330
- }
4331
- function slugify2(name) {
4332
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "project";
4333
- }
4334
- function safeProfileName(name) {
4335
- const safe = (name ?? "").replace(/[/\\:]/g, "_").replace(/\.\./g, "_").trim();
4336
- return safe || "default";
4337
- }
4338
- function activeProfileName(globalRoot) {
4339
- try {
4340
- const parsed = JSON.parse(fs5.readFileSync(path7.join(globalRoot, "config.json"), "utf8"));
4341
- return safeProfileName(typeof parsed.activeProfile === "string" ? parsed.activeProfile : void 0);
4342
- } catch {
4343
- return "default";
4344
- }
4345
- }
4346
- function wstackGlobalRoot() {
4347
- const fromEnv = process.env["WRONGSTACK_HOME"];
4348
- if (fromEnv && fromEnv.trim().length > 0) return path7.resolve(fromEnv);
4349
- return path7.join(os.homedir(), ".wrongstack");
4350
- }
4351
- function resolveWstackPaths(opts) {
4352
- const globalRoot = opts.globalRoot ?? (opts.userHome ? path7.join(opts.userHome, ".wrongstack") : wstackGlobalRoot());
4353
- const homeDir = opts.userHome ?? os.homedir();
4354
- const profileName = safeProfileName(opts.profileName ?? activeProfileName(globalRoot));
4355
- const profileDir = path7.join(globalRoot, "profiles", profileName);
4356
- const hash = projectHash(opts.projectRoot);
4357
- const slug = projectSlug(opts.projectRoot);
4358
- const projectDir = path7.join(globalRoot, "projects", slug);
4359
- return {
4360
- globalRoot,
4361
- profileName,
4362
- profileDir,
4363
- projectRoot: opts.projectRoot,
4364
- homeDir,
4365
- configDir: profileDir,
4366
- globalConfig: path7.join(globalRoot, "config.json"),
4367
- profilesDir: path7.join(globalRoot, "profiles"),
4368
- profileConfig: (name) => {
4369
- return path7.join(globalRoot, "profiles", safeProfileName(name), "config.json");
4370
- },
4371
- profileStatuslineConfig: (name) => {
4372
- return path7.join(globalRoot, "profiles", safeProfileName(name), "statusline.json");
4373
- },
4374
- profileModeConfig: (name) => {
4375
- return path7.join(globalRoot, "profiles", safeProfileName(name), "mode.json");
4376
- },
4377
- profileProviderStatus: (name) => {
4378
- return path7.join(globalRoot, "profiles", safeProfileName(name), "provider-status.json");
4379
- },
4380
- profileUpdateCache: (name) => {
4381
- return path7.join(globalRoot, "profiles", safeProfileName(name), "update-cache.json");
4382
- },
4383
- secretsKey: path7.join(globalRoot, ".key"),
4384
- globalMemory: path7.join(profileDir, "memory.md"),
4385
- globalSkills: path7.join(profileDir, "skills"),
4386
- globalClaudeSkills: path7.join(homeDir, ".claude", "skills"),
4387
- globalDesignKits: path7.join(profileDir, "design-kits"),
4388
- globalPrompts: path7.join(profileDir, "prompts"),
4389
- globalInstructions: path7.join(profileDir, "instructions"),
4390
- promptUsage: path7.join(profileDir, "prompt-usage.json"),
4391
- cacheDir: path7.join(globalRoot, "cache"),
4392
- modelsCache: path7.join(globalRoot, "cache", "models.dev.json"),
4393
- modelsOverlayCache: path7.join(globalRoot, "cache", "models-overlay.json"),
4394
- historyFile: path7.join(profileDir, "history"),
4395
- logFile: path7.join(globalRoot, "logs", "wrongstack.log"),
4396
- projectDir,
4397
- projectCodebaseIndex: path7.join(projectDir, "codebase-index"),
4398
- projectMemory: path7.join(projectDir, "memory.md"),
4399
- projectSessions: path7.join(projectDir, "sessions"),
4400
- projectTrust: path7.join(projectDir, "trust.json"),
4401
- projectMeta: path7.join(projectDir, "meta.json"),
4402
- projectLocalConfig: path7.join(projectDir, "config.local.json"),
4403
- inProjectConfig: path7.join(opts.projectRoot, ".wrongstack", "config.json"),
4404
- inProjectAgentsFile: path7.join(opts.projectRoot, ".wrongstack", "AGENTS.md"),
4405
- inProjectSkills: path7.join(opts.projectRoot, ".wrongstack", "skills"),
4406
- inProjectClaudeSkills: path7.join(opts.projectRoot, ".claude", "skills"),
4407
- inProjectPrompts: path7.join(opts.projectRoot, ".wrongstack", "prompts"),
4408
- inProjectInstructions: path7.join(opts.projectRoot, ".wrongstack", "instructions"),
4409
- inProjectDesignKits: path7.join(opts.projectRoot, ".wrongstack", "design-kits"),
4410
- inProjectWorktrees: path7.join(opts.projectRoot, ".wrongstack", "worktrees"),
4411
- projectHash: hash,
4412
- projectSlug: slug,
4413
- projectGoal: path7.join(projectDir, "goal.json"),
4414
- projectInputHistory: path7.join(projectDir, "input-history.json"),
4415
- projectSpecs: path7.join(projectDir, "specs"),
4416
- projectTaskGraphs: path7.join(projectDir, "task-graphs"),
4417
- projectSddSession: path7.join(projectDir, "sdd-session.json"),
4418
- projectPlan: path7.join(projectDir, "plan.json"),
4419
- projectAutophase: path7.join(projectDir, "autophase"),
4420
- projectSddBoards: path7.join(projectDir, "sdd-boards"),
4421
- syncConfig: path7.join(profileDir, "sync.json"),
4422
- configHistoryDir: path7.join(globalRoot, "config-history"),
4423
- projectStatus: (projectHash2) => path7.join(globalRoot, "projects", projectHash2, "status.json")
4424
- };
4425
- }
4426
-
4427
- // src/utils/heap-watchdog.ts
4428
- import * as fsp2 from "node:fs/promises";
4429
- import * as path8 from "node:path";
4430
- import * as v8 from "node:v8";
4431
- var MB = 1024 * 1024;
4432
- function defaultHeapLogPath() {
4433
- return path8.join(wstackGlobalRoot(), "logs", "heap.jsonl");
4434
- }
4435
- function takeHeapSample() {
4436
- const m = process.memoryUsage();
4437
- const limit = v8.getHeapStatistics().heap_size_limit || 0;
5376
+ // src/utils/win32-cmd.ts
5377
+ var WIN32_CMD_META = /[&|<>"\r\n\0]/;
5378
+ function buildWin32CmdShimInvocation(command, args = []) {
5379
+ assertSafeWin32CmdArgs([command, ...args]);
5380
+ const line = ["call", quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(" ");
4438
5381
  return {
4439
- ts: (/* @__PURE__ */ new Date()).toISOString(),
4440
- rss: m.rss,
4441
- heapUsed: m.heapUsed,
4442
- heapTotal: m.heapTotal,
4443
- external: m.external,
4444
- heapLimit: limit,
4445
- load: limit > 0 ? m.heapUsed / limit : 0
5382
+ command: process.env["COMSPEC"] ?? "cmd.exe",
5383
+ args: ["/d", "/c", line],
5384
+ windowsVerbatimArguments: true
4446
5385
  };
4447
5386
  }
4448
- function startHeapWatchdog(opts = {}) {
4449
- const sampleEveryMs = opts.sampleEveryMs ?? 6e4;
4450
- const logEveryMs = opts.logEveryMs ?? 3e5;
4451
- const logPath = opts.logPath ?? defaultHeapLogPath();
4452
- const warnAt = opts.warnAt ?? 0.6;
4453
- const criticalAt = opts.criticalAt ?? 0.85;
4454
- const REARM_MARGIN = 0.05;
4455
- let warnArmed = true;
4456
- let criticalArmed = true;
4457
- let lastLogAt = 0;
4458
- let writeInFlight = false;
4459
- let pendingLine;
4460
- let drainPromise;
4461
- let stopped = false;
4462
- let dirReady = false;
4463
- const writeDiagnosticLine = opts.writeDiagnosticLine ?? (async (targetPath, line) => {
4464
- if (!dirReady) {
4465
- await fsp2.mkdir(path8.dirname(targetPath), { recursive: true });
4466
- dirReady = true;
4467
- }
4468
- await fsp2.appendFile(targetPath, `${line}
4469
- `, "utf8");
4470
- });
4471
- const drainWrites = async (firstLine) => {
4472
- let line = firstLine;
4473
- while (line !== void 0) {
4474
- try {
4475
- await writeDiagnosticLine(logPath, line);
4476
- } catch {
4477
- }
4478
- line = pendingLine;
4479
- pendingLine = void 0;
4480
- }
4481
- writeInFlight = false;
4482
- };
4483
- const append = (line) => {
4484
- if (stopped) return;
4485
- if (writeInFlight) {
4486
- pendingLine = line;
4487
- return;
4488
- }
4489
- writeInFlight = true;
4490
- drainPromise = drainWrites(line);
4491
- };
4492
- const tick = () => {
4493
- let userTimings = 0;
4494
- try {
4495
- userTimings = performance.getEntriesByType("mark").length + performance.getEntriesByType("measure").length;
4496
- if (userTimings > 0) {
4497
- performance.clearMarks();
4498
- performance.clearMeasures();
4499
- }
4500
- } catch {
4501
- }
4502
- const s = takeHeapSample();
4503
- if (s.load >= criticalAt && criticalArmed) {
4504
- criticalArmed = false;
4505
- warnArmed = false;
4506
- opts.onWarn?.(
4507
- "critical",
4508
- `Heap critical: ${Math.round(s.heapUsed / MB)} MB of ~${Math.round(s.heapLimit / MB)} 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}`,
4509
- s
4510
- );
4511
- } else if (s.load >= warnAt && warnArmed) {
4512
- warnArmed = false;
4513
- opts.onWarn?.(
4514
- "warn",
4515
- `Heap high: ${Math.round(s.heapUsed / MB)} MB of ~${Math.round(s.heapLimit / MB)} MB V8 limit (${Math.round(s.load * 100)}%). Memory diagnostics are being recorded to ${logPath}`,
4516
- s
5387
+ function assertSafeWin32CmdArgs(args) {
5388
+ for (const arg of args) {
5389
+ if (typeof arg === "string" && WIN32_CMD_META.test(arg)) {
5390
+ throw new Error(
5391
+ 'win32 cmd shim spawn: argument contains a shell metacharacter (one of & | < > ", or a newline) that could enable command injection through the .cmd/.bat wrapper - refusing to run. Offending argument: ' + JSON.stringify(arg)
4517
5392
  );
4518
5393
  }
4519
- if (!warnArmed && s.load < warnAt - REARM_MARGIN) warnArmed = true;
4520
- if (!criticalArmed && s.load < criticalAt - REARM_MARGIN) criticalArmed = true;
4521
- const due = Date.now() - lastLogAt >= logEveryMs;
4522
- const crossed = s.load >= warnAt;
4523
- if (due || crossed) {
4524
- lastLogAt = Date.now();
4525
- let extras = {};
4526
- try {
4527
- extras = opts.collectStats?.() ?? {};
4528
- } catch {
4529
- }
4530
- append(JSON.stringify({ pid: process.pid, ...s, userTimings, ...extras }));
4531
- }
4532
- };
4533
- const timer = setInterval(tick, sampleEveryMs);
4534
- timer.unref?.();
4535
- tick();
4536
- return async () => {
4537
- stopped = true;
4538
- clearInterval(timer);
4539
- await drainPromise;
4540
- };
5394
+ }
5395
+ }
5396
+ function quoteWin32CmdArg(arg) {
5397
+ return `"${arg}"`;
4541
5398
  }
4542
5399
  export {
5400
+ ALLOWED_IMAGE_MEDIA_TYPES,
4543
5401
  COMPLETED_WORK_LEDGER_MARKER,
4544
5402
  DEFAULT_TOOL_DESCRIPTION_MODE,
4545
5403
  DEFAULT_TOOL_RESULT_RENDER_MODE,
@@ -4550,11 +5408,14 @@ export {
4550
5408
  IncomingImageError,
4551
5409
  MAX_INCOMING_IMAGES,
4552
5410
  MAX_INCOMING_IMAGE_BYTES,
5411
+ MAX_PATH_SEGMENT_LENGTH,
4553
5412
  PROJECT_IDENTITY_RELATIVE_PATH,
4554
5413
  PROJECT_IDENTITY_VERSION,
4555
5414
  PROJECT_ID_PREFIX,
4556
5415
  SageCachePragmas,
4557
5416
  TerminalLifecycle,
5417
+ WIRE_TOOL_NAME_MAX_LENGTH,
5418
+ WIRE_TOOL_NAME_PATTERN,
4558
5419
  activeProfileName,
4559
5420
  applyToolDescriptionModeToTool,
4560
5421
  applyToolDescriptionModes,
@@ -4565,12 +5426,14 @@ export {
4565
5426
  atomicReplaceWithWriter,
4566
5427
  atomicWrite,
4567
5428
  backupConfigFile,
5429
+ base64DecodedBytes,
4568
5430
  buildChildEnv,
4569
5431
  buildCompletedWorkLedgerBlock,
4570
5432
  buildContextEvidenceDigest,
4571
5433
  buildSgrSequence,
4572
5434
  buildTitleSequence,
4573
5435
  buildUserContentBlocks,
5436
+ buildWin32CmdShimInvocation,
4574
5437
  canonicalProjectRoot,
4575
5438
  checkConnectivity,
4576
5439
  checkUnixSocketPath,
@@ -4596,6 +5459,12 @@ export {
4596
5459
  ensureDir,
4597
5460
  ensureProjectGitignore,
4598
5461
  ensureProjectIdentity,
5462
+ envBool,
5463
+ envBoolOptional,
5464
+ envEnum,
5465
+ envFloat,
5466
+ envInt,
5467
+ envString,
4599
5468
  escapeGlobSubject,
4600
5469
  estimateMessageTokens,
4601
5470
  estimateRequestTokens,
@@ -4621,6 +5490,8 @@ export {
4621
5490
  hasMeaningfulContent,
4622
5491
  hasOpenTodos,
4623
5492
  indexParallelBatchSize,
5493
+ installCrashShield,
5494
+ isAllowedImageMediaType,
4624
5495
  isFrugalPerf,
4625
5496
  isJsonObject,
4626
5497
  isPathSubjectKey,
@@ -4629,12 +5500,18 @@ export {
4629
5500
  isPrivateIPv4,
4630
5501
  isPrivateIPv6,
4631
5502
  isProjectId,
5503
+ isSafePathSegment,
4632
5504
  isStdinTTY,
4633
5505
  isUlid,
5506
+ isValidImageBase64,
4634
5507
  jsonObjectFileExists,
4635
5508
  markAssistantReferencedEvidence,
4636
5509
  matchAny,
5510
+ matchAnyCommand,
5511
+ matchCommandGlob,
4637
5512
  matchGlob,
5513
+ mcpQualifiedToolName,
5514
+ mcpServerToolPrefix,
4638
5515
  mergeCustomModelDefs,
4639
5516
  mergeModelsPayload,
4640
5517
  normalizePathSubject,
@@ -4663,6 +5540,7 @@ export {
4663
5540
  repeatedReadPressure,
4664
5541
  resetCalibration,
4665
5542
  resetConnectivityCache,
5543
+ resolveContainedPath,
4666
5544
  resolveToolDescriptionMode,
4667
5545
  resolveToolResultRenderMode,
4668
5546
  resolveWstackPaths,
@@ -4672,6 +5550,7 @@ export {
4672
5550
  safeStringify,
4673
5551
  sanitizeJsonString,
4674
5552
  sanitizeNodeOptions,
5553
+ sanitizeWireToolName,
4675
5554
  sessionScopedPath,
4676
5555
  setJsonPath,
4677
5556
  setJsonPathInFile,
@@ -4682,9 +5561,10 @@ export {
4682
5561
  setToolResultRenderMode,
4683
5562
  simplifyToolDescription,
4684
5563
  sleep,
4685
- slugify,
5564
+ slugify2 as slugify,
4686
5565
  sqliteCachePragmas,
4687
5566
  startHeapWatchdog,
5567
+ startSharedHeapWatchdog,
4688
5568
  stripAnsi,
4689
5569
  stripCodeFences,
4690
5570
  subjectForToolInput,