@playcraft/cli 0.1.23 → 0.1.24

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 (278) hide show
  1. package/README.md +3 -38
  2. package/dist/agent/local-backend.js +1 -1
  3. package/dist/cli-root-help.js +0 -1
  4. package/dist/commands/build.js +4 -9
  5. package/dist/commands/create.js +33 -26
  6. package/dist/commands/image.js +6 -2
  7. package/dist/commands/login.js +42 -84
  8. package/dist/commands/skills.js +0 -2
  9. package/dist/commands/tools-generation.js +4 -2
  10. package/dist/commands/tools.js +0 -2
  11. package/dist/config.js +4 -59
  12. package/dist/index.js +1 -6
  13. package/dist/remix/clone.js +0 -2
  14. package/dist/remix/init-template.js +0 -2
  15. package/dist/remix/pull.js +0 -2
  16. package/dist/remix/push.js +1 -21
  17. package/dist/utils/agent-api-client.js +29 -148
  18. package/dist/utils/playcraft-http-client.js +4 -6
  19. package/package.json +2 -8
  20. package/project-template/.claude/skills/playcraft-image-generation/SKILL.md +61 -23
  21. package/project-templates/phaser/.claude/skills/playcraft-image-generation/SKILL.md +61 -23
  22. package/project-templates/threejs/.claude/skills/playcraft-image-generation/SKILL.md +61 -23
  23. package/dist/auth/account-activation.js +0 -157
  24. package/dist/auth/messages.js +0 -30
  25. package/dist/commands/platform-skills.generated.js +0 -19
  26. package/dist/commands/tools-batch.js +0 -59
  27. package/dist/commands/workspace-runtime.js +0 -54
  28. package/dist/project-skills/commands.js +0 -72
  29. package/dist/project-skills/lifecycle.js +0 -28
  30. package/dist/project-skills/local-run.js +0 -112
  31. package/dist/project-skills/local-store.js +0 -149
  32. package/dist/project-skills/messages.js +0 -72
  33. package/dist/project-skills/reconcile.js +0 -62
  34. package/dist/project-skills/remote-cache.js +0 -51
  35. package/dist/project-skills/validation.js +0 -19
  36. package/dist/utils/environment-endpoints.js +0 -17
  37. package/dist/utils/tool-operation-journal.js +0 -124
  38. package/dist/workspace-runtime/codex/app-server.js +0 -574
  39. package/dist/workspace-runtime/codex/config-toml.js +0 -108
  40. package/dist/workspace-runtime/codex/jsonrpc-stdio.js +0 -123
  41. package/dist/workspace-runtime/codex/launcher-client.js +0 -163
  42. package/dist/workspace-runtime/codex/loopback.js +0 -143
  43. package/dist/workspace-runtime/codex/model-broker.js +0 -239
  44. package/dist/workspace-runtime/codex/native-adapter.js +0 -9
  45. package/dist/workspace-runtime/main.js +0 -10
  46. package/dist/workspace-runtime/persistence/journal.js +0 -355
  47. package/dist/workspace-runtime/persistence/sqlite-client.js +0 -61
  48. package/dist/workspace-runtime/persistence/sqlite-worker.js +0 -1015
  49. package/dist/workspace-runtime/previews/publish.js +0 -259
  50. package/dist/workspace-runtime/previews/single-file.js +0 -43
  51. package/dist/workspace-runtime/processes/managed-writes.js +0 -69
  52. package/dist/workspace-runtime/production/contracts.js +0 -17
  53. package/dist/workspace-runtime/production/controller.js +0 -207
  54. package/dist/workspace-runtime/production/dependencies.js +0 -60
  55. package/dist/workspace-runtime/production/native.js +0 -70
  56. package/dist/workspace-runtime/production/processes.js +0 -86
  57. package/dist/workspace-runtime/production/save-command.js +0 -20
  58. package/dist/workspace-runtime/production/stages.js +0 -175
  59. package/dist/workspace-runtime/production/storage.js +0 -32
  60. package/dist/workspace-runtime/serve.js +0 -199
  61. package/dist/workspace-runtime/server/auth.js +0 -21
  62. package/dist/workspace-runtime/server/connectivity.js +0 -201
  63. package/dist/workspace-runtime/server/desktop-host.js +0 -429
  64. package/dist/workspace-runtime/server/desktop-preview-config.js +0 -81
  65. package/dist/workspace-runtime/server/desktop-preview-service.js +0 -157
  66. package/dist/workspace-runtime/server/desktop-preview-static.js +0 -53
  67. package/dist/workspace-runtime/server/desktop-preview.js +0 -189
  68. package/dist/workspace-runtime/server/dispatch.js +0 -848
  69. package/dist/workspace-runtime/server/endpoints.js +0 -19
  70. package/dist/workspace-runtime/server/execution-group.js +0 -85
  71. package/dist/workspace-runtime/server/http.js +0 -919
  72. package/dist/workspace-runtime/server/lock.js +0 -53
  73. package/dist/workspace-runtime/server/rfb-watch-gate.js +0 -168
  74. package/dist/workspace-runtime/server/terminal-host.js +0 -294
  75. package/dist/workspace-runtime/server/types.js +0 -1
  76. package/dist/workspace-runtime/workspaces/attachments.js +0 -109
  77. package/dist/workspace-runtime/workspaces/batch-commit.js +0 -142
  78. package/dist/workspace-runtime/workspaces/cli-credentials.js +0 -111
  79. package/dist/workspace-runtime/workspaces/context-error.js +0 -2
  80. package/dist/workspace-runtime/workspaces/dependencies.js +0 -264
  81. package/dist/workspace-runtime/workspaces/developer-command.js +0 -64
  82. package/dist/workspace-runtime/workspaces/directories.js +0 -106
  83. package/dist/workspace-runtime/workspaces/directory-access.js +0 -20
  84. package/dist/workspace-runtime/workspaces/directory-maintenance.js +0 -111
  85. package/dist/workspace-runtime/workspaces/directory-stats.js +0 -49
  86. package/dist/workspace-runtime/workspaces/empty-template.js +0 -32
  87. package/dist/workspace-runtime/workspaces/files.js +0 -113
  88. package/dist/workspace-runtime/workspaces/git-credential-broker.js +0 -312
  89. package/dist/workspace-runtime/workspaces/git-credential-helper.js +0 -68
  90. package/dist/workspace-runtime/workspaces/git-direct-store.js +0 -155
  91. package/dist/workspace-runtime/workspaces/git.js +0 -471
  92. package/dist/workspace-runtime/workspaces/json5-edit.js +0 -170
  93. package/dist/workspace-runtime/workspaces/parameters.js +0 -272
  94. package/dist/workspace-runtime/workspaces/prepare.js +0 -263
  95. package/dist/workspace-runtime/workspaces/registry.js +0 -192
  96. package/dist/workspace-runtime/workspaces/revisions.js +0 -31
  97. package/dist/workspace-runtime/workspaces/skill-artifact-loader.js +0 -46
  98. package/dist/workspace-runtime/workspaces/skills.js +0 -179
  99. package/project-template-v2/.claude/agents/artist.md +0 -82
  100. package/project-template-v2/.claude/agents/developer.md +0 -153
  101. package/project-template-v2/.claude/agents/game-designer.md +0 -264
  102. package/project-template-v2/.claude/agents/refs/artist-art-style-catalog.md +0 -533
  103. package/project-template-v2/.claude/agents/refs/artist-color-audio-recipes.md +0 -153
  104. package/project-template-v2/.claude/agents/refs/artist-dimension-axis.md +0 -27
  105. package/project-template-v2/.claude/agents/refs/artist-master-composite-recipes.md +0 -208
  106. package/project-template-v2/.claude/agents/refs/atom-skill-library.md +0 -81
  107. package/project-template-v2/.claude/agents/refs/developer-impl-cookbook.md +0 -432
  108. package/project-template-v2/.claude/agents/refs/framework-5-component-filter.md +0 -252
  109. package/project-template-v2/.claude/agents/refs/framework-game-feel-juice.md +0 -266
  110. package/project-template-v2/.claude/agents/refs/framework-mda.md +0 -147
  111. package/project-template-v2/.claude/agents/refs/game-designer-gameplay-sufficiency.md +0 -123
  112. package/project-template-v2/.claude/agents/refs/ta-3d-flip-recipe.md +0 -88
  113. package/project-template-v2/.claude/agents/refs/ta-atlas-deliverable-standard.md +0 -67
  114. package/project-template-v2/.claude/agents/refs/ta-batch-pipeline-recipes.md +0 -120
  115. package/project-template-v2/.claude/agents/refs/ta-image-generation-detail.md +0 -300
  116. package/project-template-v2/.claude/agents/refs/ta-image-ops-reference.md +0 -495
  117. package/project-template-v2/.claude/agents/refs/ta-pipeline-cookbook.md +0 -1141
  118. package/project-template-v2/.claude/agents/refs/ta-tools-reference.md +0 -111
  119. package/project-template-v2/.claude/agents/refs/ta-vfx-preset-catalog.md +0 -365
  120. package/project-template-v2/.claude/agents/refs/threejs-cannon-pitfalls.md +0 -412
  121. package/project-template-v2/.claude/agents/reviewer.md +0 -75
  122. package/project-template-v2/.claude/agents/technical-artist.md +0 -86
  123. package/project-template-v2/.claude/hooks/snapshot-milestone.mjs +0 -243
  124. package/project-template-v2/.claude/hooks/user-prompt.mjs +0 -133
  125. package/project-template-v2/.claude/settings.json +0 -33
  126. package/project-template-v2/.claude/skills/brainstorming/SKILL.md +0 -161
  127. package/project-template-v2/.claude/skills/brainstorming/scripts/frame-template.html +0 -270
  128. package/project-template-v2/.claude/skills/brainstorming/scripts/helper.js +0 -177
  129. package/project-template-v2/.claude/skills/brainstorming/scripts/server.cjs +0 -354
  130. package/project-template-v2/.claude/skills/brainstorming/scripts/start-server.sh +0 -148
  131. package/project-template-v2/.claude/skills/brainstorming/scripts/stop-server.sh +0 -56
  132. package/project-template-v2/.claude/skills/brainstorming/scripts/wait-for-selection.sh +0 -62
  133. package/project-template-v2/.claude/skills/brainstorming/spec-document-reviewer-prompt.md +0 -49
  134. package/project-template-v2/.claude/skills/brainstorming/visual-companion.md +0 -309
  135. package/project-template-v2/.claude/skills/playcraft-ad-psychology/SKILL.md +0 -182
  136. package/project-template-v2/.claude/skills/playcraft-art-style-guide/SKILL.md +0 -123
  137. package/project-template-v2/.claude/skills/playcraft-asset-state-sheet/SKILL.md +0 -205
  138. package/project-template-v2/.claude/skills/playcraft-audio-generation/SKILL.md +0 -280
  139. package/project-template-v2/.claude/skills/playcraft-batch-pipeline/SKILL.md +0 -184
  140. package/project-template-v2/.claude/skills/playcraft-build-optimizer/SKILL.md +0 -306
  141. package/project-template-v2/.claude/skills/playcraft-image-generation/SKILL.md +0 -298
  142. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/build-sprite-sheet.template.mjs +0 -123
  143. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/compare-style.template.mjs +0 -254
  144. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-batch-sprite.template.mjs +0 -324
  145. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-batch.template.mjs +0 -97
  146. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-edit-variants.template.mjs +0 -118
  147. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/process-batch.template.mjs +0 -137
  148. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/prompt-cookbook.md +0 -397
  149. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/validate-sprite-sheet.template.mjs +0 -296
  150. package/project-template-v2/.claude/skills/playcraft-image-ops/SKILL.md +0 -122
  151. package/project-template-v2/.claude/skills/playcraft-image-processing/SKILL.md +0 -219
  152. package/project-template-v2/.claude/skills/playcraft-masking/SKILL.md +0 -373
  153. package/project-template-v2/.claude/skills/playcraft-playable-optimization/SKILL.md +0 -161
  154. package/project-template-v2/.claude/skills/playcraft-research/SKILL.md +0 -215
  155. package/project-template-v2/.claude/skills/playcraft-skill-recommender/SKILL.md +0 -382
  156. package/project-template-v2/.claude/skills/playcraft-sprite-generation/SKILL.md +0 -423
  157. package/project-template-v2/.claude/skills/playcraft-sprite-remix/SKILL.md +0 -158
  158. package/project-template-v2/.claude/skills/playcraft-sprite-sheet/SKILL.md +0 -100
  159. package/project-template-v2/.claude/skills/playcraft-storyboard/SKILL.md +0 -167
  160. package/project-template-v2/.claude/skills/playcraft-style-qa/SKILL.md +0 -270
  161. package/project-template-v2/.claude/skills/playcraft-text-rendering/SKILL.md +0 -236
  162. package/project-template-v2/.claude/skills/playcraft-vfx-animation/SKILL.md +0 -130
  163. package/project-template-v2/.claude/skills/playwright-cli/SKILL.md +0 -390
  164. package/project-template-v2/.claude/skills/playwright-cli/references/element-attributes.md +0 -23
  165. package/project-template-v2/.claude/skills/playwright-cli/references/playwright-tests.md +0 -39
  166. package/project-template-v2/.claude/skills/playwright-cli/references/request-mocking.md +0 -87
  167. package/project-template-v2/.claude/skills/playwright-cli/references/running-code.md +0 -240
  168. package/project-template-v2/.claude/skills/playwright-cli/references/session-management.md +0 -226
  169. package/project-template-v2/.claude/skills/playwright-cli/references/spec-driven-testing.md +0 -308
  170. package/project-template-v2/.claude/skills/playwright-cli/references/storage-state.md +0 -275
  171. package/project-template-v2/.claude/skills/playwright-cli/references/test-generation.md +0 -134
  172. package/project-template-v2/.claude/skills/playwright-cli/references/tracing.md +0 -142
  173. package/project-template-v2/.claude/skills/playwright-cli/references/video-recording.md +0 -153
  174. package/project-template-v2/.claude/skills/session-analyzer/SKILL.md +0 -386
  175. package/project-template-v2/.claude/skills/session-analyzer/scripts/execution-breakdown.mjs +0 -182
  176. package/project-template-v2/.claude/skills/session-analyzer/scripts/find-turns.mjs +0 -72
  177. package/project-template-v2/.claude/skills/session-analyzer/scripts/heavy-output.mjs +0 -121
  178. package/project-template-v2/.claude/skills/session-analyzer/scripts/resolve-session.mjs +0 -102
  179. package/project-template-v2/.claude/skills/session-analyzer/scripts/subagent-stats.mjs +0 -127
  180. package/project-template-v2/.claude/skills/session-analyzer/scripts/subagent-tool-timeline.mjs +0 -106
  181. package/project-template-v2/.claude/skills/session-analyzer/scripts/time-gaps.mjs +0 -128
  182. package/project-template-v2/.claude/skills/session-analyzer/scripts/turn-timeline.mjs +0 -67
  183. package/project-template-v2/.claude/snapshot.mjs +0 -263
  184. package/project-template-v2/.playcraft/skills.lock.json +0 -152
  185. package/project-template-v2/CLAUDE.md +0 -146
  186. package/project-template-v2/assets/audio/bgm/.gitkeep +0 -0
  187. package/project-template-v2/assets/audio/sfx/.gitkeep +0 -0
  188. package/project-template-v2/assets/bundles/.gitkeep +0 -0
  189. package/project-template-v2/assets/images/bg/.gitkeep +0 -0
  190. package/project-template-v2/assets/images/reference/.gitkeep +0 -0
  191. package/project-template-v2/assets/images/storyboard/.gitkeep +0 -0
  192. package/project-template-v2/assets/images/tiles/.gitkeep +0 -0
  193. package/project-template-v2/assets/images/ui/.gitkeep +0 -0
  194. package/project-template-v2/assets/images/vfx/.gitkeep +0 -0
  195. package/project-template-v2/assets/models/.gitkeep +0 -0
  196. package/project-template-v2/docs/harness/iteration-1/context-flow.md +0 -254
  197. package/project-template-v2/docs/harness/iteration-1/generate-flow.md +0 -91
  198. package/project-template-v2/docs/harness/iteration-1/ideate-flow.md +0 -214
  199. package/project-template-v2/docs/harness/iteration-1/optimize-flow.md +0 -75
  200. package/project-template-v2/docs/harness/iteration-1/wrapup-flow.md +0 -63
  201. package/project-template-v2/docs/harness/iteration-2/context-flow.md +0 -223
  202. package/project-template-v2/docs/harness/iteration-2/generate-flow.md +0 -129
  203. package/project-template-v2/docs/harness/iteration-2/ideate-flow.md +0 -267
  204. package/project-template-v2/docs/harness/iteration-2/optimize-flow.md +0 -164
  205. package/project-template-v2/docs/harness/iteration-2/wrapup-flow.md +0 -115
  206. package/project-template-v2/docs/harness/orchestrator-flow.md +0 -364
  207. package/project-template-v2/docs/project-state.json +0 -60
  208. package/project-template-v2/docs/project-state.md +0 -72
  209. package/project-template-v2/docs/standards/README.md +0 -225
  210. package/project-template-v2/docs/standards/agent-behavior-standards.md +0 -174
  211. package/project-template-v2/docs/standards/artifacts/design-brief.md +0 -19
  212. package/project-template-v2/docs/standards/artifacts/design.md +0 -22
  213. package/project-template-v2/docs/standards/artifacts/game-code.md +0 -41
  214. package/project-template-v2/docs/standards/artifacts/todo-list.md +0 -41
  215. package/project-template-v2/docs/standards/iter1-agent-behavior-standards.md +0 -343
  216. package/project-template-v2/game/index.ts +0 -18
  217. package/project-template-v2/globals.d.ts +0 -51
  218. package/project-template-v2/index.css +0 -34
  219. package/project-template-v2/index.html +0 -18
  220. package/project-template-v2/main.ts +0 -9
  221. package/project-template-v2/package.json +0 -46
  222. package/project-template-v2/skills/_shared/scripts/dispatch-clear.mjs +0 -31
  223. package/project-template-v2/skills/_shared/scripts/dispatch-set.mjs +0 -86
  224. package/project-template-v2/skills/_shared/scripts/dod-check.mjs +0 -153
  225. package/project-template-v2/skills/_shared/scripts/handoff-append.mjs +0 -70
  226. package/project-template-v2/skills/_shared/scripts/lib/validator-artifacts.mjs +0 -91
  227. package/project-template-v2/skills/_shared/scripts/pipeline/dod-config.mjs +0 -131
  228. package/project-template-v2/skills/_shared/scripts/pipeline/index.mjs +0 -80
  229. package/project-template-v2/skills/_shared/scripts/pipeline/iteration-1-core.mjs +0 -90
  230. package/project-template-v2/skills/_shared/scripts/pipeline/iteration-2-wrap.mjs +0 -93
  231. package/project-template-v2/skills/_shared/scripts/pipeline/iteration-3-visual.mjs +0 -23
  232. package/project-template-v2/skills/_shared/scripts/render-project-state.mjs +0 -230
  233. package/project-template-v2/skills/_shared/scripts/state-advance-stage.mjs +0 -58
  234. package/project-template-v2/skills/_shared/scripts/state-get.mjs +0 -339
  235. package/project-template-v2/skills/_shared/scripts/state-handoff.mjs +0 -39
  236. package/project-template-v2/skills/_shared/scripts/state-set.mjs +0 -94
  237. package/project-template-v2/skills/_shared/scripts/state-store.mjs +0 -783
  238. package/project-template-v2/skills/_shared/scripts/todo-add.mjs +0 -88
  239. package/project-template-v2/skills/_shared/scripts/todo-get.mjs +0 -130
  240. package/project-template-v2/skills/_shared/scripts/todo-remove.mjs +0 -33
  241. package/project-template-v2/skills/_shared/scripts/todo-set.mjs +0 -47
  242. package/project-template-v2/skills/_shared/scripts/verify-asset-code-sync.mjs +0 -268
  243. package/project-template-v2/skills/_shared/scripts/verify-env.mjs +0 -285
  244. package/project-template-v2/skills/_shared/scripts/verify-placeholders.mjs +0 -161
  245. package/project-template-v2/skills/playable-autoplay/SKILL.md +0 -176
  246. package/project-template-v2/skills/playable-autoplay/agents/openai.yaml +0 -4
  247. package/project-template-v2/skills/playable-debug/SKILL.md +0 -116
  248. package/project-template-v2/skills/playable-debug/agents/openai.yaml +0 -4
  249. package/project-template-v2/skills/playable-debug/references/debug-config.md +0 -40
  250. package/project-template-v2/skills/playable-record/SKILL.md +0 -140
  251. package/project-template-v2/skills/playable-record/scripts/lib/dev-server.mjs +0 -104
  252. package/project-template-v2/skills/playable-record/scripts/lib/record-audio-bridge.js +0 -141
  253. package/project-template-v2/skills/playable-record/scripts/record-playable.mjs +0 -425
  254. package/project-template-v2/skills/playable-record/scripts/verify-contract.mjs +0 -261
  255. package/project-template-v2/skills/playable-record/scripts/verify-firstwin.mjs +0 -398
  256. package/project-template-v2/skills/playable-record/scripts/verify-fusion.mjs +0 -322
  257. package/project-template-v2/skills/playable-record/scripts/verify-lifecycle.mjs +0 -105
  258. package/project-template-v2/skills/playable-record/scripts/verify-vlm-video.mjs +0 -230
  259. package/project-template-v2/skills/playable-validate/SKILL.md +0 -61
  260. package/project-template-v2/skills/playable-validate/validation-rules.md +0 -14
  261. package/project-template-v2/skills/playable-verify-ui/SKILL.md +0 -63
  262. package/project-template-v2/skills/playable-verify-ui/scripts/lib/__init__.py +0 -1
  263. package/project-template-v2/skills/playable-verify-ui/scripts/lib/config_expr.js +0 -218
  264. package/project-template-v2/skills/playable-verify-ui/scripts/lib/node_utils.js +0 -51
  265. package/project-template-v2/skills/playable-verify-ui/scripts/lib/profile_loader.py +0 -59
  266. package/project-template-v2/skills/playable-verify-ui/scripts/lib/report.py +0 -106
  267. package/project-template-v2/skills/playable-verify-ui/scripts/lib/runtime_contract.js +0 -116
  268. package/project-template-v2/skills/playable-verify-ui/scripts/verify_fetch_antipatterns.py +0 -59
  269. package/project-template-v2/skills/playable-verify-ui/scripts/verify_hardcoded_layout.js +0 -64
  270. package/project-template-v2/skills/playable-verify-ui/scripts/verify_runtime_contract.js +0 -58
  271. package/project-template-v2/skills/playable-verify-ui/scripts/verify_text_overlap.py +0 -333
  272. package/project-template-v2/ta-workspace/scripts/.gitkeep +0 -0
  273. package/project-template-v2/tsconfig.json +0 -20
  274. package/project-template-v2/vite.config.ts +0 -27
  275. package/project-templates/batch-locks/phaser.yaml +0 -922
  276. package/project-templates/batch-locks/threejs.yaml +0 -978
  277. package/project-templates/empty/AGENTS.md +0 -23
  278. package/project-templates/empty/gitignore +0 -31
@@ -1,1015 +0,0 @@
1
- /**
2
- * Dedicated SQLite writer for the CLI platform state file.
3
- * The main thread never opens runtime-state.sqlite.
4
- *
5
- * Binding pin: better-sqlite3@13.0.3 vendors SQLite 3.53.4, which includes the
6
- * official WAL-reset fix (3.51.3). Node's built-in node:sqlite on Node 22.22.1
7
- * reports 3.51.2 and must not be used for this file.
8
- * Do not read Codex JSONL from this worker.
9
- */
10
- import { randomBytes, randomUUID } from 'node:crypto';
11
- import { chmodSync, mkdirSync } from 'node:fs';
12
- import { dirname } from 'node:path';
13
- import { parentPort } from 'node:worker_threads';
14
- import Database from 'better-sqlite3-pinned';
15
- import { hashOperationPayload, operationRecordSchema, pendingSourceEventSchema, terminalRecordSchema, workspaceRegistrationSchema, transitionOperation, canTransitionTurn, } from '@playcraft/common/cloud-workspace/runtime';
16
- const SCHEMA_VERSION = 1;
17
- const MIN_SQLITE = [3, 51, 3];
18
- const BINDING = 'better-sqlite3@13.0.3';
19
- const MAX_PINS = 32;
20
- const MAX_PIN_MS = 120_000;
21
- let db;
22
- const port = parentPort;
23
- if (!port)
24
- throw new Error('sqlite_worker_without_parent');
25
- port.on('message', (message) => {
26
- try {
27
- const result = dispatch(message.type, message.payload ?? {});
28
- port.postMessage({ id: message.id, ok: true, result });
29
- }
30
- catch (error) {
31
- port.postMessage({
32
- id: message.id,
33
- ok: false,
34
- error: error instanceof Error ? error.message : 'sqlite_worker_failed',
35
- });
36
- }
37
- });
38
- function dispatch(type, payload) {
39
- if (type === 'open')
40
- return openDatabase(asRecord(payload));
41
- if (type === 'close') {
42
- db?.close();
43
- db = undefined;
44
- return { closed: true };
45
- }
46
- const database = requireDb();
47
- const body = asRecord(payload);
48
- const write = database.transaction(() => {
49
- switch (type) {
50
- case 'upsertRecord':
51
- upsertRecord(database, String(body.bucket), String(body.key), body.body);
52
- return;
53
- case 'deleteRecord':
54
- database.prepare('DELETE FROM records WHERE bucket = ? AND record_key = ?').run(body.bucket, body.key);
55
- return;
56
- case 'replaceBucket':
57
- replaceBucket(database, String(body.bucket), Array.isArray(body.entries) ? body.entries : []);
58
- return;
59
- case 'forgetWorkspaces':
60
- database.prepare(`DELETE FROM records WHERE bucket = 'workspaces'`).run();
61
- return;
62
- case 'putOperation':
63
- putOperation(database, String(body.scopeKey), body.operation);
64
- return;
65
- case 'setAcceptedFence':
66
- setMeta(database, 'accepted_lease_fence', String(Math.max(metaNumber(database, 'accepted_lease_fence'), Number(body.value) || 0)));
67
- return;
68
- case 'setDestroyed':
69
- setMeta(database, 'destroyed', '1');
70
- return;
71
- case 'noteExecutionGroup':
72
- setMeta(database, 'execution_group', JSON.stringify({ ...(executionGroup(database)), ...asRecord(body.group) }));
73
- return;
74
- case 'setStopConfirmed':
75
- setMeta(database, 'execution_group', JSON.stringify({ ...executionGroup(database), stopConfirmed: body.stopConfirmed === true }));
76
- return;
77
- case 'writeExecutionEpoch':
78
- writeExecutionEpoch(database, body);
79
- return;
80
- case 'bindRuntime':
81
- bindRuntime(database, body);
82
- return;
83
- case 'allocateEvent':
84
- return allocateEvent(database, body);
85
- case 'commitIdentity':
86
- commitIdentity(database, body.event);
87
- return;
88
- case 'ingest':
89
- return ingest(database, body);
90
- case 'bindTurn':
91
- return bindTurn(database, body);
92
- case 'ack':
93
- acknowledge(database, body);
94
- return;
95
- case 'createPin':
96
- return createPin(database, body);
97
- case 'deletePin':
98
- database.prepare('DELETE FROM replay_pins WHERE pin_id = ?').run(String(body.pinId));
99
- return { deleted: true };
100
- case 'reclaim':
101
- reclaim(database, Number(body.minRetainMs) || 0);
102
- return;
103
- case 'maintain':
104
- database.pragma('wal_checkpoint(PASSIVE)');
105
- return;
106
- default:
107
- throw new Error(`unknown_sqlite_command:${type}`);
108
- }
109
- });
110
- const extra = write();
111
- return { ...dump(database), ...(extra && typeof extra === 'object' ? extra : {}) };
112
- }
113
- function openDatabase(payload) {
114
- if (db)
115
- throw new Error('sqlite_already_open');
116
- const filePath = String(payload.filePath ?? '');
117
- if (!filePath)
118
- throw new Error('sqlite_path_missing');
119
- mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
120
- const database = new Database(filePath);
121
- db = database;
122
- const version = String(database.prepare('select sqlite_version() as v').get().v);
123
- if (!sqliteAtLeast(version, MIN_SQLITE)) {
124
- database.close();
125
- db = undefined;
126
- throw new Error(`sqlite_engine_too_old:${version}`);
127
- }
128
- const existing = readSchemaVersion(database);
129
- if (existing !== null && existing !== SCHEMA_VERSION) {
130
- database.close();
131
- db = undefined;
132
- throw new Error(`unsupported_runtime_state:${existing}`);
133
- }
134
- database.pragma('journal_mode = WAL');
135
- database.pragma('synchronous = FULL');
136
- database.pragma('wal_autocheckpoint = 0');
137
- database.pragma('busy_timeout = 2000');
138
- const journalMode = String(database.pragma('journal_mode', { simple: true }));
139
- const synchronous = Number(database.pragma('synchronous', { simple: true }));
140
- if (journalMode !== 'wal')
141
- throw new Error(`journal_mode_not_wal:${journalMode}`);
142
- if (synchronous !== 2)
143
- throw new Error(`synchronous_not_full:${synchronous}`);
144
- chmodSync(filePath, 0o600);
145
- let imported = false;
146
- if (existing === null) {
147
- createSchema(database);
148
- if (payload.legacy && typeof payload.legacy === 'object') {
149
- importLegacy(database, payload.legacy);
150
- imported = true;
151
- }
152
- quarantineReservedTurns(database);
153
- }
154
- else {
155
- quarantineReservedTurns(database);
156
- }
157
- return {
158
- ...dump(database),
159
- imported,
160
- engine: { version, journalMode, synchronous, binding: BINDING },
161
- };
162
- }
163
- function createSchema(database) {
164
- database.exec(`
165
- CREATE TABLE IF NOT EXISTS library_meta (
166
- key TEXT PRIMARY KEY,
167
- value TEXT NOT NULL
168
- );
169
- CREATE TABLE IF NOT EXISTS source_epochs (
170
- runtime_id TEXT NOT NULL,
171
- generation INTEGER NOT NULL,
172
- runtime_epoch INTEGER NOT NULL,
173
- next_sequence INTEGER NOT NULL,
174
- local_durable_through INTEGER NOT NULL,
175
- cloud_ack_through INTEGER NOT NULL,
176
- retained_from INTEGER NOT NULL,
177
- PRIMARY KEY (runtime_id, generation, runtime_epoch)
178
- );
179
- CREATE TABLE IF NOT EXISTS source_events (
180
- runtime_id TEXT NOT NULL,
181
- generation INTEGER NOT NULL,
182
- runtime_epoch INTEGER NOT NULL,
183
- source_sequence INTEGER NOT NULL,
184
- payload_hash TEXT NOT NULL,
185
- workspace_id TEXT,
186
- session_id TEXT,
187
- operation_id TEXT,
188
- thread_id TEXT,
189
- turn_id TEXT,
190
- item_id TEXT,
191
- type TEXT NOT NULL,
192
- payload_json TEXT NOT NULL,
193
- occurred_at TEXT NOT NULL,
194
- PRIMARY KEY (runtime_id, generation, runtime_epoch, source_sequence)
195
- );
196
- CREATE TABLE IF NOT EXISTS native_inbox (
197
- ingress_sequence INTEGER PRIMARY KEY,
198
- runtime_epoch INTEGER NOT NULL,
199
- kind TEXT NOT NULL,
200
- method TEXT,
201
- thread_id TEXT,
202
- turn_id TEXT,
203
- item_id TEXT,
204
- payload_json TEXT NOT NULL,
205
- converted INTEGER NOT NULL DEFAULT 0,
206
- source_sequence INTEGER,
207
- received_at TEXT NOT NULL
208
- );
209
- CREATE TABLE IF NOT EXISTS operation_intents (
210
- scope_key TEXT PRIMARY KEY,
211
- operation_json TEXT NOT NULL,
212
- gateway_operation_id TEXT,
213
- sandbox_operation_id TEXT NOT NULL,
214
- payload_hash TEXT NOT NULL,
215
- native_request_id TEXT,
216
- thread_id TEXT,
217
- turn_id TEXT,
218
- reconcile_status TEXT NOT NULL
219
- );
220
- CREATE TABLE IF NOT EXISTS replay_pins (
221
- pin_id TEXT PRIMARY KEY,
222
- epochs_json TEXT NOT NULL,
223
- created_at TEXT NOT NULL,
224
- expires_at TEXT NOT NULL
225
- );
226
- CREATE TABLE IF NOT EXISTS records (
227
- bucket TEXT NOT NULL,
228
- record_key TEXT NOT NULL,
229
- body_json TEXT NOT NULL,
230
- PRIMARY KEY (bucket, record_key)
231
- );
232
- `);
233
- setMeta(database, 'schema_version', String(SCHEMA_VERSION));
234
- setMeta(database, 'migration_status', 'complete');
235
- setMeta(database, 'source_read_token', randomBytes(32).toString('base64url'));
236
- setMeta(database, 'accepted_lease_fence', '0');
237
- setMeta(database, 'destroyed', '0');
238
- setMeta(database, 'runtime_epoch', '0');
239
- setMeta(database, 'ingress_counter', '0');
240
- setMeta(database, 'execution_group', JSON.stringify({ stopConfirmed: false, replaced: false }));
241
- }
242
- function readSchemaVersion(database) {
243
- const table = database
244
- .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'library_meta'`)
245
- .get();
246
- if (!table)
247
- return null;
248
- const row = database.prepare(`SELECT value FROM library_meta WHERE key = 'schema_version'`).get();
249
- if (!row?.value)
250
- return null;
251
- const parsed = Number(row.value);
252
- return Number.isInteger(parsed) ? parsed : null;
253
- }
254
- function importLegacy(database, legacy) {
255
- const snapshot = asRecord(legacy);
256
- const operations = asRecord(snapshot.operations);
257
- for (const [scopeKey, value] of Object.entries(operations)) {
258
- const parsed = operationRecordSchema.safeParse(value);
259
- if (!parsed.success)
260
- continue;
261
- putOperation(database, scopeKey, parsed.data);
262
- }
263
- const events = asRecord(snapshot.events);
264
- const sequences = [];
265
- for (const value of Object.values(events)) {
266
- const parsed = pendingSourceEventSchema.safeParse(value);
267
- if (!parsed.success)
268
- continue;
269
- const hash = hashOperationPayload(parsed.data.payload);
270
- if (hash !== parsed.data.payloadHash)
271
- continue;
272
- insertEventRow(database, parsed.data, {});
273
- sequences.push(parsed.data.source.sourceSequence);
274
- }
275
- const declared = Number(snapshot.lastSourceSequence) || 0;
276
- const maxImported = sequences.reduce((max, value) => Math.max(max, value), 0);
277
- const counter = Math.max(declared, maxImported, 0);
278
- const runtimeId = firstString(snapshot, 'runtimeId') || eventRuntime(events, 'runtimeId');
279
- const generation = Number.isInteger(snapshot.generation) ? Number(snapshot.generation) : eventRuntimeNumber(events, 'generation');
280
- const runtimeEpoch = Number.isInteger(snapshot.runtimeEpoch)
281
- ? Number(snapshot.runtimeEpoch)
282
- : eventRuntimeNumber(events, 'runtimeEpoch');
283
- if (runtimeId) {
284
- ensureEpoch(database, runtimeId, generation, runtimeEpoch);
285
- database
286
- .prepare(`UPDATE source_epochs SET next_sequence = ?, local_durable_through = ?
287
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ?`)
288
- .run(counter, counter, runtimeId, generation, runtimeEpoch);
289
- setMeta(database, 'runtime_id', runtimeId);
290
- setMeta(database, 'generation', String(generation));
291
- }
292
- importBucket(database, 'workspaces', asRecord(snapshot.workspaces), (value) => workspaceRegistrationSchema.safeParse(value).success);
293
- importBucket(database, 'sessions', asRecord(snapshot.sessions), (value) => {
294
- const session = asRecord(value);
295
- return typeof session.sessionId === 'string' && typeof session.threadId === 'string';
296
- });
297
- importBucket(database, 'terminals', asRecord(snapshot.terminals), (value) => terminalRecordSchema.safeParse(value).success);
298
- importBucket(database, 'approvals', asRecord(snapshot.approvals), (value) => isApproval(value));
299
- importBucket(database, 'managed_writes', asRecord(snapshot.managedWrites), () => true);
300
- importBucket(database, 'file_revisions', asRecord(snapshot.fileRevisions), () => true);
301
- importBucket(database, 'receipts', asRecord(snapshot.receipts), () => true);
302
- const workspaceFiles = asRecord(snapshot.workspaceFileRevisions);
303
- for (const [workspaceId, files] of Object.entries(workspaceFiles)) {
304
- importBucket(database, `workspace_files:${workspaceId}`, asRecord(files), () => true);
305
- }
306
- setMeta(database, 'accepted_lease_fence', String(Number(snapshot.acceptedLeaseFence) || 0));
307
- setMeta(database, 'destroyed', snapshot.destroyed === true ? '1' : '0');
308
- setMeta(database, 'runtime_epoch', String(runtimeEpoch));
309
- if (snapshot.executionGroup && typeof snapshot.executionGroup === 'object') {
310
- setMeta(database, 'execution_group', JSON.stringify(snapshot.executionGroup));
311
- }
312
- setMeta(database, 'migration_status', 'complete');
313
- }
314
- function quarantineReservedTurns(database) {
315
- const rows = database.prepare('SELECT scope_key, operation_json FROM operation_intents').all();
316
- for (const row of rows) {
317
- const parsed = operationRecordSchema.safeParse(JSON.parse(row.operation_json));
318
- if (!parsed.success)
319
- continue;
320
- const operation = parsed.data;
321
- if (operation.kind !== 'session.turn' || operation.status !== 'dispatched')
322
- continue;
323
- if (!operation.nativeRequestId || operation.nativeTurnId)
324
- continue;
325
- const uncertain = transitionOperation(operation, 'uncertain', { error: 'native_receipt_lost' });
326
- putOperation(database, row.scope_key, uncertain);
327
- if (operation.sessionId) {
328
- const session = readSession(database, operation.sessionId);
329
- if (session) {
330
- upsertRecord(database, 'sessions', operation.sessionId, { ...session, turnBlock: 'uncertain', turnStatus: 'starting' });
331
- }
332
- }
333
- }
334
- }
335
- function allocateEvent(database, body) {
336
- const runtimeId = String(body.runtimeId);
337
- const generation = Number(body.generation);
338
- const runtimeEpoch = Number(body.runtimeEpoch);
339
- ensureEpoch(database, runtimeId, generation, runtimeEpoch);
340
- const allocated = database
341
- .prepare(`UPDATE source_epochs
342
- SET next_sequence = next_sequence + 1,
343
- local_durable_through = next_sequence + 1
344
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ?
345
- RETURNING next_sequence`)
346
- .get(runtimeId, generation, runtimeEpoch);
347
- const payload = body.payload ?? {};
348
- const event = pendingSourceEventSchema.parse({
349
- source: { runtimeId, generation, runtimeEpoch, sourceSequence: allocated.next_sequence },
350
- payloadHash: hashOperationPayload(payload),
351
- type: String(body.type),
352
- payload,
353
- occurredAt: String(body.occurredAt),
354
- });
355
- insertEventRow(database, event, {
356
- workspaceId: optionalString(body.workspaceId),
357
- sessionId: optionalString(body.sessionId),
358
- operationId: optionalString(body.operationId),
359
- threadId: optionalString(body.threadId),
360
- turnId: optionalString(body.turnId),
361
- itemId: optionalString(body.itemId),
362
- });
363
- return { committedEvents: [event] };
364
- }
365
- function commitIdentity(database, value) {
366
- const event = pendingSourceEventSchema.parse(value);
367
- const existing = database
368
- .prepare(`SELECT payload_hash, payload_json, type, occurred_at FROM source_events
369
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ? AND source_sequence = ?`)
370
- .get(event.source.runtimeId, event.source.generation, event.source.runtimeEpoch, event.source.sourceSequence);
371
- if (existing) {
372
- if (existing.payload_hash !== event.payloadHash)
373
- throw new Error('source_payload_mismatch');
374
- return { committedEvents: [] };
375
- }
376
- ensureEpoch(database, event.source.runtimeId, event.source.generation, event.source.runtimeEpoch);
377
- insertEventRow(database, event, {});
378
- database
379
- .prepare(`UPDATE source_epochs
380
- SET next_sequence = CASE WHEN next_sequence < ? THEN ? ELSE next_sequence END,
381
- local_durable_through = CASE WHEN local_durable_through < ? THEN ? ELSE local_durable_through END
382
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ?`)
383
- .run(event.source.sourceSequence, event.source.sourceSequence, event.source.sourceSequence, event.source.sourceSequence, event.source.runtimeId, event.source.generation, event.source.runtimeEpoch);
384
- return { committedEvents: [event] };
385
- }
386
- function ingest(database, body) {
387
- const native = nativeIds(body.params);
388
- const threadId = optionalString(body.threadId) || native.threadId;
389
- const turnId = optionalString(body.turnId) || native.turnId;
390
- const itemId = optionalString(body.itemId) || native.itemId;
391
- const ingress = nextIngress(database);
392
- const kind = String(body.kind);
393
- const method = optionalString(body.method);
394
- const session = threadId ? sessionByThread(database, threadId) : undefined;
395
- const hintedTurn = turnId || nativeIds(body.params).turnId;
396
- const operation = hintedTurn ? operationByTurn(database, hintedTurn) : undefined;
397
- const linked = canConvert(kind, threadId, hintedTurn, session, operation);
398
- database
399
- .prepare(`INSERT INTO native_inbox (
400
- ingress_sequence, runtime_epoch, kind, method, thread_id, turn_id, item_id, payload_json, converted, received_at
401
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?)`)
402
- .run(ingress, Number(body.runtimeEpoch) || 0, kind, method ?? null, threadId ?? null, hintedTurn ?? null, itemId ?? null, JSON.stringify(body.params ?? {}), String(body.occurredAt));
403
- if (!linked)
404
- return { committedEvents: [] };
405
- const earlier = operation
406
- ? releaseInbox(database, threadId ?? '', hintedTurn ?? '', { scopeKey: operation.scopeKey, operation: operation.operation }, ingress)
407
- : [];
408
- const event = convertInboxRow(database, ingress, {
409
- runtimeId: String(body.runtimeId),
410
- generation: Number(body.generation) || 0,
411
- runtimeEpoch: Number(body.runtimeEpoch) || 0,
412
- kind,
413
- method,
414
- threadId,
415
- turnId: hintedTurn,
416
- itemId,
417
- occurredAt: String(body.occurredAt),
418
- session,
419
- operation,
420
- });
421
- return { committedEvents: event ? [...earlier, event] : earlier };
422
- }
423
- function bindTurn(database, body) {
424
- const operation = operationRecordSchema.parse(body.operation);
425
- putOperation(database, String(body.scopeKey), operation);
426
- const sessionId = String(body.sessionId);
427
- const session = readSession(database, sessionId);
428
- if (session) {
429
- upsertRecord(database, 'sessions', sessionId, {
430
- ...session,
431
- turnStatus: 'running',
432
- turnBlock: undefined,
433
- activeTurnId: String(body.turnId),
434
- threadId: String(body.threadId),
435
- recoveryContextPending: undefined,
436
- });
437
- }
438
- const threadId = String(body.threadId);
439
- const turnId = String(body.turnId);
440
- const released = releaseInbox(database, threadId, turnId, { scopeKey: String(body.scopeKey), operation });
441
- applyRecordedTurn(database, threadId, turnId);
442
- return { committedEvents: released };
443
- }
444
- function releaseInbox(database, threadId, turnId, bound, beforeIngress) {
445
- const rows = database
446
- .prepare(`SELECT ingress_sequence FROM native_inbox
447
- WHERE converted = 0
448
- AND (? IS NULL OR ingress_sequence < ?)
449
- AND (turn_id = ? OR (thread_id = ? AND turn_id IS NULL))
450
- ORDER BY ingress_sequence`)
451
- .all(beforeIngress ?? null, beforeIngress ?? null, turnId, threadId);
452
- const events = [];
453
- for (const row of rows) {
454
- const stored = database.prepare('SELECT * FROM native_inbox WHERE ingress_sequence = ?').get(row.ingress_sequence);
455
- if (stored.turn_id && stored.turn_id !== turnId)
456
- continue;
457
- const session = sessionByThread(database, threadId);
458
- const operation = operationByTurn(database, turnId) ?? bound;
459
- const event = convertInboxRow(database, row.ingress_sequence, {
460
- runtimeId: metaString(database, 'runtime_id') || 'runtime',
461
- generation: metaNumber(database, 'generation'),
462
- runtimeEpoch: Number(stored.runtime_epoch) || metaNumber(database, 'runtime_epoch'),
463
- kind: String(stored.kind),
464
- method: optionalString(stored.method),
465
- threadId,
466
- turnId: optionalString(stored.turn_id) || turnId,
467
- itemId: optionalString(stored.item_id),
468
- occurredAt: String(stored.received_at),
469
- session,
470
- operation,
471
- params: JSON.parse(String(stored.payload_json || '{}')),
472
- });
473
- if (event)
474
- events.push(event);
475
- }
476
- return events;
477
- }
478
- function convertInboxRow(database, ingress, input) {
479
- const row = database.prepare('SELECT payload_json, converted FROM native_inbox WHERE ingress_sequence = ?').get(ingress);
480
- if (!row || row.converted)
481
- return undefined;
482
- const params = input.params ?? JSON.parse(row.payload_json || '{}');
483
- const payload = linkedPayload(params, input.session);
484
- const type = input.kind === 'process_exit' ? 'process.exited' : input.method || input.kind;
485
- const allocated = allocateEvent(database, {
486
- runtimeId: input.runtimeId || metaString(database, 'runtime_id'),
487
- generation: input.generation,
488
- runtimeEpoch: input.runtimeEpoch,
489
- type,
490
- payload,
491
- occurredAt: input.occurredAt,
492
- workspaceId: optionalString(input.session?.workspaceId),
493
- sessionId: optionalString(input.session?.sessionId),
494
- operationId: input.operation?.operation.operationId,
495
- threadId: input.threadId,
496
- turnId: input.turnId,
497
- itemId: input.itemId,
498
- });
499
- const event = allocated.committedEvents[0];
500
- if (!event)
501
- return undefined;
502
- database
503
- .prepare(`UPDATE native_inbox
504
- SET converted = 1, source_sequence = ?, payload_json = '{}'
505
- WHERE ingress_sequence = ?`)
506
- .run(event.source.sourceSequence, ingress);
507
- applyNativeToState(database, { ...input, operation: resolveOperation(database, input, payload) }, payload);
508
- return event;
509
- }
510
- function applyRecordedTurn(database, threadId, turnId) {
511
- const rows = database
512
- .prepare(`SELECT type, payload_json, thread_id, session_id FROM source_events
513
- WHERE turn_id = ? OR payload_json LIKE ?
514
- ORDER BY source_sequence`)
515
- .all(turnId, `%"${turnId}"%`);
516
- for (const row of rows) {
517
- if (!row.type.includes('requestApproval') && !row.type.includes('requestUserInput') && !row.type.includes('completed') && !row.type.includes('interrupted') && row.type !== 'turn.failed' && row.type !== 'approval.resolved') {
518
- continue;
519
- }
520
- const payload = asRecord(JSON.parse(row.payload_json));
521
- const session = sessionByThread(database, threadId) ?? (row.session_id ? readSession(database, row.session_id) : undefined);
522
- applyNativeToState(database, {
523
- method: row.type,
524
- kind: 'notification',
525
- threadId: optionalString(row.thread_id) || threadId,
526
- turnId,
527
- session,
528
- operation: operationByTurn(database, turnId),
529
- }, payload);
530
- }
531
- }
532
- function resolveOperation(database, input, payload) {
533
- const turnId = input.turnId || nativeIds(payload).turnId;
534
- if (turnId)
535
- return operationByTurn(database, turnId) ?? input.operation;
536
- return input.operation;
537
- }
538
- function applyNativeToState(database, input, payload) {
539
- const method = input.method ?? '';
540
- const session = input.session;
541
- if (session?.sessionId) {
542
- const next = { ...session };
543
- const approval = method.includes('requestApproval') || method.includes('requestUserInput');
544
- if (approval)
545
- next.turnStatus = moveTurn(String(session.turnStatus ?? 'running'), 'waiting_for_user');
546
- else if (method === 'approval.resolved')
547
- next.turnStatus = moveTurn(String(session.turnStatus ?? 'waiting_for_user'), 'running');
548
- else if (method.includes('delta') || method === 'turn/started' || method === 'turn.started') {
549
- const current = String(session.turnStatus ?? 'starting');
550
- if (current !== 'waiting_for_user')
551
- next.turnStatus = moveTurn(current, 'running');
552
- }
553
- const terminal = terminalTurn(method, payload);
554
- if (terminal) {
555
- let status = String(next.turnStatus ?? session.turnStatus ?? 'running');
556
- if (status === 'waiting_for_user')
557
- status = moveTurn(status, 'running');
558
- next.turnStatus = moveTurn(status, terminal);
559
- next.turnBlock = undefined;
560
- }
561
- upsertRecord(database, 'sessions', String(session.sessionId), next);
562
- }
563
- if (!input.operation)
564
- return;
565
- let operation = input.operation.operation;
566
- const approvalId = optionalString(payload.itemId) || optionalString(payload.approvalId) || input.itemId;
567
- if ((method.includes('requestApproval') || method.includes('requestUserInput')) && approvalId && operation.sessionId) {
568
- upsertRecord(database, 'approvals', `${operation.sessionId}:${approvalId}`, {
569
- approvalId,
570
- sessionId: operation.sessionId,
571
- runtimeEpoch: operation.runtimeEpoch ?? 0,
572
- nativeRequestId: operation.nativeRequestId ?? `approval:${approvalId}`,
573
- status: 'pending',
574
- });
575
- operation = operationRecordSchema.parse({
576
- ...operation,
577
- nativeApprovalId: approvalId,
578
- updatedAt: new Date().toISOString(),
579
- });
580
- putOperation(database, input.operation.scopeKey, operation);
581
- }
582
- const terminal = terminalTurn(method, payload);
583
- if (terminal && operation.status === 'accepted') {
584
- putOperation(database, input.operation.scopeKey, transitionOperation(operation, terminal, {
585
- nativeTurnId: input.turnId ?? operation.nativeTurnId,
586
- nativeThreadId: input.threadId ?? operation.nativeThreadId,
587
- }));
588
- }
589
- }
590
- function acknowledge(database, body) {
591
- const leaseFence = Number(body.leaseFence);
592
- const accepted = metaNumber(database, 'accepted_lease_fence');
593
- if (!Number.isInteger(leaseFence) || leaseFence !== accepted)
594
- throw new Error('lease_fence_mismatch');
595
- const epochs = Array.isArray(body.epochs) ? body.epochs : [];
596
- for (const value of epochs) {
597
- const epoch = asRecord(value);
598
- const row = epochRow(database, String(epoch.runtimeId), Number(epoch.generation), Number(epoch.runtimeEpoch));
599
- if (!row)
600
- throw new Error('unknown_source_epoch');
601
- const next = Number(epoch.confirmedThrough);
602
- if (!Number.isInteger(next) || next < row.cloud_ack_through)
603
- throw new Error('ack_not_monotonic');
604
- if (next > row.local_durable_through)
605
- throw new Error('ack_ahead_of_local');
606
- database
607
- .prepare(`UPDATE source_epochs SET cloud_ack_through = ?
608
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ?`)
609
- .run(next, epoch.runtimeId, epoch.generation, epoch.runtimeEpoch);
610
- }
611
- }
612
- function createPin(database, body) {
613
- const now = Date.now();
614
- database.prepare('DELETE FROM replay_pins WHERE expires_at <= ?').run(new Date(now).toISOString());
615
- const count = database.prepare('SELECT count(*) AS n FROM replay_pins').get().n;
616
- if (count >= MAX_PINS)
617
- throw new Error('pin_quota');
618
- const ttl = Math.min(Number(body.ttlMs) || 60_000, MAX_PIN_MS);
619
- const identity = asRecord(body.identity);
620
- ensureEpoch(database, String(identity.runtimeId), Number(identity.generation), Number(identity.runtimeEpoch));
621
- const epochs = database.prepare('SELECT * FROM source_epochs').all().map((row) => ({
622
- runtimeId: row.runtime_id,
623
- generation: row.generation,
624
- runtimeEpoch: row.runtime_epoch,
625
- retainedFrom: row.retained_from,
626
- highWater: row.local_durable_through,
627
- }));
628
- const current = epochs.find((epoch) => epoch.runtimeId === identity.runtimeId &&
629
- epoch.generation === Number(identity.generation) &&
630
- epoch.runtimeEpoch === Number(identity.runtimeEpoch));
631
- const pinId = `pin_${randomUUID()}`;
632
- const createdAt = new Date(now).toISOString();
633
- const expiresAt = new Date(now + ttl).toISOString();
634
- database
635
- .prepare('INSERT INTO replay_pins (pin_id, epochs_json, created_at, expires_at) VALUES (?, ?, ?, ?)')
636
- .run(pinId, JSON.stringify(epochs), createdAt, expiresAt);
637
- const highWater = current?.highWater ?? 0;
638
- return {
639
- pin: {
640
- pinId,
641
- epochs,
642
- followBoundary: {
643
- runtimeId: String(identity.runtimeId),
644
- generation: Number(identity.generation),
645
- runtimeEpoch: Number(identity.runtimeEpoch),
646
- sourceSequence: Math.max(highWater, 1),
647
- },
648
- },
649
- };
650
- }
651
- function reclaim(database, minRetainMs) {
652
- const pins = activePins(database);
653
- const epochs = database.prepare('SELECT * FROM source_epochs').all();
654
- const now = Date.now();
655
- for (const epoch of epochs) {
656
- let retained = epoch.retained_from;
657
- while (true) {
658
- const row = database
659
- .prepare(`SELECT source_sequence, occurred_at FROM source_events
660
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ? AND source_sequence >= ?
661
- ORDER BY source_sequence LIMIT 1`)
662
- .get(epoch.runtime_id, epoch.generation, epoch.runtime_epoch, retained);
663
- if (!row || row.source_sequence !== retained)
664
- break;
665
- if (row.source_sequence > epoch.cloud_ack_through)
666
- break;
667
- if (pins.some((pin) => row.source_sequence >= pin.retainedFrom && row.source_sequence <= pin.highWater && pin.runtimeId === epoch.runtime_id && pin.generation === epoch.generation && pin.runtimeEpoch === epoch.runtime_epoch)) {
668
- break;
669
- }
670
- const age = now - Date.parse(row.occurred_at);
671
- if (Number.isFinite(age) && age < minRetainMs)
672
- break;
673
- database
674
- .prepare(`DELETE FROM source_events
675
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ? AND source_sequence = ?`)
676
- .run(epoch.runtime_id, epoch.generation, epoch.runtime_epoch, row.source_sequence);
677
- retained = row.source_sequence + 1;
678
- }
679
- if (retained !== epoch.retained_from) {
680
- database
681
- .prepare(`UPDATE source_epochs SET retained_from = ?
682
- WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ?`)
683
- .run(retained, epoch.runtime_id, epoch.generation, epoch.runtime_epoch);
684
- }
685
- }
686
- }
687
- function dump(database) {
688
- const snapshot = {
689
- workspaces: bucketObject(database, 'workspaces'),
690
- workspaceFileRevisions: workspaceFiles(database),
691
- operations: operationsObject(database),
692
- receipts: bucketObject(database, 'receipts'),
693
- events: eventsObject(database),
694
- sessions: bucketObject(database, 'sessions'),
695
- terminals: bucketObject(database, 'terminals'),
696
- fileRevisions: bucketObject(database, 'file_revisions'),
697
- approvals: bucketObject(database, 'approvals'),
698
- managedWrites: bucketObject(database, 'managed_writes'),
699
- workspaceDependencies: bucketObject(database, 'workspace_dependencies'),
700
- executionGroup: executionGroup(database),
701
- runtimeEpoch: metaNumber(database, 'runtime_epoch'),
702
- lastSourceSequence: currentCounter(database),
703
- acceptedLeaseFence: metaNumber(database, 'accepted_lease_fence'),
704
- destroyed: metaString(database, 'destroyed') === '1',
705
- };
706
- return {
707
- snapshot,
708
- epochs: database.prepare('SELECT * FROM source_epochs').all(),
709
- sourceReadToken: metaString(database, 'source_read_token'),
710
- pendingInbox: database.prepare('SELECT count(*) AS n FROM native_inbox WHERE converted = 0').get().n,
711
- };
712
- }
713
- function eventsObject(database) {
714
- const rows = database.prepare('SELECT * FROM source_events ORDER BY runtime_epoch, source_sequence').all();
715
- const events = {};
716
- for (const row of rows) {
717
- const event = pendingSourceEventSchema.parse({
718
- source: {
719
- runtimeId: row.runtime_id,
720
- generation: row.generation,
721
- runtimeEpoch: row.runtime_epoch,
722
- sourceSequence: row.source_sequence,
723
- },
724
- payloadHash: row.payload_hash,
725
- type: row.type,
726
- payload: JSON.parse(String(row.payload_json)),
727
- occurredAt: row.occurred_at,
728
- });
729
- events[`${event.source.runtimeId}:${event.source.generation}:${event.source.runtimeEpoch}:${event.source.sourceSequence}`] = event;
730
- }
731
- return events;
732
- }
733
- function operationsObject(database) {
734
- const rows = database.prepare('SELECT scope_key, operation_json FROM operation_intents').all();
735
- const operations = {};
736
- for (const row of rows) {
737
- const parsed = operationRecordSchema.safeParse(JSON.parse(row.operation_json));
738
- if (parsed.success)
739
- operations[row.scope_key] = parsed.data;
740
- }
741
- return operations;
742
- }
743
- function putOperation(database, scopeKey, value) {
744
- const operation = operationRecordSchema.parse(value);
745
- database
746
- .prepare(`INSERT INTO operation_intents (
747
- scope_key, operation_json, gateway_operation_id, sandbox_operation_id, payload_hash,
748
- native_request_id, thread_id, turn_id, reconcile_status
749
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
750
- ON CONFLICT(scope_key) DO UPDATE SET
751
- operation_json = excluded.operation_json,
752
- gateway_operation_id = excluded.gateway_operation_id,
753
- sandbox_operation_id = excluded.sandbox_operation_id,
754
- payload_hash = excluded.payload_hash,
755
- native_request_id = excluded.native_request_id,
756
- thread_id = excluded.thread_id,
757
- turn_id = excluded.turn_id,
758
- reconcile_status = excluded.reconcile_status`)
759
- .run(scopeKey, JSON.stringify(operation), null, operation.sandboxOperationId ?? operation.operationId, operation.payloadHash, operation.nativeRequestId ?? null, operation.nativeThreadId ?? null, operation.nativeTurnId ?? null, operation.status);
760
- }
761
- function insertEventRow(database, event, links) {
762
- database
763
- .prepare(`INSERT INTO source_events (
764
- runtime_id, generation, runtime_epoch, source_sequence, payload_hash, workspace_id, session_id,
765
- operation_id, thread_id, turn_id, item_id, type, payload_json, occurred_at
766
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
767
- .run(event.source.runtimeId, event.source.generation, event.source.runtimeEpoch, event.source.sourceSequence, event.payloadHash, links.workspaceId ?? null, links.sessionId ?? null, links.operationId ?? null, links.threadId ?? null, links.turnId ?? null, links.itemId ?? null, event.type, JSON.stringify(event.payload), event.occurredAt);
768
- }
769
- function ensureEpoch(database, runtimeId, generation, runtimeEpoch) {
770
- database
771
- .prepare(`INSERT INTO source_epochs (
772
- runtime_id, generation, runtime_epoch, next_sequence, local_durable_through, cloud_ack_through, retained_from
773
- ) VALUES (?, ?, ?, 0, 0, 0, 1)
774
- ON CONFLICT DO NOTHING`)
775
- .run(runtimeId, generation, runtimeEpoch);
776
- }
777
- function writeExecutionEpoch(database, body) {
778
- const runtimeEpoch = Number(body.runtimeEpoch);
779
- setMeta(database, 'runtime_epoch', String(runtimeEpoch));
780
- setMeta(database, 'execution_group', JSON.stringify({
781
- pid: body.pid,
782
- startedAt: body.startedAt,
783
- previousPid: body.previousPid,
784
- stopConfirmed: body.stopConfirmed === true,
785
- replaced: true,
786
- }));
787
- const approvals = database.prepare(`SELECT record_key, body_json FROM records WHERE bucket = 'approvals'`).all();
788
- for (const row of approvals) {
789
- const approval = asRecord(JSON.parse(row.body_json));
790
- if (approval.status === 'pending') {
791
- upsertRecord(database, 'approvals', row.record_key, { ...approval, status: 'expired' });
792
- }
793
- }
794
- const runtimeId = metaString(database, 'runtime_id');
795
- const generation = metaNumber(database, 'generation');
796
- if (runtimeId)
797
- ensureEpoch(database, runtimeId, generation, runtimeEpoch);
798
- }
799
- function bindRuntime(database, body) {
800
- setMeta(database, 'runtime_id', String(body.runtimeId));
801
- setMeta(database, 'generation', String(Number(body.generation) || 0));
802
- const current = metaNumber(database, 'runtime_epoch');
803
- const next = Math.max(current, Number(body.runtimeEpoch) || 0);
804
- setMeta(database, 'runtime_epoch', String(next));
805
- ensureEpoch(database, String(body.runtimeId), Number(body.generation) || 0, next);
806
- }
807
- function upsertRecord(database, bucket, key, body) {
808
- database
809
- .prepare(`INSERT INTO records (bucket, record_key, body_json) VALUES (?, ?, ?)
810
- ON CONFLICT(bucket, record_key) DO UPDATE SET body_json = excluded.body_json`)
811
- .run(bucket, key, JSON.stringify(body));
812
- }
813
- function replaceBucket(database, bucket, entries) {
814
- database.prepare('DELETE FROM records WHERE bucket = ?').run(bucket);
815
- for (const entry of entries) {
816
- const record = asRecord(entry);
817
- upsertRecord(database, bucket, String(record.key), record.body);
818
- }
819
- }
820
- function importBucket(database, bucket, records, accept) {
821
- for (const [key, value] of Object.entries(records)) {
822
- if (accept(value))
823
- upsertRecord(database, bucket, key, value);
824
- }
825
- }
826
- function bucketObject(database, bucket) {
827
- const rows = database.prepare('SELECT record_key, body_json FROM records WHERE bucket = ? ORDER BY rowid').all(bucket);
828
- return Object.fromEntries(rows.map((row) => [row.record_key, JSON.parse(row.body_json)]));
829
- }
830
- function workspaceFiles(database) {
831
- const rows = database
832
- .prepare(`SELECT bucket, record_key, body_json FROM records WHERE bucket LIKE 'workspace_files:%'`)
833
- .all();
834
- const files = {};
835
- for (const row of rows) {
836
- const workspaceId = row.bucket.slice('workspace_files:'.length);
837
- (files[workspaceId] ??= {})[row.record_key] = JSON.parse(row.body_json);
838
- }
839
- return files;
840
- }
841
- function readSession(database, sessionId) {
842
- const row = database
843
- .prepare(`SELECT body_json FROM records WHERE bucket = 'sessions' AND record_key = ?`)
844
- .get(sessionId);
845
- return row ? asRecord(JSON.parse(row.body_json)) : undefined;
846
- }
847
- function sessionByThread(database, threadId) {
848
- const rows = database.prepare(`SELECT body_json FROM records WHERE bucket = 'sessions'`).all();
849
- const matches = rows.map((row) => asRecord(JSON.parse(row.body_json))).filter((session) => session.threadId === threadId);
850
- if (matches.length !== 1)
851
- return undefined;
852
- return matches[0];
853
- }
854
- function operationByTurn(database, turnId) {
855
- const row = database
856
- .prepare('SELECT scope_key, operation_json FROM operation_intents WHERE turn_id = ?')
857
- .get(turnId);
858
- if (!row)
859
- return undefined;
860
- const parsed = operationRecordSchema.safeParse(JSON.parse(row.operation_json));
861
- if (!parsed.success)
862
- return undefined;
863
- return { scopeKey: row.scope_key, operation: parsed.data };
864
- }
865
- function canConvert(kind, threadId, turnId, session, operation) {
866
- if (kind === 'process_exit')
867
- return true;
868
- if (turnId && !operation)
869
- return false;
870
- if (turnId && operation)
871
- return true;
872
- if (!session || !threadId)
873
- return false;
874
- return true;
875
- }
876
- function linkedPayload(params, session) {
877
- const payload = asRecord(params);
878
- delete payload.workspaceId;
879
- if (typeof session?.workspaceId === 'string')
880
- payload.workspaceId = session.workspaceId;
881
- if (typeof session?.sessionId === 'string')
882
- payload.sessionId = session.sessionId;
883
- return payload;
884
- }
885
- function nativeIds(params) {
886
- const record = asRecord(params);
887
- const turn = asRecord(record.turn);
888
- const thread = asRecord(record.thread);
889
- return {
890
- threadId: optionalString(record.threadId) || optionalString(thread.id),
891
- turnId: optionalString(record.turnId) || optionalString(turn.id),
892
- itemId: optionalString(record.itemId) || optionalString(record.approvalId),
893
- };
894
- }
895
- function terminalTurn(method, payload) {
896
- if (method !== 'turn/completed' && method !== 'turn.completed' && method !== 'turn.interrupted' && method !== 'turn.failed') {
897
- return undefined;
898
- }
899
- if (method === 'turn.interrupted')
900
- return 'interrupted';
901
- if (method === 'turn.failed')
902
- return 'failed';
903
- const status = String(asRecord(payload.turn).status ?? payload.status ?? 'completed');
904
- if (status === 'interrupted')
905
- return 'interrupted';
906
- if (status === 'failed')
907
- return 'failed';
908
- return 'completed';
909
- }
910
- function moveTurn(current, to) {
911
- if (current === to)
912
- return to;
913
- if (current === 'starting' || current === 'running' || current === 'waiting_for_user' || current === 'completed' || current === 'failed' || current === 'interrupted') {
914
- return canTransitionTurn(current, to) ? to : current;
915
- }
916
- return to;
917
- }
918
- function nextIngress(database) {
919
- const next = metaNumber(database, 'ingress_counter') + 1;
920
- setMeta(database, 'ingress_counter', String(next));
921
- return next;
922
- }
923
- function epochRow(database, runtimeId, generation, runtimeEpoch) {
924
- return database
925
- .prepare('SELECT * FROM source_epochs WHERE runtime_id = ? AND generation = ? AND runtime_epoch = ?')
926
- .get(runtimeId, generation, runtimeEpoch);
927
- }
928
- function activePins(database) {
929
- const now = new Date().toISOString();
930
- const rows = database.prepare('SELECT epochs_json, expires_at FROM replay_pins').all();
931
- const pins = [];
932
- for (const row of rows) {
933
- if (row.expires_at <= now)
934
- continue;
935
- const epochs = JSON.parse(row.epochs_json);
936
- for (const epoch of epochs)
937
- pins.push(epoch);
938
- }
939
- return pins;
940
- }
941
- function currentCounter(database) {
942
- const row = epochRow(database, metaString(database, 'runtime_id'), metaNumber(database, 'generation'), metaNumber(database, 'runtime_epoch'));
943
- return row?.next_sequence ?? 0;
944
- }
945
- function executionGroup(database) {
946
- const raw = metaString(database, 'execution_group');
947
- if (!raw)
948
- return { stopConfirmed: false, replaced: false };
949
- try {
950
- return asRecord(JSON.parse(raw));
951
- }
952
- catch {
953
- return { stopConfirmed: false, replaced: false };
954
- }
955
- }
956
- function setMeta(database, key, value) {
957
- database
958
- .prepare(`INSERT INTO library_meta (key, value) VALUES (?, ?)
959
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`)
960
- .run(key, value);
961
- }
962
- function metaString(database, key) {
963
- const row = database.prepare('SELECT value FROM library_meta WHERE key = ?').get(key);
964
- return row?.value ?? '';
965
- }
966
- function metaNumber(database, key) {
967
- const parsed = Number(metaString(database, key));
968
- return Number.isFinite(parsed) ? parsed : 0;
969
- }
970
- function requireDb() {
971
- if (!db)
972
- throw new Error('sqlite_not_open');
973
- return db;
974
- }
975
- function sqliteAtLeast(version, minimum) {
976
- const parts = version.split('.').map((item) => Number(item));
977
- for (let index = 0; index < minimum.length; index += 1) {
978
- const left = parts[index] ?? 0;
979
- const right = minimum[index] ?? 0;
980
- if (left > right)
981
- return true;
982
- if (left < right)
983
- return false;
984
- }
985
- return true;
986
- }
987
- function asRecord(value) {
988
- return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
989
- }
990
- function optionalString(value) {
991
- return typeof value === 'string' && value.length > 0 ? value : undefined;
992
- }
993
- function firstString(snapshot, key) {
994
- return typeof snapshot[key] === 'string' ? String(snapshot[key]) : undefined;
995
- }
996
- function eventRuntime(events, key) {
997
- for (const value of Object.values(events)) {
998
- const source = asRecord(asRecord(value).source);
999
- if (typeof source[key] === 'string')
1000
- return String(source[key]);
1001
- }
1002
- return undefined;
1003
- }
1004
- function eventRuntimeNumber(events, key) {
1005
- for (const value of Object.values(events)) {
1006
- const source = asRecord(asRecord(value).source);
1007
- if (Number.isInteger(source[key]))
1008
- return Number(source[key]);
1009
- }
1010
- return 0;
1011
- }
1012
- function isApproval(value) {
1013
- const record = asRecord(value);
1014
- return typeof record.approvalId === 'string' && typeof record.sessionId === 'string' && typeof record.nativeRequestId === 'string';
1015
- }