deepline 0.3.536 → 0.3.538

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 (204) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +22 -5
  2. package/dist/bundling-sources/sdk/src/index.ts +2 -0
  3. package/dist/bundling-sources/sdk/src/plays/client-core.ts +18 -1
  4. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  5. package/dist/bundling-sources/sdk/src/runs/watch-polling.ts +33 -4
  6. package/dist/bundling-sources/shared_libs/integration-contracts/billing-entitlements.ts +1 -1
  7. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +36 -0
  8. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +1 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/baked-runner-image.ts +330 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +717 -133
  11. package/dist/bundling-sources/shared_libs/play-runtime/coordinator-headers.ts +7 -0
  12. package/dist/bundling-sources/shared_libs/play-runtime/daytona-payload-contract.ts +22 -1
  13. package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +123 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/experiment-switches.ts +480 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/fixture-egress-fetch.ts +24 -16
  16. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +293 -53
  17. package/dist/bundling-sources/shared_libs/play-runtime/governor/block-reserving-budget-state-backend.ts +57 -2
  18. package/dist/bundling-sources/shared_libs/play-runtime/governor/budget-state-backend.ts +43 -0
  19. package/dist/bundling-sources/shared_libs/play-runtime/governor/governor.ts +141 -9
  20. package/dist/bundling-sources/shared_libs/play-runtime/launch-identity.ts +2 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/modal-runtime-config.ts +6 -0
  22. package/dist/bundling-sources/shared_libs/play-runtime/modal-supervisor-sidecar.ts +556 -0
  23. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +27 -0
  24. package/dist/bundling-sources/shared_libs/play-runtime/resource-governor.ts +19 -0
  25. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger.ts +54 -0
  26. package/dist/bundling-sources/shared_libs/play-runtime/run-snapshot-stream.ts +5 -0
  27. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +155 -3
  28. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/relay-connection-counter.ts +103 -0
  29. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-heartbeat.ts +75 -6
  30. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-terminal-push.ts +59 -0
  31. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-payload-transport.ts +544 -73
  32. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-runtime-watchdog.ts +8 -1
  33. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/detached-runner-readiness-pacing.ts +19 -1
  34. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/modal.ts +2390 -110
  35. package/dist/bundling-sources/shared_libs/play-runtime/runtime-flow.ts +42 -8
  36. package/dist/bundling-sources/shared_libs/play-runtime/runtime-read-through.ts +287 -0
  37. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-finish.ts +606 -0
  38. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-writer.ts +274 -119
  39. package/dist/bundling-sources/shared_libs/play-runtime/runtime-traffic-policy.ts +54 -0
  40. package/dist/bundling-sources/shared_libs/play-runtime/runtime-work-counters.ts +10 -1
  41. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +15 -0
  42. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-play-run-task.ts +18 -1
  43. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-pool.ts +18 -4
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +219 -7
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-shared.ts +3 -0
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/early-sandbox-claim-affinity.ts +340 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +1 -0
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +10 -1
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +623 -7
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +340 -5
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runner-push.ts +61 -0
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +2 -1
  53. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-ledger-reconciliation.ts +269 -2
  54. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-worker-wake.ts +238 -5
  55. package/dist/bundling-sources/shared_libs/play-runtime/startup-read-tool-ids.ts +47 -0
  56. package/dist/bundling-sources/shared_libs/play-runtime/tool-call/runtime-step-receipts-adapter.ts +5 -4
  57. package/dist/bundling-sources/shared_libs/play-runtime/tool-result.ts +6 -0
  58. package/dist/bundling-sources/shared_libs/play-runtime/transient-service-error.ts +11 -0
  59. package/dist/cli/auth-4WEVLYK4.js +43 -0
  60. package/dist/cli/{auth-KCTCUO7P.mjs → auth-KYH7N7RQ.mjs} +5 -5
  61. package/dist/cli/{billing-4VBGZ3CT.js → billing-4KTUVZ4S.js} +114 -90
  62. package/dist/cli/{billing-OOJHKLNS.mjs → billing-WK346KAI.mjs} +31 -7
  63. package/dist/cli/{chunk-4E5JXZ3W.js → chunk-25RGHJQL.js} +15 -15
  64. package/dist/cli/{chunk-MSP4DTSD.js → chunk-34PLG5OE.js} +13 -13
  65. package/dist/cli/{chunk-DQHUJMCL.mjs → chunk-35OCRH5C.mjs} +5 -5
  66. package/dist/cli/{chunk-2B4IOGFD.js → chunk-3I5TU5XE.js} +292 -279
  67. package/dist/cli/{chunk-Z7UIOGW4.mjs → chunk-4KZF6OYY.mjs} +3 -3
  68. package/dist/cli/{chunk-2YWJS76L.mjs → chunk-4NEOGPKD.mjs} +1 -1
  69. package/dist/cli/{chunk-LZXZQPA2.mjs → chunk-4WQR4DG4.mjs} +1 -1
  70. package/dist/cli/{chunk-KWYGWO4Y.js → chunk-5VSPRRTI.js} +7 -7
  71. package/dist/cli/{chunk-ANUKBZ6W.mjs → chunk-6JG3MRTM.mjs} +2 -2
  72. package/dist/cli/{chunk-VBDZIMWD.js → chunk-6SLQLWWL.js} +26 -26
  73. package/dist/cli/{chunk-E24UGPGG.mjs → chunk-7XDJKIM2.mjs} +4 -4
  74. package/dist/cli/{chunk-OUDTOMZC.mjs → chunk-A6E7TCK2.mjs} +5 -5
  75. package/dist/cli/{chunk-ZZ4MF2GI.js → chunk-ADLDU2QG.js} +6 -6
  76. package/dist/cli/{chunk-XVZRJJDS.mjs → chunk-ALARRSMZ.mjs} +3 -3
  77. package/dist/cli/{chunk-HWDKRN7L.js → chunk-B2BTBHX2.js} +3 -3
  78. package/dist/cli/{chunk-ZISEH7OL.js → chunk-BBS2BLPV.js} +16 -16
  79. package/dist/cli/{chunk-YRLAUGQY.mjs → chunk-CLO562KG.mjs} +3 -1
  80. package/dist/cli/{chunk-CXTW7SRW.mjs → chunk-E7D37PLM.mjs} +8 -0
  81. package/dist/cli/{chunk-SLPJ3LXI.js → chunk-ESX3H7Q7.js} +22 -22
  82. package/dist/cli/{chunk-AB2GBOD4.mjs → chunk-FJ5KPGCS.mjs} +10 -10
  83. package/dist/cli/{chunk-DUYAMLOC.mjs → chunk-FWE37N2P.mjs} +1 -1
  84. package/dist/cli/{chunk-3PCYV6ZJ.mjs → chunk-ICTA5ICE.mjs} +1 -1
  85. package/dist/cli/{chunk-ZILSRDIN.js → chunk-IMLFB66A.js} +3 -3
  86. package/dist/cli/{chunk-PNY3BWHP.mjs → chunk-IP3XJTWA.mjs} +2 -2
  87. package/dist/cli/{chunk-6VUGBQZQ.js → chunk-JCLRSMUP.js} +5 -5
  88. package/dist/cli/{chunk-YBMHOH6H.mjs → chunk-JPEBKN3K.mjs} +2 -2
  89. package/dist/cli/{chunk-GF32SBST.mjs → chunk-JTOV5RUA.mjs} +1 -1
  90. package/dist/cli/{chunk-Q5CXV3E3.js → chunk-KCUQNH4K.js} +2 -2
  91. package/dist/cli/{chunk-DA2I2M7D.mjs → chunk-KNIYEZVV.mjs} +2 -2
  92. package/dist/cli/{chunk-CWSLUNA6.js → chunk-LPTBHNGB.js} +7 -5
  93. package/dist/cli/{chunk-WC5M3JXE.mjs → chunk-M3NCXGNN.mjs} +2 -2
  94. package/dist/cli/{chunk-TX5TUHJN.js → chunk-MNBIGX6O.js} +10 -10
  95. package/dist/cli/{chunk-ZEV2Y56V.js → chunk-MYSPQUAO.js} +44 -44
  96. package/dist/cli/{chunk-KPQHUVYW.mjs → chunk-N2BCPZVR.mjs} +5 -5
  97. package/dist/cli/{chunk-XBAH3TKU.js → chunk-N5HSG4OV.js} +5 -5
  98. package/dist/cli/{chunk-GTVZKY3F.js → chunk-O765M4LT.js} +2 -2
  99. package/dist/cli/{chunk-2FCSUOYN.js → chunk-OOLBE6FR.js} +53 -53
  100. package/dist/cli/{chunk-W7AEIGZR.js → chunk-P3DP56HB.js} +41 -41
  101. package/dist/cli/{chunk-LN6RXDTB.js → chunk-PQKD5DMT.js} +19 -19
  102. package/dist/cli/{chunk-GHLDCLSC.mjs → chunk-T6GPTJ5F.mjs} +1 -1
  103. package/dist/cli/{chunk-XJD2GYUP.mjs → chunk-TWWYCJJW.mjs} +5 -5
  104. package/dist/cli/{chunk-BASLYGXK.mjs → chunk-UE7JHAZ2.mjs} +29 -16
  105. package/dist/cli/{chunk-Q4MNUOS4.js → chunk-UEZNIPFO.js} +107 -107
  106. package/dist/cli/{chunk-RVSSQPQO.mjs → chunk-VCHV4LS3.mjs} +1 -1
  107. package/dist/cli/{chunk-LDGZFDUB.js → chunk-VIFLWQXS.js} +2 -2
  108. package/dist/cli/{chunk-6BBGUQJJ.js → chunk-XTYHZEJ2.js} +8 -0
  109. package/dist/cli/{chunk-CIDN5K23.js → chunk-YQURGSRB.js} +1 -1
  110. package/dist/cli/{chunk-Y2NTPYGS.js → chunk-YZ2ZPHWR.js} +9 -9
  111. package/dist/cli/{chunk-HAJQGP5V.mjs → chunk-ZDLDCXY3.mjs} +2 -2
  112. package/dist/cli/{chunk-JUHDJNSI.mjs → chunk-ZU6JBRV5.mjs} +4 -4
  113. package/dist/cli/command-docs.js +2 -2
  114. package/dist/cli/command-docs.mjs +1 -1
  115. package/dist/cli/{csv-P3HLK4GO.mjs → csv-2YKLUKDR.mjs} +4 -4
  116. package/dist/cli/{csv-2V2DIFNG.js → csv-LM7FBECI.js} +13 -13
  117. package/dist/cli/{db-ZYOY3QRQ.mjs → db-234UBWJH.mjs} +6 -6
  118. package/dist/cli/{db-MREAQVW6.js → db-5PMA4IVW.js} +27 -27
  119. package/dist/cli/describe-C7GOSGYB.js +49 -0
  120. package/dist/cli/{describe-IKZFOADR.mjs → describe-W26LW5O7.mjs} +17 -17
  121. package/dist/cli/describe-core.d.mts +3 -3
  122. package/dist/cli/describe-core.d.ts +3 -3
  123. package/dist/cli/{executions-H5IJ7QSQ.js → executions-3S736GXX.js} +8 -8
  124. package/dist/cli/{executions-KTSY5M34.mjs → executions-GD7GXTJM.mjs} +6 -6
  125. package/dist/cli/{feedback-724QK3Z5.js → feedback-BUWTDY4R.js} +14 -14
  126. package/dist/cli/{feedback-WWJRIXEU.mjs → feedback-GBV5HJJZ.mjs} +6 -6
  127. package/dist/cli/git-YG36MROC.js +25 -0
  128. package/dist/cli/{git-R5VRG7X6.mjs → git-YXJGTDQL.mjs} +5 -5
  129. package/dist/cli/index.js +143 -143
  130. package/dist/cli/index.mjs +42 -42
  131. package/dist/cli/{legacy-noops-PWZ5XLAO.mjs → legacy-noops-UJM6GBNP.mjs} +6 -6
  132. package/dist/cli/{legacy-noops-C6GDEGPU.js → legacy-noops-ZSF64V2U.js} +9 -9
  133. package/dist/cli/{monitors-WQSKMHAP.mjs → monitors-UERUQ6CT.mjs} +7 -7
  134. package/dist/cli/{monitors-VAVQ4WCE.js → monitors-XQ2GNH6D.js} +100 -100
  135. package/dist/cli/{org-MAL4QPVF.mjs → org-CP4VLH6M.mjs} +6 -6
  136. package/dist/cli/{org-CWWRWXZQ.js → org-IF6MPVNR.js} +86 -86
  137. package/dist/cli/{play-WJOWK5PQ.js → play-2NHQO5MO.js} +317 -317
  138. package/dist/cli/{play-ILW6MSNG.mjs → play-ZWDYYVPI.mjs} +17 -17
  139. package/dist/cli/{providers-4V2NMLZZ.mjs → providers-2CVIATU4.mjs} +6 -6
  140. package/dist/cli/{providers-W662ANCH.js → providers-LOPXQN56.js} +9 -9
  141. package/dist/cli/{quickstart-C22BR743.mjs → quickstart-KVCFXLID.mjs} +4 -4
  142. package/dist/cli/{quickstart-BW6EBUYX.js → quickstart-N4WDEQZY.js} +6 -6
  143. package/dist/cli/{run-KW7KW4FX.js → run-BDT5LK3I.js} +42 -42
  144. package/dist/cli/{run-SPAU5IMW.mjs → run-RUXHYWLF.mjs} +22 -22
  145. package/dist/cli/search-ATDDVADT.js +32 -0
  146. package/dist/cli/{search-XPC75HLM.mjs → search-BFUTNPA5.mjs} +7 -7
  147. package/dist/cli/{search-output-VJYE7USJ.js → search-output-CTXI2QZU.js} +6 -6
  148. package/dist/cli/{search-output-JKYJSEPM.mjs → search-output-WUGH4PZA.mjs} +4 -4
  149. package/dist/cli/{secrets-YB57KGSB.js → secrets-BZJZYFOU.js} +15 -15
  150. package/dist/cli/{secrets-OJG73GXQ.mjs → secrets-Z4XQVTC6.mjs} +6 -6
  151. package/dist/cli/sessions-HNU35AFM.js +22 -0
  152. package/dist/cli/{sessions-7ZL37BW4.mjs → sessions-VZXR3MQZ.mjs} +6 -6
  153. package/dist/cli/{settings-RKSQB7FA.mjs → settings-VYEZFR4L.mjs} +12 -12
  154. package/dist/cli/{settings-A7DD2ZYE.js → settings-WBYA4JMM.js} +85 -85
  155. package/dist/cli/{setup-S3K5YU62.js → setup-FS2RMSS2.js} +49 -49
  156. package/dist/cli/{setup-NXDUTITY.mjs → setup-H7KCI4SO.mjs} +9 -9
  157. package/dist/cli/skills-VPIURCAZ.js +36 -0
  158. package/dist/cli/{skills-VMFAIDO6.mjs → skills-YQNSJUUG.mjs} +7 -7
  159. package/dist/cli/tools-273GS5HU.js +56 -0
  160. package/dist/cli/{tools-52NTHBSJ.mjs → tools-ZF6SVEGW.mjs} +16 -16
  161. package/dist/cli/{update-SAKBEKMV.mjs → update-RKQNNJM4.mjs} +9 -9
  162. package/dist/cli/update-TOD3XY55.js +34 -0
  163. package/dist/cli/{views-ACRV7MD6.mjs → views-JHHOTWDU.mjs} +6 -6
  164. package/dist/cli/{views-C3GJOBDG.js → views-KN7FEDGT.js} +21 -21
  165. package/dist/cli/{workflow-ZNWCZEGN.js → workflow-2WHSKTTV.js} +17 -17
  166. package/dist/cli/{workflow-CS22E7TC.mjs → workflow-AAYLCLWA.mjs} +7 -7
  167. package/dist/{client-BlLYQDNo.d.mts → client-D0uDBybG.d.mts} +1 -1
  168. package/dist/{client-DSQlkIDO.d.ts → client-DZTnAv4B.d.ts} +1 -1
  169. package/dist/{client-core-rX7n2H8U.d.mts → client-core-BhWf8Y1b.d.mts} +15 -2
  170. package/dist/{client-core-CDwapXy5.d.ts → client-core-og3AP1LL.d.ts} +15 -2
  171. package/dist/{compiler-manifest-BHNC4RL-.d.mts → compiler-manifest-Bes3OVA3.d.mts} +1 -1
  172. package/dist/{compiler-manifest-BHNC4RL-.d.ts → compiler-manifest-Bes3OVA3.d.ts} +1 -1
  173. package/dist/{errors-lhtIWG5Z.d.ts → errors-BJm4lLWc.d.ts} +1 -1
  174. package/dist/{errors-D7sPXrvB.d.mts → errors-Dc5r42ks.d.mts} +1 -1
  175. package/dist/{index-CQTBHXHr.d.ts → index-BfV7mRPF.d.ts} +1 -1
  176. package/dist/{index-NaDZq2xf.d.mts → index-DTkiz_Ur.d.mts} +1 -1
  177. package/dist/index.d.mts +7 -7
  178. package/dist/index.d.ts +7 -7
  179. package/dist/index.js +9 -9
  180. package/dist/index.mjs +6 -6
  181. package/dist/install-integrity.json +120 -112
  182. package/dist/plays/bundle-play-file.d.mts +3 -3
  183. package/dist/plays/bundle-play-file.d.ts +3 -3
  184. package/dist/plays/play-description.d.mts +2 -2
  185. package/dist/plays/play-description.d.ts +2 -2
  186. package/dist/plays/run-request.d.mts +2 -2
  187. package/dist/plays/run-request.d.ts +2 -2
  188. package/dist/release.d.mts +1 -1
  189. package/dist/release.d.ts +1 -1
  190. package/dist/release.js +2 -2
  191. package/dist/release.mjs +1 -1
  192. package/dist/server.d.mts +4 -4
  193. package/dist/server.d.ts +4 -4
  194. package/dist/server.js +5 -5
  195. package/dist/server.mjs +3 -3
  196. package/package.json +1 -1
  197. package/dist/cli/auth-6XQKFOLG.js +0 -43
  198. package/dist/cli/describe-WW3OQRLP.js +0 -49
  199. package/dist/cli/git-PHYRD56H.js +0 -25
  200. package/dist/cli/search-HLE54W5G.js +0 -32
  201. package/dist/cli/sessions-VEBYZIEU.js +0 -22
  202. package/dist/cli/skills-NVQ744CN.js +0 -36
  203. package/dist/cli/tools-SBDUL3WB.js +0 -56
  204. package/dist/cli/update-HHVFZPCV.js +0 -34
@@ -236,6 +236,8 @@ export type RuntimeSandboxOperationBackfillProgress = {
236
236
  projectedOperations: number;
237
237
  targets: readonly RuntimeSandboxOperationBackfillTarget[];
238
238
  nextCursor: RuntimeSandboxOperationBackfillCursor | null;
239
+ /** Repairs to the actionable lease ledger, independent of the history cursor. */
240
+ legacyCapacityLeasesRepaired?: number;
239
241
  };
240
242
 
241
243
  /** Read one bounded resource-element page without writes. */
@@ -336,12 +338,242 @@ async function previewRuntimeSandboxOperationBackfillPage(
336
338
  };
337
339
  }
338
340
 
339
- /** Persisted, resumable orchestrator. Dry-run performs no JSON expansion or writes. */
341
+ /** Repair only expired, unreleased terminal-run leases. A completed historical
342
+ * scan is not proof that this live capacity ledger has no orphaned records.
343
+ * JSON inspection is restricted to this bounded lease page's exact run IDs;
344
+ * provider reconciliation itself continues to read normalized operations only. */
345
+ async function repairLegacyRuntimeSandboxCapacityBindings(
346
+ client: PostgresSchedulerQueryClient,
347
+ input: { dryRun: boolean; batchSize?: number },
348
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
349
+ ): Promise<{
350
+ scanned: number;
351
+ repaired: number;
352
+ inserted: number;
353
+ targets: RuntimeSandboxOperationBackfillTarget[];
354
+ }> {
355
+ const { leases, runs, attempts, operations } = tables(options);
356
+ const candidates = await client.query<{
357
+ lease_id: string;
358
+ run_id: string;
359
+ org_id: string;
360
+ run_org_id: string;
361
+ sandbox_id: string;
362
+ routing_domain: string | null;
363
+ proven_domain: string | null;
364
+ domains: number;
365
+ unbound_resources: number;
366
+ nonproduction_resources: number;
367
+ attempt: number;
368
+ resource_ordinal: number;
369
+ would_insert: boolean;
370
+ proven_attempts: number[];
371
+ existing_operation_key: string | null;
372
+ existing_operation_environment: string | null;
373
+ existing_operation_run_id: string | null;
374
+ existing_operation_org_id: string | null;
375
+ existing_operation_attempt: number | null;
376
+ }>(
377
+ `
378
+ WITH page AS MATERIALIZED (
379
+ SELECT lease.*, run.org_id AS run_org_id FROM ${leases} AS lease
380
+ JOIN ${runs} AS run ON run.run_id = lease.run_id
381
+ WHERE lease.provider = 'daytona' AND lease.released_at IS NULL
382
+ AND lease.sandbox_id IS NOT NULL AND lease.expires_at < clock_timestamp()
383
+ AND run.status IN ('completed', 'failed', 'cancelled', 'crashed')
384
+ AND (lease.routing_domain IS NULL OR NOT EXISTS (
385
+ SELECT 1 FROM ${operations} AS operation
386
+ WHERE operation.provider = lease.provider
387
+ AND operation.sandbox_id = lease.sandbox_id
388
+ AND operation.routing_domain IS NOT DISTINCT FROM lease.routing_domain
389
+ AND operation.run_id = lease.run_id AND operation.org_id = lease.org_id
390
+ AND operation.environment = 'production'
391
+ ))
392
+ ORDER BY lease.lease_id LIMIT $1
393
+ )
394
+ SELECT page.lease_id, page.run_id, page.org_id, page.run_org_id, page.sandbox_id,
395
+ page.routing_domain, proof.proven_domain, proof.domains,
396
+ proof.unbound_resources, proof.nonproduction_resources, proof.attempt, proof.resource_ordinal,
397
+ proof.proven_attempts,
398
+ existing.operation_key AS existing_operation_key,
399
+ existing.environment AS existing_operation_environment,
400
+ existing.run_id AS existing_operation_run_id,
401
+ existing.org_id AS existing_operation_org_id,
402
+ existing.attempt AS existing_operation_attempt,
403
+ existing.operation_key IS NULL AS would_insert
404
+ FROM page
405
+ LEFT JOIN LATERAL (
406
+ SELECT min(NULLIF(resource.value->>'daytonaOrganizationId', '')) AS proven_domain,
407
+ count(DISTINCT NULLIF(resource.value->>'daytonaOrganizationId', ''))::integer AS domains,
408
+ count(*) FILTER (WHERE NULLIF(resource.value->>'daytonaOrganizationId', '') IS NULL)::integer AS unbound_resources,
409
+ count(*) FILTER (WHERE COALESCE(NULLIF(resource.value->>'runtimeEnvironment', ''),
410
+ NULLIF(resource.value->>'daytonaEnvironment', ''), 'production') <> 'production')::integer AS nonproduction_resources,
411
+ (array_agg(attempt.attempt ORDER BY attempt.attempt, resource.ordinal))[1] AS attempt,
412
+ (array_agg(resource.ordinal::integer ORDER BY attempt.attempt, resource.ordinal))[1] AS resource_ordinal,
413
+ array_agg(DISTINCT attempt.attempt) AS proven_attempts
414
+ FROM ${attempts} AS attempt
415
+ CROSS JOIN LATERAL jsonb_array_elements(
416
+ CASE WHEN jsonb_typeof(attempt.resource_json) = 'array'
417
+ THEN attempt.resource_json ELSE jsonb_build_array(attempt.resource_json) END
418
+ ) WITH ORDINALITY AS resource(value, ordinal)
419
+ WHERE attempt.run_id = page.run_id
420
+ AND resource.value->>'kind' = 'daytona_sandbox'
421
+ AND resource.value->>'sandboxId' = page.sandbox_id
422
+ ) AS proof ON true
423
+ LEFT JOIN ${operations} AS existing
424
+ ON existing.provider = page.provider AND existing.sandbox_id = page.sandbox_id
425
+ AND existing.routing_domain = proof.proven_domain
426
+ `,
427
+ [batchSize(input.batchSize)],
428
+ );
429
+ const rows = candidates.rows;
430
+ const unproven = rows.filter(
431
+ (row) =>
432
+ row.org_id !== row.run_org_id ||
433
+ row.domains !== 1 ||
434
+ row.unbound_resources !== 0 ||
435
+ row.nonproduction_resources !== 0 ||
436
+ !row.proven_domain ||
437
+ (row.routing_domain !== null && row.routing_domain !== row.proven_domain),
438
+ );
439
+ if (unproven.length > 0) {
440
+ throw new Error(
441
+ `Cannot prove provider ownership and Production environment for ${unproven.length} legacy capacity lease(s); no legacy repairs applied in this page.`,
442
+ );
443
+ }
444
+ // One shared preflight decides both dry-run and apply. A physical identity
445
+ // already owned by another environment/run/account/attempt is never a plan
446
+ // target, even though INSERT ... ON CONFLICT would otherwise skip it.
447
+ const conflicts = rows.filter(
448
+ (row) =>
449
+ row.existing_operation_key !== null &&
450
+ (row.existing_operation_environment !== 'production' ||
451
+ row.existing_operation_run_id !== row.run_id ||
452
+ row.existing_operation_org_id !== row.org_id ||
453
+ row.existing_operation_attempt === null ||
454
+ !row.proven_attempts.includes(row.existing_operation_attempt)),
455
+ );
456
+ if (conflicts.length > 0) {
457
+ throw new Error(
458
+ `Existing sandbox operation ownership conflicts with ${conflicts.length} legacy capacity lease(s); no legacy repairs applied in this page.`,
459
+ );
460
+ }
461
+ const targets = rows.map((row) => ({
462
+ runId: row.run_id,
463
+ attempt: row.attempt,
464
+ resourceOrdinal: row.resource_ordinal,
465
+ provider: RuntimeSandboxProvider.Daytona,
466
+ sandboxId: row.sandbox_id,
467
+ wouldInsert: row.would_insert,
468
+ }));
469
+ if (input.dryRun || rows.length === 0)
470
+ return { scanned: rows.length, repaired: 0, inserted: 0, targets };
471
+ const backfill = await backfillRuntimeSandboxOperationsFromAttemptResources(
472
+ client,
473
+ {
474
+ batchSize: input.batchSize,
475
+ resources: rows.map((row) => ({
476
+ runId: row.run_id,
477
+ sandboxId: row.sandbox_id,
478
+ routingDomain: row.proven_domain!,
479
+ })),
480
+ },
481
+ options,
482
+ );
483
+ // Binding never releases capacity. Only the ordinary reconciliation owner's
484
+ // exact-ID provider absence proof can do that, with the proven domain.
485
+ const changed = await client.query<{ lease_id: string }>(
486
+ `
487
+ UPDATE ${leases} AS lease SET routing_domain = target.routing_domain
488
+ FROM jsonb_to_recordset($1::jsonb) AS target(
489
+ lease_id text, run_id text, org_id text, sandbox_id text, routing_domain text,
490
+ proven_attempts integer[]
491
+ ), ${runs} AS run, ${operations} AS operation
492
+ WHERE lease.lease_id = target.lease_id AND lease.run_id = target.run_id
493
+ AND lease.org_id = target.org_id AND lease.sandbox_id = target.sandbox_id
494
+ AND lease.provider = 'daytona' AND lease.released_at IS NULL
495
+ AND lease.expires_at < clock_timestamp()
496
+ AND (lease.routing_domain IS NULL OR lease.routing_domain = target.routing_domain)
497
+ AND run.run_id = lease.run_id AND run.org_id = lease.org_id
498
+ AND run.status IN ('completed', 'failed', 'cancelled', 'crashed')
499
+ AND operation.provider = lease.provider AND operation.sandbox_id = lease.sandbox_id
500
+ AND operation.routing_domain = target.routing_domain
501
+ AND operation.run_id = lease.run_id AND operation.org_id = lease.org_id
502
+ AND operation.environment = 'production'
503
+ AND operation.attempt = ANY(target.proven_attempts)
504
+ RETURNING lease.lease_id
505
+ `,
506
+ [
507
+ JSON.stringify(
508
+ rows.map((row) => ({
509
+ lease_id: row.lease_id,
510
+ run_id: row.run_id,
511
+ org_id: row.org_id,
512
+ sandbox_id: row.sandbox_id,
513
+ routing_domain: row.proven_domain,
514
+ proven_attempts: row.proven_attempts,
515
+ })),
516
+ ),
517
+ ],
518
+ );
519
+ if (changed.rows.length === 0)
520
+ throw new Error(
521
+ 'Legacy capacity binding repair made no progress; inspect operation ownership conflicts.',
522
+ );
523
+ return {
524
+ scanned: rows.length,
525
+ repaired: changed.rows.length,
526
+ inserted: backfill.insertedOperations,
527
+ targets,
528
+ };
529
+ }
530
+
531
+ /** Persisted, resumable orchestrator. Dry-run performs no writes. */
340
532
  export async function advanceRuntimeSandboxOperationBackfill(
341
533
  client: PostgresSchedulerQueryClient,
342
534
  input: { dryRun: boolean; batchSize?: number; maxBatches?: number },
343
535
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
344
536
  ): Promise<RuntimeSandboxOperationBackfillProgress> {
537
+ // Always prove the actionable capacity ledger, even after history completed.
538
+ let legacyCapacityLeasesRepaired = 0;
539
+ const repairBatches = Math.max(
540
+ 1,
541
+ Math.min(200, Math.floor(input.maxBatches ?? 1)),
542
+ );
543
+ for (let batch = 0; batch < repairBatches; batch += 1) {
544
+ const repair = await repairLegacyRuntimeSandboxCapacityBindings(
545
+ client,
546
+ input,
547
+ options,
548
+ );
549
+ legacyCapacityLeasesRepaired += repair.repaired;
550
+ if (repair.scanned === 0) break;
551
+ if (
552
+ input.dryRun ||
553
+ (batch === repairBatches - 1 &&
554
+ (
555
+ await repairLegacyRuntimeSandboxCapacityBindings(
556
+ client,
557
+ { ...input, dryRun: true },
558
+ options,
559
+ )
560
+ ).scanned > 0)
561
+ ) {
562
+ return {
563
+ legacyCapacityLeasesRepaired,
564
+ phase: RuntimeSandboxOperationBackfillPhase.Pending,
565
+ dryRun: input.dryRun,
566
+ batches: batch + 1,
567
+ scannedAttempts: repair.scanned,
568
+ insertedOperations: repair.inserted,
569
+ projectedOperations: repair.targets.filter(
570
+ (target) => target.wouldInsert,
571
+ ).length,
572
+ targets: repair.targets,
573
+ nextCursor: null,
574
+ };
575
+ }
576
+ }
345
577
  const checkpoint = await readRuntimeSandboxOperationBackfillCheckpoint(
346
578
  client,
347
579
  options,
@@ -349,6 +581,7 @@ export async function advanceRuntimeSandboxOperationBackfill(
349
581
  if (input.dryRun) {
350
582
  if (checkpoint.phase === RuntimeSandboxOperationBackfillPhase.Complete) {
351
583
  return {
584
+ legacyCapacityLeasesRepaired,
352
585
  phase: checkpoint.phase,
353
586
  dryRun: true,
354
587
  batches: 0,
@@ -365,6 +598,7 @@ export async function advanceRuntimeSandboxOperationBackfill(
365
598
  options,
366
599
  );
367
600
  return {
601
+ legacyCapacityLeasesRepaired,
368
602
  phase: RuntimeSandboxOperationBackfillPhase.Pending,
369
603
  dryRun: true,
370
604
  batches: preview.scannedAttempts > 0 ? 1 : 0,
@@ -379,6 +613,7 @@ export async function advanceRuntimeSandboxOperationBackfill(
379
613
  }
380
614
  if (checkpoint.phase === RuntimeSandboxOperationBackfillPhase.Complete) {
381
615
  return {
616
+ legacyCapacityLeasesRepaired,
382
617
  phase: checkpoint.phase,
383
618
  dryRun: false,
384
619
  batches: 0,
@@ -425,6 +660,7 @@ export async function advanceRuntimeSandboxOperationBackfill(
425
660
  );
426
661
  if (phase === RuntimeSandboxOperationBackfillPhase.Complete) {
427
662
  return {
663
+ legacyCapacityLeasesRepaired,
428
664
  phase,
429
665
  dryRun: false,
430
666
  batches: batch + 1,
@@ -437,6 +673,7 @@ export async function advanceRuntimeSandboxOperationBackfill(
437
673
  }
438
674
  }
439
675
  return {
676
+ legacyCapacityLeasesRepaired,
440
677
  phase: RuntimeSandboxOperationBackfillPhase.Pending,
441
678
  dryRun: false,
442
679
  batches: maxBatches,
@@ -459,7 +696,16 @@ export async function advanceRuntimeSandboxOperationBackfill(
459
696
  */
460
697
  export async function backfillRuntimeSandboxOperationsFromAttemptResources(
461
698
  client: PostgresSchedulerQueryClient,
462
- input: { batchSize?: number; cursor?: RuntimeSandboxOperationBackfillCursor },
699
+ input: {
700
+ batchSize?: number;
701
+ cursor?: RuntimeSandboxOperationBackfillCursor;
702
+ /** Exact, ownership-proved legacy resources; absent preserves history paging. */
703
+ resources?: readonly {
704
+ runId: string;
705
+ sandboxId: string;
706
+ routingDomain: string;
707
+ }[];
708
+ },
463
709
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
464
710
  ): Promise<RuntimeSandboxOperationBackfillSummary> {
465
711
  const limit = batchSize(input.batchSize);
@@ -510,6 +756,18 @@ export async function backfillRuntimeSandboxOperationsFromAttemptResources(
510
756
  WHERE attempt.resource_json IS NOT NULL
511
757
  AND resource.value->>'kind' IN ('daytona_sandbox', 'modal_sandbox')
512
758
  AND NULLIF(resource.value->>'sandboxId', '') IS NOT NULL
759
+ AND ($7::jsonb IS NULL OR attempt.run_id IN (
760
+ SELECT target.run_id FROM jsonb_to_recordset($7::jsonb) AS target(run_id text)
761
+ ))
762
+ AND ($7::jsonb IS NULL OR EXISTS (
763
+ SELECT 1 FROM jsonb_to_recordset($7::jsonb) AS target(
764
+ run_id text, sandbox_id text, routing_domain text
765
+ )
766
+ WHERE target.run_id = attempt.run_id
767
+ AND target.sandbox_id = resource.value->>'sandboxId'
768
+ AND target.routing_domain = resource.value->>'daytonaOrganizationId'
769
+ AND resource.value->>'kind' = 'daytona_sandbox'
770
+ ))
513
771
  AND (
514
772
  $1::text IS NULL
515
773
  OR (attempt.updated_at, attempt.run_id, attempt.attempt, resource.ordinal) >
@@ -571,6 +829,15 @@ export async function backfillRuntimeSandboxOperationsFromAttemptResources(
571
829
  cursor?.resourceOrdinal ?? 0,
572
830
  limit,
573
831
  runtimeSandboxOperationTargetState('backfill_live'),
832
+ input.resources === undefined
833
+ ? null
834
+ : JSON.stringify(
835
+ input.resources.map((r) => ({
836
+ run_id: r.runId,
837
+ sandbox_id: r.sandboxId,
838
+ routing_domain: r.routingDomain,
839
+ })),
840
+ ),
574
841
  ],
575
842
  );
576
843
  const last = result.rows[0] ?? null;
@@ -1,8 +1,33 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
1
2
  import dns from 'node:dns';
2
3
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
+ import {
5
+ readCarriedExperimentSwitchOverrides,
6
+ type ExperimentSwitchOverrides,
7
+ } from '../experiment-switches';
8
+ import { parseEarlySandboxClaimOwner } from './early-sandbox-claim-affinity';
3
9
 
4
10
  export const RUNTIME_WORKER_WAKE_PATH = '/internal/runtime-worker/wake';
5
11
 
12
+ /**
13
+ * Whether an Authorization header carries `Bearer <expected>`, in constant
14
+ * time: both sides are hashed to a fixed length first, so neither the content
15
+ * nor the length of the internal token leaks through response timing. An
16
+ * unset expected token matches nothing.
17
+ */
18
+ export function internalBearerTokenMatches(
19
+ authorization: string | null | undefined,
20
+ expectedToken: string | undefined,
21
+ ): boolean {
22
+ const expected = expectedToken?.trim();
23
+ if (!expected) return false;
24
+ const digest = (value: string) => createHash('sha256').update(value).digest();
25
+ return timingSafeEqual(
26
+ digest(authorization?.trim() ?? ''),
27
+ digest(`Bearer ${expected}`),
28
+ );
29
+ }
30
+
6
31
  /** Wake the existing, fixed queue only. The hint cannot admit or name a task. */
7
32
  export function handleRuntimeWorkerWake(
8
33
  req: IncomingMessage,
@@ -25,8 +50,7 @@ export function handleRuntimeWorkerWake(
25
50
  if (req.method !== 'POST') {
26
51
  respond(405, '{"error":"Use POST."}');
27
52
  } else if (
28
- !input.expectedToken?.trim() ||
29
- req.headers.authorization?.trim() !== `Bearer ${input.expectedToken.trim()}`
53
+ !internalBearerTokenMatches(req.headers.authorization, input.expectedToken)
30
54
  ) {
31
55
  respond(401, '{"error":"Unauthorized."}');
32
56
  } else if (!input.wake?.()) {
@@ -136,9 +160,10 @@ export async function handleRuntimeGatewayWorkerWake(
136
160
  });
137
161
  if (req.method !== 'POST') return respond(405, '{"error":"Use POST."}');
138
162
  if (
139
- !input.expectedToken?.trim() ||
140
- req.headers.get('authorization')?.trim() !==
141
- `Bearer ${input.expectedToken.trim()}`
163
+ !internalBearerTokenMatches(
164
+ req.headers.get('authorization'),
165
+ input.expectedToken,
166
+ )
142
167
  ) {
143
168
  return respond(401, '{"error":"Unauthorized."}');
144
169
  }
@@ -150,3 +175,211 @@ export async function handleRuntimeGatewayWorkerWake(
150
175
  }
151
176
  return respond(202, '{"ok":true}');
152
177
  }
178
+
179
+ /**
180
+ * Preview experiment E2: an admitted run asks the worker lane to start its
181
+ * Modal sandbox early. The body names only the run's caller workflow id and
182
+ * org; the worker derives everything else from its own deployment. A lossy
183
+ * hint: a miss only means the launch creates its sandbox as today.
184
+ */
185
+ export const RUNTIME_WORKER_EARLY_SANDBOX_PATH =
186
+ '/internal/runtime-worker/early-sandbox';
187
+
188
+ export type RuntimeWorkerEarlySandboxHint = {
189
+ workflowId: string;
190
+ orgId: string | null;
191
+ /**
192
+ * EXPERIMENT: the run's admission-validated switch overrides, so the worker
193
+ * resolves E2/F2 for this run. Absent: static defaults.
194
+ */
195
+ experimentSwitchOverrides?: ExperimentSwitchOverrides;
196
+ };
197
+
198
+ function parseEarlySandboxHint(
199
+ text: string,
200
+ ): RuntimeWorkerEarlySandboxHint | null {
201
+ try {
202
+ const value = JSON.parse(text) as Record<string, unknown>;
203
+ const workflowId =
204
+ typeof value.workflowId === 'string' ? value.workflowId.trim() : '';
205
+ if (!workflowId || workflowId.length > 512) return null;
206
+ const orgId =
207
+ typeof value.orgId === 'string' && value.orgId.trim()
208
+ ? value.orgId.trim().slice(0, 128)
209
+ : null;
210
+ const experimentSwitchOverrides = readCarriedExperimentSwitchOverrides(
211
+ value.experimentSwitchOverrides,
212
+ );
213
+ return {
214
+ workflowId,
215
+ orgId,
216
+ ...(experimentSwitchOverrides ? { experimentSwitchOverrides } : {}),
217
+ };
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+
223
+ /** Worker side of the early-sandbox hint (node:http). */
224
+ export function handleRuntimeWorkerEarlySandbox(
225
+ req: IncomingMessage,
226
+ res: ServerResponse,
227
+ input: {
228
+ expectedToken: string | undefined;
229
+ start: ((hint: RuntimeWorkerEarlySandboxHint) => boolean) | null;
230
+ /**
231
+ * CA: after an accepted start, the name this worker claims under when the
232
+ * hint's run asked for claim affinity; null otherwise (reply unchanged).
233
+ */
234
+ claimOwner?: ((hint: RuntimeWorkerEarlySandboxHint) => string | null) | null;
235
+ },
236
+ ): boolean {
237
+ if (
238
+ new URL(req.url ?? '/', 'http://worker.local').pathname !==
239
+ RUNTIME_WORKER_EARLY_SANDBOX_PATH
240
+ )
241
+ return false;
242
+ const respond = (status: number, body: string) => {
243
+ res.writeHead(status, {
244
+ 'content-type': 'application/json',
245
+ 'cache-control': 'no-store',
246
+ });
247
+ res.end(body);
248
+ };
249
+ if (req.method !== 'POST') {
250
+ respond(405, '{"error":"Use POST."}');
251
+ return true;
252
+ }
253
+ if (
254
+ !internalBearerTokenMatches(req.headers.authorization, input.expectedToken)
255
+ ) {
256
+ respond(401, '{"error":"Unauthorized."}');
257
+ return true;
258
+ }
259
+ let text = '';
260
+ req.setEncoding('utf8');
261
+ req.on('data', (chunk: string) => {
262
+ if (text.length < 4096) text += chunk;
263
+ });
264
+ req.on('end', () => {
265
+ const hint = parseEarlySandboxHint(text);
266
+ if (!hint) return respond(400, '{"error":"Invalid hint."}');
267
+ if (!input.start?.(hint))
268
+ return respond(503, '{"error":"Early sandbox not started."}');
269
+ const owner = parseEarlySandboxClaimOwner(input.claimOwner?.(hint) ?? null);
270
+ respond(202, owner ? JSON.stringify({ ok: true, owner }) : '{"ok":true}');
271
+ });
272
+ return true;
273
+ }
274
+
275
+ /** Send the hint (app -> gateway, gateway -> worker). Bounded, never retried. */
276
+ export async function requestRuntimeWorkerEarlySandbox(
277
+ url: string,
278
+ token: string,
279
+ hint: RuntimeWorkerEarlySandboxHint,
280
+ ): Promise<number | null> {
281
+ return (await requestRuntimeWorkerEarlySandboxWithOwner(url, token, hint))
282
+ .status;
283
+ }
284
+
285
+ /**
286
+ * The hint, plus the CA owner a 202 reply names (null from an older worker or
287
+ * gateway, or when the run did not ask for claim affinity).
288
+ */
289
+ export async function requestRuntimeWorkerEarlySandboxWithOwner(
290
+ url: string,
291
+ token: string,
292
+ hint: RuntimeWorkerEarlySandboxHint,
293
+ ): Promise<{ status: number | null; owner: string | null }> {
294
+ const controller = new AbortController();
295
+ const timeout = setTimeout(() => controller.abort(), 1_000);
296
+ try {
297
+ const target = new URL(url);
298
+ if (target.protocol === 'http:' && target.hostname.endsWith('.internal')) {
299
+ const address = await new Promise<string>((resolve, reject) => {
300
+ dns.lookup(target.hostname, { family: 6 }, (error, resolved) =>
301
+ error ? reject(error) : resolve(resolved),
302
+ );
303
+ });
304
+ target.hostname = `[${address}]`;
305
+ }
306
+ const response = await fetch(target, {
307
+ method: 'POST',
308
+ headers: {
309
+ authorization: `Bearer ${token}`,
310
+ 'content-type': 'application/json',
311
+ },
312
+ body: JSON.stringify(hint),
313
+ redirect: 'error',
314
+ signal: controller.signal,
315
+ });
316
+ let owner: string | null = null;
317
+ if (response.status === 202) {
318
+ try {
319
+ const text = (await response.text()).slice(0, 1024);
320
+ owner = parseEarlySandboxClaimOwner(
321
+ (JSON.parse(text) as { owner?: unknown }).owner,
322
+ );
323
+ } catch {
324
+ // An unreadable reply only means no recorded owner.
325
+ }
326
+ } else {
327
+ await response.body?.cancel();
328
+ }
329
+ return { status: response.status, owner };
330
+ } catch (error) {
331
+ console.warn('[runtime.worker_early_sandbox.failed]', {
332
+ error: error instanceof Error ? error.name : 'TransportError',
333
+ });
334
+ return { status: null, owner: null };
335
+ } finally {
336
+ clearTimeout(timeout);
337
+ }
338
+ }
339
+
340
+ /** Gateway relay of the early-sandbox hint to its fixed private worker. */
341
+ export async function handleRuntimeGatewayEarlySandbox(
342
+ req: Request,
343
+ input: {
344
+ expectedToken: string | undefined;
345
+ target: RuntimeWorkerWakeTarget | null;
346
+ },
347
+ ): Promise<Response | null> {
348
+ if (new URL(req.url).pathname !== RUNTIME_WORKER_EARLY_SANDBOX_PATH)
349
+ return null;
350
+ const respond = (status: number, body: string) =>
351
+ new Response(body, {
352
+ status,
353
+ headers: {
354
+ 'content-type': 'application/json',
355
+ 'cache-control': 'no-store',
356
+ },
357
+ });
358
+ if (req.method !== 'POST') return respond(405, '{"error":"Use POST."}');
359
+ if (
360
+ !internalBearerTokenMatches(
361
+ req.headers.get('authorization'),
362
+ input.expectedToken,
363
+ )
364
+ ) {
365
+ return respond(401, '{"error":"Unauthorized."}');
366
+ }
367
+ const hint = parseEarlySandboxHint(await req.text());
368
+ if (!hint) return respond(400, '{"error":"Invalid hint."}');
369
+ if (!input.target) return respond(503, '{"error":"No worker target."}');
370
+ const workerUrl = new URL(input.target.url);
371
+ workerUrl.pathname = RUNTIME_WORKER_EARLY_SANDBOX_PATH;
372
+ const { status, owner } = await requestRuntimeWorkerEarlySandboxWithOwner(
373
+ workerUrl.toString(),
374
+ input.target.token,
375
+ hint,
376
+ );
377
+ return respond(
378
+ status ?? 503,
379
+ status === 202
380
+ ? owner
381
+ ? JSON.stringify({ ok: true, owner })
382
+ : '{"ok":true}'
383
+ : '{"ok":false}',
384
+ );
385
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Statically named tool steps anywhere in a static pipeline (loops and
3
+ * branches nest them), at most 16, excluding event waits. These name the
4
+ * read-only startup lookups (tool metadata and auth-scope GETs) a detached
5
+ * runner may prefetch while it waits for the park acknowledgement.
6
+ */
7
+ export const STARTUP_READ_TOOL_IDS_MAX = 16;
8
+
9
+ export function staticPipelineStartupReadToolIds(pipeline: unknown): string[] {
10
+ const toolIds = new Set<string>();
11
+ const visit = (node: unknown, depth: number): void => {
12
+ if (
13
+ !node ||
14
+ typeof node !== 'object' ||
15
+ depth > 64 ||
16
+ toolIds.size >= STARTUP_READ_TOOL_IDS_MAX
17
+ )
18
+ return;
19
+ if (Array.isArray(node)) {
20
+ for (const item of node) visit(item, depth + 1);
21
+ return;
22
+ }
23
+ const record = node as Record<string, unknown>;
24
+ if (
25
+ record.type === 'tool' &&
26
+ typeof record.toolId === 'string' &&
27
+ record.isEventWait !== true
28
+ ) {
29
+ const id = record.toolId.trim();
30
+ if (id) toolIds.add(id);
31
+ }
32
+ for (const value of Object.values(record)) visit(value, depth + 1);
33
+ };
34
+ visit(pipeline, 0);
35
+ return [...toolIds];
36
+ }
37
+
38
+ /** Reader default: a valid string array (trimmed, non-empty, at most 16), or null. */
39
+ export function readStartupReadToolIds(value: unknown): string[] | null {
40
+ if (!Array.isArray(value)) return null;
41
+ const ids = value
42
+ .filter((id): id is string => typeof id === 'string')
43
+ .map((id) => id.trim())
44
+ .filter(Boolean)
45
+ .slice(0, STARTUP_READ_TOOL_IDS_MAX);
46
+ return ids.length > 0 ? ids : null;
47
+ }
@@ -360,7 +360,7 @@ export function createRuntimeStepToolResultReceipts(
360
360
  // exists to cap how many stored payloads expand at once; holding one
361
361
  // of its slots across this gateway round trip only queued unrelated
362
362
  // rows behind this row's write, so the mutation runs outside it.
363
- const storedResult = stampResultReceipt(
363
+ const storedResult = stampToolResultReceiptKey(
364
364
  candidate.result,
365
365
  record.resultReceiptKey,
366
366
  );
@@ -420,7 +420,8 @@ export function createRuntimeStepToolResultReceipts(
420
420
  };
421
421
  }
422
422
 
423
- function stampResultReceipt(
423
+ /** The stored form of a live result: the result stamped with its receipt key. */
424
+ export function stampToolResultReceiptKey(
424
425
  result: ToolExecuteResult,
425
426
  resultReceiptKey: string,
426
427
  ): ToolExecuteResult {
@@ -438,13 +439,13 @@ function completedResult(
438
439
  return null;
439
440
  }
440
441
  if (isSerializedToolExecuteResult(receipt.output)) {
441
- return stampResultReceipt(
442
+ return stampToolResultReceiptKey(
442
443
  deserializeToolExecuteResult(receipt.output),
443
444
  resultReceiptKey,
444
445
  );
445
446
  }
446
447
  if (isToolExecuteResult(receipt.output)) {
447
- return stampResultReceipt(receipt.output, resultReceiptKey);
448
+ return stampToolResultReceiptKey(receipt.output, resultReceiptKey);
448
449
  }
449
450
  throw new Error(
450
451
  `Completed Tool Result Receipt ${resultReceiptKey} has no valid serialized ToolExecuteResult.`,