deepline 0.3.500 → 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 +18 -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-WK3FDPRP.mjs → auth-6ECHXOI4.mjs} +5 -5
  40. package/dist/cli/auth-VP7PMXKQ.js +43 -0
  41. package/dist/cli/{billing-O3LVKXE7.mjs → billing-75NZYRXA.mjs} +8 -8
  42. package/dist/cli/{billing-K7UHZUF4.js → billing-QRR7O6BD.js} +81 -81
  43. package/dist/cli/{chunk-RAZ3TMOS.js → chunk-463ZOO2L.js} +7 -7
  44. package/dist/cli/{chunk-W64Y7GE7.js → chunk-4OXHLTCP.js} +1 -1
  45. package/dist/cli/{chunk-5TVY5OEH.mjs → chunk-5S7MLAI7.mjs} +11 -11
  46. package/dist/cli/{chunk-SNJNPRIV.js → chunk-5X4AUFYW.js} +7 -7
  47. package/dist/cli/{chunk-CIV5GJAE.mjs → chunk-66XDYH5T.mjs} +2 -2
  48. package/dist/cli/{chunk-SRS2D27G.mjs → chunk-7L6QNHUL.mjs} +1 -1
  49. package/dist/cli/{chunk-GBRI644Y.js → chunk-APAHMCGR.js} +53 -53
  50. package/dist/cli/{chunk-UBKA33KY.mjs → chunk-BMCRTI6Z.mjs} +22 -1
  51. package/dist/cli/{chunk-K3BHKRMS.js → chunk-BOFCF4L7.js} +3 -3
  52. package/dist/cli/{chunk-KEBNXJSK.js → chunk-CJJ7JBM2.js} +16 -16
  53. package/dist/cli/{chunk-5JXGYSXH.mjs → chunk-EHVFBD36.mjs} +1 -1
  54. package/dist/cli/{chunk-5KAZGZG7.js → chunk-EKF4DKUA.js} +5 -5
  55. package/dist/cli/{chunk-IX2DPYIV.js → chunk-EKZQ5LQO.js} +3 -3
  56. package/dist/cli/{chunk-JHNFUCVT.mjs → chunk-EOO7OSS4.mjs} +4 -4
  57. package/dist/cli/{chunk-GOO4VI5M.js → chunk-FS7XYDOF.js} +16 -16
  58. package/dist/cli/{chunk-G3NA4R7M.js → chunk-HDKXSHGA.js} +53 -53
  59. package/dist/cli/{chunk-PHGMC33I.js → chunk-J6SVNKRP.js} +2 -2
  60. package/dist/cli/{chunk-L7X6ADNM.mjs → chunk-J74N375S.mjs} +4 -4
  61. package/dist/cli/{chunk-X7ODM2LK.js → chunk-KTOAJP4N.js} +6 -6
  62. package/dist/cli/{chunk-CBZTKDXW.mjs → chunk-MADTHS56.mjs} +1 -1
  63. package/dist/cli/{chunk-IZ6YWXIK.mjs → chunk-MSLXAVVK.mjs} +2 -2
  64. package/dist/cli/{chunk-Q2FXZ4Z5.js → chunk-N2TJJNCW.js} +96 -96
  65. package/dist/cli/{chunk-CS2AEAD6.mjs → chunk-N4TR6QRI.mjs} +1 -1
  66. package/dist/cli/{chunk-XCBOOB73.mjs → chunk-NA3J3F2Z.mjs} +1 -1
  67. package/dist/cli/{chunk-QRKCCY4L.mjs → chunk-O3DDVP7Z.mjs} +1 -1
  68. package/dist/cli/{chunk-XUOZYAP5.mjs → chunk-OKOXB3LY.mjs} +2 -2
  69. package/dist/cli/{chunk-SNPZ2QWL.js → chunk-PNF2ZU4R.js} +8 -8
  70. package/dist/cli/{chunk-X5SO7RV5.mjs → chunk-PXIF74UJ.mjs} +4 -4
  71. package/dist/cli/{chunk-74VKLBJD.js → chunk-QQ3JJYE2.js} +14 -14
  72. package/dist/cli/{chunk-4CJWOLOS.mjs → chunk-RFV7PPLS.mjs} +3 -3
  73. package/dist/cli/{chunk-EQR5O2D2.js → chunk-RNSHCJME.js} +3 -3
  74. package/dist/cli/{chunk-REIKJREB.js → chunk-RU5ROUFO.js} +5 -5
  75. package/dist/cli/{chunk-TOGCDNMH.js → chunk-SV2TEZ2M.js} +4 -4
  76. package/dist/cli/{chunk-MAHLIWOF.mjs → chunk-T4U245E4.mjs} +2 -2
  77. package/dist/cli/{chunk-T4AGTOKQ.mjs → chunk-T7E3XEPG.mjs} +6 -6
  78. package/dist/cli/{chunk-RHE4YI4H.js → chunk-TOE7LHEA.js} +6 -6
  79. package/dist/cli/{chunk-FJZUG633.mjs → chunk-UJRN6YP6.mjs} +3 -3
  80. package/dist/cli/{chunk-BIE57V6K.js → chunk-UR7JOSLT.js} +360 -300
  81. package/dist/cli/{chunk-5AC7NUQN.mjs → chunk-V5NHEYU7.mjs} +5 -5
  82. package/dist/cli/{chunk-PGRPNRP6.mjs → chunk-VD2374K7.mjs} +1 -1
  83. package/dist/cli/{chunk-VLCY4F6E.js → chunk-VL72UKNW.js} +26 -26
  84. package/dist/cli/{chunk-56QAHX2K.mjs → chunk-VTDAJZIJ.mjs} +90 -30
  85. package/dist/cli/{chunk-Z5LE7NXM.js → chunk-VVEMPC2I.js} +2 -2
  86. package/dist/cli/{chunk-U5GFP26N.js → chunk-W6JTHVPF.js} +21 -21
  87. package/dist/cli/{chunk-C7355NMU.mjs → chunk-WJUDAHIQ.mjs} +1 -1
  88. package/dist/cli/{chunk-XDVT3GOM.js → chunk-WSGXBROE.js} +22 -1
  89. package/dist/cli/{chunk-LNMY2T5S.js → chunk-XEBFJ2PH.js} +41 -41
  90. package/dist/cli/{chunk-HI2BFS5S.mjs → chunk-Z6AUOV7D.mjs} +2 -2
  91. package/dist/cli/{chunk-VPVEPGYS.mjs → chunk-ZUOKIBLJ.mjs} +2 -2
  92. package/dist/cli/{chunk-V7MZYIA7.mjs → chunk-ZUQHQGC5.mjs} +5 -5
  93. package/dist/cli/{csv-MWCWNIBJ.js → csv-JXX2LXK5.js} +13 -13
  94. package/dist/cli/{csv-DEUOSTEB.mjs → csv-RZJ4SOIL.mjs} +4 -4
  95. package/dist/cli/{db-QM5R5BRY.mjs → db-MUTT2NWI.mjs} +8 -8
  96. package/dist/cli/{db-Q6IRXTTG.js → db-T2KJNONM.js} +29 -29
  97. package/dist/cli/{describe-CQZ7TBOG.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-DCCDXSQI.js → executions-7HSLDRHR.js} +10 -10
  102. package/dist/cli/{executions-SWBKFCY2.mjs → executions-PHS4R2OX.mjs} +8 -8
  103. package/dist/cli/{feedback-EU3EYF4V.js → feedback-BJZRM637.js} +8 -8
  104. package/dist/cli/{feedback-Q27HN3SB.mjs → feedback-RWMDCIDF.mjs} +4 -4
  105. package/dist/cli/git-VNS7UQWN.js +25 -0
  106. package/dist/cli/{git-SEQFTQ4N.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-LCQDEVA3.js → legacy-noops-2WUV2XD7.js} +8 -8
  110. package/dist/cli/{legacy-noops-XKH4VREG.mjs → legacy-noops-5UBSUPGG.mjs} +5 -5
  111. package/dist/cli/{monitors-4XWBV46I.mjs → monitors-HWOQO3OK.mjs} +9 -9
  112. package/dist/cli/{monitors-DJCID6X5.js → monitors-YZZRKSTG.js} +97 -97
  113. package/dist/cli/{org-BU4FG5PN.js → org-JY7HLHBA.js} +74 -74
  114. package/dist/cli/{org-PSBGXBRW.mjs → org-NCXT6RB4.mjs} +8 -8
  115. package/dist/cli/{pages-3PHJYXYB.js → pages-6ZOHXL6X.js} +20 -20
  116. package/dist/cli/{pages-7QLXLJGQ.mjs → pages-QJO53QAT.mjs} +8 -8
  117. package/dist/cli/{play-4OLYXRCG.mjs → play-SQRS7JN3.mjs} +20 -20
  118. package/dist/cli/{play-S3CWPQKB.js → play-TAYGSR35.js} +336 -336
  119. package/dist/cli/{providers-JT7C2QTC.mjs → providers-3IR3N5DT.mjs} +8 -8
  120. package/dist/cli/{providers-U4JUMLB2.js → providers-4Q5LOIQ5.js} +11 -11
  121. package/dist/cli/{quickstart-OUSMXLYZ.js → quickstart-ITNUZENY.js} +6 -6
  122. package/dist/cli/{quickstart-DQF5CF2I.mjs → quickstart-KCZCYO6B.mjs} +4 -4
  123. package/dist/cli/{run-RECNI77K.mjs → run-JCWRWDSK.mjs} +24 -24
  124. package/dist/cli/{run-6XXHLB4X.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-JN7K3GC6.mjs → search-FUM27HQP.mjs} +9 -9
  128. package/dist/cli/search-I425FRTK.js +32 -0
  129. package/dist/cli/{search-output-L6PC5SPM.mjs → search-output-EWEYT34M.mjs} +4 -4
  130. package/dist/cli/{search-output-JGNYXDWZ.js → search-output-XAMWKRJH.js} +6 -6
  131. package/dist/cli/{secrets-TX6PCZ77.js → secrets-2IRRRZBL.js} +17 -17
  132. package/dist/cli/{secrets-UOXZWHBY.mjs → secrets-YTI4IAKR.mjs} +8 -8
  133. package/dist/cli/{sessions-DTE733EH.mjs → sessions-EFS4KUPF.mjs} +5 -5
  134. package/dist/cli/{sessions-GCEIX4KB.js → sessions-HWTRDXBQ.js} +6 -6
  135. package/dist/cli/{settings-UGXSDHR5.js → settings-FRVEIOKR.js} +80 -80
  136. package/dist/cli/{settings-ZGIMRCTC.mjs → settings-NTOO42DY.mjs} +13 -13
  137. package/dist/cli/{setup-JYB6Z376.js → setup-6ZIOAE2V.js} +49 -49
  138. package/dist/cli/{setup-UT7AO53D.mjs → setup-PAVQPALX.mjs} +9 -9
  139. package/dist/cli/{skills-4QJCMN7J.mjs → skills-3O3XTPUM.mjs} +7 -7
  140. package/dist/cli/skills-6ZNMO2PR.js +36 -0
  141. package/dist/cli/{tools-RGNXIAA6.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-Q62EVSXZ.mjs → update-T6CYS5ZT.mjs} +9 -9
  145. package/dist/cli/{workflow-GENV47RD.js → workflow-4KMJBMGX.js} +19 -19
  146. package/dist/cli/{workflow-YNIOWM7J.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-H4PCVUN3.js +0 -43
  172. package/dist/cli/describe-BZ544347.js +0 -50
  173. package/dist/cli/git-NW6BAXX2.js +0 -25
  174. package/dist/cli/run-identity-G257GQED.js +0 -25
  175. package/dist/cli/search-BIQ62ZBE.js +0 -32
  176. package/dist/cli/skills-53LCPB5R.js +0 -36
  177. package/dist/cli/tools-HKJK6UNJ.js +0 -57
  178. package/dist/cli/update-QMZSFTFZ.js +0 -34
@@ -0,0 +1,338 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import type { RuntimeGatewayLaunchPin } from './runtime-gateway-profile';
3
+ import {
4
+ RUNTIME_GATEWAY_OIDC_APP_HEADER,
5
+ RUNTIME_GATEWAY_OIDC_EDGE_HEADER,
6
+ } from './runtime-gateway-oidc';
7
+ import {
8
+ runtimeGatewayStagedSend,
9
+ runtimeGatewayStagingClientLimits,
10
+ } from './runtime-gateway-staging';
11
+
12
+ /**
13
+ * Where a sandbox may present its Runtime gateway OIDC credential: one exact
14
+ * origin (the pinned immutable deployment) and its gateway path prefixes.
15
+ * Derived by the worker from a validated launch pin, never by the sandbox.
16
+ */
17
+ export type RuntimeGatewayCredentialScope = Readonly<{
18
+ origin: string;
19
+ pathPrefixes: readonly string[];
20
+ }>;
21
+
22
+ /** Sandbox-side context fields for a pinned run. All absent when unpinned. */
23
+ export type RuntimeGatewaySandboxContext = {
24
+ runtimeGatewayCredentialScope?: RuntimeGatewayCredentialScope | null;
25
+ runtimeGatewayOidcToken?: string | null;
26
+ };
27
+
28
+ export const RUNTIME_GATEWAY_OIDC_FILE_SUFFIX = '.runtime-gateway-oidc';
29
+
30
+ /** File the watchdog rewrites with each renewed token, beside the runner config. */
31
+ export function runtimeGatewayOidcFilePath(configPath: string): string {
32
+ return `${configPath}${RUNTIME_GATEWAY_OIDC_FILE_SUFFIX}`;
33
+ }
34
+
35
+ export function runtimeGatewayCredentialScopeFromPin(
36
+ pin: Pick<RuntimeGatewayLaunchPin, 'origin' | 'profile'>,
37
+ ): RuntimeGatewayCredentialScope {
38
+ return Object.freeze({
39
+ origin: pin.origin,
40
+ pathPrefixes: Object.freeze([
41
+ pin.profile.receiptPath,
42
+ pin.profile.executionPath,
43
+ ]),
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Headers for one request, or null when the target is outside the scope.
49
+ *
50
+ * Self-contained on purpose: generated sandbox scripts (watchdog, crash
51
+ * terminal pusher) embed this function's source, so it must not reference
52
+ * imports or module state. `tests/shared/play-runtime/runtime-gateway-sandbox-credential.test.ts`
53
+ * pins the header literals to the OIDC module constants.
54
+ */
55
+ export function runtimeGatewayOidcRequestHeaders(
56
+ scope: unknown,
57
+ token: unknown,
58
+ target: unknown,
59
+ ): Record<string, string> | null {
60
+ if (!scope || typeof scope !== 'object') return null;
61
+ const origin = (scope as { origin?: unknown }).origin;
62
+ const prefixes = (scope as { pathPrefixes?: unknown }).pathPrefixes;
63
+ if (
64
+ typeof origin !== 'string' ||
65
+ !Array.isArray(prefixes) ||
66
+ prefixes.length === 0 ||
67
+ typeof token !== 'string' ||
68
+ token.length === 0 ||
69
+ token.length > 4096 ||
70
+ !/^[\w-]+\.[\w-]+\.[\w-]+$/.test(token)
71
+ ) {
72
+ return null;
73
+ }
74
+ let url: URL;
75
+ try {
76
+ url = new URL(String(target));
77
+ } catch {
78
+ return null;
79
+ }
80
+ if (
81
+ url.protocol !== 'https:' ||
82
+ url.origin !== origin ||
83
+ url.username ||
84
+ url.password
85
+ ) {
86
+ return null;
87
+ }
88
+ const inScope = prefixes.some(
89
+ (prefix) =>
90
+ typeof prefix === 'string' &&
91
+ prefix.startsWith('/') &&
92
+ (url.pathname === prefix || url.pathname.startsWith(prefix + '/')),
93
+ );
94
+ if (!inScope) return null;
95
+ return {
96
+ 'x-vercel-trusted-oidc-idp-token': token,
97
+ 'x-deepline-runtime-oidc': token,
98
+ };
99
+ }
100
+
101
+ /** Header names used by `runtimeGatewayOidcRequestHeaders`. */
102
+ export const RUNTIME_GATEWAY_OIDC_REQUEST_HEADER_NAMES = [
103
+ RUNTIME_GATEWAY_OIDC_EDGE_HEADER,
104
+ RUNTIME_GATEWAY_OIDC_APP_HEADER,
105
+ ] as const;
106
+
107
+ /** Latest renewed token from the watchdog's file, else the initial token. */
108
+ export function currentRuntimeGatewayOidcToken(
109
+ initial: string | null | undefined,
110
+ filePath: string | null | undefined,
111
+ readFile: (path: string) => string = (path) => readFileSync(path, 'utf8'),
112
+ ): string | null {
113
+ if (!initial) return null;
114
+ if (!filePath) return initial;
115
+ try {
116
+ const current = readFile(filePath).trim();
117
+ if (current.length <= 4096 && /^[\w-]+\.[\w-]+\.[\w-]+$/.test(current))
118
+ return current;
119
+ } catch {
120
+ // The watchdog creates the file at its first renewal.
121
+ }
122
+ return initial;
123
+ }
124
+
125
+ function requestTarget(input: Parameters<typeof fetch>[0]): string {
126
+ if (typeof input === 'string') return input;
127
+ if (input instanceof URL) return input.href;
128
+ return input.url;
129
+ }
130
+
131
+ /**
132
+ * Wrap a fetch so code-owned gateway requests to the pinned origin carry the
133
+ * OIDC credential. Every other target, including signed object URLs on other
134
+ * origins and app paths outside the gateway prefixes, passes through
135
+ * untouched. Credentialed requests never follow redirects.
136
+ *
137
+ * Credentialed requests given as a URL plus init also use staged bodies
138
+ * (`runtime-gateway-staging.ts`), so an app-hosted gateway keeps the Fly
139
+ * gateway's 16 MiB request and response contract under Vercel's body cap.
140
+ */
141
+ export function createRuntimeGatewayCredentialFetch(input: {
142
+ scope: RuntimeGatewayCredentialScope;
143
+ send: typeof fetch;
144
+ currentToken: () => string | null;
145
+ }): typeof fetch {
146
+ const { scope } = input;
147
+ const stagingLimits = runtimeGatewayStagingClientLimits(scope.pathPrefixes);
148
+ const wrapped = async (
149
+ request: Parameters<typeof fetch>[0],
150
+ init?: Parameters<typeof fetch>[1],
151
+ ): Promise<Response> => {
152
+ const headers = runtimeGatewayOidcRequestHeaders(
153
+ scope,
154
+ input.currentToken(),
155
+ requestTarget(request),
156
+ );
157
+ if (!headers) return await input.send(request, init);
158
+ const merged = new Headers(
159
+ init?.headers ??
160
+ (request instanceof Request ? request.headers : undefined),
161
+ );
162
+ for (const [name, value] of Object.entries(headers))
163
+ merged.set(name, value);
164
+ if (!(request instanceof Request)) {
165
+ return await runtimeGatewayStagedSend(
166
+ input.send,
167
+ requestTarget(request),
168
+ { ...init, headers: merged, redirect: 'manual' },
169
+ stagingLimits,
170
+ );
171
+ }
172
+ return await input.send(request, {
173
+ ...init,
174
+ headers: merged,
175
+ redirect: 'manual',
176
+ });
177
+ };
178
+ return wrapped as typeof fetch;
179
+ }
180
+
181
+ /**
182
+ * Whether a renewal failure is definitive: a 401/403/404/409 refusal by the
183
+ * gateway, with or without its named reason (`http_403_attempt_cancelled`,
184
+ * `_attempt_superseded`, `_lease_mismatch`, `_scope_mismatch`,
185
+ * `_attempt_not_found`, `_no_lease`), or a renewed token for another scope.
186
+ * Transport failures, 5xx, and `http_403_attempt_not_live` (a stale heartbeat
187
+ * while the runner catches up after a network cut) are retried.
188
+ * Self-contained: the generated watchdog embeds its source.
189
+ */
190
+ export function isRuntimeGatewayOidcRenewalFatal(errorCode: unknown): boolean {
191
+ return /^(?:http_(?:401|403|404|409)(?:_(?!attempt_not_live$)[a-z_]+)?|renewal_scope_mismatch)$/.test(
192
+ String(errorCode),
193
+ );
194
+ }
195
+
196
+ /** First retry delay after a failed renewal; doubles per failure. */
197
+ export const RUNTIME_GATEWAY_OIDC_RENEW_RETRY_BASE_MS = 5_000;
198
+ /** Longest delay between renewal retries. */
199
+ export const RUNTIME_GATEWAY_OIDC_RENEW_RETRY_MAX_MS = 60_000;
200
+
201
+ export type RuntimeGatewayOidcRenewalLoopOptions = {
202
+ /** The credential in hand: issued-at and expiry, in epoch seconds. */
203
+ initial: { iatS: number; expS: number };
204
+ renewAfterSeconds: number;
205
+ /** Stop retrying, loudly, once less than this remains. */
206
+ expiryMarginSeconds: number;
207
+ retryBaseMs: number;
208
+ retryMaxMs: number;
209
+ now: () => number;
210
+ random: () => number;
211
+ setTimer: (run: () => void, delayMs: number) => unknown;
212
+ clearTimer: (timer: unknown) => void;
213
+ /** Renew once; resolves with the new credential's times. */
214
+ renew: () => Promise<{ iatS: number; expS: number }>;
215
+ /** A definitive refusal (lost lease, wrong scope): no retry. */
216
+ isFatal: (error: unknown) => boolean;
217
+ isStopped: () => boolean;
218
+ onRetry: (
219
+ error: unknown,
220
+ diagnostic: RuntimeGatewayOidcRenewalDiagnostic,
221
+ ) => void;
222
+ onFatal: (
223
+ error: unknown,
224
+ diagnostic: RuntimeGatewayOidcRenewalDiagnostic,
225
+ ) => void;
226
+ };
227
+
228
+ export type RuntimeGatewayOidcRenewalDiagnostic = {
229
+ failures: number;
230
+ remainingSeconds: number;
231
+ nextRetryMs: number | null;
232
+ };
233
+
234
+ /**
235
+ * The renewal loop for the whole life of a sandbox (4 hours and more).
236
+ *
237
+ * Timing uses the sandbox's own clock. A renewed credential is taken to have
238
+ * been issued at the local time its renewal response arrived, and to live
239
+ * its server-stated lifetime (`expS - iatS`) from then, so once one renewal
240
+ * has succeeded, sandbox clock skew in either direction can neither spin the
241
+ * loop nor fail it early. The initial credential arrived before the loop
242
+ * started, so its age is judged from its issue time, corrected by the
243
+ * gateway clock whenever a renewal failure carries one (`serverNowMs`, from
244
+ * the response `Date` header); with no server time seen yet it is judged by
245
+ * the sandbox clock. Its first renewal is due at most `renewAfterSeconds`
246
+ * after the loop starts, so a skewed clock delays it by no more than that.
247
+ *
248
+ * Every renewal waits at least `retryBaseMs`. A failed renewal retries with
249
+ * capped exponential backoff and full jitter in its upper half, never past
250
+ * the expiry safety margin, so an outage shorter than the credential's
251
+ * remaining life is survived. A definitive refusal, or a credential inside
252
+ * the margin, stops the loop and calls `onFatal` once. Nothing here has its
253
+ * own deadline: the loop runs until `stop` or a fatal outcome.
254
+ *
255
+ * Self-contained on purpose: the generated watchdog embeds this function's
256
+ * source, so it must not reference imports, module state, or nested named
257
+ * functions.
258
+ */
259
+ export function startRuntimeGatewayOidcRenewalLoop(
260
+ options: RuntimeGatewayOidcRenewalLoopOptions,
261
+ ): { stop: () => void } {
262
+ const renewAfterMs = options.renewAfterSeconds * 1_000;
263
+ const initial = options.initial;
264
+ let lifetimeMs = Math.max(0, (initial.expS - initial.iatS) * 1_000);
265
+ /** Local issue time of the current credential; null for the initial one. */
266
+ let localIssuedMs: number | null = null;
267
+ /** Gateway clock minus sandbox clock, once a failure reported it. */
268
+ let skewMs = 0;
269
+ let failures = 0;
270
+ let timer: unknown = null;
271
+ let stopped = false;
272
+ const schedule = (delayMs: number) => {
273
+ if (stopped || options.isStopped()) return;
274
+ timer = options.setTimer(() => void tick(), Math.max(0, delayMs));
275
+ };
276
+ const remainingMs = () =>
277
+ localIssuedMs === null
278
+ ? initial.expS * 1_000 - (options.now() + skewMs)
279
+ : localIssuedMs + lifetimeMs - options.now();
280
+ const tick = async () => {
281
+ timer = null;
282
+ if (stopped || options.isStopped()) return;
283
+ try {
284
+ const next = await options.renew();
285
+ if (stopped || options.isStopped()) return;
286
+ failures = 0;
287
+ localIssuedMs = options.now();
288
+ lifetimeMs = Math.max(0, (next.expS - next.iatS) * 1_000);
289
+ schedule(Math.max(options.retryBaseMs, renewAfterMs));
290
+ } catch (error) {
291
+ if (stopped || options.isStopped()) return;
292
+ failures += 1;
293
+ const serverNowMs =
294
+ error && typeof error === 'object'
295
+ ? (error as { serverNowMs?: unknown }).serverNowMs
296
+ : undefined;
297
+ if (typeof serverNowMs === 'number' && Number.isFinite(serverNowMs)) {
298
+ skewMs = serverNowMs - options.now();
299
+ }
300
+ const left = remainingMs();
301
+ const untilMarginMs = left - options.expiryMarginSeconds * 1_000;
302
+ const diagnostic = {
303
+ failures,
304
+ remainingSeconds: Math.floor(left / 1_000),
305
+ nextRetryMs: null as number | null,
306
+ };
307
+ if (options.isFatal(error) || untilMarginMs <= 0) {
308
+ stopped = true;
309
+ options.onFatal(error, diagnostic);
310
+ return;
311
+ }
312
+ const backoffMs = Math.min(
313
+ options.retryMaxMs,
314
+ options.retryBaseMs * 2 ** Math.min(failures - 1, 30),
315
+ );
316
+ const jitteredMs = backoffMs / 2 + options.random() * (backoffMs / 2);
317
+ // The last retry lands at the margin, where a failure is fatal.
318
+ diagnostic.nextRetryMs = Math.round(Math.min(jitteredMs, untilMarginMs));
319
+ options.onRetry(error, diagnostic);
320
+ schedule(diagnostic.nextRetryMs);
321
+ }
322
+ };
323
+ schedule(
324
+ Math.min(
325
+ renewAfterMs,
326
+ Math.max(
327
+ options.retryBaseMs,
328
+ initial.iatS * 1_000 + renewAfterMs - options.now(),
329
+ ),
330
+ ),
331
+ );
332
+ return {
333
+ stop: () => {
334
+ stopped = true;
335
+ if (timer !== null) options.clearTimer(timer);
336
+ },
337
+ };
338
+ }