deepline 0.3.499 → 0.3.501

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 (178) hide show
  1. package/dist/bundling-sources/sdk/src/plays/client-core.ts +45 -7
  2. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  3. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +36 -0
  4. package/dist/bundling-sources/shared_libs/play-data-plane/r2.ts +155 -0
  5. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +7 -1
  6. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +2 -1
  7. package/dist/bundling-sources/shared_libs/play-runtime/durable-invocation-fence.ts +3 -1
  8. package/dist/bundling-sources/shared_libs/play-runtime/internal-bootstrap-token.ts +54 -1
  9. package/dist/bundling-sources/shared_libs/play-runtime/launch-identity.ts +12 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +13 -0
  11. package/dist/bundling-sources/shared_libs/play-runtime/run-identity.ts +56 -0
  12. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +21 -10
  13. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-heartbeat.ts +1 -1
  14. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-progress-push.ts +1 -2
  15. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-terminal-push.ts +1 -1
  16. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-launch-transport.ts +9 -2
  17. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-lifecycle.ts +31 -1
  18. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-payload-transport.ts +74 -3
  19. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-runtime-watchdog.ts +226 -2
  20. package/dist/bundling-sources/shared_libs/play-runtime/runtime-api-paths.ts +41 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/runtime-api.ts +5 -1
  22. package/dist/bundling-sources/shared_libs/play-runtime/runtime-app-transport.ts +374 -0
  23. package/dist/bundling-sources/shared_libs/play-runtime/runtime-authority.ts +5 -0
  24. package/dist/bundling-sources/shared_libs/play-runtime/runtime-environment.ts +49 -9
  25. package/dist/bundling-sources/shared_libs/play-runtime/runtime-gateway-oidc.ts +25 -3
  26. package/dist/bundling-sources/shared_libs/play-runtime/runtime-gateway-profile.ts +12 -1
  27. package/dist/bundling-sources/shared_libs/play-runtime/runtime-gateway-sandbox-credential.ts +338 -0
  28. package/dist/bundling-sources/shared_libs/play-runtime/runtime-gateway-staging.ts +417 -0
  29. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +15 -0
  30. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +184 -11
  31. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-shared.ts +17 -3
  32. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/gateway-progress-registry.ts +9 -0
  33. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +18 -2
  34. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +176 -16
  35. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-gateway-attempt.ts +81 -0
  36. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-gateway-staging-journal.ts +708 -0
  37. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-gateway-staging-teardown.ts +160 -0
  38. package/dist/bundling-sources/shared_libs/play-runtime/workflow-executor-auth.ts +4 -0
  39. package/dist/cli/{auth-TECJ27G3.mjs → auth-6ECHXOI4.mjs} +5 -5
  40. package/dist/cli/auth-VP7PMXKQ.js +43 -0
  41. package/dist/cli/{billing-PMKO73VG.mjs → billing-75NZYRXA.mjs} +8 -8
  42. package/dist/cli/{billing-ULZGAED6.js → billing-QRR7O6BD.js} +81 -81
  43. package/dist/cli/{chunk-K54BUQSK.js → chunk-463ZOO2L.js} +7 -7
  44. package/dist/cli/{chunk-L6C7C7IJ.js → chunk-4OXHLTCP.js} +1 -1
  45. package/dist/cli/{chunk-3GP52OHV.mjs → chunk-5S7MLAI7.mjs} +11 -11
  46. package/dist/cli/{chunk-7OQZZHZ4.js → chunk-5X4AUFYW.js} +7 -7
  47. package/dist/cli/{chunk-56JE475N.mjs → chunk-66XDYH5T.mjs} +2 -2
  48. package/dist/cli/{chunk-A2VCFBZN.mjs → chunk-7L6QNHUL.mjs} +1 -1
  49. package/dist/cli/{chunk-UOQUCFAK.js → chunk-APAHMCGR.js} +53 -53
  50. package/dist/cli/{chunk-UBKA33KY.mjs → chunk-BMCRTI6Z.mjs} +22 -1
  51. package/dist/cli/{chunk-WSOM3TY6.js → chunk-BOFCF4L7.js} +3 -3
  52. package/dist/cli/{chunk-SLWCXGKP.js → chunk-CJJ7JBM2.js} +16 -16
  53. package/dist/cli/{chunk-JM52ATUS.mjs → chunk-EHVFBD36.mjs} +1 -1
  54. package/dist/cli/{chunk-7WUMIRBV.js → chunk-EKF4DKUA.js} +5 -5
  55. package/dist/cli/{chunk-AGZRRHSB.js → chunk-EKZQ5LQO.js} +3 -3
  56. package/dist/cli/{chunk-5IDORX4E.mjs → chunk-EOO7OSS4.mjs} +4 -4
  57. package/dist/cli/{chunk-2PKZ3RUU.js → chunk-FS7XYDOF.js} +16 -16
  58. package/dist/cli/{chunk-Z2MO7FZG.js → chunk-HDKXSHGA.js} +53 -53
  59. package/dist/cli/{chunk-YRQWGWRJ.js → chunk-J6SVNKRP.js} +2 -2
  60. package/dist/cli/{chunk-QXI2W7YY.mjs → chunk-J74N375S.mjs} +4 -4
  61. package/dist/cli/{chunk-KLQ5CR77.js → chunk-KTOAJP4N.js} +6 -6
  62. package/dist/cli/{chunk-ZVAD65CF.mjs → chunk-MADTHS56.mjs} +1 -1
  63. package/dist/cli/{chunk-UMPCQ4EE.mjs → chunk-MSLXAVVK.mjs} +2 -2
  64. package/dist/cli/{chunk-JIZHGOZ5.js → chunk-N2TJJNCW.js} +96 -96
  65. package/dist/cli/{chunk-CS2AEAD6.mjs → chunk-N4TR6QRI.mjs} +1 -1
  66. package/dist/cli/{chunk-43ZERPGR.mjs → chunk-NA3J3F2Z.mjs} +1 -1
  67. package/dist/cli/{chunk-JQHJKARU.mjs → chunk-O3DDVP7Z.mjs} +1 -1
  68. package/dist/cli/{chunk-JUQESEJX.mjs → chunk-OKOXB3LY.mjs} +2 -2
  69. package/dist/cli/{chunk-FG5OZ5FB.js → chunk-PNF2ZU4R.js} +8 -8
  70. package/dist/cli/{chunk-KZJKRU24.mjs → chunk-PXIF74UJ.mjs} +4 -4
  71. package/dist/cli/{chunk-TUDYBF4Y.js → chunk-QQ3JJYE2.js} +14 -14
  72. package/dist/cli/{chunk-IGCSKXGK.mjs → chunk-RFV7PPLS.mjs} +3 -3
  73. package/dist/cli/{chunk-EQR5O2D2.js → chunk-RNSHCJME.js} +3 -3
  74. package/dist/cli/{chunk-PE3UHMMZ.js → chunk-RU5ROUFO.js} +5 -5
  75. package/dist/cli/{chunk-2RZHMCDL.js → chunk-SV2TEZ2M.js} +4 -4
  76. package/dist/cli/{chunk-P3MGNLZF.mjs → chunk-T4U245E4.mjs} +2 -2
  77. package/dist/cli/{chunk-7UC2UZYW.mjs → chunk-T7E3XEPG.mjs} +6 -6
  78. package/dist/cli/{chunk-LUNXREUI.js → chunk-TOE7LHEA.js} +6 -6
  79. package/dist/cli/{chunk-OWHQ4OG5.mjs → chunk-UJRN6YP6.mjs} +3 -3
  80. package/dist/cli/{chunk-XSUQAUG4.js → chunk-UR7JOSLT.js} +360 -300
  81. package/dist/cli/{chunk-KOD45UP5.mjs → chunk-V5NHEYU7.mjs} +5 -5
  82. package/dist/cli/{chunk-PSYGSXDS.mjs → chunk-VD2374K7.mjs} +1 -1
  83. package/dist/cli/{chunk-57LW4TGY.js → chunk-VL72UKNW.js} +26 -26
  84. package/dist/cli/{chunk-YAW7ET4P.mjs → chunk-VTDAJZIJ.mjs} +90 -30
  85. package/dist/cli/{chunk-AKLI4XSG.js → chunk-VVEMPC2I.js} +2 -2
  86. package/dist/cli/{chunk-L7O7AFSF.js → chunk-W6JTHVPF.js} +21 -21
  87. package/dist/cli/{chunk-MQ5YPD7K.mjs → chunk-WJUDAHIQ.mjs} +1 -1
  88. package/dist/cli/{chunk-XDVT3GOM.js → chunk-WSGXBROE.js} +22 -1
  89. package/dist/cli/{chunk-G7BB2VOC.js → chunk-XEBFJ2PH.js} +41 -41
  90. package/dist/cli/{chunk-WEVIUQGZ.mjs → chunk-Z6AUOV7D.mjs} +2 -2
  91. package/dist/cli/{chunk-BBFWIYAF.mjs → chunk-ZUOKIBLJ.mjs} +2 -2
  92. package/dist/cli/{chunk-C2V5U6HO.mjs → chunk-ZUQHQGC5.mjs} +5 -5
  93. package/dist/cli/{csv-VGSQ3JYE.js → csv-JXX2LXK5.js} +13 -13
  94. package/dist/cli/{csv-ACO5YC46.mjs → csv-RZJ4SOIL.mjs} +4 -4
  95. package/dist/cli/{db-CXNZOXGM.mjs → db-MUTT2NWI.mjs} +8 -8
  96. package/dist/cli/{db-QOUPHFFN.js → db-T2KJNONM.js} +29 -29
  97. package/dist/cli/{describe-J4O5GCJS.mjs → describe-K3UMAAVO.mjs} +19 -19
  98. package/dist/cli/describe-SEXUJLE4.js +50 -0
  99. package/dist/cli/describe-core.d.mts +2 -2
  100. package/dist/cli/describe-core.d.ts +2 -2
  101. package/dist/cli/{executions-YIECH2CL.js → executions-7HSLDRHR.js} +10 -10
  102. package/dist/cli/{executions-SJETRLXW.mjs → executions-PHS4R2OX.mjs} +8 -8
  103. package/dist/cli/{feedback-5BRCNERV.js → feedback-BJZRM637.js} +8 -8
  104. package/dist/cli/{feedback-GSAFFMF6.mjs → feedback-RWMDCIDF.mjs} +4 -4
  105. package/dist/cli/git-VNS7UQWN.js +25 -0
  106. package/dist/cli/{git-SF5XIGLU.mjs → git-YW6VHYZG.mjs} +5 -5
  107. package/dist/cli/index.js +137 -137
  108. package/dist/cli/index.mjs +40 -40
  109. package/dist/cli/{legacy-noops-5TBT4XC6.js → legacy-noops-2WUV2XD7.js} +8 -8
  110. package/dist/cli/{legacy-noops-TZA3CALE.mjs → legacy-noops-5UBSUPGG.mjs} +5 -5
  111. package/dist/cli/{monitors-XAYWJNSV.mjs → monitors-HWOQO3OK.mjs} +9 -9
  112. package/dist/cli/{monitors-XNB5YNC3.js → monitors-YZZRKSTG.js} +97 -97
  113. package/dist/cli/{org-2UYWJXG7.js → org-JY7HLHBA.js} +74 -74
  114. package/dist/cli/{org-S5VZL5KZ.mjs → org-NCXT6RB4.mjs} +8 -8
  115. package/dist/cli/{pages-ZQRRTZIT.js → pages-6ZOHXL6X.js} +20 -20
  116. package/dist/cli/{pages-NGVJO7PA.mjs → pages-QJO53QAT.mjs} +8 -8
  117. package/dist/cli/{play-3JNERHSC.mjs → play-SQRS7JN3.mjs} +20 -20
  118. package/dist/cli/{play-P3OYQ7JV.js → play-TAYGSR35.js} +336 -336
  119. package/dist/cli/{providers-27O6BOAP.mjs → providers-3IR3N5DT.mjs} +8 -8
  120. package/dist/cli/{providers-2FFGAPUR.js → providers-4Q5LOIQ5.js} +11 -11
  121. package/dist/cli/{quickstart-5G2UPKJV.js → quickstart-ITNUZENY.js} +6 -6
  122. package/dist/cli/{quickstart-B2EXIAU6.mjs → quickstart-KCZCYO6B.mjs} +4 -4
  123. package/dist/cli/{run-3QFXYV3Z.mjs → run-JCWRWDSK.mjs} +24 -24
  124. package/dist/cli/{run-2TGD7FAL.js → run-YQ57LMKN.js} +42 -42
  125. package/dist/cli/run-identity-HFYABUJS.js +31 -0
  126. package/dist/cli/{run-identity-MRNCEGV2.mjs → run-identity-MNRZS2N3.mjs} +9 -3
  127. package/dist/cli/{search-GXEEOMVD.mjs → search-FUM27HQP.mjs} +9 -9
  128. package/dist/cli/search-I425FRTK.js +32 -0
  129. package/dist/cli/{search-output-DMIJQTAA.mjs → search-output-EWEYT34M.mjs} +4 -4
  130. package/dist/cli/{search-output-I4RZPHU6.js → search-output-XAMWKRJH.js} +6 -6
  131. package/dist/cli/{secrets-MJMNRXZX.js → secrets-2IRRRZBL.js} +17 -17
  132. package/dist/cli/{secrets-DQI5YCS6.mjs → secrets-YTI4IAKR.mjs} +8 -8
  133. package/dist/cli/{sessions-HAUN3VYE.mjs → sessions-EFS4KUPF.mjs} +5 -5
  134. package/dist/cli/{sessions-QS74ZTRH.js → sessions-HWTRDXBQ.js} +6 -6
  135. package/dist/cli/{settings-VQBOS6VU.js → settings-FRVEIOKR.js} +80 -80
  136. package/dist/cli/{settings-E64HIUXW.mjs → settings-NTOO42DY.mjs} +13 -13
  137. package/dist/cli/{setup-KRW3JCJE.js → setup-6ZIOAE2V.js} +49 -49
  138. package/dist/cli/{setup-NRUG42F2.mjs → setup-PAVQPALX.mjs} +9 -9
  139. package/dist/cli/{skills-AHLZRTKZ.mjs → skills-3O3XTPUM.mjs} +7 -7
  140. package/dist/cli/skills-6ZNMO2PR.js +36 -0
  141. package/dist/cli/{tools-INRRIWOU.mjs → tools-7QSB65UL.mjs} +18 -18
  142. package/dist/cli/tools-DPV2JES6.js +57 -0
  143. package/dist/cli/update-Q5GUDEAW.js +34 -0
  144. package/dist/cli/{update-ETOWEJ7D.mjs → update-T6CYS5ZT.mjs} +9 -9
  145. package/dist/cli/{workflow-RUAYQK4D.js → workflow-4KMJBMGX.js} +19 -19
  146. package/dist/cli/{workflow-JT2DOSCJ.mjs → workflow-OMSXZ73T.mjs} +9 -9
  147. package/dist/{client-Cj3UqrCZ.d.ts → client-Bn8FwKGO.d.ts} +1 -1
  148. package/dist/{client-DSCTVVRj.d.mts → client-CfNRmjLK.d.mts} +1 -1
  149. package/dist/{client-core-dI4KTuWS.d.ts → client-core-B91EV0WS.d.ts} +19 -0
  150. package/dist/{client-core-B-8DTIN1.d.mts → client-core-BG8Cgrmk.d.mts} +19 -0
  151. package/dist/index.d.mts +3 -3
  152. package/dist/index.d.ts +3 -3
  153. package/dist/index.js +19 -19
  154. package/dist/index.mjs +8 -8
  155. package/dist/install-integrity.json +114 -108
  156. package/dist/plays/play-description.d.mts +1 -1
  157. package/dist/plays/play-description.d.ts +1 -1
  158. package/dist/plays/run-request.d.mts +1 -1
  159. package/dist/plays/run-request.d.ts +1 -1
  160. package/dist/plays/run-request.js +3 -3
  161. package/dist/plays/run-request.mjs +2 -2
  162. package/dist/release.d.mts +1 -1
  163. package/dist/release.d.ts +1 -1
  164. package/dist/release.js +2 -2
  165. package/dist/release.mjs +1 -1
  166. package/dist/server.d.mts +2 -2
  167. package/dist/server.d.ts +2 -2
  168. package/dist/server.js +7 -7
  169. package/dist/server.mjs +5 -5
  170. package/package.json +1 -1
  171. package/dist/cli/auth-32FRISRT.js +0 -43
  172. package/dist/cli/describe-DEXYQMBO.js +0 -50
  173. package/dist/cli/git-RDKLITUC.js +0 -25
  174. package/dist/cli/run-identity-G257GQED.js +0 -25
  175. package/dist/cli/search-YKTYDBCN.js +0 -32
  176. package/dist/cli/skills-PGVIJK6Q.js +0 -36
  177. package/dist/cli/tools-IXXN2RE4.js +0 -57
  178. package/dist/cli/update-QW4RV2UX.js +0 -34
@@ -1,3 +1,4 @@
1
+ import { runtimeToolPath } from '../runtime-api-paths';
1
2
  import {
2
3
  emptyRowFailureCounts,
3
4
  readRowFailureCounts,
@@ -9,6 +10,10 @@ import { appendFileSync, createReadStream, writeFileSync } from 'node:fs';
9
10
  import { readFile } from 'node:fs/promises';
10
11
  import { dirname, isAbsolute, resolve } from 'node:path';
11
12
  import { createRequire } from 'node:module';
13
+ import {
14
+ installSandboxRuntimeAppTransport,
15
+ sandboxRuntimeAppFetch,
16
+ } from '../runtime-app-transport';
12
17
  import { createHash, randomUUID } from 'node:crypto';
13
18
  import { formatWithOptions } from 'node:util';
14
19
  import { compileFunction } from 'node:vm';
@@ -215,21 +220,23 @@ export function createReceiptGatewayResponseObserver(): {
215
220
  };
216
221
  }
217
222
 
218
- async function safeNodeOutboundFetch(
223
+ // `safeOutboundFetch` sends with node:http, not the global fetch, so the
224
+ // pinned-run gateway credential is applied explicitly by the transport owner.
225
+ const safeNodeOutboundFetch = sandboxRuntimeAppFetch((async (
219
226
  input: string | URL,
220
227
  init?: RequestInit,
221
- ): Promise<Response> {
228
+ ): Promise<Response> => {
222
229
  const { safeOutboundFetch } = await loadSafeOutboundFetch();
223
230
  return safeOutboundFetch(input, init);
224
- }
231
+ }) as typeof fetch);
225
232
 
226
- async function safeNodeStreamingOutboundFetch(
233
+ const safeNodeStreamingOutboundFetch = sandboxRuntimeAppFetch((async (
227
234
  input: string | URL,
228
235
  init?: RequestInit,
229
- ): Promise<Response> {
236
+ ): Promise<Response> => {
230
237
  const { safeOutboundFetch } = await loadSafeOutboundFetch();
231
238
  return safeOutboundFetch(input, init, { streamResponseBody: true });
232
- }
239
+ }) as typeof fetch);
233
240
 
234
241
  import {
235
242
  resolveSheetContractForTableNamespace,
@@ -709,7 +716,7 @@ function createRuntimeToolMetadataResolver(config: PlayRunnerExecutionConfig) {
709
716
  }
710
717
 
711
718
  const promise = (async () => {
712
- const url = `${config.context.baseUrl}/api/v2/plays/runtime-tools/${encodeURIComponent(normalizedToolId)}`;
719
+ const url = `${config.context.baseUrl}${runtimeToolPath(normalizedToolId, 'metadata')}`;
713
720
  const response = await fetchRunnerRuntimeControl({
714
721
  url,
715
722
  description: `Runtime metadata lookup for tool ${normalizedToolId}`,
@@ -758,7 +765,7 @@ export function createAppRuntimeToolAuthScopeDigestResolver(
758
765
  `Runtime auth scope lookup for tool ${normalizedToolId || '<empty>'} requires executorToken and baseUrl.`,
759
766
  );
760
767
  }
761
- const url = `${config.context.baseUrl}/api/v2/plays/runtime-tools/${encodeURIComponent(normalizedToolId)}/auth-scope`;
768
+ const url = `${config.context.baseUrl}${runtimeToolPath(normalizedToolId, 'auth_scope')}`;
762
769
  const response = await fetchRunnerRuntimeControl({
763
770
  url,
764
771
  description: `Runtime auth scope lookup for tool ${normalizedToolId}`,
@@ -857,7 +864,7 @@ export function createAppRuntimeToolAuthScopeDigestResolver(
857
864
  if (!proof) {
858
865
  proof = (async () => {
859
866
  const response = await fetchRunnerRuntimeControl({
860
- url: `${executionBase}/api/v2/plays/runtime-tools/${encodeURIComponent(normalized)}/auth-scope`,
867
+ url: `${executionBase}${runtimeToolPath(normalized, 'auth_scope')}`,
861
868
  description: `Runtime async recovery capability for tool ${normalized}`,
862
869
  retrySafe: true,
863
870
  init: {
@@ -963,7 +970,7 @@ export function createRuntimeEventWaitHandler(
963
970
  boundary: IntegrationEventWaitBoundary;
964
971
  },
965
972
  ): Promise<IntegrationEventWaitBoundary> {
966
- const url = `${config.context.baseUrl}/api/v2/plays/runtime-tools/${encodeURIComponent(normalizedToolId)}/event-wait`;
973
+ const url = `${config.context.baseUrl}${runtimeToolPath(normalizedToolId, 'event_wait')}`;
967
974
  const response = await fetchRunnerRuntimeControl({
968
975
  url,
969
976
  description: `Event wait runtime call for tool ${normalizedToolId}`,
@@ -4125,6 +4132,10 @@ async function main() {
4125
4132
  ? gunzipSync(configBuffer).toString('utf-8')
4126
4133
  : configBuffer.toString('utf-8');
4127
4134
  const parsedConfig = JSON.parse(configJson) as PlayRunnerExecutionConfig;
4135
+ // Pinned runs only: code-owned requests to the pinned gateway origin and
4136
+ // paths carry the watchdog-renewed OIDC credential. Other targets, signed
4137
+ // object URLs included, are untouched. Unpinned configs install nothing.
4138
+ installSandboxRuntimeAppTransport(parsedConfig.context);
4128
4139
  writeRunnerStartupDiagnostic(
4129
4140
  process.env.DEEPLINE_PLAY_RUNNER_STARTUP_DIAGNOSTIC_PATH,
4130
4141
  { phase: 'booted' },
@@ -1,3 +1,4 @@
1
+ import { APP_RUNTIME_COMPAT_PATH } from '../runtime-api-paths';
1
2
  import { RUNTIME_CLAIM_HEARTBEAT_DIVISOR } from '../runtime-constants';
2
3
  import { PLAY_RUNTIME_TRANSPORT_ATTEMPT_HEADER } from '../runtime-contract';
3
4
  import {
@@ -106,7 +107,6 @@ export interface RunnerHeartbeatLoopHandle {
106
107
  lastSuccessAtMs: () => number;
107
108
  }
108
109
 
109
- const APP_RUNTIME_COMPAT_PATH = '/api/v2/plays/runtime';
110
110
  export const RUNNER_HEARTBEAT_REQUEST_TIMEOUT_MS = 10_000;
111
111
  // The detached startup deadline is shorter than the normal 40s cadence.
112
112
  // Retry initial transport failures while customer execution remains fenced.
@@ -1,3 +1,4 @@
1
+ import { APP_RUNTIME_COMPAT_PATH } from '../runtime-api-paths';
1
2
  import type { PlayRunnerEvent } from '../protocol';
2
3
  import { isDurableDirectRunnerLog } from '../log-provenance';
3
4
  import { jsonByteLengthUpTo } from '../output-size-limits';
@@ -28,8 +29,6 @@ export const RUNNER_PROGRESS_PUSH_MAX_BATCH = 500;
28
29
  */
29
30
  export const RUNNER_PROGRESS_PUSH_STOP_TIMEOUT_MS = 5_000;
30
31
 
31
- const APP_RUNTIME_COMPAT_PATH = '/api/v2/plays/runtime';
32
-
33
32
  export interface RunnerProgressPusher {
34
33
  snapshot: () => {
35
34
  retainedBytes: number;
@@ -1,3 +1,4 @@
1
+ import { APP_RUNTIME_COMPAT_PATH } from '../runtime-api-paths';
1
2
  import { readFileSync, writeFileSync } from 'node:fs';
2
3
  import {
3
4
  RUNNER_TERMINAL_CHECKPOINT_DISPOSITION,
@@ -45,7 +46,6 @@ const TERMINAL_PUSH_MAX_ATTEMPTS =
45
46
  const TERMINAL_PUSH_RETRY_DELAYS_MS = [500, 1_000, 2_000, 4_000] as const;
46
47
  const TERMINAL_PUSH_REQUEST_TIMEOUT_MS =
47
48
  RUNTIME_RELIABILITY_POLICY.gateway.terminalPushRequestTimeoutMs;
48
- const APP_RUNTIME_COMPAT_PATH = '/api/v2/plays/runtime';
49
49
 
50
50
  /**
51
51
  * A terminal result reserves its 5 MiB customer budget for the authored
@@ -21,7 +21,10 @@ import axios, { type InternalAxiosRequestConfig } from 'axios';
21
21
  import { Readable } from 'node:stream';
22
22
  import type { DaytonaClientOptions } from '../../daytona-runtime-config';
23
23
  import type { CreateSandboxFromSnapshotParams } from '@daytonaio/sdk';
24
- import type { DaytonaDeleteRetryAuthorization } from './daytona-lifecycle';
24
+ import type {
25
+ DaytonaDeleteRetryAuthorization,
26
+ DaytonaDomainAllowListParam,
27
+ } from './daytona-lifecycle';
25
28
  import {
26
29
  DAYTONA_CONTROL_TIMEOUT_MS,
27
30
  DaytonaControlTimeoutError,
@@ -558,7 +561,7 @@ export function createDaytonaLaunchClient(
558
561
  resolvedDomains.set(sandbox, organizationId.trim());
559
562
  },
560
563
  async create(
561
- params: CreateSandboxFromSnapshotParams,
564
+ params: CreateSandboxFromSnapshotParams & DaytonaDomainAllowListParam,
562
565
  options: { timeout?: number } = {},
563
566
  ) {
564
567
  const timeoutMs = (options.timeout ?? 60) * 1_000;
@@ -597,6 +600,10 @@ export function createDaytonaLaunchClient(
597
600
  volumes: params.volumes,
598
601
  networkBlockAll: params.networkBlockAll,
599
602
  networkAllowList: params.networkAllowList,
603
+ // Pinned Runtime gateway host only; absent on every other run.
604
+ ...(params.domainAllowList
605
+ ? { domainAllowList: params.domainAllowList }
606
+ : {}),
600
607
  linkedSandbox: params.linkedSandbox,
601
608
  },
602
609
  undefined,
@@ -84,7 +84,7 @@ export type DaytonaDeleteRetryAuthorization = {
84
84
 
85
85
  export type DaytonaClient = {
86
86
  create(
87
- params: CreateSandboxFromSnapshotParams,
87
+ params: CreateSandboxFromSnapshotParams & DaytonaDomainAllowListParam,
88
88
  options: { timeout: number },
89
89
  ): Promise<Sandbox>;
90
90
  get?(name: string): Promise<Sandbox>;
@@ -548,6 +548,31 @@ export function filterIpv4CidrAllowList(raw: string | null): string | null {
548
548
  return ipv4.length > 0 ? ipv4.join(',') : null;
549
549
  }
550
550
 
551
+ /** Daytona create accepts a comma-separated domain allow-list beside CIDRs. */
552
+ export type DaytonaDomainAllowListParam = { domainAllowList?: string };
553
+
554
+ /**
555
+ * A run pinned to an app-hosted Runtime gateway reaches that immutable
556
+ * deployment by hostname, whose addresses cannot be enumerated as CIDRs. When
557
+ * egress is already restricted to an allow-list, add exactly the pinned host;
558
+ * an unrestricted sandbox needs nothing (adding a domain list would restrict
559
+ * it). Unpinned runs return null.
560
+ */
561
+ export function runtimeGatewayDaytonaDomainAllowList(input: {
562
+ credentialScope:
563
+ | PlayRunnerExecutionConfig['context']['runtimeGatewayCredentialScope']
564
+ | undefined;
565
+ networkAllowList: string | null;
566
+ }): string | null {
567
+ const scope = input.credentialScope;
568
+ if (!scope || !input.networkAllowList) return null;
569
+ const hostname = new URL(scope.origin).hostname;
570
+ if (!hostname) {
571
+ throw new Error('Runtime gateway credential scope has no hostname.');
572
+ }
573
+ return hostname;
574
+ }
575
+
551
576
  export function resolveDaytonaSandboxNetworkPolicy(input: {
552
577
  runtimeSchedulerSchema: string | null | undefined;
553
578
  env?: NodeJS.ProcessEnv;
@@ -618,6 +643,10 @@ async function createOneShotDaytonaSandbox(input: {
618
643
  const { networkAllowList } = resolveDaytonaSandboxNetworkPolicy({
619
644
  runtimeSchedulerSchema: input.context.runtimeSchedulerSchema ?? null,
620
645
  });
646
+ const domainAllowList = runtimeGatewayDaytonaDomainAllowList({
647
+ credentialScope: input.context.runtimeGatewayCredentialScope,
648
+ networkAllowList,
649
+ });
621
650
 
622
651
  const commonParams = {
623
652
  name: input.sandboxName,
@@ -639,6 +668,7 @@ async function createOneShotDaytonaSandbox(input: {
639
668
  // the allow-list alone so the egress restriction holds without the
640
669
  // contradictory flag.
641
670
  ...(networkAllowList ? { networkAllowList } : {}),
671
+ ...(domainAllowList ? { domainAllowList } : {}),
642
672
  };
643
673
  return input.daytona.create(commonParams, {
644
674
  timeout: DAYTONA_CREATE_TIMEOUT_SECONDS,
@@ -1,3 +1,4 @@
1
+ import { APP_RUNTIME_COMPAT_PATH } from '../../runtime-api-paths';
1
2
  import { preparePlayRunnerConfigForTransport } from '../../protocol';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { readFile } from 'node:fs/promises';
@@ -35,6 +36,15 @@ import {
35
36
  } from '../../daytona-payload-contract';
36
37
  export { buildDaytonaPayloadMaterializerSource } from '../../daytona-payload-contract';
37
38
  import { compactPlayArtifactForRuntimeTransport } from '../../../plays/artifact-transport';
39
+ import {
40
+ RUNTIME_GATEWAY_OIDC_FILE_SUFFIX,
41
+ runtimeGatewayOidcRequestHeaders,
42
+ } from '../../runtime-gateway-sandbox-credential';
43
+ import {
44
+ runtimeGatewayStagedSend,
45
+ runtimeGatewayStagedSendTimeoutMs,
46
+ runtimeGatewayStagingClientLimits,
47
+ } from '../../runtime-gateway-staging';
38
48
  import type {
39
49
  DaytonaExecutionContext,
40
50
  DaytonaSandbox,
@@ -42,8 +52,10 @@ import type {
42
52
  } from './daytona-lifecycle';
43
53
  import {
44
54
  buildDaytonaRuntimeWatchdogSource,
55
+ runtimeGatewayCredentialWatchdogArgs,
45
56
  PLAY_RUNNER_UV_THREADPOOL_SIZE,
46
57
  RUNNER_MEMORY_CGROUP_ROOT,
58
+ RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON,
47
59
  RUNTIME_SANDBOX_MEMORY_ABORT_REASON,
48
60
  } from './daytona-runtime-watchdog';
49
61
 
@@ -199,6 +211,37 @@ const memoryEventsPath = process.argv[7] || '/sys/fs/cgroup/memory.events';
199
211
  const terminationDiagnosticPath = process.argv[8] || '';
200
212
  const runtimeCompletedPath = process.argv[9] || '';
201
213
  const exitCode = Number.isFinite(exitCodeRaw) ? exitCodeRaw : null;
214
+ const runtimeGatewayOidcRequestHeaders = (${runtimeGatewayOidcRequestHeaders.toString()});
215
+ // Pinned runs only: an app-hosted gateway takes bodies above Vercel's cap
216
+ // through a staged upload. Unpinned runs call fetch exactly as before.
217
+ const runtimeGatewayStagedSend = (${runtimeGatewayStagedSend.toString()});
218
+ const runtimeGatewayStagedSendTimeoutMs = (${runtimeGatewayStagedSendTimeoutMs.toString()});
219
+
220
+ // Pinned runs only: the watchdog's latest renewed credential, else the
221
+ // initial one. Unpinned configs carry neither and send no credential.
222
+ function currentRuntimeGatewayOidcToken(context) {
223
+ if (!context.runtimeGatewayOidcToken) return null;
224
+ try {
225
+ const renewed = fs.readFileSync(configPath + ${JSON.stringify(RUNTIME_GATEWAY_OIDC_FILE_SUFFIX)}, 'utf8').trim();
226
+ if (renewed) return renewed;
227
+ } catch {}
228
+ return context.runtimeGatewayOidcToken;
229
+ }
230
+
231
+ function watchdogRuntimeGatewayOidcFailure() {
232
+ try {
233
+ if (!terminationDiagnosticPath) return null;
234
+ const diagnostic = JSON.parse(fs.readFileSync(terminationDiagnosticPath, 'utf8'));
235
+ if (
236
+ diagnostic &&
237
+ diagnostic.schemaVersion === 1 &&
238
+ diagnostic.reason === ${JSON.stringify(RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON)}
239
+ ) {
240
+ return diagnostic;
241
+ }
242
+ } catch {}
243
+ return null;
244
+ }
202
245
  const MAX_OUTPUT_BYTES = ${DAYTONA_CRASH_PUSHER_OUTPUT_TAIL_MAX_BYTES};
203
246
  const MAX_POST_TERMINAL_DIAGNOSTIC_BYTES = ${RUNNER_POST_TERMINAL_DIAGNOSTIC_MAX_BYTES};
204
247
  let postTerminalDiagnosticBytesRemaining = MAX_POST_TERMINAL_DIAGNOSTIC_BYTES;
@@ -416,8 +459,12 @@ async function main() {
416
459
  // V8 aborts itself on heap exhaustion. SIGABRT alone is also authored
417
460
  // program output, so 134 needs the explicit allocation signature.
418
461
  (exitCode === 134 && explicitOomSignature));
462
+ const runtimeGatewayOidcFailure = watchdogRuntimeGatewayOidcFailure();
419
463
  const synthesizedError = runtimeLimitExceeded
420
464
  ? 'RUNTIME_LIMIT_EXCEEDED: ' + ${JSON.stringify(runtimeLimitMessage)}
465
+ : runtimeGatewayOidcFailure
466
+ ? ${JSON.stringify(RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON)} + ': the sandbox could not renew its Runtime gateway credential (' +
467
+ String(runtimeGatewayOidcFailure.errorCode) + ') and was stopped before it expired.'
421
468
  : memoryAbort
422
469
  ? memoryAbortCause(memoryAbort)
423
470
  : sandboxOom
@@ -485,11 +532,16 @@ async function main() {
485
532
  ? { finalProgressLogOffset: parsedResultEvent.finalProgressLogOffset }
486
533
  : {}),
487
534
  });
535
+ // A pinned run may stage a body up to 16 MiB through object storage, so
536
+ // its deadline scales with the body (bounded). Unpinned runs keep 10 s.
537
+ const pushTimeoutMs = context.runtimeGatewayCredentialScope
538
+ ? runtimeGatewayStagedSendTimeoutMs(Buffer.byteLength(requestBody))
539
+ : 10000;
488
540
  for (let attempt = 1; attempt <= 3; attempt += 1) {
489
541
  const controller = new AbortController();
490
- const timer = setTimeout(() => controller.abort(), 10000);
542
+ const timer = setTimeout(() => controller.abort(), pushTimeoutMs);
491
543
  try {
492
- const response = await fetch(gateway + '/api/v2/plays/runtime', {
544
+ const terminalRequest = {
493
545
  method: 'POST',
494
546
  headers: {
495
547
  'content-type': 'application/json',
@@ -497,11 +549,27 @@ async function main() {
497
549
  ...(preferredGatewayMachineId
498
550
  ? { 'fly-force-instance-id': preferredGatewayMachineId }
499
551
  : {}),
552
+ ...(runtimeGatewayOidcRequestHeaders(
553
+ context.runtimeGatewayCredentialScope,
554
+ currentRuntimeGatewayOidcToken(context),
555
+ gateway + '${APP_RUNTIME_COMPAT_PATH}',
556
+ ) || {}),
500
557
  },
501
558
  body: requestBody,
502
559
  signal: controller.signal,
503
560
  redirect: 'manual',
504
- });
561
+ };
562
+ const response = context.runtimeGatewayCredentialScope
563
+ ? await runtimeGatewayStagedSend(
564
+ fetch,
565
+ gateway + '${APP_RUNTIME_COMPAT_PATH}',
566
+ terminalRequest,
567
+ Object.assign(
568
+ ${JSON.stringify({ ...runtimeGatewayStagingClientLimits([]), pathPrefixes: undefined })},
569
+ { pathPrefixes: context.runtimeGatewayCredentialScope.pathPrefixes },
570
+ ),
571
+ )
572
+ : await fetch(gateway + '${APP_RUNTIME_COMPAT_PATH}', terminalRequest);
505
573
  // Keep the HTTP deadline through body consumption so retries do not
506
574
  // leave an unread socket behind. The status already acknowledges the
507
575
  // durable terminal even if its diagnostic response body is interrupted.
@@ -781,6 +849,9 @@ export async function stageRunnerPayload(input: {
781
849
  shellQuote(memoryPressurePath),
782
850
  shellQuote(RUNNER_MEMORY_CGROUP_ROOT),
783
851
  shellQuote(runnerPidPath),
852
+ ...runtimeGatewayCredentialWatchdogArgs(remoteConfig.context).map(
853
+ shellQuote,
854
+ ),
784
855
  ].join(' ');
785
856
  const runnerCommand = `${nodeMaterializePayloadCommand({
786
857
  envelopePath,
@@ -1,3 +1,4 @@
1
+ import { APP_RUNTIME_COMPAT_PATH } from '../../runtime-api-paths';
1
2
  import {
2
3
  STANDARD_PLAY_SANDBOX_RUNTIME_LIMITS,
3
4
  MAX_PLAY_SANDBOX_RUNTIME_LIMITS,
@@ -12,6 +13,30 @@ import {
12
13
  RUNTIME_MEMORY_LEDGER_PATH_ENV,
13
14
  RUNTIME_MEMORY_PRESSURE_PATH_ENV,
14
15
  } from '../../memory-pressure-signal';
16
+ import {
17
+ RUNTIME_GATEWAY_OIDC_FILE_ENV,
18
+ RUNTIME_GATEWAY_OIDC_RENEW_AFTER_SECONDS,
19
+ RUNTIME_GATEWAY_OIDC_RENEW_PATH,
20
+ RUNTIME_GATEWAY_OIDC_RENEW_RESPONSE_FIELD,
21
+ } from '../../runtime-gateway-oidc';
22
+ import {
23
+ RUNTIME_GATEWAY_OIDC_FILE_SUFFIX,
24
+ RUNTIME_GATEWAY_OIDC_RENEW_RETRY_BASE_MS,
25
+ RUNTIME_GATEWAY_OIDC_RENEW_RETRY_MAX_MS,
26
+ runtimeGatewayOidcRequestHeaders,
27
+ isRuntimeGatewayOidcRenewalFatal,
28
+ startRuntimeGatewayOidcRenewalLoop,
29
+ } from '../../runtime-gateway-sandbox-credential';
30
+
31
+ /** Termination reason when the watchdog cannot keep the gateway credential valid. */
32
+ export const RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON =
33
+ 'runtime_gateway_oidc_renewal_failed';
34
+ /**
35
+ * Renewal retries stop, and the runner is stopped loudly, once the current
36
+ * credential has less than this left. The remainder lets the crash epilogue
37
+ * still deliver the terminal through the pinned gateway.
38
+ */
39
+ export const RUNTIME_GATEWAY_OIDC_RENEW_EXPIRY_MARGIN_SECONDS = 90;
15
40
 
16
41
  /** Exit code reserved for the external runner watchdog's runtime deadline. */
17
42
  export const DAYTONA_RUNTIME_WATCHDOG_EXIT_CODE = 124;
@@ -248,11 +273,34 @@ export function accumulateSampledCgroupMemoryUsage(
248
273
  * 1 runnerPath, 2 configPath, 3 runtimeStartedPath, 4 runtimeCompletedPath,
249
274
  * 5 limitMs, 6 startupLimitMs, 7 terminalGraceMs, 8 runtimeLimitMarkerPath,
250
275
  * 9 terminationDiagnosticPath, 10 memoryLedgerPath, 11 memoryPressurePath,
251
- * 12 cgroupRoot, 13 runnerPidPath.
276
+ * 12 cgroupRoot, 13 runnerPidPath, 14 runtimeGatewayCredential.
277
+ *
278
+ * `runtimeGatewayCredential` is `RUNTIME_GATEWAY_CREDENTIAL_WATCHDOG_FLAG`
279
+ * only for a pinned run (the worker passes it when the config carries a
280
+ * credential scope; `runtimeGatewayCredentialWatchdogArgs`). Without it the
281
+ * watchdog never reads or parses the runner config at startup.
282
+ */
283
+ /** argv 14 of the watchdog: this run carries a Runtime gateway credential. */
284
+ export const RUNTIME_GATEWAY_CREDENTIAL_WATCHDOG_FLAG =
285
+ 'runtime-gateway-credential';
286
+
287
+ /**
288
+ * The trailing watchdog argument for a run, given its runner context: the
289
+ * flag when a credential scope exists, nothing otherwise.
252
290
  */
291
+ export function runtimeGatewayCredentialWatchdogArgs(context: {
292
+ runtimeGatewayCredentialScope?: unknown;
293
+ }): string[] {
294
+ return context.runtimeGatewayCredentialScope
295
+ ? [RUNTIME_GATEWAY_CREDENTIAL_WATCHDOG_FLAG]
296
+ : [];
297
+ }
298
+
253
299
  export function buildDaytonaRuntimeWatchdogSource(
254
300
  sandboxRuntimeLimits: PlaySandboxRuntimeLimits = STANDARD_PLAY_SANDBOX_RUNTIME_LIMITS,
255
301
  memoryLimitMiB?: number,
302
+ /** First renewal retry delay of a pinned run's watchdog (tests shorten it). */
303
+ runtimeGatewayOidcRenewRetryBaseMs: number = RUNTIME_GATEWAY_OIDC_RENEW_RETRY_BASE_MS,
256
304
  ): string {
257
305
  const nodeExecArgv = playRunnerNodeExecArgvForLimits(
258
306
  sandboxRuntimeLimits,
@@ -281,7 +329,39 @@ const memoryLedgerPath = process.argv[10] || '';
281
329
  const memoryPressurePath = process.argv[11] || '';
282
330
  const cgroupRoot = process.argv[12] || ${JSON.stringify(RUNNER_MEMORY_CGROUP_ROOT)};
283
331
  const runnerPidPath = process.argv[13] || '';
332
+ const runtimeGatewayCredentialFlagged = process.argv[14] === ${JSON.stringify(RUNTIME_GATEWAY_CREDENTIAL_WATCHDOG_FLAG)};
284
333
  const runtimeLimitSeconds = Math.max(1, Math.ceil(limitMs / 1_000));
334
+
335
+ // --- Runtime gateway credential (pinned runs only) -------------------------
336
+ // A run pinned to an app-hosted gateway presents a short-lived OIDC token to
337
+ // that exact origin and gateway paths. This process renews it and shares the
338
+ // latest token with the runner through a file beside the config. Only a run
339
+ // the worker flagged (argv 14) reads the config here; unpinned runs do none
340
+ // of this.
341
+ const runtimeGatewayOidcRequestHeaders = (${runtimeGatewayOidcRequestHeaders.toString()});
342
+ const runtimeGatewayOidcFilePath = configPath + ${JSON.stringify(RUNTIME_GATEWAY_OIDC_FILE_SUFFIX)};
343
+ const runtimeGatewayOidc = !runtimeGatewayCredentialFlagged ? null : (() => {
344
+ // Flagged as pinned: an unreadable config fails loudly below.
345
+ let context = {};
346
+ try {
347
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
348
+ context = (config && config.context) || {};
349
+ } catch {}
350
+ const renewUrl = String(context.receiptGatewayBaseUrl || '').replace(/\\/$/, '') +
351
+ ${JSON.stringify(RUNTIME_GATEWAY_OIDC_RENEW_PATH)};
352
+ const scope = context.runtimeGatewayCredentialScope;
353
+ const token = context.runtimeGatewayOidcToken;
354
+ if (
355
+ typeof context.executorToken !== 'string' ||
356
+ !context.executorToken ||
357
+ !runtimeGatewayOidcRequestHeaders(scope, token, renewUrl)
358
+ ) {
359
+ // The worker validated the pin; an unusable one here must not run quietly.
360
+ process.stderr.write('${RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON}: pinned runner config has no usable gateway credential.\\n');
361
+ process.exit(1);
362
+ }
363
+ return { scope, token, renewUrl, executorToken: context.executorToken, runId: context.runId };
364
+ })();
285
365
  const child = spawn(
286
366
  process.execPath,
287
367
  [${nodeExecArgv.map((flag) => JSON.stringify(flag)).join(', ')}, runnerPath, configPath],
@@ -294,6 +374,9 @@ const child = spawn(
294
374
  ...(memoryPressurePath
295
375
  ? { ${JSON.stringify(RUNTIME_MEMORY_PRESSURE_PATH_ENV)}: memoryPressurePath }
296
376
  : {}),
377
+ ...(runtimeGatewayOidc
378
+ ? { ${JSON.stringify(RUNTIME_GATEWAY_OIDC_FILE_ENV)}: runtimeGatewayOidcFilePath }
379
+ : {}),
297
380
  },
298
381
  stdio: 'inherit',
299
382
  },
@@ -547,13 +630,20 @@ async function runnerHeartbeatTick() {
547
630
  const sandboxHealth = takeSandboxHealth();
548
631
  try {
549
632
  const response = await fetch(
550
- config.gatewayBaseUrl + '/api/v2/plays/runtime',
633
+ config.gatewayBaseUrl + '${APP_RUNTIME_COMPAT_PATH}',
551
634
  {
552
635
  method: 'POST',
553
636
  headers: {
554
637
  'content-type': 'application/json',
555
638
  authorization: 'Bearer ' + config.executorToken,
556
639
  ${JSON.stringify(PLAY_RUNTIME_TRANSPORT_ATTEMPT_HEADER)}: require('node:crypto').randomUUID(),
640
+ ...(runtimeGatewayOidc
641
+ ? runtimeGatewayOidcRequestHeaders(
642
+ runtimeGatewayOidc.scope,
643
+ runtimeGatewayOidc.token,
644
+ config.gatewayBaseUrl + '${APP_RUNTIME_COMPAT_PATH}',
645
+ ) || {}
646
+ : {}),
557
647
  },
558
648
  body: JSON.stringify({
559
649
  action: 'runner_heartbeat',
@@ -639,6 +729,139 @@ async function runnerHeartbeatTick() {
639
729
  }
640
730
  }
641
731
 
732
+ const startRuntimeGatewayOidcRenewalLoop = (${startRuntimeGatewayOidcRenewalLoop.toString()});
733
+ const isRuntimeGatewayOidcRenewalFatal = (${isRuntimeGatewayOidcRenewalFatal.toString()});
734
+ let runtimeGatewayOidcRenewalLoop = null;
735
+
736
+ function readRuntimeGatewayOidcClaims(token) {
737
+ if (typeof token !== 'string' || token.length > 4096 || token.split('.').length !== 3) return null;
738
+ try {
739
+ const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
740
+ return claims && Number.isSafeInteger(claims.iat) && Number.isSafeInteger(claims.exp) ? claims : null;
741
+ } catch {
742
+ return null;
743
+ }
744
+ }
745
+
746
+ async function renewRuntimeGatewayOidcOnce() {
747
+ const credential = runtimeGatewayOidc;
748
+ const prior = readRuntimeGatewayOidcClaims(credential.token);
749
+ const controller = new AbortController();
750
+ const timeout = setTimeout(() => controller.abort(), ${RUNNER_HEARTBEAT_REQUEST_TIMEOUT_MS});
751
+ try {
752
+ const response = await fetch(credential.renewUrl, {
753
+ method: 'POST',
754
+ headers: {
755
+ 'content-type': 'application/json',
756
+ authorization: 'Bearer ' + credential.executorToken,
757
+ ...(runtimeGatewayOidcRequestHeaders(credential.scope, credential.token, credential.renewUrl) || {}),
758
+ },
759
+ body: JSON.stringify({ runId: credential.runId }),
760
+ redirect: 'manual',
761
+ signal: controller.signal,
762
+ });
763
+ if (!response.ok) {
764
+ const refusal = await response.json().catch(() => null);
765
+ // The gateway names why it refused. After a sandbox network cut the
766
+ // runner heartbeat may still be stale when the first renewal lands;
767
+ // only that refusal (attempt_not_live) is retried within the
768
+ // credential's remaining life. Every other refusal is definitive.
769
+ const detail = refusal && typeof refusal.detail === 'string' && /^[a-z_]{1,64}$/.test(refusal.detail) ? '_' + refusal.detail : '';
770
+ // The gateway clock, so the renewal loop can judge the initial
771
+ // credential's age despite sandbox clock skew.
772
+ const serverNowMs = Date.parse(response.headers.get('date') || '');
773
+ throw Object.assign(new Error('renewal_http_error'), {
774
+ code: 'http_' + response.status + detail,
775
+ ...(Number.isFinite(serverNowMs) ? { serverNowMs } : {}),
776
+ });
777
+ }
778
+ const body = await response.json().catch(() => null);
779
+ const nextToken = body && body[${JSON.stringify(RUNTIME_GATEWAY_OIDC_RENEW_RESPONSE_FIELD)}];
780
+ const next = readRuntimeGatewayOidcClaims(nextToken);
781
+ if (
782
+ !prior ||
783
+ !next ||
784
+ next.exp <= prior.exp ||
785
+ ['iss', 'aud', 'sub', 'deployment_id', 'run_id', 'run_attempt'].some((field) => prior[field] !== next[field]) ||
786
+ !runtimeGatewayOidcRequestHeaders(credential.scope, nextToken, credential.renewUrl)
787
+ ) {
788
+ throw Object.assign(new Error('renewal_scope_mismatch'), { code: 'renewal_scope_mismatch' });
789
+ }
790
+ const temporary = runtimeGatewayOidcFilePath + '.' + require('node:crypto').randomUUID();
791
+ try {
792
+ fs.writeFileSync(temporary, nextToken, { mode: 0o600, flag: 'wx' });
793
+ fs.renameSync(temporary, runtimeGatewayOidcFilePath);
794
+ } finally {
795
+ try { fs.unlinkSync(temporary); } catch {}
796
+ }
797
+ credential.token = nextToken;
798
+ process.stderr.write(
799
+ '[play-runner.oidc] watchdog_oidc_renewed ' +
800
+ JSON.stringify({ runId: credential.runId, issuedAt: next.iat, expiresAt: next.exp }) +
801
+ '\\n',
802
+ );
803
+ return { iatS: next.iat, expS: next.exp };
804
+ } catch (error) {
805
+ throw controller.signal.aborted
806
+ ? Object.assign(new Error('renewal_timeout'), { code: 'TimeoutError' })
807
+ : error;
808
+ } finally {
809
+ clearTimeout(timeout);
810
+ }
811
+ }
812
+
813
+ function runtimeGatewayOidcRenewalErrorCode(error) {
814
+ return error && (error.code === 'renewal_scope_mismatch' || error.code === 'TimeoutError' || /^http_/.test(String(error.code)))
815
+ ? error.code
816
+ : runnerHeartbeatErrorCode(error);
817
+ }
818
+
819
+ if (runtimeGatewayOidc) {
820
+ const initialClaims = readRuntimeGatewayOidcClaims(runtimeGatewayOidc.token);
821
+ runtimeGatewayOidcRenewalLoop = startRuntimeGatewayOidcRenewalLoop({
822
+ // An unreadable initial token is due at once (after the retry base);
823
+ // its renewal then fails loudly.
824
+ initial: initialClaims
825
+ ? { iatS: initialClaims.iat, expS: initialClaims.exp }
826
+ : { iatS: 0, expS: 0 },
827
+ renewAfterSeconds: ${RUNTIME_GATEWAY_OIDC_RENEW_AFTER_SECONDS},
828
+ expiryMarginSeconds: ${RUNTIME_GATEWAY_OIDC_RENEW_EXPIRY_MARGIN_SECONDS},
829
+ retryBaseMs: ${Math.max(1, Math.floor(runtimeGatewayOidcRenewRetryBaseMs))},
830
+ retryMaxMs: ${RUNTIME_GATEWAY_OIDC_RENEW_RETRY_MAX_MS},
831
+ now: () => Date.now(),
832
+ random: () => Math.random(),
833
+ setTimer: (run, delayMs) => {
834
+ const timer = setTimeout(run, delayMs);
835
+ timer.unref?.();
836
+ return timer;
837
+ },
838
+ clearTimer: (timer) => clearTimeout(timer),
839
+ renew: renewRuntimeGatewayOidcOnce,
840
+ // A definitive refusal (lost lease, cancelled, wrong scope) ends this
841
+ // attempt now, loudly, while the crash epilogue can still reach the
842
+ // gateway. It never silently outlives its credential.
843
+ isFatal: (error) => isRuntimeGatewayOidcRenewalFatal(runtimeGatewayOidcRenewalErrorCode(error)),
844
+ isStopped: () => settled || stopRequested,
845
+ onRetry: (error, diagnostic) => {
846
+ process.stderr.write('[play-runner.oidc] watchdog_oidc_renewal_retry ' + JSON.stringify({
847
+ runId: runtimeGatewayOidc.runId,
848
+ errorCode: runtimeGatewayOidcRenewalErrorCode(error),
849
+ ...diagnostic,
850
+ }) + '\\n');
851
+ },
852
+ onFatal: (error, diagnostic) => {
853
+ const details = {
854
+ runId: runtimeGatewayOidc.runId,
855
+ errorCode: runtimeGatewayOidcRenewalErrorCode(error),
856
+ failures: diagnostic.failures,
857
+ remainingSeconds: diagnostic.remainingSeconds,
858
+ };
859
+ process.stderr.write('${RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON}: ' + JSON.stringify(details) + '\\n');
860
+ stopChild('${RUNTIME_GATEWAY_OIDC_RENEWAL_FAILED_REASON}', details);
861
+ },
862
+ });
863
+ }
864
+
642
865
  function writeTerminationDiagnostic(reason, details = {}) {
643
866
  if (!terminationDiagnosticPath) return;
644
867
  try {
@@ -933,6 +1156,7 @@ function finish(code, signal) {
933
1156
  clearInterval(runtimeBoundaryPoll);
934
1157
  clearInterval(memoryWatch);
935
1158
  clearInterval(stallWatch);
1159
+ if (runtimeGatewayOidcRenewalLoop) runtimeGatewayOidcRenewalLoop.stop();
936
1160
  stopRunnerHeartbeat();
937
1161
  clearTimeout(startupTimer);
938
1162
  if (runtimeTimer) clearTimeout(runtimeTimer);