alchemylab-opencode 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/LICENSE +21 -0
  2. package/NODE_COMPAT.md +184 -0
  3. package/package.json +112 -0
  4. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/migration.sql +90 -0
  5. package/packages/opencode/migration/20260127222353_familiar_lady_ursula/snapshot.json +796 -0
  6. package/packages/opencode/migration/20260211171708_add_project_commands/migration.sql +1 -0
  7. package/packages/opencode/migration/20260211171708_add_project_commands/snapshot.json +806 -0
  8. package/packages/opencode/migration/20260213144116_wakeful_the_professor/migration.sql +11 -0
  9. package/packages/opencode/migration/20260213144116_wakeful_the_professor/snapshot.json +897 -0
  10. package/packages/opencode/migration/20260225215848_workspace/migration.sql +7 -0
  11. package/packages/opencode/migration/20260225215848_workspace/snapshot.json +959 -0
  12. package/packages/opencode/migration/20260227213759_add_session_workspace_id/migration.sql +2 -0
  13. package/packages/opencode/migration/20260227213759_add_session_workspace_id/snapshot.json +983 -0
  14. package/packages/opencode/migration/20260228203230_blue_harpoon/migration.sql +17 -0
  15. package/packages/opencode/migration/20260228203230_blue_harpoon/snapshot.json +1102 -0
  16. package/packages/opencode/migration/20260303231226_add_workspace_fields/migration.sql +5 -0
  17. package/packages/opencode/migration/20260303231226_add_workspace_fields/snapshot.json +1013 -0
  18. package/packages/opencode/migration/20260309230000_move_org_to_state/migration.sql +3 -0
  19. package/packages/opencode/migration/20260309230000_move_org_to_state/snapshot.json +1156 -0
  20. package/packages/opencode/migration/20260312043431_session_message_cursor/migration.sql +4 -0
  21. package/packages/opencode/migration/20260312043431_session_message_cursor/snapshot.json +1168 -0
  22. package/packages/opencode/migration/20260323234822_events/migration.sql +13 -0
  23. package/packages/opencode/migration/20260323234822_events/snapshot.json +1271 -0
  24. package/packages/opencode/package.json +140 -0
  25. package/packages/opencode/src/account/account.sql.ts +39 -0
  26. package/packages/opencode/src/account/index.ts +463 -0
  27. package/packages/opencode/src/account/repo.ts +163 -0
  28. package/packages/opencode/src/account/schema.ts +91 -0
  29. package/packages/opencode/src/acp/README.md +174 -0
  30. package/packages/opencode/src/acp/agent.ts +1847 -0
  31. package/packages/opencode/src/acp/session.ts +116 -0
  32. package/packages/opencode/src/acp/types.ts +24 -0
  33. package/packages/opencode/src/agent/agent.ts +420 -0
  34. package/packages/opencode/src/agent/generate.txt +75 -0
  35. package/packages/opencode/src/agent/prompt/compaction.txt +15 -0
  36. package/packages/opencode/src/agent/prompt/explore.txt +18 -0
  37. package/packages/opencode/src/agent/prompt/summary.txt +11 -0
  38. package/packages/opencode/src/agent/prompt/title.txt +44 -0
  39. package/packages/opencode/src/auth/index.ts +110 -0
  40. package/packages/opencode/src/bus/bus-event.ts +40 -0
  41. package/packages/opencode/src/bus/global.ts +10 -0
  42. package/packages/opencode/src/bus/index.ts +185 -0
  43. package/packages/opencode/src/cli/bootstrap.ts +17 -0
  44. package/packages/opencode/src/cli/cmd/cmd.ts +7 -0
  45. package/packages/opencode/src/cli/cmd/run.ts +689 -0
  46. package/packages/opencode/src/cli/cmd/serve.ts +24 -0
  47. package/packages/opencode/src/cli/cmd/tui/event.ts +49 -0
  48. package/packages/opencode/src/cli/effect/prompt.ts +25 -0
  49. package/packages/opencode/src/cli/error.ts +46 -0
  50. package/packages/opencode/src/cli/heap.ts +59 -0
  51. package/packages/opencode/src/cli/logo.ts +6 -0
  52. package/packages/opencode/src/cli/network.ts +60 -0
  53. package/packages/opencode/src/cli/ui.ts +133 -0
  54. package/packages/opencode/src/cli/upgrade.ts +31 -0
  55. package/packages/opencode/src/command/index.ts +195 -0
  56. package/packages/opencode/src/command/template/initialize.txt +66 -0
  57. package/packages/opencode/src/command/template/review.txt +101 -0
  58. package/packages/opencode/src/config/config.ts +1599 -0
  59. package/packages/opencode/src/config/console-state.ts +15 -0
  60. package/packages/opencode/src/config/markdown.ts +99 -0
  61. package/packages/opencode/src/config/paths.ts +167 -0
  62. package/packages/opencode/src/config/tui-migrate.ts +155 -0
  63. package/packages/opencode/src/config/tui-schema.ts +37 -0
  64. package/packages/opencode/src/config/tui.ts +179 -0
  65. package/packages/opencode/src/control-plane/adaptors/index.ts +20 -0
  66. package/packages/opencode/src/control-plane/adaptors/worktree.ts +42 -0
  67. package/packages/opencode/src/control-plane/schema.ts +17 -0
  68. package/packages/opencode/src/control-plane/sse.ts +66 -0
  69. package/packages/opencode/src/control-plane/types.ts +32 -0
  70. package/packages/opencode/src/control-plane/workspace.sql.ts +17 -0
  71. package/packages/opencode/src/control-plane/workspace.ts +168 -0
  72. package/packages/opencode/src/effect/cross-spawn-spawner.ts +502 -0
  73. package/packages/opencode/src/effect/instance-ref.ts +6 -0
  74. package/packages/opencode/src/effect/instance-registry.ts +12 -0
  75. package/packages/opencode/src/effect/instance-state.ts +82 -0
  76. package/packages/opencode/src/effect/run-service.ts +33 -0
  77. package/packages/opencode/src/effect/runner.ts +216 -0
  78. package/packages/opencode/src/env/index.ts +28 -0
  79. package/packages/opencode/src/file/ignore.ts +82 -0
  80. package/packages/opencode/src/file/index.ts +686 -0
  81. package/packages/opencode/src/file/protected.ts +59 -0
  82. package/packages/opencode/src/file/ripgrep.ts +376 -0
  83. package/packages/opencode/src/file/time.ts +133 -0
  84. package/packages/opencode/src/file/watcher.ts +173 -0
  85. package/packages/opencode/src/filesystem/index.ts +236 -0
  86. package/packages/opencode/src/flag/flag.ts +156 -0
  87. package/packages/opencode/src/format/formatter.ts +413 -0
  88. package/packages/opencode/src/format/index.ts +203 -0
  89. package/packages/opencode/src/git/index.ts +303 -0
  90. package/packages/opencode/src/global/index.ts +56 -0
  91. package/packages/opencode/src/id/id.ts +85 -0
  92. package/packages/opencode/src/ide/index.ts +74 -0
  93. package/packages/opencode/src/installation/index.ts +355 -0
  94. package/packages/opencode/src/installation/meta.ts +7 -0
  95. package/packages/opencode/src/lsp/client.ts +252 -0
  96. package/packages/opencode/src/lsp/index.ts +558 -0
  97. package/packages/opencode/src/lsp/language.ts +120 -0
  98. package/packages/opencode/src/lsp/launch.ts +21 -0
  99. package/packages/opencode/src/lsp/server.ts +1968 -0
  100. package/packages/opencode/src/mcp/auth.ts +173 -0
  101. package/packages/opencode/src/mcp/index.ts +931 -0
  102. package/packages/opencode/src/mcp/oauth-callback.ts +216 -0
  103. package/packages/opencode/src/mcp/oauth-provider.ts +185 -0
  104. package/packages/opencode/src/node-loader.mjs +104 -0
  105. package/packages/opencode/src/node-preload.mjs +39 -0
  106. package/packages/opencode/src/node.ts +1 -0
  107. package/packages/opencode/src/npm/index.ts +188 -0
  108. package/packages/opencode/src/patch/index.ts +680 -0
  109. package/packages/opencode/src/permission/arity.ts +163 -0
  110. package/packages/opencode/src/permission/evaluate.ts +15 -0
  111. package/packages/opencode/src/permission/index.ts +325 -0
  112. package/packages/opencode/src/permission/schema.ts +17 -0
  113. package/packages/opencode/src/plugin/cloudflare.ts +67 -0
  114. package/packages/opencode/src/plugin/codex.ts +608 -0
  115. package/packages/opencode/src/plugin/github-copilot/copilot.ts +361 -0
  116. package/packages/opencode/src/plugin/github-copilot/models.ts +144 -0
  117. package/packages/opencode/src/plugin/index.ts +299 -0
  118. package/packages/opencode/src/plugin/install.ts +439 -0
  119. package/packages/opencode/src/plugin/loader.ts +174 -0
  120. package/packages/opencode/src/plugin/meta.ts +188 -0
  121. package/packages/opencode/src/plugin/shared.ts +323 -0
  122. package/packages/opencode/src/project/bootstrap.ts +31 -0
  123. package/packages/opencode/src/project/instance.ts +175 -0
  124. package/packages/opencode/src/project/project.sql.ts +16 -0
  125. package/packages/opencode/src/project/project.ts +519 -0
  126. package/packages/opencode/src/project/schema.ts +16 -0
  127. package/packages/opencode/src/project/state.ts +70 -0
  128. package/packages/opencode/src/project/vcs.ts +240 -0
  129. package/packages/opencode/src/provider/auth.ts +253 -0
  130. package/packages/opencode/src/provider/error.ts +197 -0
  131. package/packages/opencode/src/provider/models.ts +162 -0
  132. package/packages/opencode/src/provider/provider.ts +1709 -0
  133. package/packages/opencode/src/provider/schema.ts +38 -0
  134. package/packages/opencode/src/provider/sdk/copilot/README.md +5 -0
  135. package/packages/opencode/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  136. package/packages/opencode/src/provider/sdk/copilot/chat/get-response-metadata.ts +15 -0
  137. package/packages/opencode/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  138. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +64 -0
  139. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  140. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +28 -0
  141. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  142. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  143. package/packages/opencode/src/provider/sdk/copilot/copilot-provider.ts +100 -0
  144. package/packages/opencode/src/provider/sdk/copilot/index.ts +2 -0
  145. package/packages/opencode/src/provider/sdk/copilot/openai-compatible-error.ts +27 -0
  146. package/packages/opencode/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  147. package/packages/opencode/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  148. package/packages/opencode/src/provider/sdk/copilot/responses/openai-config.ts +18 -0
  149. package/packages/opencode/src/provider/sdk/copilot/responses/openai-error.ts +22 -0
  150. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  151. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +1769 -0
  152. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  153. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  154. package/packages/opencode/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  155. package/packages/opencode/src/provider/sdk/copilot/responses/tool/file-search.ts +127 -0
  156. package/packages/opencode/src/provider/sdk/copilot/responses/tool/image-generation.ts +114 -0
  157. package/packages/opencode/src/provider/sdk/copilot/responses/tool/local-shell.ts +64 -0
  158. package/packages/opencode/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  159. package/packages/opencode/src/provider/sdk/copilot/responses/tool/web-search.ts +102 -0
  160. package/packages/opencode/src/provider/transform.ts +1050 -0
  161. package/packages/opencode/src/pty/index.ts +397 -0
  162. package/packages/opencode/src/pty/pty.node.ts +27 -0
  163. package/packages/opencode/src/pty/pty.ts +25 -0
  164. package/packages/opencode/src/pty/schema.ts +17 -0
  165. package/packages/opencode/src/question/index.ts +224 -0
  166. package/packages/opencode/src/question/schema.ts +17 -0
  167. package/packages/opencode/src/run.ts +28 -0
  168. package/packages/opencode/src/serve.ts +45 -0
  169. package/packages/opencode/src/server/error.ts +36 -0
  170. package/packages/opencode/src/server/event.ts +7 -0
  171. package/packages/opencode/src/server/instance.ts +324 -0
  172. package/packages/opencode/src/server/mdns.ts +60 -0
  173. package/packages/opencode/src/server/middleware.ts +33 -0
  174. package/packages/opencode/src/server/projectors.ts +28 -0
  175. package/packages/opencode/src/server/proxy.ts +131 -0
  176. package/packages/opencode/src/server/router.ts +105 -0
  177. package/packages/opencode/src/server/routes/config.ts +92 -0
  178. package/packages/opencode/src/server/routes/event.ts +83 -0
  179. package/packages/opencode/src/server/routes/experimental.ts +374 -0
  180. package/packages/opencode/src/server/routes/file.ts +197 -0
  181. package/packages/opencode/src/server/routes/global.ts +312 -0
  182. package/packages/opencode/src/server/routes/mcp.ts +225 -0
  183. package/packages/opencode/src/server/routes/permission.ts +69 -0
  184. package/packages/opencode/src/server/routes/project.ts +118 -0
  185. package/packages/opencode/src/server/routes/provider.ts +171 -0
  186. package/packages/opencode/src/server/routes/pty.ts +210 -0
  187. package/packages/opencode/src/server/routes/question.ts +99 -0
  188. package/packages/opencode/src/server/routes/session.ts +1030 -0
  189. package/packages/opencode/src/server/routes/tui.ts +379 -0
  190. package/packages/opencode/src/server/routes/workspace.ts +94 -0
  191. package/packages/opencode/src/server/server.ts +353 -0
  192. package/packages/opencode/src/session/compaction.ts +428 -0
  193. package/packages/opencode/src/session/index.ts +887 -0
  194. package/packages/opencode/src/session/instruction.ts +258 -0
  195. package/packages/opencode/src/session/llm.ts +354 -0
  196. package/packages/opencode/src/session/message-v2.ts +1031 -0
  197. package/packages/opencode/src/session/message.ts +191 -0
  198. package/packages/opencode/src/session/overflow.ts +22 -0
  199. package/packages/opencode/src/session/processor.ts +523 -0
  200. package/packages/opencode/src/session/projectors.ts +135 -0
  201. package/packages/opencode/src/session/prompt/anthropic.txt +105 -0
  202. package/packages/opencode/src/session/prompt/beast.txt +147 -0
  203. package/packages/opencode/src/session/prompt/build-switch.txt +5 -0
  204. package/packages/opencode/src/session/prompt/codex.txt +79 -0
  205. package/packages/opencode/src/session/prompt/copilot-gpt-5.txt +143 -0
  206. package/packages/opencode/src/session/prompt/default.txt +105 -0
  207. package/packages/opencode/src/session/prompt/gemini.txt +155 -0
  208. package/packages/opencode/src/session/prompt/gpt.txt +107 -0
  209. package/packages/opencode/src/session/prompt/kimi.txt +95 -0
  210. package/packages/opencode/src/session/prompt/max-steps.txt +16 -0
  211. package/packages/opencode/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  212. package/packages/opencode/src/session/prompt/plan.txt +26 -0
  213. package/packages/opencode/src/session/prompt/trinity.txt +97 -0
  214. package/packages/opencode/src/session/prompt.ts +1911 -0
  215. package/packages/opencode/src/session/retry.ts +106 -0
  216. package/packages/opencode/src/session/revert.ts +176 -0
  217. package/packages/opencode/src/session/schema.ts +38 -0
  218. package/packages/opencode/src/session/session.sql.ts +103 -0
  219. package/packages/opencode/src/session/status.ts +102 -0
  220. package/packages/opencode/src/session/summary.ts +177 -0
  221. package/packages/opencode/src/session/system.ts +76 -0
  222. package/packages/opencode/src/session/todo.ts +95 -0
  223. package/packages/opencode/src/share/share-next.ts +369 -0
  224. package/packages/opencode/src/share/share.sql.ts +13 -0
  225. package/packages/opencode/src/shell/shell.ts +110 -0
  226. package/packages/opencode/src/skill/discovery.ts +116 -0
  227. package/packages/opencode/src/skill/index.ts +277 -0
  228. package/packages/opencode/src/snapshot/index.ts +726 -0
  229. package/packages/opencode/src/sql.d.ts +4 -0
  230. package/packages/opencode/src/storage/db.node.ts +8 -0
  231. package/packages/opencode/src/storage/db.ts +177 -0
  232. package/packages/opencode/src/storage/json-migration.ts +425 -0
  233. package/packages/opencode/src/storage/schema.sql.ts +10 -0
  234. package/packages/opencode/src/storage/schema.ts +5 -0
  235. package/packages/opencode/src/storage/storage.ts +353 -0
  236. package/packages/opencode/src/sync/README.md +179 -0
  237. package/packages/opencode/src/sync/event.sql.ts +16 -0
  238. package/packages/opencode/src/sync/index.ts +263 -0
  239. package/packages/opencode/src/sync/schema.ts +14 -0
  240. package/packages/opencode/src/tool/apply_patch.ts +281 -0
  241. package/packages/opencode/src/tool/apply_patch.txt +33 -0
  242. package/packages/opencode/src/tool/bash.ts +496 -0
  243. package/packages/opencode/src/tool/bash.txt +117 -0
  244. package/packages/opencode/src/tool/batch.ts +183 -0
  245. package/packages/opencode/src/tool/batch.txt +24 -0
  246. package/packages/opencode/src/tool/codesearch.ts +132 -0
  247. package/packages/opencode/src/tool/codesearch.txt +12 -0
  248. package/packages/opencode/src/tool/edit.ts +667 -0
  249. package/packages/opencode/src/tool/edit.txt +10 -0
  250. package/packages/opencode/src/tool/external-directory.ts +46 -0
  251. package/packages/opencode/src/tool/glob.ts +78 -0
  252. package/packages/opencode/src/tool/glob.txt +6 -0
  253. package/packages/opencode/src/tool/grep.ts +156 -0
  254. package/packages/opencode/src/tool/grep.txt +8 -0
  255. package/packages/opencode/src/tool/invalid.ts +17 -0
  256. package/packages/opencode/src/tool/ls.ts +121 -0
  257. package/packages/opencode/src/tool/ls.txt +1 -0
  258. package/packages/opencode/src/tool/lsp.ts +97 -0
  259. package/packages/opencode/src/tool/lsp.txt +19 -0
  260. package/packages/opencode/src/tool/multiedit.ts +46 -0
  261. package/packages/opencode/src/tool/multiedit.txt +41 -0
  262. package/packages/opencode/src/tool/plan-enter.txt +14 -0
  263. package/packages/opencode/src/tool/plan-exit.txt +13 -0
  264. package/packages/opencode/src/tool/plan.ts +131 -0
  265. package/packages/opencode/src/tool/question.ts +46 -0
  266. package/packages/opencode/src/tool/question.txt +10 -0
  267. package/packages/opencode/src/tool/read.ts +332 -0
  268. package/packages/opencode/src/tool/read.txt +14 -0
  269. package/packages/opencode/src/tool/registry.ts +265 -0
  270. package/packages/opencode/src/tool/schema.ts +17 -0
  271. package/packages/opencode/src/tool/skill.ts +105 -0
  272. package/packages/opencode/src/tool/task.ts +166 -0
  273. package/packages/opencode/src/tool/task.txt +60 -0
  274. package/packages/opencode/src/tool/todo.ts +48 -0
  275. package/packages/opencode/src/tool/todowrite.txt +167 -0
  276. package/packages/opencode/src/tool/tool.ts +112 -0
  277. package/packages/opencode/src/tool/truncate.ts +144 -0
  278. package/packages/opencode/src/tool/truncation-dir.ts +4 -0
  279. package/packages/opencode/src/tool/webfetch.ts +206 -0
  280. package/packages/opencode/src/tool/webfetch.txt +13 -0
  281. package/packages/opencode/src/tool/websearch.ts +150 -0
  282. package/packages/opencode/src/tool/websearch.txt +14 -0
  283. package/packages/opencode/src/tool/write.ts +84 -0
  284. package/packages/opencode/src/tool/write.txt +8 -0
  285. package/packages/opencode/src/util/abort.ts +35 -0
  286. package/packages/opencode/src/util/archive.ts +17 -0
  287. package/packages/opencode/src/util/color.ts +19 -0
  288. package/packages/opencode/src/util/context.ts +25 -0
  289. package/packages/opencode/src/util/data-url.ts +9 -0
  290. package/packages/opencode/src/util/defer.ts +12 -0
  291. package/packages/opencode/src/util/effect-http-client.ts +11 -0
  292. package/packages/opencode/src/util/effect-zod.ts +98 -0
  293. package/packages/opencode/src/util/error.ts +77 -0
  294. package/packages/opencode/src/util/filesystem.ts +245 -0
  295. package/packages/opencode/src/util/flock.ts +333 -0
  296. package/packages/opencode/src/util/fn.ts +21 -0
  297. package/packages/opencode/src/util/format.ts +20 -0
  298. package/packages/opencode/src/util/glob.ts +34 -0
  299. package/packages/opencode/src/util/hash.ts +7 -0
  300. package/packages/opencode/src/util/iife.ts +3 -0
  301. package/packages/opencode/src/util/keybind.ts +103 -0
  302. package/packages/opencode/src/util/lazy.ts +23 -0
  303. package/packages/opencode/src/util/locale.ts +81 -0
  304. package/packages/opencode/src/util/lock.ts +98 -0
  305. package/packages/opencode/src/util/log.ts +182 -0
  306. package/packages/opencode/src/util/network.ts +9 -0
  307. package/packages/opencode/src/util/process.ts +176 -0
  308. package/packages/opencode/src/util/queue.ts +32 -0
  309. package/packages/opencode/src/util/record.ts +3 -0
  310. package/packages/opencode/src/util/rpc.ts +66 -0
  311. package/packages/opencode/src/util/schema.ts +53 -0
  312. package/packages/opencode/src/util/scrap.ts +10 -0
  313. package/packages/opencode/src/util/signal.ts +12 -0
  314. package/packages/opencode/src/util/timeout.ts +14 -0
  315. package/packages/opencode/src/util/token.ts +7 -0
  316. package/packages/opencode/src/util/update-schema.ts +13 -0
  317. package/packages/opencode/src/util/which.ts +14 -0
  318. package/packages/opencode/src/util/wildcard.ts +59 -0
  319. package/packages/opencode/src/worktree/index.ts +612 -0
  320. package/packages/plugin/package.json +38 -0
  321. package/packages/plugin/src/example.ts +18 -0
  322. package/packages/plugin/src/index.ts +282 -0
  323. package/packages/plugin/src/shell.ts +136 -0
  324. package/packages/plugin/src/tool.ts +38 -0
  325. package/packages/plugin/src/tui.ts +508 -0
  326. package/packages/script/package.json +16 -0
  327. package/packages/script/src/index.ts +77 -0
  328. package/packages/sdk/package.json +33 -0
  329. package/packages/sdk/src/client.ts +55 -0
  330. package/packages/sdk/src/gen/client/client.gen.ts +212 -0
  331. package/packages/sdk/src/gen/client/index.ts +25 -0
  332. package/packages/sdk/src/gen/client/types.gen.ts +222 -0
  333. package/packages/sdk/src/gen/client/utils.gen.ts +287 -0
  334. package/packages/sdk/src/gen/client.gen.ts +22 -0
  335. package/packages/sdk/src/gen/core/auth.gen.ts +41 -0
  336. package/packages/sdk/src/gen/core/bodySerializer.gen.ts +74 -0
  337. package/packages/sdk/src/gen/core/params.gen.ts +144 -0
  338. package/packages/sdk/src/gen/core/pathSerializer.gen.ts +167 -0
  339. package/packages/sdk/src/gen/core/queryKeySerializer.gen.ts +111 -0
  340. package/packages/sdk/src/gen/core/serverSentEvents.gen.ts +210 -0
  341. package/packages/sdk/src/gen/core/types.gen.ts +91 -0
  342. package/packages/sdk/src/gen/core/utils.gen.ts +109 -0
  343. package/packages/sdk/src/gen/sdk.gen.ts +1197 -0
  344. package/packages/sdk/src/gen/types.gen.ts +3904 -0
  345. package/packages/sdk/src/index.ts +21 -0
  346. package/packages/sdk/src/process.ts +31 -0
  347. package/packages/sdk/src/server.ts +134 -0
  348. package/packages/sdk/src/v2/client.ts +81 -0
  349. package/packages/sdk/src/v2/gen/client/client.gen.ts +285 -0
  350. package/packages/sdk/src/v2/gen/client/index.ts +25 -0
  351. package/packages/sdk/src/v2/gen/client/types.gen.ts +202 -0
  352. package/packages/sdk/src/v2/gen/client/utils.gen.ts +289 -0
  353. package/packages/sdk/src/v2/gen/client.gen.ts +18 -0
  354. package/packages/sdk/src/v2/gen/core/auth.gen.ts +41 -0
  355. package/packages/sdk/src/v2/gen/core/bodySerializer.gen.ts +82 -0
  356. package/packages/sdk/src/v2/gen/core/params.gen.ts +169 -0
  357. package/packages/sdk/src/v2/gen/core/pathSerializer.gen.ts +167 -0
  358. package/packages/sdk/src/v2/gen/core/queryKeySerializer.gen.ts +111 -0
  359. package/packages/sdk/src/v2/gen/core/serverSentEvents.gen.ts +239 -0
  360. package/packages/sdk/src/v2/gen/core/types.gen.ts +86 -0
  361. package/packages/sdk/src/v2/gen/core/utils.gen.ts +137 -0
  362. package/packages/sdk/src/v2/gen/sdk.gen.ts +4223 -0
  363. package/packages/sdk/src/v2/gen/types.gen.ts +5265 -0
  364. package/packages/sdk/src/v2/index.ts +21 -0
  365. package/packages/sdk/src/v2/server.ts +134 -0
  366. package/packages/util/package.json +20 -0
  367. package/packages/util/src/array.ts +10 -0
  368. package/packages/util/src/binary.ts +41 -0
  369. package/packages/util/src/encode.ts +51 -0
  370. package/packages/util/src/error.ts +54 -0
  371. package/packages/util/src/fn.ts +11 -0
  372. package/packages/util/src/identifier.ts +48 -0
  373. package/packages/util/src/iife.ts +3 -0
  374. package/packages/util/src/lazy.ts +11 -0
  375. package/packages/util/src/module.ts +10 -0
  376. package/packages/util/src/path.ts +37 -0
  377. package/packages/util/src/retry.ts +41 -0
  378. package/packages/util/src/slug.ts +74 -0
  379. package/postinstall.cjs +55 -0
@@ -0,0 +1,726 @@
1
+ import { NodeFileSystem, NodePath } from "@effect/platform-node"
2
+ import { Cause, Duration, Effect, Layer, Schedule, Semaphore, ServiceMap, Stream } from "effect"
3
+ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
4
+ import path from "path"
5
+ import z from "zod"
6
+ import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
7
+ import { InstanceState } from "@/effect/instance-state"
8
+ import { makeRuntime } from "@/effect/run-service"
9
+ import { AppFileSystem } from "@/filesystem"
10
+ import { Hash } from "@/util/hash"
11
+ import { Config } from "../config/config"
12
+ import { Global } from "../global"
13
+ import { Log } from "../util/log"
14
+
15
+ export namespace Snapshot {
16
+ export const Patch = z.object({
17
+ hash: z.string(),
18
+ files: z.string().array(),
19
+ })
20
+ export type Patch = z.infer<typeof Patch>
21
+
22
+ export const FileDiff = z
23
+ .object({
24
+ file: z.string(),
25
+ before: z.string(),
26
+ after: z.string(),
27
+ additions: z.number(),
28
+ deletions: z.number(),
29
+ status: z.enum(["added", "deleted", "modified"]).optional(),
30
+ })
31
+ .meta({
32
+ ref: "FileDiff",
33
+ })
34
+ export type FileDiff = z.infer<typeof FileDiff>
35
+
36
+ const log = Log.create({ service: "snapshot" })
37
+ const prune = "7.days"
38
+ const limit = 2 * 1024 * 1024
39
+ const core = ["-c", "core.longpaths=true", "-c", "core.symlinks=true"]
40
+ const cfg = ["-c", "core.autocrlf=false", ...core]
41
+ const quote = [...cfg, "-c", "core.quotepath=false"]
42
+ interface GitResult {
43
+ readonly code: ChildProcessSpawner.ExitCode
44
+ readonly text: string
45
+ readonly stderr: string
46
+ }
47
+
48
+ type State = Omit<Interface, "init">
49
+
50
+ export interface Interface {
51
+ readonly init: () => Effect.Effect<void>
52
+ readonly cleanup: () => Effect.Effect<void>
53
+ readonly track: () => Effect.Effect<string | undefined>
54
+ readonly patch: (hash: string) => Effect.Effect<Snapshot.Patch>
55
+ readonly restore: (snapshot: string) => Effect.Effect<void>
56
+ readonly revert: (patches: Snapshot.Patch[]) => Effect.Effect<void>
57
+ readonly diff: (hash: string) => Effect.Effect<string>
58
+ readonly diffFull: (from: string, to: string) => Effect.Effect<Snapshot.FileDiff[]>
59
+ }
60
+
61
+ export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/Snapshot") {}
62
+
63
+ export const layer: Layer.Layer<
64
+ Service,
65
+ never,
66
+ AppFileSystem.Service | ChildProcessSpawner.ChildProcessSpawner | Config.Service
67
+ > = Layer.effect(
68
+ Service,
69
+ Effect.gen(function* () {
70
+ const fs = yield* AppFileSystem.Service
71
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
72
+ const config = yield* Config.Service
73
+ const locks = new Map<string, Semaphore.Semaphore>()
74
+
75
+ const lock = (key: string) => {
76
+ const hit = locks.get(key)
77
+ if (hit) return hit
78
+
79
+ const next = Semaphore.makeUnsafe(1)
80
+ locks.set(key, next)
81
+ return next
82
+ }
83
+
84
+ const state = yield* InstanceState.make<State>(
85
+ Effect.fn("Snapshot.state")(function* (ctx) {
86
+ const state = {
87
+ directory: ctx.directory,
88
+ worktree: ctx.worktree,
89
+ gitdir: path.join(Global.Path.data, "snapshot", ctx.project.id, Hash.fast(ctx.worktree)),
90
+ vcs: ctx.project.vcs,
91
+ }
92
+
93
+ const args = (cmd: string[]) => ["--git-dir", state.gitdir, "--work-tree", state.worktree, ...cmd]
94
+
95
+ const git = Effect.fnUntraced(
96
+ function* (cmd: string[], opts?: { cwd?: string; env?: Record<string, string> }) {
97
+ const proc = ChildProcess.make("git", cmd, {
98
+ cwd: opts?.cwd,
99
+ env: opts?.env,
100
+ extendEnv: true,
101
+ })
102
+ const handle = yield* spawner.spawn(proc)
103
+ const [text, stderr] = yield* Effect.all(
104
+ [Stream.mkString(Stream.decodeText(handle.stdout)), Stream.mkString(Stream.decodeText(handle.stderr))],
105
+ { concurrency: 2 },
106
+ )
107
+ const code = yield* handle.exitCode
108
+ return { code, text, stderr } satisfies GitResult
109
+ },
110
+ Effect.scoped,
111
+ Effect.catch((err) =>
112
+ Effect.succeed({
113
+ code: ChildProcessSpawner.ExitCode(1),
114
+ text: "",
115
+ stderr: String(err),
116
+ }),
117
+ ),
118
+ )
119
+
120
+ const exists = (file: string) => fs.exists(file).pipe(Effect.orDie)
121
+ const read = (file: string) => fs.readFileString(file).pipe(Effect.catch(() => Effect.succeed("")))
122
+ const remove = (file: string) => fs.remove(file).pipe(Effect.catch(() => Effect.void))
123
+ const locked = <A, E, R>(fx: Effect.Effect<A, E, R>) => lock(state.gitdir).withPermits(1)(fx)
124
+
125
+ const enabled = Effect.fnUntraced(function* () {
126
+ if (state.vcs !== "git") return false
127
+ return (yield* config.get()).snapshot !== false
128
+ })
129
+
130
+ const excludes = Effect.fnUntraced(function* () {
131
+ const result = yield* git(["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"], {
132
+ cwd: state.worktree,
133
+ })
134
+ const file = result.text.trim()
135
+ if (!file) return
136
+ if (!(yield* exists(file))) return
137
+ return file
138
+ })
139
+
140
+ const sync = Effect.fnUntraced(function* (list: string[] = []) {
141
+ const file = yield* excludes()
142
+ const target = path.join(state.gitdir, "info", "exclude")
143
+ const text = [
144
+ file ? (yield* read(file)).trimEnd() : "",
145
+ ...list.map((item) => `/${item.replaceAll("\\", "/")}`),
146
+ ]
147
+ .filter(Boolean)
148
+ .join("\n")
149
+ yield* fs.ensureDir(path.join(state.gitdir, "info")).pipe(Effect.orDie)
150
+ yield* fs.writeFileString(target, text ? `${text}\n` : "").pipe(Effect.orDie)
151
+ })
152
+
153
+ const add = Effect.fnUntraced(function* () {
154
+ yield* sync()
155
+ const [diff, other] = yield* Effect.all(
156
+ [
157
+ git([...quote, ...args(["diff-files", "--name-only", "-z", "--", "."])], {
158
+ cwd: state.directory,
159
+ }),
160
+ git([...quote, ...args(["ls-files", "--others", "--exclude-standard", "-z", "--", "."])], {
161
+ cwd: state.directory,
162
+ }),
163
+ ],
164
+ { concurrency: 2 },
165
+ )
166
+ if (diff.code !== 0 || other.code !== 0) {
167
+ log.warn("failed to list snapshot files", {
168
+ diffCode: diff.code,
169
+ diffStderr: diff.stderr,
170
+ otherCode: other.code,
171
+ otherStderr: other.stderr,
172
+ })
173
+ return
174
+ }
175
+
176
+ const tracked = diff.text.split("\0").filter(Boolean)
177
+ const untracked = other.text.split("\0").filter(Boolean)
178
+ const all = Array.from(new Set([...tracked, ...untracked]))
179
+ if (!all.length) return
180
+
181
+ const large = (yield* Effect.all(
182
+ all.map((item) =>
183
+ fs
184
+ .stat(path.join(state.directory, item))
185
+ .pipe(Effect.catch(() => Effect.void))
186
+ .pipe(
187
+ Effect.map((stat) => {
188
+ if (!stat || stat.type !== "File") return
189
+ const size = typeof stat.size === "bigint" ? Number(stat.size) : stat.size
190
+ return size > limit ? item : undefined
191
+ }),
192
+ ),
193
+ ),
194
+ { concurrency: 8 },
195
+ )).filter((item): item is string => Boolean(item))
196
+ yield* sync(large)
197
+ const result = yield* git([...cfg, ...args(["add", "--sparse", "."])], { cwd: state.directory })
198
+ if (result.code !== 0) {
199
+ log.warn("failed to add snapshot files", {
200
+ exitCode: result.code,
201
+ stderr: result.stderr,
202
+ })
203
+ }
204
+ })
205
+
206
+ const cleanup = Effect.fnUntraced(function* () {
207
+ return yield* locked(
208
+ Effect.gen(function* () {
209
+ if (!(yield* enabled())) return
210
+ if (!(yield* exists(state.gitdir))) return
211
+ const result = yield* git(args(["gc", `--prune=${prune}`]), { cwd: state.directory })
212
+ if (result.code !== 0) {
213
+ log.warn("cleanup failed", {
214
+ exitCode: result.code,
215
+ stderr: result.stderr,
216
+ })
217
+ return
218
+ }
219
+ log.info("cleanup", { prune })
220
+ }),
221
+ )
222
+ })
223
+
224
+ const track = Effect.fnUntraced(function* () {
225
+ return yield* locked(
226
+ Effect.gen(function* () {
227
+ if (!(yield* enabled())) return
228
+ const existed = yield* exists(state.gitdir)
229
+ yield* fs.ensureDir(state.gitdir).pipe(Effect.orDie)
230
+ if (!existed) {
231
+ yield* git(["init"], {
232
+ env: { GIT_DIR: state.gitdir, GIT_WORK_TREE: state.worktree },
233
+ })
234
+ yield* git(["--git-dir", state.gitdir, "config", "core.autocrlf", "false"])
235
+ yield* git(["--git-dir", state.gitdir, "config", "core.longpaths", "true"])
236
+ yield* git(["--git-dir", state.gitdir, "config", "core.symlinks", "true"])
237
+ yield* git(["--git-dir", state.gitdir, "config", "core.fsmonitor", "false"])
238
+ log.info("initialized")
239
+ }
240
+ yield* add()
241
+ const result = yield* git(args(["write-tree"]), { cwd: state.directory })
242
+ const hash = result.text.trim()
243
+ log.info("tracking", { hash, cwd: state.directory, git: state.gitdir })
244
+ return hash
245
+ }),
246
+ )
247
+ })
248
+
249
+ const patch = Effect.fnUntraced(function* (hash: string) {
250
+ return yield* locked(
251
+ Effect.gen(function* () {
252
+ yield* add()
253
+ const result = yield* git(
254
+ [...quote, ...args(["diff", "--cached", "--no-ext-diff", "--name-only", hash, "--", "."])],
255
+ {
256
+ cwd: state.directory,
257
+ },
258
+ )
259
+ if (result.code !== 0) {
260
+ log.warn("failed to get diff", { hash, exitCode: result.code })
261
+ return { hash, files: [] }
262
+ }
263
+ return {
264
+ hash,
265
+ files: result.text
266
+ .trim()
267
+ .split("\n")
268
+ .map((x) => x.trim())
269
+ .filter(Boolean)
270
+ .map((x) => path.join(state.worktree, x).replaceAll("\\", "/")),
271
+ }
272
+ }),
273
+ )
274
+ })
275
+
276
+ const restore = Effect.fnUntraced(function* (snapshot: string) {
277
+ return yield* locked(
278
+ Effect.gen(function* () {
279
+ log.info("restore", { commit: snapshot })
280
+ const result = yield* git([...core, ...args(["read-tree", snapshot])], { cwd: state.worktree })
281
+ if (result.code === 0) {
282
+ const checkout = yield* git([...core, ...args(["checkout-index", "-a", "-f"])], {
283
+ cwd: state.worktree,
284
+ })
285
+ if (checkout.code === 0) return
286
+ log.error("failed to restore snapshot", {
287
+ snapshot,
288
+ exitCode: checkout.code,
289
+ stderr: checkout.stderr,
290
+ })
291
+ return
292
+ }
293
+ log.error("failed to restore snapshot", {
294
+ snapshot,
295
+ exitCode: result.code,
296
+ stderr: result.stderr,
297
+ })
298
+ }),
299
+ )
300
+ })
301
+
302
+ const revert = Effect.fnUntraced(function* (patches: Snapshot.Patch[]) {
303
+ return yield* locked(
304
+ Effect.gen(function* () {
305
+ const ops: { hash: string; file: string; rel: string }[] = []
306
+ const seen = new Set<string>()
307
+ for (const item of patches) {
308
+ for (const file of item.files) {
309
+ if (seen.has(file)) continue
310
+ seen.add(file)
311
+ ops.push({
312
+ hash: item.hash,
313
+ file,
314
+ rel: path.relative(state.worktree, file).replaceAll("\\", "/"),
315
+ })
316
+ }
317
+ }
318
+
319
+ const single = Effect.fnUntraced(function* (op: (typeof ops)[number]) {
320
+ log.info("reverting", { file: op.file, hash: op.hash })
321
+ const result = yield* git([...core, ...args(["checkout", op.hash, "--", op.file])], {
322
+ cwd: state.worktree,
323
+ })
324
+ if (result.code === 0) return
325
+ const tree = yield* git([...core, ...args(["ls-tree", op.hash, "--", op.rel])], {
326
+ cwd: state.worktree,
327
+ })
328
+ if (tree.code === 0 && tree.text.trim()) {
329
+ log.info("file existed in snapshot but checkout failed, keeping", { file: op.file, hash: op.hash })
330
+ return
331
+ }
332
+ log.info("file did not exist in snapshot, deleting", { file: op.file, hash: op.hash })
333
+ yield* remove(op.file)
334
+ })
335
+
336
+ const clash = (a: string, b: string) => a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`)
337
+
338
+ for (let i = 0; i < ops.length; ) {
339
+ const first = ops[i]!
340
+ const run = [first]
341
+ let j = i + 1
342
+ // Only batch adjacent files when their paths cannot affect each other.
343
+ while (j < ops.length && run.length < 100) {
344
+ const next = ops[j]!
345
+ if (next.hash !== first.hash) break
346
+ if (run.some((item) => clash(item.rel, next.rel))) break
347
+ run.push(next)
348
+ j += 1
349
+ }
350
+
351
+ if (run.length === 1) {
352
+ yield* single(first)
353
+ i = j
354
+ continue
355
+ }
356
+
357
+ const tree = yield* git(
358
+ [...core, ...args(["ls-tree", "--name-only", first.hash, "--", ...run.map((item) => item.rel)])],
359
+ {
360
+ cwd: state.worktree,
361
+ },
362
+ )
363
+
364
+ if (tree.code !== 0) {
365
+ log.info("batched ls-tree failed, falling back to single-file revert", {
366
+ hash: first.hash,
367
+ files: run.length,
368
+ })
369
+ for (const op of run) {
370
+ yield* single(op)
371
+ }
372
+ i = j
373
+ continue
374
+ }
375
+
376
+ const have = new Set(
377
+ tree.text
378
+ .trim()
379
+ .split("\n")
380
+ .map((item) => item.trim())
381
+ .filter(Boolean),
382
+ )
383
+ const list = run.filter((item) => have.has(item.rel))
384
+ if (list.length) {
385
+ log.info("reverting", { hash: first.hash, files: list.length })
386
+ const result = yield* git(
387
+ [...core, ...args(["checkout", first.hash, "--", ...list.map((item) => item.file)])],
388
+ {
389
+ cwd: state.worktree,
390
+ },
391
+ )
392
+ if (result.code !== 0) {
393
+ log.info("batched checkout failed, falling back to single-file revert", {
394
+ hash: first.hash,
395
+ files: list.length,
396
+ })
397
+ for (const op of run) {
398
+ yield* single(op)
399
+ }
400
+ i = j
401
+ continue
402
+ }
403
+ }
404
+
405
+ for (const op of run) {
406
+ if (have.has(op.rel)) continue
407
+ log.info("file did not exist in snapshot, deleting", { file: op.file, hash: op.hash })
408
+ yield* remove(op.file)
409
+ }
410
+
411
+ i = j
412
+ }
413
+ }),
414
+ )
415
+ })
416
+
417
+ const diff = Effect.fnUntraced(function* (hash: string) {
418
+ return yield* locked(
419
+ Effect.gen(function* () {
420
+ yield* add()
421
+ const result = yield* git([...quote, ...args(["diff", "--cached", "--no-ext-diff", hash, "--", "."])], {
422
+ cwd: state.worktree,
423
+ })
424
+ if (result.code !== 0) {
425
+ log.warn("failed to get diff", {
426
+ hash,
427
+ exitCode: result.code,
428
+ stderr: result.stderr,
429
+ })
430
+ return ""
431
+ }
432
+ return result.text.trim()
433
+ }),
434
+ )
435
+ })
436
+
437
+ const diffFull = Effect.fnUntraced(function* (from: string, to: string) {
438
+ return yield* locked(
439
+ Effect.gen(function* () {
440
+ type Row = {
441
+ file: string
442
+ status: "added" | "deleted" | "modified"
443
+ binary: boolean
444
+ additions: number
445
+ deletions: number
446
+ }
447
+
448
+ type Ref = {
449
+ file: string
450
+ side: "before" | "after"
451
+ ref: string
452
+ }
453
+
454
+ const show = Effect.fnUntraced(function* (row: Row) {
455
+ if (row.binary) return ["", ""]
456
+ if (row.status === "added") {
457
+ return [
458
+ "",
459
+ yield* git([...cfg, ...args(["show", `${to}:${row.file}`])]).pipe(
460
+ Effect.map((item) => item.text),
461
+ ),
462
+ ]
463
+ }
464
+ if (row.status === "deleted") {
465
+ return [
466
+ yield* git([...cfg, ...args(["show", `${from}:${row.file}`])]).pipe(
467
+ Effect.map((item) => item.text),
468
+ ),
469
+ "",
470
+ ]
471
+ }
472
+ return yield* Effect.all(
473
+ [
474
+ git([...cfg, ...args(["show", `${from}:${row.file}`])]).pipe(Effect.map((item) => item.text)),
475
+ git([...cfg, ...args(["show", `${to}:${row.file}`])]).pipe(Effect.map((item) => item.text)),
476
+ ],
477
+ { concurrency: 2 },
478
+ )
479
+ })
480
+
481
+ const load = Effect.fnUntraced(
482
+ function* (rows: Row[]) {
483
+ const refs = rows.flatMap((row) => {
484
+ if (row.binary) return []
485
+ if (row.status === "added")
486
+ return [{ file: row.file, side: "after", ref: `${to}:${row.file}` } satisfies Ref]
487
+ if (row.status === "deleted") {
488
+ return [{ file: row.file, side: "before", ref: `${from}:${row.file}` } satisfies Ref]
489
+ }
490
+ return [
491
+ { file: row.file, side: "before", ref: `${from}:${row.file}` } satisfies Ref,
492
+ { file: row.file, side: "after", ref: `${to}:${row.file}` } satisfies Ref,
493
+ ]
494
+ })
495
+ if (!refs.length) return new Map<string, { before: string; after: string }>()
496
+
497
+ const proc = ChildProcess.make("git", [...cfg, ...args(["cat-file", "--batch"])], {
498
+ cwd: state.directory,
499
+ extendEnv: true,
500
+ stdin: Stream.make(new TextEncoder().encode(refs.map((item) => item.ref).join("\n") + "\n")),
501
+ })
502
+ const handle = yield* spawner.spawn(proc)
503
+ const [out, err] = yield* Effect.all(
504
+ [Stream.mkUint8Array(handle.stdout), Stream.mkString(Stream.decodeText(handle.stderr))],
505
+ { concurrency: 2 },
506
+ )
507
+ const code = yield* handle.exitCode
508
+ if (code !== 0) {
509
+ log.info("git cat-file --batch failed during snapshot diff, falling back to per-file git show", {
510
+ stderr: err,
511
+ refs: refs.length,
512
+ })
513
+ return
514
+ }
515
+
516
+ const fail = (msg: string, extra?: Record<string, string>) => {
517
+ log.info(msg, { ...extra, refs: refs.length })
518
+ return undefined
519
+ }
520
+
521
+ const map = new Map<string, { before: string; after: string }>()
522
+ const dec = new TextDecoder()
523
+ let i = 0
524
+ // Parse the default `git cat-file --batch` stream: one header line,
525
+ // then exactly `size` bytes of blob content, then a trailing newline.
526
+ for (const ref of refs) {
527
+ let end = i
528
+ while (end < out.length && out[end] !== 10) end += 1
529
+ if (end >= out.length) {
530
+ return fail(
531
+ "git cat-file --batch returned a truncated header during snapshot diff, falling back to per-file git show",
532
+ )
533
+ }
534
+
535
+ const head = dec.decode(out.slice(i, end))
536
+ i = end + 1
537
+ const hit = map.get(ref.file) ?? { before: "", after: "" }
538
+ if (head.endsWith(" missing")) {
539
+ map.set(ref.file, hit)
540
+ continue
541
+ }
542
+
543
+ const match = head.match(/^[0-9a-f]+ blob (\d+)$/)
544
+ if (!match) {
545
+ return fail(
546
+ "git cat-file --batch returned an unexpected header during snapshot diff, falling back to per-file git show",
547
+ { head },
548
+ )
549
+ }
550
+
551
+ const size = Number(match[1])
552
+ if (!Number.isInteger(size) || size < 0 || i + size >= out.length || out[i + size] !== 10) {
553
+ return fail(
554
+ "git cat-file --batch returned truncated content during snapshot diff, falling back to per-file git show",
555
+ { head },
556
+ )
557
+ }
558
+
559
+ const text = dec.decode(out.slice(i, i + size))
560
+ if (ref.side === "before") hit.before = text
561
+ if (ref.side === "after") hit.after = text
562
+ map.set(ref.file, hit)
563
+ i += size + 1
564
+ }
565
+
566
+ if (i !== out.length) {
567
+ return fail(
568
+ "git cat-file --batch returned trailing data during snapshot diff, falling back to per-file git show",
569
+ )
570
+ }
571
+
572
+ return map
573
+ },
574
+ Effect.scoped,
575
+ Effect.catch(() =>
576
+ Effect.succeed<Map<string, { before: string; after: string }> | undefined>(undefined),
577
+ ),
578
+ )
579
+
580
+ const result: Snapshot.FileDiff[] = []
581
+ const status = new Map<string, "added" | "deleted" | "modified">()
582
+
583
+ const statuses = yield* git(
584
+ [...quote, ...args(["diff", "--no-ext-diff", "--name-status", "--no-renames", from, to, "--", "."])],
585
+ { cwd: state.directory },
586
+ )
587
+
588
+ for (const line of statuses.text.trim().split("\n")) {
589
+ if (!line) continue
590
+ const [code, file] = line.split("\t")
591
+ if (!code || !file) continue
592
+ status.set(file, code.startsWith("A") ? "added" : code.startsWith("D") ? "deleted" : "modified")
593
+ }
594
+
595
+ const numstat = yield* git(
596
+ [...quote, ...args(["diff", "--no-ext-diff", "--no-renames", "--numstat", from, to, "--", "."])],
597
+ {
598
+ cwd: state.directory,
599
+ },
600
+ )
601
+
602
+ const rows = numstat.text
603
+ .trim()
604
+ .split("\n")
605
+ .filter(Boolean)
606
+ .flatMap((line) => {
607
+ const [adds, dels, file] = line.split("\t")
608
+ if (!file) return []
609
+ const binary = adds === "-" && dels === "-"
610
+ const additions = binary ? 0 : parseInt(adds)
611
+ const deletions = binary ? 0 : parseInt(dels)
612
+ return [
613
+ {
614
+ file,
615
+ status: status.get(file) ?? "modified",
616
+ binary,
617
+ additions: Number.isFinite(additions) ? additions : 0,
618
+ deletions: Number.isFinite(deletions) ? deletions : 0,
619
+ } satisfies Row,
620
+ ]
621
+ })
622
+ const step = 100
623
+
624
+ // Keep batches bounded so a large diff does not buffer every blob at once.
625
+ for (let i = 0; i < rows.length; i += step) {
626
+ const run = rows.slice(i, i + step)
627
+ const text = yield* load(run)
628
+
629
+ for (const row of run) {
630
+ const hit = text?.get(row.file) ?? { before: "", after: "" }
631
+ const [before, after] = row.binary ? ["", ""] : text ? [hit.before, hit.after] : yield* show(row)
632
+ result.push({
633
+ file: row.file,
634
+ before,
635
+ after,
636
+ additions: row.additions,
637
+ deletions: row.deletions,
638
+ status: row.status,
639
+ })
640
+ }
641
+ }
642
+
643
+ return result
644
+ }),
645
+ )
646
+ })
647
+
648
+ yield* cleanup().pipe(
649
+ Effect.catchCause((cause) => {
650
+ log.error("cleanup loop failed", { cause: Cause.pretty(cause) })
651
+ return Effect.void
652
+ }),
653
+ Effect.repeat(Schedule.spaced(Duration.hours(1))),
654
+ Effect.delay(Duration.minutes(1)),
655
+ Effect.forkScoped,
656
+ )
657
+
658
+ return { cleanup, track, patch, restore, revert, diff, diffFull }
659
+ }),
660
+ )
661
+
662
+ return Service.of({
663
+ init: Effect.fn("Snapshot.init")(function* () {
664
+ yield* InstanceState.get(state)
665
+ }),
666
+ cleanup: Effect.fn("Snapshot.cleanup")(function* () {
667
+ return yield* InstanceState.useEffect(state, (s) => s.cleanup())
668
+ }),
669
+ track: Effect.fn("Snapshot.track")(function* () {
670
+ return yield* InstanceState.useEffect(state, (s) => s.track())
671
+ }),
672
+ patch: Effect.fn("Snapshot.patch")(function* (hash: string) {
673
+ return yield* InstanceState.useEffect(state, (s) => s.patch(hash))
674
+ }),
675
+ restore: Effect.fn("Snapshot.restore")(function* (snapshot: string) {
676
+ return yield* InstanceState.useEffect(state, (s) => s.restore(snapshot))
677
+ }),
678
+ revert: Effect.fn("Snapshot.revert")(function* (patches: Snapshot.Patch[]) {
679
+ return yield* InstanceState.useEffect(state, (s) => s.revert(patches))
680
+ }),
681
+ diff: Effect.fn("Snapshot.diff")(function* (hash: string) {
682
+ return yield* InstanceState.useEffect(state, (s) => s.diff(hash))
683
+ }),
684
+ diffFull: Effect.fn("Snapshot.diffFull")(function* (from: string, to: string) {
685
+ return yield* InstanceState.useEffect(state, (s) => s.diffFull(from, to))
686
+ }),
687
+ })
688
+ }),
689
+ )
690
+
691
+ export const defaultLayer = layer.pipe(
692
+ Layer.provide(CrossSpawnSpawner.defaultLayer),
693
+ Layer.provide(AppFileSystem.defaultLayer),
694
+ Layer.provide(Config.defaultLayer),
695
+ )
696
+
697
+ const { runPromise } = makeRuntime(Service, defaultLayer)
698
+
699
+ export async function init() {
700
+ return runPromise((svc) => svc.init())
701
+ }
702
+
703
+ export async function track() {
704
+ return runPromise((svc) => svc.track())
705
+ }
706
+
707
+ export async function patch(hash: string) {
708
+ return runPromise((svc) => svc.patch(hash))
709
+ }
710
+
711
+ export async function restore(snapshot: string) {
712
+ return runPromise((svc) => svc.restore(snapshot))
713
+ }
714
+
715
+ export async function revert(patches: Patch[]) {
716
+ return runPromise((svc) => svc.revert(patches))
717
+ }
718
+
719
+ export async function diff(hash: string) {
720
+ return runPromise((svc) => svc.diff(hash))
721
+ }
722
+
723
+ export async function diffFull(from: string, to: string) {
724
+ return runPromise((svc) => svc.diffFull(from, to))
725
+ }
726
+ }