@opengeni/worker-bundle 0.24.2-canary.0 → 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 (73) hide show
  1. package/dist/activities/agent-turn/agent-build.d.ts +3 -10
  2. package/dist/activities/agent-turn/claim.d.ts +7 -0
  3. package/dist/activities/agent-turn/credential-leases.d.ts +8 -0
  4. package/dist/activities/agent-turn/errors.d.ts +1 -1
  5. package/dist/activities/agent-turn/failure-settlement.d.ts +43 -1
  6. package/dist/activities/agent-turn/quiescence.d.ts +9 -6
  7. package/dist/activities/agent-turn/tool-environment.d.ts +2 -13
  8. package/dist/activities/agent-turn/tool-policy.d.ts +4 -0
  9. package/dist/activities/agent-turn/turn-context.d.ts +9 -1
  10. package/dist/activities/codemode-dispatcher.d.ts +10 -1
  11. package/dist/activities/codex-capacity.d.ts +32 -3
  12. package/dist/activities/codex-fleet-shadow.d.ts +1 -1
  13. package/dist/activities/codex-image-generation.d.ts +1 -1
  14. package/dist/activities/codex-rotation.d.ts +8 -67
  15. package/dist/activities/goals.d.ts +1 -1
  16. package/dist/activities/google-drive-publication.d.ts +2 -13
  17. package/dist/activities/image-generation-operation.d.ts +13 -4
  18. package/dist/activities/session-state.d.ts +4 -2
  19. package/dist/activities/types.d.ts +11 -1
  20. package/dist/{activities-control-ZWH7J4KZ.js → activities-control-CTEMLTHG.js} +45 -18
  21. package/dist/activities-control-CTEMLTHG.js.map +1 -0
  22. package/dist/activities-control.d.ts +2 -0
  23. package/dist/{activities-turn-I4OPLQLS.js → activities-turn-S5IU347A.js} +960 -815
  24. package/dist/activities-turn-S5IU347A.js.map +1 -0
  25. package/dist/activities.d.ts +2 -0
  26. package/dist/{chunk-65JEWP2Q.js → chunk-D4ZEFOYH.js} +1 -1
  27. package/dist/chunk-D4ZEFOYH.js.map +1 -0
  28. package/dist/{chunk-RQNH6CGR.js → chunk-TAUE3GYT.js} +117 -95
  29. package/dist/chunk-TAUE3GYT.js.map +1 -0
  30. package/dist/github-rest-mcp.d.ts +0 -2
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.js +2 -2
  33. package/dist/index.js.map +1 -1
  34. package/dist/observability-metrics.d.ts +1 -1
  35. package/dist/workflow-bundle.js +71 -8
  36. package/dist/workflows/activities.d.ts +1 -1
  37. package/dist/workflows/session.d.ts +3 -0
  38. package/package.json +17 -17
  39. package/src/activities/agent-turn/agent-build.ts +20 -26
  40. package/src/activities/agent-turn/claim.ts +26 -1
  41. package/src/activities/agent-turn/codex-capacity.ts +311 -234
  42. package/src/activities/agent-turn/credential-leases.ts +36 -0
  43. package/src/activities/agent-turn/errors.ts +29 -1
  44. package/src/activities/agent-turn/failure-settlement.ts +451 -323
  45. package/src/activities/agent-turn/quiescence.ts +21 -15
  46. package/src/activities/agent-turn/run.ts +18 -5
  47. package/src/activities/agent-turn/stream-attempt.ts +15 -1
  48. package/src/activities/agent-turn/tool-environment.ts +30 -32
  49. package/src/activities/agent-turn/tool-policy.ts +14 -8
  50. package/src/activities/agent-turn/turn-context.ts +13 -0
  51. package/src/activities/codemode-dispatcher.ts +235 -59
  52. package/src/activities/codex-capacity.ts +89 -10
  53. package/src/activities/codex-fleet-shadow.ts +8 -1
  54. package/src/activities/codex-image-generation.ts +19 -2
  55. package/src/activities/codex-rotation.ts +45 -142
  56. package/src/activities/goals.ts +9 -9
  57. package/src/activities/google-drive-publication.ts +4 -81
  58. package/src/activities/image-generation-operation.ts +28 -3
  59. package/src/activities/sandbox-lease.ts +29 -12
  60. package/src/activities/session-state.ts +17 -0
  61. package/src/activities/types.ts +16 -8
  62. package/src/activities.ts +1 -0
  63. package/src/github-rest-mcp.ts +0 -82
  64. package/src/observability-metrics.ts +4 -0
  65. package/src/sandbox-routing.ts +71 -16
  66. package/src/workflows/activities.ts +1 -0
  67. package/src/workflows/session.ts +85 -7
  68. package/dist/activities/api-integrations.d.ts +0 -21
  69. package/dist/activities-control-ZWH7J4KZ.js.map +0 -1
  70. package/dist/activities-turn-I4OPLQLS.js.map +0 -1
  71. package/dist/chunk-65JEWP2Q.js.map +0 -1
  72. package/dist/chunk-RQNH6CGR.js.map +0 -1
  73. package/src/activities/api-integrations.ts +0 -151
@@ -1,4 +1,4 @@
1
- import { type AttemptConnectorActionBinding, type SandboxFileDownload } from "@opengeni/runtime";
1
+ import { type AttemptConnectorActionBinding, type ConnectorActionPolicyHooks, type SandboxFileDownload } from "@opengeni/runtime";
2
2
  import { type Settings } from "@opengeni/config";
3
3
  import { type CodexRequestContext } from "@opengeni/codex";
4
4
  import type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from "../types.js";
@@ -60,15 +60,8 @@ export type BuildTurnAgentDeps = {
60
60
  sandboxCodemodeToken: string | undefined;
61
61
  fileResourceDownloads: SandboxFileDownload[];
62
62
  attemptConnectorActionBindings: readonly AttemptConnectorActionBinding[];
63
- connectorActionIdentity: {
64
- accountId: string;
65
- workspaceId: string;
66
- sessionId: string;
67
- turnId: string;
68
- attemptId: string;
69
- executionGeneration: number;
70
- initiator: Pick<ClaimTurnOk["turn"]["initiator"], "kind" | "subjectId">;
71
- };
63
+ connectorActionPolicy: ConnectorActionPolicyHooks;
64
+ trigger: ClaimTurnOk["trigger"];
72
65
  preparationIndependentToolNames: readonly string[];
73
66
  videoGenerationAcceptancesByCallId: Map<string, {
74
67
  operationId: string;
@@ -58,6 +58,13 @@ export type ClaimTurnOk = {
58
58
  * themselves.
59
59
  */
60
60
  export declare function turnAttemptProducerId(input: Pick<RunAgentTurnInput, "workflowId" | "attemptId">, turnId: string): string;
61
+ /**
62
+ * Durable Codex lease holder for one accepted turn attempt. Temporal activity
63
+ * ids may repeat after workflow restart or continue-as-new, so they are not
64
+ * owner identity. The attempt id is generated by the workflow for each
65
+ * redispatch and remains stable when the same activity input is retried.
66
+ */
67
+ export declare function codexCredentialLeaseHolderId(input: Pick<RunAgentTurnInput, "workflowId" | "attemptId">, turnId: string): string;
61
68
  export type ClaimTurnOutcome = {
62
69
  exit: RunAgentTurnResult;
63
70
  } | {
@@ -1,6 +1,11 @@
1
1
  import type { SharedActivityServices } from "../types.js";
2
2
  export type LeaseRenewReason = "timer" | "runtime_event" | "model_usage";
3
3
  export type LeaseLossReason = "deadline" | "not_found";
4
+ export declare class CodexCredentialLeaseLostError extends Error {
5
+ readonly reason: LeaseLossReason;
6
+ readonly code = "codex_credential_lease_lost";
7
+ constructor(reason: LeaseLossReason);
8
+ }
4
9
  export type TurnCredentialLeaseDeps = {
5
10
  db: SharedActivityServices["db"];
6
11
  observability: SharedActivityServices["observability"];
@@ -18,6 +23,7 @@ export declare class CodexTurnLease {
18
23
  private readonly deps;
19
24
  held: boolean;
20
25
  lost: boolean;
26
+ lossReason: LeaseLossReason | null;
21
27
  holderId: string | null;
22
28
  generation: number | null;
23
29
  confirmedUntilMs: number | null;
@@ -25,6 +31,8 @@ export declare class CodexTurnLease {
25
31
  private heartbeatTimer;
26
32
  constructor(deps: TurnCredentialLeaseDeps);
27
33
  markLost: (reason: LeaseLossReason) => void;
34
+ /** Fail closed at the last worker-confirmed lease deadline before dispatch. */
35
+ assertUsable: () => void;
28
36
  renew: (reason: LeaseRenewReason) => Promise<void>;
29
37
  startHeartbeat: () => void;
30
38
  stopHeartbeat: () => void;
@@ -280,7 +280,7 @@ export declare function codexUsageLimitFailurePayload(info: {
280
280
  }): {
281
281
  error: string;
282
282
  code: string;
283
- retryable: boolean;
283
+ retryable: false;
284
284
  detail?: string;
285
285
  };
286
286
  export declare const CODEX_USAGE_LIMIT_MAX_RESUME_MS: number;
@@ -11,7 +11,6 @@ export type TurnFailureDeps = {
11
11
  bus: ActivityServices["bus"];
12
12
  observability: ActivityServices["observability"];
13
13
  wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
14
- signalCodexCapacityWorkflow: ActivityServices["signalCodexCapacityWorkflow"];
15
14
  cancellationSignal: AbortSignal | undefined;
16
15
  sandboxRotationController: AbortController;
17
16
  noteCancellationRequested: () => void;
@@ -30,4 +29,47 @@ export type TurnFailureDeps = {
30
29
  acknowledgeLostAttemptOwnership: () => void;
31
30
  acknowledgeRecoveryQuiescence: () => void;
32
31
  };
32
+ export type CodexDefinitiveFailureDisposition = "failover" | "wait" | "terminal";
33
+ type CodexCapacityWaitFailurePayload = {
34
+ error: string;
35
+ code: string;
36
+ detail?: string;
37
+ retryable: false;
38
+ };
39
+ /**
40
+ * Pure policy for a definitive serving-credential refusal. A policy-constrained
41
+ * account and an all-unavailable pool wait for the same selected capacity to
42
+ * recover; only a truly empty/non-allocatable pool makes an auth/forbidden
43
+ * failure terminal. A different eligible account under rotation-on policy may
44
+ * recover the same durable turn immediately.
45
+ */
46
+ export declare function codexDefinitiveFailureDisposition(input: {
47
+ failureKind: "auth" | "forbidden" | "rate_limit" | "quota";
48
+ rotationEnabled: boolean;
49
+ pinDisposition: "manual" | "sharded" | "clearStale" | "unpinned";
50
+ decisionKind: "active" | "allCapped" | "none";
51
+ decisionCredentialId: string | null;
52
+ servingCredentialId: string;
53
+ }): CodexDefinitiveFailureDisposition;
54
+ /**
55
+ * Bound one turn to the alternate credentials that policy actually permits.
56
+ * The effective account list is already workspace/organization scoped;
57
+ * allocator-disabled rows must not enlarge the retry budget. The database
58
+ * requires a positive bound even though one-account paths never fail over.
59
+ */
60
+ export declare function codexCredentialFailoverLimit(accounts: ReadonlyArray<{
61
+ id: string;
62
+ allocatorEnabled: boolean;
63
+ }>, servingCredentialId: string): number;
64
+ /** Build the durable waiter payload without collapsing quota refusals into 403. */
65
+ export declare function codexCapacityWaitFailurePayload(input: {
66
+ failureKind: "auth" | "forbidden" | "rate_limit" | "quota";
67
+ usageLimit: {
68
+ resetsInSeconds: number | null;
69
+ } | null;
70
+ cooldownSeconds: number | null;
71
+ detail: string;
72
+ allAccounts: boolean;
73
+ }): CodexCapacityWaitFailurePayload;
33
74
  export declare function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgentTurnResult>;
75
+ export {};
@@ -48,6 +48,7 @@ export declare function assertSessionAttemptQuiescenceRecoveryDurable(input: {
48
48
  export declare const QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS = 250;
49
49
  export declare const QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS = 5000;
50
50
  export declare const TURN_QUIESCENCE_WATCHDOG_MS: number;
51
+ export declare const TURN_FINALIZER_STEP_TIMEOUT_MS = 30000;
51
52
  /** A fenced activity must never heartbeat forever while its physical writer
52
53
  * drain is stuck. The last-resort worker exit stops every in-process writer;
53
54
  * Kubernetes replaces the pod and the workflow's heartbeat-lease reconciler
@@ -99,13 +100,15 @@ export declare function releaseTurnSandboxAfterWriterDrain(sandbox: Pick<Resumed
99
100
  wait?: (delayMs: number) => Promise<void>;
100
101
  }): Promise<void>;
101
102
  /**
102
- * Await a finalizer operation only while this Temporal activity still owns its
103
- * execution window. Once Pause/Steer cancellation arrives, the operation keeps
104
- * its own rejection handler and may finish its idempotent, attempt-scoped
105
- * cleanup in the background, but it cannot pin activity terminalization or
106
- * delay the separately receipt-gated replacement dispatch.
103
+ * Await bounded, idempotent finalizer housekeeping only while this Temporal
104
+ * activity still owns its execution window. A completed turn must never keep
105
+ * heartbeating forever because a provider/tool close promise did not settle:
106
+ * that strands every later durable prompt behind an already-terminal attempt.
107
+ * Cancellation or the hard timeout detaches the operation with a rejection
108
+ * handler; the operation may still finish its attempt-scoped cleanup, but it
109
+ * cannot pin activity terminalization.
107
110
  */
108
- export declare function waitForTurnFinalizerStep<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<T | undefined>;
111
+ export declare function waitForTurnFinalizerStep<T>(operation: Promise<T>, signal: AbortSignal | undefined, timeoutMs?: number): Promise<T | undefined>;
109
112
  /**
110
113
  * Flush provider-facing stream state while the attempt still owns its activity
111
114
  * window. On Pause/Steer, both promises are detached with rejection handlers:
@@ -1,4 +1,4 @@
1
- import { type AttemptConnectorActionBinding } from "@opengeni/runtime";
1
+ import { type AttemptConnectorActionBinding, type ConnectorActionPolicyHooks } from "@opengeni/runtime";
2
2
  import { type Settings } from "@opengeni/config";
3
3
  import { withFirstPartyTools } from "../goals.js";
4
4
  import type { TurnActivityServices as ActivityServices, RunAgentTurnInput } from "../types.js";
@@ -125,18 +125,7 @@ export declare function prepareTurnToolPolicy(deps: PrepareTurnToolPolicyDeps):
125
125
  }>;
126
126
  export declare function prepareTurnToolRuntime(deps: PrepareTurnToolRuntimeDeps): Promise<{
127
127
  attemptConnectorActionBindings: AttemptConnectorActionBinding[];
128
- connectorActionIdentity: {
129
- readonly accountId: string;
130
- readonly workspaceId: string;
131
- readonly sessionId: string;
132
- readonly turnId: string;
133
- readonly attemptId: string;
134
- readonly executionGeneration: number;
135
- readonly initiator: {
136
- readonly kind: "service" | "subject";
137
- readonly subjectId: string;
138
- };
139
- };
128
+ connectorActionPolicy: ConnectorActionPolicyHooks;
140
129
  generateSessionTitleInParallel: boolean;
141
130
  postToolPreparationStartedAt: number;
142
131
  preparationIndependentToolNames: string[];
@@ -35,8 +35,12 @@ export declare function computerToolModeForTurn(resolvedModel: {
35
35
  /** Chat wires and Gateway models do not advertise OpenAI's hosted sandbox tool types. */
36
36
  export declare function structuredToolTransportForTurn(resolvedModel: {
37
37
  provider: {
38
+ id: string;
38
39
  kind: ResolvedModelProvider["kind"];
39
40
  api: ModelProviderApi;
41
+ wireProfile: "openai" | "azure-openai";
42
+ builtin: boolean;
43
+ baseUrl?: string | undefined;
40
44
  };
41
45
  } | null): boolean;
42
46
  /**
@@ -1,7 +1,7 @@
1
1
  import type { Settings } from "@opengeni/config";
2
2
  import type { CodexUsageHeaderSnapshot } from "@opengeni/codex";
3
3
  import type { AppendEventInput, ApplySessionTurnSettlementInput } from "@opengeni/db";
4
- import type { ModelContextContributionSummary, SessionStatus, XaiProviderAccountAuthoritySnapshotV1 } from "@opengeni/contracts";
4
+ import type { CodexCredentialPolicySnapshotV1, ModelContextContributionSummary, SessionStatus, XaiProviderAccountAuthoritySnapshotV1 } from "@opengeni/contracts";
5
5
  import type { EstablishedSandboxSession, OpenGeniRuntime, RunCredentialCommandSession, SelfhostedSession, TurnToolCancellationFence } from "@opengeni/runtime";
6
6
  import type { XaiSubscriptionRequestContext } from "@opengeni/xai-subscription";
7
7
  import type { CodemodeAttemptDispatcher } from "../codemode-dispatcher.js";
@@ -23,6 +23,7 @@ export type TurnSettleFn = (input: {
23
23
  turnStatus: "queued" | "running" | "completed" | "failed" | "cancelled" | "superseded" | "requires_action";
24
24
  sessionStatus: SessionStatus;
25
25
  activeTurnId: string | null;
26
+ suppressGoalContinuation?: boolean;
26
27
  consumeRequestedCompactionFailure?: boolean;
27
28
  runState?: ApplySessionTurnSettlementInput["runState"];
28
29
  }) => Promise<boolean>;
@@ -35,6 +36,7 @@ export type TurnControlState = {
35
36
  };
36
37
  export type AttemptIdentityState = {
37
38
  turnId: string | undefined;
39
+ dispatchId: string;
38
40
  triggerEventId: string | undefined;
39
41
  executionGeneration: number;
40
42
  providerRecoveryCount: number;
@@ -115,6 +117,12 @@ export type WorkspaceRefState = {
115
117
  };
116
118
  export type ProviderTurnState = {
117
119
  effectiveCodexCredentialId: string | null;
120
+ /** Exact row version returned by the resolver for the latest provider request. */
121
+ effectiveCodexCredentialVersion: number | null;
122
+ /** Frozen alternate-account ceiling observed by the fenced allocator. */
123
+ codexCredentialFailoverLimit: number;
124
+ /** Accepted Codex allocator policy captured with the first durable lease. */
125
+ codexPolicySnapshot: CodexCredentialPolicySnapshotV1 | null;
118
126
  effectiveXaiCredentialId: string | null;
119
127
  xaiRotationEnabled: boolean;
120
128
  xaiAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1 | null;
@@ -9,6 +9,10 @@ export type CodemodeDispatcherScope = {
9
9
  attemptId: string;
10
10
  executionGeneration: number;
11
11
  };
12
+ export type CodemodeDispatcherTimings = {
13
+ claimLeaseMs?: number;
14
+ claimHeartbeatMs?: number;
15
+ };
12
16
  /**
13
17
  * Owns the only Codemode execution edge for one exact attempt. NATS carries a
14
18
  * wake-up only; the durable row is claimed before any side effect and the call
@@ -26,10 +30,15 @@ export declare class CodemodeAttemptDispatcher {
26
30
  private pendingClaims;
27
31
  private unsubscribe;
28
32
  private closing;
29
- constructor(db: Database, bus: EventBus, environment: AttemptToolEnvironment, scope: CodemodeDispatcherScope, turnSignal?: AbortSignal | undefined, maxConcurrentCalls?: number);
33
+ private readonly claimLeaseMs;
34
+ private readonly claimHeartbeatMs;
35
+ constructor(db: Database, bus: EventBus, environment: AttemptToolEnvironment, scope: CodemodeDispatcherScope, turnSignal?: AbortSignal | undefined, maxConcurrentCalls?: number, timings?: CodemodeDispatcherTimings);
30
36
  start(): void;
31
37
  close(reason?: string): Promise<void>;
32
38
  private execute;
39
+ private executeClaimed;
40
+ private ensureToolCallCreated;
33
41
  private settleWithOutput;
34
42
  private failBeforeExecution;
35
43
  }
44
+ export declare function codemodeToolCallCreatedClientEventId(operationId: string): string;
@@ -1,5 +1,4 @@
1
- import { reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb, type CodexCapacityWakeTarget, type CodexCapacitySelectionContext } from "@opengeni/db";
2
- import type { Settings } from "@opengeni/config";
1
+ import { armCodexCapacityWait, reconcileCodexCapacityWait as reconcileCodexCapacityWaitDb, type CodexCapacityWakeTarget, type CodexCapacitySelectionContext } from "@opengeni/db";
3
2
  import type { ControlActivityServices, GetCodexCapacityWaitInput, ReconcileCodexCapacityWaitInput, ReconcileCodexCapacityWaitResult } from "./types.js";
4
3
  type CodexCapacitySignalServices = {
5
4
  signalCodexCapacityWorkflow?: NonNullable<ControlActivityServices["signalCodexCapacityWorkflow"]> | null | undefined;
@@ -18,7 +17,37 @@ export declare function signalCodexCapacityWakeTargets(services: CodexCapacitySi
18
17
  export declare function signalPendingCodexCapacityWakeTargets(services: CodexCapacitySignalServices & {
19
18
  db: ControlActivityServices["db"];
20
19
  }, workspaceId: string): Promise<void>;
21
- export declare function codexCapacityDecision(context: CodexCapacitySelectionContext, settings: Settings): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]>;
20
+ export declare function codexCapacityDecision<TPolicyScope = never, TUnavailableDiagnostic = never>(context: CodexCapacitySelectionContext<TPolicyScope, TUnavailableDiagnostic>): ReturnType<Parameters<typeof reconcileCodexCapacityWaitDb>[2]>;
21
+ /**
22
+ * Arm a durable Codex waiter and immediately re-evaluate it under the
23
+ * allocator lock. A capacity mutation that commits just before the waiter is
24
+ * inserted cannot signal a row that does not exist yet, so every arm site must
25
+ * close that edge before returning an hours-away reset timer to the workflow.
26
+ * Mutations after the arm commit still advance the waiter's wake revision.
27
+ */
28
+ export declare function armAndReconcileCodexCapacityWait(services: Pick<ControlActivityServices, "db" | "bus">, input: Parameters<typeof armCodexCapacityWait>[1], options?: {
29
+ onArmed?: () => void;
30
+ }): Promise<{
31
+ action: "stale";
32
+ waiter: import("@opengeni/db").CodexCapacityWait | null;
33
+ events: import("@opengeni/contracts").SessionEvent[];
34
+ } | {
35
+ action: "waiting";
36
+ waiter: import("@opengeni/db").CodexCapacityWait;
37
+ events: import("@opengeni/contracts").SessionEvent[];
38
+ } | {
39
+ action: "resumed";
40
+ waiter: import("@opengeni/db").CodexCapacityWait;
41
+ events: import("@opengeni/contracts").SessionEvent[];
42
+ } | {
43
+ action: "paused";
44
+ waiter: import("@opengeni/db").CodexCapacityWait;
45
+ events: import("@opengeni/contracts").SessionEvent[];
46
+ } | {
47
+ action: "superseded";
48
+ waiter: import("@opengeni/db").CodexCapacityWait;
49
+ events: import("@opengeni/contracts").SessionEvent[];
50
+ }>;
22
51
  export declare function createCodexCapacityActivities(services: () => Promise<ControlActivityServices>): {
23
52
  getCodexCapacityWait: (input: GetCodexCapacityWaitInput) => Promise<{
24
53
  provider?: "xai";
@@ -4,7 +4,7 @@ export declare const CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES: number;
4
4
  export type CodexFleetActualDecisionV1 = {
5
5
  outcome: "selected" | "waiting" | "none";
6
6
  candidateKey: string | null;
7
- reason: "lease_reused" | "pin" | "rotation" | "active" | "all_capped" | "none";
7
+ reason: "lease_reused" | "pin" | "rotation" | "active" | "all_capped" | "allocator_disabled" | "none";
8
8
  };
9
9
  export type CodexFleetShadowComparisonV1 = "match" | "different_candidate" | "different_outcome" | "not_comparable_truncated";
10
10
  export type CodexFleetShadowPayloadV1 = {
@@ -16,6 +16,6 @@ export declare function executeCodexImageGeneration(input: {
16
16
  prompt: string;
17
17
  references?: readonly ResolvedImageGenerationReference[];
18
18
  credentialId: string;
19
- codexContext: Pick<CodexRequestContext, "clientVersion" | "getToken" | "refresh">;
19
+ codexContext: Pick<CodexRequestContext, "clientVersion" | "getToken" | "refresh" | "beforeProviderDispatch">;
20
20
  abortSignal?: AbortSignal;
21
21
  }): Promise<GeneratedImageReceipt>;
@@ -51,9 +51,13 @@ export type RotationDecision = {
51
51
  } | {
52
52
  kind: "none";
53
53
  };
54
+ export type CodexTurnLeaseDecision = RotationDecision | {
55
+ kind: "allocatorDisabled";
56
+ credentialId: string;
57
+ };
54
58
  export type CodexTurnLeaseSelection = {
55
59
  credentialId: string | null;
56
- decision: RotationDecision;
60
+ decision: CodexTurnLeaseDecision;
57
61
  /** Policy/manual homes never move the workspace-global legacy pointer. */
58
62
  advanceActivePointer?: boolean;
59
63
  };
@@ -169,57 +173,6 @@ export declare function authoritativeCodexCapacityResetAt(accounts: CodexRotatio
169
173
  * earliestResetAt through this before returning continueDelayMs.
170
174
  */
171
175
  export declare function computeIdleDelayMs(earliestResetAt: Date, now: Date, maxMs: number): number;
172
- /**
173
- * Slow-retry floor (Finding 1a) for the double-fault where the just-served
174
- * account's cooldown write could NOT be confirmed persisted: the next proactive
175
- * rank might re-select the same capped account (stale-low cached usedPercent, not
176
- * cooling). A positive floor degrades that to a SLOW retry instead of a
177
- * model-paced hot loop. A few seconds — long enough to break the loop, short
178
- * enough to stay responsive once the transient write fault clears.
179
- */
180
- export declare const REACTIVE_PERSISTENCE_FAULT_FLOOR_MS = 5000;
181
- /**
182
- * Circuit-breaker slack (Finding 1b) added to the connected-account count to bound
183
- * consecutive reactive failovers. Each legitimate failover cools one account, so
184
- * after at most N failovers every account is capped and the reactive path takes the
185
- * all-capped idle instead; the +margin absorbs benign capacity re-ranks without
186
- * tripping the breaker in normal use.
187
- */
188
- export declare const REACTIVE_ROTATION_MARGIN = 2;
189
- /**
190
- * The FIXED positive idle the reactive path falls to once consecutive reactive
191
- * failovers exceed the bound (a double-fault where cooldown writes are not sticking
192
- * AND the 429s carry no usage headers, so the same account keeps getting re-picked).
193
- * Mirrors the all-capped floor — a mandatory, bounded hold, never another 0-delay
194
- * re-dispatch — so the loop can never hammer the capped backend + DB (invariant 4).
195
- */
196
- export declare const REACTIVE_CIRCUIT_BREAKER_IDLE_MS = 60000;
197
- /** The reactive-resume shape returned to the goal-continuation caller. */
198
- export type ReactiveRotationResume = {
199
- continueDelayMs: number;
200
- idleUntilReset: boolean;
201
- };
202
- /**
203
- * Decide the continueDelayMs for a reactive 429 failover onto a LIVE candidate,
204
- * bounding the (otherwise 0-delay) re-dispatch against two second-order faults:
205
- *
206
- * 1. Circuit breaker (1b): if the consecutive reactive-failover streak (prior
207
- * rotated 429 failovers since the last successful turn, PLUS this one) exceeds
208
- * `connectedAccountCount + REACTIVE_ROTATION_MARGIN`, fall to a FIXED positive,
209
- * MANDATORY idle. Covers the double-fault (cooldown write not persisted + a
210
- * header-less cap 429) where the same capped account is re-picked every turn.
211
- * 2. Persistence-fault floor (1a): if the just-served account's cooldown could NOT
212
- * be confirmed persisted, use a positive floor (slow retry) instead of 0.
213
- *
214
- * Otherwise (a confirmed cooldown + an in-bounds streak) returns the unchanged
215
- * 0-delay fast re-dispatch — the happy single-rotation path is byte-identical.
216
- * Pure so the boundedness contract is unit-testable without a worker/db env.
217
- */
218
- export declare function computeReactiveRotationResume(args: {
219
- cooldownPersisted: boolean;
220
- priorConsecutiveRotations: number;
221
- connectedAccountCount: number;
222
- }): ReactiveRotationResume;
223
176
  /**
224
177
  * THE pure rotation ranker. `accounts` arrives in stable created_at order
225
178
  * (listCodexAccountStatuses), which deterministically breaks ranking ties.
@@ -231,26 +184,14 @@ export declare function chooseRotationActive(args: {
231
184
  accounts: CodexRotationAccount[];
232
185
  now: Date;
233
186
  }): RotationDecision;
234
- /**
235
- * Exact pre-0053 selector used while the lease cutover is off.
236
- *
237
- * Old workers keep a healthy `most_remaining` active pointer sticky and know
238
- * nothing about lease counts or fairness cursors. A compatible worker must do
239
- * the same until BOTH the deployment flag and workspace cutover are enabled;
240
- * otherwise a rolling fleet would run two allocators at once. When the active
241
- * pointer is no longer eligible, zeroing the additive metadata delegates to the
242
- * same capacity ranking that the old selector used.
243
- */
244
- export declare function chooseLegacyRotationActive(args: Parameters<typeof chooseRotationActive>[0]): RotationDecision;
245
187
  /**
246
188
  * Full pure policy at the transaction boundary. A live same-turn lease is
247
- * idempotent; the rollout-off/manual path preserves pin>pointer behavior; a
189
+ * idempotent; manual and rotation-off policy preserve pin>pointer behavior; a
248
190
  * healthy pin wins only while eligible, so quota/auth quarantine cannot trap a
249
191
  * session on one subscription.
250
192
  */
251
- export declare function selectCodexCredentialLeaseForTurn(args: {
252
- context: CodexCredentialLeaseSelectionContext;
253
- leasingEnabled: boolean;
193
+ export declare function selectCodexCredentialLeaseForTurn<TPolicyScope = never, TUnavailableDiagnostic = never>(args: {
194
+ context: CodexCredentialLeaseSelectionContext<TPolicyScope, TUnavailableDiagnostic>;
254
195
  sessionId: string;
255
196
  sessionPinnedCredentialId: string | null;
256
197
  sessionPinSource: CodexPinSource | null;
@@ -17,7 +17,7 @@ export declare function goalContinuationModelDecision(input: {
17
17
  };
18
18
  export declare function goalContinuationFundedWithoutCredits(settings: Settings, model: string, codexBilled: boolean): boolean;
19
19
  export declare function goalContinuationPrompt(_goal: SessionGoal, _autoContinuation: number, _cap: number | null, options?: {
20
- goalWaitAvailable?: boolean;
20
+ inputWaitAvailable?: boolean;
21
21
  humanInputRespondAvailable?: boolean;
22
22
  }): string;
23
23
  /**
@@ -1,7 +1,7 @@
1
- import { type AttemptToolDefinition } from "@opengeni/codemode";
1
+ import type { AttemptToolDefinition } from "@opengeni/codemode";
2
2
  import type { McpPersonalConnectionDelegation } from "@opengeni/contracts";
3
3
  import { GOOGLE_DRIVE_FILE_SCOPE, GOOGLE_DRIVE_FULL_SCOPE, type GoogleDriveOutputDestination, type GoogleDrivePublicationReceipt as GoogleDrivePublicationReceiptValue, type GoogleDrivePublicationToolInput as GoogleDrivePublicationToolInputValue } from "@opengeni/contracts/google-drive";
4
- import { beginConnectorActionExecution, completeConnectorActionExecution, getConnectionMetadata, prepareConnectorActionApproval, requireFile, namedSubjectHasLiveWorkspaceAuthority, type ConnectorActionAttemptIdentity, type ConnectorActionInvocation, type Database, type ResolveConnectionCredentialInput, type ResolveConnectionCredentialResult } from "@opengeni/db";
4
+ import { getConnectionMetadata, requireFile, namedSubjectHasLiveWorkspaceAuthority, type ConnectorActionAttemptIdentity, type ConnectorActionInvocation, type Database, type ResolveConnectionCredentialInput, type ResolveConnectionCredentialResult } from "@opengeni/db";
5
5
  import { readAuthorizedEditableArtifactMaterialization } from "@opengeni/db/editable-artifact-durable-export";
6
6
  import { type FetchLike } from "@opengeni/network";
7
7
  import { type ObjectStorage } from "@opengeni/storage";
@@ -24,9 +24,6 @@ export type GoogleDrivePublicationPorts = {
24
24
  getMembership: typeof namedSubjectHasLiveWorkspaceAuthority;
25
25
  readMaterialization: typeof readAuthorizedEditableArtifactMaterialization;
26
26
  requireFile: typeof requireFile;
27
- prepare: typeof prepareConnectorActionApproval;
28
- begin: typeof beginConnectorActionExecution;
29
- complete: typeof completeConnectorActionExecution;
30
27
  fetch: FetchLike;
31
28
  };
32
29
  export declare function resolveGoogleDrivePublicationTarget(db: Database, workspace: {
@@ -44,14 +41,6 @@ export declare function createGoogleDrivePublicationAttemptTool(input: {
44
41
  signal?: AbortSignal;
45
42
  ports?: GoogleDrivePublicationPorts;
46
43
  }): AttemptToolDefinition;
47
- export declare function authorizeGoogleDrivePublicationAttempt(input: {
48
- db: Database;
49
- identity: ConnectorActionAttemptIdentity;
50
- target: GoogleDrivePublicationTarget;
51
- approvalId: string;
52
- arguments: unknown;
53
- ports?: Pick<GoogleDrivePublicationPorts, "prepare">;
54
- }): Promise<void>;
55
44
  export declare function executeGoogleDrivePublication(input: {
56
45
  db: Database;
57
46
  objectStorage: ObjectStorage;
@@ -1,4 +1,4 @@
1
- import { beginImageGenerationOperation, completeImageGenerationOperation, markImageGenerationOperationOutcomeUnknown, markImageGenerationOperationRetentionFailed, prepareImageGenerationOperation, type Database } from "@opengeni/db";
1
+ import { beginImageGenerationOperation, completeImageGenerationOperation, markImageGenerationOperationOutcomeUnknown, markImageGenerationOperationRetentionFailed, prepareImageGenerationOperation, resetImageGenerationOperationBeforeProviderDispatch, type Database } from "@opengeni/db";
2
2
  import type { ObjectStorage } from "@opengeni/storage";
3
3
  import { retainGeneratedImage, type GeneratedImageOutput, type GeneratedImageReceipt } from "./generated-images.js";
4
4
  export declare class ImageGenerationOutcomeUnknownError extends Error {
@@ -12,6 +12,7 @@ export declare class ImageGenerationRetentionFailedError extends Error {
12
12
  export type ImageGenerationOperationPorts = {
13
13
  prepare: typeof prepareImageGenerationOperation;
14
14
  begin: typeof beginImageGenerationOperation;
15
+ resetBeforeProviderDispatch: typeof resetImageGenerationOperationBeforeProviderDispatch;
15
16
  retain: typeof retainGeneratedImage;
16
17
  complete: typeof completeImageGenerationOperation;
17
18
  markOutcomeUnknown: typeof markImageGenerationOperationOutcomeUnknown;
@@ -21,9 +22,10 @@ export type ImageGenerationOperationPorts = {
21
22
  /**
22
23
  * Durable admission fence shared by every client-executed image provider.
23
24
  * Provider execution is permitted at most once after the prepared ->
24
- * provider_started transition. A crash at that boundary may conservatively
25
- * leave the outcome unknown; a retry may recover a ready artifact, but never
26
- * blindly replays the paid operation.
25
+ * provider_started transition. A verified pre-dispatch fence rejection returns
26
+ * the row to `prepared`; a crash or any error after dispatch admission may
27
+ * conservatively leave the outcome unknown. A retry may recover a ready
28
+ * artifact, but never blindly replays an admitted paid operation.
27
29
  */
28
30
  export type ExecuteImageGenerationOperationInput = {
29
31
  db: Database;
@@ -42,6 +44,13 @@ export type ExecuteImageGenerationOperationInput = {
42
44
  mediaType: string;
43
45
  sha256: string;
44
46
  }>[];
47
+ /**
48
+ * Provider-specific proof that a thrown error occurred before the paid
49
+ * provider boundary was crossed. Such a failure may return the operation to
50
+ * `prepared`; every other generation error remains outcome-ambiguous after
51
+ * `provider_started` and is never blindly replayed.
52
+ */
53
+ isProviderDispatchRejected?: (error: unknown) => boolean;
45
54
  generate: () => Promise<GeneratedImageOutput>;
46
55
  };
47
56
  export declare function executeImageGenerationOperation(input: ExecuteImageGenerationOperationInput, ports?: ImageGenerationOperationPorts): Promise<GeneratedImageReceipt>;
@@ -1,8 +1,8 @@
1
- import { settleSessionAttemptInterruptions, applySessionTurnSettlement, enqueueSessionWorkflowWake, failSessionWorkBeforeAttemptClaim, requestSessionTurnRecovery, recoverSessionDispatch, reconcileSessionAttemptQuiescence, peekSessionWork as peekSessionWorkDb, countQueuedTurns, getSessionAttemptActivityRef, getSessionEvent, getSessionTurnForAttempt, expireSessionInteractionIntervention as expireSessionInteractionInterventionDb, expireSessionHumanInputRequest, markSessionAttemptQuiesced, requireSession, settleSessionIdleWithParentOutbox } from "@opengeni/db";
1
+ import { settleSessionAttemptInterruptions, applySessionTurnSettlement, enqueueSessionWorkflowWake, failSessionWorkBeforeAttemptClaim, requestSessionTurnRecovery, recoverSessionDispatch, reconcileSessionAttemptQuiescence, peekSessionWork as peekSessionWorkDb, settleSessionInputWait as settleSessionInputWaitDb, countQueuedTurns, getSessionAttemptActivityRef, getSessionEvent, getSessionTurnForAttempt, expireSessionInteractionIntervention as expireSessionInteractionInterventionDb, expireSessionHumanInputRequest, markSessionAttemptQuiesced, requireSession, settleSessionIdleWithParentOutbox } from "@opengeni/db";
2
2
  import { publishDurableSessionEvents } from "@opengeni/events";
3
3
  import { deliverFailedChildTurnToParent, notifyParentOfChildIdle } from "./parent-wake.js";
4
4
  import { recordTurnsQueuedGauge, recordWorkerDeathRecoveryMetrics } from "../observability-metrics.js";
5
- import type { ControlActivityServices, ExpireSessionHumanInputInput, ExpireSessionHumanInputResult, ExpireSessionInteractionInterventionInput, ExpireSessionInteractionInterventionResult, PeekSessionWorkInput, FailSessionAttemptInput, FailSessionAttemptResult, SettleSessionInterruptionsInput, MarkSessionIdleInput, PersistSessionAttemptQuiescenceInput, ReconcileSessionAttemptQuiescenceInput, ReconcileSessionAttemptQuiescenceResult, RecoverDispatchInput, RecoverDispatchResult, RecoverEscapedMcpTimeoutInput, RecoverEscapedMcpTimeoutResult } from "./types.js";
5
+ import type { ControlActivityServices, ExpireSessionHumanInputInput, ExpireSessionHumanInputResult, ExpireSessionInteractionInterventionInput, ExpireSessionInteractionInterventionResult, PeekSessionWorkInput, FailSessionAttemptInput, FailSessionAttemptResult, SettleSessionInterruptionsInput, MarkSessionIdleInput, PersistSessionAttemptQuiescenceInput, ReconcileSessionAttemptQuiescenceInput, ReconcileSessionAttemptQuiescenceResult, RecoverDispatchInput, RecoverDispatchResult, RecoverEscapedMcpTimeoutInput, RecoverEscapedMcpTimeoutResult, SettleSessionInputWaitInput, SettleSessionInputWaitResult } from "./types.js";
6
6
  export type SessionStateActivityOverrides = Partial<{
7
7
  settleSessionAttemptInterruptions: typeof settleSessionAttemptInterruptions;
8
8
  applySessionTurnSettlement: typeof applySessionTurnSettlement;
@@ -12,6 +12,7 @@ export type SessionStateActivityOverrides = Partial<{
12
12
  recoverSessionDispatch: typeof recoverSessionDispatch;
13
13
  reconcileSessionAttemptQuiescence: typeof reconcileSessionAttemptQuiescence;
14
14
  peekSessionWork: typeof peekSessionWorkDb;
15
+ settleSessionInputWait: typeof settleSessionInputWaitDb;
15
16
  countQueuedTurns: typeof countQueuedTurns;
16
17
  getSessionAttemptActivityRef: typeof getSessionAttemptActivityRef;
17
18
  getSessionEvent: typeof getSessionEvent;
@@ -38,6 +39,7 @@ export declare function createSessionStateActivities(services: () => Promise<Con
38
39
  recoverDispatch: (input: RecoverDispatchInput) => Promise<RecoverDispatchResult>;
39
40
  recoverEscapedMcpTimeout: (input: RecoverEscapedMcpTimeoutInput) => Promise<RecoverEscapedMcpTimeoutResult>;
40
41
  peekSessionWork: (input: PeekSessionWorkInput) => Promise<import("@opengeni/db").SessionWorkPeek>;
42
+ settleSessionInputWait: (input: SettleSessionInputWaitInput) => Promise<SettleSessionInputWaitResult>;
41
43
  expireSessionHumanInput: (input: ExpireSessionHumanInputInput) => Promise<ExpireSessionHumanInputResult>;
42
44
  expireSessionInteractionIntervention: (input: ExpireSessionInteractionInterventionInput) => Promise<ExpireSessionInteractionInterventionResult>;
43
45
  markSessionIdle: (input: MarkSessionIdleInput) => Promise<void>;
@@ -272,6 +272,16 @@ export type PeekSessionWorkInput = {
272
272
  workspaceId: string;
273
273
  sessionId: string;
274
274
  };
275
+ export type SettleSessionInputWaitInput = {
276
+ accountId: string;
277
+ workspaceId: string;
278
+ sessionId: string;
279
+ waitTurnId: string;
280
+ disposition: "held" | "timeout" | "superseded";
281
+ };
282
+ export type SettleSessionInputWaitResult = {
283
+ action: "held" | "timeout" | "superseded" | "stale";
284
+ };
275
285
  export type ExpireSessionHumanInputInput = {
276
286
  accountId: string;
277
287
  workspaceId: string;
@@ -301,7 +311,7 @@ export type MaybeContinueGoalInput = {
301
311
  workflowId: string;
302
312
  };
303
313
  export type MaybeContinueGoalResult = {
304
- action: "none" | "queue" | "continue" | "paused" | "held" | "deferred";
314
+ action: "none" | "queue" | "continue" | "paused" | "deferred";
305
315
  };
306
316
  export type DispatchScheduledTaskRunInput = {
307
317
  workspaceId: string;