@opengeni/worker-bundle 1.0.1 → 2.0.0-canary.35625901699001

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 (125) hide show
  1. package/dist/activities/agent-turn/agent-build.d.ts +1 -0
  2. package/dist/activities/agent-turn/codex.d.ts +1 -1
  3. package/dist/activities/agent-turn/compaction-prep.d.ts +1 -5
  4. package/dist/activities/agent-turn/errors.d.ts +31 -5
  5. package/dist/activities/agent-turn/finalization-monitor.d.ts +17 -0
  6. package/dist/activities/agent-turn/finalization.d.ts +1 -1
  7. package/dist/activities/agent-turn/governance-model.d.ts +0 -2
  8. package/dist/activities/agent-turn/quiescence.d.ts +1 -0
  9. package/dist/activities/agent-turn/recovery-warning.d.ts +8 -0
  10. package/dist/activities/agent-turn/run-credentials.d.ts +0 -1
  11. package/dist/activities/agent-turn/sandbox-establish.d.ts +1 -1
  12. package/dist/activities/agent-turn/sandbox-route.d.ts +0 -20
  13. package/dist/activities/agent-turn/sandbox-runtime.d.ts +1 -1
  14. package/dist/activities/agent-turn/skill-remove.d.ts +14 -0
  15. package/dist/activities/agent-turn/skill-search.d.ts +1 -1
  16. package/dist/activities/agent-turn/stream-attempt.d.ts +1 -0
  17. package/dist/activities/agent-turn/tool-environment.d.ts +34 -4
  18. package/dist/activities/agent-turn/turn-context.d.ts +2 -0
  19. package/dist/activities/agent-turn/turn-sandbox-access.d.ts +3 -0
  20. package/dist/activities/codemode-dispatcher.d.ts +3 -1
  21. package/dist/activities/codex-capacity.d.ts +6 -1
  22. package/dist/activities/codex-rotation.d.ts +1 -1
  23. package/dist/activities/context-compaction.d.ts +7 -1
  24. package/dist/activities/mcp-account-routes.d.ts +22 -0
  25. package/dist/activities/mcp-credentials.d.ts +12 -13
  26. package/dist/activities/mcp-operation-authority.d.ts +0 -5
  27. package/dist/activities/rig-verification.d.ts +2 -3
  28. package/dist/activities/sandbox-images.d.ts +1 -1
  29. package/dist/activities/sandbox-lease.d.ts +4 -3
  30. package/dist/activities/session-state.d.ts +57 -2
  31. package/dist/activities/types.d.ts +12 -3
  32. package/dist/{activities-control-HMFGSKC5.js → activities-control-BOLIY3H4.js} +366 -187
  33. package/dist/activities-control-BOLIY3H4.js.map +1 -0
  34. package/dist/activities-control.d.ts +110 -2
  35. package/dist/{activities-turn-AP67JADS.js → activities-turn-UCFKWOAA.js} +797 -476
  36. package/dist/activities-turn-UCFKWOAA.js.map +1 -0
  37. package/dist/activities.d.ts +110 -2
  38. package/dist/artifact-materializer-entry.js +5 -2
  39. package/dist/artifact-materializer-entry.js.map +1 -1
  40. package/dist/artifact-outbox-entry.js +2 -2
  41. package/dist/artifact-outbox-entry.js.map +1 -1
  42. package/dist/{chunk-A4XQWVZK.js → chunk-I7HKKMUJ.js} +77 -1
  43. package/dist/chunk-I7HKKMUJ.js.map +1 -0
  44. package/dist/{chunk-CYITU5UH.js → chunk-TVEE2UUC.js} +275 -146
  45. package/dist/chunk-TVEE2UUC.js.map +1 -0
  46. package/dist/editable-artifact-materializer-service.d.ts +2 -2
  47. package/dist/editable-artifact-outbox-service.d.ts +2 -2
  48. package/dist/index.d.ts +55 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/observability-metrics.d.ts +11 -3
  52. package/dist/retained-process-diagnostics.d.ts +4 -0
  53. package/dist/sandbox-resume.d.ts +2 -12
  54. package/dist/sandbox-routing.d.ts +5 -3
  55. package/dist/sandbox-snapshot-diagnostics.d.ts +20 -0
  56. package/dist/warm-capture-holder.d.ts +3 -0
  57. package/dist/workflow-bundle.js +51 -11
  58. package/package.json +19 -19
  59. package/src/activities/agent-turn/agent-build.ts +47 -6
  60. package/src/activities/agent-turn/claim.ts +12 -0
  61. package/src/activities/agent-turn/codex-capacity.ts +26 -4
  62. package/src/activities/agent-turn/codex.ts +6 -2
  63. package/src/activities/agent-turn/compaction-prep.ts +53 -72
  64. package/src/activities/agent-turn/errors.ts +98 -10
  65. package/src/activities/agent-turn/failure-settlement.ts +49 -28
  66. package/src/activities/agent-turn/finalization-monitor.ts +121 -0
  67. package/src/activities/agent-turn/finalization.ts +79 -21
  68. package/src/activities/agent-turn/governance-model.ts +15 -19
  69. package/src/activities/agent-turn/history.ts +24 -10
  70. package/src/activities/agent-turn/quiescence.ts +3 -0
  71. package/src/activities/agent-turn/recovery-warning.ts +18 -0
  72. package/src/activities/agent-turn/run-credentials.ts +3 -7
  73. package/src/activities/agent-turn/run.ts +69 -52
  74. package/src/activities/agent-turn/sandbox-establish.ts +10 -2
  75. package/src/activities/agent-turn/sandbox-route.ts +0 -20
  76. package/src/activities/agent-turn/sandbox-runtime.ts +40 -7
  77. package/src/activities/agent-turn/skill-remove.ts +46 -0
  78. package/src/activities/agent-turn/skill-save.ts +1 -1
  79. package/src/activities/agent-turn/skill-search.ts +1 -1
  80. package/src/activities/agent-turn/skill-selection.ts +2 -0
  81. package/src/activities/agent-turn/skill-tools.ts +10 -5
  82. package/src/activities/agent-turn/stream-attempt.ts +52 -16
  83. package/src/activities/agent-turn/tool-environment.ts +49 -29
  84. package/src/activities/agent-turn/turn-context.ts +3 -0
  85. package/src/activities/agent-turn/turn-sandbox-access.ts +7 -1
  86. package/src/activities/capabilities.ts +17 -2
  87. package/src/activities/codemode-dispatcher.ts +6 -0
  88. package/src/activities/codex-capacity.ts +38 -9
  89. package/src/activities/codex-rotation.ts +18 -5
  90. package/src/activities/context-compaction.ts +26 -4
  91. package/src/activities/goals.ts +1 -0
  92. package/src/activities/google-drive-publication.ts +1 -3
  93. package/src/activities/mcp-account-routes.ts +139 -0
  94. package/src/activities/mcp-credentials.ts +83 -194
  95. package/src/activities/mcp-operation-authority.ts +16 -41
  96. package/src/activities/parent-wake.ts +8 -0
  97. package/src/activities/rig-verification.ts +38 -37
  98. package/src/activities/run-input.ts +25 -16
  99. package/src/activities/sandbox-images.ts +0 -1
  100. package/src/activities/sandbox-lease.ts +177 -44
  101. package/src/activities/scheduled-tasks.ts +118 -93
  102. package/src/activities/session-state.ts +83 -3
  103. package/src/activities/types.ts +18 -2
  104. package/src/activities/workflow-wake.ts +2 -17
  105. package/src/editable-artifact-materializer-service.ts +7 -3
  106. package/src/editable-artifact-outbox-service.ts +4 -4
  107. package/src/github-rest-mcp.ts +0 -1
  108. package/src/index.ts +2 -1
  109. package/src/observability-metrics.ts +105 -2
  110. package/src/personal-github-git-credentials.ts +0 -1
  111. package/src/pr-review-credentials.ts +0 -2
  112. package/src/retained-process-diagnostics.ts +50 -0
  113. package/src/sandbox-resume.ts +58 -73
  114. package/src/sandbox-routing.ts +44 -19
  115. package/src/sandbox-snapshot-diagnostics.ts +112 -0
  116. package/src/warm-capture-holder.ts +15 -0
  117. package/src/workflows/session.ts +64 -2
  118. package/dist/activities/agent-turn/knowledge-sources.d.ts +0 -20
  119. package/dist/activities/packs.d.ts +0 -55
  120. package/dist/activities-control-HMFGSKC5.js.map +0 -1
  121. package/dist/activities-turn-AP67JADS.js.map +0 -1
  122. package/dist/chunk-A4XQWVZK.js.map +0 -1
  123. package/dist/chunk-CYITU5UH.js.map +0 -1
  124. package/src/activities/agent-turn/knowledge-sources.ts +0 -86
  125. package/src/activities/packs.ts +0 -166
@@ -1,4 +1,5 @@
1
1
  import {
2
+ connectionModelAllowed,
2
3
  armCodexCapacityWait,
3
4
  fetchCodexUsageForAccount,
4
5
  getCodexCapacityWaitForSession,
@@ -90,8 +91,15 @@ export async function signalPendingCodexCapacityWakeTargets(
90
91
 
91
92
  export function codexCapacityDecision<TPolicyScope = never, TUnavailableDiagnostic = never>(
92
93
  context: CodexCapacitySelectionContext<TPolicyScope, TUnavailableDiagnostic>,
94
+ now = new Date(),
93
95
  ): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]> {
94
- const now = new Date();
96
+ context = {
97
+ ...context,
98
+ accounts: context.accounts.filter(
99
+ (account) =>
100
+ !context.modelId || connectionModelAllowed(account.allowedModelIds, context.modelId),
101
+ ),
102
+ };
95
103
  const selected = selectCodexCredentialLeaseForTurn({
96
104
  context,
97
105
  sessionId: context.sessionId,
@@ -114,8 +122,12 @@ export function codexCapacityDecision<TPolicyScope = never, TUnavailableDiagnost
114
122
  credentialId: selected.credentialId,
115
123
  diagnostic: {
116
124
  connectedCount: context.accounts.length,
117
- eligibleCount: context.accounts.filter((account) => isCodexCredentialEligible(account, now))
118
- .length,
125
+ eligibleCount: context.accounts.filter(
126
+ (account) =>
127
+ (account.id === selected.credentialId ||
128
+ !context.failedCredentialIds?.includes(account.id)) &&
129
+ isCodexCredentialEligible(account, now),
130
+ ).length,
119
131
  },
120
132
  };
121
133
  }
@@ -134,8 +146,7 @@ export function codexCapacityDecision<TPolicyScope = never, TUnavailableDiagnost
134
146
  account.status === "active" &&
135
147
  account.allocatorEnabled &&
136
148
  account.exhaustedKind === "quota" &&
137
- account.exhaustedUntil !== null &&
138
- account.exhaustedUntil > now,
149
+ account.exhaustedUntil !== null,
139
150
  );
140
151
  const policyAccount = capacityAccounts[0] ?? null;
141
152
  const mutationOnlyStatusBlock =
@@ -162,7 +173,7 @@ export function codexCapacityDecision<TPolicyScope = never, TUnavailableDiagnost
162
173
  kind: "unavailable",
163
174
  earliestResetAt: authoritativeReset,
164
175
  resetKind:
165
- selected.decision.kind === "none" ||
176
+ (selected.decision.kind === "none" && !hasReconcilableQuotaCooldown && !authoritativeReset) ||
166
177
  selected.decision.kind === "allocatorDisabled" ||
167
178
  mutationOnlyStatusBlock
168
179
  ? "mutation_only"
@@ -191,6 +202,16 @@ export async function armAndReconcileCodexCapacityWait(
191
202
  options: { onArmed?: () => void } = {},
192
203
  ) {
193
204
  const armed = await armCodexCapacityWait(services.db, input);
205
+ if (armed.action === "stopped") {
206
+ options.onArmed?.();
207
+ await publishDurableSessionEvents(
208
+ services.bus,
209
+ input.workspaceId,
210
+ input.sessionId,
211
+ armed.events,
212
+ );
213
+ return armed;
214
+ }
194
215
  if (armed.action !== "waiting") return armed;
195
216
 
196
217
  options.onArmed?.();
@@ -219,8 +240,9 @@ export async function armAndReconcileCodexCapacityWait(
219
240
  async function refreshCapacityMetadata(
220
241
  services: ControlActivityServices,
221
242
  workspaceId: string,
243
+ turnId: string,
222
244
  ): Promise<void> {
223
- const accounts = await listCodexAccountStatuses(services.db, workspaceId).catch(() => []);
245
+ const accounts = await listCodexAccountStatuses(services.db, workspaceId, turnId).catch(() => []);
224
246
  const now = new Date();
225
247
  const stale = accounts.filter(
226
248
  (account) =>
@@ -231,7 +253,14 @@ async function refreshCapacityMetadata(
231
253
  await refreshCodexUsageAndRepairCapacityWaiters(
232
254
  stale.map(
233
255
  (account) => () =>
234
- fetchCodexUsageForAccount(services.db, services.settings, workspaceId, account.id),
256
+ fetchCodexUsageForAccount(
257
+ services.db,
258
+ services.settings,
259
+ workspaceId,
260
+ account.id,
261
+ undefined,
262
+ turnId,
263
+ ),
235
264
  ),
236
265
  () => signalPendingCodexCapacityWakeTargets(services, workspaceId),
237
266
  );
@@ -338,7 +367,7 @@ export function createCodexCapacityActivities(services: () => Promise<ControlAct
338
367
  if (boundedRefreshAttempted) {
339
368
  // This is a bounded secret-safe control-plane quota refresh. It creates no
340
369
  // turn, model call, user message, schedule, or entitlement action.
341
- await refreshCapacityMetadata(resolved, input.workspaceId);
370
+ await refreshCapacityMetadata(resolved, input.workspaceId, current.blockedTurnId);
342
371
  }
343
372
  const result = await reconcileCodexCapacityWaitDb(
344
373
  resolved.db,
@@ -12,6 +12,7 @@ import type {
12
12
  CodexLeaseAccountStatus,
13
13
  CodexPinSource,
14
14
  } from "@opengeni/db";
15
+ import { connectionModelAllowed } from "@opengeni/db";
15
16
 
16
17
  export type CodexRotationAccount = CodexAccountStatus | CodexLeaseAccountStatus;
17
18
 
@@ -21,14 +22,12 @@ export function codexAccountNeedsLiveCapacityRefresh(
21
22
  CodexAccountStatus,
22
23
  "primaryUsedPercent" | "secondaryUsedPercent" | "exhaustedUntil" | "exhaustedKind"
23
24
  >,
24
- now: Date,
25
+ _now: Date,
25
26
  ): boolean {
26
27
  return (
27
28
  (account.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||
28
29
  (account.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||
29
- (account.exhaustedKind === "quota" &&
30
- account.exhaustedUntil !== null &&
31
- account.exhaustedUntil > now)
30
+ (account.exhaustedKind === "quota" && account.exhaustedUntil !== null)
32
31
  );
33
32
  }
34
33
 
@@ -524,8 +523,16 @@ export function selectCodexCredentialLeaseForTurn<
524
523
  sessionLastCredentialId: string | null;
525
524
  now: Date;
526
525
  }): CodexTurnLeaseSelection {
527
- const { accounts, activeCredentialId, rotationEnabled, rotationStrategy, existingCredentialId } =
526
+ const { activeCredentialId, rotationEnabled, rotationStrategy, existingCredentialId } =
528
527
  args.context;
528
+ if (args.context.failoverExhausted) {
529
+ return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
530
+ }
531
+ const accounts = args.context.modelId
532
+ ? args.context.accounts.filter((account) =>
533
+ connectionModelAllowed(account.allowedModelIds, args.context.modelId!),
534
+ )
535
+ : args.context.accounts;
529
536
  const failedCredentialIds = new Set(args.context.failedCredentialIds ?? []);
530
537
  // Normalized: rotation-enabled always behaves as sharded (see
531
538
  // effectiveRotationStrategy); the stored value is only ever legacy residue.
@@ -564,6 +571,9 @@ export function selectCodexCredentialLeaseForTurn<
564
571
  if (!pinned) {
565
572
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
566
573
  }
574
+ if (failedCredentialIds.has(pinned.id)) {
575
+ return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
576
+ }
567
577
  if (!pinned.allocatorEnabled) {
568
578
  return {
569
579
  credentialId: null,
@@ -633,6 +643,9 @@ export function selectCodexCredentialLeaseForTurn<
633
643
  if (!active) {
634
644
  return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
635
645
  }
646
+ if (failedCredentialIds.has(active.id)) {
647
+ return { credentialId: null, decision: { kind: "none" }, advanceActivePointer: false };
648
+ }
636
649
  if (!active.allocatorEnabled) {
637
650
  return {
638
651
  credentialId: null,
@@ -1,3 +1,4 @@
1
+ import { readReasoningConfiguration } from "@opengeni/codex";
1
2
  import {
2
3
  applyContextCompaction,
3
4
  getActiveSessionHistoryItemsPaged,
@@ -21,6 +22,7 @@ import {
21
22
  sanitizeHistoryItemsForModel,
22
23
  summarizeForCompaction,
23
24
  type CompactionItem,
25
+ type CompactionProviderRejection,
24
26
  } from "@opengeni/runtime";
25
27
  import { contextInputBudgetTokens, type Settings } from "@opengeni/config";
26
28
  import type { SessionEvent } from "@opengeni/contracts";
@@ -260,6 +262,12 @@ export async function settleFailedContextCompactionLandmark(
260
262
  options: {
261
263
  clearRequestedCompaction?: boolean;
262
264
  publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;
265
+ /**
266
+ * Closed identifier record of a definitive provider rejection. Carried on
267
+ * the visible `compaction.skipped` landmark so the timeline can name the
268
+ * rejected field instead of offering a retry that cannot succeed.
269
+ */
270
+ providerRejection?: CompactionProviderRejection | null;
263
271
  } = {},
264
272
  ): Promise<Extract<MaybeCompactResult, { compacted: false }>> {
265
273
  const settled = await settleSkippedAfterStart(db, scope, options, "summarization_failed");
@@ -287,6 +295,7 @@ async function settleSkippedAfterStart(
287
295
  },
288
296
  options: {
289
297
  clearRequestedCompaction?: boolean;
298
+ providerRejection?: CompactionProviderRejection | null;
290
299
  },
291
300
  reason:
292
301
  | "no_history"
@@ -304,6 +313,7 @@ async function settleSkippedAfterStart(
304
313
  // an operator `/compact` flag — auto/overflow never set one.
305
314
  requirePendingRequest: false,
306
315
  clearRequestedCompaction,
316
+ ...(options.providerRejection ? { providerRejection: options.providerRejection } : {}),
307
317
  });
308
318
  if (!skipped.recorded) {
309
319
  throw new TurnAttemptFencedError(
@@ -370,7 +380,10 @@ async function compactContextRemoteV2(
370
380
  );
371
381
  const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));
372
382
  const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);
373
- const tailItem = replacementHistory.at(-1);
383
+ const summaryIndex =
384
+ replacementHistory.length -
385
+ (readReasoningConfiguration(replacementHistory.at(-1) ?? {}) ? 2 : 1);
386
+ const tailItem = replacementHistory[summaryIndex];
374
387
  if (!tailItem) {
375
388
  throw new EmptyCompactionSummaryError({
376
389
  stage: "remote_v2_replacement",
@@ -384,7 +397,10 @@ async function compactContextRemoteV2(
384
397
  turnId: scope.turnId,
385
398
  expectedExecutionGeneration: scope.executionGeneration,
386
399
  expectedAttemptId: scope.attemptId,
387
- replacementItems: replacementHistory.slice(0, -1),
400
+ replacementItems: replacementHistory.slice(0, summaryIndex),
401
+ ...(replacementHistory.length > summaryIndex + 1
402
+ ? { trailingItems: replacementHistory.slice(summaryIndex + 1) }
403
+ : {}),
388
404
  summaryItem: tailItem as Record<string, unknown>,
389
405
  ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),
390
406
  eventPayload: {
@@ -447,7 +463,10 @@ async function compactContextPortable(
447
463
  const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));
448
464
  const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);
449
465
  const previousReplacementFingerprint = latestCompactionReplacementFingerprint(canonicalItems);
450
- const summaryItem = replacementHistory.at(-1);
466
+ const summaryIndex =
467
+ replacementHistory.length -
468
+ (readReasoningConfiguration(replacementHistory.at(-1) ?? {}) ? 2 : 1);
469
+ const summaryItem = replacementHistory[summaryIndex];
451
470
  if (!summaryItem) {
452
471
  // Started already fanout; settle visibly so the landmark cannot stick on
453
472
  // "Compacting…". This is not an operator-request clear path.
@@ -466,7 +485,10 @@ async function compactContextPortable(
466
485
  turnId: scope.turnId,
467
486
  expectedExecutionGeneration: scope.executionGeneration,
468
487
  expectedAttemptId: scope.attemptId,
469
- replacementItems: replacementHistory.slice(0, -1),
488
+ replacementItems: replacementHistory.slice(0, summaryIndex),
489
+ ...(replacementHistory.length > summaryIndex + 1
490
+ ? { trailingItems: replacementHistory.slice(summaryIndex + 1) }
491
+ : {}),
470
492
  summaryItem: summaryItem as Record<string, unknown>,
471
493
  ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),
472
494
  eventPayload: {
@@ -308,6 +308,7 @@ export function goalContinuationPrompt(
308
308
  "- For every explicit requirement, named artifact, command, test, gate, invariant, and deliverable, identify and inspect the authoritative evidence that would prove it.",
309
309
  "- Match verification scope to requirement scope. Treat uncertain, indirect, incomplete, or missing evidence as not achieved and continue working.",
310
310
  "- The audit must prove completion, not merely fail to find obvious remaining work.",
311
+ "- For user-facing report deliverables, including reports produced during another task, follow the Documents Skill: create the durable native document first, inspect its relevant final head after the last edit, and provide the returned artifact reference. Declare report requirements through the available goal tools before authoring and satisfy every persisted report requirement with verified artifact delivery evidence before completion. Sandbox paths and raw file IDs do not prove report delivery. If artifact tooling or access is unavailable, keep that deliverable incomplete and state the blocker; never invent proof or silently substitute a local report. Ordinary chat answers, short progress updates, source-code links, and explicitly requested local-file work remain outside this report contract.",
311
312
  "",
312
313
  "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.",
313
314
  "",
@@ -90,9 +90,7 @@ export async function resolveGoogleDrivePublicationTarget(
90
90
  );
91
91
  if (frozen.length !== 1) return null;
92
92
  const delegation = frozen[0]!;
93
- const activated = delegation.userDelegation !== undefined;
94
93
  if (
95
- !activated &&
96
94
  !(await ports.getMembership(db, {
97
95
  accountId: workspace.accountId,
98
96
  workspaceId,
@@ -101,7 +99,7 @@ export async function resolveGoogleDrivePublicationTarget(
101
99
  ) {
102
100
  return null;
103
101
  }
104
- const originWorkspaceId = activated ? delegation.originWorkspaceId : workspaceId;
102
+ const originWorkspaceId = delegation.originWorkspaceId;
105
103
  if (!originWorkspaceId) return null;
106
104
  const connection = await ports.getConnection(
107
105
  db,
@@ -0,0 +1,139 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import type {
3
+ McpConnectionAccountBinding,
4
+ ToolRef,
5
+ ToolAuthNeededPayload,
6
+ } from "@opengeni/contracts";
7
+ import type { ApiIntegrationRuntime } from "@opengeni/db";
8
+
9
+ export function accountRouteAuthNeededPayload(
10
+ payload: ToolAuthNeededPayload,
11
+ bindings: readonly McpConnectionAccountBinding[] | null | undefined,
12
+ ): ToolAuthNeededPayload {
13
+ const binding = bindings?.find((candidate) => candidate.serverId === payload.serverId);
14
+ return binding
15
+ ? {
16
+ ...payload,
17
+ canonicalServerId: binding.canonicalServerId,
18
+ connectionSubjectScope: binding.subjectScope,
19
+ }
20
+ : payload;
21
+ }
22
+
23
+ /** Expand only after canonical tool-policy admission. Aliases are execution
24
+ * identities, never an alternate way to gain admission to a connector. */
25
+ export function expandMcpAccountRoutes(input: {
26
+ settings: Settings;
27
+ tools: ToolRef[];
28
+ bindings: readonly McpConnectionAccountBinding[] | null | undefined;
29
+ }): { settings: Settings; tools: ToolRef[]; accountLabels: ReadonlyMap<string, string> } {
30
+ // Only historical work has no binding snapshot. A present empty snapshot is
31
+ // an explicit lack of account authority, never a request for current defaults.
32
+ if (input.bindings == null) {
33
+ return { settings: input.settings, tools: input.tools, accountLabels: new Map() };
34
+ }
35
+ const configured = new Map(input.settings.mcpServers.map((server) => [server.id, server]));
36
+ const byCanonical = new Map<string, McpConnectionAccountBinding[]>();
37
+ const routes = new Set<string>();
38
+ const accounts = new Set<string>();
39
+ for (const binding of input.bindings) {
40
+ const account = JSON.stringify([binding.canonicalServerId, binding.connectionId]);
41
+ if (
42
+ routes.has(binding.serverId) ||
43
+ accounts.has(account) ||
44
+ configured.has(binding.serverId) ||
45
+ (binding.subjectScope === "subject") !== (binding.ownerSubjectId !== null) ||
46
+ binding.connectionRef.authoritySource === "host" ||
47
+ binding.connectionRef.connectionId !== binding.connectionId ||
48
+ binding.connectionRef.subjectScope !== binding.subjectScope ||
49
+ binding.connectionRef.providerDomain !== binding.providerDomain ||
50
+ binding.connectionRef.kind !== binding.kind
51
+ ) {
52
+ throw new Error("Invalid accepted MCP account route");
53
+ }
54
+ routes.add(binding.serverId);
55
+ accounts.add(account);
56
+ const siblings = byCanonical.get(binding.canonicalServerId) ?? [];
57
+ siblings.push(binding);
58
+ byCanonical.set(binding.canonicalServerId, siblings);
59
+ }
60
+ const servers: Settings["mcpServers"] = [];
61
+ const tools: ToolRef[] = [];
62
+ const accountLabels = new Map<string, string>();
63
+ for (const tool of input.tools) {
64
+ const bindings = byCanonical.get(tool.id);
65
+ if (!bindings) {
66
+ if (!configured.get(tool.id)?.connectionRef) tools.push(tool);
67
+ continue;
68
+ }
69
+ const canonical = configured.get(tool.id);
70
+ if (!canonical?.connectionRef) {
71
+ throw new Error("Accepted MCP account route has no canonical connection configuration");
72
+ }
73
+ for (const binding of bindings) {
74
+ if (
75
+ canonical.connectionRef.authoritySource === "host" ||
76
+ canonical.connectionRef.providerDomain !== binding.providerDomain ||
77
+ (canonical.connectionRef.kind && canonical.connectionRef.kind !== binding.kind)
78
+ ) {
79
+ throw new Error("Accepted MCP account route does not match canonical provider");
80
+ }
81
+ // Static headers can belong to the formerly selected account. Credentials
82
+ // for account-qualified routes come exclusively from the native resolver.
83
+ const { headers: _headers, ...config } = canonical;
84
+ const label = `${canonical.name ?? canonical.id} — ${binding.subjectScope === "subject" ? "Personal" : "Workspace"}: ${binding.accountLabel}`;
85
+ servers.push({
86
+ ...config,
87
+ id: binding.serverId,
88
+ name: label,
89
+ connectionRef: structuredClone(binding.connectionRef),
90
+ });
91
+ tools.push({ ...tool, id: binding.serverId });
92
+ accountLabels.set(binding.serverId, label);
93
+ }
94
+ }
95
+ return {
96
+ settings: {
97
+ ...input.settings,
98
+ mcpServers: [
99
+ ...input.settings.mcpServers.filter((server) => !server.connectionRef),
100
+ ...servers,
101
+ ],
102
+ },
103
+ tools,
104
+ accountLabels,
105
+ };
106
+ }
107
+
108
+ /** Each adapter closes over its own immutable credential ref and authority
109
+ * generation. Sharing a provider transport never shares a credential resolver. */
110
+ export function expandApiIntegrationAccountRoutes(input: {
111
+ integrations: readonly ApiIntegrationRuntime[];
112
+ bindings: readonly McpConnectionAccountBinding[] | null | undefined;
113
+ tools: readonly ToolRef[];
114
+ }): ApiIntegrationRuntime[] {
115
+ const selected = new Set(input.tools.map((tool) => tool.id));
116
+ if (input.bindings == null)
117
+ return input.integrations.filter((item) => selected.has(item.serverId));
118
+ const acceptedBindings = input.bindings;
119
+ return input.integrations.flatMap((integration) => {
120
+ const bindings = acceptedBindings.filter(
121
+ (binding) => binding.canonicalServerId === integration.serverId,
122
+ );
123
+ if (bindings.length === 0)
124
+ return !integration.connectionRef && selected.has(integration.serverId) ? [integration] : [];
125
+ return bindings
126
+ .filter((binding) => selected.has(binding.serverId))
127
+ .map((binding) => {
128
+ if (binding.connectionAuthorityGeneration === undefined) {
129
+ throw new Error("Accepted API integration account route has no authority generation");
130
+ }
131
+ return {
132
+ ...integration,
133
+ serverId: binding.serverId,
134
+ connectionRef: structuredClone(binding.connectionRef),
135
+ connectionAuthorityGeneration: binding.connectionAuthorityGeneration,
136
+ };
137
+ });
138
+ });
139
+ }