@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.
@@ -79,6 +79,7 @@ import {
79
79
  } from "../../observability-metrics";
80
80
  import { summarizeCompanyBrainContributions } from "../../model-context-contributions";
81
81
  import { ToolResultSpill } from "./tool-result-spill";
82
+ import { createEagerOwnedSandboxSetup, hasEagerOwnedSandboxSetup } from "./owned-sandbox-setup";
82
83
  import { createTurnCredentialLeases } from "./credential-leases";
83
84
  import { createTurnMediaArtifacts } from "./media-artifacts";
84
85
  import { createTurnHistorySink } from "./history-sink";
@@ -1968,212 +1969,255 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
1968
1969
  outcome: "completed",
1969
1970
  durationSeconds: (performance.now() - postAgentPreparationStartedAt) / 1_000,
1970
1971
  });
1971
- let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];
1972
- let fileDownloadsMaterializedForRun = false;
1973
- if (
1972
+ // Platform setup (rig setup, credential hooks, repository clones)
1973
+ // needs nothing from file delivery or the model input, so it starts
1974
+ // now and the first model stream joins it. When the runtime delivers
1975
+ // files itself, setup must wait for the prepared input it annotates.
1976
+ const workerDeliversFiles = Boolean(
1974
1977
  sandboxState.resolvedSandbox &&
1975
1978
  sandboxState.setupBoxSession &&
1976
- fileResourceDownloads.length > 0
1977
- ) {
1978
- const fileMaterializationStartedAt = performance.now();
1979
- let fileMaterializationOutcome: "completed" | "failed" = "completed";
1980
- let fileMaterializationCache: "hit" | "miss" = "miss";
1981
- try {
1982
- const boxInstanceId = sandboxState.resolvedSandbox.established.instanceId;
1983
- // A successful transfer is durable for this exact filesystem instance.
1984
- // Do not turn later model startup into an integrity scan. If an owner or
1985
- // agent removes the file, it can be restored explicitly through the
1986
- // existing Files MCP using the durable file id carried in model history.
1987
- const alreadyMaterialized = await getMaterializedSandboxFileResources(db, {
1988
- accountId: input.accountId,
1989
- workspaceId: input.workspaceId,
1990
- sandboxGroupId: session.sandboxGroupId,
1991
- expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
1992
- instanceId: boxInstanceId,
1993
- });
1994
- const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(
1995
- fileResourceDownloads,
1996
- alreadyMaterialized,
1997
- );
1998
- if (downloadsToMaterialize.length === 0) {
1999
- fileMaterializationCache = "hit";
2000
- }
2001
- const runAs = sandboxRunAs(runSettings);
2002
- if (downloadsToMaterialize.length > 0) {
2003
- const materialized = await runWorkspaceMutationForSandbox(
2004
- sandboxState.resolvedSandbox,
2005
- "fileMaterialization",
2006
- async () =>
2007
- await materializeSandboxFileDownloads(
2008
- sandboxState.setupBoxSession as CodemodeTokenWriterSession,
2009
- downloadsToMaterialize,
2010
- {
2011
- onRuntimeEvent: async (event) => {
2012
- await eventing.publish!(
2013
- [{ type: event.type, payload: event.payload }],
2014
- true,
2015
- );
2016
- },
2017
- ...(runAs ? { runAs } : {}),
2018
- ...(eventing.toolCancellationFenceRef.current
2019
- ? {
2020
- commandRunner:
2021
- eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
2022
- eventing.toolCancellationFenceRef.current,
2023
- ),
2024
- }
2025
- : {}),
2026
- },
2027
- ),
2028
- );
2029
- fileMaterializationFailures = materialized.failures;
2030
- fileMaterializationOutcome = sandboxFileMaterializationOutcome(
2031
- materialized.failures,
2032
- );
2033
- const failedFileIds = new Set(
2034
- materialized.failures.map((failure) => failure.fileId),
1979
+ fileResourceDownloads.length > 0,
1980
+ );
1981
+ const eagerOwnedSandboxSetup = createEagerOwnedSandboxSetup(
1982
+ {
1983
+ input,
1984
+ db,
1985
+ observability,
1986
+ runtimeCancellationSignal,
1987
+ sandboxState,
1988
+ eventing: wiredEventing,
1989
+ leases,
1990
+ runWorkspaceMutationForSandbox,
1991
+ attachGitCredentialRenewal,
1992
+ attachRunCredentialRenewal,
1993
+ activeSandboxBackend,
1994
+ groupBoxBackend,
1995
+ turnExecutionPolicy,
1996
+ agent,
1997
+ runSettings,
1998
+ initialRunCredentialMaterial,
1999
+ initialGitCredentials,
2000
+ sandboxEnvironment,
2001
+ fileResourceDownloads,
2002
+ },
2003
+ hasEagerOwnedSandboxSetup(sandboxState) &&
2004
+ (workerDeliversFiles || fileResourceDownloads.length === 0)
2005
+ ? { fileDownloadsMaterialized: workerDeliversFiles }
2006
+ : undefined,
2007
+ );
2008
+ try {
2009
+ let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];
2010
+ let fileDownloadsMaterializedForRun = false;
2011
+ if (
2012
+ sandboxState.resolvedSandbox &&
2013
+ sandboxState.setupBoxSession &&
2014
+ fileResourceDownloads.length > 0
2015
+ ) {
2016
+ const fileMaterializationStartedAt = performance.now();
2017
+ let fileMaterializationOutcome: "completed" | "failed" = "completed";
2018
+ let fileMaterializationCache: "hit" | "miss" = "miss";
2019
+ try {
2020
+ const boxInstanceId = sandboxState.resolvedSandbox.established.instanceId;
2021
+ // A successful transfer is durable for this exact filesystem instance.
2022
+ // Do not turn later model startup into an integrity scan. If an owner or
2023
+ // agent removes the file, it can be restored explicitly through the
2024
+ // existing Files MCP using the durable file id carried in model history.
2025
+ const alreadyMaterialized = await getMaterializedSandboxFileResources(db, {
2026
+ accountId: input.accountId,
2027
+ workspaceId: input.workspaceId,
2028
+ sandboxGroupId: session.sandboxGroupId,
2029
+ expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
2030
+ instanceId: boxInstanceId,
2031
+ });
2032
+ const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(
2033
+ fileResourceDownloads,
2034
+ alreadyMaterialized,
2035
2035
  );
2036
- const succeededFileIds = downloadsToMaterialize
2037
- .map((download) => download.fileId)
2038
- .filter((fileId) => !failedFileIds.has(fileId));
2039
- if (succeededFileIds.length > 0) {
2040
- await markSandboxFileResourcesMaterialized(db, {
2041
- accountId: input.accountId,
2042
- workspaceId: input.workspaceId,
2043
- sandboxGroupId: session.sandboxGroupId,
2044
- expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
2045
- instanceId: boxInstanceId,
2046
- fileIds: succeededFileIds,
2047
- });
2036
+ if (downloadsToMaterialize.length === 0) {
2037
+ fileMaterializationCache = "hit";
2048
2038
  }
2039
+ const runAs = sandboxRunAs(runSettings);
2040
+ if (downloadsToMaterialize.length > 0) {
2041
+ const materialized = await runWorkspaceMutationForSandbox(
2042
+ sandboxState.resolvedSandbox,
2043
+ "fileMaterialization",
2044
+ async () =>
2045
+ await materializeSandboxFileDownloads(
2046
+ sandboxState.setupBoxSession as CodemodeTokenWriterSession,
2047
+ downloadsToMaterialize,
2048
+ {
2049
+ onRuntimeEvent: async (event) => {
2050
+ await eventing.publish!(
2051
+ [{ type: event.type, payload: event.payload }],
2052
+ true,
2053
+ );
2054
+ },
2055
+ ...(runAs ? { runAs } : {}),
2056
+ ...(eventing.toolCancellationFenceRef.current
2057
+ ? {
2058
+ commandRunner:
2059
+ eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
2060
+ eventing.toolCancellationFenceRef.current,
2061
+ ),
2062
+ }
2063
+ : {}),
2064
+ },
2065
+ ),
2066
+ );
2067
+ fileMaterializationFailures = materialized.failures;
2068
+ fileMaterializationOutcome = sandboxFileMaterializationOutcome(
2069
+ materialized.failures,
2070
+ );
2071
+ const failedFileIds = new Set(
2072
+ materialized.failures.map((failure) => failure.fileId),
2073
+ );
2074
+ const succeededFileIds = downloadsToMaterialize
2075
+ .map((download) => download.fileId)
2076
+ .filter((fileId) => !failedFileIds.has(fileId));
2077
+ if (succeededFileIds.length > 0) {
2078
+ await markSandboxFileResourcesMaterialized(db, {
2079
+ accountId: input.accountId,
2080
+ workspaceId: input.workspaceId,
2081
+ sandboxGroupId: session.sandboxGroupId,
2082
+ expectedEpoch: sandboxState.resolvedSandbox.leaseEpoch,
2083
+ instanceId: boxInstanceId,
2084
+ fileIds: succeededFileIds,
2085
+ });
2086
+ }
2087
+ }
2088
+ fileDownloadsMaterializedForRun = true;
2089
+ } catch (error) {
2090
+ fileMaterializationOutcome = "failed";
2091
+ throw error;
2092
+ } finally {
2093
+ recordTurnStartupPhase(observability, {
2094
+ phase: "file_materialization",
2095
+ provider: turnExecutionPolicy.providerId,
2096
+ backend: activeSandboxBackend ?? groupBoxBackend,
2097
+ outcome: fileMaterializationOutcome,
2098
+ durationSeconds: (performance.now() - fileMaterializationStartedAt) / 1_000,
2099
+ count: fileResourceDownloads.length,
2100
+ cache: fileMaterializationCache,
2101
+ });
2049
2102
  }
2050
- fileDownloadsMaterializedForRun = true;
2051
- } catch (error) {
2052
- fileMaterializationOutcome = "failed";
2053
- throw error;
2054
- } finally {
2103
+ } else {
2055
2104
  recordTurnStartupPhase(observability, {
2056
2105
  phase: "file_materialization",
2057
2106
  provider: turnExecutionPolicy.providerId,
2058
2107
  backend: activeSandboxBackend ?? groupBoxBackend,
2059
- outcome: fileMaterializationOutcome,
2060
- durationSeconds: (performance.now() - fileMaterializationStartedAt) / 1_000,
2061
- count: fileResourceDownloads.length,
2062
- cache: fileMaterializationCache,
2108
+ outcome: "completed",
2109
+ durationSeconds: 0,
2110
+ count: 0,
2063
2111
  });
2064
2112
  }
2065
- } else {
2066
- recordTurnStartupPhase(observability, {
2067
- phase: "file_materialization",
2068
- provider: turnExecutionPolicy.providerId,
2069
- backend: activeSandboxBackend ?? groupBoxBackend,
2070
- outcome: "completed",
2071
- durationSeconds: 0,
2072
- count: 0,
2073
- });
2074
- }
2075
- const requiredVideoFileIds = new Set(
2076
- requiredGeneratedVideoFiles.map((file) => file.fileId),
2077
- );
2078
- const failedRequiredVideo = fileMaterializationFailures.find((failure) =>
2079
- requiredVideoFileIds.has(failure.fileId),
2080
- );
2081
- if (failedRequiredVideo) {
2082
- // Retention is already durable. A sandbox copy miss must not fail the
2083
- // turn or replay generation; the File remains retrievable via Files MCP.
2084
- observability.warn("Generated video sandbox materialization deferred", {
2085
- errorClass: "SandboxFileDownloadFailure",
2086
- errorCode: "generated_video_materialization_deferred",
2087
- origin: "worker",
2113
+ const requiredVideoFileIds = new Set(
2114
+ requiredGeneratedVideoFiles.map((file) => file.fileId),
2115
+ );
2116
+ const failedRequiredVideo = fileMaterializationFailures.find((failure) =>
2117
+ requiredVideoFileIds.has(failure.fileId),
2118
+ );
2119
+ if (failedRequiredVideo) {
2120
+ // Retention is already durable. A sandbox copy miss must not fail the
2121
+ // turn or replay generation; the File remains retrievable via Files MCP.
2122
+ observability.warn("Generated video sandbox materialization deferred", {
2123
+ errorClass: "SandboxFileDownloadFailure",
2124
+ errorCode: "generated_video_materialization_deferred",
2125
+ origin: "worker",
2126
+ });
2127
+ }
2128
+ const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(
2129
+ fileMaterializationFailures,
2130
+ );
2131
+ return await runTurnStreamAttempt({
2132
+ input,
2133
+ settings: capabilitySettings,
2134
+ db,
2135
+ bus,
2136
+ runtime,
2137
+ objectStorage,
2138
+ observability,
2139
+ entitlements,
2140
+ startVideoGenerationWorkflow,
2141
+ startSessionTitleWorkflow,
2142
+ sessionTitleExpectedCurrent: { title: session.title, source: session.titleSource },
2143
+ cancellationSignal,
2144
+ runtimeCancellationSignal,
2145
+ activityContext,
2146
+ dispatchId,
2147
+ control,
2148
+ attempt,
2149
+ billingState,
2150
+ sandboxState,
2151
+ eventing: wiredEventing,
2152
+ providerTurn,
2153
+ leases,
2154
+ historySink,
2155
+ checkpointBeforeProviderDispatch,
2156
+ media,
2157
+ toolResultSpill,
2158
+ claimedResult,
2159
+ flushRuntimeBatcher,
2160
+ finalizeTurnOpStreamOps,
2161
+ runWorkspaceMutationForSandbox,
2162
+ throwIfWorkerShuttingDown,
2163
+ throwIfTurnCancelled,
2164
+ setLastInputTokensFenced,
2165
+ attachGitCredentialRenewal,
2166
+ attachCodemodeTokenRenewal,
2167
+ attachRunCredentialRenewal,
2168
+ withProviderRequestContext,
2169
+ withSessionTitleProviderRequestContext,
2170
+ publishCompactionLiveEvents,
2171
+ publishCompactionOutcomeEvents,
2172
+ recordCompanyBrainContributionReceiptOnce,
2173
+ modelCheckpointMemoryCollector,
2174
+ claimedModelUsageSourceKeys,
2175
+ emittedModelUsageSourceKeys,
2176
+ modelUsageDispatchId,
2177
+ workerPreparationStartedAt,
2178
+ fileDownloadsMaterializedForRun,
2179
+ eagerOwnedSandboxSetup,
2180
+ unavailableSandboxFilesNote,
2181
+ runCredentialsNote,
2182
+ mcpAvailabilityNote,
2183
+ knowledgeSourcePreparationNote,
2184
+ fileAuthoritySubjectId,
2185
+ activeSandboxBackend,
2186
+ groupBoxBackend,
2187
+ turnExecutionPolicy,
2188
+ turn,
2189
+ trigger,
2190
+ humanInputResume,
2191
+ attachPendingUpdatesAfterOpenSuffix,
2192
+ agent,
2193
+ resolvedModel,
2194
+ providerApi,
2195
+ runSettings,
2196
+ turnTools,
2197
+ generateSessionTitleInParallel,
2198
+ sessionTitlePrompt: session.initialMessage.trim()
2199
+ ? session.initialMessage
2200
+ : turn.prompt,
2201
+ compactSummarizer,
2202
+ settleDeferredSteerAfterCompaction,
2203
+ compactionModelHistoryProjector,
2204
+ generatedImageHistoryProjector,
2205
+ modelHistoryProjector,
2206
+ compactionModeOptions,
2207
+ initialRunCredentialMaterial,
2208
+ initialGitCredentials,
2209
+ sandboxEnvironment,
2210
+ sandboxCodemodeToken,
2211
+ sandboxCodemodeTokenExpiresAt,
2212
+ fileResourceDownloads,
2213
+ runCredentialResolver,
2214
+ videoGenerationAcceptancesByCallId,
2088
2215
  });
2216
+ } finally {
2217
+ // Never leave a started setup's workspace admission running past
2218
+ // this attempt, including exits before the first model stream.
2219
+ await eagerOwnedSandboxSetup.settled();
2089
2220
  }
2090
- const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(
2091
- fileMaterializationFailures,
2092
- );
2093
- return await runTurnStreamAttempt({
2094
- input,
2095
- settings: capabilitySettings,
2096
- db,
2097
- bus,
2098
- runtime,
2099
- objectStorage,
2100
- observability,
2101
- entitlements,
2102
- startVideoGenerationWorkflow,
2103
- startSessionTitleWorkflow,
2104
- sessionTitleExpectedCurrent: { title: session.title, source: session.titleSource },
2105
- cancellationSignal,
2106
- runtimeCancellationSignal,
2107
- activityContext,
2108
- dispatchId,
2109
- control,
2110
- attempt,
2111
- billingState,
2112
- sandboxState,
2113
- eventing: wiredEventing,
2114
- providerTurn,
2115
- leases,
2116
- historySink,
2117
- checkpointBeforeProviderDispatch,
2118
- media,
2119
- toolResultSpill,
2120
- claimedResult,
2121
- flushRuntimeBatcher,
2122
- finalizeTurnOpStreamOps,
2123
- runWorkspaceMutationForSandbox,
2124
- throwIfWorkerShuttingDown,
2125
- throwIfTurnCancelled,
2126
- setLastInputTokensFenced,
2127
- attachGitCredentialRenewal,
2128
- attachCodemodeTokenRenewal,
2129
- attachRunCredentialRenewal,
2130
- withProviderRequestContext,
2131
- withSessionTitleProviderRequestContext,
2132
- publishCompactionLiveEvents,
2133
- publishCompactionOutcomeEvents,
2134
- recordCompanyBrainContributionReceiptOnce,
2135
- modelCheckpointMemoryCollector,
2136
- claimedModelUsageSourceKeys,
2137
- emittedModelUsageSourceKeys,
2138
- modelUsageDispatchId,
2139
- workerPreparationStartedAt,
2140
- fileDownloadsMaterializedForRun,
2141
- unavailableSandboxFilesNote,
2142
- runCredentialsNote,
2143
- mcpAvailabilityNote,
2144
- knowledgeSourcePreparationNote,
2145
- fileAuthoritySubjectId,
2146
- activeSandboxBackend,
2147
- groupBoxBackend,
2148
- turnExecutionPolicy,
2149
- turn,
2150
- trigger,
2151
- humanInputResume,
2152
- attachPendingUpdatesAfterOpenSuffix,
2153
- agent,
2154
- resolvedModel,
2155
- providerApi,
2156
- runSettings,
2157
- turnTools,
2158
- generateSessionTitleInParallel,
2159
- sessionTitlePrompt: session.initialMessage.trim()
2160
- ? session.initialMessage
2161
- : turn.prompt,
2162
- compactSummarizer,
2163
- settleDeferredSteerAfterCompaction,
2164
- compactionModelHistoryProjector,
2165
- generatedImageHistoryProjector,
2166
- modelHistoryProjector,
2167
- compactionModeOptions,
2168
- initialRunCredentialMaterial,
2169
- initialGitCredentials,
2170
- sandboxEnvironment,
2171
- sandboxCodemodeToken,
2172
- sandboxCodemodeTokenExpiresAt,
2173
- fileResourceDownloads,
2174
- runCredentialResolver,
2175
- videoGenerationAcceptancesByCallId,
2176
- });
2177
2221
  },
2178
2222
  );
2179
2223
  } catch (error) {
@@ -49,8 +49,6 @@ import {
49
49
  type AnthropicRequestSizeError,
50
50
  ANTHROPIC_REQUEST_MAX_BYTES,
51
51
  compactionProviderRejection,
52
- withRunCredentialsSession,
53
- runOwnedSandboxSetup,
54
52
  modelResponseHasVisibleText,
55
53
  ModelStepHandover,
56
54
  isPreemptedModelResponse,
@@ -94,7 +92,6 @@ import {
94
92
  recordModelStepPhase,
95
93
  recordTurnStartupPhase,
96
94
  recordTurnWorkerPreparationTotal,
97
- recordSandboxSharedPreparation,
98
95
  StreamTimingMetrics,
99
96
  turnLifecycleMetricsFor,
100
97
  } from "../../observability-metrics";
@@ -195,7 +192,7 @@ import {
195
192
  latestDurableTurnMessageText,
196
193
  } from "./input-wait-reply";
197
194
  import { waitForTurnOperation } from "./sandbox-provision";
198
- import { createSharedRigSetupCoordinator } from "./sandbox-shared-preparation";
195
+ import { createEagerOwnedSandboxSetup, type EagerOwnedSandboxSetup } from "./owned-sandbox-setup";
199
196
  import { finalReplyNudge, needsFinalReply } from "./final-reply";
200
197
 
201
198
  import type { CompactionSummarizer } from "../context-compaction";
@@ -287,6 +284,8 @@ export type TurnStreamAttemptDeps = {
287
284
  modelUsageDispatchId: string;
288
285
  workerPreparationStartedAt: number;
289
286
  fileDownloadsMaterializedForRun: boolean;
287
+ /** Eager owned-box platform setup, possibly already started by the worker. */
288
+ eagerOwnedSandboxSetup?: EagerOwnedSandboxSetup;
290
289
  unavailableSandboxFilesNote: string | undefined;
291
290
  runCredentialsNote: string | undefined;
292
291
  mcpAvailabilityNote: string | undefined;
@@ -374,11 +373,9 @@ export async function runTurnStreamAttempt(
374
373
  claimedResult,
375
374
  flushRuntimeBatcher,
376
375
  finalizeTurnOpStreamOps,
377
- runWorkspaceMutationForSandbox,
378
376
  throwIfWorkerShuttingDown,
379
377
  throwIfTurnCancelled,
380
378
  setLastInputTokensFenced,
381
- attachGitCredentialRenewal,
382
379
  attachCodemodeTokenRenewal,
383
380
  attachRunCredentialRenewal,
384
381
  withProviderRequestContext,
@@ -418,11 +415,9 @@ export async function runTurnStreamAttempt(
418
415
  modelHistoryProjector,
419
416
  compactionModeOptions,
420
417
  initialRunCredentialMaterial,
421
- initialGitCredentials,
422
418
  sandboxEnvironment,
423
419
  sandboxCodemodeToken,
424
420
  sandboxCodemodeTokenExpiresAt,
425
- fileResourceDownloads,
426
421
  runCredentialResolver,
427
422
  videoGenerationAcceptancesByCallId,
428
423
  } = deps;
@@ -911,98 +906,19 @@ export async function runTurnStreamAttempt(
911
906
  });
912
907
  };
913
908
  const ownedEstablished = ownedTurnSandboxForAgent(sandboxState);
909
+ const eagerOwnedSandboxSetup =
910
+ deps.eagerOwnedSandboxSetup ?? createEagerOwnedSandboxSetup(deps);
914
911
  const runStreamOnce = async (): ReturnType<OpenGeniRuntime["runStream"]> => {
915
- const eagerResolvedSandbox = sandboxState.resolvedSandbox;
916
912
  // Eager owned sessions must settle the exact platform-setup provider
917
913
  // promise before the long model stream starts; otherwise one admission
918
914
  // would remain in flight for the entire turn and suppress every
919
915
  // heartbeat capture. Lazy setup already runs under the same wrapper in
920
- // its first-operation provisioner above.
921
- if (eagerResolvedSandbox && !sandboxState.lazyOwnedSandbox && ownedEstablished) {
922
- const ownedSandboxSetupStartedAt = performance.now();
923
- let ownedSandboxSetupOutcome: "completed" | "failed" = "completed";
924
- try {
925
- const eagerSetupSession = sandboxState.setupBoxSession ?? ownedEstablished.session;
926
- // `deferredSetup: true` below tells the runtime that the worker owns
927
- // platform setup, so the runtime intentionally skips its credential
928
- // session callback. Materialize host-managed run credentials here
929
- // before any setup command (including provider login hooks), then
930
- // decorate setup commands so they source the active generation.
931
- await attachRunCredentialRenewal(
932
- eagerSetupSession as RunCredentialCommandSession,
933
- initialRunCredentialMaterial,
934
- eagerResolvedSandbox,
935
- );
936
- const eagerCredentialSetupSession = initialRunCredentialMaterial
937
- ? withRunCredentialsSession(eagerSetupSession as object, input.sessionId)
938
- : eagerSetupSession;
939
- await runWorkspaceMutationForSandbox(
940
- eagerResolvedSandbox,
941
- "eagerOwnedSandboxSetup",
942
- async () =>
943
- await runOwnedSandboxSetup(
944
- agent,
945
- ownedEstablished.session as never,
946
- eagerCredentialSetupSession as never,
947
- {
948
- settings: runSettings,
949
- environment: sandboxEnvironment,
950
- preparedInput: runInput!,
951
- ...(fileDownloadsMaterializedForRun ? { fileDownloadsMaterialized: true } : {}),
952
- onRuntimeEvent: async (event) => {
953
- await leases.renewServing("runtime_event");
954
- if (leases.servingLost()) {
955
- throw new Error("Provider credential lease expired during sandbox setup");
956
- }
957
- await eventing.publish!([{ type: event.type, payload: event.payload }], true);
958
- },
959
- ...(eventing.toolCancellationFenceRef.current
960
- ? {
961
- commandRunner:
962
- eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
963
- eventing.toolCancellationFenceRef.current,
964
- ),
965
- }
966
- : {}),
967
- ...(sandboxState.sandboxGroupId && sandboxState.sandboxHolderId
968
- ? {
969
- coordinateSharedRigSetup: createSharedRigSetupCoordinator({
970
- db,
971
- accountId: input.accountId,
972
- workspaceId: input.workspaceId,
973
- sandboxGroupId: sandboxState.sandboxGroupId,
974
- attemptId: input.attemptId,
975
- holderId: sandboxState.sandboxHolderId,
976
- sandbox: eagerResolvedSandbox,
977
- ...(runtimeCancellationSignal
978
- ? { signal: runtimeCancellationSignal }
979
- : {}),
980
- observe: (measurement) =>
981
- recordSandboxSharedPreparation(observability, measurement),
982
- }),
983
- }
984
- : {}),
985
- },
986
- ),
987
- );
988
- await attachGitCredentialRenewal(
989
- eagerSetupSession as GitCredentialTokenWriterSession,
990
- initialGitCredentials,
991
- );
992
- } catch (error) {
993
- ownedSandboxSetupOutcome = "failed";
994
- throw error;
995
- } finally {
996
- recordTurnStartupPhase(observability, {
997
- phase: "owned_sandbox_setup",
998
- provider: turnExecutionPolicy.providerId,
999
- backend: activeSandboxBackend ?? groupBoxBackend,
1000
- outcome: ownedSandboxSetupOutcome,
1001
- durationSeconds: (performance.now() - ownedSandboxSetupStartedAt) / 1_000,
1002
- count: fileResourceDownloads.length,
1003
- });
1004
- }
1005
- }
916
+ // its first-operation provisioner above. The first stream may join a
917
+ // setup the worker started alongside file delivery and input preparation.
918
+ await eagerOwnedSandboxSetup.beforeModelStream({
919
+ preparedInput: runInput!,
920
+ fileDownloadsMaterialized: fileDownloadsMaterializedForRun,
921
+ });
1006
922
  // Conservative request boundary: once control enters runStream, the
1007
923
  // provider may have accepted work even if no response/event follows.
1008
924
  // Escaped MCP setup timeouts are automatically recoverable only