@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
@@ -0,0 +1,52 @@
1
+ import { resolveTurnExecutionPolicyV1, type Settings } from "@opengeni/config";
2
+ import type { TurnActivityServices as ActivityServices } from "../types.js";
3
+ import { type SessionEvent, type SessionTurn, type ToolAuthNeededPayload, type TurnExecutionPolicyV1 } from "@opengeni/contracts";
4
+ export declare class WorkspaceHumanInputDisabledError extends Error {
5
+ constructor(kind: "resume" | "interruption");
6
+ }
7
+ export declare function assertWorkspaceHumanInputAllowed(enabled: boolean, kind: "resume" | "interruption", attempted: boolean): void;
8
+ /** Broad personal lookup is allowed only for a direct human/API command. */
9
+ export declare function credentialSubjectIdForTurnInitiator(turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">): string | undefined;
10
+ /**
11
+ * Direct authenticated-human work is the persisted human source with subject
12
+ * authority and no inherited agent or legacy provenance. Use this complete
13
+ * immutable turn authority instead of inferring causality from a
14
+ * `user.message` event shape or the root initiator alone.
15
+ */
16
+ export declare function isDirectHumanTurnInitiation(turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">): boolean;
17
+ /**
18
+ * A disconnected personal Slack server is prepared best-effort before the model
19
+ * runs. Its initialize/tools-list credential miss is setup state, not evidence
20
+ * that an unrelated turn wants Slack. Keep concrete tool-call failures
21
+ * actionable, but gate setup-time Slack prompts to a human message that names
22
+ * Slack explicitly. Other providers retain the existing generic behavior.
23
+ */
24
+ export declare function shouldPublishToolAuthNeededForTurn(payload: Pick<ToolAuthNeededPayload, "providerDomain" | "toolName">, trigger: Pick<SessionEvent, "type" | "payload">, turn: Pick<SessionTurn, "source" | "initiator" | "initiatorContext">): boolean;
25
+ export declare function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {
26
+ externallyBilled: boolean;
27
+ codexSubscription: boolean;
28
+ xaiSubscription: boolean;
29
+ };
30
+ export declare function legacyTurnExecutionPolicyInput(turn: Pick<SessionTurn, "source" | "model" | "reasoningEffort" | "latencyMode">): Parameters<typeof resolveTurnExecutionPolicyV1>[1];
31
+ /** A retryable provider fault recovers the accepted turn itself. Goal state is
32
+ * irrelevant: autonomous continuation and infrastructure recovery are separate
33
+ * concerns. */
34
+ export declare function selectCodexCredentialForTurn(args: {
35
+ sessionPinnedCredentialId: string | null;
36
+ activeCredentialId: string | null;
37
+ connectedIds: Set<string>;
38
+ }): string | null;
39
+ export declare function stableHumanInputRequestId(sessionId: string, turnId: string, toolCallId: string): string;
40
+ export declare function stableInteractionInterventionId(sessionId: string, turnId: string, toolCallId: string): string;
41
+ export declare function stableInteractionInterventionOperationId(sessionId: string, turnId: string, toolCallId: string): string;
42
+ export declare function stableInteractionInterventionUuid(namespace: string, sessionId: string, turnId: string, toolCallId: string): string;
43
+ /**
44
+ * True when this activity attempt was cancelled because its hosting worker is
45
+ * shutting down gracefully (SIGTERM during a deploy), as opposed to a
46
+ * workflow-requested Pause/Steer cancellation or a server-side timeout.
47
+ */
48
+ export declare class BudgetExhaustedError extends Error {
49
+ readonly serializedRunState: string | null;
50
+ constructor(message: string, serializedRunState: string | null);
51
+ }
52
+ export declare function ensureRunAllowed(settings: Settings, db: ActivityServices["db"], accountId: string, workspaceId: string, isExternallyBilledTurn: boolean, entitlements?: ActivityServices["entitlements"]): Promise<void>;
@@ -0,0 +1,89 @@
1
+ import { type AttemptConnectorActionBinding, type SandboxFileDownload } from "@opengeni/runtime";
2
+ import { type Settings } from "@opengeni/config";
3
+ import { type CodexRequestContext } from "@opengeni/codex";
4
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from "../types.js";
5
+ import { createTurnCredentialLeases } from "./credential-leases.js";
6
+ import { createTurnMediaArtifacts } from "./media-artifacts.js";
7
+ import type { ClaimTurnOk } from "./claim.js";
8
+ import type { GovernanceModelOk } from "./governance-model.js";
9
+ import type { CompactionPrepOk } from "./compaction-prep.js";
10
+ import type { SandboxTurnRuntime } from "./sandbox-runtime.js";
11
+ import type { runtimeResourcesForTurn } from "./file-resources.js";
12
+ import type { sandboxArtifactRuntimeAdmission } from "./sandbox-route.js";
13
+ import type { loadWorkspaceEnvironmentForRunWithCredentials, sandboxEnvironmentForRun } from "../environment.js";
14
+ import type { AttemptIdentityState, EventingState, ProviderTurnState, RecordingState, SandboxRuntimeState } from "./turn-context.js";
15
+ export type BuildTurnAgentDeps = {
16
+ input: RunAgentTurnInput;
17
+ db: ActivityServices["db"];
18
+ runtime: ActivityServices["runtime"];
19
+ objectStorage: ActivityServices["objectStorage"];
20
+ observability: ActivityServices["observability"];
21
+ cancellationSignal: AbortSignal | undefined;
22
+ runtimeCancellationSignal: AbortSignal | undefined;
23
+ eventing: EventingState;
24
+ attempt: AttemptIdentityState;
25
+ sandboxState: SandboxRuntimeState;
26
+ recordingState: RecordingState;
27
+ maybeStartOnTurnRecording: SandboxTurnRuntime["maybeStartOnTurnRecording"];
28
+ providerTurn: ProviderTurnState;
29
+ media: ReturnType<typeof createTurnMediaArtifacts>;
30
+ leases: ReturnType<typeof createTurnCredentialLeases>;
31
+ turn: ClaimTurnOk["turn"];
32
+ session: ClaimTurnOk["session"];
33
+ fileAuthoritySubjectId: ClaimTurnOk["fileAuthoritySubjectId"];
34
+ capabilitySettings: ClaimTurnOk["capabilitySettings"];
35
+ humanInputResume: ClaimTurnOk["humanInputResume"];
36
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
37
+ runSettings: GovernanceModelOk["runSettings"];
38
+ logicalSandboxSettings: GovernanceModelOk["logicalSandboxSettings"];
39
+ verifiedRigProviderImageId: GovernanceModelOk["verifiedRigProviderImageId"];
40
+ resolvedModel: GovernanceModelOk["resolvedModel"];
41
+ nativeImageProviderBinding: GovernanceModelOk["nativeImageProviderBinding"];
42
+ lazyToolTransport: GovernanceModelOk["lazyToolTransport"];
43
+ modelInputPolicy: GovernanceModelOk["modelInputPolicy"];
44
+ supportsImageInput: GovernanceModelOk["supportsImageInput"];
45
+ agentHumanInputEnabled: GovernanceModelOk["agentHumanInputEnabled"];
46
+ workspaceAgentInstructions: GovernanceModelOk["workspaceAgentInstructions"];
47
+ workspaceGovernance: GovernanceModelOk["workspaceGovernance"];
48
+ structuredWorkspacePolicyActive: GovernanceModelOk["structuredWorkspacePolicyActive"];
49
+ workspaceMemory: GovernanceModelOk["workspaceMemory"];
50
+ rigVersion: GovernanceModelOk["rigVersion"];
51
+ rigName: GovernanceModelOk["rigName"];
52
+ packRuntime: GovernanceModelOk["packRuntime"];
53
+ installedSkillRuntime: GovernanceModelOk["installedSkillRuntime"];
54
+ buildCompanyBrainContributionReceiptFor: GovernanceModelOk["buildCompanyBrainContributionReceiptFor"];
55
+ promptCacheKey: CompactionPrepOk["promptCacheKey"];
56
+ workspaceVariableSet: Awaited<ReturnType<typeof loadWorkspaceEnvironmentForRunWithCredentials>>;
57
+ runtimeResources: ReturnType<typeof runtimeResourcesForTurn>;
58
+ sandboxEnvironment: Record<string, string>;
59
+ sandboxArtifactRuntime: ReturnType<typeof sandboxArtifactRuntimeAdmission>;
60
+ sandboxGitToken: string | undefined;
61
+ sandboxGitTokens: Record<string, string> | undefined;
62
+ sandboxGitCredentialBindings: Awaited<ReturnType<typeof sandboxEnvironmentForRun>>["gitCredentialBindings"];
63
+ sandboxCodemodeToken: string | undefined;
64
+ fileResourceDownloads: SandboxFileDownload[];
65
+ attemptConnectorActionBindings: readonly AttemptConnectorActionBinding[];
66
+ connectorActionIdentity: {
67
+ accountId: string;
68
+ workspaceId: string;
69
+ sessionId: string;
70
+ turnId: string;
71
+ attemptId: string;
72
+ executionGeneration: number;
73
+ initiator: Pick<ClaimTurnOk["turn"]["initiator"], "kind" | "subjectId">;
74
+ };
75
+ videoGenerationAcceptancesByCallId: Map<string, {
76
+ operationId: string;
77
+ requestDigest: string;
78
+ }>;
79
+ activeSandboxBackend: Settings["sandboxBackend"] | undefined;
80
+ groupBoxBackend: Settings["sandboxBackend"];
81
+ postToolPreparationStartedAt: number;
82
+ codexContext: CodexRequestContext | null;
83
+ };
84
+ export declare function buildTurnAgent(deps: BuildTurnAgentDeps): Promise<{
85
+ agent: import("@openai/agents-core").Agent<any, any>;
86
+ modelVisibleRuntimeSkillActivations: readonly import("@opengeni/runtime").RuntimeSkillActivation[];
87
+ postAgentPreparationStartedAt: number;
88
+ }>;
89
+ export type BuildTurnAgentOk = Awaited<ReturnType<typeof buildTurnAgent>>;
@@ -0,0 +1,67 @@
1
+ import { getSessionEvent, getHumanInputResumeForEvent, getInteractionInterventionResumeForEvent, requireSession, type ApiIntegrationRuntime, type SessionTurnForExecution } from "@opengeni/db";
2
+ import { type Settings } from "@opengeni/config";
3
+ import { currentActivityContext } from "../streaming.js";
4
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from "../types.js";
5
+ import { makeTurnOpJournal } from "../../op-journal.js";
6
+ import { createTurnCredentialLeases } from "./credential-leases.js";
7
+ import { createTurnMediaArtifacts } from "./media-artifacts.js";
8
+ import type { TurnExecutionPolicyV1 } from "@opengeni/contracts";
9
+ import type { AttemptIdentityState, BillingState, ClaimedResult, EventingState, RecordingState, SandboxRuntimeState, TurnControlState } from "./turn-context.js";
10
+ export type ClaimTurnDeps = {
11
+ input: RunAgentTurnInput;
12
+ settings: Settings;
13
+ db: ActivityServices["db"];
14
+ bus: ActivityServices["bus"];
15
+ runtime: ActivityServices["runtime"];
16
+ objectStorage: ActivityServices["objectStorage"];
17
+ observability: ActivityServices["observability"];
18
+ entitlements: ActivityServices["entitlements"];
19
+ wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
20
+ cancellationSignal: AbortSignal | undefined;
21
+ activityContext: ReturnType<typeof currentActivityContext>;
22
+ dispatchId: string;
23
+ activityStarted: number;
24
+ control: TurnControlState;
25
+ attempt: AttemptIdentityState;
26
+ billingState: BillingState;
27
+ sandboxState: SandboxRuntimeState;
28
+ recordingState: RecordingState;
29
+ eventing: EventingState;
30
+ leases: ReturnType<typeof createTurnCredentialLeases>;
31
+ media: ReturnType<typeof createTurnMediaArtifacts>;
32
+ claimedResult: ClaimedResult;
33
+ acknowledgeLostAttemptOwnership: () => void;
34
+ abandonActiveRecording: (reason: string, disposition?: "failed" | "discard") => Promise<void>;
35
+ };
36
+ export type ClaimTurnOk = {
37
+ turn: SessionTurnForExecution;
38
+ session: Awaited<ReturnType<typeof requireSession>>;
39
+ installedApiIntegrations: readonly ApiIntegrationRuntime[];
40
+ credentialSubjectId: string | undefined;
41
+ fileAuthoritySubjectId: string | null;
42
+ capabilitySettings: Settings;
43
+ codexAppsCredentialId: string | null;
44
+ turnExecutionPolicy: TurnExecutionPolicyV1;
45
+ trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>;
46
+ humanInputResume: Awaited<ReturnType<typeof getHumanInputResumeForEvent>>;
47
+ interactionInterventionResume: Awaited<ReturnType<typeof getInteractionInterventionResumeForEvent>>;
48
+ throwIfWorkerShuttingDown: () => void;
49
+ throwIfTurnCancelled: () => void;
50
+ opJournal: ReturnType<typeof makeTurnOpJournal>;
51
+ modelUsageDispatchId: string;
52
+ claimedModelUsageSourceKeys: Set<string>;
53
+ emittedModelUsageSourceKeys: Set<string>;
54
+ };
55
+ /**
56
+ * Stable for Temporal retries of one scheduled turn attempt, but unique across
57
+ * workflow runs. Temporal activity ids restart at `1` after continue-as-new or
58
+ * workflow restart, so they are not safe durable producer identities by
59
+ * themselves.
60
+ */
61
+ export declare function turnAttemptProducerId(input: Pick<RunAgentTurnInput, "workflowId" | "attemptId">, turnId: string): string;
62
+ export type ClaimTurnOutcome = {
63
+ exit: RunAgentTurnResult;
64
+ } | {
65
+ ok: ClaimTurnOk;
66
+ };
67
+ export declare function claimTurnAttempt(deps: ClaimTurnDeps): Promise<ClaimTurnOutcome>;
@@ -0,0 +1,40 @@
1
+ import { type Settings } from "@opengeni/config";
2
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from "../types.js";
3
+ import { createTurnCredentialLeases } from "./credential-leases.js";
4
+ import type { ClaimTurnOk } from "./claim.js";
5
+ import type { AttemptIdentityState, BillingState, ClaimedResult, EventingState, ProviderTurnState, TurnControlState } from "./turn-context.js";
6
+ export type CapacityPhaseDeps = {
7
+ input: RunAgentTurnInput;
8
+ settings: Settings;
9
+ db: ActivityServices["db"];
10
+ bus: ActivityServices["bus"];
11
+ observability: ActivityServices["observability"];
12
+ wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
13
+ signalCodexCapacityWorkflow: ActivityServices["signalCodexCapacityWorkflow"];
14
+ cancellationSignal: AbortSignal | undefined;
15
+ dispatchId: string;
16
+ control: TurnControlState;
17
+ attempt: AttemptIdentityState;
18
+ billingState: BillingState;
19
+ eventing: EventingState & {
20
+ publish: NonNullable<EventingState["publish"]>;
21
+ settle: NonNullable<EventingState["settle"]>;
22
+ };
23
+ providerTurn: ProviderTurnState;
24
+ leases: ReturnType<typeof createTurnCredentialLeases>;
25
+ claimedResult: ClaimedResult;
26
+ acknowledgeLostAttemptOwnership: () => void;
27
+ acknowledgeRecoveryQuiescence: () => void;
28
+ setLastInputTokensFenced: (lastInputTokens: number | null) => Promise<void>;
29
+ turn: ClaimTurnOk["turn"];
30
+ session: ClaimTurnOk["session"];
31
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
32
+ trigger: ClaimTurnOk["trigger"];
33
+ codexWorkspaceKey: string;
34
+ };
35
+ export type CapacityPhaseOutcome = {
36
+ exit: RunAgentTurnResult;
37
+ } | {
38
+ ok: true;
39
+ };
40
+ export declare function selectCodexTurnCapacity(deps: CapacityPhaseDeps): Promise<CapacityPhaseOutcome>;
@@ -0,0 +1,32 @@
1
+ import { type CodexAccountStatus } from "@opengeni/db";
2
+ import { type RegistryProviderKind, type Settings } from "@opengeni/config";
3
+ import type { TurnActivityServices as ActivityServices } from "../types.js";
4
+ export declare function codexWorkspaceMetricKey(workspaceId: string): string;
5
+ /** Stable public request identity across partial resumes and activity retries. */
6
+ export declare function acceptsPromptCacheKeyForTurn(resolvedModel: {
7
+ provider: {
8
+ kind: RegistryProviderKind;
9
+ builtin?: boolean;
10
+ };
11
+ } | null): boolean;
12
+ /**
13
+ * SELF-HEAL helper for the all-capped rotation idle (invariant 4: BOUNDED, no thrash).
14
+ * The turn hot path never refreshes Codex usage — only the usage API route does — so a
15
+ * window that has actually reset still reads OVER-threshold from the stale cache, which
16
+ * would idle-loop forever. Before idling, refresh LIVE usage for every connected account
17
+ * the cache marks exhausted (bounded to the account count), which re-writes the
18
+ * cache columns, then return the re-read rows so the ranker can pick up a genuinely-reset
19
+ * window THIS turn. A refresh/read failure is swallowed (fall back to the pre-refresh rows
20
+ * + the bounded idle). Cooling (429'd) accounts are NOT refreshed: their exhaustedUntil
21
+ * cooldown is authoritative, and refreshing them would burn a provider call for nothing.
22
+ */
23
+ export declare function refreshCappedCodexUsageRows(db: ActivityServices["db"], settings: Settings, workspaceId: string, accounts: Array<Pick<CodexAccountStatus, "id" | "status" | "primaryUsedPercent" | "secondaryUsedPercent" | "exhaustedUntil">>, capacitySignals: {
24
+ signalCodexCapacityWorkflow?: ActivityServices["signalCodexCapacityWorkflow"] | undefined;
25
+ wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
26
+ }): Promise<Array<Pick<CodexAccountStatus, "id" | "status" | "primaryUsedPercent" | "secondaryUsedPercent" | "exhaustedUntil">>>;
27
+ /**
28
+ * True once the lifetime last confirmed by Postgres is no longer trustworthy.
29
+ * A missing or malformed deadline fails closed for a holder that claims to be
30
+ * leased; callers check this before accepting an in-flight heartbeat promise.
31
+ */
32
+ export declare function codexCredentialLeaseDeadlineExpired(confirmedUntilMs: number | null, nowMs?: number): boolean;
@@ -0,0 +1,88 @@
1
+ import { serializedToolsForRemoteCompaction } from "@opengeni/runtime";
2
+ import { type Settings } from "@opengeni/config";
3
+ import { maybeCompactContext } from "../context-compaction.js";
4
+ import type { CompactionSummarizer, RemoteCompactionV2Requester } from "../context-compaction.js";
5
+ import type { TurnActivityServices as ActivityServices, RunAgentTurnInput, RunAgentTurnResult } from "../types.js";
6
+ import { createTurnCredentialLeases } from "./credential-leases.js";
7
+ import { createTurnMediaArtifacts } from "./media-artifacts.js";
8
+ import { type SessionEvent } from "@opengeni/contracts";
9
+ import type { ClaimTurnOk } from "./claim.js";
10
+ import type { GovernanceModelOk } from "./governance-model.js";
11
+ import type { AttemptIdentityState, BillingState, ClaimedResult, EventingState, ProviderTurnState, TurnControlState } from "./turn-context.js";
12
+ export type RemoteCompactionPrefix = {
13
+ tools: Awaited<ReturnType<typeof serializedToolsForRemoteCompaction>>;
14
+ instructions: string;
15
+ toolsReady: boolean;
16
+ agent: Parameters<typeof serializedToolsForRemoteCompaction>[0] | null;
17
+ };
18
+ export type CompactionPrepDeps = {
19
+ input: RunAgentTurnInput;
20
+ settings: Settings;
21
+ db: ActivityServices["db"];
22
+ bus: ActivityServices["bus"];
23
+ observability: ActivityServices["observability"];
24
+ cancellationSignal: AbortSignal | undefined;
25
+ control: TurnControlState;
26
+ attempt: AttemptIdentityState;
27
+ billingState: BillingState;
28
+ eventing: EventingState & {
29
+ publish: NonNullable<EventingState["publish"]>;
30
+ settle: NonNullable<EventingState["settle"]>;
31
+ };
32
+ providerTurn: ProviderTurnState;
33
+ leases: ReturnType<typeof createTurnCredentialLeases>;
34
+ media: ReturnType<typeof createTurnMediaArtifacts>;
35
+ claimedResult: ClaimedResult;
36
+ claimedModelUsageSourceKeys: Set<string>;
37
+ emittedModelUsageSourceKeys: Set<string>;
38
+ modelUsageDispatchId: string;
39
+ turn: ClaimTurnOk["turn"];
40
+ session: ClaimTurnOk["session"];
41
+ turnExecutionPolicy: ClaimTurnOk["turnExecutionPolicy"];
42
+ resolvedModel: GovernanceModelOk["resolvedModel"];
43
+ workspaceAgentInstructions: GovernanceModelOk["workspaceAgentInstructions"];
44
+ workspaceGovernance: GovernanceModelOk["workspaceGovernance"];
45
+ structuredWorkspacePolicyActive: GovernanceModelOk["structuredWorkspacePolicyActive"];
46
+ workspaceMemory: GovernanceModelOk["workspaceMemory"];
47
+ rigVersion: GovernanceModelOk["rigVersion"];
48
+ rigName: GovernanceModelOk["rigName"];
49
+ compactionModelHistoryProjector: GovernanceModelOk["compactionModelHistoryProjector"];
50
+ summarizeContextForCompaction: ActivityServices["summarizeContextForCompaction"];
51
+ withProviderRequestContext: <T>(fn: () => Promise<T>) => Promise<T>;
52
+ withCodexRemoteCompaction: <T>(fn: () => Promise<T>) => Promise<T>;
53
+ };
54
+ export type CompactionPrepOk = {
55
+ promptCacheKey: string | undefined;
56
+ remotePrefix: RemoteCompactionPrefix;
57
+ remoteCompactionRequester: RemoteCompactionV2Requester | undefined;
58
+ publishCompactionLiveEvents: (events: SessionEvent[]) => Promise<void>;
59
+ publishCompactionOutcomeEvents: (events: SessionEvent[]) => Promise<void>;
60
+ compactionModeOptions: NonNullable<Parameters<typeof maybeCompactContext>[5]>;
61
+ compactionOnlyTurn: boolean;
62
+ compactionSummarizerFor: (systemInstructions?: string) => CompactionSummarizer;
63
+ };
64
+ export type CompactionPrepOutcome = {
65
+ exit: RunAgentTurnResult;
66
+ } | {
67
+ ok: CompactionPrepOk;
68
+ };
69
+ export type PostAgentCompactionDeps = CompactionPrepDeps & {
70
+ remotePrefix: RemoteCompactionPrefix;
71
+ remoteCompactionRequester: CompactionPrepOk["remoteCompactionRequester"];
72
+ publishCompactionLiveEvents: CompactionPrepOk["publishCompactionLiveEvents"];
73
+ publishCompactionOutcomeEvents: CompactionPrepOk["publishCompactionOutcomeEvents"];
74
+ compactionModeOptions: CompactionPrepOk["compactionModeOptions"];
75
+ compactionOnlyTurn: boolean;
76
+ compactionSummarizerFor: CompactionPrepOk["compactionSummarizerFor"];
77
+ agent: ReturnType<ActivityServices["runtime"]["buildAgent"]>;
78
+ };
79
+ export type PostAgentCompactionOk = {
80
+ compactSummarizer: ReturnType<CompactionPrepOk["compactionSummarizerFor"]>;
81
+ };
82
+ export type PostAgentCompactionOutcome = {
83
+ exit: RunAgentTurnResult;
84
+ } | {
85
+ ok: PostAgentCompactionOk;
86
+ };
87
+ export declare function prepareCompaction(deps: CompactionPrepDeps): Promise<CompactionPrepOutcome>;
88
+ export declare function runPostAgentCompaction(deps: PostAgentCompactionDeps): Promise<PostAgentCompactionOutcome>;
@@ -0,0 +1,56 @@
1
+ import type { SharedActivityServices } from "../types.js";
2
+ export type LeaseRenewReason = "timer" | "runtime_event" | "model_usage";
3
+ export type LeaseLossReason = "deadline" | "not_found";
4
+ export type TurnCredentialLeaseDeps = {
5
+ db: SharedActivityServices["db"];
6
+ observability: SharedActivityServices["observability"];
7
+ accountId: string;
8
+ workspaceId: string;
9
+ codexWorkspaceKey: string;
10
+ getTurnId: () => string | undefined;
11
+ };
12
+ /**
13
+ * The Codex credential holder for one running turn. The DB row is the
14
+ * cross-replica fairness primitive; the heartbeat here only extends its short
15
+ * TTL. A killed worker stops heartbeating and the holder self-expires.
16
+ */
17
+ export declare class CodexTurnLease {
18
+ private readonly deps;
19
+ held: boolean;
20
+ lost: boolean;
21
+ holderId: string | null;
22
+ generation: number | null;
23
+ confirmedUntilMs: number | null;
24
+ private heartbeatInFlight;
25
+ private heartbeatTimer;
26
+ constructor(deps: TurnCredentialLeaseDeps);
27
+ markLost: (reason: LeaseLossReason) => void;
28
+ renew: (reason: LeaseRenewReason) => Promise<void>;
29
+ startHeartbeat: () => void;
30
+ stopHeartbeat: () => void;
31
+ }
32
+ /** The xAI/SuperGrok credential holder for one running turn; same shape. */
33
+ export declare class XaiTurnLease {
34
+ private readonly deps;
35
+ held: boolean;
36
+ lost: boolean;
37
+ subjectId: string | null;
38
+ holderId: string | null;
39
+ generation: number | null;
40
+ confirmedUntilMs: number | null;
41
+ private heartbeatInFlight;
42
+ private heartbeatTimer;
43
+ constructor(deps: TurnCredentialLeaseDeps);
44
+ markLost: (reason: LeaseLossReason) => void;
45
+ renew: () => Promise<void>;
46
+ startHeartbeat: () => void;
47
+ stopHeartbeat: () => void;
48
+ }
49
+ /** Both serving-credential leases for one turn attempt plus their composite views. */
50
+ export type TurnCredentialLeases = {
51
+ codex: CodexTurnLease;
52
+ xai: XaiTurnLease;
53
+ renewServing: (reason: LeaseRenewReason) => Promise<void>;
54
+ servingLost: () => boolean;
55
+ };
56
+ export declare function createTurnCredentialLeases(deps: TurnCredentialLeaseDeps): TurnCredentialLeases;