@opengeni/worker-bundle 4.4.1 → 4.5.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.
@@ -1471,6 +1471,290 @@ function uuidFromDigest(digest2, startByte) {
1471
1471
  return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
1472
1472
  }
1473
1473
 
1474
+ // src/activities/agent-turn/owned-sandbox-setup.ts
1475
+ import {
1476
+ runOwnedSandboxSetup,
1477
+ withRunCredentialsSession
1478
+ } from "@opengeni/runtime";
1479
+
1480
+ // src/activities/agent-turn/sandbox-shared-preparation.ts
1481
+ import { randomUUID } from "crypto";
1482
+ import {
1483
+ claimSandboxSharedPreparation,
1484
+ readSandboxSharedPreparation,
1485
+ SandboxLeaseSupersededError,
1486
+ settleSandboxSharedPreparation
1487
+ } from "@opengeni/db";
1488
+ function observeSharedPreparation(options, measurement) {
1489
+ try {
1490
+ options.observe?.(measurement);
1491
+ } catch {
1492
+ }
1493
+ }
1494
+ function waitForPreparationTransition(ms, signal) {
1495
+ return new Promise((resolve, reject) => {
1496
+ let settled = false;
1497
+ const timer = setTimeout(finish, ms);
1498
+ function finish() {
1499
+ if (settled) return;
1500
+ settled = true;
1501
+ signal?.removeEventListener("abort", cancel);
1502
+ resolve();
1503
+ }
1504
+ function cancel() {
1505
+ if (settled) return;
1506
+ settled = true;
1507
+ clearTimeout(timer);
1508
+ signal?.removeEventListener("abort", cancel);
1509
+ reject(signal?.reason ?? new Error("Sandbox shared preparation wait cancelled"));
1510
+ }
1511
+ signal?.addEventListener("abort", cancel, { once: true });
1512
+ if (signal?.aborted) cancel();
1513
+ });
1514
+ }
1515
+ async function settleCompletedWithRetry(options, input, claimId) {
1516
+ let delayMs = 50;
1517
+ for (let attempt = 0; attempt < 4; attempt += 1) {
1518
+ try {
1519
+ if (await settleSandboxSharedPreparation(options.db, {
1520
+ accountId: options.accountId,
1521
+ workspaceId: options.workspaceId,
1522
+ sandboxGroupId: options.sandboxGroupId,
1523
+ expectedLeaseEpoch: options.sandbox.leaseEpoch,
1524
+ expectedInstanceId: options.sandbox.established.instanceId,
1525
+ specHash: input.specHash,
1526
+ holderId: options.holderId,
1527
+ claimId,
1528
+ outcome: "completed"
1529
+ })) {
1530
+ return true;
1531
+ }
1532
+ } catch {
1533
+ }
1534
+ await waitForPreparationTransition(delayMs, options.signal);
1535
+ delayMs *= 2;
1536
+ }
1537
+ return false;
1538
+ }
1539
+ function createSharedRigSetupCoordinator(options) {
1540
+ return async (input) => {
1541
+ const startedAt = performance.now();
1542
+ const claimId = randomUUID();
1543
+ const identity = {
1544
+ accountId: options.accountId,
1545
+ workspaceId: options.workspaceId,
1546
+ sandboxGroupId: options.sandboxGroupId,
1547
+ expectedLeaseEpoch: options.sandbox.leaseEpoch,
1548
+ expectedInstanceId: options.sandbox.established.instanceId,
1549
+ specHash: input.specHash,
1550
+ holderId: options.holderId
1551
+ };
1552
+ const claimTimeoutMs = Math.min(36e5, Math.max(3e4, input.timeoutMs + 3e4));
1553
+ let delayMs = 100;
1554
+ let observedRevision = -1;
1555
+ let path = "owner";
1556
+ try {
1557
+ for (; ; ) {
1558
+ if (options.signal?.aborted) {
1559
+ throw options.signal.reason ?? new Error("Sandbox shared preparation cancelled");
1560
+ }
1561
+ const claim = await claimSandboxSharedPreparation(options.db, {
1562
+ ...identity,
1563
+ claimId,
1564
+ ownerAttemptId: options.attemptId,
1565
+ timeoutMs: claimTimeoutMs
1566
+ });
1567
+ if (claim.role === "fenced") {
1568
+ throw new SandboxLeaseSupersededError(options.sandboxGroupId, options.sandbox.leaseEpoch);
1569
+ }
1570
+ if (claim.role === "reused") {
1571
+ if (path !== "joined") path = "reused";
1572
+ observeSharedPreparation(options, {
1573
+ path,
1574
+ outcome: "completed",
1575
+ durationSeconds: (performance.now() - startedAt) / 1e3
1576
+ });
1577
+ return "reused";
1578
+ }
1579
+ if (claim.role === "owner") {
1580
+ try {
1581
+ await input.execute();
1582
+ } catch (error51) {
1583
+ await settleSandboxSharedPreparation(options.db, {
1584
+ ...identity,
1585
+ claimId,
1586
+ outcome: "failed"
1587
+ }).catch(() => void 0);
1588
+ throw error51;
1589
+ }
1590
+ if (await settleCompletedWithRetry(options, input, claimId)) {
1591
+ observeSharedPreparation(options, {
1592
+ path,
1593
+ outcome: "completed",
1594
+ durationSeconds: (performance.now() - startedAt) / 1e3
1595
+ });
1596
+ return "executed";
1597
+ }
1598
+ throw new Error(
1599
+ "Sandbox shared preparation completed but its durable settlement remains unavailable"
1600
+ );
1601
+ }
1602
+ path = "joined";
1603
+ observedRevision = claim.preparation.revision;
1604
+ const jitterMs = Math.floor(Math.random() * Math.max(1, Math.floor(delayMs / 4)));
1605
+ await waitForPreparationTransition(delayMs + jitterMs, options.signal);
1606
+ const observed = await readSandboxSharedPreparation(options.db, identity);
1607
+ if (observed.status === "fenced") {
1608
+ throw new SandboxLeaseSupersededError(options.sandboxGroupId, options.sandbox.leaseEpoch);
1609
+ }
1610
+ if (observed.preparation.status === "completed") {
1611
+ observeSharedPreparation(options, {
1612
+ path,
1613
+ outcome: "completed",
1614
+ durationSeconds: (performance.now() - startedAt) / 1e3
1615
+ });
1616
+ return "reused";
1617
+ }
1618
+ if (observed.preparation.status === "failed") {
1619
+ delayMs = 100;
1620
+ continue;
1621
+ }
1622
+ delayMs = observed.preparation.revision === observedRevision ? Math.min(2e3, delayMs * 2) : 100;
1623
+ }
1624
+ } catch (error51) {
1625
+ observeSharedPreparation(options, {
1626
+ path,
1627
+ outcome: "failed",
1628
+ durationSeconds: (performance.now() - startedAt) / 1e3
1629
+ });
1630
+ throw error51;
1631
+ }
1632
+ };
1633
+ }
1634
+
1635
+ // src/activities/agent-turn/turn-sandbox-access.ts
1636
+ function ownedTurnSandboxForAgent(sandboxState) {
1637
+ return sandboxState.lazyOwnedSandbox ?? sandboxState.resolvedSandbox?.established;
1638
+ }
1639
+ async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, unavailableMessage) {
1640
+ let sandbox = sandboxState.resolvedSandbox;
1641
+ if (!sandbox && sandboxState.turnSandboxProvisioner) {
1642
+ sandbox = await sandboxState.turnSandboxProvisioner.get();
1643
+ }
1644
+ const session = ownedTurnSandboxForAgent(sandboxState)?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
1645
+ if (!session) throw new Error(unavailableMessage);
1646
+ return {
1647
+ sandbox,
1648
+ session,
1649
+ leaseEpoch: sandbox?.leaseEpoch ?? 0
1650
+ };
1651
+ }
1652
+
1653
+ // src/activities/agent-turn/owned-sandbox-setup.ts
1654
+ function hasEagerOwnedSandboxSetup(sandboxState) {
1655
+ return Boolean(
1656
+ sandboxState.resolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedTurnSandboxForAgent(sandboxState)
1657
+ );
1658
+ }
1659
+ async function runEagerOwnedSandboxSetup(deps, options) {
1660
+ const { input, sandboxState, eventing, leases, observability } = deps;
1661
+ const eagerResolvedSandbox = sandboxState.resolvedSandbox;
1662
+ const ownedEstablished = ownedTurnSandboxForAgent(sandboxState);
1663
+ if (!eagerResolvedSandbox || sandboxState.lazyOwnedSandbox || !ownedEstablished) return;
1664
+ const ownedSandboxSetupStartedAt = performance.now();
1665
+ let ownedSandboxSetupOutcome = "completed";
1666
+ try {
1667
+ const eagerSetupSession = sandboxState.setupBoxSession ?? ownedEstablished.session;
1668
+ await deps.attachRunCredentialRenewal(
1669
+ eagerSetupSession,
1670
+ deps.initialRunCredentialMaterial,
1671
+ eagerResolvedSandbox
1672
+ );
1673
+ const eagerCredentialSetupSession = deps.initialRunCredentialMaterial ? withRunCredentialsSession(eagerSetupSession, input.sessionId) : eagerSetupSession;
1674
+ await deps.runWorkspaceMutationForSandbox(
1675
+ eagerResolvedSandbox,
1676
+ "eagerOwnedSandboxSetup",
1677
+ async () => await runOwnedSandboxSetup(
1678
+ deps.agent,
1679
+ ownedEstablished.session,
1680
+ eagerCredentialSetupSession,
1681
+ {
1682
+ settings: deps.runSettings,
1683
+ environment: deps.sandboxEnvironment,
1684
+ ...options.preparedInput ? { preparedInput: options.preparedInput } : {},
1685
+ ...options.fileDownloadsMaterialized ? { fileDownloadsMaterialized: true } : {},
1686
+ onRuntimeEvent: async (event) => {
1687
+ await leases.renewServing("runtime_event");
1688
+ if (leases.servingLost()) {
1689
+ throw new Error("Provider credential lease expired during sandbox setup");
1690
+ }
1691
+ await eventing.publish([{ type: event.type, payload: event.payload }], true);
1692
+ },
1693
+ ...eventing.toolCancellationFenceRef.current ? {
1694
+ commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
1695
+ eventing.toolCancellationFenceRef.current
1696
+ )
1697
+ } : {},
1698
+ ...sandboxState.sandboxGroupId && sandboxState.sandboxHolderId ? {
1699
+ coordinateSharedRigSetup: createSharedRigSetupCoordinator({
1700
+ db: deps.db,
1701
+ accountId: input.accountId,
1702
+ workspaceId: input.workspaceId,
1703
+ sandboxGroupId: sandboxState.sandboxGroupId,
1704
+ attemptId: input.attemptId,
1705
+ holderId: sandboxState.sandboxHolderId,
1706
+ sandbox: eagerResolvedSandbox,
1707
+ ...deps.runtimeCancellationSignal ? { signal: deps.runtimeCancellationSignal } : {},
1708
+ observe: (measurement) => recordSandboxSharedPreparation(observability, measurement)
1709
+ })
1710
+ } : {}
1711
+ }
1712
+ )
1713
+ );
1714
+ await deps.attachGitCredentialRenewal(
1715
+ eagerSetupSession,
1716
+ deps.initialGitCredentials
1717
+ );
1718
+ } catch (error51) {
1719
+ ownedSandboxSetupOutcome = "failed";
1720
+ throw error51;
1721
+ } finally {
1722
+ recordTurnStartupPhase(observability, {
1723
+ phase: "owned_sandbox_setup",
1724
+ provider: deps.turnExecutionPolicy.providerId,
1725
+ backend: deps.activeSandboxBackend ?? deps.groupBoxBackend,
1726
+ outcome: ownedSandboxSetupOutcome,
1727
+ durationSeconds: (performance.now() - ownedSandboxSetupStartedAt) / 1e3,
1728
+ count: deps.fileResourceDownloads.length
1729
+ });
1730
+ }
1731
+ }
1732
+ function createEagerOwnedSandboxSetup(deps, start, runSetup = runEagerOwnedSandboxSetup) {
1733
+ const startedFor = start ? sandboxIdentity(deps.sandboxState) : null;
1734
+ let started = start ? runSetup(deps, {
1735
+ fileDownloadsMaterialized: start.fileDownloadsMaterialized
1736
+ }) : null;
1737
+ const settled = started ? started.then(noop, noop) : Promise.resolve();
1738
+ return {
1739
+ beforeModelStream: async (options) => {
1740
+ if (started) {
1741
+ const prestarted = started;
1742
+ started = null;
1743
+ await prestarted;
1744
+ if (sandboxIdentity(deps.sandboxState) === startedFor) return;
1745
+ }
1746
+ await runSetup(deps, options);
1747
+ },
1748
+ settled: () => settled
1749
+ };
1750
+ }
1751
+ function sandboxIdentity(sandboxState) {
1752
+ const resolved = sandboxState.resolvedSandbox;
1753
+ return resolved ? `${resolved.leaseEpoch}:${resolved.established.instanceId}` : null;
1754
+ }
1755
+ function noop() {
1756
+ }
1757
+
1474
1758
  // src/activities/agent-turn/credential-leases.ts
1475
1759
  import {
1476
1760
  CODEX_CREDENTIAL_LEASE_TTL_MS,
@@ -6972,7 +7256,7 @@ import {
6972
7256
  recordUsageEvent,
6973
7257
  getActiveSessionHistoryItemsPaged,
6974
7258
  readLease,
6975
- SandboxLeaseSupersededError,
7259
+ SandboxLeaseSupersededError as SandboxLeaseSupersededError2,
6976
7260
  isSessionEventPersistenceError as isSessionEventPersistenceError2,
6977
7261
  SANDBOX_SETUP_RECOVERY_LIMIT,
6978
7262
  SubscriptionCoreCodexAccessLostError,
@@ -7988,7 +8272,7 @@ async function settleTurnFailureInAttempt(deps) {
7988
8272
  return claimedResult({ status: "recovering", deferredUntilWake: true });
7989
8273
  }
7990
8274
  const lifecycleTransition = sandboxLifecycleTransitionDiagnostic(error51);
7991
- const leaseControlError = error51 instanceof SandboxLeaseSupersededError ? error51 : lifecycleTransition;
8275
+ const leaseControlError = error51 instanceof SandboxLeaseSupersededError2 ? error51 : lifecycleTransition;
7992
8276
  if (leaseControlError && recoveryTurnId) {
7993
8277
  try {
7994
8278
  const fencedLease = await readLease(
@@ -9079,8 +9363,6 @@ import {
9079
9363
  findAnthropicRequestSizeError,
9080
9364
  ANTHROPIC_REQUEST_MAX_BYTES as ANTHROPIC_REQUEST_MAX_BYTES2,
9081
9365
  compactionProviderRejection,
9082
- withRunCredentialsSession,
9083
- runOwnedSandboxSetup,
9084
9366
  modelResponseHasVisibleText,
9085
9367
  ModelStepHandover,
9086
9368
  isPreemptedModelResponse,
@@ -9605,7 +9887,7 @@ function programmaticContinuationNote(operations) {
9605
9887
  }
9606
9888
 
9607
9889
  // src/activities/codemode-dispatcher.ts
9608
- import { randomUUID } from "crypto";
9890
+ import { randomUUID as randomUUID2 } from "crypto";
9609
9891
  import {
9610
9892
  bindMcpTelemetry,
9611
9893
  measureMcpPhase,
@@ -9712,7 +9994,7 @@ var CodemodeAttemptDispatcher = class _CodemodeAttemptDispatcher {
9712
9994
  ...this.scope,
9713
9995
  catalogDigest: request.catalogDigest,
9714
9996
  operationId: request.operationId,
9715
- claimId: randomUUID(),
9997
+ claimId: randomUUID2(),
9716
9998
  claimLeaseMs: this.claimLeaseMs
9717
9999
  });
9718
10000
  if (claim.status === "claimed") {
@@ -9818,7 +10100,7 @@ var CodemodeAttemptDispatcher = class _CodemodeAttemptDispatcher {
9818
10100
  const claim = await claimCodemodeOperation(this.db, {
9819
10101
  ...this.scope,
9820
10102
  operationId: adopted.operationId,
9821
- claimId: randomUUID(),
10103
+ claimId: randomUUID2(),
9822
10104
  catalogDigest: this.environment.catalog.digest,
9823
10105
  claimLeaseMs: this.claimLeaseMs
9824
10106
  });
@@ -10171,24 +10453,6 @@ function safeErrorMessage(error51) {
10171
10453
  return "Codemode call failed before tool execution";
10172
10454
  }
10173
10455
 
10174
- // src/activities/agent-turn/turn-sandbox-access.ts
10175
- function ownedTurnSandboxForAgent(sandboxState) {
10176
- return sandboxState.lazyOwnedSandbox ?? sandboxState.resolvedSandbox?.established;
10177
- }
10178
- async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, unavailableMessage) {
10179
- let sandbox = sandboxState.resolvedSandbox;
10180
- if (!sandbox && sandboxState.turnSandboxProvisioner) {
10181
- sandbox = await sandboxState.turnSandboxProvisioner.get();
10182
- }
10183
- const session = ownedTurnSandboxForAgent(sandboxState)?.session ?? sandbox?.established.session ?? sdkOwnedSandboxSession;
10184
- if (!session) throw new Error(unavailableMessage);
10185
- return {
10186
- sandbox,
10187
- session,
10188
- leaseEpoch: sandbox?.leaseEpoch ?? 0
10189
- };
10190
- }
10191
-
10192
10456
  // src/activities/open-suffix-resume.ts
10193
10457
  import {
10194
10458
  OPEN_SUFFIX_RUN_STATE_BLOB,
@@ -11010,161 +11274,6 @@ async function inputWaitReplyRefusal(input) {
11010
11274
  return await input.hasVisibleReply() ? null : INPUT_WAIT_REPLY_REFUSAL;
11011
11275
  }
11012
11276
 
11013
- // src/activities/agent-turn/sandbox-shared-preparation.ts
11014
- import { randomUUID as randomUUID2 } from "crypto";
11015
- import {
11016
- claimSandboxSharedPreparation,
11017
- readSandboxSharedPreparation,
11018
- SandboxLeaseSupersededError as SandboxLeaseSupersededError2,
11019
- settleSandboxSharedPreparation
11020
- } from "@opengeni/db";
11021
- function observeSharedPreparation(options, measurement) {
11022
- try {
11023
- options.observe?.(measurement);
11024
- } catch {
11025
- }
11026
- }
11027
- function waitForPreparationTransition(ms, signal) {
11028
- return new Promise((resolve, reject) => {
11029
- let settled = false;
11030
- const timer = setTimeout(finish, ms);
11031
- function finish() {
11032
- if (settled) return;
11033
- settled = true;
11034
- signal?.removeEventListener("abort", cancel);
11035
- resolve();
11036
- }
11037
- function cancel() {
11038
- if (settled) return;
11039
- settled = true;
11040
- clearTimeout(timer);
11041
- signal?.removeEventListener("abort", cancel);
11042
- reject(signal?.reason ?? new Error("Sandbox shared preparation wait cancelled"));
11043
- }
11044
- signal?.addEventListener("abort", cancel, { once: true });
11045
- if (signal?.aborted) cancel();
11046
- });
11047
- }
11048
- async function settleCompletedWithRetry(options, input, claimId) {
11049
- let delayMs = 50;
11050
- for (let attempt = 0; attempt < 4; attempt += 1) {
11051
- try {
11052
- if (await settleSandboxSharedPreparation(options.db, {
11053
- accountId: options.accountId,
11054
- workspaceId: options.workspaceId,
11055
- sandboxGroupId: options.sandboxGroupId,
11056
- expectedLeaseEpoch: options.sandbox.leaseEpoch,
11057
- expectedInstanceId: options.sandbox.established.instanceId,
11058
- specHash: input.specHash,
11059
- holderId: options.holderId,
11060
- claimId,
11061
- outcome: "completed"
11062
- })) {
11063
- return true;
11064
- }
11065
- } catch {
11066
- }
11067
- await waitForPreparationTransition(delayMs, options.signal);
11068
- delayMs *= 2;
11069
- }
11070
- return false;
11071
- }
11072
- function createSharedRigSetupCoordinator(options) {
11073
- return async (input) => {
11074
- const startedAt = performance.now();
11075
- const claimId = randomUUID2();
11076
- const identity = {
11077
- accountId: options.accountId,
11078
- workspaceId: options.workspaceId,
11079
- sandboxGroupId: options.sandboxGroupId,
11080
- expectedLeaseEpoch: options.sandbox.leaseEpoch,
11081
- expectedInstanceId: options.sandbox.established.instanceId,
11082
- specHash: input.specHash,
11083
- holderId: options.holderId
11084
- };
11085
- const claimTimeoutMs = Math.min(36e5, Math.max(3e4, input.timeoutMs + 3e4));
11086
- let delayMs = 100;
11087
- let observedRevision = -1;
11088
- let path = "owner";
11089
- try {
11090
- for (; ; ) {
11091
- if (options.signal?.aborted) {
11092
- throw options.signal.reason ?? new Error("Sandbox shared preparation cancelled");
11093
- }
11094
- const claim = await claimSandboxSharedPreparation(options.db, {
11095
- ...identity,
11096
- claimId,
11097
- ownerAttemptId: options.attemptId,
11098
- timeoutMs: claimTimeoutMs
11099
- });
11100
- if (claim.role === "fenced") {
11101
- throw new SandboxLeaseSupersededError2(options.sandboxGroupId, options.sandbox.leaseEpoch);
11102
- }
11103
- if (claim.role === "reused") {
11104
- if (path !== "joined") path = "reused";
11105
- observeSharedPreparation(options, {
11106
- path,
11107
- outcome: "completed",
11108
- durationSeconds: (performance.now() - startedAt) / 1e3
11109
- });
11110
- return "reused";
11111
- }
11112
- if (claim.role === "owner") {
11113
- try {
11114
- await input.execute();
11115
- } catch (error51) {
11116
- await settleSandboxSharedPreparation(options.db, {
11117
- ...identity,
11118
- claimId,
11119
- outcome: "failed"
11120
- }).catch(() => void 0);
11121
- throw error51;
11122
- }
11123
- if (await settleCompletedWithRetry(options, input, claimId)) {
11124
- observeSharedPreparation(options, {
11125
- path,
11126
- outcome: "completed",
11127
- durationSeconds: (performance.now() - startedAt) / 1e3
11128
- });
11129
- return "executed";
11130
- }
11131
- throw new Error(
11132
- "Sandbox shared preparation completed but its durable settlement remains unavailable"
11133
- );
11134
- }
11135
- path = "joined";
11136
- observedRevision = claim.preparation.revision;
11137
- const jitterMs = Math.floor(Math.random() * Math.max(1, Math.floor(delayMs / 4)));
11138
- await waitForPreparationTransition(delayMs + jitterMs, options.signal);
11139
- const observed = await readSandboxSharedPreparation(options.db, identity);
11140
- if (observed.status === "fenced") {
11141
- throw new SandboxLeaseSupersededError2(options.sandboxGroupId, options.sandbox.leaseEpoch);
11142
- }
11143
- if (observed.preparation.status === "completed") {
11144
- observeSharedPreparation(options, {
11145
- path,
11146
- outcome: "completed",
11147
- durationSeconds: (performance.now() - startedAt) / 1e3
11148
- });
11149
- return "reused";
11150
- }
11151
- if (observed.preparation.status === "failed") {
11152
- delayMs = 100;
11153
- continue;
11154
- }
11155
- delayMs = observed.preparation.revision === observedRevision ? Math.min(2e3, delayMs * 2) : 100;
11156
- }
11157
- } catch (error51) {
11158
- observeSharedPreparation(options, {
11159
- path,
11160
- outcome: "failed",
11161
- durationSeconds: (performance.now() - startedAt) / 1e3
11162
- });
11163
- throw error51;
11164
- }
11165
- };
11166
- }
11167
-
11168
11277
  // src/activities/agent-turn/final-reply.ts
11169
11278
  function finalReplyNudge(turnId) {
11170
11279
  return {
@@ -26895,11 +27004,9 @@ async function runTurnStreamAttempt(deps) {
26895
27004
  claimedResult,
26896
27005
  flushRuntimeBatcher,
26897
27006
  finalizeTurnOpStreamOps,
26898
- runWorkspaceMutationForSandbox,
26899
27007
  throwIfWorkerShuttingDown,
26900
27008
  throwIfTurnCancelled,
26901
27009
  setLastInputTokensFenced,
26902
- attachGitCredentialRenewal,
26903
27010
  attachCodemodeTokenRenewal,
26904
27011
  attachRunCredentialRenewal,
26905
27012
  withProviderRequestContext,
@@ -26939,11 +27046,9 @@ async function runTurnStreamAttempt(deps) {
26939
27046
  modelHistoryProjector,
26940
27047
  compactionModeOptions,
26941
27048
  initialRunCredentialMaterial,
26942
- initialGitCredentials,
26943
27049
  sandboxEnvironment,
26944
27050
  sandboxCodemodeToken,
26945
27051
  sandboxCodemodeTokenExpiresAt,
26946
- fileResourceDownloads,
26947
27052
  runCredentialResolver,
26948
27053
  videoGenerationAcceptancesByCallId
26949
27054
  } = deps;
@@ -27315,77 +27420,12 @@ async function runTurnStreamAttempt(deps) {
27315
27420
  });
27316
27421
  };
27317
27422
  const ownedEstablished = ownedTurnSandboxForAgent(sandboxState);
27423
+ const eagerOwnedSandboxSetup = deps.eagerOwnedSandboxSetup ?? createEagerOwnedSandboxSetup(deps);
27318
27424
  const runStreamOnce = async () => {
27319
- const eagerResolvedSandbox = sandboxState.resolvedSandbox;
27320
- if (eagerResolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
27321
- const ownedSandboxSetupStartedAt = performance.now();
27322
- let ownedSandboxSetupOutcome = "completed";
27323
- try {
27324
- const eagerSetupSession = sandboxState.setupBoxSession ?? ownedEstablished.session;
27325
- await attachRunCredentialRenewal(
27326
- eagerSetupSession,
27327
- initialRunCredentialMaterial,
27328
- eagerResolvedSandbox
27329
- );
27330
- const eagerCredentialSetupSession = initialRunCredentialMaterial ? withRunCredentialsSession(eagerSetupSession, input.sessionId) : eagerSetupSession;
27331
- await runWorkspaceMutationForSandbox(
27332
- eagerResolvedSandbox,
27333
- "eagerOwnedSandboxSetup",
27334
- async () => await runOwnedSandboxSetup(
27335
- agent,
27336
- ownedEstablished.session,
27337
- eagerCredentialSetupSession,
27338
- {
27339
- settings: runSettings,
27340
- environment: sandboxEnvironment,
27341
- preparedInput: runInput,
27342
- ...fileDownloadsMaterializedForRun ? { fileDownloadsMaterialized: true } : {},
27343
- onRuntimeEvent: async (event) => {
27344
- await leases.renewServing("runtime_event");
27345
- if (leases.servingLost()) {
27346
- throw new Error("Provider credential lease expired during sandbox setup");
27347
- }
27348
- await eventing.publish([{ type: event.type, payload: event.payload }], true);
27349
- },
27350
- ...eventing.toolCancellationFenceRef.current ? {
27351
- commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
27352
- eventing.toolCancellationFenceRef.current
27353
- )
27354
- } : {},
27355
- ...sandboxState.sandboxGroupId && sandboxState.sandboxHolderId ? {
27356
- coordinateSharedRigSetup: createSharedRigSetupCoordinator({
27357
- db,
27358
- accountId: input.accountId,
27359
- workspaceId: input.workspaceId,
27360
- sandboxGroupId: sandboxState.sandboxGroupId,
27361
- attemptId: input.attemptId,
27362
- holderId: sandboxState.sandboxHolderId,
27363
- sandbox: eagerResolvedSandbox,
27364
- ...runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {},
27365
- observe: (measurement) => recordSandboxSharedPreparation(observability, measurement)
27366
- })
27367
- } : {}
27368
- }
27369
- )
27370
- );
27371
- await attachGitCredentialRenewal(
27372
- eagerSetupSession,
27373
- initialGitCredentials
27374
- );
27375
- } catch (error51) {
27376
- ownedSandboxSetupOutcome = "failed";
27377
- throw error51;
27378
- } finally {
27379
- recordTurnStartupPhase(observability, {
27380
- phase: "owned_sandbox_setup",
27381
- provider: turnExecutionPolicy.providerId,
27382
- backend: activeSandboxBackend ?? groupBoxBackend,
27383
- outcome: ownedSandboxSetupOutcome,
27384
- durationSeconds: (performance.now() - ownedSandboxSetupStartedAt) / 1e3,
27385
- count: fileResourceDownloads.length
27386
- });
27387
- }
27388
- }
27425
+ await eagerOwnedSandboxSetup.beforeModelStream({
27426
+ preparedInput: runInput,
27427
+ fileDownloadsMaterialized: fileDownloadsMaterializedForRun
27428
+ });
27389
27429
  recordCompanyBrainContributionReceiptOnce();
27390
27430
  if (!eventing.firstModelRequestPreparationRecorded) {
27391
27431
  await eventing.publish([
@@ -42852,194 +42892,226 @@ These are publication receipts for the human's earlier answer. Do not call the r
42852
42892
  outcome: "completed",
42853
42893
  durationSeconds: (performance.now() - postAgentPreparationStartedAt) / 1e3
42854
42894
  });
42855
- let fileMaterializationFailures = [];
42856
- let fileDownloadsMaterializedForRun = false;
42857
- if (sandboxState.resolvedSandbox && sandboxState.setupBoxSession && fileResourceDownloads.length > 0) {
42858
- const fileMaterializationStartedAt = performance.now();
42859
- let fileMaterializationOutcome = "completed";
42860
- let fileMaterializationCache = "miss";
42861
- try {
42862
- const boxInstanceId = sandboxState.resolvedSandbox.established.instanceId;
42863
- const alreadyMaterialized = await getMaterializedSandboxFileResources3(db, {
42864
- accountId: input.accountId,
42865
- workspaceId: input.workspaceId,
42866
- sandboxGroupId: session.sandboxGroupId,
42867
- expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
42868
- instanceId: boxInstanceId
42869
- });
42870
- const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(
42871
- fileResourceDownloads,
42872
- alreadyMaterialized
42873
- );
42874
- if (downloadsToMaterialize.length === 0) {
42875
- fileMaterializationCache = "hit";
42876
- }
42877
- const runAs = sandboxRunAs6(runSettings);
42878
- if (downloadsToMaterialize.length > 0) {
42879
- const materialized = await runWorkspaceMutationForSandbox(
42880
- sandboxState.resolvedSandbox,
42881
- "fileMaterialization",
42882
- async () => await materializeSandboxFileDownloads3(
42883
- sandboxState.setupBoxSession,
42884
- downloadsToMaterialize,
42885
- {
42886
- onRuntimeEvent: async (event) => {
42887
- await eventing.publish(
42888
- [{ type: event.type, payload: event.payload }],
42889
- true
42890
- );
42891
- },
42892
- ...runAs ? { runAs } : {},
42893
- ...eventing.toolCancellationFenceRef.current ? {
42894
- commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
42895
- eventing.toolCancellationFenceRef.current
42896
- )
42897
- } : {}
42898
- }
42899
- )
42900
- );
42901
- fileMaterializationFailures = materialized.failures;
42902
- fileMaterializationOutcome = sandboxFileMaterializationOutcome(
42903
- materialized.failures
42904
- );
42905
- const failedFileIds = new Set(
42906
- materialized.failures.map((failure2) => failure2.fileId)
42895
+ const workerDeliversFiles = Boolean(
42896
+ sandboxState.resolvedSandbox && sandboxState.setupBoxSession && fileResourceDownloads.length > 0
42897
+ );
42898
+ const eagerOwnedSandboxSetup = createEagerOwnedSandboxSetup(
42899
+ {
42900
+ input,
42901
+ db,
42902
+ observability,
42903
+ runtimeCancellationSignal,
42904
+ sandboxState,
42905
+ eventing: wiredEventing,
42906
+ leases,
42907
+ runWorkspaceMutationForSandbox,
42908
+ attachGitCredentialRenewal,
42909
+ attachRunCredentialRenewal,
42910
+ activeSandboxBackend,
42911
+ groupBoxBackend,
42912
+ turnExecutionPolicy,
42913
+ agent,
42914
+ runSettings,
42915
+ initialRunCredentialMaterial,
42916
+ initialGitCredentials,
42917
+ sandboxEnvironment,
42918
+ fileResourceDownloads
42919
+ },
42920
+ hasEagerOwnedSandboxSetup(sandboxState) && (workerDeliversFiles || fileResourceDownloads.length === 0) ? { fileDownloadsMaterialized: workerDeliversFiles } : void 0
42921
+ );
42922
+ try {
42923
+ let fileMaterializationFailures = [];
42924
+ let fileDownloadsMaterializedForRun = false;
42925
+ if (sandboxState.resolvedSandbox && sandboxState.setupBoxSession && fileResourceDownloads.length > 0) {
42926
+ const fileMaterializationStartedAt = performance.now();
42927
+ let fileMaterializationOutcome = "completed";
42928
+ let fileMaterializationCache = "miss";
42929
+ try {
42930
+ const boxInstanceId = sandboxState.resolvedSandbox.established.instanceId;
42931
+ const alreadyMaterialized = await getMaterializedSandboxFileResources3(db, {
42932
+ accountId: input.accountId,
42933
+ workspaceId: input.workspaceId,
42934
+ sandboxGroupId: session.sandboxGroupId,
42935
+ expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
42936
+ instanceId: boxInstanceId
42937
+ });
42938
+ const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(
42939
+ fileResourceDownloads,
42940
+ alreadyMaterialized
42907
42941
  );
42908
- const succeededFileIds = downloadsToMaterialize.map((download) => download.fileId).filter((fileId) => !failedFileIds.has(fileId));
42909
- if (succeededFileIds.length > 0) {
42910
- await markSandboxFileResourcesMaterialized3(db, {
42911
- accountId: input.accountId,
42912
- workspaceId: input.workspaceId,
42913
- sandboxGroupId: session.sandboxGroupId,
42914
- expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
42915
- instanceId: boxInstanceId,
42916
- fileIds: succeededFileIds
42917
- });
42942
+ if (downloadsToMaterialize.length === 0) {
42943
+ fileMaterializationCache = "hit";
42944
+ }
42945
+ const runAs = sandboxRunAs6(runSettings);
42946
+ if (downloadsToMaterialize.length > 0) {
42947
+ const materialized = await runWorkspaceMutationForSandbox(
42948
+ sandboxState.resolvedSandbox,
42949
+ "fileMaterialization",
42950
+ async () => await materializeSandboxFileDownloads3(
42951
+ sandboxState.setupBoxSession,
42952
+ downloadsToMaterialize,
42953
+ {
42954
+ onRuntimeEvent: async (event) => {
42955
+ await eventing.publish(
42956
+ [{ type: event.type, payload: event.payload }],
42957
+ true
42958
+ );
42959
+ },
42960
+ ...runAs ? { runAs } : {},
42961
+ ...eventing.toolCancellationFenceRef.current ? {
42962
+ commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
42963
+ eventing.toolCancellationFenceRef.current
42964
+ )
42965
+ } : {}
42966
+ }
42967
+ )
42968
+ );
42969
+ fileMaterializationFailures = materialized.failures;
42970
+ fileMaterializationOutcome = sandboxFileMaterializationOutcome(
42971
+ materialized.failures
42972
+ );
42973
+ const failedFileIds = new Set(
42974
+ materialized.failures.map((failure2) => failure2.fileId)
42975
+ );
42976
+ const succeededFileIds = downloadsToMaterialize.map((download) => download.fileId).filter((fileId) => !failedFileIds.has(fileId));
42977
+ if (succeededFileIds.length > 0) {
42978
+ await markSandboxFileResourcesMaterialized3(db, {
42979
+ accountId: input.accountId,
42980
+ workspaceId: input.workspaceId,
42981
+ sandboxGroupId: session.sandboxGroupId,
42982
+ expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
42983
+ instanceId: boxInstanceId,
42984
+ fileIds: succeededFileIds
42985
+ });
42986
+ }
42918
42987
  }
42988
+ fileDownloadsMaterializedForRun = true;
42989
+ } catch (error51) {
42990
+ fileMaterializationOutcome = "failed";
42991
+ throw error51;
42992
+ } finally {
42993
+ recordTurnStartupPhase(observability, {
42994
+ phase: "file_materialization",
42995
+ provider: turnExecutionPolicy.providerId,
42996
+ backend: activeSandboxBackend ?? groupBoxBackend,
42997
+ outcome: fileMaterializationOutcome,
42998
+ durationSeconds: (performance.now() - fileMaterializationStartedAt) / 1e3,
42999
+ count: fileResourceDownloads.length,
43000
+ cache: fileMaterializationCache
43001
+ });
42919
43002
  }
42920
- fileDownloadsMaterializedForRun = true;
42921
- } catch (error51) {
42922
- fileMaterializationOutcome = "failed";
42923
- throw error51;
42924
- } finally {
43003
+ } else {
42925
43004
  recordTurnStartupPhase(observability, {
42926
43005
  phase: "file_materialization",
42927
43006
  provider: turnExecutionPolicy.providerId,
42928
43007
  backend: activeSandboxBackend ?? groupBoxBackend,
42929
- outcome: fileMaterializationOutcome,
42930
- durationSeconds: (performance.now() - fileMaterializationStartedAt) / 1e3,
42931
- count: fileResourceDownloads.length,
42932
- cache: fileMaterializationCache
43008
+ outcome: "completed",
43009
+ durationSeconds: 0,
43010
+ count: 0
42933
43011
  });
42934
43012
  }
42935
- } else {
42936
- recordTurnStartupPhase(observability, {
42937
- phase: "file_materialization",
42938
- provider: turnExecutionPolicy.providerId,
42939
- backend: activeSandboxBackend ?? groupBoxBackend,
42940
- outcome: "completed",
42941
- durationSeconds: 0,
42942
- count: 0
42943
- });
42944
- }
42945
- const requiredVideoFileIds = new Set(
42946
- requiredGeneratedVideoFiles.map((file2) => file2.fileId)
42947
- );
42948
- const failedRequiredVideo = fileMaterializationFailures.find(
42949
- (failure2) => requiredVideoFileIds.has(failure2.fileId)
42950
- );
42951
- if (failedRequiredVideo) {
42952
- observability.warn("Generated video sandbox materialization deferred", {
42953
- errorClass: "SandboxFileDownloadFailure",
42954
- errorCode: "generated_video_materialization_deferred",
42955
- origin: "worker"
43013
+ const requiredVideoFileIds = new Set(
43014
+ requiredGeneratedVideoFiles.map((file2) => file2.fileId)
43015
+ );
43016
+ const failedRequiredVideo = fileMaterializationFailures.find(
43017
+ (failure2) => requiredVideoFileIds.has(failure2.fileId)
43018
+ );
43019
+ if (failedRequiredVideo) {
43020
+ observability.warn("Generated video sandbox materialization deferred", {
43021
+ errorClass: "SandboxFileDownloadFailure",
43022
+ errorCode: "generated_video_materialization_deferred",
43023
+ origin: "worker"
43024
+ });
43025
+ }
43026
+ const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(
43027
+ fileMaterializationFailures
43028
+ );
43029
+ return await runTurnStreamAttempt({
43030
+ input,
43031
+ settings: capabilitySettings,
43032
+ db,
43033
+ bus,
43034
+ runtime,
43035
+ objectStorage,
43036
+ observability,
43037
+ entitlements,
43038
+ startVideoGenerationWorkflow,
43039
+ startSessionTitleWorkflow,
43040
+ sessionTitleExpectedCurrent: { title: session.title, source: session.titleSource },
43041
+ cancellationSignal,
43042
+ runtimeCancellationSignal,
43043
+ activityContext,
43044
+ dispatchId,
43045
+ control,
43046
+ attempt,
43047
+ billingState,
43048
+ sandboxState,
43049
+ eventing: wiredEventing,
43050
+ providerTurn,
43051
+ leases,
43052
+ historySink,
43053
+ checkpointBeforeProviderDispatch,
43054
+ media,
43055
+ toolResultSpill,
43056
+ claimedResult,
43057
+ flushRuntimeBatcher,
43058
+ finalizeTurnOpStreamOps,
43059
+ runWorkspaceMutationForSandbox,
43060
+ throwIfWorkerShuttingDown,
43061
+ throwIfTurnCancelled,
43062
+ setLastInputTokensFenced,
43063
+ attachGitCredentialRenewal,
43064
+ attachCodemodeTokenRenewal,
43065
+ attachRunCredentialRenewal,
43066
+ withProviderRequestContext,
43067
+ withSessionTitleProviderRequestContext,
43068
+ publishCompactionLiveEvents,
43069
+ publishCompactionOutcomeEvents,
43070
+ recordCompanyBrainContributionReceiptOnce,
43071
+ modelCheckpointMemoryCollector,
43072
+ claimedModelUsageSourceKeys,
43073
+ emittedModelUsageSourceKeys,
43074
+ modelUsageDispatchId,
43075
+ workerPreparationStartedAt,
43076
+ fileDownloadsMaterializedForRun,
43077
+ eagerOwnedSandboxSetup,
43078
+ unavailableSandboxFilesNote,
43079
+ runCredentialsNote,
43080
+ mcpAvailabilityNote,
43081
+ knowledgeSourcePreparationNote,
43082
+ fileAuthoritySubjectId,
43083
+ activeSandboxBackend,
43084
+ groupBoxBackend,
43085
+ turnExecutionPolicy,
43086
+ turn,
43087
+ trigger,
43088
+ humanInputResume,
43089
+ attachPendingUpdatesAfterOpenSuffix,
43090
+ agent,
43091
+ resolvedModel,
43092
+ providerApi,
43093
+ runSettings,
43094
+ turnTools,
43095
+ generateSessionTitleInParallel,
43096
+ sessionTitlePrompt: session.initialMessage.trim() ? session.initialMessage : turn.prompt,
43097
+ compactSummarizer,
43098
+ settleDeferredSteerAfterCompaction,
43099
+ compactionModelHistoryProjector,
43100
+ generatedImageHistoryProjector,
43101
+ modelHistoryProjector,
43102
+ compactionModeOptions,
43103
+ initialRunCredentialMaterial,
43104
+ initialGitCredentials,
43105
+ sandboxEnvironment,
43106
+ sandboxCodemodeToken,
43107
+ sandboxCodemodeTokenExpiresAt,
43108
+ fileResourceDownloads,
43109
+ runCredentialResolver,
43110
+ videoGenerationAcceptancesByCallId
42956
43111
  });
43112
+ } finally {
43113
+ await eagerOwnedSandboxSetup.settled();
42957
43114
  }
42958
- const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(
42959
- fileMaterializationFailures
42960
- );
42961
- return await runTurnStreamAttempt({
42962
- input,
42963
- settings: capabilitySettings,
42964
- db,
42965
- bus,
42966
- runtime,
42967
- objectStorage,
42968
- observability,
42969
- entitlements,
42970
- startVideoGenerationWorkflow,
42971
- startSessionTitleWorkflow,
42972
- sessionTitleExpectedCurrent: { title: session.title, source: session.titleSource },
42973
- cancellationSignal,
42974
- runtimeCancellationSignal,
42975
- activityContext,
42976
- dispatchId,
42977
- control,
42978
- attempt,
42979
- billingState,
42980
- sandboxState,
42981
- eventing: wiredEventing,
42982
- providerTurn,
42983
- leases,
42984
- historySink,
42985
- checkpointBeforeProviderDispatch,
42986
- media,
42987
- toolResultSpill,
42988
- claimedResult,
42989
- flushRuntimeBatcher,
42990
- finalizeTurnOpStreamOps,
42991
- runWorkspaceMutationForSandbox,
42992
- throwIfWorkerShuttingDown,
42993
- throwIfTurnCancelled,
42994
- setLastInputTokensFenced,
42995
- attachGitCredentialRenewal,
42996
- attachCodemodeTokenRenewal,
42997
- attachRunCredentialRenewal,
42998
- withProviderRequestContext,
42999
- withSessionTitleProviderRequestContext,
43000
- publishCompactionLiveEvents,
43001
- publishCompactionOutcomeEvents,
43002
- recordCompanyBrainContributionReceiptOnce,
43003
- modelCheckpointMemoryCollector,
43004
- claimedModelUsageSourceKeys,
43005
- emittedModelUsageSourceKeys,
43006
- modelUsageDispatchId,
43007
- workerPreparationStartedAt,
43008
- fileDownloadsMaterializedForRun,
43009
- unavailableSandboxFilesNote,
43010
- runCredentialsNote,
43011
- mcpAvailabilityNote,
43012
- knowledgeSourcePreparationNote,
43013
- fileAuthoritySubjectId,
43014
- activeSandboxBackend,
43015
- groupBoxBackend,
43016
- turnExecutionPolicy,
43017
- turn,
43018
- trigger,
43019
- humanInputResume,
43020
- attachPendingUpdatesAfterOpenSuffix,
43021
- agent,
43022
- resolvedModel,
43023
- providerApi,
43024
- runSettings,
43025
- turnTools,
43026
- generateSessionTitleInParallel,
43027
- sessionTitlePrompt: session.initialMessage.trim() ? session.initialMessage : turn.prompt,
43028
- compactSummarizer,
43029
- settleDeferredSteerAfterCompaction,
43030
- compactionModelHistoryProjector,
43031
- generatedImageHistoryProjector,
43032
- modelHistoryProjector,
43033
- compactionModeOptions,
43034
- initialRunCredentialMaterial,
43035
- initialGitCredentials,
43036
- sandboxEnvironment,
43037
- sandboxCodemodeToken,
43038
- sandboxCodemodeTokenExpiresAt,
43039
- fileResourceDownloads,
43040
- runCredentialResolver,
43041
- videoGenerationAcceptancesByCallId
43042
- });
43043
43115
  }
43044
43116
  );
43045
43117
  } catch (error51) {
@@ -44259,4 +44331,4 @@ export {
44259
44331
  createTurnActivities,
44260
44332
  createTurnActivitiesFromServices
44261
44333
  };
44262
- //# sourceMappingURL=activities-turn-G33RWTX2.js.map
44334
+ //# sourceMappingURL=activities-turn-B73PNSEA.js.map