@opengeni/worker-bundle 0.23.4 → 0.24.2-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 (84) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +17 -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 +15 -1
  6. package/dist/activities/agent-turn/quiescence.d.ts +2 -0
  7. package/dist/activities/agent-turn/run.d.ts +9 -0
  8. package/dist/activities/agent-turn/sandbox-runtime.d.ts +15 -0
  9. package/dist/activities/agent-turn/session-title.d.ts +21 -0
  10. package/dist/activities/agent-turn/stream-attempt.d.ts +4 -0
  11. package/dist/activities/agent-turn/tool-environment.d.ts +2 -0
  12. package/dist/activities/agent-turn/tool-policy.d.ts +36 -5
  13. package/dist/activities/agent-turn/turn-context.d.ts +4 -1
  14. package/dist/activities/agent-turn.d.ts +1 -1
  15. package/dist/activities/automations.d.ts +1 -0
  16. package/dist/activities/capabilities.d.ts +3 -1
  17. package/dist/activities/context-compaction.d.ts +2 -0
  18. package/dist/activities/goals.d.ts +11 -0
  19. package/dist/activities/image-generation-references.d.ts +2 -1
  20. package/dist/activities/scheduled-tasks.d.ts +1 -0
  21. package/dist/activities/types.d.ts +8 -0
  22. package/dist/{activities-control-52W5IDWM.js → activities-control-ZWH7J4KZ.js} +297 -180
  23. package/dist/activities-control-ZWH7J4KZ.js.map +1 -0
  24. package/dist/activities-control.d.ts +2 -0
  25. package/dist/{activities-turn-A2G2KLSY.js → activities-turn-I4OPLQLS.js} +898 -333
  26. package/dist/activities-turn-I4OPLQLS.js.map +1 -0
  27. package/dist/activities.d.ts +2 -0
  28. package/dist/{chunk-GFNXVZVQ.js → chunk-65JEWP2Q.js} +107 -7
  29. package/dist/chunk-65JEWP2Q.js.map +1 -0
  30. package/dist/{chunk-GRFQTTSQ.js → chunk-GDCLDKSH.js} +7 -3
  31. package/dist/{chunk-GRFQTTSQ.js.map → chunk-GDCLDKSH.js.map} +1 -1
  32. package/dist/{chunk-IPVMCAW5.js → chunk-RQNH6CGR.js} +111 -62
  33. package/dist/chunk-RQNH6CGR.js.map +1 -0
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +43 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/observability-metrics.d.ts +34 -7
  38. package/dist/sandbox-reaper-timeout.d.ts +2 -2
  39. package/dist/sandbox-resume.d.ts +6 -1
  40. package/dist/workflow-bundle.js +26 -3
  41. package/dist/workflows/activities.d.ts +5 -0
  42. package/dist/workflows/automations.d.ts +5 -0
  43. package/package.json +17 -17
  44. package/src/activities/agent-run-admission.ts +7 -1
  45. package/src/activities/agent-turn/admission.ts +47 -6
  46. package/src/activities/agent-turn/claim.ts +33 -5
  47. package/src/activities/agent-turn/codex.ts +2 -2
  48. package/src/activities/agent-turn/compaction-prep.ts +8 -1
  49. package/src/activities/agent-turn/finalization.ts +31 -17
  50. package/src/activities/agent-turn/list-models.ts +101 -0
  51. package/src/activities/agent-turn/model-usage.ts +120 -45
  52. package/src/activities/agent-turn/quiescence.ts +11 -2
  53. package/src/activities/agent-turn/run.ts +80 -4
  54. package/src/activities/agent-turn/sandbox-runtime.ts +78 -81
  55. package/src/activities/agent-turn/session-title.ts +55 -2
  56. package/src/activities/agent-turn/stream-attempt.ts +266 -135
  57. package/src/activities/agent-turn/tool-environment.ts +102 -7
  58. package/src/activities/agent-turn/tool-policy.ts +58 -5
  59. package/src/activities/agent-turn/turn-context.ts +8 -2
  60. package/src/activities/agent-turn.ts +5 -1
  61. package/src/activities/api-integrations.ts +11 -1
  62. package/src/activities/automations.ts +122 -67
  63. package/src/activities/capabilities.ts +129 -2
  64. package/src/activities/context-compaction.ts +3 -0
  65. package/src/activities/goals.ts +108 -31
  66. package/src/activities/image-generation-references.ts +9 -9
  67. package/src/activities/mcp-credentials.ts +53 -0
  68. package/src/activities/rig-verification.ts +5 -3
  69. package/src/activities/scheduled-tasks.ts +217 -110
  70. package/src/activities/site-auth-maintenance.ts +12 -12
  71. package/src/activities/types.ts +6 -0
  72. package/src/activities.ts +1 -0
  73. package/src/activity-services.ts +4 -1
  74. package/src/github-rest-mcp.ts +2 -1
  75. package/src/index.ts +34 -4
  76. package/src/observability-metrics.ts +154 -14
  77. package/src/sandbox-reaper-timeout.ts +10 -4
  78. package/src/sandbox-resume.ts +58 -8
  79. package/src/workflows/activities.ts +15 -0
  80. package/src/workflows/automations.ts +21 -2
  81. package/dist/activities-control-52W5IDWM.js.map +0 -1
  82. package/dist/activities-turn-A2G2KLSY.js.map +0 -1
  83. package/dist/chunk-GFNXVZVQ.js.map +0 -1
  84. package/dist/chunk-IPVMCAW5.js.map +0 -1
@@ -1,9 +1,18 @@
1
1
  import {
2
2
  getScheduledVariableSetExpectedGenerationForAttempt,
3
+ getWorkspaceModelPolicy,
4
+ listWorkspaceGatewayCustomModels,
5
+ listWorkspaceOpenRouterCustomModels,
6
+ listOrganizationModelProviderCustomModelsForWorkspace,
7
+ organizationModelProviderConnectionActiveForWorkspace,
3
8
  persistAttemptToolCatalog,
4
9
  namedSubjectHasLiveWorkspaceAuthority,
5
10
  updateSessionTitleWithEvent,
6
11
  withCodexAppsRequestAuthorization,
12
+ workspaceCodexSubscriptionActive,
13
+ workspaceVercelAiGatewayConnectionActive,
14
+ workspaceOpenRouterConnectionActive,
15
+ workspaceXaiSubscriptionActiveForAuthority,
7
16
  } from "@opengeni/db";
8
17
  import { publishDurableSessionEvents } from "@opengeni/events";
9
18
  import {
@@ -31,6 +40,8 @@ import {
31
40
  defaultSessionMcpServerIds,
32
41
  loadRigDefaultVariableSetEnvironment,
33
42
  mergeRigDefaultVariableSetEnvironment,
43
+ resolveCatalogSettings,
44
+ resolveWorkspaceModelSelection,
34
45
  withFrozenPersonalConnectionDelegations,
35
46
  resolveSessionToolPolicy,
36
47
  } from "@opengeni/core";
@@ -44,7 +55,11 @@ import { SandboxChannelAService } from "@opengeni/runtime/sandbox";
44
55
  import { sandboxRunAs } from "@opengeni/runtime";
45
56
  import { type ToolAuthNeededPayload } from "@opengeni/contracts";
46
57
 
47
- import { shouldPublishToolAuthNeededForTurn } from "./admission";
58
+ import {
59
+ rollingSafeToolAuthNeededPayload,
60
+ shouldPublishToolAuthNeededForTurn,
61
+ xaiCatalogReadinessAuthority,
62
+ } from "./admission";
48
63
  import { unavailableMcpOperationalContext } from "./errors";
49
64
  import { runtimeResourcesForTurn } from "./file-resources";
50
65
  import { waitForTurnOperation } from "./sandbox-provision";
@@ -65,6 +80,7 @@ import {
65
80
  shouldRequestMissingSessionTitle,
66
81
  } from "./session-title";
67
82
  import { resolveTurnSandboxAccess } from "./turn-sandbox-access";
83
+ import { createListModelsAttemptToolDefinition } from "./list-models";
68
84
 
69
85
  export type PrepareTurnToolPolicyDeps = {
70
86
  input: RunAgentTurnInput;
@@ -82,6 +98,7 @@ export type PrepareTurnToolPolicyDeps = {
82
98
 
83
99
  export type PrepareTurnToolRuntimeDeps = {
84
100
  input: RunAgentTurnInput;
101
+ catalogSourceSettings: Settings;
85
102
  db: ActivityServices["db"];
86
103
  bus: ActivityServices["bus"];
87
104
  runtime: ActivityServices["runtime"];
@@ -296,6 +313,7 @@ export async function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps) {
296
313
  export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
297
314
  const {
298
315
  input,
316
+ catalogSourceSettings,
299
317
  db,
300
318
  bus,
301
319
  runtime,
@@ -415,7 +433,10 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
415
433
  if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {
416
434
  return;
417
435
  }
418
- await eventing.publish!([{ type: "tool.auth_needed", payload }], true);
436
+ await eventing.publish!(
437
+ [{ type: "tool.auth_needed", payload: rollingSafeToolAuthNeededPayload(payload) }],
438
+ true,
439
+ );
419
440
  };
420
441
  const selectedApiIntegrationServerIds = new Set(turnTools.map((tool) => tool.id));
421
442
  const apiIntegrationMcpServers = buildApiIntegrationServersForTurn({
@@ -488,6 +509,7 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
488
509
  firstPartyMcpTools: selectedFirstPartyMcpTools,
489
510
  firstPartyMcpPermissions: session.firstPartyMcpPermissions,
490
511
  }),
512
+ parallelGenerationAvailable: typeof runtime.generateSessionTitle === "function",
491
513
  });
492
514
  const googleDrivePublicationAllowed =
493
515
  selectedFirstPartyMcpTools.includes("editable_artifact_export") &&
@@ -510,6 +532,83 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
510
532
  ]
511
533
  : [];
512
534
  const attemptToolDefinitions = [
535
+ createListModelsAttemptToolDefinition({
536
+ currentModelId: turnExecutionPolicy.productModelId,
537
+ load: async () => {
538
+ const currentCatalog = await resolveCatalogSettings(db, catalogSourceSettings);
539
+ const currentSettings = currentCatalog.settings;
540
+ const xaiReadinessAuthority = xaiCatalogReadinessAuthority(turn, credentialSubjectId);
541
+ const [
542
+ policy,
543
+ codexSubscriptionActive,
544
+ xaiSubscriptionActive,
545
+ workspaceGatewayConnectionActive,
546
+ workspaceGatewayCustomModels,
547
+ openRouterConnectionActive,
548
+ workspaceOpenRouterCustomModels,
549
+ organizationGatewayConnectionActive,
550
+ organizationGatewayCustomModels,
551
+ organizationOpenRouterConnectionActive,
552
+ organizationOpenRouterCustomModels,
553
+ ] = await Promise.all([
554
+ getWorkspaceModelPolicy(db, input.workspaceId),
555
+ workspaceCodexSubscriptionActive(db, currentSettings, input.workspaceId),
556
+ xaiReadinessAuthority && currentSettings.supergrokSubscriptionEnabled
557
+ ? workspaceXaiSubscriptionActiveForAuthority(db, currentSettings, {
558
+ workspaceId: input.workspaceId,
559
+ ...xaiReadinessAuthority,
560
+ })
561
+ : false,
562
+ workspaceVercelAiGatewayConnectionActive(db, input.workspaceId),
563
+ listWorkspaceGatewayCustomModels(db, {
564
+ accountId: input.accountId,
565
+ workspaceId: input.workspaceId,
566
+ }),
567
+ workspaceOpenRouterConnectionActive(db, input.workspaceId),
568
+ listWorkspaceOpenRouterCustomModels(db, {
569
+ accountId: input.accountId,
570
+ workspaceId: input.workspaceId,
571
+ }),
572
+ organizationModelProviderConnectionActiveForWorkspace(db, {
573
+ accountId: input.accountId,
574
+ workspaceId: input.workspaceId,
575
+ providerKind: "vercel_gateway",
576
+ }),
577
+ listOrganizationModelProviderCustomModelsForWorkspace(db, {
578
+ accountId: input.accountId,
579
+ workspaceId: input.workspaceId,
580
+ providerKind: "vercel_gateway",
581
+ }),
582
+ organizationModelProviderConnectionActiveForWorkspace(db, {
583
+ accountId: input.accountId,
584
+ workspaceId: input.workspaceId,
585
+ providerKind: "openrouter",
586
+ }),
587
+ listOrganizationModelProviderCustomModelsForWorkspace(db, {
588
+ accountId: input.accountId,
589
+ workspaceId: input.workspaceId,
590
+ providerKind: "openrouter",
591
+ }),
592
+ ]);
593
+ return {
594
+ selections: resolveWorkspaceModelSelection({
595
+ settings: currentSettings,
596
+ policy,
597
+ codexSubscriptionActive,
598
+ xaiSubscriptionActive,
599
+ workspaceGatewayConnectionActive,
600
+ workspaceGatewayCustomModels,
601
+ workspaceOpenRouterConnectionActive: openRouterConnectionActive,
602
+ workspaceOpenRouterCustomModels,
603
+ organizationGatewayConnectionActive,
604
+ organizationGatewayCustomModels,
605
+ organizationOpenRouterConnectionActive,
606
+ organizationOpenRouterCustomModels,
607
+ }),
608
+ modelNotes: currentCatalog.modelNotes,
609
+ };
610
+ },
611
+ }),
513
612
  ...(titleToolPlan.promoteTitleTool
514
613
  ? [
515
614
  createSessionTitleAttemptToolDefinition({
@@ -755,17 +854,13 @@ export async function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps) {
755
854
  } else {
756
855
  activatePreparedToolEnvironment(eventing.preparedTools);
757
856
  }
758
- // Genesis turn = the first user turn (no assistant history reconciled
759
- // yet). Durable Postgres state (countSessionHistoryItems includes
760
- // superseded rows after compaction), NOT a workflow counter (turnsThisRun
761
- // resets on continueAsNew). Drives the one-shot title hint appended to the
762
- // agent's instructions; later attempts and goal continuations never match.
763
857
  return {
764
858
  attemptConnectorActionBindings: [
765
859
  ...googleDriveConnectorBindings,
766
860
  ...githubRestMcp.connectorBindings,
767
861
  ],
768
862
  connectorActionIdentity,
863
+ generateSessionTitleInParallel: titleToolPlan.generateTitleInParallel,
769
864
  postToolPreparationStartedAt,
770
865
  preparationIndependentToolNames: titleToolPlan.preparationIndependentToolNames,
771
866
  };
@@ -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 = {
@@ -95,7 +97,8 @@ export type SandboxRuntimeState = {
95
97
  sandboxHolderId: TurnSandboxLeaseHolderId | null;
96
98
  sandboxGroupId: string | null;
97
99
  leaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;
98
- rotationInFlight: Promise<void> | null;
100
+ rotationPreemptionInFlight: Promise<void> | null;
101
+ deadlineRotationRequested: boolean;
99
102
  snapshotInFlight: Promise<void> | null;
100
103
  firstProviderRequestStarted: boolean;
101
104
  turnEndCaptureInProgress: boolean;
@@ -204,6 +207,8 @@ export function createTurnContext(input: {
204
207
  isCodexTurn: false,
205
208
  isXaiTurn: false,
206
209
  isExternallyBilledTurn: false,
210
+ chargesOpenGeniCredits: true,
211
+ countsTowardTokenCap: true,
207
212
  },
208
213
  sandboxState: {
209
214
  resolvedSandbox: null,
@@ -221,7 +226,8 @@ export function createTurnContext(input: {
221
226
  sandboxHolderId: null,
222
227
  sandboxGroupId: null,
223
228
  leaseHeartbeatTimer: undefined,
224
- rotationInFlight: null,
229
+ rotationPreemptionInFlight: null,
230
+ deadlineRotationRequested: false,
225
231
  snapshotInFlight: null,
226
232
  firstProviderRequestStarted: false,
227
233
  turnEndCaptureInProgress: false,
@@ -1,5 +1,9 @@
1
1
  /** Public agent-turn surface. Implementation lives in `./agent-turn/*`. */
2
- export { createRunAgentTurnActivity } from "./agent-turn/run";
2
+ export {
3
+ createRunAgentTurnActivity,
4
+ sessionTitleCodexRequestContext,
5
+ sessionTitleXaiRequestContext,
6
+ } from "./agent-turn/run";
3
7
  export * from "./agent-turn/admission";
4
8
  export * from "./agent-turn/codex";
5
9
  export * from "./agent-turn/errors";
@@ -92,7 +92,13 @@ function integrationCredentialResolver(
92
92
  forceRefresh: request.forceRefresh === true,
93
93
  });
94
94
  if (result.status === "auth_needed") {
95
- await publishAuthNeeded(input, integration.serverId, request.operationKey, result);
95
+ await publishAuthNeeded(
96
+ input,
97
+ integration.serverId,
98
+ request.operationKey,
99
+ result,
100
+ connectionRef,
101
+ );
96
102
  return null;
97
103
  }
98
104
  const destination = new URL(request.destinationUrl);
@@ -120,6 +126,7 @@ async function publishAuthNeeded(
120
126
  serverId: string,
121
127
  toolName: string,
122
128
  result: Extract<ResolveConnectionCredentialResult, { status: "auth_needed" }>,
129
+ connectionRef: NonNullable<ApiIntegrationRuntime["connectionRef"]>,
123
130
  ): Promise<void> {
124
131
  try {
125
132
  await input.onAuthNeeded?.({
@@ -129,6 +136,9 @@ async function publishAuthNeeded(
129
136
  ...(result.provider ? { provider: result.provider } : {}),
130
137
  reason: result.reason,
131
138
  ...(result.connectionId ? { connectionId: result.connectionId } : {}),
139
+ ...(result.authoritySource === "host" || connectionRef.authoritySource === "host"
140
+ ? { authoritySource: "host" as const }
141
+ : {}),
132
142
  ...(result.scopes ? { scopes: result.scopes } : {}),
133
143
  ...(result.resource ? { resource: result.resource } : {}),
134
144
  ...(result.selectedResources ? { selectedResources: result.selectedResources } : {}),
@@ -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
+ }