@opengeni/worker-bundle 0.23.4 → 0.26.0-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 (115) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +17 -2
  2. package/dist/activities/agent-turn/agent-build.d.ts +3 -10
  3. package/dist/activities/agent-turn/claim.d.ts +8 -0
  4. package/dist/activities/agent-turn/codex.d.ts +2 -2
  5. package/dist/activities/agent-turn/credential-leases.d.ts +8 -0
  6. package/dist/activities/agent-turn/errors.d.ts +1 -1
  7. package/dist/activities/agent-turn/failure-settlement.d.ts +43 -1
  8. package/dist/activities/agent-turn/list-models.d.ts +16 -0
  9. package/dist/activities/agent-turn/model-usage.d.ts +15 -1
  10. package/dist/activities/agent-turn/quiescence.d.ts +11 -6
  11. package/dist/activities/agent-turn/run.d.ts +9 -0
  12. package/dist/activities/agent-turn/sandbox-runtime.d.ts +15 -0
  13. package/dist/activities/agent-turn/session-title.d.ts +21 -0
  14. package/dist/activities/agent-turn/stream-attempt.d.ts +4 -0
  15. package/dist/activities/agent-turn/tool-environment.d.ts +4 -13
  16. package/dist/activities/agent-turn/tool-policy.d.ts +40 -5
  17. package/dist/activities/agent-turn/turn-context.d.ts +13 -2
  18. package/dist/activities/agent-turn.d.ts +1 -1
  19. package/dist/activities/automations.d.ts +1 -0
  20. package/dist/activities/capabilities.d.ts +3 -1
  21. package/dist/activities/codemode-dispatcher.d.ts +10 -1
  22. package/dist/activities/codex-capacity.d.ts +32 -3
  23. package/dist/activities/codex-fleet-shadow.d.ts +1 -1
  24. package/dist/activities/codex-image-generation.d.ts +1 -1
  25. package/dist/activities/codex-rotation.d.ts +8 -67
  26. package/dist/activities/context-compaction.d.ts +2 -0
  27. package/dist/activities/goals.d.ts +12 -1
  28. package/dist/activities/google-drive-publication.d.ts +2 -13
  29. package/dist/activities/image-generation-operation.d.ts +13 -4
  30. package/dist/activities/image-generation-references.d.ts +2 -1
  31. package/dist/activities/scheduled-tasks.d.ts +1 -0
  32. package/dist/activities/session-state.d.ts +4 -2
  33. package/dist/activities/types.d.ts +19 -1
  34. package/dist/{activities-control-52W5IDWM.js → activities-control-CTEMLTHG.js} +339 -195
  35. package/dist/activities-control-CTEMLTHG.js.map +1 -0
  36. package/dist/activities-control.d.ts +4 -0
  37. package/dist/{activities-turn-A2G2KLSY.js → activities-turn-S5IU347A.js} +1846 -1136
  38. package/dist/activities-turn-S5IU347A.js.map +1 -0
  39. package/dist/activities.d.ts +4 -0
  40. package/dist/{chunk-GFNXVZVQ.js → chunk-D4ZEFOYH.js} +107 -7
  41. package/dist/chunk-D4ZEFOYH.js.map +1 -0
  42. package/dist/{chunk-GRFQTTSQ.js → chunk-GDCLDKSH.js} +7 -3
  43. package/dist/{chunk-GRFQTTSQ.js.map → chunk-GDCLDKSH.js.map} +1 -1
  44. package/dist/{chunk-IPVMCAW5.js → chunk-TAUE3GYT.js} +225 -154
  45. package/dist/chunk-TAUE3GYT.js.map +1 -0
  46. package/dist/github-rest-mcp.d.ts +0 -2
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.js +43 -7
  49. package/dist/index.js.map +1 -1
  50. package/dist/observability-metrics.d.ts +35 -8
  51. package/dist/sandbox-reaper-timeout.d.ts +2 -2
  52. package/dist/sandbox-resume.d.ts +6 -1
  53. package/dist/workflow-bundle.js +96 -10
  54. package/dist/workflows/activities.d.ts +6 -1
  55. package/dist/workflows/automations.d.ts +5 -0
  56. package/dist/workflows/session.d.ts +3 -0
  57. package/package.json +17 -17
  58. package/src/activities/agent-run-admission.ts +7 -1
  59. package/src/activities/agent-turn/admission.ts +47 -6
  60. package/src/activities/agent-turn/agent-build.ts +20 -26
  61. package/src/activities/agent-turn/claim.ts +59 -6
  62. package/src/activities/agent-turn/codex-capacity.ts +311 -234
  63. package/src/activities/agent-turn/codex.ts +2 -2
  64. package/src/activities/agent-turn/compaction-prep.ts +8 -1
  65. package/src/activities/agent-turn/credential-leases.ts +36 -0
  66. package/src/activities/agent-turn/errors.ts +29 -1
  67. package/src/activities/agent-turn/failure-settlement.ts +451 -323
  68. package/src/activities/agent-turn/finalization.ts +31 -17
  69. package/src/activities/agent-turn/list-models.ts +101 -0
  70. package/src/activities/agent-turn/model-usage.ts +120 -45
  71. package/src/activities/agent-turn/quiescence.ts +32 -17
  72. package/src/activities/agent-turn/run.ts +98 -9
  73. package/src/activities/agent-turn/sandbox-runtime.ts +78 -81
  74. package/src/activities/agent-turn/session-title.ts +55 -2
  75. package/src/activities/agent-turn/stream-attempt.ts +281 -136
  76. package/src/activities/agent-turn/tool-environment.ts +132 -39
  77. package/src/activities/agent-turn/tool-policy.ts +71 -12
  78. package/src/activities/agent-turn/turn-context.ts +21 -2
  79. package/src/activities/agent-turn.ts +5 -1
  80. package/src/activities/automations.ts +122 -67
  81. package/src/activities/capabilities.ts +129 -2
  82. package/src/activities/codemode-dispatcher.ts +235 -59
  83. package/src/activities/codex-capacity.ts +89 -10
  84. package/src/activities/codex-fleet-shadow.ts +8 -1
  85. package/src/activities/codex-image-generation.ts +19 -2
  86. package/src/activities/codex-rotation.ts +45 -142
  87. package/src/activities/context-compaction.ts +3 -0
  88. package/src/activities/goals.ts +116 -39
  89. package/src/activities/google-drive-publication.ts +4 -81
  90. package/src/activities/image-generation-operation.ts +28 -3
  91. package/src/activities/image-generation-references.ts +9 -9
  92. package/src/activities/mcp-credentials.ts +53 -0
  93. package/src/activities/rig-verification.ts +5 -3
  94. package/src/activities/sandbox-lease.ts +29 -12
  95. package/src/activities/scheduled-tasks.ts +217 -110
  96. package/src/activities/session-state.ts +17 -0
  97. package/src/activities/site-auth-maintenance.ts +12 -12
  98. package/src/activities/types.ts +22 -8
  99. package/src/activities.ts +2 -0
  100. package/src/activity-services.ts +4 -1
  101. package/src/github-rest-mcp.ts +2 -83
  102. package/src/index.ts +34 -4
  103. package/src/observability-metrics.ts +158 -14
  104. package/src/sandbox-reaper-timeout.ts +10 -4
  105. package/src/sandbox-resume.ts +58 -8
  106. package/src/sandbox-routing.ts +71 -16
  107. package/src/workflows/activities.ts +16 -0
  108. package/src/workflows/automations.ts +21 -2
  109. package/src/workflows/session.ts +85 -7
  110. package/dist/activities/api-integrations.d.ts +0 -21
  111. package/dist/activities-control-52W5IDWM.js.map +0 -1
  112. package/dist/activities-turn-A2G2KLSY.js.map +0 -1
  113. package/dist/chunk-GFNXVZVQ.js.map +0 -1
  114. package/dist/chunk-IPVMCAW5.js.map +0 -1
  115. package/src/activities/api-integrations.ts +0 -141
@@ -1,5 +1,5 @@
1
1
  import type * as activities from "../activities.js";
2
- type WorkflowControlActivities = Pick<typeof activities, "enqueueGoalRetryWake" | "expireSessionHumanInput" | "expireSessionInteractionIntervention" | "failSessionAttempt" | "getCodexCapacityWait" | "markSessionIdle" | "peekSessionWork" | "persistSessionAttemptQuiescence" | "reconcileSessionAttemptQuiescence" | "reconcileCodexCapacityWait" | "recoverDispatch" | "recoverEscapedMcpTimeout" | "settleSessionInterruptions">;
2
+ type WorkflowControlActivities = Pick<typeof activities, "enqueueGoalRetryWake" | "expireSessionHumanInput" | "expireSessionInteractionIntervention" | "failSessionAttempt" | "getCodexCapacityWait" | "markSessionIdle" | "peekSessionWork" | "persistSessionAttemptQuiescence" | "reconcileSessionAttemptQuiescence" | "reconcileCodexCapacityWait" | "recoverDispatch" | "recoverEscapedMcpTimeout" | "settleSessionInterruptions" | "settleSessionInputWait">;
3
3
  /**
4
4
  * Session/schedule workflow control activities are bounded, idempotent database
5
5
  * and provider-metadata operations. They must not inherit the agent turn's
@@ -16,6 +16,11 @@ export declare const activity: import("@temporalio/workflow").ActivityInterfaceF
16
16
  * is an independent workflow and will re-evaluate current state. */
17
17
  export declare const scheduledTaskActivity: import("@temporalio/workflow").ActivityInterfaceFor<Pick<typeof activities, "dispatchScheduledTaskRun">>;
18
18
  export declare const automationActivity: import("@temporalio/workflow").ActivityInterfaceFor<Pick<typeof activities, "dispatchAutomationRun">>;
19
+ /** Dispatch has a bounded retry window, but an accepted automation event must
20
+ * not remain durably `dispatching` after that window closes. This compensating
21
+ * database write is idempotent and retries without a cap until the run reaches
22
+ * a terminal state (or is observed as already dispatched). */
23
+ export declare const automationFailureActivity: import("@temporalio/workflow").ActivityInterfaceFor<Pick<typeof activities, "settleAutomationRunFailure">>;
19
24
  /** Goal continuation evaluates a durable Postgres obligation at an idle
20
25
  * boundary. A transient failure gets a short retry window, then records an
21
26
  * explicit delayed outbox wake instead of relying on an unrelated mutation or
@@ -3,4 +3,9 @@ export type AutomationRunWorkflowInput = {
3
3
  workspaceId: string;
4
4
  runId: string;
5
5
  };
6
+ export type AutomationRunWorkflowActivities = {
7
+ dispatchAutomationRun: (input: AutomationRunWorkflowInput) => Promise<unknown>;
8
+ settleAutomationRunFailure: (input: AutomationRunWorkflowInput) => Promise<void>;
9
+ };
10
+ export declare function runAutomationRunWorkflow(input: AutomationRunWorkflowInput, activities: AutomationRunWorkflowActivities): Promise<void>;
6
11
  export declare function automationRunWorkflow(input: AutomationRunWorkflowInput): Promise<void>;
@@ -21,6 +21,9 @@ export declare function continuationHoldMs(result: {
21
21
  * signal-version and interruption paths in `sessionWorkflow`.
22
22
  */
23
23
  export declare function deferredResultMayContinue(entryWakeups: number, currentWakeups: number): boolean;
24
+ /** A typed activity cancellation is recoverable unless its exact-attempt
25
+ * redispatch budget was atomically exhausted. */
26
+ export declare function cancelledAttemptRecoveryMayContinue(action: activities.RecoverDispatchResult["action"]): boolean;
24
27
  /**
25
28
  * Bound repeated failures that happen before an attempt row exists. The
26
29
  * activity mirrors this deterministic delay into the durable wake outbox, so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/worker-bundle",
3
- "version": "0.23.4",
3
+ "version": "0.26.0-canary.0",
4
4
  "description": "OpenGeni worker entry and reusable embedded lifecycle, shipped with a release-coherent pre-bundled Temporal workflow artifact.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -54,22 +54,22 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@llamaindex/liteparse": "2.14.2",
57
- "@opengeni/agent-proto": "^0.5.1",
58
- "@opengeni/capabilities": "^0.3.1",
59
- "@opengeni/codemode": "^0.4.22",
60
- "@opengeni/codex": "^0.2.20",
61
- "@opengeni/config": "^0.22.5",
62
- "@opengeni/contracts": "^2.9.2",
63
- "@opengeni/core": "^2.6.4",
64
- "@opengeni/db": "^3.7.4",
65
- "@opengeni/documents": "^0.8.14",
66
- "@opengeni/events": "^0.4.12",
67
- "@opengeni/github": "^0.6.7",
68
- "@opengeni/network": "^0.2.3",
69
- "@opengeni/observability": "^0.8.14",
70
- "@opengeni/runtime": "^2.0.1",
71
- "@opengeni/storage": "^0.2.115",
72
- "@opengeni/xai-subscription": "^0.1.2",
57
+ "@opengeni/agent-proto": "^0.5.1-canary.9",
58
+ "@opengeni/capabilities": "^0.3.2-canary.0",
59
+ "@opengeni/codemode": "^0.4.27-canary.0",
60
+ "@opengeni/codex": "^0.2.21-canary.0",
61
+ "@opengeni/config": "^1.0.0-canary.0",
62
+ "@opengeni/contracts": "^2.13.0-canary.0",
63
+ "@opengeni/core": "^2.7.5-canary.0",
64
+ "@opengeni/db": "^4.0.0-canary.0",
65
+ "@opengeni/documents": "^0.8.19-canary.0",
66
+ "@opengeni/events": "^0.4.17-canary.0",
67
+ "@opengeni/github": "^0.7.3-canary.0",
68
+ "@opengeni/network": "^0.3.0-canary.0",
69
+ "@opengeni/observability": "^0.8.19-canary.0",
70
+ "@opengeni/runtime": "^2.3.0-canary.0",
71
+ "@opengeni/storage": "^0.2.120-canary.0",
72
+ "@opengeni/xai-subscription": "^0.1.3-canary.0",
73
73
  "@temporalio/activity": "^1.17.0",
74
74
  "@temporalio/client": "^1.17.0",
75
75
  "@temporalio/worker": "^1.17.0",
@@ -1,4 +1,5 @@
1
1
  import { configuredStaticUsageLimits, type Settings } from "@opengeni/config";
2
+ import { modelFundingForAdmission } from "@opengeni/core";
2
3
  import { getBillingBalance, isCodexBilledTurn, sumUsageQuantity } from "@opengeni/db";
3
4
  import type { ControlActivityServices } from "./types";
4
5
 
@@ -17,12 +18,17 @@ export async function agentRunAdmissionDenial(
17
18
  requestedAgentRuns: number;
18
19
  },
19
20
  ): Promise<AgentRunAdmissionDenial | null> {
20
- const externallyBilled = await isCodexBilledTurn({
21
+ const codexBilled = await isCodexBilledTurn({
21
22
  db: services.db,
22
23
  settings: services.settings,
23
24
  workspaceId: input.workspaceId,
24
25
  model: input.model,
25
26
  });
27
+ const externallyBilled = modelFundingForAdmission(
28
+ services.settings,
29
+ input.model,
30
+ codexBilled,
31
+ ).fundedWithoutCredits;
26
32
  if (
27
33
  !externallyBilled &&
28
34
  (services.settings.billingMode === "stripe" || services.settings.usageLimitsMode === "managed")
@@ -12,6 +12,7 @@ import {
12
12
  type SessionTurn,
13
13
  type ToolAuthNeededPayload,
14
14
  type TurnExecutionPolicyV1,
15
+ type XaiProviderAccountAuthoritySnapshotV1,
15
16
  } from "@opengeni/contracts";
16
17
  import { createHash } from "node:crypto";
17
18
  import { startOfUtcMonth } from "./model-usage";
@@ -38,6 +39,22 @@ export function credentialSubjectIdForTurnInitiator(
38
39
  return directPersonalConnectionSubjectId(turn);
39
40
  }
40
41
 
42
+ export function xaiCatalogReadinessAuthority(
43
+ turn: {
44
+ initiatingHumanSubjectId: string | null;
45
+ xaiProviderAccountAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;
46
+ },
47
+ directCredentialSubjectId: string | undefined,
48
+ ): {
49
+ subjectId: string;
50
+ authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;
51
+ } | null {
52
+ const subjectId = turn.initiatingHumanSubjectId ?? directCredentialSubjectId;
53
+ return subjectId
54
+ ? { subjectId, authoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot }
55
+ : null;
56
+ }
57
+
41
58
  /**
42
59
  * Direct authenticated-human work is the persisted human source with subject
43
60
  * authority and no inherited agent or legacy provenance. Use this complete
@@ -82,13 +99,34 @@ export function shouldPublishToolAuthNeededForTurn(
82
99
  return typeof text === "string" && /\bslack\b/i.test(text);
83
100
  }
84
101
 
102
+ /**
103
+ * Keep host-owned auth events inert in browsers from before authoritySource
104
+ * existed. Those bundles treat unsupported_auth as unavailable and therefore
105
+ * do not invoke native OAuth; upgraded clients read hostReason and the
106
+ * host-minted authorizationUrl.
107
+ */
108
+ export function rollingSafeToolAuthNeededPayload(
109
+ payload: ToolAuthNeededPayload,
110
+ ): ToolAuthNeededPayload {
111
+ if (payload.authoritySource !== "host") {
112
+ return payload;
113
+ }
114
+ return {
115
+ ...payload,
116
+ reason: "unsupported_auth",
117
+ hostReason: payload.hostReason ?? payload.reason,
118
+ };
119
+ }
120
+
85
121
  export function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {
86
122
  externallyBilled: boolean;
123
+ countsTowardTokenCap: boolean;
87
124
  codexSubscription: boolean;
88
125
  xaiSubscription: boolean;
89
126
  } {
90
127
  return {
91
128
  externallyBilled: policy.billing.metering === "external",
129
+ countsTowardTokenCap: policy.billing.upstreamPayer === "deployment",
92
130
  codexSubscription:
93
131
  policy.providerId === "codex-subscription" &&
94
132
  policy.credentialSource.kind === "connected_subscription" &&
@@ -222,10 +260,13 @@ export async function ensureRunAllowed(
222
260
  workspaceId: string,
223
261
  isExternallyBilledTurn: boolean,
224
262
  entitlements?: ActivityServices["entitlements"],
263
+ chargesOpenGeniCredits = !isExternallyBilledTurn,
264
+ countsTowardTokenCap = !isExternallyBilledTurn,
225
265
  ): Promise<void> {
226
- // Externally billed turns are paid outside OpenGeni: skip the credit-balance
227
- // gate and monthly token cap. The agent-run COUNT cap below is a
228
- // volume/fairness quota (not a credit/cost gate) and is intentionally kept.
266
+ // Upstream settlement and workspace-facing cost are independent. External
267
+ // metering skips the token cap; free/subscription/workspace cost skips the
268
+ // OpenGeni credit gate. The agent-run COUNT cap below is a volume/fairness
269
+ // quota and is intentionally kept for every funding path.
229
270
  //
230
271
  // §7.5 P3 — host-entitlements DELEGATION (the worker half of the same seam the
231
272
  // API edge exposes). For a non-codex turn, when the host binds `entitlements`, its
@@ -239,7 +280,7 @@ export async function ensureRunAllowed(
239
280
  // idempotency-keyed writer at recordModelUsageAndDebitCredits), so a PULL host meter
240
281
  // is consulted without ever double-charging.
241
282
  if (
242
- !isExternallyBilledTurn &&
283
+ chargesOpenGeniCredits &&
243
284
  entitlements &&
244
285
  (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
245
286
  ) {
@@ -253,7 +294,7 @@ export async function ensureRunAllowed(
253
294
  throw new Error(decision.reason || "insufficient OpenGeni credits");
254
295
  }
255
296
  } else if (
256
- !isExternallyBilledTurn &&
297
+ chargesOpenGeniCredits &&
257
298
  (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
258
299
  ) {
259
300
  const balance = await getBillingBalance(db, accountId);
@@ -278,7 +319,7 @@ export async function ensureRunAllowed(
278
319
  );
279
320
  }
280
321
  }
281
- if (!isExternallyBilledTurn && limits.maxMonthlyTokensPerWorkspace) {
322
+ if (countsTowardTokenCap && limits.maxMonthlyTokensPerWorkspace) {
282
323
  const used = await sumUsageQuantity(db, {
283
324
  workspaceId,
284
325
  eventType: "model.tokens",
@@ -6,9 +6,6 @@ import {
6
6
  setXaiSessionAccountPin,
7
7
  getWorkspaceVideoGenerationPolicy,
8
8
  loadWorkspaceVercelAiGatewayCredentialLease,
9
- beginConnectorActionExecution,
10
- completeConnectorActionExecution,
11
- prepareConnectorActionApproval,
12
9
  } from "@opengeni/db";
13
10
  import {
14
11
  type AttemptConnectorActionBinding,
@@ -128,15 +125,8 @@ export type BuildTurnAgentDeps = {
128
125
  sandboxCodemodeToken: string | undefined;
129
126
  fileResourceDownloads: SandboxFileDownload[];
130
127
  attemptConnectorActionBindings: readonly AttemptConnectorActionBinding[];
131
- connectorActionIdentity: {
132
- accountId: string;
133
- workspaceId: string;
134
- sessionId: string;
135
- turnId: string;
136
- attemptId: string;
137
- executionGeneration: number;
138
- initiator: Pick<ClaimTurnOk["turn"]["initiator"], "kind" | "subjectId">;
139
- };
128
+ connectorActionPolicy: ConnectorActionPolicyHooks;
129
+ trigger: ClaimTurnOk["trigger"];
140
130
  preparationIndependentToolNames: readonly string[];
141
131
  videoGenerationAcceptancesByCallId: Map<string, { operationId: string; requestDigest: string }>;
142
132
  activeSandboxBackend: Settings["sandboxBackend"] | undefined;
@@ -194,7 +184,8 @@ export async function buildTurnAgent(deps: BuildTurnAgentDeps) {
194
184
  sandboxCodemodeToken,
195
185
  fileResourceDownloads,
196
186
  attemptConnectorActionBindings,
197
- connectorActionIdentity,
187
+ connectorActionPolicy,
188
+ trigger,
198
189
  preparationIndependentToolNames,
199
190
  videoGenerationAcceptancesByCallId,
200
191
  activeSandboxBackend,
@@ -567,19 +558,7 @@ export async function buildTurnAgent(deps: BuildTurnAgentDeps) {
567
558
  turnExecutionPolicy.providerId,
568
559
  turnExecutionPolicy.latencyMode,
569
560
  );
570
- const connectorActionPolicy: ConnectorActionPolicyHooks = {
571
- prepare: async (call) =>
572
- await prepareConnectorActionApproval(db, connectorActionIdentity, call),
573
- begin: async (call) => await beginConnectorActionExecution(db, connectorActionIdentity, call),
574
- complete: async ({ requestId, outcome }) =>
575
- await completeConnectorActionExecution(db, {
576
- accountId: input.accountId,
577
- workspaceId: input.workspaceId,
578
- requestId,
579
- attemptId: input.attemptId,
580
- outcome,
581
- }),
582
- };
561
+ const approvedToolCallId = approvedConnectorActionCallId(trigger);
583
562
  const runtimeSkillActivations = [
584
563
  ...installedSkillRuntime.activations,
585
564
  ...packRuntime.skillActivations,
@@ -669,6 +648,7 @@ export async function buildTurnAgent(deps: BuildTurnAgentDeps) {
669
648
  resolvedMcpConnectionIds: preparedTools.resolvedMcpConnectionIds,
670
649
  connectorActionPolicy,
671
650
  attemptConnectorActionBindings,
651
+ ...(approvedToolCallId ? { approvedToolCallId } : {}),
672
652
  // LIVE by-reference connector namespaces (fills during this turn's
673
653
  // codex_apps tools/list): the codex tool_search description reads it per
674
654
  // model call so the model sees the account's real connected sources.
@@ -796,4 +776,18 @@ export async function buildTurnAgent(deps: BuildTurnAgentDeps) {
796
776
  };
797
777
  }
798
778
 
779
+ function approvedConnectorActionCallId(trigger: ClaimTurnOk["trigger"]): string | null {
780
+ if (trigger.type !== "user.approvalDecision") {
781
+ return null;
782
+ }
783
+
784
+ const payload = trigger.payload as {
785
+ approvalId?: unknown;
786
+ decision?: unknown;
787
+ };
788
+ return payload.decision === "approve" && typeof payload.approvalId === "string"
789
+ ? payload.approvalId
790
+ : null;
791
+ }
792
+
799
793
  export type BuildTurnAgentOk = Awaited<ReturnType<typeof buildTurnAgent>>;
@@ -24,11 +24,14 @@ import {
24
24
  settingsWithCodexCredential,
25
25
  settingsWithEnabledCapabilityMcpServers,
26
26
  settingsWithWorkspaceGatewayCredential,
27
+ settingsWithWorkspaceOpenRouterCredential,
28
+ settingsWithOrganizationProviderCredentials,
27
29
  withXaiSubscriptionProvider,
28
30
  } from "../capabilities";
29
31
  import { validateIncidentTelemetrySystemUpdateAuthority } from "../incident-telemetry-authority";
30
32
  import {
31
33
  assertSessionAllowsProductModel,
34
+ resolveCatalogSettings,
32
35
  resolveCodexAppsCredentialIdForRun,
33
36
  } from "@opengeni/core";
34
37
  import { TurnAttemptFencedError } from "../turn-attempt-fenced";
@@ -72,6 +75,7 @@ import type {
72
75
  export type ClaimTurnDeps = {
73
76
  input: RunAgentTurnInput;
74
77
  settings: Settings;
78
+ catalogSourceSettings: Settings;
75
79
  db: ActivityServices["db"];
76
80
  bus: ActivityServices["bus"];
77
81
  runtime: ActivityServices["runtime"];
@@ -129,12 +133,30 @@ export function turnAttemptProducerId(
129
133
  return `${input.workflowId}:${turnId}:${input.attemptId}`;
130
134
  }
131
135
 
136
+ /**
137
+ * Durable Codex lease holder for one accepted turn attempt. Temporal activity
138
+ * ids may repeat after workflow restart or continue-as-new, so they are not
139
+ * owner identity. The attempt id is generated by the workflow for each
140
+ * redispatch and remains stable when the same activity input is retried.
141
+ */
142
+ export function codexCredentialLeaseHolderId(
143
+ input: Pick<RunAgentTurnInput, "workflowId" | "attemptId">,
144
+ turnId: string,
145
+ ): string {
146
+ const parts = [input.workflowId, turnId, input.attemptId];
147
+ if (parts.some((part) => part.trim().length === 0)) {
148
+ throw new Error("Codex credential lease holder requires a complete turn attempt identity");
149
+ }
150
+ return `codex-turn:${parts.map((part) => encodeURIComponent(part)).join(":")}`;
151
+ }
152
+
132
153
  export type ClaimTurnOutcome = { exit: RunAgentTurnResult } | { ok: ClaimTurnOk };
133
154
 
134
155
  export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOutcome> {
135
156
  const {
136
157
  input,
137
158
  settings,
159
+ catalogSourceSettings,
138
160
  db,
139
161
  bus,
140
162
  runtime,
@@ -156,12 +178,15 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
156
178
  acknowledgeLostAttemptOwnership,
157
179
  } = deps;
158
180
 
181
+ const deploymentCatalogSettings = (await resolveCatalogSettings(db, catalogSourceSettings))
182
+ .settings;
183
+
159
184
  const validatePendingSystemUpdateAuthority: NonNullable<
160
185
  ClaimSessionWorkForAttemptInput["validatePendingSystemUpdateAuthority"]
161
186
  > = async (tx, update) =>
162
187
  await validateIncidentTelemetrySystemUpdateAuthority({
163
188
  db: tx,
164
- settings,
189
+ settings: deploymentCatalogSettings,
165
190
  workspaceId: input.workspaceId,
166
191
  sessionId: input.sessionId,
167
192
  update,
@@ -181,12 +206,19 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
181
206
  }
182
207
  const turn = claim.turn;
183
208
  attempt.turnId = turn.id;
209
+ attempt.dispatchId = dispatchId;
184
210
  attempt.executionGeneration = turn.executionGeneration;
185
211
  attempt.providerRecoveryCount = providerRecoveryCountFromMetadata(turn.metadata);
186
212
  attempt.triggerEventId = turn.triggerEventId;
213
+ // The durable attempt UUID is stable for a Temporal retry of this activity
214
+ // input and freshly generated for worker-death redispatch/continue-as-new.
215
+ // Keep dispatchId separate: it remains the Temporal activity identity used
216
+ // by attempt fencing, audit, and observability.
217
+ leases.codex.holderId = codexCredentialLeaseHolderId(input, turn.id);
187
218
  attempt.redispatchesAtDispatch = Number(
188
219
  (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ?? 0,
189
220
  );
221
+ const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);
190
222
  // Establish durable attempt ownership before any later read can fail.
191
223
  // Therefore every failure with no turnId came from the one atomic claim
192
224
  // transaction and can be classified without conflating ordinary runtime
@@ -198,7 +230,7 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
198
230
  const mcpSettings = await settingsWithEnabledCapabilityMcpServers(
199
231
  db,
200
232
  input.workspaceId,
201
- settings,
233
+ deploymentCatalogSettings,
202
234
  {
203
235
  ...(credentialSubjectId
204
236
  ? { subjectId: credentialSubjectId }
@@ -227,16 +259,31 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
227
259
  const xaiSettings = codexSettings.supergrokSubscriptionEnabled
228
260
  ? withXaiSubscriptionProvider(codexSettings)
229
261
  : codexSettings;
230
- const capabilitySettings = await settingsWithWorkspaceGatewayCredential(
262
+ const gatewaySettings = await settingsWithWorkspaceGatewayCredential(
231
263
  db,
264
+ input.accountId,
232
265
  input.workspaceId,
233
266
  xaiSettings,
267
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model,
268
+ );
269
+ const workspaceProviderSettings = await settingsWithWorkspaceOpenRouterCredential(
270
+ db,
271
+ input.accountId,
272
+ input.workspaceId,
273
+ gatewaySettings,
274
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model,
275
+ );
276
+ const capabilitySettings = await settingsWithOrganizationProviderCredentials(
277
+ db,
278
+ input.accountId,
279
+ input.workspaceId,
280
+ workspaceProviderSettings,
281
+ claimedPolicy.kind === "valid" ? claimedPolicy.policy.productModelId : turn.model,
234
282
  );
235
283
  const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled
236
284
  ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId)
237
285
  : null;
238
286
  runtime.configure(capabilitySettings);
239
- const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);
240
287
  const policyForAbsent =
241
288
  claimedPolicy.kind === "valid"
242
289
  ? claimedPolicy.policy
@@ -266,6 +313,8 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
266
313
  assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);
267
314
  const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);
268
315
  billingState.isExternallyBilledTurn = billingIdentity.externallyBilled;
316
+ billingState.chargesOpenGeniCredits = verifiedExecutionPolicy.model.cost === "credits";
317
+ billingState.countsTowardTokenCap = billingIdentity.countsTowardTokenCap;
269
318
  billingState.isCodexTurn = billingIdentity.codexSubscription;
270
319
  billingState.isXaiTurn = billingIdentity.xaiSubscription;
271
320
  const trigger = await getSessionEvent(db, input.workspaceId, attempt.triggerEventId);
@@ -305,12 +354,14 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
305
354
  // the local credit read). Unset port → today's local-ledger path.
306
355
  await waitForTurnOperation(
307
356
  ensureRunAllowed(
308
- settings,
357
+ capabilitySettings,
309
358
  db,
310
359
  input.accountId,
311
360
  input.workspaceId,
312
361
  billingState.isExternallyBilledTurn,
313
362
  entitlements,
363
+ billingState.chargesOpenGeniCredits,
364
+ billingState.countsTowardTokenCap,
314
365
  ),
315
366
  cancellationSignal,
316
367
  undefined,
@@ -347,7 +398,6 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
347
398
  const producerId = turnAttemptProducerId(input, attempt.turnId);
348
399
  // Fold the same durable attempt identity into positional usage source keys.
349
400
  // A retry dedupes; a re-dispatch cannot collide with the prior attempt.
350
- leases.codex.holderId = dispatchId;
351
401
  const modelUsageDispatchId = input.attemptId;
352
402
  const claimedModelUsageSourceKeys = new Set<string>();
353
403
  const emittedModelUsageSourceKeys = new Set<string>();
@@ -444,6 +494,9 @@ export async function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOu
444
494
  turnStatus: inputSettlement.turnStatus,
445
495
  sessionStatus: inputSettlement.sessionStatus,
446
496
  activeTurnId: inputSettlement.activeTurnId,
497
+ ...(inputSettlement.suppressGoalContinuation !== undefined
498
+ ? { suppressGoalContinuation: inputSettlement.suppressGoalContinuation }
499
+ : {}),
447
500
  events: inputs,
448
501
  ...(runState ? { runState } : {}),
449
502
  ...(compactionRequestFailure ? { compactionRequestFailure } : {}),