@bitkyc08/opencodex 2.100.3 → 2.100.4

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 (181) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-DcpyI78f.js} +20 -19
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-CzjPJprT.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BTIi7e69.js +1 -0
  6. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  7. package/gui/dist/assets/index-DVgU6S3y.js +138 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bn6Y-g3R.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-eYJAyNHM.js} +19 -18
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-xHMYxLkV.js} +1 -1
  11. package/gui/dist/classic/assets/index-DSaVRW4F.js +138 -0
  12. package/gui/dist/classic/assets/quota-summary-DyzHlkFl.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/package.json +2 -2
  18. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  19. package/src/adapters/anthropic.ts +3 -0
  20. package/src/adapters/claude-cli/adapter.ts +1 -0
  21. package/src/adapters/devin/cloud-direct/chat.ts +71 -14
  22. package/src/adapters/google-errors.ts +14 -2
  23. package/src/adapters/qoder/adapter.ts +9 -1
  24. package/src/adapters/zed.ts +4 -2
  25. package/src/claude/desktop-remote-store.ts +60 -10
  26. package/src/cli/account-api.ts +4 -0
  27. package/src/cli/account-auth.ts +30 -2
  28. package/src/cli/account-extended.ts +33 -2
  29. package/src/cli/capabilities-access-remote.ts +3 -3
  30. package/src/cli/capabilities-accounts.ts +3 -3
  31. package/src/cli/capabilities-base.ts +11 -6
  32. package/src/cli/capabilities-observe-system.ts +2 -2
  33. package/src/cli/claude.ts +3 -3
  34. package/src/cli/disconnect-runtime.ts +16 -6
  35. package/src/cli/dispatch.ts +7 -1
  36. package/src/cli/index.ts +2 -2
  37. package/src/cli/link-apply-restart.ts +4 -2
  38. package/src/cli/link-routes.ts +4 -1
  39. package/src/cli/link.ts +5 -4
  40. package/src/cli/preflight-exemptions.ts +3 -0
  41. package/src/cli/registry.ts +5 -2
  42. package/src/cli/resolve.ts +23 -8
  43. package/src/cli/restart-failure.ts +11 -1
  44. package/src/cli/runtime-api.ts +4 -0
  45. package/src/cli/status.ts +4 -1
  46. package/src/cli/system-command.ts +1 -1
  47. package/src/cli/system-restart-client.ts +9 -3
  48. package/src/cli/system-settings-parity.ts +2 -1
  49. package/src/client/connect.ts +63 -9
  50. package/src/client/desktop-refusal.ts +38 -0
  51. package/src/client/lifecycle-lock.ts +29 -4
  52. package/src/client/runtime-restart.ts +27 -15
  53. package/src/client/runtime.ts +4 -2
  54. package/src/client/state.ts +14 -0
  55. package/src/codex/account-pause.ts +4 -0
  56. package/src/codex/account-runtime-state.ts +4 -0
  57. package/src/codex/auth-api/main-account-probe.ts +3 -1
  58. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  59. package/src/codex/auth-context.ts +40 -2
  60. package/src/codex/catalog/build-entries.ts +10 -0
  61. package/src/codex/catalog/derive-entry.ts +7 -0
  62. package/src/codex/catalog/reserve-warn.ts +7 -5
  63. package/src/codex/catalog/reserve.ts +4 -3
  64. package/src/codex/catalog/retained-sync.ts +2 -0
  65. package/src/codex/catalog/routed-defaults.ts +35 -0
  66. package/src/codex/convergence.ts +2 -0
  67. package/src/codex/loopback-target.ts +22 -8
  68. package/src/codex/main-account.ts +88 -29
  69. package/src/codex/native-main-auth-file.ts +14 -0
  70. package/src/codex/native-main-credentials.ts +270 -0
  71. package/src/codex/native-main-owner.ts +3 -0
  72. package/src/codex/native-main-refresh-mode.ts +14 -1
  73. package/src/codex/quota.ts +63 -14
  74. package/src/combos/failover.ts +12 -1
  75. package/src/combos/index.ts +5 -0
  76. package/src/combos/resolve.ts +115 -19
  77. package/src/config/diagnostics.ts +3 -0
  78. package/src/config/live-reconcile.ts +6 -3
  79. package/src/config/load-degrade.ts +2 -0
  80. package/src/config/persisted-mutation.ts +2 -2
  81. package/src/config/persisted-projections.ts +18 -0
  82. package/src/config/process-state.ts +4 -3
  83. package/src/config/reserve-capability.ts +96 -0
  84. package/src/config/schema/config-schema.ts +6 -0
  85. package/src/config/schema/leaf-validators.ts +2 -0
  86. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  87. package/src/config.ts +7 -7
  88. package/src/desktop-update/acquire.ts +202 -0
  89. package/src/desktop-update/cli.ts +168 -0
  90. package/src/desktop-update/drain.ts +40 -0
  91. package/src/desktop-update/headless.ts +285 -0
  92. package/src/desktop-update/image.ts +85 -0
  93. package/src/desktop-update/install.ts +53 -0
  94. package/src/desktop-update/msi.ts +72 -0
  95. package/src/desktop-update/release.ts +128 -0
  96. package/src/desktop-update/runtime.ts +155 -0
  97. package/src/desktop-update/staging.ts +118 -0
  98. package/src/desktop-update/trust.ts +45 -0
  99. package/src/generated/compatibility-version.json +246 -130
  100. package/src/images/fulfill-video.ts +3 -3
  101. package/src/images/loop.ts +6 -2
  102. package/src/images/plan.ts +147 -11
  103. package/src/images/types.ts +13 -4
  104. package/src/images/xai-video-client.ts +72 -10
  105. package/src/lib/gcp-adc.ts +48 -4
  106. package/src/lib/offline-resend.ts +150 -0
  107. package/src/lib/paced-stream.ts +3 -3
  108. package/src/lib/provider-outbound.ts +17 -6
  109. package/src/lib/request-failure-model.ts +2 -0
  110. package/src/lib/response-body-inactivity.ts +23 -1
  111. package/src/lib/upstream-retry.ts +38 -5
  112. package/src/link/explicit-route.ts +4 -4
  113. package/src/link/remote-windows.ts +79 -31
  114. package/src/link/residual-recovery.ts +20 -8
  115. package/src/messaging/budget.ts +23 -5
  116. package/src/messaging/rpc.ts +4 -4
  117. package/src/oauth/antigravity-risk.ts +126 -0
  118. package/src/oauth/generic-account-failover.ts +89 -18
  119. package/src/oauth/generic-session-affinity.ts +10 -3
  120. package/src/oauth/login-cli.ts +35 -1
  121. package/src/oauth/pool-kernel.ts +3 -3
  122. package/src/providers/anthropic-billing-refusal.ts +27 -3
  123. package/src/providers/google-vertex-model-discovery.ts +6 -1
  124. package/src/providers/model-rename-fields.ts +2 -0
  125. package/src/providers/quota/workbuddy.ts +6 -2
  126. package/src/providers/workbuddy-credit-balance.ts +125 -16
  127. package/src/responses/effort-history.ts +732 -0
  128. package/src/routing/history/integrity.ts +41 -4
  129. package/src/server/auth-cors.ts +13 -3
  130. package/src/server/codex-model-list.ts +2 -1
  131. package/src/server/direct-local-http.ts +26 -3
  132. package/src/server/index/link-listener.ts +20 -14
  133. package/src/server/index/serve-options.ts +1 -0
  134. package/src/server/index.ts +3 -2
  135. package/src/server/link-turn.ts +17 -5
  136. package/src/server/management/config-routes.ts +39 -3
  137. package/src/server/management/link-child-preflight.ts +1 -1
  138. package/src/server/management/link-route-edit.ts +20 -1
  139. package/src/server/management/oauth-account-routes.ts +22 -5
  140. package/src/server/management/provider-overwrite-carry.ts +3 -0
  141. package/src/server/management/provider-routes.ts +4 -4
  142. package/src/server/management/static-catalog-probe.ts +33 -0
  143. package/src/server/proxy-liveness.ts +54 -9
  144. package/src/server/relay.ts +6 -1
  145. package/src/server/request-log-conversation.ts +2 -2
  146. package/src/server/request-log.ts +5 -1
  147. package/src/server/reserve-capability-startup.ts +32 -0
  148. package/src/server/responses/adapter-delivery.ts +2 -0
  149. package/src/server/responses/adapter-dispatch.ts +31 -10
  150. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  151. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  152. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  153. package/src/server/responses/core-combo.ts +24 -9
  154. package/src/server/responses/core-errors.ts +9 -6
  155. package/src/server/responses/core-options.ts +8 -0
  156. package/src/server/responses/core.ts +21 -0
  157. package/src/server/responses/estimated-usage.ts +115 -0
  158. package/src/server/responses/jev-model-invoke.ts +7 -2
  159. package/src/server/responses/passthrough-completion.ts +6 -3
  160. package/src/server/responses/passthrough-delivery.ts +47 -8
  161. package/src/server/responses/passthrough-dispatch.ts +3 -0
  162. package/src/server/responses/request-prepare.ts +9 -5
  163. package/src/server/responses/sidecar-execution.ts +5 -0
  164. package/src/service/desktop-supervision.d.mts +2 -0
  165. package/src/service/desktop-supervision.mjs +5 -0
  166. package/src/stall-timeout.ts +11 -0
  167. package/src/types/config.ts +15 -92
  168. package/src/types/provider.ts +13 -0
  169. package/src/types/request.ts +19 -0
  170. package/src/types/routed-catalog-defaults.ts +17 -0
  171. package/src/types/routing-profile.ts +90 -0
  172. package/src/types.ts +1 -0
  173. package/src/update/index.ts +1 -1
  174. package/src/usage/log.ts +14 -4
  175. package/src/usage/telemetry-contract.ts +1 -0
  176. package/src/web-search/passthrough-bridge.ts +7 -0
  177. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  178. package/gui/dist/assets/index-DCdXsMyZ.js +0 -105
  179. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  180. package/gui/dist/classic/assets/index-BqOaGLf5.js +0 -105
  181. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -0,0 +1,732 @@
1
+ /**
2
+ * Per-message effort history (#6895): the decision state machine behind the Anthropic adapter's
3
+ * experimental `perMessageEffort` option.
4
+ *
5
+ * A Codex conversation that changes reasoning effort mid-chat rewrites Anthropic's top-level
6
+ * `output_config.effort`, and that rewrite invalidates every cached message block. Anthropic's
7
+ * per-message effort beta instead takes an effort-only system message at the turn where the
8
+ * effort changes, so the top-level value, and with it the cached prefix, can stay pinned to the
9
+ * conversation's first effort. Codex history carries no per-turn effort, so this module remembers,
10
+ * per conversation, where each change point sits and which effort it set.
11
+ *
12
+ * Design: rkb32's contract and offline slice on #6895 (rules 0-9, failure table, bounds). The store
13
+ * is process-local and holds hashes and pinned values only, never transcript text. Every path that
14
+ * cannot prove the request extends a committed history answers "off", which sends the request
15
+ * exactly as it would be sent without the option.
16
+ *
17
+ * Owner: structure/providers/anthropic-per-message-effort.md. Production seam:
18
+ * src/adapters/anthropic/per-message-effort.ts.
19
+ */
20
+ import { createHmac, randomBytes } from "node:crypto";
21
+
22
+ // Per-process key: fingerprints are not reproducible outside this process.
23
+ const hashKey = randomBytes(32);
24
+
25
+ export const MAX_ENTRIES = 64;
26
+ /** Hard bound on everything the store holds, pending slots and their buffers included. */
27
+ export const MAX_TOTAL_BYTES = 512 * 1024;
28
+ /** Cap on the output one pending slot may commit (stored records are hashes, so this bounds the buffer). */
29
+ export const MAX_BUFFER_BYTES = 128 * 1024;
30
+ /** Change points are re-sent on every later turn, so their count is capped. */
31
+ export const MAX_CHANGE_POINTS = 64;
32
+ /** One hour from last use. */
33
+ export const ENTRY_TTL_MS = 60 * 60 * 1000;
34
+ /** A model/destination refusal is remembered this long. */
35
+ export const CAPABILITY_TTL_MS = 60 * 60 * 1000;
36
+ const MAX_CAPABILITY = 256;
37
+ /** A pending slot expires this long after admission. */
38
+ export const PENDING_TTL_MS = 10 * 60 * 1000;
39
+ export const SCOPE_PARTS = ["cohort", "provider", "destination", "adapter", "model", "credential", "authMode"] as const;
40
+ // api.anthropic.com only. Fable 5.1 stays off until its wire id is checked against the Mythos rule.
41
+ const IN_SCOPE_MODEL = /^(claude-)?(mythos-5-1|opus-5-5|opus-5|sonnet-5-5|haiku-5-5)$/;
42
+ const ENDPOINT = "api.anthropic.com";
43
+ // Effort names the serializer can emit (anthropic.ts adaptiveEffort / reasoningBudget).
44
+ const EFFORTS = new Set(["minimal", "low", "medium", "high", "xhigh", "max"]);
45
+ /**
46
+ * The documented 400 for a model without per-message effort:
47
+ * "output_config.effort requires a model that supports per-turn effort; this model does not".
48
+ * Any other 400 sets nothing.
49
+ */
50
+ export const BETA_FRAGMENT = "requires a model that supports per-turn effort";
51
+
52
+ type Rec = Record<string, unknown>;
53
+ export type EffortHistoryScope = Record<(typeof SCOPE_PARTS)[number], string | undefined>;
54
+
55
+ /** One request, as the decision sees it. Every compared value is the one actually emitted. */
56
+ export interface EffortHistoryRequest {
57
+ chatLineage?: string;
58
+ scope?: Partial<EffortHistoryScope>;
59
+ /** Raw Responses items before this turn's new input. */
60
+ parent: unknown[];
61
+ /** This turn's new input: user, tool-result, developer and configuration items. */
62
+ suffix: unknown[];
63
+ effort?: string;
64
+ /** The emitted `thinking` field. */
65
+ thinking?: unknown;
66
+ emittedMaxTokens?: number;
67
+ explicitCap?: number;
68
+ omittedMaxTokens?: number;
69
+ /** Hash of everything on the wire that does not depend on effort (system, tools, display...). */
70
+ frame?: string;
71
+ generation?: string;
72
+ cacheControl?: boolean;
73
+ stripped?: boolean;
74
+ transport?: "http" | "websocket";
75
+ apiKind?: "responses" | "messages";
76
+ previousResponseId?: unknown;
77
+ compactionSummary?: boolean;
78
+ /** A positive new-transcript receipt for this turn (never inferred from shape alone). */
79
+ newTranscriptReceipt?: boolean;
80
+ /**
81
+ * The Anthropic `messages` index the effort message for this turn's change point would take:
82
+ * the wire message that starts with this turn's user message. Undefined when it cannot be placed.
83
+ */
84
+ changeWireIndex?: number;
85
+ }
86
+
87
+ export interface EffortHistoryOptions {
88
+ enabled?: boolean;
89
+ activated?: boolean;
90
+ websocketHeaderRead?: boolean;
91
+ compactionMarkerIdentified?: boolean;
92
+ now?: number;
93
+ }
94
+
95
+ export interface EffortChangePoint { at: number; wireIndex: number; effort: string }
96
+
97
+ export type EffortHistoryDecision =
98
+ | { action: "off"; reason: string; deleted?: boolean }
99
+ | {
100
+ action: "send";
101
+ kind: "new" | "matched";
102
+ pendingToken: string;
103
+ anchorEffort: string;
104
+ changePoint?: boolean;
105
+ shape?: "a" | "tool-only";
106
+ insert?: EffortChangePoint | null;
107
+ changePoints?: EffortChangePoint[];
108
+ };
109
+
110
+ interface PinnedRequest {
111
+ /** Digest of the chat lineage; the raw value is never kept. */
112
+ lineageKey: string;
113
+ /** Digest of the model and destination the capability record is keyed by. */
114
+ capabilityKey: string;
115
+ effort?: string;
116
+ /** Digest of the emitted `thinking` field. */
117
+ thinkingKey: string;
118
+ explicitCap?: number;
119
+ emittedMaxTokens?: number;
120
+ omittedMaxTokens?: number;
121
+ frame?: string;
122
+ generation?: string;
123
+ changeAt: number;
124
+ changeWireIndex?: number;
125
+ }
126
+
127
+ interface Entry {
128
+ scopeKey: string;
129
+ frame?: string;
130
+ generation?: string;
131
+ prefixHash: string;
132
+ inputHash: string;
133
+ effortInEffect: string;
134
+ lineageKey: string;
135
+ anchorEffort: string;
136
+ thinkingKey: string;
137
+ budget: number;
138
+ limit: number;
139
+ changePoints: EffortChangePoint[];
140
+ P: number;
141
+ version: number;
142
+ lastUsed: number;
143
+ bytes: number;
144
+ }
145
+
146
+ interface Slot {
147
+ kind: "new" | "matched";
148
+ key: string;
149
+ token: string;
150
+ version: number;
151
+ createdAt: number;
152
+ inputHash: string;
153
+ scopeKey: string;
154
+ req: PinnedRequest;
155
+ pinnedBytes: number;
156
+ attemptGeneration?: string;
157
+ entry?: Entry;
158
+ changePoint?: boolean;
159
+ buffered?: number;
160
+ }
161
+
162
+ export interface EffortHistoryStore {
163
+ entries: Map<string, Entry>;
164
+ pending: Map<string, Slot>;
165
+ capability: Map<string, { state: "unsupported"; at: number }>;
166
+ committedInputs: Map<string, true>;
167
+ nextVersion: number;
168
+ }
169
+
170
+ export interface EffortHistoryCommitResult {
171
+ messageStop?: boolean;
172
+ failedBeforeSend?: boolean;
173
+ restoreOnFailure?: boolean;
174
+ cacheRead?: number;
175
+ P?: number;
176
+ outputItems?: unknown[];
177
+ generation?: string;
178
+ }
179
+
180
+ export type EffortHistoryOutcome = { action: string; reason?: string; key?: string; deleted?: boolean };
181
+
182
+ // A tool call with no output in the same request: the serializer would synthesize one the client never sent.
183
+ function hasOrphanCall(items: unknown[]): boolean {
184
+ const outputs = new Set(items.filter(i => TOOL_OUTPUTS.has(String((i as Rec | null)?.type))).map(i => (i as Rec).call_id));
185
+ return items.some(i => {
186
+ const type = (i as Rec | null)?.type;
187
+ return (type === "function_call" || type === "custom_tool_call") && !outputs.has((i as Rec).call_id);
188
+ });
189
+ }
190
+ // Activation gates: no request reached the upstream path, so nothing is deleted.
191
+ const GATE_REASONS = new Set(["switch-off", "not-activated", "websocket-before-activation"]);
192
+
193
+ // Canonical JSON: object keys sorted at every level, so equal content hashes equally. A null field
194
+ // is the same as an absent one: Codex 0.167 echoes a reasoning item with `content: null` that the
195
+ // proxy never sent (live capture, 2026-11-16).
196
+ function canonical(value: unknown): unknown {
197
+ if (Array.isArray(value)) return value.map(canonical);
198
+ if (value && typeof value === "object") {
199
+ const rec = value as Rec;
200
+ return Object.fromEntries(Object.keys(rec).filter(k => rec[k] !== null).sort().map(k => [k, canonical(rec[k])]));
201
+ }
202
+ return value;
203
+ }
204
+ const stableJson = (value: unknown): string => JSON.stringify(canonical(value)) ?? "undefined";
205
+ /** The one projection used for commit and lookup. Key order is canonical; nothing else is dropped. */
206
+ export const project = (items: unknown): unknown => canonical(items);
207
+ export const hash = (value: unknown): string => createHmac("sha256", hashKey).update(stableJson(value)).digest("hex");
208
+ // A prefix digest is a chain over per-item digests, so a pending slot can extend it at commit
209
+ // without keeping any item text.
210
+ const extendChain = (digest: string, items: unknown[]): string => items.reduce<string>((d, item) => hash([d, hash(project(item))]), digest);
211
+ export const EMPTY_CHAIN = hash([]);
212
+ export const hashItems = (items: unknown[]): string => extendChain(EMPTY_CHAIN, items);
213
+ const bytesOf = (value: unknown): number => Buffer.byteLength(stableJson(value));
214
+
215
+ /** `minimal` maps to `low` for adaptive output (anthropic.ts adaptiveEffort), so the two are not a change point. */
216
+ export const mapEffort = (effort: string): string => (effort === "minimal" ? "low" : effort);
217
+
218
+ // Reasoning budget by effort (anthropic.ts reasoningBudget).
219
+ const BUDGET: Record<string, number> = { minimal: 1024, low: 4096, medium: 8192, high: 16384, xhigh: 24576, max: 32000 };
220
+ /**
221
+ * Effective output limit for this request. The emitted `max_tokens` wins; otherwise an explicit
222
+ * client cap; otherwise the adaptive derivation max(omitted, min(40192, max(8192, budget + 8192))).
223
+ */
224
+ export function effectiveLimit(req: Pick<EffortHistoryRequest, "emittedMaxTokens" | "explicitCap" | "effort" | "omittedMaxTokens">): number {
225
+ if (req.emittedMaxTokens !== undefined) return req.emittedMaxTokens;
226
+ if (req.explicitCap !== undefined) return req.explicitCap;
227
+ const budget = (Object.hasOwn(BUDGET, mapEffort(String(req.effort))) ? BUDGET[mapEffort(String(req.effort))] : undefined) ?? 8192;
228
+ return Math.max(req.omittedMaxTokens ?? 8192, Math.min(40192, Math.max(8192, budget + 8192)));
229
+ }
230
+
231
+ const off = (reason: string, extra: { deleted?: boolean } = {}): EffortHistoryDecision => ({ action: "off", reason, ...extra });
232
+
233
+ // Capability is per model and destination, not per chat or credential.
234
+ const capabilityKey = (s: Partial<EffortHistoryScope>): string => hash({ model: s.model, destination: s.destination });
235
+
236
+ export function createStore(): EffortHistoryStore {
237
+ return { entries: new Map(), pending: new Map(), capability: new Map(), committedInputs: new Map(), nextVersion: 1 };
238
+ }
239
+
240
+ // Entry key: scope + committed prefix. The frame is a field, not part of the key, so a frame
241
+ // change finds the entry by prefix and rule 6 can fire.
242
+ const entryKey = (scopeKey: string, prefixHash: string): string => hash([scopeKey, prefixHash]);
243
+ const newKey = (scopeKey: string, inputHash: string): string => hash(["new", scopeKey, inputHash]);
244
+
245
+ /**
246
+ * Codex's own per-turn `x-codex-turn-metadata` value: true only for `history_initialization` "new".
247
+ * Codex 0.167 sends the lowercase serde spelling; the enum's source name `New` is accepted too.
248
+ * The caller decides which copy of the metadata describes the turn (see the production seam).
249
+ */
250
+ export function lineageFromMetadata(headerValue: unknown): boolean {
251
+ if (typeof headerValue !== "string") return false;
252
+ let parsed: unknown;
253
+ try {
254
+ parsed = JSON.parse(headerValue);
255
+ } catch {
256
+ return false;
257
+ }
258
+ const value = parsed !== null && typeof parsed === "object" ? (parsed as Rec).history_initialization : undefined;
259
+ return value === "new" || value === "New";
260
+ }
261
+
262
+ // Tool output types the Responses parser handles.
263
+ const TOOL_OUTPUTS = new Set(["function_call_output", "custom_tool_call_output", "tool_search_output"]);
264
+ /** Item kind: a test shorthand (`kind`), or a real Responses input item by its type and role. */
265
+ export function kindOf(item: unknown): string {
266
+ const rec = (item && typeof item === "object" ? item : {}) as Rec;
267
+ if (typeof rec.kind === "string" && rec.type === undefined && rec.role === undefined) return rec.kind;
268
+ const type = rec.type ?? (rec.role ? "message" : undefined);
269
+ if (type === "message") {
270
+ if (rec.role === "user") return "user";
271
+ if (rec.role === "assistant") return "assistant";
272
+ if (rec.role === "developer" || rec.role === "system") return "developer";
273
+ }
274
+ if (TOOL_OUTPUTS.has(String(type))) return "tool_result";
275
+ if (type === "configuration_update") return "configuration_update";
276
+ return `other:${String(type)}`;
277
+ }
278
+ const isUser = (item: unknown): boolean => kindOf(item) === "user";
279
+ const isTool = (item: unknown): boolean => kindOf(item) === "tool_result";
280
+ const isDeveloper = (item: unknown): boolean => kindOf(item) === "developer";
281
+ const hasConfigUpdate = (items: unknown[]): boolean => items.some(item => kindOf(item) === "configuration_update");
282
+
283
+ // Off, and the parent entry is deleted before the request is sent.
284
+ function offSend(store: EffortHistoryStore, parentKey: string, reason: string): EffortHistoryDecision {
285
+ store.entries.delete(parentKey);
286
+ store.pending.delete(parentKey);
287
+ return off(reason, { deleted: true });
288
+ }
289
+
290
+ // Drop entries past their TTL and pending slots past theirs.
291
+ function sweep(store: EffortHistoryStore, now: number): void {
292
+ for (const [key, cap] of store.capability) {
293
+ if (now - cap.at > CAPABILITY_TTL_MS) store.capability.delete(key);
294
+ }
295
+ for (const [key, entry] of store.entries) {
296
+ if (now - entry.lastUsed > ENTRY_TTL_MS) store.entries.delete(key);
297
+ }
298
+ for (const [key, slot] of store.pending) {
299
+ if (now - slot.createdAt > PENDING_TTL_MS) store.pending.delete(key);
300
+ }
301
+ }
302
+
303
+ // An account, provider, or model change ends the old scope of this chat.
304
+ function endOtherScopes(store: EffortHistoryStore, lineage: string, scopeKey: string): void {
305
+ for (const [key, entry] of store.entries) {
306
+ if (entry.lineageKey === lineage && entry.scopeKey !== scopeKey) store.entries.delete(key);
307
+ }
308
+ for (const [key, slot] of store.pending) {
309
+ if (slot.req?.lineageKey === lineage && slot.scopeKey !== scopeKey) store.pending.delete(key);
310
+ }
311
+ }
312
+
313
+ function dropParent(store: EffortHistoryStore, req: EffortHistoryRequest): void {
314
+ const s = req.scope;
315
+ if (!s || !req.chatLineage || !Array.isArray(req.parent)) return;
316
+ const key = entryKey(hash([s, req.chatLineage]), hashItems(req.parent));
317
+ store.entries.delete(key);
318
+ store.pending.delete(key);
319
+ }
320
+
321
+ function decideWithCleanup(store: EffortHistoryStore, req: EffortHistoryRequest, opts?: EffortHistoryOptions): EffortHistoryDecision {
322
+ const result = decideInner(store, req, opts);
323
+ if (result.action === "off" && !GATE_REASONS.has(result.reason)) dropParent(store, req);
324
+ return result;
325
+ }
326
+
327
+ const validWireIndex = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 0;
328
+
329
+ // Ordered algorithm. The first rule that decides wins.
330
+ function decideInner(store: EffortHistoryStore, req: EffortHistoryRequest, opts: EffortHistoryOptions = {}): EffortHistoryDecision {
331
+ const now = opts.now ?? Date.now();
332
+ sweep(store, now);
333
+
334
+ // Rule 0 (global gate): nothing runs unless the option is on and activated.
335
+ if (opts.enabled !== true) return off("switch-off");
336
+ if (opts.activated !== true) return off("not-activated");
337
+ if (req.transport === "websocket" && opts.websocketHeaderRead !== true) return off("websocket-before-activation");
338
+ // Rule 1: out of scope. Claude Messages requests and requests with previous_response_id are always off.
339
+ if (req.apiKind === "messages") return off("out-of-scope-messages-api");
340
+ if (req.previousResponseId) return off("out-of-scope-previous-response-id");
341
+
342
+ // Fable 5.1 is in scope only once its wire id is checked against the Mythos rule; until then off.
343
+ if (/fable/i.test(req.scope?.model ?? "")) return off("fable-wire-id-unchecked");
344
+ if (hasOrphanCall([...req.parent, ...req.suffix])) return off("orphan-tool-call");
345
+ // No effort level ("none" or absent) cannot be a per-message effort value: off, as today.
346
+ if (typeof req.effort !== "string" || !EFFORTS.has(req.effort)) return off("no-effort-level");
347
+ // Rule 2: every scope part is required.
348
+ const s = req.scope;
349
+ if (!s || SCOPE_PARTS.some(k => !s[k])) return off("missing-scope");
350
+ if (s.authMode !== "apiKey") return off("oauth-not-in-first-slice");
351
+ if (s.destination !== ENDPOINT) return off("out-of-scope-destination");
352
+ if (typeof s.model !== "string" || !IN_SCOPE_MODEL.test(s.model)) return off("out-of-scope-model");
353
+ // Chat identity: two chats can share a first message, so each chat needs its own lineage value.
354
+ if (!req.chatLineage) return off("no-chat-lineage");
355
+ const scopeKey = hash([s, req.chatLineage]);
356
+ endOtherScopes(store, hash(req.chatLineage), scopeKey);
357
+ const parentHash = hashItems(req.parent);
358
+ const parentKey = entryKey(scopeKey, parentHash);
359
+ const inputHash = hashItems([...req.parent, ...req.suffix]);
360
+
361
+ // Rule 2a: no cache breakpoint. Rule 3: the proxy stripped reasoning.
362
+ if (!req.cacheControl) return offSend(store, parentKey, "no-cache-control");
363
+ if (req.stripped) return offSend(store, parentKey, "proxy-stripped");
364
+
365
+ // Rule 3a: an unsupported capability record.
366
+ const cap = store.capability.get(capabilityKey(s));
367
+ if (cap && cap.state === "unsupported" && now - cap.at <= CAPABILITY_TTL_MS) return offSend(store, parentKey, "capability-unsupported");
368
+
369
+ // Rule 3b runs before rule 4: a thinking change on a matching parent. Only emitted fields count:
370
+ // an emitted budget_tokens change is a change; the adaptive branch's internal budget is never emitted.
371
+ const parent = store.entries.get(parentKey);
372
+ if (parent && hash(req.thinking) !== parent.thinkingKey) return offSend(store, parentKey, "thinking-change");
373
+
374
+ // Rule 4: replay. The request is a turn already committed (same input hash).
375
+ for (const [key, entry] of store.entries) {
376
+ if (entry.scopeKey === scopeKey && entry.inputHash === inputHash) {
377
+ store.entries.delete(key);
378
+ store.entries.delete(parentKey);
379
+ return off("replay", { deleted: true });
380
+ }
381
+ }
382
+ // The turn's entry may already be consumed by a later turn; the committed-input record still refuses it.
383
+ if (store.committedInputs.has(hash([scopeKey, inputHash]))) {
384
+ store.entries.delete(parentKey);
385
+ return off("replay", { deleted: true });
386
+ }
387
+ // A placeholder with the same input hash is a duplicate first request: off, and it is deleted.
388
+ const placeholder = newKey(scopeKey, inputHash);
389
+ if (store.pending.has(placeholder)) {
390
+ store.pending.delete(placeholder);
391
+ return off("placeholder-exists", { deleted: true });
392
+ }
393
+
394
+ if (hasConfigUpdate(req.suffix)) return offSend(store, parentKey, "configuration-update-in-suffix");
395
+
396
+ // A second request for a parent that is already pending is a fork or retry.
397
+ if (store.pending.has(parentKey)) {
398
+ store.pending.delete(parentKey);
399
+ return off("in-flight-collision", { deleted: true });
400
+ }
401
+
402
+ const suffix = req.suffix;
403
+ const userCount = suffix.filter(isUser).length;
404
+ const toolOnly = suffix.length > 0 && suffix.every(isTool);
405
+ // Shape (a): one user message, optionally after tool results. Developer items may appear.
406
+ const firstUser = suffix.findIndex(isUser);
407
+ const shapeA = userCount === 1
408
+ && suffix.every(item => isUser(item) || isTool(item) || isDeveloper(item))
409
+ && suffix.slice(firstUser + 1).every(item => !isTool(item));
410
+
411
+ if (!parent) {
412
+ // Rule 7: a compaction summary is user-role; it never starts a history.
413
+ if (req.compactionSummary === true) return off("compaction-summary");
414
+ if (opts.compactionMarkerIdentified !== true) return off("compaction-marker-unidentified");
415
+ // A new history needs a positive new-transcript receipt and a transcript of user and developer
416
+ // items only: a real Codex first turn carries its environment context as a second user message.
417
+ // A restart, eviction, or compaction is not new.
418
+ const newChat = req.newTranscriptReceipt === true && req.parent.length === 0
419
+ && userCount >= 1 && suffix.every(item => isUser(item) || isDeveloper(item));
420
+ if (!newChat) return off("no-history");
421
+ const pinned = pin(req);
422
+ const pinnedBytes = bytesOf(pinned);
423
+ // Decide first, evict second: a refused admission must not cost another chat its history, so
424
+ // both the byte check and the entry-count check run before anything is evicted.
425
+ if (!canFit(store, pinnedBytes)) return off("bounds-refused");
426
+ const atCount = store.entries.size + store.pending.size >= MAX_ENTRIES;
427
+ const oldest = atCount ? leastRecentlyUsed(store) : undefined;
428
+ if (atCount && oldest === undefined) return off("bounds-refused");
429
+ if (oldest !== undefined) store.entries.delete(oldest);
430
+ // The slot's bytes count against the store total: evict stored histories until it fits.
431
+ if (!evictUntilFits(store, pinnedBytes)) return off("bounds-refused");
432
+ const version = store.nextVersion++;
433
+ const token = `${placeholder}:${version}`;
434
+ store.pending.set(placeholder, {
435
+ kind: "new", key: placeholder, token, version, createdAt: now, inputHash, scopeKey, req: pinned, pinnedBytes, attemptGeneration: req.generation,
436
+ });
437
+ return { action: "send", kind: "new", pendingToken: token, anchorEffort: mapEffort(req.effort) };
438
+ }
439
+
440
+ // Rule 6: frame and generation.
441
+ if (parent.frame !== req.frame) return offSend(store, parentKey, "frame-mismatch");
442
+ if (parent.generation !== req.generation) return offSend(store, parentKey, "generation-mismatch");
443
+ // Any output limit different from the anchor's is off. A cap is never raised to make a turn eligible.
444
+ if (effectiveLimit(req) !== parent.limit) return offSend(store, parentKey, "limit-differs");
445
+
446
+ if (userCount > 1) return offSend(store, parentKey, "more-than-one-user-message");
447
+
448
+ const effort = mapEffort(req.effort);
449
+ if (toolOnly) {
450
+ if (effort !== parent.effortInEffect) return offSend(store, parentKey, "tool-only-effort-change");
451
+ return admitMatched(store, { scopeKey, parentKey, req, parent, now, inputHash, changePoint: false, shape: "tool-only" });
452
+ }
453
+ if (!shapeA) return offSend(store, parentKey, "unclassified-suffix");
454
+
455
+ const changePoint = effort !== parent.effortInEffect;
456
+ if (changePoint && parent.changePoints.length >= MAX_CHANGE_POINTS) return offSend(store, parentKey, "change-points-full");
457
+ // Mythos: any effort change is off, because its budget depends on effort.
458
+ if (changePoint && /mythos/i.test(s.model)) return offSend(store, parentKey, "mythos-effort-change");
459
+ // The effort message must land before this turn's user message on the wire; without a place, off.
460
+ if (changePoint && !validWireIndex(req.changeWireIndex)) return offSend(store, parentKey, "change-point-unplaceable");
461
+ return admitMatched(store, { scopeKey, parentKey, req, parent, now, inputHash, changePoint, shape: "a" });
462
+ }
463
+
464
+ interface MatchPlan {
465
+ scopeKey: string;
466
+ parentKey: string;
467
+ req: EffortHistoryRequest;
468
+ parent: Entry;
469
+ now: number;
470
+ inputHash: string;
471
+ changePoint: boolean;
472
+ shape: "a" | "tool-only";
473
+ }
474
+
475
+ // Matched: the parent entry moves to a pending slot until its commit.
476
+ function admitMatched(store: EffortHistoryStore, plan: MatchPlan): EffortHistoryDecision {
477
+ store.entries.delete(plan.parentKey);
478
+ const version = store.nextVersion++;
479
+ const token = `${plan.parentKey}:${version}`;
480
+ const pinned = pin(plan.req);
481
+ const pinnedBytes = bytesOf(pinned);
482
+ // The slot holds the parent entry and its pinned values; both count against the store total.
483
+ if (!evictUntilFits(store, plan.parent.bytes + pinnedBytes)) return off("bounds-refused", { deleted: true });
484
+ store.pending.set(plan.parentKey, {
485
+ kind: "matched", key: plan.parentKey, token, version, createdAt: plan.now, inputHash: plan.inputHash,
486
+ attemptGeneration: plan.req.generation,
487
+ scopeKey: plan.scopeKey, entry: plan.parent, req: pinned, pinnedBytes, changePoint: plan.changePoint,
488
+ });
489
+ const insert: EffortChangePoint | null = plan.changePoint
490
+ ? { at: pinned.changeAt, wireIndex: pinned.changeWireIndex as number, effort: mapEffort(plan.req.effort as string) }
491
+ : null;
492
+ return {
493
+ action: "send",
494
+ kind: "matched",
495
+ pendingToken: token,
496
+ anchorEffort: plan.parent.anchorEffort,
497
+ changePoint: plan.changePoint,
498
+ shape: plan.shape,
499
+ // What the adapter inserts: an effort-only system message before this turn's user message.
500
+ insert,
501
+ // Every change point on this chat, in prefix order, so the adapter re-sends all of them each turn.
502
+ changePoints: [...plan.parent.changePoints.map(c => ({ ...c })), ...(insert ? [insert] : [])],
503
+ };
504
+ }
505
+
506
+ // The pending slot is the compare-and-set check: a commit is written only if its slot still exists.
507
+ function totalBytes(store: EffortHistoryStore): number {
508
+ let total = 0;
509
+ for (const entry of store.entries.values()) total += entry.bytes;
510
+ // A matched parent in flight still holds its bytes until its commit or restore, and buffered
511
+ // streaming output counts too.
512
+ for (const slot of store.pending.values()) {
513
+ if (slot.entry) total += slot.entry.bytes;
514
+ total += (slot.pinnedBytes ?? 0) + (slot.buffered ?? 0);
515
+ }
516
+ return total;
517
+ }
518
+
519
+ // Resolve a token to its slot without removing it. A token from an earlier admission does not match.
520
+ function peekSlot(store: EffortHistoryStore, token: unknown): Slot | null {
521
+ if (typeof token !== "string") return null;
522
+ const sep = token.lastIndexOf(":");
523
+ if (sep < 0) return null;
524
+ const key = token.slice(0, sep);
525
+ const slot = store.pending.get(key);
526
+ if (!slot || slot.token !== token) return null;
527
+ return slot;
528
+ }
529
+
530
+ function takeSlot(store: EffortHistoryStore, token: unknown): Slot | null {
531
+ const slot = peekSlot(store, token);
532
+ if (slot) store.pending.delete(slot.key);
533
+ return slot;
534
+ }
535
+
536
+ // Eviction order: the entry with the oldest last use, not the first inserted.
537
+ function leastRecentlyUsed(store: EffortHistoryStore): string | undefined {
538
+ let best: string | undefined;
539
+ for (const [key, entry] of store.entries) {
540
+ if (best === undefined || entry.lastUsed < (store.entries.get(best) as Entry).lastUsed) best = key;
541
+ }
542
+ return best;
543
+ }
544
+
545
+ // Streaming: buffered output for a pending slot. Over the store cap or the per-slot cap, the slot
546
+ // is deleted and nothing commits; the response itself is not interrupted.
547
+ function bufferInner(store: EffortHistoryStore, token: unknown, bytes: number): EffortHistoryOutcome {
548
+ const slot = peekSlot(store, token);
549
+ if (!slot) return { action: "dropped", reason: "pending-missing" };
550
+ if (!Number.isFinite(bytes) || bytes < 0) {
551
+ store.pending.delete(slot.key);
552
+ return { action: "deleted", reason: "bad-bytes" };
553
+ }
554
+ if (totalBytes(store) + bytes > MAX_TOTAL_BYTES) {
555
+ store.pending.delete(slot.key);
556
+ return { action: "deleted", reason: "streaming-over-store-cap" };
557
+ }
558
+ if ((slot.buffered ?? 0) + bytes > MAX_BUFFER_BYTES) {
559
+ store.pending.delete(slot.key);
560
+ return { action: "deleted", reason: "over-buffer-cap" };
561
+ }
562
+ slot.buffered = (slot.buffered ?? 0) + bytes;
563
+ return { action: "buffering" };
564
+ }
565
+
566
+ // Whether evicting stored histories could make room: pending bytes are not evictable.
567
+ function canFit(store: EffortHistoryStore, bytes: number): boolean {
568
+ let evictable = 0;
569
+ for (const entry of store.entries.values()) evictable += entry.bytes;
570
+ return totalBytes(store) - evictable + bytes <= MAX_TOTAL_BYTES;
571
+ }
572
+
573
+ function evictUntilFits(store: EffortHistoryStore, bytes: number): boolean {
574
+ // Decide first, evict second: if the pending bytes alone do not leave room, nothing is evicted.
575
+ if (!canFit(store, bytes)) return false;
576
+ while (totalBytes(store) + bytes > MAX_TOTAL_BYTES) {
577
+ const oldest = leastRecentlyUsed(store);
578
+ if (oldest === undefined) return false;
579
+ store.entries.delete(oldest);
580
+ }
581
+ return true;
582
+ }
583
+
584
+ function recordCommittedInput(store: EffortHistoryStore, slot: Slot): void {
585
+ store.committedInputs.set(hash([slot.scopeKey, slot.inputHash]), true);
586
+ while (store.committedInputs.size > MAX_ENTRIES * 4) {
587
+ store.committedInputs.delete(store.committedInputs.keys().next().value as string);
588
+ }
589
+ }
590
+
591
+ // Outcomes after a send, in the contract's order.
592
+ function commitInner(store: EffortHistoryStore, token: unknown, result: EffortHistoryCommitResult, now = Date.now()): EffortHistoryOutcome {
593
+ const slot = takeSlot(store, token);
594
+ if (!slot) return { action: "dropped", reason: "pending-missing" };
595
+ if (now - slot.createdAt > PENDING_TTL_MS) return { action: "dropped", reason: "pending-expired" };
596
+ if (!result || typeof result !== "object") return { action: "deleted", reason: "bad-result" };
597
+ const { req } = slot;
598
+
599
+ if (result.messageStop && !result.failedBeforeSend && !Array.isArray(result.outputItems)) return { action: "deleted", reason: "bad-output" };
600
+ if (result.failedBeforeSend) {
601
+ // Default: delete. Restore only the matched parent, and only when the caller enables it.
602
+ if (slot.kind === "matched" && slot.entry && result.restoreOnFailure === true) {
603
+ if (!evictUntilFits(store, slot.entry.bytes)) return { action: "dropped", reason: "over-store-cap" };
604
+ store.entries.set(slot.key, slot.entry);
605
+ return { action: "restored" };
606
+ }
607
+ return { action: "deleted", reason: slot.kind === "matched" ? "failed-before-send" : "placeholder-failed" };
608
+ }
609
+ if (!result.messageStop) return { action: "deleted", reason: "uncertain-outcome" };
610
+
611
+ // Cache check. A missing cache read counts as zero; NaN or a non-number fails closed.
612
+ const cacheRead = result.cacheRead ?? 0;
613
+ if (slot.kind === "matched" && !(cacheRead >= (slot.entry as Entry).P)) {
614
+ return { action: "deleted", reason: "cache-below-P" };
615
+ }
616
+ if (!((result.P ?? 0) > 0)) {
617
+ if (slot.kind === "new") recordCommittedInput(store, slot);
618
+ return { action: "not-committed", reason: "P-zero" };
619
+ }
620
+ // Generation check: the generation at commit must equal both the lookup and the attempt-start value.
621
+ if (result.generation !== req.generation || result.generation !== slot.attemptGeneration) {
622
+ return { action: "deleted", reason: "generation-changed" };
623
+ }
624
+
625
+ // Size checks, after the slot check: the larger of the bytes streamed and the canonical output size.
626
+ if (Math.max(slot.buffered ?? 0, bytesOf(result.outputItems)) > MAX_BUFFER_BYTES) return { action: "deleted", reason: "over-buffer-cap" };
627
+
628
+ const prior = slot.kind === "matched" ? slot.entry as Entry : null;
629
+ const effort = mapEffort(req.effort as string);
630
+ const changePoints = prior
631
+ ? [...prior.changePoints, ...(slot.changePoint ? [{ at: req.changeAt, wireIndex: req.changeWireIndex as number, effort }] : [])]
632
+ : [];
633
+ const effortInEffect = prior && !slot.changePoint ? prior.effortInEffect : effort;
634
+
635
+ const prefixHash = extendChain(slot.inputHash, result.outputItems as unknown[]);
636
+ const record = {
637
+ scopeKey: slot.scopeKey,
638
+ frame: req.frame,
639
+ generation: result.generation,
640
+ prefixHash,
641
+ inputHash: slot.inputHash,
642
+ effortInEffect,
643
+ lineageKey: req.lineageKey,
644
+ anchorEffort: prior ? prior.anchorEffort : effort,
645
+ thinkingKey: req.thinkingKey,
646
+ budget: BUDGET[effort] ?? 8192,
647
+ limit: effectiveLimit(req),
648
+ changePoints,
649
+ P: result.P as number,
650
+ version: store.nextVersion++,
651
+ lastUsed: now,
652
+ };
653
+ const bytes = bytesOf(record);
654
+ if (!evictUntilFits(store, bytes)) return { action: "dropped", reason: "over-store-cap" };
655
+
656
+ const key = entryKey(slot.scopeKey, prefixHash);
657
+ // Remember the committed input so a later retry of this turn is refused even after its entry is consumed.
658
+ recordCommittedInput(store, slot);
659
+ store.entries.set(key, { ...record, bytes });
660
+ return { action: "committed", key };
661
+ }
662
+
663
+ // An error from upstream. A 400 with the documented model-unsupported text sets the capability
664
+ // record to unsupported. Every error deletes the pending slot; nothing is resent.
665
+ function rejectInner(store: EffortHistoryStore, token: unknown, { status, errorText = "" }: { status?: number; errorText?: string } = {}): EffortHistoryOutcome {
666
+ const slot = takeSlot(store, token);
667
+ if (!slot) return { action: "dropped", reason: "pending-missing" };
668
+ if (status === 400 && typeof errorText === "string" && errorText.includes(BETA_FRAGMENT)) {
669
+ store.capability.set(slot.req.capabilityKey, { state: "unsupported", at: Date.now() });
670
+ while (store.capability.size > MAX_CAPABILITY) store.capability.delete(store.capability.keys().next().value as string);
671
+ return { action: "off", reason: "capability-unsupported", deleted: true };
672
+ }
673
+ return { action: "error", reason: status === 400 ? "other-400" : "upstream-error", deleted: true };
674
+ }
675
+
676
+ // The client disconnected or the request was abandoned: nothing is committed. A matched parent is
677
+ // restored only when nothing was sent and the caller enables restore; otherwise it is deleted.
678
+ function abandonInner(store: EffortHistoryStore, token: unknown, { sent = true, restoreOnFailure = false }: { sent?: boolean; restoreOnFailure?: boolean } = {}): EffortHistoryOutcome {
679
+ const slot = takeSlot(store, token);
680
+ if (!slot) return { action: "dropped", reason: "pending-missing" };
681
+ if (!sent && restoreOnFailure && slot.kind === "matched" && slot.entry) {
682
+ if (!evictUntilFits(store, slot.entry.bytes)) return { action: "dropped", reason: "over-store-cap" };
683
+ store.entries.set(slot.key, slot.entry);
684
+ return { action: "restored" };
685
+ }
686
+ return { action: "deleted", reason: "abandoned" };
687
+ }
688
+
689
+ // A pending slot keeps only what commit needs: digests and pinned scalar values, never the request's
690
+ // items or the raw lineage, scope or thinking field.
691
+ function pin(req: EffortHistoryRequest): PinnedRequest {
692
+ return {
693
+ lineageKey: hash(req.chatLineage), capabilityKey: capabilityKey(req.scope ?? {}), effort: req.effort,
694
+ thinkingKey: hash(req.thinking), explicitCap: req.explicitCap,
695
+ emittedMaxTokens: req.emittedMaxTokens, omittedMaxTokens: req.omittedMaxTokens,
696
+ frame: req.frame, generation: req.generation, changeAt: changePointAt(req),
697
+ ...(validWireIndex(req.changeWireIndex) ? { changeWireIndex: req.changeWireIndex } : {}),
698
+ };
699
+ }
700
+
701
+ function takeOrIgnore(store: EffortHistoryStore, token: unknown): void {
702
+ try {
703
+ takeSlot(store, token);
704
+ } catch {
705
+ // A malformed store is left as it is; the caller gets a fail-closed result.
706
+ }
707
+ }
708
+
709
+ /** Decide one request. Any internal failure is "off". */
710
+ export function decide(store: EffortHistoryStore, req: EffortHistoryRequest, opts?: EffortHistoryOptions): EffortHistoryDecision {
711
+ try { return decideWithCleanup(store, req, opts); } catch { return off("internal-error"); }
712
+ }
713
+ export function commit(store: EffortHistoryStore, token: unknown, result: EffortHistoryCommitResult, now?: number): EffortHistoryOutcome {
714
+ try { return commitInner(store, token, result, now); } catch { takeOrIgnore(store, token); return { action: "deleted", reason: "internal-error" }; }
715
+ }
716
+ export function buffer(store: EffortHistoryStore, token: unknown, bytes: number): EffortHistoryOutcome {
717
+ try { return bufferInner(store, token, bytes); } catch { takeOrIgnore(store, token); return { action: "deleted", reason: "internal-error" }; }
718
+ }
719
+ export function rejectUpstream(store: EffortHistoryStore, token: unknown, error?: { status?: number; errorText?: string }): EffortHistoryOutcome {
720
+ try { return rejectInner(store, token, error); } catch { takeOrIgnore(store, token); return { action: "error", reason: "internal-error", deleted: true }; }
721
+ }
722
+ export function abandon(store: EffortHistoryStore, token: unknown, opts?: { sent?: boolean; restoreOnFailure?: boolean }): EffortHistoryOutcome {
723
+ try { return abandonInner(store, token, opts); } catch { takeOrIgnore(store, token); return { action: "deleted", reason: "internal-error" }; }
724
+ }
725
+
726
+ // The change point goes after the leading tool results, before the user message, as an index into
727
+ // the request input array (the parent items come first).
728
+ function changePointAt(req: EffortHistoryRequest): number {
729
+ const firstUser = req.suffix.findIndex(isUser);
730
+ return req.parent.length + (firstUser < 0 ? 0 : firstUser);
731
+ }
732
+