@opengeni/worker-bundle 2.2.0-canary.36844267522001 → 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 (40) 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-KQ5OK2GD.js → activities-control-MHNA3CYV.js} +66 -28
  11. package/dist/activities-control-MHNA3CYV.js.map +1 -0
  12. package/dist/{activities-turn-LSRAUGEK.js → activities-turn-FQ5OO2WW.js} +195 -459
  13. package/dist/activities-turn-FQ5OO2WW.js.map +1 -0
  14. package/dist/{chunk-WADNTBZZ.js → chunk-RZAAGRFQ.js} +64 -109
  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/failure-settlement.ts +0 -5
  24. package/src/activities/agent-turn/run-credentials.ts +3 -15
  25. package/src/activities/agent-turn/run.ts +3 -32
  26. package/src/activities/agent-turn/stream-attempt.ts +32 -58
  27. package/src/activities/agent-turn/tool-environment.ts +20 -13
  28. package/src/activities/agent-turn/turn-context.ts +0 -1
  29. package/src/activities/capabilities.ts +14 -52
  30. package/src/activities/goals.ts +78 -36
  31. package/src/activities/knowledge-indexing.ts +0 -29
  32. package/src/activities/run-credentials.ts +16 -22
  33. package/src/activities/scheduled-tasks.ts +0 -1
  34. package/src/activities/types.ts +0 -1
  35. package/src/activities/workspace-credential-provider.ts +0 -12
  36. package/dist/activities/agent-turn/model-call-admission.d.ts +0 -15
  37. package/dist/activities-control-KQ5OK2GD.js.map +0 -1
  38. package/dist/activities-turn-LSRAUGEK.js.map +0 -1
  39. package/dist/chunk-WADNTBZZ.js.map +0 -1
  40. 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-WADNTBZZ.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
  }
@@ -8042,81 +7972,6 @@ import {
8042
7972
  resolveWorkspaceAgentHumanInputEnabled
8043
7973
  } from "@opengeni/contracts";
8044
7974
 
8045
- // src/activities/agent-turn/model-call-admission.ts
8046
- function createModelCallAdmission(input) {
8047
- const receipts = /* @__PURE__ */ new WeakMap();
8048
- const responseReceipts = /* @__PURE__ */ new Map();
8049
- const pending = /* @__PURE__ */ new Set();
8050
- const responseId = (event) => {
8051
- const id = event?.response?.id;
8052
- return typeof id === "string" && id.length > 0 ? id : null;
8053
- };
8054
- let latest = Promise.resolve();
8055
- let failure2;
8056
- let failed = false;
8057
- let rejectHalted;
8058
- const halted = new Promise((_, reject) => {
8059
- rejectHalted = reject;
8060
- });
8061
- void halted.catch(() => void 0);
8062
- const fail = (error51) => {
8063
- if (failed) return;
8064
- failed = true;
8065
- failure2 = error51;
8066
- rejectHalted(error51);
8067
- for (const receipt of pending) receipt.reject(error51);
8068
- pending.clear();
8069
- responseReceipts.clear();
8070
- };
8071
- const abort = () => fail(input.signal.reason ?? new Error("Model stream cancelled"));
8072
- input.signal.addEventListener("abort", abort, { once: true });
8073
- if (input.signal.aborted) abort();
8074
- return {
8075
- beforeModelRequest: async () => {
8076
- await Promise.race([latest, halted]);
8077
- if (failed) throw failure2;
8078
- await Promise.race([input.admit(), halted]);
8079
- if (failed) throw failure2;
8080
- },
8081
- onModelResponse: (event) => {
8082
- if (failed) return Promise.reject(failure2);
8083
- const id = responseId(event);
8084
- const existing = receipts.get(event) ?? (id ? responseReceipts.get(id) : void 0) ?? (!id && pending.size === 1 ? pending.values().next().value : void 0);
8085
- if (existing) return existing.promise;
8086
- let resolve;
8087
- let reject;
8088
- const promise2 = new Promise((yes, no) => {
8089
- resolve = yes;
8090
- reject = no;
8091
- });
8092
- void promise2.catch(() => void 0);
8093
- const receipt = { promise: promise2, resolve, reject };
8094
- receipts.set(event, receipt);
8095
- if (id) responseReceipts.set(id, receipt);
8096
- pending.add(receipt);
8097
- latest = promise2;
8098
- return promise2;
8099
- },
8100
- settle: (event) => {
8101
- if (event.type !== "raw_model_stream_event" || !event.data || typeof event.data !== "object")
8102
- return;
8103
- if (event.data.type !== "response_done") return;
8104
- const id = responseId(event.data);
8105
- const receipt = receipts.get(event.data) ?? (id ? responseReceipts.get(id) : void 0) ?? (pending.size === 1 ? pending.values().next().value : void 0);
8106
- if (!receipt) return;
8107
- pending.delete(receipt);
8108
- if (id) responseReceipts.delete(id);
8109
- receipt.resolve();
8110
- },
8111
- fail,
8112
- close: () => {
8113
- input.signal.removeEventListener("abort", abort);
8114
- if (pending.size > 0) fail(new Error("Model stream closed before response settlement"));
8115
- responseReceipts.clear();
8116
- }
8117
- };
8118
- }
8119
-
8120
7975
  // src/activities/agent-turn/session-title.ts
8121
7976
  import { hasPermission } from "@opengeni/core";
8122
7977
  import { isManagedOpenRouterFreeRoute } from "@opengeni/config";
@@ -8712,31 +8567,12 @@ async function runTurnStreamAttempt(deps) {
8712
8567
  const modelResponseState = createModelResponseEventState(claimedModelUsageSourceKeys);
8713
8568
  let latestAssistantMessageText = null;
8714
8569
  let workerPreparationTotalRecorded = false;
8715
- const revalidateModelCallAdmission = async () => {
8716
- await historySink.reconcileConversationTruth({ requireDurable: true });
8717
- await ensureRunAllowedBetweenModelCalls({
8718
- settings,
8719
- db,
8720
- accountId: input.accountId,
8721
- workspaceId: input.workspaceId,
8722
- isExternallyBilledTurn: billingState.isExternallyBilledTurn,
8723
- entitlements,
8724
- chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
8725
- countsTowardTokenCap: billingState.countsTowardTokenCap,
8726
- initiatingHumanSubjectId: turn.initiatingHumanSubjectId
8727
- });
8728
- };
8729
8570
  const runStreamAttempt = async (options) => {
8730
8571
  if (!runInput) {
8731
8572
  throw new Error("Run input was not prepared");
8732
8573
  }
8733
- eventing.stream = void 0;
8734
- if (options.requireTerminalModelResponse) await revalidateModelCallAdmission();
8735
- const modelCallAdmission = createModelCallAdmission({
8736
- signal: runtimeCancellationSignal,
8737
- admit: revalidateModelCallAdmission
8738
- });
8739
8574
  const responseCountBeforeStream = modelResponseState.responseCount;
8575
+ eventing.stream = void 0;
8740
8576
  eventing.batcher = null;
8741
8577
  let currentToolBatchCallIds = /* @__PURE__ */ new Set();
8742
8578
  let currentToolBatchCompletedCallIds = /* @__PURE__ */ new Set();
@@ -8904,8 +8740,6 @@ async function runTurnStreamAttempt(deps) {
8904
8740
  }
8905
8741
  attempt.modelRequestStarted = true;
8906
8742
  return await runtime.runStream(agent, runInput, eventing.modelRunSettings, {
8907
- beforeModelRequest: modelCallAdmission.beforeModelRequest,
8908
- onModelResponse: modelCallAdmission.onModelResponse,
8909
8743
  signal: runtimeCancellationSignal,
8910
8744
  sandboxEnvironment,
8911
8745
  onModelVisibleContext: async (snapshot) => {
@@ -9012,13 +8846,7 @@ async function runTurnStreamAttempt(deps) {
9012
8846
  if (leases.xai.lost) {
9013
8847
  throw new Error("xAI credential lease expired before the model run");
9014
8848
  }
9015
- try {
9016
- eventing.stream = await withProviderRequestContext(runStreamOnce);
9017
- } catch (error51) {
9018
- modelCallAdmission.fail(error51);
9019
- modelCallAdmission.close();
9020
- throw error51;
9021
- }
8849
+ eventing.stream = await withProviderRequestContext(runStreamOnce);
9022
8850
  const streamTiming = new StreamTimingMetrics(observability, {
9023
8851
  provider: streamProvider
9024
8852
  });
@@ -9157,20 +8985,32 @@ async function runTurnStreamAttempt(deps) {
9157
8985
  await historySink.reconcileConversationTruth();
9158
8986
  turnLifecycleMetricsFor(observability).progress({ attemptId: input.attemptId });
9159
8987
  modelCheckpointMemoryCollector.schedule(observability);
9160
- await ensureRunAllowedBetweenModelCalls({
9161
- settings,
9162
- db,
9163
- accountId: input.accountId,
9164
- workspaceId: input.workspaceId,
9165
- isExternallyBilledTurn: billingState.isExternallyBilledTurn,
9166
- entitlements,
9167
- chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
9168
- countsTowardTokenCap: billingState.countsTowardTokenCap,
9169
- initiatingHumanSubjectId: turn.initiatingHumanSubjectId,
9170
- serializedRunState: () => media.compactMediaRunState(String(eventing.stream.state.toString()))
9171
- });
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
+ }
9172
9013
  }
9173
- modelCallAdmission.settle(next.value);
9174
9014
  const durableSdkEvent = generatedImageReceipt ? compactGeneratedImageSdkEvent(next.value, generatedImageReceipt) : next.value;
9175
9015
  const pendingToolCall = pendingToolCallFromSdkEvent(durableSdkEvent);
9176
9016
  if (pendingToolCall) {
@@ -9385,7 +9225,6 @@ async function runTurnStreamAttempt(deps) {
9385
9225
  }
9386
9226
  }
9387
9227
  } catch (error51) {
9388
- modelCallAdmission.fail(error51);
9389
9228
  closeStreamWaitAdmission?.();
9390
9229
  if (fallbackProviderRequestLifecycleStartedAt !== null) {
9391
9230
  const durationMs = Math.max(
@@ -9435,7 +9274,6 @@ async function runTurnStreamAttempt(deps) {
9435
9274
  }
9436
9275
  throw error51;
9437
9276
  } finally {
9438
- modelCallAdmission.close();
9439
9277
  if (!streamDone) {
9440
9278
  void iterator.return?.().catch(() => void 0);
9441
9279
  }
@@ -9757,7 +9595,6 @@ async function runTurnStreamAttempt(deps) {
9757
9595
  })) {
9758
9596
  return claimedResult({ status: "cancelled" });
9759
9597
  }
9760
- await revalidateModelCallAdmission();
9761
9598
  if (turn.source !== "compaction" && generateSessionTitleInParallel && runtime.generateSessionTitle && !runtimeCancellationSignal.aborted) {
9762
9599
  const serviceTier = serviceTierForLatencyMode(
9763
9600
  turnExecutionPolicy.providerId,
@@ -10004,9 +9841,7 @@ import {
10004
9841
  loadOrganizationModelProviderApiKey,
10005
9842
  listWorkspaceProviderCustomModels,
10006
9843
  getWorkspaceProviderCustomModelForExecution,
10007
- loadWorkspaceProviderApiKey,
10008
- loadClaudeSubscriptionUsageCredential,
10009
- assertModelConnectionAllowsTurn
9844
+ loadWorkspaceProviderApiKey
10010
9845
  } from "@opengeni/db";
10011
9846
  async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, attemptId, settings, options) {
10012
9847
  const encryptionKey = environmentsEncryptionKeyBytes(settings);
@@ -10164,24 +9999,12 @@ async function settingsWithOrganizationProviderCredentials(db, accountId, worksp
10164
9999
  if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled) continue;
10165
10000
  const models = await buildModels(kind, claudeProviderId(kind) + "/");
10166
10001
  result = withClaudeConnectionCatalog(result, { [kind]: { models } });
10167
- const binding = kind === "claude_subscription" ? await loadClaudeSubscriptionUsageCredential(db, settings, {
10168
- accountId,
10169
- workspaceId,
10170
- scope: "organization"
10171
- }) : null;
10172
- const credential = kind === "claude_subscription" ? binding?.serializedCredential : await loadOrganizationModelProviderApiKey(db, settings, {
10002
+ const credential = await loadOrganizationModelProviderApiKey(db, settings, {
10173
10003
  accountId,
10174
10004
  workspaceId,
10175
10005
  providerKind: kind
10176
10006
  });
10177
- if (credential)
10178
- result = withClaudeConnectionCredential(
10179
- result,
10180
- kind,
10181
- credential,
10182
- "organization",
10183
- binding ?? void 0
10184
- );
10007
+ if (credential) result = withClaudeConnectionCredential(result, kind, credential);
10185
10008
  const workspaceModels = await listWorkspaceProviderCustomModels(db, {
10186
10009
  accountId,
10187
10010
  workspaceId,
@@ -10204,27 +10027,15 @@ async function settingsWithOrganizationProviderCredentials(db, accountId, worksp
10204
10027
  { [kind]: { models: workspaceModels } },
10205
10028
  "workspace"
10206
10029
  );
10207
- const workspaceBinding = kind === "claude_subscription" ? await loadClaudeSubscriptionUsageCredential(db, settings, {
10208
- accountId,
10030
+ const workspaceCredential = await loadWorkspaceProviderApiKey(
10031
+ db,
10032
+ settings,
10209
10033
  workspaceId,
10210
- scope: "workspace"
10211
- }) : null;
10212
- if (workspaceBinding && workspaceModelId)
10213
- await assertModelConnectionAllowsTurn(db, {
10214
- workspaceId,
10215
- subjectId: "worker:model-access",
10216
- modelId: workspaceModelId,
10217
- workspaceProviderConnectionId: workspaceBinding.connectionId
10218
- });
10219
- const workspaceCredential = kind === "claude_subscription" ? workspaceBinding?.serializedCredential : await loadWorkspaceProviderApiKey(db, settings, workspaceId, kind, workspaceModelId);
10034
+ kind,
10035
+ workspaceModelId
10036
+ );
10220
10037
  if (workspaceCredential)
10221
- result = withClaudeConnectionCredential(
10222
- result,
10223
- kind,
10224
- workspaceCredential,
10225
- "workspace",
10226
- workspaceBinding ?? void 0
10227
- );
10038
+ result = withClaudeConnectionCredential(result, kind, workspaceCredential, "workspace");
10228
10039
  }
10229
10040
  return result;
10230
10041
  }
@@ -10442,27 +10253,20 @@ async function claimTurnAttempt(deps) {
10442
10253
  return attached.action === "claimed" && attached.turn.id === turn.id;
10443
10254
  };
10444
10255
  turnLifecycleMetricsFor(observability).start({ attemptId: input.attemptId });
10445
- let allowanceRefusal = null;
10446
- try {
10447
- await waitForTurnOperation(
10448
- ensureRunAllowed(
10449
- capabilitySettings,
10450
- db,
10451
- input.accountId,
10452
- input.workspaceId,
10453
- billingState.isExternallyBilledTurn,
10454
- entitlements,
10455
- billingState.chargesOpenGeniCredits,
10456
- billingState.countsTowardTokenCap,
10457
- turn.initiatingHumanSubjectId
10458
- ),
10459
- cancellationSignal,
10460
- void 0
10461
- );
10462
- } catch (error51) {
10463
- if (!(error51 instanceof AllowanceExhaustedError)) throw error51;
10464
- allowanceRefusal = error51.refusal;
10465
- }
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
+ );
10466
10270
  const throwIfWorkerShuttingDown = () => {
10467
10271
  const reason = activityContext?.cancellationSignal.reason;
10468
10272
  if (isWorkerShutdownCancellation(reason)) {
@@ -10567,7 +10371,6 @@ async function claimTurnAttempt(deps) {
10567
10371
  sessionStatus: inputSettlement.sessionStatus,
10568
10372
  activeTurnId: inputSettlement.activeTurnId,
10569
10373
  ...inputSettlement.suppressGoalContinuation !== void 0 ? { suppressGoalContinuation: inputSettlement.suppressGoalContinuation } : {},
10570
- ...inputSettlement.allowanceGoalPause ? { allowanceGoalPause: inputSettlement.allowanceGoalPause } : {},
10571
10374
  events: inputs,
10572
10375
  ...runState ? { runState } : {},
10573
10376
  ...compactionRequestFailure ? { compactionRequestFailure } : {}
@@ -10615,31 +10418,6 @@ async function claimTurnAttempt(deps) {
10615
10418
  durationSeconds: (performance.now() - activityStarted) / 1e3
10616
10419
  });
10617
10420
  const turnStartSettlementStartedAt = performance.now();
10618
- if (allowanceRefusal) {
10619
- if (!await eventing.settle({
10620
- events: [
10621
- { type: "usage.exhausted", payload: allowanceRefusal },
10622
- {
10623
- type: "turn.completed",
10624
- payload: {
10625
- output: "",
10626
- segmentLimit: "budget_exhausted",
10627
- ...allowanceRefusal
10628
- }
10629
- },
10630
- { type: "session.status.changed", payload: { status: "idle" } }
10631
- ],
10632
- turnStatus: "completed",
10633
- sessionStatus: "idle",
10634
- activeTurnId: null,
10635
- allowanceGoalPause: { rationale: allowanceRefusal.message }
10636
- })) {
10637
- return { exit: claimedResult({ status: "cancelled" }) };
10638
- }
10639
- control.turnMetricOutcome = "completed";
10640
- control.activityStatus = "idle";
10641
- return { exit: claimedResult({ status: "idle" }) };
10642
- }
10643
10421
  if (!await eventing.settle({
10644
10422
  events: [
10645
10423
  { type: "session.status.changed", payload: { status: "running" } },
@@ -14564,100 +14342,6 @@ import {
14564
14342
  } from "@opengeni/runtime";
14565
14343
  import { codemodeWorkspaceUrl as codemodeWorkspaceUrl2 } from "@opengeni/config";
14566
14344
 
14567
- // src/activities/mcp-account-routes.ts
14568
- function accountRouteAuthNeededPayload(payload, bindings) {
14569
- const binding = bindings?.find((candidate) => candidate.serverId === payload.serverId);
14570
- return binding ? {
14571
- ...payload,
14572
- canonicalServerId: binding.canonicalServerId,
14573
- connectionSubjectScope: binding.subjectScope
14574
- } : payload;
14575
- }
14576
- function expandMcpAccountRoutes(input) {
14577
- if (input.bindings == null) {
14578
- return { settings: input.settings, tools: input.tools, accountLabels: /* @__PURE__ */ new Map() };
14579
- }
14580
- const configured = new Map(input.settings.mcpServers.map((server) => [server.id, server]));
14581
- const byCanonical = /* @__PURE__ */ new Map();
14582
- const routes = /* @__PURE__ */ new Set();
14583
- const accounts = /* @__PURE__ */ new Set();
14584
- for (const binding of input.bindings) {
14585
- const account = JSON.stringify([binding.canonicalServerId, binding.connectionId]);
14586
- 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) {
14587
- throw new Error("Invalid accepted MCP account route");
14588
- }
14589
- routes.add(binding.serverId);
14590
- accounts.add(account);
14591
- const siblings = byCanonical.get(binding.canonicalServerId) ?? [];
14592
- siblings.push(binding);
14593
- byCanonical.set(binding.canonicalServerId, siblings);
14594
- }
14595
- const servers = [];
14596
- const tools = [];
14597
- const accountLabels = /* @__PURE__ */ new Map();
14598
- for (const tool of input.tools) {
14599
- const bindings = byCanonical.get(tool.id);
14600
- if (!bindings) {
14601
- if (!configured.get(tool.id)?.connectionRef) tools.push(tool);
14602
- continue;
14603
- }
14604
- const canonical = configured.get(tool.id);
14605
- if (!canonical?.connectionRef) {
14606
- throw new Error("Accepted MCP account route has no canonical connection configuration");
14607
- }
14608
- for (const binding of bindings) {
14609
- if (canonical.connectionRef.authoritySource === "host" || canonical.connectionRef.providerDomain !== binding.providerDomain || canonical.connectionRef.kind && canonical.connectionRef.kind !== binding.kind) {
14610
- throw new Error("Accepted MCP account route does not match canonical provider");
14611
- }
14612
- const { headers: _headers, ...config2 } = canonical;
14613
- const label = `${canonical.name ?? canonical.id} \u2014 ${binding.subjectScope === "subject" ? "Personal" : "Workspace"}: ${binding.accountLabel}`;
14614
- servers.push({
14615
- ...config2,
14616
- id: binding.serverId,
14617
- name: label,
14618
- connectionRef: structuredClone(binding.connectionRef)
14619
- });
14620
- tools.push({ ...tool, id: binding.serverId });
14621
- accountLabels.set(binding.serverId, label);
14622
- }
14623
- }
14624
- return {
14625
- settings: {
14626
- ...input.settings,
14627
- mcpServers: [
14628
- ...input.settings.mcpServers.filter((server) => !server.connectionRef),
14629
- ...servers
14630
- ]
14631
- },
14632
- tools,
14633
- accountLabels
14634
- };
14635
- }
14636
- function expandApiIntegrationAccountRoutes(input) {
14637
- const selected = new Set(input.tools.map((tool) => tool.id));
14638
- if (input.bindings == null)
14639
- return input.integrations.filter((item) => selected.has(item.serverId));
14640
- const acceptedBindings = input.bindings;
14641
- return input.integrations.flatMap((integration) => {
14642
- const bindings = acceptedBindings.filter(
14643
- (binding) => binding.canonicalServerId === integration.serverId
14644
- );
14645
- if (bindings.length === 0)
14646
- return !integration.connectionRef && selected.has(integration.serverId) ? [integration] : [];
14647
- return bindings.filter((binding) => selected.has(binding.serverId)).map((binding) => {
14648
- if (binding.connectionAuthorityGeneration === void 0) {
14649
- throw new Error("Accepted API integration account route has no authority generation");
14650
- }
14651
- return {
14652
- ...integration,
14653
- serverId: binding.serverId,
14654
- connectionRef: structuredClone(binding.connectionRef),
14655
- connectionAuthorityGeneration: binding.connectionAuthorityGeneration
14656
- };
14657
- });
14658
- });
14659
- }
14660
-
14661
14345
  // src/activities/git-credential-renewal.ts
14662
14346
  var GIT_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 6e4;
14663
14347
  var GIT_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 6e4;
@@ -15016,8 +14700,6 @@ function credentialProviderRequestBody(input, initiatingHumanSubjectId, initiati
15016
14700
  lane: "workspace",
15017
14701
  mcpServers: []
15018
14702
  }) {
15019
- const via = input.initiatorContext.via;
15020
- const latestHop = Array.isArray(via) ? via.at(-1) : null;
15021
14703
  return {
15022
14704
  type: "credentials.request",
15023
14705
  lane: selection.lane,
@@ -15032,11 +14714,6 @@ function credentialProviderRequestBody(input, initiatingHumanSubjectId, initiati
15032
14714
  turnId: input.turnId,
15033
14715
  attemptId: input.attemptId,
15034
14716
  initiator: { kind: input.initiator.kind, subjectId: input.initiator.subjectId },
15035
- initiatorContext: {
15036
- kind: latestHop?.kind === "agent" ? "agent" : input.initiator.kind === "subject" ? "human" : "service",
15037
- initiator: input.initiator,
15038
- context: input.initiatorContext
15039
- },
15040
14717
  initiatingHumanSubjectId,
15041
14718
  initiatingHuman,
15042
14719
  sandboxBackend: input.effectiveSandboxBackend,
@@ -15228,7 +14905,7 @@ async function bindRunCredentialResolver(input) {
15228
14905
  mcpServers: selectedSessionRemoteMcpTargets(
15229
14906
  input.settings,
15230
14907
  input.session.mcpServers ?? [],
15231
- input.effectiveTools,
14908
+ input.turn.tools ?? [],
15232
14909
  (input.localMcpServerIds ?? []).map((id) => ({ id }))
15233
14910
  )
15234
14911
  }
@@ -15244,23 +14921,22 @@ async function bindRunCredentialResolver(input) {
15244
14921
  workspaceId: input.workspaceId,
15245
14922
  sessionId: input.session.id
15246
14923
  };
15247
- const frozenRequest = structuredClone(
15248
- buildRunCredentialsRequest({
15249
- accountId: input.accountId,
15250
- workspaceId: input.workspaceId,
15251
- session: input.session,
15252
- turn: input.turn,
15253
- attemptId: input.attemptId,
15254
- effectiveSandboxBackend: input.effectiveSandboxBackend,
15255
- variableSet: input.variableSet,
15256
- rootSessionId,
15257
- purpose: "provision",
15258
- forceRefresh: false
15259
- })
15260
- );
15261
14924
  return {
15262
14925
  resolve: async ({ purpose, forceRefresh }) => {
15263
- 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
+ );
15264
14940
  return normalizeRunCredentialsResolution(resolution, scope);
15265
14941
  }
15266
14942
  };
@@ -15305,19 +14981,13 @@ async function prepareRunCredentials(deps) {
15305
14981
  const platformGitResources = turnResources.filter(
15306
14982
  (resource) => resource.kind !== "repository" || repositoryHasExplicitGitConnection(resource)
15307
14983
  );
15308
- const accountRoutes = expandMcpAccountRoutes({
15309
- settings: runSettings,
15310
- tools: deps.turnTools,
15311
- bindings: turn.mcpAccountBindings
15312
- });
15313
14984
  const runCredentialResolver = effectiveRunCredentialBackend === "none" || effectiveRunCredentialBackend === "selfhosted" ? null : await waitForTurnOperation(
15314
14985
  bindRunCredentialResolver({
15315
14986
  db,
15316
- settings: accountRoutes.settings,
14987
+ settings: runSettings,
15317
14988
  initiatingHumanSubjectId: turn.initiatingHumanSubjectId ?? null,
15318
14989
  connectionCredentials: connectionCredentials ?? null,
15319
14990
  localMcpServerIds: deps.localMcpServerIds ?? [],
15320
- effectiveTools: accountRoutes.tools,
15321
14991
  accountId: input.accountId,
15322
14992
  workspaceId: input.workspaceId,
15323
14993
  session,
@@ -15356,9 +15026,9 @@ async function prepareRunCredentials(deps) {
15356
15026
  ) : null;
15357
15027
  const runMcpCredentials = new RunMcpCredentials(
15358
15028
  selectedSessionRemoteMcpTargets2(
15359
- accountRoutes.settings,
15029
+ runSettings,
15360
15030
  session.mcpServers ?? [],
15361
- accountRoutes.tools,
15031
+ turn.tools ?? [],
15362
15032
  (deps.localMcpServerIds ?? []).map((id) => ({ id }))
15363
15033
  ),
15364
15034
  {
@@ -16740,6 +16410,100 @@ function isGitHubApiDestination(value) {
16740
16410
  }
16741
16411
  }
16742
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
+
16743
16507
  // src/activities/agent-turn/tool-environment.ts
16744
16508
  import { createMcpOperationPersistence } from "@opengeni/db/mcp-operations";
16745
16509
 
@@ -32493,10 +32257,8 @@ import {
32493
32257
  buildApiIntegrationMcpServers,
32494
32258
  resolveCatalogSettings as resolveCatalogSettings2,
32495
32259
  resolveWorkspaceModelSelection,
32496
- loadWorkspaceCodexModelAvailability,
32497
32260
  withFrozenPersonalConnectionDelegations,
32498
- resolveTurnToolPolicy,
32499
- scheduledTurnMcpServerIds,
32261
+ resolveSessionToolPolicy,
32500
32262
  hasPermission as hasPermission2
32501
32263
  } from "@opengeni/core";
32502
32264
  import { SandboxChannelAService as SandboxChannelAService3 } from "@opengeni/runtime/sandbox";
@@ -33941,17 +33703,21 @@ async function prepareTurnToolPolicy(deps) {
33941
33703
  } = deps;
33942
33704
  const turnResources = mergeResourceRefs(session.resources, turn.resources);
33943
33705
  const runtimeResources = runtimeResourcesForTurn(session.resources, turn.resources);
33944
- 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({
33945
33712
  toolPolicy: session.toolPolicy,
33946
- session,
33947
- turn,
33948
- availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),
33949
- 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(
33950
33716
  db,
33951
33717
  input.workspaceId,
33952
33718
  capabilitySettings,
33953
33719
  fileAuthoritySubjectId ?? void 0
33954
- ) : []
33720
+ ) : [])
33955
33721
  });
33956
33722
  const mcpAvailabilityNote = unavailableMcpOperationalContext({
33957
33723
  droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,
@@ -34517,8 +34283,7 @@ async function prepareTurnToolRuntime(deps) {
34517
34283
  organizationGatewayConnectionActive,
34518
34284
  organizationGatewayCustomModels,
34519
34285
  organizationOpenRouterConnectionActive,
34520
- organizationOpenRouterCustomModels,
34521
- codexModelAvailability
34286
+ organizationOpenRouterCustomModels
34522
34287
  ] = await Promise.all([
34523
34288
  getWorkspaceConnectionModelRestrictions(
34524
34289
  db,
@@ -34561,12 +34326,10 @@ async function prepareTurnToolRuntime(deps) {
34561
34326
  accountId: input.accountId,
34562
34327
  workspaceId: input.workspaceId,
34563
34328
  providerKind: "openrouter"
34564
- }),
34565
- loadWorkspaceCodexModelAvailability(db, currentSettings, input.workspaceId)
34329
+ })
34566
34330
  ]);
34567
34331
  return {
34568
34332
  selections: resolveWorkspaceModelSelection({
34569
- observations: codexModelAvailability,
34570
34333
  connectionModelRestrictions,
34571
34334
  settings: currentSettings,
34572
34335
  policy,
@@ -34710,7 +34473,7 @@ async function prepareTurnToolRuntime(deps) {
34710
34473
  sessionAttachedRemoteMcpTargets: selectedSessionRemoteMcpTargets3(
34711
34474
  githubRestMcp.settings,
34712
34475
  session.mcpServers ?? [],
34713
- githubRestMcp.tools,
34476
+ turn.tools ?? [],
34714
34477
  localMcpServers
34715
34478
  ),
34716
34479
  ...deps.runMcpCredentials ? { runMcpCredentials: deps.runMcpCredentials } : {},
@@ -37115,14 +36878,11 @@ function createRunAgentTurnActivity(services) {
37115
36878
  getModelRunSettings: () => eventing.modelRunSettings,
37116
36879
  getExecutionGeneration: () => attempt.executionGeneration
37117
36880
  });
37118
- const checkpointBeforeProviderDispatch = async () => {
37119
- await awaitModelCallAdmission();
37120
- await checkpointHistoryBeforeProviderDispatch(historySink, {
37121
- effectiveSandboxBackend: eventing.modelRunSettings.sandboxBackend,
37122
- routingEnabled: routingEnabled(settings),
37123
- readActiveSandbox: () => readActiveSandbox3(db, input.workspaceId, input.sessionId)
37124
- });
37125
- };
36881
+ const checkpointBeforeProviderDispatch = () => checkpointHistoryBeforeProviderDispatch(historySink, {
36882
+ effectiveSandboxBackend: eventing.modelRunSettings.sandboxBackend,
36883
+ routingEnabled: routingEnabled(settings),
36884
+ readActiveSandbox: () => readActiveSandbox3(db, input.workspaceId, input.sessionId)
36885
+ });
37126
36886
  try {
37127
36887
  const claimed = await claimTurnAttempt({
37128
36888
  input,
@@ -37265,7 +37025,7 @@ function createRunAgentTurnActivity(services) {
37265
37025
  requiredGeneratedVideoFiles
37266
37026
  });
37267
37027
  if ("exit" in governance) return governance.exit;
37268
- await assertModelConnectionAllowsTurn2(db, {
37028
+ await assertModelConnectionAllowsTurn(db, {
37269
37029
  workspaceId: input.workspaceId,
37270
37030
  subjectId: turn.initiatingHumanSubjectId ?? "worker:model-access",
37271
37031
  modelId: turnExecutionPolicy.productModelId,
@@ -37572,36 +37332,13 @@ function createRunAgentTurnActivity(services) {
37572
37332
  const claudeUsageObserver = await createClaudeUsageObserver(
37573
37333
  parseModelProvidersJson(runSettings.modelProvidersJson),
37574
37334
  providerTurn.latestClaudeUsage,
37575
- (scope) => loadClaudeSubscriptionUsageCredential2(db, settings, {
37335
+ (scope) => loadClaudeSubscriptionUsageCredential(db, settings, {
37576
37336
  accountId: input.accountId,
37577
37337
  workspaceId: input.workspaceId,
37578
37338
  scope
37579
37339
  })
37580
37340
  );
37581
- const withClaudeUsage = (fn) => withClaudeUsageObserver(claudeUsageObserver, fn, async (providerId, headers) => {
37582
- const binding = claudeUsageObserver.binding(providerId);
37583
- if (!binding) return headers;
37584
- const credential = await resolveClaudeSubscriptionCredential(
37585
- db,
37586
- settings,
37587
- {
37588
- accountId: input.accountId,
37589
- workspaceId: input.workspaceId,
37590
- scope: binding.scope
37591
- },
37592
- {
37593
- expectedConnectionId: binding.expectedConnectionId,
37594
- expectedCredentialVersion: binding.expectedCredentialVersion
37595
- }
37596
- );
37597
- if (!credential) return headers;
37598
- if ("reconnectRequired" in credential)
37599
- throw new ClaudeSubscriptionReconnectRequired();
37600
- claudeUsageObserver.renew(providerId, credential);
37601
- headers.set("authorization", `Bearer ${credential.token}`);
37602
- headers.delete("x-api-key");
37603
- return headers;
37604
- });
37341
+ const withClaudeUsage = (fn) => withClaudeUsageObserver(claudeUsageObserver, fn);
37605
37342
  const withCodex = (fn) => codexContext ? codexRequestStorage.run(codexContext, fn) : fn();
37606
37343
  const withProviderRequestContext = (fn) => withClaudeUsage(
37607
37344
  () => providerTurn.xaiRequestContext ? xaiSubscriptionRequestStorage.run(providerTurn.xaiRequestContext, fn) : withCodex(fn)
@@ -37805,7 +37542,6 @@ These are publication receipts for the human's earlier answer. Do not call the r
37805
37542
  void 0
37806
37543
  );
37807
37544
  const runCredentials = await prepareRunCredentials({
37808
- turnTools,
37809
37545
  localMcpServerIds: installedApiIntegrations.map((integration) => integration.serverId),
37810
37546
  input,
37811
37547
  settings,
@@ -39571,4 +39307,4 @@ export {
39571
39307
  createTurnActivities,
39572
39308
  createTurnActivitiesFromServices
39573
39309
  };
39574
- //# sourceMappingURL=activities-turn-LSRAUGEK.js.map
39310
+ //# sourceMappingURL=activities-turn-FQ5OO2WW.js.map