@opengeni/worker-bundle 0.24.2-canary.0 → 0.26.0-canary.1

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 (83) 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 +6 -5
  5. package/dist/activities/agent-turn/failure-settlement.d.ts +43 -1
  6. package/dist/activities/agent-turn/history-prefix.d.ts +8 -0
  7. package/dist/activities/agent-turn/history-sink.d.ts +6 -2
  8. package/dist/activities/agent-turn/quiescence.d.ts +13 -8
  9. package/dist/activities/agent-turn/tool-environment.d.ts +2 -13
  10. package/dist/activities/agent-turn/tool-policy.d.ts +4 -0
  11. package/dist/activities/agent-turn/turn-context.d.ts +9 -1
  12. package/dist/activities/codemode-dispatcher.d.ts +10 -1
  13. package/dist/activities/codex-capacity.d.ts +32 -3
  14. package/dist/activities/codex-fleet-shadow.d.ts +1 -1
  15. package/dist/activities/codex-image-generation.d.ts +1 -1
  16. package/dist/activities/codex-rotation.d.ts +8 -67
  17. package/dist/activities/goals.d.ts +1 -1
  18. package/dist/activities/google-drive-publication.d.ts +2 -13
  19. package/dist/activities/image-generation-operation.d.ts +13 -4
  20. package/dist/activities/sandbox-lease.d.ts +7 -2
  21. package/dist/activities/session-state.d.ts +4 -2
  22. package/dist/activities/types.d.ts +11 -1
  23. package/dist/activities/xai-quota.d.ts +3 -0
  24. package/dist/{activities-control-ZWH7J4KZ.js → activities-control-KS3ZPQVY.js} +233 -88
  25. package/dist/activities-control-KS3ZPQVY.js.map +1 -0
  26. package/dist/activities-control.d.ts +2 -0
  27. package/dist/{activities-turn-I4OPLQLS.js → activities-turn-GHSFZB64.js} +1109 -1865
  28. package/dist/activities-turn-GHSFZB64.js.map +1 -0
  29. package/dist/activities.d.ts +2 -0
  30. package/dist/{chunk-65JEWP2Q.js → chunk-D4ZEFOYH.js} +1 -1
  31. package/dist/chunk-D4ZEFOYH.js.map +1 -0
  32. package/dist/{chunk-RQNH6CGR.js → chunk-O2LQWJIK.js} +3250 -2061
  33. package/dist/chunk-O2LQWJIK.js.map +1 -0
  34. package/dist/github-rest-mcp.d.ts +0 -2
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.js +2 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/observability-metrics.d.ts +1 -1
  39. package/dist/sandbox-routing.d.ts +6 -0
  40. package/dist/workflow-bundle.js +94 -9
  41. package/dist/workflows/activities.d.ts +1 -1
  42. package/dist/workflows/session.d.ts +3 -0
  43. package/package.json +17 -17
  44. package/src/activities/agent-turn/agent-build.ts +21 -26
  45. package/src/activities/agent-turn/claim.ts +26 -1
  46. package/src/activities/agent-turn/codex-capacity.ts +311 -234
  47. package/src/activities/agent-turn/credential-leases.ts +36 -0
  48. package/src/activities/agent-turn/errors.ts +73 -12
  49. package/src/activities/agent-turn/failure-settlement.ts +472 -331
  50. package/src/activities/agent-turn/history-prefix.ts +51 -0
  51. package/src/activities/agent-turn/history-sink.ts +30 -6
  52. package/src/activities/agent-turn/quiescence.ts +29 -17
  53. package/src/activities/agent-turn/run.ts +22 -5
  54. package/src/activities/agent-turn/stream-attempt.ts +35 -8
  55. package/src/activities/agent-turn/tool-environment.ts +42 -32
  56. package/src/activities/agent-turn/tool-policy.ts +14 -8
  57. package/src/activities/agent-turn/turn-context.ts +13 -0
  58. package/src/activities/agent-turn/xai-capacity.ts +11 -0
  59. package/src/activities/codemode-dispatcher.ts +235 -59
  60. package/src/activities/codex-capacity.ts +107 -10
  61. package/src/activities/codex-fleet-shadow.ts +8 -1
  62. package/src/activities/codex-image-generation.ts +19 -2
  63. package/src/activities/codex-rotation.ts +45 -142
  64. package/src/activities/goals.ts +9 -9
  65. package/src/activities/google-drive-publication.ts +4 -81
  66. package/src/activities/image-generation-operation.ts +28 -3
  67. package/src/activities/run-input.ts +6 -7
  68. package/src/activities/sandbox-lease.ts +246 -87
  69. package/src/activities/session-state.ts +20 -1
  70. package/src/activities/types.ts +16 -8
  71. package/src/activities/xai-quota.ts +35 -0
  72. package/src/activities.ts +1 -0
  73. package/src/github-rest-mcp.ts +0 -82
  74. package/src/observability-metrics.ts +4 -0
  75. package/src/sandbox-routing.ts +186 -16
  76. package/src/workflows/activities.ts +1 -0
  77. package/src/workflows/session.ts +114 -8
  78. package/dist/activities/api-integrations.d.ts +0 -21
  79. package/dist/activities-control-ZWH7J4KZ.js.map +0 -1
  80. package/dist/activities-turn-I4OPLQLS.js.map +0 -1
  81. package/dist/chunk-65JEWP2Q.js.map +0 -1
  82. package/dist/chunk-RQNH6CGR.js.map +0 -1
  83. 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;
@@ -67,10 +67,11 @@ export declare function escapedMcpTimeoutRecoveryFailure(input: {
67
67
  * Convert the atomic claim transaction's failure into a small, stable
68
68
  * Temporal wire contract. The original error remains in activity diagnostics,
69
69
  * but SQL text, parameters, and arbitrary invariant messages never enter
70
- * workflow history. Contention and operational database unavailability are
71
- * safe to re-read after backoff because the claim transaction contains no
72
- * model/tool effects; permanent database and state failures require terminal
73
- * settlement.
70
+ * workflow history. Every database failure is safe to re-read after backoff
71
+ * because the claim transaction contains no model/tool effects. Database
72
+ * constraints and authorization guards can also be repaired by a deployment or
73
+ * authority refresh, so they must preserve pending work. Only a non-database
74
+ * claim invariant is terminal.
74
75
  */
75
76
  export declare function preClaimAdmissionFailure(error: unknown): ApplicationFailure;
76
77
  /**
@@ -280,7 +281,7 @@ export declare function codexUsageLimitFailurePayload(info: {
280
281
  }): {
281
282
  error: string;
282
283
  code: string;
283
- retryable: boolean;
284
+ retryable: false;
284
285
  detail?: string;
285
286
  };
286
287
  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 {};
@@ -0,0 +1,8 @@
1
+ /** A position is an append cursor only while the items before it stay identical. */
2
+ export declare class HistoryPrefixGuard {
3
+ private persisted;
4
+ seed(items: Array<Record<string, unknown>>, count: number, truncationTokens?: number): void;
5
+ verify(items: Array<Record<string, unknown>>, truncationTokens?: number): string[];
6
+ acknowledge(keys: string[], count: number): void;
7
+ private keys;
8
+ }
@@ -19,8 +19,8 @@ export type TurnHistorySinkDeps = {
19
19
  * Dual-write of conversation truth (issue #35): completed items are reconciled
20
20
  * into session_history_items after every model response and at every turn-end
21
21
  * path (idempotent on position), and the sandbox recovery envelope is upserted
22
- * alongside. Best-effort by design: persistence problems must never fail the
23
- * run.
22
+ * alongside. Provider dispatch and settlement require durable persistence;
23
+ * the prefix guard rejects SDK history removal/reordering before slicing.
24
24
  *
25
25
  * Orphaned-tool-output guard: `stream.state.history` is NOT a plain
26
26
  * append-only array — it is a computed getter
@@ -40,6 +40,10 @@ export type TurnHistorySinkDeps = {
40
40
  */
41
41
  export declare class TurnHistorySink {
42
42
  private readonly deps;
43
+ private readonly prefix;
44
+ seedHistory(input: string | readonly unknown[] | {
45
+ readonly history: unknown[];
46
+ }, count: number): void;
43
47
  persistedHistoryCount: number;
44
48
  nextHistoryPosition: number;
45
49
  providerArtifactCandidates: Awaited<ReturnType<typeof turnInput>>["providerArtifactCandidates"];
@@ -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:
@@ -139,8 +142,10 @@ export declare function assertSuccessfulAgentStreamCompletion(input: {
139
142
  /** Call after any more-specific empty-stream recovery has had priority. */
140
143
  export declare function assertAgentStreamNotCancelled(cancelled: boolean): void;
141
144
  /** Interruption streams do not produce a normal final output. Call this only
142
- * after the interruption branch has settled any required action. */
143
- export declare function requireAgentStreamFinalOutput(finalOutput: unknown | undefined): unknown;
145
+ * after the interruption branch has settled any required action. A successful
146
+ * runtime-owned input wait is a normal terminal result without assistant text;
147
+ * its authority comes from prepared tools, never the provider's output. */
148
+ export declare function requireAgentStreamFinalOutput(finalOutput: unknown | undefined, inputWaitYielded?: boolean): unknown;
144
149
  /**
145
150
  * Terminal settlement closes the active attempt before turn finalization. The
146
151
  * ordinary workspace admission therefore correctly returns `attempt_fenced`
@@ -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>;
@@ -94,7 +94,7 @@ export type RetainedProcessProbeResult = {
94
94
  status: "deferred";
95
95
  reason: "identity_mismatch" | "resume_state_missing" | "backend_unsupported" | "provider_running" | "provider_unknown" | "provider_timeout" | "provider_error" | "provider_binding_missing" | "provider_binding_mismatch";
96
96
  };
97
- export type RetainedProcessProbeFn = (settings: ActivityServices["settings"], lease: LeaseSnapshot, process: SandboxRetainedProcess, mode?: "observe" | "cancel") => Promise<RetainedProcessProbeResult>;
97
+ export type RetainedProcessProbeFn = (settings: ActivityServices["settings"], lease: LeaseSnapshot, process: SandboxRetainedProcess, mode?: "observe" | "cancel", captureOutput?: (result: unknown, chunkId: string) => Promise<void>) => Promise<RetainedProcessProbeResult>;
98
98
  export type HistoricalModalSandboxLifecycleProbeFn = typeof inspectModalSandboxLifecycle;
99
99
  export type DrainableProviderProbeFn = (settings: ActivityServices["settings"], lease: LeaseSnapshot) => Promise<"ready" | "missing">;
100
100
  export declare const RETAINED_PROCESS_RECONCILIATION_LIMIT = 20;
@@ -141,6 +141,10 @@ export declare function createSandboxLeaseActivities(services: () => Promise<Act
141
141
  maintainSandboxLeaseSweep: (input: SandboxLeaseSweepMaintenanceInput) => Promise<SandboxLeaseSweepMaintenanceResult>;
142
142
  reapSandboxLeases: () => Promise<ReapSandboxLeasesResult>;
143
143
  };
144
+ /** Reconcile commands only against the immutable physical locator copied at
145
+ * adoption. A successor enrollment connection is intentionally irrelevant: no
146
+ * query or cancellation is ever rebound to it. */
147
+ export declare function reconcileConnectedMachineBackgroundCommands(db: ActivityServices["db"], settings: ActivityServices["settings"], observability: ActivityServices["observability"], bus: ActivityServices["bus"], controlRpcOverride?: ControlRpc): Promise<void>;
144
148
  export declare function probeConnectedMachineBackgroundCommand(claim: ConnectedMachineBackgroundCommandClaim, controlRpc: ControlRpc, controlTimeoutMs: number, observedAt?: Date): Promise<ConnectedMachineBackgroundCommandProof | null>;
145
149
  export declare function connectedCommandProofFromStatus(status: OpStatus, observedAt: Date): ConnectedMachineBackgroundCommandProof | null;
146
150
  type RetainedProcessDeferralOutcome = Extract<RetainedProcessProbeResult, {
@@ -152,7 +156,8 @@ export declare function retainedProcessReconciliationDeferral(settings: Pick<Act
152
156
  retryAfterMs: number;
153
157
  quarantined: boolean;
154
158
  };
155
- export declare function probeRetainedProcessAtProvider(settings: ActivityServices["settings"], lease: LeaseSnapshot, process: SandboxRetainedProcess, mode?: "observe" | "cancel"): Promise<RetainedProcessProbeResult>;
159
+ export declare function captureRetainedProbeOutput(processId: string, result: unknown, capture: (result: unknown, chunkId: string) => Promise<void>): Promise<void>;
160
+ export declare function probeRetainedProcessAtProvider(settings: ActivityServices["settings"], lease: LeaseSnapshot, process: SandboxRetainedProcess, mode?: "observe" | "cancel", captureOutput?: (result: unknown, chunkId: string) => Promise<void>): Promise<RetainedProcessProbeResult>;
156
161
  /** Classify only exact SDK control banners. Arbitrary output, malformed text,
157
162
  * and a running marker are observations to retry; none is physical exit proof. */
158
163
  export declare function classifyRetainedProcessPollResult(result: unknown, providerSessionId: number): RetainedProcessProbeResult;