@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
@@ -89,6 +89,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
89
89
  return async function runAgentTurn(input: RunAgentTurnInput): Promise<RunAgentTurnResult> {
90
90
  const {
91
91
  settings,
92
+ catalogSourceSettings = settings,
92
93
  db,
93
94
  bus,
94
95
  runtime,
@@ -302,6 +303,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
302
303
  const claimed = await claimTurnAttempt({
303
304
  input,
304
305
  settings,
306
+ catalogSourceSettings,
305
307
  db,
306
308
  bus,
307
309
  runtime,
@@ -796,7 +798,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
796
798
  );
797
799
  const compactionPrep = await prepareCompaction({
798
800
  input,
799
- settings,
801
+ settings: capabilitySettings,
800
802
  db,
801
803
  bus,
802
804
  observability,
@@ -1062,6 +1064,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
1062
1064
  ];
1063
1065
  const toolRuntime = await prepareTurnToolRuntime({
1064
1066
  input,
1067
+ catalogSourceSettings,
1065
1068
  db,
1066
1069
  bus,
1067
1070
  runtime,
@@ -1243,7 +1246,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
1243
1246
  };
1244
1247
  const postAgentCompaction = await runPostAgentCompaction({
1245
1248
  input,
1246
- settings,
1249
+ settings: capabilitySettings,
1247
1250
  db,
1248
1251
  bus,
1249
1252
  observability,
@@ -1408,7 +1411,7 @@ export function createRunAgentTurnActivity(services: () => Promise<ActivityServi
1408
1411
  );
1409
1412
  return await runTurnStreamAttempt({
1410
1413
  input,
1411
- settings,
1414
+ settings: capabilitySettings,
1412
1415
  db,
1413
1416
  runtime,
1414
1417
  objectStorage,
@@ -911,6 +911,8 @@ export async function runTurnStreamAttempt(
911
911
  latencyMode: turnExecutionPolicy.latencyMode,
912
912
  metricProvider: streamProvider,
913
913
  externallyBilled: billingState.isExternallyBilledTurn,
914
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
915
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
914
916
  servingCredentialId: providerTurn.effectiveCodexCredentialId,
915
917
  priorSessionCredentialId: providerTurn.priorSessionCodexCredentialId,
916
918
  emittedSourceKeys: emittedModelUsageSourceKeys,
@@ -976,6 +978,8 @@ export async function runTurnStreamAttempt(
976
978
  input.workspaceId,
977
979
  billingState.isExternallyBilledTurn,
978
980
  entitlements,
981
+ billingState.chargesOpenGeniCredits,
982
+ billingState.countsTowardTokenCap,
979
983
  );
980
984
  } catch (limitError) {
981
985
  // Capture the run state at the boundary so the budget valve in
@@ -1351,6 +1355,8 @@ export async function runTurnStreamAttempt(
1351
1355
  turnAttemptId: input.attemptId,
1352
1356
  model: turn.model,
1353
1357
  externallyBilled: billingState.isExternallyBilledTurn,
1358
+ chargesOpenGeniCredits: billingState.chargesOpenGeniCredits,
1359
+ countsTowardTokenCap: billingState.countsTowardTokenCap,
1354
1360
  usage: aggregateUsage,
1355
1361
  normalizedUsage: normalizedAggregateUsage,
1356
1362
  sourceKey: aggregateSourceKey,
@@ -1372,6 +1378,8 @@ export async function runTurnStreamAttempt(
1372
1378
  sourceKey: aggregateSourceKey,
1373
1379
  usage: { usage: aggregateUsage },
1374
1380
  normalizedUsage: normalizedAggregateUsage,
1381
+ ...(billing ? { billingPath: billing.billingPath } : {}),
1382
+ ...(billing?.upstreamProvider ? { upstreamProvider: billing.upstreamProvider } : {}),
1375
1383
  servingAccountHash: aggregateAccountCtx.servingAccountHash,
1376
1384
  accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,
1377
1385
  emittedSourceKeys: emittedModelUsageSourceKeys,
@@ -1,9 +1,16 @@
1
1
  import {
2
2
  getScheduledVariableSetExpectedGenerationForAttempt,
3
+ getWorkspaceModelPolicy,
4
+ listWorkspaceGatewayCustomModels,
5
+ listWorkspaceOpenRouterCustomModels,
3
6
  persistAttemptToolCatalog,
4
7
  namedSubjectHasLiveWorkspaceAuthority,
5
8
  updateSessionTitleWithEvent,
6
9
  withCodexAppsRequestAuthorization,
10
+ workspaceCodexSubscriptionActive,
11
+ workspaceVercelAiGatewayConnectionActive,
12
+ workspaceOpenRouterConnectionActive,
13
+ workspaceXaiSubscriptionActiveForAuthority,
7
14
  } from "@opengeni/db";
8
15
  import { publishDurableSessionEvents } from "@opengeni/events";
9
16
  import {
@@ -31,6 +38,8 @@ import {
31
38
  defaultSessionMcpServerIds,
32
39
  loadRigDefaultVariableSetEnvironment,
33
40
  mergeRigDefaultVariableSetEnvironment,
41
+ resolveCatalogSettings,
42
+ resolveWorkspaceModelSelection,
34
43
  withFrozenPersonalConnectionDelegations,
35
44
  resolveSessionToolPolicy,
36
45
  } from "@opengeni/core";
@@ -44,7 +53,7 @@ import { SandboxChannelAService } from "@opengeni/runtime/sandbox";
44
53
  import { sandboxRunAs } from "@opengeni/runtime";
45
54
  import { type ToolAuthNeededPayload } from "@opengeni/contracts";
46
55
 
47
- import { shouldPublishToolAuthNeededForTurn } from "./admission";
56
+ import { shouldPublishToolAuthNeededForTurn, xaiCatalogReadinessAuthority } from "./admission";
48
57
  import { unavailableMcpOperationalContext } from "./errors";
49
58
  import { runtimeResourcesForTurn } from "./file-resources";
50
59
  import { waitForTurnOperation } from "./sandbox-provision";
@@ -65,6 +74,7 @@ import {
65
74
  shouldRequestMissingSessionTitle,
66
75
  } from "./session-title";
67
76
  import { resolveTurnSandboxAccess } from "./turn-sandbox-access";
77
+ import { createListModelsAttemptToolDefinition } from "./list-models";
68
78
 
69
79
  export type PrepareTurnToolPolicyDeps = {
70
80
  input: RunAgentTurnInput;
@@ -82,6 +92,7 @@ export type PrepareTurnToolPolicyDeps = {
82
92
 
83
93
  export type PrepareTurnToolRuntimeDeps = {
84
94
  input: RunAgentTurnInput;
95
+ catalogSourceSettings: Settings;
85
96
  db: ActivityServices["db"];
86
97
  bus: ActivityServices["bus"];
87
98
  runtime: ActivityServices["runtime"];
@@ -296,6 +307,7 @@ export async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {
296
307
  export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
297
308
  const {
298
309
  input,
310
+ catalogSourceSettings,
299
311
  db,
300
312
  bus,
301
313
  runtime,
@@ -510,6 +522,55 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
510
522
  ]
511
523
  : [];
512
524
  const attemptToolDefinitions = [
525
+ createListModelsAttemptToolDefinition({
526
+ currentModelId: turnExecutionPolicy.productModelId,
527
+ load: async () => {
528
+ const currentCatalog = await resolveCatalogSettings(db, catalogSourceSettings);
529
+ const currentSettings = currentCatalog.settings;
530
+ const xaiReadinessAuthority = xaiCatalogReadinessAuthority(turn, credentialSubjectId);
531
+ const [
532
+ policy,
533
+ codexSubscriptionActive,
534
+ xaiSubscriptionActive,
535
+ workspaceGatewayConnectionActive,
536
+ workspaceGatewayCustomModels,
537
+ openRouterConnectionActive,
538
+ workspaceOpenRouterCustomModels,
539
+ ] = await Promise.all([
540
+ getWorkspaceModelPolicy(db, input.workspaceId),
541
+ workspaceCodexSubscriptionActive(db, currentSettings, input.workspaceId),
542
+ xaiReadinessAuthority && currentSettings.supergrokSubscriptionEnabled
543
+ ? workspaceXaiSubscriptionActiveForAuthority(db, currentSettings, {
544
+ workspaceId: input.workspaceId,
545
+ ...xaiReadinessAuthority,
546
+ })
547
+ : false,
548
+ workspaceVercelAiGatewayConnectionActive(db, input.workspaceId),
549
+ listWorkspaceGatewayCustomModels(db, {
550
+ accountId: input.accountId,
551
+ workspaceId: input.workspaceId,
552
+ }),
553
+ workspaceOpenRouterConnectionActive(db, input.workspaceId),
554
+ listWorkspaceOpenRouterCustomModels(db, {
555
+ accountId: input.accountId,
556
+ workspaceId: input.workspaceId,
557
+ }),
558
+ ]);
559
+ return {
560
+ selections: resolveWorkspaceModelSelection({
561
+ settings: currentSettings,
562
+ policy,
563
+ codexSubscriptionActive,
564
+ xaiSubscriptionActive,
565
+ workspaceGatewayConnectionActive,
566
+ workspaceGatewayCustomModels,
567
+ workspaceOpenRouterConnectionActive: openRouterConnectionActive,
568
+ workspaceOpenRouterCustomModels,
569
+ }),
570
+ modelNotes: currentCatalog.modelNotes,
571
+ };
572
+ },
573
+ }),
513
574
  ...(titleToolPlan.promoteTitleTool
514
575
  ? [
515
576
  createSessionTitleAttemptToolDefinition({
@@ -1,17 +1,70 @@
1
- import { type LazyToolTransport } from "@opengeni/runtime";
1
+ import {
2
+ desktopCapableBackend,
3
+ type ComputerToolMode,
4
+ type LazyToolTransport,
5
+ } from "@opengeni/runtime";
2
6
  import {
3
7
  isDirectOpenAiApiBaseUrl,
4
8
  type ModelProviderApi,
5
- type RegistryProviderKind,
9
+ type ResolvedModelProvider,
6
10
  type Settings,
7
11
  } from "@opengeni/config";
8
12
  import { type ModelAttachmentInputPolicy } from "../run-input";
9
13
  import { imageProviderBindingHash } from "../image-generation-operation";
10
14
 
15
+ export function shouldStartOnTurnRecording(params: {
16
+ recordingEnabled: boolean;
17
+ desktopEnabled: boolean;
18
+ establishedBackendId: string;
19
+ effectiveBackend: Settings["sandboxBackend"] | undefined;
20
+ }): boolean {
21
+ return (
22
+ params.recordingEnabled &&
23
+ params.desktopEnabled &&
24
+ desktopCapableBackend(params.establishedBackendId) &&
25
+ params.effectiveBackend !== "selfhosted"
26
+ );
27
+ }
28
+
29
+ /**
30
+ * Decide the EXPLICIT computer-use tool transport for THIS turn.
31
+ *
32
+ * Computer-use is ordinary `computer_*` function tools bound to the live
33
+ * desktop. The worker picks the mode from the resolved provider so the runtime
34
+ * never string-sniffs the model instance:
35
+ * • catalogue `inputModalities` must include `image`, or computer-use is off
36
+ * • Responses wires (Azure/OpenAI, Gateway, Codex, legacy client) →
37
+ * "function-image": screenshot results are structured `{type:'image'}`
38
+ * • Chat Completions → "disabled": tool results on that wire are text, so a
39
+ * screenshot would become a base64 string rather than an image the model sees
40
+ *
41
+ * Pure + exported so the mapping is unit-testable without a live turn.
42
+ */
43
+ export function computerToolModeForTurn(
44
+ resolvedModel: {
45
+ provider: { kind: ResolvedModelProvider["kind"]; api: ModelProviderApi };
46
+ configured: { capabilities: { inputModalities: string[] } };
47
+ } | null,
48
+ ): ComputerToolMode {
49
+ if (!resolvedModel) {
50
+ return "function-image";
51
+ }
52
+ if (!modelSupportsImageInputForTurn(resolvedModel)) {
53
+ return "disabled";
54
+ }
55
+ if (resolvedModel.provider.kind === "codex-subscription") {
56
+ return "function-image";
57
+ }
58
+ if (resolvedModel.provider.api === "chat") {
59
+ return "disabled";
60
+ }
61
+ return "function-image";
62
+ }
63
+
11
64
  /** Chat wires and Gateway models do not advertise OpenAI's hosted sandbox tool types. */
12
65
  export function structuredToolTransportForTurn(
13
66
  resolvedModel: {
14
- provider: { kind: RegistryProviderKind; api: ModelProviderApi };
67
+ provider: { kind: ResolvedModelProvider["kind"]; api: ModelProviderApi };
15
68
  } | null,
16
69
  ): boolean {
17
70
  if (!resolvedModel) return true;
@@ -34,7 +87,7 @@ export function lazyToolTransportForTurn(
34
87
  resolvedModel: {
35
88
  provider: {
36
89
  id: string;
37
- kind: RegistryProviderKind;
90
+ kind: ResolvedModelProvider["kind"];
38
91
  api: ModelProviderApi;
39
92
  wireProfile: "openai" | "azure-openai";
40
93
  builtin: boolean;
@@ -108,7 +161,7 @@ export function openAiHostedImageProviderBindingForTurn(
108
161
  resolvedModel: {
109
162
  provider: {
110
163
  id: string;
111
- kind: RegistryProviderKind;
164
+ kind: ResolvedModelProvider["kind"];
112
165
  builtin: boolean;
113
166
  baseUrl?: string | undefined;
114
167
  };
@@ -73,6 +73,8 @@ export type BillingState = {
73
73
  isCodexTurn: boolean;
74
74
  isXaiTurn: boolean;
75
75
  isExternallyBilledTurn: boolean;
76
+ chargesOpenGeniCredits: boolean;
77
+ countsTowardTokenCap: boolean;
76
78
  };
77
79
 
78
80
  export type SandboxRuntimeState = {
@@ -204,6 +206,8 @@ export function createTurnContext(input: {
204
206
  isCodexTurn: false,
205
207
  isXaiTurn: false,
206
208
  isExternallyBilledTurn: false,
209
+ chargesOpenGeniCredits: true,
210
+ countsTowardTokenCap: true,
207
211
  },
208
212
  sandboxState: {
209
213
  resolvedSandbox: null,
@@ -1,9 +1,15 @@
1
- import { resolveTurnExecutionPolicyV1 } from "@opengeni/config";
1
+ import {
2
+ resolveTurnExecutionPolicyV1,
3
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
4
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
5
+ } from "@opengeni/config";
2
6
  import {
3
7
  assertWorkspaceModelPolicyAllows,
4
8
  canonicalConfiguredModel,
5
9
  createAndStartSessionWithOutcome,
6
10
  recordWorkspaceUsage,
11
+ resolveCatalogSettings,
12
+ resolveWorkspaceCatalogSettings,
7
13
  } from "@opengeni/core";
8
14
  import {
9
15
  AutomationAuthorityRevokedError,
@@ -40,10 +46,23 @@ export function createAutomationActivities(
40
46
  const assertModelPolicy = options.assertModelPolicy ?? assertWorkspaceModelPolicyAllows;
41
47
  const recordUsage = options.recordUsage ?? recordWorkspaceUsage;
42
48
  return {
49
+ settleAutomationRunFailure: async (input: DispatchAutomationRunInput): Promise<void> => {
50
+ const service = await services();
51
+ await settle(service.db, {
52
+ workspaceId: input.workspaceId,
53
+ runId: input.runId,
54
+ status: "failed",
55
+ errorCode: "dispatch_failed",
56
+ });
57
+ },
43
58
  dispatchAutomationRun: async (
44
59
  input: DispatchAutomationRunInput,
45
60
  ): Promise<DispatchAutomationRunResult> => {
46
61
  const service = await services();
62
+ const catalogSourceSettings = service.catalogSourceSettings ?? service.settings;
63
+ const deploymentCatalogSettings = (
64
+ await resolveCatalogSettings(service.db, catalogSourceSettings)
65
+ ).settings;
47
66
  const run = await claim(service.db, input);
48
67
  if (!run) return { action: "not_found" };
49
68
  if (run.status === "dispatched") {
@@ -51,71 +70,102 @@ export function createAutomationActivities(
51
70
  return { action: "already_dispatched", sessionId: run.sessionId };
52
71
  }
53
72
  if (run.status === "skipped") {
54
- return { action: "skipped", reason: run.errorCode ?? "authority_revoked" };
73
+ return {
74
+ action: "skipped",
75
+ reason: run.errorCode ?? "authority_revoked",
76
+ };
55
77
  }
56
-
57
- const accepted = run.acceptedExecution;
58
- if (
59
- accepted.accountId !== input.accountId ||
60
- accepted.workspaceId !== input.workspaceId ||
61
- accepted.sourceId !== run.sourceId ||
62
- accepted.triggerId !== run.triggerId ||
63
- accepted.triggerRevision !== run.triggerRevision ||
64
- accepted.eventId !== run.eventId
65
- ) {
66
- await settle(service.db, {
67
- workspaceId: input.workspaceId,
68
- runId: run.id,
69
- status: "skipped",
70
- errorCode: "accepted_execution_mismatch",
71
- });
72
- return { action: "skipped", reason: "accepted_execution_mismatch" };
78
+ if (run.status === "failed") {
79
+ return { action: "failed", reason: run.errorCode ?? "dispatch_failed" };
73
80
  }
74
81
 
75
- const template = accepted.sessionTemplate;
76
- const model = canonicalConfiguredModel(
77
- service.settings,
78
- template.model ?? service.settings.openaiModel,
79
- );
80
- if (!model) throw new Error("automation has no configured model");
81
- await assertModelPolicy(service.db, service.settings, input.workspaceId, model);
82
- const denial = await admit(service, {
83
- accountId: input.accountId,
84
- workspaceId: input.workspaceId,
85
- model,
86
- requestedAgentRuns: 1,
87
- });
88
- if (denial) {
89
- await settle(service.db, {
82
+ try {
83
+ const accepted = run.acceptedExecution;
84
+ if (
85
+ accepted.accountId !== input.accountId ||
86
+ accepted.workspaceId !== input.workspaceId ||
87
+ accepted.sourceId !== run.sourceId ||
88
+ accepted.triggerId !== run.triggerId ||
89
+ accepted.triggerRevision !== run.triggerRevision ||
90
+ accepted.eventId !== run.eventId
91
+ ) {
92
+ await settle(service.db, {
93
+ workspaceId: input.workspaceId,
94
+ runId: run.id,
95
+ status: "skipped",
96
+ errorCode: "accepted_execution_mismatch",
97
+ });
98
+ return { action: "skipped", reason: "accepted_execution_mismatch" };
99
+ }
100
+
101
+ const template = accepted.sessionTemplate;
102
+ const requestedModel = template.model ?? deploymentCatalogSettings.openaiModel;
103
+ const catalogSettings =
104
+ requestedModel.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
105
+ requestedModel.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX)
106
+ ? (
107
+ await resolveWorkspaceCatalogSettings(service.db, catalogSourceSettings, {
108
+ accountId: input.accountId,
109
+ workspaceId: input.workspaceId,
110
+ retainedProductModelId: requestedModel,
111
+ })
112
+ ).settings
113
+ : deploymentCatalogSettings;
114
+ const catalogService = { ...service, settings: catalogSettings };
115
+ let model: string;
116
+ try {
117
+ const configuredModel = canonicalConfiguredModel(catalogSettings, requestedModel);
118
+ if (!configuredModel) throw new Error("automation has no configured model");
119
+ await assertModelPolicy(service.db, catalogSettings, input.workspaceId, configuredModel);
120
+ model = configuredModel;
121
+ } catch (error) {
122
+ if (!isUnprocessableEntity(error)) throw error;
123
+ await settle(service.db, {
124
+ workspaceId: input.workspaceId,
125
+ runId: run.id,
126
+ status: "failed",
127
+ errorCode: "dispatch_failed",
128
+ });
129
+ return { action: "failed", reason: "dispatch_failed" };
130
+ }
131
+ const denial = await admit(catalogService, {
132
+ accountId: input.accountId,
90
133
  workspaceId: input.workspaceId,
91
- runId: run.id,
92
- status: "failed",
93
- errorCode: denial,
134
+ model,
135
+ requestedAgentRuns: 1,
94
136
  });
95
- throw new Error(`automation admission denied: ${denial}`);
96
- }
97
- const reasoningEffort = template.reasoningEffort ?? service.settings.openaiReasoningEffort;
98
- const sandboxBackend = template.sandboxBackend ?? service.settings.sandboxBackend;
99
- if (sandboxBackend === "selfhosted") {
100
- await settle(service.db, {
101
- workspaceId: input.workspaceId,
102
- runId: run.id,
103
- status: "skipped",
104
- errorCode: "interactive_compute_not_allowed",
137
+ if (denial) {
138
+ await settle(service.db, {
139
+ workspaceId: input.workspaceId,
140
+ runId: run.id,
141
+ status: "failed",
142
+ errorCode: denial,
143
+ });
144
+ return { action: "failed", reason: denial };
145
+ }
146
+ const reasoningEffort = template.reasoningEffort ?? catalogSettings.openaiReasoningEffort;
147
+ const sandboxBackend = template.sandboxBackend ?? catalogSettings.sandboxBackend;
148
+ if (sandboxBackend === "selfhosted") {
149
+ await settle(service.db, {
150
+ workspaceId: input.workspaceId,
151
+ runId: run.id,
152
+ status: "skipped",
153
+ errorCode: "interactive_compute_not_allowed",
154
+ });
155
+ return {
156
+ action: "skipped",
157
+ reason: "interactive_compute_not_allowed",
158
+ };
159
+ }
160
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(catalogSettings, {
161
+ modelId: model,
162
+ requestedModelId: template.model,
163
+ modelSource: template.model ? "explicit" : "deployment",
164
+ reasoningEffort,
165
+ reasoningSource: template.reasoningEffort ? "explicit" : "deployment",
166
+ latencyMode: "standard",
167
+ latencyModeSource: "deployment",
105
168
  });
106
- return { action: "skipped", reason: "interactive_compute_not_allowed" };
107
- }
108
- const turnExecutionPolicy = resolveTurnExecutionPolicyV1(service.settings, {
109
- modelId: model,
110
- requestedModelId: template.model,
111
- modelSource: template.model ? "explicit" : "deployment",
112
- reasoningEffort,
113
- reasoningSource: template.reasoningEffort ? "explicit" : "deployment",
114
- latencyMode: "standard",
115
- latencyModeSource: "deployment",
116
- });
117
-
118
- try {
119
169
  const created = await createSession({
120
170
  db: service.db,
121
171
  bus: service.bus,
@@ -163,11 +213,14 @@ export function createAutomationActivities(
163
213
  policyRole: template.policyRole,
164
214
  firstPartyMcpPermissions: template.firstPartyMcpPermissions,
165
215
  firstPartyMcpTools: template.firstPartyMcpTools,
216
+ retainWorkspaceCustomModel:
217
+ model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
218
+ model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX),
166
219
  createIdempotencyKey: `automation-run:${run.id}`,
167
220
  subjectId: accepted.serviceSubjectId,
168
221
  });
169
222
  await recordUsage(
170
- { db: service.db, settings: service.settings },
223
+ { db: service.db, settings: catalogSettings },
171
224
  {
172
225
  accountId: input.accountId,
173
226
  workspaceId: input.workspaceId,
@@ -201,14 +254,16 @@ export function createAutomationActivities(
201
254
  });
202
255
  return { action: "skipped", reason: "authority_revoked" };
203
256
  }
204
- await settle(service.db, {
205
- workspaceId: input.workspaceId,
206
- runId: run.id,
207
- status: "failed",
208
- errorCode: "dispatch_failed",
209
- });
210
257
  throw error;
211
258
  }
212
259
  },
213
260
  };
214
261
  }
262
+
263
+ function isUnprocessableEntity(error: unknown): boolean {
264
+ return (
265
+ error instanceof Error &&
266
+ "status" in error &&
267
+ (error as Error & { status?: unknown }).status === 422
268
+ );
269
+ }
@@ -1,17 +1,26 @@
1
1
  import {
2
2
  environmentsEncryptionKeyBytes,
3
3
  type Settings,
4
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
5
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
4
6
  withCodexCatalogProvider,
5
7
  withWorkspaceGatewayCatalogProvider,
6
8
  withWorkspaceGatewayCredential,
9
+ withWorkspaceOpenRouterCatalogProvider,
10
+ withWorkspaceOpenRouterCredential,
7
11
  withXaiSubscriptionCatalogProvider,
8
12
  } from "@opengeni/config";
9
13
  import { settingsWithEnabledCapabilityMcpServers } from "@opengeni/core";
10
14
  import {
15
+ getWorkspaceGatewayCustomModelForExecution,
16
+ getWorkspaceOpenRouterCustomModelForExecution,
11
17
  listSessionMcpServerMetadata,
12
18
  listSessionMcpServersForRun,
19
+ listWorkspaceGatewayCustomModels,
20
+ listWorkspaceOpenRouterCustomModels,
13
21
  workspaceCodexSubscriptionActive,
14
22
  loadWorkspaceVercelAiGatewayApiKey,
23
+ loadWorkspaceOpenRouterApiKey,
15
24
  type Database,
16
25
  type SessionMcpServerForRun,
17
26
  } from "@opengeni/db";
@@ -126,10 +135,71 @@ export function withXaiSubscriptionProvider(settings: Settings): Settings {
126
135
 
127
136
  export async function settingsWithWorkspaceGatewayCredential(
128
137
  db: Database,
138
+ accountId: string,
129
139
  workspaceId: string,
130
140
  settings: Settings,
141
+ retainedProductModelId?: string | null,
131
142
  ): Promise<Settings> {
132
- const catalogSettings = withWorkspaceGatewayCatalogProvider(settings);
143
+ const activeCustomModels = await listWorkspaceGatewayCustomModels(db, { accountId, workspaceId });
144
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
145
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
146
+ )
147
+ ? retainedProductModelId.slice(WORKSPACE_GATEWAY_MODEL_ID_PREFIX.length)
148
+ : null;
149
+ const retainedCustomModel = retainedUpstreamModelId
150
+ ? await getWorkspaceGatewayCustomModelForExecution(db, {
151
+ accountId,
152
+ workspaceId,
153
+ upstreamModelId: retainedUpstreamModelId,
154
+ })
155
+ : null;
156
+ const customModels =
157
+ retainedCustomModel &&
158
+ !activeCustomModels.some(
159
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId,
160
+ )
161
+ ? [...activeCustomModels, retainedCustomModel]
162
+ : activeCustomModels;
163
+ const catalogSettings = withWorkspaceGatewayCatalogProvider(settings, customModels);
133
164
  const apiKey = await loadWorkspaceVercelAiGatewayApiKey(db, settings, workspaceId);
134
- return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey) : catalogSettings;
165
+ return apiKey
166
+ ? withWorkspaceGatewayCredential(catalogSettings, apiKey, customModels)
167
+ : catalogSettings;
168
+ }
169
+
170
+ export async function settingsWithWorkspaceOpenRouterCredential(
171
+ db: Database,
172
+ accountId: string,
173
+ workspaceId: string,
174
+ settings: Settings,
175
+ retainedProductModelId?: string | null,
176
+ ): Promise<Settings> {
177
+ const activeCustomModels = await listWorkspaceOpenRouterCustomModels(db, {
178
+ accountId,
179
+ workspaceId,
180
+ });
181
+ const retainedUpstreamModelId = retainedProductModelId?.startsWith(
182
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
183
+ )
184
+ ? retainedProductModelId.slice(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX.length)
185
+ : null;
186
+ const retainedCustomModel = retainedUpstreamModelId
187
+ ? await getWorkspaceOpenRouterCustomModelForExecution(db, {
188
+ accountId,
189
+ workspaceId,
190
+ upstreamModelId: retainedUpstreamModelId,
191
+ })
192
+ : null;
193
+ const customModels =
194
+ retainedCustomModel &&
195
+ !activeCustomModels.some(
196
+ (model) => model.upstreamModelId === retainedCustomModel.upstreamModelId,
197
+ )
198
+ ? [...activeCustomModels, retainedCustomModel]
199
+ : activeCustomModels;
200
+ const catalogSettings = withWorkspaceOpenRouterCatalogProvider(settings, customModels);
201
+ const apiKey = await loadWorkspaceOpenRouterApiKey(db, settings, workspaceId);
202
+ return apiKey
203
+ ? withWorkspaceOpenRouterCredential(catalogSettings, apiKey, customModels)
204
+ : catalogSettings;
135
205
  }