@opengeni/worker-bundle 0.23.3-canary.0 → 0.23.4-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +10 -2
  2. package/dist/activities/agent-turn/claim.d.ts +1 -0
  3. package/dist/activities/agent-turn/codex.d.ts +2 -2
  4. package/dist/activities/agent-turn/list-models.d.ts +16 -0
  5. package/dist/activities/agent-turn/model-usage.d.ts +10 -1
  6. package/dist/activities/agent-turn/tool-environment.d.ts +1 -0
  7. package/dist/activities/agent-turn/tool-policy.d.ts +36 -5
  8. package/dist/activities/agent-turn/turn-context.d.ts +2 -0
  9. package/dist/activities/automations.d.ts +1 -0
  10. package/dist/activities/capabilities.d.ts +2 -1
  11. package/dist/activities/goals.d.ts +11 -0
  12. package/dist/activities/image-generation-references.d.ts +2 -1
  13. package/dist/activities/scheduled-tasks.d.ts +1 -0
  14. package/dist/activities/types.d.ts +8 -0
  15. package/dist/{activities-control-52W5IDWM.js → activities-control-SGU2WEVB.js} +206 -97
  16. package/dist/activities-control-SGU2WEVB.js.map +1 -0
  17. package/dist/activities-control.d.ts +2 -0
  18. package/dist/{activities-turn-A2G2KLSY.js → activities-turn-7EAQXW6Q.js} +301 -65
  19. package/dist/activities-turn-7EAQXW6Q.js.map +1 -0
  20. package/dist/activities.d.ts +2 -0
  21. package/dist/{chunk-IPVMCAW5.js → chunk-S2QVRVJW.js} +85 -23
  22. package/dist/chunk-S2QVRVJW.js.map +1 -0
  23. package/dist/{chunk-GFNXVZVQ.js → chunk-TJIPCHMP.js} +3 -2
  24. package/dist/chunk-TJIPCHMP.js.map +1 -0
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +29 -6
  27. package/dist/index.js.map +1 -1
  28. package/dist/observability-metrics.d.ts +1 -0
  29. package/dist/workflow-bundle.js +26 -3
  30. package/dist/workflows/activities.d.ts +5 -0
  31. package/dist/workflows/automations.d.ts +5 -0
  32. package/package.json +17 -17
  33. package/src/activities/agent-run-admission.ts +7 -1
  34. package/src/activities/agent-turn/admission.ts +28 -6
  35. package/src/activities/agent-turn/claim.ts +25 -5
  36. package/src/activities/agent-turn/codex.ts +2 -2
  37. package/src/activities/agent-turn/compaction-prep.ts +2 -0
  38. package/src/activities/agent-turn/list-models.ts +101 -0
  39. package/src/activities/agent-turn/model-usage.ts +88 -42
  40. package/src/activities/agent-turn/run.ts +6 -3
  41. package/src/activities/agent-turn/stream-attempt.ts +8 -0
  42. package/src/activities/agent-turn/tool-environment.ts +62 -1
  43. package/src/activities/agent-turn/tool-policy.ts +58 -5
  44. package/src/activities/agent-turn/turn-context.ts +4 -0
  45. package/src/activities/automations.ts +122 -67
  46. package/src/activities/capabilities.ts +72 -2
  47. package/src/activities/goals.ts +107 -31
  48. package/src/activities/image-generation-references.ts +9 -9
  49. package/src/activities/scheduled-tasks.ts +120 -26
  50. package/src/activities/site-auth-maintenance.ts +12 -12
  51. package/src/activities/types.ts +6 -0
  52. package/src/activities.ts +1 -0
  53. package/src/activity-services.ts +4 -1
  54. package/src/github-rest-mcp.ts +2 -1
  55. package/src/index.ts +19 -4
  56. package/src/observability-metrics.ts +2 -0
  57. package/src/workflows/activities.ts +15 -0
  58. package/src/workflows/automations.ts +21 -2
  59. package/dist/activities-control-52W5IDWM.js.map +0 -1
  60. package/dist/activities-turn-A2G2KLSY.js.map +0 -1
  61. package/dist/chunk-GFNXVZVQ.js.map +0 -1
  62. package/dist/chunk-IPVMCAW5.js.map +0 -1
@@ -81,7 +81,7 @@ import {
81
81
  waitForTurnOperation,
82
82
  waitForWarmSnapshot,
83
83
  withFirstPartyTools
84
- } from "./chunk-IPVMCAW5.js";
84
+ } from "./chunk-S2QVRVJW.js";
85
85
  import {
86
86
  StreamTimingMetrics,
87
87
  makeMachineOpObserver,
@@ -106,7 +106,7 @@ import {
106
106
  recordTurnWorkerPreparationTotal,
107
107
  runtimeMetricsHooksForObservability,
108
108
  turnLifecycleMetricsFor
109
- } from "./chunk-GFNXVZVQ.js";
109
+ } from "./chunk-TJIPCHMP.js";
110
110
 
111
111
  // src/activities-turn.ts
112
112
  import { createProductionAgentRuntime, summarizeForCompaction as summarizeForCompaction2 } from "@opengeni/runtime";
@@ -3466,7 +3466,9 @@ function createTurnContext(input) {
3466
3466
  billingState: {
3467
3467
  isCodexTurn: false,
3468
3468
  isXaiTurn: false,
3469
- isExternallyBilledTurn: false
3469
+ isExternallyBilledTurn: false,
3470
+ chargesOpenGeniCredits: true,
3471
+ countsTowardTokenCap: true
3470
3472
  },
3471
3473
  sandboxState: {
3472
3474
  resolvedSandbox: null,
@@ -4946,11 +4948,13 @@ import {
4946
4948
  } from "@opengeni/runtime";
4947
4949
  import {
4948
4950
  calculateGatewayReportedCostBreakdown,
4951
+ calculateGatewayReportedProviderCostMicros,
4949
4952
  calculateModelUsageCostBreakdown,
4950
4953
  configuredModelPricingSchedules,
4954
+ resolveModelProvider,
4951
4955
  responseSatisfiesLatencyMode,
4952
- OPENGENI_GATEWAY_MODELS,
4953
- OPENGENI_GATEWAY_PROVIDER_ID
4956
+ OPENGENI_GATEWAY_PROVIDER_ID,
4957
+ WORKSPACE_GATEWAY_PROVIDER_ID
4954
4958
  } from "@opengeni/config";
4955
4959
  import { CODEX_PROVIDER_ID } from "@opengeni/codex";
4956
4960
  function modelUsageSourceKey(input) {
@@ -5035,9 +5039,10 @@ async function processModelResponseTerminalEvent(input) {
5035
5039
  turnAttemptId: input.turnAttemptId,
5036
5040
  model: input.model,
5037
5041
  externallyBilled: input.externallyBilled,
5042
+ ...input.chargesOpenGeniCredits !== void 0 ? { chargesOpenGeniCredits: input.chargesOpenGeniCredits } : {},
5043
+ ...input.countsTowardTokenCap !== void 0 ? { countsTowardTokenCap: input.countsTowardTokenCap } : {},
5038
5044
  usage: responseUsage.usage,
5039
5045
  normalizedUsage,
5040
- gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,
5041
5046
  gatewayBilling: responseUsage.gatewayBilling,
5042
5047
  sourceKey,
5043
5048
  ...input.latencyMode ? { latencyMode: input.latencyMode } : {},
@@ -5056,6 +5061,8 @@ async function processModelResponseTerminalEvent(input) {
5056
5061
  sourceKey,
5057
5062
  usage: responseUsage,
5058
5063
  normalizedUsage,
5064
+ ...billing ? { billingPath: billing.billingPath } : {},
5065
+ ...billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {},
5059
5066
  servingAccountHash: accountContext.servingAccountHash,
5060
5067
  accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,
5061
5068
  emittedSourceKeys: input.emittedSourceKeys
@@ -5131,9 +5138,10 @@ async function processCompactionModelUsageEvent(input) {
5131
5138
  turnAttemptId: input.turnAttemptId,
5132
5139
  model: input.model,
5133
5140
  externallyBilled: input.externallyBilled,
5141
+ ...input.chargesOpenGeniCredits !== void 0 ? { chargesOpenGeniCredits: input.chargesOpenGeniCredits } : {},
5142
+ ...input.countsTowardTokenCap !== void 0 ? { countsTowardTokenCap: input.countsTowardTokenCap } : {},
5134
5143
  usage: input.usage.usage,
5135
5144
  normalizedUsage,
5136
- gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,
5137
5145
  gatewayBilling: input.usage.gatewayBilling,
5138
5146
  sourceKey,
5139
5147
  observability: input.observability
@@ -5151,6 +5159,8 @@ async function processCompactionModelUsageEvent(input) {
5151
5159
  sourceKey,
5152
5160
  usage: input.usage,
5153
5161
  normalizedUsage,
5162
+ ...billing ? { billingPath: billing.billingPath } : {},
5163
+ ...billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {},
5154
5164
  servingAccountHash: accountContext.servingAccountHash,
5155
5165
  accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,
5156
5166
  emittedSourceKeys: input.emittedSourceKeys
@@ -5197,6 +5207,8 @@ async function emitModelCallUsage(input) {
5197
5207
  providerApi: input.providerApi,
5198
5208
  model: input.model,
5199
5209
  sourceKey: input.sourceKey,
5210
+ ...input.billingPath ? { billingPath: input.billingPath } : {},
5211
+ ...input.upstreamProvider ? { upstreamProvider: input.upstreamProvider } : {},
5200
5212
  ...telemetry
5201
5213
  }
5202
5214
  }
@@ -5253,20 +5265,33 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5253
5265
  const inputTokens = sanitizedUsage.inputTokens ?? 0;
5254
5266
  const outputTokens = sanitizedUsage.outputTokens ?? 0;
5255
5267
  const totalTokens = sanitizedUsage.totalTokens ?? 0;
5256
- const gatewayBilling = input.gatewayManaged ? input.gatewayBilling : void 0;
5268
+ const chargesOpenGeniCredits = input.chargesOpenGeniCredits ?? !input.externallyBilled;
5269
+ const countsTowardTokenCap = input.countsTowardTokenCap ?? !input.externallyBilled;
5270
+ const resolvedGatewayModel = input.gatewayBilling ? resolveModelProvider(settings, input.model) : void 0;
5271
+ const gatewayProviderId = resolvedGatewayModel?.provider.id;
5272
+ const gatewayBilling = gatewayProviderId === OPENGENI_GATEWAY_PROVIDER_ID || gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID ? input.gatewayBilling : void 0;
5273
+ const allowedProviders = resolvedGatewayModel?.model.requestPolicy?.gateway.only;
5274
+ const unpinnedWorkspaceGatewayModel = gatewayProviderId === WORKSPACE_GATEWAY_PROVIDER_ID && allowedProviders === void 0;
5257
5275
  if (gatewayBilling) {
5258
- const gatewayModel = Object.values(OPENGENI_GATEWAY_MODELS).find(
5259
- (candidate) => candidate.productId === input.model
5260
- );
5261
- if (!gatewayModel || !gatewayModel.providers.includes(gatewayBilling.finalProvider)) {
5276
+ if (!unpinnedWorkspaceGatewayModel && (!allowedProviders || !allowedProviders.includes(gatewayBilling.finalProvider))) {
5262
5277
  throw new Error(
5263
5278
  `AI Gateway reported unapproved provider ${gatewayBilling.finalProvider} for ${input.model}`
5264
5279
  );
5265
5280
  }
5281
+ if (unpinnedWorkspaceGatewayModel && chargesOpenGeniCredits) {
5282
+ throw new Error(
5283
+ `Workspace Gateway custom model ${input.model} cannot charge OpenGeni credits without pinned pricing`
5284
+ );
5285
+ }
5266
5286
  }
5267
5287
  const pricingSchedules = configuredModelPricingSchedules(settings);
5268
5288
  const configuredPricingModel = pricingSchedules[input.model] ? input.model : input.model.startsWith("codex/") && pricingSchedules[input.model.slice("codex/".length)] ? input.model.slice("codex/".length) : null;
5269
- const pricingBreakdown = gatewayBilling ? calculateGatewayReportedCostBreakdown(
5289
+ const pricingBreakdown = gatewayBilling ? unpinnedWorkspaceGatewayModel ? {
5290
+ providerCostMicros: calculateGatewayReportedProviderCostMicros(
5291
+ gatewayBilling.inferenceCostUsd
5292
+ ),
5293
+ creditCostMicros: 0
5294
+ } : calculateGatewayReportedCostBreakdown(
5270
5295
  settings,
5271
5296
  input.model,
5272
5297
  gatewayBilling.inferenceCostUsd,
@@ -5277,42 +5302,43 @@ async function recordModelUsageAndDebitCredits(settings, db, input) {
5277
5302
  const hasCompleteCoreTokenTelemetry = normalizedUsage.telemetry.inputTokens !== null && normalizedUsage.telemetry.outputTokens !== null;
5278
5303
  const estimatedProviderCostMicros = gatewayBilling ? pricingBreakdown?.providerCostMicros ?? null : hasCompleteCoreTokenTelemetry ? pricingBreakdown?.providerCostMicros ?? null : null;
5279
5304
  const pricingSource = gatewayBilling ? "gateway_reported" : estimatedProviderCostMicros !== null ? "configured_list_price" : null;
5280
- if (input.externallyBilled) {
5305
+ if (countsTowardTokenCap && totalTokens > 0) {
5281
5306
  await recordUsageEvent(db, {
5282
5307
  accountId: input.accountId,
5283
5308
  workspaceId: input.workspaceId,
5284
- eventType: "model.cost",
5285
- quantity: 0,
5286
- unit: "usd_micros",
5309
+ eventType: "model.tokens",
5310
+ quantity: totalTokens,
5311
+ unit: "tokens",
5287
5312
  sourceResourceType: "model_response",
5288
5313
  sourceResourceId: `${input.turnId}:${input.sourceKey}`,
5289
5314
  sessionId: input.sessionId,
5290
5315
  turnId: input.turnId,
5291
5316
  turnAttemptId: input.turnAttemptId,
5292
- idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`
5317
+ idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`
5293
5318
  });
5294
- return {
5295
- billingPath: "external",
5296
- pricedCostMicros: 0,
5297
- estimatedProviderCostMicros,
5298
- pricingSource,
5299
- normalizedUsage
5300
- };
5301
5319
  }
5302
- if (totalTokens > 0) {
5320
+ if (!chargesOpenGeniCredits) {
5303
5321
  await recordUsageEvent(db, {
5304
5322
  accountId: input.accountId,
5305
5323
  workspaceId: input.workspaceId,
5306
- eventType: "model.tokens",
5307
- quantity: totalTokens,
5308
- unit: "tokens",
5324
+ eventType: "model.cost",
5325
+ quantity: 0,
5326
+ unit: "usd_micros",
5309
5327
  sourceResourceType: "model_response",
5310
5328
  sourceResourceId: `${input.turnId}:${input.sourceKey}`,
5311
5329
  sessionId: input.sessionId,
5312
5330
  turnId: input.turnId,
5313
5331
  turnAttemptId: input.turnAttemptId,
5314
- idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`
5332
+ idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`
5315
5333
  });
5334
+ return {
5335
+ billingPath: "external",
5336
+ pricedCostMicros: 0,
5337
+ estimatedProviderCostMicros,
5338
+ pricingSource,
5339
+ normalizedUsage,
5340
+ ...gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}
5341
+ };
5316
5342
  }
5317
5343
  const shouldDebit = settings.billingMode === "stripe" || settings.usageLimitsMode === "managed";
5318
5344
  if (!shouldDebit || totalTokens === 0 && !gatewayBilling) {
@@ -5440,6 +5466,10 @@ function assertWorkspaceHumanInputAllowed(enabled, kind, attempted) {
5440
5466
  function credentialSubjectIdForTurnInitiator(turn) {
5441
5467
  return directPersonalConnectionSubjectId(turn);
5442
5468
  }
5469
+ function xaiCatalogReadinessAuthority(turn, directCredentialSubjectId) {
5470
+ const subjectId = turn.initiatingHumanSubjectId ?? directCredentialSubjectId;
5471
+ return subjectId ? { subjectId, authoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot } : null;
5472
+ }
5443
5473
  function isDirectHumanTurnInitiation(turn) {
5444
5474
  if (turn.source !== "user" && turn.source !== "api" || turn.initiator.kind !== "subject") {
5445
5475
  return false;
@@ -5466,6 +5496,7 @@ function shouldPublishToolAuthNeededForTurn(payload, trigger, turn) {
5466
5496
  function turnExecutionPolicyBillingIdentity(policy) {
5467
5497
  return {
5468
5498
  externallyBilled: policy.billing.metering === "external",
5499
+ countsTowardTokenCap: policy.billing.upstreamPayer === "deployment",
5469
5500
  codexSubscription: policy.providerId === "codex-subscription" && policy.credentialSource.kind === "connected_subscription" && policy.credentialSource.provider === "codex",
5470
5501
  xaiSubscription: policy.providerId === "supergrok-subscription" && policy.credentialSource.kind === "connected_subscription" && policy.credentialSource.provider === "xai"
5471
5502
  };
@@ -5519,8 +5550,8 @@ var BudgetExhaustedError = class extends Error {
5519
5550
  this.name = "BudgetExhaustedError";
5520
5551
  }
5521
5552
  };
5522
- async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternallyBilledTurn, entitlements) {
5523
- if (!isExternallyBilledTurn && entitlements && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5553
+ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternallyBilledTurn, entitlements, chargesOpenGeniCredits = !isExternallyBilledTurn, countsTowardTokenCap = !isExternallyBilledTurn) {
5554
+ if (chargesOpenGeniCredits && entitlements && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5524
5555
  const decision = await entitlements.admitRun({
5525
5556
  accountId,
5526
5557
  workspaceId,
@@ -5530,7 +5561,7 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
5530
5561
  if (!decision.allowed) {
5531
5562
  throw new Error(decision.reason || "insufficient OpenGeni credits");
5532
5563
  }
5533
- } else if (!isExternallyBilledTurn && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5564
+ } else if (chargesOpenGeniCredits && (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")) {
5534
5565
  const balance = await getBillingBalance(db, accountId);
5535
5566
  if (balance.balanceMicros <= 0) {
5536
5567
  throw new Error("insufficient OpenGeni credits");
@@ -5550,7 +5581,7 @@ async function ensureRunAllowed(settings, db, accountId, workspaceId, isExternal
5550
5581
  );
5551
5582
  }
5552
5583
  }
5553
- if (!isExternallyBilledTurn && limits.maxMonthlyTokensPerWorkspace) {
5584
+ if (countsTowardTokenCap && limits.maxMonthlyTokensPerWorkspace) {
5554
5585
  const used = await sumUsageQuantity(db, {
5555
5586
  workspaceId,
5556
5587
  eventType: "model.tokens",
@@ -8452,6 +8483,8 @@ async function runTurnStreamAttempt(deps) {
8452
8483
  latencyMode: turnExecutionPolicy.latencyMode,
8453
8484
  metricProvider: streamProvider,
8454
8485
  externallyBilled: billingState.isExternallyBilledTurn,
8486
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
8487
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
8455
8488
  servingCredentialId: providerTurn.effectiveCodexCredentialId,
8456
8489
  priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,
8457
8490
  emittedSourceKeys: emittedModelUsageSourceKeys,
@@ -8509,7 +8542,9 @@ async function runTurnStreamAttempt(deps) {
8509
8542
  input.accountId,
8510
8543
  input.workspaceId,
8511
8544
  billingState.isExternallyBilledTurn,
8512
- entitlements
8545
+ entitlements,
8546
+ billingState.chargesOpenGeniCredits,
8547
+ billingState.countsTowardTokenCap
8513
8548
  );
8514
8549
  } catch (limitError) {
8515
8550
  let serializedRunState = null;
@@ -8802,6 +8837,8 @@ async function runTurnStreamAttempt(deps) {
8802
8837
  turnAttemptId: input.attemptId,
8803
8838
  model: turn.model,
8804
8839
  externallyBilled: billingState.isExternallyBilledTurn,
8840
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
8841
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
8805
8842
  usage: aggregateUsage,
8806
8843
  normalizedUsage: normalizedAggregateUsage,
8807
8844
  sourceKey: aggregateSourceKey,
@@ -8823,6 +8860,8 @@ async function runTurnStreamAttempt(deps) {
8823
8860
  sourceKey: aggregateSourceKey,
8824
8861
  usage: { usage: aggregateUsage },
8825
8862
  normalizedUsage: normalizedAggregateUsage,
8863
+ ...billing ? { billingPath: billing.billingPath } : {},
8864
+ ...billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {},
8826
8865
  servingAccountHash: aggregateAccountCtx.servingAccountHash,
8827
8866
  accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,
8828
8867
  emittedSourceKeys: emittedModelUsageSourceKeys
@@ -9191,17 +9230,26 @@ import {
9191
9230
  // src/activities/capabilities.ts
9192
9231
  import {
9193
9232
  environmentsEncryptionKeyBytes as environmentsEncryptionKeyBytes2,
9233
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
9234
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
9194
9235
  withCodexCatalogProvider,
9195
9236
  withWorkspaceGatewayCatalogProvider,
9196
9237
  withWorkspaceGatewayCredential,
9238
+ withWorkspaceOpenRouterCatalogProvider,
9239
+ withWorkspaceOpenRouterCredential,
9197
9240
  withXaiSubscriptionCatalogProvider
9198
9241
  } from "@opengeni/config";
9199
9242
  import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
9200
9243
  import {
9244
+ getWorkspaceGatewayCustomModelForExecution,
9245
+ getWorkspaceOpenRouterCustomModelForExecution,
9201
9246
  listSessionMcpServerMetadata,
9202
9247
  listSessionMcpServersForRun,
9248
+ listWorkspaceGatewayCustomModels,
9249
+ listWorkspaceOpenRouterCustomModels,
9203
9250
  workspaceCodexSubscriptionActive,
9204
- loadWorkspaceVercelAiGatewayApiKey
9251
+ loadWorkspaceVercelAiGatewayApiKey,
9252
+ loadWorkspaceOpenRouterApiKey
9205
9253
  } from "@opengeni/db";
9206
9254
  async function settingsWithSessionMcpServersForRun(db, workspaceId, sessionId, attemptId, settings, options) {
9207
9255
  const encryptionKey = environmentsEncryptionKeyBytes2(settings);
@@ -9263,15 +9311,48 @@ function withCodexProvider(settings) {
9263
9311
  function withXaiSubscriptionProvider(settings) {
9264
9312
  return withXaiSubscriptionCatalogProvider(settings);
9265
9313
  }
9266
- async function settingsWithWorkspaceGatewayCredential(db, workspaceId, settings) {
9267
- const catalogSettings = withWorkspaceGatewayCatalogProvider(settings);
9314
+ async function settingsWithWorkspaceGatewayCredential(db, accountId, workspaceId, settings, retainedProductModelId) {
9315
+ const activeCustomModels = await listWorkspaceGatewayCustomModels(db, { accountId, workspaceId });
9316
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
9317
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX
9318
+ ) ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX.length) : null;
9319
+ const retainedCustomModel = retainedUpstreamModelId ? await getWorkspaceGatewayCustomModelForExecution(db, {
9320
+ accountId,
9321
+ workspaceId,
9322
+ upstreamModelId: retainedUpstreamModelId
9323
+ }) : null;
9324
+ const customModels = retainedCustomModel && !activeCustomModels.some(
9325
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId
9326
+ ) ? [...activeCustomModels, retainedCustomModel] : activeCustomModels;
9327
+ const catalogSettings = withWorkspaceGatewayCatalogProvider(settings, customModels);
9268
9328
  const apiKey = await loadWorkspaceVercelAiGatewayApiKey(db, settings, workspaceId);
9269
- return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey) : catalogSettings;
9329
+ return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey, customModels) : catalogSettings;
9330
+ }
9331
+ async function settingsWithWorkspaceOpenRouterCredential(db, accountId, workspaceId, settings, retainedProductModelId) {
9332
+ const activeCustomModels = await listWorkspaceOpenRouterCustomModels(db, {
9333
+ accountId,
9334
+ workspaceId
9335
+ });
9336
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
9337
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX
9338
+ ) ? retainedProductModelId.slice(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX.length) : null;
9339
+ const retainedCustomModel = retainedUpstreamModelId ? await getWorkspaceOpenRouterCustomModelForExecution(db, {
9340
+ accountId,
9341
+ workspaceId,
9342
+ upstreamModelId: retainedUpstreamModelId
9343
+ }) : null;
9344
+ const customModels = retainedCustomModel && !activeCustomModels.some(
9345
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId
9346
+ ) ? [...activeCustomModels, retainedCustomModel] : activeCustomModels;
9347
+ const catalogSettings = withWorkspaceOpenRouterCatalogProvider(settings, customModels);
9348
+ const apiKey = await loadWorkspaceOpenRouterApiKey(db, settings, workspaceId);
9349
+ return apiKey ? withWorkspaceOpenRouterCredential(catalogSettings, apiKey, customModels) : catalogSettings;
9270
9350
  }
9271
9351
 
9272
9352
  // src/activities/agent-turn/claim.ts
9273
9353
  import {
9274
9354
  assertSessionAllowsProductModel,
9355
+ resolveCatalogSettings,
9275
9356
  resolveCodexAppsCredentialIdForRun
9276
9357
  } from "@opengeni/core";
9277
9358
 
@@ -9295,6 +9376,7 @@ async function claimTurnAttempt(deps) {
9295
9376
  const {
9296
9377
  input,
9297
9378
  settings,
9379
+ catalogSourceSettings,
9298
9380
  db,
9299
9381
  bus,
9300
9382
  runtime,
@@ -9315,9 +9397,10 @@ async function claimTurnAttempt(deps) {
9315
9397
  claimedResult,
9316
9398
  acknowledgeLostAttemptOwnership
9317
9399
  } = deps;
9400
+ const deploymentCatalogSettings = (await resolveCatalogSettings(db, catalogSourceSettings)).settings;
9318
9401
  const validatePendingSystemUpdateAuthority = async (tx, update) => await validateIncidentTelemetrySystemUpdateAuthority({
9319
9402
  db: tx,
9320
- settings,
9403
+ settings: deploymentCatalogSettings,
9321
9404
  workspaceId: input.workspaceId,
9322
9405
  sessionId: input.sessionId,
9323
9406
  update
@@ -9343,6 +9426,7 @@ async function claimTurnAttempt(deps) {
9343
9426
  attempt.redispatchesAtDispatch = Number(
9344
9427
  turn.metadata?.workerDeathRedispatches ?? 0
9345
9428
  );
9429
+ const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);
9346
9430
  const session = await requireSession(db, input.workspaceId, input.sessionId);
9347
9431
  let installedApiIntegrations = [];
9348
9432
  const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);
@@ -9350,7 +9434,7 @@ async function claimTurnAttempt(deps) {
9350
9434
  const mcpSettings = await settingsWithEnabledCapabilityMcpServers(
9351
9435
  db,
9352
9436
  input.workspaceId,
9353
- settings,
9437
+ deploymentCatalogSettings,
9354
9438
  {
9355
9439
  ...credentialSubjectId ? { subjectId: credentialSubjectId } : {
9356
9440
  personalConnectionDelegations: turn.personalConnectionDelegations
@@ -9372,14 +9456,22 @@ async function claimTurnAttempt(deps) {
9372
9456
  codexSubscriptionActive
9373
9457
  );
9374
9458
  const xaiSettings = codexSettings.supergrokSubscriptionEnabled ? withXaiSubscriptionProvider(codexSettings) : codexSettings;
9375
- const capabilitySettings = await settingsWithWorkspaceGatewayCredential(
9459
+ const gatewaySettings = await settingsWithWorkspaceGatewayCredential(
9376
9460
  db,
9461
+ input.accountId,
9377
9462
  input.workspaceId,
9378
- xaiSettings
9463
+ xaiSettings,
9464
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
9465
+ );
9466
+ const capabilitySettings = await settingsWithWorkspaceOpenRouterCredential(
9467
+ db,
9468
+ input.accountId,
9469
+ input.workspaceId,
9470
+ gatewaySettings,
9471
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model
9379
9472
  );
9380
9473
  const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId) : null;
9381
9474
  runtime.configure(capabilitySettings);
9382
- const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);
9383
9475
  const policyForAbsent = claimedPolicy.kind === "valid" ? claimedPolicy.policy : resolveTurnExecutionPolicyV12(capabilitySettings, legacyTurnExecutionPolicyInput(turn));
9384
9476
  const installedPolicy = await installOrReadTurnExecutionPolicyForAttempt(db, {
9385
9477
  accountId: input.accountId,
@@ -9406,6 +9498,8 @@ async function claimTurnAttempt(deps) {
9406
9498
  assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);
9407
9499
  const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);
9408
9500
  billingState.isExternallyBilledTurn = billingIdentity.externallyBilled;
9501
+ billingState.chargesOpenGeniCredits = verifiedExecutionPolicy.model.cost === "credits";
9502
+ billingState.countsTowardTokenCap = billingIdentity.countsTowardTokenCap;
9409
9503
  billingState.isCodexTurn = billingIdentity.codexSubscription;
9410
9504
  billingState.isXaiTurn = billingIdentity.xaiSubscription;
9411
9505
  const trigger = await getSessionEvent3(db, input.workspaceId, attempt.triggerEventId);
@@ -9441,12 +9535,14 @@ async function claimTurnAttempt(deps) {
9441
9535
  turnLifecycleMetricsFor(observability).start(attempt.turnId);
9442
9536
  await waitForTurnOperation(
9443
9537
  ensureRunAllowed(
9444
- settings,
9538
+ capabilitySettings,
9445
9539
  db,
9446
9540
  input.accountId,
9447
9541
  input.workspaceId,
9448
9542
  billingState.isExternallyBilledTurn,
9449
- entitlements
9543
+ entitlements,
9544
+ billingState.chargesOpenGeniCredits,
9545
+ billingState.countsTowardTokenCap
9450
9546
  ),
9451
9547
  cancellationSignal,
9452
9548
  void 0
@@ -10432,6 +10528,9 @@ import {
10432
10528
  } from "@opengeni/contracts";
10433
10529
 
10434
10530
  // src/activities/agent-turn/tool-policy.ts
10531
+ import {
10532
+ desktopCapableBackend
10533
+ } from "@opengeni/runtime";
10435
10534
  import {
10436
10535
  isDirectOpenAiApiBaseUrl
10437
10536
  } from "@opengeni/config";
@@ -11036,6 +11135,8 @@ async function prepareCompaction(deps) {
11036
11135
  providerApi: resolvedModel?.provider.api ?? "responses",
11037
11136
  model: resolvedModel?.configured.id ?? turn.model,
11038
11137
  externallyBilled: billingState.isExternallyBilledTurn,
11138
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
11139
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
11039
11140
  turnAttemptId: input.attemptId,
11040
11141
  servingCredentialId: providerTurn.effectiveCodexCredentialId,
11041
11142
  priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,
@@ -14963,10 +15064,17 @@ async function prepareRunCredentials(deps) {
14963
15064
  // src/activities/agent-turn/tool-environment.ts
14964
15065
  import {
14965
15066
  getScheduledVariableSetExpectedGenerationForAttempt,
15067
+ getWorkspaceModelPolicy as getWorkspaceModelPolicy2,
15068
+ listWorkspaceGatewayCustomModels as listWorkspaceGatewayCustomModels2,
15069
+ listWorkspaceOpenRouterCustomModels as listWorkspaceOpenRouterCustomModels2,
14966
15070
  persistAttemptToolCatalog,
14967
15071
  namedSubjectHasLiveWorkspaceAuthority as namedSubjectHasLiveWorkspaceAuthority2,
14968
15072
  updateSessionTitleWithEvent,
14969
- withCodexAppsRequestAuthorization
15073
+ withCodexAppsRequestAuthorization,
15074
+ workspaceCodexSubscriptionActive as workspaceCodexSubscriptionActive3,
15075
+ workspaceVercelAiGatewayConnectionActive,
15076
+ workspaceOpenRouterConnectionActive,
15077
+ workspaceXaiSubscriptionActiveForAuthority
14970
15078
  } from "@opengeni/db";
14971
15079
  import { publishDurableSessionEvents as publishDurableSessionEvents8 } from "@opengeni/events";
14972
15080
  import {
@@ -15880,6 +15988,7 @@ import {
15880
15988
  } from "@opengeni/codemode";
15881
15989
  import { createGitHubAppInstallationTokenWithExpiry as createGitHubAppInstallationTokenWithExpiry2, githubAppBotIdentity as githubAppBotIdentity2 } from "@opengeni/github";
15882
15990
  import {
15991
+ ConnectorActionBindingRejectedError,
15883
15992
  prefixedMcpToolName
15884
15993
  } from "@opengeni/runtime";
15885
15994
  import {
@@ -16314,7 +16423,7 @@ function githubConnectorBindings(serverId, repositories) {
16314
16423
  const args = objectRecord(arguments_);
16315
16424
  const repository = typeof args.repository === "string" ? byName.get(args.repository.toLowerCase()) : null;
16316
16425
  if (!repository) {
16317
- throw new GitHubRestAuthorityError(
16426
+ throw new ConnectorActionBindingRejectedError(
16318
16427
  "GitHub action repository does not match an accepted resource"
16319
16428
  );
16320
16429
  }
@@ -16782,6 +16891,8 @@ import {
16782
16891
  defaultSessionMcpServerIds,
16783
16892
  loadRigDefaultVariableSetEnvironment,
16784
16893
  mergeRigDefaultVariableSetEnvironment,
16894
+ resolveCatalogSettings as resolveCatalogSettings2,
16895
+ resolveWorkspaceModelSelection,
16785
16896
  withFrozenPersonalConnectionDelegations,
16786
16897
  resolveSessionToolPolicy
16787
16898
  } from "@opengeni/core";
@@ -16881,6 +16992,83 @@ async function resolveTurnSandboxAccess(sandboxState, sdkOwnedSandboxSession, un
16881
16992
  };
16882
16993
  }
16883
16994
 
16995
+ // src/activities/agent-turn/list-models.ts
16996
+ import {
16997
+ compareModelPickerOrder,
16998
+ modelPickerBillingClassFor
16999
+ } from "@opengeni/contracts/model-picker-order";
17000
+ var LIST_MODELS_TOOL_NAME = "list_models";
17001
+ var LIST_MODELS_TOOL_DESCRIPTION = "List the models this workspace can select right now, in picker order, with deployment-defined cost and optional guidance. This does not switch the current session model; use an ID with session_create or the human model picker.";
17002
+ function safeLineField(value) {
17003
+ return value.replace(/[\r\n|]/gu, " ").replace(/\s+/gu, " ").trim();
17004
+ }
17005
+ function renderListModels(input) {
17006
+ const lines = [];
17007
+ if (input.currentModelId) {
17008
+ lines.push(`Current: ${safeLineField(input.currentModelId)}`);
17009
+ }
17010
+ const selectable = input.selections.filter((entry) => entry.availability.selectable).map((selection) => ({
17011
+ selection,
17012
+ billingClass: modelPickerBillingClassFor(selection.model),
17013
+ selectable: selection.availability.selectable,
17014
+ label: selection.model.label
17015
+ })).sort(compareModelPickerOrder);
17016
+ if (selectable.length === 0) {
17017
+ lines.push("No models are available in this workspace.");
17018
+ return lines.join("\n");
17019
+ }
17020
+ for (const { selection } of selectable) {
17021
+ const { model } = selection;
17022
+ const fields = [safeLineField(model.id), safeLineField(model.label), model.cost];
17023
+ const note = input.modelNotes[model.id];
17024
+ if (note) fields.push(safeLineField(note));
17025
+ lines.push(`- ${fields.join(" | ")}`);
17026
+ }
17027
+ return lines.join("\n");
17028
+ }
17029
+ function createListModelsAttemptToolDefinition(input) {
17030
+ return {
17031
+ identity: { serverId: "opengeni", toolName: LIST_MODELS_TOOL_NAME },
17032
+ modelName: LIST_MODELS_TOOL_NAME,
17033
+ codemodePath: ["opengeni", LIST_MODELS_TOOL_NAME],
17034
+ title: "List selectable models",
17035
+ description: LIST_MODELS_TOOL_DESCRIPTION,
17036
+ inputSchema: {
17037
+ type: "object",
17038
+ properties: {},
17039
+ additionalProperties: false
17040
+ },
17041
+ annotations: {
17042
+ title: "List selectable models",
17043
+ readOnlyHint: true,
17044
+ destructiveHint: false,
17045
+ idempotentHint: true,
17046
+ openWorldHint: false
17047
+ },
17048
+ source: "opengeni",
17049
+ approval: "none",
17050
+ execute: async (args) => {
17051
+ if (Object.keys(args).length !== 0) {
17052
+ throw new Error("list_models accepts no arguments");
17053
+ }
17054
+ const catalog = await input.load();
17055
+ return {
17056
+ isError: false,
17057
+ content: [
17058
+ {
17059
+ type: "text",
17060
+ text: renderListModels({
17061
+ currentModelId: input.currentModelId,
17062
+ selections: catalog.selections,
17063
+ modelNotes: catalog.modelNotes
17064
+ })
17065
+ }
17066
+ ]
17067
+ };
17068
+ }
17069
+ };
17070
+ }
17071
+
16884
17072
  // src/activities/agent-turn/tool-environment.ts
16885
17073
  async function prepareTurnToolPolicy(deps) {
16886
17074
  const {
@@ -17002,6 +17190,7 @@ async function prepareTurnToolPolicy(deps) {
17002
17190
  async function prepareTurnToolRuntime(deps) {
17003
17191
  const {
17004
17192
  input,
17193
+ catalogSourceSettings,
17005
17194
  db,
17006
17195
  bus,
17007
17196
  runtime,
@@ -17187,6 +17376,53 @@ async function prepareTurnToolRuntime(deps) {
17187
17376
  }
17188
17377
  ] : [];
17189
17378
  const attemptToolDefinitions = [
17379
+ createListModelsAttemptToolDefinition({
17380
+ currentModelId: turnExecutionPolicy.productModelId,
17381
+ load: async () => {
17382
+ const currentCatalog = await resolveCatalogSettings2(db, catalogSourceSettings);
17383
+ const currentSettings = currentCatalog.settings;
17384
+ const xaiReadinessAuthority = xaiCatalogReadinessAuthority(turn, credentialSubjectId);
17385
+ const [
17386
+ policy,
17387
+ codexSubscriptionActive,
17388
+ xaiSubscriptionActive,
17389
+ workspaceGatewayConnectionActive,
17390
+ workspaceGatewayCustomModels,
17391
+ openRouterConnectionActive,
17392
+ workspaceOpenRouterCustomModels
17393
+ ] = await Promise.all([
17394
+ getWorkspaceModelPolicy2(db, input.workspaceId),
17395
+ workspaceCodexSubscriptionActive3(db, currentSettings, input.workspaceId),
17396
+ xaiReadinessAuthority && currentSettings.supergrokSubscriptionEnabled ? workspaceXaiSubscriptionActiveForAuthority(db, currentSettings, {
17397
+ workspaceId: input.workspaceId,
17398
+ ...xaiReadinessAuthority
17399
+ }) : false,
17400
+ workspaceVercelAiGatewayConnectionActive(db, input.workspaceId),
17401
+ listWorkspaceGatewayCustomModels2(db, {
17402
+ accountId: input.accountId,
17403
+ workspaceId: input.workspaceId
17404
+ }),
17405
+ workspaceOpenRouterConnectionActive(db, input.workspaceId),
17406
+ listWorkspaceOpenRouterCustomModels2(db, {
17407
+ accountId: input.accountId,
17408
+ workspaceId: input.workspaceId
17409
+ })
17410
+ ]);
17411
+ return {
17412
+ selections: resolveWorkspaceModelSelection({
17413
+ settings: currentSettings,
17414
+ policy,
17415
+ codexSubscriptionActive,
17416
+ xaiSubscriptionActive,
17417
+ workspaceGatewayConnectionActive,
17418
+ workspaceGatewayCustomModels,
17419
+ workspaceOpenRouterConnectionActive: openRouterConnectionActive,
17420
+ workspaceOpenRouterCustomModels
17421
+ }),
17422
+ modelNotes: currentCatalog.modelNotes
17423
+ };
17424
+ }
17425
+ }),
17190
17426
  ...titleToolPlan.promoteTitleTool ? [
17191
17427
  createSessionTitleAttemptToolDefinition({
17192
17428
  updateTitle: async (title) => {
@@ -17604,8 +17840,8 @@ import {
17604
17840
  import {
17605
17841
  serviceTierForLatencyMode,
17606
17842
  environmentsEncryptionKeyBytes as environmentsEncryptionKeyBytes4,
17607
- WORKSPACE_GATEWAY_PROVIDER_ID,
17608
- resolveModelProvider
17843
+ WORKSPACE_GATEWAY_PROVIDER_ID as WORKSPACE_GATEWAY_PROVIDER_ID2,
17844
+ resolveModelProvider as resolveModelProvider2
17609
17845
  } from "@opengeni/config";
17610
17846
 
17611
17847
  // src/activities/xai-image-generation.ts
@@ -18679,19 +18915,16 @@ async function referenceBytes(input, reference2) {
18679
18915
  );
18680
18916
  }
18681
18917
  return {
18682
- bytes: await readStoredFile(input.objectStorage, file),
18918
+ bytes: await readStoredImageReferenceFile(input.objectStorage, file),
18683
18919
  file
18684
18920
  };
18685
18921
  }
18686
- async function readStoredFile(objectStorage, file) {
18687
- const bytes = await objectStorage.getFileRange(file, {
18688
- start: 0,
18689
- end: file.sizeBytes - 1
18690
- });
18691
- if (!bytes) {
18922
+ async function readStoredImageReferenceFile(objectStorage, file) {
18923
+ const bytes = await objectStorage.getFileBytes(file);
18924
+ if (bytes.byteLength !== file.sizeBytes) {
18692
18925
  throw new ImageGenerationReferenceError(
18693
- "reference_unavailable",
18694
- "The durable image reference bytes are unavailable."
18926
+ "reference_integrity_mismatch",
18927
+ "The durable image reference bytes do not match their file metadata."
18695
18928
  );
18696
18929
  }
18697
18930
  return bytes;
@@ -18940,9 +19173,9 @@ async function buildTurnAgent(deps) {
18940
19173
  }
18941
19174
  };
18942
19175
  }
18943
- const gatewayResolution = resolveModelProvider(
19176
+ const gatewayResolution = resolveModelProvider2(
18944
19177
  capabilitySettings,
18945
- WORKSPACE_GATEWAY_PROVIDER_ID
19178
+ WORKSPACE_GATEWAY_PROVIDER_ID2
18946
19179
  );
18947
19180
  const gateway = gatewayResolution?.provider;
18948
19181
  if (gateway?.kind !== "vercel-gateway-workspace" || !gateway.apiKey) return {};
@@ -19326,6 +19559,7 @@ function createRunAgentTurnActivity(services) {
19326
19559
  return async function runAgentTurn(input) {
19327
19560
  const {
19328
19561
  settings,
19562
+ catalogSourceSettings = settings,
19329
19563
  db,
19330
19564
  bus,
19331
19565
  runtime,
@@ -19493,6 +19727,7 @@ function createRunAgentTurnActivity(services) {
19493
19727
  const claimed = await claimTurnAttempt({
19494
19728
  input,
19495
19729
  settings,
19730
+ catalogSourceSettings,
19496
19731
  db,
19497
19732
  bus,
19498
19733
  runtime,
@@ -19897,7 +20132,7 @@ function createRunAgentTurnActivity(services) {
19897
20132
  );
19898
20133
  const compactionPrep = await prepareCompaction({
19899
20134
  input,
19900
- settings,
20135
+ settings: capabilitySettings,
19901
20136
  db,
19902
20137
  bus,
19903
20138
  observability,
@@ -20150,6 +20385,7 @@ function createRunAgentTurnActivity(services) {
20150
20385
  ];
20151
20386
  const toolRuntime = await prepareTurnToolRuntime({
20152
20387
  input,
20388
+ catalogSourceSettings,
20153
20389
  db,
20154
20390
  bus,
20155
20391
  runtime,
@@ -20325,7 +20561,7 @@ function createRunAgentTurnActivity(services) {
20325
20561
  };
20326
20562
  const postAgentCompaction = await runPostAgentCompaction({
20327
20563
  input,
20328
- settings,
20564
+ settings: capabilitySettings,
20329
20565
  db,
20330
20566
  bus,
20331
20567
  observability,
@@ -20473,7 +20709,7 @@ function createRunAgentTurnActivity(services) {
20473
20709
  );
20474
20710
  return await runTurnStreamAttempt({
20475
20711
  input,
20476
- settings,
20712
+ settings: capabilitySettings,
20477
20713
  db,
20478
20714
  runtime,
20479
20715
  objectStorage,
@@ -21697,4 +21933,4 @@ export {
21697
21933
  createTurnActivities,
21698
21934
  createTurnActivitiesFromServices
21699
21935
  };
21700
- //# sourceMappingURL=activities-turn-A2G2KLSY.js.map
21936
+ //# sourceMappingURL=activities-turn-7EAQXW6Q.js.map