@opengeni/worker-bundle 0.22.7-canary.0 → 0.23.3-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 (74) hide show
  1. package/dist/activities/agent-turn/agent-build.d.ts +1 -4
  2. package/dist/activities/agent-turn/claim.d.ts +2 -4
  3. package/dist/activities/agent-turn/codex.d.ts +6 -5
  4. package/dist/activities/agent-turn/compaction-prep.d.ts +2 -0
  5. package/dist/activities/agent-turn/errors.d.ts +13 -0
  6. package/dist/activities/agent-turn/finalization.d.ts +1 -3
  7. package/dist/activities/agent-turn/quiescence.d.ts +39 -0
  8. package/dist/activities/agent-turn/sandbox-route.d.ts +14 -24
  9. package/dist/activities/agent-turn/sandbox-runtime.d.ts +1 -4
  10. package/dist/activities/agent-turn/sandbox-shared-preparation.d.ts +30 -0
  11. package/dist/activities/agent-turn/stream-attempt.d.ts +7 -0
  12. package/dist/activities/agent-turn/tool-policy.d.ts +3 -32
  13. package/dist/activities/agent-turn/turn-context.d.ts +1 -8
  14. package/dist/activities/agent-turn/turn-sandbox-access.d.ts +12 -0
  15. package/dist/activities/agent-turn/video-reference-sandbox.d.ts +7 -0
  16. package/dist/activities/codex-rotation.d.ts +2 -0
  17. package/dist/activities/session-state.d.ts +2 -1
  18. package/dist/{activities-control-VZIIV7RX.js → activities-control-52W5IDWM.js} +125 -13
  19. package/dist/activities-control-52W5IDWM.js.map +1 -0
  20. package/dist/{activities-turn-5RGQDBFV.js → activities-turn-A2G2KLSY.js} +534 -482
  21. package/dist/activities-turn-A2G2KLSY.js.map +1 -0
  22. package/dist/{chunk-NAVSAZ56.js → chunk-GFNXVZVQ.js} +160 -1
  23. package/dist/chunk-GFNXVZVQ.js.map +1 -0
  24. package/dist/{chunk-O4HDX5SC.js → chunk-IPVMCAW5.js} +144 -15
  25. package/dist/chunk-IPVMCAW5.js.map +1 -0
  26. package/dist/index.js +42 -2
  27. package/dist/index.js.map +1 -1
  28. package/dist/observability-metrics.d.ts +28 -0
  29. package/dist/personal-github-git-credentials.d.ts +1 -0
  30. package/dist/unhandled-rejection-boundary.d.ts +29 -0
  31. package/package.json +18 -18
  32. package/src/activities/agent-turn/agent-build.ts +15 -31
  33. package/src/activities/agent-turn/claim.ts +29 -68
  34. package/src/activities/agent-turn/codex.ts +19 -10
  35. package/src/activities/agent-turn/compaction-prep.ts +50 -1
  36. package/src/activities/agent-turn/errors.ts +78 -0
  37. package/src/activities/agent-turn/failure-settlement.ts +30 -19
  38. package/src/activities/agent-turn/finalization.ts +24 -21
  39. package/src/activities/agent-turn/history.ts +5 -1
  40. package/src/activities/agent-turn/quiescence.ts +86 -0
  41. package/src/activities/agent-turn/run-credentials.ts +12 -1
  42. package/src/activities/agent-turn/run.ts +14 -11
  43. package/src/activities/agent-turn/sandbox-establish.ts +46 -11
  44. package/src/activities/agent-turn/sandbox-route.ts +21 -25
  45. package/src/activities/agent-turn/sandbox-runtime.ts +1 -116
  46. package/src/activities/agent-turn/sandbox-shared-preparation.ts +206 -0
  47. package/src/activities/agent-turn/stream-attempt.ts +98 -14
  48. package/src/activities/agent-turn/tool-environment.ts +10 -13
  49. package/src/activities/agent-turn/tool-policy.ts +3 -55
  50. package/src/activities/agent-turn/turn-context.ts +8 -14
  51. package/src/activities/agent-turn/{image-reference-sandbox.ts → turn-sandbox-access.ts} +15 -13
  52. package/src/activities/agent-turn/video-reference-sandbox.ts +23 -0
  53. package/src/activities/codex-capacity.ts +13 -5
  54. package/src/activities/codex-rotation.ts +17 -0
  55. package/src/activities/goals.ts +10 -4
  56. package/src/activities/retained-screenshots.ts +104 -21
  57. package/src/activities/sandbox-lease.ts +7 -4
  58. package/src/activities/scheduled-tasks.ts +128 -4
  59. package/src/activities/session-state.ts +8 -1
  60. package/src/github-rest-mcp.ts +6 -3
  61. package/src/http.ts +3 -0
  62. package/src/index.ts +19 -0
  63. package/src/observability-metrics.ts +200 -0
  64. package/src/personal-github-git-credentials.ts +45 -4
  65. package/src/sandbox-resume.ts +1 -1
  66. package/src/sandbox-routing.ts +7 -4
  67. package/src/unhandled-rejection-boundary.ts +73 -0
  68. package/dist/activities/agent-turn/image-reference-sandbox.d.ts +0 -14
  69. package/dist/activities/recording.d.ts +0 -90
  70. package/dist/activities-control-VZIIV7RX.js.map +0 -1
  71. package/dist/activities-turn-5RGQDBFV.js.map +0 -1
  72. package/dist/chunk-NAVSAZ56.js.map +0 -1
  73. package/dist/chunk-O4HDX5SC.js.map +0 -1
  74. 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-IPVMCAW5.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-GFNXVZVQ.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
@@ -3456,11 +3500,6 @@ function createTurnContext(input) {
3456
3500
  codemodeTokenRenewalClosed: false,
3457
3501
  publishedRunCredentialNotices: /* @__PURE__ */ new Set()
3458
3502
  },
3459
- recordingState: {
3460
- activeRecording: null,
3461
- computerUseRecordingStart: null,
3462
- didComputerUse: false
3463
- },
3464
3503
  eventing: {
3465
3504
  heartbeatTimer: void 0,
3466
3505
  batcher: null,
@@ -4359,14 +4398,12 @@ async function finalizeTurnAttempt(deps) {
4359
4398
  attempt,
4360
4399
  sandboxState,
4361
4400
  renewals,
4362
- recordingState,
4363
4401
  eventing,
4364
4402
  providerTurn,
4365
4403
  workspaceRefs,
4366
4404
  runWorkspaceMutationForSandbox,
4367
4405
  requireResolvedSandboxForMutation,
4368
4406
  stopLeaseHeartbeat,
4369
- abandonActiveRecording,
4370
4407
  turnCompletionMemoryCollector
4371
4408
  } = deps;
4372
4409
  if (sandboxState.resolvedSandbox === null && !sandboxResumeController.signal.aborted) {
@@ -4378,6 +4415,17 @@ async function finalizeTurnAttempt(deps) {
4378
4415
  let finalizationError;
4379
4416
  let physicalToolQuiescenceConfirmed = !control.acknowledgeQuiescence;
4380
4417
  let quiescenceReceiptOrProofDurable = !control.acknowledgeQuiescence;
4418
+ const disarmQuiescenceWatchdog = armTurnQuiescenceWatchdog({
4419
+ enabled: control.acknowledgeQuiescence,
4420
+ onTimeout: () => {
4421
+ observability.error("turn quiescence drain exceeded hard containment deadline", {
4422
+ "opengeni.session_id": input.sessionId,
4423
+ "opengeni.turn_id": attempt.turnId ?? "",
4424
+ "opengeni.attempt_id": input.attemptId
4425
+ });
4426
+ },
4427
+ terminateWorker: () => process.exit(1)
4428
+ });
4381
4429
  const finalizerSignal = turnFinalizerCancellationSignal(
4382
4430
  cancellationSignal,
4383
4431
  control.activityStatus
@@ -4508,6 +4556,7 @@ async function finalizeTurnAttempt(deps) {
4508
4556
  }
4509
4557
  });
4510
4558
  quiescenceReceiptOrProofDurable = true;
4559
+ disarmQuiescenceWatchdog();
4511
4560
  if (recoveryMode === "signal") {
4512
4561
  observability.info("agent turn quiescence proof handed to workflow recovery", {
4513
4562
  "opengeni.session_id": input.sessionId,
@@ -4531,7 +4580,10 @@ async function finalizeTurnAttempt(deps) {
4531
4580
  machineOpEvents.map((event) => ({
4532
4581
  ...event,
4533
4582
  turnId: attempt.turnId ?? null
4534
- }))
4583
+ })),
4584
+ {
4585
+ onAppendPhase: (observation) => recordSessionEventAppendPhase(observability, observation)
4586
+ }
4535
4587
  ).catch(() => void 0),
4536
4588
  finalizerSignal
4537
4589
  );
@@ -4698,13 +4750,6 @@ async function finalizeTurnAttempt(deps) {
4698
4750
  () => void 0
4699
4751
  );
4700
4752
  }
4701
- await waitForTurnFinalizerStep(
4702
- abandonActiveRecording(
4703
- "activity ended without recording settlement",
4704
- recordingState.didComputerUse ? "failed" : "discard"
4705
- ),
4706
- finalizerSignal
4707
- );
4708
4753
  if (sandboxState.resolvedSandbox) {
4709
4754
  const settledTurnId = attempt.turnId;
4710
4755
  if (runTurnEndPersistence && sandboxState.setupBoxSession && sandboxState.sandboxGroupId && settledTurnId) {
@@ -4868,7 +4913,6 @@ import {
4868
4913
  settleCodexCredentialFailover,
4869
4914
  readLease,
4870
4915
  SandboxLeaseSupersededError,
4871
- SandboxLeaseTransitionError,
4872
4916
  isSessionEventPersistenceError as isSessionEventPersistenceError2
4873
4917
  } from "@opengeni/db";
4874
4918
  import { publishDurableSessionEvents as publishDurableSessionEvents2 } from "@opengeni/events";
@@ -5547,29 +5591,32 @@ async function settleTurnFailure(deps) {
5547
5591
  acknowledgeRecoveryQuiescence
5548
5592
  } = deps;
5549
5593
  const recoveryTurnId = attempt.turnId;
5550
- if ((error instanceof SandboxLeaseSupersededError || error instanceof SandboxLeaseTransitionError) && recoveryTurnId) {
5594
+ const lifecycleTransition = sandboxLifecycleTransitionDiagnostic(error);
5595
+ const leaseControlError = error instanceof SandboxLeaseSupersededError ? error : lifecycleTransition;
5596
+ if (leaseControlError && recoveryTurnId) {
5551
5597
  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;
5598
+ const fencedLease = await readLease(
5599
+ db,
5600
+ input.workspaceId,
5601
+ leaseControlError.sandboxGroupId
5602
+ ).catch(() => null);
5603
+ const rotationPending = fencedLease?.rotationRequestedAt != null || lifecycleTransition?.reason === "rotation_in_progress";
5604
+ const transitionPending = lifecycleTransition !== null || rotationPending;
5558
5605
  const deadlineRotationPending = rotationPending && fencedLease?.rotationReason === "provider_deadline";
5559
5606
  const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {
5560
5607
  sessionId: input.sessionId,
5561
5608
  turnId: recoveryTurnId,
5562
5609
  triggerEventId: attempt.triggerEventId,
5563
5610
  attemptId: input.attemptId,
5564
- reason: deadlineRotationPending ? "sandbox_deadline_rotation" : lifecycleTransition ? "sandbox_lifecycle_transition" : "sandbox_lease_superseded",
5611
+ reason: deadlineRotationPending ? "sandbox_deadline_rotation" : lifecycleTransition !== null ? "sandbox_lifecycle_transition" : "sandbox_lease_superseded",
5565
5612
  ...transitionPending ? {
5566
5613
  detail: {
5567
- sandboxGroupId: error.sandboxGroupId,
5568
- leaseEpoch: error.leaseEpoch,
5614
+ sandboxGroupId: leaseControlError.sandboxGroupId,
5615
+ leaseEpoch: leaseControlError.leaseEpoch,
5569
5616
  ...rotationPending ? {
5570
5617
  rotationReason: fencedLease?.rotationReason ?? "operator"
5571
5618
  } : {},
5572
- ...lifecycleTransition ? { transitionReason: error.reason } : {}
5619
+ ...lifecycleTransition ? { transitionReason: lifecycleTransition.reason } : {}
5573
5620
  }
5574
5621
  } : {}
5575
5622
  });
@@ -5916,7 +5963,11 @@ async function settleTurnFailure(deps) {
5916
5963
  kind: "status",
5917
5964
  status: "error",
5918
5965
  lastError: "model request was forbidden for this credential"
5919
- } : { kind: "cooldown", until: cooldownUntil }
5966
+ } : {
5967
+ kind: "cooldown",
5968
+ until: cooldownUntil,
5969
+ cooldownKind: codexCredentialFailure.kind
5970
+ }
5920
5971
  }) : false;
5921
5972
  if (!statePersisted && leases.codex.holderId && leases.codex.generation !== null) {
5922
5973
  leases.codex.lost = true;
@@ -6114,6 +6165,7 @@ async function settleTurnFailure(deps) {
6114
6165
  let rotationResumeIdleUntilReset = false;
6115
6166
  let allCappedResetAt = null;
6116
6167
  let capacityAuthoritativeResetAt = null;
6168
+ let capacityNeedsBoundedRefresh = false;
6117
6169
  if (providerTurn.effectiveCodexCredentialId) {
6118
6170
  const [rotation, sessionCodex] = await Promise.all([
6119
6171
  getCodexRotationSettings(db, input.workspaceId).catch(() => null),
@@ -6140,7 +6192,8 @@ async function settleTurnFailure(deps) {
6140
6192
  db,
6141
6193
  input.workspaceId,
6142
6194
  providerTurn.effectiveCodexCredentialId,
6143
- until
6195
+ until,
6196
+ "quota"
6144
6197
  ).catch(() => null);
6145
6198
  const cooldownPersisted = cooldownMutation?.result ?? false;
6146
6199
  if (cooldownMutation) {
@@ -6150,7 +6203,7 @@ async function settleTurnFailure(deps) {
6150
6203
  );
6151
6204
  }
6152
6205
  const fresh = accounts.map(
6153
- (a) => a.id === providerTurn.effectiveCodexCredentialId ? { ...a, exhaustedUntil: until } : a
6206
+ (a) => a.id === providerTurn.effectiveCodexCredentialId ? { ...a, exhaustedUntil: until, exhaustedKind: "quota" } : a
6154
6207
  );
6155
6208
  if (reactiveSharded) {
6156
6209
  const newHome = shardCredentialForSession({
@@ -6205,6 +6258,7 @@ async function settleTurnFailure(deps) {
6205
6258
  rotated = true;
6206
6259
  allCappedResetAt = earliestCodexReset(fresh, /* @__PURE__ */ new Date());
6207
6260
  capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, /* @__PURE__ */ new Date());
6261
+ capacityNeedsBoundedRefresh = true;
6208
6262
  }
6209
6263
  } else {
6210
6264
  const decision = chooseRotationActive({
@@ -6232,6 +6286,7 @@ async function settleTurnFailure(deps) {
6232
6286
  rotated = true;
6233
6287
  allCappedResetAt = decision.earliestResetAt;
6234
6288
  capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, /* @__PURE__ */ new Date());
6289
+ capacityNeedsBoundedRefresh = true;
6235
6290
  }
6236
6291
  }
6237
6292
  }
@@ -6258,7 +6313,7 @@ async function settleTurnFailure(deps) {
6258
6313
  goalId: goalActive && goal ? goal.id : null,
6259
6314
  goalVersion: goalActive && goal ? goal.version : null,
6260
6315
  earliestResetAt: providerResetAt,
6261
- resetKind: providerResetAt ? "authoritative" : "bounded_refresh",
6316
+ resetKind: providerResetAt && !capacityNeedsBoundedRefresh ? "authoritative" : "bounded_refresh",
6262
6317
  failurePayload,
6263
6318
  ...leases.codex.holderId && leases.codex.generation !== null ? {
6264
6319
  leaseFence: {
@@ -7696,6 +7751,168 @@ import {
7696
7751
  OPEN_SUFFIX_RUN_STATE_BLOB as OPEN_SUFFIX_RUN_STATE_BLOB2,
7697
7752
  resolveWorkspaceAgentHumanInputEnabled
7698
7753
  } from "@opengeni/contracts";
7754
+
7755
+ // src/activities/agent-turn/sandbox-shared-preparation.ts
7756
+ import { randomUUID } from "crypto";
7757
+ import {
7758
+ claimSandboxSharedPreparation,
7759
+ readSandboxSharedPreparation,
7760
+ SandboxLeaseSupersededError as SandboxLeaseSupersededError2,
7761
+ settleSandboxSharedPreparation
7762
+ } from "@opengeni/db";
7763
+ function observeSharedPreparation(options, measurement) {
7764
+ try {
7765
+ options.observe?.(measurement);
7766
+ } catch {
7767
+ }
7768
+ }
7769
+ function waitForPreparationTransition(ms, signal) {
7770
+ return new Promise((resolve, reject) => {
7771
+ let settled = false;
7772
+ const timer = setTimeout(finish, ms);
7773
+ function finish() {
7774
+ if (settled) return;
7775
+ settled = true;
7776
+ signal?.removeEventListener("abort", cancel);
7777
+ resolve();
7778
+ }
7779
+ function cancel() {
7780
+ if (settled) return;
7781
+ settled = true;
7782
+ clearTimeout(timer);
7783
+ signal?.removeEventListener("abort", cancel);
7784
+ reject(signal?.reason ?? new Error("Sandbox shared preparation wait cancelled"));
7785
+ }
7786
+ signal?.addEventListener("abort", cancel, { once: true });
7787
+ if (signal?.aborted) cancel();
7788
+ });
7789
+ }
7790
+ async function settleCompletedWithRetry(options, input, claimId) {
7791
+ let delayMs = 50;
7792
+ for (let attempt = 0; attempt < 4; attempt += 1) {
7793
+ try {
7794
+ if (await settleSandboxSharedPreparation(options.db, {
7795
+ accountId: options.accountId,
7796
+ workspaceId: options.workspaceId,
7797
+ sandboxGroupId: options.sandboxGroupId,
7798
+ expectedLeaseEpoch: options.sandbox.leaseEpoch,
7799
+ expectedInstanceId: options.sandbox.established.instanceId,
7800
+ specHash: input.specHash,
7801
+ holderId: options.holderId,
7802
+ claimId,
7803
+ outcome: "completed"
7804
+ })) {
7805
+ return true;
7806
+ }
7807
+ } catch {
7808
+ }
7809
+ await waitForPreparationTransition(delayMs, options.signal);
7810
+ delayMs *= 2;
7811
+ }
7812
+ return false;
7813
+ }
7814
+ function createSharedRigSetupCoordinator(options) {
7815
+ return async (input) => {
7816
+ const startedAt = performance.now();
7817
+ const claimId = randomUUID();
7818
+ const identity = {
7819
+ accountId: options.accountId,
7820
+ workspaceId: options.workspaceId,
7821
+ sandboxGroupId: options.sandboxGroupId,
7822
+ expectedLeaseEpoch: options.sandbox.leaseEpoch,
7823
+ expectedInstanceId: options.sandbox.established.instanceId,
7824
+ specHash: input.specHash,
7825
+ holderId: options.holderId
7826
+ };
7827
+ const claimTimeoutMs = Math.min(36e5, Math.max(3e4, input.timeoutMs + 3e4));
7828
+ let delayMs = 100;
7829
+ let observedRevision = -1;
7830
+ let path = "owner";
7831
+ try {
7832
+ for (; ; ) {
7833
+ if (options.signal?.aborted) {
7834
+ throw options.signal.reason ?? new Error("Sandbox shared preparation cancelled");
7835
+ }
7836
+ const claim = await claimSandboxSharedPreparation(options.db, {
7837
+ ...identity,
7838
+ claimId,
7839
+ ownerAttemptId: options.attemptId,
7840
+ timeoutMs: claimTimeoutMs
7841
+ });
7842
+ if (claim.role === "fenced") {
7843
+ throw new SandboxLeaseSupersededError2(options.sandboxGroupId, options.sandbox.leaseEpoch);
7844
+ }
7845
+ if (claim.role === "reused") {
7846
+ if (path !== "joined") path = "reused";
7847
+ observeSharedPreparation(options, {
7848
+ path,
7849
+ outcome: "completed",
7850
+ durationSeconds: (performance.now() - startedAt) / 1e3
7851
+ });
7852
+ return "reused";
7853
+ }
7854
+ if (claim.role === "owner") {
7855
+ try {
7856
+ await input.execute();
7857
+ } catch (error) {
7858
+ await settleSandboxSharedPreparation(options.db, {
7859
+ ...identity,
7860
+ claimId,
7861
+ outcome: "failed"
7862
+ }).catch(() => void 0);
7863
+ throw error;
7864
+ }
7865
+ if (await settleCompletedWithRetry(options, input, claimId)) {
7866
+ observeSharedPreparation(options, {
7867
+ path,
7868
+ outcome: "completed",
7869
+ durationSeconds: (performance.now() - startedAt) / 1e3
7870
+ });
7871
+ return "executed";
7872
+ }
7873
+ throw new Error(
7874
+ "Sandbox shared preparation completed but its durable settlement remains unavailable"
7875
+ );
7876
+ }
7877
+ path = "joined";
7878
+ observedRevision = claim.preparation.revision;
7879
+ const jitterMs = Math.floor(Math.random() * Math.max(1, Math.floor(delayMs / 4)));
7880
+ await waitForPreparationTransition(delayMs + jitterMs, options.signal);
7881
+ const observed = await readSandboxSharedPreparation(options.db, identity);
7882
+ if (observed.status === "fenced") {
7883
+ throw new SandboxLeaseSupersededError2(options.sandboxGroupId, options.sandbox.leaseEpoch);
7884
+ }
7885
+ if (observed.preparation.status === "completed") {
7886
+ observeSharedPreparation(options, {
7887
+ path,
7888
+ outcome: "completed",
7889
+ durationSeconds: (performance.now() - startedAt) / 1e3
7890
+ });
7891
+ return "reused";
7892
+ }
7893
+ if (observed.preparation.status === "failed") {
7894
+ delayMs = 100;
7895
+ continue;
7896
+ }
7897
+ delayMs = observed.preparation.revision === observedRevision ? Math.min(2e3, delayMs * 2) : 100;
7898
+ }
7899
+ } catch (error) {
7900
+ observeSharedPreparation(options, {
7901
+ path,
7902
+ outcome: "failed",
7903
+ durationSeconds: (performance.now() - startedAt) / 1e3
7904
+ });
7905
+ throw error;
7906
+ }
7907
+ };
7908
+ }
7909
+
7910
+ // src/activities/agent-turn/stream-attempt.ts
7911
+ async function attachPendingUpdatesBeforePreparingModelInput(input) {
7912
+ if (input.shouldAttach && !await input.attachPendingUpdates()) return false;
7913
+ await input.prepareModelInput();
7914
+ return true;
7915
+ }
7699
7916
  async function runTurnStreamAttempt(deps) {
7700
7917
  const {
7701
7918
  input,
@@ -7750,12 +7967,14 @@ async function runTurnStreamAttempt(deps) {
7750
7967
  turn,
7751
7968
  trigger,
7752
7969
  humanInputResume,
7970
+ attachPendingUpdatesAfterOpenSuffix,
7753
7971
  agent,
7754
7972
  resolvedModel,
7755
7973
  providerApi,
7756
7974
  runSettings,
7757
7975
  turnTools,
7758
7976
  compactSummarizer,
7977
+ settleDeferredSteerAfterCompaction,
7759
7978
  compactionModelHistoryProjector,
7760
7979
  generatedImageHistoryProjector,
7761
7980
  modelHistoryProjector,
@@ -7898,6 +8117,7 @@ async function runTurnStreamAttempt(deps) {
7898
8117
  const streamProvider = resolvedModel?.provider.id ?? settings.openaiProvider ?? "openai";
7899
8118
  const providerPublishesNativeRequestEvents = resolvedModel?.provider.kind === "codex-subscription" || resolvedModel?.provider.kind === "xai-subscription";
7900
8119
  let fallbackProviderRequestStartedAt = null;
8120
+ let fallbackProviderRequestLifecycleStartedAt = null;
7901
8121
  const recordFallbackProviderDispatchAtWire = async () => {
7902
8122
  await checkpointHistoryBeforeProviderDispatch(historySink);
7903
8123
  if (providerPublishesNativeRequestEvents || eventing.firstModelRequestPreparationRecorded || eventing.firstModelRequestPreparationStartedAt === null) {
@@ -7941,6 +8161,7 @@ async function runTurnStreamAttempt(deps) {
7941
8161
  }
7942
8162
  ]);
7943
8163
  fallbackProviderRequestStartedAt = performance.now();
8164
+ fallbackProviderRequestLifecycleStartedAt = fallbackProviderRequestStartedAt;
7944
8165
  } catch (error) {
7945
8166
  auditOutcome = "failed";
7946
8167
  throw error;
@@ -7957,7 +8178,8 @@ async function runTurnStreamAttempt(deps) {
7957
8178
  };
7958
8179
  const ownedEstablished = sandboxState.resolvedSandbox?.established ?? sandboxState.lazyOwnedSandbox;
7959
8180
  const runStreamOnce = async () => {
7960
- if (sandboxState.resolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
8181
+ const eagerResolvedSandbox = sandboxState.resolvedSandbox;
8182
+ if (eagerResolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
7961
8183
  const ownedSandboxSetupStartedAt = performance.now();
7962
8184
  let ownedSandboxSetupOutcome = "completed";
7963
8185
  try {
@@ -7965,11 +8187,11 @@ async function runTurnStreamAttempt(deps) {
7965
8187
  await attachRunCredentialRenewal(
7966
8188
  eagerSetupSession,
7967
8189
  initialRunCredentialMaterial,
7968
- sandboxState.resolvedSandbox
8190
+ eagerResolvedSandbox
7969
8191
  );
7970
8192
  const eagerCredentialSetupSession = initialRunCredentialMaterial ? withRunCredentialsSession(eagerSetupSession, input.sessionId) : eagerSetupSession;
7971
8193
  await runWorkspaceMutationForSandbox(
7972
- sandboxState.resolvedSandbox,
8194
+ eagerResolvedSandbox,
7973
8195
  "eagerOwnedSandboxSetup",
7974
8196
  async () => await runOwnedSandboxSetup(
7975
8197
  agent,
@@ -7991,6 +8213,19 @@ async function runTurnStreamAttempt(deps) {
7991
8213
  commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
7992
8214
  eventing.toolCancellationFenceRef.current
7993
8215
  )
8216
+ } : {},
8217
+ ...sandboxState.sandboxGroupId && sandboxState.sandboxHolderId ? {
8218
+ coordinateSharedRigSetup: createSharedRigSetupCoordinator({
8219
+ db,
8220
+ accountId: input.accountId,
8221
+ workspaceId: input.workspaceId,
8222
+ sandboxGroupId: sandboxState.sandboxGroupId,
8223
+ attemptId: input.attemptId,
8224
+ holderId: sandboxState.sandboxHolderId,
8225
+ sandbox: eagerResolvedSandbox,
8226
+ ...runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {},
8227
+ observe: (measurement) => recordSandboxSharedPreparation(observability, measurement)
8228
+ })
7994
8229
  } : {}
7995
8230
  }
7996
8231
  )
@@ -8233,6 +8468,28 @@ async function runTurnStreamAttempt(deps) {
8233
8468
  ...resolvedModel?.provider.id ? { providerId: resolvedModel.provider.id } : {}
8234
8469
  });
8235
8470
  if (responseResult.status === "processed") {
8471
+ if (!providerPublishesNativeRequestEvents && fallbackProviderRequestLifecycleStartedAt !== null) {
8472
+ const durationMs = Math.max(
8473
+ 0,
8474
+ performance.now() - fallbackProviderRequestLifecycleStartedAt
8475
+ );
8476
+ fallbackProviderRequestLifecycleStartedAt = null;
8477
+ await eventing.publish([
8478
+ {
8479
+ type: "agent.model.request",
8480
+ payload: {
8481
+ phase: "completed",
8482
+ provider: streamProvider,
8483
+ durationMs: Math.round(durationMs),
8484
+ turnId: activeTurnId,
8485
+ attemptId: input.attemptId,
8486
+ dispatchId,
8487
+ executionGeneration: attempt.executionGeneration
8488
+ }
8489
+ }
8490
+ ]);
8491
+ attempt.providerRecoveryCount = 0;
8492
+ }
8236
8493
  const rawStreamHistory = eventing.stream.state.history;
8237
8494
  if (Array.isArray(rawStreamHistory)) {
8238
8495
  await media.retainNativeGeneratedImagesFromHistory(
@@ -8451,9 +8708,13 @@ async function runTurnStreamAttempt(deps) {
8451
8708
  }
8452
8709
  }
8453
8710
  } catch (error) {
8454
- if (fallbackProviderRequestStartedAt !== null) {
8455
- const durationMs = Math.max(0, performance.now() - fallbackProviderRequestStartedAt);
8711
+ if (fallbackProviderRequestLifecycleStartedAt !== null) {
8712
+ const durationMs = Math.max(
8713
+ 0,
8714
+ performance.now() - fallbackProviderRequestLifecycleStartedAt
8715
+ );
8456
8716
  fallbackProviderRequestStartedAt = null;
8717
+ fallbackProviderRequestLifecycleStartedAt = null;
8457
8718
  await eventing.publish([
8458
8719
  {
8459
8720
  type: "agent.model.request",
@@ -8499,16 +8760,18 @@ async function runTurnStreamAttempt(deps) {
8499
8760
  void iterator.return?.().catch(() => void 0);
8500
8761
  }
8501
8762
  }
8502
- await waitForTurnStreamCleanup(
8503
- eventing.batcher.flush(),
8504
- eventing.stream.completed.catch(() => void 0),
8505
- cancellationSignal
8506
- );
8763
+ await assertSuccessfulAgentStreamCompletion({
8764
+ batcherFlush: eventing.batcher.flush(),
8765
+ stream: eventing.stream,
8766
+ temporalCancellationSignal: cancellationSignal,
8767
+ runtimeCancellationSignal
8768
+ });
8507
8769
  if (options.requireTerminalModelResponse && eventing.stream.interruptions.length === 0 && modelResponseState.responseCount === responseCountBeforeStream) {
8508
8770
  throwIfWorkerShuttingDown();
8509
8771
  throwIfTurnCancelled();
8510
8772
  throw new PostCompactionContinuationEmptyError();
8511
8773
  }
8774
+ assertAgentStreamNotCancelled(eventing.stream.cancelled);
8512
8775
  if (!streamSawPerResponseUsage) {
8513
8776
  const aggregateUsage = eventing.stream.state.usage;
8514
8777
  const normalizedAggregateUsage = normalizeModelCallUsage2(aggregateUsage);
@@ -8722,7 +8985,7 @@ async function runTurnStreamAttempt(deps) {
8722
8985
  control.activityStatus = "requires_action";
8723
8986
  return claimedResult({ status: "requires_action" });
8724
8987
  }
8725
- const finalOutput = String(eventing.stream.finalOutput ?? "");
8988
+ const finalOutput = String(requireAgentStreamFinalOutput(eventing.stream.finalOutput));
8726
8989
  await historySink.reconcileConversationTruth({ requireDurable: true });
8727
8990
  await finalizeTurnOpStreamOps();
8728
8991
  if (!await eventing.settle({
@@ -8779,7 +9042,13 @@ async function runTurnStreamAttempt(deps) {
8779
9042
  control.activityStatus = "requires_action";
8780
9043
  return claimedResult({ status: "requires_action" });
8781
9044
  }
8782
- await prepareRunAttemptInput();
9045
+ if (!await attachPendingUpdatesBeforePreparingModelInput({
9046
+ shouldAttach: trigger.type === "user.approvalDecision" || trigger.type === "user.humanInputResponse",
9047
+ attachPendingUpdates: attachPendingUpdatesAfterOpenSuffix,
9048
+ prepareModelInput: prepareRunAttemptInput
9049
+ })) {
9050
+ return claimedResult({ status: "cancelled" });
9051
+ }
8783
9052
  let retriedAfterCompaction = false;
8784
9053
  while (true) {
8785
9054
  try {
@@ -8848,6 +9117,8 @@ async function runTurnStreamAttempt(deps) {
8848
9117
  );
8849
9118
  compactionRequestCleared = landmark.requestConsumed;
8850
9119
  if (!isCompactionSummaryFailure(compactError)) throw compactError;
9120
+ const deferredSteer2 = await settleDeferredSteerAfterCompaction();
9121
+ if (deferredSteer2) return deferredSteer2;
8851
9122
  compactionFailureMessage = String(compactionFailureReasonFromError(compactError));
8852
9123
  observability.warn("context compaction recovery compaction failed", {
8853
9124
  sessionId: input.sessionId,
@@ -8886,6 +9157,8 @@ async function runTurnStreamAttempt(deps) {
8886
9157
  control.activityError = attemptError;
8887
9158
  return claimedResult({ status: "idle", deferredUntilWake: true });
8888
9159
  }
9160
+ const deferredSteer = await settleDeferredSteerAfterCompaction();
9161
+ if (deferredSteer) return deferredSteer;
8889
9162
  retriedAfterCompaction = true;
8890
9163
  observability.info("context compaction recovery retrying turn after compaction", {
8891
9164
  sessionId: input.sessionId,
@@ -8910,7 +9183,6 @@ import {
8910
9183
  requireSession
8911
9184
  } from "@opengeni/db";
8912
9185
  import { appendAndPublishTurnEventsFenced as appendAndPublishTurnEventsFenced2, publishDurableSessionEvents as publishDurableSessionEvents3 } from "@opengeni/events";
8913
- import { deleteRecordingArtifacts as deleteRecordingArtifacts2 } from "@opengeni/runtime";
8914
9186
  import {
8915
9187
  assertTurnExecutionPolicyMatchesConfigV1,
8916
9188
  resolveTurnExecutionPolicyV1 as resolveTurnExecutionPolicyV12
@@ -9014,169 +9286,6 @@ function makeTurnOpJournal(context, details) {
9014
9286
  };
9015
9287
  }
9016
9288
 
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
9289
  // src/activities/agent-turn/claim.ts
9181
9290
  import { readTurnExecutionPolicyV1 } from "@opengeni/contracts";
9182
9291
  function turnAttemptProducerId(input, turnId) {
@@ -9189,7 +9298,6 @@ async function claimTurnAttempt(deps) {
9189
9298
  db,
9190
9299
  bus,
9191
9300
  runtime,
9192
- objectStorage,
9193
9301
  observability,
9194
9302
  entitlements,
9195
9303
  wakeSessionWorkflow,
@@ -9201,14 +9309,19 @@ async function claimTurnAttempt(deps) {
9201
9309
  attempt,
9202
9310
  billingState,
9203
9311
  sandboxState,
9204
- recordingState,
9205
9312
  eventing,
9206
9313
  leases,
9207
9314
  media,
9208
9315
  claimedResult,
9209
- acknowledgeLostAttemptOwnership,
9210
- abandonActiveRecording
9316
+ acknowledgeLostAttemptOwnership
9211
9317
  } = deps;
9318
+ const validatePendingSystemUpdateAuthority = async (tx, update) => await validateIncidentTelemetrySystemUpdateAuthority({
9319
+ db: tx,
9320
+ settings,
9321
+ workspaceId: input.workspaceId,
9322
+ sessionId: input.sessionId,
9323
+ update
9324
+ });
9212
9325
  const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {
9213
9326
  sessionId: input.sessionId,
9214
9327
  workflowId: input.workflowId,
@@ -9216,13 +9329,7 @@ async function claimTurnAttempt(deps) {
9216
9329
  attemptId: input.attemptId,
9217
9330
  dispatchId,
9218
9331
  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
- })
9332
+ validatePendingSystemUpdateAuthority
9226
9333
  });
9227
9334
  if (claim.action === "unclaimed") {
9228
9335
  control.activityStatus = "unclaimed";
@@ -9318,6 +9425,19 @@ async function claimTurnAttempt(deps) {
9318
9425
  trigger
9319
9426
  );
9320
9427
  attempt.triggerType = trigger.type;
9428
+ const attachPendingUpdatesAfterOpenSuffix = async () => {
9429
+ const attached = await claimSessionWorkForAttempt(db, input.workspaceId, {
9430
+ sessionId: input.sessionId,
9431
+ workflowId: input.workflowId,
9432
+ workflowRunId: input.workflowRunId,
9433
+ attemptId: input.attemptId,
9434
+ dispatchId,
9435
+ trigger: input.trigger,
9436
+ validatePendingSystemUpdateAuthority,
9437
+ attachPendingUpdatesToRunningAttempt: true
9438
+ });
9439
+ return attached.action === "claimed" && attached.turn.id === turn.id;
9440
+ };
9321
9441
  turnLifecycleMetricsFor(observability).start(attempt.turnId);
9322
9442
  await waitForTurnOperation(
9323
9443
  ensureRunAllowed(
@@ -9384,6 +9504,7 @@ async function claimTurnAttempt(deps) {
9384
9504
  onAppend: ({ durationSeconds }) => recordSessionEventAppendLatency(observability, {
9385
9505
  durationSeconds
9386
9506
  }),
9507
+ onAppendPhase: (observation) => recordSessionEventAppendPhase(observability, observation),
9387
9508
  onPublish: ({ durationSeconds }) => recordSessionEventPublishLatency(observability, {
9388
9509
  durationSeconds
9389
9510
  })
@@ -9407,28 +9528,6 @@ async function claimTurnAttempt(deps) {
9407
9528
  return appended;
9408
9529
  };
9409
9530
  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
9531
  const compactionRequestFailure = inputSettlement.consumeRequestedCompactionFailure ? {
9433
9532
  reason: "summarization_failed",
9434
9533
  producerId,
@@ -9457,36 +9556,16 @@ async function claimTurnAttempt(deps) {
9457
9556
  activeTurnId: inputSettlement.activeTurnId,
9458
9557
  events: inputs,
9459
9558
  ...runState ? { runState } : {},
9460
- ...recordingMutation ? { recording: recordingMutation } : {},
9461
9559
  ...compactionRequestFailure ? { compactionRequestFailure } : {}
9462
9560
  });
9463
9561
  if (result.action === "stale") {
9464
9562
  acknowledgeLostAttemptOwnership();
9465
- if (recordingForSettlement) {
9466
- await abandonActiveRecording(
9467
- "recording settlement lost attempt ownership",
9468
- preparedRecording?.mutation.action === "discard" ? "discard" : "failed"
9469
- );
9470
- }
9471
9563
  control.activityStatus = "cancelled";
9472
9564
  control.turnMetricOutcome = "cancelled";
9473
9565
  return false;
9474
9566
  }
9475
9567
  recordCanonicalStartupMilestones(result.canonicalStartupMilestones);
9476
9568
  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
9569
  await publishDurableSessionEvents3(bus, input.workspaceId, input.sessionId, result.events);
9491
9570
  if (inputSettlement.turnStatus === "requires_action") {
9492
9571
  await deliverChildRequiresActionToParent(
@@ -9553,6 +9632,7 @@ async function claimTurnAttempt(deps) {
9553
9632
  trigger,
9554
9633
  humanInputResume,
9555
9634
  interactionInterventionResume,
9635
+ attachPendingUpdatesAfterOpenSuffix,
9556
9636
  throwIfWorkerShuttingDown,
9557
9637
  throwIfTurnCancelled,
9558
9638
  opJournal,
@@ -9770,7 +9850,7 @@ function safeErrorName(error) {
9770
9850
  }
9771
9851
 
9772
9852
  // src/activities/agent-turn/codex-capacity.ts
9773
- import { randomUUID } from "crypto";
9853
+ import { randomUUID as randomUUID2 } from "crypto";
9774
9854
  async function selectCodexTurnCapacity(deps) {
9775
9855
  const {
9776
9856
  input,
@@ -10005,7 +10085,7 @@ async function selectCodexTurnCapacity(deps) {
10005
10085
  fencedInFlight,
10006
10086
  nearExhaustionPct: settings.codexRotationNearExhaustionPct,
10007
10087
  now: /* @__PURE__ */ new Date(),
10008
- aliasSeed: randomUUID()
10088
+ aliasSeed: randomUUID2()
10009
10089
  },
10010
10090
  publish: eventing.publish
10011
10091
  });
@@ -10352,9 +10432,6 @@ import {
10352
10432
  } from "@opengeni/contracts";
10353
10433
 
10354
10434
  // src/activities/agent-turn/tool-policy.ts
10355
- import {
10356
- desktopCapableBackend
10357
- } from "@opengeni/runtime";
10358
10435
  import {
10359
10436
  isDirectOpenAiApiBaseUrl
10360
10437
  } from "@opengeni/config";
@@ -10581,24 +10658,6 @@ function uuidFromDigest3(digestValue) {
10581
10658
  }
10582
10659
 
10583
10660
  // 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
10661
  function structuredToolTransportForTurn(resolvedModel) {
10603
10662
  if (!resolvedModel) return true;
10604
10663
  if (resolvedModel.provider.api === "chat") return false;
@@ -10621,7 +10680,7 @@ function lazyToolTransportForTurn(resolvedModel) {
10621
10680
  }
10622
10681
  function shouldDeferNonEagerToolPreparation(args) {
10623
10682
  return Boolean(
10624
- args.lazyToolTransport && args.progressiveDisclosureEnabled && !args.artifactRuntimeAvailable && args.triggerKind === "next" && (args.triggerType === "user.message" || args.triggerType === "system.update.delivered")
10683
+ args.lazyToolTransport && args.progressiveDisclosureEnabled && args.triggerKind === "next" && (args.triggerType === "user.message" || args.triggerType === "system.update.delivered")
10625
10684
  );
10626
10685
  }
10627
10686
  function hostedWebSearchForTurn(resolvedModel, deploymentWebSearchEnabled) {
@@ -10906,7 +10965,7 @@ async function prepareGovernanceAndModel(deps) {
10906
10965
  }
10907
10966
 
10908
10967
  // src/activities/agent-turn/compaction-prep.ts
10909
- import { isSessionCompactionRequested as isSessionCompactionRequested2 } from "@opengeni/db";
10968
+ import { hasPendingSteerAfterContextCompaction, isSessionCompactionRequested as isSessionCompactionRequested2 } from "@opengeni/db";
10910
10969
  import { publishDurableSessionEvents as publishDurableSessionEvents5 } from "@opengeni/events";
10911
10970
  import {
10912
10971
  appendSessionInstructions,
@@ -11059,6 +11118,35 @@ async function prepareCompaction(deps) {
11059
11118
  };
11060
11119
  const compactionOnlyTurn = turn.source === "compaction";
11061
11120
  const remoteV2CompactionNeedsAgentPrefix = Boolean(remoteCompactionRequester) && session.codexCompactionMode === "remote_v2";
11121
+ const settleDeferredSteerAfterCompaction = async () => {
11122
+ if (compactionOnlyTurn) return null;
11123
+ const pending = await hasPendingSteerAfterContextCompaction(db, {
11124
+ accountId: input.accountId,
11125
+ workspaceId: input.workspaceId,
11126
+ sessionId: input.sessionId,
11127
+ turnId: turn.id,
11128
+ executionGeneration: attempt.executionGeneration,
11129
+ attemptId: input.attemptId
11130
+ });
11131
+ if (!pending) return null;
11132
+ if (!await eventing.settle({
11133
+ events: [
11134
+ {
11135
+ type: "turn.superseded",
11136
+ payload: { reason: "steer", deferredUntilCompaction: true }
11137
+ },
11138
+ { type: "session.status.changed", payload: { status: "queued" } }
11139
+ ],
11140
+ turnStatus: "superseded",
11141
+ sessionStatus: "queued",
11142
+ activeTurnId: null
11143
+ })) {
11144
+ return claimedResult({ status: "cancelled" });
11145
+ }
11146
+ control.turnMetricOutcome = "cancelled";
11147
+ control.activityStatus = "idle";
11148
+ return claimedResult({ status: "idle" });
11149
+ };
11062
11150
  if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {
11063
11151
  const compactionInstructions = appendWorkspaceMemory(
11064
11152
  appendSessionInstructions(
@@ -11190,7 +11278,8 @@ async function prepareCompaction(deps) {
11190
11278
  publishCompactionOutcomeEvents,
11191
11279
  compactionModeOptions,
11192
11280
  compactionOnlyTurn,
11193
- compactionSummarizerFor
11281
+ compactionSummarizerFor,
11282
+ settleDeferredSteerAfterCompaction
11194
11283
  }
11195
11284
  };
11196
11285
  }
@@ -11213,6 +11302,7 @@ async function runPostAgentCompaction(deps) {
11213
11302
  compactionModeOptions,
11214
11303
  compactionOnlyTurn,
11215
11304
  compactionSummarizerFor,
11305
+ settleDeferredSteerAfterCompaction,
11216
11306
  compactionModelHistoryProjector,
11217
11307
  media,
11218
11308
  agent
@@ -11379,6 +11469,12 @@ async function runPostAgentCompaction(deps) {
11379
11469
  }
11380
11470
  await publishCompactionOutcomeEvents(outcome.events);
11381
11471
  }
11472
+ if (outcome.events.some(
11473
+ (event) => event.type === "session.context.compacted" || event.type === "session.context.compaction.skipped"
11474
+ )) {
11475
+ const deferredSteer = await settleDeferredSteerAfterCompaction();
11476
+ if (deferredSteer) return { exit: deferredSteer };
11477
+ }
11382
11478
  } catch (compactError) {
11383
11479
  if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;
11384
11480
  if (compactError instanceof TurnAttemptFencedError) throw compactError;
@@ -11398,6 +11494,8 @@ async function runPostAgentCompaction(deps) {
11398
11494
  }
11399
11495
  );
11400
11496
  if (!isCompactionSummaryFailure(compactError)) throw compactError;
11497
+ const deferredSteer = await settleDeferredSteerAfterCompaction();
11498
+ if (deferredSteer) return { exit: deferredSteer };
11401
11499
  const errorMessage = String(compactionFailureReasonFromError(compactError));
11402
11500
  observability.error("context compaction failed", {
11403
11501
  sessionId: input.sessionId,
@@ -11441,20 +11539,16 @@ import {
11441
11539
  heartbeatLeaseHolder,
11442
11540
  readLease as readLease2,
11443
11541
  accrueWarmSeconds,
11444
- abandonRecordingForTurnAttempt,
11445
11542
  SandboxWorkspaceMutationFencedError
11446
11543
  } from "@opengeni/db";
11447
11544
  import {
11448
- RoutingMutationOutcomeUnknownError,
11449
- stopRecording as stopRecordingOnBox2
11545
+ RoutingMutationOutcomeUnknownError
11450
11546
  } from "@opengeni/runtime";
11451
11547
  import {
11452
11548
  sandboxLifecycleTransitionWaitMs,
11453
11549
  sandboxWarmRateMicrosPerSecond
11454
11550
  } from "@opengeni/config";
11455
11551
  import { ChannelAPartialMutationError } from "@opengeni/runtime/sandbox";
11456
- import { sandboxRunAs as sandboxRunAs3 } from "@opengeni/runtime";
11457
- import { randomUUID as randomUUID2 } from "crypto";
11458
11552
  function createSandboxTurnRuntime(deps) {
11459
11553
  const {
11460
11554
  input,
@@ -11466,7 +11560,6 @@ function createSandboxTurnRuntime(deps) {
11466
11560
  activityContext,
11467
11561
  sandboxRotationController,
11468
11562
  sandboxState,
11469
- recordingState,
11470
11563
  eventing,
11471
11564
  attempt
11472
11565
  } = deps;
@@ -11654,29 +11747,6 @@ function createSandboxTurnRuntime(deps) {
11654
11747
  clearInterval(sandboxState.leaseHeartbeatTimer);
11655
11748
  sandboxState.leaseHeartbeatTimer = void 0;
11656
11749
  };
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
11750
  const flushRuntimeBatcher = async () => {
11681
11751
  const current = eventing.batcher;
11682
11752
  await current?.flush().catch(() => void 0);
@@ -11843,64 +11913,6 @@ function createSandboxTurnRuntime(deps) {
11843
11913
  sandboxState.leaseHeartbeatTimer.unref();
11844
11914
  }
11845
11915
  };
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
11916
  return {
11905
11917
  releaseLateSandbox,
11906
11918
  requireResolvedSandboxForMutation,
@@ -11908,12 +11920,10 @@ function createSandboxTurnRuntime(deps) {
11908
11920
  onHomeSandboxRebound,
11909
11921
  runWorkspaceMutationForSandbox,
11910
11922
  stopLeaseHeartbeat,
11911
- abandonActiveRecording,
11912
11923
  flushRuntimeBatcher,
11913
11924
  publishSandboxLifecycleEvents,
11914
11925
  publishSandboxLost,
11915
- startLeaseHeartbeat,
11916
- maybeStartOnTurnRecording
11926
+ startLeaseHeartbeat
11917
11927
  };
11918
11928
  }
11919
11929
 
@@ -11933,6 +11943,7 @@ import {
11933
11943
  sdkBackendIdForSandboxBackend,
11934
11944
  resolveConnectedMachineWorkspaceRoot as resolveConnectedMachineWorkspaceRoot2
11935
11945
  } from "@opengeni/runtime";
11946
+ import { managedSessionGroupBackend, managedSessionGroupOs } from "@opengeni/core";
11936
11947
 
11937
11948
  // src/sandbox-routing.ts
11938
11949
  import { sandboxLifecycleTransitionWaitMs as sandboxLifecycleTransitionWaitMs2 } from "@opengeni/config";
@@ -12251,7 +12262,7 @@ function settleRetainedProcessForTurn(services, ids) {
12251
12262
  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
12263
  throw new Error("Retained-process settlement lost its exact durable backend identity");
12253
12264
  }
12254
- await settleRetainedProcess(services.db, {
12265
+ const settlement = await settleRetainedProcess(services.db, {
12255
12266
  accountId: fence.accountId,
12256
12267
  workspaceId: ids.workspaceId,
12257
12268
  sessionId: ids.sessionId,
@@ -12262,14 +12273,17 @@ function settleRetainedProcessForTurn(services, ids) {
12262
12273
  reason: proof.reason,
12263
12274
  idleGraceMs: services.settings.sandboxIdleGraceMs
12264
12275
  });
12276
+ if (settlement.process.state === "active") {
12277
+ throw new Error("Retained-process settlement returned an active durable process");
12278
+ }
12265
12279
  await settleSessionBackgroundCommandForRetainedProcess(services.db, {
12266
12280
  accountId: fence.accountId,
12267
12281
  workspaceId: ids.workspaceId,
12268
12282
  sessionId: ids.sessionId,
12269
12283
  retainedProcessId: process2.id,
12270
- outcome: proof.outcome,
12271
- exitCode: proof.exitCode,
12272
- reason: proof.reason
12284
+ outcome: settlement.process.state,
12285
+ exitCode: settlement.process.exitCode,
12286
+ reason: settlement.process.settlementReason ?? proof.reason
12273
12287
  });
12274
12288
  };
12275
12289
  }
@@ -12832,6 +12846,9 @@ function managedSandboxOwnershipForTurn(machinePrimary, attemptId, sandboxGroupI
12832
12846
  sandboxGroupId
12833
12847
  };
12834
12848
  }
12849
+ function sandboxSettingsForRoute(input) {
12850
+ return input.runSettings.sandboxBackend === "selfhosted" && !input.machinePrimary && input.groupBoxBackend !== "selfhosted" ? { ...input.runSettings, sandboxBackend: input.groupBoxBackend } : input.runSettings;
12851
+ }
12835
12852
  function shouldEstablishSandboxForTurn(sandboxOwnershipEnabled, homeBackend, machinePrimary) {
12836
12853
  return sandboxOwnershipEnabled && (homeBackend !== "none" || machinePrimary);
12837
12854
  }
@@ -13017,11 +13034,22 @@ async function resolveSandboxRoute(deps) {
13017
13034
  sandboxBackend: "selfhosted"
13018
13035
  };
13019
13036
  }
13020
- const groupBoxBackend = runSettings.sandboxBackend === "selfhosted" && !machinePrimary ? settings.sandboxBackend : runSettings.sandboxBackend;
13037
+ const groupBoxBackend = !machinePrimary ? managedSessionGroupBackend(settings.sandboxBackend, runSettings.sandboxBackend) ?? runSettings.sandboxBackend : runSettings.sandboxBackend;
13038
+ const groupRouteSettings = sandboxSettingsForRoute({
13039
+ runSettings,
13040
+ machinePrimary,
13041
+ groupBoxBackend
13042
+ });
13043
+ if (groupRouteSettings !== runSettings) {
13044
+ eventing.modelRunSettings = {
13045
+ ...eventing.modelRunSettings,
13046
+ sandboxBackend: groupRouteSettings.sandboxBackend
13047
+ };
13048
+ }
13021
13049
  sandboxState.startupMilestoneBackend = activeSandboxBackend ?? groupBoxBackend;
13022
13050
  media.sandboxFileDownloadBackend = sandboxState.startupMilestoneBackend;
13023
13051
  const groupBoxImage = rigProviderImageSourceImage(logicalSandboxSettings, groupBoxBackend);
13024
- const sandboxCreationBackend = settings.sandboxOwnershipEnabled && runSettings.sandboxBackend !== "none" ? groupBoxBackend : runSettings.sandboxBackend;
13052
+ const sandboxCreationBackend = groupRouteSettings.sandboxBackend;
13025
13053
  const effectiveRunCredentialBackend = activeSandboxBackend ?? groupBoxBackend;
13026
13054
  return {
13027
13055
  routingOn,
@@ -13072,6 +13100,7 @@ async function establishTurnSandbox(deps) {
13072
13100
  rigVersion,
13073
13101
  turnResources
13074
13102
  } = deps;
13103
+ const groupBoxOs = managedSessionGroupOs(runSettings.sandboxBackend, session.sandboxOs);
13075
13104
  const {
13076
13105
  releaseLateSandbox,
13077
13106
  onHomeSandboxRebound,
@@ -13276,7 +13305,7 @@ async function establishTurnSandbox(deps) {
13276
13305
  sandboxGroupId: lazyGroupId,
13277
13306
  sessionId: input.sessionId,
13278
13307
  backend: groupBoxBackend,
13279
- os: session.sandboxOs,
13308
+ os: groupBoxOs,
13280
13309
  environment: sandboxEnvironment,
13281
13310
  ...groupBoxImage ? {
13282
13311
  image: groupBoxImage
@@ -13351,7 +13380,7 @@ async function establishTurnSandbox(deps) {
13351
13380
  // deployment default), never a "selfhosted" box (which would throw
13352
13381
  // for lack of a bound agentId).
13353
13382
  backend: groupBoxBackend,
13354
- os: session.sandboxOs,
13383
+ os: groupBoxOs,
13355
13384
  environment: sandboxEnvironment,
13356
13385
  // IMAGE IS SHARED STATE (B3): the container image
13357
13386
  // this run resolves. The lease stamps it + conflicts on a live shared box
@@ -13628,6 +13657,19 @@ async function bindLazySandboxProvisioner(deps) {
13628
13657
  commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
13629
13658
  eventing.toolCancellationFenceRef.current
13630
13659
  )
13660
+ } : {},
13661
+ ...sandboxState.sandboxGroupId && sandboxState.sandboxHolderId ? {
13662
+ coordinateSharedRigSetup: createSharedRigSetupCoordinator({
13663
+ db,
13664
+ accountId: input.accountId,
13665
+ workspaceId: input.workspaceId,
13666
+ sandboxGroupId: sandboxState.sandboxGroupId,
13667
+ attemptId: input.attemptId,
13668
+ holderId: sandboxState.sandboxHolderId,
13669
+ sandbox: provisioned,
13670
+ ...runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {},
13671
+ observe: (measurement) => recordSandboxSharedPreparation(observability, measurement)
13672
+ })
13631
13673
  } : {}
13632
13674
  }
13633
13675
  ),
@@ -14391,7 +14433,7 @@ async function bindRunCredentialResolver(input) {
14391
14433
  }
14392
14434
 
14393
14435
  // src/activities/agent-turn/run-credentials.ts
14394
- import { sandboxRunAs as sandboxRunAs4 } from "@opengeni/runtime";
14436
+ import { sandboxRunAs as sandboxRunAs3 } from "@opengeni/runtime";
14395
14437
  async function prepareRunCredentials(deps) {
14396
14438
  const {
14397
14439
  input,
@@ -14421,6 +14463,11 @@ async function prepareRunCredentials(deps) {
14421
14463
  connectionScope,
14422
14464
  runWorkspaceMutationForSandbox
14423
14465
  } = deps;
14466
+ const sandboxEnvironmentSettings = sandboxSettingsForRoute({
14467
+ runSettings,
14468
+ machinePrimary,
14469
+ groupBoxBackend
14470
+ });
14424
14471
  const runCredentialResolver = effectiveRunCredentialBackend === "none" ? null : await waitForTurnOperation(
14425
14472
  bindRunCredentialResolver({
14426
14473
  db,
@@ -14555,7 +14602,7 @@ async function prepareRunCredentials(deps) {
14555
14602
  codemodeTokenExpiresAt: sandboxCodemodeTokenExpiresAt
14556
14603
  } = await waitForTurnOperation(
14557
14604
  sandboxEnvironmentForRun(
14558
- runSettings,
14605
+ sandboxEnvironmentSettings,
14559
14606
  turnResources,
14560
14607
  // Rig default sets merged BELOW the session set (session wins); rig-less
14561
14608
  // turns pass exactly workspaceVariableSet?.values (byte-for-byte today).
@@ -14646,7 +14693,7 @@ async function prepareRunCredentials(deps) {
14646
14693
  if (!pendingBinding) {
14647
14694
  throw new Error("credential renewal produced no binding token");
14648
14695
  }
14649
- const runAs = sandboxRunAs4(runSettings);
14696
+ const runAs = sandboxRunAs3(runSettings);
14650
14697
  const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
14651
14698
  if (!targetSandbox) {
14652
14699
  throw new Error("Git credential renewal has no exact sandbox lease target");
@@ -14713,7 +14760,7 @@ async function prepareRunCredentials(deps) {
14713
14760
  };
14714
14761
  const write = async (material) => {
14715
14762
  if (tokenSession) {
14716
- const runAs = sandboxRunAs4(runSettings);
14763
+ const runAs = sandboxRunAs3(runSettings);
14717
14764
  const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
14718
14765
  if (!targetSandbox) {
14719
14766
  throw new Error("Codemode token renewal has no exact sandbox lease target");
@@ -16007,9 +16054,12 @@ function appRepositoryAuthority(resources) {
16007
16054
  );
16008
16055
  const repositoryId = positiveSafeInteger(resource.githubRepositoryId ?? resource.repositoryId);
16009
16056
  const fullName = canonicalGitHubFullName(resource.uri);
16010
- if (!installationId || !repositoryId || !fullName) {
16057
+ if (!installationId || !repositoryId) {
16011
16058
  throw new GitHubRestAuthorityError("GitHub App repository authority is incomplete");
16012
16059
  }
16060
+ if (!fullName) {
16061
+ throw new GitHubRestAuthorityError("GitHub App repository URL is invalid");
16062
+ }
16013
16063
  return [
16014
16064
  {
16015
16065
  repositoryId: String(repositoryId),
@@ -16285,8 +16335,9 @@ function githubConnectorBindings(serverId, repositories) {
16285
16335
  function canonicalGitHubFullName(uri) {
16286
16336
  try {
16287
16337
  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)) {
16338
+ const clonePath = url.pathname.replace(/^\/+|\/+$/gu, "");
16339
+ const path = clonePath.endsWith(".git") ? clonePath.slice(0, -4) : clonePath;
16340
+ 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
16341
  return null;
16291
16342
  }
16292
16343
  return path;
@@ -16735,7 +16786,7 @@ import {
16735
16786
  resolveSessionToolPolicy
16736
16787
  } from "@opengeni/core";
16737
16788
  import { SandboxChannelAService as SandboxChannelAService3 } from "@opengeni/runtime/sandbox";
16738
- import { sandboxRunAs as sandboxRunAs5 } from "@opengeni/runtime";
16789
+ import { sandboxRunAs as sandboxRunAs4 } from "@opengeni/runtime";
16739
16790
 
16740
16791
  // src/activities/agent-turn/session-title.ts
16741
16792
  import { hasPermission } from "@opengeni/core";
@@ -16815,6 +16866,21 @@ function createSessionTitleAttemptToolDefinition(input) {
16815
16866
  };
16816
16867
  }
16817
16868
 
16869
+ // src/activities/agent-turn/turn-sandbox-access.ts
16870
+ async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, unavailableMessage) {
16871
+ let sandbox = sandboxState.resolvedSandbox;
16872
+ if (!sandbox && sandboxState.turnSandboxProvisioner) {
16873
+ sandbox = await sandboxState.turnSandboxProvisioner.get();
16874
+ }
16875
+ const session = sandboxState.lazyOwnedSandbox?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
16876
+ if (!session) throw new Error(unavailableMessage);
16877
+ return {
16878
+ sandbox,
16879
+ session,
16880
+ leaseEpoch: sandbox?.leaseEpoch ?? 0
16881
+ };
16882
+ }
16883
+
16818
16884
  // src/activities/agent-turn/tool-environment.ts
16819
16885
  async function prepareTurnToolPolicy(deps) {
16820
16886
  const {
@@ -17185,19 +17251,17 @@ async function prepareTurnToolRuntime(deps) {
17185
17251
  const materializeConnectorAttachments = async (request) => {
17186
17252
  throwIfWorkerShuttingDown();
17187
17253
  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);
17254
+ const sandboxAccess = await resolveTurnSandboxAccess(
17255
+ sandboxState,
17256
+ media.sdkOwnedSandboxSession,
17257
+ "Connector attachment sandbox is unavailable"
17258
+ );
17259
+ const sandbox = sandboxAccess.sandbox;
17260
+ const runAs = sandboxRunAs4(runSettings);
17197
17261
  const channel = new SandboxChannelAService3({
17198
- session: sessionForImport,
17262
+ session: sandboxAccess.session,
17199
17263
  workspaceRoot: "/workspace",
17200
- leaseEpoch: sandbox?.leaseEpoch ?? 0,
17264
+ leaseEpoch: sandboxAccess.leaseEpoch,
17201
17265
  emit: async (events) => {
17202
17266
  await eventing.publish?.(events, true);
17203
17267
  },
@@ -18679,23 +18743,17 @@ function validateReferenceImage(bytes) {
18679
18743
 
18680
18744
  // src/activities/agent-turn/agent-build.ts
18681
18745
  import { SandboxChannelAService as SandboxChannelAService4 } from "@opengeni/runtime/sandbox";
18682
- import { sandboxRunAs as sandboxRunAs6 } from "@opengeni/runtime";
18746
+ import { sandboxRunAs as sandboxRunAs5 } from "@opengeni/runtime";
18683
18747
  import { VideoGenerationRejectedResult } from "@opengeni/contracts";
18684
18748
 
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
- };
18749
+ // src/activities/agent-turn/video-reference-sandbox.ts
18750
+ async function resolveVideoReferenceSandboxAccess(request, sandboxState, sdkOwnedSandboxSession) {
18751
+ if (videoReferencePaths(request).length === 0) return null;
18752
+ return await resolveTurnSandboxAccess(
18753
+ sandboxState,
18754
+ sdkOwnedSandboxSession,
18755
+ "Video reference sandbox is unavailable"
18756
+ );
18699
18757
  }
18700
18758
 
18701
18759
  // src/activities/agent-turn/agent-build.ts
@@ -18710,8 +18768,6 @@ async function buildTurnAgent(deps) {
18710
18768
  runtimeCancellationSignal,
18711
18769
  eventing,
18712
18770
  sandboxState,
18713
- recordingState,
18714
- maybeStartOnTurnRecording,
18715
18771
  providerTurn,
18716
18772
  media,
18717
18773
  leases,
@@ -18778,12 +18834,13 @@ async function buildTurnAgent(deps) {
18778
18834
  subjectId: fileAuthoritySubjectId,
18779
18835
  references,
18780
18836
  readSandboxFile: async (path, maxBytes) => {
18781
- const imageReferenceSandbox = await resolveImageReferenceSandboxSession(
18837
+ const imageReferenceSandbox = await resolveTurnSandboxAccess(
18782
18838
  sandboxState,
18783
- media.sdkOwnedSandboxSession
18839
+ media.sdkOwnedSandboxSession,
18840
+ "Sandbox image reference is unavailable"
18784
18841
  );
18785
18842
  const relativePath = path.slice("/workspace/".length);
18786
- const referenceRunAs = sandboxRunAs6(eventing.modelRunSettings);
18843
+ const referenceRunAs = sandboxRunAs5(eventing.modelRunSettings);
18787
18844
  const channel = new SandboxChannelAService4({
18788
18845
  session: imageReferenceSandbox.session,
18789
18846
  workspaceRoot: "/workspace",
@@ -19007,9 +19064,16 @@ async function buildTurnAgent(deps) {
19007
19064
  videoGeneration: {
19008
19065
  capabilities: async () => capabilities,
19009
19066
  execute: async (toolInput, { toolCallId }) => {
19010
- const sessionForReference = sandboxState.resolvedSandbox?.established.session ?? media.sdkOwnedSandboxSession;
19067
+ const referenceSandbox = await resolveVideoReferenceSandboxAccess(
19068
+ toolInput,
19069
+ sandboxState,
19070
+ media.sdkOwnedSandboxSession
19071
+ );
19011
19072
  const fence = eventing.toolCancellationFenceRef.current;
19012
- const runAs = sandboxRunAs6(eventing.modelRunSettings);
19073
+ if (referenceSandbox && !fence) {
19074
+ throw new Error("Video reference command fence is unavailable");
19075
+ }
19076
+ const runAs = sandboxRunAs5(eventing.modelRunSettings);
19013
19077
  let accepted;
19014
19078
  try {
19015
19079
  accepted = await admitVideoGenerationRequest({
@@ -19025,9 +19089,9 @@ async function buildTurnAgent(deps) {
19025
19089
  toolInput,
19026
19090
  policy: videoGenerationPolicy,
19027
19091
  credential: videoGenerationCredential,
19028
- ...sessionForReference && fence ? {
19092
+ ...referenceSandbox && fence ? {
19029
19093
  runCommand: async (command) => await fence.runSandboxCommandStructured(
19030
- sessionForReference,
19094
+ referenceSandbox.session,
19031
19095
  {
19032
19096
  ...command,
19033
19097
  ...runAs ? { runAs } : {}
@@ -19184,29 +19248,15 @@ async function buildTurnAgent(deps) {
19184
19248
  // typed input_image content. Chat wires have no proven typed image
19185
19249
  // result transport and therefore receive no view_image tool.
19186
19250
  structuredToolTransport: structuredToolTransportForTurn(resolvedModel),
19187
- // EXPLICIT computer-use tool transport. See {@link computerToolModeForTurn}.
19188
- computerToolMode: computerToolModeForTurn(resolvedModel),
19189
19251
  ...promptCacheKey ? { promptCacheKey } : {}
19190
19252
  } : (
19191
19253
  // LEGACY global-client fallback (resolveTurnModel returned null → the model
19192
19254
  // 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.
19255
+ // client).
19195
19256
  {
19196
- computerToolMode: computerToolModeForTurn(null),
19197
19257
  promptCacheKey: input.sessionId
19198
19258
  }
19199
19259
  ),
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
19260
  onRetainableSessionImageOutput: media.retainSessionImageAtToolBoundary,
19211
19261
  ...runtimeSkillActivations.length > 0 ? { skillActivations: runtimeSkillActivations } : {},
19212
19262
  ...!structuredWorkspacePolicyActive && workspaceAgentInstructions ? { instructionsTemplate: workspaceAgentInstructions } : {},
@@ -19302,7 +19352,6 @@ function createRunAgentTurnActivity(services) {
19302
19352
  billingState,
19303
19353
  sandboxState,
19304
19354
  renewals,
19305
- recordingState,
19306
19355
  eventing,
19307
19356
  workspaceRefs,
19308
19357
  providerTurn
@@ -19378,7 +19427,6 @@ function createRunAgentTurnActivity(services) {
19378
19427
  activityContext,
19379
19428
  sandboxRotationController,
19380
19429
  sandboxState,
19381
- recordingState,
19382
19430
  eventing,
19383
19431
  attempt
19384
19432
  });
@@ -19386,9 +19434,7 @@ function createRunAgentTurnActivity(services) {
19386
19434
  requireResolvedSandboxForMutation,
19387
19435
  runWorkspaceMutationForSandbox,
19388
19436
  stopLeaseHeartbeat,
19389
- abandonActiveRecording,
19390
19437
  flushRuntimeBatcher,
19391
- maybeStartOnTurnRecording,
19392
19438
  finalizeTurnOpStreamOps
19393
19439
  } = sandboxRuntime;
19394
19440
  const media = createTurnMediaArtifacts({
@@ -19450,7 +19496,6 @@ function createRunAgentTurnActivity(services) {
19450
19496
  db,
19451
19497
  bus,
19452
19498
  runtime,
19453
- objectStorage,
19454
19499
  observability,
19455
19500
  entitlements,
19456
19501
  wakeSessionWorkflow,
@@ -19462,13 +19507,11 @@ function createRunAgentTurnActivity(services) {
19462
19507
  attempt,
19463
19508
  billingState,
19464
19509
  sandboxState,
19465
- recordingState,
19466
19510
  eventing,
19467
19511
  leases,
19468
19512
  media,
19469
19513
  claimedResult,
19470
- acknowledgeLostAttemptOwnership,
19471
- abandonActiveRecording
19514
+ acknowledgeLostAttemptOwnership
19472
19515
  });
19473
19516
  if ("exit" in claimed) return claimed.exit;
19474
19517
  if (!eventing.publish || !eventing.settle) {
@@ -19487,6 +19530,7 @@ function createRunAgentTurnActivity(services) {
19487
19530
  trigger,
19488
19531
  humanInputResume,
19489
19532
  interactionInterventionResume,
19533
+ attachPendingUpdatesAfterOpenSuffix,
19490
19534
  throwIfWorkerShuttingDown,
19491
19535
  throwIfTurnCancelled,
19492
19536
  opJournal,
@@ -19688,6 +19732,10 @@ function createRunAgentTurnActivity(services) {
19688
19732
  }
19689
19733
  }
19690
19734
  ]);
19735
+ attempt.providerRecoveryCount = providerRecoveryCountAfterModelRequestPhase(
19736
+ attempt.providerRecoveryCount,
19737
+ event.phase
19738
+ );
19691
19739
  } catch (error) {
19692
19740
  auditOutcome = "failed";
19693
19741
  throw error;
@@ -19807,6 +19855,10 @@ function createRunAgentTurnActivity(services) {
19807
19855
  }
19808
19856
  }
19809
19857
  ]);
19858
+ attempt.providerRecoveryCount = providerRecoveryCountAfterModelRequestPhase(
19859
+ attempt.providerRecoveryCount,
19860
+ event.phase
19861
+ );
19810
19862
  } catch (error) {
19811
19863
  auditOutcome = "failed";
19812
19864
  throw error;
@@ -19885,7 +19937,8 @@ function createRunAgentTurnActivity(services) {
19885
19937
  publishCompactionOutcomeEvents,
19886
19938
  compactionModeOptions,
19887
19939
  compactionOnlyTurn,
19888
- compactionSummarizerFor
19940
+ compactionSummarizerFor,
19941
+ settleDeferredSteerAfterCompaction
19889
19942
  } = compactionPrep.ok;
19890
19943
  const toolPolicy = await prepareTurnToolPolicy({
19891
19944
  input,
@@ -20150,8 +20203,6 @@ function createRunAgentTurnActivity(services) {
20150
20203
  eventing,
20151
20204
  attempt,
20152
20205
  sandboxState,
20153
- recordingState,
20154
- maybeStartOnTurnRecording,
20155
20206
  providerTurn,
20156
20207
  media,
20157
20208
  leases,
@@ -20311,6 +20362,7 @@ function createRunAgentTurnActivity(services) {
20311
20362
  compactionModeOptions,
20312
20363
  compactionOnlyTurn,
20313
20364
  compactionSummarizerFor,
20365
+ settleDeferredSteerAfterCompaction,
20314
20366
  agent
20315
20367
  });
20316
20368
  if ("exit" in postAgentCompaction) return postAgentCompaction.exit;
@@ -20344,7 +20396,7 @@ function createRunAgentTurnActivity(services) {
20344
20396
  if (downloadsToMaterialize.length === 0) {
20345
20397
  fileMaterializationCache = "hit";
20346
20398
  }
20347
- const runAs = sandboxRunAs7(runSettings);
20399
+ const runAs = sandboxRunAs6(runSettings);
20348
20400
  if (downloadsToMaterialize.length > 0) {
20349
20401
  const materialized = await runWorkspaceMutationForSandbox(
20350
20402
  sandboxState.resolvedSandbox,
@@ -20472,12 +20524,14 @@ function createRunAgentTurnActivity(services) {
20472
20524
  turn,
20473
20525
  trigger,
20474
20526
  humanInputResume,
20527
+ attachPendingUpdatesAfterOpenSuffix,
20475
20528
  agent,
20476
20529
  resolvedModel,
20477
20530
  providerApi,
20478
20531
  runSettings,
20479
20532
  turnTools,
20480
20533
  compactSummarizer,
20534
+ settleDeferredSteerAfterCompaction,
20481
20535
  compactionModelHistoryProjector,
20482
20536
  generatedImageHistoryProjector,
20483
20537
  modelHistoryProjector,
@@ -20541,14 +20595,12 @@ function createRunAgentTurnActivity(services) {
20541
20595
  attempt,
20542
20596
  sandboxState,
20543
20597
  renewals,
20544
- recordingState,
20545
20598
  eventing,
20546
20599
  providerTurn,
20547
20600
  workspaceRefs,
20548
20601
  runWorkspaceMutationForSandbox,
20549
20602
  requireResolvedSandboxForMutation,
20550
20603
  stopLeaseHeartbeat,
20551
- abandonActiveRecording,
20552
20604
  turnCompletionMemoryCollector
20553
20605
  });
20554
20606
  }
@@ -21645,4 +21697,4 @@ export {
21645
21697
  createTurnActivities,
21646
21698
  createTurnActivitiesFromServices
21647
21699
  };
21648
- //# sourceMappingURL=activities-turn-5RGQDBFV.js.map
21700
+ //# sourceMappingURL=activities-turn-A2G2KLSY.js.map