@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
@@ -2,6 +2,12 @@ import {
2
2
  allowedFirstPartyMcpToolsForSession,
3
3
  configuredStaticUsageLimits,
4
4
  policyProviderIdForModel,
5
+ resolveModelProvider,
6
+ resolveTurnExecutionPolicyV1,
7
+ withCodexCatalogProvider,
8
+ withXaiSubscriptionCatalogProvider,
9
+ WORKSPACE_GATEWAY_MODEL_ID_PREFIX,
10
+ WORKSPACE_OPENROUTER_MODEL_ID_PREFIX,
5
11
  type Settings,
6
12
  } from "@opengeni/config";
7
13
  import {
@@ -28,6 +34,11 @@ import type {
28
34
  MaybeContinueGoalInput,
29
35
  MaybeContinueGoalResult,
30
36
  } from "./types";
37
+ import {
38
+ modelFundingForAdmission,
39
+ resolveCatalogSettings,
40
+ resolveWorkspaceCatalogSettings,
41
+ } from "@opengeni/core";
31
42
 
32
43
  export function createGoalActivities(services: () => Promise<ControlActivityServices>) {
33
44
  async function enqueueGoalRetryWake(input: MaybeContinueGoalInput): Promise<void> {
@@ -47,12 +58,15 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
47
58
  async function maybeContinueGoal(
48
59
  input: MaybeContinueGoalInput,
49
60
  ): Promise<MaybeContinueGoalResult> {
50
- const { settings, db, bus } = await services();
61
+ const service = await services();
62
+ const { db, bus } = service;
63
+ const catalogSourceSettings = service.catalogSourceSettings ?? service.settings;
51
64
  // Cheap pre-read: the common goal-less session skips the budget queries.
52
65
  const existingGoal = await getSessionGoal(db, input.workspaceId, input.sessionId);
53
66
  if (!existingGoal || existingGoal.status !== "active") {
54
67
  return { action: "none" };
55
68
  }
69
+ let settings = (await resolveCatalogSettings(db, catalogSourceSettings)).settings;
56
70
  // Loaded before the budget check so the codex-billed predicate and the
57
71
  // synthesized turn use the SAME effective policy. An explicit per-turn
58
72
  // model can differ from the persisted session default; follow-up goal work
@@ -66,34 +80,34 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
66
80
  input.workspaceId,
67
81
  input.sessionId,
68
82
  );
69
- let continuationModel = latestStartedTurn?.model ?? session.model;
83
+ const inheritedContinuationModel = latestStartedTurn?.model ?? session.model;
84
+ let continuationModel = inheritedContinuationModel;
70
85
  const continuationReasoningEffort =
71
86
  latestStartedTurn?.reasoningEffort ?? session.reasoningEffort;
72
87
  const continuationLatencyMode = latestStartedTurn?.latencyMode ?? session.latencyMode;
73
- // Workspace model policy: a continuation inherits the last STARTED turn's
74
- // model, so a single policy-violating turn would otherwise re-arm itself on
75
- // every continuation (exactly how one bare-model turn kept a goal loop on
76
- // the paid built-in provider all night). If the inherited model is blocked
77
- // but the session's own default is allowed, recover to the default; if
78
- // both are blocked, pause the goal visibly (the budget-pause channel, with
79
- // a truthful rationale) instead of synthesizing a turn the worker's hard
80
- // gate would fail over and over.
81
- let modelPolicyBlocked: string | null = null;
82
88
  const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);
83
- if (workspaceModelPolicy) {
84
- const policyBlocks = (modelId: string): boolean =>
85
- !evaluateWorkspaceModelPolicy(workspaceModelPolicy, {
86
- providerId: policyProviderIdForModel(settings, modelId),
87
- modelId,
88
- }).allowed;
89
- if (policyBlocks(continuationModel)) {
90
- if (continuationModel !== session.model && !policyBlocks(session.model)) {
91
- continuationModel = session.model;
92
- } else {
93
- modelPolicyBlocked = `workspace model policy blocks model "${continuationModel}"; pick an allowed model or change the workspace model policy`;
94
- }
95
- }
89
+ if (
90
+ inheritedContinuationModel.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
91
+ inheritedContinuationModel.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX) ||
92
+ session.model.startsWith(WORKSPACE_GATEWAY_MODEL_ID_PREFIX) ||
93
+ session.model.startsWith(WORKSPACE_OPENROUTER_MODEL_ID_PREFIX)
94
+ ) {
95
+ settings = (
96
+ await resolveWorkspaceCatalogSettings(db, catalogSourceSettings, {
97
+ accountId: input.accountId,
98
+ workspaceId: input.workspaceId,
99
+ retainedProductModelIds: [inheritedContinuationModel, session.model],
100
+ })
101
+ ).settings;
96
102
  }
103
+ const modelDecision = goalContinuationModelDecision({
104
+ settings,
105
+ workspaceModelPolicy,
106
+ inheritedModel: inheritedContinuationModel,
107
+ sessionModel: session.model,
108
+ });
109
+ continuationModel = modelDecision.model;
110
+ let modelPolicyBlocked = modelDecision.blocked;
97
111
  // remote_v2 sessions may only continue on Codex models — refuse synthesis
98
112
  // that would leave the portable/non-Codex path (and mixed history shapes).
99
113
  if (
@@ -112,6 +126,11 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
112
126
  workspaceId: input.workspaceId,
113
127
  model: continuationModel,
114
128
  });
129
+ const fundedWithoutCredits = goalContinuationFundedWithoutCredits(
130
+ settings,
131
+ continuationModel,
132
+ isCodexRun,
133
+ );
115
134
  // Budget exhaustion pauses the goal visibly instead of failing the
116
135
  // session. Computed up front and applied inside the locked decision so a
117
136
  // limits pause never consumes continuation budget.
@@ -120,8 +139,17 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
120
139
  db,
121
140
  input.accountId,
122
141
  input.workspaceId,
123
- isCodexRun,
142
+ fundedWithoutCredits,
124
143
  );
144
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(settings, {
145
+ modelId: continuationModel,
146
+ requestedModelId: null,
147
+ modelSource: "continuation",
148
+ reasoningEffort: continuationReasoningEffort,
149
+ reasoningSource: "continuation",
150
+ latencyMode: continuationLatencyMode,
151
+ latencyModeSource: "continuation",
152
+ });
125
153
  const decision = await materializeGoalContinuation(db, {
126
154
  accountId: input.accountId,
127
155
  workspaceId: input.workspaceId,
@@ -142,6 +170,7 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
142
170
  model: continuationModel,
143
171
  reasoningEffort: continuationReasoningEffort,
144
172
  latencyMode: continuationLatencyMode,
173
+ turnExecutionPolicy,
145
174
  tools: withFirstPartyTools(settings, session.tools),
146
175
  sandboxBackend: session.sandboxBackend,
147
176
  },
@@ -174,6 +203,53 @@ export function createGoalActivities(services: () => Promise<ControlActivityServ
174
203
  };
175
204
  }
176
205
 
206
+ export function goalContinuationModelDecision(input: {
207
+ settings: Settings;
208
+ workspaceModelPolicy: Awaited<ReturnType<typeof getWorkspaceModelPolicy>>;
209
+ inheritedModel: string;
210
+ sessionModel: string;
211
+ }): { model: string; blocked: string | null } {
212
+ const catalogSettings = input.settings.supergrokSubscriptionEnabled
213
+ ? withXaiSubscriptionCatalogProvider(
214
+ input.settings.codexSubscriptionEnabled
215
+ ? withCodexCatalogProvider(input.settings)
216
+ : input.settings,
217
+ )
218
+ : input.settings.codexSubscriptionEnabled
219
+ ? withCodexCatalogProvider(input.settings)
220
+ : input.settings;
221
+ const policyBlocks = (modelId: string): boolean =>
222
+ input.workspaceModelPolicy !== null &&
223
+ !evaluateWorkspaceModelPolicy(input.workspaceModelPolicy, {
224
+ providerId: policyProviderIdForModel(catalogSettings, modelId),
225
+ modelId,
226
+ }).allowed;
227
+ const candidates = [...new Set([input.inheritedModel, input.sessionModel])];
228
+ for (const model of candidates) {
229
+ if (resolveModelProvider(catalogSettings, model) && !policyBlocks(model)) {
230
+ return { model, blocked: null };
231
+ }
232
+ }
233
+ if (!resolveModelProvider(catalogSettings, input.inheritedModel)) {
234
+ return {
235
+ model: input.inheritedModel,
236
+ blocked: `model "${input.inheritedModel}" is no longer in the deployment or workspace catalog; choose an available model before resuming the goal`,
237
+ };
238
+ }
239
+ return {
240
+ model: input.inheritedModel,
241
+ blocked: `workspace model policy blocks model "${input.inheritedModel}"; pick an allowed model or change the workspace model policy`,
242
+ };
243
+ }
244
+
245
+ export function goalContinuationFundedWithoutCredits(
246
+ settings: Settings,
247
+ model: string,
248
+ codexBilled: boolean,
249
+ ): boolean {
250
+ return modelFundingForAdmission(settings, model, codexBilled).fundedWithoutCredits;
251
+ }
252
+
177
253
  export function goalContinuationPrompt(
178
254
  _goal: SessionGoal,
179
255
  _autoContinuation: number,
@@ -269,13 +345,13 @@ async function goalRunBudgetBlocked(
269
345
  db: Database,
270
346
  accountId: string,
271
347
  workspaceId: string,
272
- isCodexRun: boolean,
348
+ fundedWithoutCredits: boolean,
273
349
  ): Promise<string | null> {
274
- // Codex-billed continuations are paid by the user's ChatGPT/Codex plan: skip
275
- // the credit-balance gate and the monthly model-cost cap. The agent-run COUNT
276
- // cap below is a volume quota (not a credit/cost gate) and is intentionally kept.
350
+ // Free, subscription, and workspace-funded continuations skip OpenGeni's
351
+ // credit-balance gate and monthly model-cost cap. The agent-run COUNT cap
352
+ // below is a volume quota (not a credit/cost gate) and remains enforced.
277
353
  if (
278
- !isCodexRun &&
354
+ !fundedWithoutCredits &&
279
355
  (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
280
356
  ) {
281
357
  const balance = await getBillingBalance(db, accountId);
@@ -285,7 +361,7 @@ async function goalRunBudgetBlocked(
285
361
  }
286
362
  if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
287
363
  const limits = configuredStaticUsageLimits(settings);
288
- if (!isCodexRun && limits.maxMonthlyCostMicrosPerAccount) {
364
+ if (!fundedWithoutCredits && limits.maxMonthlyCostMicrosPerAccount) {
289
365
  const used = await sumUsageQuantity(db, {
290
366
  accountId,
291
367
  eventType: "model.cost",
@@ -200,20 +200,20 @@ async function referenceBytes(
200
200
  );
201
201
  }
202
202
  return {
203
- bytes: await readStoredFile(input.objectStorage, file),
203
+ bytes: await readStoredImageReferenceFile(input.objectStorage, file),
204
204
  file,
205
205
  };
206
206
  }
207
207
 
208
- async function readStoredFile(objectStorage: ObjectStorage, file: FileAsset): Promise<Uint8Array> {
209
- const bytes = await objectStorage.getFileRange(file, {
210
- start: 0,
211
- end: file.sizeBytes - 1,
212
- });
213
- if (!bytes) {
208
+ export async function readStoredImageReferenceFile(
209
+ objectStorage: Pick<ObjectStorage, "getFileBytes">,
210
+ file: FileAsset,
211
+ ): Promise<Uint8Array> {
212
+ const bytes = await objectStorage.getFileBytes(file);
213
+ if (bytes.byteLength !== file.sizeBytes) {
214
214
  throw new ImageGenerationReferenceError(
215
- "reference_unavailable",
216
- "The durable image reference bytes are unavailable.",
215
+ "reference_integrity_mismatch",
216
+ "The durable image reference bytes do not match their file metadata.",
217
217
  );
218
218
  }
219
219
  return bytes;
@@ -10,6 +10,7 @@ import {
10
10
  normalizeAutomaticSessionTitle,
11
11
  scheduledOccurrencePayloadUtf8Bytes,
12
12
  stableJson,
13
+ TurnExecutionPolicyV1,
13
14
  type ScheduledTask,
14
15
  type ScheduledTaskRun,
15
16
  } from "@opengeni/contracts";
@@ -17,7 +18,9 @@ import {
17
18
  defaultSessionMcpServerIds,
18
19
  openGeniSlackBotMetadata,
19
20
  requireOpenGeniSlackBotConnection,
21
+ resolveWorkspaceCatalogSettings,
20
22
  resolveSessionToolPolicy,
23
+ workspaceCustomModelReference,
21
24
  scheduledSlackBotConnectionId,
22
25
  swapActiveSandbox,
23
26
  } from "@opengeni/core";
@@ -49,6 +52,8 @@ import {
49
52
  getVariableSet,
50
53
  isCodexBilledModel,
51
54
  initializeSessionStartAtomically,
55
+ lockActiveWorkspaceGatewayCustomModelForAdmission,
56
+ lockActiveWorkspaceOpenRouterCustomModelForAdmission,
52
57
  materializeScheduledTaskReusableSessionFromRun,
53
58
  listEnabledMcpCapabilityServerIds,
54
59
  listInstalledApiIntegrationServerIdsForDelegations,
@@ -67,8 +72,9 @@ import {
67
72
  withSessionActivityRlsContext,
68
73
  } from "@opengeni/db";
69
74
  import { publishDurableSessionEvents } from "@opengeni/events";
70
- import { resolveFirstPartyMcpToolPolicy } from "@opengeni/config";
75
+ import { resolveFirstPartyMcpToolPolicy, resolveTurnExecutionPolicyV1 } from "@opengeni/config";
71
76
  import { Context } from "@temporalio/activity";
77
+ import { createHash } from "node:crypto";
72
78
  import {
73
79
  assertReusableSessionRevivable,
74
80
  scheduledUserMessagePayload,
@@ -128,6 +134,14 @@ export function scheduledTaskRunProducerKey(
128
134
  })}`;
129
135
  }
130
136
 
137
+ export function scheduledTaskGeneratedSessionCreateIdempotencyKey(producerKey: string): string {
138
+ const digest = createHash("sha256")
139
+ .update("scheduled-task-run\0", "utf8")
140
+ .update(producerKey, "utf8")
141
+ .digest("hex");
142
+ return `scheduled-task-run:${digest}`;
143
+ }
144
+
131
145
  /**
132
146
  * Display title for a session the scheduler generates for a task.
133
147
  *
@@ -234,14 +248,26 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
234
248
  dispatchScheduledTaskRun: async (
235
249
  input: DispatchScheduledTaskRunInput,
236
250
  ): Promise<DispatchScheduledTaskRunResult> => {
237
- const service = await services();
238
- const { settings, db, bus, wakeSessionWorkflow } = service;
251
+ const baseService = await services();
239
252
  // Histories created before the manual-initiator workflow patch already
240
253
  // contain this activity command. Reject their incomplete wire input here
241
254
  // so replay consumes the recorded command and the retry loop settles.
242
255
  if (input.triggerType !== "scheduled" && !input.initiator) {
243
256
  return { action: "blocked", reason: "malformed_manual_trigger" };
244
257
  }
258
+ const { db, bus, wakeSessionWorkflow } = baseService;
259
+ const settingsForTask = async (task: ScheduledTask, retainedProductModelId?: string | null) =>
260
+ (
261
+ await resolveWorkspaceCatalogSettings(
262
+ db,
263
+ baseService.catalogSourceSettings ?? baseService.settings,
264
+ {
265
+ accountId: task.accountId,
266
+ workspaceId: task.workspaceId,
267
+ ...(retainedProductModelId !== undefined ? { retainedProductModelId } : {}),
268
+ },
269
+ )
270
+ ).settings;
245
271
  const stableProducerKey = scheduledTaskRunProducerKey(input);
246
272
  const priorRun = await getScheduledTaskRunByProducerKey(db, {
247
273
  workspaceId: input.workspaceId,
@@ -275,6 +301,15 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
275
301
  });
276
302
  }
277
303
  if (priorRun.status === "queued") {
304
+ const acceptedPolicy = acceptedExecution.turnExecutionPolicy
305
+ ? TurnExecutionPolicyV1.parse(acceptedExecution.turnExecutionPolicy)
306
+ : null;
307
+ const settings = await settingsForTask(
308
+ acceptedExecution.task,
309
+ acceptedPolicy?.productModelId ??
310
+ acceptedExecution.targetSessionExecution?.model ??
311
+ acceptedExecution.resolvedModel,
312
+ );
278
313
  try {
279
314
  return await recoverBoundScheduledTaskDispatch({
280
315
  db,
@@ -444,6 +479,27 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
444
479
  taskRevisionAuthority?.subjectId ??
445
480
  taskPersonalResourceAuthoritySubjectId ??
446
481
  taskConnectionAuthoritySubjectId;
482
+ const acceptedTargetSessionId =
483
+ task.runMode === "existing_session"
484
+ ? task.targetSessionId
485
+ : task.runMode === "reusable_session"
486
+ ? task.reusableSessionId
487
+ : null;
488
+ // A targeted task whose exact session was deleted has no target to
489
+ // resolve; database admission settles that occurrence terminally
490
+ // (`scheduled_target_session_unavailable`) instead of retrying forever.
491
+ // Resolve this before the catalog so an existing session's retired
492
+ // custom Gateway model remains executable without becoming selectable
493
+ // for a new scheduled session.
494
+ const targetSessionExecutionBase = acceptedTargetSessionId
495
+ ? await getScheduledTargetSessionExecution(
496
+ db,
497
+ task.workspaceId,
498
+ acceptedTargetSessionId,
499
+ taskAuthoritySubjectId,
500
+ )
501
+ : null;
502
+ const settings = await settingsForTask(task, targetSessionExecutionBase?.model);
447
503
  const model = task.agentConfig.model ?? settings.openaiModel;
448
504
  const reasoningEffort = task.agentConfig.reasoningEffort ?? settings.openaiReasoningEffort;
449
505
  let sandboxBackend = task.agentConfig.sandboxBackend ?? settings.sandboxBackend;
@@ -515,22 +571,6 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
515
571
  };
516
572
  })()
517
573
  : null;
518
- const acceptedTargetSessionId = generatedTarget
519
- ? null
520
- : task.runMode === "existing_session"
521
- ? task.targetSessionId
522
- : task.reusableSessionId;
523
- // A targeted task whose exact session was deleted has no target to
524
- // resolve; database admission settles that occurrence terminally
525
- // (`scheduled_target_session_unavailable`) instead of retrying forever.
526
- const targetSessionExecutionBase = acceptedTargetSessionId
527
- ? await getScheduledTargetSessionExecution(
528
- db,
529
- task.workspaceId,
530
- acceptedTargetSessionId,
531
- taskAuthoritySubjectId,
532
- )
533
- : null;
534
574
  const targetSessionExecution = targetSessionExecutionBase
535
575
  ? await (async () => {
536
576
  const [capabilityServerIds, apiIntegrationServerIds] = await Promise.all([
@@ -727,15 +767,63 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
727
767
  ) {
728
768
  throw new Error("scheduled personal-resource execution has no causal human");
729
769
  }
730
- const admissionDenial = await agentRunAdmissionDenial(service, {
731
- accountId: task.accountId,
732
- workspaceId: task.workspaceId,
733
- model: targetSessionExecution?.model ?? model,
734
- requestedAgentRuns: input.agentRunUsageIdempotencyKey ? 0 : 1,
735
- });
770
+ const admissionDenial = await agentRunAdmissionDenial(
771
+ { ...baseService, settings },
772
+ {
773
+ accountId: task.accountId,
774
+ workspaceId: task.workspaceId,
775
+ model: targetSessionExecution?.model ?? model,
776
+ requestedAgentRuns: input.agentRunUsageIdempotencyKey ? 0 : 1,
777
+ },
778
+ );
736
779
  if (admissionDenial) {
737
780
  return { action: "blocked", reason: admissionDenial };
738
781
  }
782
+ const acceptedModel = targetSessionExecution?.model ?? model;
783
+ const acceptedReasoningEffort = targetSessionExecution?.reasoningEffort ?? reasoningEffort;
784
+ const acceptedLatencyMode = targetSessionExecution?.latencyMode ?? "standard";
785
+ const acceptedCustomModel = generatedTarget
786
+ ? workspaceCustomModelReference(settings, acceptedModel)
787
+ : null;
788
+ const beforeFreshAgentRunCommit = acceptedCustomModel
789
+ ? async (tx: Database): Promise<void> => {
790
+ const active =
791
+ acceptedCustomModel.providerKind === "openrouter"
792
+ ? await lockActiveWorkspaceOpenRouterCustomModelForAdmission(tx, {
793
+ accountId: task.accountId,
794
+ workspaceId: task.workspaceId,
795
+ upstreamModelId: acceptedCustomModel.upstreamModelId,
796
+ })
797
+ : await lockActiveWorkspaceGatewayCustomModelForAdmission(tx, {
798
+ accountId: task.accountId,
799
+ workspaceId: task.workspaceId,
800
+ upstreamModelId: acceptedCustomModel.upstreamModelId,
801
+ });
802
+ if (!active) {
803
+ throw new ScheduledRunTerminalAuthorityError(
804
+ "scheduled_model_unavailable",
805
+ `model is not available: ${acceptedModel}`,
806
+ );
807
+ }
808
+ }
809
+ : undefined;
810
+ const turnExecutionPolicy: TurnExecutionPolicyV1 = resolveTurnExecutionPolicyV1(settings, {
811
+ modelId: acceptedModel,
812
+ requestedModelId: generatedTarget && task.agentConfig.model ? task.agentConfig.model : null,
813
+ modelSource: generatedTarget
814
+ ? task.agentConfig.model
815
+ ? "explicit"
816
+ : "deployment"
817
+ : "session",
818
+ reasoningEffort: acceptedReasoningEffort,
819
+ reasoningSource: generatedTarget
820
+ ? task.agentConfig.reasoningEffort
821
+ ? "explicit"
822
+ : "deployment"
823
+ : "session",
824
+ latencyMode: acceptedLatencyMode,
825
+ latencyModeSource: generatedTarget ? "deployment" : "session",
826
+ });
739
827
  const deferredEvents: Array<{
740
828
  sessionId: string;
741
829
  events: Awaited<ReturnType<typeof appendSessionEvents>>;
@@ -748,7 +836,7 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
748
836
  alertResponderSessionCreateIdempotencyKey ??
749
837
  (task.runMode === "reusable_session"
750
838
  ? `scheduled-task-reusable:${task.id}:${task.authorityRevision}:${task.executionDigest}`
751
- : `scheduled-task-run:${admittedRunId}`),
839
+ : scheduledTaskGeneratedSessionCreateIdempotencyKey(stableProducerKey)),
752
840
  effectiveMaxNestedAgentDepth:
753
841
  generatedSessionDepthPolicy!.effectiveMaxNestedAgentDepth,
754
842
  nestedAgentDepthPolicySource:
@@ -762,6 +850,7 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
762
850
  resolvedModel: model,
763
851
  resolvedReasoningEffort: reasoningEffort,
764
852
  resolvedLatencyMode: "standard",
853
+ turnExecutionPolicy,
765
854
  resolvedSandboxBackend: sandboxBackend,
766
855
  resolvedSandboxOs: sandboxOs,
767
856
  resolvedTools: taskTools,
@@ -832,6 +921,7 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
832
921
  producerKey: stableProducerKey,
833
922
  scheduledAt: null,
834
923
  acceptedExecutionSnapshot: acceptedExecution,
924
+ ...(beforeFreshAgentRunCommit ? { beforeFreshAgentRunCommit } : {}),
835
925
  });
836
926
  await recordScheduledTaskFiredUsage(dispatchDb, acceptedExecution, run);
837
927
  if (run.status === "failed" && run.error === "scheduled_authority_exhausted") {
@@ -1571,6 +1661,10 @@ export function createScheduledTaskActivities(services: () => Promise<ControlAct
1571
1661
  if (error instanceof IncidentTelemetryPreflightBlockedError) {
1572
1662
  return { action: "blocked", reason: error.reason };
1573
1663
  }
1664
+ const terminalError = scheduledRunRecoveryTerminalError(error);
1665
+ if (terminalError?.code === "scheduled_model_unavailable") {
1666
+ return scheduledRunTerminalResult(terminalError.code);
1667
+ }
1574
1668
  throw error;
1575
1669
  }
1576
1670
  if (dispatchOutcome.kind === "replay") {
@@ -10,6 +10,7 @@ import {
10
10
  canonicalConfiguredModel,
11
11
  createAndStartSessionWithOutcome,
12
12
  recordWorkspaceUsage,
13
+ resolveCatalogSettings,
13
14
  } from "@opengeni/core";
14
15
  import {
15
16
  claimSiteAuthMaintenance,
@@ -127,23 +128,22 @@ async function dispatchMaintenanceSession(
127
128
  assertModelPolicy: typeof assertWorkspaceModelPolicyAllows;
128
129
  },
129
130
  ): Promise<void> {
130
- const model = canonicalConfiguredModel(service.settings, service.settings.openaiModel);
131
+ const catalogSettings = (
132
+ await resolveCatalogSettings(service.db, service.catalogSourceSettings ?? service.settings)
133
+ ).settings;
134
+ const catalogService = { ...service, settings: catalogSettings };
135
+ const model = canonicalConfiguredModel(catalogSettings, catalogSettings.openaiModel);
131
136
  if (!model) throw new Error("site auth maintenance has no configured model");
132
- await dependencies.assertModelPolicy(
133
- service.db,
134
- service.settings,
135
- maintenance.workspaceId,
136
- model,
137
- );
138
- const denial = await dependencies.admit(service, {
137
+ await dependencies.assertModelPolicy(service.db, catalogSettings, maintenance.workspaceId, model);
138
+ const denial = await dependencies.admit(catalogService, {
139
139
  accountId: maintenance.accountId,
140
140
  workspaceId: maintenance.workspaceId,
141
141
  model,
142
142
  requestedAgentRuns: 1,
143
143
  });
144
144
  if (denial) throw new Error(`site auth maintenance admission denied: ${denial}`);
145
- const reasoningEffort = service.settings.openaiReasoningEffort;
146
- const turnExecutionPolicy = resolveTurnExecutionPolicyV1(service.settings, {
145
+ const reasoningEffort = catalogSettings.openaiReasoningEffort;
146
+ const turnExecutionPolicy = resolveTurnExecutionPolicyV1(catalogSettings, {
147
147
  modelId: model,
148
148
  requestedModelId: null,
149
149
  modelSource: "deployment",
@@ -180,7 +180,7 @@ async function dispatchMaintenanceSession(
180
180
  model,
181
181
  reasoningEffort,
182
182
  turnExecutionPolicy,
183
- sandboxBackend: service.settings.sandboxBackend,
183
+ sandboxBackend: catalogSettings.sandboxBackend,
184
184
  metadata: {
185
185
  role: "site_auth_maintenance",
186
186
  [SITE_AUTH_MAINTENANCE_CONNECTION_CONTEXT_KEY]: maintenance.siteAuthConnectionId,
@@ -205,7 +205,7 @@ async function dispatchMaintenanceSession(
205
205
  });
206
206
  try {
207
207
  await dependencies.recordUsage(
208
- { db: service.db, settings: service.settings },
208
+ { db: service.db, settings: catalogSettings },
209
209
  {
210
210
  accountId: maintenance.accountId,
211
211
  workspaceId: maintenance.workspaceId,
@@ -75,6 +75,11 @@ export type InspectSessionAttemptActivity = (input: {
75
75
  * agent runtime and document parser so each process can load only its role. */
76
76
  export type SharedActivityServices = {
77
77
  settings: Settings;
78
+ /**
79
+ * Original environment/host settings retained across live database-catalog
80
+ * refreshes. Older embedded test hosts may omit it and fall back to settings.
81
+ */
82
+ catalogSourceSettings?: Settings;
78
83
  db: Database;
79
84
  bus: EventBus;
80
85
  objectStorage: ObjectStorage | null;
@@ -461,6 +466,7 @@ export type DispatchAutomationRunResult =
461
466
  | { action: "started"; sessionId: string }
462
467
  | { action: "already_dispatched"; sessionId: string }
463
468
  | { action: "skipped"; reason: string }
469
+ | { action: "failed"; reason: string }
464
470
  | { action: "not_found" };
465
471
 
466
472
  export type RunKnowledgeSourceSyncBatchResult =
package/src/activities.ts CHANGED
@@ -107,6 +107,7 @@ export const expireSessionInteractionIntervention =
107
107
  export const markSessionIdle = defaultControlActivities.markSessionIdle;
108
108
  export const dispatchScheduledTaskRun = defaultControlActivities.dispatchScheduledTaskRun;
109
109
  export const dispatchAutomationRun = defaultControlActivities.dispatchAutomationRun;
110
+ export const settleAutomationRunFailure = defaultControlActivities.settleAutomationRunFailure;
110
111
  export const runKnowledgeSourceSyncBatch = defaultControlActivities.runKnowledgeSourceSyncBatch;
111
112
  export const enqueueGoalRetryWake = defaultControlActivities.enqueueGoalRetryWake;
112
113
  export const maybeContinueGoal = defaultControlActivities.maybeContinueGoal;
@@ -2,6 +2,7 @@ import { dbSearchPath, getSettings, resolveNatsControlPlaneAuth } from "@opengen
2
2
  import { configureChildLifecycleNotices, createDb } from "@opengeni/db";
3
3
  import { createNatsEventBus } from "@opengeni/events";
4
4
  import { createObservability } from "@opengeni/observability";
5
+ import { resolveCatalogSettings } from "@opengeni/core";
5
6
  import { createObjectStorage } from "@opengeni/storage";
6
7
  import type { ActivityDependencies, SharedActivityServices } from "./activities/types";
7
8
  import { observabilityEventLogger } from "./observability-metrics";
@@ -35,11 +36,13 @@ export function createSharedActivityServices(
35
36
  });
36
37
  const controlPlaneAuth = resolveNatsControlPlaneAuth(settings);
37
38
  const db = dependencies.db ?? dbClient!.db;
39
+ const resolvedSettings = (await resolveCatalogSettings(db, settings)).settings;
38
40
  // Child lifecycle notice producers are process-global in @opengeni/db;
39
41
  // install the boot-validated rollout flag once for this worker.
40
42
  configureChildLifecycleNotices({ enabled: settings.childLifecycleNoticesEnabled });
41
43
  return {
42
- settings,
44
+ settings: resolvedSettings,
45
+ catalogSourceSettings: settings,
43
46
  db,
44
47
  bus:
45
48
  dependencies.bus ??
@@ -31,6 +31,7 @@ import {
31
31
  import { createGitHubAppInstallationTokenWithExpiry, githubAppBotIdentity } from "@opengeni/github";
32
32
  import {
33
33
  type AttemptConnectorActionBinding,
34
+ ConnectorActionBindingRejectedError,
34
35
  type LocalMcpServerRegistration,
35
36
  prefixedMcpToolName,
36
37
  } from "@opengeni/runtime";
@@ -624,7 +625,7 @@ function githubConnectorBindings(
624
625
  const repository =
625
626
  typeof args.repository === "string" ? byName.get(args.repository.toLowerCase()) : null;
626
627
  if (!repository) {
627
- throw new GitHubRestAuthorityError(
628
+ throw new ConnectorActionBindingRejectedError(
628
629
  "GitHub action repository does not match an accepted resource",
629
630
  );
630
631
  }