@opengeni/worker-bundle 0.20.1 → 0.22.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 (189) hide show
  1. package/dist/activities/agent-turn/admission.d.ts +52 -0
  2. package/dist/activities/agent-turn/agent-build.d.ts +89 -0
  3. package/dist/activities/agent-turn/claim.d.ts +67 -0
  4. package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
  5. package/dist/activities/agent-turn/codex.d.ts +32 -0
  6. package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
  7. package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
  8. package/dist/activities/agent-turn/errors.d.ts +253 -0
  9. package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
  10. package/dist/activities/agent-turn/file-resources.d.ts +37 -0
  11. package/dist/activities/agent-turn/finalization.d.ts +42 -0
  12. package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
  13. package/dist/activities/agent-turn/governance-model.d.ts +66 -0
  14. package/dist/activities/agent-turn/history-sink.d.ts +52 -0
  15. package/dist/activities/agent-turn/history.d.ts +63 -0
  16. package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
  17. package/dist/activities/agent-turn/model-usage.d.ts +218 -0
  18. package/dist/activities/agent-turn/quiescence.d.ts +135 -0
  19. package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
  20. package/dist/activities/agent-turn/run.d.ts +3 -0
  21. package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
  22. package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
  23. package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
  24. package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
  25. package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
  26. package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
  27. package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
  28. package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
  29. package/dist/activities/agent-turn/turn-context.d.ts +144 -0
  30. package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
  31. package/dist/activities/agent-turn.d.ts +12 -954
  32. package/dist/activities/automations.d.ts +16 -0
  33. package/dist/activities/common.d.ts +1 -1
  34. package/dist/activities/connector-attachments.d.ts +13 -0
  35. package/dist/activities/documents.d.ts +1 -0
  36. package/dist/activities/environment.d.ts +26 -15
  37. package/dist/activities/generated-images.d.ts +1 -1
  38. package/dist/activities/git-credential-renewal.d.ts +3 -1
  39. package/dist/activities/goals.d.ts +4 -1
  40. package/dist/activities/google-drive-provider.d.ts +29 -0
  41. package/dist/activities/google-drive-publication.d.ts +66 -0
  42. package/dist/activities/image-generation-references.d.ts +2 -0
  43. package/dist/activities/incident-telemetry-authority.d.ts +52 -0
  44. package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
  45. package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
  46. package/dist/activities/knowledge-source-sync.d.ts +33 -1
  47. package/dist/activities/mcp-credentials.d.ts +9 -3
  48. package/dist/activities/open-suffix-resume.d.ts +77 -0
  49. package/dist/activities/packs.d.ts +3 -11
  50. package/dist/activities/parent-wake.d.ts +19 -0
  51. package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
  52. package/dist/activities/retained-screenshots.d.ts +1 -1
  53. package/dist/activities/rig-verification.d.ts +1 -1
  54. package/dist/activities/run-input.d.ts +16 -7
  55. package/dist/activities/sandbox-images.d.ts +1 -14
  56. package/dist/activities/sandbox-lease.d.ts +21 -3
  57. package/dist/activities/scheduled-tasks.d.ts +47 -0
  58. package/dist/activities/types.d.ts +23 -2
  59. package/dist/activities/video-media-validation.d.ts +1 -1
  60. package/dist/activities/video-output-retention.d.ts +1 -2
  61. package/dist/activities/xai-auth.d.ts +3 -0
  62. package/dist/{activities-control-SMKF2OBE.js → activities-control-DKG22ONJ.js} +2946 -549
  63. package/dist/activities-control-DKG22ONJ.js.map +1 -0
  64. package/dist/activities-control.d.ts +6 -2
  65. package/dist/activities-turn-4IMC3MAA.js +21326 -0
  66. package/dist/activities-turn-4IMC3MAA.js.map +1 -0
  67. package/dist/activities.d.ts +7 -3
  68. package/dist/artifact-materializer-entry.js +41 -22
  69. package/dist/artifact-materializer-entry.js.map +1 -1
  70. package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
  71. package/dist/chunk-CE7TPKBS.js.map +1 -0
  72. package/dist/chunk-CNYGVRKF.js +4698 -0
  73. package/dist/chunk-CNYGVRKF.js.map +1 -0
  74. package/dist/connection-provider-use.d.ts +18 -0
  75. package/dist/editable-artifact-materializer.d.ts +4 -3
  76. package/dist/github-rest-mcp.d.ts +26 -0
  77. package/dist/index.d.ts +10 -2
  78. package/dist/index.js +58 -14
  79. package/dist/index.js.map +1 -1
  80. package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
  81. package/dist/model-context-contributions.d.ts +8 -4
  82. package/dist/observability-metrics.d.ts +63 -4
  83. package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
  84. package/dist/personal-github-git-credentials.d.ts +9 -0
  85. package/dist/pr-review-credentials.d.ts +6 -0
  86. package/dist/sandbox-archive-storage.d.ts +45 -0
  87. package/dist/sandbox-resume.d.ts +65 -6
  88. package/dist/sandbox-routing.d.ts +38 -2
  89. package/dist/scheduled-alert-occurrence.d.ts +33 -0
  90. package/dist/workflow-bundle.js +87 -28
  91. package/dist/workflows/activities.d.ts +1 -0
  92. package/dist/workflows/automations.d.ts +6 -0
  93. package/dist/workflows/document-index.d.ts +1 -0
  94. package/dist/workflows.d.ts +1 -0
  95. package/package.json +17 -17
  96. package/src/activities/agent-turn/admission.ts +292 -0
  97. package/src/activities/agent-turn/agent-build.ts +802 -0
  98. package/src/activities/agent-turn/claim.ts +590 -0
  99. package/src/activities/agent-turn/codex-capacity.ts +720 -0
  100. package/src/activities/agent-turn/codex.ts +94 -0
  101. package/src/activities/agent-turn/compaction-prep.ts +722 -0
  102. package/src/activities/agent-turn/credential-leases.ts +240 -0
  103. package/src/activities/agent-turn/errors.ts +1068 -0
  104. package/src/activities/agent-turn/failure-settlement.ts +1436 -0
  105. package/src/activities/agent-turn/file-resources.ts +227 -0
  106. package/src/activities/agent-turn/finalization.ts +754 -0
  107. package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
  108. package/src/activities/agent-turn/governance-model.ts +465 -0
  109. package/src/activities/agent-turn/history-sink.ts +139 -0
  110. package/src/activities/agent-turn/history.ts +200 -0
  111. package/src/activities/agent-turn/media-artifacts.ts +359 -0
  112. package/src/activities/agent-turn/model-usage.ts +823 -0
  113. package/src/activities/agent-turn/quiescence.ts +353 -0
  114. package/src/activities/agent-turn/run-credentials.ts +761 -0
  115. package/src/activities/agent-turn/run.ts +1530 -0
  116. package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
  117. package/src/activities/agent-turn/sandbox-provision.ts +569 -0
  118. package/src/activities/agent-turn/sandbox-route.ts +358 -0
  119. package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
  120. package/src/activities/agent-turn/stream-attempt.ts +1670 -0
  121. package/src/activities/agent-turn/tool-environment.ts +729 -0
  122. package/src/activities/agent-turn/tool-policy.ts +216 -0
  123. package/src/activities/agent-turn/tool-result-spill.ts +265 -0
  124. package/src/activities/agent-turn/turn-context.ts +281 -0
  125. package/src/activities/agent-turn/xai-capacity.ts +229 -0
  126. package/src/activities/agent-turn.ts +12 -12575
  127. package/src/activities/api-integrations.ts +3 -0
  128. package/src/activities/automations.ts +214 -0
  129. package/src/activities/codemode-dispatcher.ts +12 -1
  130. package/src/activities/common.ts +1 -5
  131. package/src/activities/connector-attachments.ts +168 -0
  132. package/src/activities/context-compaction.ts +18 -0
  133. package/src/activities/documents.ts +6 -4
  134. package/src/activities/environment.ts +151 -55
  135. package/src/activities/generated-images.ts +26 -11
  136. package/src/activities/git-credential-renewal.ts +13 -3
  137. package/src/activities/goals.ts +85 -19
  138. package/src/activities/google-drive-provider.ts +178 -0
  139. package/src/activities/google-drive-publication.ts +938 -0
  140. package/src/activities/image-generation-references.ts +11 -2
  141. package/src/activities/incident-telemetry-authority.ts +327 -0
  142. package/src/activities/incident-telemetry-preflight.ts +317 -0
  143. package/src/activities/knowledge-source-sync-driver.ts +23 -0
  144. package/src/activities/knowledge-source-sync.ts +556 -40
  145. package/src/activities/mcp-credentials.ts +191 -17
  146. package/src/activities/open-suffix-resume.ts +422 -0
  147. package/src/activities/packs.ts +12 -60
  148. package/src/activities/parent-wake.ts +64 -14
  149. package/src/activities/retained-screenshot-reaper.ts +6 -3
  150. package/src/activities/retained-screenshots.ts +15 -47
  151. package/src/activities/rig-verification.ts +1 -1
  152. package/src/activities/run-input.ts +128 -136
  153. package/src/activities/sandbox-images.ts +7 -166
  154. package/src/activities/sandbox-lease.ts +406 -15
  155. package/src/activities/scheduled-tasks.ts +2103 -411
  156. package/src/activities/session-state.ts +10 -2
  157. package/src/activities/types.ts +32 -2
  158. package/src/activities/video-media-validation.ts +3 -3
  159. package/src/activities/video-output-retention.ts +2 -57
  160. package/src/activities/xai-auth.ts +8 -0
  161. package/src/activities-control.ts +2 -0
  162. package/src/activities.ts +3 -0
  163. package/src/activity-services.ts +13 -4
  164. package/src/connection-provider-use.ts +36 -0
  165. package/src/editable-artifact-materializer-subprocess.ts +25 -14
  166. package/src/editable-artifact-materializer.ts +29 -18
  167. package/src/github-rest-mcp.ts +713 -0
  168. package/src/http.ts +16 -6
  169. package/src/index.ts +40 -5
  170. package/src/knowledge-source-sync-activity-policy.ts +2 -0
  171. package/src/model-context-contributions.ts +33 -10
  172. package/src/observability-metrics.ts +357 -0
  173. package/src/opensandbox-kubernetes-inventory.ts +292 -0
  174. package/src/personal-github-git-credentials.ts +331 -0
  175. package/src/pr-review-credentials.ts +163 -0
  176. package/src/sandbox-archive-storage.ts +159 -0
  177. package/src/sandbox-resume.ts +449 -63
  178. package/src/sandbox-routing.ts +314 -16
  179. package/src/scheduled-alert-occurrence.ts +176 -0
  180. package/src/workflows/activities.ts +18 -2
  181. package/src/workflows/automations.ts +11 -0
  182. package/src/workflows/session.ts +13 -3
  183. package/src/workflows.ts +1 -0
  184. package/dist/activities-control-SMKF2OBE.js.map +0 -1
  185. package/dist/activities-turn-IDS3WEHA.js +0 -16532
  186. package/dist/activities-turn-IDS3WEHA.js.map +0 -1
  187. package/dist/chunk-N5TJIFCE.js.map +0 -1
  188. package/dist/chunk-P6Z2SLAA.js +0 -3092
  189. package/dist/chunk-P6Z2SLAA.js.map +0 -1
@@ -15,6 +15,7 @@ export declare const activity: import("@temporalio/workflow").ActivityInterfaceF
15
15
  * not leave a Temporal activity retrying forever; the next scheduled occurrence
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
+ export declare const automationActivity: import("@temporalio/workflow").ActivityInterfaceFor<Pick<typeof activities, "dispatchAutomationRun">>;
18
19
  /** Goal continuation evaluates a durable Postgres obligation at an idle
19
20
  * boundary. A transient failure gets a short retry window, then records an
20
21
  * explicit delayed outbox wake instead of relying on an unrelated mutation or
@@ -0,0 +1,6 @@
1
+ export type AutomationRunWorkflowInput = {
2
+ accountId: string;
3
+ workspaceId: string;
4
+ runId: string;
5
+ };
6
+ export declare function automationRunWorkflow(input: AutomationRunWorkflowInput): Promise<void>;
@@ -22,6 +22,7 @@ export declare function documentIndexWorkflow(input: DocumentIndexWorkflowInput)
22
22
  authorityKind: "organization" | "personal" | "workspace";
23
23
  authorityWorkspaceId: string | null;
24
24
  authoritySubjectId: string | null;
25
+ authorityId?: string | null | undefined;
25
26
  visibility: "private" | "workspace";
26
27
  createdBy: string | null;
27
28
  agentAccess: boolean;
@@ -1,6 +1,7 @@
1
1
  export { documentIndexWorkflow, type DocumentIndexWorkflowInput } from "./workflows/document-index.js";
2
2
  export { approvalDecision, codexCapacityChanged, sessionControl, sessionAttemptQuiesced, queueChanged, sessionWorkflow, userMessage, type SessionWorkflowInput, } from "./workflows/session.js";
3
3
  export { scheduledTaskFireWorkflow, type ScheduledTaskFireWorkflowInput, } from "./workflows/scheduled-tasks.js";
4
+ export { automationRunWorkflow, type AutomationRunWorkflowInput } from "./workflows/automations.js";
4
5
  export { knowledgeSourceSyncWake, knowledgeSourceSyncWorkflow, knowledgeSourceSyncWorkflowId, type KnowledgeSourceSyncWorkflowInput, } from "./workflows/knowledge-source-sync.js";
5
6
  export { sandboxDrainWorkflow, sandboxReaperMaintenanceWorkflow, sandboxReaperWorkflow, sandboxReaperWorkflowV2, } from "./workflows/sandbox-reaper.js";
6
7
  export { fileUploadReaperWorkflow } from "./workflows/file-upload-reaper.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/worker-bundle",
3
- "version": "0.20.1",
3
+ "version": "0.22.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": "^1.5.3",
57
- "@opengeni/agent-proto": "^0.5.0",
58
- "@opengeni/capabilities": "^0.2.0",
59
- "@opengeni/codemode": "^0.4.2",
60
- "@opengeni/codex": "^0.2.17",
61
- "@opengeni/config": "^0.16.2",
62
- "@opengeni/contracts": "^0.50.0",
63
- "@opengeni/core": "^0.28.1",
64
- "@opengeni/db": "^0.36.1",
65
- "@opengeni/documents": "^0.5.39",
66
- "@opengeni/events": "^0.3.110",
67
- "@opengeni/github": "^0.4.57",
68
- "@opengeni/network": "^0.2.2",
69
- "@opengeni/observability": "^0.7.5",
70
- "@opengeni/runtime": "^0.23.1",
71
- "@opengeni/storage": "^0.2.94",
72
- "@opengeni/xai-subscription": "^0.1.0",
57
+ "@opengeni/agent-proto": "^0.5.1-canary.0",
58
+ "@opengeni/capabilities": "^0.3.0-canary.0",
59
+ "@opengeni/codemode": "^0.4.12-canary.0",
60
+ "@opengeni/codex": "^0.2.18-canary.0",
61
+ "@opengeni/config": "^0.19.0-canary.0",
62
+ "@opengeni/contracts": "^2.2.0-canary.0",
63
+ "@opengeni/core": "^2.1.0-canary.0",
64
+ "@opengeni/db": "^3.1.0-canary.0",
65
+ "@opengeni/documents": "^0.6.9-canary.0",
66
+ "@opengeni/events": "^0.3.123-canary.0",
67
+ "@opengeni/github": "^0.5.2-canary.0",
68
+ "@opengeni/network": "^0.2.2-canary.0",
69
+ "@opengeni/observability": "^0.8.3-canary.0",
70
+ "@opengeni/runtime": "^1.3.0-canary.0",
71
+ "@opengeni/storage": "^0.2.105-canary.0",
72
+ "@opengeni/xai-subscription": "^0.1.1-canary.0",
73
73
  "@temporalio/activity": "^1.17.0",
74
74
  "@temporalio/client": "^1.17.0",
75
75
  "@temporalio/worker": "^1.17.0",
@@ -0,0 +1,292 @@
1
+ import { getBillingBalance, sumUsageQuantity } from "@opengeni/db";
2
+ import {
3
+ configuredStaticUsageLimits,
4
+ resolveTurnExecutionPolicyV1,
5
+ type Settings,
6
+ } from "@opengeni/config";
7
+ import { selectCodexCredentialId } from "@opengeni/codex";
8
+ import { directPersonalConnectionSubjectId } from "@opengeni/core";
9
+ import type { TurnActivityServices as ActivityServices } from "../types";
10
+ import {
11
+ type SessionEvent,
12
+ type SessionTurn,
13
+ type ToolAuthNeededPayload,
14
+ type TurnExecutionPolicyV1,
15
+ } from "@opengeni/contracts";
16
+ import { createHash } from "node:crypto";
17
+ import { startOfUtcMonth } from "./model-usage";
18
+
19
+ export class WorkspaceHumanInputDisabledError extends Error {
20
+ constructor(kind: "resume" | "interruption") {
21
+ super(`Workspace policy rejects structured human-input ${kind}`);
22
+ this.name = "WorkspaceHumanInputDisabledError";
23
+ }
24
+ }
25
+
26
+ export function assertWorkspaceHumanInputAllowed(
27
+ enabled: boolean,
28
+ kind: "resume" | "interruption",
29
+ attempted: boolean,
30
+ ): void {
31
+ if (!enabled && attempted) throw new WorkspaceHumanInputDisabledError(kind);
32
+ }
33
+
34
+ /** Broad personal lookup is allowed only for a direct human/API command. */
35
+ export function credentialSubjectIdForTurnInitiator(
36
+ turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">,
37
+ ): string | undefined {
38
+ return directPersonalConnectionSubjectId(turn);
39
+ }
40
+
41
+ /**
42
+ * Direct authenticated-human work is the persisted human source with subject
43
+ * authority and no inherited agent or legacy provenance. Use this complete
44
+ * immutable turn authority instead of inferring causality from a
45
+ * `user.message` event shape or the root initiator alone.
46
+ */
47
+ export function isDirectHumanTurnInitiation(
48
+ turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">,
49
+ ): boolean {
50
+ if ((turn.source !== "user" && turn.source !== "api") || turn.initiator.kind !== "subject") {
51
+ return false;
52
+ }
53
+ return !["via", "viaTruncated", "provenanceError", "backfill"].some((key) =>
54
+ Object.prototype.hasOwnProperty.call(turn.initiatorContext, key),
55
+ );
56
+ }
57
+
58
+ /**
59
+ * A disconnected personal Slack server is prepared best-effort before the model
60
+ * runs. Its initialize/tools-list credential miss is setup state, not evidence
61
+ * that an unrelated turn wants Slack. Keep concrete tool-call failures
62
+ * actionable, but gate setup-time Slack prompts to a human message that names
63
+ * Slack explicitly. Other providers retain the existing generic behavior.
64
+ */
65
+ export function shouldPublishToolAuthNeededForTurn(
66
+ payload: Pick<ToolAuthNeededPayload, "providerDomain" | "toolName">,
67
+ trigger: Pick<SessionEvent, "type" | "payload">,
68
+ turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">,
69
+ ): boolean {
70
+ if (typeof payload.toolName === "string" && payload.toolName.trim().length > 0) {
71
+ return true;
72
+ }
73
+ const providerDomain = payload.providerDomain.trim().toLowerCase();
74
+ const isSlack = providerDomain === "slack.com" || providerDomain.endsWith(".slack.com");
75
+ if (!isSlack) {
76
+ return true;
77
+ }
78
+ if (!isDirectHumanTurnInitiation(turn) || trigger.type !== "user.message") {
79
+ return false;
80
+ }
81
+ const text = (trigger.payload as { text?: unknown }).text;
82
+ return typeof text === "string" && /\bslack\b/i.test(text);
83
+ }
84
+
85
+ export function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {
86
+ externallyBilled: boolean;
87
+ codexSubscription: boolean;
88
+ xaiSubscription: boolean;
89
+ } {
90
+ return {
91
+ externallyBilled: policy.billing.metering === "external",
92
+ codexSubscription:
93
+ policy.providerId === "codex-subscription" &&
94
+ policy.credentialSource.kind === "connected_subscription" &&
95
+ policy.credentialSource.provider === "codex",
96
+ xaiSubscription:
97
+ policy.providerId === "supergrok-subscription" &&
98
+ policy.credentialSource.kind === "connected_subscription" &&
99
+ policy.credentialSource.provider === "xai",
100
+ };
101
+ }
102
+
103
+ export function legacyTurnExecutionPolicyInput(
104
+ turn: Pick<SessionTurn, "source" | "model" | "reasoningEffort" | "latencyMode">,
105
+ ): Parameters<typeof resolveTurnExecutionPolicyV1>[1] {
106
+ const explicit = turn.source === "user" || turn.source === "api";
107
+ return {
108
+ modelId: turn.model,
109
+ requestedModelId: explicit ? turn.model : null,
110
+ modelSource: explicit ? "explicit" : "continuation",
111
+ reasoningEffort: turn.reasoningEffort,
112
+ reasoningSource: explicit ? "explicit" : "continuation",
113
+ latencyMode: turn.latencyMode,
114
+ latencyModeSource: explicit ? "explicit" : "continuation",
115
+ };
116
+ }
117
+
118
+ /** A retryable provider fault recovers the accepted turn itself. Goal state is
119
+ * irrelevant: autonomous continuation and infrastructure recovery are separate
120
+ * concerns. */
121
+ export function selectCodexCredentialForTurn(args: {
122
+ sessionPinnedCredentialId: string | null;
123
+ activeCredentialId: string | null;
124
+ connectedIds: Set<string>;
125
+ }): string | null {
126
+ return selectCodexCredentialId(args);
127
+ }
128
+
129
+ export function stableHumanInputRequestId(
130
+ sessionId: string,
131
+ turnId: string,
132
+ toolCallId: string,
133
+ ): string {
134
+ const hex = createHash("sha256")
135
+ .update("opengeni-human-input-v1\0")
136
+ .update(sessionId)
137
+ .update("\0")
138
+ .update(turnId)
139
+ .update("\0")
140
+ .update(toolCallId)
141
+ .digest("hex")
142
+ .slice(0, 32)
143
+ .split("");
144
+ hex[12] = "5";
145
+ hex[16] = ["8", "9", "a", "b"][Number.parseInt(hex[16] ?? "0", 16) % 4] ?? "8";
146
+ const value = hex.join("");
147
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
148
+ }
149
+
150
+ export function stableInteractionInterventionId(
151
+ sessionId: string,
152
+ turnId: string,
153
+ toolCallId: string,
154
+ ): string {
155
+ return stableInteractionInterventionUuid(
156
+ "opengeni-interaction-intervention-v1",
157
+ sessionId,
158
+ turnId,
159
+ toolCallId,
160
+ );
161
+ }
162
+
163
+ export function stableInteractionInterventionOperationId(
164
+ sessionId: string,
165
+ turnId: string,
166
+ toolCallId: string,
167
+ ): string {
168
+ return stableInteractionInterventionUuid(
169
+ "opengeni-interaction-intervention-operation-v1",
170
+ sessionId,
171
+ turnId,
172
+ toolCallId,
173
+ );
174
+ }
175
+
176
+ export function stableInteractionInterventionUuid(
177
+ namespace: string,
178
+ sessionId: string,
179
+ turnId: string,
180
+ toolCallId: string,
181
+ ): string {
182
+ const hex = createHash("sha256")
183
+ .update(namespace)
184
+ .update("\0")
185
+ .update(sessionId)
186
+ .update("\0")
187
+ .update(turnId)
188
+ .update("\0")
189
+ .update(toolCallId)
190
+ .digest("hex")
191
+ .slice(0, 32)
192
+ .split("");
193
+ hex[12] = "5";
194
+ hex[16] = ["8", "9", "a", "b"][Number.parseInt(hex[16] ?? "0", 16) % 4] ?? "8";
195
+ const value = hex.join("");
196
+ return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
197
+ }
198
+
199
+ /**
200
+ * True when this activity attempt was cancelled because its hosting worker is
201
+ * shutting down gracefully (SIGTERM during a deploy), as opposed to a
202
+ * workflow-requested Pause/Steer cancellation or a server-side timeout.
203
+ */
204
+ export class BudgetExhaustedError extends Error {
205
+ constructor(
206
+ message: string,
207
+ readonly serializedRunState: string | null,
208
+ ) {
209
+ super(message);
210
+ this.name = "BudgetExhaustedError";
211
+ }
212
+ }
213
+
214
+ // Exported for unit testing the external-billing bypass (codex-billing.test.ts); not
215
+ // part of the activity surface. Takes the accepted policy's billing attribution and
216
+ // the optional §7.5 P3 host `entitlements` port (when bound, its `admitRun` REPLACES
217
+ // the local credit read for an OpenGeni-metered turn; unset → local ledger).
218
+ export async function ensureRunAllowed(
219
+ settings: Settings,
220
+ db: ActivityServices["db"],
221
+ accountId: string,
222
+ workspaceId: string,
223
+ isExternallyBilledTurn: boolean,
224
+ entitlements?: ActivityServices["entitlements"],
225
+ ): 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.
229
+ //
230
+ // §7.5 P3 — host-entitlements DELEGATION (the worker half of the same seam the
231
+ // API edge exposes). For a non-codex turn, when the host binds `entitlements`, its
232
+ // `admitRun` decision REPLACES the local credit-balance read below: a host that owns
233
+ // its ledger/meter is the funding authority. A deny throws the SAME Error the local
234
+ // read throws, so the mid-stream budget-valve at :727 wraps it in a
235
+ // `BudgetExhaustedError` and pauses identically — the valve never learns whether the
236
+ // deny came from the local ledger or the host meter.
237
+ //
238
+ // This is an admission READ only; it records NO usage (metering stays the sole,
239
+ // idempotency-keyed writer at recordModelUsageAndDebitCredits), so a PULL host meter
240
+ // is consulted without ever double-charging.
241
+ if (
242
+ !isExternallyBilledTurn &&
243
+ entitlements &&
244
+ (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
245
+ ) {
246
+ const decision = await entitlements.admitRun({
247
+ accountId,
248
+ workspaceId,
249
+ action: "agent_run:create",
250
+ quantity: 1,
251
+ });
252
+ if (!decision.allowed) {
253
+ throw new Error(decision.reason || "insufficient OpenGeni credits");
254
+ }
255
+ } else if (
256
+ !isExternallyBilledTurn &&
257
+ (settings.billingMode === "stripe" || settings.usageLimitsMode === "managed")
258
+ ) {
259
+ const balance = await getBillingBalance(db, accountId);
260
+ if (balance.balanceMicros <= 0) {
261
+ throw new Error("insufficient OpenGeni credits");
262
+ }
263
+ }
264
+ if (settings.usageLimitsMode === "static" || settings.usageLimitsMode === "managed") {
265
+ const limits = configuredStaticUsageLimits(settings);
266
+ if (limits.maxMonthlyAgentRunsPerWorkspace) {
267
+ const used = await sumUsageQuantity(db, {
268
+ workspaceId,
269
+ eventType: "agent_run.created",
270
+ since: startOfUtcMonth(),
271
+ });
272
+ // Agent turns are admitted and recorded before this worker activity starts.
273
+ // Equality means this accepted turn is exactly at the cap; greater-than is
274
+ // the race/backstop case where another admission already exceeded the cap.
275
+ if (used > limits.maxMonthlyAgentRunsPerWorkspace) {
276
+ throw new Error(
277
+ `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,
278
+ );
279
+ }
280
+ }
281
+ if (!isExternallyBilledTurn && limits.maxMonthlyTokensPerWorkspace) {
282
+ const used = await sumUsageQuantity(db, {
283
+ workspaceId,
284
+ eventType: "model.tokens",
285
+ since: startOfUtcMonth(),
286
+ });
287
+ if (used >= limits.maxMonthlyTokensPerWorkspace) {
288
+ throw new Error(`monthly token limit reached (${limits.maxMonthlyTokensPerWorkspace})`);
289
+ }
290
+ }
291
+ }
292
+ }