@opengeni/worker-bundle 0.20.3 → 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 (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
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  applyGitAuthPointerEnvironment,
3
3
  codemodeWorkspaceUrl,
4
- resolveFirstPartyDelegationSecret,
5
4
  stableSandboxEnvironmentForRun,
6
5
  type Settings,
7
6
  } from "@opengeni/config";
@@ -9,7 +8,6 @@ import {
9
8
  gitCredentialBindingIdForRepository,
10
9
  gitCredentialProviderForRepository,
11
10
  gitRemoteIdentity,
12
- signDelegatedAccessToken,
13
11
  type ConnectionCredentialsPort,
14
12
  type GitCredentialProvider,
15
13
  type GitCredentialRepositoryRef,
@@ -21,6 +19,8 @@ import {
21
19
  type TurnInitiator,
22
20
  type TurnInitiatorContext,
23
21
  } from "@opengeni/contracts";
22
+ import { personalGitHubRepositoryResources } from "@opengeni/core";
23
+ import { mintSandboxCodemodeToken, type SandboxCodemodeAuthority } from "@opengeni/runtime/sandbox";
24
24
  import {
25
25
  loadVariableSetForRun as loadWorkspaceEnvironmentForRunFromDb,
26
26
  type Database,
@@ -45,6 +45,15 @@ export type ConnectionScope = {
45
45
  workspaceId: string;
46
46
  };
47
47
 
48
+ export type VariableSetCredentialAuthority = {
49
+ sessionId: string;
50
+ turnId: string;
51
+ attemptId: string;
52
+ executionGeneration: number;
53
+ initiator: TurnInitiator;
54
+ initiatingHumanSubjectId: string | null;
55
+ };
56
+
48
57
  export type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;
49
58
  export type GitTokenExpiries = Partial<Record<GitCredentialProvider, string>>;
50
59
  export type GitCredentialBindingSeed = {
@@ -63,49 +72,20 @@ export type MintedRunGitCredentials = {
63
72
  expiresAt: GitTokenExpiries;
64
73
  };
65
74
 
66
- export type GitHubTokenMintAuthorization = (selection: {
75
+ export type GitHubTokenMintSelection = {
76
+ credentialBindingId: string;
67
77
  installationId: number;
68
78
  repositoryIds: number[];
69
- }) => Promise<void>;
70
-
71
- export const CODEMODE_TOKEN_TTL_SECONDS = 60 * 60;
72
-
73
- export type MintedSandboxCodemodeToken = {
74
- token: string;
75
- expiresAt: Date;
76
- };
77
-
78
- export type SandboxCodemodeAuthority = {
79
- sessionId: string;
80
- turnId: string;
81
- attemptId: string;
82
- executionGeneration: number;
79
+ repositoryRefs: GitCredentialRepositoryRef[];
83
80
  };
81
+ export type GitHubTokenMintAuthorization = (selection: GitHubTokenMintSelection) => Promise<void>;
84
82
 
85
- export async function mintSandboxCodemodeToken(
86
- settings: Settings,
87
- scope: ConnectionScope,
88
- authority: SandboxCodemodeAuthority,
89
- nowMs = Date.now(),
90
- ): Promise<MintedSandboxCodemodeToken | undefined> {
91
- const delegationSecret = resolveFirstPartyDelegationSecret(settings);
92
- if (!delegationSecret) return undefined;
93
- const expiresAtSeconds = Math.floor(nowMs / 1000) + CODEMODE_TOKEN_TTL_SECONDS;
94
- const token = await signDelegatedAccessToken(delegationSecret, {
95
- accountId: scope.accountId,
96
- workspaceId: scope.workspaceId,
97
- subjectId: `sandbox:${authority.attemptId}`,
98
- subjectLabel: "sandbox Codemode",
99
- permissions: ["codemode:call"],
100
- sessionId: authority.sessionId,
101
- turnId: authority.turnId,
102
- attemptId: authority.attemptId,
103
- executionGeneration: authority.executionGeneration,
104
- principalKind: "agent_attempt",
105
- exp: expiresAtSeconds,
106
- });
107
- return { token, expiresAt: new Date(expiresAtSeconds * 1000) };
108
- }
83
+ export {
84
+ CODEMODE_TOKEN_TTL_SECONDS,
85
+ mintSandboxCodemodeToken,
86
+ type MintedSandboxCodemodeToken,
87
+ type SandboxCodemodeAuthority,
88
+ } from "@opengeni/runtime/sandbox";
109
89
 
110
90
  export type GitCredentialAuthority = {
111
91
  sessionId: string;
@@ -138,6 +118,7 @@ type RunGitCredentialOptions = {
138
118
  scope?: ConnectionScope;
139
119
  authority?: GitCredentialAuthority;
140
120
  gitCredentials?: ConnectionCredentialsPort["gitCredentials"];
121
+ personalGitHubCredentials?: ConnectionCredentialsPort["gitCredentials"];
141
122
  authorizeGitHubTokenMint?: GitHubTokenMintAuthorization;
142
123
  };
143
124
 
@@ -155,27 +136,63 @@ export async function loadWorkspaceEnvironmentForRunWithCredentials(
155
136
  settings: Settings,
156
137
  scope: ConnectionScope,
157
138
  environmentId: string | null,
139
+ authority: VariableSetCredentialAuthority,
158
140
  sandboxSecrets?: ConnectionCredentialsPort["sandboxSecrets"],
141
+ options: {
142
+ /**
143
+ * Exact accepted scheduled-occurrence generation for this Variable Set,
144
+ * resolved by the caller from the immutable run snapshot; null/omitted for
145
+ * ordinary live turns.
146
+ */
147
+ expectedGeneration?: number | null;
148
+ } = {},
159
149
  ): Promise<WorkspaceEnvironmentForRun | null> {
160
150
  if (!sandboxSecrets) {
161
- // Standalone default: today's local decrypt, unchanged.
162
- return loadWorkspaceEnvironmentForRunFromDb(db, settings, scope.workspaceId, environmentId);
151
+ return loadWorkspaceEnvironmentForRunFromDb(db, settings, {
152
+ ...scope,
153
+ variableSetId: environmentId,
154
+ authority: {
155
+ kind: "agent_attempt",
156
+ subjectId: authority.initiatingHumanSubjectId ?? authority.initiator.subjectId,
157
+ ...authority,
158
+ },
159
+ });
163
160
  }
164
161
  if (!environmentId) {
165
162
  return null;
166
163
  }
164
+ const expectedGeneration = options.expectedGeneration ?? null;
167
165
  const secrets: SandboxSecrets = await sandboxSecrets({
168
166
  accountId: scope.accountId,
169
167
  workspaceId: scope.workspaceId,
168
+ ...authority,
170
169
  variableSetId: environmentId,
170
+ ...(expectedGeneration === null ? {} : { expectedGeneration }),
171
171
  });
172
172
  // workspace-scope cross-check: the provider must echo THIS run's workspace before we apply its
173
173
  // decrypted values into the sandbox.
174
174
  assertWorkspaceEcho("sandboxSecrets", scope, secrets.workspaceId);
175
+ if (
176
+ secrets.accountId !== scope.accountId ||
177
+ secrets.sessionId !== authority.sessionId ||
178
+ secrets.turnId !== authority.turnId ||
179
+ secrets.attemptId !== authority.attemptId ||
180
+ secrets.executionGeneration !== authority.executionGeneration ||
181
+ secrets.variableSetId !== environmentId ||
182
+ // A scheduled attempt materializes only the exact accepted generation:
183
+ // the host must echo it and return that generation's values.
184
+ (expectedGeneration !== null &&
185
+ (secrets.expectedGeneration !== expectedGeneration ||
186
+ secrets.generation !== expectedGeneration))
187
+ ) {
188
+ throw new Error("connection-credential provider (sandboxSecrets) returned stale authority");
189
+ }
175
190
  return {
176
191
  id: secrets.id ?? environmentId,
177
192
  name: secrets.name ?? environmentId,
178
193
  description: secrets.description ?? null,
194
+ scope: secrets.scope,
195
+ generation: secrets.generation,
179
196
  values: secrets.values,
180
197
  };
181
198
  }
@@ -342,7 +359,11 @@ export async function mintRunGitCredentials(
342
359
  }
343
360
  const minted = await mintRunGitTokensWithIdentity(settings, selections, options);
344
361
  return minted.bindings.length > 0
345
- ? { bindings: minted.bindings, gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }
362
+ ? {
363
+ bindings: minted.bindings,
364
+ gitTokens: minted.gitTokens,
365
+ expiresAt: minted.expiresAt,
366
+ }
346
367
  : undefined;
347
368
  }
348
369
 
@@ -427,18 +448,22 @@ async function mintRunGitTokensWithIdentity(
427
448
  // the current workspace binding before every host-brokered or built-in
428
449
  // GitHub installation-token mint.
429
450
  await options.authorizeGitHubTokenMint?.({
451
+ credentialBindingId: selection.credentialBindingId,
430
452
  installationId: selection.installationId,
431
453
  repositoryIds: selection.repositoryIds,
454
+ repositoryRefs: selection.repositoryRefs,
432
455
  });
433
456
  }
434
- if (options?.gitCredentials && options.scope) {
457
+ const gitCredentials = credentialsForSelection(options, selection);
458
+ assertPersonalGitHubConsumerAvailable(selection, gitCredentials, options.scope);
459
+ if (gitCredentials && options.scope) {
435
460
  const request = gitCredentialsRequestForSelection(
436
461
  options.scope,
437
462
  requireGitCredentialAuthority(options),
438
463
  selection,
439
464
  "token",
440
465
  );
441
- const minted: GitCredentials = await options.gitCredentials(request);
466
+ const minted: GitCredentials = await gitCredentials(request);
442
467
  // workspace-scope cross-check: assert the provider scoped the token to THIS run's workspace
443
468
  // before accepting the token for clone seeding.
444
469
  assertWorkspaceEcho("gitCredentials", options.scope, minted.workspaceId);
@@ -454,9 +479,9 @@ async function mintRunGitTokensWithIdentity(
454
479
  ? validatedGitCredentialExpiry(selection.provider, minted.expiresAt)
455
480
  : undefined;
456
481
  if (minted.identity) {
457
- identity = minted.identity;
482
+ identity = mergeGitIdentity(identity, minted.identity);
458
483
  } else if (selection.provider === "github") {
459
- identity = githubAppBotIdentity(settings);
484
+ identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));
460
485
  }
461
486
  } else if (selection.provider === "github" && selection.installationId > 0) {
462
487
  const minted = await createGitHubAppInstallationTokenWithExpiry(settings, {
@@ -467,7 +492,7 @@ async function mintRunGitTokensWithIdentity(
467
492
  tokenExpiresAt = minted.expiresAt
468
493
  ? validatedGitCredentialExpiry("github", minted.expiresAt)
469
494
  : undefined;
470
- identity = githubAppBotIdentity(settings);
495
+ identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));
471
496
  }
472
497
  if (token) {
473
498
  bindings.push({
@@ -632,23 +657,25 @@ async function resolveRunGitIdentityWithSelections(
632
657
  ): Promise<{ name: string; email: string } | null> {
633
658
  let identity: { name: string; email: string } | null = null;
634
659
  for (const selection of selections) {
635
- if (options.gitCredentials && options.scope) {
660
+ const gitCredentials = credentialsForSelection(options, selection);
661
+ assertPersonalGitHubConsumerAvailable(selection, gitCredentials, options.scope);
662
+ if (gitCredentials && options.scope) {
636
663
  const request = gitCredentialsRequestForSelection(
637
664
  options.scope,
638
665
  requireGitCredentialAuthority(options),
639
666
  selection,
640
667
  "identity",
641
668
  );
642
- const resolved: GitCredentials = await options.gitCredentials(request);
669
+ const resolved: GitCredentials = await gitCredentials(request);
643
670
  assertWorkspaceEcho("gitCredentials", options.scope, resolved.workspaceId);
644
671
  assertGitCredentialBindingEcho(selection, request, resolved);
645
672
  if (resolved.identity) {
646
- identity = resolved.identity;
673
+ identity = mergeGitIdentity(identity, resolved.identity);
647
674
  } else if (selection.provider === "github") {
648
- identity = githubAppBotIdentity(settings);
675
+ identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));
649
676
  }
650
677
  } else if (selection.provider === "github" && selection.installationId > 0) {
651
- identity = githubAppBotIdentity(settings);
678
+ identity = mergeGitIdentity(identity, githubAppBotIdentity(settings));
652
679
  }
653
680
  }
654
681
  return identity;
@@ -663,6 +690,7 @@ type GitCredentialSelection = {
663
690
  installationId: number;
664
691
  repositoryIds: number[];
665
692
  repositoryRefs: GitCredentialRepositoryRef[];
693
+ personalGitHub: boolean;
666
694
  };
667
695
 
668
696
  function gitCredentialsRequestForSelection(
@@ -749,7 +777,29 @@ export function gitHubTokenMintSelections(
749
777
  candidate.installationId > 0 &&
750
778
  candidate.repositoryIds.length > 0,
751
779
  )
752
- .map(({ installationId, repositoryIds }) => ({ installationId, repositoryIds }));
780
+ .map(({ installationId, repositoryIds }) => ({
781
+ installationId,
782
+ repositoryIds,
783
+ }));
784
+ }
785
+
786
+ /** Exact binding-aware selections used by authorization immediately before mint. */
787
+ export function gitHubTokenAuthorizationSelections(
788
+ resources: ResourceRef[],
789
+ ): GitHubTokenMintSelection[] {
790
+ return gitCredentialSelections(resources)
791
+ .filter(
792
+ (candidate) =>
793
+ candidate.provider === "github" &&
794
+ candidate.installationId > 0 &&
795
+ candidate.repositoryIds.length > 0,
796
+ )
797
+ .map(({ credentialBindingId, installationId, repositoryIds, repositoryRefs }) => ({
798
+ credentialBindingId,
799
+ installationId,
800
+ repositoryIds,
801
+ repositoryRefs,
802
+ }));
753
803
  }
754
804
 
755
805
  /** @deprecated Use gitHubTokenMintSelections for multi-installation sessions. */
@@ -764,6 +814,12 @@ export function gitHubTokenMintSelection(
764
814
  }
765
815
 
766
816
  function gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {
817
+ // The repository-authority phase admits and freezes this selection, while the
818
+ // personal Git broker owns immediately-before-use revalidation. Until that
819
+ // consumer is active, never let a generic host/App callback substitute a token.
820
+ const personalGitHubResources = new Set<ResourceRef>(
821
+ personalGitHubRepositoryResources(resources),
822
+ );
767
823
  const byBinding = new Map<string, GitCredentialSelection>();
768
824
  const remoteBindings = new Map<string, string>();
769
825
  const bindingProviders = new Map<string, GitCredentialProvider>();
@@ -771,6 +827,7 @@ function gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelecti
771
827
  if (resource.kind !== "repository") {
772
828
  continue;
773
829
  }
830
+ const personalGitHub = personalGitHubResources.has(resource);
774
831
  const provider = repositoryCredentialProvider(resource);
775
832
  if (!provider) {
776
833
  continue;
@@ -804,7 +861,13 @@ function gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelecti
804
861
  installationId: 0,
805
862
  repositoryIds: [],
806
863
  repositoryRefs: [],
864
+ personalGitHub,
807
865
  };
866
+ if (entry.personalGitHub !== personalGitHub) {
867
+ throw new Error(
868
+ `credential binding ${credentialBindingId} mixes personal and app GitHub repositories`,
869
+ );
870
+ }
808
871
  entry.explicitCredentialBinding ||= Boolean(resource.credentialBindingId);
809
872
  const ref = gitCredentialRepositoryRef(resource, provider);
810
873
  entry.repositoryRefs.push(ref);
@@ -839,6 +902,38 @@ function gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelecti
839
902
  return selections;
840
903
  }
841
904
 
905
+ function credentialsForSelection(
906
+ options: RunGitCredentialOptions,
907
+ selection: GitCredentialSelection,
908
+ ): ConnectionCredentialsPort["gitCredentials"] | undefined {
909
+ return selection.personalGitHub ? options.personalGitHubCredentials : options.gitCredentials;
910
+ }
911
+
912
+ function assertPersonalGitHubConsumerAvailable(
913
+ selection: GitCredentialSelection,
914
+ resolver: ConnectionCredentialsPort["gitCredentials"] | undefined,
915
+ scope: ConnectionScope | undefined,
916
+ ): void {
917
+ if (selection.personalGitHub && (!resolver || !scope)) {
918
+ throw new Error("personal GitHub Git broker is unavailable for this managed sandbox turn");
919
+ }
920
+ }
921
+
922
+ function mergeGitIdentity(
923
+ current: { name: string; email: string } | null,
924
+ candidate: { name: string; email: string } | null,
925
+ ): { name: string; email: string } | null {
926
+ if (!candidate) return current;
927
+ if (
928
+ current &&
929
+ (current.name !== candidate.name ||
930
+ current.email.toLowerCase() !== candidate.email.toLowerCase())
931
+ ) {
932
+ throw new Error("repository resources require different Git commit identities");
933
+ }
934
+ return current ?? candidate;
935
+ }
936
+
842
937
  function normalizedGitHost(uri: string): string {
843
938
  try {
844
939
  return new URL(uri).host.toLowerCase();
@@ -863,6 +958,7 @@ function gitCredentialRepositoryRef(
863
958
  ...(resource.access ? { access: resource.access } : {}),
864
959
  uri: resource.uri,
865
960
  ref: resource.ref,
961
+ ...(resource.expectedCommitSha ? { expectedCommitSha: resource.expectedCommitSha } : {}),
866
962
  ...(resource.repositoryId !== undefined
867
963
  ? { repositoryId: resource.repositoryId }
868
964
  : resource.githubRepositoryId !== undefined
@@ -4,6 +4,7 @@ import {
4
4
  GENERATED_IMAGE_MAX_BYTES,
5
5
  GeneratedImageReceiptSchema,
6
6
  retainedGeneratedImageReferenceFromFile,
7
+ sandboxShellPath,
7
8
  type GeneratedImageReceipt,
8
9
  } from "@opengeni/contracts";
9
10
  import {
@@ -15,7 +16,7 @@ import {
15
16
  type GeneratedImageArtifact,
16
17
  type GeneratedImageSourceStrategy,
17
18
  } from "@opengeni/db";
18
- import type { ObjectHead, ObjectStorage } from "@opengeni/storage";
19
+ import { retryWhileMissing, type ObjectHead, type ObjectStorage } from "@opengeni/storage";
19
20
  import { createHash } from "node:crypto";
20
21
  import { ScreenshotValidationError, validateRetainableSessionImage } from "./retained-screenshots";
21
22
 
@@ -338,7 +339,6 @@ export async function retainGeneratedImage(input: {
338
339
  });
339
340
 
340
341
  if (prepared.artifact.status === "ready") {
341
- await verifyReadyGeneratedImage(input.objectStorage, prepared.artifact, image);
342
342
  return retainedGeneratedImageFromArtifact(prepared.artifact);
343
343
  }
344
344
 
@@ -356,11 +356,9 @@ export async function retainGeneratedImage(input: {
356
356
  body: image.bytes,
357
357
  sha256: image.sha256,
358
358
  });
359
+ } else {
360
+ await assertGeneratedImageObject(input.objectStorage, prepared.artifact.file, image);
359
361
  }
360
- assertStoredGeneratedImageHead(
361
- await input.objectStorage.headFile(prepared.artifact.file),
362
- image,
363
- );
364
362
  await completeFileUpload(input.db, input.workspaceId, identity.uploadId);
365
363
  } else {
366
364
  await verifyReadyGeneratedImage(input.objectStorage, prepared.artifact, image);
@@ -702,7 +700,7 @@ function generatedImageModelFact(receipt: GeneratedImageReceipt): string {
702
700
  return [
703
701
  "Generated image artifact:",
704
702
  `Artifact ID: ${receipt.artifact.artifactId}`,
705
- `Sandbox path: ${receipt.sandboxPath}`,
703
+ `Sandbox path: ${sandboxShellPath(receipt.sandboxPath)}`,
706
704
  `Format: ${receipt.artifact.contentType}`,
707
705
  `Dimensions: ${receipt.artifact.dimensions?.width ?? "?"}x${receipt.artifact.dimensions?.height ?? "?"}`,
708
706
  ].join("\n");
@@ -764,7 +762,7 @@ export async function verifyReadyGeneratedImageArtifact(
764
762
  if (artifact.status !== "ready" || artifact.file.status !== "ready") {
765
763
  throw new Error("Generated image artifact is not durably ready");
766
764
  }
767
- assertStoredGeneratedImageHead(await storage.headFile(artifact.file), {
765
+ await assertGeneratedImageObject(storage, artifact.file, {
768
766
  sizeBytes: artifact.sizeBytes,
769
767
  mediaType: artifact.mediaType as GeneratedImageMediaType,
770
768
  sha256: artifact.sha256,
@@ -789,8 +787,12 @@ export async function recoverGeneratedImageArtifact(input: {
789
787
  return artifact;
790
788
  }
791
789
  if (artifact.status !== "pending") return null;
792
- if (!(await input.storage.fileExists(artifact.file))) return null;
793
- assertStoredGeneratedImageHead(await input.storage.headFile(artifact.file), {
790
+ const recovered = await retryWhileMissing(async () => {
791
+ if (!(await input.storage.fileExists(artifact.file))) return null;
792
+ return artifact.file;
793
+ });
794
+ if (!recovered) return null;
795
+ await assertGeneratedImageObject(input.storage, artifact.file, {
794
796
  sizeBytes: artifact.sizeBytes,
795
797
  mediaType: artifact.mediaType as GeneratedImageMediaType,
796
798
  sha256: artifact.sha256,
@@ -812,7 +814,7 @@ async function verifyReadyGeneratedImage(
812
814
  artifact: GeneratedImageArtifact,
813
815
  expected: ValidatedGeneratedImage,
814
816
  ): Promise<void> {
815
- assertStoredGeneratedImageHead(await storage.headFile(artifact.file), expected);
817
+ await assertGeneratedImageObject(storage, artifact.file, expected);
816
818
  if (
817
819
  artifact.sizeBytes !== expected.sizeBytes ||
818
820
  artifact.sha256 !== expected.sha256 ||
@@ -824,6 +826,19 @@ async function verifyReadyGeneratedImage(
824
826
  }
825
827
  }
826
828
 
829
+ async function assertGeneratedImageObject(
830
+ storage: ObjectStorage,
831
+ file: GeneratedImageArtifact["file"],
832
+ expected: Pick<ValidatedGeneratedImage, "sizeBytes" | "mediaType" | "sha256">,
833
+ ): Promise<void> {
834
+ const head = await retryWhileMissing(async () => {
835
+ if (!(await storage.fileExists(file))) return null;
836
+ return await storage.headFile(file);
837
+ });
838
+ if (!head) throw new Error("generated image object is missing");
839
+ assertStoredGeneratedImageHead(head, expected);
840
+ }
841
+
827
842
  function assertStoredGeneratedImageHead(
828
843
  head: ObjectHead,
829
844
  expected: Pick<ValidatedGeneratedImage, "sizeBytes" | "mediaType" | "sha256">,
@@ -27,6 +27,8 @@ export type GitCredentialRenewalController = {
27
27
  export type GitCredentialRenewalOptions = {
28
28
  expectedProviders: readonly GitCredentialProvider[];
29
29
  initialExpiresAt?: GitTokenExpiries;
30
+ /** Override the default five-minute provider-token lead for shorter broker bearers. */
31
+ expiryLeadMs?: number;
30
32
  mint: () => Promise<MintedRunGitCredentials | undefined>;
31
33
  write: (tokens: GitTokenSeeds) => Promise<void>;
32
34
  now?: () => number;
@@ -47,6 +49,7 @@ export function nextGitCredentialRenewalDelay(
47
49
  expiresAt: GitTokenExpiries | undefined,
48
50
  providers: readonly GitCredentialProvider[],
49
51
  nowMs = Date.now(),
52
+ expiryLeadMs = GIT_CREDENTIAL_EXPIRY_LEAD_MS,
50
53
  ): number {
51
54
  let delay = GIT_CREDENTIAL_DEFAULT_REFRESH_MS;
52
55
  for (const provider of providers) {
@@ -56,7 +59,7 @@ export function nextGitCredentialRenewalDelay(
56
59
  if (!Number.isFinite(expiryMs)) continue;
57
60
  delay = Math.min(
58
61
  delay,
59
- Math.max(GIT_CREDENTIAL_MIN_REFRESH_MS, expiryMs - nowMs - GIT_CREDENTIAL_EXPIRY_LEAD_MS),
62
+ Math.max(GIT_CREDENTIAL_MIN_REFRESH_MS, expiryMs - nowMs - expiryLeadMs),
60
63
  );
61
64
  }
62
65
  return delay;
@@ -126,7 +129,12 @@ export function startGitCredentialRenewalLoop(
126
129
  }
127
130
  if (stopped) return;
128
131
  retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;
129
- const nextDelayMs = nextGitCredentialRenewalDelay(minted.expiresAt, providers, now());
132
+ const nextDelayMs = nextGitCredentialRenewalDelay(
133
+ minted.expiresAt,
134
+ providers,
135
+ now(),
136
+ options.expiryLeadMs,
137
+ );
130
138
  try {
131
139
  options.onSuccess?.({ providers, nextDelayMs });
132
140
  } catch {
@@ -162,7 +170,9 @@ export function startGitCredentialRenewalLoop(
162
170
  return operation;
163
171
  };
164
172
 
165
- scheduleRefresh(nextGitCredentialRenewalDelay(options.initialExpiresAt, providers, now()));
173
+ scheduleRefresh(
174
+ nextGitCredentialRenewalDelay(options.initialExpiresAt, providers, now(), options.expiryLeadMs),
175
+ );
166
176
 
167
177
  return {
168
178
  refreshNow,
@@ -1,13 +1,12 @@
1
1
  import {
2
+ allowedFirstPartyMcpToolsForSession,
2
3
  configuredStaticUsageLimits,
3
4
  policyProviderIdForModel,
4
5
  type Settings,
5
6
  } from "@opengeni/config";
6
7
  import {
7
8
  evaluateWorkspaceModelPolicy,
8
- latencyModeForMetadata,
9
9
  mergeToolRefs,
10
- reasoningEffortForMetadata,
11
10
  type SessionGoal,
12
11
  type ToolRef,
13
12
  } from "@opengeni/contracts";
@@ -69,10 +68,8 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
69
68
  );
70
69
  let continuationModel = latestStartedTurn?.model ?? session.model;
71
70
  const continuationReasoningEffort =
72
- latestStartedTurn?.reasoningEffort ??
73
- reasoningEffortForMetadata(session.metadata, settings.openaiReasoningEffort);
74
- const continuationLatencyMode =
75
- latestStartedTurn?.latencyMode ?? latencyModeForMetadata(session.metadata, "standard");
71
+ latestStartedTurn?.reasoningEffort ?? session.reasoningEffort;
72
+ const continuationLatencyMode = latestStartedTurn?.latencyMode ?? session.latencyMode;
76
73
  // Workspace model policy: a continuation inherits the last STARTED turn's
77
74
  // model, so a single policy-violating turn would otherwise re-arm itself on
78
75
  // every continuation (exactly how one bare-model turn kept a goal loop on
@@ -131,7 +128,12 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
131
128
  sessionId: input.sessionId,
132
129
  workflowId: input.workflowId,
133
130
  defaultMaxAutoContinuations: settings.goalMaxAutoContinuations ?? null,
134
- noProgressLimit: settings.goalNoProgressLimit,
131
+ // Pacing between consecutive no-input continuations (never a cap). The
132
+ // materializer re-arms a delayed outbox wake and returns `deferred`.
133
+ idleBackoff: {
134
+ scheduleMs: settings.goalIdleBackoffMs,
135
+ maxMs: settings.goalIdleBackoffMaxMs,
136
+ },
135
137
  // A model-policy block takes precedence: it is deterministic (a budget
136
138
  // pause can clear on its own; a policy pause needs a model/policy change)
137
139
  // and rides the same visible-pause channel.
@@ -143,7 +145,22 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
143
145
  tools: withFirstPartyTools(settings, session.tools),
144
146
  sandboxBackend: session.sandboxBackend,
145
147
  },
146
- prompt: goalContinuationPrompt,
148
+ // The hold guidance is only given when `goal_wait` is actually in this
149
+ // session's effective first-party selection (the same source the worker
150
+ // signs into the delegated token and the API uses to register tools), so
151
+ // a pre-existing narrowed selection is never told to call a missing tool.
152
+ prompt: (goal, autoContinuation, cap) => {
153
+ const effectiveFirstPartyTools = allowedFirstPartyMcpToolsForSession(
154
+ settings,
155
+ session.firstPartyMcpTools,
156
+ );
157
+ return goalContinuationPrompt(goal, autoContinuation, cap, {
158
+ goalWaitAvailable: effectiveFirstPartyTools.includes("goal_wait"),
159
+ humanInputRespondAvailable: effectiveFirstPartyTools.includes(
160
+ "session_human_input_respond",
161
+ ),
162
+ });
163
+ },
147
164
  });
148
165
  if (decision.events.length > 0) {
149
166
  await bus.publish(input.workspaceId, input.sessionId, decision.events);
@@ -158,19 +175,68 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
158
175
  }
159
176
 
160
177
  export function goalContinuationPrompt(
161
- goal: SessionGoal,
162
- autoContinuation: number,
163
- cap: number | null,
178
+ _goal: SessionGoal,
179
+ _autoContinuation: number,
180
+ _cap: number | null,
181
+ options: { goalWaitAvailable?: boolean; humanInputRespondAvailable?: boolean } = {},
164
182
  ): string {
165
- const counter = cap === null ? `${autoContinuation}` : `${autoContinuation}/${cap}`;
183
+ const waitingGuidance = options.goalWaitAvailable
184
+ ? [
185
+ "Waiting on child sessions or external events:",
186
+ "- When the next progress depends on child sessions you spawned or on an external event, do not sleep, loop, or poll sessions_list/session_get/session_events to wait for it.",
187
+ "- Re-check sessions_list or session_get once; if the work is still in flight, call opengeni__goal_wait with a concrete reason and a deadline (untilSeconds), then end your turn immediately. You will be woken by a child result, a message, a human prompt, or at the deadline, and this goal stays active.",
188
+ "- A hold is for child/external progress only. If you are blocked on a human decision, use opengeni__goal_pause under the blocked audit below instead.",
189
+ "",
190
+ ]
191
+ : [];
192
+ const childNoticeGuidance = [
193
+ "Child lifecycle notices:",
194
+ "- A `child_requires_action` update means a worker you spawned is blocked on a question or a tool approval and will not progress until it is answered. " +
195
+ (options.humanInputRespondAvailable
196
+ ? "If you know the answer to its question, answer it with opengeni__session_human_input_respond (pass the worker's sessionId, the requestId from the notice, and a response). "
197
+ : "") +
198
+ "Tool approvals can only be decided by a human. If you cannot resolve the blocker yourself, report the exact blocker (worker session id, the question) to the user and wait or pause instead of retrying the worker.",
199
+ "- `child_requires_action_resolved`, `child_paused`, `child_waiting_capacity`, and `child_progress` updates are informational: a resolved notice means the worker is moving again; a paused worker needs a human or you to resume it; a capacity wait resumes by itself; a progress note needs no action.",
200
+ "",
201
+ ];
166
202
  return [
167
- `[GOAL CONTINUATION ${counter}] The session goal is not done. Goal: ${goal.text}.`,
168
- `Success criteria: ${goal.successCriteria ?? "none specified"}.`,
169
- `Objective revision: ${goal.objectiveRevision}. Mutation policy: ${goal.mutationPolicy}.`,
170
- "Continue from the existing conversation state. Do not repeat completed session setup, persistent metadata settings, or context checks merely because this is a new continuation turn.",
171
- "Continue working toward the goal now. If it is actually complete, call opengeni__goal_complete with concrete evidence.",
172
- "If you are blocked or continuing is not productive, call opengeni__goal_pause with your rationale.",
173
- "Record concrete progress with opengeni__goal_progress. Revise the goal only when explicit user direction or material new evidence justifies the declared change kind; use opengeni__goal_update with this objective revision and a rationale. A rewrite alone is not progress. Do not stop without goal_complete, goal_pause, or concrete continued work.",
203
+ "Continue working toward the active session goal.",
204
+ "",
205
+ "Continuation behavior:",
206
+ "- This goal persists across turns. Ending this turn does not require shrinking the objective to what fits now.",
207
+ "- Keep the full objective intact. If it cannot be finished now, make concrete progress toward the real requested end state, leave the goal active, and do not redefine success around a smaller or easier task.",
208
+ "- Temporary rough edges are acceptable while the work is moving in the right direction. Completion still requires the requested end state to be true and verified.",
209
+ "",
210
+ "Work from evidence:",
211
+ "Use the current workspace and external state as authoritative. Previous conversation context can help locate relevant work, but inspect the current state before relying on it. Improve, replace, or remove existing work as needed to satisfy the actual objective.",
212
+ "",
213
+ "Progress visibility:",
214
+ "If a planning tool is available and the next work is meaningfully multi-step, use it to show a concise plan tied to the real objective. Keep the plan current as steps complete or the next best action changes. Skip planning overhead for trivial one-step progress, and do not treat a plan update as a substitute for doing the work.",
215
+ "",
216
+ "Fidelity:",
217
+ "- Optimize each turn for movement toward the requested end state, not for the smallest stable-looking subset or easiest passing change.",
218
+ "- Do not substitute a narrower, safer, smaller, merely compatible, or easier-to-test solution because it is more likely to pass current tests.",
219
+ "- Treat alignment as movement toward the requested end state. An edit is aligned only if it makes the requested final state more true; useful-looking behavior that preserves a different end state is misaligned.",
220
+ "",
221
+ "Completion audit:",
222
+ "Before deciding that the goal is achieved, treat completion as unproven and verify it against the actual current state:",
223
+ "- Derive concrete requirements from the objective and any referenced files, plans, specifications, issues, or user instructions.",
224
+ "- Preserve the original scope; do not redefine success around the work that already exists.",
225
+ "- For every explicit requirement, named artifact, command, test, gate, invariant, and deliverable, identify and inspect the authoritative evidence that would prove it.",
226
+ "- Match verification scope to requirement scope. Treat uncertain, indirect, incomplete, or missing evidence as not achieved and continue working.",
227
+ "- The audit must prove completion, not merely fail to find obvious remaining work.",
228
+ "",
229
+ "Do not rely on intent, partial progress, memory of earlier work, or a plausible final answer as proof of completion. Call opengeni__goal_complete with concrete evidence only when the full objective is actually achieved and no required work remains.",
230
+ "",
231
+ ...waitingGuidance,
232
+ ...childNoticeGuidance,
233
+ "Blocked audit:",
234
+ "- Do not call opengeni__goal_pause the first time a blocker appears.",
235
+ "- Pause only when the same blocking condition has repeated for at least three consecutive goal turns and meaningful progress is impossible without user input or an external-state change.",
236
+ "- Do not pause merely because the work is hard, slow, uncertain, incomplete, or would benefit from clarification.",
237
+ "- Once that threshold is satisfied, call opengeni__goal_pause with the concrete blocker instead of repeatedly reporting it while leaving the goal active.",
238
+ "",
239
+ "Do not call opengeni__goal_complete or opengeni__goal_pause unless the corresponding audit above is satisfied.",
174
240
  ].join("\n");
175
241
  }
176
242