@sayknow-cli/coding-agent 0.7.11 → 0.7.12

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 (425) hide show
  1. package/CHANGELOG.md +10 -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 +20 -1
  71. package/dist/types/session/messages.d.ts +5 -1
  72. package/dist/types/session/session-manager.d.ts +13 -0
  73. package/dist/types/session/session-storage.d.ts +8 -0
  74. package/dist/types/session/streaming-output.d.ts +11 -0
  75. package/dist/types/session-import/redact.d.ts +1 -1
  76. package/dist/types/skc-runtime/managed-owner-admission.d.ts +3 -0
  77. package/dist/types/skc-runtime/psmux-detect.d.ts +5 -4
  78. package/dist/types/skc-runtime/ralplan-runtime.d.ts +5 -0
  79. package/dist/types/skc-runtime/sidecar-bootstrap-env.d.ts +6 -0
  80. package/dist/types/skc-runtime/state-writer.d.ts +4 -1
  81. package/dist/types/skc-runtime/tmux-sessions.d.ts +24 -0
  82. package/dist/types/skc-runtime/ultragoal-runtime.d.ts +4 -0
  83. package/dist/types/skill-state/workflow-mutation-guard.d.ts +20 -1
  84. package/dist/types/slash-commands/helpers/mcp.d.ts +5 -0
  85. package/dist/types/ssh/ssh-executor.d.ts +3 -1
  86. package/dist/types/system-prompt.d.ts +5 -2
  87. package/dist/types/task/executor.d.ts +17 -3
  88. package/dist/types/task/isolation-dir.d.ts +26 -0
  89. package/dist/types/task/role-body.d.ts +11 -0
  90. package/dist/types/task/token-log-mode.test.d.ts +1 -0
  91. package/dist/types/tools/ask.d.ts +77 -254
  92. package/dist/types/tools/ast-edit-write-path.d.ts +23 -0
  93. package/dist/types/tools/atomic-file-write.d.ts +74 -0
  94. package/dist/types/tools/auto-generated-guard.d.ts +5 -2
  95. package/dist/types/tools/bash-allowed-prefixes.d.ts +16 -0
  96. package/dist/types/tools/bash-interactive.d.ts +2 -0
  97. package/dist/types/tools/bash-skill-urls.d.ts +5 -1
  98. package/dist/types/tools/bash.d.ts +1 -0
  99. package/dist/types/tools/browser/cdp-url.d.ts +2 -0
  100. package/dist/types/tools/browser/tab-worker.d.ts +2 -0
  101. package/dist/types/tools/debug.d.ts +2 -2
  102. package/dist/types/tools/explicit-artifact.d.ts +8 -0
  103. package/dist/types/tools/fetch.d.ts +7 -4
  104. package/dist/types/tools/github-side-effect.d.ts +22 -0
  105. package/dist/types/tools/index.d.ts +3 -0
  106. package/dist/types/tools/monitor-mutation.d.ts +9 -0
  107. package/dist/types/tools/recipe/index.d.ts +2 -0
  108. package/dist/types/tools/recipe/recipe-guard.d.ts +7 -0
  109. package/dist/types/tools/restricted-cwd.d.ts +1 -0
  110. package/dist/types/tools/reverse-engineer.d.ts +81 -0
  111. package/dist/types/tools/search-tool-bm25.d.ts +2 -0
  112. package/dist/types/tools/tmux-self-injection-guard.d.ts +17 -0
  113. package/dist/types/tools/untrusted-content.d.ts +12 -0
  114. package/dist/types/utils/file-mentions.d.ts +5 -0
  115. package/dist/types/utils/open.d.ts +0 -1
  116. package/dist/types/utils/shell-snapshot.d.ts +2 -0
  117. package/dist/types/utils/title-generator.d.ts +12 -2
  118. package/dist/types/utils/tools-checksum.d.ts +7 -0
  119. package/dist/types/utils/xml-escape.d.ts +2 -0
  120. package/dist/types/web/scrapers/types.d.ts +8 -1
  121. package/dist/types/web/search/providers/codex.d.ts +6 -7
  122. package/dist/types/web/search/providers/insane.d.ts +7 -1
  123. package/dist/types/web/search/providers/kimi.d.ts +2 -0
  124. package/dist/types/web/search/providers/searxng.d.ts +7 -0
  125. package/dist/types/web/search/providers/xai.d.ts +2 -0
  126. package/package.json +7 -7
  127. package/scripts/generate-sdk-operation-inventory.ts +4 -0
  128. package/src/async/job-manager.ts +23 -9
  129. package/src/async/result-formatting.ts +40 -0
  130. package/src/capability/fs.ts +78 -11
  131. package/src/capability/mcp.ts +2 -0
  132. package/src/cli/append-system-prompt.ts +12 -0
  133. package/src/cli/auth-broker-cli.ts +22 -12
  134. package/src/cli/config-cli.ts +8 -18
  135. package/src/cli/migrate-cli.ts +7 -5
  136. package/src/cli/ssh-cli.ts +6 -3
  137. package/src/cli/stats-cli.ts +9 -4
  138. package/src/cli/update-cli.ts +42 -0
  139. package/src/cli/web-search-cli.ts +9 -3
  140. package/src/cli.ts +5 -9
  141. package/src/commands/commit.ts +2 -2
  142. package/src/commands/contribution-prep.ts +1 -3
  143. package/src/commands/harness.ts +25 -15
  144. package/src/commands/launch.ts +1 -1
  145. package/src/commands/migrate.ts +3 -3
  146. package/src/commands/sdk.ts +115 -14
  147. package/src/commands/ultragoal.ts +14 -8
  148. package/src/commit/agentic/agent.ts +6 -6
  149. package/src/commit/analysis/conventional.ts +14 -5
  150. package/src/commit/changelog/index.ts +39 -1
  151. package/src/commit/message.ts +10 -3
  152. package/src/config/config-file.ts +106 -3
  153. package/src/config/keybindings.ts +154 -7
  154. package/src/config/mcp-schema.json +4 -0
  155. package/src/config/model-registry.ts +10 -2
  156. package/src/config/settings-schema.ts +18 -0
  157. package/src/config/settings.ts +32 -4
  158. package/src/coordinator-mcp/policy.ts +14 -4
  159. package/src/coordinator-mcp/server.ts +44 -4
  160. package/src/coordinator-mcp/session-reaper.ts +9 -1
  161. package/src/cursor-delete-path.ts +10 -0
  162. package/src/cursor-mcp-name.ts +15 -0
  163. package/src/cursor.ts +13 -2
  164. package/src/dap/client.ts +9 -2
  165. package/src/dap/config.ts +33 -13
  166. package/src/dap/defaults.json +1 -1
  167. package/src/dap/session.ts +161 -36
  168. package/src/debug/crash-diagnostics.ts +89 -6
  169. package/src/debug/report-bundle-parent.ts +22 -0
  170. package/src/debug/report-bundle.ts +100 -3
  171. package/src/debug/system-info.ts +21 -4
  172. package/src/defaults/skc/extensions/grok-cli-vendor/src/shared/base-url.ts +21 -7
  173. package/src/defaults/skc/skills/deep-interview/SKILL.md +1 -1
  174. package/src/discovery/agents-md.ts +3 -2
  175. package/src/discovery/agents.ts +3 -2
  176. package/src/discovery/builtin.ts +21 -11
  177. package/src/discovery/claude.ts +5 -4
  178. package/src/discovery/cline.ts +2 -2
  179. package/src/discovery/codex.ts +6 -5
  180. package/src/discovery/cursor.ts +11 -2
  181. package/src/discovery/gemini.ts +4 -3
  182. package/src/discovery/github.ts +2 -2
  183. package/src/discovery/helpers.ts +51 -11
  184. package/src/discovery/mcp-json.ts +28 -12
  185. package/src/discovery/opencode.ts +2 -1
  186. package/src/discovery/ssh.ts +11 -6
  187. package/src/discovery/substitute-plugin-root.ts +3 -1
  188. package/src/discovery/vscode.ts +3 -3
  189. package/src/edit/apply-patch/index.ts +12 -1
  190. package/src/edit/file-read-cache.ts +24 -6
  191. package/src/edit/index.ts +90 -20
  192. package/src/edit/modes/patch.ts +215 -9
  193. package/src/edit/modes/replace.ts +141 -0
  194. package/src/eval/js/context-manager.ts +29 -3
  195. package/src/eval/js/worker-entry.ts +51 -18
  196. package/src/eval/py/runner.py +144 -5
  197. package/src/eval/py/runtime.ts +44 -4
  198. package/src/eval/py/tool-bridge.ts +4 -0
  199. package/src/exa/mcp-client.ts +53 -11
  200. package/src/exec/bash-executor.ts +87 -4
  201. package/src/exec/non-interactive-env.ts +0 -1
  202. package/src/export/html/css-color.ts +9 -0
  203. package/src/export/html/html-export-destination.ts +16 -0
  204. package/src/export/html/index.ts +102 -8
  205. package/src/export/html/template.generated.ts +1 -1
  206. package/src/extensibility/custom-tools/loader.ts +13 -3
  207. package/src/extensibility/custom-tools/types.ts +3 -1
  208. package/src/extensibility/custom-tools/wrapper.ts +3 -1
  209. package/src/extensibility/plugins/manager.ts +3 -2
  210. package/src/extensibility/plugins/marketplace/cache.ts +15 -0
  211. package/src/extensibility/plugins/marketplace/fetcher.ts +2 -2
  212. package/src/extensibility/plugins/marketplace/manager.ts +5 -3
  213. package/src/extensibility/plugins/plugin-link-path.ts +12 -0
  214. package/src/extensibility/skc-plugins/mcp-policy.ts +2 -1
  215. package/src/goals/runtime.ts +30 -8
  216. package/src/harness-control-plane/finalize.ts +10 -0
  217. package/src/harness-control-plane/operate.ts +12 -4
  218. package/src/harness-control-plane/owner.ts +8 -1
  219. package/src/harness-control-plane/receipt-spool.ts +105 -28
  220. package/src/harness-control-plane/storage.ts +124 -6
  221. package/src/hashline/execute.ts +3 -3
  222. package/src/hashline/recovery.ts +85 -2
  223. package/src/hindsight/config.ts +9 -3
  224. package/src/hindsight/content.ts +116 -16
  225. package/src/hindsight/mental-models.ts +22 -10
  226. package/src/hindsight/state.ts +7 -4
  227. package/src/hooks/native-skill-hook.ts +17 -12
  228. package/src/i18n/messages/de.settings.ts +3 -0
  229. package/src/i18n/messages/es.settings.ts +3 -0
  230. package/src/i18n/messages/fr.settings.ts +3 -0
  231. package/src/i18n/messages/ja.settings.ts +3 -0
  232. package/src/i18n/messages/ko.settings.ts +3 -0
  233. package/src/i18n/messages/zh.settings.ts +3 -0
  234. package/src/internal-urls/artifact-protocol.ts +3 -1
  235. package/src/internal-urls/docs-index.generated.ts +10 -10
  236. package/src/internal-urls/local-protocol.ts +167 -8
  237. package/src/internal-urls/skill-path.ts +18 -0
  238. package/src/internal-urls/skill-protocol.ts +2 -0
  239. package/src/internal-urls/types.ts +2 -0
  240. package/src/lsp/client.ts +2 -1
  241. package/src/lsp/clients/biome-client.ts +2 -0
  242. package/src/lsp/clients/swiftlint-client.ts +2 -0
  243. package/src/lsp/config.ts +18 -62
  244. package/src/lsp/edits.ts +6 -0
  245. package/src/lsp/index.ts +29 -0
  246. package/src/lsp/workspace-path.ts +75 -0
  247. package/src/main.ts +33 -11
  248. package/src/memories/index.ts +141 -9
  249. package/src/migrate/action-planner.ts +57 -0
  250. package/src/migrate/adapters/claude-code.ts +23 -4
  251. package/src/migrate/adapters/codex.ts +22 -4
  252. package/src/migrate/adapters/index.ts +22 -4
  253. package/src/migrate/adapters/opencode.ts +6 -1
  254. package/src/migrate/executor.ts +84 -7
  255. package/src/migrate/report.ts +19 -2
  256. package/src/migrate/types.ts +14 -4
  257. package/src/modes/DESIGN.md +5 -0
  258. package/src/modes/acp/acp-agent.ts +35 -2
  259. package/src/modes/acp/permission-mode.ts +18 -1
  260. package/src/modes/components/custom-editor.ts +14 -0
  261. package/src/modes/components/extensions/extension-dashboard.ts +2 -2
  262. package/src/modes/components/extensions/inspector-panel.ts +9 -5
  263. package/src/modes/components/extensions/state-manager.ts +15 -5
  264. package/src/modes/components/model-selector.ts +144 -94
  265. package/src/modes/components/welcome.ts +3 -2
  266. package/src/modes/controllers/command-controller.ts +300 -9
  267. package/src/modes/controllers/event-controller.ts +1 -1
  268. package/src/modes/controllers/extension-ui-controller.ts +32 -19
  269. package/src/modes/controllers/input-controller.ts +62 -26
  270. package/src/modes/controllers/plan-mode-controller.ts +17 -7
  271. package/src/modes/controllers/runtime-mcp-command-controller.ts +25 -20
  272. package/src/modes/controllers/ssh-command-controller.ts +3 -1
  273. package/src/modes/interactive-mode.ts +10 -0
  274. package/src/modes/utils/macos-option-forwarding.ts +80 -0
  275. package/src/prompts/system/irc-incoming.md +3 -1
  276. package/src/prompts/system/project-prompt.md +19 -0
  277. package/src/prompts/system/system-prompt.md +3 -0
  278. package/src/prompts/tools/ask.md +2 -0
  279. package/src/prompts/tools/debug.md +1 -1
  280. package/src/prompts/tools/monitor.md +7 -5
  281. package/src/prompts/tools/reverse-engineer.md +29 -0
  282. package/src/runtime-credential-selector.ts +2 -2
  283. package/src/runtime-mcp/config-writer.ts +10 -6
  284. package/src/runtime-mcp/config.ts +1 -0
  285. package/src/runtime-mcp/content-limits.ts +7 -0
  286. package/src/runtime-mcp/json-rpc.ts +2 -1
  287. package/src/runtime-mcp/manager.ts +57 -9
  288. package/src/runtime-mcp/mcp-redirect.ts +73 -0
  289. package/src/runtime-mcp/oauth-flow.ts +43 -5
  290. package/src/runtime-mcp/oauth-public-url.ts +8 -0
  291. package/src/runtime-mcp/plugin-mcp-name-filter.ts +62 -0
  292. package/src/runtime-mcp/plugin-network-boundary.ts +4 -0
  293. package/src/runtime-mcp/project-host-values.ts +50 -0
  294. package/src/runtime-mcp/render.ts +16 -1
  295. package/src/runtime-mcp/smithery-registry.ts +22 -3
  296. package/src/runtime-mcp/tool-bridge.ts +194 -21
  297. package/src/runtime-mcp/transports/http.ts +4 -3
  298. package/src/runtime-mcp/transports/stdio.ts +2 -1
  299. package/src/runtime-mcp/types.ts +6 -0
  300. package/src/sdk/broker/broker.ts +11 -2
  301. package/src/sdk/broker/ensure.ts +131 -10
  302. package/src/sdk/broker/lifecycle-ledger.ts +18 -3
  303. package/src/sdk/broker/lifecycle.ts +21 -19
  304. package/src/sdk/broker/runtime.ts +1 -1
  305. package/src/sdk/bus/chat-daemon-cli.ts +38 -1
  306. package/src/sdk/bus/chat-daemon-control.ts +5 -3
  307. package/src/sdk/bus/index.ts +5 -3
  308. package/src/sdk/bus/lifecycle-control-runtime.ts +9 -2
  309. package/src/sdk/bus/session-control.ts +2 -0
  310. package/src/sdk/bus/slack-daemon.ts +8 -1
  311. package/src/sdk/bus/slack-live-provider.ts +3 -1
  312. package/src/sdk/bus/telegram-daemon-contract.ts +3 -1
  313. package/src/sdk/bus/telegram-daemon-control.ts +17 -12
  314. package/src/sdk/bus/telegram-daemon.ts +41 -1
  315. package/src/sdk/host/events.ts +67 -4
  316. package/src/sdk/mcp/server.ts +16 -3
  317. package/src/sdk/protocol/operation-inventory.generated.json +22 -0
  318. package/src/sdk/session.ts +18 -25
  319. package/src/secrets/obfuscator.ts +92 -12
  320. package/src/session/agent-session.ts +395 -79
  321. package/src/session/artifacts.ts +3 -1
  322. package/src/session/history-storage.ts +172 -8
  323. package/src/session/internal/managed-session-scope.ts +130 -52
  324. package/src/session/messages.ts +47 -6
  325. package/src/session/session-manager.ts +116 -8
  326. package/src/session/session-storage.ts +31 -1
  327. package/src/session/streaming-output.ts +263 -4
  328. package/src/session-import/redact.ts +76 -3
  329. package/src/setup/hermes-setup.ts +4 -1
  330. package/src/skc-runtime/gc-runtime.ts +26 -4
  331. package/src/skc-runtime/launch-tmux.ts +21 -11
  332. package/src/skc-runtime/launch-worktree.ts +42 -3
  333. package/src/skc-runtime/managed-owner-admission.ts +46 -2
  334. package/src/skc-runtime/psmux-detect.ts +29 -5
  335. package/src/skc-runtime/ralplan-runtime.ts +14 -1
  336. package/src/skc-runtime/session-resolution.ts +38 -6
  337. package/src/skc-runtime/sidecar-bootstrap-env.ts +19 -0
  338. package/src/skc-runtime/state-writer.ts +134 -16
  339. package/src/skc-runtime/tmux-sessions.ts +85 -4
  340. package/src/skc-runtime/ultragoal-change-set.ts +18 -2
  341. package/src/skc-runtime/ultragoal-guard.ts +9 -1
  342. package/src/skc-runtime/ultragoal-runtime.ts +26 -9
  343. package/src/skill-state/active-state.ts +13 -0
  344. package/src/skill-state/workflow-mutation-guard.ts +3297 -180
  345. package/src/slash-commands/builtin-registry.ts +14 -8
  346. package/src/slash-commands/helpers/mcp.ts +20 -7
  347. package/src/ssh/ssh-executor.ts +3 -1
  348. package/src/stt/recorder.ts +26 -9
  349. package/src/system-prompt.ts +65 -16
  350. package/src/task/commands.ts +3 -1
  351. package/src/task/executor.ts +52 -7
  352. package/src/task/index.ts +28 -0
  353. package/src/task/isolation-dir.ts +143 -0
  354. package/src/task/role-body.ts +84 -0
  355. package/src/task/token-log-mode.test.ts +162 -0
  356. package/src/task/token-log.ts +91 -2
  357. package/src/task/worktree.ts +16 -7
  358. package/src/tools/archive-reader.ts +653 -31
  359. package/src/tools/ask.ts +86 -14
  360. package/src/tools/ast-edit-write-path.ts +133 -0
  361. package/src/tools/ast-edit.ts +27 -1
  362. package/src/tools/ast-grep.ts +7 -2
  363. package/src/tools/atomic-file-write.ts +625 -0
  364. package/src/tools/auto-generated-guard.ts +28 -8
  365. package/src/tools/bash-allowed-prefixes.ts +225 -6
  366. package/src/tools/bash-interactive.ts +12 -0
  367. package/src/tools/bash-skill-urls.ts +113 -7
  368. package/src/tools/bash.ts +152 -20
  369. package/src/tools/browser/cdp-url.ts +18 -0
  370. package/src/tools/browser/tab-worker.ts +49 -14
  371. package/src/tools/browser.ts +25 -8
  372. package/src/tools/cron.ts +10 -1
  373. package/src/tools/debug.ts +16 -8
  374. package/src/tools/eval.ts +71 -34
  375. package/src/tools/explicit-artifact.ts +89 -0
  376. package/src/tools/fetch.ts +26 -17
  377. package/src/tools/gh.ts +40 -12
  378. package/src/tools/github-side-effect.ts +112 -0
  379. package/src/tools/image-gen.ts +24 -10
  380. package/src/tools/index.ts +6 -0
  381. package/src/tools/monitor-mutation.ts +27 -0
  382. package/src/tools/monitor.ts +28 -1
  383. package/src/tools/output-meta.ts +74 -5
  384. package/src/tools/read.ts +24 -36
  385. package/src/tools/recipe/index.ts +12 -0
  386. package/src/tools/recipe/recipe-guard.ts +19 -0
  387. package/src/tools/recipe/runner.ts +23 -12
  388. package/src/tools/render-utils.ts +2 -2
  389. package/src/tools/restricted-cwd.ts +10 -0
  390. package/src/tools/reverse-engineer.ts +497 -0
  391. package/src/tools/search-tool-bm25.ts +14 -3
  392. package/src/tools/search.ts +3 -2
  393. package/src/tools/ssh.ts +235 -8
  394. package/src/tools/subagent-render.ts +43 -7
  395. package/src/tools/subagent.ts +7 -3
  396. package/src/tools/tmux-self-injection-guard.ts +3538 -0
  397. package/src/tools/todo-write.ts +41 -3
  398. package/src/tools/untrusted-content.ts +23 -0
  399. package/src/tools/vim.ts +2 -2
  400. package/src/tools/write.ts +37 -4
  401. package/src/tui/tree-list.ts +15 -1
  402. package/src/utils/commit-message-generator.ts +9 -2
  403. package/src/utils/external-editor.ts +21 -7
  404. package/src/utils/file-mentions.ts +75 -7
  405. package/src/utils/git.ts +38 -7
  406. package/src/utils/open.ts +73 -4
  407. package/src/utils/shell-snapshot.ts +9 -1
  408. package/src/utils/title-generator.ts +61 -16
  409. package/src/utils/tools-checksum.ts +34 -0
  410. package/src/utils/tools-manager.ts +24 -6
  411. package/src/utils/xml-escape.ts +14 -0
  412. package/src/web/insane/url-guard.ts +2 -1
  413. package/src/web/scrapers/types.ts +8 -0
  414. package/src/web/scrapers/youtube.ts +3 -2
  415. package/src/web/search/index.ts +4 -3
  416. package/src/web/search/providers/anthropic.ts +4 -4
  417. package/src/web/search/providers/codex.ts +31 -34
  418. package/src/web/search/providers/insane.ts +145 -28
  419. package/src/web/search/providers/kimi.ts +15 -5
  420. package/src/web/search/providers/searxng.ts +47 -4
  421. package/src/web/search/providers/xai.ts +7 -2
  422. package/dist/types/cli/shell-cli.d.ts +0 -8
  423. package/dist/types/commands/shell.d.ts +0 -21
  424. package/src/cli/shell-cli.ts +0 -176
  425. package/src/commands/shell.ts +0 -29
@@ -0,0 +1,625 @@
1
+ /**
2
+ * Fail-atomic user-file writes for the write/edit/LSP writethrough path.
3
+ *
4
+ * The guarantee is visibility, not crash durability: a failed write never
5
+ * publishes partial or truncated bytes, and the destination is left byte-
6
+ * identical. It is deliberately NOT crash-atomic -- the parent directory is
7
+ * never fsynced, so a rename can be lost across a system crash.
8
+ *
9
+ * Publication is last-writer-wins, not conditional. Identity is revalidated
10
+ * immediately before the rename, which rejects a destination that was replaced
11
+ * or retargeted while staging, but `rename(2)` commits against the pathname:
12
+ * a writer that publishes a successor inside the window between that check and
13
+ * the rename is overwritten. Closing that window needs an OS conditional-
14
+ * replace primitive; the exchange-based one available here was removed because
15
+ * it validated only after committing and leaked protocol debris into user
16
+ * directories on every successful write. `write` is a last-writer-wins tool by
17
+ * contract, so this is the documented behavior rather than a silent race.
18
+ *
19
+ * `Bun.write` truncates the destination then copies bytes. A permission or IO
20
+ * failure after that truncate leaves a 0-byte target even though the tool
21
+ * reported an error. Stage to a sibling temp, then rename over the destination
22
+ * so a failed attempt never publishes a truncated file. Directory fsync is
23
+ * intentionally omitted: Windows reports `EPERM` for it (#4457) and user-file
24
+ * publication does not need that durability barrier.
25
+ *
26
+ * Destination symlinks are followed: the referent is replaced, the link stays.
27
+ * The referent is re-resolved immediately before publication so a retargeted
28
+ * link cannot silently repoint the write. When the lexical destination sits
29
+ * inside the active explicit artifacts local root (`<artifacts>/local`) or a
30
+ * session-scoped `skc-local` root, the resolved referent and its parent must
31
+ * remain inside that root (a link there must not redirect the write out of
32
+ * the trust boundary).
33
+ *
34
+ * Staging uses exclusive create (`wx`) so a colliding leftover temp is never
35
+ * truncated or unlinked; only the temp this call created is cleaned on failure.
36
+ * Existing-file mode and ownership are re-applied after staging so a process
37
+ * umask or replacement inode never changes the target's identity. Hard-linked
38
+ * targets are rejected because replacement would split their link group, and
39
+ * target identity is revalidated before the final same-directory rename. The
40
+ * staged bytes are synced before publication; directory fsync is intentionally not
41
+ * promised because Windows reports EPERM for it (#4457).
42
+ */
43
+
44
+ import * as fs from "node:fs/promises";
45
+ import * as os from "node:os";
46
+ import * as path from "node:path";
47
+ import { hasFsCode, isEacces, isEisdir, isEnoent, isFsError } from "@sayknow-cli/utils";
48
+ import { LocalProtocolHandler } from "../internal-urls/local-protocol";
49
+
50
+ const TEMP_CREATE_ATTEMPTS = 8;
51
+ const DEFAULT_FILE_MODE = 0o666;
52
+ const WINDOWS_RENAME_BACKOFF_MS = [10, 25, 50, 100, 200] as const;
53
+ const WINDOWS_SHARING_VIOLATION_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
54
+
55
+ export type FileWritePublicationState = "not_published" | "published" | "unknown";
56
+
57
+ interface ExistingFileMetadata {
58
+ mode: number;
59
+ uid: number;
60
+ gid: number;
61
+ nlink: number;
62
+ dev: number;
63
+ ino: number;
64
+ }
65
+
66
+ interface ResolvedPublishPath {
67
+ publishPath: string;
68
+ existing?: ExistingFileMetadata;
69
+ }
70
+
71
+ export class FileWriteNotPublishedError extends Error {
72
+ readonly dest: string;
73
+ readonly destUnchanged: boolean;
74
+ readonly publicationState: FileWritePublicationState;
75
+ override readonly cause: unknown;
76
+ constructor(
77
+ dest: string,
78
+ cause: unknown,
79
+ options: { destUnchanged?: boolean; publicationState?: FileWritePublicationState } = {},
80
+ ) {
81
+ const destUnchanged = options.destUnchanged ?? true;
82
+ super(formatFileWriteError(cause, dest, { destUnchanged }));
83
+ this.name = "FileWriteNotPublishedError";
84
+ this.dest = dest;
85
+ this.destUnchanged = destUnchanged;
86
+ this.publicationState = options.publicationState ?? (destUnchanged ? "not_published" : "unknown");
87
+ this.cause = cause;
88
+ if (isFsError(cause)) {
89
+ (this as Error & { code?: string }).code = cause.code;
90
+ }
91
+ }
92
+ }
93
+
94
+ export function isFileWritePermissionError(error: unknown): boolean {
95
+ return isEacces(error) || hasFsCode(error, "EPERM") || hasFsCode(error, "EROFS");
96
+ }
97
+
98
+ export function formatFileWriteError(error: unknown, dest: string, options: { destUnchanged?: boolean } = {}): string {
99
+ if (error instanceof FileWriteNotPublishedError && options.destUnchanged !== false) return error.message;
100
+ if (isEisdir(error)) {
101
+ return `Cannot write '${dest}': path is a directory.`;
102
+ }
103
+ if (isFileWritePermissionError(error)) {
104
+ const code = isFsError(error) ? error.code : "EPERM";
105
+ const unchanged = options.destUnchanged
106
+ ? " The original file was left unchanged."
107
+ : " The destination may already have been replaced if a formatter published earlier in this write.";
108
+ return `Permission denied writing '${dest}' (${code}).${unchanged} Check directory write bits, file immutability, and any sandbox policy. Do not retry the same path through the shell tool.`;
109
+ }
110
+ return error instanceof Error ? error.message : String(error);
111
+ }
112
+
113
+ export interface WriteFileAtomicallyOptions {
114
+ /**
115
+ * Trusted root that a resolved symlink referent and its parent must not
116
+ * leave. When omitted, a destination inside the active explicit artifacts
117
+ * local root (`<artifacts>/local`) uses that root. Otherwise the helper
118
+ * still enforces the session-scoped `skc-local` boundary implied by a
119
+ * lexical destination under `<tmpdir>/skc-local/<session-id>`.
120
+ */
121
+ trustBoundary?: string;
122
+ /** Platform override used by deterministic retry tests. */
123
+ platform?: NodeJS.Platform;
124
+ /** Sleep seam used by deterministic retry tests. */
125
+ sleep?: (delayMs: number) => Promise<void>;
126
+ /** Test seam invoked after the fallback handle is opened and before mutation. */
127
+ beforeInPlaceMutation?: () => Promise<void>;
128
+ }
129
+
130
+ function tempPathFor(dest: string): string {
131
+ const unique = `${process.pid}.${Date.now().toString(36)}.${Math.random().toString(36).slice(2, 8)}`;
132
+ return path.join(path.dirname(dest), `.${path.basename(dest)}.${unique}.tmp`);
133
+ }
134
+
135
+ function eisdir(dest: string): Error & { code: string } {
136
+ const error = new Error(`EISDIR: illegal operation on a directory, write '${dest}'`) as Error & {
137
+ code: string;
138
+ };
139
+ error.code = "EISDIR";
140
+ return error;
141
+ }
142
+
143
+ async function resolvePublishPath(dest: string, depth = 0): Promise<ResolvedPublishPath> {
144
+ if (depth > 40) {
145
+ throw new Error(`ELOOP: too many symbolic links, write '${dest}'`);
146
+ }
147
+ try {
148
+ const lst = await fs.lstat(dest);
149
+ if (lst.isDirectory()) throw eisdir(dest);
150
+ if (lst.isSymbolicLink()) {
151
+ const target = await fs.readlink(dest);
152
+ return resolvePublishPath(path.resolve(path.dirname(dest), target), depth + 1);
153
+ }
154
+ return {
155
+ publishPath: dest,
156
+ existing: {
157
+ mode: lst.mode,
158
+ uid: lst.uid,
159
+ gid: lst.gid,
160
+ nlink: lst.nlink,
161
+ dev: lst.dev,
162
+ ino: lst.ino,
163
+ },
164
+ };
165
+ } catch (error) {
166
+ if (!isEnoent(error)) throw error;
167
+ return { publishPath: dest };
168
+ }
169
+ }
170
+
171
+ function pathIsWithin(target: string, root: string): boolean {
172
+ return target === root || target.startsWith(`${root}${path.sep}`);
173
+ }
174
+
175
+ async function realpathOrSelf(p: string): Promise<string> {
176
+ const resolved = path.resolve(p);
177
+ const missing: string[] = [];
178
+ let cursor = resolved;
179
+ for (;;) {
180
+ try {
181
+ const real = await fs.realpath(cursor);
182
+ return missing.length === 0 ? real : path.join(real, ...missing.reverse());
183
+ } catch (error) {
184
+ if (!isEnoent(error)) throw error;
185
+ const parent = path.dirname(cursor);
186
+ if (parent === cursor) return resolved;
187
+ missing.push(path.basename(cursor));
188
+ cursor = parent;
189
+ }
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Derive the session-scoped `local://` trust boundary from a lexical write
195
+ * destination. Session roots live at `<tmpdir>/skc-local/<session-id>`, and a
196
+ * symlink placed inside one must not be able to redirect a write out of it.
197
+ */
198
+ function sessionLocalRootFor(lexicalDest: string): string | undefined {
199
+ const resolvedDest = path.resolve(lexicalDest);
200
+ const localParent = path.join(os.tmpdir(), "skc-local");
201
+ if (!pathIsWithin(resolvedDest, localParent)) return undefined;
202
+ const rest = resolvedDest.slice(localParent.length + path.sep.length);
203
+ const sessionSegment = rest.split(path.sep, 1)[0] ?? "";
204
+ if (sessionSegment.length === 0) return undefined;
205
+ return path.join(localParent, sessionSegment);
206
+ }
207
+
208
+ /**
209
+ * Active explicit artifacts root (`<artifacts>/local`) when `lexicalDest` is
210
+ * inside it. That root is not under `<tmpdir>/skc-local`, so the tmp helper
211
+ * above would leave the write unbounded. Managed sessions keep the tmp root.
212
+ */
213
+ function explicitLocalRootFor(lexicalDest: string): string | undefined {
214
+ const options = LocalProtocolHandler.resolveOptions();
215
+ if (!options || options.isManagedDestination?.()) return undefined;
216
+ const artifactsDir = options.getArtifactsDir?.();
217
+ if (!artifactsDir) return undefined;
218
+ const root = path.resolve(artifactsDir, "local");
219
+ if (!pathIsWithin(path.resolve(lexicalDest), root)) return undefined;
220
+ return root;
221
+ }
222
+
223
+ function trustBoundaryForDestination(lexicalDest: string): string | undefined {
224
+ return explicitLocalRootFor(lexicalDest) ?? sessionLocalRootFor(lexicalDest);
225
+ }
226
+
227
+ /**
228
+ * Reject publication when the resolved referent's real parent (and therefore
229
+ * the referent itself) leaves the trust boundary. The boundary root is
230
+ * realpathed so a symlinked `skc-local` root cannot smuggle a write out.
231
+ *
232
+ * This must run before any directory is created. A dangling symlink inside a
233
+ * trusted root resolves to a path outside it, so creating parents first would
234
+ * let an attacker-selected directory tree be materialized outside the sandbox
235
+ * before publication is refused. A missing path is resolved through the
236
+ * nearest existing ancestor's realpath, then the missing suffix is appended.
237
+ */
238
+ async function assertWithinTrustBoundary(publishPath: string, trustBoundary: string): Promise<void> {
239
+ const boundary = path.resolve(trustBoundary);
240
+ const realBoundary = await realpathOrSelf(boundary);
241
+ const realParent = await realpathOrSelf(path.dirname(publishPath));
242
+ if (!pathIsWithin(realParent, realBoundary)) {
243
+ throw new Error(`write target '${publishPath}' resolves outside trust boundary '${trustBoundary}'`);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Identity of the publication parent directory. A realpath string alone cannot
249
+ * detect a parent that was unlinked and replaced by a different directory at
250
+ * the same path: the string still matches while the rename would publish into
251
+ * the replacement. Pin device and inode instead.
252
+ */
253
+ interface ParentIdentity {
254
+ realpath: string;
255
+ dev: number;
256
+ ino: number;
257
+ }
258
+
259
+ async function captureParentIdentity(publishPath: string): Promise<ParentIdentity> {
260
+ const parent = path.dirname(publishPath);
261
+ const realpath = await realpathOrSelf(parent);
262
+ const stat = await fs.stat(parent);
263
+ return { realpath, dev: stat.dev, ino: stat.ino };
264
+ }
265
+
266
+ /**
267
+ * Rename replaces the referent without consulting its file permissions, so a
268
+ * writable parent could otherwise overwrite a read-only or ACL-denied target in
269
+ * a way a direct write would not. Probe effective write authorization the way a
270
+ * direct write would: open the existing referent for append (requires write
271
+ * permission and mutates nothing). Native Windows read-only attributes surface
272
+ * as EPERM/EACCES here just like POSIX immutable/`0444` targets.
273
+ */
274
+ async function assertExistingTargetWritable(publishPath: string): Promise<void> {
275
+ const handle = await fs.open(publishPath, "a");
276
+ await handle.close();
277
+ }
278
+
279
+ function sameFileIdentity(left: ExistingFileMetadata, right: ExistingFileMetadata): boolean {
280
+ return (
281
+ left.dev === right.dev &&
282
+ left.ino === right.ino &&
283
+ left.nlink === right.nlink &&
284
+ left.mode === right.mode &&
285
+ left.uid === right.uid &&
286
+ left.gid === right.gid
287
+ );
288
+ }
289
+
290
+ function metadataFromStat(stat: {
291
+ mode: number;
292
+ uid: number;
293
+ gid: number;
294
+ nlink: number;
295
+ dev: number;
296
+ ino: number;
297
+ }): ExistingFileMetadata {
298
+ return {
299
+ mode: stat.mode,
300
+ uid: stat.uid,
301
+ gid: stat.gid,
302
+ nlink: stat.nlink,
303
+ dev: stat.dev,
304
+ ino: stat.ino,
305
+ };
306
+ }
307
+
308
+ async function readWholeFileAtPositionZero(handle: fs.FileHandle): Promise<Uint8Array> {
309
+ const stat = await handle.stat();
310
+ const bytes = new Uint8Array(stat.size);
311
+ let read = 0;
312
+ while (read < bytes.byteLength) {
313
+ const result = await handle.read(bytes, read, bytes.byteLength - read, read);
314
+ if (result.bytesRead === 0) throw new Error(`in-place read stalled at ${read} of ${bytes.byteLength} bytes`);
315
+ read += result.bytesRead;
316
+ }
317
+ return bytes;
318
+ }
319
+
320
+ async function preserveExistingMetadata(tmp: string, existing: ExistingFileMetadata): Promise<void> {
321
+ const staged = await fs.stat(tmp);
322
+ if (staged.uid !== existing.uid || staged.gid !== existing.gid) {
323
+ await fs.chown(tmp, existing.uid, existing.gid);
324
+ }
325
+ await fs.chmod(tmp, existing.mode);
326
+ }
327
+
328
+ async function cleanupOwnedTemp(tmp: string, cause: unknown): Promise<void> {
329
+ try {
330
+ await fs.unlink(tmp);
331
+ } catch (cleanupError) {
332
+ if (isEnoent(cleanupError)) return;
333
+ throw new AggregateError([cause, cleanupError], `Failed to clean up staging file '${tmp}'.`);
334
+ }
335
+ }
336
+
337
+ function isWindowsSharingViolation(error: unknown): boolean {
338
+ return isFsError(error) && WINDOWS_SHARING_VIOLATION_CODES.has(error.code);
339
+ }
340
+
341
+ async function renameIntoPlace(
342
+ from: string,
343
+ to: string,
344
+ platform: NodeJS.Platform,
345
+ sleep: (delayMs: number) => Promise<void>,
346
+ ): Promise<void> {
347
+ try {
348
+ await fs.rename(from, to);
349
+ return;
350
+ } catch (error) {
351
+ if (platform !== "win32" || !isWindowsSharingViolation(error)) throw error;
352
+ let lastError: unknown = error;
353
+ for (const delay of WINDOWS_RENAME_BACKOFF_MS) {
354
+ await sleep(delay);
355
+ try {
356
+ await fs.rename(from, to);
357
+ return;
358
+ } catch (retryError) {
359
+ lastError = retryError;
360
+ if (!isWindowsSharingViolation(retryError)) throw retryError;
361
+ }
362
+ }
363
+ throw lastError;
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Windows permits another process to share writes while denying delete/rename.
369
+ * In that narrow case preserve the existing inode and perform a rollback-capable
370
+ * in-place replacement. Hard-linked files never enter this path: they are
371
+ * rejected before staging because a failed write cannot safely preserve every
372
+ * alias with a pathname replacement contract.
373
+ */
374
+ /**
375
+ * Write `bytes` as the file's entire leading content starting at absolute
376
+ * position 0, looping until every byte is accepted. `FileHandle.writeFile()`
377
+ * writes from the handle's current position, which makes it unsafe for a
378
+ * rollback that must reproduce the original bytes exactly.
379
+ */
380
+ async function writeWholeFileAtPositionZero(handle: fs.FileHandle, bytes: Uint8Array): Promise<void> {
381
+ let written = 0;
382
+ while (written < bytes.byteLength) {
383
+ const result = await handle.write(bytes, written, bytes.byteLength - written, written);
384
+ if (result.bytesWritten === 0)
385
+ throw new Error(`in-place write stalled at ${written} of ${bytes.byteLength} bytes`);
386
+ written += result.bytesWritten;
387
+ }
388
+ }
389
+
390
+ async function replaceInPlaceAfterSharingViolation(
391
+ dest: string,
392
+ tmp: string,
393
+ platform: NodeJS.Platform,
394
+ expectedExisting: ExistingFileMetadata,
395
+ beforeMutation?: () => Promise<void>,
396
+ ): Promise<void> {
397
+ if (platform !== "win32") throw new Error("in-place sharing fallback is Windows-only");
398
+ // This fallback mutates the destination by pathname instead of publishing a
399
+ // staged inode, so it must re-establish that the pathname still names the
400
+ // file we were authorized to replace. Rename retries and their backoff give a
401
+ // concurrent writer time to substitute a different inode; overwriting that
402
+ // one in place would be an unauthorized mutation with no rollback source.
403
+ // Open the pathname first, then bind all reads and writes to that handle. A
404
+ // pathname read followed by a later open can read one inode and mutate its
405
+ // successor. The handle identity and pathname identity are both checked
406
+ // immediately before the first mutation; a race therefore fails closed and
407
+ // never writes the successor.
408
+ const replacement = new Uint8Array(await Bun.file(tmp).arrayBuffer());
409
+ const handle = await fs.open(dest, "r+");
410
+ let original: Uint8Array | undefined;
411
+ let failure: unknown;
412
+ let committed = false;
413
+ let mutationStarted = false;
414
+ try {
415
+ try {
416
+ const opened = metadataFromStat(await handle.stat());
417
+ if (!sameFileIdentity(opened, expectedExisting)) {
418
+ throw new FileWriteNotPublishedError(
419
+ dest,
420
+ new Error(`destination '${dest}' changed before the in-place fallback was opened`),
421
+ { destUnchanged: true, publicationState: "not_published" },
422
+ );
423
+ }
424
+ original = await readWholeFileAtPositionZero(handle);
425
+ if (beforeMutation) await beforeMutation();
426
+ const current = (await resolvePublishPath(dest)).existing;
427
+ const bound = metadataFromStat(await handle.stat());
428
+ if (
429
+ current === undefined ||
430
+ !sameFileIdentity(current, expectedExisting) ||
431
+ !sameFileIdentity(bound, expectedExisting)
432
+ ) {
433
+ throw new FileWriteNotPublishedError(
434
+ dest,
435
+ new Error(
436
+ `destination '${dest}' was replaced before the in-place fallback mutation; refusing to overwrite a different file`,
437
+ ),
438
+ { destUnchanged: true, publicationState: "not_published" },
439
+ );
440
+ }
441
+ // Write at an explicit absolute position: handle.writeFile() appends from
442
+ // the handle's current offset, so a retry or rollback after a partial
443
+ // write would otherwise land mid-file and interleave bytes.
444
+ mutationStarted = true;
445
+ await writeWholeFileAtPositionZero(handle, replacement);
446
+ await handle.sync();
447
+ await handle.truncate(replacement.byteLength);
448
+ await handle.sync();
449
+ committed = true;
450
+ } catch (error) {
451
+ if (original !== undefined && mutationStarted) {
452
+ try {
453
+ await writeWholeFileAtPositionZero(handle, original);
454
+ await handle.truncate(original.byteLength);
455
+ await handle.sync();
456
+ } catch (rollbackError) {
457
+ failure = new FileWriteNotPublishedError(
458
+ dest,
459
+ new AggregateError([error, rollbackError], "In-place write rollback failed."),
460
+ { destUnchanged: false, publicationState: "unknown" },
461
+ );
462
+ }
463
+ }
464
+ if (failure === undefined) failure = error;
465
+ }
466
+ } finally {
467
+ try {
468
+ await handle.close();
469
+ } catch (closeError) {
470
+ if (committed) {
471
+ failure = new FileWriteNotPublishedError(dest, closeError, {
472
+ destUnchanged: false,
473
+ publicationState: "published",
474
+ });
475
+ } else if (failure === undefined) {
476
+ failure = closeError;
477
+ }
478
+ }
479
+ }
480
+ if (failure !== undefined) {
481
+ if (failure instanceof FileWriteNotPublishedError) throw failure;
482
+ throw new FileWriteNotPublishedError(dest, failure, {
483
+ destUnchanged: !committed,
484
+ publicationState: committed ? "published" : "not_published",
485
+ });
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Revalidate the resolved destination immediately before publication so a
491
+ * symlink retargeted while staging cannot silently repoint the write at a
492
+ * different file.
493
+ */
494
+ async function assertPublishTargetStillIntended(
495
+ dest: string,
496
+ publishPath: string,
497
+ trustBoundary: string | undefined,
498
+ expectedExisting: ExistingFileMetadata | undefined,
499
+ expectedParent: ParentIdentity,
500
+ ): Promise<void> {
501
+ const after = await resolvePublishPath(dest);
502
+ if (after.publishPath !== publishPath) {
503
+ throw new Error(`destination '${dest}' was retargeted while staging; refusing to overwrite a different file`);
504
+ }
505
+ const currentParent = await captureParentIdentity(publishPath);
506
+ if (
507
+ currentParent.realpath !== expectedParent.realpath ||
508
+ currentParent.dev !== expectedParent.dev ||
509
+ currentParent.ino !== expectedParent.ino
510
+ ) {
511
+ throw new Error(
512
+ `destination '${dest}' parent was retargeted while staging; refusing to overwrite a different file`,
513
+ );
514
+ }
515
+ if (expectedExisting === undefined) {
516
+ if (after.existing !== undefined) {
517
+ throw new Error(`destination '${dest}' appeared while staging; refusing to overwrite a different file`);
518
+ }
519
+ } else if (after.existing === undefined || !sameFileIdentity(after.existing, expectedExisting)) {
520
+ throw new Error(`destination '${dest}' was replaced while staging; refusing to overwrite a different file`);
521
+ }
522
+ if (trustBoundary !== undefined) {
523
+ await assertWithinTrustBoundary(after.publishPath, trustBoundary);
524
+ }
525
+ }
526
+
527
+ export async function writeFileAtomically(
528
+ dest: string,
529
+ content: string | Uint8Array,
530
+ options: WriteFileAtomicallyOptions = {},
531
+ ): Promise<void> {
532
+ let publishPath = dest;
533
+ try {
534
+ const platform = options.platform ?? process.platform;
535
+ const sleep = options.sleep ?? (async (delayMs: number): Promise<void> => await Bun.sleep(delayMs));
536
+ const trustBoundary = options.trustBoundary ?? trustBoundaryForDestination(dest);
537
+ const resolved = await resolvePublishPath(dest);
538
+ publishPath = resolved.publishPath;
539
+ // Boundary first, then create parents. A dangling symlink inside a trusted
540
+ // root resolves outside it, so creating directories before this check would
541
+ // materialize an attacker-selected tree outside the sandbox and only then
542
+ // refuse to publish.
543
+ if (trustBoundary !== undefined) {
544
+ await assertWithinTrustBoundary(publishPath, trustBoundary);
545
+ }
546
+ await fs.mkdir(path.dirname(publishPath), { recursive: true });
547
+ // Re-check after creation: `mkdir -p` follows existing symlinked ancestors,
548
+ // so the post-creation parent is the one publication must be bound to.
549
+ if (trustBoundary !== undefined) {
550
+ await assertWithinTrustBoundary(publishPath, trustBoundary);
551
+ }
552
+ const expectedParent = await captureParentIdentity(publishPath);
553
+ const existing = resolved.existing;
554
+ if (existing !== undefined && existing.nlink > 1) {
555
+ throw new Error(
556
+ `Cannot atomically replace hard-linked file '${dest}': replacement would split its link group.`,
557
+ );
558
+ }
559
+ if (existing !== undefined) {
560
+ await assertExistingTargetWritable(publishPath);
561
+ }
562
+ let lastError: unknown;
563
+ for (let attempt = 0; attempt < TEMP_CREATE_ATTEMPTS; attempt++) {
564
+ const tmp = tempPathFor(publishPath);
565
+ let owned = false;
566
+ try {
567
+ const handle = await fs.open(tmp, "wx", existing?.mode ?? DEFAULT_FILE_MODE);
568
+ owned = true;
569
+ try {
570
+ await handle.writeFile(content);
571
+ await handle.sync();
572
+ } finally {
573
+ await handle.close();
574
+ }
575
+ if (existing !== undefined) {
576
+ await preserveExistingMetadata(tmp, existing);
577
+ }
578
+ await assertPublishTargetStillIntended(dest, publishPath, trustBoundary, existing, expectedParent);
579
+ // The staged file lives beside the destination, so rename is one
580
+ // same-directory atomic publication. A failed rename leaves the
581
+ // destination untouched and the owned staging file is cleaned below.
582
+ try {
583
+ await renameIntoPlace(tmp, publishPath, platform, sleep);
584
+ } catch (error) {
585
+ if (existing !== undefined && platform === "win32" && isWindowsSharingViolation(error)) {
586
+ await replaceInPlaceAfterSharingViolation(
587
+ publishPath,
588
+ tmp,
589
+ platform,
590
+ existing,
591
+ options.beforeInPlaceMutation,
592
+ );
593
+ try {
594
+ await fs.unlink(tmp);
595
+ } catch (cleanupError) {
596
+ owned = false;
597
+ throw new FileWriteNotPublishedError(
598
+ dest,
599
+ new AggregateError([error, cleanupError], "Published bytes could not be cleaned up."),
600
+ { destUnchanged: false, publicationState: "published" },
601
+ );
602
+ }
603
+ owned = false;
604
+ return;
605
+ }
606
+ throw error;
607
+ }
608
+ owned = false;
609
+ return;
610
+ } catch (error) {
611
+ lastError = error;
612
+ // A temp that never got created was a genuine pre-existing
613
+ // collision file: leave it alone and try a fresh sibling name.
614
+ if (hasFsCode(error, "EEXIST") && !owned) continue;
615
+ // Any failure after we exclusively created the temp must not leak it.
616
+ if (owned) await cleanupOwnedTemp(tmp, error);
617
+ throw error;
618
+ }
619
+ }
620
+ throw lastError;
621
+ } catch (error) {
622
+ if (error instanceof FileWriteNotPublishedError) throw error;
623
+ throw new FileWriteNotPublishedError(dest, error);
624
+ }
625
+ }