@sayknow-cli/coding-agent 0.7.11 → 0.7.13

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 (427) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/types/async/result-formatting.d.ts +2 -0
  3. package/dist/types/capability/fs.d.ts +22 -3
  4. package/dist/types/capability/mcp.d.ts +2 -0
  5. package/dist/types/cli/append-system-prompt.d.ts +6 -0
  6. package/dist/types/cli/update-cli.d.ts +3 -0
  7. package/dist/types/commands/contribution-prep.d.ts +0 -3
  8. package/dist/types/commands/migrate.d.ts +1 -1
  9. package/dist/types/commands/sdk.d.ts +9 -0
  10. package/dist/types/commit/changelog/index.d.ts +1 -0
  11. package/dist/types/config/settings-schema.d.ts +14 -0
  12. package/dist/types/config/settings.d.ts +7 -1
  13. package/dist/types/coordinator-mcp/session-reaper.d.ts +5 -0
  14. package/dist/types/cursor-delete-path.d.ts +1 -0
  15. package/dist/types/cursor-mcp-name.d.ts +8 -0
  16. package/dist/types/dap/config.d.ts +8 -4
  17. package/dist/types/dap/session.d.ts +11 -2
  18. package/dist/types/debug/report-bundle-parent.d.ts +2 -0
  19. package/dist/types/debug/system-info.d.ts +6 -1
  20. package/dist/types/discovery/helpers.d.ts +11 -3
  21. package/dist/types/discovery/mcp-json.d.ts +1 -0
  22. package/dist/types/edit/file-read-cache.d.ts +4 -0
  23. package/dist/types/edit/modes/patch.d.ts +14 -0
  24. package/dist/types/edit/modes/replace.d.ts +8 -0
  25. package/dist/types/eval/py/runtime.d.ts +9 -0
  26. package/dist/types/exa/mcp-client.d.ts +11 -6
  27. package/dist/types/exec/bash-executor.d.ts +18 -1
  28. package/dist/types/export/html/css-color.d.ts +2 -0
  29. package/dist/types/export/html/html-export-destination.d.ts +2 -0
  30. package/dist/types/export/html/template.generated.d.ts +1 -1
  31. package/dist/types/extensibility/custom-tools/loader.d.ts +3 -2
  32. package/dist/types/extensibility/custom-tools/types.d.ts +3 -1
  33. package/dist/types/extensibility/plugins/marketplace/cache.d.ts +2 -0
  34. package/dist/types/extensibility/plugins/plugin-link-path.d.ts +2 -0
  35. package/dist/types/goals/runtime.d.ts +6 -0
  36. package/dist/types/harness-control-plane/receipt-spool.d.ts +4 -0
  37. package/dist/types/hindsight/content.d.ts +5 -6
  38. package/dist/types/internal-urls/skill-path.d.ts +1 -0
  39. package/dist/types/internal-urls/types.d.ts +2 -0
  40. package/dist/types/lsp/clients/swiftlint-client.d.ts +0 -4
  41. package/dist/types/lsp/config.d.ts +8 -5
  42. package/dist/types/lsp/workspace-path.d.ts +1 -0
  43. package/dist/types/migrate/adapters/codex.d.ts +2 -1
  44. package/dist/types/migrate/adapters/index.d.ts +10 -1
  45. package/dist/types/migrate/executor.d.ts +3 -1
  46. package/dist/types/migrate/types.d.ts +15 -3
  47. package/dist/types/modes/components/custom-editor.d.ts +6 -0
  48. package/dist/types/modes/components/extensions/state-manager.d.ts +4 -3
  49. package/dist/types/modes/components/model-selector.d.ts +46 -0
  50. package/dist/types/modes/controllers/input-controller.d.ts +9 -0
  51. package/dist/types/modes/interactive-mode.d.ts +1 -0
  52. package/dist/types/modes/utils/macos-option-forwarding.d.ts +17 -0
  53. package/dist/types/runtime-mcp/content-limits.d.ts +4 -0
  54. package/dist/types/runtime-mcp/manager.d.ts +9 -1
  55. package/dist/types/runtime-mcp/mcp-redirect.d.ts +9 -0
  56. package/dist/types/runtime-mcp/oauth-public-url.d.ts +1 -0
  57. package/dist/types/runtime-mcp/plugin-mcp-name-filter.d.ts +22 -0
  58. package/dist/types/runtime-mcp/plugin-network-boundary.d.ts +1 -0
  59. package/dist/types/runtime-mcp/project-host-values.d.ts +33 -0
  60. package/dist/types/runtime-mcp/smithery-registry.d.ts +24 -0
  61. package/dist/types/runtime-mcp/tool-bridge.d.ts +4 -0
  62. package/dist/types/runtime-mcp/types.d.ts +6 -0
  63. package/dist/types/sdk/broker/ensure.d.ts +2 -0
  64. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -1
  65. package/dist/types/sdk/broker/runtime.d.ts +1 -1
  66. package/dist/types/sdk/bus/chat-daemon-control.d.ts +3 -1
  67. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +3 -1
  68. package/dist/types/sdk/bus/telegram-daemon.d.ts +1 -0
  69. package/dist/types/sdk/host/events.d.ts +4 -0
  70. package/dist/types/session/agent-session.d.ts +22 -2
  71. package/dist/types/session/auto-resume.d.ts +5 -0
  72. package/dist/types/session/messages.d.ts +5 -1
  73. package/dist/types/session/session-manager.d.ts +13 -0
  74. package/dist/types/session/session-storage.d.ts +8 -0
  75. package/dist/types/session/streaming-output.d.ts +11 -0
  76. package/dist/types/session-import/redact.d.ts +1 -1
  77. package/dist/types/skc-runtime/managed-owner-admission.d.ts +3 -0
  78. package/dist/types/skc-runtime/psmux-detect.d.ts +5 -4
  79. package/dist/types/skc-runtime/ralplan-runtime.d.ts +5 -0
  80. package/dist/types/skc-runtime/sidecar-bootstrap-env.d.ts +6 -0
  81. package/dist/types/skc-runtime/state-writer.d.ts +4 -1
  82. package/dist/types/skc-runtime/tmux-sessions.d.ts +24 -0
  83. package/dist/types/skc-runtime/ultragoal-runtime.d.ts +4 -0
  84. package/dist/types/skill-state/workflow-mutation-guard.d.ts +20 -1
  85. package/dist/types/slash-commands/helpers/mcp.d.ts +5 -0
  86. package/dist/types/ssh/ssh-executor.d.ts +3 -1
  87. package/dist/types/system-prompt.d.ts +5 -2
  88. package/dist/types/task/executor.d.ts +17 -3
  89. package/dist/types/task/isolation-dir.d.ts +26 -0
  90. package/dist/types/task/role-body.d.ts +11 -0
  91. package/dist/types/task/token-log-mode.test.d.ts +1 -0
  92. package/dist/types/tools/ask.d.ts +77 -254
  93. package/dist/types/tools/ast-edit-write-path.d.ts +23 -0
  94. package/dist/types/tools/atomic-file-write.d.ts +74 -0
  95. package/dist/types/tools/auto-generated-guard.d.ts +5 -2
  96. package/dist/types/tools/bash-allowed-prefixes.d.ts +16 -0
  97. package/dist/types/tools/bash-interactive.d.ts +2 -0
  98. package/dist/types/tools/bash-skill-urls.d.ts +5 -1
  99. package/dist/types/tools/bash.d.ts +1 -0
  100. package/dist/types/tools/browser/cdp-url.d.ts +2 -0
  101. package/dist/types/tools/browser/tab-worker.d.ts +2 -0
  102. package/dist/types/tools/debug.d.ts +2 -2
  103. package/dist/types/tools/explicit-artifact.d.ts +8 -0
  104. package/dist/types/tools/fetch.d.ts +7 -4
  105. package/dist/types/tools/github-side-effect.d.ts +22 -0
  106. package/dist/types/tools/index.d.ts +3 -0
  107. package/dist/types/tools/monitor-mutation.d.ts +9 -0
  108. package/dist/types/tools/recipe/index.d.ts +2 -0
  109. package/dist/types/tools/recipe/recipe-guard.d.ts +7 -0
  110. package/dist/types/tools/restricted-cwd.d.ts +1 -0
  111. package/dist/types/tools/reverse-engineer.d.ts +81 -0
  112. package/dist/types/tools/search-tool-bm25.d.ts +2 -0
  113. package/dist/types/tools/tmux-self-injection-guard.d.ts +17 -0
  114. package/dist/types/tools/untrusted-content.d.ts +12 -0
  115. package/dist/types/utils/file-mentions.d.ts +5 -0
  116. package/dist/types/utils/open.d.ts +0 -1
  117. package/dist/types/utils/shell-snapshot.d.ts +2 -0
  118. package/dist/types/utils/title-generator.d.ts +12 -2
  119. package/dist/types/utils/tools-checksum.d.ts +7 -0
  120. package/dist/types/utils/xml-escape.d.ts +2 -0
  121. package/dist/types/web/scrapers/types.d.ts +8 -1
  122. package/dist/types/web/search/providers/codex.d.ts +6 -7
  123. package/dist/types/web/search/providers/insane.d.ts +7 -1
  124. package/dist/types/web/search/providers/kimi.d.ts +2 -0
  125. package/dist/types/web/search/providers/searxng.d.ts +7 -0
  126. package/dist/types/web/search/providers/xai.d.ts +2 -0
  127. package/package.json +7 -7
  128. package/scripts/generate-sdk-operation-inventory.ts +4 -0
  129. package/src/async/job-manager.ts +23 -9
  130. package/src/async/result-formatting.ts +40 -0
  131. package/src/capability/fs.ts +78 -11
  132. package/src/capability/mcp.ts +2 -0
  133. package/src/cli/append-system-prompt.ts +12 -0
  134. package/src/cli/auth-broker-cli.ts +22 -12
  135. package/src/cli/config-cli.ts +8 -18
  136. package/src/cli/migrate-cli.ts +7 -5
  137. package/src/cli/ssh-cli.ts +6 -3
  138. package/src/cli/stats-cli.ts +9 -4
  139. package/src/cli/update-cli.ts +42 -0
  140. package/src/cli/web-search-cli.ts +9 -3
  141. package/src/cli.ts +5 -9
  142. package/src/commands/commit.ts +2 -2
  143. package/src/commands/contribution-prep.ts +1 -3
  144. package/src/commands/harness.ts +25 -15
  145. package/src/commands/launch.ts +1 -1
  146. package/src/commands/migrate.ts +3 -3
  147. package/src/commands/sdk.ts +115 -14
  148. package/src/commands/ultragoal.ts +14 -8
  149. package/src/commit/agentic/agent.ts +6 -6
  150. package/src/commit/analysis/conventional.ts +14 -5
  151. package/src/commit/changelog/index.ts +39 -1
  152. package/src/commit/message.ts +10 -3
  153. package/src/config/config-file.ts +106 -3
  154. package/src/config/keybindings.ts +154 -7
  155. package/src/config/mcp-schema.json +4 -0
  156. package/src/config/model-registry.ts +10 -2
  157. package/src/config/settings-schema.ts +18 -0
  158. package/src/config/settings.ts +32 -4
  159. package/src/coordinator-mcp/policy.ts +14 -4
  160. package/src/coordinator-mcp/server.ts +44 -4
  161. package/src/coordinator-mcp/session-reaper.ts +9 -1
  162. package/src/cursor-delete-path.ts +10 -0
  163. package/src/cursor-mcp-name.ts +15 -0
  164. package/src/cursor.ts +13 -2
  165. package/src/dap/client.ts +9 -2
  166. package/src/dap/config.ts +33 -13
  167. package/src/dap/defaults.json +1 -1
  168. package/src/dap/session.ts +161 -36
  169. package/src/debug/crash-diagnostics.ts +89 -6
  170. package/src/debug/report-bundle-parent.ts +22 -0
  171. package/src/debug/report-bundle.ts +100 -3
  172. package/src/debug/system-info.ts +21 -4
  173. package/src/defaults/skc/extensions/grok-cli-vendor/src/shared/base-url.ts +21 -7
  174. package/src/defaults/skc/skills/deep-interview/SKILL.md +1 -1
  175. package/src/discovery/agents-md.ts +3 -2
  176. package/src/discovery/agents.ts +3 -2
  177. package/src/discovery/builtin.ts +21 -11
  178. package/src/discovery/claude.ts +5 -4
  179. package/src/discovery/cline.ts +2 -2
  180. package/src/discovery/codex.ts +6 -5
  181. package/src/discovery/cursor.ts +11 -2
  182. package/src/discovery/gemini.ts +4 -3
  183. package/src/discovery/github.ts +2 -2
  184. package/src/discovery/helpers.ts +51 -11
  185. package/src/discovery/mcp-json.ts +28 -12
  186. package/src/discovery/opencode.ts +2 -1
  187. package/src/discovery/ssh.ts +11 -6
  188. package/src/discovery/substitute-plugin-root.ts +3 -1
  189. package/src/discovery/vscode.ts +3 -3
  190. package/src/edit/apply-patch/index.ts +12 -1
  191. package/src/edit/file-read-cache.ts +24 -6
  192. package/src/edit/index.ts +90 -20
  193. package/src/edit/modes/patch.ts +215 -9
  194. package/src/edit/modes/replace.ts +141 -0
  195. package/src/eval/js/context-manager.ts +29 -3
  196. package/src/eval/js/worker-entry.ts +51 -18
  197. package/src/eval/py/runner.py +144 -5
  198. package/src/eval/py/runtime.ts +44 -4
  199. package/src/eval/py/tool-bridge.ts +4 -0
  200. package/src/exa/mcp-client.ts +53 -11
  201. package/src/exec/bash-executor.ts +87 -4
  202. package/src/exec/non-interactive-env.ts +0 -1
  203. package/src/export/html/css-color.ts +9 -0
  204. package/src/export/html/html-export-destination.ts +16 -0
  205. package/src/export/html/index.ts +102 -8
  206. package/src/export/html/template.generated.ts +1 -1
  207. package/src/extensibility/custom-tools/loader.ts +13 -3
  208. package/src/extensibility/custom-tools/types.ts +3 -1
  209. package/src/extensibility/custom-tools/wrapper.ts +3 -1
  210. package/src/extensibility/plugins/manager.ts +3 -2
  211. package/src/extensibility/plugins/marketplace/cache.ts +15 -0
  212. package/src/extensibility/plugins/marketplace/fetcher.ts +2 -2
  213. package/src/extensibility/plugins/marketplace/manager.ts +5 -3
  214. package/src/extensibility/plugins/plugin-link-path.ts +12 -0
  215. package/src/extensibility/skc-plugins/mcp-policy.ts +2 -1
  216. package/src/goals/runtime.ts +30 -8
  217. package/src/harness-control-plane/finalize.ts +10 -0
  218. package/src/harness-control-plane/operate.ts +12 -4
  219. package/src/harness-control-plane/owner.ts +8 -1
  220. package/src/harness-control-plane/receipt-spool.ts +105 -28
  221. package/src/harness-control-plane/storage.ts +124 -6
  222. package/src/hashline/execute.ts +3 -3
  223. package/src/hashline/recovery.ts +85 -2
  224. package/src/hindsight/config.ts +9 -3
  225. package/src/hindsight/content.ts +116 -16
  226. package/src/hindsight/mental-models.ts +22 -10
  227. package/src/hindsight/state.ts +7 -4
  228. package/src/hooks/native-skill-hook.ts +17 -12
  229. package/src/i18n/messages/de.settings.ts +3 -0
  230. package/src/i18n/messages/es.settings.ts +3 -0
  231. package/src/i18n/messages/fr.settings.ts +3 -0
  232. package/src/i18n/messages/ja.settings.ts +3 -0
  233. package/src/i18n/messages/ko.settings.ts +3 -0
  234. package/src/i18n/messages/zh.settings.ts +3 -0
  235. package/src/internal-urls/artifact-protocol.ts +3 -1
  236. package/src/internal-urls/docs-index.generated.ts +10 -10
  237. package/src/internal-urls/local-protocol.ts +167 -8
  238. package/src/internal-urls/skill-path.ts +18 -0
  239. package/src/internal-urls/skill-protocol.ts +2 -0
  240. package/src/internal-urls/types.ts +2 -0
  241. package/src/lsp/client.ts +2 -1
  242. package/src/lsp/clients/biome-client.ts +2 -0
  243. package/src/lsp/clients/swiftlint-client.ts +2 -0
  244. package/src/lsp/config.ts +18 -62
  245. package/src/lsp/edits.ts +6 -0
  246. package/src/lsp/index.ts +29 -0
  247. package/src/lsp/workspace-path.ts +75 -0
  248. package/src/main.ts +33 -11
  249. package/src/memories/index.ts +141 -9
  250. package/src/migrate/action-planner.ts +57 -0
  251. package/src/migrate/adapters/claude-code.ts +23 -4
  252. package/src/migrate/adapters/codex.ts +22 -4
  253. package/src/migrate/adapters/index.ts +22 -4
  254. package/src/migrate/adapters/opencode.ts +6 -1
  255. package/src/migrate/executor.ts +84 -7
  256. package/src/migrate/report.ts +19 -2
  257. package/src/migrate/types.ts +14 -4
  258. package/src/modes/DESIGN.md +5 -0
  259. package/src/modes/acp/acp-agent.ts +35 -2
  260. package/src/modes/acp/permission-mode.ts +18 -1
  261. package/src/modes/components/custom-editor.ts +14 -0
  262. package/src/modes/components/extensions/extension-dashboard.ts +2 -2
  263. package/src/modes/components/extensions/inspector-panel.ts +9 -5
  264. package/src/modes/components/extensions/state-manager.ts +15 -5
  265. package/src/modes/components/model-selector.ts +144 -94
  266. package/src/modes/components/welcome.ts +3 -2
  267. package/src/modes/controllers/command-controller.ts +300 -9
  268. package/src/modes/controllers/event-controller.ts +1 -1
  269. package/src/modes/controllers/extension-ui-controller.ts +32 -19
  270. package/src/modes/controllers/input-controller.ts +62 -26
  271. package/src/modes/controllers/plan-mode-controller.ts +17 -7
  272. package/src/modes/controllers/runtime-mcp-command-controller.ts +25 -20
  273. package/src/modes/controllers/ssh-command-controller.ts +3 -1
  274. package/src/modes/interactive-mode.ts +10 -0
  275. package/src/modes/utils/macos-option-forwarding.ts +80 -0
  276. package/src/prompts/system/irc-incoming.md +3 -1
  277. package/src/prompts/system/project-prompt.md +19 -0
  278. package/src/prompts/system/system-prompt.md +3 -0
  279. package/src/prompts/tools/ask.md +2 -0
  280. package/src/prompts/tools/debug.md +1 -1
  281. package/src/prompts/tools/monitor.md +7 -5
  282. package/src/prompts/tools/reverse-engineer.md +29 -0
  283. package/src/runtime-credential-selector.ts +2 -2
  284. package/src/runtime-mcp/config-writer.ts +10 -6
  285. package/src/runtime-mcp/config.ts +1 -0
  286. package/src/runtime-mcp/content-limits.ts +7 -0
  287. package/src/runtime-mcp/json-rpc.ts +2 -1
  288. package/src/runtime-mcp/manager.ts +57 -9
  289. package/src/runtime-mcp/mcp-redirect.ts +73 -0
  290. package/src/runtime-mcp/oauth-flow.ts +43 -5
  291. package/src/runtime-mcp/oauth-public-url.ts +8 -0
  292. package/src/runtime-mcp/plugin-mcp-name-filter.ts +62 -0
  293. package/src/runtime-mcp/plugin-network-boundary.ts +4 -0
  294. package/src/runtime-mcp/project-host-values.ts +50 -0
  295. package/src/runtime-mcp/render.ts +16 -1
  296. package/src/runtime-mcp/smithery-registry.ts +22 -3
  297. package/src/runtime-mcp/tool-bridge.ts +194 -21
  298. package/src/runtime-mcp/transports/http.ts +4 -3
  299. package/src/runtime-mcp/transports/stdio.ts +2 -1
  300. package/src/runtime-mcp/types.ts +6 -0
  301. package/src/sdk/broker/broker.ts +11 -2
  302. package/src/sdk/broker/ensure.ts +131 -10
  303. package/src/sdk/broker/lifecycle-ledger.ts +18 -3
  304. package/src/sdk/broker/lifecycle.ts +21 -19
  305. package/src/sdk/broker/runtime.ts +1 -1
  306. package/src/sdk/bus/chat-daemon-cli.ts +38 -1
  307. package/src/sdk/bus/chat-daemon-control.ts +5 -3
  308. package/src/sdk/bus/index.ts +5 -3
  309. package/src/sdk/bus/lifecycle-control-runtime.ts +9 -2
  310. package/src/sdk/bus/session-control.ts +2 -0
  311. package/src/sdk/bus/slack-daemon.ts +8 -1
  312. package/src/sdk/bus/slack-live-provider.ts +3 -1
  313. package/src/sdk/bus/telegram-daemon-contract.ts +3 -1
  314. package/src/sdk/bus/telegram-daemon-control.ts +17 -12
  315. package/src/sdk/bus/telegram-daemon.ts +41 -1
  316. package/src/sdk/host/events.ts +67 -4
  317. package/src/sdk/mcp/server.ts +16 -3
  318. package/src/sdk/protocol/operation-inventory.generated.json +22 -0
  319. package/src/sdk/session.ts +18 -25
  320. package/src/secrets/obfuscator.ts +92 -12
  321. package/src/session/agent-session.ts +466 -100
  322. package/src/session/artifacts.ts +3 -1
  323. package/src/session/auto-resume.ts +45 -8
  324. package/src/session/history-storage.ts +172 -8
  325. package/src/session/internal/managed-session-scope.ts +130 -52
  326. package/src/session/messages.ts +47 -6
  327. package/src/session/session-manager.ts +116 -8
  328. package/src/session/session-storage.ts +31 -1
  329. package/src/session/streaming-output.ts +263 -4
  330. package/src/session-import/redact.ts +76 -3
  331. package/src/setup/hermes-setup.ts +4 -1
  332. package/src/skc-runtime/gc-runtime.ts +26 -4
  333. package/src/skc-runtime/launch-tmux.ts +21 -11
  334. package/src/skc-runtime/launch-worktree.ts +42 -3
  335. package/src/skc-runtime/managed-owner-admission.ts +46 -2
  336. package/src/skc-runtime/psmux-detect.ts +29 -5
  337. package/src/skc-runtime/ralplan-runtime.ts +14 -1
  338. package/src/skc-runtime/session-resolution.ts +38 -6
  339. package/src/skc-runtime/sidecar-bootstrap-env.ts +19 -0
  340. package/src/skc-runtime/state-writer.ts +134 -16
  341. package/src/skc-runtime/tmux-sessions.ts +85 -4
  342. package/src/skc-runtime/ultragoal-change-set.ts +18 -2
  343. package/src/skc-runtime/ultragoal-guard.ts +9 -1
  344. package/src/skc-runtime/ultragoal-runtime.ts +26 -9
  345. package/src/skill-state/active-state.ts +13 -0
  346. package/src/skill-state/workflow-mutation-guard.ts +3297 -180
  347. package/src/slash-commands/builtin-registry.ts +14 -8
  348. package/src/slash-commands/helpers/mcp.ts +20 -7
  349. package/src/ssh/ssh-executor.ts +3 -1
  350. package/src/stt/recorder.ts +26 -9
  351. package/src/system-prompt.ts +65 -16
  352. package/src/task/commands.ts +3 -1
  353. package/src/task/executor.ts +52 -7
  354. package/src/task/index.ts +28 -0
  355. package/src/task/isolation-dir.ts +143 -0
  356. package/src/task/role-body.ts +84 -0
  357. package/src/task/token-log-mode.test.ts +162 -0
  358. package/src/task/token-log.ts +91 -2
  359. package/src/task/worktree.ts +16 -7
  360. package/src/tools/archive-reader.ts +653 -31
  361. package/src/tools/ask.ts +86 -14
  362. package/src/tools/ast-edit-write-path.ts +133 -0
  363. package/src/tools/ast-edit.ts +27 -1
  364. package/src/tools/ast-grep.ts +7 -2
  365. package/src/tools/atomic-file-write.ts +625 -0
  366. package/src/tools/auto-generated-guard.ts +28 -8
  367. package/src/tools/bash-allowed-prefixes.ts +225 -6
  368. package/src/tools/bash-interactive.ts +12 -0
  369. package/src/tools/bash-skill-urls.ts +113 -7
  370. package/src/tools/bash.ts +152 -20
  371. package/src/tools/browser/cdp-url.ts +18 -0
  372. package/src/tools/browser/tab-worker.ts +49 -14
  373. package/src/tools/browser.ts +25 -8
  374. package/src/tools/cron.ts +10 -1
  375. package/src/tools/debug.ts +16 -8
  376. package/src/tools/eval.ts +71 -34
  377. package/src/tools/explicit-artifact.ts +89 -0
  378. package/src/tools/fetch.ts +26 -17
  379. package/src/tools/gh.ts +40 -12
  380. package/src/tools/github-side-effect.ts +112 -0
  381. package/src/tools/image-gen.ts +24 -10
  382. package/src/tools/index.ts +6 -0
  383. package/src/tools/monitor-mutation.ts +27 -0
  384. package/src/tools/monitor.ts +28 -1
  385. package/src/tools/output-meta.ts +74 -5
  386. package/src/tools/read.ts +24 -36
  387. package/src/tools/recipe/index.ts +12 -0
  388. package/src/tools/recipe/recipe-guard.ts +19 -0
  389. package/src/tools/recipe/runner.ts +23 -12
  390. package/src/tools/render-utils.ts +2 -2
  391. package/src/tools/restricted-cwd.ts +10 -0
  392. package/src/tools/reverse-engineer.ts +497 -0
  393. package/src/tools/search-tool-bm25.ts +14 -3
  394. package/src/tools/search.ts +3 -2
  395. package/src/tools/ssh.ts +235 -8
  396. package/src/tools/subagent-render.ts +43 -7
  397. package/src/tools/subagent.ts +7 -3
  398. package/src/tools/tmux-self-injection-guard.ts +3538 -0
  399. package/src/tools/todo-write.ts +41 -3
  400. package/src/tools/untrusted-content.ts +23 -0
  401. package/src/tools/vim.ts +2 -2
  402. package/src/tools/write.ts +37 -4
  403. package/src/tui/tree-list.ts +15 -1
  404. package/src/utils/commit-message-generator.ts +9 -2
  405. package/src/utils/external-editor.ts +21 -7
  406. package/src/utils/file-mentions.ts +75 -7
  407. package/src/utils/git.ts +38 -7
  408. package/src/utils/open.ts +73 -4
  409. package/src/utils/shell-snapshot.ts +9 -1
  410. package/src/utils/title-generator.ts +61 -16
  411. package/src/utils/tools-checksum.ts +34 -0
  412. package/src/utils/tools-manager.ts +24 -6
  413. package/src/utils/xml-escape.ts +14 -0
  414. package/src/web/insane/url-guard.ts +2 -1
  415. package/src/web/scrapers/types.ts +8 -0
  416. package/src/web/scrapers/youtube.ts +3 -2
  417. package/src/web/search/index.ts +4 -3
  418. package/src/web/search/providers/anthropic.ts +4 -4
  419. package/src/web/search/providers/codex.ts +31 -34
  420. package/src/web/search/providers/insane.ts +145 -28
  421. package/src/web/search/providers/kimi.ts +15 -5
  422. package/src/web/search/providers/searxng.ts +47 -4
  423. package/src/web/search/providers/xai.ts +7 -2
  424. package/dist/types/cli/shell-cli.d.ts +0 -8
  425. package/dist/types/commands/shell.d.ts +0 -21
  426. package/src/cli/shell-cli.ts +0 -176
  427. package/src/commands/shell.ts +0 -29
@@ -18,6 +18,7 @@ import * as typebox from "../typebox";
18
18
  import { createNoOpUIContext, resolvePath } from "../utils";
19
19
  import type { CustomToolAPI, CustomToolFactory, LoadedCustomTool, ToolLoadError } from "./types";
20
20
 
21
+ export type CustomToolImportGuard = (resolvedPath: string) => Promise<void>;
21
22
  /**
22
23
  * Load a single tool module using native Bun import.
23
24
  */
@@ -26,6 +27,7 @@ async function loadTool(
26
27
  cwd: string,
27
28
  sharedApi: CustomToolAPI,
28
29
  source?: { provider: string; providerName: string; level: "user" | "project" },
30
+ beforeImport?: CustomToolImportGuard,
29
31
  ): Promise<{ tools: LoadedCustomTool[] | null; error: ToolLoadError | null }> {
30
32
  const resolvedPath = resolvePath(toolPath, cwd);
31
33
 
@@ -42,6 +44,7 @@ async function loadTool(
42
44
  }
43
45
 
44
46
  try {
47
+ await beforeImport?.(resolvedPath);
45
48
  const module = await import(resolvedPath);
46
49
  const factory = (module.default ?? module) as CustomToolFactory;
47
50
 
@@ -121,9 +124,15 @@ export class CustomToolLoader {
121
124
  this.#seenNames = new Set<string>(builtInToolNames);
122
125
  }
123
126
 
124
- async load(pathsWithSources: ToolPathWithSource[]): Promise<void> {
127
+ async load(pathsWithSources: ToolPathWithSource[], beforeImport?: CustomToolImportGuard): Promise<void> {
125
128
  for (const { path: toolPath, source } of pathsWithSources) {
126
- const { tools: loadedTools, error } = await loadTool(toolPath, this.#sharedApi.cwd, this.#sharedApi, source);
129
+ const { tools: loadedTools, error } = await loadTool(
130
+ toolPath,
131
+ this.#sharedApi.cwd,
132
+ this.#sharedApi,
133
+ source,
134
+ beforeImport,
135
+ );
127
136
 
128
137
  if (error) {
129
138
  this.errors.push(error);
@@ -171,6 +180,7 @@ export async function loadCustomTools(
171
180
  apply(reason: string): Promise<AgentToolResult<unknown>>;
172
181
  reject?(reason: string): Promise<AgentToolResult<unknown> | undefined>;
173
182
  }) => void,
183
+ beforeImport?: CustomToolImportGuard,
174
184
  ) {
175
185
  const loader = new CustomToolLoader(
176
186
  await import("@sayknow-cli/coding-agent"),
@@ -178,7 +188,7 @@ export async function loadCustomTools(
178
188
  builtInToolNames,
179
189
  pushPendingAction,
180
190
  );
181
- await loader.load(pathsWithSources);
191
+ await loader.load(pathsWithSources, beforeImport);
182
192
  return {
183
193
  tools: loader.tools,
184
194
  errors: loader.errors,
@@ -70,6 +70,8 @@ export interface CustomToolContext {
70
70
  sessionManager: ReadonlySessionManager;
71
71
  /** Model registry - use for API key resolution and model retrieval */
72
72
  modelRegistry: ModelRegistry;
73
+ /** Credential-selection identity for provider authentication. */
74
+ credentialSessionId?: string;
73
75
  /** Current model (may be undefined if no model is selected yet) */
74
76
  model: Model | undefined;
75
77
  /** Whether the agent is idle (not streaming) */
@@ -78,7 +80,7 @@ export interface CustomToolContext {
78
80
  hasQueuedMessages(): boolean;
79
81
  /** Abort the current agent operation (fire-and-forget, does not wait) */
80
82
  abort(): void;
81
- /** Settings instance for the current session. Prefer over the global singleton. */
83
+ /** Settings-compatible, read-only session facade. Mutating or secret accessors are blocked at runtime. */
82
84
  settings?: Settings;
83
85
  }
84
86
 
@@ -21,9 +21,11 @@ export class CustomToolAdapter<TParams extends TSchema = TSchema, TDetails = any
21
21
  private tool: CustomTool<TParams, TDetails>,
22
22
  private getContext: () => CustomToolContext,
23
23
  ) {
24
- applyToolProxy(tool, this);
24
+ // Own these before proxying: with useDefineForClassFields off, the uninitialized fields do not
25
+ // exist yet, so applyToolProxy would install getter-only accessors that reject assignment.
25
26
  this.strict = tool.strict;
26
27
  this.concurrency = tool.concurrency;
28
+ applyToolProxy(tool, this);
27
29
  }
28
30
 
29
31
  execute(
@@ -12,6 +12,7 @@ import {
12
12
  } from "@sayknow-cli/utils";
13
13
  import { settings } from "../../config/settings";
14
14
  import { extractPackageName, parsePluginSpec } from "./parser";
15
+ import { resolvePluginLinkPath } from "./plugin-link-path";
15
16
  import { scanPluginDir, toDoctorChecks } from "./security-scanner";
16
17
  import type {
17
18
  DoctorCheck,
@@ -335,11 +336,11 @@ export class PluginManager {
335
336
 
336
337
  await this.#ensurePluginsDir();
337
338
 
338
- const linkPath = path.join(getPluginsNodeModules(), pkg.name);
339
+ const linkPath = resolvePluginLinkPath(getPluginsNodeModules(), pkg.name);
339
340
 
340
341
  // Handle scoped packages
341
342
  if (pkg.name.startsWith("@")) {
342
- const scopeDir = path.join(getPluginsNodeModules(), pkg.name.split("/")[0]);
343
+ const scopeDir = path.dirname(linkPath);
343
344
  await fs.promises.mkdir(scopeDir, { recursive: true });
344
345
  }
345
346
 
@@ -40,6 +40,21 @@ function validateCacheComponents(marketplace: string, pluginName: string, versio
40
40
  }
41
41
  }
42
42
 
43
+ /** Write a regular file. A symlink at the destination is removed, not followed. */
44
+ export async function writeCachedRegularFile(targetPath: string, content: string): Promise<void> {
45
+ try {
46
+ const stat = await fs.lstat(targetPath);
47
+ if (stat.isSymbolicLink()) {
48
+ await fs.unlink(targetPath);
49
+ } else if (!stat.isFile()) {
50
+ throw new Error("unsafe cache artifact");
51
+ }
52
+ } catch (error) {
53
+ if (!isEnoent(error)) throw error;
54
+ }
55
+ await Bun.write(targetPath, content);
56
+ }
57
+
43
58
  /**
44
59
  * Return the absolute path for a cached plugin directory.
45
60
  * Throws if any component fails validation.
@@ -10,7 +10,7 @@ import * as https from "node:https";
10
10
  import * as net from "node:net";
11
11
  import * as os from "node:os";
12
12
  import * as path from "node:path";
13
- import { isEnoent, logger } from "@sayknow-cli/utils";
13
+ import { isEnoent, logger, redactCrashSecrets } from "@sayknow-cli/utils";
14
14
  import * as git from "../../../utils/git";
15
15
  import { isPrivateOrSpecialAddress, validatePublicHttpUrl } from "../../../web/insane/url-guard";
16
16
 
@@ -461,7 +461,7 @@ async function cloneAndReadCatalog(url: string, cacheDir: string): Promise<Fetch
461
461
  const tmpDir = path.join(cacheDir, `.tmp-clone-${Date.now()}`);
462
462
  await fs.mkdir(cacheDir, { recursive: true });
463
463
 
464
- logger.debug(`[marketplace] cloning ${url} → ${tmpDir}`);
464
+ logger.debug(redactCrashSecrets(`[marketplace] cloning ${url} → ${tmpDir}`));
465
465
  await git.clone(url, tmpDir);
466
466
 
467
467
  const catalogPath = path.join(tmpDir, CATALOG_RELATIVE_PATH);
@@ -14,7 +14,7 @@ import { isEnoent, logger, pathIsWithin } from "@sayknow-cli/utils";
14
14
  import { settings } from "../../../config/settings";
15
15
  import { scanPluginDir } from "../security-scanner";
16
16
 
17
- import { cachePlugin, getCachedPluginPath } from "./cache";
17
+ import { cachePlugin, getCachedPluginPath, writeCachedRegularFile } from "./cache";
18
18
  import { classifySource, fetchMarketplace, parseMarketplaceCatalog, promoteCloneToCache } from "./fetcher";
19
19
  import {
20
20
  addInstalledPlugin,
@@ -363,12 +363,14 @@ export class MarketplaceManager {
363
363
  if (!pathIsWithin(cachePath, sourcePath)) {
364
364
  throw new Error(`Plugin "${entry.name}" lspServers path escapes the plugin directory`);
365
365
  }
366
+ const sourceStat = await fs.lstat(sourcePath);
367
+ if (sourceStat.isSymbolicLink()) throw new Error(`Plugin "${entry.name}" lspServers path is a symlink`);
366
368
  const content = await Bun.file(sourcePath).text();
367
- await Bun.write(targetPath, content);
369
+ await writeCachedRegularFile(targetPath, content);
368
370
  return;
369
371
  }
370
372
 
371
- await Bun.write(targetPath, `${JSON.stringify({ servers: lspServers }, null, 2)}\n`);
373
+ await writeCachedRegularFile(targetPath, `${JSON.stringify({ servers: lspServers }, null, 2)}\n`);
372
374
  }
373
375
 
374
376
  /**
@@ -0,0 +1,12 @@
1
+ import path from "node:path";
2
+
3
+ /** Resolve a package.json name under the plugins node_modules root, or throw. */
4
+ export function resolvePluginLinkPath(root: string, name: string): string {
5
+ const base = path.resolve(root);
6
+ const destination = path.resolve(base, name);
7
+ const relative = path.relative(base, destination);
8
+ if (relative === "" || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
9
+ throw new Error(`package.json name is not a safe plugin link path: ${name}`);
10
+ }
11
+ return destination;
12
+ }
@@ -6,7 +6,7 @@ import { SkcPluginLoadError, type SkcPluginMcpManifestEntry } from "./types";
6
6
  /**
7
7
  * Shared MCP security policy applied at BOTH install validation and runtime
8
8
  * connect for third-party plugin-bundle MCP servers. Defaults are deny-first:
9
- * HTTPS only, no private/loopback/link-local/metadata endpoints, stdio confined
9
+ * HTTPS only, no private/loopback/link-local/CGNAT/metadata endpoints, stdio confined
10
10
  * to the plugin root.
11
11
  */
12
12
 
@@ -34,6 +34,7 @@ export function isDeniedIpv4(host: string): boolean {
34
34
  if (a === 172 && b >= 16 && b <= 31) return true; // private 172.16.0.0/12
35
35
  if (a === 192 && b === 168) return true; // private 192.168.0.0/16
36
36
  if (a === 169 && b === 254) return true; // link-local 169.254.0.0/16 (incl 169.254.169.254 metadata)
37
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT 100.64.0.0/10
37
38
  if (a === 0) return true; // 0.0.0.0/8 unspecified/this-network
38
39
  if (a >= 224) return true; // multicast/reserved 224.0.0.0/4 and 240.0.0.0/4
39
40
  return false;
@@ -104,6 +104,9 @@ export function renderGoalPrompt(kind: GoalPromptKind, goal: Goal): string {
104
104
  });
105
105
  }
106
106
 
107
+ /** Flush usage into in-memory state only; the caller writes (or defers) the durable entry. */
108
+ const IN_MEMORY_FLUSH = { persist: false } as const;
109
+
107
110
  function isAccountingStatus(goal: Goal): boolean {
108
111
  return goal.status === "active";
109
112
  }
@@ -113,6 +116,8 @@ export class GoalRuntime {
113
116
  #turnSnapshot: GoalTurnSnapshot | undefined;
114
117
  #wallClock: GoalWallClockSnapshot;
115
118
  #accountingTail: Promise<void> = Promise.resolve();
119
+ /** In-memory usage advanced at a tool boundary that no durable entry records yet. */
120
+ #usagePendingPersist = false;
116
121
 
117
122
  constructor(host: GoalRuntimeHost) {
118
123
  this.#host = host;
@@ -167,6 +172,7 @@ export class GoalRuntime {
167
172
  ): Promise<void> {
168
173
  this.#host.setState(state ? cloneState(state) : undefined);
169
174
  if (options?.persist) {
175
+ this.#usagePendingPersist = false;
170
176
  this.#host.persist(options.persist, state);
171
177
  }
172
178
  if (options?.emit !== false) {
@@ -208,15 +214,21 @@ export class GoalRuntime {
208
214
  }
209
215
  }
210
216
 
217
+ /**
218
+ * Tool boundaries refresh live accounting in memory only. Persisting a
219
+ * `mode_change` per tool call made usage counters the dominant session-log
220
+ * writer (issue #5949); the durable copy is written at agent end and on every
221
+ * status transition, which already carry the latest in-memory counters.
222
+ */
211
223
  async onToolCompleted(toolName: string): Promise<void> {
212
224
  if (toolName === "goal") return;
213
225
  if (!this.#hasAccountingState()) return;
214
- await this.flushUsage();
226
+ await this.#withAccounting(() => this.#flushUsageLocked(this.#host.getCurrentUsage(), IN_MEMORY_FLUSH));
215
227
  }
216
228
 
217
229
  async onGoalToolCompleted(): Promise<void> {
218
230
  if (!this.#hasAccountingState()) return;
219
- await this.flushUsage();
231
+ await this.#withAccounting(() => this.#flushUsageLocked(this.#host.getCurrentUsage(), IN_MEMORY_FLUSH));
220
232
  }
221
233
 
222
234
  async onAgentEnd(options?: { turnCompleted?: boolean; currentUsage?: GoalTokenUsage }): Promise<void> {
@@ -236,7 +248,7 @@ export class GoalRuntime {
236
248
  return;
237
249
  }
238
250
  await this.#withAccounting(async () => {
239
- await this.#flushUsageLocked();
251
+ await this.#flushUsageLocked(this.#host.getCurrentUsage(), IN_MEMORY_FLUSH);
240
252
  this.#turnSnapshot = undefined;
241
253
  const cloned = this.#getStateClone();
242
254
  if (!cloned?.enabled || !isAccountingStatus(cloned.goal)) return;
@@ -261,7 +273,10 @@ export class GoalRuntime {
261
273
  return state;
262
274
  }
263
275
 
264
- async #flushUsageLocked(currentUsage: GoalTokenUsage = this.#host.getCurrentUsage()): Promise<void> {
276
+ async #flushUsageLocked(
277
+ currentUsage: GoalTokenUsage = this.#host.getCurrentUsage(),
278
+ options: { persist: boolean } = { persist: true },
279
+ ): Promise<void> {
265
280
  const state = this.#getStateClone();
266
281
  if (!state?.enabled || !isAccountingStatus(state.goal)) return;
267
282
  if (this.#turnSnapshot?.activeGoalId !== state.goal.id && this.#wallClock.activeGoalId !== state.goal.id) return;
@@ -274,7 +289,13 @@ export class GoalRuntime {
274
289
  this.#wallClock.activeGoalId === state.goal.id
275
290
  ? Math.max(0, Math.floor((this.#now() - this.#wallClock.lastAccountedAt) / 1000))
276
291
  : 0;
277
- if (tokenDelta <= 0 && wallSeconds <= 0) return;
292
+ if (tokenDelta <= 0 && wallSeconds <= 0) {
293
+ if (options.persist && this.#usagePendingPersist) {
294
+ this.#usagePendingPersist = false;
295
+ this.#host.persist("goal", state);
296
+ }
297
+ return;
298
+ }
278
299
 
279
300
  state.goal.tokensUsed += tokenDelta;
280
301
  state.goal.timeUsedSeconds += wallSeconds;
@@ -287,7 +308,8 @@ export class GoalRuntime {
287
308
  this.#wallClock.lastAccountedAt += wallSeconds * 1000;
288
309
  }
289
310
 
290
- await this.#commitState(state, { persist: "goal" });
311
+ this.#usagePendingPersist = !options.persist;
312
+ await this.#commitState(state, options.persist ? { persist: "goal" } : undefined);
291
313
  }
292
314
 
293
315
  async flushUsage(currentUsage: GoalTokenUsage = this.#host.getCurrentUsage()): Promise<void> {
@@ -357,7 +379,7 @@ export class GoalRuntime {
357
379
 
358
380
  async pauseGoal(): Promise<GoalModeState | undefined> {
359
381
  return await this.#withAccounting(async () => {
360
- await this.#flushUsageLocked();
382
+ await this.#flushUsageLocked(this.#host.getCurrentUsage(), IN_MEMORY_FLUSH);
361
383
  const state = this.#getStateClone();
362
384
  if (!state?.goal) return undefined;
363
385
  if (state.goal.status !== "active") {
@@ -393,7 +415,7 @@ export class GoalRuntime {
393
415
 
394
416
  async completeGoalFromTool(): Promise<Goal> {
395
417
  return await this.#withAccounting(async () => {
396
- await this.#flushUsageLocked();
418
+ await this.#flushUsageLocked(this.#host.getCurrentUsage(), IN_MEMORY_FLUSH);
397
419
  const state = this.#getStateClone();
398
420
  if (!state?.goal) {
399
421
  throw new Error("cannot complete goal because no goal is active");
@@ -12,6 +12,7 @@
12
12
  import { execFileSync } from "node:child_process";
13
13
  import { randomBytes } from "node:crypto";
14
14
  import { readFile } from "node:fs/promises";
15
+ import { checkTmuxSelfInjection } from "../tools/tmux-self-injection-guard";
15
16
  import {
16
17
  buildReceipt,
17
18
  type CompletionEvidence,
@@ -312,6 +313,15 @@ function git(workspace: string, args: string[]): string | null {
312
313
  export function defaultFinalizeChecks(workspace: string): FinalizeChecks {
313
314
  return {
314
315
  async runValidation(spec) {
316
+ // Same preflight as BashTool: refuse before spawn so a plan command cannot type into this pane.
317
+ const injection = await checkTmuxSelfInjection(spec.command, {
318
+ env: process.env,
319
+ cwd: workspace,
320
+ executionEnv: process.env,
321
+ });
322
+ if (injection.block) {
323
+ return { exactCommand: spec.command, cwd: workspace, exitStatus: 1, pass: false };
324
+ }
315
325
  const proc = Bun.spawnSync(["bash", "-lc", spec.command], { cwd: workspace, stdout: "pipe", stderr: "pipe" });
316
326
  const exitStatus = proc.exitCode ?? 1;
317
327
  return { exactCommand: spec.command, cwd: workspace, exitStatus, pass: exitStatus === 0 };
@@ -142,6 +142,7 @@ export async function operate(goal: string, opts: OperateOptions): Promise<Opera
142
142
  lifecycle = "finalizing";
143
143
  break;
144
144
  }
145
+ lifecycle = accepted ? "observing" : "submitted";
145
146
  continue;
146
147
  }
147
148
 
@@ -182,11 +183,18 @@ export async function operate(goal: string, opts: OperateOptions): Promise<Opera
182
183
  return { completed: false, lifecycle, iterations, classifications, vanishReceiptIds, blockers };
183
184
  }
184
185
 
185
- // B3: never finalize on loop-exhaustion — require an explicit observed completion.
186
+ // An observation budget bounds this invocation, not the work itself. Keep active
187
+ // sessions nonterminal so a caller can resume observation without treating a slow
188
+ // but healthy owner as a failure. Completion still requires an explicit signal.
186
189
  if (lifecycle !== "finalizing") {
187
- blockers.push("no-observed-completion");
188
- await emit("critical", "operate_blocked", { blockers });
189
- return { completed: false, lifecycle: "blocked", iterations, classifications, vanishReceiptIds, blockers };
190
+ await emit("info", "operate_observation_window_ended", {
191
+ lifecycle,
192
+ iterations,
193
+ lastClassification: classifications.at(-1) ?? null,
194
+ completionObserved: false,
195
+ resumeWith: "observe",
196
+ });
197
+ return { completed: false, lifecycle, iterations, classifications, vanishReceiptIds, blockers };
190
198
  }
191
199
 
192
200
  const finalize = await runFinalize({
@@ -619,7 +619,14 @@ export class RuntimeOwner {
619
619
  kind: string,
620
620
  evidence: Record<string, unknown>,
621
621
  ): Promise<void> => {
622
- if (kind === "operate_blocked" || kind === "operate_finalized") {
622
+ if (kind === "operate_observation_window_ended") {
623
+ // The observation budget ended, not the work: persist the resumable state.
624
+ const windowState = await this.#loadState();
625
+ windowState.lifecycle = evidence.lifecycle === "submitted" ? "submitted" : "observing";
626
+ windowState.blockers = [];
627
+ windowState.updatedAt = new Date(this.#opts.clock ? this.#opts.clock() : Date.now()).toISOString();
628
+ await writeSessionState(this.#opts.root, windowState);
629
+ } else if (kind === "operate_blocked" || kind === "operate_finalized") {
623
630
  const terminalState = await this.#loadState();
624
631
  terminalState.lifecycle =
625
632
  kind === "operate_finalized" && evidence.completed === true ? "completed" : "blocked";
@@ -1,6 +1,8 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { constants as fsConstants } from "node:fs";
2
3
  import * as fs from "node:fs/promises";
3
4
  import * as path from "node:path";
5
+ import { canonicalEnvKey, loadedProjectEnvSnapshot } from "@sayknow-cli/utils/dirs";
4
6
  import { withFileLock } from "../config/file-lock";
5
7
  import type { ReceiptEnvelope } from "./receipts";
6
8
 
@@ -21,6 +23,42 @@ export interface ReceiptSpoolAppendResult {
21
23
  const receiptSpoolDirStorage = new AsyncLocalStorage<string | undefined>();
22
24
  const spoolQueues = new Map<string, Promise<void>>();
23
25
  const noop = (): void => undefined;
26
+ const NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0;
27
+
28
+ /** True only when an exception's `code` is `ENOENT`. Other codes propagate. */
29
+ export function isEnoent(error: unknown): boolean {
30
+ return (error as NodeJS.ErrnoException).code === "ENOENT";
31
+ }
32
+
33
+ /**
34
+ * Bun copies the cwd dotenv into `process.env` before module init. The startup
35
+ * project snapshot is the declaration set trusted directory overrides use: a
36
+ * path that resolves like that declaration, or a dynamic declaration, is not a
37
+ * spool directory. A shell or `--receipt-spool-dir` value that resolves
38
+ * somewhere else is kept.
39
+ */
40
+ function projectDeclaredReceiptSpoolDir(raw: string): boolean {
41
+ const snapshot = loadedProjectEnvSnapshot();
42
+ const key = canonicalEnvKey(RECEIPT_SPOOL_DIR_ENV);
43
+ const projectValue = snapshot.values[key];
44
+ if (projectValue === undefined) return false;
45
+ if (snapshot.dynamic.has(key)) return true;
46
+ const declared = projectValue.trim();
47
+ const candidate = raw.trim();
48
+ if (!declared || !candidate) return declared === candidate;
49
+ return path.resolve(declared) === path.resolve(candidate);
50
+ }
51
+
52
+ function adoptReceiptSpoolDir(raw: string | undefined): string | undefined {
53
+ if (raw === undefined || projectDeclaredReceiptSpoolDir(raw)) return undefined;
54
+ const trimmed = raw.trim();
55
+ return trimmed ? path.resolve(trimmed) : undefined;
56
+ }
57
+
58
+ /** A spool directory the startup project snapshot does not declare. */
59
+ export function trustedReceiptSpoolDir(raw: string | undefined): string | undefined {
60
+ return adoptReceiptSpoolDir(raw);
61
+ }
24
62
 
25
63
  interface ReceiptSpoolCursorCache {
26
64
  mtimeMs: number;
@@ -44,10 +82,15 @@ export function resetReceiptSpoolCursorCacheForTesting(): void {
44
82
 
45
83
  async function spoolStat(spoolFile: string): Promise<{ mtimeMs: number; size: number } | undefined> {
46
84
  try {
47
- const stats = await fs.stat(spoolFile);
48
- return { mtimeMs: stats.mtimeMs, size: stats.size };
85
+ const handle = await fs.open(spoolFile, fsConstants.O_RDONLY | NOFOLLOW);
86
+ try {
87
+ const stats = await handle.stat();
88
+ return { mtimeMs: stats.mtimeMs, size: stats.size };
89
+ } finally {
90
+ await handle.close();
91
+ }
49
92
  } catch (error) {
50
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
93
+ if (isEnoent(error)) return undefined;
51
94
  throw error;
52
95
  }
53
96
  }
@@ -64,15 +107,17 @@ async function cacheHighestCursor(spoolFile: string, highest: bigint): Promise<v
64
107
  export async function withReceiptSpoolDir<T>(spoolDir: string, fn: () => Promise<T>): Promise<T> {
65
108
  const trimmed = spoolDir.trim();
66
109
  if (!trimmed) throw new Error("receipt_spool_dir_empty");
67
- const resolved = path.resolve(trimmed);
110
+ const resolved = adoptReceiptSpoolDir(trimmed);
111
+ // Owner input repeats process.env. A project-declared directory must not
112
+ // become the active spool via that copy.
113
+ if (!resolved) return fn();
68
114
  return receiptSpoolDirStorage.run(resolved, fn);
69
115
  }
70
116
 
71
117
  export function resolveReceiptSpoolDir(env: NodeJS.ProcessEnv = process.env): string | undefined {
72
118
  const active = receiptSpoolDirStorage.getStore();
73
119
  if (active !== undefined) return active;
74
- const raw = env[RECEIPT_SPOOL_DIR_ENV]?.trim();
75
- return raw ? path.resolve(raw) : undefined;
120
+ return adoptReceiptSpoolDir(env[RECEIPT_SPOOL_DIR_ENV]);
76
121
  }
77
122
 
78
123
  export function receiptSpoolPath(spoolDir: string): string {
@@ -95,30 +140,56 @@ export function formatReceiptSpoolCursor(cursor: bigint): string {
95
140
 
96
141
  export async function readHighestReceiptSpoolCursor(spoolDir: string): Promise<bigint> {
97
142
  const spoolFile = receiptSpoolPath(spoolDir);
98
- const revision = await spoolStat(spoolFile);
99
- if (!revision) {
100
- cursorCache.delete(spoolFile);
101
- return 0n;
143
+ let handle: fs.FileHandle;
144
+ try {
145
+ handle = await fs.open(spoolFile, fsConstants.O_RDONLY | NOFOLLOW);
146
+ } catch (error) {
147
+ if (isEnoent(error)) {
148
+ cursorCache.delete(spoolFile);
149
+ return 0n;
150
+ }
151
+ throw error;
102
152
  }
103
- const cached = cursorCache.get(spoolFile);
104
- if (cached && sameSpoolRevision(cached, revision)) return cached.highest;
105
-
106
- fullScanCount++;
107
- const raw = await fs.readFile(spoolFile, "utf8");
108
- let highest = 0n;
109
- for (const line of raw.split("\n")) {
110
- const trimmed = line.trim();
111
- if (!trimmed) continue;
112
- try {
113
- const parsed = JSON.parse(trimmed) as { cursor?: unknown };
114
- const cursor = parseCursor(parsed.cursor);
115
- if (cursor !== undefined && cursor > highest) highest = cursor;
116
- } catch {
117
- // A crash may leave a torn tail; a full scan ignores it and re-establishes the cache.
153
+ try {
154
+ const stats = await handle.stat();
155
+ const revision = { mtimeMs: stats.mtimeMs, size: stats.size };
156
+ const cached = cursorCache.get(spoolFile);
157
+ if (cached && sameSpoolRevision(cached, revision)) return cached.highest;
158
+
159
+ fullScanCount++;
160
+ const raw = await handle.readFile({ encoding: "utf8" });
161
+ let highest = 0n;
162
+ for (const line of raw.split("\n")) {
163
+ const trimmed = line.trim();
164
+ if (!trimmed) continue;
165
+ try {
166
+ const parsed = JSON.parse(trimmed) as { cursor?: unknown };
167
+ const cursor = parseCursor(parsed.cursor);
168
+ if (cursor !== undefined && cursor > highest) highest = cursor;
169
+ } catch {
170
+ // A crash may leave a torn tail; a full scan ignores it and re-establishes the cache.
171
+ }
118
172
  }
173
+ cursorCache.set(spoolFile, { ...revision, highest });
174
+ return highest;
175
+ } finally {
176
+ await handle.close();
177
+ }
178
+ }
179
+
180
+ async function tightenSpoolDir(dir: string): Promise<void> {
181
+ if (process.platform === "win32") return;
182
+ let handle: fs.FileHandle;
183
+ try {
184
+ handle = await fs.open(dir, fsConstants.O_RDONLY | (fsConstants.O_DIRECTORY ?? 0) | NOFOLLOW);
185
+ } catch {
186
+ return;
187
+ }
188
+ try {
189
+ await handle.chmod(0o700);
190
+ } finally {
191
+ await handle.close();
119
192
  }
120
- cursorCache.set(spoolFile, { ...revision, highest });
121
- return highest;
122
193
  }
123
194
 
124
195
  async function enqueueSpoolAppend<T>(spoolFile: string, task: () => Promise<T>): Promise<T> {
@@ -142,13 +213,19 @@ export async function appendReceiptToSpool(
142
213
  const spoolFile = receiptSpoolPath(resolvedDir);
143
214
  return enqueueSpoolAppend(spoolFile, async () => {
144
215
  await fs.mkdir(resolvedDir, { recursive: true, mode: 0o700 });
216
+ await tightenSpoolDir(resolvedDir);
145
217
  return withFileLock(
146
218
  spoolFile,
147
219
  async () => {
148
220
  const cursor = formatReceiptSpoolCursor((await readHighestReceiptSpoolCursor(resolvedDir)) + 1n);
149
221
  const record: ReceiptSpoolRecord = { cursor, envelope };
150
- const handle = await fs.open(spoolFile, "a", 0o600);
222
+ const handle = await fs.open(
223
+ spoolFile,
224
+ fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND | NOFOLLOW,
225
+ 0o600,
226
+ );
151
227
  try {
228
+ if (process.platform !== "win32") await handle.chmod(0o600);
152
229
  await handle.writeFile(`${JSON.stringify(record)}\n`, "utf8");
153
230
  await handle.sync();
154
231
  } finally {