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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +66 -0
  42. package/dist/activities/image-generation-references.d.ts +2 -0
  43. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  44. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  45. package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
  46. package/dist/activities/knowledge-source-sync.d.ts +33 -1
  47. package/dist/activities/mcp-credentials.d.ts +9 -3
  48. package/dist/activities/open-suffix-resume.d.ts +77 -0
  49. package/dist/activities/packs.d.ts +3 -11
  50. package/dist/activities/parent-wake.d.ts +19 -0
  51. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  52. package/dist/activities/retained-screenshots.d.ts +1 -1
  53. package/dist/activities/rig-verification.d.ts +1 -1
  54. package/dist/activities/run-input.d.ts +16 -7
  55. package/dist/activities/sandbox-images.d.ts +1 -14
  56. package/dist/activities/sandbox-lease.d.ts +21 -3
  57. package/dist/activities/scheduled-tasks.d.ts +47 -0
  58. package/dist/activities/types.d.ts +23 -2
  59. package/dist/activities/video-media-validation.d.ts +1 -1
  60. package/dist/activities/video-output-retention.d.ts +1 -2
  61. package/dist/activities/xai-auth.d.ts +3 -0
  62. package/dist/{activities-control-SMKF2OBE.js → activities-control-DKG22ONJ.js} +2946 -549
  63. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  64. package/dist/activities-control.d.ts +6 -2
  65. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  66. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  67. package/dist/activities.d.ts +7 -3
  68. package/dist/artifact-materializer-entry.js +41 -22
  69. package/dist/artifact-materializer-entry.js.map +1 -1
  70. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  71. package/dist/chunk-CE7TPKBS.js.map +1 -0
  72. package/dist/chunk-CNYGVRKF.js +4698 -0
  73. package/dist/chunk-CNYGVRKF.js.map +1 -0
  74. package/dist/connection-provider-use.d.ts +18 -0
  75. package/dist/editable-artifact-materializer.d.ts +4 -3
  76. package/dist/github-rest-mcp.d.ts +26 -0
  77. package/dist/index.d.ts +10 -2
  78. package/dist/index.js +58 -14
  79. package/dist/index.js.map +1 -1
  80. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  81. package/dist/model-context-contributions.d.ts +8 -4
  82. package/dist/observability-metrics.d.ts +63 -4
  83. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  84. package/dist/personal-github-git-credentials.d.ts +9 -0
  85. package/dist/pr-review-credentials.d.ts +6 -0
  86. package/dist/sandbox-archive-storage.d.ts +45 -0
  87. package/dist/sandbox-resume.d.ts +65 -6
  88. package/dist/sandbox-routing.d.ts +38 -2
  89. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  90. package/dist/workflow-bundle.js +87 -28
  91. package/dist/workflows/activities.d.ts +1 -0
  92. package/dist/workflows/automations.d.ts +6 -0
  93. package/dist/workflows/document-index.d.ts +1 -0
  94. package/dist/workflows.d.ts +1 -0
  95. package/package.json +17 -17
  96. package/src/activities/agent-turn/admission.ts +292 -0
  97. package/src/activities/agent-turn/agent-build.ts +802 -0
  98. package/src/activities/agent-turn/claim.ts +590 -0
  99. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  100. package/src/activities/agent-turn/codex.ts +94 -0
  101. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  102. package/src/activities/agent-turn/credential-leases.ts +240 -0
  103. package/src/activities/agent-turn/errors.ts +1068 -0
  104. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  105. package/src/activities/agent-turn/file-resources.ts +227 -0
  106. package/src/activities/agent-turn/finalization.ts +754 -0
  107. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  108. package/src/activities/agent-turn/governance-model.ts +465 -0
  109. package/src/activities/agent-turn/history-sink.ts +139 -0
  110. package/src/activities/agent-turn/history.ts +200 -0
  111. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  112. package/src/activities/agent-turn/model-usage.ts +823 -0
  113. package/src/activities/agent-turn/quiescence.ts +353 -0
  114. package/src/activities/agent-turn/run-credentials.ts +761 -0
  115. package/src/activities/agent-turn/run.ts +1530 -0
  116. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  117. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  118. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  119. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  120. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  121. package/src/activities/agent-turn/tool-environment.ts +729 -0
  122. package/src/activities/agent-turn/tool-policy.ts +216 -0
  123. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  124. package/src/activities/agent-turn/turn-context.ts +281 -0
  125. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  126. package/src/activities/agent-turn.ts +12 -12575
  127. package/src/activities/api-integrations.ts +3 -0
  128. package/src/activities/automations.ts +214 -0
  129. package/src/activities/codemode-dispatcher.ts +12 -1
  130. package/src/activities/common.ts +1 -5
  131. package/src/activities/connector-attachments.ts +168 -0
  132. package/src/activities/context-compaction.ts +18 -0
  133. package/src/activities/documents.ts +6 -4
  134. package/src/activities/environment.ts +151 -55
  135. package/src/activities/generated-images.ts +26 -11
  136. package/src/activities/git-credential-renewal.ts +13 -3
  137. package/src/activities/goals.ts +85 -19
  138. package/src/activities/google-drive-provider.ts +178 -0
  139. package/src/activities/google-drive-publication.ts +938 -0
  140. package/src/activities/image-generation-references.ts +11 -2
  141. package/src/activities/incident-telemetry-authority.ts +327 -0
  142. package/src/activities/incident-telemetry-preflight.ts +317 -0
  143. package/src/activities/knowledge-source-sync-driver.ts +23 -0
  144. package/src/activities/knowledge-source-sync.ts +556 -40
  145. package/src/activities/mcp-credentials.ts +191 -17
  146. package/src/activities/open-suffix-resume.ts +422 -0
  147. package/src/activities/packs.ts +12 -60
  148. package/src/activities/parent-wake.ts +64 -14
  149. package/src/activities/retained-screenshot-reaper.ts +6 -3
  150. package/src/activities/retained-screenshots.ts +15 -47
  151. package/src/activities/rig-verification.ts +1 -1
  152. package/src/activities/run-input.ts +128 -136
  153. package/src/activities/sandbox-images.ts +7 -166
  154. package/src/activities/sandbox-lease.ts +406 -15
  155. package/src/activities/scheduled-tasks.ts +2103 -411
  156. package/src/activities/session-state.ts +10 -2
  157. package/src/activities/types.ts +32 -2
  158. package/src/activities/video-media-validation.ts +3 -3
  159. package/src/activities/video-output-retention.ts +2 -57
  160. package/src/activities/xai-auth.ts +8 -0
  161. package/src/activities-control.ts +2 -0
  162. package/src/activities.ts +3 -0
  163. package/src/activity-services.ts +13 -4
  164. package/src/connection-provider-use.ts +36 -0
  165. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  166. package/src/editable-artifact-materializer.ts +29 -18
  167. package/src/github-rest-mcp.ts +713 -0
  168. package/src/http.ts +16 -6
  169. package/src/index.ts +40 -5
  170. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  171. package/src/model-context-contributions.ts +33 -10
  172. package/src/observability-metrics.ts +357 -0
  173. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  174. package/src/personal-github-git-credentials.ts +331 -0
  175. package/src/pr-review-credentials.ts +163 -0
  176. package/src/sandbox-archive-storage.ts +159 -0
  177. package/src/sandbox-resume.ts +449 -63
  178. package/src/sandbox-routing.ts +314 -16
  179. package/src/scheduled-alert-occurrence.ts +176 -0
  180. package/src/workflows/activities.ts +18 -2
  181. package/src/workflows/automations.ts +11 -0
  182. package/src/workflows/session.ts +13 -3
  183. package/src/workflows.ts +1 -0
  184. package/dist/activities-control-SMKF2OBE.js.map +0 -1
  185. package/dist/activities-turn-IDS3WEHA.js +0 -16532
  186. package/dist/activities-turn-IDS3WEHA.js.map +0 -1
  187. package/dist/chunk-N5TJIFCE.js.map +0 -1
  188. package/dist/chunk-P6Z2SLAA.js +0 -3092
  189. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -0,0 +1,729 @@
1
+ import {
2
+ getScheduledVariableSetExpectedGenerationForAttempt,
3
+ persistAttemptToolCatalog,
4
+ namedSubjectHasLiveWorkspaceAuthority,
5
+ withCodexAppsRequestAuthorization,
6
+ } from "@opengeni/db";
7
+ import {
8
+ type OpenGeniRuntime,
9
+ type AttemptConnectorActionBinding,
10
+ type ConnectorAttachmentMaterializationRequest,
11
+ createFirstPartyInteractionAttemptToolDefinitions,
12
+ } from "@opengeni/runtime";
13
+ import {
14
+ authorizeGoogleDrivePublicationAttempt,
15
+ createGoogleDrivePublicationAttemptTool,
16
+ googleDrivePublicationConnectorCall,
17
+ resolveGoogleDrivePublicationTarget,
18
+ } from "../google-drive-publication";
19
+ import { connectionTokenResolverForTurn } from "../mcp-credentials";
20
+ import { buildApiIntegrationServersForTurn } from "../api-integrations";
21
+ import { buildGitHubRestMcpForTurn } from "../../github-rest-mcp";
22
+ import { materializeConnectorAttachmentsInChannel } from "../connector-attachments";
23
+ import { allowedFirstPartyMcpToolsForSession, type Settings } from "@opengeni/config";
24
+ import { CodemodeAttemptDispatcher } from "../codemode-dispatcher";
25
+ import { buildCodexTokenResolver } from "../codex-auth";
26
+ import { CODEX_CLIENT_VERSION } from "@opengeni/codex";
27
+ import { mergeResourceRefs } from "../common";
28
+ import {
29
+ defaultSessionMcpServerIds,
30
+ loadRigDefaultVariableSetEnvironment,
31
+ mergeRigDefaultVariableSetEnvironment,
32
+ withFrozenPersonalConnectionDelegations,
33
+ resolveSessionToolPolicy,
34
+ } from "@opengeni/core";
35
+ import { loadWorkspaceEnvironmentForRunWithCredentials } from "../environment";
36
+ import { withFirstPartyTools } from "../goals";
37
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from "../types";
38
+ import { recordTurnStartupPhase } from "../../observability-metrics";
39
+ import { ToolResultSpill } from "./tool-result-spill";
40
+ import { createTurnMediaArtifacts } from "./media-artifacts";
41
+ import { SandboxChannelAService, type ChannelASession } from "@opengeni/runtime/sandbox";
42
+ import { sandboxRunAs } from "@opengeni/runtime";
43
+ import { type ToolAuthNeededPayload } from "@opengeni/contracts";
44
+
45
+ import { shouldPublishToolAuthNeededForTurn } from "./admission";
46
+ import { unavailableMcpOperationalContext } from "./errors";
47
+ import { runtimeResourcesForTurn } from "./file-resources";
48
+ import { waitForTurnOperation } from "./sandbox-provision";
49
+ import { shouldDeferNonEagerToolPreparation } from "./tool-policy";
50
+ import type { ClaimTurnOk } from "./claim";
51
+ import type { GovernanceModelOk } from "./governance-model";
52
+ import type { SandboxTurnRuntime } from "./sandbox-runtime";
53
+ import type { sandboxArtifactRuntimeAdmission } from "./sandbox-route";
54
+ import type {
55
+ AttemptIdentityState,
56
+ EventingState,
57
+ SandboxRuntimeState,
58
+ WorkspaceRefState,
59
+ } from "./turn-context";
60
+
61
+ export type PrepareTurnToolPolicyDeps = {
62
+ input: RunAgentTurnInput;
63
+ db: ActivityServices["db"];
64
+ cancellationSignal: AbortSignal | undefined;
65
+ connectionCredentials: ActivityServices["connectionCredentials"];
66
+ turn: ClaimTurnOk["turn"];
67
+ session: ClaimTurnOk["session"];
68
+ fileAuthoritySubjectId: ClaimTurnOk["fileAuthoritySubjectId"];
69
+ capabilitySettings: ClaimTurnOk["capabilitySettings"];
70
+ runSettings: GovernanceModelOk["runSettings"];
71
+ rigVersion: GovernanceModelOk["rigVersion"];
72
+ workspaceRefs: WorkspaceRefState;
73
+ };
74
+
75
+ export type PrepareTurnToolRuntimeDeps = {
76
+ input: RunAgentTurnInput;
77
+ db: ActivityServices["db"];
78
+ bus: ActivityServices["bus"];
79
+ runtime: ActivityServices["runtime"];
80
+ objectStorage: ActivityServices["objectStorage"];
81
+ observability: ActivityServices["observability"];
82
+ cancellationSignal: AbortSignal | undefined;
83
+ connectionCredentials: ActivityServices["connectionCredentials"];
84
+ eventing: EventingState;
85
+ attempt: AttemptIdentityState;
86
+ sandboxState: SandboxRuntimeState;
87
+ media: ReturnType<typeof createTurnMediaArtifacts>;
88
+ toolResultSpill: ToolResultSpill;
89
+ turn: ClaimTurnOk["turn"];
90
+ session: ClaimTurnOk["session"];
91
+ fileAuthoritySubjectId: ClaimTurnOk["fileAuthoritySubjectId"];
92
+ capabilitySettings: ClaimTurnOk["capabilitySettings"];
93
+ installedApiIntegrations: ClaimTurnOk["installedApiIntegrations"];
94
+ codexAppsCredentialId: ClaimTurnOk["codexAppsCredentialId"];
95
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
96
+ trigger: ClaimTurnOk["trigger"];
97
+ runSettings: GovernanceModelOk["runSettings"];
98
+ lazyToolTransport: GovernanceModelOk["lazyToolTransport"];
99
+ turnTools: ReturnType<typeof withFirstPartyTools>;
100
+ connectionScope: { accountId: string; workspaceId: string };
101
+ hostCredentialRootSessionId: string | null;
102
+ sandboxArtifactRuntime: ReturnType<typeof sandboxArtifactRuntimeAdmission>;
103
+ activeSandboxBackend: Settings["sandboxBackend"] | undefined;
104
+ groupBoxBackend: Settings["sandboxBackend"];
105
+ routingOn: boolean;
106
+ runtimeCancellationSignal: AbortSignal | undefined;
107
+ credentialSubjectId: ClaimTurnOk["credentialSubjectId"];
108
+ interactionInterventionResume: ClaimTurnOk["interactionInterventionResume"];
109
+ runWorkspaceMutationForSandbox: SandboxTurnRuntime["runWorkspaceMutationForSandbox"];
110
+ throwIfWorkerShuttingDown: () => void;
111
+ throwIfTurnCancelled: () => void;
112
+ };
113
+
114
+ export async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {
115
+ const {
116
+ input,
117
+ db,
118
+ cancellationSignal,
119
+ connectionCredentials,
120
+ turn,
121
+ session,
122
+ fileAuthoritySubjectId,
123
+ capabilitySettings,
124
+ runSettings,
125
+ rigVersion,
126
+ workspaceRefs,
127
+ } = deps;
128
+
129
+ const turnResources = mergeResourceRefs(session.resources, turn.resources);
130
+ // Repositories remain durable workspace inputs. File attachments do not:
131
+ // only files attached to this exact turn enter the sandbox manifest and
132
+ // eager materialization path. Historical file ids remain in canonical
133
+ // history/session metadata and are recoverable through the Files MCP.
134
+ const runtimeResources = runtimeResourcesForTurn(session.resources, turn.resources);
135
+ // Attach the first-party MCP server to EVERY turn, regardless of how/when
136
+ // the session was created (API, scheduled task, or a pre-existing session
137
+ // whose stored tools predate this). The server registration is then
138
+ // narrowed by the session's exact firstPartyMcpTools selection and
139
+ // authorization. Idempotent: mergeToolRefs dedupes if already present.
140
+ // Resolve the durable policy at the turn boundary. Workspace-default
141
+ // sessions follow the current configured MCP set,
142
+ // while explicit, inherited-fixed, and legacy sessions remain narrowed
143
+ // to their stored materialized allow-list.
144
+ const scheduledEffectiveMcpServerIds = (() => {
145
+ const value =
146
+ turn.metadata && typeof turn.metadata === "object" && !Array.isArray(turn.metadata)
147
+ ? (turn.metadata as Record<string, unknown>).scheduledEffectiveMcpServerIds
148
+ : null;
149
+ return Array.isArray(value) && value.every((id) => typeof id === "string")
150
+ ? [...new Set(value)].sort()
151
+ : null;
152
+ })();
153
+ const currentMcpServerIds = new Set(runSettings.mcpServers.map((server) => server.id));
154
+ const resolvedToolPolicy = resolveSessionToolPolicy({
155
+ toolPolicy: session.toolPolicy,
156
+ sessionTools: scheduledEffectiveMcpServerIds ? turn.tools : session.tools,
157
+ availableMcpServerIds: scheduledEffectiveMcpServerIds
158
+ ? scheduledEffectiveMcpServerIds.filter((id) => currentMcpServerIds.has(id))
159
+ : [...currentMcpServerIds],
160
+ defaultMcpServerIds:
161
+ scheduledEffectiveMcpServerIds ?? defaultSessionMcpServerIds(capabilitySettings.mcpServers),
162
+ });
163
+ const mcpAvailabilityNote = unavailableMcpOperationalContext({
164
+ droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
165
+ droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped,
166
+ });
167
+ const effectivePolicyTools = resolvedToolPolicy.toolRefs;
168
+ const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);
169
+ // §7.6 connection-credential provider — load (and decrypt) selected Variable Sets via the
170
+ // host `sandboxSecrets` provider when bound; unset → today's local decrypt. Preserve the
171
+ // legacy null-attachment fast path: turns with neither a session set nor rig defaults perform
172
+ // no Variable Set work. Organization/workspace sets use the exact turn actor; personal sets
173
+ // additionally require the causal human frozen into the admitted turn.
174
+ const connectionScope = {
175
+ accountId: input.accountId,
176
+ workspaceId: input.workspaceId,
177
+ };
178
+ const rigDefaultVariableSetIds = rigVersion?.defaultVariableSetIds ?? [];
179
+ let workspaceVariableSet: Awaited<
180
+ ReturnType<typeof loadWorkspaceEnvironmentForRunWithCredentials>
181
+ > = null;
182
+ const rigDefaultEnvironmentValues: Record<string, string> = {};
183
+ if (session.variableSetId !== null || rigDefaultVariableSetIds.length > 0) {
184
+ const variableSetAuthority = {
185
+ sessionId: input.sessionId,
186
+ turnId: turn.id,
187
+ attemptId: input.attemptId,
188
+ executionGeneration: turn.executionGeneration,
189
+ initiator: turn.initiator,
190
+ initiatingHumanSubjectId: fileAuthoritySubjectId,
191
+ };
192
+ // A scheduled attempt may materialize only the exact generation frozen
193
+ // on its accepted occurrence; ordinary turns resolve to null.
194
+ const expectedVariableSetGeneration = async (
195
+ candidateVariableSetId: string,
196
+ ): Promise<number | null> =>
197
+ await getScheduledVariableSetExpectedGenerationForAttempt(db, {
198
+ accountId: input.accountId,
199
+ workspaceId: input.workspaceId,
200
+ subjectId: fileAuthoritySubjectId ?? turn.initiator.subjectId,
201
+ initiatingHumanSubjectId: fileAuthoritySubjectId,
202
+ sessionId: input.sessionId,
203
+ turnId: turn.id,
204
+ attemptId: input.attemptId,
205
+ executionGeneration: turn.executionGeneration,
206
+ variableSetId: candidateVariableSetId,
207
+ });
208
+ workspaceVariableSet = await waitForTurnOperation(
209
+ (async () =>
210
+ loadWorkspaceEnvironmentForRunWithCredentials(
211
+ db,
212
+ runSettings,
213
+ connectionScope,
214
+ session.variableSetId,
215
+ variableSetAuthority,
216
+ connectionCredentials?.sandboxSecrets,
217
+ session.variableSetId && connectionCredentials?.sandboxSecrets
218
+ ? { expectedGeneration: await expectedVariableSetGeneration(session.variableSetId) }
219
+ : {},
220
+ ))(),
221
+ cancellationSignal,
222
+ undefined,
223
+ );
224
+ // RIG DEFAULT VARIABLE SETS (M3): decrypt the frozen rig version's default
225
+ // variable sets and layer them BELOW the session's own set — the session's
226
+ // values WIN on any key collision. Loaded through the SAME host-secrets
227
+ // provider path as the session set (embedded-topology parity). Precedence
228
+ // WITHIN the rig defaults is listed order (a later set overrides an earlier
229
+ // one), then the session set overrides all. STABLE-ENV INVARIANT: the rig
230
+ // VERSION is frozen per session, so the SET of default variable sets is
231
+ // fixed for the session's life — the merged manifest env is therefore stable
232
+ // across the session's turns (the same guarantee the session's own variable
233
+ // set already relies on), keeping validateNoEnvironmentDelta empty.
234
+ Object.assign(
235
+ rigDefaultEnvironmentValues,
236
+ await loadRigDefaultVariableSetEnvironment(
237
+ rigDefaultVariableSetIds,
238
+ async (rigDefaultVariableSetId) =>
239
+ await waitForTurnOperation(
240
+ (async () =>
241
+ loadWorkspaceEnvironmentForRunWithCredentials(
242
+ db,
243
+ runSettings,
244
+ connectionScope,
245
+ rigDefaultVariableSetId,
246
+ variableSetAuthority,
247
+ connectionCredentials?.sandboxSecrets,
248
+ connectionCredentials?.sandboxSecrets
249
+ ? {
250
+ expectedGeneration:
251
+ await expectedVariableSetGeneration(rigDefaultVariableSetId),
252
+ }
253
+ : {},
254
+ ))(),
255
+ cancellationSignal,
256
+ undefined,
257
+ ),
258
+ ),
259
+ );
260
+ }
261
+ workspaceRefs.variableSetId = workspaceVariableSet?.id ?? "";
262
+ // Session set wins collisions with the rig defaults (explicit precedence).
263
+ const sandboxWorkspaceEnvironmentValues = mergeRigDefaultVariableSetEnvironment(
264
+ rigDefaultEnvironmentValues,
265
+ workspaceVariableSet?.values ?? {},
266
+ );
267
+ return {
268
+ turnResources,
269
+ runtimeResources,
270
+ mcpAvailabilityNote,
271
+ turnTools,
272
+ connectionScope,
273
+ workspaceVariableSet,
274
+ sandboxWorkspaceEnvironmentValues,
275
+ };
276
+ }
277
+
278
+ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
279
+ const {
280
+ input,
281
+ db,
282
+ bus,
283
+ runtime,
284
+ objectStorage,
285
+ observability,
286
+ cancellationSignal,
287
+ connectionCredentials,
288
+ eventing,
289
+ attempt,
290
+ sandboxState,
291
+ media,
292
+ toolResultSpill,
293
+ turn,
294
+ session,
295
+ installedApiIntegrations,
296
+ codexAppsCredentialId,
297
+ turnExecutionPolicy,
298
+ trigger,
299
+ runSettings,
300
+ lazyToolTransport,
301
+ turnTools,
302
+ hostCredentialRootSessionId,
303
+ sandboxArtifactRuntime,
304
+ activeSandboxBackend,
305
+ groupBoxBackend,
306
+ routingOn,
307
+ runtimeCancellationSignal,
308
+ credentialSubjectId,
309
+ interactionInterventionResume,
310
+ runWorkspaceMutationForSandbox,
311
+ throwIfWorkerShuttingDown,
312
+ throwIfTurnCancelled,
313
+ } = deps;
314
+
315
+ const toolContextPreparationStartedAt = performance.now();
316
+ throwIfWorkerShuttingDown();
317
+ throwIfTurnCancelled();
318
+ const mcpCredentialRootSessionId =
319
+ connectionCredentials?.mcpCredentials && hostCredentialRootSessionId
320
+ ? hostCredentialRootSessionId
321
+ : input.sessionId;
322
+ // Connection credentials and the optional Apps credential are resolved
323
+ // independently. Inference auth is never an Apps fallback.
324
+ const rawResolveCredential = connectionTokenResolverForTurn({
325
+ db,
326
+ settings: runSettings,
327
+ connectionCredentials: connectionCredentials ?? null,
328
+ accountId: input.accountId,
329
+ workspaceId: input.workspaceId,
330
+ sessionId: input.sessionId,
331
+ rootSessionId: mcpCredentialRootSessionId,
332
+ attemptId: input.attemptId,
333
+ turn,
334
+ observability,
335
+ });
336
+ const personalConnectionDelegations = turn.personalConnectionDelegations;
337
+ const delegatedMembershipChecks = new Map<string, Promise<boolean>>();
338
+ // The canonical live-authority resolver, not a bare `workspace_memberships`
339
+ // join: a managed human's personal workspace deliberately has no membership
340
+ // row (migration 0219), so the bare join would revoke the owner's own frozen
341
+ // personal connections for every turn that runs in their private workspace.
342
+ const delegatedOwnerHasMembership = async (subjectId: string): Promise<boolean> => {
343
+ const existing = delegatedMembershipChecks.get(subjectId);
344
+ if (existing) return await existing;
345
+ const check = namedSubjectHasLiveWorkspaceAuthority(db, {
346
+ accountId: input.accountId,
347
+ workspaceId: input.workspaceId,
348
+ subjectId,
349
+ });
350
+ delegatedMembershipChecks.set(subjectId, check);
351
+ return await check;
352
+ };
353
+ const resolveFrozenCredential = withFrozenPersonalConnectionDelegations({
354
+ resolveCredential: rawResolveCredential,
355
+ settings: runSettings,
356
+ personalConnectionDelegations,
357
+ ownerHasWorkspaceMembership: delegatedOwnerHasMembership,
358
+ });
359
+ const resolveCredential: typeof rawResolveCredential = async (request) => {
360
+ const result = await resolveFrozenCredential(request);
361
+ if (result.status === "ok") {
362
+ }
363
+ return result;
364
+ };
365
+ const connectorActionIdentity = {
366
+ accountId: input.accountId,
367
+ workspaceId: input.workspaceId,
368
+ sessionId: input.sessionId,
369
+ turnId: turn.id,
370
+ attemptId: input.attemptId,
371
+ executionGeneration: attempt.executionGeneration,
372
+ initiator: {
373
+ kind: turn.initiator.kind,
374
+ subjectId: turn.initiator.subjectId,
375
+ },
376
+ } as const;
377
+ const googleDrivePublicationTarget = objectStorage
378
+ ? await resolveGoogleDrivePublicationTarget(
379
+ db,
380
+ { accountId: input.accountId, workspaceId: input.workspaceId },
381
+ personalConnectionDelegations,
382
+ )
383
+ : null;
384
+ const googleDrivePublicationTool =
385
+ objectStorage && googleDrivePublicationTarget
386
+ ? createGoogleDrivePublicationAttemptTool({
387
+ db,
388
+ objectStorage,
389
+ identity: connectorActionIdentity,
390
+ subjectId: googleDrivePublicationTarget.ownerSubjectId,
391
+ target: googleDrivePublicationTarget,
392
+ resolveCredential,
393
+ ...(runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {}),
394
+ })
395
+ : null;
396
+ const publishToolAuthNeeded = async (payload: ToolAuthNeededPayload): Promise<void> => {
397
+ if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
398
+ return;
399
+ }
400
+ await eventing.publish!([{ type: "tool.auth_needed", payload }], true);
401
+ };
402
+ const selectedApiIntegrationServerIds = new Set(turnTools.map((tool) => tool.id));
403
+ const apiIntegrationMcpServers = buildApiIntegrationServersForTurn({
404
+ settings: runSettings,
405
+ integrations: installedApiIntegrations.filter((integration) =>
406
+ selectedApiIntegrationServerIds.has(integration.serverId),
407
+ ),
408
+ authority: {
409
+ accountId: input.accountId,
410
+ workspaceId: input.workspaceId,
411
+ sessionId: input.sessionId,
412
+ rootSessionId: session.rootSessionId,
413
+ turnId: turn.id,
414
+ attemptId: input.attemptId,
415
+ ...(credentialSubjectId ? { initiatingSubjectId: credentialSubjectId } : {}),
416
+ },
417
+ resolveCredential,
418
+ onAuthNeeded: publishToolAuthNeeded,
419
+ });
420
+ const githubRestMcp = await buildGitHubRestMcpForTurn({
421
+ db,
422
+ settings: runSettings,
423
+ accountId: input.accountId,
424
+ workspaceId: input.workspaceId,
425
+ sessionId: input.sessionId,
426
+ attemptId: input.attemptId,
427
+ turn,
428
+ resources: mergeResourceRefs(session.resources, turn.resources),
429
+ tools: turnTools,
430
+ resolveCredential,
431
+ });
432
+ const localMcpServers = [...apiIntegrationMcpServers, ...githubRestMcp.localMcpServers];
433
+ const codexAppsAuth = codexAppsCredentialId
434
+ ? (() => {
435
+ const resolver = buildCodexTokenResolver(
436
+ db,
437
+ runSettings,
438
+ input.workspaceId,
439
+ codexAppsCredentialId,
440
+ );
441
+ return {
442
+ clientVersion: CODEX_CLIENT_VERSION,
443
+ withAuthorization: async <T>(
444
+ use: (token: { accessToken: string; chatgptAccountId: string | null }) => Promise<T>,
445
+ ): Promise<T> => {
446
+ const snapshot = await resolver.getToken();
447
+
448
+ return await withCodexAppsRequestAuthorization(
449
+ db,
450
+ {
451
+ workspaceId: input.workspaceId,
452
+ credentialId: codexAppsCredentialId,
453
+ },
454
+ async () => await use(snapshot),
455
+ );
456
+ },
457
+ };
458
+ })()
459
+ : undefined;
460
+ const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession(
461
+ runSettings,
462
+ session.firstPartyMcpTools,
463
+ );
464
+ const googleDrivePublicationAllowed =
465
+ selectedFirstPartyMcpTools.includes("editable_artifact_export") &&
466
+ selectedFirstPartyMcpTools.includes("editable_artifact_export_status") &&
467
+ (!session.firstPartyMcpPermissions?.length ||
468
+ (session.firstPartyMcpPermissions.includes("artifacts:read") &&
469
+ session.firstPartyMcpPermissions.includes("artifacts:publish")));
470
+ const googleDriveConnectorBindings: readonly AttemptConnectorActionBinding[] =
471
+ googleDrivePublicationTool && googleDrivePublicationTarget && googleDrivePublicationAllowed
472
+ ? [
473
+ {
474
+ modelName: googleDrivePublicationTool.modelName,
475
+ call: (approvalId, arguments_) =>
476
+ googleDrivePublicationConnectorCall(
477
+ googleDrivePublicationTarget,
478
+ arguments_,
479
+ approvalId,
480
+ ),
481
+ },
482
+ ]
483
+ : [];
484
+ const attemptToolDefinitions = [
485
+ ...createFirstPartyInteractionAttemptToolDefinitions({
486
+ settings: runSettings,
487
+ scope: {
488
+ accountId: input.accountId,
489
+ workspaceId: input.workspaceId,
490
+ sessionId: input.sessionId,
491
+ turnId: turn.id,
492
+ attemptId: input.attemptId,
493
+ executionGeneration: attempt.executionGeneration,
494
+ },
495
+ ...(session.firstPartyMcpPermissions?.length
496
+ ? { permissions: session.firstPartyMcpPermissions }
497
+ : {}),
498
+ selectedTools: selectedFirstPartyMcpTools,
499
+ subjectId: "worker:first-party-mcp",
500
+ subjectLabel: "OpenGeni worker",
501
+ ...(interactionInterventionResume
502
+ ? { interventionResume: interactionInterventionResume }
503
+ : {}),
504
+ }),
505
+ ...(googleDrivePublicationTool && googleDrivePublicationAllowed
506
+ ? [googleDrivePublicationTool]
507
+ : []),
508
+ ];
509
+ recordTurnStartupPhase(observability, {
510
+ phase: "tool_context_preparation",
511
+ provider: turnExecutionPolicy.providerId,
512
+ backend: activeSandboxBackend ?? groupBoxBackend,
513
+ outcome: "completed",
514
+ durationSeconds: (performance.now() - toolContextPreparationStartedAt) / 1_000,
515
+ count: githubRestMcp.tools.length,
516
+ });
517
+ await eventing.publish!([
518
+ {
519
+ type: "turn.startup.phase.started",
520
+ payload: { phase: "tools" },
521
+ },
522
+ ]);
523
+ const toolPreparationStartedAt = performance.now();
524
+ let toolPreparationOutcome: "completed" | "failed" = "completed";
525
+ const progressiveDisclosureEnabled =
526
+ lazyToolTransport === "codex_native"
527
+ ? runSettings.codexToolSearchEnabled
528
+ : runSettings.lazyToolSearchEnabled;
529
+ const deferNonEagerToolPreparation = shouldDeferNonEagerToolPreparation({
530
+ lazyToolTransport,
531
+ progressiveDisclosureEnabled,
532
+ artifactRuntimeAvailable: sandboxArtifactRuntime.available,
533
+ triggerKind: input.trigger.kind,
534
+ triggerType: trigger.type,
535
+ });
536
+ const materializeConnectorAttachments = async (
537
+ request: ConnectorAttachmentMaterializationRequest,
538
+ ) => {
539
+ throwIfWorkerShuttingDown();
540
+ throwIfTurnCancelled();
541
+ let sandbox = sandboxState.resolvedSandbox;
542
+ if (!sandbox && sandboxState.turnSandboxProvisioner) {
543
+ sandbox = await sandboxState.turnSandboxProvisioner.get();
544
+ }
545
+ const sessionForImport = (sandboxState.lazyOwnedSandbox?.session ??
546
+ sandbox?.established.session ??
547
+ media.sdkOwnedSandboxSession) as ChannelASession | null;
548
+ if (!sessionForImport) {
549
+ throw new Error("Connector attachment sandbox is unavailable");
550
+ }
551
+ const runAs = sandboxRunAs(runSettings);
552
+ const channel = new SandboxChannelAService({
553
+ session: sessionForImport,
554
+ workspaceRoot: "/workspace",
555
+ leaseEpoch: sandbox?.leaseEpoch ?? 0,
556
+ emit: async (events) => {
557
+ await eventing.publish?.(events, true);
558
+ },
559
+ ...(runAs ? { runAs } : {}),
560
+ });
561
+ return await materializeConnectorAttachmentsInChannel(channel, request, {
562
+ runMutation: async (mutation) => {
563
+ if (sandbox && !routingOn) {
564
+ return await runWorkspaceMutationForSandbox(
565
+ sandbox,
566
+ "connectorAttachmentMaterialization",
567
+ mutation,
568
+ );
569
+ }
570
+ return await mutation();
571
+ },
572
+ });
573
+ };
574
+ try {
575
+ eventing.preparedTools = await waitForTurnOperation(
576
+ runtime.prepareTools(githubRestMcp.settings, githubRestMcp.tools, {
577
+ accountId: input.accountId,
578
+ workspaceId: input.workspaceId,
579
+ sessionId: input.sessionId,
580
+ // Sign the calling turn into the first-party token so tools classify
581
+ // the caller by its own identity (sacred-pause guard), not the racy
582
+ // live active pointer.
583
+ ...(attempt.turnId ? { turnId: attempt.turnId } : {}),
584
+ attemptId: input.attemptId,
585
+ executionGeneration: attempt.executionGeneration,
586
+ subjectId: "worker:first-party-mcp",
587
+ subjectLabel: "OpenGeni worker",
588
+ ...(credentialSubjectId ? { credentialSubjectId } : {}),
589
+ ...(codexAppsAuth ? { codexAppsAuth } : {}),
590
+ resolveCredential,
591
+ onAuthNeeded: publishToolAuthNeeded,
592
+ materializeConnectorAttachments,
593
+ spillOversizedModelToolResult: async ({ operationId, result }) =>
594
+ await toolResultSpill.spill({ operationId, result }),
595
+ localMcpServers,
596
+ ...(deferNonEagerToolPreparation ? { deferNonEagerUntilToolDemand: true } : {}),
597
+ onPreparationPhase: (measurement) => {
598
+ recordTurnStartupPhase(observability, {
599
+ phase: `tool_${measurement.phase}`,
600
+ provider: turnExecutionPolicy.providerId,
601
+ backend: activeSandboxBackend ?? groupBoxBackend,
602
+ outcome: measurement.outcome,
603
+ durationSeconds: measurement.durationSeconds,
604
+ count: githubRestMcp.tools.length,
605
+ });
606
+ },
607
+ onAttemptToolCatalog: async (catalog) => {
608
+ await persistAttemptToolCatalog(db, catalog);
609
+ },
610
+ // Manager-style sessions carry a creation-validated permission set
611
+ // for their first-party MCP token; null keeps the fixed default.
612
+ ...(session.firstPartyMcpPermissions?.length
613
+ ? { firstPartyPermissions: session.firstPartyMcpPermissions }
614
+ : {}),
615
+ firstPartyTools: selectedFirstPartyMcpTools,
616
+ nestedAgentDepth: session.nestedAgentDepth,
617
+ effectiveMaxNestedAgentDepth: session.effectiveMaxNestedAgentDepth,
618
+ attemptToolDefinitions,
619
+ ...((googleDrivePublicationTarget && googleDrivePublicationAllowed) ||
620
+ githubRestMcp.authorizeCodemodeCall
621
+ ? {
622
+ attemptToolAuthorize: async (authorization) => {
623
+ const { call } = authorization;
624
+ if (
625
+ googleDrivePublicationTarget &&
626
+ googleDrivePublicationAllowed &&
627
+ call.caller.kind === "codemode" &&
628
+ call.identity.serverId === "google-drive-publishing" &&
629
+ call.identity.toolName === "google_drive_publish_file"
630
+ ) {
631
+ await authorizeGoogleDrivePublicationAttempt({
632
+ db,
633
+ identity: connectorActionIdentity,
634
+ target: googleDrivePublicationTarget,
635
+ approvalId: call.operationId,
636
+ arguments: call.arguments,
637
+ });
638
+ }
639
+ await githubRestMcp.authorizeCodemodeCall?.(authorization);
640
+ },
641
+ }
642
+ : {}),
643
+ }),
644
+ cancellationSignal,
645
+ async (latePreparedTools) => await latePreparedTools.close().catch(() => undefined),
646
+ );
647
+ } catch (error) {
648
+ toolPreparationOutcome = "failed";
649
+ throw error;
650
+ } finally {
651
+ const toolPreparationDurationMs = performance.now() - toolPreparationStartedAt;
652
+ recordTurnStartupPhase(observability, {
653
+ phase: "tool_preparation",
654
+ provider: turnExecutionPolicy.providerId,
655
+ backend: activeSandboxBackend ?? groupBoxBackend,
656
+ outcome: toolPreparationOutcome,
657
+ durationSeconds: toolPreparationDurationMs / 1_000,
658
+ count: githubRestMcp.tools.length,
659
+ });
660
+ await eventing.publish!([
661
+ {
662
+ type:
663
+ toolPreparationOutcome === "completed"
664
+ ? "turn.startup.phase.completed"
665
+ : "turn.startup.phase.failed",
666
+ payload: {
667
+ phase: "tools",
668
+ durationMs: Math.max(0, Math.round(toolPreparationDurationMs)),
669
+ },
670
+ },
671
+ ]);
672
+ }
673
+ const postToolPreparationStartedAt = performance.now();
674
+ const activatePreparedToolEnvironment = (
675
+ tools: Awaited<ReturnType<OpenGeniRuntime["prepareTools"]>>,
676
+ ): void => {
677
+ if (
678
+ eventing.toolPreparationClosing ||
679
+ !attempt.turnId ||
680
+ !tools.attemptToolEnvironment ||
681
+ eventing.codemodeDispatcher
682
+ ) {
683
+ return;
684
+ }
685
+ eventing.codemodeDispatcher = new CodemodeAttemptDispatcher(
686
+ db,
687
+ bus,
688
+ tools.attemptToolEnvironment,
689
+ {
690
+ accountId: input.accountId,
691
+ workspaceId: input.workspaceId,
692
+ sessionId: input.sessionId,
693
+ turnId: attempt.turnId,
694
+ attemptId: input.attemptId,
695
+ executionGeneration: attempt.executionGeneration,
696
+ },
697
+ cancellationSignal,
698
+ );
699
+ eventing.codemodeDispatcher.start();
700
+ };
701
+ if (eventing.preparedTools.ready) {
702
+ const toolPreparationReady = eventing.preparedTools.ready.then((tools) => {
703
+ activatePreparedToolEnvironment(tools);
704
+ });
705
+ // The lazy runtime awaits and rethrows this exact failure when a model
706
+ // attempts to use tools. Attach a handler immediately so an early MCP
707
+ // rejection cannot become a process-level unhandled rejection first.
708
+ void toolPreparationReady.catch(() => undefined);
709
+ eventing.toolPreparationReady = toolPreparationReady;
710
+ } else {
711
+ activatePreparedToolEnvironment(eventing.preparedTools);
712
+ }
713
+ // Genesis turn = the first user turn (no assistant history reconciled
714
+ // yet). Durable Postgres state (countSessionHistoryItems includes
715
+ // superseded rows after compaction), NOT a workflow counter (turnsThisRun
716
+ // resets on continueAsNew). Drives the one-shot title hint appended to the
717
+ // agent's instructions; later attempts and goal continuations never match.
718
+ return {
719
+ attemptConnectorActionBindings: [
720
+ ...googleDriveConnectorBindings,
721
+ ...githubRestMcp.connectorBindings,
722
+ ],
723
+ connectorActionIdentity,
724
+ postToolPreparationStartedAt,
725
+ };
726
+ }
727
+
728
+ export type PrepareTurnToolPolicyOk = Awaited<ReturnType<typeof prepareTurnToolPolicy>>;
729
+ export type PrepareTurnToolRuntimeOk = Awaited<ReturnType<typeof prepareTurnToolRuntime>>;