deepline 0.3.537 → 0.3.539

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 (205) 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 +18 -0
  8. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +9 -1
  9. package/dist/bundling-sources/shared_libs/play-runtime/baked-runner-image.ts +392 -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 +4 -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 -7
  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 +2399 -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-speed-profile.ts +136 -0
  40. package/dist/bundling-sources/shared_libs/play-runtime/runtime-traffic-policy.ts +54 -0
  41. package/dist/bundling-sources/shared_libs/play-runtime/runtime-work-counters.ts +10 -1
  42. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +22 -0
  43. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-play-run-task.ts +18 -1
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-pool.ts +18 -4
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +219 -7
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-shared.ts +3 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/early-sandbox-claim-affinity.ts +340 -0
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +1 -0
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +10 -1
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +623 -7
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +340 -5
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runner-push.ts +61 -0
  53. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +2 -1
  54. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-ledger-reconciliation.ts +269 -2
  55. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-worker-wake.ts +238 -5
  56. package/dist/bundling-sources/shared_libs/play-runtime/startup-read-tool-ids.ts +47 -0
  57. package/dist/bundling-sources/shared_libs/play-runtime/tool-call/runtime-step-receipts-adapter.ts +5 -4
  58. package/dist/bundling-sources/shared_libs/play-runtime/tool-result.ts +6 -0
  59. package/dist/bundling-sources/shared_libs/play-runtime/transient-service-error.ts +11 -0
  60. package/dist/cli/auth-O5Y2VYXK.js +43 -0
  61. package/dist/cli/{auth-4SUPGDIM.mjs → auth-QD7QGD3B.mjs} +5 -5
  62. package/dist/cli/{billing-5JUA3ZM3.mjs → billing-FIZXMHBW.mjs} +31 -7
  63. package/dist/cli/{billing-SQU726P7.js → billing-KOQAF6WS.js} +114 -90
  64. package/dist/cli/{chunk-R7JYG6XO.mjs → chunk-2XMFT44N.mjs} +1 -1
  65. package/dist/cli/{chunk-XDS26J7Z.js → chunk-3YDI2PTN.js} +10 -10
  66. package/dist/cli/{chunk-KH27B2HJ.mjs → chunk-55ITVU2V.mjs} +2 -2
  67. package/dist/cli/{chunk-2Q7VXTMS.js → chunk-5QL4GJB2.js} +2 -2
  68. package/dist/cli/{chunk-D77W6Q67.js → chunk-5RUB53KG.js} +26 -26
  69. package/dist/cli/{chunk-JS2SBCWD.js → chunk-5YF35HAV.js} +6 -6
  70. package/dist/cli/{chunk-C37VELBR.mjs → chunk-6KG4KVTH.mjs} +5 -5
  71. package/dist/cli/{chunk-AX2OAXDL.mjs → chunk-6NZBLFL4.mjs} +1 -1
  72. package/dist/cli/{chunk-C3XD2WHM.mjs → chunk-6V3LNYK5.mjs} +2 -2
  73. package/dist/cli/{chunk-GPMS6OPX.mjs → chunk-ADV2IB2C.mjs} +5 -5
  74. package/dist/cli/{chunk-ZUAMXZXC.mjs → chunk-APKZGUTU.mjs} +4 -4
  75. package/dist/cli/{chunk-IQOIT6E3.js → chunk-CQJCLHBE.js} +41 -41
  76. package/dist/cli/{chunk-W3J3LT22.mjs → chunk-DZFVVP3S.mjs} +5 -5
  77. package/dist/cli/{chunk-V5IIBG2E.mjs → chunk-E4QHTDPF.mjs} +1 -1
  78. package/dist/cli/{chunk-CXTW7SRW.mjs → chunk-E7D37PLM.mjs} +8 -0
  79. package/dist/cli/{chunk-KULT6O5K.js → chunk-EAZS52DL.js} +15 -15
  80. package/dist/cli/{chunk-L3JVGNAT.mjs → chunk-F43MXIN3.mjs} +2 -2
  81. package/dist/cli/{chunk-WBTYWJLN.js → chunk-FH3P3E4S.js} +2 -2
  82. package/dist/cli/{chunk-K4WJ4BYO.mjs → chunk-FIRV7BXJ.mjs} +1 -1
  83. package/dist/cli/{chunk-NXGLJGPB.js → chunk-FSQCB5SJ.js} +2 -2
  84. package/dist/cli/{chunk-AVQET3NR.js → chunk-FTBWFDF3.js} +7 -7
  85. package/dist/cli/{chunk-QDBGPRR2.mjs → chunk-G3UFDUYU.mjs} +3 -1
  86. package/dist/cli/{chunk-ZHPSJ3LJ.mjs → chunk-GEO2EMM7.mjs} +29 -16
  87. package/dist/cli/{chunk-CGDW2CRR.mjs → chunk-GLEGINSP.mjs} +2 -2
  88. package/dist/cli/{chunk-EEFSUCYP.mjs → chunk-GLKUC5PO.mjs} +2 -2
  89. package/dist/cli/{chunk-BFHR7IC2.mjs → chunk-GNCIMHO2.mjs} +10 -10
  90. package/dist/cli/{chunk-PU42VOBI.js → chunk-ISXX5DUD.js} +3 -3
  91. package/dist/cli/{chunk-Y6AMMXWS.mjs → chunk-JBCQFG7G.mjs} +3 -3
  92. package/dist/cli/{chunk-Z2PPB3IO.mjs → chunk-JHEZQMOM.mjs} +1 -1
  93. package/dist/cli/{chunk-WBFOV5HT.js → chunk-K22EKW6L.js} +5 -5
  94. package/dist/cli/{chunk-CHIGEDAE.js → chunk-K5MZHTK7.js} +3 -3
  95. package/dist/cli/{chunk-L6QAIZNZ.js → chunk-KAEVL62Q.js} +44 -44
  96. package/dist/cli/{chunk-PJ4ZGZAN.js → chunk-KQTX545E.js} +13 -13
  97. package/dist/cli/{chunk-VP2K5B3R.mjs → chunk-LE5KN7CZ.mjs} +3 -3
  98. package/dist/cli/{chunk-BGXEMTIG.js → chunk-LEREPTAE.js} +19 -19
  99. package/dist/cli/{chunk-QPDLG7DQ.js → chunk-MI53W4DN.js} +53 -53
  100. package/dist/cli/{chunk-RMVZTBI5.mjs → chunk-MKESK3SW.mjs} +4 -4
  101. package/dist/cli/{chunk-NU7B5X6J.mjs → chunk-N3LPGGWD.mjs} +1 -1
  102. package/dist/cli/{chunk-VRYX2BR4.js → chunk-NR5PLMNG.js} +107 -107
  103. package/dist/cli/{chunk-JMHYDDBQ.js → chunk-Q4HNK7JX.js} +292 -279
  104. package/dist/cli/{chunk-37AZHCTP.mjs → chunk-RULRGMMM.mjs} +5 -5
  105. package/dist/cli/{chunk-GI3V4D7K.mjs → chunk-SDAP5MCO.mjs} +2 -2
  106. package/dist/cli/{chunk-5EOEJKSV.js → chunk-TZBCJHV6.js} +1 -1
  107. package/dist/cli/{chunk-3PMCQ3LK.js → chunk-V7DEGIYO.js} +7 -5
  108. package/dist/cli/{chunk-ALHKB3AE.js → chunk-VK5UTS5B.js} +9 -9
  109. package/dist/cli/{chunk-ZFSB7GXF.js → chunk-W32KT6LM.js} +5 -5
  110. package/dist/cli/{chunk-6BBGUQJJ.js → chunk-XTYHZEJ2.js} +8 -0
  111. package/dist/cli/{chunk-UGA5KI4A.js → chunk-XZBXQCRJ.js} +22 -22
  112. package/dist/cli/{chunk-BRRCWUOW.mjs → chunk-Y66ZMOJI.mjs} +1 -1
  113. package/dist/cli/{chunk-CFND2ACL.js → chunk-YMQFQO3K.js} +16 -16
  114. package/dist/cli/command-docs.js +2 -2
  115. package/dist/cli/command-docs.mjs +1 -1
  116. package/dist/cli/{csv-JITYN27L.js → csv-BWWJYV2C.js} +13 -13
  117. package/dist/cli/{csv-HZP6QMG7.mjs → csv-G5RQQ74W.mjs} +4 -4
  118. package/dist/cli/{db-FYSRB7O4.js → db-5KNDLADE.js} +27 -27
  119. package/dist/cli/{db-QRIRTOMM.mjs → db-AJZHWB3V.mjs} +6 -6
  120. package/dist/cli/describe-B6CN6CFJ.js +49 -0
  121. package/dist/cli/{describe-REXJVJC3.mjs → describe-QY5TKWVD.mjs} +17 -17
  122. package/dist/cli/describe-core.d.mts +3 -3
  123. package/dist/cli/describe-core.d.ts +3 -3
  124. package/dist/cli/{executions-BSTF4DDS.js → executions-BCCW76BI.js} +8 -8
  125. package/dist/cli/{executions-53KJAFOW.mjs → executions-SJPH3MZT.mjs} +6 -6
  126. package/dist/cli/{feedback-6MW3QOXX.js → feedback-GF65JKK6.js} +14 -14
  127. package/dist/cli/{feedback-CWUJJF3J.mjs → feedback-S6SZOFGK.mjs} +6 -6
  128. package/dist/cli/git-DX6NB7VF.js +25 -0
  129. package/dist/cli/{git-CKVZTJFS.mjs → git-F5FT5YVB.mjs} +5 -5
  130. package/dist/cli/index.js +143 -143
  131. package/dist/cli/index.mjs +42 -42
  132. package/dist/cli/{legacy-noops-QBL4PNGB.js → legacy-noops-ECR6FS6U.js} +9 -9
  133. package/dist/cli/{legacy-noops-USTBRFRX.mjs → legacy-noops-NOA4P5NE.mjs} +6 -6
  134. package/dist/cli/{monitors-6UCG5D7W.mjs → monitors-CTYSAGP4.mjs} +7 -7
  135. package/dist/cli/{monitors-VCR6SUZD.js → monitors-DEWBSURN.js} +100 -100
  136. package/dist/cli/{org-GSRBOJVO.mjs → org-EKSKKT7H.mjs} +6 -6
  137. package/dist/cli/{org-HPILTEG4.js → org-ZM2UUMZZ.js} +86 -86
  138. package/dist/cli/{play-TK7WOP5H.js → play-6JQOM6DE.js} +317 -317
  139. package/dist/cli/{play-QRTYQNG4.mjs → play-R2BH374J.mjs} +17 -17
  140. package/dist/cli/{providers-HEXNJ5QC.js → providers-CMIYHEMN.js} +9 -9
  141. package/dist/cli/{providers-OAQJWVBS.mjs → providers-X7WMIWO4.mjs} +6 -6
  142. package/dist/cli/{quickstart-PYZTFXZX.js → quickstart-6HVPAMSW.js} +6 -6
  143. package/dist/cli/{quickstart-FFVHTPSP.mjs → quickstart-ZZ7L6VZJ.mjs} +4 -4
  144. package/dist/cli/{run-HLN6YYZH.mjs → run-FP32RKBU.mjs} +22 -22
  145. package/dist/cli/{run-4DWJXJRO.js → run-OOHYH3GI.js} +42 -42
  146. package/dist/cli/search-34C6LFOJ.js +32 -0
  147. package/dist/cli/{search-ZHRCXGEL.mjs → search-BDDNC23Z.mjs} +7 -7
  148. package/dist/cli/{search-output-2KY6PFDH.js → search-output-5VZIQQAM.js} +6 -6
  149. package/dist/cli/{search-output-N7QXACVK.mjs → search-output-QXJ6CV5G.mjs} +4 -4
  150. package/dist/cli/{secrets-WXQ7XO5C.js → secrets-EN2HQCO3.js} +15 -15
  151. package/dist/cli/{secrets-FKMWBLHU.mjs → secrets-Z7CQSQGC.mjs} +6 -6
  152. package/dist/cli/{sessions-3YDTEDA5.mjs → sessions-I2H37OTJ.mjs} +6 -6
  153. package/dist/cli/sessions-RYQX3NDD.js +22 -0
  154. package/dist/cli/{settings-67TWLQ6E.js → settings-CTRAPFNZ.js} +85 -85
  155. package/dist/cli/{settings-JTPASUZN.mjs → settings-IYSC5PPQ.mjs} +12 -12
  156. package/dist/cli/{setup-VYNGXUJ6.mjs → setup-PU3HOVI3.mjs} +9 -9
  157. package/dist/cli/{setup-KUERQJUX.js → setup-XIN53GEW.js} +49 -49
  158. package/dist/cli/skills-576CX7DK.js +36 -0
  159. package/dist/cli/{skills-KI4KYHH6.mjs → skills-TYBML2ZO.mjs} +7 -7
  160. package/dist/cli/tools-EXMUWA3Z.js +56 -0
  161. package/dist/cli/{tools-UQDJS2RS.mjs → tools-ZVNE6M6J.mjs} +16 -16
  162. package/dist/cli/{update-7FQQUBOD.mjs → update-54WENBNT.mjs} +9 -9
  163. package/dist/cli/update-RAHETNL2.js +34 -0
  164. package/dist/cli/{views-MJK7JGZG.js → views-7L75EZOJ.js} +21 -21
  165. package/dist/cli/{views-JAM4MNNV.mjs → views-EUBB4ONT.mjs} +6 -6
  166. package/dist/cli/{workflow-AQPRIWQX.js → workflow-EZVYCR6Y.js} +17 -17
  167. package/dist/cli/{workflow-TQRV5FGO.mjs → workflow-GUKGFJ72.mjs} +7 -7
  168. package/dist/{client-BlLYQDNo.d.mts → client-D0uDBybG.d.mts} +1 -1
  169. package/dist/{client-DSQlkIDO.d.ts → client-DZTnAv4B.d.ts} +1 -1
  170. package/dist/{client-core-rX7n2H8U.d.mts → client-core-BhWf8Y1b.d.mts} +15 -2
  171. package/dist/{client-core-CDwapXy5.d.ts → client-core-og3AP1LL.d.ts} +15 -2
  172. package/dist/{compiler-manifest-BHNC4RL-.d.ts → compiler-manifest-Bes3OVA3.d.mts} +1 -1
  173. package/dist/{compiler-manifest-BHNC4RL-.d.mts → compiler-manifest-Bes3OVA3.d.ts} +1 -1
  174. package/dist/{errors-lhtIWG5Z.d.ts → errors-BJm4lLWc.d.ts} +1 -1
  175. package/dist/{errors-D7sPXrvB.d.mts → errors-Dc5r42ks.d.mts} +1 -1
  176. package/dist/{index-CQTBHXHr.d.ts → index-BfV7mRPF.d.ts} +1 -1
  177. package/dist/{index-NaDZq2xf.d.mts → index-DTkiz_Ur.d.mts} +1 -1
  178. package/dist/index.d.mts +7 -7
  179. package/dist/index.d.ts +7 -7
  180. package/dist/index.js +9 -9
  181. package/dist/index.mjs +6 -6
  182. package/dist/install-integrity.json +121 -112
  183. package/dist/plays/bundle-play-file.d.mts +3 -3
  184. package/dist/plays/bundle-play-file.d.ts +3 -3
  185. package/dist/plays/play-description.d.mts +2 -2
  186. package/dist/plays/play-description.d.ts +2 -2
  187. package/dist/plays/run-request.d.mts +2 -2
  188. package/dist/plays/run-request.d.ts +2 -2
  189. package/dist/release.d.mts +1 -1
  190. package/dist/release.d.ts +1 -1
  191. package/dist/release.js +2 -2
  192. package/dist/release.mjs +1 -1
  193. package/dist/server.d.mts +4 -4
  194. package/dist/server.d.ts +4 -4
  195. package/dist/server.js +5 -5
  196. package/dist/server.mjs +3 -3
  197. package/package.json +1 -1
  198. package/dist/cli/auth-Y2K2ZYYA.js +0 -43
  199. package/dist/cli/describe-LSOHOLFI.js +0 -49
  200. package/dist/cli/git-S7SWUZ3T.js +0 -25
  201. package/dist/cli/search-WERQBC6V.js +0 -32
  202. package/dist/cli/sessions-LXQ4Q6BS.js +0 -22
  203. package/dist/cli/skills-EFRLHY3F.js +0 -36
  204. package/dist/cli/tools-C3EIGFFP.js +0 -56
  205. package/dist/cli/update-KCY72RXH.js +0 -34
@@ -89,6 +89,7 @@ import {
89
89
  normalizePlayRunIntegrationMode,
90
90
  normalizePlayStatus,
91
91
  resolveStartPlayRunRequest,
92
+ playRunStartHeaders,
92
93
  runtimeSelectionHeaders,
93
94
  } from './plays/client-core';
94
95
  import { PRODUCT_NOTIFICATION_SLACK_OAUTH_SCOPES } from '../../shared_libs/product-notifications/contract.js';
@@ -2592,6 +2593,18 @@ export type WorkspacesNamespace = {
2592
2593
  serviceAccounts: WorkspaceServiceAccountsNamespace;
2593
2594
  };
2594
2595
 
2596
+ /** Recorded retained-result consumers, not counterfactual credit savings. */
2597
+ export type WorkspaceReuseResult = {
2598
+ org_id: string;
2599
+ reuse: {
2600
+ reused_result_calls: number;
2601
+ confirmed_runs: number;
2602
+ recorded_since: number;
2603
+ updated_at: number;
2604
+ coverage: 'confirmed_recorded_runs';
2605
+ } | null;
2606
+ };
2607
+
2595
2608
  /** One authenticated per-request usage event from `/api/v2/usage/events`. */
2596
2609
  export type BillingUsageEvent = {
2597
2610
  id: string | null;
@@ -2783,6 +2796,8 @@ export type BillingNamespace = {
2783
2796
  ) => Promise<BillingUsageEventsResult>;
2784
2797
  /** Read current billing usage, or look up one exact execution charge by request ID. */
2785
2798
  usage: (options?: BillingUsageOptions) => Promise<BillingUsageResult>;
2799
+ /** Recorded result reuse; historical or incomplete runs are excluded. */
2800
+ reuse: () => Promise<WorkspaceReuseResult>;
2786
2801
  /** Metronome-authored target catalog and current Contract projection. */
2787
2802
  targetPlans: (options?: {
2788
2803
  promoCode?: string;
@@ -3272,6 +3287,7 @@ export class DeeplineClient {
3272
3287
  usageEvent: (requestId) => this.getBillingUsageEvent(requestId),
3273
3288
  usageEvents: (options) => this.getBillingUsageEvents(options),
3274
3289
  usage: (options) => this.getBillingUsage(options),
3290
+ reuse: () => this.http.get<WorkspaceReuseResult>('/api/v2/usage/reuse'),
3275
3291
  targetPlans: (options) => this.getTargetBillingPlans(options),
3276
3292
  targetStatus: () => this.getTargetBillingStatus(),
3277
3293
  autoRecharge: {
@@ -3556,9 +3572,7 @@ export class DeeplineClient {
3556
3572
 
3557
3573
  /** The view's share links, newest first. Their tokens are never returned. */
3558
3574
  async listViewShareLinks(id: string): Promise<{ links: ViewShareLink[] }> {
3559
- return await this.http.get(
3560
- `/api/v2/views/${encodeURIComponent(id)}/links`,
3561
- );
3575
+ return await this.http.get(`/api/v2/views/${encodeURIComponent(id)}/links`);
3562
3576
  }
3563
3577
 
3564
3578
  /**
@@ -3587,7 +3601,10 @@ export class DeeplineClient {
3587
3601
  }
3588
3602
 
3589
3603
  /** Revoke a share link. It stops opening the view at once. */
3590
- async revokeViewShareLink(id: string, linkId: string): Promise<ViewShareLink> {
3604
+ async revokeViewShareLink(
3605
+ id: string,
3606
+ linkId: string,
3607
+ ): Promise<ViewShareLink> {
3591
3608
  return await this.http.delete(
3592
3609
  `/api/v2/views/${encodeURIComponent(id)}/links/${encodeURIComponent(linkId)}`,
3593
3610
  );
@@ -4066,7 +4083,7 @@ export class DeeplineClient {
4066
4083
  options,
4067
4084
  );
4068
4085
  const bodyJson = JSON.stringify(prepared.body);
4069
- const runtimeHeaders = runtimeSelectionHeaders(
4086
+ const runtimeHeaders = playRunStartHeaders(
4070
4087
  resolved.runtime,
4071
4088
  this.environment,
4072
4089
  );
@@ -433,3 +433,5 @@ export type {
433
433
  RunToolReceiptResult,
434
434
  RunToolReceiptsResponse,
435
435
  } from './runs/receipts';
436
+
437
+ export type { WorkspaceReuseResult } from './client-core.js';
@@ -25,6 +25,7 @@ import {
25
25
  type PlayRunStartOptions,
26
26
  } from './run-request';
27
27
  import {
28
+ EXPERIMENT_SWITCHES_HEADER,
28
29
  RUNTIME_ENVIRONMENT_TOKEN_HEADER,
29
30
  RETAINED_PIPELINE_RECEIVERS_HEADER,
30
31
  } from '../../../shared_libs/play-runtime/coordinator-headers.js';
@@ -230,6 +231,22 @@ export function runtimeSelectionHeaders(
230
231
  };
231
232
  }
232
233
 
234
+ /**
235
+ * Headers for a Play run start: the runtime selection credential plus, for
236
+ * internal measurement only, `DEEPLINE_EXPERIMENT_SWITCHES` forwarded verbatim.
237
+ * The server validates and authorizes it and rejects a bad or unauthorized
238
+ * value; the SDK never interprets it.
239
+ */
240
+ export function playRunStartHeaders(
241
+ runtime: PlayRunRuntimeSelection | undefined,
242
+ env: ClientEnvironment,
243
+ ): Record<string, string> | undefined {
244
+ const headers = runtimeSelectionHeaders(runtime, env);
245
+ const experimentSwitches = env.DEEPLINE_EXPERIMENT_SWITCHES?.trim();
246
+ if (!experimentSwitches) return headers;
247
+ return { ...headers, [EXPERIMENT_SWITCHES_HEADER]: experimentSwitches };
248
+ }
249
+
233
250
  function normalizeTestPolicyOverrides(
234
251
  value: unknown,
235
252
  source: string,
@@ -327,7 +344,7 @@ export class PlayClient {
327
344
  options?: PlayRunStartOptions,
328
345
  ): Promise<PlayRunStart> {
329
346
  const resolved = resolveStartPlayRunRequest(request, this.environment);
330
- const headers = runtimeSelectionHeaders(resolved.runtime, this.environment);
347
+ const headers = playRunStartHeaders(resolved.runtime, this.environment);
331
348
  return startPlayRun(
332
349
  this.http,
333
350
  resolved.request,
@@ -205,7 +205,7 @@ export const SDK_RELEASE = {
205
205
  // getters keep their established compatibility behavior.
206
206
  // 0.3.1 deprecated the legacy `deepline enrich` command in favor of Plays.
207
207
  // 0.3.90 is the first deliberately versioned SDK release for API v3.
208
- version: '0.3.537',
208
+ version: '0.3.539',
209
209
  updateSummary: {
210
210
  introducedIn: '0.3.90',
211
211
  summary:
@@ -15,6 +15,21 @@ export const RUN_WATCH_POLL_INTERVAL_MS = 2_000;
15
15
  // two-second steady-state cadence below.
16
16
  const RUN_WATCH_STARTUP_POLL_INTERVAL_MS = 300;
17
17
  const RUN_WATCH_STARTUP_WINDOW_MS = 6_000;
18
+ /**
19
+ * Server-held wait per snapshot request once the startup window has passed:
20
+ * the run route answers as soon as the run is terminal, or after this bound,
21
+ * so terminal detection no longer waits out the 2 s cadence. 0 (off) keeps
22
+ * client-side polling only. Used only by watchers that defer logs, whose
23
+ * progress output does not depend on intermediate snapshots. Lands off.
24
+ */
25
+ export const RUN_WATCH_SERVER_WAIT_MS = 0;
26
+ /**
27
+ * Use the server-held wait from the first snapshot request instead of only
28
+ * after the startup window, so a short run is seen as soon as it is terminal
29
+ * rather than on the next 300 ms poll. Same watchers (deferred logs) and the
30
+ * same bounded server wait. Off.
31
+ */
32
+ export const RUN_WATCH_SERVER_WAIT_FROM_START = false;
18
33
  export const TERMINAL_LOG_PROJECTION_RETRY_LIMIT = 3;
19
34
 
20
35
  type WatchHttp = {
@@ -217,11 +232,23 @@ export async function* watchRunEvents(
217
232
  const poll = ++pollCount;
218
233
  // Keep terminal detection responsive through the sandbox startup window,
219
234
  // then reduce snapshot reads for runs that continue beyond it.
235
+ const pastStartup =
236
+ pollStartedAt - watchStartedAt >= RUN_WATCH_STARTUP_WINDOW_MS;
237
+ const serverWaitMs =
238
+ options.pollIntervalMs === undefined &&
239
+ options.deferLogs &&
240
+ (pastStartup || RUN_WATCH_SERVER_WAIT_FROM_START) &&
241
+ RUN_WATCH_SERVER_WAIT_MS > 0
242
+ ? RUN_WATCH_SERVER_WAIT_MS
243
+ : 0;
244
+ // A held request already waited server-side; poll again immediately.
220
245
  const pollIntervalMs =
221
246
  options.pollIntervalMs ??
222
- (pollStartedAt - watchStartedAt < RUN_WATCH_STARTUP_WINDOW_MS
223
- ? RUN_WATCH_STARTUP_POLL_INTERVAL_MS
224
- : RUN_WATCH_POLL_INTERVAL_MS);
247
+ (serverWaitMs > 0
248
+ ? 0
249
+ : pastStartup
250
+ ? RUN_WATCH_POLL_INTERVAL_MS
251
+ : RUN_WATCH_STARTUP_POLL_INTERVAL_MS);
225
252
  let snapshot: PlayRunLiveSnapshot;
226
253
  let terminalStatus: Record<string, unknown> | undefined;
227
254
  let responseStatus: number | undefined;
@@ -242,7 +269,9 @@ export async function* watchRunEvents(
242
269
  }
243
270
  };
244
271
  try {
245
- const response = await http.get<unknown>(path, {
272
+ const response = await http.get<unknown>(
273
+ serverWaitMs > 0 ? `${path}&waitForTerminalMs=${serverWaitMs}` : path,
274
+ {
246
275
  signal,
247
276
  ...(options.onPoll
248
277
  ? {
@@ -72,7 +72,7 @@ export type BillingEntitlements = {
72
72
 
73
73
  /** `GET`/`POST /api/v2/billing/included-compute`. */
74
74
  export type IncludedCompute = {
75
- /** `unavailable`: the workspace is outside the November pricing rollout. */
75
+ /** `unavailable`: returned only by older deployments (retired November rollout). */
76
76
  status: 'on' | 'off' | 'unavailable';
77
77
  /** Credits per standard-equivalent sandbox minute; null at provider cost. */
78
78
  credits_per_minute: number | null;
@@ -1935,5 +1935,23 @@
1935
1935
  "runTimeoutMs": 800000,
1936
1936
  "failureAlert": "vercel_route_wrapper",
1937
1937
  "domainReportRequired": true
1938
+ },
1939
+ {
1940
+ "id": "convex.play-result-reuse-fold",
1941
+ "name": "Play result reuse summary fold",
1942
+ "scheduler": "convex_scheduled_mutation",
1943
+ "cadence": "runAfter(0) after confirmed terminal run summaries; lease-owned continuation",
1944
+ "timezone": "UTC",
1945
+ "source": "packages/convex/playRunReuse.ts",
1946
+ "locator": "drainDeltas",
1947
+ "owner": "platform",
1948
+ "criticality": "reporting",
1949
+ "purpose": "Fold confirmed terminal Play reuse contributions into a workspace total through the existing counter journal.",
1950
+ "successDefinition": "A bounded journal page applies and deletes atomically, or the owner observes no pending contributions.",
1951
+ "failureDefinition": "The native scheduled mutation fails; its unapplied journal contributions remain available to the owning drain.",
1952
+ "startGraceMs": 120000,
1953
+ "runTimeoutMs": 120000,
1954
+ "failureAlert": "convex_native_scheduled_function",
1955
+ "domainReportRequired": true
1938
1956
  }
1939
1957
  ]
@@ -148,6 +148,7 @@ export type RuntimeStatusUpdate = {
148
148
  attempt: number;
149
149
  invocationSeq: number;
150
150
  segmentId: string;
151
+ reusableResultCalls?: number;
151
152
  logicalCalls: number;
152
153
  providerRequests: number;
153
154
  provider429s: number;
@@ -3115,10 +3116,17 @@ export async function applyRowUpdatesViaAppRuntime(
3115
3116
  ? Omit<T & { action: 'apply_row_updates' }, 'action'>
3116
3117
  : never,
3117
3118
  ): Promise<void> {
3119
+ // The receiver reads `contractSnapshot` only to derive a sheet contract when
3120
+ // none is sent. With `sheetContract` present it is dead weight, and a
3121
+ // hydrated pipeline that inlines prebuilt Plays can alone exceed the ingress
3122
+ // budget, failing every checkpoint whatever the row size.
3123
+ const envelope = input.sheetContract
3124
+ ? { ...input, contractSnapshot: undefined }
3125
+ : input;
3118
3126
  const requestForUpdates = (updates: typeof input.updates) =>
3119
3127
  ({
3120
3128
  action: 'apply_row_updates',
3121
- ...input,
3129
+ ...envelope,
3122
3130
  updates,
3123
3131
  }) as Extract<RuntimeApiRequest, { action: 'apply_row_updates' }>;
3124
3132
  if (input.updates.length === 0) {
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Prebaked runner image contract (Modal published image).
3
+ *
4
+ * The play-runner bundle is static across runs of one deploy, yet every run
5
+ * used to gzip and upload it inside the payload envelope. A sandbox image that
6
+ * already carries the bundle at a path keyed by the bundle's own SHA-256 lets
7
+ * the launcher upload only the per-run config and Play artifact.
8
+ *
9
+ * Trust model: nothing here is assumed. The launcher only plans a baked run
10
+ * when the expected hash (an operator pin, or in self mode the hash of this
11
+ * worker's own bundle) equals the hash of the bundle this very launcher would
12
+ * otherwise upload, and Modal resolved the image named after it. It verifies,
13
+ * inside the acquired sandbox and before any command that could start the
14
+ * runner, that the file exists and hashes to that value. Any other outcome
15
+ * (unset, stale, absent file, mismatched bytes, probe failure) keeps the
16
+ * existing full-upload path. No wire or schema version changes: the envelope
17
+ * field set is unchanged and `runnerCode: ''` simply means "already on disk".
18
+ */
19
+ import { createHash } from 'node:crypto';
20
+ import { gzipSync } from 'node:zlib';
21
+
22
+ /**
23
+ * Worker setting. Values:
24
+ * - a 64-hex SHA-256: exact pin (the original operator opt-in, unchanged);
25
+ * - `self`: look up the image named after this worker's own bundle hash;
26
+ * - `off`: disabled, whatever the default below says (the kill switch);
27
+ * - unset: `self` when `BAKED_RUNNER_SELF_VERSIONED` is true, else disabled.
28
+ * Anything else enables nothing.
29
+ */
30
+ export const BAKED_RUNNER_HASH_ENV = 'DEEPLINE_BAKED_RUNNER_HASH';
31
+ export const BAKED_RUNNER_SELF_MODE = 'self';
32
+ export const BAKED_RUNNER_OFF_MODE = 'off';
33
+
34
+ /**
35
+ * Release-owned enable for self-versioned baked runner images. While false, an
36
+ * unset worker setting keeps today's full upload, and the Production release
37
+ * and Preview `runtime up` do not publish. Flipping it to true makes, in the
38
+ * same release, the release publish `deepline-play-runner:<own bundle hash>`
39
+ * before its workers roll and those workers look that image up. Read by
40
+ * `.github/workflows/production-release.yml` and `scripts/runtime-target.ts`.
41
+ */
42
+ export const BAKED_RUNNER_SELF_VERSIONED: boolean = false;
43
+ export const BAKED_RUNNER_ROOT = '/opt/deepline/runner';
44
+ export const BAKED_RUNNER_FILE_NAME = 'play-runner.cjs';
45
+
46
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
47
+
48
+ export function runnerBundleSha256(bundle: string): string {
49
+ return createHash('sha256').update(bundle, 'utf-8').digest('hex');
50
+ }
51
+
52
+ let lastHashed: { bundle: string; hash: string } | null = null;
53
+
54
+ /**
55
+ * The bundle is cached per worker process, so the same string is hashed run
56
+ * after run. Single-entry memo by content: a changed bundle recomputes.
57
+ */
58
+ export function runnerBundleSha256Memoized(bundle: string): string {
59
+ if (lastHashed && lastHashed.bundle === bundle) return lastHashed.hash;
60
+ const hash = runnerBundleSha256(bundle);
61
+ lastHashed = { bundle, hash };
62
+ return hash;
63
+ }
64
+
65
+ export function bakedRunnerPath(hash: string): string {
66
+ if (!SHA256_HEX.test(hash)) {
67
+ throw new Error('Baked runner hash must be 64 lowercase hex characters.');
68
+ }
69
+ return `${BAKED_RUNNER_ROOT}/${hash}/${BAKED_RUNNER_FILE_NAME}`;
70
+ }
71
+
72
+ export type BakedRunnerPlan =
73
+ | { status: 'disabled' }
74
+ | { status: 'invalid_config' }
75
+ | { status: 'stale_config'; configuredHash: string; bundleHash: string }
76
+ | { status: 'expected'; hash: string; path: string };
77
+
78
+ /**
79
+ * Decide whether this launch should try the baked path. `expected` is only a
80
+ * hypothesis that still has to be verified in the sandbox.
81
+ */
82
+ export function planBakedRunner(input: {
83
+ configuredHash: string | null | undefined;
84
+ bundle: string;
85
+ }): BakedRunnerPlan {
86
+ const configured = input.configuredHash?.trim().toLowerCase() ?? '';
87
+ if (!configured) return { status: 'disabled' };
88
+ if (!SHA256_HEX.test(configured)) return { status: 'invalid_config' };
89
+ const bundleHash = runnerBundleSha256Memoized(input.bundle);
90
+ if (bundleHash !== configured) {
91
+ return { status: 'stale_config', configuredHash: configured, bundleHash };
92
+ }
93
+ return {
94
+ status: 'expected',
95
+ hash: configured,
96
+ path: bakedRunnerPath(configured),
97
+ };
98
+ }
99
+
100
+ /** The configured hash when it is well formed; malformed config enables nothing. */
101
+ export function configuredBakedRunnerHash(
102
+ env: NodeJS.ProcessEnv = process.env,
103
+ ): string | null {
104
+ const configured = env[BAKED_RUNNER_HASH_ENV]?.trim().toLowerCase() ?? '';
105
+ return SHA256_HEX.test(configured) ? configured : null;
106
+ }
107
+
108
+ export type BakedRunnerMode =
109
+ | { kind: 'disabled' }
110
+ | { kind: 'pin'; hash: string }
111
+ | { kind: 'self' };
112
+
113
+ /** How this worker chooses its baked runner image (see BAKED_RUNNER_HASH_ENV). */
114
+ export function bakedRunnerMode(
115
+ env: NodeJS.ProcessEnv = process.env,
116
+ selfVersionedByDefault: boolean = BAKED_RUNNER_SELF_VERSIONED,
117
+ ): BakedRunnerMode {
118
+ const configured = env[BAKED_RUNNER_HASH_ENV]?.trim().toLowerCase() ?? '';
119
+ if (configured === BAKED_RUNNER_OFF_MODE) return { kind: 'disabled' };
120
+ if (configured === BAKED_RUNNER_SELF_MODE) return { kind: 'self' };
121
+ if (SHA256_HEX.test(configured)) return { kind: 'pin', hash: configured };
122
+ if (!configured && selfVersionedByDefault) return { kind: 'self' };
123
+ return { kind: 'disabled' };
124
+ }
125
+
126
+ /**
127
+ * The hash whose published image this launch should look up, or null for
128
+ * today's path. Disabled and pinned modes never wait on the bundle; self mode
129
+ * hashes this worker's own bundle, so its image can never be stale. A bundle
130
+ * that cannot be read yields null here: the launch then takes today's path and
131
+ * the build failure still surfaces where the payload is staged.
132
+ */
133
+ export async function bakedRunnerLookupHash(input: {
134
+ /** Called only in self mode, so a disabled or pinned launch reads nothing. */
135
+ bundle: () => Promise<string>;
136
+ mode?: BakedRunnerMode;
137
+ }): Promise<string | null> {
138
+ const mode = input.mode ?? bakedRunnerMode();
139
+ if (mode.kind === 'disabled') return null;
140
+ if (mode.kind === 'pin') return mode.hash;
141
+ let bundle: string;
142
+ try {
143
+ bundle = await input.bundle();
144
+ } catch {
145
+ return null;
146
+ }
147
+ return bundle.length > 0 ? runnerBundleSha256Memoized(bundle) : null;
148
+ }
149
+
150
+ const MODAL_IMAGE_PRESENT_TTL_MS = 10 * 60_000;
151
+ const MODAL_IMAGE_ABSENT_TTL_MS = 30_000;
152
+
153
+ /**
154
+ * Modal published-image name for a runner hash. Modal object names must be
155
+ * shorter than 64 characters, so the tag is a 32-hex (128-bit) prefix; the
156
+ * full hash is still what the sandbox verifies before the file is used.
157
+ */
158
+ export const BAKED_MODAL_IMAGE_NAME = 'deepline-play-runner';
159
+
160
+ export function bakedModalImageRef(hash: string): string {
161
+ if (!SHA256_HEX.test(hash)) {
162
+ throw new Error('Baked runner hash must be 64 lowercase hex characters.');
163
+ }
164
+ return `${BAKED_MODAL_IMAGE_NAME}:${hash.slice(0, 32)}`;
165
+ }
166
+
167
+ /** Below Linux's 128 KiB single-argument limit for each `/bin/sh -c` RUN. */
168
+ const MODAL_RUN_CHUNK_CHARS = 96 * 1024;
169
+
170
+ /**
171
+ * Dockerfile commands that bake the runner into a Modal-built image. Modal's
172
+ * JS SDK cannot COPY from a local build context, so the gzipped bundle is
173
+ * carried as base64 in bounded RUN chunks and reassembled at
174
+ * /opt/deepline/runner/<sha256>/play-runner.cjs (file 0444, directory 0555),
175
+ * and the build fails unless the reassembled bytes hash to the bundle's SHA-256.
176
+ * The commands are a pure function of the bundle, so a rebuild is a cache hit.
177
+ */
178
+ export function bakedRunnerModalDockerfileCommands(bundle: string): string[] {
179
+ if (bundle.length === 0) throw new Error('Runner bundle is empty.');
180
+ const hash = runnerBundleSha256(bundle);
181
+ const encoded = gzipSync(Buffer.from(bundle, 'utf-8'), { level: 9 }).toString(
182
+ 'base64',
183
+ );
184
+ const staged = '/tmp/deepline-play-runner.gz.b64';
185
+ const commands = [`RUN rm -f ${staged}`];
186
+ for (
187
+ let offset = 0;
188
+ offset < encoded.length;
189
+ offset += MODAL_RUN_CHUNK_CHARS
190
+ ) {
191
+ commands.push(
192
+ `RUN printf '%s' '${encoded.slice(offset, offset + MODAL_RUN_CHUNK_CHARS)}' >> ${staged}`,
193
+ );
194
+ }
195
+ const dir = `${BAKED_RUNNER_ROOT}/${hash}`;
196
+ commands.push(
197
+ [
198
+ 'RUN set -eu',
199
+ `base64 -d < ${staged} | gzip -dc > /tmp/play-runner.cjs`,
200
+ `echo "${hash} /tmp/play-runner.cjs" | sha256sum -c -`,
201
+ `install -d -m 0755 "${dir}"`,
202
+ `install -m 0444 /tmp/play-runner.cjs "${dir}/${BAKED_RUNNER_FILE_NAME}"`,
203
+ `chmod 0555 "${dir}"`,
204
+ `rm -f /tmp/play-runner.cjs ${staged}`,
205
+ ].join('; '),
206
+ );
207
+ return commands;
208
+ }
209
+
210
+ /**
211
+ * The published image id, or null only when Modal says the name does not
212
+ * exist. Any other lookup failure (auth, network, throttling) is rethrown:
213
+ * a publisher must not read it as "absent" and rebuild over a live image.
214
+ */
215
+ export async function existingPublishedModalImageId(
216
+ lookup: () => Promise<{ imageId: string }>,
217
+ ): Promise<string | null> {
218
+ try {
219
+ return (await lookup()).imageId;
220
+ } catch (error) {
221
+ if (error instanceof Error && error.name === 'NotFoundError') return null;
222
+ throw error;
223
+ }
224
+ }
225
+
226
+ type ModalImageLookup<TImage> = { image: TImage | null; expiresAtMs: number };
227
+ const modalImageCaches = new WeakMap<
228
+ object,
229
+ Map<string, Promise<ModalImageLookup<unknown>>>
230
+ >();
231
+ const MODAL_IMAGE_LOOKUP_TIMEOUT_MS = 5_000;
232
+
233
+ /**
234
+ * Pick the image a new Modal sandbox is created from. The published baked
235
+ * image is chosen only when an operator configured a hash AND Modal resolves
236
+ * that exact published name; absence, any lookup failure, or a slow lookup
237
+ * keeps the profile's existing image. An operator-chosen runner image
238
+ * (DEEPLINE_MODAL_RUNNER_IMAGE) keeps its precedence: the baked image never
239
+ * replaces it, and the result says so (`skipped`) instead of silently. The runner file inside it is still
240
+ * verified in the sandbox before use, so a wrong image is harmless.
241
+ *
242
+ * Cached per Modal client (an image handle is bound to its client) for the
243
+ * 10 minutes when present and 30 seconds when absent; concurrent callers share
244
+ * one lookup.
245
+ */
246
+ export async function resolveModalRunnerImage<TImage>(input: {
247
+ client: object;
248
+ configuredHash: string | null;
249
+ /** DEEPLINE_MODAL_RUNNER_IMAGE chose the default image. */
250
+ explicitImage?: boolean;
251
+ defaultImage: () => TImage;
252
+ lookupPublished: (ref: string) => Promise<TImage>;
253
+ now?: () => number;
254
+ timeoutMs?: number;
255
+ }): Promise<{
256
+ image: TImage;
257
+ baked: boolean;
258
+ ref: string | null;
259
+ skipped?: 'explicit_runner_image';
260
+ }> {
261
+ if (!input.configuredHash) {
262
+ return { image: input.defaultImage(), baked: false, ref: null };
263
+ }
264
+ if (input.explicitImage) {
265
+ return {
266
+ image: input.defaultImage(),
267
+ baked: false,
268
+ ref: null,
269
+ skipped: 'explicit_runner_image',
270
+ };
271
+ }
272
+ const ref = bakedModalImageRef(input.configuredHash);
273
+ const now = input.now ?? Date.now;
274
+ let cache = modalImageCaches.get(input.client);
275
+ if (!cache) {
276
+ cache = new Map();
277
+ modalImageCaches.set(input.client, cache);
278
+ }
279
+ let entry: ModalImageLookup<TImage> | null = null;
280
+ const cached = cache.get(ref) as
281
+ | Promise<ModalImageLookup<TImage>>
282
+ | undefined;
283
+ if (cached) {
284
+ entry = await cached;
285
+ if (entry.expiresAtMs <= now()) entry = null;
286
+ }
287
+ if (!entry) {
288
+ let timer: ReturnType<typeof setTimeout> | undefined;
289
+ const absent = (): ModalImageLookup<TImage> => ({
290
+ image: null,
291
+ expiresAtMs: now() + MODAL_IMAGE_ABSENT_TTL_MS,
292
+ });
293
+ const lookup = Promise.race([
294
+ // A synchronous throw (for example a client without named images) is
295
+ // a failed lookup like any other, never a failed launch.
296
+ Promise.resolve()
297
+ .then(() => input.lookupPublished(ref))
298
+ .then(
299
+ (image): ModalImageLookup<TImage> => ({
300
+ image,
301
+ expiresAtMs: now() + MODAL_IMAGE_PRESENT_TTL_MS,
302
+ }),
303
+ absent,
304
+ ),
305
+ new Promise<ModalImageLookup<TImage>>((resolve) => {
306
+ timer = setTimeout(
307
+ () => resolve(absent()),
308
+ input.timeoutMs ?? MODAL_IMAGE_LOOKUP_TIMEOUT_MS,
309
+ );
310
+ }),
311
+ ]).finally(() => {
312
+ if (timer) clearTimeout(timer);
313
+ });
314
+ cache.set(ref, lookup);
315
+ entry = await lookup;
316
+ }
317
+ return entry.image === null
318
+ ? { image: input.defaultImage(), baked: false, ref }
319
+ : { image: entry.image, baked: true, ref };
320
+ }
321
+
322
+ const VERIFICATION_PREFIX = 'baked-runner:';
323
+
324
+ /**
325
+ * Runs inside the sandbox with Node alone. Arguments: absolute path, expected
326
+ * hash. Prints exactly one verdict line and always exits 0, so a probe failure
327
+ * is distinguishable from a verdict (no verdict line means "not verified").
328
+ */
329
+ export function buildBakedRunnerVerifySource(): string {
330
+ return `const fs=require('node:fs');const c=require('node:crypto');let r='missing';try{r=c.createHash('sha256').update(fs.readFileSync(process.argv[1])).digest('hex')===process.argv[2]?'ok':'mismatch'}catch(e){}console.log('${VERIFICATION_PREFIX}'+r);`;
331
+ }
332
+
333
+ /**
334
+ * `late`: no verdict line within the launcher's bound while the stream was
335
+ * still open. The in-sandbox guard alone decides then (it runs the baked file
336
+ * only on `ok`), and the detached-runner readiness check proves the runner
337
+ * live or recovers the attempt. A fallback on `late` could stop a runner that
338
+ * is already running.
339
+ */
340
+ export type BakedRunnerVerdict =
341
+ | 'ok'
342
+ | 'mismatch'
343
+ | 'missing'
344
+ | 'no_verdict'
345
+ | 'late';
346
+
347
+ /** Whether the launcher must start today's full upload for this verdict. */
348
+ export function bakedVerdictRequiresFallback(
349
+ verdict: BakedRunnerVerdict,
350
+ ): boolean {
351
+ return verdict !== 'ok' && verdict !== 'late';
352
+ }
353
+
354
+ /** Anything but an exact `ok` verdict is "not verified". */
355
+ export function parseBakedRunnerVerdict(stdout: string): BakedRunnerVerdict {
356
+ const line = stdout
357
+ .split(/\r?\n/)
358
+ .map((value) => value.trim())
359
+ .find((value) => value.startsWith(VERIFICATION_PREFIX));
360
+ const verdict = line?.slice(VERIFICATION_PREFIX.length);
361
+ return verdict === 'ok' || verdict === 'mismatch' || verdict === 'missing'
362
+ ? verdict
363
+ : 'no_verdict';
364
+ }
365
+
366
+ /**
367
+ * The launch-time decision. Resolves to a plan only when the operator enabled
368
+ * the baked path and this deploy's bundle hashes to the configured value; a
369
+ * stale or disabled configuration returns undefined and leaves the full upload
370
+ * untouched. `onStale` lets the caller log the skipped, otherwise silent, case.
371
+ */
372
+ export async function bakedRunnerPlanForLaunch(input: {
373
+ bundlePromise: Promise<string>;
374
+ configuredHash?: string | null;
375
+ onStale?: (
376
+ plan: Extract<BakedRunnerPlan, { status: 'stale_config' }>,
377
+ ) => void;
378
+ }): Promise<{ hash: string; path: string } | undefined> {
379
+ const configuredHash =
380
+ input.configuredHash === undefined
381
+ ? await bakedRunnerLookupHash({ bundle: () => input.bundlePromise })
382
+ : input.configuredHash;
383
+ if (!configuredHash) return undefined;
384
+ const plan = planBakedRunner({
385
+ configuredHash,
386
+ bundle: await input.bundlePromise,
387
+ });
388
+ if (plan.status === 'stale_config') input.onStale?.(plan);
389
+ return plan.status === 'expected'
390
+ ? { hash: plan.hash, path: plan.path }
391
+ : undefined;
392
+ }