@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,17 +1,10 @@
1
1
  import {
2
2
  requestSessionTurnRecovery,
3
3
  getSessionGoal,
4
- armCodexCapacityWait,
5
4
  armXaiCapacityWait,
6
5
  reconcileXaiCapacityWait,
7
- getCodexRotationSettings,
8
6
  listCodexAccountStatuses,
9
- getSessionCodexState,
10
- setSessionCodexPinInTransaction,
11
7
  quarantineCodexCredentialForLease,
12
- setCodexCredentialExhaustedWithWakeTargets,
13
- withSessionCodexCapacityMutation,
14
- countConsecutiveReactiveRotations,
15
8
  recordUsageEvent,
16
9
  getActiveSessionHistoryItemsPaged,
17
10
  settleCodexCredentialLeaseLoss,
@@ -19,21 +12,17 @@ import {
19
12
  readLease,
20
13
  SandboxLeaseSupersededError,
21
14
  isSessionEventPersistenceError,
15
+ type CodexLeaseAccountStatus,
22
16
  } from "@opengeni/db";
23
17
  import { publishDurableSessionEvents } from "@opengeni/events";
24
18
  import { maxTurnsExceededRunState } from "@opengeni/runtime";
25
19
  import { CancelledFailure } from "@temporalio/activity";
26
20
  import {
27
21
  authoritativeCodexCapacityResetAt,
28
- chooseRotationActive,
29
22
  classifyCodexPin,
30
- computeIdleDelayMs,
31
- computeReactiveRotationResume,
32
- shardCredentialForSession,
33
- earliestCodexReset,
23
+ selectCodexCredentialLeaseForTurn,
34
24
  type CodexRotationStrategy,
35
25
  } from "../codex-rotation";
36
- import { signalCodexCapacityWakeTargets } from "../codex-capacity";
37
26
  import type { Settings } from "@opengeni/config";
38
27
  import {
39
28
  classifyCodexEncryptedArtifactRejection,
@@ -48,7 +37,7 @@ import type {
48
37
  RunAgentTurnInput,
49
38
  RunAgentTurnResult,
50
39
  } from "../types";
51
- import { createTurnCredentialLeases } from "./credential-leases";
40
+ import { CodexCredentialLeaseLostError, createTurnCredentialLeases } from "./credential-leases";
52
41
  import { createTurnHistorySink } from "./history-sink";
53
42
 
54
43
  import { BudgetExhaustedError } from "./admission";
@@ -68,7 +57,6 @@ import {
68
57
  codexCredentialCooldownUntil,
69
58
  classifyCodexCredentialFailure,
70
59
  codexUsageLimitFailurePayload,
71
- CODEX_USAGE_LIMIT_MAX_RESUME_MS,
72
60
  } from "./errors";
73
61
  import { selectRejectedProviderArtifactHistoryIds } from "./history";
74
62
  import { waitForTurnFinalizerStep, turnFinalizerCancellationSignal } from "./quiescence";
@@ -84,6 +72,8 @@ import type {
84
72
  ProviderTurnState,
85
73
  TurnControlState,
86
74
  } from "./turn-context";
75
+ import type { CodexCredentialPolicySnapshotV1 } from "@opengeni/contracts";
76
+ import { armAndReconcileCodexCapacityWait } from "../codex-capacity";
87
77
 
88
78
  export type TurnFailureDeps = {
89
79
  error: unknown;
@@ -93,7 +83,6 @@ export type TurnFailureDeps = {
93
83
  bus: ActivityServices["bus"];
94
84
  observability: ActivityServices["observability"];
95
85
  wakeSessionWorkflow: ActivityServices["wakeSessionWorkflow"];
96
- signalCodexCapacityWorkflow: ActivityServices["signalCodexCapacityWorkflow"];
97
86
  cancellationSignal: AbortSignal | undefined;
98
87
  sandboxRotationController: AbortController;
99
88
  noteCancellationRequested: () => void;
@@ -116,6 +105,125 @@ export type TurnFailureDeps = {
116
105
  acknowledgeRecoveryQuiescence: () => void;
117
106
  };
118
107
 
108
+ export type CodexDefinitiveFailureDisposition = "failover" | "wait" | "terminal";
109
+
110
+ type CodexCapacityWaitFailurePayload = {
111
+ error: string;
112
+ code: string;
113
+ detail?: string;
114
+ retryable: false;
115
+ };
116
+
117
+ /**
118
+ * Pure policy for a definitive serving-credential refusal. A policy-constrained
119
+ * account and an all-unavailable pool wait for the same selected capacity to
120
+ * recover; only a truly empty/non-allocatable pool makes an auth/forbidden
121
+ * failure terminal. A different eligible account under rotation-on policy may
122
+ * recover the same durable turn immediately.
123
+ */
124
+ export function codexDefinitiveFailureDisposition(input: {
125
+ failureKind: "auth" | "forbidden" | "rate_limit" | "quota";
126
+ rotationEnabled: boolean;
127
+ pinDisposition: "manual" | "sharded" | "clearStale" | "unpinned";
128
+ decisionKind: "active" | "allCapped" | "none";
129
+ decisionCredentialId: string | null;
130
+ servingCredentialId: string;
131
+ }): CodexDefinitiveFailureDisposition {
132
+ const alternateAvailable =
133
+ input.rotationEnabled &&
134
+ input.pinDisposition !== "manual" &&
135
+ input.decisionKind === "active" &&
136
+ input.decisionCredentialId !== null &&
137
+ input.decisionCredentialId !== input.servingCredentialId;
138
+ if (alternateAvailable) return "failover";
139
+ if (
140
+ input.failureKind === "quota" ||
141
+ input.failureKind === "rate_limit" ||
142
+ input.decisionKind === "allCapped" ||
143
+ !input.rotationEnabled ||
144
+ input.pinDisposition === "manual"
145
+ ) {
146
+ return "wait";
147
+ }
148
+ return "terminal";
149
+ }
150
+
151
+ /**
152
+ * Bound one turn to the alternate credentials that policy actually permits.
153
+ * The effective account list is already workspace/organization scoped;
154
+ * allocator-disabled rows must not enlarge the retry budget. The database
155
+ * requires a positive bound even though one-account paths never fail over.
156
+ */
157
+ export function codexCredentialFailoverLimit(
158
+ accounts: ReadonlyArray<{ id: string; allocatorEnabled: boolean }>,
159
+ servingCredentialId: string,
160
+ ): number {
161
+ const allocatableAccounts = accounts.filter((account) => account.allocatorEnabled).length;
162
+ const servingIsAllocatable = accounts.some(
163
+ (account) => account.id === servingCredentialId && account.allocatorEnabled,
164
+ );
165
+ return Math.max(1, allocatableAccounts - (servingIsAllocatable ? 1 : 0));
166
+ }
167
+
168
+ /** Build the durable waiter payload without collapsing quota refusals into 403. */
169
+ export function codexCapacityWaitFailurePayload(input: {
170
+ failureKind: "auth" | "forbidden" | "rate_limit" | "quota";
171
+ usageLimit: { resetsInSeconds: number | null } | null;
172
+ cooldownSeconds: number | null;
173
+ detail: string;
174
+ allAccounts: boolean;
175
+ }): CodexCapacityWaitFailurePayload {
176
+ if (input.failureKind === "quota") {
177
+ return codexUsageLimitFailurePayload(
178
+ input.usageLimit ?? { resetsInSeconds: input.cooldownSeconds },
179
+ input.detail,
180
+ input.allAccounts ? { allAccounts: true } : undefined,
181
+ );
182
+ }
183
+ if (input.failureKind === "rate_limit") {
184
+ return {
185
+ error: "The serving Codex subscription is temporarily rate limited.",
186
+ code: "codex_account_rate_limited",
187
+ detail: input.detail,
188
+ retryable: false,
189
+ };
190
+ }
191
+ if (input.failureKind === "auth") {
192
+ return {
193
+ error: "The serving Codex account requires reconnection.",
194
+ code: "codex_relogin_required",
195
+ detail: "the same accepted turn is waiting for the selected account to recover",
196
+ retryable: false,
197
+ };
198
+ }
199
+ return {
200
+ error: "The serving Codex account is not authorized for this request.",
201
+ code: "codex_account_forbidden",
202
+ detail: "the same accepted turn is waiting for the selected account to recover",
203
+ retryable: false,
204
+ };
205
+ }
206
+
207
+ function codexLeaseAccountsForSelection(
208
+ accounts: Awaited<ReturnType<typeof listCodexAccountStatuses>>,
209
+ ): CodexLeaseAccountStatus[] {
210
+ return accounts.map((account) => ({
211
+ ...account,
212
+ activeLeaseCount: 0,
213
+ selectionCount: 0,
214
+ lastSelectedAt: null,
215
+ }));
216
+ }
217
+
218
+ function acceptedCodexPolicySnapshot(
219
+ providerTurn: ProviderTurnState,
220
+ ): CodexCredentialPolicySnapshotV1 {
221
+ if (!providerTurn.codexPolicySnapshot) {
222
+ throw new Error("Codex accepted policy snapshot is missing after durable lease acquisition");
223
+ }
224
+ return providerTurn.codexPolicySnapshot;
225
+ }
226
+
119
227
  export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgentTurnResult> {
120
228
  const {
121
229
  error,
@@ -125,7 +233,6 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
125
233
  bus,
126
234
  observability,
127
235
  wakeSessionWorkflow,
128
- signalCodexCapacityWorkflow,
129
236
  cancellationSignal,
130
237
  sandboxRotationController,
131
238
  noteCancellationRequested,
@@ -508,8 +615,7 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
508
615
  // recoverable, but a successor attempt or worker recovery makes this activity
509
616
  // stale and unable to clobber the shared turn/session.
510
617
  if (
511
- leases.codex.lost &&
512
- settings.codexCredentialLeasingEnabled &&
618
+ (leases.codex.lost || error instanceof CodexCredentialLeaseLostError) &&
513
619
  billingState.isCodexTurn &&
514
620
  eventing.publish &&
515
621
  attempt.turnId &&
@@ -558,10 +664,9 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
558
664
  // malformed/partial 200 stream, invalid content, prompt 4xx, or provider
559
665
  // 5xx does not classify here and therefore cannot consume another
560
666
  // subscription or duplicate a side effect.
667
+ const usageLimit = isCodexTransportError(error) ? classifyCodexUsageLimitError(error) : null;
561
668
  const codexCredentialFailure =
562
- settings.codexCredentialLeasingEnabled &&
563
- billingState.isCodexTurn &&
564
- providerTurn.effectiveCodexCredentialId
669
+ billingState.isCodexTurn && providerTurn.effectiveCodexCredentialId
565
670
  ? classifyCodexCredentialFailure(error)
566
671
  : null;
567
672
  if (
@@ -625,15 +730,26 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
625
730
  }
626
731
  : null;
627
732
  const cooldownUntil = codexCredentialCooldownUntil(codexCredentialFailure, serving, now);
628
- const statePersisted =
629
- leases.codex.holderId && leases.codex.generation !== null
733
+ const quarantineResult =
734
+ leases.codex.holderId &&
735
+ leases.codex.generation !== null &&
736
+ providerTurn.effectiveCodexCredentialVersion !== null
630
737
  ? await quarantineCodexCredentialForLease(db, {
631
738
  accountId: input.accountId,
632
739
  workspaceId: input.workspaceId,
740
+ sessionId: input.sessionId,
633
741
  turnId: attempt.turnId,
742
+ attemptId: input.attemptId,
743
+ executionGeneration: attempt.executionGeneration,
744
+ workflowId: input.workflowId,
745
+ workflowRunId: input.workflowRunId,
746
+ dispatchId: attempt.dispatchId,
747
+ expectedRedispatches: attempt.redispatchesAtDispatch,
634
748
  credentialId: providerTurn.effectiveCodexCredentialId,
749
+ credentialVersion: providerTurn.effectiveCodexCredentialVersion,
635
750
  holderId: leases.codex.holderId,
636
751
  generation: leases.codex.generation,
752
+ maxFailovers: providerTurn.codexCredentialFailoverLimit,
637
753
  quarantine:
638
754
  codexCredentialFailure.kind === "auth"
639
755
  ? {
@@ -653,7 +769,46 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
653
769
  cooldownKind: codexCredentialFailure.kind,
654
770
  },
655
771
  })
656
- : false;
772
+ : null;
773
+ if (
774
+ quarantineResult?.action === "credential_changed" &&
775
+ leases.codex.holderId &&
776
+ leases.codex.generation !== null
777
+ ) {
778
+ const recovery = await settleCodexCredentialLeaseLoss(db, {
779
+ accountId: input.accountId,
780
+ workspaceId: input.workspaceId,
781
+ sessionId: input.sessionId,
782
+ turnId: attempt.turnId,
783
+ attemptId: input.attemptId,
784
+ holderId: leases.codex.holderId,
785
+ generation: leases.codex.generation,
786
+ expectedRedispatches: attempt.redispatchesAtDispatch,
787
+ checkpointDurable: true,
788
+ recoveryPayload: {
789
+ triggerEventId: attempt.triggerEventId!,
790
+ reason: "codex_credential_version_changed",
791
+ },
792
+ failedPayload: {},
793
+ });
794
+ if (recovery.action === "recovering") {
795
+ leases.codex.held = false;
796
+ await publishDurableSessionEvents(
797
+ bus,
798
+ input.workspaceId,
799
+ input.sessionId,
800
+ recovery.events,
801
+ );
802
+ control.activityStatus = "recovering";
803
+ control.turnMetricOutcome = "recovering";
804
+ return claimedResult({ status: "recovering" });
805
+ }
806
+ acknowledgeLostAttemptOwnership();
807
+ control.activityStatus = "cancelled";
808
+ control.turnMetricOutcome = "cancelled";
809
+ return claimedResult({ status: "cancelled" });
810
+ }
811
+ const statePersisted = quarantineResult?.action === "recorded";
657
812
  if (!statePersisted && leases.codex.holderId && leases.codex.generation !== null) {
658
813
  leases.codex.lost = true;
659
814
  return await settleLostCodexAttempt(
@@ -663,26 +818,129 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
663
818
  true,
664
819
  );
665
820
  }
666
- const [rotation, accounts] = await Promise.all([
667
- getCodexRotationSettings(db, input.workspaceId).catch(() => null),
668
- listCodexAccountStatuses(db, input.workspaceId).catch(() => []),
669
- ]);
670
- const decision = rotation
671
- ? chooseRotationActive({
672
- rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,
673
- activeCredentialId: rotation.activeCredentialId,
674
- priorCredentialId: providerTurn.effectiveCodexCredentialId,
675
- accounts,
676
- now: new Date(),
677
- })
678
- : ({ kind: "none" } as const);
679
- const candidateAvailable =
680
- statePersisted &&
681
- Boolean(rotation?.rotationEnabled && rotation?.leaseRotationEnabled) &&
682
- decision.kind === "active" &&
683
- decision.credentialId !== providerTurn.effectiveCodexCredentialId;
821
+ if (
822
+ quarantineResult?.action === "recorded" &&
823
+ quarantineResult.exhausted &&
824
+ leases.codex.holderId &&
825
+ leases.codex.generation !== null
826
+ ) {
827
+ const settlement = await settleCodexCredentialFailover(db, {
828
+ accountId: input.accountId,
829
+ workspaceId: input.workspaceId,
830
+ sessionId: input.sessionId,
831
+ turnId: attempt.turnId,
832
+ attemptId: input.attemptId,
833
+ holderId: leases.codex.holderId,
834
+ generation: leases.codex.generation,
835
+ expectedRedispatches: attempt.redispatchesAtDispatch,
836
+ maxFailovers: quarantineResult.maxFailovers,
837
+ recoveryPayload: {
838
+ triggerEventId: attempt.triggerEventId!,
839
+ reason: "codex_credential_failover",
840
+ credentialId: providerTurn.effectiveCodexCredentialId,
841
+ failureKind: codexCredentialFailure.kind,
842
+ },
843
+ failedPayload: {
844
+ error:
845
+ "Automatic Codex credential failover stopped after every bounded account attempt was consumed. Send a new message after checking account health or capacity.",
846
+ code: "codex_credential_failover_exhausted",
847
+ retryable: false,
848
+ recovery: "user_message",
849
+ failoverCount: quarantineResult.failoverCount,
850
+ maxFailovers: quarantineResult.maxFailovers,
851
+ },
852
+ });
853
+ if (settlement.action === "limit_exceeded") {
854
+ leases.codex.held = false;
855
+ await publishDurableSessionEvents(
856
+ bus,
857
+ input.workspaceId,
858
+ input.sessionId,
859
+ settlement.events,
860
+ );
861
+ control.activityError = error;
862
+ control.activityStatus = "idle";
863
+ control.turnMetricOutcome = "failed";
864
+ await deliverFailedChildTurnToParent(
865
+ { db, bus, settings, observability, wakeSessionWorkflow },
866
+ input.workspaceId,
867
+ input.sessionId,
868
+ attempt.turnId,
869
+ );
870
+ return claimedResult({ status: "idle" });
871
+ }
872
+ if (settlement.action === "stale") {
873
+ acknowledgeLostAttemptOwnership();
874
+ control.activityStatus = "cancelled";
875
+ control.turnMetricOutcome = "cancelled";
876
+ return claimedResult({ status: "cancelled" });
877
+ }
878
+ throw new Error("Exhausted Codex failover receipt unexpectedly recovered");
879
+ }
880
+ let accounts: Awaited<ReturnType<typeof listCodexAccountStatuses>>;
881
+ try {
882
+ accounts = await listCodexAccountStatuses(db, input.workspaceId);
883
+ } catch (metadataError) {
884
+ // Current account health/cooldown metadata is still required after
885
+ // quarantine. Operational database failures re-enter the existing
886
+ // exact-attempt recovery lane; no policy choice is made from partial
887
+ // account state.
888
+ const recoveryFailure = postClaimDatabaseRecoveryFailure({
889
+ error: metadataError,
890
+ turnId: attempt.turnId,
891
+ triggerEventId: attempt.triggerEventId!,
892
+ executionGeneration: attempt.executionGeneration,
893
+ });
894
+ if (recoveryFailure) {
895
+ control.activityStatus = "recovering";
896
+ control.turnMetricOutcome = "recovering";
897
+ control.activityError = metadataError;
898
+ throw recoveryFailure;
899
+ }
900
+ throw metadataError;
901
+ }
902
+ const acceptedPolicy = acceptedCodexPolicySnapshot(providerTurn);
903
+ const selected = selectCodexCredentialLeaseForTurn({
904
+ context: {
905
+ accounts: codexLeaseAccountsForSelection(accounts),
906
+ activeCredentialId: acceptedPolicy.activeCredentialId,
907
+ rotationEnabled: acceptedPolicy.rotationEnabled,
908
+ rotationStrategy: acceptedPolicy.rotationStrategy,
909
+ existingCredentialId: null,
910
+ failedCredentialIds: [providerTurn.effectiveCodexCredentialId],
911
+ policyScope: null,
912
+ unavailableDiagnostics: [],
913
+ },
914
+ sessionId: input.sessionId,
915
+ sessionPinnedCredentialId: acceptedPolicy.pinnedCredentialId,
916
+ sessionPinSource: acceptedPolicy.pinSource,
917
+ sessionLastCredentialId: acceptedPolicy.lastCredentialId,
918
+ now,
919
+ });
920
+ const decisionKind =
921
+ selected.decision.kind === "allocatorDisabled" ? "allCapped" : selected.decision.kind;
922
+ const pinDisposition = classifyCodexPin({
923
+ pinnedCredentialId: acceptedPolicy.pinnedCredentialId,
924
+ pinSource: acceptedPolicy.pinSource,
925
+ strategy: acceptedPolicy.rotationStrategy as CodexRotationStrategy,
926
+ rotationEnabled: acceptedPolicy.rotationEnabled,
927
+ });
928
+ const failureDisposition = codexDefinitiveFailureDisposition({
929
+ failureKind: codexCredentialFailure.kind,
930
+ rotationEnabled: acceptedPolicy.rotationEnabled,
931
+ pinDisposition,
932
+ decisionKind,
933
+ decisionCredentialId: selected.decision.kind === "active" ? selected.credentialId : null,
934
+ servingCredentialId: providerTurn.effectiveCodexCredentialId,
935
+ });
936
+ const maxFailovers = providerTurn.codexCredentialFailoverLimit;
684
937
 
685
- if (candidateAvailable && leases.codex.holderId && leases.codex.generation !== null) {
938
+ if (
939
+ statePersisted &&
940
+ failureDisposition === "failover" &&
941
+ leases.codex.holderId &&
942
+ leases.codex.generation !== null
943
+ ) {
686
944
  const settlement = await settleCodexCredentialFailover(db, {
687
945
  accountId: input.accountId,
688
946
  workspaceId: input.workspaceId,
@@ -692,7 +950,7 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
692
950
  holderId: leases.codex.holderId,
693
951
  generation: leases.codex.generation,
694
952
  expectedRedispatches: attempt.redispatchesAtDispatch,
695
- maxFailovers: Math.max(1, accounts.length),
953
+ maxFailovers,
696
954
  recoveryPayload: {
697
955
  triggerEventId: attempt.triggerEventId!,
698
956
  reason: "codex_credential_failover",
@@ -700,6 +958,15 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
700
958
  failureKind: codexCredentialFailure.kind,
701
959
  ...(cooldownUntil ? { cooldownUntil: cooldownUntil.toISOString() } : {}),
702
960
  },
961
+ failedPayload: {
962
+ error:
963
+ "Automatic Codex credential failover stopped after every bounded account attempt was consumed. Send a new message after checking account health or capacity.",
964
+ code: "codex_credential_failover_exhausted",
965
+ retryable: false,
966
+ recovery: "user_message",
967
+ failoverCount: quarantineResult.failoverCount,
968
+ maxFailovers: quarantineResult.maxFailovers,
969
+ },
703
970
  });
704
971
  observability.incrementCounter({
705
972
  name: "opengeni_codex_failover_settlements_total",
@@ -738,8 +1005,137 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
738
1005
  acknowledgeLostAttemptOwnership();
739
1006
  control.activityStatus = "cancelled";
740
1007
  control.turnMetricOutcome = "cancelled";
1008
+ return claimedResult({ status: "cancelled" });
1009
+ }
1010
+ if (settlement.action === "limit_exceeded") {
1011
+ leases.codex.held = false;
1012
+ await publishDurableSessionEvents(
1013
+ bus,
1014
+ input.workspaceId,
1015
+ input.sessionId,
1016
+ settlement.events,
1017
+ );
1018
+ control.activityError = error;
1019
+ control.activityStatus = "idle";
1020
+ control.turnMetricOutcome = "failed";
1021
+ await deliverFailedChildTurnToParent(
1022
+ { db, bus, settings, observability, wakeSessionWorkflow },
1023
+ input.workspaceId,
1024
+ input.sessionId,
1025
+ attempt.turnId,
1026
+ );
1027
+ return claimedResult({ status: "idle" });
1028
+ }
1029
+ }
1030
+
1031
+ if (
1032
+ statePersisted &&
1033
+ failureDisposition === "wait" &&
1034
+ leases.codex.holderId &&
1035
+ leases.codex.generation !== null
1036
+ ) {
1037
+ let goal: Awaited<ReturnType<typeof getSessionGoal>>;
1038
+ try {
1039
+ goal = await getSessionGoal(db, input.workspaceId, input.sessionId);
1040
+ } catch (metadataError) {
1041
+ const recoveryFailure = postClaimDatabaseRecoveryFailure({
1042
+ error: metadataError,
1043
+ turnId: attempt.turnId,
1044
+ triggerEventId: attempt.triggerEventId!,
1045
+ executionGeneration: attempt.executionGeneration,
1046
+ });
1047
+ if (recoveryFailure) {
1048
+ control.activityStatus = "recovering";
1049
+ control.turnMetricOutcome = "recovering";
1050
+ control.activityError = metadataError;
1051
+ throw recoveryFailure;
1052
+ }
1053
+ throw metadataError;
1054
+ }
1055
+ const activeGoal = goal?.status === "active" ? goal : null;
1056
+ const exactProviderReset =
1057
+ codexCredentialFailure.cooldownSeconds !== null &&
1058
+ Number.isFinite(codexCredentialFailure.cooldownSeconds) &&
1059
+ codexCredentialFailure.cooldownSeconds > 0;
1060
+ const policyCredentialId =
1061
+ pinDisposition === "manual" && acceptedPolicy.pinnedCredentialId
1062
+ ? acceptedPolicy.pinnedCredentialId
1063
+ : !acceptedPolicy.rotationEnabled
1064
+ ? acceptedPolicy.activeCredentialId
1065
+ : null;
1066
+ const capacityAccounts = policyCredentialId
1067
+ ? accounts.filter((account) => account.id === policyCredentialId)
1068
+ : accounts;
1069
+ const authoritativeResetAt = exactProviderReset
1070
+ ? (authoritativeCodexCapacityResetAt(capacityAccounts, now) ?? cooldownUntil)
1071
+ : null;
1072
+ const allAccounts =
1073
+ acceptedPolicy.rotationEnabled &&
1074
+ pinDisposition !== "manual" &&
1075
+ decisionKind === "allCapped";
1076
+ const failurePayload = codexCapacityWaitFailurePayload({
1077
+ failureKind: codexCredentialFailure.kind,
1078
+ usageLimit,
1079
+ cooldownSeconds: codexCredentialFailure.cooldownSeconds,
1080
+ detail:
1081
+ codexCredentialFailure.kind === "quota"
1082
+ ? error instanceof Error
1083
+ ? error.message
1084
+ : String(error)
1085
+ : "the same accepted turn is waiting for eligible credential capacity",
1086
+ allAccounts,
1087
+ });
1088
+ const evaluated = await armAndReconcileCodexCapacityWait(
1089
+ { db, bus },
1090
+ {
1091
+ accountId: input.accountId,
1092
+ workspaceId: input.workspaceId,
1093
+ sessionId: input.sessionId,
1094
+ turnId: attempt.turnId,
1095
+ attemptId: input.attemptId,
1096
+ workflowId: input.workflowId,
1097
+ goalId: activeGoal?.id ?? null,
1098
+ goalVersion: activeGoal?.version ?? null,
1099
+ earliestResetAt: authoritativeResetAt,
1100
+ resetKind: authoritativeResetAt
1101
+ ? "authoritative"
1102
+ : codexCredentialFailure.kind === "auth" ||
1103
+ codexCredentialFailure.kind === "forbidden"
1104
+ ? "mutation_only"
1105
+ : "bounded_refresh",
1106
+ failurePayload,
1107
+ leaseFence: {
1108
+ holderId: leases.codex.holderId,
1109
+ generation: leases.codex.generation,
1110
+ },
1111
+ expectedRedispatches: attempt.redispatchesAtDispatch,
1112
+ },
1113
+ { onArmed: () => (leases.codex.held = false) },
1114
+ );
1115
+ control.activityError = error;
1116
+ if (evaluated.action === "resumed") {
1117
+ control.activityStatus = "recovering";
1118
+ control.turnMetricOutcome = "recovering";
741
1119
  return claimedResult({ status: "recovering" });
742
1120
  }
1121
+ if (evaluated.action === "waiting") {
1122
+ control.activityError = error;
1123
+ control.activityStatus = "waiting_capacity";
1124
+ control.turnMetricOutcome = "recovering";
1125
+ return claimedResult({
1126
+ status: "waiting_capacity",
1127
+ capacityWait: {
1128
+ waiterId: evaluated.waiter.id,
1129
+ generation: evaluated.waiter.generation,
1130
+ nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),
1131
+ wakeRevision: evaluated.waiter.wakeRevision,
1132
+ },
1133
+ });
1134
+ }
1135
+ acknowledgeLostAttemptOwnership();
1136
+ control.activityStatus = "cancelled";
1137
+ control.turnMetricOutcome = "cancelled";
1138
+ return claimedResult({ status: "cancelled" });
743
1139
  }
744
1140
  }
745
1141
  }
@@ -882,262 +1278,26 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
882
1278
  control.activityError = error;
883
1279
  return claimedResult({ status: "recovering" });
884
1280
  }
885
- // A ChatGPT/Codex usage cap (429 usage_limit_reached) is account state,
886
- // NOT an agent failure: surface the precise, actionable message (so the
887
- // user sees the reset window) but idle the session — never go terminal,
888
- // which would reject the user's next message after the cap lifts. The
889
- // payload is retryable:false so the generic provider-backpressure auto-retry
890
- // does not loop. For an active goal we hold the continuation for the reported
891
- // reset window (capped) so it resumes itself when access returns, instead of
892
- // hammering the capped backend.
893
- const usageLimit = isCodexTransportError(error) ? classifyCodexUsageLimitError(error) : null;
1281
+ // The leased credential path above normally quarantines quota state and
1282
+ // either recovers the same turn or arms a durable capacity wait. This narrow
1283
+ // fallback covers failures before a credential lease existed, or a failed
1284
+ // durable checkpoint where replay would be unsafe. Keep the session usable,
1285
+ // but never synthesize another turn or walk an unfenced legacy pointer.
894
1286
  if (usageLimit && eventing.publish && attempt.turnId && eventing.turnStartedPublished) {
895
- const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(() => null);
896
- const goalActive = Boolean(goal && goal.status === "active");
897
1287
  await flushRuntimeBatcher();
898
1288
  await historySink.reconcileConversationTruth();
899
- // --- P3 reactive rotation (gated; re-fetch fresh state on this already-failed,
900
- // already-idling path). Mark THIS account cooling until its reset, then CONSULT the
901
- // engine over fresh accounts to decide continueDelayMs: a fast 0-delay re-dispatch
902
- // when another account is available, or idle-until-earliest when all are capped. The
903
- // catch deliberately does NOT move the active pointer — the re-dispatched turn's
904
- // proactive seam (turn-start) is the single authoritative pointer-move + strip site.
905
- let rotated = false;
906
- let rotationResumeMs: number | null = null; // 0 ⇒ a candidate is available; re-dispatch now
907
- let rotationResumeIdleUntilReset = false; // circuit-breaker fall (Finding 1b) ⇒ MANDATORY hold
908
- let allCappedResetAt: Date | null = null; // set ⇒ every account capped; idle until this
909
- let capacityAuthoritativeResetAt: Date | null = null;
910
- let capacityNeedsBoundedRefresh = false;
911
- if (providerTurn.effectiveCodexCredentialId) {
912
- const [rotation, sessionCodex] = await Promise.all([
913
- getCodexRotationSettings(db, input.workspaceId).catch(() => null),
914
- getSessionCodexState(db, input.workspaceId, input.sessionId).catch(() => null),
915
- ]);
916
- const reactiveStrategy = (rotation?.rotationStrategy ??
917
- "most_remaining") as CodexRotationStrategy;
918
- const reactiveDisposition = classifyCodexPin({
919
- pinnedCredentialId: sessionCodex?.pinnedCredentialId ?? null,
920
- pinSource: sessionCodex?.pinSource ?? null,
921
- strategy: reactiveStrategy,
922
- rotationEnabled: Boolean(rotation?.rotationEnabled),
923
- });
924
- const reactiveSharded = reactiveDisposition === "sharded";
925
- const rotating =
926
- Boolean(rotation?.rotationEnabled || rotation?.leaseRotationEnabled) &&
927
- reactiveDisposition !== "manual";
928
- if (rotating && rotation) {
929
- const accounts = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);
930
- const serving =
931
- accounts.find((a) => a.id === providerTurn.effectiveCodexCredentialId) ?? null;
932
- // Both provider allowance windows bind. Use the same canonical
933
- // quarantine calculation as the fenced failover path so a short
934
- // five-hour reset can never overwrite a later weekly reset.
935
- const until = codexCredentialCooldownUntil(
936
- { kind: "quota", cooldownSeconds: usageLimit.resetsInSeconds },
937
- serving,
938
- new Date(),
939
- )!;
940
- // Finding 1a: INSPECT the cooldown-write result. A swallowed best-effort
941
- // write whose failure went unnoticed is exactly what lets the next proactive
942
- // rank re-pick this just-capped account (stale-low cached usedPercent, not
943
- // cooling) — so capture whether it PERSISTED and feed it into the resume floor.
944
- const cooldownMutation = await setCodexCredentialExhaustedWithWakeTargets(
945
- db,
946
- input.workspaceId,
947
- providerTurn.effectiveCodexCredentialId,
948
- until,
949
- "quota",
950
- ).catch(() => null);
951
- const cooldownPersisted = cooldownMutation?.result ?? false;
952
- if (cooldownMutation) {
953
- await signalCodexCapacityWakeTargets(
954
- { signalCodexCapacityWorkflow, wakeSessionWorkflow },
955
- cooldownMutation.wakeTargets,
956
- );
957
- }
958
- // Re-rank over the fresh accounts; the in-memory list predates the cooldown
959
- // write, so stamp the just-cooled account so the engine excludes it now. The
960
- // serving account is thus walked AT MOST ONCE per turn (invariant 4: bounded).
961
- const fresh = accounts.map((a) =>
962
- a.id === providerTurn.effectiveCodexCredentialId
963
- ? { ...a, exhaustedUntil: until, exhaustedKind: "quota" as const }
964
- : a,
965
- );
966
- if (reactiveSharded) {
967
- // AM-5: RE-SHARD over the healthy survivors (the just-capped serving account is
968
- // marked cooling in `fresh` → excluded) so sessions sharing a capped account
969
- // spread across the pool rather than re-concentrating on one first-eligible
970
- // failover. AM-3: DURABLY REWRITE the session's POLICY pin to the new home —
971
- // selectCodexCredentialForTurn returns a cooling pinned account with NO
972
- // exhaustion check, so a pointer-only move would leave the re-dispatched turn on
973
- // the capped pin. Like the classic path we do NOT touch the workspace active
974
- // pointer; the session pin is the sharded home.
975
- const newHome = shardCredentialForSession({
976
- sessionId: input.sessionId,
977
- accounts: fresh,
978
- now: new Date(),
979
- });
980
- if (newHome) {
981
- rotated = true;
982
- const pinMutation = await withSessionCodexCapacityMutation(
983
- db,
984
- {
985
- workspaceId: input.workspaceId,
986
- reason: "codex_policy_pin_resharded",
987
- },
988
- async (tx) => {
989
- const changed = await setSessionCodexPinInTransaction(
990
- tx,
991
- input.workspaceId,
992
- input.sessionId,
993
- newHome,
994
- "policy",
995
- {
996
- expected: {
997
- pinnedCredentialId: sessionCodex?.pinnedCredentialId ?? null,
998
- pinSource: sessionCodex?.pinSource ?? null,
999
- },
1000
- },
1001
- );
1002
- return { result: changed, changed };
1003
- },
1004
- ).catch(() => null);
1005
- if (pinMutation) {
1006
- await signalCodexCapacityWakeTargets(
1007
- { signalCodexCapacityWorkflow, wakeSessionWorkflow },
1008
- pinMutation.wakeTargets,
1009
- );
1010
- }
1011
- const priorConsecutiveRotations = await countConsecutiveReactiveRotations(
1012
- db,
1013
- input.workspaceId,
1014
- input.sessionId,
1015
- ).catch(() => 0);
1016
- const resume = computeReactiveRotationResume({
1017
- cooldownPersisted,
1018
- priorConsecutiveRotations,
1019
- connectedAccountCount: accounts.length,
1020
- });
1021
- rotationResumeMs = resume.continueDelayMs;
1022
- rotationResumeIdleUntilReset = resume.idleUntilReset;
1023
- } else {
1024
- // Every account capped/cooling → idle until the earliest reset across all.
1025
- rotated = true;
1026
- allCappedResetAt = earliestCodexReset(fresh, new Date());
1027
- capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, new Date());
1028
- capacityNeedsBoundedRefresh = true;
1029
- }
1030
- } else {
1031
- const decision = chooseRotationActive({
1032
- rotationStrategy: reactiveStrategy,
1033
- activeCredentialId: rotation.activeCredentialId,
1034
- priorCredentialId: providerTurn.effectiveCodexCredentialId,
1035
- accounts: fresh,
1036
- now: new Date(),
1037
- });
1038
- if (decision.kind === "active") {
1039
- rotated = true;
1040
- // Finding 1: a live candidate normally re-dispatches NOW (0). Two second-order
1041
- // faults would turn that 0 into a hot loop, so bound it. Count the consecutive
1042
- // reactive failovers since the last successful turn (this one is not yet
1043
- // published) and combine with the cooldown-persistence result.
1044
- const priorConsecutiveRotations = await countConsecutiveReactiveRotations(
1045
- db,
1046
- input.workspaceId,
1047
- input.sessionId,
1048
- ).catch(() => 0);
1049
- const resume = computeReactiveRotationResume({
1050
- cooldownPersisted,
1051
- priorConsecutiveRotations,
1052
- connectedAccountCount: accounts.length,
1053
- });
1054
- rotationResumeMs = resume.continueDelayMs; // 0 (happy path), a slow-retry floor, or the circuit-breaker idle
1055
- rotationResumeIdleUntilReset = resume.idleUntilReset; // true only on the circuit-breaker fall (MANDATORY hold)
1056
- } else if (decision.kind === "allCapped") {
1057
- rotated = true;
1058
- allCappedResetAt = decision.earliestResetAt;
1059
- capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, new Date());
1060
- capacityNeedsBoundedRefresh = true;
1061
- }
1062
- // kind:"none" → fall through to today's single-account idle.
1063
- }
1064
- }
1065
- }
1066
-
1067
- const failurePayload = allCappedResetAt
1068
- ? codexUsageLimitFailurePayload(
1069
- {
1070
- resetsInSeconds: Math.ceil(Math.max(0, allCappedResetAt.getTime() - Date.now()) / 1000),
1071
- },
1072
- error instanceof Error ? error.message : String(error),
1073
- { allAccounts: true },
1074
- )
1075
- : codexUsageLimitFailurePayload(
1076
- usageLimit,
1077
- error instanceof Error ? error.message : String(error),
1078
- );
1079
- // A live alternate is still handled by the existing immediate,
1080
- // same-policy continuation path. When no alternate exists (all capped,
1081
- // or a single non-rotating account), persist the native capacity wait
1082
- // instead of an in-memory delay/user-message recovery.
1083
- if (rotationResumeMs === null) {
1084
- const providerResetAt =
1085
- capacityAuthoritativeResetAt ??
1086
- (usageLimit.resetsInSeconds !== null &&
1087
- Number.isFinite(usageLimit.resetsInSeconds) &&
1088
- usageLimit.resetsInSeconds > 0
1089
- ? new Date(Date.now() + Math.ceil(usageLimit.resetsInSeconds) * 1000)
1090
- : null);
1091
- const armed = await armCodexCapacityWait(db, {
1092
- accountId: input.accountId,
1093
- workspaceId: input.workspaceId,
1094
- sessionId: input.sessionId,
1095
- turnId: attempt.turnId,
1096
- attemptId: input.attemptId,
1097
- workflowId: input.workflowId,
1098
- goalId: goalActive && goal ? goal.id : null,
1099
- goalVersion: goalActive && goal ? goal.version : null,
1100
- earliestResetAt: providerResetAt,
1101
- resetKind:
1102
- providerResetAt && !capacityNeedsBoundedRefresh ? "authoritative" : "bounded_refresh",
1103
- failurePayload,
1104
- ...(leases.codex.holderId && leases.codex.generation !== null
1105
- ? {
1106
- leaseFence: {
1107
- holderId: leases.codex.holderId,
1108
- generation: leases.codex.generation,
1109
- },
1110
- expectedRedispatches: attempt.redispatchesAtDispatch,
1111
- }
1112
- : {}),
1113
- });
1114
- if (armed.action === "waiting") {
1115
- await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, armed.events);
1116
- control.turnMetricOutcome = "recovering";
1117
- control.activityStatus = "waiting_capacity";
1118
- control.activityError = error;
1119
- return claimedResult({
1120
- status: "waiting_capacity",
1121
- capacityWait: {
1122
- waiterId: armed.waiter.id,
1123
- generation: armed.waiter.generation,
1124
- nextCheckAt: armed.waiter.nextCheckAt.toISOString(),
1125
- wakeRevision: armed.waiter.wakeRevision,
1126
- },
1127
- });
1128
- }
1129
- }
1289
+ const failurePayload = codexUsageLimitFailurePayload(
1290
+ usageLimit,
1291
+ error instanceof Error ? error.message : String(error),
1292
+ );
1130
1293
  if (
1131
1294
  !(await eventing.settle!({
1132
1295
  events: [
1133
- // `rotated:true` ONLY on the reactive rotation path tells evaluateGoalContinuation to
1134
- // freeze autoContinuations (a rotation walk must not burn the goal's continuation budget).
1135
1296
  {
1136
1297
  type: "turn.failed",
1137
1298
  payload: {
1138
1299
  ...failurePayload,
1139
- recovery: goalActive ? "goal_continuation" : "user_message",
1140
- ...(rotated ? { rotated: true } : {}),
1300
+ recovery: "user_message",
1141
1301
  },
1142
1302
  },
1143
1303
  { type: "session.status.changed", payload: { status: "idle" } },
@@ -1152,38 +1312,6 @@ export async function settleTurnFailure(deps: TurnFailureDeps): Promise<RunAgent
1152
1312
  control.turnMetricOutcome = "failed";
1153
1313
  control.activityStatus = "idle";
1154
1314
  control.activityError = error;
1155
- if (goalActive) {
1156
- // Rotation: a candidate is available → continue NOW (0). All-capped → idle until the
1157
- // earliest reset across all accounts (capped at 1h). Else the unchanged single-account idle.
1158
- if (rotationResumeMs !== null) {
1159
- // A candidate IS available. Normally the just-failed account is now cooling so
1160
- // the ranker cannot re-pick it → 0 (re-dispatch NOW, the legitimate skip-the-hold
1161
- // case). Finding 1 bounds the two exceptions: a persistence fault yields a positive
1162
- // slow-retry floor, and once consecutive failovers exceed the account count + margin
1163
- // the circuit breaker returns a fixed MANDATORY idle (idleUntilReset) — never a 0-delay
1164
- // hot loop against a capped backend + DB.
1165
- return claimedResult({
1166
- status: "idle",
1167
- continueDelayMs: rotationResumeMs,
1168
- ...(rotationResumeIdleUntilReset ? { idleUntilReset: true } : {}),
1169
- });
1170
- }
1171
- // All-capped: clamp to [MIN_IDLE_MS, max] — a POSITIVE, BOUNDED hold (never 0,
1172
- // so session.ts can never tight-loop). The post-idle continuation re-dispatch
1173
- // hits the proactive seam, which refreshes usage and self-heals.
1174
- const resumeMs = allCappedResetAt
1175
- ? computeIdleDelayMs(allCappedResetAt, new Date(), CODEX_USAGE_LIMIT_MAX_RESUME_MS)
1176
- : usageLimit.resetsInSeconds !== null &&
1177
- Number.isFinite(usageLimit.resetsInSeconds) &&
1178
- usageLimit.resetsInSeconds > 0
1179
- ? Math.min(Math.ceil(usageLimit.resetsInSeconds) * 1000, CODEX_USAGE_LIMIT_MAX_RESUME_MS)
1180
- : CODEX_USAGE_LIMIT_MAX_RESUME_MS;
1181
- return claimedResult({
1182
- status: "idle",
1183
- continueDelayMs: resumeMs,
1184
- ...(allCappedResetAt ? { idleUntilReset: true } : {}),
1185
- });
1186
- }
1187
1315
  return claimedResult({ status: "idle" });
1188
1316
  }
1189
1317
  // Budget/limit exhaustion between model calls is account state, not an