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
@@ -0,0 +1,556 @@
1
+ /**
2
+ * `modal_sidecar` runtime profile: the trusted supervisor that runs beside an
3
+ * untrusted Play runner inside one Modal sandbox.
4
+ *
5
+ * The supervisor is the unchanged runtime gateway bundle
6
+ * (`scripts/build-runtime-gateway-preview-bundle.ts`): `gateway.js` in the
7
+ * receipt role and `relay.js` in the execution role, exactly the two processes
8
+ * the Fly gateway and relay run. Receipt reads and commits, provider permits,
9
+ * rate state, attempt fences, the relay's backpressure 429 and the proxied
10
+ * Vercel execute route are that code, not a reimplementation. The runner
11
+ * reaches it over the sandbox-local network at `http://sup:<port>`; the main
12
+ * container has no outbound network.
13
+ *
14
+ * Images are published by content hash (`deepline-runtime-supervisor:<hash>`)
15
+ * and selected by `DEEPLINE_MODAL_SUPERVISOR_HASH`, so a supervisor change is
16
+ * a bundle build and publish plus one worker setting, never a runtime rebuild.
17
+ */
18
+ import { createHash } from 'node:crypto';
19
+ import { gzipSync } from 'node:zlib';
20
+ import {
21
+ resolveExperimentSwitch,
22
+ type ExperimentSwitchOverrides,
23
+ } from './experiment-switches';
24
+
25
+ export const MODAL_SUPERVISOR_SIDECAR_NAME = 'sup';
26
+ export const MODAL_SUPERVISOR_RECEIPT_PORT = 8787;
27
+ export const MODAL_SUPERVISOR_EXECUTION_PORT = 8788;
28
+ export const MODAL_SUPERVISOR_IMAGE_NAME = 'deepline-runtime-supervisor';
29
+ export const MODAL_SUPERVISOR_BASE_IMAGE = 'oven/bun:1.4.4';
30
+ export const MODAL_SUPERVISOR_ROOT = '/opt/deepline/supervisor';
31
+ /** Printed once by the sidecar when both gateway ports answer. */
32
+ export const MODAL_SUPERVISOR_READY_MARKER = 'DEEPLINE_SUPERVISOR_READY';
33
+ export const MODAL_SUPERVISOR_HASH_ENV = 'DEEPLINE_MODAL_SUPERVISOR_HASH';
34
+ /**
35
+ * Set to `1` in the supervisor's plain env by the worker: the gateway is
36
+ * running as the in-sandbox sidecar. It then binds its metrics port to
37
+ * loopback, serves no worker wake or early-sandbox route, and accepts only
38
+ * the executor token of the run the sidecar is pinned to.
39
+ */
40
+ export const MODAL_SUPERVISOR_GATEWAY_ENV = 'DEEPLINE_RUNTIME_GATEWAY_SIDECAR';
41
+
42
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
43
+ /** Below Linux's 128 KiB single-argument limit for each `/bin/sh -c` RUN. */
44
+ const MODAL_RUN_CHUNK_CHARS = 96 * 1024;
45
+
46
+ export type ModalSupervisorBundle = { gateway: string; relay: string };
47
+
48
+ /** One hash over both files, so a change to either selects a new image. */
49
+ export function modalSupervisorBundleSha256(
50
+ bundle: ModalSupervisorBundle,
51
+ ): string {
52
+ return createHash('sha256')
53
+ .update('gateway.js\0')
54
+ .update(bundle.gateway)
55
+ .update('\0relay.js\0')
56
+ .update(bundle.relay)
57
+ .digest('hex');
58
+ }
59
+
60
+ export function modalSupervisorImageRef(hash: string): string {
61
+ if (!SHA256_HEX.test(hash)) {
62
+ throw new Error('Supervisor hash must be 64 lowercase hex characters.');
63
+ }
64
+ return `${MODAL_SUPERVISOR_IMAGE_NAME}:${hash.slice(0, 32)}`;
65
+ }
66
+
67
+ export function configuredModalSupervisorHash(
68
+ env: Readonly<Record<string, string | undefined>> = process.env,
69
+ ): string | null {
70
+ const value = env[MODAL_SUPERVISOR_HASH_ENV]?.trim().toLowerCase();
71
+ if (!value) return null;
72
+ if (!SHA256_HEX.test(value)) {
73
+ throw new Error(
74
+ `${MODAL_SUPERVISOR_HASH_ENV} must be 64 lowercase hex characters.`,
75
+ );
76
+ }
77
+ return value;
78
+ }
79
+
80
+ function bakeFileCommands(name: string, content: string): string[] {
81
+ const fileHash = createHash('sha256').update(content).digest('hex');
82
+ const encoded = gzipSync(Buffer.from(content, 'utf-8'), { level: 9 }).toString(
83
+ 'base64',
84
+ );
85
+ const staged = `/tmp/${name}.gz.b64`;
86
+ const commands = [`RUN rm -f ${staged}`];
87
+ for (let offset = 0; offset < encoded.length; offset += MODAL_RUN_CHUNK_CHARS) {
88
+ commands.push(
89
+ `RUN printf '%s' '${encoded.slice(offset, offset + MODAL_RUN_CHUNK_CHARS)}' >> ${staged}`,
90
+ );
91
+ }
92
+ commands.push(
93
+ [
94
+ 'RUN set -eu',
95
+ `base64 -d < ${staged} | gzip -dc > /tmp/${name}`,
96
+ `echo "${fileHash} /tmp/${name}" | sha256sum -c -`,
97
+ `install -m 0444 /tmp/${name} "${MODAL_SUPERVISOR_ROOT}/${name}"`,
98
+ `rm -f /tmp/${name} ${staged}`,
99
+ ].join('; '),
100
+ );
101
+ return commands;
102
+ }
103
+
104
+ /**
105
+ * Dockerfile layers that bake both gateway bundles into the supervisor image,
106
+ * one layer per file because Modal bounds each image definition at 2 MB.
107
+ * Modal's JS SDK cannot COPY from a local build context, so each file rides as
108
+ * base64 in bounded RUN chunks and the build fails unless the reassembled
109
+ * bytes hash to the source. A pure function of the bundle, so a rebuild of the
110
+ * same bundle is a Modal cache hit.
111
+ */
112
+ export function modalSupervisorDockerfileLayers(
113
+ bundle: ModalSupervisorBundle,
114
+ ): string[][] {
115
+ if (!bundle.gateway || !bundle.relay) {
116
+ throw new Error('Supervisor bundle files must be non-empty.');
117
+ }
118
+ return [
119
+ [
120
+ `RUN install -d -m 0755 ${MODAL_SUPERVISOR_ROOT}`,
121
+ ...bakeFileCommands('gateway.js', bundle.gateway),
122
+ ],
123
+ [
124
+ ...bakeFileCommands('relay.js', bundle.relay),
125
+ `RUN chmod 0555 ${MODAL_SUPERVISOR_ROOT}`,
126
+ ],
127
+ ];
128
+ }
129
+
130
+ /**
131
+ * Worker-owned launch options for the profile. The runtime worker sets them
132
+ * once at startup from `apps/absurd-runtime-worker/modal-sidecar-launch.ts`, which
133
+ * is outside the app and Convex release inputs, so changing one rebuilds only
134
+ * the worker image. Unset fields keep the defaults below. Nothing here
135
+ * changes the billed resource profile; a cpu override is for measurement.
136
+ */
137
+ export type ModalSupervisorLaunchOptions = {
138
+ /** Sandbox CPU for a modal_sidecar sandbox. Default: the Play profile's. */
139
+ cpu?: number;
140
+ /** Modal regions for a modal_sidecar sandbox. Default: ['us-east']. */
141
+ regions?: string[];
142
+ /** Runner probe attempt timeout while the supervisor starts. Default 100 ms. */
143
+ readinessProbeTimeoutMs?: number;
144
+ /**
145
+ * Send one unauthenticated `OPTIONS` to the app's integrations execute route
146
+ * when sandbox creation starts, so a cold app function boots (and loads the
147
+ * execute modules) while the sandbox starts instead of on the first tool
148
+ * call. No credential beyond the Preview protection bypass, no data read or
149
+ * written, no retry, no effect on the run when it fails. Default: off.
150
+ */
151
+ prewarmAppExecuteRoute?: boolean;
152
+ /**
153
+ * With `prewarmAppExecuteRoute`, send the authenticated no-op prewarm
154
+ * (`integrations_execute.runtime_prewarm`: the run's executor token plus the
155
+ * worker's internal service token) instead of the unauthenticated OPTIONS,
156
+ * so the execute function's auth and catalog are warm too. Sent only after
157
+ * admission and token issuance (at sandbox create). No provider call, no
158
+ * charge. Default: off.
159
+ */
160
+ authenticatedAppPrewarm?: boolean;
161
+ /**
162
+ * Reuse this process's Modal app handle, Preview Python image build and
163
+ * supervisor image lookup for 10 minutes (a failed lookup is never kept),
164
+ * and resolve the supervisor plan alongside the app and image instead of
165
+ * after them. Every value is content-addressed or a stable named object.
166
+ * Default: off (each launch looks all three up in sequence).
167
+ */
168
+ cacheModalLaunchLookups?: boolean;
169
+ };
170
+
171
+ /**
172
+ * Fast mode B: the run route sends the authenticated execute prewarm itself,
173
+ * right after it admits the run (the run's executor token exists from then),
174
+ * instead of the worker sending it at sandbox create ~350 ms later. A cold
175
+ * execute instance then has that much more time to boot before the first
176
+ * tool call. With this on the worker sends no prewarm of its own, so the
177
+ * number of prewarms per run is unchanged. Same credential and route; the
178
+ * request is sent from the app's own function to its own deployment origin.
179
+ * Off.
180
+ */
181
+ export const PREWARM_EXECUTE_AT_ADMISSION = false;
182
+
183
+ /**
184
+ * B for one run. The run route (send at admission) and the worker's Modal
185
+ * launch (skip its own prewarm) both ask this with the run's carried
186
+ * overrides, so the two sides always agree.
187
+ */
188
+ export function executePrewarmSentAtAdmission(
189
+ overrides: ExperimentSwitchOverrides | null | undefined,
190
+ ): boolean {
191
+ return resolveExperimentSwitch('B', overrides, PREWARM_EXECUTE_AT_ADMISSION);
192
+ }
193
+
194
+ let modalSupervisorLaunchOptions: Readonly<ModalSupervisorLaunchOptions> = {};
195
+
196
+ export function configureModalSupervisorLaunch(
197
+ options: ModalSupervisorLaunchOptions,
198
+ ): void {
199
+ if (
200
+ (options.cpu !== undefined &&
201
+ !(Number.isFinite(options.cpu) && options.cpu > 0 && options.cpu <= 8)) ||
202
+ (options.regions !== undefined &&
203
+ (options.regions.length === 0 ||
204
+ options.regions.some((region) => !/^[a-z0-9-]{2,32}$/.test(region)))) ||
205
+ (options.readinessProbeTimeoutMs !== undefined &&
206
+ !(
207
+ Number.isInteger(options.readinessProbeTimeoutMs) &&
208
+ options.readinessProbeTimeoutMs >= 10 &&
209
+ options.readinessProbeTimeoutMs <= 5_000
210
+ )) ||
211
+ (options.prewarmAppExecuteRoute !== undefined &&
212
+ typeof options.prewarmAppExecuteRoute !== 'boolean') ||
213
+ (options.cacheModalLaunchLookups !== undefined &&
214
+ typeof options.cacheModalLaunchLookups !== 'boolean') ||
215
+ (options.authenticatedAppPrewarm !== undefined &&
216
+ typeof options.authenticatedAppPrewarm !== 'boolean')
217
+ ) {
218
+ throw new Error('Invalid modal_sidecar launch options.');
219
+ }
220
+ modalSupervisorLaunchOptions = Object.freeze({
221
+ ...options,
222
+ ...(options.regions ? { regions: [...options.regions] } : {}),
223
+ });
224
+ }
225
+
226
+ export function modalSupervisorLaunch(): Readonly<ModalSupervisorLaunchOptions> {
227
+ return modalSupervisorLaunchOptions;
228
+ }
229
+
230
+ /**
231
+ * Worker environment the supervisor inherits. Secrets travel as a Modal
232
+ * Secret, never as plain sidecar env. Only names the Fly gateway and relay
233
+ * already receive are forwarded; the main container receives none of them.
234
+ * Not the worker wake URL: the sidecar serves no wake route, and the worker's
235
+ * Fly-private address is unreachable from Modal anyway.
236
+ */
237
+ const SUPERVISOR_SECRET_ENV = [
238
+ 'WORKFLOW_RUNTIME_POSTGRES',
239
+ 'DEEPLINE_INTERNAL_TOKEN',
240
+ 'VERCEL_PROTECTION_BYPASS_TOKEN',
241
+ 'CLOUDFLARE_R2_ENDPOINT',
242
+ 'CLOUDFLARE_R2_ACCESS_KEY_ID',
243
+ 'CLOUDFLARE_R2_SECRET_ACCESS_KEY',
244
+ 'CLOUDFLARE_R2_BUCKET_NAME',
245
+ ] as const;
246
+
247
+ export type ModalSupervisorEnvironment = {
248
+ env: Record<string, string>;
249
+ secretEnv: Record<string, string>;
250
+ /**
251
+ * The only hosts the sidecar may reach (its outbound domain allowlist):
252
+ * the app origin(s) it verifies tokens against and relays execution to,
253
+ * the runtime Postgres host, and the R2 endpoint (path and virtual-hosted
254
+ * bucket forms). Derived from the same config the gateway reads.
255
+ */
256
+ egressDomains: string[];
257
+ };
258
+
259
+ const EGRESS_HOSTNAME = /^(?=.{1,253}$)[a-z0-9-]+(?:\.[a-z0-9-]+)*$/u;
260
+
261
+ function egressHostname(value: string, label: string): string {
262
+ const hostname = value.trim().toLowerCase().replace(/^\[|\]$/gu, '');
263
+ if (!EGRESS_HOSTNAME.test(hostname)) {
264
+ throw new Error(
265
+ `RUNTIME_MODAL_SUPERVISOR_CONFIG_INVALID: ${label} has no usable host.`,
266
+ );
267
+ }
268
+ return hostname;
269
+ }
270
+
271
+ /** Hosts of a Postgres URL, including libpq's `host1:port,host2:port` form. */
272
+ function postgresEgressHostnames(url: string): string[] {
273
+ const authority = /^postgres(?:ql)?:\/\/(?:[^@/?#]*@)?([^/?#]+)/iu.exec(
274
+ url.trim(),
275
+ )?.[1];
276
+ if (!authority) {
277
+ throw new Error(
278
+ 'RUNTIME_MODAL_SUPERVISOR_CONFIG_INVALID: WORKFLOW_RUNTIME_POSTGRES has no usable host.',
279
+ );
280
+ }
281
+ return authority
282
+ .split(',')
283
+ .map((hostPort) =>
284
+ egressHostname(
285
+ hostPort.startsWith('[')
286
+ ? hostPort.slice(0, hostPort.indexOf(']') + 1)
287
+ : hostPort.replace(/:\d+$/u, ''),
288
+ 'WORKFLOW_RUNTIME_POSTGRES',
289
+ ),
290
+ );
291
+ }
292
+
293
+ /**
294
+ * The app origins this worker trusts with its internal service token: the
295
+ * JWKS origin (or `DEEPLINE_HOST_URL`, as for the sidecar) and any additional
296
+ * JWKS origins, the same set the gateway accepts executor tokens from.
297
+ * Canonical `URL.origin` strings; an unparseable entry is skipped.
298
+ */
299
+ export function modalSupervisorTrustedAppOrigins(
300
+ env: Readonly<Record<string, string | undefined>>,
301
+ ): string[] {
302
+ const read = (name: string) => env[name]?.trim() || undefined;
303
+ const origins = new Set<string>();
304
+ for (const value of [
305
+ read('DEEPLINE_RUNTIME_JWKS_ORIGIN') ?? read('DEEPLINE_HOST_URL'),
306
+ ...(read('DEEPLINE_RUNTIME_ADDITIONAL_JWKS_ORIGINS') ?? '').split(','),
307
+ ]) {
308
+ if (!value?.trim()) continue;
309
+ try {
310
+ const url = new URL(value.trim());
311
+ if (url.protocol === 'https:') origins.add(url.origin);
312
+ } catch {
313
+ // Not an origin; never trusted.
314
+ }
315
+ }
316
+ return [...origins];
317
+ }
318
+
319
+ /**
320
+ * The supervisor's environment, derived from the worker's. The JWKS origin is
321
+ * the app origin the worker already calls (`DEEPLINE_HOST_URL`) unless the
322
+ * worker carries an explicit one. Throws when a value the gateway requires at
323
+ * startup is missing, so a misconfigured worker fails before any sandbox work.
324
+ */
325
+ export function modalSupervisorEnvironment(input: {
326
+ env: Readonly<Record<string, string | undefined>>;
327
+ runtimeSchedulerSchema: string | null | undefined;
328
+ }): ModalSupervisorEnvironment {
329
+ const read = (name: string) => input.env[name]?.trim() || undefined;
330
+ const jwksOrigin =
331
+ read('DEEPLINE_RUNTIME_JWKS_ORIGIN') ?? read('DEEPLINE_HOST_URL');
332
+ const schema =
333
+ input.runtimeSchedulerSchema?.trim() ||
334
+ read('DEEPLINE_RUNTIME_SCHEDULER_SCHEMA');
335
+ const missing = [
336
+ ...(jwksOrigin ? [] : ['DEEPLINE_RUNTIME_JWKS_ORIGIN or DEEPLINE_HOST_URL']),
337
+ ...(schema ? [] : ['DEEPLINE_RUNTIME_SCHEDULER_SCHEMA']),
338
+ ...(read('WORKFLOW_RUNTIME_POSTGRES') ? [] : ['WORKFLOW_RUNTIME_POSTGRES']),
339
+ ];
340
+ if (missing.length > 0) {
341
+ throw new Error(
342
+ `RUNTIME_MODAL_SUPERVISOR_CONFIG_MISSING: ${missing.join(', ')}.`,
343
+ );
344
+ }
345
+ const env: Record<string, string> = {
346
+ NODE_ENV: 'production',
347
+ DEEPLINE_RUNTIME_JWKS_ORIGIN: jwksOrigin!.replace(/\/+$/u, ''),
348
+ DEEPLINE_RUNTIME_SCHEDULER_SCHEMA: schema!,
349
+ // One runner per sandbox: the Fly relay runs with one client per process.
350
+ DEEPLINE_RUNTIME_GATEWAY_POOL_MAX_CLIENTS: '2',
351
+ [MODAL_SUPERVISOR_GATEWAY_ENV]: '1',
352
+ };
353
+ for (const name of [
354
+ 'DEEPLINE_RUNTIME_ADDITIONAL_JWKS_ORIGINS',
355
+ 'DEEPLINE_ENV',
356
+ 'DEEPLINE_TEST_RUNTIME_SEAMS',
357
+ ]) {
358
+ const value = read(name);
359
+ if (value) env[name] = value;
360
+ }
361
+ const secretEnv: Record<string, string> = {};
362
+ for (const name of SUPERVISOR_SECRET_ENV) {
363
+ const value = read(name);
364
+ if (value) secretEnv[name] = value;
365
+ }
366
+ const egressDomains = new Set<string>([
367
+ egressHostname(new URL(env.DEEPLINE_RUNTIME_JWKS_ORIGIN!).hostname, 'the JWKS origin'),
368
+ ...postgresEgressHostnames(read('WORKFLOW_RUNTIME_POSTGRES')!),
369
+ ]);
370
+ for (const origin of (read('DEEPLINE_RUNTIME_ADDITIONAL_JWKS_ORIGINS') ?? '')
371
+ .split(',')
372
+ .map((value) => value.trim())
373
+ .filter(Boolean)) {
374
+ egressDomains.add(
375
+ egressHostname(
376
+ new URL(origin).hostname,
377
+ 'DEEPLINE_RUNTIME_ADDITIONAL_JWKS_ORIGINS',
378
+ ),
379
+ );
380
+ }
381
+ const r2Endpoint = read('CLOUDFLARE_R2_ENDPOINT');
382
+ if (r2Endpoint) {
383
+ const r2Host = egressHostname(
384
+ new URL(r2Endpoint).hostname,
385
+ 'CLOUDFLARE_R2_ENDPOINT',
386
+ );
387
+ egressDomains.add(r2Host);
388
+ // The S3 client addresses objects virtual-hosted: <bucket>.<endpoint>.
389
+ const bucket = read('CLOUDFLARE_R2_BUCKET_NAME');
390
+ if (bucket)
391
+ egressDomains.add(egressHostname(`${bucket}.${r2Host}`, 'the R2 bucket'));
392
+ }
393
+ return { env, secretEnv, egressDomains: [...egressDomains].sort() };
394
+ }
395
+
396
+ /**
397
+ * The sidecar's one process: both gateway roles with inherited output (the
398
+ * sidecar's log is the gateways' structured telemetry, readable from Modal by
399
+ * sandbox id). It exits as soon as either gateway exits, so a dead supervisor
400
+ * is never half alive and the runner sees refused connections.
401
+ */
402
+ const SUPERVISOR_LAUNCH_SOURCE = `
403
+ console.error('DEEPLINE_SUPERVISOR_LAUNCHER_START ' + Date.now());
404
+ const root = ${JSON.stringify(MODAL_SUPERVISOR_ROOT)};
405
+ const roles = [
406
+ { file: 'gateway.js', role: 'receipt', port: ${MODAL_SUPERVISOR_RECEIPT_PORT}, metrics: 8789 },
407
+ { file: 'relay.js', role: 'execution', port: ${MODAL_SUPERVISOR_EXECUTION_PORT}, metrics: 8790 },
408
+ ];
409
+ // Diagnostics only (stderr, never on the request path): TCP retransmits of
410
+ // this network namespace at start and every 5 s; per role, the Bun process
411
+ // start (a preload that runs before the bundle is evaluated), so the split
412
+ // spawn -> process start -> first gateway log -> listen is readable.
413
+ const tcp = () => { try { const l = require('fs').readFileSync('/proc/net/snmp', 'utf8').split('\\n').filter((x) => x.startsWith('Tcp:')); const k = l[0].split(' '), v = l[1].split(' '); return { outSegs: +v[k.indexOf('OutSegs')], retransSegs: +v[k.indexOf('RetransSegs')] }; } catch { return null; } };
414
+ const reportTcp = () => console.error('DEEPLINE_SUPERVISOR_TCP ' + JSON.stringify({ at: Date.now(), ...tcp() }));
415
+ reportTcp(); setInterval(reportTcp, 5000);
416
+ const preload = '/tmp/deepline-supervisor-process-start.js';
417
+ require('fs').writeFileSync(preload, "console.error('DEEPLINE_SUPERVISOR_PROCESS_START ' + process.env.DEEPLINE_RUNTIME_GATEWAY_ROLE + ' ' + Date.now());");
418
+ for (const r of roles) {
419
+ console.error('DEEPLINE_SUPERVISOR_SPAWN ' + r.role + ' ' + Date.now());
420
+ const child = Bun.spawn(['bun', '--preload', preload, root + '/' + r.file], {
421
+ env: { ...process.env, PORT: String(r.port), GATEWAY_METRICS_PORT: String(r.metrics), DEEPLINE_RUNTIME_GATEWAY_ROLE: r.role },
422
+ stdout: 'inherit', stderr: 'inherit',
423
+ });
424
+ child.exited.then((code) => { console.error('DEEPLINE_SUPERVISOR_EXITED ' + r.role + ' ' + code); process.exit(1); });
425
+ }
426
+ `;
427
+
428
+ export function modalSupervisorCommand(): string[] {
429
+ return ['bun', '-e', SUPERVISOR_LAUNCH_SOURCE];
430
+ }
431
+
432
+ /**
433
+ * Run inside the sidecar by the worker: prints the ready marker and exits 0
434
+ * once each gateway port accepts a request (any HTTP status proves the
435
+ * listener), or exits 1 at its deadline.
436
+ */
437
+ const SUPERVISOR_READY_PROBE_SOURCE = `
438
+ const ports = [${MODAL_SUPERVISOR_RECEIPT_PORT}, ${MODAL_SUPERVISOR_EXECUTION_PORT}];
439
+ const deadline = Date.now() + 25000;
440
+ for (const port of ports) {
441
+ for (;;) {
442
+ try { await fetch('http://127.0.0.1:' + port + '/healthz', { signal: AbortSignal.timeout(1000) }); break; }
443
+ catch { if (Date.now() > deadline) { console.log('DEEPLINE_SUPERVISOR_NOT_READY ' + port); process.exit(1); } await Bun.sleep(10); }
444
+ }
445
+ }
446
+ console.log(${JSON.stringify(MODAL_SUPERVISOR_READY_MARKER)});
447
+ `;
448
+
449
+ export function modalSupervisorReadyProbeCommand(): string[] {
450
+ return ['bun', '-e', SUPERVISOR_READY_PROBE_SOURCE];
451
+ }
452
+
453
+ /**
454
+ * The run a sidecar serves. The sidecar's gateway holds credentials for every
455
+ * org, so it accepts only executor tokens for this run and org. The trusted
456
+ * side sets it: in the sidecar's plain env at create (ordinary launch), or,
457
+ * for an early sidecar started before its run was known (S1), as a file the
458
+ * worker writes by exec into the sidecar after adoption. Until a pin exists,
459
+ * the gateway refuses every executor token. `attempt` is diagnostic: the
460
+ * executor token is minted once per launch and reused across attempts, and
461
+ * attempt fencing is the gateway's existing lease-token authority.
462
+ */
463
+ export type ModalSupervisorRunPin = {
464
+ runId: string;
465
+ orgId: string;
466
+ attempt: string;
467
+ };
468
+ export const MODAL_SUPERVISOR_RUN_PIN_ENV = 'DEEPLINE_RUNTIME_GATEWAY_RUN_PIN';
469
+ export const MODAL_SUPERVISOR_RUN_PIN_PATH =
470
+ '/tmp/deepline-supervisor/run-pin.json';
471
+
472
+ export function modalSupervisorRunPin(context: {
473
+ runId?: string | null;
474
+ orgId?: string | null;
475
+ runAttempt?: number | null;
476
+ }): ModalSupervisorRunPin {
477
+ const runId = context.runId?.trim();
478
+ const orgId = context.orgId?.trim();
479
+ if (!runId || !orgId) {
480
+ throw new Error(
481
+ 'RUNTIME_MODAL_SUPERVISOR_FAILED: a sidecar needs the run and org it is pinned to.',
482
+ );
483
+ }
484
+ return { runId, orgId, attempt: String(context.runAttempt ?? 0) };
485
+ }
486
+
487
+ export function parseModalSupervisorRunPin(
488
+ text: string | null | undefined,
489
+ ): ModalSupervisorRunPin | null {
490
+ if (!text?.trim()) return null;
491
+ try {
492
+ const value = JSON.parse(text) as Record<string, unknown>;
493
+ const field = (name: string) =>
494
+ typeof value[name] === 'string' && value[name].trim()
495
+ ? value[name].trim()
496
+ : null;
497
+ const runId = field('runId');
498
+ const orgId = field('orgId');
499
+ const attempt = field('attempt');
500
+ return runId && orgId && attempt ? { runId, orgId, attempt } : null;
501
+ } catch {
502
+ return null;
503
+ }
504
+ }
505
+
506
+ /**
507
+ * Exec'd in the sidecar by the worker: writes the pin once, atomically
508
+ * (temp file, then an exclusive hard link). Exit 0 when the pin is written or
509
+ * already identical; exit 3 when a different pin is already there, which
510
+ * never changes.
511
+ */
512
+ export function modalSupervisorRunPinCommand(
513
+ pin: ModalSupervisorRunPin,
514
+ path: string = MODAL_SUPERVISOR_RUN_PIN_PATH,
515
+ ): string[] {
516
+ const source = `
517
+ const fs = require('fs');
518
+ const path = ${JSON.stringify(path)};
519
+ const want = ${JSON.stringify(JSON.stringify(pin))};
520
+ fs.mkdirSync(require('path').dirname(path), { recursive: true, mode: 0o700 });
521
+ const tmp = path + '.' + process.pid + '.tmp';
522
+ fs.writeFileSync(tmp, want, { mode: 0o444 });
523
+ try { fs.linkSync(tmp, path); }
524
+ catch (error) {
525
+ if (error.code !== 'EEXIST') throw error;
526
+ if (fs.readFileSync(path, 'utf8') !== want) { console.log('DEEPLINE_SUPERVISOR_PIN_CONFLICT'); process.exit(3); }
527
+ } finally { fs.rmSync(tmp, { force: true }); }
528
+ console.log('DEEPLINE_SUPERVISOR_PINNED');
529
+ `;
530
+ return ['bun', '-e', source];
531
+ }
532
+
533
+ /**
534
+ * The runner's view under the profile: both gateway origins are the sidecar,
535
+ * and ctx.fetch goes through the gateway to the existing egress broker
536
+ * because the main container has no outbound network.
537
+ */
538
+ export function modalSupervisorRunnerContext<
539
+ T extends {
540
+ receiptGatewayBaseUrl?: string | null;
541
+ executionGatewayBaseUrl?: string | null;
542
+ egressViaRuntimeBroker?: boolean;
543
+ awaitRuntimeSupervisor?: boolean;
544
+ runtimeSupervisorProbeTimeoutMs?: number;
545
+ },
546
+ >(context: T): T {
547
+ return {
548
+ ...context,
549
+ receiptGatewayBaseUrl: `http://${MODAL_SUPERVISOR_SIDECAR_NAME}:${MODAL_SUPERVISOR_RECEIPT_PORT}`,
550
+ executionGatewayBaseUrl: `http://${MODAL_SUPERVISOR_SIDECAR_NAME}:${MODAL_SUPERVISOR_EXECUTION_PORT}`,
551
+ egressViaRuntimeBroker: true,
552
+ awaitRuntimeSupervisor: true,
553
+ runtimeSupervisorProbeTimeoutMs:
554
+ modalSupervisorLaunchOptions.readinessProbeTimeoutMs ?? 100,
555
+ };
556
+ }
@@ -24,6 +24,7 @@ import type { PlayRunFailureDetails } from './run-failure';
24
24
  import type { ToolExecutionErrorSchemaVersion } from '../plays/tool-execution-error';
25
25
  import type { ToolResponseContract } from '../plays/tool-response-contract';
26
26
  import type { FixtureBehavior } from './fixture-behavior';
27
+ import type { ExperimentSwitchOverrides } from './experiment-switches';
27
28
  import type { CtxFetchHttpFailureDiagnostic } from './log-provenance';
28
29
 
29
30
  import type { PrebuiltResultQuality } from './prebuilt-result-quality';
@@ -253,6 +254,20 @@ export interface PlayRunnerContextConfig extends RetainedPipelineCarrier {
253
254
  */
254
255
  executionGatewayBaseUrl?: string | null;
255
256
  receiptGatewayBaseUrl?: string | null;
257
+ /**
258
+ * The runner has no outbound network (`modal_sidecar`): ctx.fetch goes to
259
+ * the execution gateway's egress-fetch path and the existing broker. Absent
260
+ * keeps direct guarded egress.
261
+ */
262
+ egressViaRuntimeBroker?: boolean;
263
+ /**
264
+ * The gateways are a supervisor sidecar starting beside the runner
265
+ * (`modal_sidecar`): the first heartbeat waits until they listen. Absent
266
+ * starts heartbeats immediately.
267
+ */
268
+ awaitRuntimeSupervisor?: boolean;
269
+ /** Probe attempt timeout while waiting for the supervisor (default 100 ms). */
270
+ runtimeSupervisorProbeTimeoutMs?: number;
256
271
  /**
257
272
  * Internal fixture-canary pin for a cordoned receipt-gateway candidate. This
258
273
  * is a signed launch fact, never a customer-authored or sandbox-supplied
@@ -271,6 +286,11 @@ export interface PlayRunnerContextConfig extends RetainedPipelineCarrier {
271
286
  */
272
287
  durableInvocationFence?: boolean;
273
288
  runtimeTestFaultHeader?: string | null;
289
+ /**
290
+ * EXPERIMENT: the launch's per-run switch overrides, read by the worker's
291
+ * runner backend (B, H1, E2 adoption). Absent: static defaults.
292
+ */
293
+ experimentSwitchOverrides?: ExperimentSwitchOverrides | null;
274
294
  vercelProtectionBypassToken?: string | null;
275
295
  integrationMode?: 'live' | 'eval_stub' | 'fixture';
276
296
  /**
@@ -313,6 +333,12 @@ export interface PlayRunnerContextConfig extends RetainedPipelineCarrier {
313
333
  | null;
314
334
  convexUrl?: string;
315
335
  staticPipeline?: PlayStaticPipeline | null;
336
+ /**
337
+ * Optional: tool ids from the launch's static plan, for the read-only startup
338
+ * prefetch during the park fence (`runnerStartupReadPrefetch`). Absent: the
339
+ * runner derives them from `staticPipeline` as before (skipped when absent).
340
+ */
341
+ startupReadToolIds?: string[] | null;
316
342
  force?: boolean | null;
317
343
  forceToolRefresh?: boolean | null;
318
344
  /**
@@ -409,6 +435,7 @@ export type PlayRunnerEvent =
409
435
  attempt: number;
410
436
  invocationSeq: number;
411
437
  segmentId: string;
438
+ reusableResultCalls?: number;
412
439
  logicalCalls: number;
413
440
  providerRequests: number;
414
441
  provider429s: number;
@@ -6,6 +6,7 @@ import type {
6
6
  import type {
7
7
  PlayExecutionGovernor,
8
8
  ProviderPermit,
9
+ SpeculativeBudgetCharge,
9
10
  WorkLease,
10
11
  } from './governor/governor';
11
12
  import type {
@@ -904,6 +905,12 @@ export interface RuntimeResourceGovernor {
904
905
  providerResourceKey?: string | null;
905
906
  }): RuntimeResourceLease | null;
906
907
  chargeToolCall(): Promise<void>;
908
+ /**
909
+ * Charge the logical call from budget already reserved here, without
910
+ * waiting; null when only `chargeToolCall` can decide. `refund` returns an
911
+ * undispatched charge exactly.
912
+ */
913
+ tryChargeToolCall(): SpeculativeBudgetCharge | null;
907
914
  acquireProviderPermit(input: {
908
915
  toolId: string;
909
916
  signal?: AbortSignal;
@@ -943,6 +950,11 @@ export interface RuntimeResourceGovernor {
943
950
  recordProvider429(): void;
944
951
  /** Count one admitted ctx.tools.execute invocation, including a later failure. */
945
952
  recordLogicalToolCall(): void;
953
+ /**
954
+ * Uncount a speculative invocation that never dispatched and is retried as
955
+ * the same logical call (read-through fallback).
956
+ */
957
+ forgetLogicalToolCall(): void;
946
958
  /**
947
959
  * Probe app transport capacity at the physical provider-dispatch edge. A
948
960
  * caller that misses it must cancel and re-admit its provider ticket.
@@ -1956,6 +1968,9 @@ export function createRuntimeResourceGovernor(input: {
1956
1968
 
1957
1969
  chargeToolCall: () => input.executionGovernor.chargeBudget('toolCall'),
1958
1970
 
1971
+ tryChargeToolCall: () =>
1972
+ input.executionGovernor.tryChargeBudget?.('toolCall') ?? null,
1973
+
1959
1974
  async acquireProviderPermit(providerInput) {
1960
1975
  const startedAt = Date.now();
1961
1976
  const lease = await input.executionGovernor.acquireProviderPermit(
@@ -2032,6 +2047,10 @@ export function createRuntimeResourceGovernor(input: {
2032
2047
  workCounters.logicalCalls += 1;
2033
2048
  },
2034
2049
 
2050
+ forgetLogicalToolCall() {
2051
+ workCounters.logicalCalls = Math.max(0, workCounters.logicalCalls - 1);
2052
+ },
2053
+
2035
2054
  tryAcquireIntegrationRequestSlot() {
2036
2055
  return input.executionGovernor.tryAcquireIntegrationRequestSlot();
2037
2056
  },