@crewx/sdk 0.9.0-rc.23 → 0.9.0-rc.230

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 (460) hide show
  1. package/README.md +1 -1
  2. package/dist/account/auth-client.d.ts +61 -0
  3. package/dist/account/auth-json-v2.d.ts +1 -0
  4. package/dist/account/auth-json.d.ts +30 -0
  5. package/dist/account/config.d.ts +37 -0
  6. package/dist/account/env-bootstrap.d.ts +11 -0
  7. package/dist/account/errors.d.ts +24 -0
  8. package/dist/account/index.d.ts +12 -0
  9. package/dist/account/index.js +2 -0
  10. package/dist/account/session-manager.d.ts +47 -0
  11. package/dist/activity-log/builder.d.ts +59 -6
  12. package/dist/agent/agent-list-view.d.ts +19 -0
  13. package/dist/agent-interceptor/chain.d.ts +25 -0
  14. package/dist/agent-interceptor/index.d.ts +6 -0
  15. package/dist/agent-interceptor/model-runner.d.ts +19 -0
  16. package/dist/agent-interceptor/program-runner.d.ts +13 -0
  17. package/dist/agent-interceptor/protocol.d.ts +68 -0
  18. package/dist/agent-interceptor/run-stop.d.ts +3 -0
  19. package/dist/agent-interceptor/schema.d.ts +267 -0
  20. package/dist/agent-interceptor/types.d.ts +88 -0
  21. package/dist/app/app-files/args.d.ts +12 -0
  22. package/dist/app/app-files/errors.d.ts +6 -0
  23. package/dist/app/app-files/index.d.ts +35 -0
  24. package/dist/app/app-files/lock.d.ts +26 -0
  25. package/dist/app/app-files/root.d.ts +22 -0
  26. package/dist/app/app-files/store.d.ts +48 -0
  27. package/dist/app/app-files/write.child.d.ts +1 -0
  28. package/dist/app/app.d.ts +168 -0
  29. package/dist/app/backend-env.d.ts +3 -0
  30. package/dist/app/content-media-types.d.ts +2 -0
  31. package/dist/app/context.d.ts +2 -0
  32. package/dist/app/entry.d.ts +9 -0
  33. package/dist/app/frame.d.ts +55 -0
  34. package/dist/app/index.d.ts +20 -0
  35. package/dist/app/index.js +13 -0
  36. package/dist/app/job-bridge.child.d.ts +1 -0
  37. package/dist/app/job-bridge.d.ts +67 -0
  38. package/dist/app/job-bridge.drain.child.d.ts +1 -0
  39. package/dist/app/job-bridge.example.d.ts +11 -0
  40. package/dist/app/job-contract.d.ts +40 -0
  41. package/dist/app/job-wire.d.ts +149 -0
  42. package/dist/app/protocol.d.ts +9 -0
  43. package/dist/app/runtime.d.ts +23 -0
  44. package/dist/app/schedule-contract.d.ts +59 -0
  45. package/dist/app/tool-mode.d.ts +3 -0
  46. package/dist/app-artifact-policy/check.d.ts +2 -0
  47. package/dist/app-artifact-policy/contract.d.ts +54 -0
  48. package/dist/app-artifact-policy/helper.d.ts +15 -0
  49. package/dist/app-artifact-policy/index.d.ts +3 -0
  50. package/dist/app-artifact-policy/index.js +18 -0
  51. package/dist/app-artifact-policy/paths.d.ts +24 -0
  52. package/dist/app-artifact-policy/scan.d.ts +47 -0
  53. package/dist/app-install/dependencies.d.ts +30 -0
  54. package/dist/app-install/errors.d.ts +9 -0
  55. package/dist/app-install/index.d.ts +9 -0
  56. package/dist/app-install/index.js +7 -0
  57. package/dist/app-install/process.d.ts +33 -0
  58. package/dist/app-install/runtime-env.d.ts +2 -0
  59. package/dist/app-install/verify.d.ts +10 -0
  60. package/dist/app-sync/continuation.d.ts +67 -0
  61. package/dist/app-sync/coordinator.d.ts +92 -0
  62. package/dist/app-sync/create-ledger.d.ts +27 -0
  63. package/dist/app-sync/index.d.ts +9 -0
  64. package/dist/app-sync/index.js +390 -0
  65. package/dist/app-sync/scope.d.ts +35 -0
  66. package/dist/app-sync/session-fence.d.ts +26 -0
  67. package/dist/app-sync/sqlite-store.d.ts +237 -0
  68. package/dist/app-sync/types.d.ts +855 -0
  69. package/dist/app-ui/index.d.ts +95 -0
  70. package/dist/app-ui/index.js +1 -0
  71. package/dist/attachment-receive/index.d.ts +76 -0
  72. package/dist/attachment-receive/index.js +2 -0
  73. package/dist/boxing/box.types.d.ts +4 -0
  74. package/dist/config/canonicalize-agent-options.d.ts +13 -0
  75. package/dist/config/default-agent-models.d.ts +11 -0
  76. package/dist/config/global-settings.d.ts +33 -0
  77. package/dist/config/migrate-grok-mode.d.ts +6 -0
  78. package/dist/config/model-compat.d.ts +31 -0
  79. package/dist/config/models.generated.d.ts +38 -0
  80. package/dist/config/models.remote.d.ts +1 -0
  81. package/dist/config/overdrive.d.ts +7 -0
  82. package/dist/config/pricing.d.ts +6 -3
  83. package/dist/config/pricing.generated.d.ts +4 -0
  84. package/dist/config/pricing.types.d.ts +4 -0
  85. package/dist/config/timeout.config.d.ts +4 -0
  86. package/dist/config/wi-boards.d.ts +19 -0
  87. package/dist/context/GoalLoader.d.ts +6 -0
  88. package/dist/context-budget/continuity.d.ts +64 -0
  89. package/dist/context-budget/fixed-slot-shrink.d.ts +97 -0
  90. package/dist/context-budget/index.d.ts +168 -0
  91. package/dist/conversation/index.d.ts +1 -1
  92. package/dist/conversation/sqlite-provider.d.ts +9 -3
  93. package/dist/conversation/to-template-messages.d.ts +12 -2
  94. package/dist/conversation/types.d.ts +94 -1
  95. package/dist/desktop/command-runner.d.ts +4 -0
  96. package/dist/desktop/default-adapters.d.ts +4 -0
  97. package/dist/desktop/global-install.d.ts +19 -0
  98. package/dist/desktop/index.d.ts +3 -0
  99. package/dist/desktop/index.js +3 -0
  100. package/dist/desktop/install.d.ts +5 -0
  101. package/dist/desktop/lnk.d.ts +22 -0
  102. package/dist/desktop/manifest.d.ts +21 -0
  103. package/dist/desktop/types.d.ts +67 -0
  104. package/dist/desktop/version.d.ts +1 -0
  105. package/dist/desktop/windows-paths.d.ts +21 -0
  106. package/dist/desktop/wrapper.d.ts +18 -0
  107. package/dist/esm/account/index.js +2 -0
  108. package/dist/esm/app/index.js +13 -0
  109. package/dist/esm/app-artifact-policy/index.js +18 -0
  110. package/dist/esm/app-install/index.js +7 -0
  111. package/dist/esm/app-sync/index.js +390 -0
  112. package/dist/esm/attachment-receive/index.js +2 -0
  113. package/dist/esm/desktop/index.js +3 -0
  114. package/dist/esm/history-snapshot/index.js +16 -0
  115. package/dist/esm/index.js +1450 -224
  116. package/dist/esm/node/index.js +2 -0
  117. package/dist/esm/plugins/index.js +604 -219
  118. package/dist/esm/process/index.js +1 -0
  119. package/dist/esm/publish/index.js +2 -0
  120. package/dist/esm/repository/index.js +863 -211
  121. package/dist/esm/skills/index.js +2 -0
  122. package/dist/esm/testing/index.js +1 -1
  123. package/dist/events/types.d.ts +44 -0
  124. package/dist/facade/Crewx.d.ts +108 -5
  125. package/dist/facade/task-ticket.d.ts +14 -0
  126. package/dist/highlight/thread-highlight-prompt.d.ts +2 -0
  127. package/dist/highlight/thread-highlighter.d.ts +326 -0
  128. package/dist/history-snapshot/index.d.ts +84 -0
  129. package/dist/history-snapshot/index.js +16 -0
  130. package/dist/index.browser.d.ts +26 -1
  131. package/dist/index.browser.js +6 -2
  132. package/dist/index.d.ts +175 -20
  133. package/dist/index.js +1450 -224
  134. package/dist/internal/console-decoder.d.ts +38 -0
  135. package/dist/internal/windows-spawn.d.ts +10 -0
  136. package/dist/layout/types.d.ts +18 -1
  137. package/dist/lifecycle/process-lease.d.ts +80 -0
  138. package/dist/lifecycle/process-owner.d.ts +20 -0
  139. package/dist/lifecycle/task-heartbeat.d.ts +41 -0
  140. package/dist/lifecycle/task-stop.d.ts +112 -0
  141. package/dist/lifecycle/update-admission.d.ts +45 -0
  142. package/dist/local-server/base-url.d.ts +18 -0
  143. package/dist/local-server/index.d.ts +8 -0
  144. package/dist/local-server/opencode.d.ts +8 -0
  145. package/dist/local-server/probe.d.ts +3 -0
  146. package/dist/local-server/runtime.d.ts +26 -0
  147. package/dist/local-server/types.d.ts +43 -0
  148. package/dist/mcp-app/agent-access.d.ts +33 -0
  149. package/dist/mcp-app/app-handoff.d.ts +109 -0
  150. package/dist/mcp-app/app-icon-read.d.ts +7 -0
  151. package/dist/mcp-app/app-job-bridge.d.ts +30 -0
  152. package/dist/mcp-app/app-job-bridge.example.d.ts +36 -0
  153. package/dist/mcp-app/app-job.d.ts +168 -0
  154. package/dist/mcp-app/app-schedule.d.ts +85 -0
  155. package/dist/mcp-app/apps-context.d.ts +32 -0
  156. package/dist/mcp-app/bundle-provenance.d.ts +3 -0
  157. package/dist/mcp-app/candidate-registration.d.ts +4 -0
  158. package/dist/mcp-app/card-handler.d.ts +7 -0
  159. package/dist/mcp-app/catalog.d.ts +7 -0
  160. package/dist/mcp-app/content-channel.d.ts +86 -0
  161. package/dist/mcp-app/content-declarations.d.ts +31 -0
  162. package/dist/mcp-app/dev-checks.d.ts +31 -0
  163. package/dist/mcp-app/diagnostic-reason.d.ts +3 -0
  164. package/dist/mcp-app/discovery.d.ts +164 -0
  165. package/dist/mcp-app/errors.d.ts +7 -0
  166. package/dist/mcp-app/index.d.ts +46 -0
  167. package/dist/mcp-app/installed-app-ref.d.ts +25 -0
  168. package/dist/mcp-app/model-context.d.ts +29 -0
  169. package/dist/mcp-app/node-app-discovery-fs.d.ts +23 -0
  170. package/dist/mcp-app/product-bundle-assets.d.ts +27 -0
  171. package/dist/mcp-app/product-bundle-loader.d.ts +53 -0
  172. package/dist/mcp-app/projection.d.ts +14 -0
  173. package/dist/mcp-app/prompt-cards.d.ts +28 -0
  174. package/dist/mcp-app/registry.d.ts +28 -0
  175. package/dist/mcp-app/skill-backend.d.ts +141 -0
  176. package/dist/mcp-app/state-set.d.ts +9 -0
  177. package/dist/mcp-app/types.d.ts +501 -0
  178. package/dist/mcp-app/view-call.d.ts +7 -0
  179. package/dist/mcp-app/workspace-app-assets.d.ts +42 -0
  180. package/dist/mcp-app/workspace-app-scan-cache.d.ts +27 -0
  181. package/dist/mcp-app/workspace-snapshot.d.ts +81 -0
  182. package/dist/migrations/0011_far_black_tarantula.sql +1 -0
  183. package/dist/migrations/0012_blue_turbo.sql +23 -0
  184. package/dist/migrations/0013_hesitant_adam_destine.sql +15 -0
  185. package/dist/migrations/0014_organic_mongu.sql +73 -0
  186. package/dist/migrations/0015_panoramic_gorilla_man.sql +71 -0
  187. package/dist/migrations/0016_fuzzy_hemingway.sql +14 -0
  188. package/dist/migrations/0017_project_stage_sdk_migration.sql +29 -0
  189. package/dist/migrations/0018_bored_jackal.sql +33 -0
  190. package/dist/migrations/0019_backfill_task_thread_ids.sql +74 -0
  191. package/dist/migrations/0020_useful_iron_lad.sql +55 -0
  192. package/dist/migrations/0021_dashing_peter_quill.sql +51 -0
  193. package/dist/migrations/0022_wandering_bucky.sql +1 -0
  194. package/dist/migrations/0023_red_payback.sql +1 -0
  195. package/dist/migrations/0024_storage_metadata.sql +262 -0
  196. package/dist/migrations/0025_task_heartbeat.sql +8 -0
  197. package/dist/migrations/0025_thread_app_instance_ledger.sql +2 -0
  198. package/dist/migrations/0026_mcp_action_source.sql +47 -0
  199. package/dist/migrations/0027_task_stop_scope_cleanup.sql +5 -0
  200. package/dist/migrations/0027_ui_instance_active_unique.sql +2 -0
  201. package/dist/migrations/0029_nice_rhino.sql +1 -0
  202. package/dist/migrations/0031_petite_arclight.sql +6 -0
  203. package/dist/migrations/0032_ui_instance_opened_by.sql +1 -0
  204. package/dist/migrations/0033_thread_creator_boundary_guard.sql +38 -0
  205. package/dist/migrations/0034_keen_fallen_one.sql +36 -0
  206. package/dist/migrations/0035_request_log_daily.sql +11 -0
  207. package/dist/migrations/0036_ui_definition_archive.sql +8 -0
  208. package/dist/migrations/0037_ui_instance_agent_open_request.sql +1 -0
  209. package/dist/migrations/0038_task_rating.sql +3 -0
  210. package/dist/migrations/0039_aspiring_purifiers.sql +9 -0
  211. package/dist/migrations/0040_task_provider_inputs.sql +53 -0
  212. package/dist/migrations/0041_tranquil_vivisector.sql +54 -0
  213. package/dist/migrations/0042_breezy_blue_shield.sql +31 -0
  214. package/dist/migrations/0043_nervous_darkstar.sql +1 -0
  215. package/dist/migrations/0044_military_galactus.sql +8 -0
  216. package/dist/migrations/0045_task_pid_started_at.sql +1 -0
  217. package/dist/migrations/0046_acoustic_karnak.sql +49 -0
  218. package/dist/migrations/0047_doc_sync_connect_requests.sql +18 -0
  219. package/dist/migrations/0048_smart_gertrude_yorkes.sql +47 -0
  220. package/dist/migrations/0049_blue_sleepwalker.sql +25 -0
  221. package/dist/migrations/0050_rapid_black_cat.sql +89 -0
  222. package/dist/migrations/0051_lying_sinister_six.sql +1 -0
  223. package/dist/migrations/0052_lying_gambit.sql +33 -0
  224. package/dist/migrations/0053_smart_shriek.sql +172 -0
  225. package/dist/migrations/0054_lying_surge.sql +63 -0
  226. package/dist/migrations/0055_curious_talkback.sql +92 -0
  227. package/dist/migrations/0056_stale_menace.sql +14 -0
  228. package/dist/migrations/0057_eager_captain_flint.sql +18 -0
  229. package/dist/migrations/0058_thread_branches.sql +37 -0
  230. package/dist/migrations/meta/0011_snapshot.json +1342 -0
  231. package/dist/migrations/meta/0012_snapshot.json +1494 -0
  232. package/dist/migrations/meta/0013_snapshot.json +1592 -0
  233. package/dist/migrations/meta/0014_snapshot.json +1975 -0
  234. package/dist/migrations/meta/0015_snapshot.json +2315 -0
  235. package/dist/migrations/meta/0016_snapshot.json +2419 -0
  236. package/dist/migrations/meta/0017_snapshot.json +2419 -0
  237. package/dist/migrations/meta/0018_snapshot.json +2570 -0
  238. package/dist/migrations/meta/0020_snapshot.json +2895 -0
  239. package/dist/migrations/meta/0021_snapshot.json +3031 -0
  240. package/dist/migrations/meta/0022_snapshot.json +3039 -0
  241. package/dist/migrations/meta/0023_snapshot.json +3047 -0
  242. package/dist/migrations/meta/0029_snapshot.json +3206 -0
  243. package/dist/migrations/meta/0031_snapshot.json +3251 -0
  244. package/dist/migrations/meta/0034_snapshot.json +3473 -0
  245. package/dist/migrations/meta/0035_snapshot.json +3547 -0
  246. package/dist/migrations/meta/0036_snapshot.json +3591 -0
  247. package/dist/migrations/meta/0037_snapshot.json +3598 -0
  248. package/dist/migrations/meta/0038_snapshot.json +3626 -0
  249. package/dist/migrations/meta/0039_snapshot.json +3684 -0
  250. package/dist/migrations/meta/0040_snapshot.json +3759 -0
  251. package/dist/migrations/meta/0041_snapshot.json +4156 -0
  252. package/dist/migrations/meta/0042_snapshot.json +4383 -0
  253. package/dist/migrations/meta/0043_snapshot.json +4390 -0
  254. package/dist/migrations/meta/0044_snapshot.json +4435 -0
  255. package/dist/migrations/meta/0045_snapshot.json +4442 -0
  256. package/dist/migrations/meta/0046_snapshot.json +4733 -0
  257. package/dist/migrations/meta/0047_snapshot.json +4832 -0
  258. package/dist/migrations/meta/0048_snapshot.json +5128 -0
  259. package/dist/migrations/meta/0049_snapshot.json +5165 -0
  260. package/dist/migrations/meta/0050_snapshot.json +5717 -0
  261. package/dist/migrations/meta/0051_snapshot.json +5725 -0
  262. package/dist/migrations/meta/0052_snapshot.json +5930 -0
  263. package/dist/migrations/meta/0053_snapshot.json +6780 -0
  264. package/dist/migrations/meta/0054_snapshot.json +6784 -0
  265. package/dist/migrations/meta/0055_snapshot.json +6896 -0
  266. package/dist/migrations/meta/0056_snapshot.json +6971 -0
  267. package/dist/migrations/meta/0057_snapshot.json +6971 -0
  268. package/dist/migrations/meta/0058_snapshot.json +7227 -0
  269. package/dist/migrations/meta/_journal.json +336 -0
  270. package/dist/node/index.d.ts +1 -0
  271. package/dist/node/index.js +2 -0
  272. package/dist/paths.d.ts +1 -0
  273. package/dist/plugin/types.d.ts +1 -0
  274. package/dist/plugins/index.d.ts +1 -1
  275. package/dist/plugins/index.js +604 -219
  276. package/dist/plugins/sqlite-tracing.d.ts +46 -0
  277. package/dist/process/index.d.ts +2 -0
  278. package/dist/process/index.js +1 -0
  279. package/dist/process/process-control.d.ts +74 -0
  280. package/dist/prompt/tag-names.d.ts +23 -0
  281. package/dist/provider/acp/adapter.d.ts +37 -2
  282. package/dist/provider/acp/adapters/antigravity-account.d.ts +4 -0
  283. package/dist/provider/acp/completion-observer.d.ts +24 -0
  284. package/dist/provider/acp/connection.d.ts +69 -3
  285. package/dist/provider/acp/index.d.ts +3 -3
  286. package/dist/provider/acp/meta.d.ts +11 -0
  287. package/dist/provider/acp/register.d.ts +1 -0
  288. package/dist/provider/acp/runtime.d.ts +1 -0
  289. package/dist/provider/acp/types.d.ts +31 -4
  290. package/dist/provider/bridge.browser.d.ts +3 -0
  291. package/dist/provider/bridge.d.ts +28 -4
  292. package/dist/provider/classify-task-error.d.ts +2 -0
  293. package/dist/provider/claude-agent-env.d.ts +1 -0
  294. package/dist/provider/cli/adapter.types.d.ts +35 -7
  295. package/dist/provider/cli/adapters/agent-call.util.d.ts +1 -1
  296. package/dist/provider/cli/adapters/antigravity-stream.d.ts +27 -0
  297. package/dist/provider/cli/adapters/antigravity.d.ts +1 -0
  298. package/dist/provider/cli/adapters/claude-task-events.d.ts +48 -0
  299. package/dist/provider/cli/adapters/cli-knob.util.d.ts +7 -0
  300. package/dist/provider/cli/adapters/codex-item.d.ts +1 -0
  301. package/dist/provider/cli/adapters/event-timestamp.util.d.ts +1 -0
  302. package/dist/provider/cli/adapters/grok.d.ts +2 -0
  303. package/dist/provider/cli/adapters/index.d.ts +5 -0
  304. package/dist/provider/cli/adapters/opencode-data-dir.d.ts +17 -0
  305. package/dist/provider/cli/adapters/opencode.d.ts +1 -0
  306. package/dist/provider/cli/builtin-allow.d.ts +6 -0
  307. package/dist/provider/cli/index.d.ts +3 -2
  308. package/dist/provider/cli/meta.d.ts +18 -1
  309. package/dist/provider/cli/protocol-envelope.d.ts +3 -0
  310. package/dist/provider/errors.d.ts +11 -1
  311. package/dist/provider/idle-watchdog.d.ts +19 -0
  312. package/dist/provider/model-ladder.d.ts +8 -0
  313. package/dist/provider/models.d.ts +17 -12
  314. package/dist/provider/order.d.ts +1 -1
  315. package/dist/provider/parse-usage.d.ts +6 -0
  316. package/dist/provider/provider-selection.d.ts +8 -0
  317. package/dist/provider/redact-technical-message.d.ts +1 -0
  318. package/dist/provider/safe-opencode-text.d.ts +2 -0
  319. package/dist/provider/task-error.types.d.ts +20 -0
  320. package/dist/provider-account/accounts.d.ts +15 -0
  321. package/dist/provider-account/antigravity-acp/auth.d.ts +29 -0
  322. package/dist/provider-account/antigravity-acp/browser.d.ts +4 -0
  323. package/dist/provider-account/antigravity-acp/install.d.ts +42 -0
  324. package/dist/provider-account/antigravity-acp/lease.d.ts +23 -0
  325. package/dist/provider-account/antigravity-acp/lifecycle.d.ts +76 -0
  326. package/dist/provider-account/antigravity-acp/manifest.d.ts +76 -0
  327. package/dist/provider-account/antigravity-acp/profile.d.ts +4 -0
  328. package/dist/provider-account/capabilities.d.ts +6 -0
  329. package/dist/provider-account/index.d.ts +13 -0
  330. package/dist/provider-account/registry.d.ts +30 -0
  331. package/dist/provider-account/types.d.ts +47 -0
  332. package/dist/publish/constants.d.ts +6 -0
  333. package/dist/publish/errors.d.ts +7 -0
  334. package/dist/publish/index.d.ts +55 -0
  335. package/dist/publish/index.js +2 -0
  336. package/dist/publish/manifest.d.ts +47 -0
  337. package/dist/publish/marketplace-api.constants.d.ts +1 -0
  338. package/dist/publish/pack.d.ts +6 -0
  339. package/dist/publish/scan.d.ts +10 -0
  340. package/dist/publish/secrets.d.ts +6 -0
  341. package/dist/publish/upload.d.ts +19 -0
  342. package/dist/remote/execution-profile.d.ts +9 -0
  343. package/dist/remote/index.d.ts +1 -0
  344. package/dist/remote/types.d.ts +28 -0
  345. package/dist/repository/agent-send-history.repository.d.ts +23 -0
  346. package/dist/repository/agent-suggestion.repository.d.ts +34 -0
  347. package/dist/repository/base-sqlite-repository.d.ts +1 -0
  348. package/dist/repository/common-code.repository.d.ts +45 -0
  349. package/dist/repository/db.d.ts +13 -1
  350. package/dist/repository/index.d.ts +63 -6
  351. package/dist/repository/index.js +863 -211
  352. package/dist/repository/logs-db.d.ts +12 -0
  353. package/dist/repository/notification.repository.d.ts +58 -0
  354. package/dist/repository/project.repository.d.ts +90 -0
  355. package/dist/repository/public-task-answer.d.ts +24 -0
  356. package/dist/repository/request-log-mover.d.ts +70 -0
  357. package/dist/repository/request-log.repository.d.ts +7 -3
  358. package/dist/repository/run-columns.d.ts +10 -0
  359. package/dist/repository/run-history.repository.d.ts +112 -0
  360. package/dist/repository/schedule-run.repository.d.ts +103 -0
  361. package/dist/repository/sidebar-tab.repository.d.ts +87 -0
  362. package/dist/repository/storage-metadata.repository.d.ts +64 -0
  363. package/dist/repository/task-log-migration.d.ts +74 -0
  364. package/dist/repository/task-log.repository.d.ts +47 -0
  365. package/dist/repository/task-status.d.ts +21 -0
  366. package/dist/repository/task.repository.d.ts +329 -8
  367. package/dist/repository/thread-branch.repository.d.ts +106 -0
  368. package/dist/repository/thread-history.repository.d.ts +193 -0
  369. package/dist/repository/thread-origin-verdict.d.ts +27 -0
  370. package/dist/repository/thread-title.types.d.ts +29 -0
  371. package/dist/repository/thread.repository.d.ts +134 -5
  372. package/dist/repository/usage-backfill.d.ts +62 -0
  373. package/dist/repository/usage-from-logs.d.ts +22 -0
  374. package/dist/repository/workflow-anchor-kinds.d.ts +4 -0
  375. package/dist/repository/workspace.repository.d.ts +3 -0
  376. package/dist/route/decide.d.ts +56 -0
  377. package/dist/route/eligibility.d.ts +11 -0
  378. package/dist/route/errors.d.ts +11 -0
  379. package/dist/route/index.d.ts +14 -0
  380. package/dist/route/runner.d.ts +15 -0
  381. package/dist/route/sqlite-store.d.ts +18 -0
  382. package/dist/route/store.d.ts +48 -0
  383. package/dist/route/strategies.d.ts +4 -0
  384. package/dist/route/types.d.ts +440 -0
  385. package/dist/schema/agent-send-history.d.ts +85 -0
  386. package/dist/schema/agent-suggestions.d.ts +199 -0
  387. package/dist/schema/app-sync.d.ts +2533 -0
  388. package/dist/schema/common-codes.d.ts +216 -0
  389. package/dist/schema/doc-create-dispatches.d.ts +101 -0
  390. package/dist/schema/doc-sync-connect-requests.d.ts +140 -0
  391. package/dist/schema/doc-sync-links.d.ts +556 -0
  392. package/dist/schema/index.d.ts +24 -0
  393. package/dist/schema/model-routes.d.ts +638 -0
  394. package/dist/schema/notifications.d.ts +303 -0
  395. package/dist/schema/projects.d.ts +610 -0
  396. package/dist/schema/request-log-daily.d.ts +151 -0
  397. package/dist/schema/run-column-backfill.d.ts +81 -0
  398. package/dist/schema/schedule-runs.d.ts +451 -0
  399. package/dist/schema/sidebar-tabs.d.ts +466 -0
  400. package/dist/schema/storage-metadata.d.ts +181 -0
  401. package/dist/schema/task-log-events.d.ts +119 -0
  402. package/dist/schema/task-provider-inputs.d.ts +100 -0
  403. package/dist/schema/tasks.d.ts +1172 -1
  404. package/dist/schema/thread-branches.d.ts +424 -0
  405. package/dist/schema/thread-creator-unverified.d.ts +45 -0
  406. package/dist/schema/thread-history.d.ts +734 -0
  407. package/dist/schema/threads.d.ts +59 -0
  408. package/dist/schema/ui-action-receipts.d.ts +358 -0
  409. package/dist/schema/ui-definition-archive.d.ts +63 -0
  410. package/dist/schema/ui-instance-repins.d.ts +222 -0
  411. package/dist/schema/ui-instances.d.ts +324 -0
  412. package/dist/schema/workspaces.d.ts +17 -0
  413. package/dist/skills/index.d.ts +15 -0
  414. package/dist/skills/index.js +2 -0
  415. package/dist/skills/types.d.ts +18 -0
  416. package/dist/task-log/anchor-child-tasks.d.ts +7 -0
  417. package/dist/task-log/claude-background-task.d.ts +30 -0
  418. package/dist/task-log/delegation-trailer.d.ts +34 -0
  419. package/dist/template/engine.d.ts +2 -2
  420. package/dist/template/helpers/exec.browser.d.ts +4 -3
  421. package/dist/template/helpers/exec.d.ts +4 -3
  422. package/dist/template/helpers/format-conversation.d.ts +1 -0
  423. package/dist/template/types.d.ts +20 -0
  424. package/dist/testing/index.js +1 -1
  425. package/dist/types/index.d.ts +3325 -84
  426. package/dist/types/task-log.types.d.ts +6 -1
  427. package/dist/ui-card/index.d.ts +2 -0
  428. package/dist/ui-card/legacy-card-parser.d.ts +11 -0
  429. package/dist/ui-instance/definition.d.ts +6 -0
  430. package/dist/ui-instance/errors.d.ts +18 -0
  431. package/dist/ui-instance/index.d.ts +11 -0
  432. package/dist/ui-instance/json.d.ts +19 -0
  433. package/dist/ui-instance/lineage.d.ts +24 -0
  434. package/dist/ui-instance/runtime.d.ts +19 -0
  435. package/dist/ui-instance/store.d.ts +221 -0
  436. package/dist/ui-instance/types.d.ts +384 -0
  437. package/dist/ui-plugin/app-icon.d.ts +50 -0
  438. package/dist/ui-plugin/app-manifest.d.ts +64 -0
  439. package/dist/ui-plugin/csp.d.ts +28 -0
  440. package/dist/ui-plugin/index.d.ts +8 -0
  441. package/dist/ui-plugin/limits.d.ts +27 -0
  442. package/dist/ui-plugin/manifest.d.ts +3 -0
  443. package/dist/ui-plugin/types.d.ts +220 -0
  444. package/dist/ui-plugin/validator.d.ts +18 -0
  445. package/dist/utils/crewx-executable.d.ts +76 -0
  446. package/dist/utils/crewx-home.d.ts +1 -0
  447. package/dist/utils/env-defaults.d.ts +3 -0
  448. package/dist/utils/id.d.ts +1 -1
  449. package/dist/utils/local-identity.d.ts +2 -0
  450. package/dist/utils/runner-env.d.ts +3 -0
  451. package/dist/utils/timestamp.d.ts +1 -0
  452. package/dist/utils/workspace.d.ts +1 -0
  453. package/dist/wi/create.d.ts +48 -0
  454. package/dist/wi/select.d.ts +20 -0
  455. package/package.json +97 -3
  456. package/templates/agents/default.yaml +319 -128
  457. package/templates/documents/crewx-manual.md +138 -138
  458. package/templates/documents/crewx-quick-guide.md +8 -7
  459. package/templates/workflows/wi-default-flow.yaml +65 -0
  460. package/templates/workflows/wi-plan-flow.yaml +140 -0
@@ -0,0 +1,390 @@
1
+ 'use strict';var fs$1=require('fs'),ne=require('path'),Ko=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');require('string_decoder'),require('fs/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var Ko__default=/*#__PURE__*/_interopDefault(Ko);var xt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var d=k(()=>{});function jo(t){if(t===":memory:")return t;let e=ne.resolve(t),n=e,r=[];for(;!fs$1.existsSync(n);){let s=ne.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=fs$1.realpathSync(n);for(let s of r)o=ne.join(o,s);return ne.resolve(o)}function cd(t,e){let n=jo(t),r=jo(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Qe(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&ud.some(e=>cd(t,ne.join(Ko__default.default.homedir(),".crewx",e))))throw new Error(`${dd}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var dd,ud,D,P=k(()=>{d();dd="[crewx] Refusing to open the real CrewX database from a test process";ud=["crewx.db","logs.db"];D=class{resolveDbPath(){if(process.env.CREWX_TRACES_DB!==void 0)throw new Error(`CREWX_TRACES_DB is removed. Use CREWX_DB instead. (got: ${process.env.CREWX_TRACES_DB})`);let e=process.env.CREWX_DB||ne.join(Ko__default.default.homedir(),".crewx","crewx.db");return Qe(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs$1.existsSync(e??this.resolveDbPath())}};});var L=k(()=>{d();});function x(t,e={}){let n=Qe(t),r=xt("better-sqlite3"),{drizzle:o}=xt("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${_n}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,a=[])=>s.prepare(i).run(...a),close:()=>s.close()}}var _n,M=k(()=>{d();P();_n=32*1024*1024;});function ht(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function _d(t,e){if(e>0||!ht(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(pd))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function fd(t,e,n){if(!ht(t,"__drizzle_migrations")||!ht(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=gd[i.tag];if(!a)continue;let c=ne__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(c))continue;let u=fs$1.readFileSync(c,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let f=t.all("PRAGMA table_info(tasks)"),_=new Set(f.map(S=>S.name));for(let[S,w]of Object.entries(a))_.has(S)||(t.run(`ALTER TABLE tasks ADD COLUMN ${S} ${w}`),_.add(S));}}function Yo(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function Jo(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function hd(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function md(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function gn(t,e){return e.kind==="add-column"?hd(t,e.table,e.column):md(t,e.name)}function Xo(t,e,n){let r=t;for(let o of Jo(e)){let s=Yo(o);s?.kind==="add-column"&&gn(r,s)||s?.kind==="create-index"&&gn(r,s)||s?.kind==="drop-index"&&!gn(r,s)||r.run(n.raw(o));}}function yd(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=ne__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(a))continue;let c=fs$1.readFileSync(a,"utf-8"),u=crypto.createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let f=Jo(c).map(Yo);if(f.some(S=>!S))continue;let _=f;_.some(S=>S.kind==="add-column")&&_.some(S=>gn(t,S))&&(t.transaction(S=>{Xo(S,c,n),S.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function kd(t,e){let{sql:n}=xt("drizzle-orm"),r=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let a=r.entries.find(u=>u.tag===i);if(!a)throw new Error(`Missing release/App compatibility migration: ${i}`);let c=fs$1.readFileSync(ne__default.default.join(e,`${i}.sql`),"utf-8");return {entry:a,content:c,hash:crypto.createHash("sha256").update(c).digest("hex")}});t.transaction(i=>{let a=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(c=>c.hash));if(a.has(s[0].hash))for(let c of s.slice(1))a.has(c.hash)||(Xo(i,c.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c.hash}, ${c.entry.when})`),a.add(c.hash),console.error(`[crewx] Replayed release/App migration ${c.entry.tag} safely.`));},{behavior:"immediate"});}function Ed(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:f})=>f===Sd);if(!s)return;let i=ne__default.default.join(e,`${s.tag}.sql`);if(!fs$1.existsSync(i))return;let a=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a))return;if(!ht(t,"tasks"))return {hash:a,affectedRows:0};let c=t.all("PRAGMA table_info(tasks)"),u=new Set(c.map(f=>f.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:a,affectedRows:0};let p=t.get(n`
2
+ SELECT count(*) AS count
3
+ FROM tasks
4
+ WHERE status IN ('success', 'failed')
5
+ AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
6
+ `);return {hash:a,affectedRows:p?.count??0}}function Td(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:f})=>f===wd);if(!s)return;let i=ne__default.default.join(e,`${s.tag}.sql`);if(!fs$1.existsSync(i))return;let a=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a))return;if(!ht(t,"threads"))return {hash:a,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(f=>f.name==="created_by_task_id"))return {hash:a,markedPointers:0};let u=ht(t,zo)?`AND NOT EXISTS (
7
+ SELECT 1
8
+ FROM ${zo} AS marked
9
+ WHERE marked.thread_id = current.id
10
+ AND marked.created_by_task_id = current.created_by_task_id
11
+ )`:"",p=t.get(`SELECT count(*) AS count
12
+ FROM threads AS current
13
+ WHERE current.created_by_task_id IS NOT NULL
14
+ AND NOT EXISTS (
15
+ SELECT 1
16
+ FROM sqlite_master
17
+ WHERE type = 'trigger'
18
+ AND name = '${Rd}'
19
+ )
20
+ ${u}`);return {hash:a,markedPointers:p?.count??0}}function fn(t){let{migrate:e}=xt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=xt("drizzle-orm"),r=[ne__default.default.join(__dirname,"../migrations"),ne__default.default.join(__dirname,"migrations"),ne__default.default.join(__dirname,"../../../../drizzle/migrations"),ne__default.default.join(process.cwd(),"drizzle/migrations")],o=r.find(f=>fs$1.existsSync(ne__default.default.join(f,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
21
+ ${r.join(`
22
+ `)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),_d(t,i),s?.cnt&&(kd(t,o),yd(t,o,n),fd(t,o,n));let a=Ed(t,o,n,!!s?.cnt),c=Td(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let p=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(p>0){let f=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${f} (${p} migration${p>1?"s":""} applied).`);}a&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a.hash)&&console.error(`[crewx] Task stop-marker cleanup (${a.affectedRows} success/failed row(s) affected).`),c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function B(t,e){Vo.has(e)||(fn(t),Vo.add(e));}var Vo,pd,gd,Sd,wd,Rd,zo,q=k(()=>{d();Vo=new Set,pd={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT",metadata:"TEXT"};gd={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};Sd="0027_task_stop_scope_cleanup",wd="0033_thread_creator_boundary_guard",Rd="trg_threads_creator_late_fill_guard",zo="thread_creator_unverified";});var Se,hn=k(()=>{d();Se=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var V,C_,N_,mt=k(()=>{d();V=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),pid_started_at:sqliteCore.text("pid_started_at"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at"),workflow_run_id:sqliteCore.text("workflow_run_id"),schedule_id:sqliteCore.text("schedule_id")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:C_,...N_}=drizzleOrm.getTableColumns(V);});var ts=k(()=>{d();mt();sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>V.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var rs=k(()=>{d();mt();sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>V.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Fd,Ud,G,yt=k(()=>{d();hn();Fd="json_extract(metadata, '$.threadTitle.state')",Ud="json_extract(metadata, '$.threadTitle.priority')",G=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Se.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Fd)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Ud))}));});var is=k(()=>{d();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var gr,ds=k(()=>{d();mt();gr=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>V.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>gr.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var us=k(()=>{d();mt();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>V.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var _s=k(()=>{d();yt();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var fs,hs=k(()=>{d();yt();fs=sqliteCore.sqliteTable("thread_branches",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),parent_thread_id:sqliteCore.text("parent_thread_id").notNull().references(()=>G.id),child_thread_id:sqliteCore.text("child_thread_id").notNull().unique().references(()=>G.id,{onDelete:"cascade"}),branch_point_task_id:sqliteCore.text("branch_point_task_id").notNull(),branch_answer_no:sqliteCore.integer("branch_answer_no").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),parent_title:sqliteCore.text("parent_title").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),payload_hash:sqliteCore.text("payload_hash").notNull(),snapshot_version:sqliteCore.integer("snapshot_version").notNull(),carry_json:sqliteCore.text("carry_json").notNull(),carried_turns:sqliteCore.integer("carried_turns").notNull(),carried_chars:sqliteCore.integer("carried_chars").notNull(),carried_truncated:sqliteCore.integer("carried_truncated").notNull().default(0),status:sqliteCore.text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:sqliteCore.text("created_at").notNull(),undone_at:sqliteCore.text("undone_at")},t=>({idx_thread_branches_parent_point:sqliteCore.index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:sqliteCore.unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:sqliteCore.check("thread_branches_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:sqliteCore.check("thread_branches_carried_truncated_ck",drizzleOrm.sql`${t.carried_truncated} IN (0, 1)`)})),sqliteCore.sqliteTable("thread_branch_sources",{branch_id:sqliteCore.text("branch_id").primaryKey().references(()=>fs.id,{onDelete:"cascade"}),source_json:sqliteCore.text("source_json").notNull(),bytes:sqliteCore.integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:sqliteCore.check("thread_branch_sources_bytes_ck",drizzleOrm.sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var ys=k(()=>{d();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var ks=k(()=>{d();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var Rs=k(()=>{d();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Es=k(()=>{d();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var As=k(()=>{d();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var bs=k(()=>{d();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Cs=k(()=>{d();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Os=k(()=>{d();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
23
+ (${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
24
+ OR
25
+ (${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
26
+ )`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var vs=k(()=>{d();sqliteCore.sqliteTable("ui_instance_repins",{instance_id:sqliteCore.text("instance_id").notNull(),from_version:sqliteCore.integer("from_version").notNull(),from_hash:sqliteCore.text("from_hash").notNull(),to_version:sqliteCore.integer("to_version").notNull(),to_hash:sqliteCore.text("to_hash").notNull(),from_revision:sqliteCore.integer("from_revision").notNull(),to_revision:sqliteCore.integer("to_revision"),status:sqliteCore.text("status").notNull(),code:sqliteCore.text("code"),attempts:sqliteCore.integer("attempts").notNull().default(1),first_at:sqliteCore.integer("first_at").notNull(),last_at:sqliteCore.integer("last_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:sqliteCore.check("ui_instance_repins_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:sqliteCore.check("ui_instance_repins_from_version_ck",drizzleOrm.sql`${t.from_version} >= 1`),toVersionCheck:sqliteCore.check("ui_instance_repins_to_version_ck",drizzleOrm.sql`${t.to_version} >= 1`),fromHashCheck:sqliteCore.check("ui_instance_repins_from_hash_ck",drizzleOrm.sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:sqliteCore.check("ui_instance_repins_to_hash_ck",drizzleOrm.sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:sqliteCore.check("ui_instance_repins_from_revision_ck",drizzleOrm.sql`${t.from_revision} >= 0`),toRevisionCheck:sqliteCore.check("ui_instance_repins_to_revision_ck",drizzleOrm.sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:sqliteCore.check("ui_instance_repins_status_ck",drizzleOrm.sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:sqliteCore.check("ui_instance_repins_attempts_ck",drizzleOrm.sql`${t.attempts} >= 1`),datesCheck:sqliteCore.check("ui_instance_repins_dates_ck",drizzleOrm.sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:sqliteCore.check("ui_instance_repins_result_ck",drizzleOrm.sql`(
27
+ (${t.status} = 'applied' AND ${t.code} IS NULL
28
+ AND ${t.to_revision} = ${t.from_revision} + 1)
29
+ OR
30
+ (${t.status} IN ('deferred', 'failed') AND ${t.code} IS NOT NULL
31
+ AND ${t.to_revision} IS NULL)
32
+ )`)}));});var Ps=k(()=>{d();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var Er,Ls=k(()=>{d();Er=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Er.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Er.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var br=k(()=>{d();sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Ms,Fs,Us,qs,Bs,Hs=k(()=>{d();yt();Ms=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Fs=["user","agent","system"],Us=["auto","manual"],qs=["decision","judgment","issue","result","pivot"],Bs=["queued","running","completed","failed"],sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var Gs=k(()=>{d();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var Ws=k(()=>{d();sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var vr,zs=k(()=>{d();yt();hn();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>Se.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),vr=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>Se.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue', 'green', 'lime', 'yellow', 'coral', 'pink', 'indigo', 'sand', 'gray')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>Se.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>vr.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>Se.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>vr.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>Se.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Ys=k(()=>{d();sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(t.workspace_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(t.schedule_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(drizzleOrm.sql`${t.status} = 'running'`)}));});var Js=k(()=>{d();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var Xs=k(()=>{d();sqliteCore.sqliteTable("doc_sync_connect_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref:sqliteCore.text("ref").notNull(),sent_hash:sqliteCore.text("sent_hash").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({requestIdCheck:sqliteCore.check("doc_sync_connect_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) = 36`),accountKeyCheck:sqliteCore.check("doc_sync_connect_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_connect_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_connect_requests_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:sqliteCore.check("doc_sync_connect_requests_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:sqliteCore.check("doc_sync_connect_requests_sent_hash_ck",drizzleOrm.sql`length(${t.sent_hash}) = 71 AND substr(${t.sent_hash}, 1, 7) = 'sha256:' AND substr(${t.sent_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),createdAtCheck:sqliteCore.check("doc_sync_connect_requests_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),connectUnique:sqliteCore.uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var Qs=k(()=>{d();sqliteCore.sqliteTable("doc_sync_links",{doc_id:sqliteCore.text("doc_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),root_segments:sqliteCore.text("root_segments").notNull(),ref:sqliteCore.text("ref").notNull(),cloud_ref:sqliteCore.text("cloud_ref").notNull(),connection_kind:sqliteCore.text("connection_kind").$type().notNull().default("document"),app_grant_id:sqliteCore.text("app_grant_id"),app_grant_generation:sqliteCore.integer("app_grant_generation"),app_scope_version:sqliteCore.text("app_scope_version"),origin:sqliteCore.text("origin").notNull().default("own"),sync_state:sqliteCore.text("sync_state").notNull().default("ok"),end_reason:sqliteCore.text("end_reason"),file_state:sqliteCore.text("file_state").notNull().default("present"),synced_revision:sqliteCore.integer("synced_revision").notNull(),synced_hash:sqliteCore.text("synced_hash").notNull(),synced_at:sqliteCore.integer("synced_at").notNull(),file_dev_ino:sqliteCore.text("file_dev_ino"),conflict_revision:sqliteCore.integer("conflict_revision"),conflict_hash:sqliteCore.text("conflict_hash"),conflict_at:sqliteCore.integer("conflict_at"),remote_revision:sqliteCore.integer("remote_revision"),remote_checked_at:sqliteCore.integer("remote_checked_at"),published_revision:sqliteCore.integer("published_revision"),bundle_sha256:sqliteCore.text("bundle_sha256"),missing_since:sqliteCore.integer("missing_since"),connected_at:sqliteCore.integer("connected_at").notNull(),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({docIdCheck:sqliteCore.check("doc_sync_links_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_sync_links_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_links_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_links_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:sqliteCore.check("doc_sync_links_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:sqliteCore.check("doc_sync_links_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:sqliteCore.check("doc_sync_links_cloud_ref_ck",drizzleOrm.sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:sqliteCore.check("doc_sync_links_origin_ck",drizzleOrm.sql`${t.origin} IN ('own', 'received')`),syncStateCheck:sqliteCore.check("doc_sync_links_sync_state_ck",drizzleOrm.sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:sqliteCore.check("doc_sync_links_end_reason_ck",drizzleOrm.sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:sqliteCore.check("doc_sync_links_ended_reason_ck",drizzleOrm.sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:sqliteCore.check("doc_sync_links_file_state_ck",drizzleOrm.sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:sqliteCore.check("doc_sync_links_synced_revision_ck",drizzleOrm.sql`${t.synced_revision} >= 0`),syncedHashCheck:sqliteCore.check("doc_sync_links_synced_hash_ck",drizzleOrm.sql`length(${t.synced_hash}) = 71 AND substr(${t.synced_hash}, 1, 7) = 'sha256:' AND substr(${t.synced_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),connectedAtCheck:sqliteCore.check("doc_sync_links_connected_at_ck",drizzleOrm.sql`${t.connected_at} >= 0`),createdAtCheck:sqliteCore.check("doc_sync_links_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("doc_sync_links_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:sqliteCore.uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(drizzleOrm.sql`${t.sync_state} <> 'ended'`),accountStateIdx:sqliteCore.index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:sqliteCore.index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id),connectionKindAccountIdx:sqliteCore.index("doc_sync_links_connection_account_idx").on(t.account_key,t.connection_kind,t.app_id)}));});var Zs=k(()=>{d();sqliteCore.sqliteTable("doc_create_dispatches",{dispatch_id:sqliteCore.text("dispatch_id").primaryKey().notNull(),request_id:sqliteCore.text("request_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),source:sqliteCore.text("source").$type().notNull(),dispatched_at:sqliteCore.integer("dispatched_at").notNull()},t=>({dispatchIdCheck:sqliteCore.check("doc_create_dispatches_id_ck",drizzleOrm.sql`length(${t.dispatch_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("doc_create_dispatches_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_create_dispatches_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),sourceCheck:sqliteCore.check("doc_create_dispatches_source_ck",drizzleOrm.sql`${t.source} IN ('human', 'app_create', 'app_reattach')`),timestampCheck:sqliteCore.check("doc_create_dispatches_time_ck",drizzleOrm.sql`${t.dispatched_at} >= 0`),accountDispatchedIndex:sqliteCore.index("doc_create_dispatches_account_time_idx").on(t.account_key,t.dispatched_at)}));});var Rt,ou,ei=k(()=>{d();Rt=sqliteCore.sqliteTable("app_sync_bindings",{binding_id:sqliteCore.text("binding_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),root_segments:sqliteCore.text("root_segments").notNull(),grant_id:sqliteCore.text("grant_id"),grant_generation:sqliteCore.integer("grant_generation"),scope_version:sqliteCore.text("scope_version"),status:sqliteCore.text("status").notNull().default("local_only"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({bindingIdCheck:sqliteCore.check("app_sync_bindings_binding_id_ck",drizzleOrm.sql`length(${t.binding_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_bindings_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("app_sync_bindings_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("app_sync_bindings_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),rootSegmentsCheck:sqliteCore.check("app_sync_bindings_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),grantGenerationCheck:sqliteCore.check("app_sync_bindings_generation_ck",drizzleOrm.sql`${t.grant_generation} IS NULL OR ${t.grant_generation} >= 1`),statusCheck:sqliteCore.check("app_sync_bindings_status_ck",drizzleOrm.sql`${t.status} IN ('local_only', 'consent_required', 'checking', 'syncing', 'synced', 'partial', 'offline', 'revoked', 'unavailable', 'stopping')`),timestampsCheck:sqliteCore.check("app_sync_bindings_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),ownerAppUnique:sqliteCore.uniqueIndex("app_sync_bindings_owner_app_uq").on(t.account_key,t.app_id)})),sqliteCore.sqliteTable("app_sync_creation_jobs",{job_id:sqliteCore.text("job_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),request_id:sqliteCore.text("request_id").notNull(),fingerprint:sqliteCore.text("fingerprint").notNull(),operation_kind:sqliteCore.text("operation_kind").$type().notNull().default("create"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull().default("waiting"),attempts:sqliteCore.integer("attempts").notNull().default(0),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({jobIdCheck:sqliteCore.check("app_sync_creation_jobs_job_id_ck",drizzleOrm.sql`length(${t.job_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("app_sync_creation_jobs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),generationCheck:sqliteCore.check("app_sync_creation_jobs_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),refCheck:sqliteCore.check("app_sync_creation_jobs_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),documentIdCheck:sqliteCore.check("app_sync_creation_jobs_document_id_ck",drizzleOrm.sql`${t.document_id} IS NULL OR length(${t.document_id}) BETWEEN 1 AND 128`),operationKindCheck:sqliteCore.check("app_sync_creation_jobs_operation_kind_ck",drizzleOrm.sql`${t.operation_kind} IN ('create', 'reattach')`),reattachDocumentCheck:sqliteCore.check("app_sync_creation_jobs_reattach_document_ck",drizzleOrm.sql`${t.operation_kind} != 'reattach' OR ${t.document_id} IS NOT NULL`),fingerprintCheck:sqliteCore.check("app_sync_creation_jobs_fingerprint_ck",drizzleOrm.sql`length(${t.fingerprint}) = 71 AND substr(${t.fingerprint}, 1, 7) = 'sha256:' AND substr(${t.fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),statusCheck:sqliteCore.check("app_sync_creation_jobs_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'completed', 'failed', 'conflict', 'blocked', 'invalidated', 'deleted')`),attemptsCheck:sqliteCore.check("app_sync_creation_jobs_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),timestampsCheck:sqliteCore.check("app_sync_creation_jobs_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Rt.binding_id]}).onDelete("cascade"),requestIdUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_request_id_uq").on(t.request_id),activeFingerprintUnique:sqliteCore.uniqueIndex("app_sync_creation_jobs_active_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.fingerprint,t.operation_kind).where(drizzleOrm.sql`${t.status} IN ('waiting', 'processing')`),runnableIndex:sqliteCore.index("app_sync_creation_jobs_runnable_idx").on(t.binding_id,t.status,t.next_attempt_at),accountIndex:sqliteCore.index("app_sync_creation_jobs_account_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_results",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),ref:sqliteCore.text("ref").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),source_fingerprint:sqliteCore.text("source_fingerprint"),synced_fingerprint:sqliteCore.text("synced_fingerprint"),document_id:sqliteCore.text("document_id"),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),next_attempt_at:sqliteCore.integer("next_attempt_at").notNull().default(0),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resultAccountCheck:sqliteCore.check("app_sync_results_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resultRefCheck:sqliteCore.check("app_sync_results_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),resultGenerationCheck:sqliteCore.check("app_sync_results_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),resultStatusCheck:sqliteCore.check("app_sync_results_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'synced', 'failed', 'conflict', 'blocked', 'excluded', 'deleted')`),resultAttemptsCheck:sqliteCore.check("app_sync_results_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0`),resultBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Rt.binding_id]}).onDelete("cascade"),resultIdentityUnique:sqliteCore.uniqueIndex("app_sync_results_binding_ref_uq").on(t.binding_id,t.ref),resultAccountIndex:sqliteCore.index("app_sync_results_account_status_idx").on(t.account_key,t.status)})),sqliteCore.sqliteTable("app_sync_control_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),kind:sqliteCore.text("kind").notNull(),state:sqliteCore.text("state").notNull().default("pending"),grant_id:sqliteCore.text("grant_id"),generation:sqliteCore.integer("generation"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull(),resolved_at:sqliteCore.integer("resolved_at"),resolution:sqliteCore.text("resolution"),resolution_id:sqliteCore.text("resolution_id")},t=>({requestIdCheck:sqliteCore.check("app_sync_control_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),requestAccountCheck:sqliteCore.check("app_sync_control_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),requestAppCheck:sqliteCore.check("app_sync_control_requests_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),requestWorkspaceCheck:sqliteCore.check("app_sync_control_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),rootFingerprintCheck:sqliteCore.check("app_sync_control_requests_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),requestKindCheck:sqliteCore.check("app_sync_control_requests_kind_ck",drizzleOrm.sql`${t.kind} IN ('connect', 'revoke')`),requestStateCheck:sqliteCore.check("app_sync_control_requests_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'confirmed', 'failed')`),revokeGrantCheck:sqliteCore.check("app_sync_control_requests_revoke_grant_ck",drizzleOrm.sql`${t.kind} != 'revoke' OR (${t.grant_id} IS NOT NULL AND ${t.generation} >= 1)`),requestResolutionCheck:sqliteCore.check("app_sync_control_requests_resolution_ck",drizzleOrm.sql`(${t.state} IN ('pending', 'unknown') AND ${t.resolved_at} IS NULL AND ${t.resolution} IS NULL AND ${t.resolution_id} IS NULL) OR (${t.state} IN ('confirmed', 'failed') AND ${t.resolved_at} IS NOT NULL AND ${t.resolution} IN ('remote', 'human') AND length(${t.resolution_id}) BETWEEN 1 AND 128)`),generationCheck:sqliteCore.check("app_sync_control_requests_generation_ck",drizzleOrm.sql`${t.generation} IS NULL OR ${t.generation} >= 1`),timestampsCheck:sqliteCore.check("app_sync_control_requests_timestamps_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),bindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Rt.binding_id]}).onDelete("cascade"),unresolvedPerBinding:sqliteCore.uniqueIndex("app_sync_control_requests_one_pending_uq").on(t.binding_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`),accountLookup:sqliteCore.index("app_sync_control_requests_account_idx").on(t.account_key,t.app_id,t.state)})),sqliteCore.sqliteTable("app_sync_deleted_refs",{account_key:sqliteCore.text("account_key").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref_sha256:sqliteCore.text("ref_sha256").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({deletedAccountCheck:sqliteCore.check("app_sync_deleted_refs_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),deletedAppCheck:sqliteCore.check("app_sync_deleted_refs_app_id_ck",drizzleOrm.sql`${t.app_id} = 'workout-log'`),deletedHashCheck:sqliteCore.check("app_sync_deleted_refs_hash_ck",drizzleOrm.sql`length(${t.ref_sha256}) = 64 AND ${t.ref_sha256} NOT GLOB '*[^0-9a-f]*'`),deletedIdentityUnique:sqliteCore.uniqueIndex("app_sync_deleted_refs_identity_uq").on(t.account_key,t.app_id,t.ref_sha256)})),sqliteCore.sqliteTable("app_sync_discovery_checkpoints",{binding_id:sqliteCore.text("binding_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),last_cycle_started_at:sqliteCore.integer("last_cycle_started_at"),cycle_started_at:sqliteCore.integer("cycle_started_at"),docs_cursor:sqliteCore.text("docs_cursor"),docs_complete:sqliteCore.integer("docs_complete").notNull().default(0),deleted_cursor:sqliteCore.text("deleted_cursor"),deleted_complete:sqliteCore.integer("deleted_complete").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({checkpointAccountCheck:sqliteCore.check("app_sync_discovery_checkpoints_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),checkpointRootCheck:sqliteCore.check("app_sync_discovery_checkpoints_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),checkpointGenerationCheck:sqliteCore.check("app_sync_discovery_checkpoints_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),checkpointScopeCheck:sqliteCore.check("app_sync_discovery_checkpoints_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),checkpointDocsCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_docs_complete_ck",drizzleOrm.sql`${t.docs_complete} IN (0, 1)`),checkpointDeletedCompleteCheck:sqliteCore.check("app_sync_discovery_checkpoints_deleted_complete_ck",drizzleOrm.sql`${t.deleted_complete} IN (0, 1)`),checkpointTimeCheck:sqliteCore.check("app_sync_discovery_checkpoints_time_ck",drizzleOrm.sql`${t.updated_at} >= 0 AND (${t.last_cycle_started_at} IS NULL OR ${t.last_cycle_started_at} >= 0) AND (${t.cycle_started_at} IS NULL OR ${t.cycle_started_at} >= 0)`),checkpointBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Rt.binding_id]}).onDelete("cascade"),checkpointAccountIndex:sqliteCore.index("app_sync_discovery_checkpoints_account_idx").on(t.account_key,t.grant_id,t.grant_generation)})),sqliteCore.sqliteTable("app_sync_pending_discoveries",{binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),listed_revision:sqliteCore.integer("listed_revision").notNull(),listed_fingerprint:sqliteCore.text("listed_fingerprint").notNull(),app_grant_generation:sqliteCore.integer("app_grant_generation").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),needs_reconcile:sqliteCore.integer("needs_reconcile").notNull().default(0),status:sqliteCore.text("status").notNull().default("waiting"),error_code:sqliteCore.text("error_code"),attempts:sqliteCore.integer("attempts").notNull().default(0),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({pendingAccountCheck:sqliteCore.check("app_sync_pending_discoveries_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),pendingRefCheck:sqliteCore.check("app_sync_pending_discoveries_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),pendingDocCheck:sqliteCore.check("app_sync_pending_discoveries_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),pendingRevisionCheck:sqliteCore.check("app_sync_pending_discoveries_revision_ck",drizzleOrm.sql`${t.listed_revision} >= 0`),pendingFingerprintCheck:sqliteCore.check("app_sync_pending_discoveries_fingerprint_ck",drizzleOrm.sql`length(${t.listed_fingerprint}) = 71 AND substr(${t.listed_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.listed_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),pendingGenerationCheck:sqliteCore.check("app_sync_pending_discoveries_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1 AND ${t.app_grant_generation} >= 1`),pendingFlagsCheck:sqliteCore.check("app_sync_pending_discoveries_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.needs_reconcile} IN (0, 1)`),pendingStatusCheck:sqliteCore.check("app_sync_pending_discoveries_status_ck",drizzleOrm.sql`${t.status} IN ('waiting', 'processing', 'failed', 'invalidated')`),pendingAttemptsCheck:sqliteCore.check("app_sync_pending_discoveries_attempts_ck",drizzleOrm.sql`${t.attempts} >= 0 AND ${t.updated_at} >= 0`),pendingBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Rt.binding_id]}).onDelete("cascade"),pendingIdentityUnique:sqliteCore.uniqueIndex("app_sync_pending_discoveries_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref),pendingRunnableIdx:sqliteCore.index("app_sync_pending_discoveries_runnable_idx").on(t.binding_id,t.grant_id,t.grant_generation,t.status,t.ref)})),ou=sqliteCore.sqliteTable("app_sync_conflicts",{conflict_id:sqliteCore.text("conflict_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),grant_id:sqliteCore.text("grant_id").notNull(),grant_generation:sqliteCore.integer("grant_generation").notNull(),scope_version:sqliteCore.text("scope_version").notNull(),ref:sqliteCore.text("ref").notNull(),doc_id:sqliteCore.text("doc_id").notNull(),local_version:sqliteCore.text("local_version").notNull(),local_fingerprint:sqliteCore.text("local_fingerprint").notNull(),baseline_revision:sqliteCore.integer("baseline_revision"),baseline_fingerprint:sqliteCore.text("baseline_fingerprint"),remote_revision:sqliteCore.integer("remote_revision").notNull(),remote_fingerprint:sqliteCore.text("remote_fingerprint").notNull(),needs_reattach:sqliteCore.integer("needs_reattach").notNull().default(0),vault_handle:sqliteCore.text("vault_handle"),preservation_status:sqliteCore.text("preservation_status").notNull().default("pending"),state:sqliteCore.text("state").notNull().default("open"),superseded_by:sqliteCore.text("superseded_by"),resolution_request_id:sqliteCore.text("resolution_request_id"),resolution_choice:sqliteCore.text("resolution_choice"),cleanup_pending:sqliteCore.integer("cleanup_pending").notNull().default(0),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({conflictIdCheck:sqliteCore.check("app_sync_conflicts_id_ck",drizzleOrm.sql`length(${t.conflict_id}) BETWEEN 1 AND 128`),conflictAccountCheck:sqliteCore.check("app_sync_conflicts_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),conflictRootCheck:sqliteCore.check("app_sync_conflicts_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),conflictGenerationCheck:sqliteCore.check("app_sync_conflicts_generation_ck",drizzleOrm.sql`${t.grant_generation} >= 1`),conflictScopeCheck:sqliteCore.check("app_sync_conflicts_scope_ck",drizzleOrm.sql`${t.scope_version} = 'workout-log.records.v1'`),conflictRefCheck:sqliteCore.check("app_sync_conflicts_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),conflictDocCheck:sqliteCore.check("app_sync_conflicts_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),conflictLocalVersionCheck:sqliteCore.check("app_sync_conflicts_local_version_ck",drizzleOrm.sql`length(${t.local_version}) BETWEEN 1 AND 256 AND instr(${t.local_version}, '/') = 0 AND instr(${t.local_version}, char(92)) = 0`),conflictLocalFingerprintCheck:sqliteCore.check("app_sync_conflicts_local_fingerprint_ck",drizzleOrm.sql`length(${t.local_fingerprint}) = 71 AND substr(${t.local_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.local_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictBaselineCheck:sqliteCore.check("app_sync_conflicts_baseline_ck",drizzleOrm.sql`(${t.baseline_revision} IS NULL) = (${t.baseline_fingerprint} IS NULL) AND (${t.baseline_revision} IS NULL OR (${t.baseline_revision} >= 0 AND length(${t.baseline_fingerprint}) = 71 AND substr(${t.baseline_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.baseline_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'))`),conflictRemoteCheck:sqliteCore.check("app_sync_conflicts_remote_ck",drizzleOrm.sql`${t.remote_revision} >= 0 AND length(${t.remote_fingerprint}) = 71 AND substr(${t.remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),conflictFlagsCheck:sqliteCore.check("app_sync_conflicts_flags_ck",drizzleOrm.sql`${t.needs_reattach} IN (0, 1) AND ${t.cleanup_pending} IN (0, 1)`),conflictHandleCheck:sqliteCore.check("app_sync_conflicts_handle_ck",drizzleOrm.sql`${t.vault_handle} IS NULL OR (length(${t.vault_handle}) BETWEEN 1 AND 256 AND instr(${t.vault_handle}, '/') = 0 AND instr(${t.vault_handle}, char(92)) = 0)`),conflictPreservationCheck:sqliteCore.check("app_sync_conflicts_preservation_ck",drizzleOrm.sql`${t.preservation_status} IN ('pending', 'ready', 'failed')`),conflictStateCheck:sqliteCore.check("app_sync_conflicts_state_ck",drizzleOrm.sql`${t.state} IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both', 'purging')`),conflictArchiveLifecycleCheck:sqliteCore.check("app_sync_conflicts_archive_lifecycle_ck",drizzleOrm.sql`(
33
+ (${t.preservation_status} IN ('pending', 'failed') AND ${t.vault_handle} IS NULL
34
+ AND ${t.state} IN ('open', 'purging') AND ${t.cleanup_pending} = 0
35
+ AND (${t.state} = 'purging' OR ${t.superseded_by} IS NULL))
36
+ OR (${t.preservation_status} = 'ready' AND (
37
+ (${t.state} IN ('open', 'resolving', 'superseded') AND ${t.vault_handle} IS NOT NULL AND ${t.cleanup_pending} = 0)
38
+ OR (${t.state} = 'kept_both' AND ${t.resolution_request_id} IS NOT NULL
39
+ AND ${t.vault_handle} IS NOT NULL AND ${t.cleanup_pending} = 0)
40
+ OR (${t.state} = 'purging' AND ${t.cleanup_pending} = 0)
41
+ OR (${t.state} = 'resolved' AND ${t.resolution_request_id} IS NOT NULL
42
+ AND ((${t.cleanup_pending} = 1 AND ${t.vault_handle} IS NOT NULL)
43
+ OR (${t.cleanup_pending} = 0 AND ${t.vault_handle} IS NULL)))
44
+ ))
45
+ )`),conflictSupersededCheck:sqliteCore.check("app_sync_conflicts_superseded_ck",drizzleOrm.sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:sqliteCore.check("app_sync_conflicts_resolution_ck",drizzleOrm.sql`(${t.resolution_request_id} IS NULL AND ${t.resolution_choice} IS NULL) OR (length(${t.resolution_request_id}) BETWEEN 1 AND 128 AND ${t.resolution_choice} IN ('keep_local', 'use_cloud', 'keep_both'))`),conflictTimeCheck:sqliteCore.check("app_sync_conflicts_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:sqliteCore.foreignKey({columns:[t.binding_id],foreignColumns:[Rt.binding_id]}).onDelete("cascade"),conflictIdentityUnique:sqliteCore.uniqueIndex("app_sync_conflicts_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref,t.local_version,t.remote_revision,t.remote_fingerprint),conflictLookup:sqliteCore.index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteCore.sqliteTable("app_sync_conflict_resolutions",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),conflict_id:sqliteCore.text("conflict_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),choice:sqliteCore.text("choice").notNull(),expected_local_version:sqliteCore.text("expected_local_version").notNull(),expected_remote_revision:sqliteCore.integer("expected_remote_revision").notNull(),expected_remote_fingerprint:sqliteCore.text("expected_remote_fingerprint").notNull(),state:sqliteCore.text("state").notNull().default("pending"),error_code:sqliteCore.text("error_code"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:sqliteCore.check("app_sync_conflict_resolutions_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:sqliteCore.check("app_sync_conflict_resolutions_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:sqliteCore.check("app_sync_conflict_resolutions_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:sqliteCore.check("app_sync_conflict_resolutions_choice_ck",drizzleOrm.sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:sqliteCore.check("app_sync_conflict_resolutions_local_version_ck",drizzleOrm.sql`length(${t.expected_local_version}) BETWEEN 1 AND 256 AND instr(${t.expected_local_version}, '/') = 0 AND instr(${t.expected_local_version}, char(92)) = 0`),resolutionRemoteCheck:sqliteCore.check("app_sync_conflict_resolutions_remote_ck",drizzleOrm.sql`${t.expected_remote_revision} >= 0 AND length(${t.expected_remote_fingerprint}) = 71 AND substr(${t.expected_remote_fingerprint}, 1, 7) = 'sha256:' AND substr(${t.expected_remote_fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),resolutionStateCheck:sqliteCore.check("app_sync_conflict_resolutions_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:sqliteCore.check("app_sync_conflict_resolutions_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:sqliteCore.foreignKey({columns:[t.conflict_id],foreignColumns:[ou.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:sqliteCore.index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:sqliteCore.uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(drizzleOrm.sql`${t.state} IN ('pending', 'unknown')`)})),sqliteCore.sqliteTable("app_sync_account_data_purges",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),binding_id:sqliteCore.text("binding_id").notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),root_fingerprint:sqliteCore.text("root_fingerprint").notNull(),human_identity:sqliteCore.text("human_identity").notNull(),state:sqliteCore.text("state").notNull().default("pending"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({purgeRequestIdCheck:sqliteCore.check("app_sync_account_data_purges_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:sqliteCore.check("app_sync_account_data_purges_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:sqliteCore.check("app_sync_account_data_purges_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:sqliteCore.check("app_sync_account_data_purges_root_fingerprint_ck",drizzleOrm.sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:sqliteCore.check("app_sync_account_data_purges_human_identity_ck",drizzleOrm.sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:sqliteCore.check("app_sync_account_data_purges_state_ck",drizzleOrm.sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:sqliteCore.check("app_sync_account_data_purges_time_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:sqliteCore.index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var ti=k(()=>{d();sqliteCore.sqliteTable("route_states",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),config_revision:sqliteCore.text("config_revision").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk_route_state_workspace:sqliteCore.primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteCore.sqliteTable("route_sticky_bindings",{workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({uniq_route_sticky_thread:sqliteCore.uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:sqliteCore.index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteCore.sqliteTable("route_decisions",{id:sqliteCore.text("id").primaryKey(),workspace_key:sqliteCore.text("workspace_key").notNull().default("legacy"),route_id:sqliteCore.text("route_id").notNull(),task_id:sqliteCore.text("task_id").notNull(),config_revision:sqliteCore.text("config_revision").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),provider:sqliteCore.text("provider").notNull(),model:sqliteCore.text("model").notNull(),reason:sqliteCore.text("reason").notNull(),eligible_ids:sqliteCore.text("eligible_ids").notNull(),blocked_causes:sqliteCore.text("blocked_causes").notNull(),link_errors:sqliteCore.text("link_errors").notNull(),created_at:sqliteCore.text("created_at").notNull()},t=>({uniq_route_task_decision:sqliteCore.uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:sqliteCore.index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteCore.sqliteTable("route_quota_observations",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),model:sqliteCore.text("model"),status:sqliteCore.text("status",{enum:["ok","blocked"]}).notNull(),source:sqliteCore.text("source").notNull(),reset_at:sqliteCore.text("reset_at"),observed_at:sqliteCore.text("observed_at").notNull()},t=>({uniq_route_quota_observation:sqliteCore.uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:sqliteCore.index("idx_route_quota_observations_reset").on(t.reset_at)}));});var F=k(()=>{d();hn();mt();ts();rs();yt();is();ds();us();_s();hs();ys();ks();Rs();Es();As();bs();Cs();Os();vs();Ps();Ls();br();Hs();Gs();Ws();zs();Ys();Js();Xs();Qs();Zs();ei();ti();});var Fr=k(()=>{d();P();M();q();L();F();});var Et,Tt=k(()=>{d();Et=["workflow_card","workflow_ui_instance","workflow_run"];});var qr=k(()=>{d();});var On=k(()=>{d();qr();qr();});var Br=k(()=>{d();});var Hr=k(()=>{d();});var vn=k(()=>{d();P();M();q();L();F();});var ai=k(()=>{d();});var pu,j,Ve=k(()=>{d();pu=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),j=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=pu.has(this.code)?"config":o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs,this.settingReason=o?.settingReason,this.replacementModel=o?.replacementModel,this.providerReason=o?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var Jt,$r=k(()=>{d();Ve();Jt=class extends j{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Dn(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${ie}]`),e=gu(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${ie}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,ie),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,ie),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,ie),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,ie),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,ie),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,ie),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,ie),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,ie),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,ie),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${ie}${r}${ie}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${ie}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,di),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,di),e=e.replace(/[\r\n]{3,}/g,`
46
+
47
+ `).trim(),_u(e,1024)||void 0}function _u(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",o=0;for(let s of t){let i=n.encode(s).byteLength;if(o+i>e)break;r+=s,o+=i;}return r}function gu(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,o;for(;(o=e.exec(t))!==null;){if(o.index<r)continue;let s=o.index+o[0].length,i=fu(t,s),a=i>=0?i:t.indexOf(`
48
+ `,s)>=0?t.indexOf(`
49
+ `,s):t.length;n+=t.slice(r,o.index),n+=`[HTTP BODY ${ie}]`,r=a;}return n+t.slice(r)}function fu(t,e){let n=t[e];if(n==='"'||n==="'")return hu(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],o,s=false;for(let i=e;i<t.length;i+=1){let a=t[i];if(o){s?s=false:a==="\\"?s=true:a===o&&(o=void 0);continue}if(a==='"'||a==="'"){o=a;continue}if(a==="{"||a==="["){r.push(a);continue}if(a!=="}"&&a!=="]")continue;let c=r.pop();if(a==="}"&&c!=="{"||a==="]"&&c!=="[")return -1;if(r.length===0)return i+1}return -1}function hu(t,e,n){let r=false;for(let o=e+1;o<t.length;o+=1){let s=t[o];if(r)r=false;else if(s==="\\")r=true;else if(s===n)return o+1}return -1}var ie,di,Gr=k(()=>{d();ie="[REDACTED]",di="[PATH]";});function Wr(t){if(!Pn(t)||t.type!=="item.started"||!ui(t)||!ci(t))return false;let e=t.item;return !Pn(e)||!ui(e)||!ci(e)||!jr(e.id)?false:e.type==="web_search"?e.query===""&&Pn(e.action)&&e.action.type==="other":e.type==="file_change"?e.status!=="in_progress"||!Array.isArray(e.changes)||e.changes.length===0?false:e.changes.every(n=>Pn(n)&&jr(n.path)&&jr(n.kind)):false}function Pn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function li(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function jr(t){return typeof t=="string"&&t.trim().length>0}function ci(t){return !li(t,"status")||t.status==="in_progress"}function ui(t){for(let e of ["error","errors","isError","is_error"])if(li(t,e))return false;return true}var Kr=k(()=>{d();});function At(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function It(t){return typeof t=="string"&&t.trim().length>0}function Vr(t){return typeof t=="string"?t.trim().length>0:At(t)?It(t.code)||It(t.message)||It(t.error)||It(t.reason):false}function Xt(t){let e;try{e=JSON.parse(t);}catch{return}if(At(e))switch(e.event){case "init":return At(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!At(e.step_update))return;let n=e.step_update;return !It(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!It(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return At(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=Vr(e)?e:e.error;return Vr(n)?{kind:"agy_error",envelope:e,error:n}:void 0}default:return (e.status==="SUCCESS"||e.status==="ERROR")&&typeof e.response=="string"&&(typeof e.conversation_id=="string"||Vr(e.error)||At(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function pi(t){return Xt(t)!==void 0}function bt(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=Xt(n);r&&e.push(r);}return e}var xn=k(()=>{d();});function mu(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=typeof r.type=="string"?r.type:"",s=e?Au[e]:void 0;return s?s(r,o):o?Object.values(gi).some(i=>i(r,o)):false}function dt(t,e){let n=t.split(`
50
+ `).filter(r=>r.trim());return n.length===0?false:n.every(r=>mu(r,e))}function ce(t){return typeof t=="object"&&t!==null}function _i(t,e){if(e==="assistant"||e==="user"){let n=t.message;return ce(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||ce(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?ce(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function yu(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:_i(t,e)}function ku(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||ce(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return ce(n)&&typeof n.type=="string"}return false}function Su(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||ce(t.part);if(e==="text"||e==="tool_use")return ce(t.part);if(e==="error"){let n=t.error;return ce(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function wu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||ce(t.part)||e==="result"&&typeof t.result=="string")}function Ru(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?ce(t.data):e==="result"?typeof t.result=="string":false}function Eu(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function Tu(t,e){return e==="available_commands"?ce(t.tools)||ce(t.commands):e==="usage"?ce(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||ce(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var gi,Au,Qt=k(()=>{d();Kr();xn();gi={claude:_i,codex:ku,opencode:Su,copilot:Ru,gemini:Eu},Au={...gi,claude:yu,opencode:wu,grok:Tu,antigravity:t=>pi(JSON.stringify(t))};});function Pe(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function xe(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var Ct=k(()=>{d();});function Cu(t){let e=Nu(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>vu(s.value)),r=Ou(e);return {result:n.length===1&&n[0].index===r?Du(n[0].line.value):null,resultPreview:Lu(e,n),hasReservedLine:n.length>0}}function Le(t,e){let n=Cu(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Nu(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
51
+ `&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
52
+ `?`\r
53
+ `:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Ou(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function vu(t){return t.trimStart().startsWith(Iu)}function Du(t){let e=t.trim();if(!e.startsWith(fi)||!e.endsWith("]]"))return null;let n=e.slice(fi.length,-2);if(!n)return null;try{return Pu(JSON.parse(n))}catch{return null}}function Pu(t){return xu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function xu(t){if(!Mu(t)||Object.keys(t).some(r=>!bu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?hi(t.taskId)&&hi(t.agentId):t.isError===true}function Lu(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function hi(t){return typeof t=="string"&&t.trim().length>0}function Mu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fi,Iu,bu,Nt=k(()=>{d();fi="[[crewx:delegation-result ",Iu="[[crewx:delegation-result",bu=new Set(["schema","taskId","agentId","isError"]);});function Me(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var Ot=k(()=>{d();});var mi,Ln,zr,Mn=k(()=>{d();mi=["none","minimal","low","medium","high","xhigh","max","ultra"],Ln={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},zr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(zr).map(([t,e])=>[t,e.models]));});function Yr(t){return Uu[t]??t}function Bu(t){return qu.get(t)??t}function Jr(t){if(!t)return {};let e=$u.get(t);return e?{...e}:{model:t}}function Xr(t,e){return t==="antigravity"||t==="cli/antigravity"?Jr(e):e===void 0?{}:{model:Bu(e)}}var Fu,Uu,qu,Hu,$u,Zt=k(()=>{d();Fu=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],Uu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};qu=new Map(Fu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Hu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],$u=new Map(Hu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function ju(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function ze(t){return en(t).models}function en(t){let e=Gu[t],n=zr[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??ju()}function tn(t,e){let n=en(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Xr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Qr(t){return en(t).modelOverrides}function yi(){return ze("claude")}function ki(){return ze("codex")}function Si(){return ze("copilot")}function wi(){return ze("antigravity")}var Gu,Ye=k(()=>{d();Mn();On();Zt();Gu={};});function Ri(t){return Vu[t]??t}var Vu,Ei=k(()=>{d();Ye();Zt();Vu={auto:"default"};});function Zr(t,e){return (Ln[t]??[]).includes(e)}function ct(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return zu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ti(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ai(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ii(t){return !t||!Zr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function bi(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Ri(t);return e.has(n)?["--permission-mode",n]:[]}function Ci(t){return t?Zr("claude",t)?["--effort",t]:[]:[]}function Ni(t){if(!t)return [];switch(Yr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Oi(t){return t?Zr("antigravity",t)?["--effort",t]:[]:[]}var zu,nn=k(()=>{d();Ei();Zt();Mn();zu=new Set(mi);});function Yu(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function Ju(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,c=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:c}}function Xu(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function vi(t){let e=new Map,n;for(let s of t.split(`
54
+ `))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,c=a?.id,u=a?.usage;if(typeof c!="string"||!u)continue;let p=Number(u.input_tokens??0),f=Number(u.cache_read_input_tokens??0);e.set(c,{inputTokens:p+f,cachedInputTokens:f});let _=a?.model;typeof _=="string"&&_&&(n=_);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function rn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
55
+ `))if(r.trim())try{let o=JSON.parse(r),s=Xu(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Yu(o)??Ju(o);i&&(e=i);}catch{}return n||(e??void 0)}var on=k(()=>{d();});function $e(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var ut=k(()=>{d();});var Fn,Di=k(()=>{d();Fn=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function xi(t){return t==="all"?[...Pi,...Qu]:Pi}function Li(t){return xi(t).map(e=>`Bash(${e} *)`)}function Mi(t){return xi(t).map(e=>`command(${e})`)}var Pi,Qu,eo=k(()=>{d();Pi=["crewx memory","crewx search","crewx doc","crewx notify"],Qu=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function Fi(t){let e=t.split(`
56
+ `).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Ui(t){let e=t.split(`
57
+ `).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Gi(t){let e=vt(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=ol(t);return n?`Claude rate limit: ${n}`:"Claude rate limit"}if(t.type==="result"&&t.is_error===true){let n=typeof t.result=="string"?t.result:"";if(sl(n))return `Claude rate limit: ${n}`}}function tl(t){for(let e of t.split(`
58
+ `)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=vt(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function nl(t){let e=vt(t);if(e?.type!=="rate_limit_event")return;let n=vt(vt(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=qi(n.five_hour),o=qi(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function qi(t){let e=vt(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Bi(t){if(t?.is_error===true)return Dn(t.result)}function rl(t){let e=Gi(t);if(e)return e;if(t.type!=="result"||t.is_error!==true)return;let n=typeof t.result=="string"?t.result:"";if(n.trim())return n;let r=typeof t.subtype=="string"?t.subtype:"unknown",o=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${o})`}function ol(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
59
+
60
+ `):""}function sl(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function $i(t){return t.replace(/\s+/g," ").trim()}function il(t,e){let n=t?.description;if(typeof n!="string")return;let r=$i(n);if(!r||r===$i(e))return;if(r.length<=Hi)return r;let o=r.slice(0,Hi-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function al(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=Me(s);if(r==="Bash"&&Pe(i))return xe(t,i,o);let a=il(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...a?{toolTitle:a}:{}}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
61
+ `):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...Le(i,r)}}return null}var Zu,el,to,Hi,no=k(()=>{d();$r();Ve();Gr();Qt();Ct();Nt();Ot();nn();Ye();on();ut();Di();eo();Zu=new Set(["tool_progress"]),el="cli/claude";to={command:"claude",meta:{displayName:"Claude",models:yi(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ct(e.model),s=e.effort??o,i=bi(e.mode),a=Ci(s),c=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...Li(e.builtinAllow)],p=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let _=[...e.additionalArgs];return _.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...p,...i,...a,...c,...u,..._],stdinMessage:t,env:Fn}:{args:["--output-format","stream-json","--verbose",...p,...i,...a,...c,...u,..._],stdinMessage:t,env:Fn}}return {args:["-p","--output-format","stream-json","--verbose",...p,...i,...a,...c,...u],stdinMessage:t,env:Fn}},extractText(t){let e=Ui(t);if(e?.is_error===true){let o=to.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new j(Bi(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,el,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Fi(t);if(n)return n;let r=t.trim();return dt(r,"claude")?"":r},extractPartialText(t){return Fi(t)},extractFailure(t){try{let e=JSON.parse(t),n=Gi(e);if(n)return new Jt(n)}catch{}return null},interpretExit(t,e,n){let r=tl(n??"");if(r)return new j(`Claude is not logged in (exit ${t}): ${r}. Sign in to this account with the official "claude auth login".`,"cli/claude",{code:"AUTH_REQUIRED",kind:"config"});let o=Bi(Ui(n??""));return o?new j(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return nl(e)}catch{return}},parseResultMeta(t){let e=t.split(`
62
+ `);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,c=a?Object.keys(a)[0]??null:null;return {usage:i,model:c}}}catch{}let n=vi(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=$e(n,e??new Date().toISOString()),s=rl(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];if(r!=="assistant"&&r!=="user")return [];let a=n.message?.content;if(!Array.isArray(a))return [];let c=[];for(let u of a){let p=al(o,u);p&&c.push(p);}return c},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Zu.has(r):!1}catch{return false}}};Hi=200;});function ji(t){let e=t.split(`
63
+ `).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var dl,ro=k(()=>{d();Qt();on();Ct();Ot();Nt();Ye();Mn();ut();dl=new Set(["interactive","plan","autopilot"]);({command:"copilot",meta:{displayName:"Copilot",models:Si()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&dl.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Ln.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=ji(t);if(e)return e;let n=t.trim();return dt(n,"copilot")?"":n},extractPartialText(t){return ji(t)},parseResultMeta(t){let e=rn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=$e(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let a=String(o.toolName||""),c=o.arguments,u=Me(c);return (a==="bash"||a==="Bash")&&Pe(u)?[xe(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let a=o.error;if(a)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Le(String(a.message||""),true)}];let c=o.result,u=String(c?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Le(u,false)}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}});});function ll(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let c=t[a];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,a+1).trim();u&&e.push(u),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function pl(t){return t[0]==="exec"?t.slice(1):t}function Ki(t){let e=t.split(`
64
+ `).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zi(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Je(t.error)}function Yi(t){let e=Je(t.error)?t.error:void 0,n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0];for(let r of n)if(typeof r=="string"&&r.trim())return r;return t.type==="turn.failed"?"Codex turn failed.":"Codex CLI reported an error."}function _l(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Je(n)&&zi(n))return Yi(n)}}function Vi(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let c=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(c),o.set(s,u),c}let i=o.get(s),a=i?.pop();return i?.length||o.delete(s),a}function gl(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return Pe(o)?[xe(t,o,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:o,...n?{toolUseId:n}:{}}]}return r==="mcp_tool_call"?typeof e.server!="string"||typeof e.tool!="string"?[]:[{timestamp:t,type:"tool_use",toolName:`${e.server}/${e.tool}`,toolInput:Me(e.arguments),...n?{toolUseId:n}:{}}]:[]}function fl(t,e,n){let r=e.type;if(r==="message"||r==="text"){let o=e.content;if(Array.isArray(o))for(let s of o){let i=hl(t,s);if(i)return i}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(r==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(r==="reasoning"){let o=typeof e.text=="string"?e.text.trim():"";return o?{timestamp:t,type:"thinking",content:o}:null}if(r==="command_execution"){let o=String(e.aggregated_output||e.output||""),s=!!e.is_error;return {timestamp:t,type:"tool_result",...Le(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Je(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(c=>Je(c)&&c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
65
+ `),a=typeof e.error=="string"?e.error:Je(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||a,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=Me(s);return o==="Bash"&&Pe(i)?xe(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...Le(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(Je(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(a=>String(a.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function hl(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=Me(o);return r==="Bash"&&Pe(s)?xe(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var cl,ul,oo=k(()=>{d();Ve();Qt();on();Ct();Ot();Kr();Nt();nn();Ye();ut();cl=new Set(["turn.started","turn.completed","item.updated"]),ul="cli/codex";({command:"codex",meta:{displayName:"Codex",models:ki(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ct(e.model),s=e.effort??o,i=e.resumeSessionId?Ai(e.mode):Ti(e.mode),a=Ii(s),c=r?["-m",r]:[],u=pl(e.additionalArgs??[]),f=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...f,...i,...a,...c,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...f,...i,...a,...c,...u],stdinMessage:t}},extractText(t){let e=_l(t);if(e)throw new j(e,ul);let n=Ki(t);if(n)return n;let r=t.trim();return dt(r,"codex")?"":r},extractPartialText(t){return Ki(t)},parseResultMeta(t){let e=rn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),o=[],s;try{JSON.parse(t),s=[t];}catch{s=ll(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,a]of s.entries()){let c;try{c=JSON.parse(a);}catch{continue}if(!Je(c))continue;let u=c.type;if(!u)continue;let p=$e(c,r);if(zi(c)){let _=Yi(c);o.push({timestamp:p,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Wr(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let f=c.item;if(f){if(u==="item.started"){o.push(...gl(p,f,Vi(f,u,n,i)));continue}if(u==="item.completed"){let _=fl(p,f,Vi(f,u,n,i));_&&o.push(_);continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?cl.has(r):!1}catch{return false}}});});var Xi=k(()=>{d();});var Qi=k(()=>{d();});function yl(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function kl(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Zi),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:Zi,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(yl(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function Sl(){return process.platform!=="win32"?Promise.resolve(null):(Un||(Un=kl(),Un.then(t=>{},()=>{})),Un)}function wl(){process.platform==="win32"&&Sl();}var Zi,Un,ta=k(()=>{d();Zi=1e3;wl();});var so=k(()=>{d();});var na=k(()=>{d();});var io=k(()=>{d();Ve();so();na();});var ra=k(()=>{d();ao();Qi();ta();so();io();Ye();});var co=k(()=>{d();Ve();Xi();on();Ot();ut();ra();io();});var oa=k(()=>{d();});function Dt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function vl(t,e){return t&&sa.has(t)||Dt(e,"--dangerously-skip-permissions")?true:e.some((n,r)=>{let o=n==="--mode"?e[r+1]:n.startsWith("--mode=")?n.slice(7):void 0;return typeof o=="string"&&sa.has(o)})}function Dl(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function Pl(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!Nl.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function me(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xl(t,e){if(!(t?Cl.has(t)||ze(uo).some(s=>s.id===t):false)||!t)return e;let r=tn(uo,t),o=Qr(uo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Ge(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function _o(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function go(t){return t.step.step_index}function $(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Dn(e)?.slice(0,500).trim()||void 0}function Ll(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Ol.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(s=>s.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function Ml(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function da(t){let e=me(t)?t:void 0,n=e&&me(e.error)?e.error:void 0,r=e?$(e.code)??$(e.error_code)??$(n?.code)??$(n?.error_code):void 0,o=typeof t=="string"?$(t):e?$(e.message)??$(e.error)??$(e.reason)??$(n?.message)??$(n?.error)??$(n?.reason):void 0,s=Ll(r,o),i=e?Ge(e.retry_after_ms)??Ge(e.retryAfterMs)??Ge(n?.retry_after_ms)??Ge(n?.retryAfterMs):void 0;return {code:s,kind:Ml(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Bn(t){let e=da(t);return new j(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function fo(t){return new j(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Fl(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=po))throw new j(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${po} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function lo(){return new j("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"})}function Hn(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function $n(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function Ul(t){let e=$n(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Hn(e.event)?.status!=="SUCCESS"||qn(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=_o(o),i=go(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!me(o.usage)||Ge(o.usage.input_tokens)===void 0||Ge(o.usage.output_tokens)===void 0)return false;return true}function ql(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function Bl(t,e){return me(t)&&me(e)?{...e,...t}:me(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&me(e)?{...e,message:t}:t??e}function Hl(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let a=me(i)?i:void 0,c=typeof i=="string"?$(i):$(a?.display_name)??$(a?.action);c&&!n.includes(c)&&n.length<5&&n.push(c.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"",s=`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`;return new j("Could not run because of permissions.","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function qn(t){let e=$n(t);if(!e)return;if(e.event.kind==="agy_error")return Bn(e.event.error);let n=Hn(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Hl(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return fo("Antigravity returned a result with an unsupported status.");let r=n.error,o=Bl(r==null||r===""?n:r,ql(t,e.index));return Bn(o)}function ca(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function $l(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function Gl(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function ua(t){let e=ca(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function jl(t){let e=me(t)?t:void 0,n=e&&me(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=($(e?.type)??$(e?.code)??$(e?.error_type)??$(n?.type)??$(n?.code)??$(n?.error_type)??$(r)??"TOOL_ERROR").slice(0,60),s=da(t).message.slice(0,250);return ua({type:o,message:s})??"Antigravity reported a tool error."}function ia(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function aa(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var uo,Cl,Nl,sa,po,Ol,ho=k(()=>{d();Ve();oa();Gr();Zt();Ye();nn();xn();eo();uo="antigravity",Cl=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Nl=new Set(["--conversation","--resume","--continue"]),sa=new Set(["bypassPermissions","agent-full-access","yolo"]),po=18e4,Ol=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);({command:"agy",maxInitialInputBytes:po,meta:{displayName:"Antigravity",models:wi(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Xt(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){Fl(t);let{model:r,effort:o}=ct(e.model),s=Jr(r),i=s.model,a=e.effort??o??s.effort,c=xl(i,a),u=e.additionalArgs??[],p=Pl(Dl(u,new Set(["--input-format","--output-format"]))),f=i&&!Dt(u,"--model")?["--model",i]:[],_=Dt(u,"--effort")?[]:Oi(c),S=Dt(u,"--mode")||Dt(u,"--dangerously-skip-permissions")?[]:Ni(e.mode),w=vl(e.mode,u)||Dt(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:Mi(e.builtinAllow)}})],E=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...f,..._,...S,...E,...w,...p],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
66
+ `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=bt(t),n=$n(e)?.event,r=qn(e);if(r)throw r;let o=n?Hn(n):void 0;if(o){if(o.status!=="SUCCESS")throw fo("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw fo("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw lo();return o.response}if(e.length>0)throw lo();let s=t.trim();if(!s)throw lo();return s},extractPartialText(t){let e=bt(t),n=$n(e)?.event;if(!n||n.kind==="agy_error")return;let r=Hn(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=bt(n??""),o=qn(r);return o||(t!==0&&e.trim()?Bn(e):null)},parseResultMeta(t){let e=bt(t),n=0,r=0,o=0,s=0,i=new Set;for(let c of e){if(c.kind!=="step_update"||c.step.state!=="DONE"||!me(c.step.usage))continue;let u=_o(c),p=go(c);if(!u||!Number.isSafeInteger(p))continue;let f=JSON.stringify([u,p]);if(i.has(f))continue;let _=c.step.usage,S=Ge(_.input_tokens),w=Ge(_.output_tokens);if(S===void 0||w===void 0)continue;i.add(f);let E=Ge(_.cache_read_tokens)??0;n+=S+E,r+=w,o+=E,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:Ul(e)},model:null}},parseEvent(t,e,n){let r=Xt(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [aa(o,Bn(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let S=qn([r]);return S?[aa(o,S)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=_o(r)??"unknown",a=go(r),c=`${i}:${a}`;if((s.state==="DONE"||s.state==="ERROR")&&ia(n,`antigravity:terminal:${c}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=me(s.tool_info)?s.tool_info:void 0,p=Gl(s,u);if(!p)return [];let f=$l(s);if(s.state==="ACTIVE"){if(ia(n,`antigravity:active:${c}`))return [];let S=ca(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:p,toolUseId:f,...S===void 0?{}:{toolInput:S}}]}let _=s.state==="ERROR"?jl(u?.error):ua(u?.output);return [{timestamp:o,type:"tool_result",toolName:p,toolUseId:f,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}});});var pa=k(()=>{d();Ct();Ot();Nt();ut();});var mo=k(()=>{d();Ve();$r();Ye();Nt();nn();ut();});var ao=k(()=>{d();no();ro();oo();co();ho();pa();mo();no();ro();oo();co();ho();mo();Ct();});var _a=k(()=>{d();ai();ao();});var yo=k(()=>{d();_a();On();});var sn,lt=k(()=>{d();sn=["success","completed","done","failed","error","stopped","runner_lost"];});var an=k(()=>{d();});var So=k(()=>{d();Hr();an();});var sp,Pt=k(()=>{d();P();M();q();L();F();Tt();On();Br();Hr();vn();Fr();yo();lt();an();So();an();Tt();sp="0.8.9-rc.13",parseInt(sp.split("rc.")[1]),new Set(sn);});d();d();d();var T="workout-log",Xe="workout-log.records.v1",pt=500,Kn=100,Vn=4096,Lt=6e4,zn=200,Mt=20,dn=6e4;d();var Ft=class{epoch=0;activeSession=null;grantControllers=new Map;get activeAccountKey(){return this.activeSession?.accountKey??null}get activeSessionEpoch(){let e=this.activeSession;return e&&!e.controller.signal.aborted?e.epoch:null}currentToken(e){let n=this.activeSession;return !n||n.accountKey!==e||n.controller.signal.aborted?null:this.toSessionToken(n)}activate(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("INVALID_ACCOUNT_KEY");if(this.activeSession?.accountKey===e&&!this.activeSession.controller.signal.aborted)return this.toSessionToken(this.activeSession);this.abortActiveSession();let n={accountKey:e,epoch:++this.epoch,controller:new AbortController};return this.activeSession=n,this.toSessionToken(n)}captureGrant(e,n,r){if(!this.isCurrent(e))throw new Error("APP_SYNC_SESSION_STALE");if(!n||!Number.isSafeInteger(r)||r<1)throw new Error("INVALID_GRANT_FENCE");let o=new AbortController,s=this.grantKey(e.accountKey,n,r),i=()=>o.abort(e.signal.reason);e.signal.aborted?i():e.signal.addEventListener("abort",i,{once:true});let a=this.grantControllers.get(s)??new Set;return a.add({controller:o,sessionSignal:e.signal,onSessionAbort:i}),this.grantControllers.set(s,a),{accountKey:e.accountKey,epoch:e.epoch,grantId:n,generation:r,signal:o.signal}}isCurrent(e){let n=this.activeSession;return n!==null&&n.accountKey===e.accountKey&&n.epoch===e.epoch&&!n.controller.signal.aborted&&!e.signal.aborted}release(e){let n=this.grantKey(e.accountKey,e.grantId,e.generation),r=this.grantControllers.get(n);if(r){for(let o of r)o.controller.signal===e.signal&&(o.sessionSignal.removeEventListener("abort",o.onSessionAbort),r.delete(o));r.size===0&&this.grantControllers.delete(n);}}cancelGrant(e,n,r){let o=this.grantKey(e,n,r),s=this.grantControllers.get(o);if(s){for(let i of s)i.sessionSignal.removeEventListener("abort",i.onSessionAbort),i.controller.abort("grant_invalidated");this.grantControllers.delete(o);}}suspend(e){this.activeSession&&(e===void 0||this.activeSession.accountKey===e)&&(this.abortActiveSession(),this.epoch+=1);}toSessionToken(e){return {accountKey:e.accountKey,epoch:e.epoch,signal:e.controller.signal}}abortActiveSession(){let e=this.activeSession;if(e){e.controller.abort("session_suspended");for(let[n,r]of this.grantControllers)if(n.startsWith(`${e.accountKey}:${e.epoch}:`)){for(let o of r)o.sessionSignal.removeEventListener("abort",o.onSessionAbort),o.controller.abort("session_suspended");this.grantControllers.delete(n);}this.activeSession=null;}}grantKey(e,n,r){return `${e}:${this.activeSession?.epoch??this.epoch}:${n}:${r}`}};d();var Da=Xe,_e=Object.freeze({root:"docs/apps/workout-log",include:Object.freeze(["exercises.md","routines/<id>.md","workouts/<YYYY-MM-DD>-<id>.md"]),idPattern:"^[A-Za-z0-9_-]{1,40}$",exclude:Object.freeze(["migration/**","*.json","app-state/**",".*","*~","*.tmp","*.swp","*.part",".env*","auth.json","*.key","*.pem"])}),Yn=Object.freeze({exactFiles:Object.freeze(["exercises.md"]),directFolders:Object.freeze(["routines","workouts"]),suffix:".md",maxDepth:1}),Pa=/^[A-Za-z0-9_-]{1,40}$/,No=["root","include","idPattern","exclude"];function Oo(t,e){return Array.isArray(t)&&t.length===e.length&&t.every((n,r)=>n===e[r])}function xa(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function La(t){if(t==="exercises.md")return "exercises";if(/^routines\/[A-Za-z0-9_-]{1,40}\.md$/.test(t))return "routine";let e=/^workouts\/(\d{4})-(\d{2})-(\d{2})-([A-Za-z0-9_-]{1,40})\.md$/.exec(t);if(!e||!Pa.test(e[4]))return null;let[,n,r,o]=e,s=Number(n),i=Number(r),a=Number(o);if(s<1||i<1||i>12||a<1||a>31)return null;let c=new Date(0);return c.setUTCHours(0,0,0,0),c.setUTCFullYear(s,i-1,a),c.getUTCFullYear()!==s||c.getUTCMonth()!==i-1||c.getUTCDate()!==a?null:"workout"}function Ma(t){let n=t.trim().replace(/[ \t]+#.*$/,"").trim();return /^[A-Za-z0-9_-]+$/.test(n)?n:/^"[A-Za-z0-9_-]+"$/.test(n)||/^'[A-Za-z0-9_-]+'$/.test(n)?n.slice(1,-1):null}function Fa(t){if(typeof t!="string")return null;let e=t.indexOf(`
67
+ `);if((e<0?t:t.slice(0,e)).replace(/\r$/,"")!=="---")return null;let r=new Map,o=e<0?t.length:e+1;for(;o<=t.length;){let s=t.indexOf(`
68
+ `,o),i=s<0?t.length:s,a=t.slice(o,i);a.endsWith("\r")&&(a=a.slice(0,-1));let c=s<0?i:s+1;if(Buffer.byteLength(t.slice(0,c),"utf8")>4096)return null;if(a==="---")return r.has("crewx_app")&&r.has("kind")?r:null;let u=/^(crewx_app|kind):[ \t]*(.*)$/.exec(a);if(u){let p=u[1];if(r.has(p))return null;let f=Ma(u[2]);if(f===null)return null;r.set(p,f);}if(s<0)break;o=s+1;}return null}var Ut=class{scopeVersion=Xe;definition=_e;matchesDefinition(e,n){return e!==Da||!xa(n)||Object.keys(n).length!==No.length||!No.every(r=>Object.hasOwn(n,r))?false:n.root===_e.root&&n.idPattern===_e.idPattern&&Oo(n.include,_e.include)&&Oo(n.exclude,_e.exclude)}validateRef(e){if(typeof e!="string"||e.length===0||e.length>256)return {valid:false,reason:"out_of_scope"};if(e.includes("\0")||e.includes("\\")||e.startsWith("/")||e.startsWith("~"))return {valid:false,reason:"out_of_scope"};if(e.split("/").some(o=>o===""||o==="."||o===".."))return {valid:false,reason:"out_of_scope"};if(e.startsWith(".")||/(?:^|\/)\./.test(e)||/(?:^|\/)[^/]*(?:~|\.tmp|\.swp|\.part)$/.test(e))return {valid:false,reason:"out_of_scope"};if(/(?:^|\/)(?:auth\.json|[^/]*\.key|[^/]*\.pem)$/.test(e)||/\.env[^/]*$/.test(e))return {valid:false,reason:"out_of_scope"};let r=La(e);return r===null?{valid:false,reason:"out_of_scope"}:{valid:true,kind:r}}validateFrontMatter(e,n){let r=this.validateRef(e);if(!r.valid)return {valid:false,reason:"invalid_front_matter"};let o=Fa(n);return o?o.get("crewx_app")!==T?{valid:false,reason:"app_mismatch"}:o.get("kind")!==r.kind?{valid:false,reason:"kind_mismatch"}:{valid:true,kind:r.kind}:{valid:false,reason:"invalid_front_matter"}}};function U(t){return `sha256:${crypto.createHash("sha256").update(t,"utf8").digest("hex")}`}function _t(t){if(!Array.isArray(t)||t.length===0||t.length>64)return null;let e=[];for(let n of t){if(typeof n!="string"||n.length===0)return null;let r=n.normalize("NFC");if(r==="."||r===".."||r.includes("/")||r.includes("\\")||r.includes("\0")||/^[A-Za-z]:$/.test(r)||r.startsWith("~"))return null;e.push(r);}return e}d();d();var qa=10*6e4,Ba=5e3,je=class extends Error{constructor(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("INVALID_APP_SYNC_BUDGET_RETRY_AT");super("APP_SYNC_BUDGET_DEFERRED");this.retryAt=n;this.name="AppSyncBudgetDeferredError";}retryAt;code="APP_SYNC_BUDGET_DEFERRED"},Jn=class{constructor(e){this.sqlite=e;if(!e||typeof e.prepare!="function"||typeof e.transaction!="function")throw new Error("INVALID_DOC_CREATE_LEDGER_DATABASE")}sqlite;peek(e,n){Xn(e),cn(n),this.deleteExpired(n);let r=this.readWindow(e,n);return r.count<20?{available:true,remaining:20-r.count}:{available:false,retryAt:vo(r,n)}}reserve(e){return Do(e),this.sqlite.transaction(r=>{this.deleteExpired(r.now);let o=this.readWindow(r.accountKey,r.now);return o.count>=20?{ok:false,retryAt:vo(o,r.now)}:(this.insert(r),{ok:true})}).immediate(e)}reserveForced(e){Do(e),this.deleteExpired(e.now),this.insert(e);}prune(e){return cn(e),this.deleteExpired(e)}readWindow(e,n){let r=this.sqlite.prepare(`
69
+ SELECT COUNT(*) AS count, MIN(dispatched_at) AS oldest
70
+ FROM doc_create_dispatches
71
+ WHERE account_key = ? AND dispatched_at > ?
72
+ `).get(e,n-6e4);if(!r||!Number.isSafeInteger(r.count)||r.count<0||r.oldest!==null&&!Number.isSafeInteger(r.oldest))throw new Error("DOC_CREATE_LEDGER_READ_INVALID");return r}insert(e){this.sqlite.prepare(`
73
+ INSERT INTO doc_create_dispatches (dispatch_id, request_id, account_key, source, dispatched_at)
74
+ VALUES (?, ?, ?, ?, ?)
75
+ `).run(crypto.randomUUID(),e.requestId,e.accountKey,e.source,e.now);}deleteExpired(e){return this.sqlite.prepare("DELETE FROM doc_create_dispatches WHERE dispatched_at <= ?").run(e-qa).changes}};function qt(t){if(Xn(t.accountKey),Po(t.requestId),xo(t.source),typeof t.now!="function"||typeof t.ledger?.peek!="function"||typeof t.ledger.reserve!="function"||typeof t.ledger.reserveForced!="function"||typeof t.ledger.prune!="function"||t.guard!==void 0&&typeof t.guard!="function")throw new Error("INVALID_DOC_CREATE_DISPATCH_GATE");let e=0,n=(()=>{e+=1;let r=t.guard?.();if(r!=null&&typeof r.then=="function")throw Promise.resolve(r).catch(()=>{}),new Error("APP_SYNC_DISPATCH_GUARD_MUST_BE_SYNCHRONOUS");let o=t.now();cn(o);try{let s=t.ledger.reserve({accountKey:t.accountKey,requestId:t.requestId,source:t.source,now:o});if(s.ok===!0||s.ok===!1&&Number.isSafeInteger(s.retryAt)&&s.retryAt>=0)return s;throw new Error("DOC_CREATE_LEDGER_DECISION_INVALID")}catch{throw new je(o+Ba)}});return Object.defineProperty(n,"calls",{enumerable:true,get:()=>e}),n}function vo(t,e){if(t.oldest===null)throw new Error("DOC_CREATE_LEDGER_WINDOW_EMPTY");let n=t.oldest+6e4;if(!Number.isSafeInteger(n)||n<e)throw new Error("DOC_CREATE_LEDGER_RETRY_AT_INVALID");return n}function Do(t){if(!t||typeof t!="object")throw new Error("INVALID_DOC_CREATE_DISPATCH_INPUT");Xn(t.accountKey),Po(t.requestId),xo(t.source),cn(t.now);}function Xn(t){if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))throw new Error("INVALID_DOC_CREATE_LEDGER_ACCOUNT_KEY")}function Po(t){if(typeof t!="string"||t.length<1||t.length>128)throw new Error("INVALID_DOC_CREATE_LEDGER_REQUEST_ID")}function xo(t){if(t!=="human"&&t!=="app_create"&&t!=="app_reattach")throw new Error("INVALID_DOC_CREATE_LEDGER_SOURCE")}function cn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("INVALID_DOC_CREATE_LEDGER_TIME")}var Lo=1e4,$a=12e4,ln=class{constructor(e,n,r,o,s,i){this.dependencies=e;this.scopeRegistry=n;this.sessionFence=r;this.now=o;this.createId=s;this.hasPendingRevoke=i;if(!e.continuation)throw new Error("APP_SYNC_CONTINUATION_CAPABILITY_REQUIRED");if(!e.remote.listGrantDocs||!e.remote.listDeletedRefs||!e.documents.inspectContinuation||!e.documents.applyContinuation)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");this.continuation=e.continuation,this.continuationStore=e.continuation.store;let a=e.continuation.pageSize??100;if(!Number.isSafeInteger(a)||a<1)throw new Error("APP_SYNC_CONTINUATION_PAGE_SIZE_INVALID");this.pageSize=Math.min(a,200);}dependencies;scopeRegistry;sessionFence;now;createId;hasPendingRevoke;continuation;continuationStore;pageSize;async tick(e,n,r,o,s){let i=this.createFenceContext(e,n,r,o);i.fence.assertCurrent(),!(this.continuationStore.beginDiscoveryCycle({binding:e,fence:i.fence,now:this.now()})&&!await this.traverseWithCursorRecovery(i))&&(i.fence.assertCurrent(),await this.processPendingDiscoveries(i));}listConflicts(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n||!e.session.authenticated||e.session.accountKey!==n.accountKey||n.workspaceId!==e.workspaceId||!Mo(n.rootSegments,e.resolvedRootSegments))return [];let r=this.sessionFence.currentToken(n.accountKey);return !r||this.sessionFence.activeAccountKey!==n.accountKey||this.hasPendingRevoke(n.bindingId)?[]:this.continuationStore.listConflicts(n.bindingId).map(({vaultHandle:o,...s})=>({...s,sessionEpoch:r.epoch}))}assertHumanBindingIdentity(e,n){if(ja({bindingId:n.bindingId,session:n.session,workspaceId:n.workspaceId,resolvedRootSegments:n.resolvedRootSegments}),!n.session?.authenticated||n.session.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||!Mo(e.rootSegments,n.resolvedRootSegments))throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}requireCurrentSession(e,n){if(!Number.isSafeInteger(n)||n<1)throw new g("APP_SYNC_SESSION_STALE");let r=this.sessionFence.currentToken(e.accountKey);if(!r||this.sessionFence.activeAccountKey!==e.accountKey||r.epoch!==n)throw new g("APP_SYNC_SESSION_STALE");return r}requireHumanOperationBinding(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404);return this.assertHumanBindingIdentity(n,e),n}async readConflictArchive(e){let n=this.requireHumanOperationBinding(e),r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Fo(e.eligibility)||!Qn(n.status))throw new g("DOC_APP_GRANT_REQUIRED",409);let o=this.continuationStore.getConflict(e.conflictId);if(!o)throw new g("APP_SYNC_CONFLICT_NOT_FOUND",404);if(Uo(o,n),o.preservationStatus!=="ready"||!o.vaultHandle||o.state==="purging")throw new g("APP_SYNC_CONFLICT_NOT_PRESERVED",409);let s=this.archiveFenceGrant(n,o),i=this.createArchiveFenceContext(n,s,r);try{i.fence.assertCurrent();let a=await this.readVerifiedArchive(o,i);return {conflictId:o.conflictId,localVersion:o.localVersion,localFingerprint:o.localFingerprint,remoteRevision:o.remoteRevision,remoteFingerprint:o.remoteFingerprint,markdown:a}}finally{this.sessionFence.release(i.grantToken);}}async purgeAccountData(e){Wa(e);let n=this.sessionFence.currentToken(e.session.accountKey);if(!n||n.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==e.session.accountKey)throw new g("APP_SYNC_SESSION_STALE");let r=ae(JSON.stringify(e.resolvedRootSegments)),o=this.continuationStore.getAccountDataPurge(e.requestId);if(o&&(o.bindingId!==e.bindingId||o.accountKey!==e.session.accountKey||o.workspaceId!==e.workspaceId||o.rootFingerprint!==r||o.humanIdentity!==e.humanIdentity))throw new g("APP_SYNC_PURGE_REQUEST_ID_REUSED",409);let s=this.dependencies.store.getBinding(e.bindingId);if(!s){if(o?.state==="complete")return {requestId:e.requestId,status:"purged",remainingArchiveCount:0};throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}this.assertHumanBindingIdentity(s,e);let i=this.requireCurrentSession(s,e.expectedSessionEpoch);if(this.hasPendingRevoke(s.bindingId))throw new g("APP_SYNC_REVOKE_PENDING",409);let a=this.purgeFenceGrant(s),c={allowNonTransferStatus:true,purgeRequestId:e.requestId},u=this.createArchiveFenceContext(s,a,i,c),p=u;try{this.continuationStore.beginAccountDataPurge({requestId:e.requestId,binding:s,humanIdentity:e.humanIdentity,fence:u.fence,now:this.now()}),s.grantId&&s.grantGeneration&&this.sessionFence.cancelGrant(s.accountKey,s.grantId,s.grantGeneration),this.sessionFence.release(u.grantToken),p=this.createArchiveFenceContext(s,a,i,c);let f=this.continuationStore.listConflicts(s.bindingId);for(let _ of f)try{p.fence.assertCurrent();let S=_.state==="purging"?_:this.continuationStore.markConflictPurging({conflictId:_.conflictId,fence:p.fence,now:this.now()});S.vaultHandle&&(await this.continuation.conflictVault.remove({accountKey:s.accountKey,handle:S.vaultHandle,fence:p.fence}),p.fence.assertCurrent()),this.continuationStore.deletePurgedConflict({conflictId:S.conflictId,expectedVaultHandle:S.vaultHandle,fence:p.fence,now:this.now()});}catch(S){if(!this.isFenceCurrent(p))throw S;let w=this.continuationStore.listConflicts(s.bindingId).length;return {requestId:e.requestId,status:"cleanup_pending",remainingArchiveCount:w}}return this.continuationStore.finishAccountDataPurge({requestId:e.requestId,binding:s,fence:p.fence,now:this.now()}),{requestId:e.requestId,status:"purged",remainingArchiveCount:0}}finally{this.sessionFence.release(u.grantToken),p!==u&&this.sessionFence.release(p.grantToken);}}async resolveConflict(e){Ka(e);let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH");this.assertHumanBindingIdentity(n,e);let r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Fo(e.eligibility)||!Qn(n.status))throw new g("DOC_APP_GRANT_REQUIRED",409);if(!n.grantId||!n.grantGeneration||!n.scopeVersion||n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new g("DOC_APP_GRANT_REQUIRED",409);if(this.hasPendingRevoke(n.bindingId))throw new g("APP_SYNC_REVOKE_PENDING");let o=er(n);if(r.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==n.accountKey)throw new g("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,o.grantId,o.generation),i=this.createFenceContext(n,o,r,s);try{i.fence.assertCurrent();let a=this.continuationStore.getConflict(e.conflictId);if(!a)throw new g("APP_SYNC_CONFLICT_NOT_FOUND",404);if(Uo(a,n),a.state==="purging")throw new g("APP_SYNC_CONFLICT_PURGING",409);if(!(a.state==="superseded"&&e.choice==="keep_both")&&!await this.readActiveGrant(i))throw new g("DOC_APP_GRANT_STALE",409);if(a.state==="resolved"||a.state==="kept_both"){if(a.resolutionRequestId!==e.requestId||a.resolutionChoice!==e.choice)throw new g("APP_SYNC_CONFLICT_ALREADY_RESOLVED",409);return this.cleanupResolvedConflict(a,i)}if(a.preservationStatus!=="ready"||!a.vaultHandle)throw new g("APP_SYNC_CONFLICT_NOT_PRESERVED",409);this.continuationStore.beginConflictResolution({conflictId:a.conflictId,requestId:e.requestId,humanIdentity:e.humanIdentity,choice:e.choice,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,fence:i.fence,now:this.now()});let u=await this.applyHumanResolution(e,a,i);if(u.status==="stale")throw this.continuationStore.abortConflictResolution({conflictId:a.conflictId,requestId:e.requestId,state:"stale",errorCode:"APP_SYNC_CONFLICT_STALE",fence:i.fence,now:this.now()}),u.refreshed?await this.preserveConflict(tr(i,a.ref,u.refreshed.remote.docId,u.refreshed.remote),u.refreshed.local,u.refreshed.remote,i):await this.refreshConflictAfterStale(a,i),new g("APP_SYNC_CONFLICT_STALE",409);let p=this.continuationStore.finishConflictResolution({conflictId:a.conflictId,requestId:e.requestId,choice:e.choice,fence:i.fence,now:this.now()});return this.cleanupResolvedConflict(p,i)}catch(a){if(this.isFenceCurrent(i)){let c=this.continuationStore.getConflict(e.conflictId);c?.state==="resolving"&&c.resolutionRequestId===e.requestId&&(Fe(a)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"?this.continuationStore.markConflictResolutionUnknown({conflictId:e.conflictId,requestId:e.requestId,fence:i.fence,now:this.now()}):Va(a)||this.continuationStore.abortConflictResolution({conflictId:e.conflictId,requestId:e.requestId,state:"failed",errorCode:Zn(a),fence:i.fence,now:this.now()}));}throw a}finally{this.sessionFence.release(s);}}async dispatchReattachCreation(e,n,r,o,s){if(!o.documentId||o.operationKind!=="reattach"||o.bindingId!==e.bindingId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(this.hasPendingRevoke(e.bindingId)||!this.sessionFence.isCurrent(r))return;if(this.dependencies.createLedger)try{let u=this.dependencies.createLedger.peek(e.accountKey,this.now());if(!u.available||u.remaining<1)return}catch(u){this.dependencies.onAdapterError?.(u);return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),$a);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.createFenceContext(e,n,r,a);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,ae(o.ref))){this.dependencies.store.updateCreation(o.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}let u=await this.readRemoteDocument(o.documentId,c);if(U(u.markdown)!==o.fingerprint||u.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,u.markdown).valid){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}if(u.appGrantId===n.grantId&&u.appGrantGeneration===n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);return}let p=await this.dependencies.creationBudget.runCreate({accountKey:e.accountKey,signal:a.signal,dispatch:async()=>{c.fence.assertCurrent();let S=await this.readRemoteDocument(o.documentId,c);if(U(S.markdown)!==o.fingerprint||S.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,S.markdown).valid)return {kind:"changed"};let w=this.dependencies.createLedger?qt({ledger:this.dependencies.createLedger,accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now,guard:()=>{if(c.fence.assertCurrent(),this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING")}}):void 0,E;try{E=await this.dependencies.remote.createGrantedDocument({accountKey:e.accountKey,appId:T,ref:o.ref,requestId:o.requestId,markdown:S.markdown,appVersion:s.appVersion,appGrant:{grantId:n.grantId,generation:n.generation},signal:a.signal,fence:c.fence,...w?{dispatchGate:w}:{}});}catch(R){if(R instanceof je)return {kind:"budget_deferred",retryAt:R.retryAt};throw R}if(w&&w.calls===0){let R=new g("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger.reserveForced({accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now()});}catch(I){this.dependencies.onAdapterError?.(I);}throw this.dependencies.onAdapterError?.(R),R}return c.fence.assertCurrent(),{kind:"created",created:E}}});if(c.fence.assertCurrent(),p.status==="deferred"){let S=this.now();return this.deferClaim(i,p.retryAt,S),void 0}if(p.value.kind==="budget_deferred"){let S=this.now();return this.deferClaim(i,p.value.retryAt,S),void 0}if(p.value.kind==="changed"){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let f=p.value.created;if(f.docId!==o.documentId||f.appGrantId!==n.grantId||f.appGrantGeneration!==n.generation||f.markdownVersion!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let _=await this.readRemoteDocument(o.documentId,c);if(_.appGrantId!==n.grantId||_.appGrantGeneration!==n.generation||_.markdownVersion!==o.fingerprint||U(_.markdown)!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);}catch(u){if(!this.isFenceCurrent(c))return;if(gt(u)){this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let p=za(u);this.dependencies.store.updateCreation(o.jobId,{status:p?"waiting":"failed",nextAttemptAt:p?this.now()+Math.min(1e3*2**Math.min(i.attempts,10),3e5):0,now:this.now()}),p&&this.markPendingForReconcile(e,n,o.ref,c,"APP_SYNC_REATTACH_RESPONSE_UNKNOWN");}finally{this.sessionFence.release(a);}}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}async traverseWithCursorRecovery(e){let n=0;for(;;)try{return await this.traverseGrantDocs(e),await this.traverseDeletedRefs(e),!0}catch(r){if(!Ya(r))throw r;let o=await this.readActiveGrant(e);if(this.continuationStore.resetDiscoveryCycle({binding:e.binding,fence:e.fence,now:this.now()}),!o)return false;if(n+=1,n>1)throw r}}async traverseGrantDocs(e){let n=this.dependencies.remote.listGrantDocs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.docsComplete)return;let i=s.docsCursor;if(i!==null){if(r.has(i))throw new g("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateGrantDocsPage(a,e),a.items.length>this.pageSize)throw new g("APP_SYNC_DOCS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new g("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Lo)throw new g("APP_SYNC_DOCS_TRAVERSAL_LIMIT");this.continuationStore.commitGrantDocsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}async traverseDeletedRefs(e){let n=this.dependencies.remote.listDeletedRefs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.deletedComplete)return;let i=s.deletedCursor;if(i!==null){if(r.has(i))throw new g("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateDeletedRefsPage(a,e),a.items.length>this.pageSize)throw new g("APP_SYNC_DELETED_REFS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new g("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Lo)throw new g("APP_SYNC_DELETED_REFS_TRAVERSAL_LIMIT");this.continuationStore.commitDeletedRefsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}validateGrantDocsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||e.scopeVersion!==n.grant.scopeVersion||!un(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new g("APP_SYNC_DOCS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!J(o.docId,128)||!J(o.title,80)||!Number.isSafeInteger(o.currentRevision)||o.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(o.markdownVersion)||!Number.isSafeInteger(o.appGrantGeneration)||o.appGrantGeneration<1||o.appGrantGeneration>n.grant.generation||typeof o.needsReattach!="boolean"||!un(o.updatedAt)||!this.scopeRegistry.validateRef(o.ref).valid||r.has(o.ref))throw new g("APP_SYNC_DOCS_PAGE_INVALID");if(!o.needsReattach&&o.appGrantGeneration!==n.grant.generation)throw new g("APP_SYNC_DOCS_PAGE_INVALID");r.add(o.ref);}}validateDeletedRefsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||!un(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new g("APP_SYNC_DELETED_REFS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!/^[0-9a-f]{64}$/.test(o.refHash)||!un(o.deletedAt)||r.has(o.refHash))throw new g("APP_SYNC_DELETED_REFS_PAGE_INVALID");r.add(o.refHash);}}async readActiveGrant(e){e.fence.assertCurrent();let n=await this.dependencies.remote.readGrant({accountKey:e.binding.accountKey,appId:T,signal:e.fence.signal,fence:e.fence});return e.fence.assertCurrent(),n.appId!==T||n.available!==true||n.status!=="active"||!n.grant?false:n.grant.grantId===e.grant.grantId&&n.grant.generation===e.grant.generation&&n.grant.scopeVersion===e.grant.scopeVersion&&this.scopeRegistry.matchesDefinition(n.grant.scopeVersion,n.grant.scope)}async processPendingDiscoveries(e){let n=this.continuationStore.listPendingDiscoveries(e.binding.bindingId,e.grant.grantId,e.grant.generation,500);for(let r of n){if(!this.isFenceCurrent(e))return;try{this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"processing",errorCode:null},now:this.now()});let o=await this.reconcileDiscoveredDocument(r,e);if(o==="complete")this.continuationStore.completePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence});else if(o==="retry")this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",attempts:r.attempts+1},now:this.now()});else {this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:"DOC_APP_GRANT_REQUIRED"},now:this.now()});return}}catch(o){if(!this.isFenceCurrent(e))return;if(gt(o)){this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:Zn(o)},now:this.now()});return}this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:Zn(o),needsReconcile:true,attempts:r.attempts+1},now:this.now()});}}}async reconcileDiscoveredDocument(e,n){if(n.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(n.binding.accountKey,T,ae(e.ref)))return "complete";let r=await this.inspectLocal(e.ref,n),o=this.continuationStore.listConflicts(n.binding.bindingId).filter(E=>E.accountKey===n.binding.accountKey&&E.ref===e.ref);if(r.exists){if(o.some(I=>I.state==="kept_both"&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint))return "complete";let R=o.find(I=>(I.state==="open"||I.state==="resolving")&&I.preservationStatus==="ready"&&I.vaultHandle!==null&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint&&I.documentId===e.docId&&I.remoteRevision===e.listedRevision&&I.remoteFingerprint===e.listedFingerprint);if(R)return R.state==="open"&&(R.grantId!==n.grant.grantId||R.grantGeneration!==n.grant.generation||R.needsReattach!==e.needsReattach)&&this.continuationStore.rebindConflict({conflictId:R.conflictId,grant:n.grant,needsReattach:e.needsReattach,fence:n.fence,now:this.now()}),"complete"}let s=r.baseline,i=s!==null&&r.exists&&r.localFingerprint!==s.markdownVersion,a=s!==null&&(e.listedRevision!==s.revision||e.listedFingerprint!==s.markdownVersion);if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&!i)return "complete";if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&i)return this.applyConditionalSave(e.ref,e.docId,r,e.listedRevision,e.listedFingerprint,false,n);let c=await this.readPendingDocument(e,n);if(!c)return "complete";let u=c,p=e;if(e.needsReattach){let E=await this.queueOrConfirmReattachment(e,c,n);if(!E)return "retry";u=E.document,p=E.pending;}let f=await this.inspectLocal(e.ref,n);if(f.exists&&f.localFingerprint===u.markdownVersion){let E={kind:"attach_equal",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,expectedLocalFingerprint:f.localFingerprint,fence:n.fence},R=await this.applyEffect(E,n);if(R.status==="applied")return this.recordOutcome(n,e.ref,f.localFingerprint,u.markdownVersion,u.docId,"synced",null),"complete";if(R.status==="stale_local")return this.reconcileAfterLocalRace(p,u,n);if(R.status==="conflict")return this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n);if(R.status==="deferred"||R.status==="failed")return "retry"}let _=f.baseline??s;if(!f.exists){let E={kind:"create_absent",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:null,fence:n.fence},R=await this.applyEffect(E,n);return R.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):R.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):R.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}if(!_)return this.preserveConflict(p,f,u,n);let S=f.localFingerprint!==_.markdownVersion,w=u.currentRevision!==_.revision||u.markdownVersion!==_.markdownVersion;if(S&&w)return this.preserveConflict(p,f,u,n);if(w&&!S){let E={kind:"cas_pull",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,fence:n.fence},R=await this.applyEffect(E,n);return R.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):R.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):R.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}return S&&!w?this.applyConditionalSave(e.ref,u.docId,f,u.currentRevision,u.markdownVersion,p.needsReattach,n):"complete"}async inspectLocal(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.inspectContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=await r({binding:n.binding,grant:n.grant,ref:e,fence:n.fence});if(n.fence.assertCurrent(),!o||typeof o.exists!="boolean")throw new g("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.exists){if(!nr(o.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(o.localFingerprint)||U(o.markdown)!==o.localFingerprint||!this.scopeRegistry.validateFrontMatter(e,o.markdown).valid)throw new g("APP_SYNC_LOCAL_STATE_INVALID")}else if(o.localVersion!==null||o.localFingerprint!==null||o.markdown!==null)throw new g("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.baseline&&(!Number.isSafeInteger(o.baseline.revision)||o.baseline.revision<0||!/^sha256:[0-9a-f]{64}$/.test(o.baseline.markdownVersion)))throw new g("APP_SYNC_BASELINE_INVALID");return o}async readPendingDocument(e,n){n.fence.assertCurrent();try{let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e.docId,signal:n.fence.signal,fence:n.fence});return n.fence.assertCurrent(),this.validateRemoteDocument(r,e,n),r}catch(r){if(n.fence.assertCurrent(),Fe(r)==="DOC_NOT_FOUND"&&qo(r)===404)return this.continuationStore.recordKnownDeletion({binding:n.binding,grant:n.grant,ref:e.ref,refHash:ae(e.ref),documentId:e.docId,fence:n.fence,now:this.now()}),null;throw r}}validateRemoteDocument(e,n,r){if(!e||e.docId!==n.docId||!Number.isSafeInteger(e.currentRevision)||e.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(e.markdownVersion)||U(e.markdown)!==e.markdownVersion||!J(e.appGrantId,128)||!Number.isSafeInteger(e.appGrantGeneration)||e.appGrantGeneration<1||!this.scopeRegistry.validateFrontMatter(n.ref,e.markdown).valid)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let o=e.appGrantId===r.grant.grantId&&e.appGrantGeneration===r.grant.generation,s=e.appGrantGeneration===n.appGrantGeneration&&e.appGrantGeneration<=r.grant.generation;if(!o&&!(n.needsReattach&&s))throw new g("DOC_APP_GRANT_STALE",409)}async queueOrConfirmReattachment(e,n,r){if(n.appGrantId===r.grant.grantId&&n.appGrantGeneration===r.grant.generation){this.markReattached(r.binding,r.grant,e.ref,r,n);let a=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:n,pending:a}}if(this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:e.ref,documentId:n.docId,fingerprint:n.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}).status!=="completed")return this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:e.grantId,generation:e.grantGeneration,ref:e.ref,fence:r.fence,patch:{status:"waiting",errorCode:"APP_SYNC_REATTACH_PENDING",needsReconcile:true},now:this.now()}),null;let s=await this.readRemoteDocument(n.docId,r);if(s.appGrantId!==r.grant.grantId||s.appGrantGeneration!==r.grant.generation)return null;if(U(s.markdown)!==s.markdownVersion||!this.scopeRegistry.validateFrontMatter(e.ref,s.markdown).valid)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);this.markReattached(r.binding,r.grant,e.ref,r,s);let i=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:s,pending:i}}markReattached(e,n,r,o,s){this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)&&this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{needsReattach:false,needsReconcile:true,...s?{listedRevision:s.currentRevision,listedFingerprint:s.markdownVersion}:{},appGrantGeneration:n.generation,status:"waiting",errorCode:null},now:this.now()});}markPendingForReconcile(e,n,r,o,s){!this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)||!this.isFenceCurrent(o)||this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{status:"waiting",needsReconcile:true,errorCode:s},now:this.now()});}async applyConditionalSave(e,n,r,o,s,i,a){let c={kind:"conditional_save",binding:a.binding,grant:a.grant,ref:e,documentId:n,expectedLocalVersion:r.localVersion,expectedRemoteRevision:o,expectedRemoteFingerprint:s,markdown:r.markdown,markdownFingerprint:r.localFingerprint,needsReattach:i,fence:a.fence,beforeDispatch:async()=>{if(a.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(a.binding.accountKey,T,ae(e)))return {ok:false,reason:"deleted"};let S=await this.inspectLocal(e,a);return !S.exists||S.localVersion!==r.localVersion||S.localFingerprint!==r.localFingerprint?{ok:false,reason:"stale"}:(a.fence.assertCurrent(),{ok:true,localVersion:S.localVersion,markdown:S.markdown,fingerprint:S.localFingerprint})}},u;try{u=await this.applyEffect(c,a);}catch(S){throw this.isFenceCurrent(a)&&!gt(S)&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),S}if(u.status==="applied")return this.recordOutcome(a,e,r.localFingerprint,r.localFingerprint,n,"synced",null),"complete";if(u.status==="deferred"||u.status==="failed")return u.dispatch==="attempted"&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),"retry";let p=this.continuationStore.getPendingDiscovery(a.binding.bindingId,a.grant.grantId,a.grant.generation,e),f=await this.readRemoteById(n,p,a);if(!f)return "complete";let _=await this.inspectLocal(e,a);if(u.status==="conflict"||_.exists&&_.localFingerprint!==f.markdownVersion)return this.preserveConflict(p??tr(a,e,n,f),_,f,a);if(_.exists&&_.localFingerprint===f.markdownVersion){let S={kind:"attach_equal",binding:a.binding,grant:a.grant,ref:e,document:f,expectedLocalVersion:_.localVersion,expectedLocalFingerprint:_.localFingerprint,fence:a.fence};return (await this.applyEffect(S,a)).status==="applied"?(this.recordOutcome(a,e,_.localFingerprint,f.markdownVersion,n,"synced",null),"complete"):"retry"}return "retry"}async applyEffect(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.applyContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=false,s;if(e.kind==="conditional_save"){let i={...e,beforeDispatch:async()=>{o=true;let a=await e.beforeDispatch();return n.fence.assertCurrent(),a}};if(s=await r(i),s.dispatch==="attempted"&&!o)throw new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if((s.status==="applied"||s.status==="conflict")&&s.dispatch!=="attempted")throw new g("APP_SYNC_ADAPTER_DID_NOT_DISPATCH")}else s=await r(e);return n.fence.assertCurrent(),s}async reconcileAfterLocalRace(e,n,r){let o=await this.inspectLocal(e.ref,r);if(!o.exists){let s={kind:"create_absent",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:null,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,n.markdownVersion,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}if(o.localFingerprint===n.markdownVersion){let s={kind:"attach_equal",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:o.localVersion,expectedLocalFingerprint:o.localFingerprint,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,o.localFingerprint,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}return this.preserveConflict(e,o,n,r)}async preserveConflict(e,n,r,o){if(!n.exists)return "retry";let s=o.fence.rootFingerprint,i=`c_${ae(JSON.stringify([o.binding.bindingId,o.grant.grantId,o.grant.generation,e.ref,n.localVersion,r.currentRevision,r.markdownVersion]))}`,a={conflictId:i,bindingId:o.binding.bindingId,accountKey:o.binding.accountKey,workspaceId:o.binding.workspaceId,rootFingerprint:s,grantId:o.grant.grantId,grantGeneration:o.grant.generation,scopeVersion:o.grant.scopeVersion,ref:e.ref,documentId:r.docId,localVersion:n.localVersion,localFingerprint:n.localFingerprint,baselineRevision:n.baseline?.revision??null,baselineFingerprint:n.baseline?.markdownVersion??null,remoteRevision:r.currentRevision,remoteFingerprint:r.markdownVersion,needsReattach:e.needsReattach,vaultHandle:null,preservationStatus:"pending",state:"open",supersededBy:null,resolutionRequestId:null,resolutionChoice:null,cleanupPending:false,createdAt:this.now(),updatedAt:this.now()},c=this.continuationStore.putConflict({conflict:a,fence:o.fence});if(this.recordOutcome(o,e.ref,n.localFingerprint,n.baseline?.markdownVersion??null,r.docId,"conflict","APP_SYNC_CONFLICT"),c.preservationStatus==="ready"&&c.vaultHandle)return this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),"complete";try{o.fence.assertCurrent();let u=await this.continuation.conflictVault.preserve({accountKey:o.binding.accountKey,conflictId:i,markdown:r.markdown,fingerprint:r.markdownVersion,fence:o.fence});if(o.fence.assertCurrent(),!nr(u.handle)||u.fingerprint!==r.markdownVersion||U(r.markdown)!==u.fingerprint)throw new g("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return c=this.continuationStore.putConflict({conflict:{...a,vaultHandle:u.handle,preservationStatus:"ready",updatedAt:this.now()},fence:o.fence}),c.preservationStatus==="ready"&&this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),c.preservationStatus==="ready"?"complete":"retry"}catch(u){if(!this.isFenceCurrent(o))throw u;return this.continuationStore.putConflict({conflict:{...a,preservationStatus:"failed",updatedAt:this.now()},fence:o.fence}),this.markPendingForReconcile(o.binding,o.grant,e.ref,o,"APP_SYNC_CONFLICT_ARCHIVE_FAILED"),"retry"}}recordOutcome(e,n,r,o,s,i,a){this.continuationStore.recordContinuationOutcome({binding:e.binding,grant:e.grant,ref:n,sourceFingerprint:r,syncedFingerprint:o,documentId:s,status:i,errorCode:a,fence:e.fence,now:this.now()});}async readRemoteById(e,n,r){return n?this.readPendingDocument(n,r):this.readRemoteDocument(e,r)}async readRemoteDocument(e,n){n.fence.assertCurrent();let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e,signal:n.fence.signal,fence:n.fence});if(n.fence.assertCurrent(),!r||r.docId!==e||U(r.markdown)!==r.markdownVersion)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);return r}async applyHumanResolution(e,n,r){if(r.fence.assertCurrent(),n.state==="superseded"&&e.choice==="keep_both"){let E=await this.inspectLocal(n.ref,r);return !E.exists||E.localVersion!==e.expectedLocalVersion||E.localFingerprint!==n.localFingerprint?{status:"stale"}:(await this.readVerifiedArchive(n,r),{status:"resolved"})}let o=await this.readRemoteDocument(n.documentId,r);if(!this.scopeRegistry.validateFrontMatter(n.ref,o.markdown).valid)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let s=o.appGrantId===r.grant.grantId&&o.appGrantGeneration===r.grant.generation;if(!s&&(!n.needsReattach||o.appGrantGeneration>=r.grant.generation))throw new g("DOC_APP_GRANT_STALE",409);let i=await this.inspectLocal(n.ref,r);if(!i.exists)return {status:"stale"};let a=o.currentRevision===e.expectedRemoteRevision&&o.markdownVersion===e.expectedRemoteFingerprint,c=o.currentRevision===n.remoteRevision&&o.markdownVersion===n.remoteFingerprint;if(!a||!c)return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};if(!(i.localVersion===e.expectedLocalVersion&&i.localFingerprint===n.localFingerprint))return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};let p=await this.readVerifiedArchive(n,r);if(e.choice==="keep_both")return {status:"resolved"};if(e.choice==="use_cloud"){let E={kind:"cas_pull",binding:r.binding,grant:r.grant,ref:n.ref,document:{...o,markdown:p},expectedLocalVersion:e.expectedLocalVersion,fence:r.fence},R;try{R=await this.applyEffect(E,r);}catch(I){throw gt(I)?I:new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN")}if(R.status==="applied")return {status:"resolved"};if(R.status==="stale_local")return i=await this.inspectLocal(n.ref,r),i.exists&&i.localFingerprint===o.markdownVersion?{status:"resolved"}:{status:"stale",...i.exists?{refreshed:{local:i,remote:o}}:{}};if(R.status==="conflict"){let I=await this.readRemoteDocument(n.documentId,r),Ae=await this.inspectLocal(n.ref,r);return {status:"stale",...Ae.exists?{refreshed:{local:Ae,remote:I}}:{}}}if(R.status==="failed"||R.status==="deferred")throw R.dispatch==="attempted"?new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new g(R.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}if(n.needsReattach||!s){let E=this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,fingerprint:o.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}),R={session:e.session,eligibility:e.eligibility,appVersion:e.appVersion};E.status!=="completed"&&await this.dispatchReattachCreation(r.binding,r.grant,r.session,E,R);let I=await this.readRemoteDocument(n.documentId,r);if(I.appGrantId!==r.grant.grantId||I.appGrantGeneration!==r.grant.generation||I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion){let Ae=await this.inspectLocal(n.ref,r);if(I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion)return {status:"stale",...Ae.exists?{refreshed:{local:Ae,remote:I}}:{}};throw new g("APP_SYNC_REATTACH_PENDING")}}let _=false,S={kind:"conditional_save",binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,markdown:i.markdown,markdownFingerprint:i.localFingerprint,needsReattach:false,fence:r.fence,beforeDispatch:async()=>{_=true,r.fence.assertCurrent();let E=await this.inspectLocal(n.ref,r);return !E.exists||E.localVersion!==e.expectedLocalVersion||E.localFingerprint!==n.localFingerprint?{ok:false,reason:"stale"}:{ok:true,localVersion:E.localVersion,markdown:E.markdown,fingerprint:E.localFingerprint}}},w;try{w=await this.applyEffect(S,r);}catch(E){throw gt(E)?E:_?new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):E}if(w.status==="applied")return {status:"resolved"};if(w.status==="conflict"){let E=await this.readRemoteDocument(n.documentId,r),R=await this.inspectLocal(n.ref,r);return {status:"stale",...R.exists?{refreshed:{local:R,remote:E}}:{}}}if(w.status==="stale_local"){let E=await this.readRemoteDocument(n.documentId,r),R=await this.inspectLocal(n.ref,r);return R.exists&&R.localFingerprint===E.markdownVersion?{status:"resolved"}:{status:"stale",...R.exists?{refreshed:{local:R,remote:E}}:{}}}if(w.status==="failed"||w.status==="deferred")throw w.dispatch==="attempted"?new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new g(w.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}async cleanupResolvedConflict(e,n){let r=e;if(this.recordOutcome(n,r.ref,r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.state==="kept_both"?r.baselineFingerprint:r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.documentId,r.state==="kept_both"?"conflict":"synced",r.state==="kept_both"?"APP_SYNC_CONFLICT_KEPT_BOTH":null),r.cleanupPending&&r.vaultHandle)try{n.fence.assertCurrent(),await this.continuation.conflictVault.remove({accountKey:n.binding.accountKey,handle:r.vaultHandle,fence:n.fence}),n.fence.assertCurrent(),this.continuationStore.finishConflictArchiveCleanup({conflictId:r.conflictId,fence:n.fence,now:this.now()}),r=this.continuationStore.getConflict(r.conflictId)??r;}catch{}let{vaultHandle:o,...s}=r;return {status:r.state==="kept_both"?"kept_both":"resolved",conflict:{...s,sessionEpoch:n.session.epoch},cleanupPending:r.cleanupPending}}async readVerifiedArchive(e,n){if(e.preservationStatus!=="ready"||!e.vaultHandle)throw new g("APP_SYNC_CONFLICT_NOT_PRESERVED",409);n.fence.assertCurrent();let r=await this.continuation.conflictVault.read({accountKey:n.binding.accountKey,handle:e.vaultHandle,expectedFingerprint:e.remoteFingerprint,fence:n.fence});if(n.fence.assertCurrent(),r.fingerprint!==e.remoteFingerprint||U(r.markdown)!==e.remoteFingerprint||!this.scopeRegistry.validateFrontMatter(e.ref,r.markdown).valid)throw new g("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return r.markdown}async refreshConflictAfterStale(e,n){n.fence.assertCurrent();let r=await this.inspectLocal(e.ref,n),o=await this.readRemoteDocument(e.documentId,n);r.exists&&(r.localVersion===e.localVersion&&r.localFingerprint===e.localFingerprint&&o.docId===e.documentId&&o.currentRevision===e.remoteRevision&&o.markdownVersion===e.remoteFingerprint||await this.preserveConflict(tr(n,e.ref,o.docId,o),r,o,n));}archiveFenceGrant(e,n){return e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion?er(e):{grantId:n.grantId,appId:T,generation:n.grantGeneration,scopeVersion:n.scopeVersion,scope:_e}}purgeFenceGrant(e){if(e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion)return er(e);let n=this.continuationStore.listConflicts(e.bindingId)[0];return {grantId:n?.grantId??"account-data-purge",appId:T,generation:n?.grantGeneration??1,scopeVersion:this.scopeRegistry.scopeVersion,scope:_e}}createArchiveFenceContext(e,n,r,o={}){if(n.scopeVersion!==this.scopeRegistry.scopeVersion||!this.sessionFence.isCurrent(r)||r.accountKey!==e.accountKey)throw new g("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,n.grantId,n.generation),i=ae(JSON.stringify(e.rootSegments)),a;a=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:i,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:s.signal,assertCurrent:()=>this.assertArchiveFenceCurrent(e,n,r,s,o)});let c={binding:e,grant:n,session:r,grantToken:s,fence:a};return a.assertCurrent(),c}assertArchiveFenceCurrent(e,n,r,o,s){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||this.sessionFence.activeAccountKey!==e.accountKey||this.sessionFence.activeSessionEpoch!==r.epoch||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.generation!==n.generation)throw new g("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING");let i=this.dependencies.store.getBinding(e.bindingId);if(!i){let a=s.purgeRequestId?this.continuationStore.getAccountDataPurge(s.purgeRequestId):void 0;if(a?.state==="complete"&&a.bindingId===e.bindingId&&a.accountKey===e.accountKey&&a.workspaceId===e.workspaceId&&a.rootFingerprint===ae(JSON.stringify(e.rootSegments)))return;throw new g("APP_SYNC_ROOT_STALE")}if(i.accountKey!==e.accountKey||i.workspaceId!==e.workspaceId||ae(JSON.stringify(i.rootSegments))!==ae(JSON.stringify(e.rootSegments)))throw new g("APP_SYNC_ROOT_STALE");if(i.grantId!==e.grantId||i.grantGeneration!==e.grantGeneration||i.scopeVersion!==e.scopeVersion)throw new g("DOC_APP_GRANT_STALE",409);if(i.status==="stopping")throw new g("APP_SYNC_REVOKE_PENDING",409);if(!s.allowNonTransferStatus&&!Qn(i.status))throw new g("DOC_APP_GRANT_REQUIRED",409);if(i.grantId&&(i.grantId!==n.grantId||i.grantGeneration!==n.generation||i.scopeVersion!==n.scopeVersion))throw new g("DOC_APP_GRANT_STALE",409)}createFenceContext(e,n,r,o){if(!e.grantId||!e.grantGeneration||!e.scopeVersion||e.grantId!==n.grantId||e.grantGeneration!==n.generation||e.scopeVersion!==n.scopeVersion||n.scopeVersion!==this.scopeRegistry.scopeVersion)throw new g("DOC_APP_GRANT_STALE",409);let s=ae(JSON.stringify(e.rootSegments)),i;i=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:s,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:o.signal,assertCurrent:()=>this.assertFenceCurrent(e,n,r,o)});let a={binding:e,grant:n,session:r,grantToken:o,fence:i};return i.assertCurrent(),a}assertFenceCurrent(e,n,r,o){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||o.grantId!==n.grantId||o.generation!==n.generation||o.accountKey!==e.accountKey)throw new g("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING");let s=this.dependencies.store.getBinding(e.bindingId);if(!s||s.accountKey!==e.accountKey||s.workspaceId!==e.workspaceId||ae(JSON.stringify(s.rootSegments))!==ae(JSON.stringify(e.rootSegments)))throw new g("APP_SYNC_ROOT_STALE");if(s.grantId!==n.grantId||s.grantGeneration!==n.generation||s.scopeVersion!==n.scopeVersion)throw new g("DOC_APP_GRANT_STALE",409);if(s.status==="revoked"||s.status==="stopping"||s.status==="unavailable")throw new g(s.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED",409)}isFenceCurrent(e){try{return e.fence.assertCurrent(),!0}catch{return false}}},Ga=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","TOKEN_EXPIRED","DOC_SCOPE_REQUIRED","DOC_PILOT_NOT_ALLOWED","DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE","DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH","APP_SYNC_SESSION_STALE","APP_SYNC_ROOT_STALE","APP_SYNC_REVOKE_PENDING"]);function ae(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Mo(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function J(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!t.includes("\0")}function un(t){if(typeof t!="string"||t.length>40)return false;let e=Date.parse(t);return Number.isFinite(e)&&new Date(e).toISOString()===t}function nr(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function Fo(t){return t?.featureEnabled===true&&t.ownerAllowlisted===true}function Qn(t){return t==="checking"||t==="syncing"||t==="synced"||t==="partial"}function ja(t){if(!t||!J(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\")))throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Wa(t){if(!t||t.intent!=="device_account_data_deleted"||!J(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!J(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity))throw new g("APP_SYNC_ACCOUNT_DATA_PURGE_INPUT_INVALID",400)}function Ka(t){if(!t||!t.session||!J(t.bindingId,128)||!t.session.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!J(t.conflictId,128)||!J(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!J(t.appVersion,128)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!nr(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new g("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID",400)}function Fe(t){return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error&&/^[A-Z0-9_:-]{1,128}$/.test(t.message)?t.message:"APP_SYNC_OPERATION_FAILED"}function qo(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function gt(t){return Ga.has(Fe(t))}function Va(t){return Fe(t)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"||Fe(t)==="APP_SYNC_REATTACH_PENDING"}function Zn(t){let e=Fe(t);return /^[A-Z0-9_:-]{1,128}$/.test(e)?e:"APP_SYNC_OPERATION_FAILED"}function za(t){if(gt(t))return false;let e=qo(t);return e===408||e===409||e===429||e!==void 0&&e>=500||new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","APP_SYNC_REATTACH_RESPONSE_UNKNOWN","APP_SYNC_SAVE_RESPONSE_UNKNOWN"]).has(Fe(t))}function Ya(t){return Fe(t)==="DOC_APP_GRANT_STALE"||Fe(t)==="DOC_APP_CURSOR_INVALID"}function er(t){if(!t.grantId||!t.grantGeneration||!t.scopeVersion)throw new g("DOC_APP_GRANT_REQUIRED",409);return {grantId:t.grantId,appId:T,generation:t.grantGeneration,scopeVersion:t.scopeVersion,scope:_e}}function Uo(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==ae(JSON.stringify(e.rootSegments))||t.scopeVersion!==Xe)throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function tr(t,e,n,r){return {bindingId:t.binding.bindingId,accountKey:t.binding.accountKey,grantId:t.grant.grantId,grantGeneration:t.grant.generation,ref:e,docId:n,listedRevision:r.currentRevision,listedFingerprint:r.markdownVersion,appGrantGeneration:r.appGrantGeneration,needsReattach:r.appGrantId!==t.grant.grantId||r.appGrantGeneration!==t.grant.generation,needsReconcile:true,status:"waiting",errorCode:null,attempts:0,updatedAt:Date.now()}}var Xa=12e4,Qa=1e4,Za=1e3,ed=15*6e4,td=4,rr=new Set(["DOC_STORAGE_LIMIT_REACHED","DOC_SYNC_LIMIT","DOC_PILOT_NOT_ALLOWED"]),Bt=new Set(["DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH"]),or=new Set(["DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE"]),pn=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","DOC_SCOPE_REQUIRED","TOKEN_EXPIRED"]),nd=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]),g=class extends Error{constructor(n,r,o){super(n);this.code=n;this.status=r;this.retryAfterMs=o;this.name="AppSyncRemoteError";}code;status;retryAfterMs},ar=class{constructor(e){this.dependencies=e;if(e.continuation&&e.continuation.store!==e.store)throw new Error("APP_SYNC_CONTINUATION_STORE_MISMATCH");if(e.createLedger&&e.remote.capabilities?.dispatchGate!==true)throw new Error("APP_SYNC_DISPATCH_GATE_UNSUPPORTED");if(e.createLedger&&!e.store.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");this.scopeRegistry=e.scopeRegistry??new Ut,this.sessionFence=e.sessionFence??new Ft,this.now=e.now??Date.now,this.createId=e.createId??crypto.randomUUID,this.continuationRuntime=e.continuation?new ln(e,this.scopeRegistry,this.sessionFence,this.now,this.createId,n=>this.hasPendingRevoke(n)):null;}dependencies;scopeRegistry;sessionFence;now;createId;scanRuns=new Map;tickRuns=new Map;remoteReadSemaphore=new cr(td);continuationRuntime;scanEpoch=0;get activeSessionEpoch(){return this.sessionFence.activeSessionEpoch}async bind(e){let n=this.requireAuthenticatedAccount(e.session),r=_t(e.resolvedRootSegments);if(!r)throw new Error("APP_SYNC_ROOT_INVALID");if(typeof e.workspaceId!="string"||e.workspaceId.trim().length===0||e.workspaceId.length>256)throw new Error("APP_SYNC_WORKSPACE_INVALID");let o=this.sessionFence.activeAccountKey,s=this.sessionFence.activate(n);o&&o!==n&&await this.suspendBindingsForAccount(o,"account_switch");let i=this.dependencies.store.bind({bindingId:this.createId(),accountKey:n,workspaceId:e.workspaceId,appId:T,rootSegments:r,now:this.now()});return this.isCurrent(s)?(this.hasPendingRevoke(i.bindingId)?await this.holdPendingRevoke(i):this.isEligible(e.eligibility)?this.dependencies.store.updateBinding(i.bindingId,{status:"checking"},this.now()):(this.dependencies.store.updateBinding(i.bindingId,{status:"unavailable"},this.now()),this.sessionFence.suspend(n),await this.dependencies.documents.suspendBinding({binding:i,grantId:i.grantId,generation:i.grantGeneration,reason:"ineligible"})),this.dependencies.store.getBinding(i.bindingId)??i):i}scan(e,n){let r=this.dependencies.store.getBinding(e),o=r!==void 0&&(!n.session.authenticated||!n.session.accountKey||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility));o&&(this.scanEpoch+=1,this.sessionFence.suspend(r.accountKey));let s=`${e}:${n.session.accountKey??"signed-out"}:${this.scanEpoch}:${n.eligibility?.featureEnabled===true?1:0}:${n.eligibility?.ownerAllowlisted===true?1:0}`,i=o?void 0:this.scanRuns.get(s);if(i)return i;let a=this.performScan(e,n).finally(()=>{this.scanRuns.get(s)===a&&this.scanRuns.delete(s);});return o||this.scanRuns.set(s,a),a}tick(e,n){let r=this.dependencies.store.getBinding(e);r&&(!n.session.authenticated||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility))&&this.sessionFence.suspend(r.accountKey);let o=this.tickRuns.get(e),i=(o?o.catch(()=>{}):Promise.resolve()).then(()=>this.performTick(e,n)).finally(()=>{this.tickRuns.get(e)===i&&this.tickRuns.delete(e);});return this.tickRuns.set(e,i),i}async performTick(e,n){let r=await this.scan(e,n),o=this.dependencies.store.getBinding(e);if(o&&this.hasPendingRevoke(e))return await this.holdPendingRevoke(o),this.snapshot(e);if(!r.binding||!this.isTransferStatus(r.status))return r;let s=this.dependencies.store.getBinding(e);if(!s?.grantId||!s.grantGeneration||!s.scopeVersion)return this.snapshot(e);let i=await this.activateSession(s.accountKey);if(!i||!this.isCurrent(i))return this.snapshot(e);let a=this.grantFromBinding(s),c=this.sessionFence.captureGrant(i,a.grantId,a.generation);try{if(this.continuationRuntime&&await this.continuationRuntime.tick(s,a,i,c,n),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}if(!this.isCurrent(i)||!this.isCurrent(c))return this.snapshot(e);let u=this.dependencies.store.listResults(e),p=this.dependencies.store.listRunnableCreations(e,a.grantId,a.generation,this.now()),f=this.limitCreationClaims(s.accountKey,p);if(await Promise.all([...u.filter(_=>!this.continuationRuntime&&this.shouldReconcile(_,a)).map(_=>this.reconcileExisting(s,a,c,_)),...f.map(_=>this.dispatchCreation(s,a,i,_,n))]),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}return !this.isCurrent(i)||!this.isCurrent(c)?this.snapshot(e):(this.refreshBindingStatus(e),this.snapshot(e))}finally{this.sessionFence.release(c);}}limitCreationClaims(e,n){let r=this.dependencies.createLedger;if(!r)return n;try{let o=r.peek(e,this.now());return o.available?n.slice(0,o.remaining):[]}catch(o){return this.dependencies.onAdapterError?.(o),[]}}makeDispatchGate(e){let n=this.dependencies.createLedger;if(n)return qt({ledger:n,accountKey:e.accountKey,requestId:e.requestId,source:e.source,now:this.now,guard:()=>{if(e.token.signal.aborted||!this.isCurrent(e.token)||!this.bindingHasGrant(e.bindingId,e.grant))throw new g("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING")}})}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}recordMissingDispatchGate(e){let n=new g("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger?.reserveForced({...e,now:this.now()});}catch(r){this.dependencies.onAdapterError?.(r);}return this.dependencies.onAdapterError?.(n),n}async suspendAccount(e){/^[0-9a-f]{64}$/.test(e)&&(this.scanEpoch+=1,this.sessionFence.suspend(e),await this.suspendBindingsForAccount(e,"logout"));}async invalidateGrant(e){let n=this.dependencies.store.getBinding(e.bindingId),r=e.session.accountKey;!n||!e.session.authenticated||!r||n.accountKey!==r||n.grantId!==e.grantId||n.grantGeneration!==e.generation||(this.scanEpoch+=1,this.sessionFence.suspend(r),this.sessionFence.cancelGrant(r,e.grantId,e.generation),this.dependencies.store.invalidateGrantJobs(n.bindingId,e.grantId,e.generation,this.now()),this.dependencies.store.updateBinding(n.bindingId,{status:this.hasPendingRevoke(n.bindingId)?"stopping":"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:n,grantId:e.grantId,generation:e.generation,reason:"revoked"}));}async beginControlRequest(e){let{binding:n,accountKey:r,rootFingerprint:o}=this.validateControlIdentity(e),s=e.requestId;if(typeof s!="string"||s.length<1||s.length>128||s.includes("\0"))throw new Error("APP_SYNC_REQUEST_ID_INVALID");if(e.kind!=="connect"&&e.kind!=="revoke")throw new Error("APP_SYNC_CONTROL_REQUEST_KIND_INVALID");if(e.kind==="connect"&&n.grantId&&n.grantGeneration){let p=this.dependencies.store.getConfirmedRevoke(n.bindingId,n.grantId,n.grantGeneration);if(!(n.status==="revoked"||p!==void 0)&&!this.dependencies.store.getControlRequest(s))throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_GRANTED")}let i=e.kind==="revoke"?e.grantId??null:null,a=e.kind==="revoke"?e.generation??null:null;if(e.kind==="revoke"&&(!i||!Number.isSafeInteger(a)||a<1||i!==n.grantId||a!==n.grantGeneration))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");if(e.kind==="connect"&&(e.grantId!=null||e.generation!=null))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let c=this.now(),u=this.dependencies.store.beginControlRequest({requestId:s,bindingId:n.bindingId,accountKey:r,appId:T,workspaceId:n.workspaceId,rootFingerprint:o,kind:e.kind,state:"pending",grantId:i,generation:a,createdAt:c,updatedAt:c,resolvedAt:null,resolution:null,resolutionId:null});return u.kind==="revoke"&&(u.state==="pending"||u.state==="unknown")&&await this.holdPendingRevoke(n),u}getControlRequest(e){let{rootFingerprint:n}=this.validateControlIdentity(e),r=this.dependencies.store.getControlRequest(e.requestId);if(r&&!od(r,e,n))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return r}getPendingControlRequest(e){let{binding:n}=this.validateControlIdentity(e);return this.dependencies.store.getPendingControlRequest(n.bindingId)}async markControlRequestUnknown(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(n.state==="unknown")return n;if(n.state!=="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED");let r=this.dependencies.store.updateControlRequest(n.requestId,{state:"unknown",grantId:n.grantId,generation:n.generation,resolution:null,resolutionId:null,resolvedAt:null,now:this.now()});if(r.kind==="revoke"){let o=this.dependencies.store.getBinding(r.bindingId);o&&await this.holdPendingRevoke(o);}return r}async resolveControlRequest(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(e.outcome!=="confirmed"&&e.outcome!=="failed")throw new Error("APP_SYNC_CONTROL_REQUEST_OUTCOME_INVALID");if(e.resolution!=="remote"&&e.resolution!=="human")throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_INVALID");if(typeof e.resolutionId!="string"||e.resolutionId.length<1||e.resolutionId.length>128||e.resolutionId.includes("\0"))throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_ID_INVALID");if(n.state==="confirmed"||n.state==="failed"){if(n.state===e.outcome&&n.resolution===e.resolution&&n.resolutionId===e.resolutionId)return n;throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED")}let r=n.grantId,o=n.generation;if(n.kind==="connect"&&e.outcome==="confirmed"){let c=e.observedGrant;if(!c||c.appId!==T||!c.grantId||!Number.isSafeInteger(c.generation)||c.generation<1||!this.scopeRegistry.matchesDefinition(c.scopeVersion,c.scope))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_INVALID");r=c.grantId,o=c.generation;}let s=this.now(),i=this.dependencies.store.updateControlRequest(n.requestId,{state:e.outcome,grantId:r,generation:o,resolution:e.resolution,resolutionId:e.resolutionId,resolvedAt:s,now:s}),a=this.dependencies.store.getBinding(i.bindingId);return a&&n.kind==="revoke"?e.outcome==="confirmed"?(n.grantId&&n.generation&&(this.sessionFence.cancelGrant(a.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(a.bindingId,n.grantId,n.generation,s)),this.dependencies.store.updateBinding(a.bindingId,{status:"revoked"},s),await this.suspendDocumentBinding(a,"revoked")):this.dependencies.store.updateBinding(a.bindingId,{status:"checking"},s):a&&n.kind==="connect"&&e.outcome==="confirmed"&&r&&o&&this.dependencies.store.updateBinding(a.bindingId,{grantId:r,grantGeneration:o,scopeVersion:this.scopeRegistry.scopeVersion,status:"checking"},s),i}async snapshot(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:dr(),results:[]};let r=this.dependencies.store.listResults(e),o=Bo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T));return {binding:n,status:n.status,counts:o,results:r}}async performScan(e,n){let r=this.dependencies.store.getBinding(e);if(!r)throw new Error("APP_SYNC_BINDING_NOT_FOUND");let o=this.dependencies.store.getPendingControlRequest(e);if(o?.kind==="revoke")return await this.holdPendingRevoke(r),this.snapshot(e);if(!n.session.authenticated||!n.session.accountKey)return await this.suspendAccount(r.accountKey),this.snapshot(e);if(n.session.accountKey!==r.accountKey)return this.sessionFence.suspend(r.accountKey),await this.suspendBindingsForAccount(r.accountKey,"account_switch"),this.snapshot(e);if(!this.isEligible(n.eligibility))return await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e);let s=await this.activateSession(r.accountKey);if(!s)return this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);this.dependencies.store.updateBinding(e,{status:"checking"},this.now());let i;try{i=await this.dependencies.remote.readGrant({accountKey:r.accountKey,appId:T,signal:s.signal});}catch(u){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=ft(u);return sr(u)&&!Bt.has(p)&&!rr.has(p)?await this.pauseAuthentication(r):Bt.has(p)||sd(u)?await this.pauseUnavailableBinding(r,p==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"):or.has(p)?(r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):ir(u)?this.dependencies.store.updateBinding(e,{status:"offline"},this.now()):await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)}if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(i.appId!==T||i.available!==true)return await this.pauseUnavailableBinding(r,i.available===true?"scope_mismatch":"ineligible"),this.snapshot(e);if(i.status==="none")return r.grantId&&r.grantGeneration?(await this.invalidateStoredGeneration(r,"revoked"),r=this.dependencies.store.getBinding(e)??r,this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):this.dependencies.store.updateBinding(e,{status:"consent_required"},this.now()),this.snapshot(e);if(i.status==="revoked")return r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),this.snapshot(e);if(i.status!=="active")return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);let a=i.grant;if(!a||a.appId!==T||!a.grantId||!Number.isSafeInteger(a.generation)||a.generation<1||!this.scopeRegistry.matchesDefinition(a.scopeVersion,a.scope))return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(this.dependencies.store.getConfirmedRevoke(e,a.grantId,a.generation))return this.sessionFence.suspend(r.accountKey),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),await this.suspendDocumentBinding(r,"revoked"),this.snapshot(e);o?.kind==="connect"&&this.dependencies.store.updateControlRequest(o.requestId,{state:"confirmed",grantId:a.grantId,generation:a.generation,resolution:"remote",resolutionId:"doc023-active",resolvedAt:this.now(),now:this.now()}),(r.grantId!==a.grantId||r.grantGeneration!==a.generation)&&r.grantId&&r.grantGeneration&&(this.sessionFence.cancelGrant(r.accountKey,r.grantId,r.grantGeneration),this.dependencies.store.invalidateGrantJobs(e,r.grantId,r.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:"regranted"})),this.dependencies.store.updateBinding(e,{grantId:a.grantId,grantGeneration:a.generation,scopeVersion:a.scopeVersion,status:"checking"},this.now()),r=this.dependencies.store.getBinding(e)??r;try{let u=await this.listAllowedRefs(r,s);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=new Set(u.map(f=>f.ref));for(let f of this.dependencies.store.listResults(e))!p.has(f.ref)&&f.status!=="deleted"&&this.writeResult(r,a,f.ref,{sourceFingerprint:null,syncedFingerprint:f.syncedFingerprint,documentId:f.documentId,status:"excluded",errorCode:"APP_FILE_MISSING_OR_OUT_OF_SCOPE"});u.sort((f,_)=>f.ref.localeCompare(_.ref));for(let[f,_]of u.entries()){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let S=crypto.createHash("sha256").update(_.ref,"utf8").digest("hex");if(this.dependencies.store.hasDeletedRef(r.accountKey,T,S)){let ke=this.dependencies.store.getResult(e,_.ref);this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:ke?.syncedFingerprint??null,documentId:ke?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});continue}let w=this.dependencies.store.getResult(e,_.ref);if(f>=500){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"blocked",errorCode:"APP_LOCAL_QUOTA"});continue}let E=await this.readEligibleFile(r,_.ref,s.signal);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(E.status==="unsafe"||E.status==="missing"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:E.status==="unsafe"?"APP_FILE_UNSAFE":"APP_FILE_MISSING"});continue}if(E.status==="read_error"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"failed",errorCode:"APP_FILE_READ_FAILED"});continue}let R=this.scopeRegistry.validateFrontMatter(_.ref,E.markdown),I=U(E.markdown);if(!R.valid){this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});continue}if(w?.status==="conflict"&&w.grantGeneration===a.generation)continue;if(w?.documentId&&w.grantGeneration===a.generation){if(w.status==="synced"&&w.syncedFingerprint===I)continue;let ke=w?.sourceFingerprint===I;this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w.syncedFingerprint,documentId:w.documentId,status:ke?w.status:"waiting",errorCode:ke?w.errorCode:null,nextAttemptAt:ke?w.nextAttemptAt:0});continue}if(w?.status==="failed"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I&&!pn.has(w.errorCode??"")||w?.status==="blocked"&&w.errorCode!=="APP_LOCAL_QUOTA"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I)continue;let Ae=this.dependencies.store.enqueueCreation({jobId:this.createId(),requestId:this.createId(),bindingId:e,accountKey:r.accountKey,grantId:a.grantId,grantGeneration:a.generation,ref:_.ref,fingerprint:I,now:this.now()}),O=w?.sourceFingerprint===I,Ie=w?.status==="failed"&&pn.has(w.errorCode??"");this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:Ae.status==="completed"?"processing":"waiting",errorCode:O&&!Ie?w.errorCode:null,nextAttemptAt:O&&!Ie?w.nextAttemptAt:0});}return this.refreshBindingStatus(e),this.snapshot(e)}catch{return this.isCurrent(s)?(await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)):this.snapshot(e)}}async listAllowedRefs(e,n){let r=new Map,o=new Set,s=null;for(let i=0;i<Qa;i+=1){if(this.hasPendingRevoke(e.bindingId))return [];let a=await this.dependencies.workspace.listAllowedFiles({rootSegments:e.rootSegments,selectors:Yn,cursor:s,pageSize:100,signal:n.signal});if(this.hasPendingRevoke(e.bindingId))return [];if(!this.isCurrent(n))return [];for(let c of a.entries)c.isSymlink||!c.staysWithinRoot||this.scopeRegistry.validateRef(c.ref).valid&&r.set(c.ref,{ref:c.ref});if(a.nextCursor===null)return [...r.values()];if(o.has(a.nextCursor))throw new Error("APP_SYNC_PAGE_CURSOR_REPEATED");o.add(a.nextCursor),s=a.nextCursor;}throw new Error("APP_SYNC_PAGE_LIMIT_REACHED")}async readEligibleFile(e,n,r){if(!this.scopeRegistry.validateRef(n).valid)return {status:"unsafe"};try{let o=await this.dependencies.workspace.readFile({rootSegments:e.rootSegments,ref:n,signal:r});return o.isSymlink||!o.staysWithinRoot?{status:"unsafe"}:{status:"ok",markdown:o.markdown}}catch(o){let s=ft(o);return s==="ENOENT"||s==="APP_FILE_MISSING"?{status:"missing"}:{status:"read_error"}}}async beforeDocumentDispatch(e,n,r,o){if(!this.isCurrent(r))return {ok:false,reason:"session_stale"};if(!this.bindingHasGrant(e.bindingId,n))return {ok:false,reason:"grant_stale"};if(this.hasPendingRevoke(e.bindingId))return {ok:false,reason:"control_request_pending"};if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o)))return {ok:false,reason:"deleted"};let s=await this.readEligibleFile(e,o,r.signal);return this.isCurrent(r)?this.hasPendingRevoke(e.bindingId)?{ok:false,reason:"control_request_pending"}:this.bindingHasGrant(e.bindingId,n)?this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o))?{ok:false,reason:"deleted"}:s.status!=="ok"?{ok:false,reason:s.status}:this.scopeRegistry.validateFrontMatter(o,s.markdown).valid?{ok:true,markdown:s.markdown,fingerprint:U(s.markdown)}:{ok:false,reason:"out_of_scope"}:{ok:false,reason:"grant_stale"}:{ok:false,reason:"session_stale"}}async readRemoteDocument(e){return this.remoteReadSemaphore.run(e.signal,()=>this.dependencies.remote.readDocument(e))}async dispatchCreation(e,n,r,o,s){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(o.accountKey!==e.accountKey||o.bindingId!==e.bindingId||o.grantId!==n.grantId||o.grantGeneration!==n.generation||e.grantId!==n.grantId||e.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(!this.isCurrent(r))return;if(o.operationKind==="reattach"){this.continuationRuntime?await this.continuationRuntime.dispatchReattachCreation(e,n,r,o,s):this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),Xa);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.dependencies.store.getResult(e.bindingId,i.ref);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(i.ref))){await this.markDeleted(e,n,i,c);return}let u=await this.readEligibleFile(e,i.ref,a.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(u.status!=="ok"){this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:u.status==="read_error"?"failed":"excluded",errorCode:u.status==="unsafe"?"APP_FILE_UNSAFE":u.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:u.status==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}if(!this.scopeRegistry.validateFrontMatter(i.ref,u.markdown).valid){this.writeResult(e,n,i.ref,{sourceFingerprint:U(u.markdown),syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(U(u.markdown)!==i.fingerprint){this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"processing",errorCode:null});let _=await this.dependencies.creationBudget.runCreate({accountKey:i.accountKey,signal:a.signal,dispatch:async()=>{if(this.hasPendingRevoke(e.bindingId))return {kind:"control_pending"};let O=await this.readEligibleFile(e,i.ref,a.signal);if(!this.isCurrent(a))throw new g("APP_SYNC_SESSION_STALE");if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(i.ref)))return {kind:"deleted"};if(O.status!=="ok")return {kind:"local_file",status:O.status};if(!this.scopeRegistry.validateFrontMatter(i.ref,O.markdown).valid)return {kind:"out_of_scope"};let Ie=U(O.markdown);if(Ie!==i.fingerprint)return {kind:"source_changed",fingerprint:Ie};let ke=this.makeDispatchGate({bindingId:e.bindingId,accountKey:i.accountKey,grant:n,token:a,requestId:i.requestId,source:"app_create"}),Co;try{Co=await this.dependencies.remote.createGrantedDocument({accountKey:i.accountKey,appId:T,ref:i.ref,requestId:i.requestId,markdown:O.markdown,appVersion:s.appVersion,appGrant:{grantId:i.grantId,generation:i.grantGeneration},signal:a.signal,...ke?{dispatchGate:ke}:{}});}catch(Wn){if(Wn instanceof je)return {kind:"budget_deferred",retryAt:Wn.retryAt};throw Wn}if(ke&&ke.calls===0)throw this.recordMissingDispatchGate({accountKey:i.accountKey,requestId:i.requestId,source:"app_create"});return {kind:"created",result:Co}}});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(_.status==="deferred"){let O=this.now();if(!this.deferClaim(i,_.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.retryAt});return}if(_.value.kind==="budget_deferred"){let O=this.now();if(!this.deferClaim(i,_.value.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.value.retryAt});return}if(_.value.kind!=="created"){let O=_.value;if(O.kind==="control_pending"){this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()}),this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now());return}if(O.kind==="deleted"){await this.markDeleted(e,n,i,c);return}if(O.kind==="source_changed"){this.writeResult(e,n,i.ref,{sourceFingerprint:O.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}let Ie=O.kind==="local_file"?O.status:"unsafe";this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:Ie==="read_error"?"failed":"excluded",errorCode:O.kind==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":Ie==="unsafe"?"APP_FILE_UNSAFE":Ie==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:Ie==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}let S=_.value.result;if(S.appGrantId!==n.grantId||S.appGrantGeneration!==n.generation)throw new g("DOC_APP_GRANT_STALE",409);let w=await this.readRemoteDocument({accountKey:i.accountKey,docId:S.docId,signal:a.signal});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(!this.validRemoteDocument(w,S,n)){this.recordOutcome(e,n,i.ref,i.fingerprint,c,S.docId,{status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH",dispatch:"none"}),this.dependencies.store.updateCreation(i.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()});return}let E=U(w.markdown),R,I=i.fingerprint;if(!S.replayed&&!S.reattached&&E===i.fingerprint&&w.markdownVersion===i.fingerprint)R=await this.dependencies.documents.attachCreated({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal});else {let O;if(R=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal,beforeDispatch:async()=>(O=await this.beforeDocumentDispatch(e,n,a,i.ref),O)}),!O&&R.dispatch!=="none")throw new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(R.dispatch==="attempted"&&!O)throw new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(O&&!O.ok){this.recordBeforeDispatchFailure(e,n,i.ref,c,O,i);return}O?.ok&&R.dispatch!=="none"&&(I=O.fingerprint);}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;let Ae=this.recordOutcome(e,n,i.ref,I,c,S.docId,R);this.dependencies.store.updateCreation(i.jobId,{status:Ae==="conflict"?"conflict":Ae==="failed"?"failed":R.status==="failed"&&R.retryAt!==void 0?"waiting":"completed",nextAttemptAt:R.status==="failed"&&R.retryAt!==void 0?this.retryAt(i.attempts+1,R.retryAt):0,now:this.now()});}catch(u){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;await this.handleCreationError(e,n,i,c,u);}finally{this.sessionFence.release(a);}}async reconcileExisting(e,n,r,o){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!o.documentId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation||o.status==="conflict"||o.status==="excluded"||o.status==="deleted"||!this.isCurrent(r))return;let s=await this.readEligibleFile(e,o.ref,r.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;if(s.status!=="ok"){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:s.status==="read_error"?"failed":"excluded",errorCode:s.status==="unsafe"?"APP_FILE_UNSAFE":s.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"});return}if(!this.scopeRegistry.validateFrontMatter(o.ref,s.markdown).valid){this.writeResult(e,n,o.ref,{sourceFingerprint:U(s.markdown),syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"failed",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});return}let a=U(s.markdown);if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o.ref))){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});return}let u;try{u=await this.readRemoteDocument({accountKey:e.accountKey,docId:o.documentId,signal:r.signal});}catch(p){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);return}if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(this.isCurrent(r)){if(u.appGrantId!==n.grantId||u.appGrantGeneration!==n.generation||U(u.markdown)!==u.markdownVersion){this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH"});return}this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"processing",errorCode:null});try{let p,f=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:o.ref,document:u,localMarkdown:s.markdown,sourceFingerprint:a,signal:r.signal,beforeDispatch:async()=>(p=await this.beforeDocumentDispatch(e,n,r,o.ref),p)});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r)||!this.bindingHasGrant(e.bindingId,n))return;if(!p&&f.dispatch!=="none"){await this.handleExistingError(e,n,o,a,new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(f.dispatch==="attempted"&&!p){await this.handleExistingError(e,n,o,a,new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(p&&!p.ok){this.recordBeforeDispatchFailure(e,n,o.ref,o,p);return}let _=p?.ok&&f.dispatch!=="none"?p.fingerprint:a;this.recordOutcome(e,n,o.ref,_,o,o.documentId,f);}catch(p){if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);}}}async handleCreationError(e,n,r,o,s){let i=ft(s);if(i==="DOC_APP_REF_DELETED"){await this.markDeleted(e,n,r,o);return}if(i==="DOC_APP_REF_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"excluded",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(Bt.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}if(or.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(i==="DOC_APP_BODY_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"failed",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"failed",nextAttemptAt:0,now:this.now()});return}if(rr.has(i)){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"blocked",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"blocked",nextAttemptAt:0,now:this.now()});return}if(sr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=this.retryAt(r.attempts,Ho(s,this.now())),c=ir(s);this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:c?"waiting":"failed",errorCode:i||"APP_SYNC_CREATE_FAILED",nextAttemptAt:c?a:0}),this.dependencies.store.updateCreation(r.jobId,{status:c?"waiting":"failed",nextAttemptAt:c?a:0,now:this.now()}),c&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async handleExistingError(e,n,r,o,s){let i=ft(s);if(i==="DOC_APP_REF_DELETED"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"deleted",errorCode:i});return}if(or.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(Bt.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:i,nextAttemptAt:this.now()});return}if(rr.has(i)){i==="DOC_PILOT_NOT_ALLOWED"&&await this.pauseUnavailableBinding(e,"ineligible"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"blocked",errorCode:i});return}if(sr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=ir(s),c=r.sourceFingerprint===o?r.attempts+1:1,u=a?this.retryAt(c,Ho(s,this.now())):0;this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:a?"waiting":"failed",errorCode:i||"APP_SYNC_RECONCILE_FAILED",nextAttemptAt:u,attempts:a?c:0}),a&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async markDeleted(e,n,r,o){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),this.dependencies.store.updateCreation(r.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});}recordOutcome(e,n,r,o,s,i,a){let c=a.status==="synced"&&a.syncedFingerprint===o?o:s?.syncedFingerprint??null,u=a.status==="synced"&&c!==o?"conflict":(a.status==="failed"||a.status==="waiting")&&a.retryAt!==void 0?"waiting":a.status,p=u==="waiting"&&a.retryAt!==void 0?s?.sourceFingerprint===o?s.attempts+1:1:u==="synced"||u==="conflict"?0:s?.sourceFingerprint===o?s.attempts:0;return this.writeResult(e,n,r,{sourceFingerprint:o,syncedFingerprint:c,documentId:i,status:u,errorCode:u==="conflict"&&a.status==="synced"?"DOC_SYNC_ACK_MISMATCH":a.errorCode??null,nextAttemptAt:u==="waiting"&&a.retryAt!==void 0?this.retryAt(p,a.retryAt):0,attempts:p}),u}recordBeforeDispatchFailure(e,n,r,o,s,i){if(s.reason==="session_stale"||s.reason==="grant_stale")return;if(s.reason==="deleted"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r),this.now()),this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),i&&this.dependencies.store.updateCreation(i.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}if(s.reason==="control_request_pending"){this.writeResult(e,n,r,{sourceFingerprint:o?.sourceFingerprint??null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),i&&this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}let a=s.reason==="read_error"?"failed":"excluded",c=s.reason==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":s.reason==="unsafe"?"APP_FILE_UNSAFE":s.reason==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED";this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:a,errorCode:c,nextAttemptAt:0}),i&&this.dependencies.store.updateCreation(i.jobId,{status:s.reason==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});}writeResult(e,n,r,o){let s=this.dependencies.store.getResult(e.bindingId,r),i=o.attempts??(s?.sourceFingerprint===o.sourceFingerprint?s.attempts:0);this.dependencies.store.upsertResult({bindingId:e.bindingId,accountKey:e.accountKey,ref:r,grantId:n.grantId,grantGeneration:n.generation,...o,nextAttemptAt:o.nextAttemptAt??0,attempts:i,updatedAt:this.now()});}validateControlIdentity(e){let n=this.requireAuthenticatedAccount(e.session),r=this.dependencies.store.getBinding(e.bindingId);if(!r||r.accountKey!==n)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");let o=_t(e.resolvedRootSegments);if(!o||r.workspaceId!==e.workspaceId||!rd(r.rootSegments,o))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return {binding:r,accountKey:n,rootFingerprint:Ue(JSON.stringify(o))}}hasPendingRevoke(e){let n=this.dependencies.store.getPendingControlRequest(e);return n?.kind==="revoke"&&(n.state==="pending"||n.state==="unknown")}async holdPendingRevoke(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_REVOKE_PENDING")),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),await this.suspendDocumentBinding(e,"revoke_pending");}async invalidateStoredGeneration(e,n){!e.grantId||!e.grantGeneration||(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.invalidateGrantJobs(e.bindingId,e.grantId,e.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n}));}async pauseUnavailableBinding(e,n){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_UNAVAILABLE")),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,n);}async pauseAuthentication(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"AUTH_REQUIRED",true)),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,"auth_required");}returnProcessingResultsToWaiting(e,n,r,o,s=false){for(let i of this.dependencies.store.listResults(e.bindingId)){let a=i.status==="processing",c=s&&i.status==="failed"&&pn.has(i.errorCode??"");i.grantId!==n||i.grantGeneration!==r||!a&&!c||this.dependencies.store.upsertResult({...i,status:"waiting",errorCode:o,nextAttemptAt:this.now(),updatedAt:this.now()});}}async suspendDocumentBinding(e,n){try{await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n});}catch(r){this.reportAdapterError(r);}}reportAdapterError(e){try{this.dependencies.onAdapterError?.(e);}catch{}}async activateSession(e){let n=this.sessionFence.activeAccountKey,r=this.sessionFence.activate(e);return n&&n!==e&&await this.suspendBindingsForAccount(n,"account_switch"),r}async suspendBindingsForAccount(e,n){for(let r of this.dependencies.store.listBindingsForAccount(e)){this.dependencies.store.updateBinding(r.bindingId,{status:"stopping"},this.now());try{await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:n});}catch(o){this.reportAdapterError(o);}finally{try{this.dependencies.store.updateBinding(r.bindingId,{status:this.hasPendingRevoke(r.bindingId)?"stopping":"local_only"},this.now());}catch(o){this.reportAdapterError(o);}}}}shouldReconcile(e,n){return e.documentId!==null&&e.grantId===n.grantId&&e.grantGeneration===n.generation&&(e.status==="processing"||e.status==="waiting"&&e.nextAttemptAt<=this.now())}validRemoteDocument(e,n,r){return e.docId===n.docId&&e.appGrantId===r.grantId&&e.appGrantGeneration===r.generation&&n.appGrantId===r.grantId&&n.appGrantGeneration===r.generation&&n.markdownVersion===e.markdownVersion&&U(e.markdown)===e.markdownVersion}grantFromBinding(e){if(!e.grantId||!e.grantGeneration||e.scopeVersion!==this.scopeRegistry.scopeVersion)throw new Error("APP_SYNC_BINDING_GRANT_INVALID");return {grantId:e.grantId,appId:T,generation:e.grantGeneration,scopeVersion:e.scopeVersion,scope:_e}}bindingHasGrant(e,n){let r=this.dependencies.store.getBinding(e);return r?.grantId===n.grantId&&r.grantGeneration===n.generation}isTransferStatus(e){return e==="checking"||e==="syncing"||e==="synced"||e==="partial"}isEligible(e){return e?.featureEnabled===true&&e?.ownerAllowlisted===true}requireAuthenticatedAccount(e){if(!e||e.authenticated!==true||typeof e.accountKey!="string"||!/^[0-9a-f]{64}$/.test(e.accountKey))throw new Error("APP_SYNC_SESSION_REQUIRED");return e.accountKey}isCurrent(e){return this.sessionFence.isCurrent(e)}refreshBindingStatus(e){let n=this.snapshotNow(e);if(!n.binding||["offline","unavailable","revoked","stopping","local_only","consent_required"].includes(n.binding.status))return;let r=n.counts,o=r.P+r.I>0?"syncing":r.F+r.C+r.B>0?"partial":"synced";this.dependencies.store.updateBinding(e,{status:o},this.now());}snapshotNow(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:dr(),results:[]};let r=this.dependencies.store.listResults(e);return {binding:n,status:n.status,counts:Bo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T)),results:r}}listConflicts(e){return this.continuationRuntime?this.continuationRuntime.listConflicts(e):[]}readConflictArchive(e){return this.continuationRuntime?this.continuationRuntime.readConflictArchive(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}resolveConflict(e){return this.continuationRuntime?this.continuationRuntime.resolveConflict(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}purgeAccountData(e){return this.continuationRuntime?this.continuationRuntime.purgeAccountData(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}retryAt(e,n){if(n!==void 0&&Number.isFinite(n))return Math.max(this.now(),n);let r=Math.min(Math.max(e-1,0),10);return this.now()+Math.min(Za*2**r,ed)}};function dr(){return {N:0,S:0,P:0,I:0,F:0,C:0,B:0,D:0}}function Bo(t,e){let n=dr(),r=n;for(let o of t)switch(o.status){case "synced":r.S+=1;break;case "waiting":r.P+=1;break;case "processing":r.I+=1;break;case "failed":r.F+=1;break;case "conflict":r.C+=1;break;case "blocked":r.B+=1;break;}return r.N=r.S+r.P+r.I+r.F+r.C+r.B,r.D=e,n}function rd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function od(t,e,n){return t.bindingId===e.bindingId&&t.accountKey===e.session.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===n&&t.appId===T}function Ue(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function ft(t){return t instanceof g||t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error?t.message:""}function Ho(t,e){if(t instanceof g&&t.retryAfterMs!==void 0||t&&typeof t=="object"&&"retryAfterMs"in t&&typeof t.retryAfterMs=="number")return e+Math.max(t.retryAfterMs,0)}function ur(t){return t instanceof g||t&&typeof t=="object"&&"status"in t&&typeof t.status=="number"?t.status:void 0}function sr(t){let e=ft(t);if(Bt.has(e))return false;let n=ur(t);return pn.has(e)||n===401||n===403}function sd(t){let e=ur(t);return e!==void 0&&e>=400&&e<500}function ir(t){let e=ur(t);return e!==void 0?e===408||e===425||e===429||e>=500:nd.has(ft(t))}var cr=class{constructor(e){this.limit=e;if(!Number.isSafeInteger(e)||e<1)throw new Error("INVALID_SEMAPHORE_LIMIT")}limit;active=0;waiters=[];async run(e,n){await this.acquire(e);try{return await n()}finally{this.release();}}acquire(e){return e.aborted?Promise.reject(this.abortError()):this.active<this.limit?(this.active+=1,Promise.resolve()):new Promise((n,r)=>{let o={signal:e,resolve:()=>{e.removeEventListener("abort",o.onAbort),n();},reject:s=>{e.removeEventListener("abort",o.onAbort),r(s);},onAbort:()=>{let s=this.waiters.indexOf(o);s>=0&&this.waiters.splice(s,1),o.reject(this.abortError());}};this.waiters.push(o),e.addEventListener("abort",o.onAbort,{once:true}),e.aborted&&o.onAbort();})}release(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(e.signal.aborted){e.reject(this.abortError());continue}e.resolve();return}this.active=Math.max(0,this.active-1);}abortError(){return Object.assign(new Error("APP_SYNC_SESSION_STALE"),{code:"APP_SYNC_SESSION_STALE"})}};d();P();d();P();L();d();P();M();q();L();F();br();d();P();M();q();L();F();d();Fr();d();P();M();q();L();d();F();var Ur=["outcome_plan","contract_check","feature_link","use_verify","result_review"];new Set(Ur);M();q();d();q();F();F();F();F();Pt();Pt();So();an();lt();Pt();Pt();Tt();d();P();d();var wa=["success","failed","completed"];new Set(wa);vn();Pt();yo();xn();var pp=[{key:"usageBackfill",field:"metadata.usageBackfill",before:"before_usage_backfill",after:"after_usage_backfill"},{key:"usageAccounting",field:"metadata.usageAccounting",before:"before_usage_accounting",after:"after_usage_accounting"},{key:"usageAccountingReason",field:"metadata.usageAccountingReason",before:"before_usage_accounting_reason",after:"after_usage_accounting_reason"},{key:"usageByEpoch",field:"metadata.usageByEpoch",before:"before_usage_by_epoch",after:"after_usage_by_epoch"},{key:"usageIncomplete",field:"metadata.usageIncomplete",before:"before_usage_incomplete",after:"after_usage_incomplete"}];["run_epoch","completed_at","input_tokens","output_tokens","cached_input_tokens","cost_usd","model",...pp.map(t=>t.field)];vn();d();P();M();q();L();F();Tt();lt();d();d();Qt();d();P();M();q();L();F();d();P();M();q();L();F();d();var Ra=["urgent","high","medium","low"],Ea=["investigating","in-progress","in-review","on-hold","done"];new Set(Ra);new Set(Ea);lt();new Set(Fs);new Set(Ms);new Set(Us);new Set(qs);new Set(Bs);d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();M();P();L();q();lt();F();d();P();d();P();M();L();L();d();P();M();L();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();lt();Tt();Br();Et.map(t=>`'${t}'`).join(", ");var Io=class extends D{handle;sqlite;constructor(e){super();let n=e??this.resolveDbPath();this.handle=x(n),this.sqlite=this.handle.sqlite,B(this.handle.db,n);}close(){this.handle.close();}bind(e){if(this.assertAccountKey(e.accountKey),this.assertText(e.bindingId,"bindingId",128),this.assertText(e.workspaceId,"workspaceId",256),e.appId!==T)throw new Error("APP_SYNC_APP_UNSUPPORTED");let n=_t(e.rootSegments);if(!n)throw new Error("APP_SYNC_ROOT_INVALID");let r=this.getBindingForAccountApp(e.accountKey,e.appId);if(r){if(r.workspaceId!==e.workspaceId||!Oa(r.rootSegments,n))throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");return r}try{this.sqlite.prepare(`
76
+ INSERT INTO app_sync_bindings (
77
+ binding_id, account_key, workspace_id, app_id, root_segments,
78
+ grant_id, grant_generation, scope_version, status, created_at, updated_at
79
+ ) VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL, 'local_only', ?, ?)
80
+ `).run(e.bindingId,e.accountKey,e.workspaceId,e.appId,JSON.stringify(n),e.now,e.now);}catch(s){let i=this.getBindingForAccountApp(e.accountKey,e.appId);if(i){if(i.workspaceId===e.workspaceId&&Oa(i.rootSegments,n))return i;throw new Error("APP_SYNC_ROOT_ALREADY_BOUND")}throw Op(s)?new Error("APP_SYNC_BINDING_ID_CONFLICT"):s}let o=this.getBinding(e.bindingId);if(!o)throw new Error("APP_SYNC_BINDING_WRITE_FAILED");return o}getBinding(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE binding_id = ?").get(e);return n?Ro(n):void 0}getBindingForAccountApp(e,n){let r=this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE account_key = ? AND app_id = ?").get(e,n);return r?Ro(r):void 0}beginControlRequest(e){let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.appId!==e.appId||n.workspaceId!==e.workspaceId||ye(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");if(this.assertAccountKey(e.accountKey),this.assertText(e.requestId,"requestId",128),this.assertText(e.workspaceId,"workspaceId",256),e.state!=="pending"||e.resolvedAt!==null||e.resolution!==null||e.resolutionId!==null)throw new Error("APP_SYNC_CONTROL_REQUEST_INITIAL_STATE_INVALID");if(!/^[0-9a-f]{64}$/.test(e.rootFingerprint))throw new Error("APP_SYNC_ROOT_FINGERPRINT_INVALID");if(e.kind==="revoke"&&(e.grantId!==n.grantId||e.generation!==n.grantGeneration||!e.grantId||!e.generation))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let r=this.getControlRequest(e.requestId);if(r){if(!Na(r,e))throw new Error("APP_SYNC_CONTROL_REQUEST_ID_REUSED");return r}try{this.sqlite.prepare(`
81
+ INSERT INTO app_sync_control_requests (
82
+ request_id, binding_id, account_key, app_id, workspace_id, root_fingerprint,
83
+ kind, state, grant_id, generation, created_at, updated_at, resolved_at, resolution, resolution_id
84
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
85
+ `).run(e.requestId,e.bindingId,e.accountKey,e.appId,e.workspaceId,e.rootFingerprint,e.kind,e.state,e.grantId,e.generation,e.createdAt,e.updatedAt,e.resolvedAt,e.resolution,e.resolutionId);}catch(s){let i=this.getControlRequest(e.requestId);if(i){if(!Na(i,e))throw new Error("APP_SYNC_CONTROL_REQUEST_ID_REUSED");return i}throw this.getPendingControlRequest(e.bindingId)?new Error("APP_SYNC_CONTROL_REQUEST_PENDING"):s}let o=this.getControlRequest(e.requestId);if(!o)throw new Error("APP_SYNC_CONTROL_REQUEST_WRITE_FAILED");return o}getControlRequest(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_control_requests WHERE request_id = ?").get(e);return n?Ao(n):void 0}getPendingControlRequest(e){let n=this.sqlite.prepare(`
86
+ SELECT * FROM app_sync_control_requests
87
+ WHERE binding_id = ? AND state IN ('pending', 'unknown')
88
+ ORDER BY created_at, request_id LIMIT 1
89
+ `).get(e);return n?Ao(n):void 0}getConfirmedRevoke(e,n,r){let o=this.sqlite.prepare(`
90
+ SELECT * FROM app_sync_control_requests
91
+ WHERE binding_id = ? AND kind = 'revoke' AND state = 'confirmed'
92
+ AND grant_id = ? AND generation = ?
93
+ ORDER BY resolved_at DESC, request_id LIMIT 1
94
+ `).get(e,n,r);return o?Ao(o):void 0}updateControlRequest(e,n){let r=this.getControlRequest(e);if(!r)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(r.state==="confirmed"||r.state==="failed"){if(r.state===n.state&&r.grantId===n.grantId&&r.generation===n.generation&&r.resolution===n.resolution&&r.resolutionId===n.resolutionId&&r.resolvedAt===n.resolvedAt)return r;throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED")}if(n.state==="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_STATE_TRANSITION_INVALID");if(n.state==="unknown"&&r.state!=="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_STATE_TRANSITION_INVALID");if(this.sqlite.prepare(`
95
+ UPDATE app_sync_control_requests
96
+ SET state = ?, grant_id = ?, generation = ?, resolution = ?, resolution_id = ?, resolved_at = ?, updated_at = ?
97
+ WHERE request_id = ? AND state IN ('pending', 'unknown')
98
+ `).run(n.state,n.grantId,n.generation,n.resolution,n.resolutionId,n.resolvedAt,n.now,e).changes===0)throw new Error("APP_SYNC_CONTROL_REQUEST_STATE_TRANSITION_INVALID");let s=this.getControlRequest(e);if(!s)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");return s}updateBinding(e,n,r){let o=this.getBinding(e);if(!o)throw new Error("APP_SYNC_BINDING_NOT_FOUND");let s=n.grantId===void 0?o.grantId:n.grantId,i=n.grantGeneration===void 0?o.grantGeneration:n.grantGeneration,a=n.scopeVersion===void 0?o.scopeVersion:n.scopeVersion,c=n.status===void 0?o.status:n.status;this.sqlite.prepare(`
99
+ UPDATE app_sync_bindings
100
+ SET grant_id = ?, grant_generation = ?, scope_version = ?, status = ?, updated_at = ?
101
+ WHERE binding_id = ?
102
+ `).run(s,i,a,c,r,e);}enqueueCreation(e){let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey)throw new Error("APP_SYNC_BINDING_ACCOUNT_MISMATCH");if(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration)throw new Error("APP_SYNC_GRANT_STALE");if(this.assertText(e.jobId,"jobId",128),this.assertText(e.requestId,"requestId",128),this.assertText(e.ref,"ref",256),!/^sha256:[0-9a-f]{64}$/.test(e.fingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");let r=()=>this.sqlite.prepare(`
103
+ SELECT * FROM app_sync_creation_jobs
104
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
105
+ AND operation_kind = 'create' AND status IN ('waiting', 'processing')
106
+ ORDER BY created_at, job_id LIMIT 1
107
+ `).get(e.bindingId,e.grantId,e.grantGeneration,e.ref,e.fingerprint),o=r();if(!o){let s=this.sqlite.prepare(`
108
+ SELECT job_id FROM app_sync_creation_jobs
109
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
110
+ AND operation_kind = 'create' AND status = 'failed'
111
+ ORDER BY created_at DESC, job_id DESC LIMIT 1
112
+ `).get(e.bindingId,e.grantId,e.grantGeneration,e.ref,e.fingerprint);s&&(this.sqlite.prepare(`
113
+ UPDATE app_sync_creation_jobs
114
+ SET status = 'waiting', next_attempt_at = 0, updated_at = ?
115
+ WHERE job_id = ? AND status = 'failed'
116
+ `).run(e.now,s.job_id),o=r());}if(o||(this.sqlite.prepare(`
117
+ INSERT OR IGNORE INTO app_sync_creation_jobs (
118
+ job_id, binding_id, account_key, grant_id, grant_generation, ref, request_id,
119
+ fingerprint, operation_kind, document_id, status, attempts, next_attempt_at, created_at, updated_at
120
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'create', NULL, 'waiting', 0, 0, ?, ?)
121
+ `).run(e.jobId,e.bindingId,e.accountKey,e.grantId,e.grantGeneration,e.ref,e.requestId,e.fingerprint,e.now,e.now),o=r()),!o)throw new Error("APP_SYNC_JOB_WRITE_FAILED");return jn(o)}listRunnableCreations(e,n,r,o){return this.sqlite.prepare(`
122
+ SELECT * FROM app_sync_creation_jobs
123
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ?
124
+ AND status IN ('waiting', 'processing') AND next_attempt_at <= ?
125
+ ORDER BY created_at, ref, job_id
126
+ `).all(e,n,r,o).map(jn)}claimCreation(e,n,r){if(this.sqlite.prepare(`
127
+ UPDATE app_sync_creation_jobs
128
+ SET status = 'processing', attempts = attempts + 1, next_attempt_at = ?, updated_at = ?
129
+ WHERE job_id = ? AND status IN ('waiting', 'processing') AND next_attempt_at <= ?
130
+ `).run(n+Math.max(r,1),n,e,n).changes===0)return;let s=this.sqlite.prepare("SELECT * FROM app_sync_creation_jobs WHERE job_id = ?").get(e);return s?jn(s):void 0}deferCreation(e,n,r){if(!e||typeof e.jobId!="string"||!Number.isSafeInteger(e.attempts)||e.attempts<1||!Number.isSafeInteger(e.nextAttemptAt)||!Number.isSafeInteger(n)||n<0||!Number.isSafeInteger(r)||r<0)throw new Error("INVALID_APP_SYNC_CREATION_CLAIM");return this.sqlite.prepare(`
131
+ UPDATE app_sync_creation_jobs
132
+ SET status = 'waiting', attempts = CASE WHEN attempts > 0 THEN attempts - 1 ELSE 0 END,
133
+ next_attempt_at = ?, updated_at = ?
134
+ WHERE job_id = ? AND status = 'processing' AND attempts = ? AND next_attempt_at = ?
135
+ `).run(n,r,e.jobId,e.attempts,e.nextAttemptAt).changes===1}updateCreation(e,n){this.sqlite.prepare(`
136
+ UPDATE app_sync_creation_jobs SET status = ?, next_attempt_at = ?, updated_at = ? WHERE job_id = ?
137
+ `).run(n.status,n.nextAttemptAt,n.now,e);}releaseProcessingCreations(e,n,r,o){this.sqlite.prepare(`
138
+ UPDATE app_sync_creation_jobs
139
+ SET status = 'waiting', next_attempt_at = ?, updated_at = ?
140
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND status = 'processing'
141
+ `).run(o,o,e,n,r);}invalidateGrantJobs(e,n,r,o){this.sqlite.prepare(`
142
+ UPDATE app_sync_creation_jobs
143
+ SET status = 'invalidated', next_attempt_at = 0, updated_at = ?
144
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND status IN ('waiting', 'processing')
145
+ `).run(o,e,n,r);}upsertResult(e){let n=e.attempts??this.getResult(e.bindingId,e.ref)?.attempts??0;this.sqlite.prepare(`
146
+ INSERT INTO app_sync_results (
147
+ binding_id, account_key, ref, grant_id, grant_generation, source_fingerprint,
148
+ synced_fingerprint, document_id, status, error_code, next_attempt_at, attempts, updated_at
149
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
150
+ ON CONFLICT(binding_id, ref) DO UPDATE SET
151
+ account_key = excluded.account_key,
152
+ grant_id = excluded.grant_id,
153
+ grant_generation = excluded.grant_generation,
154
+ source_fingerprint = excluded.source_fingerprint,
155
+ synced_fingerprint = excluded.synced_fingerprint,
156
+ document_id = excluded.document_id,
157
+ status = excluded.status,
158
+ error_code = excluded.error_code,
159
+ next_attempt_at = excluded.next_attempt_at,
160
+ attempts = excluded.attempts,
161
+ updated_at = excluded.updated_at
162
+ `).run(e.bindingId,e.accountKey,e.ref,e.grantId,e.grantGeneration,e.sourceFingerprint,e.syncedFingerprint,e.documentId,e.status,e.errorCode,e.nextAttemptAt??0,n,e.updatedAt);}getResult(e,n){let r=this.sqlite.prepare("SELECT * FROM app_sync_results WHERE binding_id = ? AND ref = ?").get(e,n);return r?Ca(r):void 0}listResults(e){return this.sqlite.prepare("SELECT * FROM app_sync_results WHERE binding_id = ? ORDER BY ref").all(e).map(Ca)}hasDeletedRef(e,n,r){return this.sqlite.prepare(`
163
+ SELECT 1 AS found FROM app_sync_deleted_refs WHERE account_key = ? AND app_id = ? AND ref_sha256 = ?
164
+ `).get(e,n,r)!==void 0}suppressDeletedRef(e,n,r,o){if(this.assertAccountKey(e),!/^[0-9a-f]{64}$/.test(r))throw new Error("APP_SYNC_REF_HASH_INVALID");this.sqlite.prepare(`
165
+ INSERT OR IGNORE INTO app_sync_deleted_refs (account_key, app_id, ref_sha256, created_at)
166
+ VALUES (?, ?, ?, ?)
167
+ `).run(e,n,r,o);}countDeletedRefs(e,n){return this.sqlite.prepare(`
168
+ SELECT count(*) AS count FROM app_sync_deleted_refs WHERE account_key = ? AND app_id = ?
169
+ `).get(e,n).count}listBindingsForAccount(e){return this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE account_key = ? ORDER BY created_at, binding_id").all(e).map(Ro)}getDiscoveryCheckpoint(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(e);return n?Eo(n):void 0}beginDiscoveryCycle(e){return this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let{binding:r,now:o}=e,s=ye(JSON.stringify(r.rootSegments)),i=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(r.bindingId);if(i){if(i.account_key!==r.accountKey||i.workspace_id!==r.workspaceId||i.root_fingerprint!==s)throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");let c=i.grant_id===r.grantId&&i.grant_generation===r.grantGeneration&&i.scope_version===r.scopeVersion,u=i.cycle_started_at!==null&&!(i.docs_complete===1&&i.deleted_complete===1);if(c&&u)return Eo(i);if(c&&i.last_cycle_started_at!==null&&o-i.last_cycle_started_at<6e4)return null;c||this.sqlite.prepare(`
170
+ UPDATE app_sync_pending_discoveries
171
+ SET status = 'invalidated', error_code = 'DOC_APP_GRANT_STALE', updated_at = ?
172
+ WHERE binding_id = ? AND status IN ('waiting', 'processing')
173
+ `).run(o,r.bindingId);}this.sqlite.prepare(`
174
+ INSERT INTO app_sync_discovery_checkpoints (
175
+ binding_id, account_key, workspace_id, root_fingerprint, grant_id, grant_generation, scope_version,
176
+ last_cycle_started_at, cycle_started_at, docs_cursor, docs_complete, deleted_cursor, deleted_complete, updated_at
177
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, NULL, 0, ?)
178
+ ON CONFLICT(binding_id) DO UPDATE SET
179
+ account_key = excluded.account_key,
180
+ workspace_id = excluded.workspace_id,
181
+ root_fingerprint = excluded.root_fingerprint,
182
+ grant_id = excluded.grant_id,
183
+ grant_generation = excluded.grant_generation,
184
+ scope_version = excluded.scope_version,
185
+ last_cycle_started_at = excluded.last_cycle_started_at,
186
+ cycle_started_at = excluded.cycle_started_at,
187
+ docs_cursor = NULL,
188
+ docs_complete = 0,
189
+ deleted_cursor = NULL,
190
+ deleted_complete = 0,
191
+ updated_at = excluded.updated_at
192
+ `).run(r.bindingId,r.accountKey,r.workspaceId,s,r.grantId,r.grantGeneration,r.scopeVersion,o,o,o),this.assertContinuationFence(e.fence);let a=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(r.bindingId);if(!a)throw new Error("APP_SYNC_DISCOVERY_CHECKPOINT_WRITE_FAILED");return Eo(a)})()}resetDiscoveryCycle(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=ye(JSON.stringify(e.binding.rootSegments));if(this.sqlite.prepare(`
193
+ UPDATE app_sync_discovery_checkpoints
194
+ SET last_cycle_started_at = ?, cycle_started_at = ?, docs_cursor = NULL, docs_complete = 0,
195
+ deleted_cursor = NULL, deleted_complete = 0, updated_at = ?
196
+ WHERE binding_id = ? AND account_key = ? AND workspace_id = ? AND root_fingerprint = ?
197
+ AND grant_id = ? AND grant_generation = ? AND scope_version = ?
198
+ `).run(e.now,e.now,e.now,e.binding.bindingId,e.binding.accountKey,e.binding.workspaceId,r,e.binding.grantId,e.binding.grantGeneration,e.binding.scopeVersion).changes===0)throw new Error("APP_SYNC_DISCOVERY_CHECKPOINT_STALE");this.assertContinuationFence(e.fence);})();}commitGrantDocsPage(e){this.sqlite.transaction(()=>{if(this.assertContinuationFence(e.fence),this.assertCheckpointCursor(e.binding,"docs_cursor","docs_complete",e.expectedCursor),e.nextCursor!==null&&e.nextCursor===e.expectedCursor)throw new Error("APP_SYNC_REMOTE_CURSOR_LOOP");let r=this.sqlite.prepare(`
199
+ INSERT INTO app_sync_pending_discoveries (
200
+ binding_id, account_key, grant_id, grant_generation, ref, doc_id, listed_revision, listed_fingerprint,
201
+ app_grant_generation, needs_reattach, needs_reconcile, status, error_code, attempts, updated_at
202
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'waiting', NULL, 0, ?)
203
+ ON CONFLICT(binding_id, grant_id, grant_generation, ref) DO UPDATE SET
204
+ needs_reconcile = CASE
205
+ WHEN listed_revision != excluded.listed_revision OR listed_fingerprint != excluded.listed_fingerprint
206
+ OR doc_id != excluded.doc_id THEN 1 ELSE needs_reconcile END,
207
+ doc_id = excluded.doc_id,
208
+ listed_revision = excluded.listed_revision,
209
+ listed_fingerprint = excluded.listed_fingerprint,
210
+ app_grant_generation = excluded.app_grant_generation,
211
+ needs_reattach = excluded.needs_reattach,
212
+ status = CASE WHEN status = 'invalidated' THEN 'waiting' ELSE status END,
213
+ error_code = NULL,
214
+ updated_at = excluded.updated_at
215
+ `);for(let o of e.items){let s=ye(o.ref);if(this.hasDeletedRef(e.binding.accountKey,T,s)){this.markResultDeleted(e.binding,o.ref,o.docId,e.now);continue}r.run(e.binding.bindingId,e.binding.accountKey,e.binding.grantId,e.binding.grantGeneration,o.ref,o.docId,o.currentRevision,o.markdownVersion,o.appGrantGeneration,o.needsReattach?1:0,e.now);}this.sqlite.prepare(`
216
+ UPDATE app_sync_discovery_checkpoints
217
+ SET docs_cursor = ?, docs_complete = ?,
218
+ cycle_started_at = CASE WHEN ? = 1 AND deleted_complete = 1 THEN NULL ELSE cycle_started_at END,
219
+ updated_at = ?
220
+ WHERE binding_id = ? AND docs_cursor IS ? AND docs_complete = 0
221
+ `).run(e.nextCursor,e.nextCursor===null?1:0,e.nextCursor===null?1:0,e.now,e.binding.bindingId,e.expectedCursor),this.assertContinuationFence(e.fence);})();}commitDeletedRefsPage(e){this.sqlite.transaction(()=>{if(this.assertContinuationFence(e.fence),this.assertCheckpointCursor(e.binding,"deleted_cursor","deleted_complete",e.expectedCursor),e.nextCursor!==null&&e.nextCursor===e.expectedCursor)throw new Error("APP_SYNC_REMOTE_CURSOR_LOOP");for(let r of e.items){if(!/^[0-9a-f]{64}$/.test(r.refHash))throw new Error("APP_SYNC_REF_HASH_INVALID");this.sqlite.prepare(`
222
+ INSERT OR IGNORE INTO app_sync_deleted_refs (account_key, app_id, ref_sha256, created_at)
223
+ VALUES (?, ?, ?, ?)
224
+ `).run(e.binding.accountKey,T,r.refHash,e.now);let o=this.sqlite.prepare(`
225
+ SELECT ref FROM app_sync_results WHERE binding_id = ? AND account_key = ?
226
+ `).all(e.binding.bindingId,e.binding.accountKey);for(let a of o)ye(a.ref)===r.refHash&&this.markResultDeleted(e.binding,a.ref,void 0,e.now);let s=this.sqlite.prepare(`
227
+ SELECT job_id, ref FROM app_sync_creation_jobs
228
+ WHERE binding_id = ? AND account_key = ? AND status IN ('waiting', 'processing')
229
+ `).all(e.binding.bindingId,e.binding.accountKey);for(let a of s)ye(a.ref)===r.refHash&&this.sqlite.prepare(`
230
+ UPDATE app_sync_creation_jobs SET status = 'deleted', next_attempt_at = 0, updated_at = ?
231
+ WHERE job_id = ? AND status IN ('waiting', 'processing')
232
+ `).run(e.now,a.job_id);let i=this.sqlite.prepare(`
233
+ SELECT ref FROM app_sync_pending_discoveries WHERE binding_id = ? AND account_key = ?
234
+ `).all(e.binding.bindingId,e.binding.accountKey);for(let a of i)ye(a.ref)===r.refHash&&this.sqlite.prepare("DELETE FROM app_sync_pending_discoveries WHERE binding_id = ? AND ref = ?").run(e.binding.bindingId,a.ref);}this.sqlite.prepare(`
235
+ UPDATE app_sync_discovery_checkpoints
236
+ SET deleted_cursor = ?, deleted_complete = ?,
237
+ cycle_started_at = CASE WHEN ? = 1 AND docs_complete = 1 THEN NULL ELSE cycle_started_at END,
238
+ updated_at = ?
239
+ WHERE binding_id = ? AND deleted_cursor IS ? AND deleted_complete = 0
240
+ `).run(e.nextCursor,e.nextCursor===null?1:0,e.nextCursor===null?1:0,e.now,e.binding.bindingId,e.expectedCursor),this.assertContinuationFence(e.fence);})();}listPendingDiscoveries(e,n,r,o=500){let s=Math.min(Math.max(Math.trunc(o),1),500);return this.sqlite.prepare(`
241
+ SELECT * FROM app_sync_pending_discoveries
242
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND status IN ('waiting', 'processing')
243
+ ORDER BY ref LIMIT ?
244
+ `).all(e,n,r,s).map(To)}getPendingDiscovery(e,n,r,o){let s=this.sqlite.prepare(`
245
+ SELECT * FROM app_sync_pending_discoveries
246
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
247
+ `).get(e,n,r,o);return s?To(s):void 0}updatePendingDiscovery(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.sqlite.prepare(`
248
+ SELECT * FROM app_sync_pending_discoveries
249
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
250
+ `).get(e.bindingId,e.grantId,e.generation,e.ref);if(!r)return;let o={...To(r),...e.patch};Ap(o),this.sqlite.prepare(`
251
+ UPDATE app_sync_pending_discoveries
252
+ SET doc_id = ?, listed_revision = ?, listed_fingerprint = ?, app_grant_generation = ?,
253
+ needs_reattach = ?, needs_reconcile = ?, status = ?, error_code = ?, attempts = ?, updated_at = ?
254
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
255
+ `).run(o.docId,o.listedRevision,o.listedFingerprint,o.appGrantGeneration,o.needsReattach?1:0,o.needsReconcile?1:0,o.status,o.errorCode,o.attempts,e.now,e.bindingId,e.grantId,e.generation,e.ref),this.assertContinuationFence(e.fence);})();}completePendingDiscovery(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
256
+ DELETE FROM app_sync_pending_discoveries
257
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
258
+ `).run(e.bindingId,e.grantId,e.generation,e.ref),this.assertContinuationFence(e.fence);})();}recordKnownDeletion(e){if(ye(e.ref)!==e.refHash)throw new Error("APP_SYNC_REF_HASH_INVALID");this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
259
+ INSERT OR IGNORE INTO app_sync_deleted_refs (account_key, app_id, ref_sha256, created_at)
260
+ VALUES (?, ?, ?, ?)
261
+ `).run(e.binding.accountKey,T,e.refHash,e.now),this.markResultDeleted(e.binding,e.ref,e.documentId,e.now),this.sqlite.prepare(`
262
+ UPDATE app_sync_creation_jobs SET status = 'deleted', next_attempt_at = 0, updated_at = ?
263
+ WHERE binding_id = ? AND ref = ? AND status IN ('waiting', 'processing')
264
+ `).run(e.now,e.binding.bindingId,e.ref),this.sqlite.prepare(`
265
+ DELETE FROM app_sync_pending_discoveries WHERE binding_id = ? AND ref = ?
266
+ `).run(e.binding.bindingId,e.ref),this.assertContinuationFence(e.fence);})();}recordContinuationOutcome(e){if(e.sourceFingerprint!==null&&!/^sha256:[0-9a-f]{64}$/.test(e.sourceFingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");if(e.syncedFingerprint!==null&&!/^sha256:[0-9a-f]{64}$/.test(e.syncedFingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");if(e.errorCode!==null&&!/^[A-Z0-9_:-]{1,128}$/.test(e.errorCode))throw new Error("APP_SYNC_RESULT_ERROR_CODE_INVALID");this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
267
+ INSERT INTO app_sync_results (
268
+ binding_id, account_key, ref, grant_id, grant_generation, source_fingerprint, synced_fingerprint,
269
+ document_id, status, error_code, next_attempt_at, attempts, updated_at
270
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?)
271
+ ON CONFLICT(binding_id, ref) DO UPDATE SET
272
+ account_key = excluded.account_key,
273
+ grant_id = excluded.grant_id,
274
+ grant_generation = excluded.grant_generation,
275
+ source_fingerprint = excluded.source_fingerprint,
276
+ synced_fingerprint = excluded.synced_fingerprint,
277
+ document_id = excluded.document_id,
278
+ status = excluded.status,
279
+ error_code = excluded.error_code,
280
+ next_attempt_at = 0,
281
+ attempts = 0,
282
+ updated_at = excluded.updated_at
283
+ `).run(e.binding.bindingId,e.binding.accountKey,e.ref,e.grant.grantId,e.grant.generation,e.sourceFingerprint,e.syncedFingerprint,e.documentId,e.status,e.errorCode,e.now),this.assertContinuationFence(e.fence);})();}enqueueReattachJob(e){return this.sqlite.transaction(()=>{if(this.assertContinuationFence(e.fence),this.assertText(e.requestId,"requestId",128),this.assertText(e.jobId,"jobId",128),this.assertText(e.ref,"ref",256),this.assertText(e.documentId,"documentId",128),!/^sha256:[0-9a-f]{64}$/.test(e.fingerprint))throw new Error("APP_SYNC_FINGERPRINT_INVALID");if(e.binding.grantId!==e.grant.grantId||e.binding.grantGeneration!==e.grant.generation)throw new Error("DOC_APP_GRANT_STALE");let r=this.sqlite.prepare(`
284
+ SELECT * FROM app_sync_creation_jobs
285
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
286
+ AND operation_kind = 'reattach' AND document_id = ?
287
+ ORDER BY created_at DESC, job_id DESC LIMIT 1
288
+ `).get(e.binding.bindingId,e.grant.grantId,e.grant.generation,e.ref,e.fingerprint,e.documentId);if(r&&(r.status==="failed"||r.status==="conflict")&&(this.sqlite.prepare(`
289
+ UPDATE app_sync_creation_jobs SET status = 'waiting', next_attempt_at = 0, updated_at = ?
290
+ WHERE job_id = ?
291
+ `).run(e.now,r.job_id),r=this.sqlite.prepare("SELECT * FROM app_sync_creation_jobs WHERE job_id = ?").get(r.job_id)),r||(this.sqlite.prepare(`
292
+ INSERT OR IGNORE INTO app_sync_creation_jobs (
293
+ job_id, binding_id, account_key, grant_id, grant_generation, ref, request_id,
294
+ fingerprint, operation_kind, document_id, status, attempts, next_attempt_at, created_at, updated_at
295
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'reattach', ?, 'waiting', 0, 0, ?, ?)
296
+ `).run(e.jobId,e.binding.bindingId,e.binding.accountKey,e.grant.grantId,e.grant.generation,e.ref,e.requestId,e.fingerprint,e.documentId,e.now,e.now),r=this.sqlite.prepare(`
297
+ SELECT * FROM app_sync_creation_jobs
298
+ WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
299
+ AND operation_kind = 'reattach' AND document_id = ?
300
+ ORDER BY created_at DESC, job_id DESC LIMIT 1
301
+ `).get(e.binding.bindingId,e.grant.grantId,e.grant.generation,e.ref,e.fingerprint,e.documentId)),!r)throw new Error("APP_SYNC_REATTACH_JOB_WRITE_FAILED");return this.assertContinuationFence(e.fence),jn(r)})()}putConflict(e){return Ip(e.conflict),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),Cp(e.conflict,e.fence);let r=this.getConflict(e.conflict.conflictId);if(r&&!Np(r,e.conflict))throw new Error("APP_SYNC_CONFLICT_IDENTITY_MISMATCH");if(r?.state==="resolved"||r?.state==="kept_both")return r;let o=r?.preservationStatus==="ready"?"ready":e.conflict.preservationStatus,s=r?.vaultHandle??e.conflict.vaultHandle,i={...e.conflict,preservationStatus:o,vaultHandle:s};this.sqlite.prepare(`
302
+ INSERT INTO app_sync_conflicts (
303
+ conflict_id, binding_id, account_key, workspace_id, root_fingerprint, grant_id, grant_generation,
304
+ scope_version, ref, doc_id, local_version, local_fingerprint, baseline_revision, baseline_fingerprint,
305
+ remote_revision, remote_fingerprint, needs_reattach, vault_handle, preservation_status, state, superseded_by,
306
+ resolution_request_id, resolution_choice, cleanup_pending, created_at, updated_at
307
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
308
+ ON CONFLICT(conflict_id) DO UPDATE SET
309
+ vault_handle = excluded.vault_handle,
310
+ preservation_status = excluded.preservation_status,
311
+ updated_at = excluded.updated_at
312
+ `).run(i.conflictId,i.bindingId,i.accountKey,i.workspaceId,i.rootFingerprint,i.grantId,i.grantGeneration,i.scopeVersion,i.ref,i.documentId,i.localVersion,i.localFingerprint,i.baselineRevision,i.baselineFingerprint,i.remoteRevision,i.remoteFingerprint,i.needsReattach?1:0,i.vaultHandle,i.preservationStatus,i.state,i.supersededBy,i.resolutionRequestId,i.resolutionChoice,i.cleanupPending?1:0,i.createdAt,i.updatedAt),i.preservationStatus==="ready"&&i.vaultHandle&&this.sqlite.prepare(`
313
+ UPDATE app_sync_conflicts
314
+ SET state = 'superseded', superseded_by = ?, updated_at = ?
315
+ WHERE binding_id = ? AND ref = ? AND conflict_id <> ? AND state = 'open'
316
+ AND preservation_status = 'ready' AND vault_handle IS NOT NULL
317
+ `).run(i.conflictId,e.conflict.updatedAt,i.bindingId,i.ref,i.conflictId),this.assertContinuationFence(e.fence);let a=this.getConflict(i.conflictId);if(!a)throw new Error("APP_SYNC_CONFLICT_WRITE_FAILED");return a})()}rebindConflict(e){return this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.state!=="open"||r.preservationStatus!=="ready"||!r.vaultHandle)throw new Error("APP_SYNC_CONFLICT_REBIND_INVALID");if(e.grant.grantId!==e.fence.grantId||e.grant.generation!==e.fence.grantGeneration||e.grant.scopeVersion!==e.fence.scopeVersion)throw new Error("DOC_APP_GRANT_STALE");this.sqlite.prepare(`
318
+ UPDATE app_sync_conflicts
319
+ SET grant_id = ?, grant_generation = ?, scope_version = ?, needs_reattach = ?, updated_at = ?
320
+ WHERE conflict_id = ? AND state = 'open' AND preservation_status = 'ready'
321
+ `).run(e.grant.grantId,e.grant.generation,e.grant.scopeVersion,e.needsReattach?1:0,e.now,e.conflictId),this.assertContinuationFence(e.fence);let o=this.getConflict(e.conflictId);if(!o)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");return o})()}supersedeOpenConflicts(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
322
+ UPDATE app_sync_conflicts
323
+ SET state = 'superseded', superseded_by = ?, updated_at = ?
324
+ WHERE binding_id = ? AND ref = ? AND conflict_id <> ? AND state = 'open'
325
+ AND preservation_status = 'ready' AND vault_handle IS NOT NULL
326
+ `).run(e.supersededBy,e.now,e.bindingId,e.ref,e.supersededBy),this.assertContinuationFence(e.fence);})();}getConflict(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_conflicts WHERE conflict_id = ?").get(e);return n?ba(n):void 0}listConflicts(e){return this.sqlite.prepare(`
327
+ SELECT * FROM app_sync_conflicts WHERE binding_id = ? ORDER BY created_at, conflict_id
328
+ `).all(e).map(ba)}beginConflictResolution(e){bp(e),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.accountKey!==e.fence.accountKey)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");if(r.preservationStatus!=="ready"||!r.vaultHandle)throw new Error("APP_SYNC_CONFLICT_NOT_PRESERVED");if(r.localVersion!==e.expectedLocalVersion||r.remoteRevision!==e.expectedRemoteRevision||r.remoteFingerprint!==e.expectedRemoteFingerprint)throw new Error("APP_SYNC_CONFLICT_STALE");if(r.state==="superseded"&&e.choice!=="keep_both")throw new Error("APP_SYNC_CONFLICT_SUPERSEDED");let o=this.sqlite.prepare("SELECT * FROM app_sync_conflict_resolutions WHERE request_id = ?").get(e.requestId);if(o){if(!(o.conflict_id===e.conflictId&&o.account_key===e.fence.accountKey&&o.human_identity===e.humanIdentity&&o.choice===e.choice&&o.expected_local_version===e.expectedLocalVersion&&o.expected_remote_revision===e.expectedRemoteRevision&&o.expected_remote_fingerprint===e.expectedRemoteFingerprint))throw new Error("APP_SYNC_REQUEST_ID_REUSED");if(o.state==="stale"||o.state==="failed")throw new Error("APP_SYNC_CONFLICT_RESOLUTION_ALREADY_ENDED");if(r.state==="resolved"||r.state==="kept_both"||r.state==="resolving"&&r.resolutionRequestId===e.requestId)return;throw new Error("APP_SYNC_CONFLICT_RESOLUTION_IN_PROGRESS")}if(r.state!=="open"&&!(r.state==="superseded"&&e.choice==="keep_both"))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_IN_PROGRESS");this.sqlite.prepare(`
329
+ INSERT INTO app_sync_conflict_resolutions (
330
+ request_id, conflict_id, account_key, human_identity, choice, expected_local_version,
331
+ expected_remote_revision, expected_remote_fingerprint, state, error_code, created_at, updated_at
332
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NULL, ?, ?)
333
+ `).run(e.requestId,e.conflictId,e.fence.accountKey,e.humanIdentity,e.choice,e.expectedLocalVersion,e.expectedRemoteRevision,e.expectedRemoteFingerprint,e.now,e.now),this.sqlite.prepare(`
334
+ UPDATE app_sync_conflicts SET state = 'resolving', resolution_request_id = ?, resolution_choice = ?, updated_at = ?
335
+ WHERE conflict_id = ? AND state IN ('open', 'superseded')
336
+ `).run(e.requestId,e.choice,e.now,e.conflictId),this.assertContinuationFence(e.fence);})();}finishConflictResolution(e){return this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");if(r.resolutionRequestId===e.requestId&&r.state===(e.choice==="keep_both"?"kept_both":"resolved"))return r;if(this.sqlite.prepare(`
337
+ UPDATE app_sync_conflict_resolutions SET state = 'resolved', error_code = NULL, updated_at = ?
338
+ WHERE request_id = ? AND conflict_id = ? AND state IN ('pending', 'unknown')
339
+ `).run(e.now,e.requestId,e.conflictId).changes===0)throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INTENT_MISSING");this.sqlite.prepare(`
340
+ UPDATE app_sync_conflicts SET state = ?, resolution_request_id = ?, resolution_choice = ?,
341
+ cleanup_pending = CASE WHEN ? = 'keep_both' OR vault_handle IS NULL THEN 0 ELSE 1 END, updated_at = ?
342
+ WHERE conflict_id = ? AND state = 'resolving' AND resolution_request_id = ?
343
+ `).run(e.choice==="keep_both"?"kept_both":"resolved",e.requestId,e.choice,e.choice,e.now,e.conflictId,e.requestId),this.assertContinuationFence(e.fence);let s=this.getConflict(e.conflictId);if(!s)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");return s})()}abortConflictResolution(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
344
+ UPDATE app_sync_conflict_resolutions SET state = ?, error_code = ?, updated_at = ?
345
+ WHERE request_id = ? AND conflict_id = ? AND state IN ('pending', 'unknown')
346
+ `).run(e.state,e.errorCode,e.now,e.requestId,e.conflictId),this.sqlite.prepare(`
347
+ UPDATE app_sync_conflicts
348
+ SET state = CASE WHEN superseded_by IS NULL THEN 'open' ELSE 'superseded' END,
349
+ resolution_request_id = NULL, resolution_choice = NULL, updated_at = ?
350
+ WHERE conflict_id = ? AND resolution_request_id = ? AND state = 'resolving'
351
+ `).run(e.now,e.conflictId,e.requestId),this.assertContinuationFence(e.fence);})();}markConflictResolutionUnknown(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.state!=="resolving"||r.resolutionRequestId!==e.requestId)throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INTENT_MISSING");this.sqlite.prepare(`
352
+ UPDATE app_sync_conflict_resolutions SET state = 'unknown', updated_at = ?
353
+ WHERE request_id = ? AND conflict_id = ? AND state IN ('pending', 'unknown')
354
+ `).run(e.now,e.requestId,e.conflictId),this.assertContinuationFence(e.fence);})();}finishConflictArchiveCleanup(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),this.sqlite.prepare(`
355
+ UPDATE app_sync_conflicts SET vault_handle = NULL, cleanup_pending = 0, updated_at = ?
356
+ WHERE conflict_id = ? AND binding_id = ? AND state = 'resolved'
357
+ `).run(e.now,e.conflictId,e.fence.bindingId),this.assertContinuationFence(e.fence);})();}markConflictPurging(e){return this.sqlite.transaction(()=>{this.assertPurgeFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.accountKey!==e.fence.accountKey)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");r.state!=="purging"&&this.sqlite.prepare(`
358
+ UPDATE app_sync_conflicts SET state = 'purging', cleanup_pending = 0, updated_at = ?
359
+ WHERE conflict_id = ? AND state IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both')
360
+ `).run(e.now,e.conflictId),this.assertPurgeFence(e.fence);let o=this.getConflict(e.conflictId);if(!o||o.state!=="purging")throw new Error("APP_SYNC_CONFLICT_PURGE_STATE_INVALID");return o})()}deletePurgedConflict(e){this.sqlite.transaction(()=>{this.assertPurgeFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.state!=="purging"||r.vaultHandle!==e.expectedVaultHandle)throw new Error("APP_SYNC_CONFLICT_PURGE_STATE_INVALID");this.sqlite.prepare(`
361
+ DELETE FROM app_sync_conflicts WHERE conflict_id = ? AND binding_id = ? AND state = 'purging'
362
+ AND vault_handle IS ?
363
+ `).run(e.conflictId,e.fence.bindingId,e.expectedVaultHandle),this.assertPurgeFence(e.fence);})();}beginAccountDataPurge(e){this.sqlite.transaction(()=>{if(this.assertPurgeFence(e.fence),this.assertText(e.requestId,"requestId",128),!/^[0-9a-f]{64}$/.test(e.humanIdentity))throw new Error("APP_SYNC_HUMAN_IDENTITY_INVALID");let r=ye(JSON.stringify(e.binding.rootSegments));if(e.binding.bindingId!==e.fence.bindingId||e.binding.accountKey!==e.fence.accountKey||e.binding.workspaceId!==e.fence.workspaceId||r!==e.fence.rootFingerprint)throw new Error("APP_SYNC_CONFLICT_BINDING_MISMATCH");let o=this.getAccountDataPurge(e.requestId);if(o){if(o.bindingId!==e.binding.bindingId||o.accountKey!==e.binding.accountKey||o.workspaceId!==e.binding.workspaceId||o.rootFingerprint!==r||o.humanIdentity!==e.humanIdentity)throw new Error("APP_SYNC_PURGE_REQUEST_ID_REUSED");return}if(this.sqlite.prepare(`
364
+ SELECT request_id FROM app_sync_account_data_purges
365
+ WHERE binding_id = ? AND state = 'pending' LIMIT 1
366
+ `).get(e.binding.bindingId))throw new Error("APP_SYNC_ACCOUNT_DATA_PURGE_IN_PROGRESS");this.sqlite.prepare(`
367
+ INSERT INTO app_sync_account_data_purges (
368
+ request_id, binding_id, account_key, workspace_id, root_fingerprint, human_identity, state, created_at, updated_at
369
+ ) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)
370
+ `).run(e.requestId,e.binding.bindingId,e.binding.accountKey,e.binding.workspaceId,r,e.humanIdentity,e.now,e.now),this.assertPurgeFence(e.fence);})();}getAccountDataPurge(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_account_data_purges WHERE request_id = ?").get(e);if(n)return {requestId:n.request_id,bindingId:n.binding_id,accountKey:n.account_key,workspaceId:n.workspace_id,rootFingerprint:n.root_fingerprint,humanIdentity:n.human_identity,state:n.state}}finishAccountDataPurge(e){this.sqlite.transaction(()=>{this.assertPurgeFence(e.fence);let r=this.getAccountDataPurge(e.requestId),o=ye(JSON.stringify(e.binding.rootSegments));if(!r||r.bindingId!==e.binding.bindingId||r.accountKey!==e.binding.accountKey||r.workspaceId!==e.binding.workspaceId||r.rootFingerprint!==o)throw new Error("APP_SYNC_PURGE_REQUEST_NOT_FOUND");if(r.state==="complete")return;if(this.sqlite.prepare("SELECT count(*) AS count FROM app_sync_conflicts WHERE binding_id = ?").get(e.binding.bindingId).count!==0)throw new Error("APP_SYNC_PURGE_ARCHIVES_REMAIN");if(this.sqlite.prepare(`
371
+ DELETE FROM doc_sync_links
372
+ WHERE account_key = ? AND workspace_id = ? AND app_id = ? AND root_segments = ? AND connection_kind = 'app_grant'
373
+ `).run(e.binding.accountKey,e.binding.workspaceId,T,JSON.stringify(e.binding.rootSegments)),this.sqlite.prepare("DELETE FROM app_sync_deleted_refs WHERE account_key = ? AND app_id = ?").run(e.binding.accountKey,T),this.sqlite.prepare("DELETE FROM app_sync_bindings WHERE binding_id = ? AND account_key = ?").run(e.binding.bindingId,e.binding.accountKey).changes!==1)throw new Error("APP_SYNC_PURGE_BINDING_DELETE_FAILED");this.sqlite.prepare(`
374
+ UPDATE app_sync_account_data_purges SET state = 'complete', updated_at = ?
375
+ WHERE request_id = ? AND state = 'pending'
376
+ `).run(e.now,e.requestId),e.fence.assertCurrent();})();}assertCheckpointCursor(e,n,r,o){let s=this.sqlite.prepare("SELECT * FROM app_sync_discovery_checkpoints WHERE binding_id = ?").get(e.bindingId);if(!s||s.grant_id!==e.grantId||s.grant_generation!==e.grantGeneration||s.scope_version!==e.scopeVersion||s[n]!==o||s[r]!==0)throw new Error("APP_SYNC_DISCOVERY_CURSOR_RACE")}markResultDeleted(e,n,r,o){this.sqlite.prepare("SELECT * FROM app_sync_results WHERE binding_id = ? AND ref = ?").get(e.bindingId,n)&&this.sqlite.prepare(`
377
+ UPDATE app_sync_results SET account_key = ?, grant_id = ?, grant_generation = ?,
378
+ document_id = COALESCE(?, document_id), status = 'deleted', error_code = 'DOC_APP_REF_DELETED',
379
+ next_attempt_at = 0, updated_at = ?
380
+ WHERE binding_id = ? AND ref = ?
381
+ `).run(e.accountKey,e.grantId,e.grantGeneration,r??null,o,e.bindingId,n);}assertContinuationFence(e){e.assertCurrent();let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||ye(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_ROOT_STALE");if(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration||n.scopeVersion!==e.scopeVersion)throw new Error("DOC_APP_GRANT_STALE");if(n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new Error(n.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED");if(this.sqlite.prepare(`
382
+ SELECT 1 AS found FROM app_sync_control_requests
383
+ WHERE binding_id = ? AND kind = 'revoke' AND state IN ('pending', 'unknown') LIMIT 1
384
+ `).get(n.bindingId))throw new Error("APP_SYNC_REVOKE_PENDING");if(this.sqlite.prepare(`
385
+ SELECT 1 AS found FROM app_sync_account_data_purges
386
+ WHERE binding_id = ? AND state = 'pending' LIMIT 1
387
+ `).get(n.bindingId))throw new Error("APP_SYNC_ACCOUNT_DATA_PURGE_PENDING");e.assertCurrent();}assertPurgeFence(e){e.assertCurrent();let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||ye(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_ROOT_STALE");if(n.grantId&&(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration))throw new Error("DOC_APP_GRANT_STALE");if(n.status==="stopping")throw new Error("APP_SYNC_REVOKE_PENDING");if(this.sqlite.prepare(`
388
+ SELECT 1 AS found FROM app_sync_control_requests
389
+ WHERE binding_id = ? AND kind = 'revoke' AND state IN ('pending', 'unknown') LIMIT 1
390
+ `).get(n.bindingId))throw new Error("APP_SYNC_REVOKE_PENDING");e.assertCurrent();}assertAccountKey(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("APP_SYNC_ACCOUNT_KEY_INVALID")}assertText(e,n,r){if(typeof e!="string"||e.length===0||e.length>r||e.includes("\0"))throw new Error(`APP_SYNC_${n.toUpperCase()}_INVALID`)}};function Ro(t){let e;try{e=JSON.parse(t.root_segments);}catch{throw new Error("APP_SYNC_ROOT_STORAGE_INVALID")}if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error("APP_SYNC_ROOT_STORAGE_INVALID");return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,appId:T,rootSegments:e,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at}}function jn(t){return {jobId:t.job_id,bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,requestId:t.request_id,fingerprint:t.fingerprint,operationKind:t.operation_kind==="reattach"?"reattach":"create",documentId:t.document_id,status:t.status,attempts:t.attempts,nextAttemptAt:t.next_attempt_at,createdAt:t.created_at,updatedAt:t.updated_at}}function Eo(t){return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,lastCycleStartedAt:t.last_cycle_started_at,cycleStartedAt:t.cycle_started_at,docsCursor:t.docs_cursor,docsComplete:t.docs_complete===1,deletedCursor:t.deleted_cursor,deletedComplete:t.deleted_complete===1,updatedAt:t.updated_at}}function To(t){return {bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,docId:t.doc_id,listedRevision:t.listed_revision,listedFingerprint:t.listed_fingerprint,appGrantGeneration:t.app_grant_generation,needsReattach:t.needs_reattach===1,needsReconcile:t.needs_reconcile===1,status:t.status,errorCode:t.error_code,attempts:t.attempts,updatedAt:t.updated_at}}function ba(t){return {conflictId:t.conflict_id,bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,ref:t.ref,documentId:t.doc_id,localVersion:t.local_version,localFingerprint:t.local_fingerprint,baselineRevision:t.baseline_revision,baselineFingerprint:t.baseline_fingerprint,remoteRevision:t.remote_revision,remoteFingerprint:t.remote_fingerprint,needsReattach:t.needs_reattach===1,vaultHandle:t.vault_handle,preservationStatus:t.preservation_status,state:t.state,supersededBy:t.superseded_by,resolutionRequestId:t.resolution_request_id,resolutionChoice:t.resolution_choice,cleanupPending:t.cleanup_pending===1,createdAt:t.created_at,updatedAt:t.updated_at}}function Ap(t){if(!/^[0-9a-f]{64}$/.test(t.accountKey)||typeof t.ref!="string"||t.ref.length<1||t.ref.length>256||typeof t.docId!="string"||t.docId.length<1||t.docId.length>128||!Number.isSafeInteger(t.listedRevision)||t.listedRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.listedFingerprint)||!Number.isSafeInteger(t.grantGeneration)||t.grantGeneration<1||!Number.isSafeInteger(t.appGrantGeneration)||t.appGrantGeneration<1||!Number.isSafeInteger(t.attempts)||t.attempts<0||!["waiting","processing","failed","invalidated"].includes(t.status))throw new Error("APP_SYNC_PENDING_DISCOVERY_INVALID");if(t.errorCode!==null&&!/^[A-Z0-9_:-]{1,128}$/.test(t.errorCode))throw new Error("APP_SYNC_PENDING_DISCOVERY_METADATA_INVALID")}function Ip(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t.conflictId)||!/^[0-9a-f]{64}$/.test(t.accountKey)||!/^[0-9a-f]{64}$/.test(t.rootFingerprint)||typeof t.workspaceId!="string"||t.workspaceId.length<1||t.workspaceId.length>256||typeof t.ref!="string"||t.ref.length<1||t.ref.length>256||typeof t.documentId!="string"||t.documentId.length<1||t.documentId.length>128||!bo(t.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(t.localFingerprint)||!Number.isSafeInteger(t.remoteRevision)||t.remoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.remoteFingerprint)||!["pending","ready","failed"].includes(t.preservationStatus)||!["open","resolving","superseded","resolved","kept_both","purging"].includes(t.state)||t.supersededBy!==null&&!/^[A-Za-z0-9_-]{1,128}$/.test(t.supersededBy)||t.state==="superseded"&&t.supersededBy===null||!Number.isSafeInteger(t.createdAt)||!Number.isSafeInteger(t.updatedAt)||t.updatedAt<t.createdAt)throw new Error("APP_SYNC_CONFLICT_METADATA_INVALID");if(t.baselineRevision===null!=(t.baselineFingerprint===null))throw new Error("APP_SYNC_CONFLICT_BASELINE_INVALID");if(t.baselineRevision!==null&&(!Number.isSafeInteger(t.baselineRevision)||t.baselineRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.baselineFingerprint??"")))throw new Error("APP_SYNC_CONFLICT_BASELINE_INVALID");if(t.vaultHandle!==null&&!bo(t.vaultHandle))throw new Error("APP_SYNC_CONFLICT_HANDLE_INVALID");if(!(t.state==="open"?t.preservationStatus==="ready"&&t.vaultHandle!==null&&!t.cleanupPending||t.preservationStatus!=="ready"&&t.vaultHandle===null&&!t.cleanupPending:t.state==="resolving"||t.state==="superseded"?t.preservationStatus==="ready"&&t.vaultHandle!==null&&!t.cleanupPending:t.state==="purging"?!t.cleanupPending:t.state==="kept_both"?t.preservationStatus==="ready"&&t.resolutionRequestId!==null&&t.resolutionChoice==="keep_both"&&t.vaultHandle!==null&&!t.cleanupPending:t.preservationStatus==="ready"&&t.resolutionRequestId!==null&&(t.cleanupPending?t.vaultHandle!==null:t.vaultHandle===null)))throw new Error("APP_SYNC_CONFLICT_PRESERVATION_INVALID");if(t.resolutionRequestId===null!=(t.resolutionChoice===null))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INVALID")}function bp(t){if(typeof t.requestId!="string"||t.requestId.length<1||t.requestId.length>128||t.requestId.includes("\0")||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!bo(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID")}function Cp(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==e.rootFingerprint||t.grantId!==e.grantId||t.grantGeneration!==e.grantGeneration||t.scopeVersion!==e.scopeVersion)throw new Error("APP_SYNC_CONFLICT_BINDING_MISMATCH")}function Np(t,e){return t.bindingId===e.bindingId&&t.accountKey===e.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===e.rootFingerprint&&t.grantId===e.grantId&&t.grantGeneration===e.grantGeneration&&t.ref===e.ref&&t.documentId===e.documentId&&t.localVersion===e.localVersion&&t.localFingerprint===e.localFingerprint&&t.remoteRevision===e.remoteRevision&&t.remoteFingerprint===e.remoteFingerprint}function bo(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function Ca(t){return {bindingId:t.binding_id,accountKey:t.account_key,ref:t.ref,grantId:t.grant_id,grantGeneration:t.grant_generation,sourceFingerprint:t.source_fingerprint,syncedFingerprint:t.synced_fingerprint,documentId:t.document_id,status:t.status,errorCode:t.error_code,nextAttemptAt:t.next_attempt_at,attempts:t.attempts,updatedAt:t.updated_at}}function Ao(t){return {requestId:t.request_id,bindingId:t.binding_id,accountKey:t.account_key,appId:T,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,kind:t.kind,state:t.state,grantId:t.grant_id,generation:t.generation,createdAt:t.created_at,updatedAt:t.updated_at,resolvedAt:t.resolved_at,resolution:t.resolution,resolutionId:t.resolution_id}}function Na(t,e){return t.requestId===e.requestId&&t.bindingId===e.bindingId&&t.accountKey===e.accountKey&&t.appId===e.appId&&t.workspaceId===e.workspaceId&&t.rootFingerprint===e.rootFingerprint&&t.kind===e.kind&&(t.kind==="connect"||t.grantId===e.grantId&&t.generation===e.generation)}function ye(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Oa(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function Op(t){return t instanceof Error&&t.code==="SQLITE_CONSTRAINT_UNIQUE"}exports.APP_SYNC_APP_ID=T;exports.APP_SYNC_CONTINUATION_MAX_PAGE_SIZE=zn;exports.APP_SYNC_CONTINUATION_MIN_INTERVAL_MS=Lt;exports.APP_SYNC_FRONT_MATTER_MAX_BYTES=Vn;exports.APP_SYNC_LOCAL_RECORD_LIMIT=pt;exports.APP_SYNC_PAGE_SIZE=Kn;exports.APP_SYNC_SCOPE_DEFINITION=_e;exports.APP_SYNC_SCOPE_SELECTORS=Yn;exports.APP_SYNC_SCOPE_VERSION=Xe;exports.AppSyncBudgetDeferredError=je;exports.AppSyncCoordinator=ar;exports.AppSyncRemoteError=g;exports.AppSyncScopeRegistry=Ut;exports.AppSyncSessionFence=Ft;exports.DOC001_CREATE_LIMIT_PER_WINDOW=Mt;exports.DOC001_CREATE_WINDOW_MS=dn;exports.SqliteAppSyncStore=Io;exports.SqliteDocCreateLedger=Jn;exports.createDispatchGate=qt;exports.fingerprintMarkdown=U;exports.normalizeResolvedRootSegments=_t;