@opengeni/worker-bundle 0.20.3 → 0.22.1-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 (184) 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 +17 -4
  42. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  43. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  44. package/dist/activities/knowledge-source-sync.d.ts +4 -0
  45. package/dist/activities/mcp-credentials.d.ts +9 -3
  46. package/dist/activities/open-suffix-resume.d.ts +77 -0
  47. package/dist/activities/packs.d.ts +3 -11
  48. package/dist/activities/parent-wake.d.ts +19 -0
  49. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  50. package/dist/activities/retained-screenshots.d.ts +1 -1
  51. package/dist/activities/rig-verification.d.ts +1 -1
  52. package/dist/activities/run-input.d.ts +9 -10
  53. package/dist/activities/sandbox-images.d.ts +1 -14
  54. package/dist/activities/sandbox-lease.d.ts +21 -3
  55. package/dist/activities/scheduled-tasks.d.ts +47 -0
  56. package/dist/activities/types.d.ts +23 -2
  57. package/dist/activities/video-media-validation.d.ts +1 -1
  58. package/dist/activities/video-output-retention.d.ts +1 -2
  59. package/dist/activities/xai-auth.d.ts +3 -0
  60. package/dist/{activities-control-BJSDRSIP.js → activities-control-DKG22ONJ.js} +2646 -551
  61. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  62. package/dist/activities-control.d.ts +6 -2
  63. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  64. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  65. package/dist/activities.d.ts +7 -3
  66. package/dist/artifact-materializer-entry.js +41 -22
  67. package/dist/artifact-materializer-entry.js.map +1 -1
  68. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  69. package/dist/chunk-CE7TPKBS.js.map +1 -0
  70. package/dist/chunk-CNYGVRKF.js +4698 -0
  71. package/dist/chunk-CNYGVRKF.js.map +1 -0
  72. package/dist/connection-provider-use.d.ts +18 -0
  73. package/dist/editable-artifact-materializer.d.ts +4 -3
  74. package/dist/github-rest-mcp.d.ts +26 -0
  75. package/dist/index.d.ts +10 -2
  76. package/dist/index.js +58 -14
  77. package/dist/index.js.map +1 -1
  78. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  79. package/dist/model-context-contributions.d.ts +8 -4
  80. package/dist/observability-metrics.d.ts +63 -4
  81. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  82. package/dist/personal-github-git-credentials.d.ts +9 -0
  83. package/dist/pr-review-credentials.d.ts +6 -0
  84. package/dist/sandbox-archive-storage.d.ts +45 -0
  85. package/dist/sandbox-resume.d.ts +65 -6
  86. package/dist/sandbox-routing.d.ts +38 -2
  87. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  88. package/dist/workflow-bundle.js +87 -28
  89. package/dist/workflows/activities.d.ts +1 -0
  90. package/dist/workflows/automations.d.ts +6 -0
  91. package/dist/workflows/document-index.d.ts +1 -0
  92. package/dist/workflows.d.ts +1 -0
  93. package/package.json +17 -17
  94. package/src/activities/agent-turn/admission.ts +292 -0
  95. package/src/activities/agent-turn/agent-build.ts +802 -0
  96. package/src/activities/agent-turn/claim.ts +590 -0
  97. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  98. package/src/activities/agent-turn/codex.ts +94 -0
  99. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  100. package/src/activities/agent-turn/credential-leases.ts +240 -0
  101. package/src/activities/agent-turn/errors.ts +1068 -0
  102. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  103. package/src/activities/agent-turn/file-resources.ts +227 -0
  104. package/src/activities/agent-turn/finalization.ts +754 -0
  105. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  106. package/src/activities/agent-turn/governance-model.ts +465 -0
  107. package/src/activities/agent-turn/history-sink.ts +139 -0
  108. package/src/activities/agent-turn/history.ts +200 -0
  109. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  110. package/src/activities/agent-turn/model-usage.ts +823 -0
  111. package/src/activities/agent-turn/quiescence.ts +353 -0
  112. package/src/activities/agent-turn/run-credentials.ts +761 -0
  113. package/src/activities/agent-turn/run.ts +1530 -0
  114. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  115. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  116. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  117. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  118. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  119. package/src/activities/agent-turn/tool-environment.ts +729 -0
  120. package/src/activities/agent-turn/tool-policy.ts +216 -0
  121. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  122. package/src/activities/agent-turn/turn-context.ts +281 -0
  123. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  124. package/src/activities/agent-turn.ts +12 -12701
  125. package/src/activities/api-integrations.ts +3 -0
  126. package/src/activities/automations.ts +214 -0
  127. package/src/activities/codemode-dispatcher.ts +12 -1
  128. package/src/activities/common.ts +1 -5
  129. package/src/activities/connector-attachments.ts +168 -0
  130. package/src/activities/context-compaction.ts +18 -0
  131. package/src/activities/environment.ts +151 -55
  132. package/src/activities/generated-images.ts +26 -11
  133. package/src/activities/git-credential-renewal.ts +13 -3
  134. package/src/activities/goals.ts +85 -19
  135. package/src/activities/google-drive-provider.ts +178 -0
  136. package/src/activities/google-drive-publication.ts +147 -49
  137. package/src/activities/incident-telemetry-authority.ts +327 -0
  138. package/src/activities/incident-telemetry-preflight.ts +317 -0
  139. package/src/activities/knowledge-source-sync.ts +178 -37
  140. package/src/activities/mcp-credentials.ts +191 -17
  141. package/src/activities/open-suffix-resume.ts +422 -0
  142. package/src/activities/packs.ts +12 -60
  143. package/src/activities/parent-wake.ts +64 -14
  144. package/src/activities/retained-screenshot-reaper.ts +6 -3
  145. package/src/activities/retained-screenshots.ts +15 -47
  146. package/src/activities/rig-verification.ts +1 -1
  147. package/src/activities/run-input.ts +102 -142
  148. package/src/activities/sandbox-images.ts +7 -166
  149. package/src/activities/sandbox-lease.ts +406 -15
  150. package/src/activities/scheduled-tasks.ts +2103 -411
  151. package/src/activities/session-state.ts +10 -2
  152. package/src/activities/types.ts +32 -2
  153. package/src/activities/video-media-validation.ts +3 -3
  154. package/src/activities/video-output-retention.ts +2 -57
  155. package/src/activities/xai-auth.ts +8 -0
  156. package/src/activities-control.ts +2 -0
  157. package/src/activities.ts +3 -0
  158. package/src/activity-services.ts +13 -4
  159. package/src/connection-provider-use.ts +36 -0
  160. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  161. package/src/editable-artifact-materializer.ts +29 -18
  162. package/src/github-rest-mcp.ts +713 -0
  163. package/src/http.ts +16 -6
  164. package/src/index.ts +40 -5
  165. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  166. package/src/model-context-contributions.ts +33 -10
  167. package/src/observability-metrics.ts +357 -0
  168. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  169. package/src/personal-github-git-credentials.ts +331 -0
  170. package/src/pr-review-credentials.ts +163 -0
  171. package/src/sandbox-archive-storage.ts +159 -0
  172. package/src/sandbox-resume.ts +449 -63
  173. package/src/sandbox-routing.ts +314 -16
  174. package/src/scheduled-alert-occurrence.ts +176 -0
  175. package/src/workflows/activities.ts +18 -2
  176. package/src/workflows/automations.ts +11 -0
  177. package/src/workflows/session.ts +13 -3
  178. package/src/workflows.ts +1 -0
  179. package/dist/activities-control-BJSDRSIP.js.map +0 -1
  180. package/dist/activities-turn-J5YO7XXX.js +0 -17243
  181. package/dist/activities-turn-J5YO7XXX.js.map +0 -1
  182. package/dist/chunk-N5TJIFCE.js.map +0 -1
  183. package/dist/chunk-P6Z2SLAA.js +0 -3092
  184. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -0,0 +1,761 @@
1
+ import { getSessionRootId, resolvePrReviewGitCredential } from "@opengeni/db";
2
+ import { prReviewRegistrationIdFromCredentialBinding } from "@opengeni/core";
3
+ import {
4
+ materializeRunCredentials,
5
+ clearRunCredentials,
6
+ clearRunCredentialsForAttempt,
7
+ refreshGitCredentialBindingTokenFiles,
8
+ refreshCodemodeTokenFile,
9
+ codemodeTokenFileFromEnvironment,
10
+ type GitCredentialTokenWriterSession,
11
+ type NormalizedRunCredentialMaterial,
12
+ type RunCredentialCommandSession,
13
+ type CodemodeTokenWriterSession,
14
+ } from "@opengeni/runtime";
15
+ import { codemodeWorkspaceUrl, type Settings } from "@opengeni/config";
16
+ import {
17
+ assertGitCredentialRenewalTransportUnchanged,
18
+ gitCredentialAuthorityForTurn,
19
+ mintSandboxCodemodeToken,
20
+ mintRunGitCredentials,
21
+ mintRunGitCredentialBinding,
22
+ sandboxEnvironmentForRun,
23
+ type GitHubTokenMintAuthorization,
24
+ type MintedRunGitCredentials,
25
+ type loadWorkspaceEnvironmentForRunWithCredentials,
26
+ } from "../environment";
27
+ import type { mergeResourceRefs } from "../common";
28
+ import { startGitCredentialRenewalLoop } from "../git-credential-renewal";
29
+ import {
30
+ RUN_CREDENTIAL_EXPIRY_LEAD_MS,
31
+ startRunCredentialRenewalLoop,
32
+ } from "../run-credential-renewal";
33
+ import {
34
+ CODEMODE_TOKEN_EXPIRY_LEAD_MS,
35
+ startCodemodeTokenRenewalLoop,
36
+ } from "../codemode-token-renewal";
37
+ import {
38
+ bindRunCredentialResolver,
39
+ runCredentialAuthNeededPayloads,
40
+ runCredentialModelNote,
41
+ } from "../run-credentials";
42
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from "../types";
43
+ import { type ResumedTurnSandbox } from "../../sandbox-resume";
44
+ import { lazyProvisionEnabled } from "../../sandbox-routing";
45
+ import { recordTurnSandboxEstablishPolicy } from "../../observability-metrics";
46
+ import { sandboxRunAs } from "@opengeni/runtime";
47
+
48
+ import {
49
+ assertGitHubResourcesRemainAuthorized,
50
+ assertFileResourcesRemainAuthorized,
51
+ assertGitHubTokenMintSelectionAuthorized,
52
+ requiresSignedFileResourceDownloads,
53
+ } from "./file-resources";
54
+ import { throwIfTurnOperationCancelled, waitForTurnOperation } from "./sandbox-provision";
55
+ import {
56
+ sandboxEstablishPolicyDecision,
57
+ ensureTurnModalRegistryImage,
58
+ sandboxArtifactRuntimeAdmission,
59
+ } from "./sandbox-route";
60
+ import type { ClaimTurnOk } from "./claim";
61
+ import type { GovernanceModelOk } from "./governance-model";
62
+ import type { SandboxTurnRuntime } from "./sandbox-runtime";
63
+ import type {
64
+ AttemptIdentityState,
65
+ EventingState,
66
+ RenewalState,
67
+ SandboxRuntimeState,
68
+ } from "./turn-context";
69
+
70
+ export type PrepareRunCredentialsDeps = {
71
+ input: RunAgentTurnInput;
72
+ settings: Settings;
73
+ db: ActivityServices["db"];
74
+ observability: ActivityServices["observability"];
75
+ cancellationSignal: AbortSignal | undefined;
76
+ connectionCredentials: ActivityServices["connectionCredentials"];
77
+ personalGitHubCredentials: ActivityServices["personalGitHubCredentials"];
78
+ eventing: EventingState;
79
+ attempt: AttemptIdentityState;
80
+ renewals: RenewalState;
81
+ sandboxState: SandboxRuntimeState;
82
+ sandboxRuntime: SandboxTurnRuntime;
83
+ turn: ClaimTurnOk["turn"];
84
+ session: ClaimTurnOk["session"];
85
+ fileAuthoritySubjectId: ClaimTurnOk["fileAuthoritySubjectId"];
86
+ runSettings: GovernanceModelOk["runSettings"];
87
+ workspaceVariableSet: Awaited<ReturnType<typeof loadWorkspaceEnvironmentForRunWithCredentials>>;
88
+ turnResources: ReturnType<typeof mergeResourceRefs>;
89
+ requiredGeneratedVideoFiles: Array<{
90
+ operationId: string;
91
+ artifactId: string;
92
+ fileId: string;
93
+ objectKey: string;
94
+ sizeBytes: number;
95
+ sha256: string;
96
+ filename: string;
97
+ }>;
98
+ machinePrimary: boolean;
99
+ activeSandboxBackend: Settings["sandboxBackend"] | undefined;
100
+ groupBoxBackend: Settings["sandboxBackend"];
101
+ sandboxCreationBackend: Settings["sandboxBackend"];
102
+ effectiveRunCredentialBackend: Settings["sandboxBackend"];
103
+ sandboxWorkspaceEnvironmentValues: Record<string, string>;
104
+ connectionScope: { accountId: string; workspaceId: string };
105
+ runWorkspaceMutationForSandbox: SandboxTurnRuntime["runWorkspaceMutationForSandbox"];
106
+ };
107
+
108
+ export async function prepareRunCredentials(deps: PrepareRunCredentialsDeps) {
109
+ const {
110
+ input,
111
+ settings,
112
+ db,
113
+ observability,
114
+ cancellationSignal,
115
+ connectionCredentials,
116
+ personalGitHubCredentials,
117
+ eventing,
118
+ attempt,
119
+ renewals,
120
+ sandboxState,
121
+ turn,
122
+ session,
123
+ fileAuthoritySubjectId,
124
+ runSettings,
125
+ workspaceVariableSet,
126
+ turnResources,
127
+ requiredGeneratedVideoFiles,
128
+ machinePrimary,
129
+ activeSandboxBackend,
130
+ groupBoxBackend,
131
+ sandboxCreationBackend,
132
+ effectiveRunCredentialBackend,
133
+ sandboxWorkspaceEnvironmentValues,
134
+ connectionScope,
135
+ runWorkspaceMutationForSandbox,
136
+ } = deps;
137
+
138
+ const runCredentialResolver =
139
+ effectiveRunCredentialBackend === "none"
140
+ ? null
141
+ : await waitForTurnOperation(
142
+ bindRunCredentialResolver({
143
+ db,
144
+ connectionCredentials: connectionCredentials ?? null,
145
+ accountId: input.accountId,
146
+ workspaceId: input.workspaceId,
147
+ session,
148
+ turn,
149
+ attemptId: input.attemptId,
150
+ effectiveSandboxBackend: effectiveRunCredentialBackend,
151
+ variableSet: workspaceVariableSet
152
+ ? {
153
+ id: workspaceVariableSet.id,
154
+ name: workspaceVariableSet.name,
155
+ }
156
+ : null,
157
+ }),
158
+ cancellationSignal,
159
+ undefined,
160
+ );
161
+ const establishDecision = sandboxEstablishPolicyDecision({
162
+ lazyEnabled: lazyProvisionEnabled(settings),
163
+ machinePrimary,
164
+ sandboxBackend: runSettings.sandboxBackend,
165
+ hasRunCredentialResolver: runCredentialResolver !== null,
166
+ generatedVideoFileCount: requiredGeneratedVideoFiles.length,
167
+ hasSignedFileResources:
168
+ requiresSignedFileResourceDownloads(runSettings, activeSandboxBackend ?? groupBoxBackend) &&
169
+ turn.resources.some((resource) => resource.kind === "file"),
170
+ });
171
+ const establishPolicy = establishDecision.policy;
172
+ recordTurnSandboxEstablishPolicy(observability, {
173
+ policy: establishDecision.policy,
174
+ reason: establishDecision.reason,
175
+ backend: machinePrimary ? "selfhosted" : groupBoxBackend,
176
+ });
177
+ // Resolve once before model preparation so partial/auth-needed host state
178
+ // is available as bounded model context and reconnect UI even when an
179
+ // on-demand turn never provisions a box. Resolution alone performs no
180
+ // sandbox write or renewal; both paths reuse this exact material and the
181
+ // lazy path materializes it only inside its first-operation single-flight.
182
+ const initialRunCredentialMaterial = runCredentialResolver
183
+ ? await waitForTurnOperation(
184
+ runCredentialResolver.resolve({
185
+ purpose: "provision",
186
+ forceRefresh: false,
187
+ }),
188
+ cancellationSignal,
189
+ undefined,
190
+ )
191
+ : null;
192
+ if (initialRunCredentialMaterial) {
193
+ for (const payload of runCredentialAuthNeededPayloads(initialRunCredentialMaterial)) {
194
+ renewals.publishedRunCredentialNotices.add(JSON.stringify(payload));
195
+ await eventing.publish!([{ type: "credential.auth_needed", payload }], true);
196
+ }
197
+ }
198
+ const runCredentialsNote = initialRunCredentialMaterial
199
+ ? runCredentialModelNote(initialRunCredentialMaterial)
200
+ : undefined;
201
+ throwIfTurnOperationCancelled(cancellationSignal);
202
+ const authorizeGitHubTokenMint: GitHubTokenMintAuthorization = async (selection) => {
203
+ const registrationId = prReviewRegistrationIdFromCredentialBinding(
204
+ selection.credentialBindingId,
205
+ );
206
+ if (registrationId) {
207
+ await resolvePrReviewGitCredential(db, {
208
+ accountId: input.accountId,
209
+ workspaceId: input.workspaceId,
210
+ registrationId,
211
+ provider: "github",
212
+ sessionId: input.sessionId,
213
+ rootSessionId: input.sessionId,
214
+ turnId: turn.id,
215
+ attemptId: input.attemptId,
216
+ executionGeneration: turn.executionGeneration,
217
+ repositoryRefs: selection.repositoryRefs.map((reference) => ({
218
+ uri: reference.uri,
219
+ ...(reference.expectedCommitSha !== undefined
220
+ ? { expectedCommitSha: reference.expectedCommitSha }
221
+ : {}),
222
+ ...(reference.repositoryId !== undefined ? { repositoryId: reference.repositoryId } : {}),
223
+ ...(reference.installationId !== undefined
224
+ ? { installationId: reference.installationId }
225
+ : {}),
226
+ ...(reference.projectId !== undefined ? { projectId: reference.projectId } : {}),
227
+ })),
228
+ });
229
+ return;
230
+ }
231
+ await assertGitHubTokenMintSelectionAuthorized(
232
+ db,
233
+ input.workspaceId,
234
+ selection.installationId,
235
+ selection.repositoryIds,
236
+ );
237
+ };
238
+ await Promise.all([
239
+ waitForTurnOperation(
240
+ ensureTurnModalRegistryImage(runSettings, sandboxCreationBackend),
241
+ cancellationSignal,
242
+ undefined,
243
+ ),
244
+ activeSandboxBackend !== "selfhosted"
245
+ ? assertGitHubResourcesRemainAuthorized(
246
+ db,
247
+ input.workspaceId,
248
+ turnResources,
249
+ authorizeGitHubTokenMint,
250
+ )
251
+ : Promise.resolve(),
252
+ assertFileResourcesRemainAuthorized(
253
+ db,
254
+ input.accountId,
255
+ input.workspaceId,
256
+ fileAuthoritySubjectId,
257
+ turn.resources,
258
+ ),
259
+ ]);
260
+ // Computed exactly ONCE per turn and reused for BOTH the box manifest
261
+ // (resumeBoxForTurn -> establishSandboxSessionFromEnvelope, below) AND the
262
+ // agent (runtime.buildAgent, below). sandboxEnvironmentForRun mints a FRESH
263
+ // run-scoped git provider tokens on every call, so a second call would
264
+ // yield DIFFERENT token values and re-introduce the manifest-env delta the
265
+ // SDK's provided-session guard throws on — the box and the agent MUST share
266
+ // this same object. A machine-primary turn skips the (inert) token mint entirely
267
+ // (the machine uses its own git creds); the SAME base env still feeds the box +
268
+ // the agent, so env-parity holds.
269
+ // TOKEN-BROKER (B1): sandboxEnvironmentForRun now returns the STABLE manifest
270
+ // env (no rotating GH_TOKEN/GITHUB_TOKEN/GIT_CONFIG_* extraheader) PLUS the
271
+ // run-scoped git tokens minted ONCE per turn as provider seeds, with `gitToken`
272
+ // retained as the GitHub alias. The env feeds BOTH the box manifest AND the
273
+ // agent (env-parity, as before); tokens are threaded OFF-MANIFEST as
274
+ // clone-seeds to buildAgent (below) so the box never carries rotating values
275
+ // on its manifest. When a platform token IS minted, the host `gitCredentials`
276
+ // provider may supply it; unset still self-mints GitHub from settings.
277
+ // gitToken/gitTokens are undefined on the selfhosted skip path (the machine
278
+ // uses its own git creds).
279
+ // Git and MCP credentials share one lineage snapshot for this turn. A
280
+ // host that supplies both ports must never see two independently resolved
281
+ // roots for the same execution merely because the call sites are far apart.
282
+ const needsHostCredentialRoot = Boolean(
283
+ connectionCredentials?.gitCredentials ||
284
+ personalGitHubCredentials ||
285
+ connectionCredentials?.mcpCredentials,
286
+ );
287
+ const hostCredentialRootSessionId = needsHostCredentialRoot
288
+ ? await getSessionRootId(db, input.workspaceId, input.sessionId)
289
+ : null;
290
+ if (needsHostCredentialRoot && !hostCredentialRootSessionId) {
291
+ throw new Error(`cannot resolve host credentials for missing session ${input.sessionId}`);
292
+ }
293
+ const gitCredentialAuthority =
294
+ (connectionCredentials?.gitCredentials || personalGitHubCredentials) &&
295
+ hostCredentialRootSessionId
296
+ ? gitCredentialAuthorityForTurn({
297
+ sessionId: input.sessionId,
298
+ rootSessionId: hostCredentialRootSessionId,
299
+ attemptId: input.attemptId,
300
+ turn,
301
+ })
302
+ : undefined;
303
+ const codemodeAuthority = {
304
+ sessionId: input.sessionId,
305
+ turnId: turn.id,
306
+ attemptId: input.attemptId,
307
+ executionGeneration: turn.executionGeneration,
308
+ };
309
+ const sandboxArtifactRuntime = sandboxArtifactRuntimeAdmission(
310
+ settings,
311
+ runSettings,
312
+ activeSandboxBackend ?? groupBoxBackend,
313
+ );
314
+ const {
315
+ environment: baseSandboxEnvironment,
316
+ gitToken: sandboxGitToken,
317
+ gitTokens: sandboxGitTokens,
318
+ gitTokenExpiresAt: sandboxGitTokenExpiresAt,
319
+ gitCredentialBindings: sandboxGitCredentialBindings,
320
+ codemodeToken: sandboxCodemodeToken,
321
+ codemodeTokenExpiresAt: sandboxCodemodeTokenExpiresAt,
322
+ } = await waitForTurnOperation(
323
+ sandboxEnvironmentForRun(
324
+ runSettings,
325
+ turnResources,
326
+ // Rig default sets merged BELOW the session set (session wins); rig-less
327
+ // turns pass exactly workspaceVariableSet?.values (byte-for-byte today).
328
+ sandboxWorkspaceEnvironmentValues,
329
+ {
330
+ skipGitHubToken: activeSandboxBackend === "selfhosted",
331
+ codemodeDelivery: activeSandboxBackend === "selfhosted" ? "transient_exec" : "managed_file",
332
+ deferGitHubToken: activeSandboxBackend !== "selfhosted" && establishPolicy === "on-demand",
333
+ scope: connectionScope,
334
+ ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),
335
+ gitCredentials: connectionCredentials?.gitCredentials,
336
+ personalGitHubCredentials: personalGitHubCredentials ?? undefined,
337
+ authorizeGitHubTokenMint,
338
+ codemodeAuthority,
339
+ },
340
+ ),
341
+ cancellationSignal,
342
+ undefined,
343
+ );
344
+ // Reserved, image-owned paths win over workspace/session variables. The
345
+ // exact same merged object feeds both box manifest and agent declaration,
346
+ // preserving the no-environment-delta invariant.
347
+ const sandboxEnvironment = sandboxArtifactRuntime.available
348
+ ? { ...baseSandboxEnvironment, ...sandboxArtifactRuntime.environment }
349
+ : baseSandboxEnvironment;
350
+
351
+ // One mutable in-memory bearer cell serves every Connected Machine route
352
+ // in this attempt. SelfhostedSession snapshots it into each exact exec
353
+ // request; it never enters the manifest, argv, filesystem, RunState, or
354
+ // serialized session state. Managed renewal updates the same cell so a
355
+ // later mid-turn swap sees the fresh bearer too.
356
+ const codemodeTokenState = sandboxCodemodeToken ? { token: sandboxCodemodeToken } : undefined;
357
+ const transientCodemodeEnvironment = codemodeTokenState
358
+ ? (): Readonly<Record<string, string>> => ({
359
+ OPENGENI_CODEMODE_URL: codemodeWorkspaceUrl(runSettings, input.workspaceId),
360
+ OPENGENI_CODEMODE_TOKEN: codemodeTokenState.token,
361
+ ...(runSettings.ogtoolPackageSpec
362
+ ? { OPENGENI_OGTOOL_PACKAGE_SPEC: runSettings.ogtoolPackageSpec }
363
+ : {}),
364
+ })
365
+ : undefined;
366
+
367
+ const sandboxCodemodeTokenFile = sandboxCodemodeToken
368
+ ? codemodeTokenFileFromEnvironment(sandboxEnvironment, input.sessionId)
369
+ : undefined;
370
+
371
+ const initialGitCredentials: MintedRunGitCredentials | undefined = sandboxGitCredentialBindings
372
+ ? {
373
+ bindings: sandboxGitCredentialBindings,
374
+ gitTokens: sandboxGitTokens ?? {},
375
+ expiresAt: sandboxGitTokenExpiresAt ?? {},
376
+ }
377
+ : undefined;
378
+ // Lazy cloud provision mints the run-scoped git token while Modal create
379
+ // runs. Chat-only turns never call get(), so this stays unstarted there.
380
+ let runGitCredentialsMint: Promise<MintedRunGitCredentials | undefined> | undefined;
381
+ const startRunGitCredentialsMint = (): Promise<MintedRunGitCredentials | undefined> => {
382
+ if (activeSandboxBackend === "selfhosted") {
383
+ return Promise.resolve(undefined);
384
+ }
385
+ runGitCredentialsMint ??= waitForTurnOperation(
386
+ mintRunGitCredentials(runSettings, turnResources, {
387
+ scope: connectionScope,
388
+ ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),
389
+ gitCredentials: connectionCredentials?.gitCredentials,
390
+ personalGitHubCredentials: personalGitHubCredentials ?? undefined,
391
+ authorizeGitHubTokenMint,
392
+ }),
393
+ cancellationSignal,
394
+ undefined,
395
+ );
396
+ return runGitCredentialsMint;
397
+ };
398
+ const attachGitCredentialRenewal = async (
399
+ tokenSession: GitCredentialTokenWriterSession,
400
+ initial: MintedRunGitCredentials | undefined,
401
+ initialSandbox?: ResumedTurnSandbox,
402
+ ): Promise<void> => {
403
+ if (!initial || initial.bindings.length === 0) return;
404
+ const previous = renewals.gitCredentialRenewals;
405
+ renewals.gitCredentialRenewals = [];
406
+ await Promise.all(previous.map(async (controller) => await controller.stop()));
407
+ if (renewals.gitCredentialRenewalClosed) return;
408
+
409
+ const controllers = initial.bindings.map((initialBinding) => {
410
+ let pendingBinding: typeof initialBinding | undefined;
411
+ return startGitCredentialRenewalLoop({
412
+ expectedProviders: [initialBinding.provider],
413
+ ...(initialBinding.transport?.kind === "http_broker" ? { expiryLeadMs: 60_000 } : {}),
414
+ initialExpiresAt: initialBinding.expiresAt
415
+ ? { [initialBinding.provider]: initialBinding.expiresAt }
416
+ : {},
417
+ mint: async () => {
418
+ const binding = await mintRunGitCredentialBinding(
419
+ runSettings,
420
+ turnResources,
421
+ initialBinding.provider,
422
+ initialBinding.credentialBindingId,
423
+ {
424
+ scope: connectionScope,
425
+ ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),
426
+ gitCredentials: connectionCredentials?.gitCredentials,
427
+ personalGitHubCredentials: personalGitHubCredentials ?? undefined,
428
+ authorizeGitHubTokenMint,
429
+ },
430
+ );
431
+ if (binding) {
432
+ assertGitCredentialRenewalTransportUnchanged(initialBinding, binding);
433
+ }
434
+ pendingBinding = binding;
435
+ return binding
436
+ ? {
437
+ bindings: [binding],
438
+ gitTokens: { [binding.provider]: binding.token },
439
+ expiresAt: binding.expiresAt ? { [binding.provider]: binding.expiresAt } : {},
440
+ }
441
+ : undefined;
442
+ },
443
+ write: async () => {
444
+ if (!pendingBinding) {
445
+ throw new Error("credential renewal produced no binding token");
446
+ }
447
+ const runAs = sandboxRunAs(runSettings);
448
+ const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
449
+ if (!targetSandbox) {
450
+ throw new Error("Git credential renewal has no exact sandbox lease target");
451
+ }
452
+ await runWorkspaceMutationForSandbox(
453
+ targetSandbox,
454
+ "gitCredentialRenewal",
455
+ async () =>
456
+ await refreshGitCredentialBindingTokenFiles(tokenSession, [pendingBinding!], {
457
+ ...(runAs ? { runAs } : {}),
458
+ ...(eventing.toolCancellationFenceRef.current
459
+ ? {
460
+ commandRunner:
461
+ eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
462
+ eventing.toolCancellationFenceRef.current,
463
+ ),
464
+ }
465
+ : {}),
466
+ }),
467
+ );
468
+ },
469
+ onSuccess: ({ providers: renewedProviders }) => {
470
+ for (const provider of renewedProviders) {
471
+ observability.incrementCounter({
472
+ name: "opengeni_git_credential_renewals_total",
473
+ help: "Host-managed Git credential renewal attempts by provider and outcome.",
474
+ labels: { provider, outcome: "completed" },
475
+ });
476
+ }
477
+ },
478
+ onFailure: ({ providers: failedProviders, retryDelayMs, errorClass }) => {
479
+ for (const provider of failedProviders) {
480
+ observability.incrementCounter({
481
+ name: "opengeni_git_credential_renewals_total",
482
+ help: "Host-managed Git credential renewal attempts by provider and outcome.",
483
+ labels: { provider, outcome: "error" },
484
+ });
485
+ }
486
+ observability.warn("Sandbox Git credential renewal failed; retry scheduled", {
487
+ sessionId: input.sessionId,
488
+ turnId: attempt.turnId,
489
+ providers: failedProviders.join(","),
490
+ errorClass,
491
+ retryDelayMs,
492
+ });
493
+ },
494
+ });
495
+ });
496
+ if (renewals.gitCredentialRenewalClosed) {
497
+ await Promise.all(controllers.map(async (controller) => await controller.stop()));
498
+ return;
499
+ }
500
+ renewals.gitCredentialRenewals = controllers;
501
+ };
502
+
503
+ const attachCodemodeTokenRenewal = async (
504
+ tokenSession?: CodemodeTokenWriterSession,
505
+ initialExpiresAt = sandboxCodemodeTokenExpiresAt,
506
+ initialSandbox?: ResumedTurnSandbox,
507
+ ): Promise<void> => {
508
+ if (!codemodeTokenState || !initialExpiresAt) return;
509
+ const previous = renewals.codemodeTokenRenewal;
510
+ renewals.codemodeTokenRenewal = null;
511
+ await previous?.stop();
512
+ if (renewals.codemodeTokenRenewalClosed) return;
513
+
514
+ const mint = async () => {
515
+ const material = await mintSandboxCodemodeToken(
516
+ runSettings,
517
+ connectionScope,
518
+ codemodeAuthority,
519
+ );
520
+ return material;
521
+ };
522
+ const write = async (material: NonNullable<Awaited<ReturnType<typeof mint>>>) => {
523
+ if (tokenSession) {
524
+ const runAs = sandboxRunAs(runSettings);
525
+ const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
526
+ if (!targetSandbox) {
527
+ throw new Error("Codemode token renewal has no exact sandbox lease target");
528
+ }
529
+ await runWorkspaceMutationForSandbox(
530
+ targetSandbox,
531
+ "codemodeTokenRenewal",
532
+ async () =>
533
+ await refreshCodemodeTokenFile(tokenSession, material.token, {
534
+ ...(runAs ? { runAs } : {}),
535
+ ...(sandboxCodemodeTokenFile
536
+ ? {
537
+ tokenFile: sandboxCodemodeTokenFile,
538
+ legacyTokenFile: sandboxEnvironment.OPENGENI_CODEMODE_TOKEN_FILE!,
539
+ }
540
+ : {}),
541
+ ...(eventing.toolCancellationFenceRef.current
542
+ ? {
543
+ commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
544
+ eventing.toolCancellationFenceRef.current,
545
+ ),
546
+ }
547
+ : {}),
548
+ }),
549
+ );
550
+ }
551
+ codemodeTokenState.token = material.token;
552
+ };
553
+ let renewalExpiresAt = initialExpiresAt;
554
+ if (renewalExpiresAt.getTime() <= Date.now() + CODEMODE_TOKEN_EXPIRY_LEAD_MS) {
555
+ const fresh = await mint();
556
+ if (!fresh) {
557
+ throw new Error("Codemode token mint became unavailable during sandbox setup");
558
+ }
559
+ await write(fresh);
560
+ renewalExpiresAt = fresh.expiresAt;
561
+ }
562
+ const controller = startCodemodeTokenRenewalLoop({
563
+ initialExpiresAt: renewalExpiresAt,
564
+ mint,
565
+ write,
566
+ onSuccess: () => {
567
+ observability.incrementCounter({
568
+ name: "opengeni_codemode_token_renewals_total",
569
+ help: "Sandbox Codemode token renewal attempts by outcome.",
570
+ labels: { outcome: "completed" },
571
+ });
572
+ },
573
+ onFailure: ({ retryDelayMs, errorClass }) => {
574
+ observability.incrementCounter({
575
+ name: "opengeni_codemode_token_renewals_total",
576
+ help: "Sandbox Codemode token renewal attempts by outcome.",
577
+ labels: { outcome: "error" },
578
+ });
579
+ observability.warn("Sandbox Codemode token renewal failed; retry scheduled", {
580
+ sessionId: input.sessionId,
581
+ turnId: attempt.turnId,
582
+ errorClass,
583
+ retryDelayMs,
584
+ });
585
+ },
586
+ });
587
+ if (renewals.codemodeTokenRenewalClosed) {
588
+ await controller.stop();
589
+ return;
590
+ }
591
+ renewals.codemodeTokenRenewal = controller;
592
+ };
593
+
594
+ // A Connected Machine needs renewal, but renewal is purely worker-local:
595
+ // starting this loop performs no control-plane or machine operation.
596
+ if (activeSandboxBackend === "selfhosted") {
597
+ await attachCodemodeTokenRenewal();
598
+ }
599
+
600
+ const attachRunCredentialRenewal = async (
601
+ credentialSession: RunCredentialCommandSession,
602
+ initialMaterial: NormalizedRunCredentialMaterial | null,
603
+ initialSandbox?: ResumedTurnSandbox,
604
+ ): Promise<void> => {
605
+ if (!runCredentialResolver) return;
606
+ const previous = renewals.runCredentialRenewal;
607
+ renewals.runCredentialRenewal = null;
608
+ await previous?.stop();
609
+ if (renewals.runCredentialRenewalClosed) return;
610
+ renewals.runCredentialSession = credentialSession;
611
+
612
+ const requireTargetSandbox = (): ResumedTurnSandbox => {
613
+ const targetSandbox = sandboxState.resolvedSandbox ?? initialSandbox;
614
+ if (!targetSandbox) {
615
+ throw new Error("Run credential mutation has no exact sandbox lease target");
616
+ }
617
+ return targetSandbox;
618
+ };
619
+
620
+ if (!initialMaterial) {
621
+ await runWorkspaceMutationForSandbox(
622
+ requireTargetSandbox(),
623
+ "runCredentialClear",
624
+ async () =>
625
+ await clearRunCredentials(
626
+ credentialSession,
627
+ input.sessionId,
628
+ eventing.toolCancellationFenceRef.current
629
+ ? eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
630
+ eventing.toolCancellationFenceRef.current,
631
+ )
632
+ : undefined,
633
+ ),
634
+ );
635
+ return;
636
+ }
637
+
638
+ const write = async (
639
+ material: NormalizedRunCredentialMaterial | null,
640
+ pruneOtherAttempts = false,
641
+ ): Promise<void> => {
642
+ if (!material) {
643
+ await runWorkspaceMutationForSandbox(
644
+ requireTargetSandbox(),
645
+ "runCredentialAttemptClear",
646
+ async () =>
647
+ await clearRunCredentialsForAttempt(credentialSession, {
648
+ sessionId: input.sessionId,
649
+ attemptId: input.attemptId,
650
+ executionGeneration: attempt.executionGeneration,
651
+ }),
652
+ );
653
+ return;
654
+ }
655
+
656
+ await runWorkspaceMutationForSandbox(
657
+ requireTargetSandbox(),
658
+ "runCredentialMaterialization",
659
+ async () =>
660
+ await materializeRunCredentials(credentialSession, material, {
661
+ sessionId: input.sessionId,
662
+ attemptId: input.attemptId,
663
+ executionGeneration: attempt.executionGeneration,
664
+ ...(pruneOtherAttempts ? { pruneOtherAttempts: true } : {}),
665
+ ...(!pruneOtherAttempts ? { pruneSupersededGenerations: true } : {}),
666
+ ...(material.authNeeded.length > 0 &&
667
+ Object.keys(material.environment).length === 0 &&
668
+ material.files.length === 0
669
+ ? { prunePreviousGenerations: true }
670
+ : {}),
671
+ ...(eventing.toolCancellationFenceRef.current
672
+ ? {
673
+ commandRunner: eventing.toolCancellationFenceRef.current.runSandboxCommand.bind(
674
+ eventing.toolCancellationFenceRef.current,
675
+ ),
676
+ }
677
+ : {}),
678
+ }),
679
+ );
680
+ for (const payload of runCredentialAuthNeededPayloads(material)) {
681
+ const key = JSON.stringify(payload);
682
+ if (renewals.publishedRunCredentialNotices.has(key)) continue;
683
+ renewals.publishedRunCredentialNotices.add(key);
684
+ await eventing.publish!([{ type: "credential.auth_needed", payload }], true);
685
+ }
686
+ };
687
+
688
+ const initialExpiryMs = initialMaterial.expiresAt?.getTime() ?? null;
689
+ const seed =
690
+ initialExpiryMs !== null && initialExpiryMs <= Date.now() + RUN_CREDENTIAL_EXPIRY_LEAD_MS
691
+ ? await runCredentialResolver.resolve({
692
+ purpose: "provision",
693
+ forceRefresh: true,
694
+ })
695
+ : initialMaterial;
696
+ await write(seed, true);
697
+ if (renewals.runCredentialRenewalClosed) return;
698
+ const controller = startRunCredentialRenewalLoop({
699
+ initialExpiresAt: seed?.expiresAt ?? null,
700
+ resolve: async () =>
701
+ await runCredentialResolver.resolve({
702
+ purpose: "renewal",
703
+ forceRefresh: true,
704
+ }),
705
+ write: async (material) => await write(material),
706
+ onSuccess: ({ authNeeded }) => {
707
+ observability.incrementCounter({
708
+ name: "opengeni_run_credential_renewals_total",
709
+ help: "Host-managed run credential renewal attempts by outcome.",
710
+ labels: { outcome: authNeeded ? "auth_needed" : "completed" },
711
+ });
712
+ },
713
+ onFailure: ({ retryDelayMs, errorClass }) => {
714
+ observability.incrementCounter({
715
+ name: "opengeni_run_credential_renewals_total",
716
+ help: "Host-managed run credential renewal attempts by outcome.",
717
+ labels: { outcome: "error" },
718
+ });
719
+ observability.warn("Host run credential renewal failed; retry scheduled", {
720
+ sessionId: input.sessionId,
721
+ turnId: attempt.turnId,
722
+ errorClass,
723
+ retryDelayMs,
724
+ });
725
+ },
726
+ });
727
+ if (renewals.runCredentialRenewalClosed) {
728
+ await controller.stop();
729
+ return;
730
+ }
731
+ renewals.runCredentialRenewal = controller;
732
+ };
733
+
734
+ return {
735
+ runCredentialResolver,
736
+ establishPolicy,
737
+ initialRunCredentialMaterial,
738
+ runCredentialsNote,
739
+ authorizeGitHubTokenMint,
740
+ hostCredentialRootSessionId,
741
+ gitCredentialAuthority,
742
+ codemodeAuthority,
743
+ sandboxArtifactRuntime,
744
+ sandboxEnvironment,
745
+ sandboxGitToken,
746
+ sandboxGitTokens,
747
+ sandboxGitTokenExpiresAt,
748
+ sandboxGitCredentialBindings,
749
+ sandboxCodemodeToken,
750
+ sandboxCodemodeTokenExpiresAt,
751
+ sandboxCodemodeTokenFile,
752
+ transientCodemodeEnvironment,
753
+ initialGitCredentials,
754
+ startRunGitCredentialsMint,
755
+ attachGitCredentialRenewal,
756
+ attachCodemodeTokenRenewal,
757
+ attachRunCredentialRenewal,
758
+ };
759
+ }
760
+
761
+ export type PrepareRunCredentialsOk = Awaited<ReturnType<typeof prepareRunCredentials>>;