@bitkyc08/opencodex 2.7.9-preview.20260712.2 → 2.7.9

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.
@@ -0,0 +1,187 @@
1
+ import type { OcxProviderConfig } from "../types";
2
+ import { getValidAccessToken } from "../oauth";
3
+ import { ANTHROPIC_OAUTH_BETA, CLAUDE_CODE_SYSTEM_INSTRUCTION } from "../oauth/anthropic";
4
+ import { CLAUDE_CODE_HEADERS, claudeCodeSessionId } from "../adapters/client-fingerprint";
5
+ import { signalWithTimeout, cancelBodyOnAbort } from "../lib/abort";
6
+ import { sidecarEnter } from "../lib/sidecar-tracker";
7
+ import { fetchWithResetRetry } from "../lib/upstream-retry";
8
+ import type { WebSearchSource } from "./parse";
9
+ import { BASE_INSTRUCTION, IMAGE_INSTRUCTION, type SidecarOutcome, type SidecarSettings } from "./executor";
10
+
11
+ /** Hardcoded per-turn search bound handed to the server tool (mirrors the loop's maxSearches intent). */
12
+ const ANTHROPIC_MAX_USES = 3;
13
+ /** Answer budget; the injected tool_result is clamped downstream, so this only bounds the sidecar turn. */
14
+ const ANTHROPIC_MAX_TOKENS = 8192;
15
+
16
+ function isRec(v: unknown): v is Record<string, unknown> {
17
+ return !!v && typeof v === "object" && !Array.isArray(v);
18
+ }
19
+
20
+ /**
21
+ * Fold an Anthropic Messages SSE stream (a web_search_20250305 turn) into a WebSearchResult.
22
+ *
23
+ * Anthropic streams the FULL `web_search_tool_result.content` array on `content_block_start` (not via
24
+ * deltas), so sources are collected there; the answer text arrives as `text_delta` events, and
25
+ * `citations_delta` (web_search_result_location) contributes any additional cited URLs. A
26
+ * `web_search_tool_result_error` content object yields no sources. Never throws.
27
+ */
28
+ export async function parseAnthropicSidecarSSE(res: Response): Promise<SidecarOutcome> {
29
+ const sources: WebSearchSource[] = [];
30
+ const seen = new Set<string>();
31
+ const pushSource = (url: unknown, title: unknown): void => {
32
+ if (typeof url !== "string" || url.length === 0 || seen.has(url)) return;
33
+ seen.add(url);
34
+ sources.push(typeof title === "string" && title.length > 0 ? { url, title } : { url });
35
+ };
36
+
37
+ let text = "";
38
+ let sawToolResultError = false;
39
+ if (!res.body) return { text: "", sources, error: "anthropic sidecar returned no response body" };
40
+
41
+ const decoder = new TextDecoder();
42
+ const reader = res.body.getReader();
43
+ let buffer = "";
44
+
45
+ const handleFrame = (data: Record<string, unknown>): void => {
46
+ const type = typeof data.type === "string" ? data.type : "";
47
+ if (type === "content_block_start") {
48
+ const block = isRec(data.content_block) ? data.content_block : {};
49
+ if (block.type === "web_search_tool_result") {
50
+ if (Array.isArray(block.content)) {
51
+ for (const hit of block.content) {
52
+ if (isRec(hit) && hit.type === "web_search_result") pushSource(hit.url, hit.title);
53
+ }
54
+ } else if (isRec(block.content) && block.content.type === "web_search_tool_result_error") {
55
+ sawToolResultError = true;
56
+ }
57
+ }
58
+ } else if (type === "content_block_delta") {
59
+ const delta = isRec(data.delta) ? data.delta : {};
60
+ if (delta.type === "text_delta" && typeof delta.text === "string") {
61
+ text += delta.text;
62
+ } else if (delta.type === "citations_delta") {
63
+ const citation = isRec(delta.citation) ? delta.citation : {};
64
+ if (citation.type === "web_search_result_location") pushSource(citation.url, citation.title);
65
+ }
66
+ }
67
+ };
68
+
69
+ // Parse one SSE frame's `data:` payload and fold it. Shared by the streaming loop and the EOF flush.
70
+ const processFrame = (rawFrame: string): void => {
71
+ let dataLine = "";
72
+ for (const line of rawFrame.split("\n")) {
73
+ if (line.startsWith("data:")) dataLine += line.slice(line.startsWith("data: ") ? 6 : 5);
74
+ }
75
+ if (!dataLine || dataLine === "[DONE]") return;
76
+ let data: unknown;
77
+ try { data = JSON.parse(dataLine); } catch { return; }
78
+ if (isRec(data)) handleFrame(data);
79
+ };
80
+
81
+ try {
82
+ for (;;) {
83
+ const { done, value } = await reader.read();
84
+ if (done) break;
85
+ // Normalize CRLF on the ACCUMULATED buffer so a `\r\n` pair split across two network chunks
86
+ // (chunk ends in `\r`, next starts with `\n`) still collapses to `\n` (audit round-2 F2).
87
+ buffer = (buffer + decoder.decode(value, { stream: true })).replace(/\r\n/g, "\n");
88
+ let sep: number;
89
+ while ((sep = buffer.indexOf("\n\n")) !== -1) {
90
+ const rawFrame = buffer.slice(0, sep);
91
+ buffer = buffer.slice(sep + 2);
92
+ processFrame(rawFrame);
93
+ }
94
+ }
95
+ // Flush the decoder and process any final unterminated frame (a stream that ends without \n\n).
96
+ buffer = (buffer + decoder.decode()).replace(/\r\n/g, "\n");
97
+ if (buffer.trim().length > 0) processFrame(buffer);
98
+ } catch {
99
+ /* mid-stream abort/decode failure: fall through with whatever text/sources were gathered */
100
+ }
101
+
102
+ const trimmed = text.trim();
103
+ if (trimmed.length === 0) {
104
+ return { text: "", sources, error: sawToolResultError ? "anthropic web search returned an error result" : "anthropic sidecar produced no answer" };
105
+ }
106
+ return { text: trimmed, sources };
107
+ }
108
+
109
+ /**
110
+ * Execute ONE web search via a Claude sidecar through the STORED anthropic OAuth credential — the
111
+ * Anthropic-backed analog of runWebSearch. Authenticates with getValidAccessToken (refresh handled)
112
+ * and reproduces the Claude Code OAuth fingerprint (identity system block first, oauth beta, client
113
+ * headers, stable session id) so the request is first-party-shaped. Never throws — returns `{error}`
114
+ * so the caller injects a graceful tool result.
115
+ */
116
+ export async function runAnthropicWebSearch(
117
+ query: string,
118
+ providerName: string,
119
+ provider: OcxProviderConfig,
120
+ settings: SidecarSettings,
121
+ abortSignal?: AbortSignal,
122
+ ): Promise<SidecarOutcome> {
123
+ const base = provider.baseUrl.replace(/\/v1\/?$/, "");
124
+ const url = `${base}/v1/messages`;
125
+ let token: string;
126
+ try {
127
+ token = await getValidAccessToken(providerName);
128
+ } catch (e) {
129
+ return { text: "", sources: [], error: `anthropic sidecar auth failed: ${e instanceof Error ? e.message : String(e)}` };
130
+ }
131
+ const headers: Record<string, string> = {
132
+ "Content-Type": "application/json",
133
+ "anthropic-version": "2023-06-01",
134
+ "Accept": "text/event-stream",
135
+ "User-Agent": "@anthropic-ai/sdk/0.74.0",
136
+ "Authorization": `Bearer ${token}`,
137
+ "anthropic-beta": ANTHROPIC_OAUTH_BETA,
138
+ ...CLAUDE_CODE_HEADERS,
139
+ "X-Claude-Code-Session-Id": claudeCodeSessionId(token),
140
+ "x-client-request-id": crypto.randomUUID(),
141
+ };
142
+ if (provider.headers) Object.assign(headers, provider.headers);
143
+
144
+ const instruction = settings.describeImages ? BASE_INSTRUCTION + IMAGE_INSTRUCTION : BASE_INSTRUCTION;
145
+ const body = {
146
+ model: settings.model,
147
+ max_tokens: ANTHROPIC_MAX_TOKENS,
148
+ // sonnet-5 defaults to adaptive thinking when omitted; keep the sidecar fast/cheap (audit F2).
149
+ thinking: { type: "disabled" },
150
+ // OAuth fingerprint requires the Claude Code identity as the FIRST system block (audit F6/anthropic.ts).
151
+ system: [
152
+ { type: "text", text: CLAUDE_CODE_SYSTEM_INSTRUCTION },
153
+ { type: "text", text: instruction },
154
+ ],
155
+ messages: [{ role: "user", content: [{ type: "text", text: query }] }],
156
+ tools: [{ type: "web_search_20250305", name: "web_search", max_uses: ANTHROPIC_MAX_USES }],
157
+ stream: true,
158
+ };
159
+
160
+ const linkedSignal = signalWithTimeout(settings.timeoutMs, abortSignal);
161
+ const sidecarExit = sidecarEnter("web-search");
162
+ const t0 = Date.now();
163
+ try {
164
+ const res = await fetchWithResetRetry(
165
+ () => fetch(url, { method: "POST", headers, body: JSON.stringify(body), signal: linkedSignal.signal }),
166
+ { abortSignal: linkedSignal.signal, label: "web-search-sidecar-anthropic" },
167
+ );
168
+ if (!res.ok) {
169
+ const t = await res.text().catch(() => "");
170
+ console.warn(`[web-search] anthropic sidecar HTTP ${res.status} for query "${query.slice(0, 80)}" (${Date.now() - t0}ms)`);
171
+ return { text: "", sources: [], error: `sidecar HTTP ${res.status}: ${t.slice(0, 200)}` };
172
+ }
173
+ const detachBodyGuard = cancelBodyOnAbort(res.body, linkedSignal.signal);
174
+ try {
175
+ return await parseAnthropicSidecarSSE(res);
176
+ } finally {
177
+ detachBodyGuard();
178
+ }
179
+ } catch (e) {
180
+ const kind = e instanceof Error && e.name === "TimeoutError" ? "timeout" : "connect_error";
181
+ console.warn(`[web-search] anthropic sidecar ${kind} for query "${query.slice(0, 80)}" (${Date.now() - t0}ms)`);
182
+ return { text: "", sources: [], error: e instanceof Error ? e.message : String(e) };
183
+ } finally {
184
+ sidecarExit();
185
+ linkedSignal.cleanup();
186
+ }
187
+ }
@@ -18,11 +18,13 @@ export interface SidecarSettings {
18
18
  describeImages?: boolean;
19
19
  }
20
20
 
21
- const BASE_INSTRUCTION =
21
+ // Shared with the anthropic-backed executor (single source; audit F3). The instruction is
22
+ // backend-agnostic — both the gpt-mini sidecar and a Claude sidecar answer the same way.
23
+ export const BASE_INSTRUCTION =
22
24
  "You are a web-search assistant. Use the web_search tool to find current information for the " +
23
25
  "user's query, then reply with a concise, factual answer. End your reply with a `Sources:` " +
24
26
  "section listing each source you used on its own line as `- Title: URL` (one per line).";
25
- const IMAGE_INSTRUCTION =
27
+ export const IMAGE_INSTRUCTION =
26
28
  " The model that will read your answer is TEXT-ONLY and cannot see images: if the results include " +
27
29
  "relevant images, describe what they show in words and include their source URLs in your answer.";
28
30
 
@@ -2,11 +2,15 @@ import type { OcxConfig, OcxParsedRequest, OcxProviderConfig } from "../types";
2
2
  import { modelInList } from "../types";
3
3
  import type { SidecarSettings } from "./executor";
4
4
  import type { CodexAuthContext } from "../codex/auth-context";
5
+ import { getAccountSet } from "../oauth/store";
5
6
 
6
7
  export { runWithWebSearch } from "./loop";
7
8
  export { buildWebSearchTool, extractHostedWebSearch, WEB_SEARCH_TOOL_NAME } from "./synthetic-tool";
9
+ export { runAnthropicWebSearch, parseAnthropicSidecarSSE } from "./anthropic-executor";
8
10
 
9
11
  const DEFAULT_SIDECAR_MODEL = "gpt-5.6-luna";
12
+ // Default Claude model for the anthropic-backed sidecar (used when cfg.model is unset).
13
+ const DEFAULT_ANTHROPIC_SIDECAR_MODEL = "claude-sonnet-5";
10
14
  // "low" is the lightest effort the ChatGPT backend allows with web_search ("minimal" is rejected:
11
15
  // "tools cannot be used with reasoning.effort 'minimal'") — keeps the sidecar fast/cheap.
12
16
  const DEFAULT_SIDECAR_REASONING = "low";
@@ -70,8 +74,45 @@ export function findForwardProvider(config: OcxConfig): OcxProviderConfig | unde
70
74
  return undefined;
71
75
  }
72
76
 
77
+ /** A configured anthropic-adapter OAuth provider whose ACTIVE stored account is usable (not needs-reauth). */
78
+ export interface AnthropicSidecarProvider {
79
+ providerName: string;
80
+ provider: OcxProviderConfig;
81
+ }
82
+
83
+ /**
84
+ * First enabled anthropic-adapter OAuth provider whose ACTIVE account holds a usable credential — the
85
+ * only path that can run web_search_20250305 without a ChatGPT forward provider. Presence is decided by
86
+ * getAccountSet + the active account's `needsReauth` marker (audit F1: getCredential alone can pick a
87
+ * terminally-invalid account); token refresh happens later at executor time.
88
+ */
89
+ export function findAnthropicSidecarProvider(config: OcxConfig): AnthropicSidecarProvider | undefined {
90
+ for (const [name, prov] of Object.entries(config.providers)) {
91
+ if (prov.disabled === true) continue;
92
+ if (prov.adapter !== "anthropic" || prov.authMode !== "oauth") continue;
93
+ const set = getAccountSet(name);
94
+ const active = set?.accounts.find(a => a.id === set.activeAccountId);
95
+ if (active && active.needsReauth !== true) return { providerName: name, provider: prov };
96
+ }
97
+ return undefined;
98
+ }
99
+
100
+ /** Precedence (audit F4/F7): explicit config wins; unset resolves to anthropic when a usable credential exists, else openai. */
101
+ export function resolveSidecarBackend(
102
+ explicit: "openai" | "anthropic" | undefined,
103
+ anthropicSidecar: AnthropicSidecarProvider | undefined,
104
+ ): "openai" | "anthropic" {
105
+ if (explicit === "anthropic" || explicit === "openai") return explicit;
106
+ return anthropicSidecar ? "anthropic" : "openai";
107
+ }
108
+
73
109
  export interface SidecarPlan {
74
- forwardProvider: OcxProviderConfig;
110
+ /** Which executor runs the search. Anthropic does not require a forward provider. */
111
+ backend: "openai" | "anthropic";
112
+ /** Present for the openai backend (ChatGPT forward path); undefined for anthropic. */
113
+ forwardProvider?: OcxProviderConfig;
114
+ /** Present for the anthropic backend (stored-OAuth /v1/messages path); undefined for openai. */
115
+ anthropicSidecar?: AnthropicSidecarProvider;
75
116
  hostedTool: Record<string, unknown>;
76
117
  settings: SidecarSettings;
77
118
  maxSearches: number;
@@ -99,30 +140,51 @@ export function planWebSearch(
99
140
  if (!parsed._webSearch || isPassthrough) return undefined;
100
141
  const cfg = config.webSearchSidecar ?? {};
101
142
  if (cfg.enabled === false) return undefined;
102
- if (authContext.kind === "main" && !incomingHeaders.get("authorization")) return undefined; // not logged into ChatGPT → sidecar can't run
103
- const forwardProvider = findForwardProvider(config);
104
- if (!forwardProvider) return undefined;
105
143
  const timeoutMs = cfg.timeoutMs ?? DEFAULT_TIMEOUT_MS;
106
144
  const routedModelStallTimeoutMs = resolveRoutedModelStallTimeoutMs(cfg.routedModelStallTimeoutMs);
107
145
  // Same `?? 200_000` default the server applies when threading connectTimeoutMs into the loop.
108
146
  const connectTimeoutMs = config.connectTimeoutMs ?? 200_000;
147
+ const anthropicSidecar = findAnthropicSidecarProvider(config);
148
+ const backend = resolveSidecarBackend(cfg.backend, anthropicSidecar);
149
+ const maxSearches = cfg.maxSearchesPerTurn ?? DEFAULT_MAX_SEARCHES;
150
+ const stallTimeoutSec = webSearchStallTimeoutSec(
151
+ config.stallTimeoutSec,
152
+ connectTimeoutMs,
153
+ routedModelStallTimeoutMs,
154
+ timeoutMs,
155
+ );
156
+ // The routed model being text-only means the search model must verbalize image results (either backend).
157
+ const describeImages = modelInList(provider.noVisionModels, modelId);
158
+ const reasoning = cfg.reasoning ?? DEFAULT_SIDECAR_REASONING;
159
+
160
+ // Anthropic backend authenticates with the STORED credential — no forward provider or ChatGPT login gate.
161
+ // resolveSidecarBackend only returns "anthropic" when it was explicitly configured OR a usable credential
162
+ // exists; an EXPLICIT anthropic choice with no usable credential FAILS CLOSED (no plan) rather than
163
+ // silently borrowing ChatGPT credentials (audit round-2 F1).
164
+ if (backend === "anthropic") {
165
+ if (!anthropicSidecar) return undefined;
166
+ return {
167
+ backend: "anthropic",
168
+ anthropicSidecar,
169
+ hostedTool: parsed._webSearch,
170
+ settings: { model: cfg.model ?? DEFAULT_ANTHROPIC_SIDECAR_MODEL, reasoning, timeoutMs, describeImages },
171
+ maxSearches,
172
+ routedModelStallTimeoutMs,
173
+ stallTimeoutSec,
174
+ };
175
+ }
176
+
177
+ // OpenAI backend: needs a ChatGPT login (main) and a forward provider to reach server-side web_search.
178
+ if (authContext.kind === "main" && !incomingHeaders.get("authorization")) return undefined;
179
+ const forwardProvider = findForwardProvider(config);
180
+ if (!forwardProvider) return undefined;
109
181
  return {
182
+ backend: "openai",
110
183
  forwardProvider,
111
184
  hostedTool: parsed._webSearch,
112
- settings: {
113
- model: cfg.model ?? DEFAULT_SIDECAR_MODEL,
114
- reasoning: cfg.reasoning ?? DEFAULT_SIDECAR_REASONING,
115
- timeoutMs,
116
- // The routed model is text-only → have the search model verbalize image results.
117
- describeImages: modelInList(provider.noVisionModels, modelId),
118
- },
119
- maxSearches: cfg.maxSearchesPerTurn ?? DEFAULT_MAX_SEARCHES,
185
+ settings: { model: cfg.model ?? DEFAULT_SIDECAR_MODEL, reasoning, timeoutMs, describeImages },
186
+ maxSearches,
120
187
  routedModelStallTimeoutMs,
121
- stallTimeoutSec: webSearchStallTimeoutSec(
122
- config.stallTimeoutSec,
123
- connectTimeoutMs,
124
- routedModelStallTimeoutMs,
125
- timeoutMs,
126
- ),
188
+ stallTimeoutSec,
127
189
  };
128
190
  }
@@ -3,6 +3,7 @@ import type { AdapterEvent, OcxMessage, OcxParsedRequest, OcxProviderConfig, Ocx
3
3
  import { namespacedToolName } from "../types";
4
4
  import { bridgeToResponsesSSE } from "../bridge";
5
5
  import { runWebSearch, type SidecarOutcome, type SidecarOutcomeRecorder, type SidecarSettings } from "./executor";
6
+ import { runAnthropicWebSearch } from "./anthropic-executor";
6
7
  import { clearableDeadline } from "../lib/abort";
7
8
  import { readBoundedResponseBody } from "../lib/bounded-body";
8
9
  import { fetchWithResetRetry } from "../lib/upstream-retry";
@@ -162,7 +163,12 @@ class LoopError extends Error {
162
163
  export interface WebSearchLoopDeps {
163
164
  parsed: OcxParsedRequest;
164
165
  adapter: ProviderAdapter;
165
- forwardProvider: OcxProviderConfig;
166
+ /** Which executor runs searches. Defaults to "openai" so existing callers keep the ChatGPT path (audit F4). */
167
+ backend?: "openai" | "anthropic";
168
+ /** Required for the openai backend; unused (and typically undefined) for the anthropic backend. */
169
+ forwardProvider?: OcxProviderConfig;
170
+ /** Required for the anthropic backend: the stored-OAuth provider that runs web_search_20250305. */
171
+ anthropicSidecar?: { providerName: string; provider: OcxProviderConfig };
166
172
  hostedTool: Record<string, unknown>;
167
173
  selectedForwardHeaders: Headers;
168
174
  settings: SidecarSettings;
@@ -195,6 +201,8 @@ export interface WebSearchLoopDeps {
195
201
  */
196
202
  export async function runWithWebSearch(deps: WebSearchLoopDeps): Promise<Response> {
197
203
  const { parsed, selectedForwardHeaders, forwardProvider, hostedTool, settings, maxSearches, abortSignal, recordSidecarOutcome } = deps;
204
+ const backend = deps.backend ?? "openai";
205
+ const anthropicSidecar = deps.anthropicSidecar;
198
206
  // Mutable: 429 key-failover (deps.on429) can swap in a rebuilt adapter mid-loop.
199
207
  let adapter = deps.adapter;
200
208
 
@@ -399,7 +407,11 @@ export async function runWithWebSearch(deps: WebSearchLoopDeps): Promise<Respons
399
407
  beganCell = true;
400
408
  yield { type: "web_search_call_begin", id: call.id };
401
409
  }
402
- outcome = await runWebSearch(query, hostedTool, forwardProvider, selectedForwardHeaders, settings, signal, recordSidecarOutcome);
410
+ // F5: the anthropic sidecar authenticates with its own stored OAuth — it never touches the
411
+ // ChatGPT forward headers and must NOT record a Codex/OpenAI pool outcome.
412
+ outcome = backend === "anthropic" && anthropicSidecar
413
+ ? await runAnthropicWebSearch(query, anthropicSidecar.providerName, anthropicSidecar.provider, settings, signal)
414
+ : await runWebSearch(query, hostedTool, forwardProvider!, selectedForwardHeaders, settings, signal, recordSidecarOutcome);
403
415
  searchesExecuted++;
404
416
  executedSearchCount++;
405
417
  if (outcome.error) failedQueries.add(normalizeQuery(query));