@opengeni/worker-bundle 0.20.1 → 0.22.0-canary.0

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 (189) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +66 -0
  42. package/dist/activities/image-generation-references.d.ts +2 -0
  43. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  44. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  45. package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
  46. package/dist/activities/knowledge-source-sync.d.ts +33 -1
  47. package/dist/activities/mcp-credentials.d.ts +9 -3
  48. package/dist/activities/open-suffix-resume.d.ts +77 -0
  49. package/dist/activities/packs.d.ts +3 -11
  50. package/dist/activities/parent-wake.d.ts +19 -0
  51. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  52. package/dist/activities/retained-screenshots.d.ts +1 -1
  53. package/dist/activities/rig-verification.d.ts +1 -1
  54. package/dist/activities/run-input.d.ts +16 -7
  55. package/dist/activities/sandbox-images.d.ts +1 -14
  56. package/dist/activities/sandbox-lease.d.ts +21 -3
  57. package/dist/activities/scheduled-tasks.d.ts +47 -0
  58. package/dist/activities/types.d.ts +23 -2
  59. package/dist/activities/video-media-validation.d.ts +1 -1
  60. package/dist/activities/video-output-retention.d.ts +1 -2
  61. package/dist/activities/xai-auth.d.ts +3 -0
  62. package/dist/{activities-control-SMKF2OBE.js → activities-control-DKG22ONJ.js} +2946 -549
  63. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  64. package/dist/activities-control.d.ts +6 -2
  65. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  66. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  67. package/dist/activities.d.ts +7 -3
  68. package/dist/artifact-materializer-entry.js +41 -22
  69. package/dist/artifact-materializer-entry.js.map +1 -1
  70. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  71. package/dist/chunk-CE7TPKBS.js.map +1 -0
  72. package/dist/chunk-CNYGVRKF.js +4698 -0
  73. package/dist/chunk-CNYGVRKF.js.map +1 -0
  74. package/dist/connection-provider-use.d.ts +18 -0
  75. package/dist/editable-artifact-materializer.d.ts +4 -3
  76. package/dist/github-rest-mcp.d.ts +26 -0
  77. package/dist/index.d.ts +10 -2
  78. package/dist/index.js +58 -14
  79. package/dist/index.js.map +1 -1
  80. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  81. package/dist/model-context-contributions.d.ts +8 -4
  82. package/dist/observability-metrics.d.ts +63 -4
  83. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  84. package/dist/personal-github-git-credentials.d.ts +9 -0
  85. package/dist/pr-review-credentials.d.ts +6 -0
  86. package/dist/sandbox-archive-storage.d.ts +45 -0
  87. package/dist/sandbox-resume.d.ts +65 -6
  88. package/dist/sandbox-routing.d.ts +38 -2
  89. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  90. package/dist/workflow-bundle.js +87 -28
  91. package/dist/workflows/activities.d.ts +1 -0
  92. package/dist/workflows/automations.d.ts +6 -0
  93. package/dist/workflows/document-index.d.ts +1 -0
  94. package/dist/workflows.d.ts +1 -0
  95. package/package.json +17 -17
  96. package/src/activities/agent-turn/admission.ts +292 -0
  97. package/src/activities/agent-turn/agent-build.ts +802 -0
  98. package/src/activities/agent-turn/claim.ts +590 -0
  99. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  100. package/src/activities/agent-turn/codex.ts +94 -0
  101. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  102. package/src/activities/agent-turn/credential-leases.ts +240 -0
  103. package/src/activities/agent-turn/errors.ts +1068 -0
  104. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  105. package/src/activities/agent-turn/file-resources.ts +227 -0
  106. package/src/activities/agent-turn/finalization.ts +754 -0
  107. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  108. package/src/activities/agent-turn/governance-model.ts +465 -0
  109. package/src/activities/agent-turn/history-sink.ts +139 -0
  110. package/src/activities/agent-turn/history.ts +200 -0
  111. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  112. package/src/activities/agent-turn/model-usage.ts +823 -0
  113. package/src/activities/agent-turn/quiescence.ts +353 -0
  114. package/src/activities/agent-turn/run-credentials.ts +761 -0
  115. package/src/activities/agent-turn/run.ts +1530 -0
  116. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  117. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  118. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  119. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  120. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  121. package/src/activities/agent-turn/tool-environment.ts +729 -0
  122. package/src/activities/agent-turn/tool-policy.ts +216 -0
  123. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  124. package/src/activities/agent-turn/turn-context.ts +281 -0
  125. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  126. package/src/activities/agent-turn.ts +12 -12575
  127. package/src/activities/api-integrations.ts +3 -0
  128. package/src/activities/automations.ts +214 -0
  129. package/src/activities/codemode-dispatcher.ts +12 -1
  130. package/src/activities/common.ts +1 -5
  131. package/src/activities/connector-attachments.ts +168 -0
  132. package/src/activities/context-compaction.ts +18 -0
  133. package/src/activities/documents.ts +6 -4
  134. package/src/activities/environment.ts +151 -55
  135. package/src/activities/generated-images.ts +26 -11
  136. package/src/activities/git-credential-renewal.ts +13 -3
  137. package/src/activities/goals.ts +85 -19
  138. package/src/activities/google-drive-provider.ts +178 -0
  139. package/src/activities/google-drive-publication.ts +938 -0
  140. package/src/activities/image-generation-references.ts +11 -2
  141. package/src/activities/incident-telemetry-authority.ts +327 -0
  142. package/src/activities/incident-telemetry-preflight.ts +317 -0
  143. package/src/activities/knowledge-source-sync-driver.ts +23 -0
  144. package/src/activities/knowledge-source-sync.ts +556 -40
  145. package/src/activities/mcp-credentials.ts +191 -17
  146. package/src/activities/open-suffix-resume.ts +422 -0
  147. package/src/activities/packs.ts +12 -60
  148. package/src/activities/parent-wake.ts +64 -14
  149. package/src/activities/retained-screenshot-reaper.ts +6 -3
  150. package/src/activities/retained-screenshots.ts +15 -47
  151. package/src/activities/rig-verification.ts +1 -1
  152. package/src/activities/run-input.ts +128 -136
  153. package/src/activities/sandbox-images.ts +7 -166
  154. package/src/activities/sandbox-lease.ts +406 -15
  155. package/src/activities/scheduled-tasks.ts +2103 -411
  156. package/src/activities/session-state.ts +10 -2
  157. package/src/activities/types.ts +32 -2
  158. package/src/activities/video-media-validation.ts +3 -3
  159. package/src/activities/video-output-retention.ts +2 -57
  160. package/src/activities/xai-auth.ts +8 -0
  161. package/src/activities-control.ts +2 -0
  162. package/src/activities.ts +3 -0
  163. package/src/activity-services.ts +13 -4
  164. package/src/connection-provider-use.ts +36 -0
  165. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  166. package/src/editable-artifact-materializer.ts +29 -18
  167. package/src/github-rest-mcp.ts +713 -0
  168. package/src/http.ts +16 -6
  169. package/src/index.ts +40 -5
  170. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  171. package/src/model-context-contributions.ts +33 -10
  172. package/src/observability-metrics.ts +357 -0
  173. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  174. package/src/personal-github-git-credentials.ts +331 -0
  175. package/src/pr-review-credentials.ts +163 -0
  176. package/src/sandbox-archive-storage.ts +159 -0
  177. package/src/sandbox-resume.ts +449 -63
  178. package/src/sandbox-routing.ts +314 -16
  179. package/src/scheduled-alert-occurrence.ts +176 -0
  180. package/src/workflows/activities.ts +18 -2
  181. package/src/workflows/automations.ts +11 -0
  182. package/src/workflows/session.ts +13 -3
  183. package/src/workflows.ts +1 -0
  184. package/dist/activities-control-SMKF2OBE.js.map +0 -1
  185. package/dist/activities-turn-IDS3WEHA.js +0 -16532
  186. package/dist/activities-turn-IDS3WEHA.js.map +0 -1
  187. package/dist/chunk-N5TJIFCE.js.map +0 -1
  188. package/dist/chunk-P6Z2SLAA.js +0 -3092
  189. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -0,0 +1,358 @@
1
+ import {
2
+ readActiveSandbox,
3
+ setActiveSandbox,
4
+ type ActiveSandboxPointer,
5
+ type SandboxRecord,
6
+ } from "@opengeni/db";
7
+ import {
8
+ ensureModalRegistryImage,
9
+ swapTargetEstablishability,
10
+ type BackendUnresolvableCode,
11
+ } from "@opengeni/runtime";
12
+ import { type Settings } from "@opengeni/config";
13
+ import type { TurnActivityServices as ActivityServices } from "../types";
14
+ import {
15
+ sandboxLeaseHolderIdForAttempt,
16
+ type TurnSandboxLeaseHolderId,
17
+ } from "../../sandbox-resume";
18
+ import { type TurnSandboxEstablishReason } from "../../observability-metrics";
19
+ import { type SessionEventType } from "@opengeni/contracts";
20
+ import { safeErrorDiagnostic } from "./errors";
21
+
22
+ export async function resolveActiveSandboxBackend(
23
+ routingOn: boolean,
24
+ loadPointer: () => Promise<{ activeSandboxId: string | null } | null>,
25
+ loadSandboxKind: (sandboxId: string) => Promise<string | null>,
26
+ ): Promise<Settings["sandboxBackend"] | undefined> {
27
+ // The active pointer + swap tools only exist when selfhosted routing is on; with
28
+ // the flag off there is nothing to resolve and we keep the home-backend default.
29
+ if (!routingOn) {
30
+ return undefined;
31
+ }
32
+ try {
33
+ const pointer = await loadPointer();
34
+ // A null pointer (no swap) means "use the session's own cloud group box" — the
35
+ // home backend already governs that path, so leave the override unset.
36
+ if (!pointer?.activeSandboxId) {
37
+ return undefined;
38
+ }
39
+ const kind = await loadSandboxKind(pointer.activeSandboxId);
40
+ return kind === "selfhosted" ? "selfhosted" : undefined;
41
+ } catch (error) {
42
+ console.error(
43
+ "active sandbox backend resolution failed (turn proceeds on home backend)",
44
+ safeErrorDiagnostic(error),
45
+ );
46
+ return undefined;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Managed-sandbox ownership exists only when this turn actually uses the
52
+ * managed home. A Connected Machine is fenced by its active-route epoch and
53
+ * must remain independent from cloud recovery state for the same session.
54
+ */
55
+ export function managedSandboxOwnershipForTurn(
56
+ machinePrimary: boolean,
57
+ attemptId: string,
58
+ sandboxGroupId: string,
59
+ ): { holderId: TurnSandboxLeaseHolderId; sandboxGroupId: string } | null {
60
+ if (machinePrimary) return null;
61
+ return {
62
+ holderId: sandboxLeaseHolderIdForAttempt(attemptId),
63
+ sandboxGroupId,
64
+ };
65
+ }
66
+
67
+ /** A sandboxless home still establishes an explicitly attached Connected Machine. */
68
+ export function shouldEstablishSandboxForTurn(
69
+ sandboxOwnershipEnabled: boolean,
70
+ homeBackend: Settings["sandboxBackend"],
71
+ machinePrimary: boolean,
72
+ ): boolean {
73
+ return sandboxOwnershipEnabled && (homeBackend !== "none" || machinePrimary);
74
+ }
75
+
76
+ export function sandboxEstablishPolicyDecision(input: {
77
+ lazyEnabled: boolean;
78
+ machinePrimary: boolean;
79
+ sandboxBackend: Settings["sandboxBackend"];
80
+ hasRunCredentialResolver: boolean;
81
+ generatedVideoFileCount: number;
82
+ hasSignedFileResources: boolean;
83
+ }): { policy: "eager" | "on-demand"; reason: TurnSandboxEstablishReason } {
84
+ if (!input.lazyEnabled) return { policy: "eager", reason: "lazy_disabled" };
85
+ if (input.machinePrimary) return { policy: "eager", reason: "machine_primary" };
86
+ if (input.sandboxBackend === "none") return { policy: "eager", reason: "backend_none" };
87
+ if (input.generatedVideoFileCount > 0) {
88
+ return { policy: "eager", reason: "generated_video_files" };
89
+ }
90
+ // Signed file downloads must finish before the first model boundary so any
91
+ // integrity/download failure is present in the prepared input. Deferring the
92
+ // box until the first tool call would make that first request advertise a
93
+ // path whose materialization outcome is not known yet.
94
+ if (input.hasSignedFileResources) {
95
+ return { policy: "eager", reason: "signed_file_resources" };
96
+ }
97
+ // Merely having a host run-credential resolver is not proof that this turn
98
+ // will use the sandbox. Resolve its attempt-bound material before model input
99
+ // so auth-needed context remains deterministic, but defer every sandbox
100
+ // write, lease, renewal, and cleanup action to the first-operation
101
+ // provisioner. The eager file paths above remain unchanged.
102
+ if (input.hasRunCredentialResolver) {
103
+ return { policy: "on-demand", reason: "initial_run_credentials_deferred" };
104
+ }
105
+ return { policy: "on-demand", reason: "eligible" };
106
+ }
107
+
108
+ /**
109
+ * Repo-backed workspace skills bind into the first-request prompt-cache prefix
110
+ * (`WorkspaceSkillsCapability.instructions()` listDirs the live box). Starting
111
+ * the managed-box establish as soon as its inputs exist lets Modal create overlap
112
+ * tools/history/agent; `get()` still owns clone/setup after `buildAgent`.
113
+ *
114
+ * Do not flip those turns to eager: that serializes create BEFORE tools and
115
+ * increases first-token latency. Chat-only turns without a repository still
116
+ * never create a box. Portable `/compact` returns before this path. Connected
117
+ * Machines and `backend: none` have no managed Modal/docker create to overlap.
118
+ */
119
+ export function shouldPrefetchManagedSandbox(input: {
120
+ establishPolicy: "eager" | "on-demand";
121
+ machinePrimary: boolean;
122
+ groupBoxBackend: Settings["sandboxBackend"];
123
+ hasRepositoryResources: boolean;
124
+ }): boolean {
125
+ if (input.establishPolicy !== "on-demand") return false;
126
+ if (input.machinePrimary) return false;
127
+ if (input.groupBoxBackend === "none" || input.groupBoxBackend === "selfhosted") {
128
+ return false;
129
+ }
130
+ return input.hasRepositoryResources;
131
+ }
132
+
133
+ /**
134
+ * Classify a persisted active-sandbox pointer for TURN-START RECONCILE (issue #341
135
+ * invariant B). Returns the typed reason to RESET the pointer to the session HOME,
136
+ * or null to leave it in place. STRUCTURAL unestablishability only:
137
+ * - no record → the pointed-at sandbox row is gone (`stale_pointer`);
138
+ * - an unestablishable kind (a non-group Modal sibling, or an unknown backend) per
139
+ * the SHARED `swapTargetEstablishability` predicate (`unsupported_backend_context`);
140
+ * - a selfhosted sandbox with no enrollment id to address (`offline_enrollment`).
141
+ * A selfhosted sandbox WITH an enrollment is deliberately left in place even when it
142
+ * is momentarily offline: the machine may recover mid-turn and its ops surface
143
+ * agent_offline lazily, so the user's explicit machine target is never abandoned for
144
+ * a transient control-plane blip (that is #339's concern, not this one).
145
+ */
146
+ export function pointerReconcileReason(
147
+ record: { kind: string; enrollmentId: string | null } | null,
148
+ ): BackendUnresolvableCode | null {
149
+ if (!record) {
150
+ return "stale_pointer";
151
+ }
152
+ const establishable = swapTargetEstablishability({
153
+ kind: record.kind,
154
+ isSessionGroup: false,
155
+ });
156
+ if (!establishable.ok) {
157
+ return establishable.code;
158
+ }
159
+ if (record.kind === "selfhosted" && !record.enrollmentId) {
160
+ return "offline_enrollment";
161
+ }
162
+ return null;
163
+ }
164
+
165
+ /** The active pointer + its sandbox row, loaded once at turn start and threaded
166
+ * through the reconcile so the establish branch reads the SAME (possibly reset)
167
+ * values with no second query. */
168
+ export type LoadedActivePointer = {
169
+ pointer: ActiveSandboxPointer | null;
170
+ record: SandboxRecord | null;
171
+ };
172
+
173
+ /**
174
+ * TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2). If the persisted pointer's
175
+ * target is STRUCTURALLY unestablishable ({@link pointerReconcileReason}) reset the pointer
176
+ * to the session HOME (null) under the epoch fence, emit a VISIBLE `session.route.reconciled`
177
+ * event, and return the reconciled pointer/record so the rest of the turn runs on home. NEVER
178
+ * a silent downgrade. Bounded to ONE attempt: a lost CAS means a concurrent user swap won a
179
+ * higher epoch, so re-read + honor it rather than clobber a newer, user-directed pointer. The
180
+ * event publish is best-effort — a publish failure never fails the turn.
181
+ *
182
+ * FAIL-OPEN on a lookup failure (issue #341 review): the sandbox row is fetched HERE via the
183
+ * caller's NON-swallowing `loadRecord`, so a null decision means the row is genuinely absent,
184
+ * never a suppressed transient DB error. If `loadRecord` THROWS, reconciliation is skipped
185
+ * entirely this turn — the pointer is left UNTOUCHED (record null → the turn runs
186
+ * machinePrimary:false on the group box exactly as before reconcile existed), no CAS, no
187
+ * event — and the next turn retries. A TRANSIENT LOOKUP FAILURE MUST NEVER MUTATE THE POINTER.
188
+ */
189
+ export async function reconcileActiveSandboxPointer(
190
+ db: ActivityServices["db"],
191
+ ids: { accountId: string; workspaceId: string; sessionId: string },
192
+ pointer: ActiveSandboxPointer | null,
193
+ loadRecord: (sandboxId: string) => Promise<SandboxRecord | null>,
194
+ publish?: (events: Array<{ type: SessionEventType; payload: unknown }>) => Promise<void> | void,
195
+ ): Promise<LoadedActivePointer> {
196
+ if (!pointer?.activeSandboxId) {
197
+ return { pointer, record: null };
198
+ }
199
+ // Re-fetch the row WITHOUT error swallowing. A throw here (a transient DB blip) is NOT
200
+ // "row absent": fail open — skip reconciliation, leave the pointer untouched.
201
+ let record: SandboxRecord | null;
202
+ try {
203
+ record = await loadRecord(pointer.activeSandboxId);
204
+ } catch {
205
+ return { pointer, record: null };
206
+ }
207
+ const reason = pointerReconcileReason(record);
208
+ if (!reason) {
209
+ return { pointer, record };
210
+ }
211
+ const fromEpoch = pointer.activeEpoch;
212
+ const reset = await setActiveSandbox(db, {
213
+ accountId: ids.accountId,
214
+ workspaceId: ids.workspaceId,
215
+ sessionId: ids.sessionId,
216
+ targetSandboxId: null,
217
+ expectedEpoch: fromEpoch,
218
+ }).catch(
219
+ () => ({ swapped: false, pointer: null }) as Awaited<ReturnType<typeof setActiveSandbox>>,
220
+ );
221
+ if (reset.swapped && reset.pointer) {
222
+ await Promise.resolve(
223
+ publish?.([
224
+ {
225
+ type: "session.route.reconciled",
226
+ payload: { reason, fromEpoch, toEpoch: reset.pointer.activeEpoch },
227
+ },
228
+ ]),
229
+ ).catch(() => undefined);
230
+ return { pointer: reset.pointer, record: null };
231
+ }
232
+ // The fence was lost: a concurrent higher-epoch swap won. Honor the newer pointer; its
233
+ // record is re-fetched fail-open too (a transient failure leaves record null, never a
234
+ // mutation — we already did not win the CAS).
235
+ const reread = await readActiveSandbox(db, ids.workspaceId, ids.sessionId).catch(() => null);
236
+ if (!reread) {
237
+ return { pointer, record: null };
238
+ }
239
+ let rereadRecord: SandboxRecord | null = null;
240
+ if (reread.activeSandboxId) {
241
+ try {
242
+ rereadRecord = await loadRecord(reread.activeSandboxId);
243
+ } catch {
244
+ rereadRecord = null;
245
+ }
246
+ }
247
+ return { pointer: reread, record: rereadRecord };
248
+ }
249
+
250
+ /**
251
+ * Warm the Modal private-registry image for the image ref this turn actually
252
+ * resolved, not only the deployment-global OPENGENI_MODAL_IMAGE_REF warmed at
253
+ * worker boot. A provider-native modalImageId bypasses registry import and is
254
+ * resolved by ModalImageSelector.fromId during create. Otherwise packs can
255
+ * override `modalImageRef` per workspace/turn, so a private pack image must be
256
+ * resolved before sandbox creation or Modal falls back to the unauthenticated
257
+ * `fromTag` path.
258
+ */
259
+ export async function ensureTurnModalRegistryImage(
260
+ runSettings: Settings,
261
+ sandboxCreationBackend: Settings["sandboxBackend"] | undefined,
262
+ ensureRegistryImage: (settings: Settings) => Promise<void> = ensureModalRegistryImage,
263
+ ): Promise<void> {
264
+ if (sandboxCreationBackend !== "modal") {
265
+ return;
266
+ }
267
+ if (runSettings.modalImageId) {
268
+ return;
269
+ }
270
+ if (!runSettings.modalImageRegistrySecret || !runSettings.modalImageRef) {
271
+ return;
272
+ }
273
+ await ensureRegistryImage(runSettings);
274
+ }
275
+
276
+ export const SANDBOX_ARTIFACT_RUNTIME_MANIFEST = "/opt/opengeni/artifact-runtime/installation.json";
277
+ export const SANDBOX_ARTIFACT_TOOL_ENTRY = "/opt/opengeni/artifact-runtime/skill-facade-entry.mjs";
278
+
279
+ export type SandboxArtifactRuntimeAdmission = Readonly<{
280
+ available: boolean;
281
+ environment: Readonly<Record<string, string>>;
282
+ }>;
283
+
284
+ /**
285
+ * Admit the optional native standalone-file runtime only for the deployment's
286
+ * exact base sandbox image contract. A pack/rig image override is an
287
+ * independent filesystem and therefore fails closed even when the deployment
288
+ * base image is capable. Collaborative artifact skills are admitted separately
289
+ * from the frozen canonical tool catalog.
290
+ *
291
+ * This keeps lazy provisioning intact: CI/release proves the image closure,
292
+ * while a before-agent-start doctor verifies the actual box before any model
293
+ * call. No speculative sandbox is created merely to populate the skill index.
294
+ */
295
+ export function sandboxArtifactRuntimeAdmission(
296
+ deploymentSettings: Settings,
297
+ runSettings: Settings,
298
+ backend: Settings["sandboxBackend"] | undefined,
299
+ options: Readonly<{ production?: boolean }> = {},
300
+ ): SandboxArtifactRuntimeAdmission {
301
+ if (!deploymentSettings.sandboxArtifactRuntimeEnabled) {
302
+ return { available: false, environment: {} };
303
+ }
304
+ const production = options.production ?? process.env.NODE_ENV === "production";
305
+ if (backend === "docker") {
306
+ const image = deploymentSettings.dockerImage;
307
+ const localDevelopmentImage = /^opengeni-sandbox:local-[0-9a-f]{12}$/u.test(image);
308
+ if (
309
+ runSettings.dockerImage !== image ||
310
+ (!/@sha256:[0-9a-f]{64}$/u.test(image) && (production || !localDevelopmentImage))
311
+ ) {
312
+ return { available: false, environment: {} };
313
+ }
314
+ } else if (backend === "modal") {
315
+ if (
316
+ !deploymentSettings.modalImageRef ||
317
+ !/@sha256:[0-9a-f]{64}$/u.test(deploymentSettings.modalImageRef) ||
318
+ runSettings.modalImageRef !== deploymentSettings.modalImageRef ||
319
+ runSettings.modalImageId !== deploymentSettings.modalImageId
320
+ ) {
321
+ return { available: false, environment: {} };
322
+ }
323
+ } else {
324
+ return { available: false, environment: {} };
325
+ }
326
+ return {
327
+ available: true,
328
+ environment: {
329
+ OPENGENI_ARTIFACT_RUNTIME_MANIFEST: SANDBOX_ARTIFACT_RUNTIME_MANIFEST,
330
+ OPENGENI_ARTIFACT_TOOL_ENTRY: SANDBOX_ARTIFACT_TOOL_ENTRY,
331
+ },
332
+ };
333
+ }
334
+
335
+ /**
336
+ * Decide whether the first actual computer action may start a proof recording.
337
+ *
338
+ * On-turn recording runs ffmpeg/x11grab INSIDE the box and reads the .mp4 back
339
+ * out of the box's /tmp — plumbing that exists only for OpenGeni-operated cloud
340
+ * boxes (the Modal desktop backend). A turn whose EFFECTIVE backend is a connected
341
+ * machine ("selfhosted") runs on the user's REAL computer, which has none of that
342
+ * capture plumbing (and the platform must never shell ffmpeg onto a user's machine
343
+ * — the same reason the runtime skips its setup hooks for selfhosted). Left ungated
344
+ * it films nothing, finds no /tmp file, and emits recording.started followed by
345
+ * recording.failed{box-death} on EVERY machine-primary turn — misleading timeline
346
+ * noise + wasted work. So gate it off, exactly like a recording-disabled deployment:
347
+ * skip silently, emit nothing (no new event shape).
348
+ *
349
+ * `effectiveBackend` is the resolved ACTIVE backend for the turn
350
+ * (resolveActiveSandboxBackend) — NOT the session's home backend. A modal-home
351
+ * session actively swapped onto a machine resolves to "selfhosted" here and
352
+ * correctly skips; a machine-home turn that degraded back to its cloud group box
353
+ * (swap-away / flag-off) resolves to undefined and records as before.
354
+ *
355
+ * EDGE — mid-turn swap: this is evaluated once when computer-use first runs. A swap
356
+ * after recording starts is deliberately ignored; the partial recording already has
357
+ * defined failure semantics, so there is no stop/restart machinery.
358
+ */