@coseung2/opencodex 2.8.0-cs.13 → 2.8.0-cs.14

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 (60) hide show
  1. package/gui/dist/assets/index-MUpaVatk.js +67 -0
  2. package/gui/dist/index.html +1 -1
  3. package/package.json +3 -3
  4. package/packages/ocx-notch/README.md +2 -1
  5. package/src/adapters/cursor/discovery.ts +6 -2
  6. package/src/adapters/cursor/effort-map.ts +3 -0
  7. package/src/adapters/google-antigravity-replay.ts +24 -0
  8. package/src/adapters/google.ts +16 -11
  9. package/src/chat/inbound.ts +5 -11
  10. package/src/cli/account-api.ts +9 -1
  11. package/src/cli/account-extended.ts +4 -1
  12. package/src/codex/account-label.ts +14 -1
  13. package/src/codex/account-lifecycle.ts +12 -1
  14. package/src/codex/account-namespaces.ts +21 -0
  15. package/src/codex/account-priority.ts +49 -0
  16. package/src/codex/account-store.ts +2 -1
  17. package/src/codex/auth-api.ts +108 -17
  18. package/src/codex/auth-context.ts +61 -16
  19. package/src/codex/catalog/metadata.ts +34 -12
  20. package/src/codex/catalog/parsing.ts +8 -1
  21. package/src/codex/catalog/provider-fetch.ts +24 -6
  22. package/src/codex/catalog.ts +1 -1
  23. package/src/codex/pool-rotation.ts +51 -4
  24. package/src/codex/quota.ts +154 -35
  25. package/src/codex/routing.ts +133 -33
  26. package/src/codex/warmup.ts +193 -85
  27. package/src/config.ts +84 -1
  28. package/src/lib/bounded-body.ts +13 -6
  29. package/src/lib/bun-stream-caps.ts +5 -6
  30. package/src/lib/redact.ts +13 -0
  31. package/src/oauth/index.ts +79 -12
  32. package/src/oauth/log.ts +3 -1
  33. package/src/oauth/store.ts +31 -8
  34. package/src/providers/antigravity-models.ts +53 -24
  35. package/src/providers/codex-capacity.ts +303 -0
  36. package/src/providers/model-rename-migration.ts +147 -0
  37. package/src/providers/model-rename-startup.ts +29 -0
  38. package/src/providers/quota.ts +126 -16
  39. package/src/providers/registry.ts +258 -38
  40. package/src/responses/parser.ts +19 -12
  41. package/src/responses/spill-store.ts +14 -1
  42. package/src/responses/state.ts +108 -14
  43. package/src/server/index.ts +9 -1
  44. package/src/server/management/logs-usage-routes.ts +1 -0
  45. package/src/server/management/oauth-account-routes.ts +8 -1
  46. package/src/server/relay.ts +10 -42
  47. package/src/server/request-log.ts +42 -1
  48. package/src/server/responses/compact.ts +16 -4
  49. package/src/server/responses/core.ts +217 -59
  50. package/src/server/responses/empty-completion-guard.ts +275 -0
  51. package/src/server/responses/encrypted-payload.ts +54 -39
  52. package/src/server/responses/fetch-helpers.ts +24 -3
  53. package/src/server/responses/ws-upstream.ts +318 -0
  54. package/src/server/sse-frame-buffer.ts +292 -0
  55. package/src/server/ws-bridge.ts +17 -11
  56. package/src/types.ts +8 -0
  57. package/src/usage/log.ts +24 -0
  58. package/src/usage/summary.ts +152 -2
  59. package/vendor/ocx-notch/win32-x64/ocx-notch.exe +0 -0
  60. package/gui/dist/assets/index-BucjyD4I.js +0 -67
@@ -0,0 +1,275 @@
1
+ import type { AdapterEvent, OcxConfig, OcxUsage } from "../../types";
2
+
3
+ /**
4
+ * Empty-completion guard for Responses turns (port of codex-router's
5
+ * empty-completion-guard + single retry, PR #145).
6
+ *
7
+ * Failure mode: the upstream answers 200 and completes the turn but never
8
+ * produced output text or a tool call (a reasoning-only stream that ends with
9
+ * nothing is the canonical shape). The client has no code path for "the model
10
+ * said nothing", so it silently records the turn as done — the "random stop"
11
+ * nobody can explain. The guard holds pre-content events (reasoning deltas
12
+ * are deliberately NOT content), and when a terminal event arrives with no
13
+ * content it suppresses the terminal and retries the IDENTICAL turn once
14
+ * (same request bytes, same headers). If the retry is also empty — or fails
15
+ * upstream — the client sees a stated failure instead of a second silent
16
+ * success.
17
+ *
18
+ * The retry is explicitly enabled by top-level config. The environment switch
19
+ * is a disable-only emergency override: OCX_EMPTY_COMPLETION_RETRY=0 restores
20
+ * the previous relay behavior without editing the persisted config.
21
+ */
22
+ export const EMPTY_COMPLETION_RETRY_ENV = "OCX_EMPTY_COMPLETION_RETRY";
23
+
24
+ /** Retained pre-content events are bounded independently by count and encoded size. */
25
+ export const EMPTY_COMPLETION_MAX_BUFFERED_EVENTS = 1_024;
26
+ export const EMPTY_COMPLETION_MAX_BUFFERED_BYTES = 1_048_576;
27
+
28
+ export function emptyCompletionRetryEnabled(
29
+ config: Pick<OcxConfig, "emptyCompletionRetry">,
30
+ env: Record<string, string | undefined> = process.env,
31
+ ): boolean {
32
+ return config.emptyCompletionRetry === true && env[EMPTY_COMPLETION_RETRY_ENV] !== "0";
33
+ }
34
+
35
+ /** Surfaced when the single retry was also empty or failed upstream. */
36
+ export const EMPTY_COMPLETION_RETRY_FAILED_CODE = "empty_completion_retry_failed";
37
+
38
+ /**
39
+ * Terminal stop reasons the bridge renders as a visible `response.incomplete`
40
+ * (max_tokens / content_filter). Those are already a stated failure, not the
41
+ * silent empty success this guard exists to catch, and retrying the identical
42
+ * request would burn tokens for the same truncated result.
43
+ */
44
+ const VISIBLE_INCOMPLETE_STOP_REASONS = new Set(["max_tokens", "content_filter"]);
45
+ const UTF8_ENCODER = new TextEncoder();
46
+
47
+ function retainedEventBytes(event: AdapterEvent): number {
48
+ return UTF8_ENCODER.encode(JSON.stringify(event)).byteLength;
49
+ }
50
+
51
+ function isReasoningEvent(event: AdapterEvent): boolean {
52
+ return event.type === "thinking_delta"
53
+ || event.type === "thinking_signature"
54
+ || event.type === "redacted_thinking"
55
+ || event.type === "reasoning_raw_delta";
56
+ }
57
+
58
+ function isTerminalEvent(
59
+ event: AdapterEvent,
60
+ ): event is Extract<AdapterEvent, { type: "done" | "incomplete" | "error" }> {
61
+ return event.type === "done" || event.type === "incomplete" || event.type === "error";
62
+ }
63
+
64
+ /**
65
+ * Content means something the client can act on: output text or a tool call
66
+ * (web-search cells included). Reasoning deltas are deliberately not content —
67
+ * a turn that streams only reasoning and then completes with nothing is
68
+ * exactly the empty completion this guard exists to catch. Empty text deltas
69
+ * (some batch adapters always carry `""`) are not content either.
70
+ */
71
+ export function isContentEvent(event: AdapterEvent): boolean {
72
+ switch (event.type) {
73
+ case "text_delta":
74
+ return event.text.length > 0;
75
+ case "tool_call_start":
76
+ case "tool_call_delta":
77
+ case "tool_call_end":
78
+ case "web_search_call_begin":
79
+ case "web_search_call_end":
80
+ return true;
81
+ default:
82
+ return false;
83
+ }
84
+ }
85
+
86
+ export function emptyCompletionRetryFailedEvent(
87
+ usage?: OcxUsage,
88
+ retryFailedUpstream = false,
89
+ ): Extract<AdapterEvent, { type: "error" }> {
90
+ return {
91
+ type: "error",
92
+ status: 502,
93
+ errorType: "upstream_error",
94
+ code: EMPTY_COMPLETION_RETRY_FAILED_CODE,
95
+ message: retryFailedUpstream
96
+ ? "The model returned an empty completion and the retry failed upstream."
97
+ : "The model returned an empty completion. opencodex retried once and the completion was empty again.",
98
+ ...(usage ? { usage } : {}),
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Sum two usage snapshots. Same semantics as terminal-guard's mergeUsage and
104
+ * request-log's aggregateAttemptUsage: token totals add across the attempts;
105
+ * `estimated` wins when either attempt only estimated.
106
+ */
107
+ export function mergeUsage(
108
+ first: OcxUsage | undefined,
109
+ second: OcxUsage | undefined,
110
+ ): OcxUsage | undefined {
111
+ if (!first) return second;
112
+ if (!second) return first;
113
+ const sumOptional = (key: keyof OcxUsage): number | undefined => {
114
+ const left = first[key];
115
+ const right = second[key];
116
+ return typeof left === "number" || typeof right === "number"
117
+ ? (typeof left === "number" ? left : 0) + (typeof right === "number" ? right : 0)
118
+ : undefined;
119
+ };
120
+ const cachedInputTokens = sumOptional("cachedInputTokens");
121
+ const cacheReadInputTokens = sumOptional("cacheReadInputTokens");
122
+ const cacheCreationInputTokens = sumOptional("cacheCreationInputTokens");
123
+ const reasoningOutputTokens = sumOptional("reasoningOutputTokens");
124
+ const contextTotalTokens = second.contextTotalTokens ?? first.contextTotalTokens;
125
+ const inputTokens = first.inputTokens + second.inputTokens;
126
+ const outputTokens = first.outputTokens + second.outputTokens;
127
+ return {
128
+ inputTokens,
129
+ outputTokens,
130
+ totalTokens: inputTokens + outputTokens,
131
+ ...(contextTotalTokens !== undefined ? { contextTotalTokens } : {}),
132
+ ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
133
+ ...(cacheReadInputTokens !== undefined ? { cacheReadInputTokens } : {}),
134
+ ...(cacheCreationInputTokens !== undefined ? { cacheCreationInputTokens } : {}),
135
+ ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
136
+ ...(first.estimated || second.estimated ? { estimated: true } : {}),
137
+ };
138
+ }
139
+
140
+ export interface EmptyCompletionGuardOptions {
141
+ firstEvents: AsyncIterable<AdapterEvent>;
142
+ /**
143
+ * Re-run the IDENTICAL turn: same request body, same headers, same signal.
144
+ * Receives no arguments — the request must not be modified between attempts.
145
+ */
146
+ continuation: () => AsyncIterable<AdapterEvent> | Promise<AsyncIterable<AdapterEvent>>;
147
+ /** How many times an empty completion is retried; default 1 (the router's single retry). */
148
+ maxRetries?: number;
149
+ }
150
+
151
+ /**
152
+ * Watch an adapter event stream for the empty-completion failure mode. Events
153
+ * are held until the turn produces content or ends: reasoning and other
154
+ * pre-content events stay buffered (released in order on first content), the
155
+ * terminal is withheld, and an empty terminal triggers one identical-turn
156
+ * retry through `continuation`. Usage is merged across attempts so the bridge
157
+ * and request log meter the whole turn, not just the attempt that succeeded.
158
+ *
159
+ * Heartbeats always pass through untouched: they feed the bridge's stall
160
+ * watchdog, so holding them behind the content gate would trip false
161
+ * upstream_stall_timeout failures on slow reasoning-only turns.
162
+ */
163
+ export async function* guardEmptyCompletionEventStream(
164
+ options: EmptyCompletionGuardOptions,
165
+ ): AsyncGenerator<AdapterEvent> {
166
+ const maxRetries = Math.max(0, Math.floor(options.maxRetries ?? 1));
167
+ let source = options.firstEvents;
168
+ let held: AdapterEvent[] = [];
169
+ let heldBytes = 0;
170
+ let sawContent = false;
171
+ let passthrough = false;
172
+ let retries = 0;
173
+ let usage: OcxUsage | undefined;
174
+
175
+ const withUsage = (event: AdapterEvent & { usage?: OcxUsage }): AdapterEvent => {
176
+ const merged = mergeUsage(usage, event.usage);
177
+ return merged ? { ...event, ...(merged ? { usage: merged } : {}) } : event;
178
+ };
179
+ const releaseHeld = (): AdapterEvent[] => {
180
+ const released = held;
181
+ held = [];
182
+ heldBytes = 0;
183
+ return released;
184
+ };
185
+
186
+ while (true) {
187
+ let terminalSeen = false;
188
+ for await (const event of source) {
189
+ if (event.type === "heartbeat") {
190
+ yield event;
191
+ continue;
192
+ }
193
+ if (sawContent || passthrough) {
194
+ // Buffered content is already flowing; everything downstream passes
195
+ // through. Every terminal carries usage merged across every attempt.
196
+ yield isTerminalEvent(event) ? withUsage(event) : event;
197
+ continue;
198
+ }
199
+ if (isContentEvent(event)) {
200
+ sawContent = true;
201
+ yield* releaseHeld();
202
+ yield event;
203
+ continue;
204
+ }
205
+ if (event.type === "done") {
206
+ usage = mergeUsage(usage, event.usage);
207
+ if (event.stopReason !== undefined && VISIBLE_INCOMPLETE_STOP_REASONS.has(event.stopReason)) {
208
+ // Rendered as response.incomplete: a stated failure, not the silent
209
+ // empty success this guard exists to catch.
210
+ yield* releaseHeld();
211
+ yield { ...event, ...(usage ? { usage } : {}) };
212
+ return;
213
+ }
214
+ if (retries < maxRetries) {
215
+ // Suppress the terminal: the client must never see a completed event
216
+ // for a turn that produced nothing. Retry the identical turn.
217
+ retries += 1;
218
+ try {
219
+ source = await options.continuation();
220
+ } catch {
221
+ yield emptyCompletionRetryFailedEvent(usage, true);
222
+ return;
223
+ }
224
+ terminalSeen = true;
225
+ break;
226
+ }
227
+ // The retry was also empty: a stated failure, not a second silent
228
+ // success.
229
+ yield emptyCompletionRetryFailedEvent(usage);
230
+ return;
231
+ }
232
+ if (event.type === "error") {
233
+ if (retries > 0 && event.status !== 499) {
234
+ // The retry failed upstream. Its body cannot reach the client (the
235
+ // 200 head went out with the first attempt), so state the failure in
236
+ // the stream's own error framing — same move as the router's
237
+ // empty_completion_retry_failed. Client cancels (499) pass through.
238
+ yield emptyCompletionRetryFailedEvent(mergeUsage(usage, event.usage), true);
239
+ return;
240
+ }
241
+ yield* releaseHeld();
242
+ yield withUsage(event);
243
+ return;
244
+ }
245
+ if (event.type === "incomplete") {
246
+ // A structured incomplete is already a visible failure; never convert
247
+ // it into an empty completion.
248
+ yield* releaseHeld();
249
+ yield withUsage(event);
250
+ return;
251
+ }
252
+ const eventBytes = retainedEventBytes(event);
253
+ if (held.length + 1 > EMPTY_COMPLETION_MAX_BUFFERED_EVENTS
254
+ || heldBytes + eventBytes > EMPTY_COMPLETION_MAX_BUFFERED_BYTES) {
255
+ // Preserve data rather than retaining without bound: release the prefix,
256
+ // emit this event, and stop attempting an empty-completion retry for the turn.
257
+ yield* releaseHeld();
258
+ yield event;
259
+ passthrough = true;
260
+ continue;
261
+ }
262
+ held.push(event);
263
+ heldBytes += eventBytes;
264
+ // The bridge watchdog sees only yielded events. Feed it while reasoning is
265
+ // held so a long reasoning-only prefix remains live without exposing it early.
266
+ if (isReasoningEvent(event)) yield { type: "heartbeat" };
267
+ }
268
+ if (!terminalSeen) {
269
+ // The source ended without a terminal event (truncated stream). Release
270
+ // what was held so the bridge can mark the stream incomplete.
271
+ yield* releaseHeld();
272
+ return;
273
+ }
274
+ }
275
+ }
@@ -261,48 +261,63 @@ export function hasEncryptedContentPart(content: unknown): boolean {
261
261
  export function sanitizeEncryptedContentInPlace(input: unknown): number {
262
262
  if (!Array.isArray(input)) return 0;
263
263
  let rewritten = 0;
264
- const visit = (node: unknown): number => {
265
- const before = rewritten;
266
- if (Array.isArray(node)) {
267
- for (let i = 0; i < node.length; i += 1) {
268
- const child = node[i] as unknown;
269
- if (
270
- child && typeof child === "object"
271
- && (child as { type?: unknown }).type === "encrypted_content"
272
- && typeof (child as { encrypted_content?: unknown }).encrypted_content === "string"
273
- ) {
274
- const payload = (child as { encrypted_content: string }).encrypted_content;
275
- if (!looksLikeBackendCiphertext(payload)) {
276
- const parts = encryptedSlotParts(payload);
277
- node.splice(i, 1, ...parts);
278
- i += parts.length - 1;
279
- rewritten += 1;
280
- continue;
281
- }
282
- }
283
- const childRewrites = visit(child);
284
- if (
285
- childRewrites > 0
286
- && child && typeof child === "object"
287
- && (child as { type?: unknown }).type === "agent_message"
288
- && !hasEncryptedContentPart((child as { content?: unknown }).content)
289
- ) {
290
- const message = child as { type: string; role?: string; id?: unknown; author?: unknown; recipient?: unknown };
291
- message.type = "message";
292
- message.role = "user";
293
- delete message.id;
294
- delete message.author;
295
- delete message.recipient;
264
+ type VisitFrame =
265
+ | { kind: "visit"; node: unknown }
266
+ | { kind: "array"; node: unknown[]; index: number }
267
+ | { kind: "object"; values: unknown[]; index: number }
268
+ | { kind: "agent"; message: Record<string, unknown>; rewrittenBefore: number };
269
+ const stack: VisitFrame[] = [{ kind: "visit", node: input }];
270
+
271
+ while (stack.length > 0) {
272
+ const frame = stack.pop()!;
273
+ if (frame.kind === "visit") {
274
+ if (Array.isArray(frame.node)) stack.push({ kind: "array", node: frame.node, index: 0 });
275
+ else if (frame.node && typeof frame.node === "object") {
276
+ stack.push({ kind: "object", values: Object.values(frame.node), index: 0 });
277
+ }
278
+ continue;
279
+ }
280
+ if (frame.kind === "array") {
281
+ if (frame.index >= frame.node.length) continue;
282
+ const child = frame.node[frame.index] as unknown;
283
+ if (
284
+ child && typeof child === "object"
285
+ && (child as { type?: unknown }).type === "encrypted_content"
286
+ && typeof (child as { encrypted_content?: unknown }).encrypted_content === "string"
287
+ ) {
288
+ const payload = (child as { encrypted_content: string }).encrypted_content;
289
+ if (!looksLikeBackendCiphertext(payload)) {
290
+ const parts = encryptedSlotParts(payload);
291
+ frame.node.splice(frame.index, 1, ...parts);
292
+ rewritten += 1;
293
+ stack.push({ kind: "array", node: frame.node, index: frame.index + parts.length });
294
+ continue;
296
295
  }
297
296
  }
298
- return rewritten - before;
297
+ stack.push({ kind: "array", node: frame.node, index: frame.index + 1 });
298
+ if (child && typeof child === "object" && (child as { type?: unknown }).type === "agent_message") {
299
+ stack.push({ kind: "agent", message: child as Record<string, unknown>, rewrittenBefore: rewritten });
300
+ }
301
+ stack.push({ kind: "visit", node: child });
302
+ continue;
299
303
  }
300
- if (node && typeof node === "object") {
301
- for (const value of Object.values(node)) visit(value);
304
+ if (frame.kind === "object") {
305
+ if (frame.index >= frame.values.length) continue;
306
+ stack.push({ kind: "object", values: frame.values, index: frame.index + 1 });
307
+ stack.push({ kind: "visit", node: frame.values[frame.index] });
308
+ continue;
309
+ }
310
+ if (
311
+ rewritten > frame.rewrittenBefore
312
+ && frame.message.type === "agent_message"
313
+ && !hasEncryptedContentPart(frame.message.content)
314
+ ) {
315
+ frame.message.type = "message";
316
+ frame.message.role = "user";
317
+ delete frame.message.id;
318
+ delete frame.message.author;
319
+ delete frame.message.recipient;
302
320
  }
303
- return rewritten - before;
304
- };
305
- visit(input);
321
+ }
306
322
  return rewritten;
307
323
  }
308
-
@@ -1,4 +1,10 @@
1
1
  import type { Server } from "bun";
2
+ import {
3
+ codexWsUpstreamFetch,
4
+ currentBunRuntimeIdentity,
5
+ shouldUseCodexWsUpstream,
6
+ type BunRuntimeGateInput,
7
+ } from "./ws-upstream";
2
8
  import { bridgeToResponsesSSE, buildResponseJSON, formatErrorResponse, type ResponsesTerminalStatus } from "../../bridge";
3
9
  import {
4
10
  getConfigPath,
@@ -120,8 +126,24 @@ export function safeHostLabel(url: string): string {
120
126
 
121
127
 
122
128
 
123
- export function providerFetch(provider: OcxProviderConfig): typeof globalThis.fetch {
124
- return (provider as OcxProviderConfig & { fetch?: typeof globalThis.fetch }).fetch ?? globalThis.fetch;
129
+ export function providerFetch(
130
+ provider: OcxProviderConfig,
131
+ runtime: BunRuntimeGateInput = currentBunRuntimeIdentity(),
132
+ ): typeof globalThis.fetch {
133
+ const base = (provider as OcxProviderConfig & { fetch?: typeof globalThis.fetch }).fetch ?? globalThis.fetch;
134
+ const wrapped = async (
135
+ input: Parameters<typeof globalThis.fetch>[0],
136
+ init?: RequestInit,
137
+ ): Promise<Response> => {
138
+ if (typeof input === "string" && init && shouldUseCodexWsUpstream(input, init, runtime)) {
139
+ return codexWsUpstreamFetch(input, init, base, runtime);
140
+ }
141
+ return base(input, init);
142
+ };
143
+ const preconnect = (...args: Parameters<typeof globalThis.fetch.preconnect>): void => {
144
+ base.preconnect?.(...args);
145
+ };
146
+ return Object.assign(wrapped, { preconnect });
125
147
  }
126
148
 
127
149
 
@@ -154,4 +176,3 @@ export async function fetchWithHeaderTimeout(
154
176
  clearTimeout(timer);
155
177
  }
156
178
  }
157
-