@opengeni/worker-bundle 2.2.0-canary.36855269964001 → 2.2.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 (44) hide show
  1. package/dist/activities/agent-run-admission.d.ts +1 -3
  2. package/dist/activities/agent-turn/admission.d.ts +3 -24
  3. package/dist/activities/agent-turn/claude-usage-observer.d.ts +1 -13
  4. package/dist/activities/agent-turn/run-credentials.d.ts +0 -2
  5. package/dist/activities/agent-turn/stream-attempt.d.ts +0 -1
  6. package/dist/activities/agent-turn/turn-context.d.ts +0 -1
  7. package/dist/activities/goals.d.ts +0 -8
  8. package/dist/activities/run-credentials.d.ts +2 -4
  9. package/dist/activities/types.d.ts +1 -1
  10. package/dist/{activities-control-YKXRDVMB.js → activities-control-MHNA3CYV.js} +66 -28
  11. package/dist/activities-control-MHNA3CYV.js.map +1 -0
  12. package/dist/{activities-turn-V37B7CQY.js → activities-turn-FQ5OO2WW.js} +197 -540
  13. package/dist/activities-turn-FQ5OO2WW.js.map +1 -0
  14. package/dist/{chunk-ZCCLJK3V.js → chunk-RZAAGRFQ.js} +65 -145
  15. package/dist/chunk-RZAAGRFQ.js.map +1 -0
  16. package/dist/index.js +1 -1
  17. package/dist/workflow-bundle.js +1 -1
  18. package/package.json +20 -20
  19. package/src/activities/agent-run-admission.ts +1 -17
  20. package/src/activities/agent-turn/admission.ts +1 -64
  21. package/src/activities/agent-turn/claim.ts +14 -56
  22. package/src/activities/agent-turn/claude-usage-observer.ts +1 -33
  23. package/src/activities/agent-turn/errors.ts +0 -46
  24. package/src/activities/agent-turn/failure-settlement.ts +0 -5
  25. package/src/activities/agent-turn/run-credentials.ts +3 -15
  26. package/src/activities/agent-turn/run.ts +3 -32
  27. package/src/activities/agent-turn/stream-attempt.ts +35 -138
  28. package/src/activities/agent-turn/tool-environment.ts +20 -13
  29. package/src/activities/agent-turn/turn-context.ts +0 -1
  30. package/src/activities/capabilities.ts +14 -52
  31. package/src/activities/goals.ts +78 -38
  32. package/src/activities/knowledge-indexing.ts +0 -29
  33. package/src/activities/run-credentials.ts +16 -22
  34. package/src/activities/scheduled-tasks.ts +0 -1
  35. package/src/activities/types.ts +0 -1
  36. package/src/activities/workspace-credential-provider.ts +0 -12
  37. package/src/sandbox-routing.ts +2 -4
  38. package/dist/activities/agent-turn/final-reply.d.ts +0 -18
  39. package/dist/activities/agent-turn/model-call-admission.d.ts +0 -15
  40. package/dist/activities-control-YKXRDVMB.js.map +0 -1
  41. package/dist/activities-turn-V37B7CQY.js.map +0 -1
  42. package/dist/chunk-ZCCLJK3V.js.map +0 -1
  43. package/src/activities/agent-turn/final-reply.ts +0 -46
  44. package/src/activities/agent-turn/model-call-admission.ts +0 -94
@@ -94,7 +94,7 @@ import {
94
94
  withFirstPartyTools,
95
95
  wrapLazyTurnBoxWithRouting,
96
96
  wrapTurnBoxWithRouting
97
- } from "./chunk-ZCCLJK3V.js";
97
+ } from "./chunk-RZAAGRFQ.js";
98
98
  import {
99
99
  StreamTimingMetrics,
100
100
  makeMachineOpObserver,
@@ -139,12 +139,10 @@ import {
139
139
  getSessionAuthorityProjection,
140
140
  readActiveSandbox as readActiveSandbox3,
141
141
  getWorkspaceCredentialProvider,
142
- loadClaudeSubscriptionUsageCredential as loadClaudeSubscriptionUsageCredential2,
143
- resolveClaudeSubscriptionCredential,
144
- ClaudeSubscriptionReconnectRequired
142
+ loadClaudeSubscriptionUsageCredential
145
143
  } from "@opengeni/db";
146
144
  import {
147
- assertModelConnectionAllowsTurn as assertModelConnectionAllowsTurn2,
145
+ assertModelConnectionAllowsTurn,
148
146
  freezeAgentLearningPolicy as freezeAgentLearningPolicy2,
149
147
  recoverLegacyKnowledgeConfirmations,
150
148
  withSessionRlsActorContext
@@ -163,7 +161,6 @@ import {
163
161
  import {
164
162
  REMOTE_COMPACTION_V2_BETA_FEATURE,
165
163
  REMOTE_COMPACTION_V2_IMPLEMENTATION as REMOTE_COMPACTION_V2_IMPLEMENTATION2,
166
- awaitModelCallAdmission,
167
164
  materializeSandboxFileDownloads as materializeSandboxFileDownloads3,
168
165
  sandboxFileDownloadFailureNote
169
166
  } from "@opengeni/runtime";
@@ -194,17 +191,6 @@ async function createClaudeUsageObserver(providers, latest, readCredential) {
194
191
  (provider) => provider.kind === "claude-subscription-workspace" || provider.kind === "claude-subscription-organization"
195
192
  ).map(async (provider) => {
196
193
  const scope = provider.kind === "claude-subscription-workspace" ? "workspace" : "organization";
197
- const binding = provider.anthropic?.credentialBinding;
198
- if (binding && provider.apiKey)
199
- return [
200
- provider.id,
201
- {
202
- scope,
203
- token: provider.apiKey,
204
- expectedConnectionId: binding.connectionId,
205
- expectedCredentialVersion: binding.credentialVersion
206
- }
207
- ];
208
194
  const credential = await readCredential(scope).catch(() => null);
209
195
  if (!credential || credential.token !== provider.apiKey) return null;
210
196
  return [
@@ -219,7 +205,7 @@ async function createClaudeUsageObserver(providers, latest, readCredential) {
219
205
  })
220
206
  );
221
207
  const captured = new Map(bindings.filter((binding) => binding !== null));
222
- const observe2 = (providerId, response) => {
208
+ return (providerId, response) => {
223
209
  const binding = captured.get(providerId);
224
210
  if (!binding) return;
225
211
  const { scope, ...identity } = binding;
@@ -244,16 +230,6 @@ async function createClaudeUsageObserver(providers, latest, readCredential) {
244
230
  ...response.status === 401 ? { refresh: { status: "reconnect", checkedAt: (/* @__PURE__ */ new Date()).toISOString() } } : {}
245
231
  });
246
232
  };
247
- return Object.assign(observe2, {
248
- binding(providerId) {
249
- return captured.get(providerId);
250
- },
251
- renew(providerId, credential) {
252
- const binding = captured.get(providerId);
253
- if (binding && binding.expectedConnectionId === credential.connectionId && binding.expectedCredentialVersion === credential.credentialVersion)
254
- captured.set(providerId, { ...binding, token: credential.token });
255
- }
256
- });
257
233
  }
258
234
 
259
235
  // src/activities/agent-turn/run.ts
@@ -5280,7 +5256,7 @@ import {
5280
5256
  } from "@opengeni/codex";
5281
5257
 
5282
5258
  // src/activities/agent-turn/admission.ts
5283
- import { checkWorkspaceAllowance, getBillingBalance, sumUsageQuantity } from "@opengeni/db";
5259
+ import { getBillingBalance, sumUsageQuantity } from "@opengeni/db";
5284
5260
  import {
5285
5261
  configuredStaticUsageLimits
5286
5262
  } from "@opengeni/config";
@@ -5925,48 +5901,13 @@ function stableInteractionInterventionUuid(namespace, sessionId, turnId, toolCal
5925
5901
  return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
5926
5902
  }
5927
5903
  var BudgetExhaustedError = class extends Error {
5928
- constructor(message, serializedRunState, allowance = null) {
5904
+ constructor(message, serializedRunState) {
5929
5905
  super(message);
5930
5906
  this.serializedRunState = serializedRunState;
5931
- this.allowance = allowance;
5932
5907
  this.name = "BudgetExhaustedError";
5933
5908
  }
5934
5909
  };
5935
- var AllowanceExhaustedError = class extends Error {
5936
- constructor(refusal) {
5937
- super(refusal.message);
5938
- this.refusal = refusal;
5939
- this.name = "AllowanceExhaustedError";
5940
- }
5941
- code = "allowance_exhausted";
5942
- };
5943
- async function ensureRunAllowedBetweenModelCalls(input) {
5944
- try {
5945
- await ensureRunAllowed(
5946
- input.settings,
5947
- input.db,
5948
- input.accountId,
5949
- input.workspaceId,
5950
- input.isExternallyBilledTurn,
5951
- input.entitlements,
5952
- input.chargesOpenGeniCredits,
5953
- input.countsTowardTokenCap,
5954
- input.initiatingHumanSubjectId
5955
- );
5956
- } catch (limitError) {
5957
- let serializedRunState = null;
5958
- try {
5959
- serializedRunState = input.serializedRunState?.() ?? null;
5960
- } catch {
5961
- }
5962
- throw new BudgetExhaustedError(
5963
- limitError instanceof Error ? limitError.message : String(limitError),
5964
- serializedRunState,
5965
- limitError instanceof AllowanceExhaustedError ? limitError.refusal : null
5966
- );
5967
- }
5968
- }
5969
- async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternallyBilledTurn, entitlements, chargesOpenGeniCredits = !isExternallyBilledTurn, countsTowardTokenCap = !isExternallyBilledTurn, initiatingHumanSubjectId = null) {
5910
+ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternallyBilledTurn, entitlements, chargesOpenGeniCredits = !isExternallyBilledTurn, countsTowardTokenCap = !isExternallyBilledTurn) {
5970
5911
  if (chargesOpenGeniCredits && entitlements && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5971
5912
  const decision = await entitlements.admitRun({
5972
5913
  accountId,
@@ -5983,14 +5924,6 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
5983
5924
  throw new Error("insufficient OpenGeni credits");
5984
5925
  }
5985
5926
  }
5986
- if (chargesOpenGeniCredits) {
5987
- const refusal = await checkWorkspaceAllowance(db, {
5988
- accountId,
5989
- workspaceId,
5990
- subjectId: initiatingHumanSubjectId
5991
- });
5992
- if (refusal) throw new AllowanceExhaustedError(refusal);
5993
- }
5994
5927
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
5995
5928
  const limits = configuredStaticUsageLimits(settings);
5996
5929
  if (limits.maxMonthlyAgentRunsPerWorkspace) {
@@ -7065,22 +6998,19 @@ async function settleTurnFailure(deps) {
7065
6998
  await historySink.reconcileConversationTruth();
7066
6999
  if (!await eventing.settle({
7067
7000
  events: [
7068
- ...error51.allowance ? [{ type: "usage.exhausted", payload: error51.allowance }] : [],
7069
7001
  {
7070
7002
  type: "turn.completed",
7071
7003
  payload: {
7072
7004
  output: "",
7073
7005
  segmentLimit: "budget_exhausted",
7074
- detail: error51.message,
7075
- ...error51.allowance ?? {}
7006
+ detail: error51.message
7076
7007
  }
7077
7008
  },
7078
7009
  { type: "session.status.changed", payload: { status: "idle" } }
7079
7010
  ],
7080
7011
  turnStatus: "completed",
7081
7012
  sessionStatus: "idle",
7082
- activeTurnId: null,
7083
- ...error51.allowance ? { allowanceGoalPause: { rationale: error51.allowance.message } } : {}
7013
+ activeTurnId: null
7084
7014
  })) {
7085
7015
  return claimedResult({ status: "cancelled" });
7086
7016
  }
@@ -7286,9 +7216,6 @@ async function settleTurnFailure(deps) {
7286
7216
  // src/activities/agent-turn/stream-attempt.ts
7287
7217
  import { measureMcpPhase, withMcpCallIdentity } from "@opengeni/observability";
7288
7218
  import {
7289
- appendSessionHistoryItems as appendSessionHistoryItems3,
7290
- sessionTurnFinalReplyFacts,
7291
- sessionTurnHasFinalReplyNudge,
7292
7219
  getSessionHumanInputRequest,
7293
7220
  getWorkspace,
7294
7221
  recordUsageEvent as recordUsageEvent3,
@@ -8045,81 +7972,6 @@ import {
8045
7972
  resolveWorkspaceAgentHumanInputEnabled
8046
7973
  } from "@opengeni/contracts";
8047
7974
 
8048
- // src/activities/agent-turn/model-call-admission.ts
8049
- function createModelCallAdmission(input) {
8050
- const receipts = /* @__PURE__ */ new WeakMap();
8051
- const responseReceipts = /* @__PURE__ */ new Map();
8052
- const pending = /* @__PURE__ */ new Set();
8053
- const responseId = (event) => {
8054
- const id = event?.response?.id;
8055
- return typeof id === "string" && id.length > 0 ? id : null;
8056
- };
8057
- let latest = Promise.resolve();
8058
- let failure2;
8059
- let failed = false;
8060
- let rejectHalted;
8061
- const halted = new Promise((_, reject) => {
8062
- rejectHalted = reject;
8063
- });
8064
- void halted.catch(() => void 0);
8065
- const fail = (error51) => {
8066
- if (failed) return;
8067
- failed = true;
8068
- failure2 = error51;
8069
- rejectHalted(error51);
8070
- for (const receipt of pending) receipt.reject(error51);
8071
- pending.clear();
8072
- responseReceipts.clear();
8073
- };
8074
- const abort = () => fail(input.signal.reason ?? new Error("Model stream cancelled"));
8075
- input.signal.addEventListener("abort", abort, { once: true });
8076
- if (input.signal.aborted) abort();
8077
- return {
8078
- beforeModelRequest: async () => {
8079
- await Promise.race([latest, halted]);
8080
- if (failed) throw failure2;
8081
- await Promise.race([input.admit(), halted]);
8082
- if (failed) throw failure2;
8083
- },
8084
- onModelResponse: (event) => {
8085
- if (failed) return Promise.reject(failure2);
8086
- const id = responseId(event);
8087
- const existing = receipts.get(event) ?? (id ? responseReceipts.get(id) : void 0) ?? (!id && pending.size === 1 ? pending.values().next().value : void 0);
8088
- if (existing) return existing.promise;
8089
- let resolve;
8090
- let reject;
8091
- const promise2 = new Promise((yes, no) => {
8092
- resolve = yes;
8093
- reject = no;
8094
- });
8095
- void promise2.catch(() => void 0);
8096
- const receipt = { promise: promise2, resolve, reject };
8097
- receipts.set(event, receipt);
8098
- if (id) responseReceipts.set(id, receipt);
8099
- pending.add(receipt);
8100
- latest = promise2;
8101
- return promise2;
8102
- },
8103
- settle: (event) => {
8104
- if (event.type !== "raw_model_stream_event" || !event.data || typeof event.data !== "object")
8105
- return;
8106
- if (event.data.type !== "response_done") return;
8107
- const id = responseId(event.data);
8108
- const receipt = receipts.get(event.data) ?? (id ? responseReceipts.get(id) : void 0) ?? (pending.size === 1 ? pending.values().next().value : void 0);
8109
- if (!receipt) return;
8110
- pending.delete(receipt);
8111
- if (id) responseReceipts.delete(id);
8112
- receipt.resolve();
8113
- },
8114
- fail,
8115
- close: () => {
8116
- input.signal.removeEventListener("abort", abort);
8117
- if (pending.size > 0) fail(new Error("Model stream closed before response settlement"));
8118
- responseReceipts.clear();
8119
- }
8120
- };
8121
- }
8122
-
8123
7975
  // src/activities/agent-turn/session-title.ts
8124
7976
  import { hasPermission } from "@opengeni/core";
8125
7977
  import { isManagedOpenRouterFreeRoute } from "@opengeni/config";
@@ -8449,24 +8301,6 @@ function createSharedRigSetupCoordinator(options) {
8449
8301
  };
8450
8302
  }
8451
8303
 
8452
- // src/activities/agent-turn/final-reply.ts
8453
- function finalReplyNudge(turnId) {
8454
- return {
8455
- type: "message",
8456
- role: "developer",
8457
- content: [
8458
- {
8459
- type: "input_text",
8460
- text: `[Runtime final-reply handoff for turn ${turnId}]
8461
- Your final user-facing answer was empty. Reply to the user now with the requested deliverable or a concise outcome and its retained artifact link. Goal evidence is a short ledger proof, not the answer, and goal_complete does not deliver a chat reply. Use the completed work and tool results already in history; do not repeat completed tools or restart the task. If this is a late child result after goal completion, integrate material new findings and deliver any still-missing handoff. Do not change the completed goal or invent a result.`
8462
- }
8463
- ]
8464
- };
8465
- }
8466
- function needsFinalReply(input) {
8467
- return typeof input.output === "string" && input.output.trim().length === 0 && !input.inputWaitYielded && !input.interrupted && !input.maintenance && (input.toolsExecuted || input.completedGoal);
8468
- }
8469
-
8470
8304
  // src/activities/agent-turn/stream-attempt.ts
8471
8305
  async function attachPendingUpdatesBeforePreparingModelInput(input) {
8472
8306
  if (input.shouldAttach && !await input.attachPendingUpdates()) return false;
@@ -8733,33 +8567,12 @@ async function runTurnStreamAttempt(deps) {
8733
8567
  const modelResponseState = createModelResponseEventState(claimedModelUsageSourceKeys);
8734
8568
  let latestAssistantMessageText = null;
8735
8569
  let workerPreparationTotalRecorded = false;
8736
- let toolsExecuted = false;
8737
- let finalReplyNudged = false;
8738
- const revalidateModelCallAdmission = async () => {
8739
- await historySink.reconcileConversationTruth({ requireDurable: true });
8740
- await ensureRunAllowedBetweenModelCalls({
8741
- settings,
8742
- db,
8743
- accountId: input.accountId,
8744
- workspaceId: input.workspaceId,
8745
- isExternallyBilledTurn: billingState.isExternallyBilledTurn,
8746
- entitlements,
8747
- chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
8748
- countsTowardTokenCap: billingState.countsTowardTokenCap,
8749
- initiatingHumanSubjectId: turn.initiatingHumanSubjectId
8750
- });
8751
- };
8752
8570
  const runStreamAttempt = async (options) => {
8753
8571
  if (!runInput) {
8754
8572
  throw new Error("Run input was not prepared");
8755
8573
  }
8756
- eventing.stream = void 0;
8757
- if (options.requireTerminalModelResponse) await revalidateModelCallAdmission();
8758
- const modelCallAdmission = createModelCallAdmission({
8759
- signal: runtimeCancellationSignal,
8760
- admit: revalidateModelCallAdmission
8761
- });
8762
8574
  const responseCountBeforeStream = modelResponseState.responseCount;
8575
+ eventing.stream = void 0;
8763
8576
  eventing.batcher = null;
8764
8577
  let currentToolBatchCallIds = /* @__PURE__ */ new Set();
8765
8578
  let currentToolBatchCompletedCallIds = /* @__PURE__ */ new Set();
@@ -8927,8 +8740,6 @@ async function runTurnStreamAttempt(deps) {
8927
8740
  }
8928
8741
  attempt.modelRequestStarted = true;
8929
8742
  return await runtime.runStream(agent, runInput, eventing.modelRunSettings, {
8930
- beforeModelRequest: modelCallAdmission.beforeModelRequest,
8931
- onModelResponse: modelCallAdmission.onModelResponse,
8932
8743
  signal: runtimeCancellationSignal,
8933
8744
  sandboxEnvironment,
8934
8745
  onModelVisibleContext: async (snapshot) => {
@@ -9035,13 +8846,7 @@ async function runTurnStreamAttempt(deps) {
9035
8846
  if (leases.xai.lost) {
9036
8847
  throw new Error("xAI credential lease expired before the model run");
9037
8848
  }
9038
- try {
9039
- eventing.stream = await withProviderRequestContext(runStreamOnce);
9040
- } catch (error51) {
9041
- modelCallAdmission.fail(error51);
9042
- modelCallAdmission.close();
9043
- throw error51;
9044
- }
8849
+ eventing.stream = await withProviderRequestContext(runStreamOnce);
9045
8850
  const streamTiming = new StreamTimingMetrics(observability, {
9046
8851
  provider: streamProvider
9047
8852
  });
@@ -9180,20 +8985,32 @@ async function runTurnStreamAttempt(deps) {
9180
8985
  await historySink.reconcileConversationTruth();
9181
8986
  turnLifecycleMetricsFor(observability).progress({ attemptId: input.attemptId });
9182
8987
  modelCheckpointMemoryCollector.schedule(observability);
9183
- await ensureRunAllowedBetweenModelCalls({
9184
- settings,
9185
- db,
9186
- accountId: input.accountId,
9187
- workspaceId: input.workspaceId,
9188
- isExternallyBilledTurn: billingState.isExternallyBilledTurn,
9189
- entitlements,
9190
- chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
9191
- countsTowardTokenCap: billingState.countsTowardTokenCap,
9192
- initiatingHumanSubjectId: turn.initiatingHumanSubjectId,
9193
- serializedRunState: () => media.compactMediaRunState(String(eventing.stream.state.toString()))
9194
- });
8988
+ try {
8989
+ await ensureRunAllowed(
8990
+ settings,
8991
+ db,
8992
+ input.accountId,
8993
+ input.workspaceId,
8994
+ billingState.isExternallyBilledTurn,
8995
+ entitlements,
8996
+ billingState.chargesOpenGeniCredits,
8997
+ billingState.countsTowardTokenCap
8998
+ );
8999
+ } catch (limitError) {
9000
+ let serializedRunState = null;
9001
+ try {
9002
+ serializedRunState = media.compactMediaRunState(
9003
+ String(eventing.stream.state.toString())
9004
+ );
9005
+ } catch {
9006
+ serializedRunState = null;
9007
+ }
9008
+ throw new BudgetExhaustedError(
9009
+ limitError instanceof Error ? limitError.message : String(limitError),
9010
+ serializedRunState
9011
+ );
9012
+ }
9195
9013
  }
9196
- modelCallAdmission.settle(next.value);
9197
9014
  const durableSdkEvent = generatedImageReceipt ? compactGeneratedImageSdkEvent(next.value, generatedImageReceipt) : next.value;
9198
9015
  const pendingToolCall = pendingToolCallFromSdkEvent(durableSdkEvent);
9199
9016
  if (pendingToolCall) {
@@ -9227,7 +9044,6 @@ async function runTurnStreamAttempt(deps) {
9227
9044
  }
9228
9045
  const completedToolCall = completedToolCallFromSdkEvent(durableSdkEvent);
9229
9046
  if (completedToolCall) {
9230
- toolsExecuted = true;
9231
9047
  retainedScreenshotMetadata = media.retainedScreenshotReceiptsByCallId.get(completedToolCall.callId) ?? null;
9232
9048
  const typedScreenshot = retainedScreenshotMetadata ? null : typedScreenshotFromSdkEvent(durableSdkEvent);
9233
9049
  if (!retainedScreenshotMetadata && media.retainedSessionImageCallIds.has(completedToolCall.callId) && sdkEventContainsInlineImage(durableSdkEvent) && !typedScreenshot) {
@@ -9409,7 +9225,6 @@ async function runTurnStreamAttempt(deps) {
9409
9225
  }
9410
9226
  }
9411
9227
  } catch (error51) {
9412
- modelCallAdmission.fail(error51);
9413
9228
  closeStreamWaitAdmission?.();
9414
9229
  if (fallbackProviderRequestLifecycleStartedAt !== null) {
9415
9230
  const durationMs = Math.max(
@@ -9459,7 +9274,6 @@ async function runTurnStreamAttempt(deps) {
9459
9274
  }
9460
9275
  throw error51;
9461
9276
  } finally {
9462
- modelCallAdmission.close();
9463
9277
  if (!streamDone) {
9464
9278
  void iterator.return?.().catch(() => void 0);
9465
9279
  }
@@ -9470,7 +9284,7 @@ async function runTurnStreamAttempt(deps) {
9470
9284
  temporalCancellationSignal: cancellationSignal,
9471
9285
  runtimeCancellationSignal
9472
9286
  });
9473
- await eventing.preparedTools?.inputWaitYield?.drainForHandoff(runtimeCancellationSignal);
9287
+ await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);
9474
9288
  if (options.requireTerminalModelResponse && !eventing.preparedTools?.inputWaitYield?.yielded && eventing.stream.interruptions.length === 0 && modelResponseState.responseCount === responseCountBeforeStream) {
9475
9289
  throwIfWorkerShuttingDown();
9476
9290
  throwIfTurnCancelled();
@@ -9566,7 +9380,6 @@ async function runTurnStreamAttempt(deps) {
9566
9380
  }
9567
9381
  }
9568
9382
  if (eventing.stream.interruptions.length > 0) {
9569
- await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);
9570
9383
  await historySink.reconcileConversationTruth({ requireDurable: true });
9571
9384
  const approvals = runtime.serializeApprovals(eventing.stream.interruptions);
9572
9385
  const humanInputInterruptions = runtime.serializeHumanInputRequests?.(eventing.stream.interruptions) ?? [];
@@ -9707,48 +9520,6 @@ async function runTurnStreamAttempt(deps) {
9707
9520
  const finalOutput = String(
9708
9521
  requireAgentStreamFinalOutput(eventing.stream.finalOutput, inputWaitYielded)
9709
9522
  );
9710
- const durableReplyFacts = !inputWaitYielded && finalOutput.trim().length === 0 ? await sessionTurnFinalReplyFacts(db, input.workspaceId, input.sessionId, activeTurnId) : { toolsExecuted: false, completedGoal: false };
9711
- let emptyFinalReply = false;
9712
- if (needsFinalReply({
9713
- output: finalOutput,
9714
- inputWaitYielded: inputWaitYielded || eventing.preparedTools?.inputWaitYield?.requested === true,
9715
- interrupted: false,
9716
- // interruption settlement returned above
9717
- maintenance: turn.source === "compaction",
9718
- toolsExecuted: toolsExecuted || finalReplyNudged || durableReplyFacts.toolsExecuted,
9719
- completedGoal: durableReplyFacts.completedGoal
9720
- })) {
9721
- await historySink.reconcileConversationTruth({ requireDurable: true });
9722
- if (finalReplyNudged || await sessionTurnHasFinalReplyNudge(
9723
- db,
9724
- input.workspaceId,
9725
- input.sessionId,
9726
- activeTurnId,
9727
- finalReplyNudge(activeTurnId).content[0].text
9728
- )) {
9729
- emptyFinalReply = true;
9730
- } else {
9731
- const appended = await appendSessionHistoryItems3(db, {
9732
- accountId: input.accountId,
9733
- workspaceId: input.workspaceId,
9734
- sessionId: input.sessionId,
9735
- turnId: activeTurnId,
9736
- expectedExecutionGeneration: attempt.executionGeneration,
9737
- expectedAttemptId: input.attemptId,
9738
- items: [
9739
- {
9740
- position: await nextSessionHistoryPosition2(db, input.workspaceId, input.sessionId),
9741
- item: finalReplyNudge(activeTurnId)
9742
- }
9743
- ]
9744
- });
9745
- if (!appended) throw new TurnAttemptFencedError("turn ended before final reply handoff");
9746
- finalReplyNudged = true;
9747
- await prepareRunAttemptInput();
9748
- return "reply_nudge";
9749
- }
9750
- }
9751
- await eventing.preparedTools?.inputWaitYield?.sealForSettlement(runtimeCancellationSignal);
9752
9523
  const finalOutputAlreadyCompleted = latestStreamedAssistantText === finalOutput;
9753
9524
  const reply = await inputWaitReply({
9754
9525
  inputWaitYielded,
@@ -9768,11 +9539,7 @@ async function runTurnStreamAttempt(deps) {
9768
9539
  ...inputWaitYielded || finalOutputAlreadyCompleted ? [] : [{ type: "agent.message.completed", payload: { text: finalOutput } }],
9769
9540
  {
9770
9541
  type: "turn.completed",
9771
- payload: {
9772
- output: finalOutput,
9773
- ...reply === null ? {} : { reply },
9774
- ...emptyFinalReply ? { emptyFinalReply: true } : {}
9775
- }
9542
+ payload: { output: finalOutput, ...reply === null ? {} : { reply } }
9776
9543
  },
9777
9544
  { type: "session.status.changed", payload: { status: "idle" } }
9778
9545
  ],
@@ -9828,7 +9595,6 @@ async function runTurnStreamAttempt(deps) {
9828
9595
  })) {
9829
9596
  return claimedResult({ status: "cancelled" });
9830
9597
  }
9831
- await revalidateModelCallAdmission();
9832
9598
  if (turn.source !== "compaction" && generateSessionTitleInParallel && runtime.generateSessionTitle && !runtimeCancellationSignal.aborted) {
9833
9599
  const serviceTier = serviceTierForLatencyMode(
9834
9600
  turnExecutionPolicy.providerId,
@@ -9860,19 +9626,11 @@ async function runTurnStreamAttempt(deps) {
9860
9626
  }
9861
9627
  try {
9862
9628
  let retriedAfterCompaction = false;
9863
- finalReplyNudged = await sessionTurnHasFinalReplyNudge(
9864
- db,
9865
- input.workspaceId,
9866
- input.sessionId,
9867
- activeTurnId,
9868
- finalReplyNudge(activeTurnId).content[0].text
9869
- );
9870
9629
  while (true) {
9871
9630
  try {
9872
9631
  const result = await runStreamAttempt({
9873
9632
  requireTerminalModelResponse: retriedAfterCompaction
9874
9633
  });
9875
- if (result === "reply_nudge") continue;
9876
9634
  if (retriedAfterCompaction) {
9877
9635
  observability.info("context compaction recovery succeeded after in-activity retry", {
9878
9636
  sessionId: input.sessionId,
@@ -10083,9 +9841,7 @@ import {
10083
9841
  loadOrganizationModelProviderApiKey,
10084
9842
  listWorkspaceProviderCustomModels,
10085
9843
  getWorkspaceProviderCustomModelForExecution,
10086
- loadWorkspaceProviderApiKey,
10087
- loadClaudeSubscriptionUsageCredential,
10088
- assertModelConnectionAllowsTurn
9844
+ loadWorkspaceProviderApiKey
10089
9845
  } from "@opengeni/db";
10090
9846
  async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, attemptId, settings, options) {
10091
9847
  const encryptionKey = environmentsEncryptionKeyBytes(settings);
@@ -10243,24 +9999,12 @@ async function settingsWithOrganizationProviderCredentials(db, accountId, worksp
10243
9999
  if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled) continue;
10244
10000
  const models = await buildModels(kind, claudeProviderId(kind) + "/");
10245
10001
  result = withClaudeConnectionCatalog(result, { [kind]: { models } });
10246
- const binding = kind === "claude_subscription" ? await loadClaudeSubscriptionUsageCredential(db, settings, {
10247
- accountId,
10248
- workspaceId,
10249
- scope: "organization"
10250
- }) : null;
10251
- const credential = kind === "claude_subscription" ? binding?.serializedCredential : await loadOrganizationModelProviderApiKey(db, settings, {
10002
+ const credential = await loadOrganizationModelProviderApiKey(db, settings, {
10252
10003
  accountId,
10253
10004
  workspaceId,
10254
10005
  providerKind: kind
10255
10006
  });
10256
- if (credential)
10257
- result = withClaudeConnectionCredential(
10258
- result,
10259
- kind,
10260
- credential,
10261
- "organization",
10262
- binding ?? void 0
10263
- );
10007
+ if (credential) result = withClaudeConnectionCredential(result, kind, credential);
10264
10008
  const workspaceModels = await listWorkspaceProviderCustomModels(db, {
10265
10009
  accountId,
10266
10010
  workspaceId,
@@ -10283,27 +10027,15 @@ async function settingsWithOrganizationProviderCredentials(db, accountId, worksp
10283
10027
  { [kind]: { models: workspaceModels } },
10284
10028
  "workspace"
10285
10029
  );
10286
- const workspaceBinding = kind === "claude_subscription" ? await loadClaudeSubscriptionUsageCredential(db, settings, {
10287
- accountId,
10030
+ const workspaceCredential = await loadWorkspaceProviderApiKey(
10031
+ db,
10032
+ settings,
10288
10033
  workspaceId,
10289
- scope: "workspace"
10290
- }) : null;
10291
- if (workspaceBinding && workspaceModelId)
10292
- await assertModelConnectionAllowsTurn(db, {
10293
- workspaceId,
10294
- subjectId: "worker:model-access",
10295
- modelId: workspaceModelId,
10296
- workspaceProviderConnectionId: workspaceBinding.connectionId
10297
- });
10298
- const workspaceCredential = kind === "claude_subscription" ? workspaceBinding?.serializedCredential : await loadWorkspaceProviderApiKey(db, settings, workspaceId, kind, workspaceModelId);
10034
+ kind,
10035
+ workspaceModelId
10036
+ );
10299
10037
  if (workspaceCredential)
10300
- result = withClaudeConnectionCredential(
10301
- result,
10302
- kind,
10303
- workspaceCredential,
10304
- "workspace",
10305
- workspaceBinding ?? void 0
10306
- );
10038
+ result = withClaudeConnectionCredential(result, kind, workspaceCredential, "workspace");
10307
10039
  }
10308
10040
  return result;
10309
10041
  }
@@ -10521,27 +10253,20 @@ async function claimTurnAttempt(deps) {
10521
10253
  return attached.action === "claimed" && attached.turn.id === turn.id;
10522
10254
  };
10523
10255
  turnLifecycleMetricsFor(observability).start({ attemptId: input.attemptId });
10524
- let allowanceRefusal = null;
10525
- try {
10526
- await waitForTurnOperation(
10527
- ensureRunAllowed(
10528
- capabilitySettings,
10529
- db,
10530
- input.accountId,
10531
- input.workspaceId,
10532
- billingState.isExternallyBilledTurn,
10533
- entitlements,
10534
- billingState.chargesOpenGeniCredits,
10535
- billingState.countsTowardTokenCap,
10536
- turn.initiatingHumanSubjectId
10537
- ),
10538
- cancellationSignal,
10539
- void 0
10540
- );
10541
- } catch (error51) {
10542
- if (!(error51 instanceof AllowanceExhaustedError)) throw error51;
10543
- allowanceRefusal = error51.refusal;
10544
- }
10256
+ await waitForTurnOperation(
10257
+ ensureRunAllowed(
10258
+ capabilitySettings,
10259
+ db,
10260
+ input.accountId,
10261
+ input.workspaceId,
10262
+ billingState.isExternallyBilledTurn,
10263
+ entitlements,
10264
+ billingState.chargesOpenGeniCredits,
10265
+ billingState.countsTowardTokenCap
10266
+ ),
10267
+ cancellationSignal,
10268
+ void 0
10269
+ );
10545
10270
  const throwIfWorkerShuttingDown = () => {
10546
10271
  const reason = activityContext?.cancellationSignal.reason;
10547
10272
  if (isWorkerShutdownCancellation(reason)) {
@@ -10646,7 +10371,6 @@ async function claimTurnAttempt(deps) {
10646
10371
  sessionStatus: inputSettlement.sessionStatus,
10647
10372
  activeTurnId: inputSettlement.activeTurnId,
10648
10373
  ...inputSettlement.suppressGoalContinuation !== void 0 ? { suppressGoalContinuation: inputSettlement.suppressGoalContinuation } : {},
10649
- ...inputSettlement.allowanceGoalPause ? { allowanceGoalPause: inputSettlement.allowanceGoalPause } : {},
10650
10374
  events: inputs,
10651
10375
  ...runState ? { runState } : {},
10652
10376
  ...compactionRequestFailure ? { compactionRequestFailure } : {}
@@ -10694,31 +10418,6 @@ async function claimTurnAttempt(deps) {
10694
10418
  durationSeconds: (performance.now() - activityStarted) / 1e3
10695
10419
  });
10696
10420
  const turnStartSettlementStartedAt = performance.now();
10697
- if (allowanceRefusal) {
10698
- if (!await eventing.settle({
10699
- events: [
10700
- { type: "usage.exhausted", payload: allowanceRefusal },
10701
- {
10702
- type: "turn.completed",
10703
- payload: {
10704
- output: "",
10705
- segmentLimit: "budget_exhausted",
10706
- ...allowanceRefusal
10707
- }
10708
- },
10709
- { type: "session.status.changed", payload: { status: "idle" } }
10710
- ],
10711
- turnStatus: "completed",
10712
- sessionStatus: "idle",
10713
- activeTurnId: null,
10714
- allowanceGoalPause: { rationale: allowanceRefusal.message }
10715
- })) {
10716
- return { exit: claimedResult({ status: "cancelled" }) };
10717
- }
10718
- control.turnMetricOutcome = "completed";
10719
- control.activityStatus = "idle";
10720
- return { exit: claimedResult({ status: "idle" }) };
10721
- }
10722
10421
  if (!await eventing.settle({
10723
10422
  events: [
10724
10423
  { type: "session.status.changed", payload: { status: "running" } },
@@ -14643,100 +14342,6 @@ import {
14643
14342
  } from "@opengeni/runtime";
14644
14343
  import { codemodeWorkspaceUrl as codemodeWorkspaceUrl2 } from "@opengeni/config";
14645
14344
 
14646
- // src/activities/mcp-account-routes.ts
14647
- function accountRouteAuthNeededPayload(payload, bindings) {
14648
- const binding = bindings?.find((candidate) => candidate.serverId === payload.serverId);
14649
- return binding ? {
14650
- ...payload,
14651
- canonicalServerId: binding.canonicalServerId,
14652
- connectionSubjectScope: binding.subjectScope
14653
- } : payload;
14654
- }
14655
- function expandMcpAccountRoutes(input) {
14656
- if (input.bindings == null) {
14657
- return { settings: input.settings, tools: input.tools, accountLabels: /* @__PURE__ */ new Map() };
14658
- }
14659
- const configured = new Map(input.settings.mcpServers.map((server) => [server.id, server]));
14660
- const byCanonical = /* @__PURE__ */ new Map();
14661
- const routes = /* @__PURE__ */ new Set();
14662
- const accounts = /* @__PURE__ */ new Set();
14663
- for (const binding of input.bindings) {
14664
- const account = JSON.stringify([binding.canonicalServerId, binding.connectionId]);
14665
- if (routes.has(binding.serverId) || accounts.has(account) || configured.has(binding.serverId) || binding.subjectScope === "subject" !== (binding.ownerSubjectId !== null) || binding.connectionRef.authoritySource === "host" || binding.connectionRef.connectionId !== binding.connectionId || binding.connectionRef.subjectScope !== binding.subjectScope || binding.connectionRef.providerDomain !== binding.providerDomain || binding.connectionRef.kind !== binding.kind) {
14666
- throw new Error("Invalid accepted MCP account route");
14667
- }
14668
- routes.add(binding.serverId);
14669
- accounts.add(account);
14670
- const siblings = byCanonical.get(binding.canonicalServerId) ?? [];
14671
- siblings.push(binding);
14672
- byCanonical.set(binding.canonicalServerId, siblings);
14673
- }
14674
- const servers = [];
14675
- const tools = [];
14676
- const accountLabels = /* @__PURE__ */ new Map();
14677
- for (const tool of input.tools) {
14678
- const bindings = byCanonical.get(tool.id);
14679
- if (!bindings) {
14680
- if (!configured.get(tool.id)?.connectionRef) tools.push(tool);
14681
- continue;
14682
- }
14683
- const canonical = configured.get(tool.id);
14684
- if (!canonical?.connectionRef) {
14685
- throw new Error("Accepted MCP account route has no canonical connection configuration");
14686
- }
14687
- for (const binding of bindings) {
14688
- if (canonical.connectionRef.authoritySource === "host" || canonical.connectionRef.providerDomain !== binding.providerDomain || canonical.connectionRef.kind && canonical.connectionRef.kind !== binding.kind) {
14689
- throw new Error("Accepted MCP account route does not match canonical provider");
14690
- }
14691
- const { headers: _headers, ...config2 } = canonical;
14692
- const label = `${canonical.name ?? canonical.id} \u2014 ${binding.subjectScope === "subject" ? "Personal" : "Workspace"}: ${binding.accountLabel}`;
14693
- servers.push({
14694
- ...config2,
14695
- id: binding.serverId,
14696
- name: label,
14697
- connectionRef: structuredClone(binding.connectionRef)
14698
- });
14699
- tools.push({ ...tool, id: binding.serverId });
14700
- accountLabels.set(binding.serverId, label);
14701
- }
14702
- }
14703
- return {
14704
- settings: {
14705
- ...input.settings,
14706
- mcpServers: [
14707
- ...input.settings.mcpServers.filter((server) => !server.connectionRef),
14708
- ...servers
14709
- ]
14710
- },
14711
- tools,
14712
- accountLabels
14713
- };
14714
- }
14715
- function expandApiIntegrationAccountRoutes(input) {
14716
- const selected = new Set(input.tools.map((tool) => tool.id));
14717
- if (input.bindings == null)
14718
- return input.integrations.filter((item) => selected.has(item.serverId));
14719
- const acceptedBindings = input.bindings;
14720
- return input.integrations.flatMap((integration) => {
14721
- const bindings = acceptedBindings.filter(
14722
- (binding) => binding.canonicalServerId === integration.serverId
14723
- );
14724
- if (bindings.length === 0)
14725
- return !integration.connectionRef && selected.has(integration.serverId) ? [integration] : [];
14726
- return bindings.filter((binding) => selected.has(binding.serverId)).map((binding) => {
14727
- if (binding.connectionAuthorityGeneration === void 0) {
14728
- throw new Error("Accepted API integration account route has no authority generation");
14729
- }
14730
- return {
14731
- ...integration,
14732
- serverId: binding.serverId,
14733
- connectionRef: structuredClone(binding.connectionRef),
14734
- connectionAuthorityGeneration: binding.connectionAuthorityGeneration
14735
- };
14736
- });
14737
- });
14738
- }
14739
-
14740
14345
  // src/activities/git-credential-renewal.ts
14741
14346
  var GIT_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 6e4;
14742
14347
  var GIT_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 6e4;
@@ -15095,8 +14700,6 @@ function credentialProviderRequestBody(input, initiatingHumanSubjectId, initiati
15095
14700
  lane: "workspace",
15096
14701
  mcpServers: []
15097
14702
  }) {
15098
- const via = input.initiatorContext.via;
15099
- const latestHop = Array.isArray(via) ? via.at(-1) : null;
15100
14703
  return {
15101
14704
  type: "credentials.request",
15102
14705
  lane: selection.lane,
@@ -15111,11 +14714,6 @@ function credentialProviderRequestBody(input, initiatingHumanSubjectId, initiati
15111
14714
  turnId: input.turnId,
15112
14715
  attemptId: input.attemptId,
15113
14716
  initiator: { kind: input.initiator.kind, subjectId: input.initiator.subjectId },
15114
- initiatorContext: {
15115
- kind: latestHop?.kind === "agent" ? "agent" : input.initiator.kind === "subject" ? "human" : "service",
15116
- initiator: input.initiator,
15117
- context: input.initiatorContext
15118
- },
15119
14717
  initiatingHumanSubjectId,
15120
14718
  initiatingHuman,
15121
14719
  sandboxBackend: input.effectiveSandboxBackend,
@@ -15307,7 +14905,7 @@ async function bindRunCredentialResolver(input) {
15307
14905
  mcpServers: selectedSessionRemoteMcpTargets(
15308
14906
  input.settings,
15309
14907
  input.session.mcpServers ?? [],
15310
- input.effectiveTools,
14908
+ input.turn.tools ?? [],
15311
14909
  (input.localMcpServerIds ?? []).map((id) => ({ id }))
15312
14910
  )
15313
14911
  }
@@ -15323,23 +14921,22 @@ async function bindRunCredentialResolver(input) {
15323
14921
  workspaceId: input.workspaceId,
15324
14922
  sessionId: input.session.id
15325
14923
  };
15326
- const frozenRequest = structuredClone(
15327
- buildRunCredentialsRequest({
15328
- accountId: input.accountId,
15329
- workspaceId: input.workspaceId,
15330
- session: input.session,
15331
- turn: input.turn,
15332
- attemptId: input.attemptId,
15333
- effectiveSandboxBackend: input.effectiveSandboxBackend,
15334
- variableSet: input.variableSet,
15335
- rootSessionId,
15336
- purpose: "provision",
15337
- forceRefresh: false
15338
- })
15339
- );
15340
14924
  return {
15341
14925
  resolve: async ({ purpose, forceRefresh }) => {
15342
- const resolution = await resolver({ ...frozenRequest, purpose, forceRefresh });
14926
+ const resolution = await resolver(
14927
+ buildRunCredentialsRequest({
14928
+ accountId: input.accountId,
14929
+ workspaceId: input.workspaceId,
14930
+ session: input.session,
14931
+ turn: input.turn,
14932
+ attemptId: input.attemptId,
14933
+ effectiveSandboxBackend: input.effectiveSandboxBackend,
14934
+ variableSet: input.variableSet,
14935
+ rootSessionId,
14936
+ purpose,
14937
+ forceRefresh
14938
+ })
14939
+ );
15343
14940
  return normalizeRunCredentialsResolution(resolution, scope);
15344
14941
  }
15345
14942
  };
@@ -15384,19 +14981,13 @@ async function prepareRunCredentials(deps) {
15384
14981
  const platformGitResources = turnResources.filter(
15385
14982
  (resource) => resource.kind !== "repository" || repositoryHasExplicitGitConnection(resource)
15386
14983
  );
15387
- const accountRoutes = expandMcpAccountRoutes({
15388
- settings: runSettings,
15389
- tools: deps.turnTools,
15390
- bindings: turn.mcpAccountBindings
15391
- });
15392
14984
  const runCredentialResolver = effectiveRunCredentialBackend === "none" || effectiveRunCredentialBackend === "selfhosted" ? null : await waitForTurnOperation(
15393
14985
  bindRunCredentialResolver({
15394
14986
  db,
15395
- settings: accountRoutes.settings,
14987
+ settings: runSettings,
15396
14988
  initiatingHumanSubjectId: turn.initiatingHumanSubjectId ?? null,
15397
14989
  connectionCredentials: connectionCredentials ?? null,
15398
14990
  localMcpServerIds: deps.localMcpServerIds ?? [],
15399
- effectiveTools: accountRoutes.tools,
15400
14991
  accountId: input.accountId,
15401
14992
  workspaceId: input.workspaceId,
15402
14993
  session,
@@ -15435,9 +15026,9 @@ async function prepareRunCredentials(deps) {
15435
15026
  ) : null;
15436
15027
  const runMcpCredentials = new RunMcpCredentials(
15437
15028
  selectedSessionRemoteMcpTargets2(
15438
- accountRoutes.settings,
15029
+ runSettings,
15439
15030
  session.mcpServers ?? [],
15440
- accountRoutes.tools,
15031
+ turn.tools ?? [],
15441
15032
  (deps.localMcpServerIds ?? []).map((id) => ({ id }))
15442
15033
  ),
15443
15034
  {
@@ -16819,6 +16410,100 @@ function isGitHubApiDestination(value) {
16819
16410
  }
16820
16411
  }
16821
16412
 
16413
+ // src/activities/mcp-account-routes.ts
16414
+ function accountRouteAuthNeededPayload(payload, bindings) {
16415
+ const binding = bindings?.find((candidate) => candidate.serverId === payload.serverId);
16416
+ return binding ? {
16417
+ ...payload,
16418
+ canonicalServerId: binding.canonicalServerId,
16419
+ connectionSubjectScope: binding.subjectScope
16420
+ } : payload;
16421
+ }
16422
+ function expandMcpAccountRoutes(input) {
16423
+ if (input.bindings == null) {
16424
+ return { settings: input.settings, tools: input.tools, accountLabels: /* @__PURE__ */ new Map() };
16425
+ }
16426
+ const configured = new Map(input.settings.mcpServers.map((server) => [server.id, server]));
16427
+ const byCanonical = /* @__PURE__ */ new Map();
16428
+ const routes = /* @__PURE__ */ new Set();
16429
+ const accounts = /* @__PURE__ */ new Set();
16430
+ for (const binding of input.bindings) {
16431
+ const account = JSON.stringify([binding.canonicalServerId, binding.connectionId]);
16432
+ if (routes.has(binding.serverId) || accounts.has(account) || configured.has(binding.serverId) || binding.subjectScope === "subject" !== (binding.ownerSubjectId !== null) || binding.connectionRef.authoritySource === "host" || binding.connectionRef.connectionId !== binding.connectionId || binding.connectionRef.subjectScope !== binding.subjectScope || binding.connectionRef.providerDomain !== binding.providerDomain || binding.connectionRef.kind !== binding.kind) {
16433
+ throw new Error("Invalid accepted MCP account route");
16434
+ }
16435
+ routes.add(binding.serverId);
16436
+ accounts.add(account);
16437
+ const siblings = byCanonical.get(binding.canonicalServerId) ?? [];
16438
+ siblings.push(binding);
16439
+ byCanonical.set(binding.canonicalServerId, siblings);
16440
+ }
16441
+ const servers = [];
16442
+ const tools = [];
16443
+ const accountLabels = /* @__PURE__ */ new Map();
16444
+ for (const tool of input.tools) {
16445
+ const bindings = byCanonical.get(tool.id);
16446
+ if (!bindings) {
16447
+ if (!configured.get(tool.id)?.connectionRef) tools.push(tool);
16448
+ continue;
16449
+ }
16450
+ const canonical = configured.get(tool.id);
16451
+ if (!canonical?.connectionRef) {
16452
+ throw new Error("Accepted MCP account route has no canonical connection configuration");
16453
+ }
16454
+ for (const binding of bindings) {
16455
+ if (canonical.connectionRef.authoritySource === "host" || canonical.connectionRef.providerDomain !== binding.providerDomain || canonical.connectionRef.kind && canonical.connectionRef.kind !== binding.kind) {
16456
+ throw new Error("Accepted MCP account route does not match canonical provider");
16457
+ }
16458
+ const { headers: _headers, ...config2 } = canonical;
16459
+ const label = `${canonical.name ?? canonical.id} \u2014 ${binding.subjectScope === "subject" ? "Personal" : "Workspace"}: ${binding.accountLabel}`;
16460
+ servers.push({
16461
+ ...config2,
16462
+ id: binding.serverId,
16463
+ name: label,
16464
+ connectionRef: structuredClone(binding.connectionRef)
16465
+ });
16466
+ tools.push({ ...tool, id: binding.serverId });
16467
+ accountLabels.set(binding.serverId, label);
16468
+ }
16469
+ }
16470
+ return {
16471
+ settings: {
16472
+ ...input.settings,
16473
+ mcpServers: [
16474
+ ...input.settings.mcpServers.filter((server) => !server.connectionRef),
16475
+ ...servers
16476
+ ]
16477
+ },
16478
+ tools,
16479
+ accountLabels
16480
+ };
16481
+ }
16482
+ function expandApiIntegrationAccountRoutes(input) {
16483
+ const selected = new Set(input.tools.map((tool) => tool.id));
16484
+ if (input.bindings == null)
16485
+ return input.integrations.filter((item) => selected.has(item.serverId));
16486
+ const acceptedBindings = input.bindings;
16487
+ return input.integrations.flatMap((integration) => {
16488
+ const bindings = acceptedBindings.filter(
16489
+ (binding) => binding.canonicalServerId === integration.serverId
16490
+ );
16491
+ if (bindings.length === 0)
16492
+ return !integration.connectionRef && selected.has(integration.serverId) ? [integration] : [];
16493
+ return bindings.filter((binding) => selected.has(binding.serverId)).map((binding) => {
16494
+ if (binding.connectionAuthorityGeneration === void 0) {
16495
+ throw new Error("Accepted API integration account route has no authority generation");
16496
+ }
16497
+ return {
16498
+ ...integration,
16499
+ serverId: binding.serverId,
16500
+ connectionRef: structuredClone(binding.connectionRef),
16501
+ connectionAuthorityGeneration: binding.connectionAuthorityGeneration
16502
+ };
16503
+ });
16504
+ });
16505
+ }
16506
+
16822
16507
  // src/activities/agent-turn/tool-environment.ts
16823
16508
  import { createMcpOperationPersistence } from "@opengeni/db/mcp-operations";
16824
16509
 
@@ -32572,10 +32257,8 @@ import {
32572
32257
  buildApiIntegrationMcpServers,
32573
32258
  resolveCatalogSettings as resolveCatalogSettings2,
32574
32259
  resolveWorkspaceModelSelection,
32575
- loadWorkspaceCodexModelAvailability,
32576
32260
  withFrozenPersonalConnectionDelegations,
32577
- resolveTurnToolPolicy,
32578
- scheduledTurnMcpServerIds,
32261
+ resolveSessionToolPolicy,
32579
32262
  hasPermission as hasPermission2
32580
32263
  } from "@opengeni/core";
32581
32264
  import { SandboxChannelAService as SandboxChannelAService3 } from "@opengeni/runtime/sandbox";
@@ -34020,17 +33703,21 @@ async function prepareTurnToolPolicy(deps) {
34020
33703
  } = deps;
34021
33704
  const turnResources = mergeResourceRefs(session.resources, turn.resources);
34022
33705
  const runtimeResources = runtimeResourcesForTurn(session.resources, turn.resources);
34023
- const resolvedToolPolicy = resolveTurnToolPolicy({
33706
+ const scheduledEffectiveMcpServerIds = (() => {
33707
+ const value = turn.metadata && typeof turn.metadata === "object" && !Array.isArray(turn.metadata) ? turn.metadata.scheduledEffectiveMcpServerIds : null;
33708
+ return Array.isArray(value) && value.every((id) => typeof id === "string") ? [...new Set(value)].sort() : null;
33709
+ })();
33710
+ const currentMcpServerIds = new Set(runSettings.mcpServers.map((server) => server.id));
33711
+ const resolvedToolPolicy = resolveSessionToolPolicy({
34024
33712
  toolPolicy: session.toolPolicy,
34025
- session,
34026
- turn,
34027
- availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),
34028
- defaultMcpServerIds: scheduledTurnMcpServerIds(turn) === null && session.toolPolicy.mode === "workspace_default" ? await workspaceSessionToolPolicyDefaultServerIds(
33713
+ sessionTools: scheduledEffectiveMcpServerIds ? turn.tools : session.tools,
33714
+ availableMcpServerIds: scheduledEffectiveMcpServerIds ? scheduledEffectiveMcpServerIds.filter((id) => currentMcpServerIds.has(id)) : [...currentMcpServerIds],
33715
+ defaultMcpServerIds: scheduledEffectiveMcpServerIds ?? (session.toolPolicy.mode === "workspace_default" ? await workspaceSessionToolPolicyDefaultServerIds(
34029
33716
  db,
34030
33717
  input.workspaceId,
34031
33718
  capabilitySettings,
34032
33719
  fileAuthoritySubjectId ?? void 0
34033
- ) : []
33720
+ ) : [])
34034
33721
  });
34035
33722
  const mcpAvailabilityNote = unavailableMcpOperationalContext({
34036
33723
  droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
@@ -34596,8 +34283,7 @@ async function prepareTurnToolRuntime(deps) {
34596
34283
  organizationGatewayConnectionActive,
34597
34284
  organizationGatewayCustomModels,
34598
34285
  organizationOpenRouterConnectionActive,
34599
- organizationOpenRouterCustomModels,
34600
- codexModelAvailability
34286
+ organizationOpenRouterCustomModels
34601
34287
  ] = await Promise.all([
34602
34288
  getWorkspaceConnectionModelRestrictions(
34603
34289
  db,
@@ -34640,12 +34326,10 @@ async function prepareTurnToolRuntime(deps) {
34640
34326
  accountId: input.accountId,
34641
34327
  workspaceId: input.workspaceId,
34642
34328
  providerKind: "openrouter"
34643
- }),
34644
- loadWorkspaceCodexModelAvailability(db, currentSettings, input.workspaceId)
34329
+ })
34645
34330
  ]);
34646
34331
  return {
34647
34332
  selections: resolveWorkspaceModelSelection({
34648
- observations: codexModelAvailability,
34649
34333
  connectionModelRestrictions,
34650
34334
  settings: currentSettings,
34651
34335
  policy,
@@ -34789,7 +34473,7 @@ async function prepareTurnToolRuntime(deps) {
34789
34473
  sessionAttachedRemoteMcpTargets: selectedSessionRemoteMcpTargets3(
34790
34474
  githubRestMcp.settings,
34791
34475
  session.mcpServers ?? [],
34792
- githubRestMcp.tools,
34476
+ turn.tools ?? [],
34793
34477
  localMcpServers
34794
34478
  ),
34795
34479
  ...deps.runMcpCredentials ? { runMcpCredentials: deps.runMcpCredentials } : {},
@@ -37194,14 +36878,11 @@ function createRunAgentTurnActivity(services) {
37194
36878
  getModelRunSettings: () => eventing.modelRunSettings,
37195
36879
  getExecutionGeneration: () => attempt.executionGeneration
37196
36880
  });
37197
- const checkpointBeforeProviderDispatch = async () => {
37198
- await awaitModelCallAdmission();
37199
- await checkpointHistoryBeforeProviderDispatch(historySink, {
37200
- effectiveSandboxBackend: eventing.modelRunSettings.sandboxBackend,
37201
- routingEnabled: routingEnabled(settings),
37202
- readActiveSandbox: () => readActiveSandbox3(db, input.workspaceId, input.sessionId)
37203
- });
37204
- };
36881
+ const checkpointBeforeProviderDispatch = () => checkpointHistoryBeforeProviderDispatch(historySink, {
36882
+ effectiveSandboxBackend: eventing.modelRunSettings.sandboxBackend,
36883
+ routingEnabled: routingEnabled(settings),
36884
+ readActiveSandbox: () => readActiveSandbox3(db, input.workspaceId, input.sessionId)
36885
+ });
37205
36886
  try {
37206
36887
  const claimed = await claimTurnAttempt({
37207
36888
  input,
@@ -37344,7 +37025,7 @@ function createRunAgentTurnActivity(services) {
37344
37025
  requiredGeneratedVideoFiles
37345
37026
  });
37346
37027
  if ("exit" in governance) return governance.exit;
37347
- await assertModelConnectionAllowsTurn2(db, {
37028
+ await assertModelConnectionAllowsTurn(db, {
37348
37029
  workspaceId: input.workspaceId,
37349
37030
  subjectId: turn.initiatingHumanSubjectId ?? "worker:model-access",
37350
37031
  modelId: turnExecutionPolicy.productModelId,
@@ -37651,36 +37332,13 @@ function createRunAgentTurnActivity(services) {
37651
37332
  const claudeUsageObserver = await createClaudeUsageObserver(
37652
37333
  parseModelProvidersJson(runSettings.modelProvidersJson),
37653
37334
  providerTurn.latestClaudeUsage,
37654
- (scope) => loadClaudeSubscriptionUsageCredential2(db, settings, {
37335
+ (scope) => loadClaudeSubscriptionUsageCredential(db, settings, {
37655
37336
  accountId: input.accountId,
37656
37337
  workspaceId: input.workspaceId,
37657
37338
  scope
37658
37339
  })
37659
37340
  );
37660
- const withClaudeUsage = (fn) => withClaudeUsageObserver(claudeUsageObserver, fn, async (providerId, headers) => {
37661
- const binding = claudeUsageObserver.binding(providerId);
37662
- if (!binding) return headers;
37663
- const credential = await resolveClaudeSubscriptionCredential(
37664
- db,
37665
- settings,
37666
- {
37667
- accountId: input.accountId,
37668
- workspaceId: input.workspaceId,
37669
- scope: binding.scope
37670
- },
37671
- {
37672
- expectedConnectionId: binding.expectedConnectionId,
37673
- expectedCredentialVersion: binding.expectedCredentialVersion
37674
- }
37675
- );
37676
- if (!credential) return headers;
37677
- if ("reconnectRequired" in credential)
37678
- throw new ClaudeSubscriptionReconnectRequired();
37679
- claudeUsageObserver.renew(providerId, credential);
37680
- headers.set("authorization", `Bearer ${credential.token}`);
37681
- headers.delete("x-api-key");
37682
- return headers;
37683
- });
37341
+ const withClaudeUsage = (fn) => withClaudeUsageObserver(claudeUsageObserver, fn);
37684
37342
  const withCodex = (fn) => codexContext ? codexRequestStorage.run(codexContext, fn) : fn();
37685
37343
  const withProviderRequestContext = (fn) => withClaudeUsage(
37686
37344
  () => providerTurn.xaiRequestContext ? xaiSubscriptionRequestStorage.run(providerTurn.xaiRequestContext, fn) : withCodex(fn)
@@ -37884,7 +37542,6 @@ These are publication receipts for the human's earlier answer. Do not call the r
37884
37542
  void 0
37885
37543
  );
37886
37544
  const runCredentials = await prepareRunCredentials({
37887
- turnTools,
37888
37545
  localMcpServerIds: installedApiIntegrations.map((integration) => integration.serverId),
37889
37546
  input,
37890
37547
  settings,
@@ -39650,4 +39307,4 @@ export {
39650
39307
  createTurnActivities,
39651
39308
  createTurnActivitiesFromServices
39652
39309
  };
39653
- //# sourceMappingURL=activities-turn-V37B7CQY.js.map
39310
+ //# sourceMappingURL=activities-turn-FQ5OO2WW.js.map