@opengeni/worker-bundle 1.4.2 → 1.4.5-canary.37458084490001

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 (48) hide show
  1. package/dist/activities/agent-turn/errors.d.ts +75 -2
  2. package/dist/activities/agent-turn/governance-model.d.ts +2 -1
  3. package/dist/activities/agent-turn/model-usage.d.ts +22 -0
  4. package/dist/activities/agent-turn/provider-recovery-copy.d.ts +24 -0
  5. package/dist/activities/agent-turn/provider-recovery-policy.d.ts +6 -0
  6. package/dist/activities/agent-turn/turn-context.d.ts +9 -0
  7. package/dist/activities/capabilities.d.ts +2 -0
  8. package/dist/activities/sandbox-lease.d.ts +5 -0
  9. package/dist/activities/types.d.ts +3 -0
  10. package/dist/{activities-control-AKJZHDTY.js → activities-control-KBOSUF5Y.js} +45 -15
  11. package/dist/activities-control-KBOSUF5Y.js.map +1 -0
  12. package/dist/{activities-turn-AOXNE6BM.js → activities-turn-QOR26CTC.js} +230 -39
  13. package/dist/activities-turn-QOR26CTC.js.map +1 -0
  14. package/dist/artifact-materializer-entry.js +0 -0
  15. package/dist/artifact-outbox-entry.js +0 -0
  16. package/dist/{chunk-DCQ7XTXW.js → chunk-CMIUQ2D3.js} +114 -13
  17. package/dist/chunk-CMIUQ2D3.js.map +1 -0
  18. package/dist/{chunk-WVZQJBGD.js → chunk-WX5PX2C6.js} +245 -20
  19. package/dist/chunk-WX5PX2C6.js.map +1 -0
  20. package/dist/index.js +5 -5
  21. package/dist/index.js.map +1 -1
  22. package/dist/observability-metrics.d.ts +61 -6
  23. package/dist/workflow-bundle.js +72 -39
  24. package/package.json +21 -21
  25. package/src/activities/agent-turn/admission.ts +7 -8
  26. package/src/activities/agent-turn/claim.ts +20 -1
  27. package/src/activities/agent-turn/errors.ts +296 -13
  28. package/src/activities/agent-turn/failure-settlement.ts +19 -7
  29. package/src/activities/agent-turn/governance-model.ts +3 -0
  30. package/src/activities/agent-turn/model-usage.ts +114 -3
  31. package/src/activities/agent-turn/provider-recovery-copy.ts +76 -0
  32. package/src/activities/agent-turn/provider-recovery-metrics.ts +1 -1
  33. package/src/activities/agent-turn/provider-recovery-policy.ts +25 -0
  34. package/src/activities/agent-turn/run.ts +14 -1
  35. package/src/activities/agent-turn/stream-attempt.ts +68 -1
  36. package/src/activities/agent-turn/turn-context.ts +5 -0
  37. package/src/activities/automations.ts +5 -2
  38. package/src/activities/capabilities.ts +58 -2
  39. package/src/activities/sandbox-lease.ts +17 -3
  40. package/src/activities/session-state.ts +41 -5
  41. package/src/activities/types.ts +3 -1
  42. package/src/index.ts +2 -2
  43. package/src/observability-metrics.ts +186 -17
  44. package/src/workflows/session.ts +22 -12
  45. package/dist/activities-control-AKJZHDTY.js.map +0 -1
  46. package/dist/activities-turn-AOXNE6BM.js.map +0 -1
  47. package/dist/chunk-DCQ7XTXW.js.map +0 -1
  48. package/dist/chunk-WVZQJBGD.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  CODEX_USAGE_LIMIT_MAX_RESUME_MS,
3
3
  CodexPlanEntitlementError,
4
+ PROVIDER_OVERLOAD_RECOVERY_CODE,
4
5
  PostCompactionContinuationEmptyError,
5
6
  SandboxDeadlineRotationError,
6
7
  agentRunFailurePayload,
@@ -9,6 +10,7 @@ import {
9
10
  armTurnQuiescenceWatchdog,
10
11
  assertAgentStreamNotCancelled,
11
12
  assertPhysicalToolQuiescenceForCancellation,
13
+ assertProviderOverloadRecoveryActive,
12
14
  assertSessionAttemptQuiescenceRecoveryDurable,
13
15
  assertSuccessfulAgentStreamCompletion,
14
16
  assessCodexPlanEntitlement,
@@ -61,11 +63,14 @@ import {
61
63
  postClaimDatabaseRecoveryFailure,
62
64
  preClaimAdmissionFailure,
63
65
  projectRejectedProviderArtifacts,
66
+ providerRecoveryCode,
64
67
  providerRecoveryCountAfterModelRequestPhase,
65
68
  providerRecoveryCountFromMetadata,
66
69
  providerRecoveryExhaustedFailure,
70
+ providerRecoveryLimit,
67
71
  providerRecoveryResult,
68
72
  providerRetryAfterMs,
73
+ readProviderRecoveryStartedAt,
69
74
  refreshCodexUsageAndRepairCapacityWaiters,
70
75
  refreshExhaustedXaiQuota,
71
76
  releaseTurnSandboxAfterWriterDrain,
@@ -99,9 +104,10 @@ import {
99
104
  waitForTurnOperation,
100
105
  waitForWarmSnapshot,
101
106
  withFirstPartyTools,
107
+ withModelRoutePresentation,
102
108
  wrapLazyTurnBoxWithRouting,
103
109
  wrapTurnBoxWithRouting
104
- } from "./chunk-WVZQJBGD.js";
110
+ } from "./chunk-WX5PX2C6.js";
105
111
  import {
106
112
  StreamTimingMetrics,
107
113
  makeMachineOpObserver,
@@ -115,8 +121,10 @@ import {
115
121
  recordContextCompactionStarted,
116
122
  recordCreditMicros,
117
123
  recordModelCacheTokens,
124
+ recordModelCreditsCharged,
118
125
  recordModelInputTokens,
119
126
  recordModelRequestPhase,
127
+ recordModelResponseUsage,
120
128
  recordSandboxAutomaticRecoverySelected,
121
129
  recordSandboxLogicalProvision,
122
130
  recordSandboxProvisionAttempt,
@@ -134,7 +142,7 @@ import {
134
142
  runtimeMetricsHooksForObservability,
135
143
  sandboxAutomaticRecoveryOutcome,
136
144
  turnLifecycleMetricsFor
137
- } from "./chunk-DCQ7XTXW.js";
145
+ } from "./chunk-CMIUQ2D3.js";
138
146
  import {
139
147
  __export
140
148
  } from "./chunk-PZ5AY32C.js";
@@ -154,7 +162,7 @@ import {
154
162
  import { resolveAgentToolFamilies as resolveAgentToolFamilies3 } from "@opengeni/contracts";
155
163
  import {
156
164
  assertModelConnectionAllowsTurn,
157
- freezeAgentLearningPolicy as freezeAgentLearningPolicy2,
165
+ freezeAgentLearningPolicy as freezeAgentLearningPolicy3,
158
166
  recoverLegacyKnowledgeConfirmations,
159
167
  withSessionRlsActorContext
160
168
  } from "@opengeni/db";
@@ -5321,11 +5329,16 @@ import {
5321
5329
  calculateModelListUsageCostSnapshot,
5322
5330
  calculateModelUsageCostBreakdown,
5323
5331
  configuredModelListPricingSchedules,
5332
+ configuredModels,
5324
5333
  configuredModelPricingSchedules,
5325
5334
  resolveModelProvider,
5326
5335
  responseSatisfiesLatencyMode,
5327
5336
  OPENGENI_GATEWAY_PROVIDER_ID,
5328
- WORKSPACE_GATEWAY_PROVIDER_ID
5337
+ OPPER_PROVIDER_ID,
5338
+ ORGANIZATION_OPPER_PROVIDER_ID,
5339
+ WORKSPACE_GATEWAY_PROVIDER_ID,
5340
+ WORKSPACE_OPPER_PROVIDER_ID,
5341
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX
5329
5342
  } from "@opengeni/config";
5330
5343
  import { CODEX_PROVIDER_ID } from "@opengeni/codex";
5331
5344
  function modelUsageSourceKey(input) {
@@ -5433,7 +5446,8 @@ async function processModelResponseTerminalEvent(input) {
5433
5446
  gatewayBilling: responseUsage.gatewayBilling,
5434
5447
  sourceKey,
5435
5448
  ...input.latencyMode ? { latencyMode: input.latencyMode } : {},
5436
- observability: input.observability
5449
+ observability: input.observability,
5450
+ metricProvider: input.provider
5437
5451
  });
5438
5452
  authoritative = await emitModelCallUsage({
5439
5453
  observability: input.observability,
@@ -5471,6 +5485,14 @@ async function processModelResponseTerminalEvent(input) {
5471
5485
  billing,
5472
5486
  ...input.contextContributions !== void 0 ? { contextContributions: input.contextContributions } : {}
5473
5487
  });
5488
+ recordAuthoritativeModelUsageMetrics({
5489
+ observability: input.observability,
5490
+ settings: input.settings,
5491
+ provider: input.provider,
5492
+ model: input.model,
5493
+ externallyBilled: input.externallyBilled,
5494
+ billing
5495
+ });
5474
5496
  }
5475
5497
  const observedInput = normalizedUsage.telemetry.inputTokens;
5476
5498
  if (authoritative && observedInput !== null && observedInput > 0) {
@@ -5533,7 +5555,8 @@ async function processCompactionModelUsageEvent(input) {
5533
5555
  normalizedUsage,
5534
5556
  gatewayBilling: input.usage.gatewayBilling,
5535
5557
  sourceKey,
5536
- observability: input.observability
5558
+ observability: input.observability,
5559
+ metricProvider: input.provider
5537
5560
  });
5538
5561
  authoritative = await emitModelCallUsage({
5539
5562
  observability: input.observability,
@@ -5571,6 +5594,14 @@ async function processCompactionModelUsageEvent(input) {
5571
5594
  billing,
5572
5595
  ...input.contextContributions !== void 0 ? { contextContributions: input.contextContributions } : {}
5573
5596
  });
5597
+ recordAuthoritativeModelUsageMetrics({
5598
+ observability: input.observability,
5599
+ settings: input.settings,
5600
+ provider: input.provider,
5601
+ model: input.model,
5602
+ externallyBilled: input.externallyBilled,
5603
+ billing
5604
+ });
5574
5605
  }
5575
5606
  }
5576
5607
  });
@@ -5673,10 +5704,11 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5673
5704
  const countsTowardTokenCap = input.countsTowardTokenCap ?? !input.externallyBilled;
5674
5705
  const resolvedGatewayModel = input.gatewayBilling ? resolveModelProvider(settings, input.model) : void 0;
5675
5706
  const gatewayProviderId = resolvedGatewayModel?.provider.id;
5676
- const gatewayBilling = gatewayProviderId === OPENGENI_GATEWAY_PROVIDER_ID || gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID ? input.gatewayBilling : void 0;
5707
+ const opperReported = (gatewayProviderId === OPPER_PROVIDER_ID || gatewayProviderId === WORKSPACE_OPPER_PROVIDER_ID || gatewayProviderId === ORGANIZATION_OPPER_PROVIDER_ID) && input.gatewayBilling?.finalProvider === "opper";
5708
+ const gatewayBilling = gatewayProviderId === OPENGENI_GATEWAY_PROVIDER_ID || gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID || opperReported ? input.gatewayBilling : void 0;
5677
5709
  const allowedProviders = resolvedGatewayModel?.model.requestPolicy?.gateway.only;
5678
- const unpinnedWorkspaceGatewayModel = gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID && allowedProviders === void 0;
5679
- if (gatewayBilling) {
5710
+ const unpinnedWorkspaceGatewayModel = gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID && allowedProviders === void 0 || opperReported && gatewayProviderId !== OPPER_PROVIDER_ID;
5711
+ if (gatewayBilling && !opperReported) {
5680
5712
  if (!unpinnedWorkspaceGatewayModel && (!allowedProviders || !allowedProviders.includes(gatewayBilling.finalProvider))) {
5681
5713
  throw new Error(
5682
5714
  `AI Gateway reported unapproved provider ${gatewayBilling.finalProvider} for ${input.model}`
@@ -5815,6 +5847,15 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5815
5847
  }
5816
5848
  });
5817
5849
  recordCreditMicros(input.observability, "usage", result.debitedMicros);
5850
+ try {
5851
+ recordModelCreditsCharged(input.observability, {
5852
+ provider: input.metricProvider ?? "unknown",
5853
+ model: modelMetricProductId(settings, input.metricProvider, input.model),
5854
+ debitedMicros: result.debitedMicros,
5855
+ grantDebitedMicros: result.grantDebitedMicros
5856
+ });
5857
+ } catch {
5858
+ }
5818
5859
  }
5819
5860
  return {
5820
5861
  billingPath: "opengeni_credits",
@@ -5827,6 +5868,43 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5827
5868
  ...gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}
5828
5869
  };
5829
5870
  }
5871
+ var modelMetricProductIds = /* @__PURE__ */ new WeakMap();
5872
+ function modelMetricProductId(settings, provider, model) {
5873
+ if (provider?.startsWith("workspace-") || model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX)) {
5874
+ return "custom";
5875
+ }
5876
+ let cache = modelMetricProductIds.get(settings);
5877
+ if (!cache) {
5878
+ cache = /* @__PURE__ */ new Map();
5879
+ modelMetricProductIds.set(settings, cache);
5880
+ }
5881
+ const cached2 = cache.get(model);
5882
+ if (cached2 !== void 0) return cached2;
5883
+ let label = "custom";
5884
+ try {
5885
+ const canonical = canonicalizeConfiguredModelId(settings, model);
5886
+ if (configuredModels(settings).some((candidate) => candidate.id === canonical)) {
5887
+ label = canonical;
5888
+ }
5889
+ } catch {
5890
+ }
5891
+ if (cache.size < 256) cache.set(model, label);
5892
+ return label;
5893
+ }
5894
+ function recordAuthoritativeModelUsageMetrics(input) {
5895
+ try {
5896
+ const telemetry = input.billing.normalizedUsage.telemetry;
5897
+ recordModelResponseUsage(input.observability, {
5898
+ provider: input.provider,
5899
+ model: modelMetricProductId(input.settings, input.provider, input.model),
5900
+ payer: input.externallyBilled ? "external" : "deployment",
5901
+ tokens: telemetry,
5902
+ estimatedProviderCostMicros: input.billing.estimatedProviderCostMicros,
5903
+ pricingSource: input.billing.pricingSource
5904
+ });
5905
+ } catch {
5906
+ }
5907
+ }
5830
5908
  async function recordAuthoritativeModelCallFact(input) {
5831
5909
  try {
5832
5910
  const telemetry = input.billing.normalizedUsage.telemetry;
@@ -6040,14 +6118,13 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
6040
6118
  throw new Error("insufficient Opengeni credits");
6041
6119
  }
6042
6120
  }
6043
- if (chargesOpenGeniCredits) {
6044
- const refusal = await checkWorkspaceAllowance(db, {
6045
- accountId,
6046
- workspaceId,
6047
- subjectId: initiatingHumanSubjectId
6048
- });
6049
- if (refusal) throw new AllowanceExhaustedError(refusal);
6050
- }
6121
+ const refusal = await checkWorkspaceAllowance(db, {
6122
+ accountId,
6123
+ workspaceId,
6124
+ subjectId: initiatingHumanSubjectId,
6125
+ ...chargesOpenGeniCredits ? {} : { fundedWithoutCredits: true }
6126
+ });
6127
+ if (refusal) throw new AllowanceExhaustedError(refusal);
6051
6128
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
6052
6129
  const limits = configuredStaticUsageLimits(settings);
6053
6130
  if (limits.maxMonthlyAgentRunsPerWorkspace) {
@@ -6079,7 +6156,7 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
6079
6156
  // src/activities/agent-turn/provider-recovery-metrics.ts
6080
6157
  function providerRecoveryCause(code) {
6081
6158
  if (code === "provider_rate_limited") return "rate_limited";
6082
- if (code === "provider_unavailable") return "unavailable";
6159
+ if (code === "provider_unavailable" || code === "provider_overloaded") return "unavailable";
6083
6160
  if (code === "upstream_connectivity_unavailable") return "connectivity";
6084
6161
  return null;
6085
6162
  }
@@ -7486,14 +7563,19 @@ async function settleTurnFailureInAttempt(deps) {
7486
7563
  const earlyDefinitionMismatch = error51 instanceof TurnExecutionPolicyDefinitionMismatchError && !attempt.modelRequestStarted && !eventing.turnStartedPublished && !!attempt.turnId && !!attempt.triggerEventId && attempt.executionGeneration > 0;
7487
7564
  const earlyCommandStartUnavailable = isModalTaskExecStartPreDispatchUnavailableError(error51) && !attempt.modelRequestStarted && !eventing.turnStartedPublished && !!attempt.turnId && !!attempt.triggerEventId && attempt.executionGeneration > 0;
7488
7565
  const earlyRecoverableSetup = earlyDefinitionMismatch || earlyCommandStartUnavailable;
7489
- let failure2 = earlyDefinitionMismatch ? { error: error51.message, code: error51.code, retryable: true } : codexTerminalFailure ?? agentRunFailurePayload(error51, {
7490
- isCodexTurn: billingState.isCodexTurn
7491
- });
7566
+ let failure2 = withModelRoutePresentation(
7567
+ earlyDefinitionMismatch ? { error: error51.message, code: error51.code, retryable: true } : codexTerminalFailure ?? agentRunFailurePayload(error51, {
7568
+ isCodexTurn: billingState.isCodexTurn
7569
+ }),
7570
+ attempt.modelRoutePresentation
7571
+ );
7492
7572
  if (attempt.turnId && (earlyRecoverableSetup || failure2.retryable && eventing.publish && eventing.turnStartedPublished)) {
7493
7573
  const nextProviderRecoveryCount = attempt.providerRecoveryCount + 1;
7574
+ const recoveryCode = providerRecoveryCode(error51, failure2);
7494
7575
  const recoveryResult = providerRecoveryResult({
7495
- failureCode: failure2.code,
7576
+ failureCode: recoveryCode,
7496
7577
  attemptNumber: nextProviderRecoveryCount,
7578
+ recoveryStartedAt: attempt.providerRecoveryCount > 0 ? attempt.providerRecoveryStartedAt : void 0,
7497
7579
  retryAfterMs: providerRetryAfterMs(error51),
7498
7580
  jitterSample: Math.random()
7499
7581
  });
@@ -7540,12 +7622,13 @@ async function settleTurnFailureInAttempt(deps) {
7540
7622
  turnId: attempt.turnId,
7541
7623
  triggerEventId: attempt.triggerEventId,
7542
7624
  attemptId: input.attemptId,
7543
- reason: failure2.code ?? "provider_unavailable",
7625
+ reason: recoveryCode ?? "provider_unavailable",
7544
7626
  providerRecoveryCount: nextProviderRecoveryCount,
7545
7627
  detail: {
7546
7628
  ...agentRunRecoveryFailurePayload(error51, failure2),
7547
7629
  continueDelayMs: recoveryResult.continueDelayMs,
7548
- providerRecoveryCount: nextProviderRecoveryCount
7630
+ providerRecoveryCount: nextProviderRecoveryCount,
7631
+ maxProviderRecoveryCount: providerRecoveryLimit(recoveryCode)
7549
7632
  }
7550
7633
  });
7551
7634
  if (recovery.action === "stale") {
@@ -7614,8 +7697,9 @@ async function settleTurnFailureInAttempt(deps) {
7614
7697
  triggerEventId: attempt.triggerEventId,
7615
7698
  executionGeneration: attempt.executionGeneration,
7616
7699
  providerRecovery: {
7617
- failureCode: failure2.code ?? "provider_unavailable",
7618
- providerRecoveryCount: nextProviderRecoveryCount
7700
+ failureCode: recoveryCode ?? "provider_unavailable",
7701
+ providerRecoveryCount: nextProviderRecoveryCount,
7702
+ ...recoveryCode === PROVIDER_OVERLOAD_RECOVERY_CODE ? { continueDelayMs: recoveryResult.continueDelayMs } : {}
7619
7703
  }
7620
7704
  }) : setupRecoveryExhausted ? postClaimDatabaseRecoveryFailure({
7621
7705
  error: recoveryError,
@@ -7665,7 +7749,14 @@ async function settleTurnFailureInAttempt(deps) {
7665
7749
  }
7666
7750
 
7667
7751
  // src/activities/agent-turn/stream-attempt.ts
7668
- import { measureMcpPhase as measureMcpPhase2, withMcpCallIdentity as withMcpCallIdentity2 } from "@opengeni/observability";
7752
+ import {
7753
+ agentToolCallOutcome,
7754
+ agentToolMetricFamily,
7755
+ interactionInterventionMetricObserver,
7756
+ measureMcpPhase as measureMcpPhase2,
7757
+ recordAgentToolCall,
7758
+ withMcpCallIdentity as withMcpCallIdentity2
7759
+ } from "@opengeni/observability";
7669
7760
  import {
7670
7761
  appendSessionHistoryItems as appendSessionHistoryItems3,
7671
7762
  sessionTurnFinalReplyFacts,
@@ -9755,6 +9846,7 @@ async function runTurnStreamAttempt(deps) {
9755
9846
  const responseCountBeforeStream = modelResponseState.responseCount;
9756
9847
  eventing.batcher = null;
9757
9848
  let currentToolBatchCallIds = /* @__PURE__ */ new Set();
9849
+ const toolCallMetricStarts = /* @__PURE__ */ new Map();
9758
9850
  let currentToolBatchCompletedCallIds = /* @__PURE__ */ new Set();
9759
9851
  let streamSawPerResponseUsage = false;
9760
9852
  const messagePhases = new AssistantMessagePhaseTracker();
@@ -9826,6 +9918,11 @@ async function runTurnStreamAttempt(deps) {
9826
9918
  count: turnTools.length
9827
9919
  });
9828
9920
  }
9921
+ assertProviderOverloadRecoveryActive({
9922
+ failureCode: attempt.providerRecoveryPolicyCode,
9923
+ providerRecoveryCount: attempt.providerRecoveryCount,
9924
+ recoveryStartedAt: attempt.providerRecoveryStartedAt
9925
+ });
9829
9926
  };
9830
9927
  const ownedEstablished = ownedTurnSandboxForAgent(sandboxState);
9831
9928
  const runStreamOnce = async () => {
@@ -10378,6 +10475,26 @@ async function runTurnStreamAttempt(deps) {
10378
10475
  runSettings.mcpServers,
10379
10476
  withMcpToolDisplayMetadata(preparedServers, event.payload)
10380
10477
  );
10478
+ const created = event.payload;
10479
+ if (typeof created.id === "string") {
10480
+ toolCallMetricStarts.set(created.id, {
10481
+ family: agentToolMetricFamily(
10482
+ typeof created.toolFamily === "string" ? created.toolFamily : null,
10483
+ typeof created.name === "string" ? created.name : typeof created.toolName === "string" ? created.toolName : null
10484
+ ),
10485
+ startedAtMs: performance.now()
10486
+ });
10487
+ }
10488
+ }
10489
+ if (event.type === "agent.toolCall.output") {
10490
+ const id = event.payload.id;
10491
+ const started = typeof id === "string" ? toolCallMetricStarts.get(id) : void 0;
10492
+ if (typeof id === "string") toolCallMetricStarts.delete(id);
10493
+ recordAgentToolCall(observability, {
10494
+ family: started?.family ?? "other",
10495
+ outcome: agentToolCallOutcome(event.payload),
10496
+ ...started ? { durationMs: performance.now() - started.startedAtMs } : {}
10497
+ });
10381
10498
  }
10382
10499
  streamTiming.onEvent(event.type);
10383
10500
  if (event.type === "agent.toolCall.output") {
@@ -10536,7 +10653,8 @@ async function runTurnStreamAttempt(deps) {
10536
10653
  normalizedUsage: normalizedAggregateUsage,
10537
10654
  sourceKey: aggregateSourceKey,
10538
10655
  latencyMode: turnExecutionPolicy.latencyMode,
10539
- observability
10656
+ observability,
10657
+ metricProvider: resolvedModel?.provider.id ?? settings.openaiProvider
10540
10658
  });
10541
10659
  const aggregateProvider = resolvedModel?.provider.id ?? settings.openaiProvider;
10542
10660
  const aggregateProviderApi = resolvedModel?.provider.api ?? "responses";
@@ -10575,6 +10693,14 @@ async function runTurnStreamAttempt(deps) {
10575
10693
  billing,
10576
10694
  contextContributions: eventing.companyBrainContextContributions
10577
10695
  });
10696
+ recordAuthoritativeModelUsageMetrics({
10697
+ observability,
10698
+ settings,
10699
+ provider: aggregateProvider,
10700
+ model: turn.model,
10701
+ externallyBilled: billingState.isExternallyBilledTurn,
10702
+ billing
10703
+ });
10578
10704
  }
10579
10705
  if (aggregateAuthoritative && aggregateInput !== null && aggregateInput > 0) {
10580
10706
  recordModelInputTokens(observability, streamProvider, aggregateInput);
@@ -10734,6 +10860,11 @@ async function runTurnStreamAttempt(deps) {
10734
10860
  })) {
10735
10861
  return claimedResult({ status: "cancelled" });
10736
10862
  }
10863
+ const observeIntervention = interactionInterventionMetricObserver(observability);
10864
+ for (const interruption of interactionInterventionInterruptions) {
10865
+ if (interruption.input.operation !== "request") continue;
10866
+ observeIntervention({ kind: interruption.input.kind, outcome: "opened" });
10867
+ }
10737
10868
  await finalizeTurnOpStreamOps();
10738
10869
  control.activityStatus = "requires_action";
10739
10870
  return claimedResult({ status: "requires_action" });
@@ -11115,7 +11246,7 @@ import {
11115
11246
  } from "@opengeni/config";
11116
11247
  import {
11117
11248
  environmentsEncryptionKeyBytes as environmentsEncryptionKeyBytes3,
11118
- WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
11249
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX as WORKSPACE_GATEWAY_MODEL_ID_PREFIX2,
11119
11250
  WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
11120
11251
  withCodexCatalogProvider,
11121
11252
  withWorkspaceGatewayCatalogProvider,
@@ -11128,6 +11259,12 @@ import {
11128
11259
  withOrganizationOpenRouterCredential,
11129
11260
  ORGANIZATION_GATEWAY_MODEL_ID_PREFIX,
11130
11261
  ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX,
11262
+ ORGANIZATION_OPPER_MODEL_ID_PREFIX,
11263
+ WORKSPACE_OPPER_MODEL_ID_PREFIX,
11264
+ withOrganizationOpperCatalogProvider,
11265
+ withOrganizationOpperCredential,
11266
+ withWorkspaceOpperCatalogProvider,
11267
+ withWorkspaceOpperCredential,
11131
11268
  withXaiSubscriptionCatalogProvider
11132
11269
  } from "@opengeni/config";
11133
11270
  import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
@@ -11142,6 +11279,7 @@ import {
11142
11279
  workspaceCodexSubscriptionActive,
11143
11280
  loadWorkspaceVercelAiGatewayApiKey,
11144
11281
  loadWorkspaceOpenRouterApiKey,
11282
+ loadWorkspaceOpperApiKey,
11145
11283
  listOrganizationModelProviderCustomModelsForWorkspace,
11146
11284
  getOrganizationModelProviderCustomModelForExecution,
11147
11285
  loadOrganizationModelProviderApiKey,
@@ -11235,8 +11373,8 @@ async function settingsWithWorkspaceGatewayCredential(db, accountId, workspaceId
11235
11373
  workspaceId
11236
11374
  });
11237
11375
  const retainedUpstreamModelId = retainedProductModelId?.startsWith(
11238
- WORKSPACE_GATEWAY_MODEL_ID_PREFIX
11239
- ) ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX.length) : null;
11376
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX2
11377
+ ) ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX2.length) : null;
11240
11378
  const retainedCustomModel = retainedUpstreamModelId ? await getWorkspaceGatewayCustomModelForExecution(db, {
11241
11379
  accountId,
11242
11380
  workspaceId,
@@ -11279,6 +11417,28 @@ async function settingsWithWorkspaceOpenRouterCredential(db, accountId, workspac
11279
11417
  );
11280
11418
  return apiKey ? withWorkspaceOpenRouterCredential(catalogSettings, apiKey, customModels) : catalogSettings;
11281
11419
  }
11420
+ async function settingsWithWorkspaceOpperCredential(db, accountId, workspaceId, settings, retainedProductModelId) {
11421
+ const activeCustomModels = await listWorkspaceProviderCustomModels(db, {
11422
+ accountId,
11423
+ workspaceId,
11424
+ providerKind: "opper"
11425
+ });
11426
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
11427
+ WORKSPACE_OPPER_MODEL_ID_PREFIX
11428
+ ) ? retainedProductModelId.slice(WORKSPACE_OPPER_MODEL_ID_PREFIX.length) : null;
11429
+ const retainedCustomModel = retainedUpstreamModelId ? await getWorkspaceProviderCustomModelForExecution(db, {
11430
+ accountId,
11431
+ workspaceId,
11432
+ providerKind: "opper",
11433
+ upstreamModelId: retainedUpstreamModelId
11434
+ }) : null;
11435
+ const customModels = retainedCustomModel && !activeCustomModels.some(
11436
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId
11437
+ ) ? [...activeCustomModels, retainedCustomModel] : activeCustomModels;
11438
+ const catalogSettings = withWorkspaceOpperCatalogProvider(settings, customModels);
11439
+ const apiKey = await loadWorkspaceOpperApiKey(db, settings, workspaceId, retainedProductModelId);
11440
+ return apiKey ? withWorkspaceOpperCredential(catalogSettings, apiKey, customModels) : catalogSettings;
11441
+ }
11282
11442
  async function settingsWithOrganizationProviderCredentials(db, accountId, workspaceId, settings, retainedProductModelId) {
11283
11443
  const buildModels = async (providerKind, prefix) => {
11284
11444
  const active = await listOrganizationModelProviderCustomModelsForWorkspace(db, {
@@ -11308,7 +11468,14 @@ async function settingsWithOrganizationProviderCredentials(db, accountId, worksp
11308
11468
  workspaceId,
11309
11469
  providerKind: "openrouter"
11310
11470
  });
11311
- let result = openRouterKey ? withOrganizationOpenRouterCredential(gatewaySettings, openRouterKey, openRouterModels) : withOrganizationOpenRouterCatalogProvider(gatewaySettings, openRouterModels);
11471
+ const openRouterSettings = openRouterKey ? withOrganizationOpenRouterCredential(gatewaySettings, openRouterKey, openRouterModels) : withOrganizationOpenRouterCatalogProvider(gatewaySettings, openRouterModels);
11472
+ const opperModels = await buildModels("opper", ORGANIZATION_OPPER_MODEL_ID_PREFIX);
11473
+ const opperKey = await loadOrganizationModelProviderApiKey(db, settings, {
11474
+ accountId,
11475
+ workspaceId,
11476
+ providerKind: "opper"
11477
+ });
11478
+ let result = opperKey ? withOrganizationOpperCredential(openRouterSettings, opperKey, opperModels) : withOrganizationOpperCatalogProvider(openRouterSettings, opperModels);
11312
11479
  for (const kind of CLAUDE_CONNECTION_KINDS) {
11313
11480
  if (kind === "claude_subscription" && !settings.claudeSubscriptionEnabled) continue;
11314
11481
  const models = await buildModels(kind, claudeProviderId(kind) + "/");
@@ -11453,7 +11620,9 @@ async function claimTurnAttempt(deps) {
11453
11620
  attempt.dispatchId = dispatchId;
11454
11621
  attempt.executionGeneration = turn.executionGeneration;
11455
11622
  attempt.providerRecoveryCount = providerRecoveryCountFromMetadata(turn.metadata);
11623
+ attempt.providerRecoveryPolicyCode = typeof turn.metadata.providerRecoveryReason === "string" ? turn.metadata.providerRecoveryReason : void 0;
11456
11624
  attempt.providerRecoveryObservation = readProviderRecoveryObservation(turn.metadata ?? {});
11625
+ attempt.providerRecoveryStartedAt = readProviderRecoveryStartedAt(turn.metadata);
11457
11626
  const authRecovery = turn.metadata?.claudeAuthRecovery;
11458
11627
  attempt.claudeAuthRecovery = authRecovery && typeof authRecovery === "object" && "credentialId" in authRecovery && typeof authRecovery.credentialId === "string" && "credentialVersion" in authRecovery && typeof authRecovery.credentialVersion === "number" && Number.isSafeInteger(authRecovery.credentialVersion) && authRecovery.credentialVersion > 0 ? {
11459
11628
  credentialId: authRecovery.credentialId,
@@ -11515,13 +11684,20 @@ async function claimTurnAttempt(deps) {
11515
11684
  xaiSettings,
11516
11685
  claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
11517
11686
  );
11518
- const workspaceProviderSettings = await settingsWithWorkspaceOpenRouterCredential(
11687
+ const openRouterSettings = await settingsWithWorkspaceOpenRouterCredential(
11519
11688
  db,
11520
11689
  input.accountId,
11521
11690
  input.workspaceId,
11522
11691
  gatewaySettings,
11523
11692
  claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
11524
11693
  );
11694
+ const workspaceProviderSettings = await settingsWithWorkspaceOpperCredential(
11695
+ db,
11696
+ input.accountId,
11697
+ input.workspaceId,
11698
+ openRouterSettings,
11699
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
11700
+ );
11525
11701
  let capabilitySettings = await settingsWithOrganizationProviderCredentials(
11526
11702
  db,
11527
11703
  input.accountId,
@@ -11579,6 +11755,11 @@ async function claimTurnAttempt(deps) {
11579
11755
  provider: turnExecutionPolicy.providerId,
11580
11756
  model: turnExecutionPolicy.productModelId
11581
11757
  };
11758
+ attempt.modelRoutePresentation = {
11759
+ model: turnExecutionPolicy.productModelId,
11760
+ modelLabel: verifiedExecutionPolicy.model.label,
11761
+ providerLabel: verifiedExecutionPolicy.model.providerLabel
11762
+ };
11582
11763
  assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);
11583
11764
  const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);
11584
11765
  billingState.isExternallyBilledTurn = billingIdentity.externallyBilled;
@@ -13251,6 +13432,7 @@ async function prepareGovernanceAndModel(deps) {
13251
13432
  const companyProfileIncluded = contextSelection.receipt.companyProfileIncluded;
13252
13433
  const workspaceGovernance = renderWorkspaceGovernanceContext(
13253
13434
  {
13435
+ learningPolicy: deps.learningPolicy,
13254
13436
  companyProfile: companyProfileSnapshot,
13255
13437
  instructionPolicy: instructionPolicySnapshot,
13256
13438
  preferences: preferenceSnapshot
@@ -17284,13 +17466,13 @@ async function prepareRunCredentials(deps) {
17284
17466
  // src/activities/agent-turn/knowledge-source-tools.ts
17285
17467
  import { isRetiredNativeAtlassianSource } from "@opengeni/contracts/atlassian-native-retirement";
17286
17468
  import {
17287
- freezeAgentLearningPolicy,
17469
+ freezeAgentLearningPolicy as freezeAgentLearningPolicy2,
17288
17470
  getScheduledTaskRunAcceptedExecution,
17289
17471
  readScheduledKnowledgeSource
17290
17472
  } from "@opengeni/db";
17291
17473
  async function createKnowledgeSourceAttemptTools(input) {
17292
17474
  if (input.context.actor.kind !== "agent") return [];
17293
- const policy = await freezeAgentLearningPolicy(input.db, input.context);
17475
+ const policy = await freezeAgentLearningPolicy2(input.db, input.context);
17294
17476
  if (typeof policy.scheduledTaskRunId !== "string") return [];
17295
17477
  const runId = policy.scheduledTaskRunId;
17296
17478
  const accepted = await getScheduledTaskRunAcceptedExecution(input.db, {
@@ -17302,7 +17484,7 @@ async function createKnowledgeSourceAttemptTools(input) {
17302
17484
  if (isRetiredNativeAtlassianSource(source)) return [];
17303
17485
  const actor = input.context.actor;
17304
17486
  const authorize = async () => {
17305
- const current = await freezeAgentLearningPolicy(input.db, input.context);
17487
+ const current = await freezeAgentLearningPolicy2(input.db, input.context);
17306
17488
  if (current.scheduledTaskRunId !== runId) throw new Error("Source run authority changed");
17307
17489
  };
17308
17490
  const definition = (name, title, description, inputSchema, execute, readOnly) => ({
@@ -17333,7 +17515,7 @@ async function createKnowledgeSourceAttemptTools(input) {
17333
17515
  "Fetch selected source",
17334
17516
  "Fetch a checkpointed batch from this scheduled task's selected source. Retains original files and searchable source content under the run's Knowledge policy. It does not create findings. Use knowledge_source_read to inspect content, then knowledge_save for useful findings with evidence. Call again if action is continue. Review first stages content without interrupting this task; Off keeps Knowledge disabled.",
17335
17517
  { type: "object", properties: {}, additionalProperties: false },
17336
- async () => (await freezeAgentLearningPolicy(input.db, input.context)).effective.knowledge === "off" ? { action: "disabled", reason: "Knowledge is Off for this run" } : input.fetch({
17518
+ async () => (await freezeAgentLearningPolicy2(input.db, input.context)).effective.knowledge === "off" ? { action: "disabled", reason: "Knowledge is Off for this run" } : input.fetch({
17337
17519
  accountId: input.context.accountId,
17338
17520
  workspaceId: input.context.workspaceId,
17339
17521
  taskId: accepted.task.id,
@@ -38547,13 +38729,20 @@ function createRunAgentTurnActivity(services) {
38547
38729
  } catch {
38548
38730
  }
38549
38731
  };
38732
+ const assertRecoveryWindow = () => assertProviderOverloadRecoveryActive({
38733
+ failureCode: attempt.providerRecoveryPolicyCode,
38734
+ providerRecoveryCount: attempt.providerRecoveryCount,
38735
+ recoveryStartedAt: attempt.providerRecoveryStartedAt
38736
+ });
38550
38737
  const checkpointBeforeProviderDispatch = async () => {
38738
+ assertRecoveryWindow();
38551
38739
  await awaitModelCallAdmission();
38552
38740
  await checkpointHistoryBeforeProviderDispatch(historySink, {
38553
38741
  effectiveSandboxBackend: eventing.modelRunSettings.sandboxBackend,
38554
38742
  routingEnabled: routingEnabled(settings),
38555
38743
  readActiveSandbox: () => readActiveSandbox3(db, input.workspaceId, input.sessionId)
38556
38744
  });
38745
+ assertRecoveryWindow();
38557
38746
  };
38558
38747
  try {
38559
38748
  const claimed = await claimTurnAttempt({
@@ -38584,6 +38773,7 @@ function createRunAgentTurnActivity(services) {
38584
38773
  if (!eventing.publish || !eventing.settle) {
38585
38774
  throw new Error("turn eventing was not wired during claim");
38586
38775
  }
38776
+ assertRecoveryWindow();
38587
38777
  const wiredEventing = eventing;
38588
38778
  const {
38589
38779
  turn,
@@ -38622,7 +38812,7 @@ function createRunAgentTurnActivity(services) {
38622
38812
  provider: turnExecutionPolicy.providerId,
38623
38813
  backend: turn.sandboxBackend
38624
38814
  },
38625
- () => freezeAgentLearningPolicy2(db, {
38815
+ () => freezeAgentLearningPolicy3(db, {
38626
38816
  accountId: input.accountId,
38627
38817
  workspaceId: input.workspaceId,
38628
38818
  actor: learningActor
@@ -38724,6 +38914,7 @@ function createRunAgentTurnActivity(services) {
38724
38914
  );
38725
38915
  }
38726
38916
  const governance = await prepareGovernanceAndModel({
38917
+ learningPolicy: learning,
38727
38918
  input,
38728
38919
  db,
38729
38920
  observability,
@@ -41096,4 +41287,4 @@ export {
41096
41287
  createTurnActivities,
41097
41288
  createTurnActivitiesFromServices
41098
41289
  };
41099
- //# sourceMappingURL=activities-turn-AOXNE6BM.js.map
41290
+ //# sourceMappingURL=activities-turn-QOR26CTC.js.map