@opengeni/worker-bundle 0.22.8 → 0.23.4-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 (103) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +10 -2
  2. package/dist/activities/agent-turn/agent-build.d.ts +1 -4
  3. package/dist/activities/agent-turn/claim.d.ts +3 -4
  4. package/dist/activities/agent-turn/codex.d.ts +8 -7
  5. package/dist/activities/agent-turn/compaction-prep.d.ts +2 -0
  6. package/dist/activities/agent-turn/errors.d.ts +13 -0
  7. package/dist/activities/agent-turn/finalization.d.ts +1 -3
  8. package/dist/activities/agent-turn/list-models.d.ts +16 -0
  9. package/dist/activities/agent-turn/model-usage.d.ts +10 -1
  10. package/dist/activities/agent-turn/quiescence.d.ts +39 -0
  11. package/dist/activities/agent-turn/sandbox-route.d.ts +14 -24
  12. package/dist/activities/agent-turn/sandbox-runtime.d.ts +1 -4
  13. package/dist/activities/agent-turn/sandbox-shared-preparation.d.ts +30 -0
  14. package/dist/activities/agent-turn/stream-attempt.d.ts +7 -0
  15. package/dist/activities/agent-turn/tool-environment.d.ts +1 -0
  16. package/dist/activities/agent-turn/tool-policy.d.ts +7 -5
  17. package/dist/activities/agent-turn/turn-context.d.ts +3 -8
  18. package/dist/activities/agent-turn/turn-sandbox-access.d.ts +12 -0
  19. package/dist/activities/agent-turn/video-reference-sandbox.d.ts +7 -0
  20. package/dist/activities/automations.d.ts +1 -0
  21. package/dist/activities/capabilities.d.ts +2 -1
  22. package/dist/activities/codex-rotation.d.ts +2 -0
  23. package/dist/activities/goals.d.ts +11 -0
  24. package/dist/activities/image-generation-references.d.ts +2 -1
  25. package/dist/activities/scheduled-tasks.d.ts +1 -0
  26. package/dist/activities/session-state.d.ts +2 -1
  27. package/dist/activities/types.d.ts +8 -0
  28. package/dist/{activities-control-VZIIV7RX.js → activities-control-SGU2WEVB.js} +328 -107
  29. package/dist/activities-control-SGU2WEVB.js.map +1 -0
  30. package/dist/activities-control.d.ts +2 -0
  31. package/dist/{activities-turn-5RGQDBFV.js → activities-turn-7EAQXW6Q.js} +828 -540
  32. package/dist/activities-turn-7EAQXW6Q.js.map +1 -0
  33. package/dist/activities.d.ts +2 -0
  34. package/dist/{chunk-O4HDX5SC.js → chunk-S2QVRVJW.js} +227 -36
  35. package/dist/chunk-S2QVRVJW.js.map +1 -0
  36. package/dist/{chunk-NAVSAZ56.js → chunk-TJIPCHMP.js} +162 -2
  37. package/dist/chunk-TJIPCHMP.js.map +1 -0
  38. package/dist/index.d.ts +1 -0
  39. package/dist/index.js +69 -6
  40. package/dist/index.js.map +1 -1
  41. package/dist/observability-metrics.d.ts +29 -0
  42. package/dist/personal-github-git-credentials.d.ts +1 -0
  43. package/dist/unhandled-rejection-boundary.d.ts +29 -0
  44. package/dist/workflow-bundle.js +26 -3
  45. package/dist/workflows/activities.d.ts +5 -0
  46. package/dist/workflows/automations.d.ts +5 -0
  47. package/package.json +18 -18
  48. package/src/activities/agent-run-admission.ts +7 -1
  49. package/src/activities/agent-turn/admission.ts +28 -6
  50. package/src/activities/agent-turn/agent-build.ts +15 -31
  51. package/src/activities/agent-turn/claim.ts +53 -72
  52. package/src/activities/agent-turn/codex.ts +21 -12
  53. package/src/activities/agent-turn/compaction-prep.ts +52 -1
  54. package/src/activities/agent-turn/errors.ts +78 -0
  55. package/src/activities/agent-turn/failure-settlement.ts +30 -19
  56. package/src/activities/agent-turn/finalization.ts +24 -21
  57. package/src/activities/agent-turn/history.ts +5 -1
  58. package/src/activities/agent-turn/list-models.ts +101 -0
  59. package/src/activities/agent-turn/model-usage.ts +88 -42
  60. package/src/activities/agent-turn/quiescence.ts +86 -0
  61. package/src/activities/agent-turn/run-credentials.ts +12 -1
  62. package/src/activities/agent-turn/run.ts +20 -14
  63. package/src/activities/agent-turn/sandbox-establish.ts +46 -11
  64. package/src/activities/agent-turn/sandbox-route.ts +21 -25
  65. package/src/activities/agent-turn/sandbox-runtime.ts +1 -116
  66. package/src/activities/agent-turn/sandbox-shared-preparation.ts +206 -0
  67. package/src/activities/agent-turn/stream-attempt.ts +106 -14
  68. package/src/activities/agent-turn/tool-environment.ts +72 -14
  69. package/src/activities/agent-turn/tool-policy.ts +7 -6
  70. package/src/activities/agent-turn/turn-context.ts +12 -14
  71. package/src/activities/agent-turn/{image-reference-sandbox.ts → turn-sandbox-access.ts} +15 -13
  72. package/src/activities/agent-turn/video-reference-sandbox.ts +23 -0
  73. package/src/activities/automations.ts +122 -67
  74. package/src/activities/capabilities.ts +72 -2
  75. package/src/activities/codex-capacity.ts +13 -5
  76. package/src/activities/codex-rotation.ts +17 -0
  77. package/src/activities/goals.ts +117 -35
  78. package/src/activities/image-generation-references.ts +9 -9
  79. package/src/activities/retained-screenshots.ts +104 -21
  80. package/src/activities/sandbox-lease.ts +7 -4
  81. package/src/activities/scheduled-tasks.ts +248 -30
  82. package/src/activities/session-state.ts +8 -1
  83. package/src/activities/site-auth-maintenance.ts +12 -12
  84. package/src/activities/types.ts +6 -0
  85. package/src/activities.ts +1 -0
  86. package/src/activity-services.ts +4 -1
  87. package/src/github-rest-mcp.ts +8 -4
  88. package/src/http.ts +3 -0
  89. package/src/index.ts +38 -4
  90. package/src/observability-metrics.ts +202 -0
  91. package/src/personal-github-git-credentials.ts +45 -4
  92. package/src/sandbox-resume.ts +1 -1
  93. package/src/sandbox-routing.ts +7 -4
  94. package/src/unhandled-rejection-boundary.ts +73 -0
  95. package/src/workflows/activities.ts +15 -0
  96. package/src/workflows/automations.ts +21 -2
  97. package/dist/activities/agent-turn/image-reference-sandbox.d.ts +0 -14
  98. package/dist/activities/recording.d.ts +0 -90
  99. package/dist/activities-control-VZIIV7RX.js.map +0 -1
  100. package/dist/activities-turn-5RGQDBFV.js.map +0 -1
  101. package/dist/chunk-NAVSAZ56.js.map +0 -1
  102. package/dist/chunk-O4HDX5SC.js.map +0 -1
  103. package/src/activities/recording.ts +0 -279
@@ -1,11 +1,13 @@
1
1
  import {
2
- CODEX_USAGE_EXHAUSTED_PCT,
3
2
  CODEX_USAGE_LIMIT_MAX_RESUME_MS,
4
3
  PostCompactionContinuationEmptyError,
5
4
  SandboxDeadlineRotationError,
6
5
  agentRunFailurePayload,
6
+ armTurnQuiescenceWatchdog,
7
+ assertAgentStreamNotCancelled,
7
8
  assertPhysicalToolQuiescenceForCancellation,
8
9
  assertSessionAttemptQuiescenceRecoveryDurable,
10
+ assertSuccessfulAgentStreamCompletion,
9
11
  authoritativeCodexCapacityResetAt,
10
12
  chooseRotationActive,
11
13
  classifyCodexCredentialFailure,
@@ -14,6 +16,7 @@ import {
14
16
  classifySandboxLogicalProvisionFailure,
15
17
  classifyXaiCredentialFailure,
16
18
  clearAttemptCredentialsWithSettledFence,
19
+ codexAccountNeedsLiveCapacityRefresh,
17
20
  codexCredentialCooldownUntil,
18
21
  codexUsageLimitFailurePayload,
19
22
  compactionFailureReason,
@@ -41,12 +44,14 @@ import {
41
44
  persistSandboxDeadlineRotationCheckpoint,
42
45
  postClaimDatabaseRecoveryFailure,
43
46
  preClaimAdmissionFailure,
47
+ providerRecoveryCountAfterModelRequestPhase,
44
48
  providerRecoveryCountFromMetadata,
45
49
  providerRecoveryExhaustedFailure,
46
50
  providerRecoveryResult,
47
51
  providerRetryAfterMs,
48
52
  refreshCodexUsageAndRepairCapacityWaiters,
49
53
  releaseTurnSandboxAfterWriterDrain,
54
+ requireAgentStreamFinalOutput,
50
55
  resolveWorkspaceInstalledSkillRuntime,
51
56
  resolveWorkspacePackRuntime,
52
57
  resumeBoxForTurn,
@@ -56,6 +61,7 @@ import {
56
61
  safeErrorForTelemetry,
57
62
  sandboxDeadlineRotationRecoveryDelayMs,
58
63
  sandboxLeaseHolderIdForAttempt,
64
+ sandboxLifecycleTransitionDiagnostic,
59
65
  sandboxRouteTransitionCode,
60
66
  selectCodexCredentialLeaseForTurn,
61
67
  settingsWithPackSandboxImage,
@@ -73,10 +79,9 @@ import {
73
79
  validateIncidentTelemetrySystemUpdateAuthority,
74
80
  waitForTurnFinalizerStep,
75
81
  waitForTurnOperation,
76
- waitForTurnStreamCleanup,
77
82
  waitForWarmSnapshot,
78
83
  withFirstPartyTools
79
- } from "./chunk-O4HDX5SC.js";
84
+ } from "./chunk-S2QVRVJW.js";
80
85
  import {
81
86
  StreamTimingMetrics,
82
87
  makeMachineOpObserver,
@@ -91,7 +96,9 @@ import {
91
96
  recordModelRequestPhase,
92
97
  recordSandboxLogicalProvision,
93
98
  recordSandboxProvisionAttempt,
99
+ recordSandboxSharedPreparation,
94
100
  recordSessionEventAppendLatency,
101
+ recordSessionEventAppendPhase,
95
102
  recordSessionEventPublishLatency,
96
103
  recordTurnSandboxEstablishPolicy,
97
104
  recordTurnStartupMilestone,
@@ -99,7 +106,7 @@ import {
99
106
  recordTurnWorkerPreparationTotal,
100
107
  runtimeMetricsHooksForObservability,
101
108
  turnLifecycleMetricsFor
102
- } from "./chunk-NAVSAZ56.js";
109
+ } from "./chunk-TJIPCHMP.js";
103
110
 
104
111
  // src/activities-turn.ts
105
112
  import { createProductionAgentRuntime, summarizeForCompaction as summarizeForCompaction2 } from "@opengeni/runtime";
@@ -1232,8 +1239,9 @@ function acceptsPromptCacheKeyForTurn(resolvedModel) {
1232
1239
  return resolvedModel.provider.builtin === true || resolvedModel.provider.kind === "codex-subscription";
1233
1240
  }
1234
1241
  async function refreshCappedCodexUsageRows(db, settings, workspaceId, accounts, capacitySignals) {
1242
+ const now = /* @__PURE__ */ new Date();
1235
1243
  const stale = accounts.filter(
1236
- (a) => a.status === "active" && ((a.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT || (a.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT)
1244
+ (account) => account.status === "active" && codexAccountNeedsLiveCapacityRefresh(account, now)
1237
1245
  );
1238
1246
  if (stale.length === 0) {
1239
1247
  return accounts;
@@ -1549,16 +1557,16 @@ function imageBytesFromSdkToolOutput(output) {
1549
1557
  for (const entry of output) {
1550
1558
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
1551
1559
  const record5 = entry;
1552
- if (record5.type !== "input_image") continue;
1553
- const decoded = imageBytesFromSdkImageSource(
1554
- record5.image ?? record5.image_url ?? record5.imageUrl
1555
- );
1560
+ const decoded = record5.type === "input_image" ? imageBytesFromSdkImageSource(record5.image ?? record5.image_url ?? record5.imageUrl) : record5.type === "image" ? decodeInlineMcpImage(record5.data, record5.mimeType) : null;
1556
1561
  if (decoded) return decoded;
1557
1562
  }
1558
1563
  return null;
1559
1564
  }
1560
1565
  if (!output || typeof output !== "object") return null;
1561
1566
  const outputRecord = output;
1567
+ if (Array.isArray(outputRecord.content)) {
1568
+ return imageBytesFromSdkToolOutput(outputRecord.content);
1569
+ }
1562
1570
  if (outputRecord.type !== "image" || !outputRecord.image || typeof outputRecord.image !== "object" || Array.isArray(outputRecord.image)) {
1563
1571
  return null;
1564
1572
  }
@@ -1585,13 +1593,25 @@ function toolOutputContainsInlineImage(output) {
1585
1593
  return output.some((entry) => {
1586
1594
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
1587
1595
  const record6 = entry;
1588
- return record6.type === "input_image" && sdkImageSourceContainsInlineImage(record6.image ?? record6.image_url ?? record6.imageUrl);
1596
+ return record6.type === "input_image" && sdkImageSourceContainsInlineImage(record6.image ?? record6.image_url ?? record6.imageUrl) || record6.type === "image" && decodeInlineMcpImage(record6.data, record6.mimeType) !== null;
1589
1597
  });
1590
1598
  }
1591
1599
  if (!output || typeof output !== "object") return false;
1592
1600
  const record5 = output;
1601
+ if (Array.isArray(record5.content)) return toolOutputContainsInlineImage(record5.content);
1593
1602
  return record5.type === "image" && sdkImageSourceContainsInlineImage(record5.image);
1594
1603
  }
1604
+ function decodeInlineMcpImage(data, mimeType) {
1605
+ if (typeof data !== "string" || typeof mimeType !== "string" || !["image/png", "image/jpeg", "image/webp"].includes(mimeType)) {
1606
+ return null;
1607
+ }
1608
+ const maxEncodedLength = Math.ceil(COMPUTER_SCREENSHOT_MAX_BYTES / 3) * 4;
1609
+ if (data.length === 0 || data.length > maxEncodedLength || data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(data)) {
1610
+ return null;
1611
+ }
1612
+ const bytes = Uint8Array.from(Buffer.from(data, "base64"));
1613
+ return bytes.byteLength > 0 && bytes.byteLength <= COMPUTER_SCREENSHOT_MAX_BYTES ? { bytes, mediaType: mimeType } : null;
1614
+ }
1595
1615
  function decodeInlineImageDataUrl(value) {
1596
1616
  if (typeof value !== "string") return null;
1597
1617
  const match = /^data:(image\/(?:png|jpeg|webp));base64,/u.exec(value);
@@ -1955,18 +1975,34 @@ function compactRetainedScreenshotHistory(history, receiptsByCallId) {
1955
1975
  output: { type: RETAINED_IMAGE_MARKER, artifact: receipt }
1956
1976
  };
1957
1977
  }
1978
+ if (item.output && typeof item.output === "object" && !Array.isArray(item.output) && Array.isArray(item.output.content)) {
1979
+ const result = item.output;
1980
+ const content = compactInlineImageContent(result.content, receipt);
1981
+ return content.changed ? { ...item, output: { ...result, content: content.entries } } : item;
1982
+ }
1958
1983
  if (!Array.isArray(item.output)) return item;
1959
- let changed = false;
1960
- const output = item.output.map((entry) => {
1961
- if (!isInlineImageContent(entry)) return entry;
1962
- changed = true;
1984
+ const output = compactInlineImageContent(item.output, receipt);
1985
+ return output.changed ? { ...item, output: output.entries } : item;
1986
+ });
1987
+ }
1988
+ function compactInlineImageContent(entries, receipt) {
1989
+ let changed = false;
1990
+ const compacted = entries.map((entry) => {
1991
+ if (!isInlineImageContent(entry)) return entry;
1992
+ changed = true;
1993
+ const record5 = entry;
1994
+ if (record5.type === "image") {
1963
1995
  return {
1964
- ...entry,
1996
+ type: "input_image",
1965
1997
  image: { type: RETAINED_IMAGE_MARKER, artifact: receipt }
1966
1998
  };
1967
- });
1968
- return changed ? { ...item, output } : item;
1999
+ }
2000
+ return {
2001
+ ...record5,
2002
+ image: { type: RETAINED_IMAGE_MARKER, artifact: receipt }
2003
+ };
1969
2004
  });
2005
+ return { entries: compacted, changed };
1970
2006
  }
1971
2007
  function collectRetainedScreenshotReceipts(history, target = /* @__PURE__ */ new Map()) {
1972
2008
  for (const item of history) {
@@ -1977,8 +2013,9 @@ function collectRetainedScreenshotReceipts(history, target = /* @__PURE__ */ new
1977
2013
  target.set(callId, direct);
1978
2014
  continue;
1979
2015
  }
1980
- if (!Array.isArray(item.output)) continue;
1981
- for (const entry of item.output) {
2016
+ const outputEntries = Array.isArray(item.output) ? item.output : item.output && typeof item.output === "object" && !Array.isArray(item.output) && Array.isArray(item.output.content) ? item.output.content : null;
2017
+ if (!outputEntries) continue;
2018
+ for (const entry of outputEntries) {
1982
2019
  const receipt = retainedReceiptFromImageContent(entry);
1983
2020
  if (receipt) {
1984
2021
  target.set(callId, receipt);
@@ -2063,18 +2100,25 @@ async function materializeRetainedScreenshotHistoryWithCache(input, cache) {
2063
2100
  });
2064
2101
  continue;
2065
2102
  }
2066
- if (!Array.isArray(item.output)) {
2103
+ const resultOutput = item.output && typeof item.output === "object" && !Array.isArray(item.output) ? item.output : null;
2104
+ const outputEntries = Array.isArray(item.output) ? item.output : resultOutput && Array.isArray(resultOutput.content) ? resultOutput.content : null;
2105
+ if (!outputEntries) {
2067
2106
  materialized.push(item);
2068
2107
  continue;
2069
2108
  }
2070
2109
  let changed = false;
2071
2110
  const output = [];
2072
- for (const entry of item.output) {
2111
+ for (const entry of outputEntries) {
2073
2112
  const next = await materializeEntry(entry);
2074
2113
  changed ||= next !== entry;
2075
2114
  output.push(next);
2076
2115
  }
2077
- materialized.push(changed ? { ...item, output } : item);
2116
+ materialized.push(
2117
+ changed ? {
2118
+ ...item,
2119
+ output: resultOutput ? { ...resultOutput, content: output } : output
2120
+ } : item
2121
+ );
2078
2122
  }
2079
2123
  return materialized;
2080
2124
  }
@@ -2175,7 +2219,7 @@ function retainedReceipt(value) {
2175
2219
  function isInlineImageContent(entry) {
2176
2220
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) return false;
2177
2221
  const record5 = entry;
2178
- return record5.type === "input_image" && typeof record5.image === "string" && record5.image.startsWith("data:image/");
2222
+ return record5.type === "input_image" && typeof record5.image === "string" && record5.image.startsWith("data:image/") || record5.type === "image" && decodeInlineMcpImage(record5.data, record5.mimeType) !== null;
2179
2223
  }
2180
2224
  function historyCallId(item) {
2181
2225
  const value = item.callId ?? item.call_id;
@@ -3208,7 +3252,7 @@ function pendingToolCallFromSdkEvent(event) {
3208
3252
  };
3209
3253
  }
3210
3254
  function toolCallProducesRetainableSessionImage(name) {
3211
- return name === "computer_screenshot" || name === "view_image";
3255
+ return name === "computer_screenshot" || name === "view_image" || name === "interaction__computer_observe";
3212
3256
  }
3213
3257
  function completedToolCallFromSdkEvent(event) {
3214
3258
  if (!event || typeof event !== "object") return null;
@@ -3319,7 +3363,7 @@ async function checkpointHistoryBeforeProviderDispatch(historySink) {
3319
3363
  }
3320
3364
 
3321
3365
  // src/activities/agent-turn/run.ts
3322
- import { sandboxRunAs as sandboxRunAs7 } from "@opengeni/runtime";
3366
+ import { sandboxRunAs as sandboxRunAs6 } from "@opengeni/runtime";
3323
3367
  import { randomUUID as randomUUID6 } from "crypto";
3324
3368
 
3325
3369
  // src/model-checkpoint-memory-collector.ts
@@ -3422,7 +3466,9 @@ function createTurnContext(input) {
3422
3466
  billingState: {
3423
3467
  isCodexTurn: false,
3424
3468
  isXaiTurn: false,
3425
- isExternallyBilledTurn: false
3469
+ isExternallyBilledTurn: false,
3470
+ chargesOpenGeniCredits: true,
3471
+ countsTowardTokenCap: true
3426
3472
  },
3427
3473
  sandboxState: {
3428
3474
  resolvedSandbox: null,
@@ -3456,11 +3502,6 @@ function createTurnContext(input) {
3456
3502
  codemodeTokenRenewalClosed: false,
3457
3503
  publishedRunCredentialNotices: /* @__PURE__ */ new Set()
3458
3504
  },
3459
- recordingState: {
3460
- activeRecording: null,
3461
- computerUseRecordingStart: null,
3462
- didComputerUse: false
3463
- },
3464
3505
  eventing: {
3465
3506
  heartbeatTimer: void 0,
3466
3507
  batcher: null,
@@ -4359,14 +4400,12 @@ async function finalizeTurnAttempt(deps) {
4359
4400
  attempt,
4360
4401
  sandboxState,
4361
4402
  renewals,
4362
- recordingState,
4363
4403
  eventing,
4364
4404
  providerTurn,
4365
4405
  workspaceRefs,
4366
4406
  runWorkspaceMutationForSandbox,
4367
4407
  requireResolvedSandboxForMutation,
4368
4408
  stopLeaseHeartbeat,
4369
- abandonActiveRecording,
4370
4409
  turnCompletionMemoryCollector
4371
4410
  } = deps;
4372
4411
  if (sandboxState.resolvedSandbox === null && !sandboxResumeController.signal.aborted) {
@@ -4378,6 +4417,17 @@ async function finalizeTurnAttempt(deps) {
4378
4417
  let finalizationError;
4379
4418
  let physicalToolQuiescenceConfirmed = !control.acknowledgeQuiescence;
4380
4419
  let quiescenceReceiptOrProofDurable = !control.acknowledgeQuiescence;
4420
+ const disarmQuiescenceWatchdog = armTurnQuiescenceWatchdog({
4421
+ enabled: control.acknowledgeQuiescence,
4422
+ onTimeout: () => {
4423
+ observability.error("turn quiescence drain exceeded hard containment deadline", {
4424
+ "opengeni.session_id": input.sessionId,
4425
+ "opengeni.turn_id": attempt.turnId ?? "",
4426
+ "opengeni.attempt_id": input.attemptId
4427
+ });
4428
+ },
4429
+ terminateWorker: () => process.exit(1)
4430
+ });
4381
4431
  const finalizerSignal = turnFinalizerCancellationSignal(
4382
4432
  cancellationSignal,
4383
4433
  control.activityStatus
@@ -4508,6 +4558,7 @@ async function finalizeTurnAttempt(deps) {
4508
4558
  }
4509
4559
  });
4510
4560
  quiescenceReceiptOrProofDurable = true;
4561
+ disarmQuiescenceWatchdog();
4511
4562
  if (recoveryMode === "signal") {
4512
4563
  observability.info("agent turn quiescence proof handed to workflow recovery", {
4513
4564
  "opengeni.session_id": input.sessionId,
@@ -4531,7 +4582,10 @@ async function finalizeTurnAttempt(deps) {
4531
4582
  machineOpEvents.map((event) => ({
4532
4583
  ...event,
4533
4584
  turnId: attempt.turnId ?? null
4534
- }))
4585
+ })),
4586
+ {
4587
+ onAppendPhase: (observation) => recordSessionEventAppendPhase(observability, observation)
4588
+ }
4535
4589
  ).catch(() => void 0),
4536
4590
  finalizerSignal
4537
4591
  );
@@ -4698,13 +4752,6 @@ async function finalizeTurnAttempt(deps) {
4698
4752
  () => void 0
4699
4753
  );
4700
4754
  }
4701
- await waitForTurnFinalizerStep(
4702
- abandonActiveRecording(
4703
- "activity ended without recording settlement",
4704
- recordingState.didComputerUse ? "failed" : "discard"
4705
- ),
4706
- finalizerSignal
4707
- );
4708
4755
  if (sandboxState.resolvedSandbox) {
4709
4756
  const settledTurnId = attempt.turnId;
4710
4757
  if (runTurnEndPersistence && sandboxState.setupBoxSession && sandboxState.sandboxGroupId && settledTurnId) {
@@ -4868,7 +4915,6 @@ import {
4868
4915
  settleCodexCredentialFailover,
4869
4916
  readLease,
4870
4917
  SandboxLeaseSupersededError,
4871
- SandboxLeaseTransitionError,
4872
4918
  isSessionEventPersistenceError as isSessionEventPersistenceError2
4873
4919
  } from "@opengeni/db";
4874
4920
  import { publishDurableSessionEvents as publishDurableSessionEvents2 } from "@opengeni/events";
@@ -4902,11 +4948,13 @@ import {
4902
4948
  } from "@opengeni/runtime";
4903
4949
  import {
4904
4950
  calculateGatewayReportedCostBreakdown,
4951
+ calculateGatewayReportedProviderCostMicros,
4905
4952
  calculateModelUsageCostBreakdown,
4906
4953
  configuredModelPricingSchedules,
4954
+ resolveModelProvider,
4907
4955
  responseSatisfiesLatencyMode,
4908
- OPENGENI_GATEWAY_MODELS,
4909
- OPENGENI_GATEWAY_PROVIDER_ID
4956
+ OPENGENI_GATEWAY_PROVIDER_ID,
4957
+ WORKSPACE_GATEWAY_PROVIDER_ID
4910
4958
  } from "@opengeni/config";
4911
4959
  import { CODEX_PROVIDER_ID } from "@opengeni/codex";
4912
4960
  function modelUsageSourceKey(input) {
@@ -4991,9 +5039,10 @@ async function processModelResponseTerminalEvent(input) {
4991
5039
  turnAttemptId: input.turnAttemptId,
4992
5040
  model: input.model,
4993
5041
  externallyBilled: input.externallyBilled,
5042
+ ...input.chargesOpenGeniCredits !== void 0 ? { chargesOpenGeniCredits: input.chargesOpenGeniCredits } : {},
5043
+ ...input.countsTowardTokenCap !== void 0 ? { countsTowardTokenCap: input.countsTowardTokenCap } : {},
4994
5044
  usage: responseUsage.usage,
4995
5045
  normalizedUsage,
4996
- gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,
4997
5046
  gatewayBilling: responseUsage.gatewayBilling,
4998
5047
  sourceKey,
4999
5048
  ...input.latencyMode ? { latencyMode: input.latencyMode } : {},
@@ -5012,6 +5061,8 @@ async function processModelResponseTerminalEvent(input) {
5012
5061
  sourceKey,
5013
5062
  usage: responseUsage,
5014
5063
  normalizedUsage,
5064
+ ...billing ? { billingPath: billing.billingPath } : {},
5065
+ ...billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {},
5015
5066
  servingAccountHash: accountContext.servingAccountHash,
5016
5067
  accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,
5017
5068
  emittedSourceKeys: input.emittedSourceKeys
@@ -5087,9 +5138,10 @@ async function processCompactionModelUsageEvent(input) {
5087
5138
  turnAttemptId: input.turnAttemptId,
5088
5139
  model: input.model,
5089
5140
  externallyBilled: input.externallyBilled,
5141
+ ...input.chargesOpenGeniCredits !== void 0 ? { chargesOpenGeniCredits: input.chargesOpenGeniCredits } : {},
5142
+ ...input.countsTowardTokenCap !== void 0 ? { countsTowardTokenCap: input.countsTowardTokenCap } : {},
5090
5143
  usage: input.usage.usage,
5091
5144
  normalizedUsage,
5092
- gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,
5093
5145
  gatewayBilling: input.usage.gatewayBilling,
5094
5146
  sourceKey,
5095
5147
  observability: input.observability
@@ -5107,6 +5159,8 @@ async function processCompactionModelUsageEvent(input) {
5107
5159
  sourceKey,
5108
5160
  usage: input.usage,
5109
5161
  normalizedUsage,
5162
+ ...billing ? { billingPath: billing.billingPath } : {},
5163
+ ...billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {},
5110
5164
  servingAccountHash: accountContext.servingAccountHash,
5111
5165
  accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,
5112
5166
  emittedSourceKeys: input.emittedSourceKeys
@@ -5153,6 +5207,8 @@ async function emitModelCallUsage(input) {
5153
5207
  providerApi: input.providerApi,
5154
5208
  model: input.model,
5155
5209
  sourceKey: input.sourceKey,
5210
+ ...input.billingPath ? { billingPath: input.billingPath } : {},
5211
+ ...input.upstreamProvider ? { upstreamProvider: input.upstreamProvider } : {},
5156
5212
  ...telemetry
5157
5213
  }
5158
5214
  }
@@ -5209,20 +5265,33 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5209
5265
  const inputTokens = sanitizedUsage.inputTokens ?? 0;
5210
5266
  const outputTokens = sanitizedUsage.outputTokens ?? 0;
5211
5267
  const totalTokens = sanitizedUsage.totalTokens ?? 0;
5212
- const gatewayBilling = input.gatewayManaged ? input.gatewayBilling : void 0;
5268
+ const chargesOpenGeniCredits = input.chargesOpenGeniCredits ?? !input.externallyBilled;
5269
+ const countsTowardTokenCap = input.countsTowardTokenCap ?? !input.externallyBilled;
5270
+ const resolvedGatewayModel = input.gatewayBilling ? resolveModelProvider(settings, input.model) : void 0;
5271
+ const gatewayProviderId = resolvedGatewayModel?.provider.id;
5272
+ const gatewayBilling = gatewayProviderId === OPENGENI_GATEWAY_PROVIDER_ID || gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID ? input.gatewayBilling : void 0;
5273
+ const allowedProviders = resolvedGatewayModel?.model.requestPolicy?.gateway.only;
5274
+ const unpinnedWorkspaceGatewayModel = gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID && allowedProviders === void 0;
5213
5275
  if (gatewayBilling) {
5214
- const gatewayModel = Object.values(OPENGENI_GATEWAY_MODELS).find(
5215
- (candidate) => candidate.productId === input.model
5216
- );
5217
- if (!gatewayModel || !gatewayModel.providers.includes(gatewayBilling.finalProvider)) {
5276
+ if (!unpinnedWorkspaceGatewayModel && (!allowedProviders || !allowedProviders.includes(gatewayBilling.finalProvider))) {
5218
5277
  throw new Error(
5219
5278
  `AI Gateway reported unapproved provider ${gatewayBilling.finalProvider} for ${input.model}`
5220
5279
  );
5221
5280
  }
5281
+ if (unpinnedWorkspaceGatewayModel && chargesOpenGeniCredits) {
5282
+ throw new Error(
5283
+ `Workspace Gateway custom model ${input.model} cannot charge OpenGeni credits without pinned pricing`
5284
+ );
5285
+ }
5222
5286
  }
5223
5287
  const pricingSchedules = configuredModelPricingSchedules(settings);
5224
5288
  const configuredPricingModel = pricingSchedules[input.model] ? input.model : input.model.startsWith("codex/") && pricingSchedules[input.model.slice("codex/".length)] ? input.model.slice("codex/".length) : null;
5225
- const pricingBreakdown = gatewayBilling ? calculateGatewayReportedCostBreakdown(
5289
+ const pricingBreakdown = gatewayBilling ? unpinnedWorkspaceGatewayModel ? {
5290
+ providerCostMicros: calculateGatewayReportedProviderCostMicros(
5291
+ gatewayBilling.inferenceCostUsd
5292
+ ),
5293
+ creditCostMicros: 0
5294
+ } : calculateGatewayReportedCostBreakdown(
5226
5295
  settings,
5227
5296
  input.model,
5228
5297
  gatewayBilling.inferenceCostUsd,
@@ -5233,42 +5302,43 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5233
5302
  const hasCompleteCoreTokenTelemetry = normalizedUsage.telemetry.inputTokens !== null && normalizedUsage.telemetry.outputTokens !== null;
5234
5303
  const estimatedProviderCostMicros = gatewayBilling ? pricingBreakdown?.providerCostMicros ?? null : hasCompleteCoreTokenTelemetry ? pricingBreakdown?.providerCostMicros ?? null : null;
5235
5304
  const pricingSource = gatewayBilling ? "gateway_reported" : estimatedProviderCostMicros !== null ? "configured_list_price" : null;
5236
- if (input.externallyBilled) {
5305
+ if (countsTowardTokenCap && totalTokens > 0) {
5237
5306
  await recordUsageEvent(db, {
5238
5307
  accountId: input.accountId,
5239
5308
  workspaceId: input.workspaceId,
5240
- eventType: "model.cost",
5241
- quantity: 0,
5242
- unit: "usd_micros",
5309
+ eventType: "model.tokens",
5310
+ quantity: totalTokens,
5311
+ unit: "tokens",
5243
5312
  sourceResourceType: "model_response",
5244
5313
  sourceResourceId: `${input.turnId}:${input.sourceKey}`,
5245
5314
  sessionId: input.sessionId,
5246
5315
  turnId: input.turnId,
5247
5316
  turnAttemptId: input.turnAttemptId,
5248
- idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`
5317
+ idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`
5249
5318
  });
5250
- return {
5251
- billingPath: "external",
5252
- pricedCostMicros: 0,
5253
- estimatedProviderCostMicros,
5254
- pricingSource,
5255
- normalizedUsage
5256
- };
5257
5319
  }
5258
- if (totalTokens > 0) {
5320
+ if (!chargesOpenGeniCredits) {
5259
5321
  await recordUsageEvent(db, {
5260
5322
  accountId: input.accountId,
5261
5323
  workspaceId: input.workspaceId,
5262
- eventType: "model.tokens",
5263
- quantity: totalTokens,
5264
- unit: "tokens",
5324
+ eventType: "model.cost",
5325
+ quantity: 0,
5326
+ unit: "usd_micros",
5265
5327
  sourceResourceType: "model_response",
5266
5328
  sourceResourceId: `${input.turnId}:${input.sourceKey}`,
5267
5329
  sessionId: input.sessionId,
5268
5330
  turnId: input.turnId,
5269
5331
  turnAttemptId: input.turnAttemptId,
5270
- idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`
5332
+ idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`
5271
5333
  });
5334
+ return {
5335
+ billingPath: "external",
5336
+ pricedCostMicros: 0,
5337
+ estimatedProviderCostMicros,
5338
+ pricingSource,
5339
+ normalizedUsage,
5340
+ ...gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}
5341
+ };
5272
5342
  }
5273
5343
  const shouldDebit = settings.billingMode === "stripe" || settings.usageLimitsMode === "managed";
5274
5344
  if (!shouldDebit || totalTokens === 0 && !gatewayBilling) {
@@ -5396,6 +5466,10 @@ function assertWorkspaceHumanInputAllowed(enabled, kind, attempted) {
5396
5466
  function credentialSubjectIdForTurnInitiator(turn) {
5397
5467
  return directPersonalConnectionSubjectId(turn);
5398
5468
  }
5469
+ function xaiCatalogReadinessAuthority(turn, directCredentialSubjectId) {
5470
+ const subjectId = turn.initiatingHumanSubjectId ?? directCredentialSubjectId;
5471
+ return subjectId ? { subjectId, authoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot } : null;
5472
+ }
5399
5473
  function isDirectHumanTurnInitiation(turn) {
5400
5474
  if (turn.source !== "user" && turn.source !== "api" || turn.initiator.kind !== "subject") {
5401
5475
  return false;
@@ -5422,6 +5496,7 @@ function shouldPublishToolAuthNeededForTurn(payload, trigger, turn) {
5422
5496
  function turnExecutionPolicyBillingIdentity(policy) {
5423
5497
  return {
5424
5498
  externallyBilled: policy.billing.metering === "external",
5499
+ countsTowardTokenCap: policy.billing.upstreamPayer === "deployment",
5425
5500
  codexSubscription: policy.providerId === "codex-subscription" && policy.credentialSource.kind === "connected_subscription" && policy.credentialSource.provider === "codex",
5426
5501
  xaiSubscription: policy.providerId === "supergrok-subscription" && policy.credentialSource.kind === "connected_subscription" && policy.credentialSource.provider === "xai"
5427
5502
  };
@@ -5475,8 +5550,8 @@ var BudgetExhaustedError = class extends Error {
5475
5550
  this.name = "BudgetExhaustedError";
5476
5551
  }
5477
5552
  };
5478
- async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternallyBilledTurn, entitlements) {
5479
- if (!isExternallyBilledTurn && entitlements && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5553
+ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternallyBilledTurn, entitlements, chargesOpenGeniCredits = !isExternallyBilledTurn, countsTowardTokenCap = !isExternallyBilledTurn) {
5554
+ if (chargesOpenGeniCredits && entitlements && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5480
5555
  const decision = await entitlements.admitRun({
5481
5556
  accountId,
5482
5557
  workspaceId,
@@ -5486,7 +5561,7 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
5486
5561
  if (!decision.allowed) {
5487
5562
  throw new Error(decision.reason || "insufficient OpenGeni credits");
5488
5563
  }
5489
- } else if (!isExternallyBilledTurn && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5564
+ } else if (chargesOpenGeniCredits && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5490
5565
  const balance = await getBillingBalance(db, accountId);
5491
5566
  if (balance.balanceMicros <= 0) {
5492
5567
  throw new Error("insufficient OpenGeni credits");
@@ -5506,7 +5581,7 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
5506
5581
  );
5507
5582
  }
5508
5583
  }
5509
- if (!isExternallyBilledTurn && limits.maxMonthlyTokensPerWorkspace) {
5584
+ if (countsTowardTokenCap && limits.maxMonthlyTokensPerWorkspace) {
5510
5585
  const used = await sumUsageQuantity(db, {
5511
5586
  workspaceId,
5512
5587
  eventType: "model.tokens",
@@ -5547,29 +5622,32 @@ async function settleTurnFailure(deps) {
5547
5622
  acknowledgeRecoveryQuiescence
5548
5623
  } = deps;
5549
5624
  const recoveryTurnId = attempt.turnId;
5550
- if ((error instanceof SandboxLeaseSupersededError || error instanceof SandboxLeaseTransitionError) && recoveryTurnId) {
5625
+ const lifecycleTransition = sandboxLifecycleTransitionDiagnostic(error);
5626
+ const leaseControlError = error instanceof SandboxLeaseSupersededError ? error : lifecycleTransition;
5627
+ if (leaseControlError && recoveryTurnId) {
5551
5628
  try {
5552
- const fencedLease = await readLease(db, input.workspaceId, error.sandboxGroupId).catch(
5553
- () => null
5554
- );
5555
- const lifecycleTransition = error instanceof SandboxLeaseTransitionError;
5556
- const rotationPending = fencedLease?.rotationRequestedAt != null || lifecycleTransition && error.reason === "rotation_in_progress";
5557
- const transitionPending = lifecycleTransition || rotationPending;
5629
+ const fencedLease = await readLease(
5630
+ db,
5631
+ input.workspaceId,
5632
+ leaseControlError.sandboxGroupId
5633
+ ).catch(() => null);
5634
+ const rotationPending = fencedLease?.rotationRequestedAt != null || lifecycleTransition?.reason === "rotation_in_progress";
5635
+ const transitionPending = lifecycleTransition !== null || rotationPending;
5558
5636
  const deadlineRotationPending = rotationPending && fencedLease?.rotationReason === "provider_deadline";
5559
5637
  const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {
5560
5638
  sessionId: input.sessionId,
5561
5639
  turnId: recoveryTurnId,
5562
5640
  triggerEventId: attempt.triggerEventId,
5563
5641
  attemptId: input.attemptId,
5564
- reason: deadlineRotationPending ? "sandbox_deadline_rotation" : lifecycleTransition ? "sandbox_lifecycle_transition" : "sandbox_lease_superseded",
5642
+ reason: deadlineRotationPending ? "sandbox_deadline_rotation" : lifecycleTransition !== null ? "sandbox_lifecycle_transition" : "sandbox_lease_superseded",
5565
5643
  ...transitionPending ? {
5566
5644
  detail: {
5567
- sandboxGroupId: error.sandboxGroupId,
5568
- leaseEpoch: error.leaseEpoch,
5645
+ sandboxGroupId: leaseControlError.sandboxGroupId,
5646
+ leaseEpoch: leaseControlError.leaseEpoch,
5569
5647
  ...rotationPending ? {
5570
5648
  rotationReason: fencedLease?.rotationReason ?? "operator"
5571
5649
  } : {},
5572
- ...lifecycleTransition ? { transitionReason: error.reason } : {}
5650
+ ...lifecycleTransition ? { transitionReason: lifecycleTransition.reason } : {}
5573
5651
  }
5574
5652
  } : {}
5575
5653
  });
@@ -5916,7 +5994,11 @@ async function settleTurnFailure(deps) {
5916
5994
  kind: "status",
5917
5995
  status: "error",
5918
5996
  lastError: "model request was forbidden for this credential"
5919
- } : { kind: "cooldown", until: cooldownUntil }
5997
+ } : {
5998
+ kind: "cooldown",
5999
+ until: cooldownUntil,
6000
+ cooldownKind: codexCredentialFailure.kind
6001
+ }
5920
6002
  }) : false;
5921
6003
  if (!statePersisted && leases.codex.holderId && leases.codex.generation !== null) {
5922
6004
  leases.codex.lost = true;
@@ -6114,6 +6196,7 @@ async function settleTurnFailure(deps) {
6114
6196
  let rotationResumeIdleUntilReset = false;
6115
6197
  let allCappedResetAt = null;
6116
6198
  let capacityAuthoritativeResetAt = null;
6199
+ let capacityNeedsBoundedRefresh = false;
6117
6200
  if (providerTurn.effectiveCodexCredentialId) {
6118
6201
  const [rotation, sessionCodex] = await Promise.all([
6119
6202
  getCodexRotationSettings(db, input.workspaceId).catch(() => null),
@@ -6140,7 +6223,8 @@ async function settleTurnFailure(deps) {
6140
6223
  db,
6141
6224
  input.workspaceId,
6142
6225
  providerTurn.effectiveCodexCredentialId,
6143
- until
6226
+ until,
6227
+ "quota"
6144
6228
  ).catch(() => null);
6145
6229
  const cooldownPersisted = cooldownMutation?.result ?? false;
6146
6230
  if (cooldownMutation) {
@@ -6150,7 +6234,7 @@ async function settleTurnFailure(deps) {
6150
6234
  );
6151
6235
  }
6152
6236
  const fresh = accounts.map(
6153
- (a) => a.id === providerTurn.effectiveCodexCredentialId ? { ...a, exhaustedUntil: until } : a
6237
+ (a) => a.id === providerTurn.effectiveCodexCredentialId ? { ...a, exhaustedUntil: until, exhaustedKind: "quota" } : a
6154
6238
  );
6155
6239
  if (reactiveSharded) {
6156
6240
  const newHome = shardCredentialForSession({
@@ -6205,6 +6289,7 @@ async function settleTurnFailure(deps) {
6205
6289
  rotated = true;
6206
6290
  allCappedResetAt = earliestCodexReset(fresh, /* @__PURE__ */ new Date());
6207
6291
  capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, /* @__PURE__ */ new Date());
6292
+ capacityNeedsBoundedRefresh = true;
6208
6293
  }
6209
6294
  } else {
6210
6295
  const decision = chooseRotationActive({
@@ -6232,6 +6317,7 @@ async function settleTurnFailure(deps) {
6232
6317
  rotated = true;
6233
6318
  allCappedResetAt = decision.earliestResetAt;
6234
6319
  capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, /* @__PURE__ */ new Date());
6320
+ capacityNeedsBoundedRefresh = true;
6235
6321
  }
6236
6322
  }
6237
6323
  }
@@ -6258,7 +6344,7 @@ async function settleTurnFailure(deps) {
6258
6344
  goalId: goalActive && goal ? goal.id : null,
6259
6345
  goalVersion: goalActive && goal ? goal.version : null,
6260
6346
  earliestResetAt: providerResetAt,
6261
- resetKind: providerResetAt ? "authoritative" : "bounded_refresh",
6347
+ resetKind: providerResetAt && !capacityNeedsBoundedRefresh ? "authoritative" : "bounded_refresh",
6262
6348
  failurePayload,
6263
6349
  ...leases.codex.holderId && leases.codex.generation !== null ? {
6264
6350
  leaseFence: {
@@ -7696,6 +7782,168 @@ import {
7696
7782
  OPEN_SUFFIX_RUN_STATE_BLOB as OPEN_SUFFIX_RUN_STATE_BLOB2,
7697
7783
  resolveWorkspaceAgentHumanInputEnabled
7698
7784
  } from "@opengeni/contracts";
7785
+
7786
+ // src/activities/agent-turn/sandbox-shared-preparation.ts
7787
+ import { randomUUID } from "crypto";
7788
+ import {
7789
+ claimSandboxSharedPreparation,
7790
+ readSandboxSharedPreparation,
7791
+ SandboxLeaseSupersededError as SandboxLeaseSupersededError2,
7792
+ settleSandboxSharedPreparation
7793
+ } from "@opengeni/db";
7794
+ function observeSharedPreparation(options, measurement) {
7795
+ try {
7796
+ options.observe?.(measurement);
7797
+ } catch {
7798
+ }
7799
+ }
7800
+ function waitForPreparationTransition(ms, signal) {
7801
+ return new Promise((resolve, reject) => {
7802
+ let settled = false;
7803
+ const timer = setTimeout(finish, ms);
7804
+ function finish() {
7805
+ if (settled) return;
7806
+ settled = true;
7807
+ signal?.removeEventListener("abort", cancel);
7808
+ resolve();
7809
+ }
7810
+ function cancel() {
7811
+ if (settled) return;
7812
+ settled = true;
7813
+ clearTimeout(timer);
7814
+ signal?.removeEventListener("abort", cancel);
7815
+ reject(signal?.reason ?? new Error("Sandbox shared preparation wait cancelled"));
7816
+ }
7817
+ signal?.addEventListener("abort", cancel, { once: true });
7818
+ if (signal?.aborted) cancel();
7819
+ });
7820
+ }
7821
+ async function settleCompletedWithRetry(options, input, claimId) {
7822
+ let delayMs = 50;
7823
+ for (let attempt = 0; attempt < 4; attempt += 1) {
7824
+ try {
7825
+ if (await settleSandboxSharedPreparation(options.db, {
7826
+ accountId: options.accountId,
7827
+ workspaceId: options.workspaceId,
7828
+ sandboxGroupId: options.sandboxGroupId,
7829
+ expectedLeaseEpoch: options.sandbox.leaseEpoch,
7830
+ expectedInstanceId: options.sandbox.established.instanceId,
7831
+ specHash: input.specHash,
7832
+ holderId: options.holderId,
7833
+ claimId,
7834
+ outcome: "completed"
7835
+ })) {
7836
+ return true;
7837
+ }
7838
+ } catch {
7839
+ }
7840
+ await waitForPreparationTransition(delayMs, options.signal);
7841
+ delayMs *= 2;
7842
+ }
7843
+ return false;
7844
+ }
7845
+ function createSharedRigSetupCoordinator(options) {
7846
+ return async (input) => {
7847
+ const startedAt = performance.now();
7848
+ const claimId = randomUUID();
7849
+ const identity = {
7850
+ accountId: options.accountId,
7851
+ workspaceId: options.workspaceId,
7852
+ sandboxGroupId: options.sandboxGroupId,
7853
+ expectedLeaseEpoch: options.sandbox.leaseEpoch,
7854
+ expectedInstanceId: options.sandbox.established.instanceId,
7855
+ specHash: input.specHash,
7856
+ holderId: options.holderId
7857
+ };
7858
+ const claimTimeoutMs = Math.min(36e5, Math.max(3e4, input.timeoutMs + 3e4));
7859
+ let delayMs = 100;
7860
+ let observedRevision = -1;
7861
+ let path = "owner";
7862
+ try {
7863
+ for (; ; ) {
7864
+ if (options.signal?.aborted) {
7865
+ throw options.signal.reason ?? new Error("Sandbox shared preparation cancelled");
7866
+ }
7867
+ const claim = await claimSandboxSharedPreparation(options.db, {
7868
+ ...identity,
7869
+ claimId,
7870
+ ownerAttemptId: options.attemptId,
7871
+ timeoutMs: claimTimeoutMs
7872
+ });
7873
+ if (claim.role === "fenced") {
7874
+ throw new SandboxLeaseSupersededError2(options.sandboxGroupId, options.sandbox.leaseEpoch);
7875
+ }
7876
+ if (claim.role === "reused") {
7877
+ if (path !== "joined") path = "reused";
7878
+ observeSharedPreparation(options, {
7879
+ path,
7880
+ outcome: "completed",
7881
+ durationSeconds: (performance.now() - startedAt) / 1e3
7882
+ });
7883
+ return "reused";
7884
+ }
7885
+ if (claim.role === "owner") {
7886
+ try {
7887
+ await input.execute();
7888
+ } catch (error) {
7889
+ await settleSandboxSharedPreparation(options.db, {
7890
+ ...identity,
7891
+ claimId,
7892
+ outcome: "failed"
7893
+ }).catch(() => void 0);
7894
+ throw error;
7895
+ }
7896
+ if (await settleCompletedWithRetry(options, input, claimId)) {
7897
+ observeSharedPreparation(options, {
7898
+ path,
7899
+ outcome: "completed",
7900
+ durationSeconds: (performance.now() - startedAt) / 1e3
7901
+ });
7902
+ return "executed";
7903
+ }
7904
+ throw new Error(
7905
+ "Sandbox shared preparation completed but its durable settlement remains unavailable"
7906
+ );
7907
+ }
7908
+ path = "joined";
7909
+ observedRevision = claim.preparation.revision;
7910
+ const jitterMs = Math.floor(Math.random() * Math.max(1, Math.floor(delayMs / 4)));
7911
+ await waitForPreparationTransition(delayMs + jitterMs, options.signal);
7912
+ const observed = await readSandboxSharedPreparation(options.db, identity);
7913
+ if (observed.status === "fenced") {
7914
+ throw new SandboxLeaseSupersededError2(options.sandboxGroupId, options.sandbox.leaseEpoch);
7915
+ }
7916
+ if (observed.preparation.status === "completed") {
7917
+ observeSharedPreparation(options, {
7918
+ path,
7919
+ outcome: "completed",
7920
+ durationSeconds: (performance.now() - startedAt) / 1e3
7921
+ });
7922
+ return "reused";
7923
+ }
7924
+ if (observed.preparation.status === "failed") {
7925
+ delayMs = 100;
7926
+ continue;
7927
+ }
7928
+ delayMs = observed.preparation.revision === observedRevision ? Math.min(2e3, delayMs * 2) : 100;
7929
+ }
7930
+ } catch (error) {
7931
+ observeSharedPreparation(options, {
7932
+ path,
7933
+ outcome: "failed",
7934
+ durationSeconds: (performance.now() - startedAt) / 1e3
7935
+ });
7936
+ throw error;
7937
+ }
7938
+ };
7939
+ }
7940
+
7941
+ // src/activities/agent-turn/stream-attempt.ts
7942
+ async function attachPendingUpdatesBeforePreparingModelInput(input) {
7943
+ if (input.shouldAttach && !await input.attachPendingUpdates()) return false;
7944
+ await input.prepareModelInput();
7945
+ return true;
7946
+ }
7699
7947
  async function runTurnStreamAttempt(deps) {
7700
7948
  const {
7701
7949
  input,
@@ -7750,12 +7998,14 @@ async function runTurnStreamAttempt(deps) {
7750
7998
  turn,
7751
7999
  trigger,
7752
8000
  humanInputResume,
8001
+ attachPendingUpdatesAfterOpenSuffix,
7753
8002
  agent,
7754
8003
  resolvedModel,
7755
8004
  providerApi,
7756
8005
  runSettings,
7757
8006
  turnTools,
7758
8007
  compactSummarizer,
8008
+ settleDeferredSteerAfterCompaction,
7759
8009
  compactionModelHistoryProjector,
7760
8010
  generatedImageHistoryProjector,
7761
8011
  modelHistoryProjector,
@@ -7898,6 +8148,7 @@ async function runTurnStreamAttempt(deps) {
7898
8148
  const streamProvider = resolvedModel?.provider.id ?? settings.openaiProvider ?? "openai";
7899
8149
  const providerPublishesNativeRequestEvents = resolvedModel?.provider.kind === "codex-subscription" || resolvedModel?.provider.kind === "xai-subscription";
7900
8150
  let fallbackProviderRequestStartedAt = null;
8151
+ let fallbackProviderRequestLifecycleStartedAt = null;
7901
8152
  const recordFallbackProviderDispatchAtWire = async () => {
7902
8153
  await checkpointHistoryBeforeProviderDispatch(historySink);
7903
8154
  if (providerPublishesNativeRequestEvents || eventing.firstModelRequestPreparationRecorded || eventing.firstModelRequestPreparationStartedAt === null) {
@@ -7941,6 +8192,7 @@ async function runTurnStreamAttempt(deps) {
7941
8192
  }
7942
8193
  ]);
7943
8194
  fallbackProviderRequestStartedAt = performance.now();
8195
+ fallbackProviderRequestLifecycleStartedAt = fallbackProviderRequestStartedAt;
7944
8196
  } catch (error) {
7945
8197
  auditOutcome = "failed";
7946
8198
  throw error;
@@ -7957,7 +8209,8 @@ async function runTurnStreamAttempt(deps) {
7957
8209
  };
7958
8210
  const ownedEstablished = sandboxState.resolvedSandbox?.established ?? sandboxState.lazyOwnedSandbox;
7959
8211
  const runStreamOnce = async () => {
7960
- if (sandboxState.resolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
8212
+ const eagerResolvedSandbox = sandboxState.resolvedSandbox;
8213
+ if (eagerResolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
7961
8214
  const ownedSandboxSetupStartedAt = performance.now();
7962
8215
  let ownedSandboxSetupOutcome = "completed";
7963
8216
  try {
@@ -7965,11 +8218,11 @@ async function runTurnStreamAttempt(deps) {
7965
8218
  await attachRunCredentialRenewal(
7966
8219
  eagerSetupSession,
7967
8220
  initialRunCredentialMaterial,
7968
- sandboxState.resolvedSandbox
8221
+ eagerResolvedSandbox
7969
8222
  );
7970
8223
  const eagerCredentialSetupSession = initialRunCredentialMaterial ? withRunCredentialsSession(eagerSetupSession, input.sessionId) : eagerSetupSession;
7971
8224
  await runWorkspaceMutationForSandbox(
7972
- sandboxState.resolvedSandbox,
8225
+ eagerResolvedSandbox,
7973
8226
  "eagerOwnedSandboxSetup",
7974
8227
  async () => await runOwnedSandboxSetup(
7975
8228
  agent,
@@ -7991,6 +8244,19 @@ async function runTurnStreamAttempt(deps) {
7991
8244
  commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
7992
8245
  eventing.toolCancellationFenceRef.current
7993
8246
  )
8247
+ } : {},
8248
+ ...sandboxState.sandboxGroupId && sandboxState.sandboxHolderId ? {
8249
+ coordinateSharedRigSetup: createSharedRigSetupCoordinator({
8250
+ db,
8251
+ accountId: input.accountId,
8252
+ workspaceId: input.workspaceId,
8253
+ sandboxGroupId: sandboxState.sandboxGroupId,
8254
+ attemptId: input.attemptId,
8255
+ holderId: sandboxState.sandboxHolderId,
8256
+ sandbox: eagerResolvedSandbox,
8257
+ ...runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {},
8258
+ observe: (measurement) => recordSandboxSharedPreparation(observability, measurement)
8259
+ })
7994
8260
  } : {}
7995
8261
  }
7996
8262
  )
@@ -8217,6 +8483,8 @@ async function runTurnStreamAttempt(deps) {
8217
8483
  latencyMode: turnExecutionPolicy.latencyMode,
8218
8484
  metricProvider: streamProvider,
8219
8485
  externallyBilled: billingState.isExternallyBilledTurn,
8486
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
8487
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
8220
8488
  servingCredentialId: providerTurn.effectiveCodexCredentialId,
8221
8489
  priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,
8222
8490
  emittedSourceKeys: emittedModelUsageSourceKeys,
@@ -8233,6 +8501,28 @@ async function runTurnStreamAttempt(deps) {
8233
8501
  ...resolvedModel?.provider.id ? { providerId: resolvedModel.provider.id } : {}
8234
8502
  });
8235
8503
  if (responseResult.status === "processed") {
8504
+ if (!providerPublishesNativeRequestEvents && fallbackProviderRequestLifecycleStartedAt !== null) {
8505
+ const durationMs = Math.max(
8506
+ 0,
8507
+ performance.now() - fallbackProviderRequestLifecycleStartedAt
8508
+ );
8509
+ fallbackProviderRequestLifecycleStartedAt = null;
8510
+ await eventing.publish([
8511
+ {
8512
+ type: "agent.model.request",
8513
+ payload: {
8514
+ phase: "completed",
8515
+ provider: streamProvider,
8516
+ durationMs: Math.round(durationMs),
8517
+ turnId: activeTurnId,
8518
+ attemptId: input.attemptId,
8519
+ dispatchId,
8520
+ executionGeneration: attempt.executionGeneration
8521
+ }
8522
+ }
8523
+ ]);
8524
+ attempt.providerRecoveryCount = 0;
8525
+ }
8236
8526
  const rawStreamHistory = eventing.stream.state.history;
8237
8527
  if (Array.isArray(rawStreamHistory)) {
8238
8528
  await media.retainNativeGeneratedImagesFromHistory(
@@ -8252,7 +8542,9 @@ async function runTurnStreamAttempt(deps) {
8252
8542
  input.accountId,
8253
8543
  input.workspaceId,
8254
8544
  billingState.isExternallyBilledTurn,
8255
- entitlements
8545
+ entitlements,
8546
+ billingState.chargesOpenGeniCredits,
8547
+ billingState.countsTowardTokenCap
8256
8548
  );
8257
8549
  } catch (limitError) {
8258
8550
  let serializedRunState = null;
@@ -8451,9 +8743,13 @@ async function runTurnStreamAttempt(deps) {
8451
8743
  }
8452
8744
  }
8453
8745
  } catch (error) {
8454
- if (fallbackProviderRequestStartedAt !== null) {
8455
- const durationMs = Math.max(0, performance.now() - fallbackProviderRequestStartedAt);
8746
+ if (fallbackProviderRequestLifecycleStartedAt !== null) {
8747
+ const durationMs = Math.max(
8748
+ 0,
8749
+ performance.now() - fallbackProviderRequestLifecycleStartedAt
8750
+ );
8456
8751
  fallbackProviderRequestStartedAt = null;
8752
+ fallbackProviderRequestLifecycleStartedAt = null;
8457
8753
  await eventing.publish([
8458
8754
  {
8459
8755
  type: "agent.model.request",
@@ -8499,16 +8795,18 @@ async function runTurnStreamAttempt(deps) {
8499
8795
  void iterator.return?.().catch(() => void 0);
8500
8796
  }
8501
8797
  }
8502
- await waitForTurnStreamCleanup(
8503
- eventing.batcher.flush(),
8504
- eventing.stream.completed.catch(() => void 0),
8505
- cancellationSignal
8506
- );
8798
+ await assertSuccessfulAgentStreamCompletion({
8799
+ batcherFlush: eventing.batcher.flush(),
8800
+ stream: eventing.stream,
8801
+ temporalCancellationSignal: cancellationSignal,
8802
+ runtimeCancellationSignal
8803
+ });
8507
8804
  if (options.requireTerminalModelResponse && eventing.stream.interruptions.length === 0 && modelResponseState.responseCount === responseCountBeforeStream) {
8508
8805
  throwIfWorkerShuttingDown();
8509
8806
  throwIfTurnCancelled();
8510
8807
  throw new PostCompactionContinuationEmptyError();
8511
8808
  }
8809
+ assertAgentStreamNotCancelled(eventing.stream.cancelled);
8512
8810
  if (!streamSawPerResponseUsage) {
8513
8811
  const aggregateUsage = eventing.stream.state.usage;
8514
8812
  const normalizedAggregateUsage = normalizeModelCallUsage2(aggregateUsage);
@@ -8539,6 +8837,8 @@ async function runTurnStreamAttempt(deps) {
8539
8837
  turnAttemptId: input.attemptId,
8540
8838
  model: turn.model,
8541
8839
  externallyBilled: billingState.isExternallyBilledTurn,
8840
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
8841
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
8542
8842
  usage: aggregateUsage,
8543
8843
  normalizedUsage: normalizedAggregateUsage,
8544
8844
  sourceKey: aggregateSourceKey,
@@ -8560,6 +8860,8 @@ async function runTurnStreamAttempt(deps) {
8560
8860
  sourceKey: aggregateSourceKey,
8561
8861
  usage: { usage: aggregateUsage },
8562
8862
  normalizedUsage: normalizedAggregateUsage,
8863
+ ...billing ? { billingPath: billing.billingPath } : {},
8864
+ ...billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {},
8563
8865
  servingAccountHash: aggregateAccountCtx.servingAccountHash,
8564
8866
  accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,
8565
8867
  emittedSourceKeys: emittedModelUsageSourceKeys
@@ -8722,7 +9024,7 @@ async function runTurnStreamAttempt(deps) {
8722
9024
  control.activityStatus = "requires_action";
8723
9025
  return claimedResult({ status: "requires_action" });
8724
9026
  }
8725
- const finalOutput = String(eventing.stream.finalOutput ?? "");
9027
+ const finalOutput = String(requireAgentStreamFinalOutput(eventing.stream.finalOutput));
8726
9028
  await historySink.reconcileConversationTruth({ requireDurable: true });
8727
9029
  await finalizeTurnOpStreamOps();
8728
9030
  if (!await eventing.settle({
@@ -8779,7 +9081,13 @@ async function runTurnStreamAttempt(deps) {
8779
9081
  control.activityStatus = "requires_action";
8780
9082
  return claimedResult({ status: "requires_action" });
8781
9083
  }
8782
- await prepareRunAttemptInput();
9084
+ if (!await attachPendingUpdatesBeforePreparingModelInput({
9085
+ shouldAttach: trigger.type === "user.approvalDecision" || trigger.type === "user.humanInputResponse",
9086
+ attachPendingUpdates: attachPendingUpdatesAfterOpenSuffix,
9087
+ prepareModelInput: prepareRunAttemptInput
9088
+ })) {
9089
+ return claimedResult({ status: "cancelled" });
9090
+ }
8783
9091
  let retriedAfterCompaction = false;
8784
9092
  while (true) {
8785
9093
  try {
@@ -8848,6 +9156,8 @@ async function runTurnStreamAttempt(deps) {
8848
9156
  );
8849
9157
  compactionRequestCleared = landmark.requestConsumed;
8850
9158
  if (!isCompactionSummaryFailure(compactError)) throw compactError;
9159
+ const deferredSteer2 = await settleDeferredSteerAfterCompaction();
9160
+ if (deferredSteer2) return deferredSteer2;
8851
9161
  compactionFailureMessage = String(compactionFailureReasonFromError(compactError));
8852
9162
  observability.warn("context compaction recovery compaction failed", {
8853
9163
  sessionId: input.sessionId,
@@ -8886,6 +9196,8 @@ async function runTurnStreamAttempt(deps) {
8886
9196
  control.activityError = attemptError;
8887
9197
  return claimedResult({ status: "idle", deferredUntilWake: true });
8888
9198
  }
9199
+ const deferredSteer = await settleDeferredSteerAfterCompaction();
9200
+ if (deferredSteer) return deferredSteer;
8889
9201
  retriedAfterCompaction = true;
8890
9202
  observability.info("context compaction recovery retrying turn after compaction", {
8891
9203
  sessionId: input.sessionId,
@@ -8910,7 +9222,6 @@ import {
8910
9222
  requireSession
8911
9223
  } from "@opengeni/db";
8912
9224
  import { appendAndPublishTurnEventsFenced as appendAndPublishTurnEventsFenced2, publishDurableSessionEvents as publishDurableSessionEvents3 } from "@opengeni/events";
8913
- import { deleteRecordingArtifacts as deleteRecordingArtifacts2 } from "@opengeni/runtime";
8914
9225
  import {
8915
9226
  assertTurnExecutionPolicyMatchesConfigV1,
8916
9227
  resolveTurnExecutionPolicyV1 as resolveTurnExecutionPolicyV12
@@ -8919,17 +9230,26 @@ import {
8919
9230
  // src/activities/capabilities.ts
8920
9231
  import {
8921
9232
  environmentsEncryptionKeyBytes as environmentsEncryptionKeyBytes2,
9233
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
9234
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
8922
9235
  withCodexCatalogProvider,
8923
9236
  withWorkspaceGatewayCatalogProvider,
8924
9237
  withWorkspaceGatewayCredential,
9238
+ withWorkspaceOpenRouterCatalogProvider,
9239
+ withWorkspaceOpenRouterCredential,
8925
9240
  withXaiSubscriptionCatalogProvider
8926
9241
  } from "@opengeni/config";
8927
9242
  import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
8928
9243
  import {
9244
+ getWorkspaceGatewayCustomModelForExecution,
9245
+ getWorkspaceOpenRouterCustomModelForExecution,
8929
9246
  listSessionMcpServerMetadata,
8930
9247
  listSessionMcpServersForRun,
9248
+ listWorkspaceGatewayCustomModels,
9249
+ listWorkspaceOpenRouterCustomModels,
8931
9250
  workspaceCodexSubscriptionActive,
8932
- loadWorkspaceVercelAiGatewayApiKey
9251
+ loadWorkspaceVercelAiGatewayApiKey,
9252
+ loadWorkspaceOpenRouterApiKey
8933
9253
  } from "@opengeni/db";
8934
9254
  async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, attemptId, settings, options) {
8935
9255
  const encryptionKey = environmentsEncryptionKeyBytes2(settings);
@@ -8991,15 +9311,48 @@ function withCodexProvider(settings) {
8991
9311
  function withXaiSubscriptionProvider(settings) {
8992
9312
  return withXaiSubscriptionCatalogProvider(settings);
8993
9313
  }
8994
- async function settingsWithWorkspaceGatewayCredential(db, workspaceId, settings) {
8995
- const catalogSettings = withWorkspaceGatewayCatalogProvider(settings);
9314
+ async function settingsWithWorkspaceGatewayCredential(db, accountId, workspaceId, settings, retainedProductModelId) {
9315
+ const activeCustomModels = await listWorkspaceGatewayCustomModels(db, { accountId, workspaceId });
9316
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
9317
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX
9318
+ ) ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX.length) : null;
9319
+ const retainedCustomModel = retainedUpstreamModelId ? await getWorkspaceGatewayCustomModelForExecution(db, {
9320
+ accountId,
9321
+ workspaceId,
9322
+ upstreamModelId: retainedUpstreamModelId
9323
+ }) : null;
9324
+ const customModels = retainedCustomModel && !activeCustomModels.some(
9325
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId
9326
+ ) ? [...activeCustomModels, retainedCustomModel] : activeCustomModels;
9327
+ const catalogSettings = withWorkspaceGatewayCatalogProvider(settings, customModels);
8996
9328
  const apiKey = await loadWorkspaceVercelAiGatewayApiKey(db, settings, workspaceId);
8997
- return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey) : catalogSettings;
9329
+ return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey, customModels) : catalogSettings;
9330
+ }
9331
+ async function settingsWithWorkspaceOpenRouterCredential(db, accountId, workspaceId, settings, retainedProductModelId) {
9332
+ const activeCustomModels = await listWorkspaceOpenRouterCustomModels(db, {
9333
+ accountId,
9334
+ workspaceId
9335
+ });
9336
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
9337
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX
9338
+ ) ? retainedProductModelId.slice(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX.length) : null;
9339
+ const retainedCustomModel = retainedUpstreamModelId ? await getWorkspaceOpenRouterCustomModelForExecution(db, {
9340
+ accountId,
9341
+ workspaceId,
9342
+ upstreamModelId: retainedUpstreamModelId
9343
+ }) : null;
9344
+ const customModels = retainedCustomModel && !activeCustomModels.some(
9345
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId
9346
+ ) ? [...activeCustomModels, retainedCustomModel] : activeCustomModels;
9347
+ const catalogSettings = withWorkspaceOpenRouterCatalogProvider(settings, customModels);
9348
+ const apiKey = await loadWorkspaceOpenRouterApiKey(db, settings, workspaceId);
9349
+ return apiKey ? withWorkspaceOpenRouterCredential(catalogSettings, apiKey, customModels) : catalogSettings;
8998
9350
  }
8999
9351
 
9000
9352
  // src/activities/agent-turn/claim.ts
9001
9353
  import {
9002
9354
  assertSessionAllowsProductModel,
9355
+ resolveCatalogSettings,
9003
9356
  resolveCodexAppsCredentialIdForRun
9004
9357
  } from "@opengeni/core";
9005
9358
 
@@ -9014,169 +9367,6 @@ function makeTurnOpJournal(context, details) {
9014
9367
  };
9015
9368
  }
9016
9369
 
9017
- // src/activities/recording.ts
9018
- import { deleteRecording } from "@opengeni/db";
9019
- import {
9020
- contentTypeForCodec,
9021
- deleteRecordingArtifacts,
9022
- RecordingError,
9023
- recordingStorageKey,
9024
- startRecording as startRecordingOnBox,
9025
- stopRecording as stopRecordingOnBox,
9026
- uploadRecordingArtifact
9027
- } from "@opengeni/runtime";
9028
- import { DOWNLOAD_URL_TTL_SECONDS } from "@opengeni/storage";
9029
- var RECORDING_SETTLEMENT_PREP_TIMEOUT_MS = 1e5;
9030
- var RECORDING_SETTLEMENT_UPLOAD_MAX_SECONDS = 45;
9031
- async function withRecordingPreparationTimeout(preparation, timeoutResult, timeoutMs = RECORDING_SETTLEMENT_PREP_TIMEOUT_MS) {
9032
- let timer;
9033
- try {
9034
- return await Promise.race([
9035
- preparation,
9036
- new Promise((resolve) => {
9037
- timer = setTimeout(() => resolve(timeoutResult), timeoutMs);
9038
- })
9039
- ]);
9040
- } finally {
9041
- if (timer) clearTimeout(timer);
9042
- }
9043
- }
9044
- async function beginRecording(args) {
9045
- const { settings, db } = args;
9046
- const codec = settings.recordingDefaultCodec;
9047
- const dimensions = [
9048
- settings.streamResolutionWidth,
9049
- settings.streamResolutionHeight
9050
- ];
9051
- const framerate = settings.recordingFramerate;
9052
- await import("@opengeni/db").then(
9053
- ({ insertRecording }) => insertRecording(db, {
9054
- id: args.recordingId,
9055
- accountId: args.accountId,
9056
- workspaceId: args.workspaceId,
9057
- sessionId: args.sessionId,
9058
- turnId: args.turnId,
9059
- mode: args.mode,
9060
- codec,
9061
- width: dimensions[0],
9062
- height: dimensions[1],
9063
- reason: scrubFreeText(args.reason)
9064
- })
9065
- );
9066
- let proc;
9067
- try {
9068
- proc = await startRecordingOnBox(args.session, {
9069
- recordingId: args.recordingId,
9070
- codec,
9071
- framerate,
9072
- maxSeconds: settings.recordingMaxSeconds,
9073
- dimensions,
9074
- ...args.runAs ? { runAs: args.runAs } : {}
9075
- });
9076
- } catch (error) {
9077
- await deleteRecording(db, {
9078
- accountId: args.accountId,
9079
- workspaceId: args.workspaceId,
9080
- recordingId: args.recordingId
9081
- }).catch(() => void 0);
9082
- throw error;
9083
- }
9084
- const active = {
9085
- recordingId: args.recordingId,
9086
- turnId: args.turnId,
9087
- mode: args.mode,
9088
- proc,
9089
- dimensions,
9090
- framerate
9091
- };
9092
- const started = {
9093
- recordingId: args.recordingId,
9094
- turnId: args.turnId,
9095
- mode: args.mode,
9096
- codec,
9097
- dimensions,
9098
- framerate,
9099
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
9100
- reason: scrubFreeText(args.reason)
9101
- };
9102
- return { active, started };
9103
- }
9104
- async function prepareRecordingForSettlement(args) {
9105
- const { settings, objectStorage, active } = args;
9106
- const codec = active.proc.codec;
9107
- const fail = (reason, detail) => {
9108
- return {
9109
- mutation: {
9110
- action: "failed",
9111
- recordingId: active.recordingId,
9112
- reason,
9113
- detail: scrubFreeText(detail)
9114
- },
9115
- deleteArtifactsAfterCommit: false
9116
- };
9117
- };
9118
- const prepare = async () => {
9119
- try {
9120
- await stopRecordingOnBox(args.session, active.proc);
9121
- if (!args.didComputerUse) {
9122
- return {
9123
- mutation: { action: "discard", recordingId: active.recordingId },
9124
- deleteArtifactsAfterCommit: true
9125
- };
9126
- }
9127
- if (!objectStorage) {
9128
- return fail("upload-failed", "object storage is not configured");
9129
- }
9130
- const key = recordingStorageKey(args.workspaceId, args.sessionId, active.recordingId, codec);
9131
- const upload = await objectStorage.createPutUrl({
9132
- key,
9133
- contentType: contentTypeForCodec(codec)
9134
- });
9135
- const finalized = await uploadRecordingArtifact(args.session, active.proc, {
9136
- url: upload.url,
9137
- requiredHeaders: upload.requiredHeaders,
9138
- maxBytes: settings.recordingMaxBytes,
9139
- maxSeconds: RECORDING_SETTLEMENT_UPLOAD_MAX_SECONDS
9140
- });
9141
- return {
9142
- mutation: {
9143
- action: "available",
9144
- recordingId: active.recordingId,
9145
- storageKey: key,
9146
- sizeBytes: finalized.sizeBytes,
9147
- durationSeconds: finalized.durationSeconds
9148
- },
9149
- deleteArtifactsAfterCommit: true
9150
- };
9151
- } catch (error) {
9152
- const reason = error instanceof RecordingError ? error.reason : "upload-failed";
9153
- return fail(reason, error instanceof Error ? error.message : String(error));
9154
- }
9155
- };
9156
- return await withRecordingPreparationTimeout(
9157
- prepare(),
9158
- fail("upload-failed", "recording settlement preparation timed out")
9159
- );
9160
- }
9161
- async function discardUnpublishedRecording(args) {
9162
- const { db, active } = args;
9163
- try {
9164
- await stopRecordingOnBox(args.session, active.proc).catch(() => void 0);
9165
- await deleteRecordingArtifacts(args.session, active.proc).catch(() => void 0);
9166
- } finally {
9167
- await deleteRecording(db, {
9168
- accountId: args.accountId,
9169
- workspaceId: args.workspaceId,
9170
- recordingId: active.recordingId
9171
- }).catch(() => void 0);
9172
- }
9173
- }
9174
- function scrubFreeText(value) {
9175
- if (value === null || value === void 0) return null;
9176
- const exact = String(value);
9177
- return exact.length === 0 ? null : exact;
9178
- }
9179
-
9180
9370
  // src/activities/agent-turn/claim.ts
9181
9371
  import { readTurnExecutionPolicyV1 } from "@opengeni/contracts";
9182
9372
  function turnAttemptProducerId(input, turnId) {
@@ -9186,10 +9376,10 @@ async function claimTurnAttempt(deps) {
9186
9376
  const {
9187
9377
  input,
9188
9378
  settings,
9379
+ catalogSourceSettings,
9189
9380
  db,
9190
9381
  bus,
9191
9382
  runtime,
9192
- objectStorage,
9193
9383
  observability,
9194
9384
  entitlements,
9195
9385
  wakeSessionWorkflow,
@@ -9201,14 +9391,20 @@ async function claimTurnAttempt(deps) {
9201
9391
  attempt,
9202
9392
  billingState,
9203
9393
  sandboxState,
9204
- recordingState,
9205
9394
  eventing,
9206
9395
  leases,
9207
9396
  media,
9208
9397
  claimedResult,
9209
- acknowledgeLostAttemptOwnership,
9210
- abandonActiveRecording
9398
+ acknowledgeLostAttemptOwnership
9211
9399
  } = deps;
9400
+ const deploymentCatalogSettings = (await resolveCatalogSettings(db, catalogSourceSettings)).settings;
9401
+ const validatePendingSystemUpdateAuthority = async (tx, update) => await validateIncidentTelemetrySystemUpdateAuthority({
9402
+ db: tx,
9403
+ settings: deploymentCatalogSettings,
9404
+ workspaceId: input.workspaceId,
9405
+ sessionId: input.sessionId,
9406
+ update
9407
+ });
9212
9408
  const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {
9213
9409
  sessionId: input.sessionId,
9214
9410
  workflowId: input.workflowId,
@@ -9216,13 +9412,7 @@ async function claimTurnAttempt(deps) {
9216
9412
  attemptId: input.attemptId,
9217
9413
  dispatchId,
9218
9414
  trigger: input.trigger,
9219
- validatePendingSystemUpdateAuthority: async (tx, update) => await validateIncidentTelemetrySystemUpdateAuthority({
9220
- db: tx,
9221
- settings,
9222
- workspaceId: input.workspaceId,
9223
- sessionId: input.sessionId,
9224
- update
9225
- })
9415
+ validatePendingSystemUpdateAuthority
9226
9416
  });
9227
9417
  if (claim.action === "unclaimed") {
9228
9418
  control.activityStatus = "unclaimed";
@@ -9236,6 +9426,7 @@ async function claimTurnAttempt(deps) {
9236
9426
  attempt.redispatchesAtDispatch = Number(
9237
9427
  turn.metadata?.workerDeathRedispatches ?? 0
9238
9428
  );
9429
+ const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);
9239
9430
  const session = await requireSession(db, input.workspaceId, input.sessionId);
9240
9431
  let installedApiIntegrations = [];
9241
9432
  const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);
@@ -9243,7 +9434,7 @@ async function claimTurnAttempt(deps) {
9243
9434
  const mcpSettings = await settingsWithEnabledCapabilityMcpServers(
9244
9435
  db,
9245
9436
  input.workspaceId,
9246
- settings,
9437
+ deploymentCatalogSettings,
9247
9438
  {
9248
9439
  ...credentialSubjectId ? { subjectId: credentialSubjectId } : {
9249
9440
  personalConnectionDelegations: turn.personalConnectionDelegations
@@ -9265,14 +9456,22 @@ async function claimTurnAttempt(deps) {
9265
9456
  codexSubscriptionActive
9266
9457
  );
9267
9458
  const xaiSettings = codexSettings.supergrokSubscriptionEnabled ? withXaiSubscriptionProvider(codexSettings) : codexSettings;
9268
- const capabilitySettings = await settingsWithWorkspaceGatewayCredential(
9459
+ const gatewaySettings = await settingsWithWorkspaceGatewayCredential(
9460
+ db,
9461
+ input.accountId,
9462
+ input.workspaceId,
9463
+ xaiSettings,
9464
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
9465
+ );
9466
+ const capabilitySettings = await settingsWithWorkspaceOpenRouterCredential(
9269
9467
  db,
9468
+ input.accountId,
9270
9469
  input.workspaceId,
9271
- xaiSettings
9470
+ gatewaySettings,
9471
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
9272
9472
  );
9273
9473
  const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId) : null;
9274
9474
  runtime.configure(capabilitySettings);
9275
- const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);
9276
9475
  const policyForAbsent = claimedPolicy.kind === "valid" ? claimedPolicy.policy : resolveTurnExecutionPolicyV12(capabilitySettings, legacyTurnExecutionPolicyInput(turn));
9277
9476
  const installedPolicy = await installOrReadTurnExecutionPolicyForAttempt(db, {
9278
9477
  accountId: input.accountId,
@@ -9299,6 +9498,8 @@ async function claimTurnAttempt(deps) {
9299
9498
  assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);
9300
9499
  const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);
9301
9500
  billingState.isExternallyBilledTurn = billingIdentity.externallyBilled;
9501
+ billingState.chargesOpenGeniCredits = verifiedExecutionPolicy.model.cost === "credits";
9502
+ billingState.countsTowardTokenCap = billingIdentity.countsTowardTokenCap;
9302
9503
  billingState.isCodexTurn = billingIdentity.codexSubscription;
9303
9504
  billingState.isXaiTurn = billingIdentity.xaiSubscription;
9304
9505
  const trigger = await getSessionEvent3(db, input.workspaceId, attempt.triggerEventId);
@@ -9318,15 +9519,30 @@ async function claimTurnAttempt(deps) {
9318
9519
  trigger
9319
9520
  );
9320
9521
  attempt.triggerType = trigger.type;
9522
+ const attachPendingUpdatesAfterOpenSuffix = async () => {
9523
+ const attached = await claimSessionWorkForAttempt(db, input.workspaceId, {
9524
+ sessionId: input.sessionId,
9525
+ workflowId: input.workflowId,
9526
+ workflowRunId: input.workflowRunId,
9527
+ attemptId: input.attemptId,
9528
+ dispatchId,
9529
+ trigger: input.trigger,
9530
+ validatePendingSystemUpdateAuthority,
9531
+ attachPendingUpdatesToRunningAttempt: true
9532
+ });
9533
+ return attached.action === "claimed" && attached.turn.id === turn.id;
9534
+ };
9321
9535
  turnLifecycleMetricsFor(observability).start(attempt.turnId);
9322
9536
  await waitForTurnOperation(
9323
9537
  ensureRunAllowed(
9324
- settings,
9538
+ capabilitySettings,
9325
9539
  db,
9326
9540
  input.accountId,
9327
9541
  input.workspaceId,
9328
9542
  billingState.isExternallyBilledTurn,
9329
- entitlements
9543
+ entitlements,
9544
+ billingState.chargesOpenGeniCredits,
9545
+ billingState.countsTowardTokenCap
9330
9546
  ),
9331
9547
  cancellationSignal,
9332
9548
  void 0
@@ -9384,6 +9600,7 @@ async function claimTurnAttempt(deps) {
9384
9600
  onAppend: ({ durationSeconds }) => recordSessionEventAppendLatency(observability, {
9385
9601
  durationSeconds
9386
9602
  }),
9603
+ onAppendPhase: (observation) => recordSessionEventAppendPhase(observability, observation),
9387
9604
  onPublish: ({ durationSeconds }) => recordSessionEventPublishLatency(observability, {
9388
9605
  durationSeconds
9389
9606
  })
@@ -9407,28 +9624,6 @@ async function claimTurnAttempt(deps) {
9407
9624
  return appended;
9408
9625
  };
9409
9626
  eventing.settle = async (inputSettlement) => {
9410
- const attemptClosing = ["completed", "failed", "cancelled", "requires_action"].includes(
9411
- inputSettlement.turnStatus
9412
- );
9413
- const recordingForSettlement = attemptClosing && recordingState.activeRecording && sandboxState.resolvedSandbox ? recordingState.activeRecording : null;
9414
- const preparedRecording = recordingForSettlement ? await prepareRecordingForSettlement({
9415
- settings,
9416
- objectStorage,
9417
- workspaceId: input.workspaceId,
9418
- sessionId: input.sessionId,
9419
- active: recordingForSettlement,
9420
- session: sandboxState.resolvedSandbox.established.session,
9421
- didComputerUse: recordingState.didComputerUse
9422
- }) : null;
9423
- let recordingMutation;
9424
- if (preparedRecording) {
9425
- const mutation = preparedRecording.mutation;
9426
- recordingMutation = mutation.action === "discard" ? mutation : {
9427
- ...mutation,
9428
- producerId,
9429
- producerSeq: ++producerSeq
9430
- };
9431
- }
9432
9627
  const compactionRequestFailure = inputSettlement.consumeRequestedCompactionFailure ? {
9433
9628
  reason: "summarization_failed",
9434
9629
  producerId,
@@ -9457,36 +9652,16 @@ async function claimTurnAttempt(deps) {
9457
9652
  activeTurnId: inputSettlement.activeTurnId,
9458
9653
  events: inputs,
9459
9654
  ...runState ? { runState } : {},
9460
- ...recordingMutation ? { recording: recordingMutation } : {},
9461
9655
  ...compactionRequestFailure ? { compactionRequestFailure } : {}
9462
9656
  });
9463
9657
  if (result.action === "stale") {
9464
9658
  acknowledgeLostAttemptOwnership();
9465
- if (recordingForSettlement) {
9466
- await abandonActiveRecording(
9467
- "recording settlement lost attempt ownership",
9468
- preparedRecording?.mutation.action === "discard" ? "discard" : "failed"
9469
- );
9470
- }
9471
9659
  control.activityStatus = "cancelled";
9472
9660
  control.turnMetricOutcome = "cancelled";
9473
9661
  return false;
9474
9662
  }
9475
9663
  recordCanonicalStartupMilestones(result.canonicalStartupMilestones);
9476
9664
  turnLifecycleMetricsFor(observability).progress(attempt.turnId);
9477
- if (recordingForSettlement && preparedRecording) {
9478
- if (result.recordingMutationApplied) {
9479
- recordingState.activeRecording = null;
9480
- if (preparedRecording.deleteArtifactsAfterCommit) {
9481
- await deleteRecordingArtifacts2(
9482
- sandboxState.resolvedSandbox.established.session,
9483
- recordingForSettlement.proc
9484
- );
9485
- }
9486
- } else {
9487
- await abandonActiveRecording("recording row was unavailable during turn settlement");
9488
- }
9489
- }
9490
9665
  await publishDurableSessionEvents3(bus, input.workspaceId, input.sessionId, result.events);
9491
9666
  if (inputSettlement.turnStatus === "requires_action") {
9492
9667
  await deliverChildRequiresActionToParent(
@@ -9553,6 +9728,7 @@ async function claimTurnAttempt(deps) {
9553
9728
  trigger,
9554
9729
  humanInputResume,
9555
9730
  interactionInterventionResume,
9731
+ attachPendingUpdatesAfterOpenSuffix,
9556
9732
  throwIfWorkerShuttingDown,
9557
9733
  throwIfTurnCancelled,
9558
9734
  opJournal,
@@ -9770,7 +9946,7 @@ function safeErrorName(error) {
9770
9946
  }
9771
9947
 
9772
9948
  // src/activities/agent-turn/codex-capacity.ts
9773
- import { randomUUID } from "crypto";
9949
+ import { randomUUID as randomUUID2 } from "crypto";
9774
9950
  async function selectCodexTurnCapacity(deps) {
9775
9951
  const {
9776
9952
  input,
@@ -10005,7 +10181,7 @@ async function selectCodexTurnCapacity(deps) {
10005
10181
  fencedInFlight,
10006
10182
  nearExhaustionPct: settings.codexRotationNearExhaustionPct,
10007
10183
  now: /* @__PURE__ */ new Date(),
10008
- aliasSeed: randomUUID()
10184
+ aliasSeed: randomUUID2()
10009
10185
  },
10010
10186
  publish: eventing.publish
10011
10187
  });
@@ -10581,24 +10757,6 @@ function uuidFromDigest3(digestValue) {
10581
10757
  }
10582
10758
 
10583
10759
  // src/activities/agent-turn/tool-policy.ts
10584
- function shouldStartOnTurnRecording(params) {
10585
- return params.recordingEnabled && params.desktopEnabled && desktopCapableBackend(params.establishedBackendId) && params.effectiveBackend !== "selfhosted";
10586
- }
10587
- function computerToolModeForTurn(resolvedModel) {
10588
- if (!resolvedModel) {
10589
- return "function-image";
10590
- }
10591
- if (!modelSupportsImageInputForTurn(resolvedModel)) {
10592
- return "disabled";
10593
- }
10594
- if (resolvedModel.provider.kind === "codex-subscription") {
10595
- return "function-image";
10596
- }
10597
- if (resolvedModel.provider.api === "chat") {
10598
- return "disabled";
10599
- }
10600
- return "function-image";
10601
- }
10602
10760
  function structuredToolTransportForTurn(resolvedModel) {
10603
10761
  if (!resolvedModel) return true;
10604
10762
  if (resolvedModel.provider.api === "chat") return false;
@@ -10621,7 +10779,7 @@ function lazyToolTransportForTurn(resolvedModel) {
10621
10779
  }
10622
10780
  function shouldDeferNonEagerToolPreparation(args) {
10623
10781
  return Boolean(
10624
- args.lazyToolTransport && args.progressiveDisclosureEnabled && !args.artifactRuntimeAvailable && args.triggerKind === "next" && (args.triggerType === "user.message" || args.triggerType === "system.update.delivered")
10782
+ args.lazyToolTransport && args.progressiveDisclosureEnabled && args.triggerKind === "next" && (args.triggerType === "user.message" || args.triggerType === "system.update.delivered")
10625
10783
  );
10626
10784
  }
10627
10785
  function hostedWebSearchForTurn(resolvedModel, deploymentWebSearchEnabled) {
@@ -10906,7 +11064,7 @@ async function prepareGovernanceAndModel(deps) {
10906
11064
  }
10907
11065
 
10908
11066
  // src/activities/agent-turn/compaction-prep.ts
10909
- import { isSessionCompactionRequested as isSessionCompactionRequested2 } from "@opengeni/db";
11067
+ import { hasPendingSteerAfterContextCompaction, isSessionCompactionRequested as isSessionCompactionRequested2 } from "@opengeni/db";
10910
11068
  import { publishDurableSessionEvents as publishDurableSessionEvents5 } from "@opengeni/events";
10911
11069
  import {
10912
11070
  appendSessionInstructions,
@@ -10977,6 +11135,8 @@ async function prepareCompaction(deps) {
10977
11135
  providerApi: resolvedModel?.provider.api ?? "responses",
10978
11136
  model: resolvedModel?.configured.id ?? turn.model,
10979
11137
  externallyBilled: billingState.isExternallyBilledTurn,
11138
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
11139
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
10980
11140
  turnAttemptId: input.attemptId,
10981
11141
  servingCredentialId: providerTurn.effectiveCodexCredentialId,
10982
11142
  priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,
@@ -11059,6 +11219,35 @@ async function prepareCompaction(deps) {
11059
11219
  };
11060
11220
  const compactionOnlyTurn = turn.source === "compaction";
11061
11221
  const remoteV2CompactionNeedsAgentPrefix = Boolean(remoteCompactionRequester) && session.codexCompactionMode === "remote_v2";
11222
+ const settleDeferredSteerAfterCompaction = async () => {
11223
+ if (compactionOnlyTurn) return null;
11224
+ const pending = await hasPendingSteerAfterContextCompaction(db, {
11225
+ accountId: input.accountId,
11226
+ workspaceId: input.workspaceId,
11227
+ sessionId: input.sessionId,
11228
+ turnId: turn.id,
11229
+ executionGeneration: attempt.executionGeneration,
11230
+ attemptId: input.attemptId
11231
+ });
11232
+ if (!pending) return null;
11233
+ if (!await eventing.settle({
11234
+ events: [
11235
+ {
11236
+ type: "turn.superseded",
11237
+ payload: { reason: "steer", deferredUntilCompaction: true }
11238
+ },
11239
+ { type: "session.status.changed", payload: { status: "queued" } }
11240
+ ],
11241
+ turnStatus: "superseded",
11242
+ sessionStatus: "queued",
11243
+ activeTurnId: null
11244
+ })) {
11245
+ return claimedResult({ status: "cancelled" });
11246
+ }
11247
+ control.turnMetricOutcome = "cancelled";
11248
+ control.activityStatus = "idle";
11249
+ return claimedResult({ status: "idle" });
11250
+ };
11062
11251
  if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {
11063
11252
  const compactionInstructions = appendWorkspaceMemory(
11064
11253
  appendSessionInstructions(
@@ -11190,7 +11379,8 @@ async function prepareCompaction(deps) {
11190
11379
  publishCompactionOutcomeEvents,
11191
11380
  compactionModeOptions,
11192
11381
  compactionOnlyTurn,
11193
- compactionSummarizerFor
11382
+ compactionSummarizerFor,
11383
+ settleDeferredSteerAfterCompaction
11194
11384
  }
11195
11385
  };
11196
11386
  }
@@ -11213,6 +11403,7 @@ async function runPostAgentCompaction(deps) {
11213
11403
  compactionModeOptions,
11214
11404
  compactionOnlyTurn,
11215
11405
  compactionSummarizerFor,
11406
+ settleDeferredSteerAfterCompaction,
11216
11407
  compactionModelHistoryProjector,
11217
11408
  media,
11218
11409
  agent
@@ -11379,6 +11570,12 @@ async function runPostAgentCompaction(deps) {
11379
11570
  }
11380
11571
  await publishCompactionOutcomeEvents(outcome.events);
11381
11572
  }
11573
+ if (outcome.events.some(
11574
+ (event) => event.type === "session.context.compacted" || event.type === "session.context.compaction.skipped"
11575
+ )) {
11576
+ const deferredSteer = await settleDeferredSteerAfterCompaction();
11577
+ if (deferredSteer) return { exit: deferredSteer };
11578
+ }
11382
11579
  } catch (compactError) {
11383
11580
  if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;
11384
11581
  if (compactError instanceof TurnAttemptFencedError) throw compactError;
@@ -11398,6 +11595,8 @@ async function runPostAgentCompaction(deps) {
11398
11595
  }
11399
11596
  );
11400
11597
  if (!isCompactionSummaryFailure(compactError)) throw compactError;
11598
+ const deferredSteer = await settleDeferredSteerAfterCompaction();
11599
+ if (deferredSteer) return { exit: deferredSteer };
11401
11600
  const errorMessage = String(compactionFailureReasonFromError(compactError));
11402
11601
  observability.error("context compaction failed", {
11403
11602
  sessionId: input.sessionId,
@@ -11441,20 +11640,16 @@ import {
11441
11640
  heartbeatLeaseHolder,
11442
11641
  readLease as readLease2,
11443
11642
  accrueWarmSeconds,
11444
- abandonRecordingForTurnAttempt,
11445
11643
  SandboxWorkspaceMutationFencedError
11446
11644
  } from "@opengeni/db";
11447
11645
  import {
11448
- RoutingMutationOutcomeUnknownError,
11449
- stopRecording as stopRecordingOnBox2
11646
+ RoutingMutationOutcomeUnknownError
11450
11647
  } from "@opengeni/runtime";
11451
11648
  import {
11452
11649
  sandboxLifecycleTransitionWaitMs,
11453
11650
  sandboxWarmRateMicrosPerSecond
11454
11651
  } from "@opengeni/config";
11455
11652
  import { ChannelAPartialMutationError } from "@opengeni/runtime/sandbox";
11456
- import { sandboxRunAs as sandboxRunAs3 } from "@opengeni/runtime";
11457
- import { randomUUID as randomUUID2 } from "crypto";
11458
11653
  function createSandboxTurnRuntime(deps) {
11459
11654
  const {
11460
11655
  input,
@@ -11466,7 +11661,6 @@ function createSandboxTurnRuntime(deps) {
11466
11661
  activityContext,
11467
11662
  sandboxRotationController,
11468
11663
  sandboxState,
11469
- recordingState,
11470
11664
  eventing,
11471
11665
  attempt
11472
11666
  } = deps;
@@ -11654,29 +11848,6 @@ function createSandboxTurnRuntime(deps) {
11654
11848
  clearInterval(sandboxState.leaseHeartbeatTimer);
11655
11849
  sandboxState.leaseHeartbeatTimer = void 0;
11656
11850
  };
11657
- const abandonActiveRecording = async (reason, disposition = "failed") => {
11658
- const recording = recordingState.activeRecording;
11659
- if (!recording) return;
11660
- recordingState.activeRecording = null;
11661
- if (sandboxState.resolvedSandbox) {
11662
- await stopRecordingOnBox2(
11663
- sandboxState.resolvedSandbox.established.session,
11664
- recording.proc
11665
- ).catch(() => void 0);
11666
- }
11667
- if (!attempt.turnId || attempt.executionGeneration <= 0) return;
11668
- await abandonRecordingForTurnAttempt(db, {
11669
- accountId: input.accountId,
11670
- workspaceId: input.workspaceId,
11671
- sessionId: input.sessionId,
11672
- turnId: attempt.turnId,
11673
- executionGeneration: attempt.executionGeneration,
11674
- attemptId: input.attemptId,
11675
- recordingId: recording.recordingId,
11676
- disposition,
11677
- reason
11678
- }).catch(() => void 0);
11679
- };
11680
11851
  const flushRuntimeBatcher = async () => {
11681
11852
  const current = eventing.batcher;
11682
11853
  await current?.flush().catch(() => void 0);
@@ -11843,64 +12014,6 @@ function createSandboxTurnRuntime(deps) {
11843
12014
  sandboxState.leaseHeartbeatTimer.unref();
11844
12015
  }
11845
12016
  };
11846
- const maybeStartOnTurnRecording = async (sandbox, effectiveBackend) => {
11847
- if (recordingState.activeRecording) {
11848
- return;
11849
- }
11850
- if (recordingState.computerUseRecordingStart) {
11851
- await recordingState.computerUseRecordingStart;
11852
- return;
11853
- }
11854
- if (shouldStartOnTurnRecording({
11855
- recordingEnabled: settings.recordingEnabled,
11856
- desktopEnabled: settings.sandboxDesktopEnabled,
11857
- establishedBackendId: sandbox.established.backendId,
11858
- // EFFECTIVE (active) backend, not the session home: a machine-primary turn
11859
- // resolves to "selfhosted" and skips; a swap back to the cloud group box
11860
- // resolves to undefined and records as before.
11861
- effectiveBackend
11862
- })) {
11863
- recordingState.computerUseRecordingStart = (async () => {
11864
- let begun = null;
11865
- try {
11866
- begun = await beginRecording({
11867
- settings,
11868
- db,
11869
- accountId: input.accountId,
11870
- workspaceId: input.workspaceId,
11871
- sessionId: input.sessionId,
11872
- turnId: attempt.turnId,
11873
- recordingId: randomUUID2(),
11874
- mode: "on-turn",
11875
- session: sandbox.established.session,
11876
- runAs: sandboxRunAs3(settings),
11877
- reason: null
11878
- });
11879
- if (!eventing.publish) {
11880
- throw new Error("recording started before the turn event publisher was ready");
11881
- }
11882
- await eventing.publish([{ type: "recording.started", payload: begun.started }]);
11883
- recordingState.activeRecording = begun.active;
11884
- } catch (recordingError) {
11885
- recordingState.activeRecording = null;
11886
- if (begun) {
11887
- await discardUnpublishedRecording({
11888
- db,
11889
- accountId: input.accountId,
11890
- workspaceId: input.workspaceId,
11891
- active: begun.active,
11892
- session: sandbox.established.session
11893
- });
11894
- }
11895
- console.error(
11896
- "computer-use recording start failed (action outcome unaffected)",
11897
- safeErrorDiagnostic(recordingError)
11898
- );
11899
- }
11900
- })();
11901
- await recordingState.computerUseRecordingStart;
11902
- }
11903
- };
11904
12017
  return {
11905
12018
  releaseLateSandbox,
11906
12019
  requireResolvedSandboxForMutation,
@@ -11908,12 +12021,10 @@ function createSandboxTurnRuntime(deps) {
11908
12021
  onHomeSandboxRebound,
11909
12022
  runWorkspaceMutationForSandbox,
11910
12023
  stopLeaseHeartbeat,
11911
- abandonActiveRecording,
11912
12024
  flushRuntimeBatcher,
11913
12025
  publishSandboxLifecycleEvents,
11914
12026
  publishSandboxLost,
11915
- startLeaseHeartbeat,
11916
- maybeStartOnTurnRecording
12027
+ startLeaseHeartbeat
11917
12028
  };
11918
12029
  }
11919
12030
 
@@ -11933,6 +12044,7 @@ import {
11933
12044
  sdkBackendIdForSandboxBackend,
11934
12045
  resolveConnectedMachineWorkspaceRoot as resolveConnectedMachineWorkspaceRoot2
11935
12046
  } from "@opengeni/runtime";
12047
+ import { managedSessionGroupBackend, managedSessionGroupOs } from "@opengeni/core";
11936
12048
 
11937
12049
  // src/sandbox-routing.ts
11938
12050
  import { sandboxLifecycleTransitionWaitMs as sandboxLifecycleTransitionWaitMs2 } from "@opengeni/config";
@@ -12251,7 +12363,7 @@ function settleRetainedProcessForTurn(services, ids) {
12251
12363
  if (!durable || durable.providerSessionId !== process2.providerSessionId || durable.providerBackend !== backend.kind || durable.providerInstanceId !== backend.providerInstanceId || durable.leaseEpoch !== backend.leaseEpoch || durable.routeKind !== (backend.sandboxId === null ? "home" : "active") || durable.routeTargetId !== backend.sandboxId || durable.routeEpoch !== backend.activeEpoch) {
12252
12364
  throw new Error("Retained-process settlement lost its exact durable backend identity");
12253
12365
  }
12254
- await settleRetainedProcess(services.db, {
12366
+ const settlement = await settleRetainedProcess(services.db, {
12255
12367
  accountId: fence.accountId,
12256
12368
  workspaceId: ids.workspaceId,
12257
12369
  sessionId: ids.sessionId,
@@ -12262,14 +12374,17 @@ function settleRetainedProcessForTurn(services, ids) {
12262
12374
  reason: proof.reason,
12263
12375
  idleGraceMs: services.settings.sandboxIdleGraceMs
12264
12376
  });
12377
+ if (settlement.process.state === "active") {
12378
+ throw new Error("Retained-process settlement returned an active durable process");
12379
+ }
12265
12380
  await settleSessionBackgroundCommandForRetainedProcess(services.db, {
12266
12381
  accountId: fence.accountId,
12267
12382
  workspaceId: ids.workspaceId,
12268
12383
  sessionId: ids.sessionId,
12269
12384
  retainedProcessId: process2.id,
12270
- outcome: proof.outcome,
12271
- exitCode: proof.exitCode,
12272
- reason: proof.reason
12385
+ outcome: settlement.process.state,
12386
+ exitCode: settlement.process.exitCode,
12387
+ reason: settlement.process.settlementReason ?? proof.reason
12273
12388
  });
12274
12389
  };
12275
12390
  }
@@ -12832,6 +12947,9 @@ function managedSandboxOwnershipForTurn(machinePrimary, attemptId, sandboxGroupI
12832
12947
  sandboxGroupId
12833
12948
  };
12834
12949
  }
12950
+ function sandboxSettingsForRoute(input) {
12951
+ return input.runSettings.sandboxBackend === "selfhosted" && !input.machinePrimary && input.groupBoxBackend !== "selfhosted" ? { ...input.runSettings, sandboxBackend: input.groupBoxBackend } : input.runSettings;
12952
+ }
12835
12953
  function shouldEstablishSandboxForTurn(sandboxOwnershipEnabled, homeBackend, machinePrimary) {
12836
12954
  return sandboxOwnershipEnabled && (homeBackend !== "none" || machinePrimary);
12837
12955
  }
@@ -13017,11 +13135,22 @@ async function resolveSandboxRoute(deps) {
13017
13135
  sandboxBackend: "selfhosted"
13018
13136
  };
13019
13137
  }
13020
- const groupBoxBackend = runSettings.sandboxBackend === "selfhosted" && !machinePrimary ? settings.sandboxBackend : runSettings.sandboxBackend;
13138
+ const groupBoxBackend = !machinePrimary ? managedSessionGroupBackend(settings.sandboxBackend, runSettings.sandboxBackend) ?? runSettings.sandboxBackend : runSettings.sandboxBackend;
13139
+ const groupRouteSettings = sandboxSettingsForRoute({
13140
+ runSettings,
13141
+ machinePrimary,
13142
+ groupBoxBackend
13143
+ });
13144
+ if (groupRouteSettings !== runSettings) {
13145
+ eventing.modelRunSettings = {
13146
+ ...eventing.modelRunSettings,
13147
+ sandboxBackend: groupRouteSettings.sandboxBackend
13148
+ };
13149
+ }
13021
13150
  sandboxState.startupMilestoneBackend = activeSandboxBackend ?? groupBoxBackend;
13022
13151
  media.sandboxFileDownloadBackend = sandboxState.startupMilestoneBackend;
13023
13152
  const groupBoxImage = rigProviderImageSourceImage(logicalSandboxSettings, groupBoxBackend);
13024
- const sandboxCreationBackend = settings.sandboxOwnershipEnabled && runSettings.sandboxBackend !== "none" ? groupBoxBackend : runSettings.sandboxBackend;
13153
+ const sandboxCreationBackend = groupRouteSettings.sandboxBackend;
13025
13154
  const effectiveRunCredentialBackend = activeSandboxBackend ?? groupBoxBackend;
13026
13155
  return {
13027
13156
  routingOn,
@@ -13072,6 +13201,7 @@ async function establishTurnSandbox(deps) {
13072
13201
  rigVersion,
13073
13202
  turnResources
13074
13203
  } = deps;
13204
+ const groupBoxOs = managedSessionGroupOs(runSettings.sandboxBackend, session.sandboxOs);
13075
13205
  const {
13076
13206
  releaseLateSandbox,
13077
13207
  onHomeSandboxRebound,
@@ -13276,7 +13406,7 @@ async function establishTurnSandbox(deps) {
13276
13406
  sandboxGroupId: lazyGroupId,
13277
13407
  sessionId: input.sessionId,
13278
13408
  backend: groupBoxBackend,
13279
- os: session.sandboxOs,
13409
+ os: groupBoxOs,
13280
13410
  environment: sandboxEnvironment,
13281
13411
  ...groupBoxImage ? {
13282
13412
  image: groupBoxImage
@@ -13351,7 +13481,7 @@ async function establishTurnSandbox(deps) {
13351
13481
  // deployment default), never a "selfhosted" box (which would throw
13352
13482
  // for lack of a bound agentId).
13353
13483
  backend: groupBoxBackend,
13354
- os: session.sandboxOs,
13484
+ os: groupBoxOs,
13355
13485
  environment: sandboxEnvironment,
13356
13486
  // IMAGE IS SHARED STATE (B3): the container image
13357
13487
  // this run resolves. The lease stamps it + conflicts on a live shared box
@@ -13628,6 +13758,19 @@ async function bindLazySandboxProvisioner(deps) {
13628
13758
  commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
13629
13759
  eventing.toolCancellationFenceRef.current
13630
13760
  )
13761
+ } : {},
13762
+ ...sandboxState.sandboxGroupId && sandboxState.sandboxHolderId ? {
13763
+ coordinateSharedRigSetup: createSharedRigSetupCoordinator({
13764
+ db,
13765
+ accountId: input.accountId,
13766
+ workspaceId: input.workspaceId,
13767
+ sandboxGroupId: sandboxState.sandboxGroupId,
13768
+ attemptId: input.attemptId,
13769
+ holderId: sandboxState.sandboxHolderId,
13770
+ sandbox: provisioned,
13771
+ ...runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {},
13772
+ observe: (measurement) => recordSandboxSharedPreparation(observability, measurement)
13773
+ })
13631
13774
  } : {}
13632
13775
  }
13633
13776
  ),
@@ -14391,7 +14534,7 @@ async function bindRunCredentialResolver(input) {
14391
14534
  }
14392
14535
 
14393
14536
  // src/activities/agent-turn/run-credentials.ts
14394
- import { sandboxRunAs as sandboxRunAs4 } from "@opengeni/runtime";
14537
+ import { sandboxRunAs as sandboxRunAs3 } from "@opengeni/runtime";
14395
14538
  async function prepareRunCredentials(deps) {
14396
14539
  const {
14397
14540
  input,
@@ -14421,6 +14564,11 @@ async function prepareRunCredentials(deps) {
14421
14564
  connectionScope,
14422
14565
  runWorkspaceMutationForSandbox
14423
14566
  } = deps;
14567
+ const sandboxEnvironmentSettings = sandboxSettingsForRoute({
14568
+ runSettings,
14569
+ machinePrimary,
14570
+ groupBoxBackend
14571
+ });
14424
14572
  const runCredentialResolver = effectiveRunCredentialBackend === "none" ? null : await waitForTurnOperation(
14425
14573
  bindRunCredentialResolver({
14426
14574
  db,
@@ -14555,7 +14703,7 @@ async function prepareRunCredentials(deps) {
14555
14703
  codemodeTokenExpiresAt: sandboxCodemodeTokenExpiresAt
14556
14704
  } = await waitForTurnOperation(
14557
14705
  sandboxEnvironmentForRun(
14558
- runSettings,
14706
+ sandboxEnvironmentSettings,
14559
14707
  turnResources,
14560
14708
  // Rig default sets merged BELOW the session set (session wins); rig-less
14561
14709
  // turns pass exactly workspaceVariableSet?.values (byte-for-byte today).
@@ -14646,7 +14794,7 @@ async function prepareRunCredentials(deps) {
14646
14794
  if (!pendingBinding) {
14647
14795
  throw new Error("credential renewal produced no binding token");
14648
14796
  }
14649
- const runAs = sandboxRunAs4(runSettings);
14797
+ const runAs = sandboxRunAs3(runSettings);
14650
14798
  const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
14651
14799
  if (!targetSandbox) {
14652
14800
  throw new Error("Git credential renewal has no exact sandbox lease target");
@@ -14713,7 +14861,7 @@ async function prepareRunCredentials(deps) {
14713
14861
  };
14714
14862
  const write = async (material) => {
14715
14863
  if (tokenSession) {
14716
- const runAs = sandboxRunAs4(runSettings);
14864
+ const runAs = sandboxRunAs3(runSettings);
14717
14865
  const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
14718
14866
  if (!targetSandbox) {
14719
14867
  throw new Error("Codemode token renewal has no exact sandbox lease target");
@@ -14916,10 +15064,17 @@ async function prepareRunCredentials(deps) {
14916
15064
  // src/activities/agent-turn/tool-environment.ts
14917
15065
  import {
14918
15066
  getScheduledVariableSetExpectedGenerationForAttempt,
15067
+ getWorkspaceModelPolicy as getWorkspaceModelPolicy2,
15068
+ listWorkspaceGatewayCustomModels as listWorkspaceGatewayCustomModels2,
15069
+ listWorkspaceOpenRouterCustomModels as listWorkspaceOpenRouterCustomModels2,
14919
15070
  persistAttemptToolCatalog,
14920
15071
  namedSubjectHasLiveWorkspaceAuthority as namedSubjectHasLiveWorkspaceAuthority2,
14921
15072
  updateSessionTitleWithEvent,
14922
- withCodexAppsRequestAuthorization
15073
+ withCodexAppsRequestAuthorization,
15074
+ workspaceCodexSubscriptionActive as workspaceCodexSubscriptionActive3,
15075
+ workspaceVercelAiGatewayConnectionActive,
15076
+ workspaceOpenRouterConnectionActive,
15077
+ workspaceXaiSubscriptionActiveForAuthority
14923
15078
  } from "@opengeni/db";
14924
15079
  import { publishDurableSessionEvents as publishDurableSessionEvents8 } from "@opengeni/events";
14925
15080
  import {
@@ -15833,6 +15988,7 @@ import {
15833
15988
  } from "@opengeni/codemode";
15834
15989
  import { createGitHubAppInstallationTokenWithExpiry as createGitHubAppInstallationTokenWithExpiry2, githubAppBotIdentity as githubAppBotIdentity2 } from "@opengeni/github";
15835
15990
  import {
15991
+ ConnectorActionBindingRejectedError,
15836
15992
  prefixedMcpToolName
15837
15993
  } from "@opengeni/runtime";
15838
15994
  import {
@@ -16007,9 +16163,12 @@ function appRepositoryAuthority(resources) {
16007
16163
  );
16008
16164
  const repositoryId = positiveSafeInteger(resource.githubRepositoryId ?? resource.repositoryId);
16009
16165
  const fullName = canonicalGitHubFullName(resource.uri);
16010
- if (!installationId || !repositoryId || !fullName) {
16166
+ if (!installationId || !repositoryId) {
16011
16167
  throw new GitHubRestAuthorityError("GitHub App repository authority is incomplete");
16012
16168
  }
16169
+ if (!fullName) {
16170
+ throw new GitHubRestAuthorityError("GitHub App repository URL is invalid");
16171
+ }
16013
16172
  return [
16014
16173
  {
16015
16174
  repositoryId: String(repositoryId),
@@ -16264,7 +16423,7 @@ function githubConnectorBindings(serverId, repositories) {
16264
16423
  const args = objectRecord(arguments_);
16265
16424
  const repository = typeof args.repository === "string" ? byName.get(args.repository.toLowerCase()) : null;
16266
16425
  if (!repository) {
16267
- throw new GitHubRestAuthorityError(
16426
+ throw new ConnectorActionBindingRejectedError(
16268
16427
  "GitHub action repository does not match an accepted resource"
16269
16428
  );
16270
16429
  }
@@ -16285,8 +16444,9 @@ function githubConnectorBindings(serverId, repositories) {
16285
16444
  function canonicalGitHubFullName(uri) {
16286
16445
  try {
16287
16446
  const url = new URL(uri);
16288
- const path = url.pathname.replace(/^\/+|\/+$/gu, "");
16289
- if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash || path.endsWith(".git") || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(path)) {
16447
+ const clonePath = url.pathname.replace(/^\/+|\/+$/gu, "");
16448
+ const path = clonePath.endsWith(".git") ? clonePath.slice(0, -4) : clonePath;
16449
+ if (url.protocol !== "https:" || url.hostname !== "github.com" || url.port || url.username || url.password || url.search || url.hash || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(path)) {
16290
16450
  return null;
16291
16451
  }
16292
16452
  return path;
@@ -16731,11 +16891,13 @@ import {
16731
16891
  defaultSessionMcpServerIds,
16732
16892
  loadRigDefaultVariableSetEnvironment,
16733
16893
  mergeRigDefaultVariableSetEnvironment,
16894
+ resolveCatalogSettings as resolveCatalogSettings2,
16895
+ resolveWorkspaceModelSelection,
16734
16896
  withFrozenPersonalConnectionDelegations,
16735
16897
  resolveSessionToolPolicy
16736
16898
  } from "@opengeni/core";
16737
16899
  import { SandboxChannelAService as SandboxChannelAService3 } from "@opengeni/runtime/sandbox";
16738
- import { sandboxRunAs as sandboxRunAs5 } from "@opengeni/runtime";
16900
+ import { sandboxRunAs as sandboxRunAs4 } from "@opengeni/runtime";
16739
16901
 
16740
16902
  // src/activities/agent-turn/session-title.ts
16741
16903
  import { hasPermission } from "@opengeni/core";
@@ -16815,6 +16977,98 @@ function createSessionTitleAttemptToolDefinition(input) {
16815
16977
  };
16816
16978
  }
16817
16979
 
16980
+ // src/activities/agent-turn/turn-sandbox-access.ts
16981
+ async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, unavailableMessage) {
16982
+ let sandbox = sandboxState.resolvedSandbox;
16983
+ if (!sandbox && sandboxState.turnSandboxProvisioner) {
16984
+ sandbox = await sandboxState.turnSandboxProvisioner.get();
16985
+ }
16986
+ const session = sandboxState.lazyOwnedSandbox?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
16987
+ if (!session) throw new Error(unavailableMessage);
16988
+ return {
16989
+ sandbox,
16990
+ session,
16991
+ leaseEpoch: sandbox?.leaseEpoch ?? 0
16992
+ };
16993
+ }
16994
+
16995
+ // src/activities/agent-turn/list-models.ts
16996
+ import {
16997
+ compareModelPickerOrder,
16998
+ modelPickerBillingClassFor
16999
+ } from "@opengeni/contracts/model-picker-order";
17000
+ var LIST_MODELS_TOOL_NAME = "list_models";
17001
+ var LIST_MODELS_TOOL_DESCRIPTION = "List the models this workspace can select right now, in picker order, with deployment-defined cost and optional guidance. This does not switch the current session model; use an ID with session_create or the human model picker.";
17002
+ function safeLineField(value) {
17003
+ return value.replace(/[\r\n|]/gu, " ").replace(/\s+/gu, " ").trim();
17004
+ }
17005
+ function renderListModels(input) {
17006
+ const lines = [];
17007
+ if (input.currentModelId) {
17008
+ lines.push(`Current: ${safeLineField(input.currentModelId)}`);
17009
+ }
17010
+ const selectable = input.selections.filter((entry) => entry.availability.selectable).map((selection) => ({
17011
+ selection,
17012
+ billingClass: modelPickerBillingClassFor(selection.model),
17013
+ selectable: selection.availability.selectable,
17014
+ label: selection.model.label
17015
+ })).sort(compareModelPickerOrder);
17016
+ if (selectable.length === 0) {
17017
+ lines.push("No models are available in this workspace.");
17018
+ return lines.join("\n");
17019
+ }
17020
+ for (const { selection } of selectable) {
17021
+ const { model } = selection;
17022
+ const fields = [safeLineField(model.id), safeLineField(model.label), model.cost];
17023
+ const note = input.modelNotes[model.id];
17024
+ if (note) fields.push(safeLineField(note));
17025
+ lines.push(`- ${fields.join(" | ")}`);
17026
+ }
17027
+ return lines.join("\n");
17028
+ }
17029
+ function createListModelsAttemptToolDefinition(input) {
17030
+ return {
17031
+ identity: { serverId: "opengeni", toolName: LIST_MODELS_TOOL_NAME },
17032
+ modelName: LIST_MODELS_TOOL_NAME,
17033
+ codemodePath: ["opengeni", LIST_MODELS_TOOL_NAME],
17034
+ title: "List selectable models",
17035
+ description: LIST_MODELS_TOOL_DESCRIPTION,
17036
+ inputSchema: {
17037
+ type: "object",
17038
+ properties: {},
17039
+ additionalProperties: false
17040
+ },
17041
+ annotations: {
17042
+ title: "List selectable models",
17043
+ readOnlyHint: true,
17044
+ destructiveHint: false,
17045
+ idempotentHint: true,
17046
+ openWorldHint: false
17047
+ },
17048
+ source: "opengeni",
17049
+ approval: "none",
17050
+ execute: async (args) => {
17051
+ if (Object.keys(args).length !== 0) {
17052
+ throw new Error("list_models accepts no arguments");
17053
+ }
17054
+ const catalog = await input.load();
17055
+ return {
17056
+ isError: false,
17057
+ content: [
17058
+ {
17059
+ type: "text",
17060
+ text: renderListModels({
17061
+ currentModelId: input.currentModelId,
17062
+ selections: catalog.selections,
17063
+ modelNotes: catalog.modelNotes
17064
+ })
17065
+ }
17066
+ ]
17067
+ };
17068
+ }
17069
+ };
17070
+ }
17071
+
16818
17072
  // src/activities/agent-turn/tool-environment.ts
16819
17073
  async function prepareTurnToolPolicy(deps) {
16820
17074
  const {
@@ -16936,6 +17190,7 @@ async function prepareTurnToolPolicy(deps) {
16936
17190
  async function prepareTurnToolRuntime(deps) {
16937
17191
  const {
16938
17192
  input,
17193
+ catalogSourceSettings,
16939
17194
  db,
16940
17195
  bus,
16941
17196
  runtime,
@@ -17121,6 +17376,53 @@ async function prepareTurnToolRuntime(deps) {
17121
17376
  }
17122
17377
  ] : [];
17123
17378
  const attemptToolDefinitions = [
17379
+ createListModelsAttemptToolDefinition({
17380
+ currentModelId: turnExecutionPolicy.productModelId,
17381
+ load: async () => {
17382
+ const currentCatalog = await resolveCatalogSettings2(db, catalogSourceSettings);
17383
+ const currentSettings = currentCatalog.settings;
17384
+ const xaiReadinessAuthority = xaiCatalogReadinessAuthority(turn, credentialSubjectId);
17385
+ const [
17386
+ policy,
17387
+ codexSubscriptionActive,
17388
+ xaiSubscriptionActive,
17389
+ workspaceGatewayConnectionActive,
17390
+ workspaceGatewayCustomModels,
17391
+ openRouterConnectionActive,
17392
+ workspaceOpenRouterCustomModels
17393
+ ] = await Promise.all([
17394
+ getWorkspaceModelPolicy2(db, input.workspaceId),
17395
+ workspaceCodexSubscriptionActive3(db, currentSettings, input.workspaceId),
17396
+ xaiReadinessAuthority && currentSettings.supergrokSubscriptionEnabled ? workspaceXaiSubscriptionActiveForAuthority(db, currentSettings, {
17397
+ workspaceId: input.workspaceId,
17398
+ ...xaiReadinessAuthority
17399
+ }) : false,
17400
+ workspaceVercelAiGatewayConnectionActive(db, input.workspaceId),
17401
+ listWorkspaceGatewayCustomModels2(db, {
17402
+ accountId: input.accountId,
17403
+ workspaceId: input.workspaceId
17404
+ }),
17405
+ workspaceOpenRouterConnectionActive(db, input.workspaceId),
17406
+ listWorkspaceOpenRouterCustomModels2(db, {
17407
+ accountId: input.accountId,
17408
+ workspaceId: input.workspaceId
17409
+ })
17410
+ ]);
17411
+ return {
17412
+ selections: resolveWorkspaceModelSelection({
17413
+ settings: currentSettings,
17414
+ policy,
17415
+ codexSubscriptionActive,
17416
+ xaiSubscriptionActive,
17417
+ workspaceGatewayConnectionActive,
17418
+ workspaceGatewayCustomModels,
17419
+ workspaceOpenRouterConnectionActive: openRouterConnectionActive,
17420
+ workspaceOpenRouterCustomModels
17421
+ }),
17422
+ modelNotes: currentCatalog.modelNotes
17423
+ };
17424
+ }
17425
+ }),
17124
17426
  ...titleToolPlan.promoteTitleTool ? [
17125
17427
  createSessionTitleAttemptToolDefinition({
17126
17428
  updateTitle: async (title) => {
@@ -17185,19 +17487,17 @@ async function prepareTurnToolRuntime(deps) {
17185
17487
  const materializeConnectorAttachments = async (request) => {
17186
17488
  throwIfWorkerShuttingDown();
17187
17489
  throwIfTurnCancelled();
17188
- let sandbox = sandboxState.resolvedSandbox;
17189
- if (!sandbox && sandboxState.turnSandboxProvisioner) {
17190
- sandbox = await sandboxState.turnSandboxProvisioner.get();
17191
- }
17192
- const sessionForImport = sandboxState.lazyOwnedSandbox?.session ?? sandbox?.established.session ?? media.sdkOwnedSandboxSession;
17193
- if (!sessionForImport) {
17194
- throw new Error("Connector attachment sandbox is unavailable");
17195
- }
17196
- const runAs = sandboxRunAs5(runSettings);
17490
+ const sandboxAccess = await resolveTurnSandboxAccess(
17491
+ sandboxState,
17492
+ media.sdkOwnedSandboxSession,
17493
+ "Connector attachment sandbox is unavailable"
17494
+ );
17495
+ const sandbox = sandboxAccess.sandbox;
17496
+ const runAs = sandboxRunAs4(runSettings);
17197
17497
  const channel = new SandboxChannelAService3({
17198
- session: sessionForImport,
17498
+ session: sandboxAccess.session,
17199
17499
  workspaceRoot: "/workspace",
17200
- leaseEpoch: sandbox?.leaseEpoch ?? 0,
17500
+ leaseEpoch: sandboxAccess.leaseEpoch,
17201
17501
  emit: async (events) => {
17202
17502
  await eventing.publish?.(events, true);
17203
17503
  },
@@ -17540,8 +17840,8 @@ import {
17540
17840
  import {
17541
17841
  serviceTierForLatencyMode,
17542
17842
  environmentsEncryptionKeyBytes as environmentsEncryptionKeyBytes4,
17543
- WORKSPACE_GATEWAY_PROVIDER_ID,
17544
- resolveModelProvider
17843
+ WORKSPACE_GATEWAY_PROVIDER_ID as WORKSPACE_GATEWAY_PROVIDER_ID2,
17844
+ resolveModelProvider as resolveModelProvider2
17545
17845
  } from "@opengeni/config";
17546
17846
 
17547
17847
  // src/activities/xai-image-generation.ts
@@ -18615,19 +18915,16 @@ async function referenceBytes(input, reference2) {
18615
18915
  );
18616
18916
  }
18617
18917
  return {
18618
- bytes: await readStoredFile(input.objectStorage, file),
18918
+ bytes: await readStoredImageReferenceFile(input.objectStorage, file),
18619
18919
  file
18620
18920
  };
18621
18921
  }
18622
- async function readStoredFile(objectStorage, file) {
18623
- const bytes = await objectStorage.getFileRange(file, {
18624
- start: 0,
18625
- end: file.sizeBytes - 1
18626
- });
18627
- if (!bytes) {
18922
+ async function readStoredImageReferenceFile(objectStorage, file) {
18923
+ const bytes = await objectStorage.getFileBytes(file);
18924
+ if (bytes.byteLength !== file.sizeBytes) {
18628
18925
  throw new ImageGenerationReferenceError(
18629
- "reference_unavailable",
18630
- "The durable image reference bytes are unavailable."
18926
+ "reference_integrity_mismatch",
18927
+ "The durable image reference bytes do not match their file metadata."
18631
18928
  );
18632
18929
  }
18633
18930
  return bytes;
@@ -18679,23 +18976,17 @@ function validateReferenceImage(bytes) {
18679
18976
 
18680
18977
  // src/activities/agent-turn/agent-build.ts
18681
18978
  import { SandboxChannelAService as SandboxChannelAService4 } from "@opengeni/runtime/sandbox";
18682
- import { sandboxRunAs as sandboxRunAs6 } from "@opengeni/runtime";
18979
+ import { sandboxRunAs as sandboxRunAs5 } from "@opengeni/runtime";
18683
18980
  import { VideoGenerationRejectedResult } from "@opengeni/contracts";
18684
18981
 
18685
- // src/activities/agent-turn/image-reference-sandbox.ts
18686
- async function resolveImageReferenceSandboxSession(sandboxState, sdkOwnedSandboxSession) {
18687
- let sandbox = sandboxState.resolvedSandbox;
18688
- if (!sandbox && sandboxState.turnSandboxProvisioner) {
18689
- sandbox = await sandboxState.turnSandboxProvisioner.get();
18690
- }
18691
- const session = sandboxState.lazyOwnedSandbox?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
18692
- if (!session) {
18693
- throw new Error("Sandbox image reference is unavailable");
18694
- }
18695
- return {
18696
- session,
18697
- leaseEpoch: sandbox?.leaseEpoch ?? 0
18698
- };
18982
+ // src/activities/agent-turn/video-reference-sandbox.ts
18983
+ async function resolveVideoReferenceSandboxAccess(request, sandboxState, sdkOwnedSandboxSession) {
18984
+ if (videoReferencePaths(request).length === 0) return null;
18985
+ return await resolveTurnSandboxAccess(
18986
+ sandboxState,
18987
+ sdkOwnedSandboxSession,
18988
+ "Video reference sandbox is unavailable"
18989
+ );
18699
18990
  }
18700
18991
 
18701
18992
  // src/activities/agent-turn/agent-build.ts
@@ -18710,8 +19001,6 @@ async function buildTurnAgent(deps) {
18710
19001
  runtimeCancellationSignal,
18711
19002
  eventing,
18712
19003
  sandboxState,
18713
- recordingState,
18714
- maybeStartOnTurnRecording,
18715
19004
  providerTurn,
18716
19005
  media,
18717
19006
  leases,
@@ -18778,12 +19067,13 @@ async function buildTurnAgent(deps) {
18778
19067
  subjectId: fileAuthoritySubjectId,
18779
19068
  references,
18780
19069
  readSandboxFile: async (path, maxBytes) => {
18781
- const imageReferenceSandbox = await resolveImageReferenceSandboxSession(
19070
+ const imageReferenceSandbox = await resolveTurnSandboxAccess(
18782
19071
  sandboxState,
18783
- media.sdkOwnedSandboxSession
19072
+ media.sdkOwnedSandboxSession,
19073
+ "Sandbox image reference is unavailable"
18784
19074
  );
18785
19075
  const relativePath = path.slice("/workspace/".length);
18786
- const referenceRunAs = sandboxRunAs6(eventing.modelRunSettings);
19076
+ const referenceRunAs = sandboxRunAs5(eventing.modelRunSettings);
18787
19077
  const channel = new SandboxChannelAService4({
18788
19078
  session: imageReferenceSandbox.session,
18789
19079
  workspaceRoot: "/workspace",
@@ -18883,9 +19173,9 @@ async function buildTurnAgent(deps) {
18883
19173
  }
18884
19174
  };
18885
19175
  }
18886
- const gatewayResolution = resolveModelProvider(
19176
+ const gatewayResolution = resolveModelProvider2(
18887
19177
  capabilitySettings,
18888
- WORKSPACE_GATEWAY_PROVIDER_ID
19178
+ WORKSPACE_GATEWAY_PROVIDER_ID2
18889
19179
  );
18890
19180
  const gateway = gatewayResolution?.provider;
18891
19181
  if (gateway?.kind !== "vercel-gateway-workspace" || !gateway.apiKey) return {};
@@ -19007,9 +19297,16 @@ async function buildTurnAgent(deps) {
19007
19297
  videoGeneration: {
19008
19298
  capabilities: async () => capabilities,
19009
19299
  execute: async (toolInput, { toolCallId }) => {
19010
- const sessionForReference = sandboxState.resolvedSandbox?.established.session ?? media.sdkOwnedSandboxSession;
19300
+ const referenceSandbox = await resolveVideoReferenceSandboxAccess(
19301
+ toolInput,
19302
+ sandboxState,
19303
+ media.sdkOwnedSandboxSession
19304
+ );
19011
19305
  const fence = eventing.toolCancellationFenceRef.current;
19012
- const runAs = sandboxRunAs6(eventing.modelRunSettings);
19306
+ if (referenceSandbox && !fence) {
19307
+ throw new Error("Video reference command fence is unavailable");
19308
+ }
19309
+ const runAs = sandboxRunAs5(eventing.modelRunSettings);
19013
19310
  let accepted;
19014
19311
  try {
19015
19312
  accepted = await admitVideoGenerationRequest({
@@ -19025,9 +19322,9 @@ async function buildTurnAgent(deps) {
19025
19322
  toolInput,
19026
19323
  policy: videoGenerationPolicy,
19027
19324
  credential: videoGenerationCredential,
19028
- ...sessionForReference && fence ? {
19325
+ ...referenceSandbox && fence ? {
19029
19326
  runCommand: async (command) => await fence.runSandboxCommandStructured(
19030
- sessionForReference,
19327
+ referenceSandbox.session,
19031
19328
  {
19032
19329
  ...command,
19033
19330
  ...runAs ? { runAs } : {}
@@ -19184,29 +19481,15 @@ async function buildTurnAgent(deps) {
19184
19481
  // typed input_image content. Chat wires have no proven typed image
19185
19482
  // result transport and therefore receive no view_image tool.
19186
19483
  structuredToolTransport: structuredToolTransportForTurn(resolvedModel),
19187
- // EXPLICIT computer-use tool transport. See {@link computerToolModeForTurn}.
19188
- computerToolMode: computerToolModeForTurn(resolvedModel),
19189
19484
  ...promptCacheKey ? { promptCacheKey } : {}
19190
19485
  } : (
19191
19486
  // LEGACY global-client fallback (resolveTurnModel returned null → the model
19192
19487
  // is not in the registry, served by the built-in OpenAI/Azure Responses
19193
- // client). Pin computerToolMode to function-image EXPLICITLY rather than
19194
- // leaving the runtime to sniff the instance.
19488
+ // client).
19195
19489
  {
19196
- computerToolMode: computerToolModeForTurn(null),
19197
19490
  promptCacheKey: input.sessionId
19198
19491
  }
19199
19492
  ),
19200
- // Lazy computer-use seam: runtime first brings up :0 only after the model
19201
- // selects a computer tool, then this hook begins the optional proof
19202
- // recording. Shell/filesystem turns never invoke either operation.
19203
- onComputerUseReady: async () => {
19204
- if (!sandboxState.resolvedSandbox) {
19205
- throw new Error("Computer-use display became ready without a resolved sandbox");
19206
- }
19207
- recordingState.didComputerUse = true;
19208
- await maybeStartOnTurnRecording(sandboxState.resolvedSandbox, activeSandboxBackend);
19209
- },
19210
19493
  onRetainableSessionImageOutput: media.retainSessionImageAtToolBoundary,
19211
19494
  ...runtimeSkillActivations.length > 0 ? { skillActivations: runtimeSkillActivations } : {},
19212
19495
  ...!structuredWorkspacePolicyActive && workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {},
@@ -19276,6 +19559,7 @@ function createRunAgentTurnActivity(services) {
19276
19559
  return async function runAgentTurn(input) {
19277
19560
  const {
19278
19561
  settings,
19562
+ catalogSourceSettings = settings,
19279
19563
  db,
19280
19564
  bus,
19281
19565
  runtime,
@@ -19302,7 +19586,6 @@ function createRunAgentTurnActivity(services) {
19302
19586
  billingState,
19303
19587
  sandboxState,
19304
19588
  renewals,
19305
- recordingState,
19306
19589
  eventing,
19307
19590
  workspaceRefs,
19308
19591
  providerTurn
@@ -19378,7 +19661,6 @@ function createRunAgentTurnActivity(services) {
19378
19661
  activityContext,
19379
19662
  sandboxRotationController,
19380
19663
  sandboxState,
19381
- recordingState,
19382
19664
  eventing,
19383
19665
  attempt
19384
19666
  });
@@ -19386,9 +19668,7 @@ function createRunAgentTurnActivity(services) {
19386
19668
  requireResolvedSandboxForMutation,
19387
19669
  runWorkspaceMutationForSandbox,
19388
19670
  stopLeaseHeartbeat,
19389
- abandonActiveRecording,
19390
19671
  flushRuntimeBatcher,
19391
- maybeStartOnTurnRecording,
19392
19672
  finalizeTurnOpStreamOps
19393
19673
  } = sandboxRuntime;
19394
19674
  const media = createTurnMediaArtifacts({
@@ -19447,10 +19727,10 @@ function createRunAgentTurnActivity(services) {
19447
19727
  const claimed = await claimTurnAttempt({
19448
19728
  input,
19449
19729
  settings,
19730
+ catalogSourceSettings,
19450
19731
  db,
19451
19732
  bus,
19452
19733
  runtime,
19453
- objectStorage,
19454
19734
  observability,
19455
19735
  entitlements,
19456
19736
  wakeSessionWorkflow,
@@ -19462,13 +19742,11 @@ function createRunAgentTurnActivity(services) {
19462
19742
  attempt,
19463
19743
  billingState,
19464
19744
  sandboxState,
19465
- recordingState,
19466
19745
  eventing,
19467
19746
  leases,
19468
19747
  media,
19469
19748
  claimedResult,
19470
- acknowledgeLostAttemptOwnership,
19471
- abandonActiveRecording
19749
+ acknowledgeLostAttemptOwnership
19472
19750
  });
19473
19751
  if ("exit" in claimed) return claimed.exit;
19474
19752
  if (!eventing.publish || !eventing.settle) {
@@ -19487,6 +19765,7 @@ function createRunAgentTurnActivity(services) {
19487
19765
  trigger,
19488
19766
  humanInputResume,
19489
19767
  interactionInterventionResume,
19768
+ attachPendingUpdatesAfterOpenSuffix,
19490
19769
  throwIfWorkerShuttingDown,
19491
19770
  throwIfTurnCancelled,
19492
19771
  opJournal,
@@ -19688,6 +19967,10 @@ function createRunAgentTurnActivity(services) {
19688
19967
  }
19689
19968
  }
19690
19969
  ]);
19970
+ attempt.providerRecoveryCount = providerRecoveryCountAfterModelRequestPhase(
19971
+ attempt.providerRecoveryCount,
19972
+ event.phase
19973
+ );
19691
19974
  } catch (error) {
19692
19975
  auditOutcome = "failed";
19693
19976
  throw error;
@@ -19807,6 +20090,10 @@ function createRunAgentTurnActivity(services) {
19807
20090
  }
19808
20091
  }
19809
20092
  ]);
20093
+ attempt.providerRecoveryCount = providerRecoveryCountAfterModelRequestPhase(
20094
+ attempt.providerRecoveryCount,
20095
+ event.phase
20096
+ );
19810
20097
  } catch (error) {
19811
20098
  auditOutcome = "failed";
19812
20099
  throw error;
@@ -19845,7 +20132,7 @@ function createRunAgentTurnActivity(services) {
19845
20132
  );
19846
20133
  const compactionPrep = await prepareCompaction({
19847
20134
  input,
19848
- settings,
20135
+ settings: capabilitySettings,
19849
20136
  db,
19850
20137
  bus,
19851
20138
  observability,
@@ -19885,7 +20172,8 @@ function createRunAgentTurnActivity(services) {
19885
20172
  publishCompactionOutcomeEvents,
19886
20173
  compactionModeOptions,
19887
20174
  compactionOnlyTurn,
19888
- compactionSummarizerFor
20175
+ compactionSummarizerFor,
20176
+ settleDeferredSteerAfterCompaction
19889
20177
  } = compactionPrep.ok;
19890
20178
  const toolPolicy = await prepareTurnToolPolicy({
19891
20179
  input,
@@ -20097,6 +20385,7 @@ function createRunAgentTurnActivity(services) {
20097
20385
  ];
20098
20386
  const toolRuntime = await prepareTurnToolRuntime({
20099
20387
  input,
20388
+ catalogSourceSettings,
20100
20389
  db,
20101
20390
  bus,
20102
20391
  runtime,
@@ -20150,8 +20439,6 @@ function createRunAgentTurnActivity(services) {
20150
20439
  eventing,
20151
20440
  attempt,
20152
20441
  sandboxState,
20153
- recordingState,
20154
- maybeStartOnTurnRecording,
20155
20442
  providerTurn,
20156
20443
  media,
20157
20444
  leases,
@@ -20274,7 +20561,7 @@ function createRunAgentTurnActivity(services) {
20274
20561
  };
20275
20562
  const postAgentCompaction = await runPostAgentCompaction({
20276
20563
  input,
20277
- settings,
20564
+ settings: capabilitySettings,
20278
20565
  db,
20279
20566
  bus,
20280
20567
  observability,
@@ -20311,6 +20598,7 @@ function createRunAgentTurnActivity(services) {
20311
20598
  compactionModeOptions,
20312
20599
  compactionOnlyTurn,
20313
20600
  compactionSummarizerFor,
20601
+ settleDeferredSteerAfterCompaction,
20314
20602
  agent
20315
20603
  });
20316
20604
  if ("exit" in postAgentCompaction) return postAgentCompaction.exit;
@@ -20344,7 +20632,7 @@ function createRunAgentTurnActivity(services) {
20344
20632
  if (downloadsToMaterialize.length === 0) {
20345
20633
  fileMaterializationCache = "hit";
20346
20634
  }
20347
- const runAs = sandboxRunAs7(runSettings);
20635
+ const runAs = sandboxRunAs6(runSettings);
20348
20636
  if (downloadsToMaterialize.length > 0) {
20349
20637
  const materialized = await runWorkspaceMutationForSandbox(
20350
20638
  sandboxState.resolvedSandbox,
@@ -20421,7 +20709,7 @@ function createRunAgentTurnActivity(services) {
20421
20709
  );
20422
20710
  return await runTurnStreamAttempt({
20423
20711
  input,
20424
- settings,
20712
+ settings: capabilitySettings,
20425
20713
  db,
20426
20714
  runtime,
20427
20715
  objectStorage,
@@ -20472,12 +20760,14 @@ function createRunAgentTurnActivity(services) {
20472
20760
  turn,
20473
20761
  trigger,
20474
20762
  humanInputResume,
20763
+ attachPendingUpdatesAfterOpenSuffix,
20475
20764
  agent,
20476
20765
  resolvedModel,
20477
20766
  providerApi,
20478
20767
  runSettings,
20479
20768
  turnTools,
20480
20769
  compactSummarizer,
20770
+ settleDeferredSteerAfterCompaction,
20481
20771
  compactionModelHistoryProjector,
20482
20772
  generatedImageHistoryProjector,
20483
20773
  modelHistoryProjector,
@@ -20541,14 +20831,12 @@ function createRunAgentTurnActivity(services) {
20541
20831
  attempt,
20542
20832
  sandboxState,
20543
20833
  renewals,
20544
- recordingState,
20545
20834
  eventing,
20546
20835
  providerTurn,
20547
20836
  workspaceRefs,
20548
20837
  runWorkspaceMutationForSandbox,
20549
20838
  requireResolvedSandboxForMutation,
20550
20839
  stopLeaseHeartbeat,
20551
- abandonActiveRecording,
20552
20840
  turnCompletionMemoryCollector
20553
20841
  });
20554
20842
  }
@@ -21645,4 +21933,4 @@ export {
21645
21933
  createTurnActivities,
21646
21934
  createTurnActivitiesFromServices
21647
21935
  };
21648
- //# sourceMappingURL=activities-turn-5RGQDBFV.js.map
21936
+ //# sourceMappingURL=activities-turn-7EAQXW6Q.js.map