diff --git a/.changes/web-search-support.md b/.changes/web-search-support.md new file mode 100644 index 0000000..a7a06a6 --- /dev/null +++ b/.changes/web-search-support.md @@ -0,0 +1,4 @@ +--- +bump: minor +--- +Restore `web_search` and `web_fetch` for Claude Code through the gateway: the worker now runs these tools internally against Microsoft Web IQ in a transparent agentic loop, and a new `/web-search-support` command stores the WebIQ API key. diff --git a/e2e/RESULTS.md b/e2e/RESULTS.md index 6327996..5751a4c 100644 --- a/e2e/RESULTS.md +++ b/e2e/RESULTS.md @@ -3,6 +3,30 @@ Latest run of the end-to-end suite. Regenerate after every code change with `npm run test:e2e` and update this file (paste the summary). +- **2026-06-26 (Codex /responses)** — Fixed Codex startup: new Codex removed `wire_api = "chat"` + (codex#7782) and requires `"responses"`, which makes it POST `{base_url}/responses`. Implemented the + OpenAI Responses API at `POST /openai/responses` (new `src/core/responses-inbound.ts`: item-centric + request → canonical, canonical → response object, and a stateful SSE emitter with `sequence_number` + and the `response.created → output_item.added → content_part.added → output_text.delta → … → + response.completed` event sequence). Codex config now writes `wire_api = "responses"` (base_url + stays `…/openai`; Codex appends `/responses`). Verified live end-to-end against real Copilot: + non-stream returns a completed `response` object with an `output_text` item; stream begins + `response.created` and ends `response.completed` with `output_text.delta` in between. Full suite + green: `npm test` → **294 passed** (52 files), `npm run test:e2e` → **31 passed**, tsc build clean. + +- **2026-06-26** — Restored web_search / web_fetch for Claude Code through the gateway. The inbound + translator now converts Anthropic's server-side web tools to function tools (instead of dropping + them); a capped agentic loop in the Anthropic endpoint runs those tools internally against + Microsoft Web IQ (`api.microsoft.ai`) and feeds results back, so the client only ever sees the + final grounded answer (transparent). A new `/web-search-support` command stores the WebIQ key + (data dir or `WEBIQ_API_KEY`, read lazily — no worker restart). Also added a startup status card + (GitHub login state — connected/expired/signed-out, since the device-flow token has no real + expiry — plus web search readiness, worker, and configured clients) and a live `web ✓/✗` indicator + in the now two-line HUD footer. Verified live end-to-end (real Copilot + real WebIQ): a + `web_search` request returned `stop_reason: end_turn` with a fresh answer and no tool_use block + leaked to the client. Full suite green: `npm test` → **281 passed** (51 files), `npm run test:e2e` + → **31 passed** (4 files), tsc build clean. + - **2026-06-25** — Fixed the `/login` deadlock: the slash command buffered the device code behind a blocking token poll, so the Repl showed nothing and the user could never authorize. Split device login into `beginDeviceLogin` (returns the code immediately) + `complete()` (polls), and gave the diff --git a/src/cli/index.ts b/src/cli/index.ts index ee46a33..d8ee04e 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -11,12 +11,14 @@ import { startSupervisor } from "../supervisor/index.js"; import { runAssistantTurn } from "../tui/assistant/runtime.js"; import { makeOnChat } from "../tui/assistant/on-chat.js"; import { readGhToken, clearGhToken } from "../shared/creds.js"; +import { writeWebIqKey, readWebIqKey } from "../shared/webiq-key.js"; import { readClientSetup, writeClientSetup } from "../shared/client-setup.js"; import { readChatModel, writeChatModel } from "../shared/prefs.js"; import { CopilotTokenStore, isCopilotTokenValid } from "../providers/copilot/token.js"; import { fetchCopilotModels, fetchModelLimits } from "../providers/copilot/models.js"; import { applyClaude, applyCodex, resetClaude, resetCodex, CLAUDE_ENV_KEYS, CODEX_ENV_KEYS, type Scope } from "../tui/setup/apply.js"; import { readClientStatus } from "../tui/setup/status.js"; +import { summarizeStatus } from "../tui/status-summary.js"; import { applyCodexToml } from "../tui/setup/codex-toml.js"; import type { SetupClient } from "../tui/setup/wizard.js"; import { claudeCopilotReverseEnv } from "../tui/setup/clients.js"; @@ -112,19 +114,21 @@ async function launchTui(): Promise { // Apply a client's config (shared by the /setup wizard and the assistant's setup_* tools). // For Claude Code we also write the selected model's real context window so the client doesn't + // For Claude Code we also write the selected model's real context window so the client doesn't // assume the default 200K (which makes a 1M model read "context 100%" far too early). For Codex - // we write BOTH a .env (legacy) and ~/.codex/config.toml (the native Codex config, with the - // model's context window) so either Codex setup style works. + // the native config is ~/.codex/config.toml (what the standalone CLI actually reads); we also keep + // a legacy .env for older OpenAI-style tooling, but report the config.toml path since that's the + // one that matters. const applyClient = (clientKind: SetupClient, scope: Scope, model: string) => { if (clientKind === "claude") { const r = applyClaude(scope, claudeCopilotReverseEnv(anthropicBase, "copilot-reverse-local", model, modelLimits[model])); writeClientSetup(dataDir(), { ...readClientSetup(dataDir()), claude: true }); return r; } - const r = applyCodex(scope, { OPENAI_BASE_URL: openaiBase, OPENAI_API_KEY: "copilot-reverse-local", OPENAI_MODEL: model }); - applyCodexToml({ baseUrl: openaiBase, model, contextWindow: modelLimits[model] }); + applyCodex(scope, { OPENAI_BASE_URL: openaiBase, OPENAI_API_KEY: "copilot-reverse-local", OPENAI_MODEL: model }); // legacy .env + const toml = applyCodexToml({ baseUrl: openaiBase, model, contextWindow: modelLimits[model], apiKey: "copilot-reverse-local" }); writeClientSetup(dataDir(), { ...readClientSetup(dataDir()), codex: true }); - return r; + return toml; // the native config Codex reads — surface this path in the setup card }; const setup = { apply: async (clientKind: SetupClient, scope: Scope, model: string) => applyClient(clientKind, scope, model) }; @@ -150,6 +154,17 @@ async function launchTui(): Promise { const persistedModel = readChatModel(dataDir()); + // Startup overview. The token was already validated above (re-auth happens before we get here), so + // GitHub is connected; web search readiness and configured clients are read from disk. + const clientStatus = readClientStatus(); + const startupStatus = summarizeStatus({ + hasToken: Boolean(readGhToken(dataDir())), + tokenValid: true, + webSearchReady: Boolean(readWebIqKey(dataDir())), + worker: "ready", + clients: { claude: clientStatus.claude.user || clientStatus.claude.project, codex: clientStatus.codex.user || clientStatus.codex.project }, + }); + app = render( React.createElement(App, { registry, @@ -171,6 +186,14 @@ async function launchTui(): Promise { onModelChange: (m: string) => writeChatModel(dataDir(), m), pickModelOnStart: !persistedModel, login: doLogin, + saveWebIqKey: (k: string) => writeWebIqKey(k, dataDir()), + webSearchReady: () => Boolean(readWebIqKey(dataDir())), + startupStatus, + githubStatus: async () => { + const token = readGhToken(dataDir()); + if (!token) return "signed-out"; + return (await isCopilotTokenValid(token)) ? "connected" : "expired"; + }, }), ); } diff --git a/src/core/anthropic-inbound.ts b/src/core/anthropic-inbound.ts index a75742b..0e2e37a 100644 --- a/src/core/anthropic-inbound.ts +++ b/src/core/anthropic-inbound.ts @@ -1,9 +1,12 @@ import type { CanonicalRequest, CanonicalResponse, CanonicalMessage, ContentBlock } from "./canonical.js"; +import { GATEWAY_TOOL_DEFS, isGatewayTool } from "./server-tools.js"; interface AnthropicImageSource { type: "base64" | "url"; media_type?: string; data?: string; url?: string } interface AnthropicBlock { type: string; text?: string; id?: string; name?: string; input?: unknown; tool_use_id?: string; content?: unknown; source?: AnthropicImageSource } interface AnthropicMsg { role: "user" | "assistant"; content: string | AnthropicBlock[] } -interface AnthropicTool { name: string; description?: string; input_schema: Record } +// Custom tools carry an input_schema. Server-side tools (web_search, web_fetch, bash, computer, …) +// instead carry a dated `type` (e.g. "web_search_20250305") and a bare `name`, with no schema. +interface AnthropicTool { type?: string; name: string; description?: string; input_schema?: Record } interface AnthropicRequest { model: string; max_tokens: number; stream?: boolean; temperature?: number; system?: string | AnthropicBlock[]; tools?: AnthropicTool[]; messages: AnthropicMsg[]; @@ -47,16 +50,32 @@ export function anthropicRequestToCanonical(req: AnthropicRequest): CanonicalReq } return { model: req.model, stream: Boolean(req.stream), temperature: req.temperature, maxTokens: req.max_tokens, - // Keep only custom tools with a real JSON-Schema. Anthropic server-side tools (web_search, - // bash, computer, …) arrive with a `type` and no `input_schema`; forwarding them produces an - // invalid tool the model can't fulfil, and the client hangs forever waiting for a tool_result. - tools: req.tools - ?.filter((t) => t.input_schema != null && typeof t.input_schema === "object") - .map((t) => ({ name: t.name, description: t.description, parameters: t.input_schema })), + tools: mapTools(req.tools), messages, }; } +// Custom tools (with a real JSON-Schema) pass through. Anthropic server-side tools arrive with a +// dated `type` and no input_schema: web_search / web_fetch are converted to gateway function tools +// (the gateway runs them itself against WebIQ), and every OTHER server tool (bash, computer, …) is +// dropped — forwarding an unfulfillable tool makes the client hang forever waiting for a result. +function mapTools(tools: AnthropicTool[] | undefined): CanonicalRequest["tools"] { + if (!tools) return undefined; + const out: NonNullable = []; + let injectedGateway = false; + for (const t of tools) { + if (t.input_schema != null && typeof t.input_schema === "object") { + out.push({ name: t.name, description: t.description, parameters: t.input_schema }); + } else if (isGatewayTool(t.name) && !injectedGateway) { + // Replace the schema-less server tool with our gateway defs. Inject the whole set once so the + // model can use both web_search and web_fetch whenever it asks for either. + out.push(...GATEWAY_TOOL_DEFS); + injectedGateway = true; + } + } + return out; +} + export function canonicalToAnthropicResponse(r: CanonicalResponse) { const content = r.content.map((b) => b.type === "text" ? { type: "text", text: b.text } : diff --git a/src/core/responses-inbound.ts b/src/core/responses-inbound.ts new file mode 100644 index 0000000..4c2c9f2 --- /dev/null +++ b/src/core/responses-inbound.ts @@ -0,0 +1,146 @@ +import type { CanonicalRequest, CanonicalResponse, CanonicalMessage, ContentBlock } from "./canonical.js"; +import { joinText } from "./canonical.js"; + +// OpenAI Responses API translation. Codex (post codex#7782) speaks ONLY this API — it POSTs to +// {base_url}/responses. Like agent-maestro's implementation we are STATELESS: previous_response_id / +// conversation / item_reference are unsupported (the client sends full history in `input` each turn), +// and only function tools are honored. Mirrors the chat-completions translator in openai-inbound.ts. + +interface ResponsesContentPart { type?: string; text?: string; image_url?: string | { url?: string } } +interface ResponsesInputItem { + type?: string; role?: string; + content?: string | ResponsesContentPart[]; // message + call_id?: string; name?: string; arguments?: string; // function_call + output?: string; // function_call_output +} +interface ResponsesTool { type: string; name?: string; description?: string; parameters?: Record } +export interface ResponsesRequest { + model: string; input: string | ResponsesInputItem[]; instructions?: string; + stream?: boolean; temperature?: number; max_output_tokens?: number; tools?: ResponsesTool[]; +} + +function partsText(content: string | ResponsesContentPart[] | undefined): string { + if (content == null) return ""; + if (typeof content === "string") return content; + return content.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join(""); +} +function partsImages(content: string | ResponsesContentPart[] | undefined): ContentBlock[] { + if (!Array.isArray(content)) return []; + const urlOf = (p: ResponsesContentPart): string | undefined => typeof p.image_url === "string" ? p.image_url : p.image_url?.url; + return content.filter((p) => p?.type === "input_image" && urlOf(p)).map((p) => ({ type: "image", dataUrl: urlOf(p)! })); +} +function safeJson(s: string | undefined): unknown { try { return s ? JSON.parse(s) : {}; } catch { return {}; } } + +function itemToMessage(it: ResponsesInputItem): CanonicalMessage | null { + if (it.type === "function_call" && it.call_id) { + return { role: "assistant", content: [{ type: "tool_use", id: it.call_id, name: it.name ?? "", input: safeJson(it.arguments) }] }; + } + if (it.type === "function_call_output" && it.call_id) { + return { role: "tool", content: [{ type: "tool_result", toolUseId: it.call_id, content: it.output ?? "" }] }; + } + // default: a message item + const role = (["system", "user", "assistant"].includes(it.role ?? "") ? it.role : "user") as CanonicalMessage["role"]; + const content: ContentBlock[] = []; + const text = partsText(it.content); + if (text) content.push({ type: "text", text }); + content.push(...partsImages(it.content)); + return content.length ? { role, content } : null; +} + +export function responsesRequestToCanonical(req: ResponsesRequest): CanonicalRequest { + const messages: CanonicalMessage[] = []; + if (req.instructions) messages.push({ role: "system", content: [{ type: "text", text: req.instructions }] }); + if (typeof req.input === "string") { + messages.push({ role: "user", content: [{ type: "text", text: req.input }] }); + } else { + for (const it of req.input) { const m = itemToMessage(it); if (m) messages.push(m); } + } + return { + model: req.model, stream: Boolean(req.stream), temperature: req.temperature, maxTokens: req.max_output_tokens, + tools: req.tools?.filter((t) => t.type === "function" && t.name).map((t) => ({ name: t.name!, description: t.description, parameters: t.parameters ?? {} })), + messages, + }; +} + +// Build the non-stream Responses object: text -> an output_text message item, tool_use -> function_call items. +export function canonicalToResponsesResponse(r: CanonicalResponse) { + const output: unknown[] = []; + const text = joinText(r.content); + if (text) output.push({ type: "message", id: `msg_${r.id}`, role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] }); + for (const b of r.content) { + if (b.type === "tool_use") output.push({ type: "function_call", id: `fc_${b.id}`, call_id: b.id, name: b.name, arguments: JSON.stringify(b.input ?? {}), status: "completed" }); + } + return { + id: r.id, object: "response" as const, status: "completed" as const, model: r.model, + output, output_text: text, + usage: { input_tokens: r.usage.promptTokens, output_tokens: r.usage.completionTokens, total_tokens: r.usage.promptTokens + r.usage.completionTokens }, + }; +} + +// Stateful SSE emitter for the Responses stream. Each event carries a monotonically increasing +// sequence_number (Codex/agent-maestro require it). Text streams as one output_text message item; +// each tool call is its own function_call output item. Indices are allocated sequentially. +const frame = (event: unknown): string => `data: ${JSON.stringify(event)}\n\n`; +export class ResponsesSSE { + private seq = 0; + private nextIndex = 0; + private textIndex?: number; + private textItemId?: string; + private toolIndex = new Map(); + constructor(private responseId: string, private model: string) {} + + private ev(type: string, extra: Record): string { + return frame({ type, sequence_number: this.seq++, ...extra }); + } + private envelope(status: string) { + return { id: this.responseId, object: "response", status, model: this.model }; + } + + start(): string { + return this.ev("response.created", { response: { ...this.envelope("in_progress"), output: [] } }); + } + + text(delta: string): string[] { + const out: string[] = []; + if (this.textIndex === undefined) { + this.textIndex = this.nextIndex++; + this.textItemId = `msg_${this.responseId}`; + out.push(this.ev("response.output_item.added", { output_index: this.textIndex, item: { type: "message", id: this.textItemId, role: "assistant", status: "in_progress", content: [] } })); + out.push(this.ev("response.content_part.added", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text: "", annotations: [] } })); + } + out.push(this.ev("response.output_text.delta", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, delta })); + return out; + } + + toolStart(copilotIdx: number, callId: string, name: string): string[] { + if (this.toolIndex.has(copilotIdx)) return []; + const outputIndex = this.nextIndex++; + const itemId = `fc_${callId}`; + this.toolIndex.set(copilotIdx, { outputIndex, itemId }); + return [this.ev("response.output_item.added", { output_index: outputIndex, item: { type: "function_call", id: itemId, call_id: callId, name, arguments: "", status: "in_progress" } })]; + } + + toolArgs(copilotIdx: number, deltaArgs: string): string[] { + const t = this.toolIndex.get(copilotIdx); + if (!t) return []; + return [this.ev("response.function_call_arguments.delta", { item_id: t.itemId, output_index: t.outputIndex, delta: deltaArgs })]; + } + + // Close all open items and complete the response. `argsByIdx` supplies final accumulated tool args. + finish(usage: { promptTokens: number; completionTokens: number } | undefined, _finishReason: string, argsByIdx?: Map): string[] { + const out: string[] = []; + if (this.textIndex !== undefined) { + out.push(this.ev("response.output_text.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, text: "" })); + out.push(this.ev("response.content_part.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text: "", annotations: [] } })); + out.push(this.ev("response.output_item.done", { output_index: this.textIndex, item: { type: "message", id: this.textItemId, role: "assistant", status: "completed", content: [] } })); + } + for (const [copilotIdx, t] of this.toolIndex) { + const args = argsByIdx?.get(copilotIdx) ?? ""; + out.push(this.ev("response.function_call_arguments.done", { item_id: t.itemId, output_index: t.outputIndex, arguments: args })); + out.push(this.ev("response.output_item.done", { output_index: t.outputIndex, item: { type: "function_call", id: t.itemId, status: "completed" } })); + } + const u = usage ? { input_tokens: usage.promptTokens, output_tokens: usage.completionTokens, total_tokens: usage.promptTokens + usage.completionTokens } : undefined; + out.push(this.ev("response.completed", { response: { ...this.envelope("completed"), ...(u ? { usage: u } : {}) } })); + return out; + } +} diff --git a/src/core/server-tools.ts b/src/core/server-tools.ts new file mode 100644 index 0000000..041a382 --- /dev/null +++ b/src/core/server-tools.ts @@ -0,0 +1,55 @@ +import type { CanonicalTool } from "./canonical.js"; +import { webSearch, webFetch, formatSearchResults, formatFetchResult, type SearchOutcome, type FetchOutcome } from "../providers/webiq/client.js"; + +// Tools the GATEWAY executes itself (against WebIQ), rather than forwarding to the model's client. +// These mirror Claude Code's server-side web_search / web_fetch, which a Copilot-backed gateway must +// fulfil internally — the model calls them like normal function tools and we run them in-process. +export const GATEWAY_TOOL_DEFS: CanonicalTool[] = [ + { + name: "web_search", + description: "Search the web for current information. Returns ranked results with titles, URLs, and content snippets.", + parameters: { type: "object", properties: { query: { type: "string", description: "The search query." } }, required: ["query"] }, + }, + { + name: "web_fetch", + description: "Fetch and read the content of a specific web page by URL.", + parameters: { type: "object", properties: { url: { type: "string", description: "The URL of the page to fetch." } }, required: ["url"] }, + }, +]; + +const GATEWAY_TOOL_NAMES = new Set(GATEWAY_TOOL_DEFS.map((t) => t.name)); +export function isGatewayTool(name: string): boolean { return GATEWAY_TOOL_NAMES.has(name); } + +// Executes a gateway tool call and returns the tool_result text fed back to the model. Always +// resolves to a string — failures become readable messages so the agentic loop never wedges. +export type GatewayToolRunner = (name: string, input: unknown) => Promise; + +// Injection seam: production passes the real WebIQ functions; tests pass fakes. +export interface WebIqClient { + search: (key: string, params: { query: string }, fetchFn?: typeof fetch) => Promise; + fetchPage: (key: string, params: { url: string }, fetchFn?: typeof fetch) => Promise; +} +const DEFAULT_CLIENT: WebIqClient = { search: webSearch, fetchPage: webFetch }; + +const NO_KEY = "web search is not configured — run /web-search-support to add a WebIQ API key"; + +export function makeGatewayRunner(getKey: () => string | null, client: WebIqClient = DEFAULT_CLIENT): GatewayToolRunner { + return async (name, input) => { + const key = getKey(); + if (!key) return NO_KEY; + const arg = (input ?? {}) as Record; + if (name === "web_search") { + const query = typeof arg.query === "string" ? arg.query : ""; + if (!query) return "web_search error: missing 'query'"; + const out = await client.search(key, { query }); + return out.ok ? formatSearchResults(out.results) : out.error; + } + if (name === "web_fetch") { + const url = typeof arg.url === "string" ? arg.url : ""; + if (!url) return "web_fetch error: missing 'url'"; + const out = await client.fetchPage(key, { url }); + return out.ok ? formatFetchResult(out) : out.error; + } + return `unknown gateway tool: ${name}`; + }; +} diff --git a/src/providers/copilot/models.ts b/src/providers/copilot/models.ts index eaa6040..a3558f9 100644 --- a/src/providers/copilot/models.ts +++ b/src/providers/copilot/models.ts @@ -12,7 +12,7 @@ const HEADERS = (token: string) => ({ const DEFAULT_TIMEOUT_MS = 8000; // A stalled Copilot endpoint must never hang the model picker forever — abort after timeoutMs. -async function getModels(token: string, fetchFn: typeof fetch, timeoutMs: number): Promise<{ id?: string; capabilities?: { limits?: { max_prompt_tokens?: number; max_context_window_tokens?: number } } }[] | null> { +async function getModels(token: string, fetchFn: typeof fetch, timeoutMs: number): Promise<{ id?: string; supported_endpoints?: string[]; capabilities?: { limits?: { max_prompt_tokens?: number; max_context_window_tokens?: number } } }[] | null> { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), timeoutMs); try { @@ -33,6 +33,19 @@ export async function fetchCopilotModels(token: string, fetchFn: typeof fetch = return ids.length ? ids : FALLBACK_MODELS; } +// Map of model id -> the Copilot API endpoints it supports (e.g. ["/responses","ws:/responses"]). +// Used to route each request to the right upstream: newer gpt-5.x models are /responses-only and +// reject /chat/completions. Returns {} on failure so the adapter falls back to chat/completions. +export async function fetchModelEndpoints(token: string, fetchFn: typeof fetch = fetch, timeoutMs = DEFAULT_TIMEOUT_MS): Promise> { + const data = await getModels(token, fetchFn, timeoutMs); + if (!data) return {}; + const out: Record = {}; + for (const m of data) { + if (m.id && Array.isArray(m.supported_endpoints) && m.supported_endpoints.length) out[m.id] = m.supported_endpoints; + } + return out; +} + // Map of model id -> its real input/context window, used to size auto-compaction per model and // to show the window in the picker. Returns {} on failure/timeout so callers fall back gracefully. export async function fetchModelLimits(token: string, fetchFn: typeof fetch = fetch, timeoutMs = DEFAULT_TIMEOUT_MS): Promise> { diff --git a/src/providers/webiq/client.ts b/src/providers/webiq/client.ts new file mode 100644 index 0000000..b5ca5ed --- /dev/null +++ b/src/providers/webiq/client.ts @@ -0,0 +1,65 @@ +// Microsoft Web IQ REST client. Two grounding endpoints used to back Claude Code's server-side +// web_search / web_fetch tools, which our gateway executes itself (Copilot can't). Every call +// returns a discriminated result instead of throwing: a failed search must degrade to a message the +// model can read and answer around, never abort the in-flight turn. +const SEARCH_URL = "https://api.microsoft.ai/v3/search/web"; +const BROWSE_URL = "https://api.microsoft.ai/v3/browse"; +const DEFAULT_TIMEOUT_MS = 15_000; + +export interface WebResult { title: string; url: string; content: string; crawledAt?: string; lastUpdatedAt?: string } +export type SearchOutcome = { ok: true; results: WebResult[] } | { ok: false; error: string }; +export type FetchOutcome = { ok: true; title: string; url: string; content: string } | { ok: false; error: string }; + +export interface SearchParams { query: string; maxResults?: number; language?: string; region?: string; maxLength?: number; contentFormat?: string } +export interface FetchParams { url: string; maxLength?: number; language?: string; region?: string; contentFormat?: string; liveCrawl?: string } + +const headers = (key: string) => ({ host: "api.microsoft.ai", "x-apikey": key, "content-type": "application/json" }); + +// Status -> readable, model-facing reason. Kept identical across both endpoints so the model gets a +// consistent, actionable string it can reason about (e.g. fall back to its own knowledge). +function statusError(status: number, kind: "search" | "fetch"): string { + if (status === 401 || status === 403) return "web search unavailable: WebIQ API key missing or invalid — run /web-search-support to set it"; + if (status === 429) return "web search unavailable: WebIQ rate limit exceeded — try again shortly"; + if (status === 404 && kind === "fetch") return "web fetch failed: the page was not found or is not indexed"; + return `web ${kind} failed: WebIQ returned ${status}`; +} + +async function post(url: string, key: string, body: unknown, fetchFn: typeof fetch, timeoutMs: number): Promise { + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), timeoutMs); + try { return await fetchFn(url, { method: "POST", headers: headers(key), body: JSON.stringify(body), signal: ctrl.signal }); } + finally { clearTimeout(timer); } +} + +export async function webSearch(key: string, params: SearchParams, fetchFn: typeof fetch = fetch, timeoutMs = DEFAULT_TIMEOUT_MS): Promise { + if (!key) return { ok: false, error: statusError(401, "search") }; + try { + const res = await post(SEARCH_URL, key, { maxResults: 10, contentFormat: "passage", ...params }, fetchFn, timeoutMs); + if (!res.ok) return { ok: false, error: statusError(res.status, "search") }; + const data = (await res.json()) as { webResults?: WebResult[] }; + return { ok: true, results: data.webResults ?? [] }; + } catch { + return { ok: false, error: "web search failed: could not reach WebIQ" }; + } +} + +export async function webFetch(key: string, params: FetchParams, fetchFn: typeof fetch = fetch, timeoutMs = DEFAULT_TIMEOUT_MS): Promise { + if (!key) return { ok: false, error: statusError(401, "fetch") }; + try { + const res = await post(BROWSE_URL, key, { maxLength: 10_000, contentFormat: "markdown", ...params }, fetchFn, timeoutMs); + if (!res.ok) return { ok: false, error: statusError(res.status, "fetch") }; + const data = (await res.json()) as { title?: string; url?: string; content?: string }; + return { ok: true, title: data.title ?? "", url: data.url ?? params.url, content: data.content ?? "" }; + } catch { + return { ok: false, error: "web fetch failed: could not reach WebIQ" }; + } +} + +// Render results as the tool_result text fed back to the model — compact, citation-friendly. +export function formatSearchResults(results: WebResult[]): string { + if (!results.length) return "no results found"; + return results.map((r, i) => `[${i + 1}] ${r.title}\n${r.url}\n${r.content}`.trim()).join("\n\n"); +} +export function formatFetchResult(r: { title: string; url: string; content: string }): string { + return `${r.title}\n${r.url}\n\n${r.content}`.trim(); +} diff --git a/src/shared/webiq-key.ts b/src/shared/webiq-key.ts new file mode 100644 index 0000000..523a81c --- /dev/null +++ b/src/shared/webiq-key.ts @@ -0,0 +1,20 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; + +// WebIQ API key for the gateway-run web_search / web_fetch tools. Stored like the GitHub token +// (plaintext, 0600, in the data dir). The WEBIQ_API_KEY env var takes precedence so CI / headless +// runs can inject it without writing a file. Read lazily per request → no worker restart on change. +const file = (dir: string) => join(dir, "webiq.json"); + +export function writeWebIqKey(key: string, dir: string): void { + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); + writeFileSync(file(dir), JSON.stringify({ apiKey: key }), { mode: 0o600 }); +} +export function readWebIqKey(dir: string): string | null { + if (process.env.WEBIQ_API_KEY) return process.env.WEBIQ_API_KEY; + if (!existsSync(file(dir))) return null; + return (JSON.parse(readFileSync(file(dir), "utf8")) as { apiKey?: string }).apiKey ?? null; +} +export function clearWebIqKey(dir: string): void { + rmSync(file(dir), { force: true }); +} diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 641255e..2c2517f 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -5,6 +5,8 @@ import { Repl, type CommandHint } from "./repl.js"; import { SetupWizard, type SetupClient } from "./setup/wizard.js"; import { ModelScreen } from "./screens/model.js"; import { ConfigScreen, type ConfigInfo } from "./screens/config.js"; +import { WebIqKeyScreen } from "./screens/webiq-key.js"; +import { summarizeStatus, type StatusSummary, type GithubLoginState } from "./status-summary.js"; import type { Scope, ApplyResult } from "./setup/apply.js"; import type { ClientStatus } from "./setup/status.js"; import { theme } from "./theme.js"; @@ -18,7 +20,7 @@ type Entry = | { type: "card"; title: string; tone: "info" | "ok" | "error"; lines: string[] } | { type: "help"; commands: CommandHint[] }; -type Screen = { kind: "model" } | { kind: "setup"; client: SetupClient } | { kind: "config" } | null; +type Screen = { kind: "model" } | { kind: "setup"; client: SetupClient } | { kind: "config" } | { kind: "webiq-key" } | null; const stateColor: Record = { ready: theme.ready, starting: theme.starting, crashed: theme.crashed, unhealthy: theme.unhealthy, @@ -27,6 +29,23 @@ const stateColor: Record = { const EMPTY_STATUS: ClientStatus = { claude: { user: false, project: false }, codex: { user: false, project: false } }; const SPINNER = ["✶", "✸", "✹", "✺", "✹", "✷"]; +// Startup overview card. GitHub shows a login STATE (no real token expiry exists), web search shows +// whether a WebIQ key is configured with the command to fix it when not. `extra` appends detail +// lines (e.g. worker restart history for /status). +function statusCard(s: StatusSummary, extra: string[] = []): Entry { + const gh = s.github === "connected" ? "✓ connected" : s.github === "expired" ? "✗ expired — run /login" : "✗ signed out — run /login"; + const web = s.webSearch === "ready" ? "✓ ready" : "✗ not configured — run /web-search-support"; + const clients = `claude ${s.clients.claude ? "✓" : "○"} codex ${s.clients.codex ? "✓" : "○"}`; + const tone: "ok" | "error" = s.github === "connected" ? "ok" : "error"; + return { type: "card", title: "status", tone, lines: [ + `GitHub login ${gh}`, + `web search ${web}`, + `worker ${s.worker}`, + `clients ${clients}`, + ...extra, + ] }; +} + const fmtElapsed = (ms: number): string => { const s = Math.floor(ms / 1000); return s >= 60 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${s}s`; @@ -51,6 +70,14 @@ export interface AppProps { // returned promise resolves with a completion message once the user authorizes. The two-phase // shape is required: a single blocking call would hide the code behind the token poll. login?: (show: (lines: string[]) => void) => Promise; + // Persist a WebIQ API key entered via /web-search-support (enables gateway web_search/web_fetch). + saveWebIqKey?: (key: string) => void; + // Whether web search is configured (a WebIQ key is present). Read live so the HUD reflects it. + webSearchReady?: () => boolean; + // One-time status overview shown as the first card on startup. + startupStatus?: StatusSummary; + // Live GitHub login check for /status (a real token-exchange check). Defaults to the startup value. + githubStatus?: () => Promise; } function OutputCard({ title, lines, tone }: { title: string; lines: string[]; tone: "info" | "ok" | "error" }) { @@ -105,21 +132,23 @@ function ClientBadge({ name, status }: { name: string; status: { user: boolean; export function App({ registry, title, workerState = "starting", initialModel = "—", statusSource, readStatus, modelLimits, onChat, - loadModels, setup, info, onModelChange, pickModelOnStart, login, + loadModels, setup, info, onModelChange, pickModelOnStart, login, saveWebIqKey, webSearchReady, startupStatus, githubStatus, }: AppProps) { const cmds: CommandHint[] = registry.list().map((c) => ({ name: c.name, describe: c.describe })); - const [entries, setEntries] = useState([ + const [entries, setEntries] = useState(() => [ + ...(startupStatus ? [statusCard(startupStatus)] : []), { type: "system", text: "Type a message to chat with the assistant, or /help for commands." }, ]); const [state, setState] = useState(workerState); const [status, setStatus] = useState(() => readStatus?.() ?? EMPTY_STATUS); + const [webReady, setWebReady] = useState(() => webSearchReady?.() ?? false); const [model, setModel] = useState(initialModel); const [screen, setScreen] = useState(pickModelOnStart && loadModels ? { kind: "model" } : null); const [, setNow] = useState(0); // ticks the live loading line while the assistant streams const abortRef = useRef(null); // current turn's interrupt handle const loginInFlight = useRef(false); // guards against starting a second device-login flow const add = (e: Entry) => setEntries((p) => [...p, e].slice(-100)); - const refreshStatus = () => { if (readStatus) setStatus(readStatus()); }; + const refreshStatus = () => { if (readStatus) setStatus(readStatus()); if (webSearchReady) setWebReady(webSearchReady()); }; // esc interrupts an in-flight assistant turn (the Repl doesn't use esc, so this is unambiguous). useInput((_input, key) => { if (key.escape) abortRef.current?.abort(); }); @@ -154,6 +183,23 @@ export function App({ add({ type: "user", text: `› ${line}` }); const t = line.trim(); if (t === "/model" && loadModels) { setScreen({ kind: "model" }); return; } + if (t === "/web-search-support" && saveWebIqKey) { setScreen({ kind: "webiq-key" }); return; } + if (t === "/status" && (startupStatus || githubStatus || webSearchReady)) { + // Render the live status overview (same card as startup), then the worker restart history. + const github = githubStatus ? await githubStatus() : (startupStatus?.github ?? "signed-out"); + let worker = state, restarts: string[] = []; + try { + const s = await statusSource?.(); + if (s) { worker = s.workerState; restarts = s.restarts.slice(0, 5).map((r) => ` ${r.reason} exit=${r.exitCode ?? "-"} ${r.stderrTail.slice(0, 60)}`); } + } catch { /* daemon momentarily down — show what we have */ } + const summary = summarizeStatus({ + hasToken: github !== "signed-out", tokenValid: github === "connected", + webSearchReady: webSearchReady?.() ?? webReady, worker, + clients: { claude: status.claude.user || status.claude.project, codex: status.codex.user || status.codex.project }, + }); + add(statusCard(summary, restarts.length ? ["", "recent restarts:", ...restarts] : [])); + return; + } if (t === "/config" && info) { setScreen({ kind: "config" }); return; } if (t === "/login" && login) { // Show the verification URL + code right away, then resolve a completion card once the user @@ -240,6 +286,13 @@ export function App({ }} /> ); + } else if (screen?.kind === "webiq-key" && saveWebIqKey) { + body = ( + { saveWebIqKey(k); setWebReady(true); setScreen(null); add({ type: "card", title: "/web-search-support", tone: "ok", lines: ["✓ WebIQ key saved — web search is now enabled for connected clients"] }); }} + onCancel={() => { setScreen(null); add({ type: "system", text: "web-search-support cancelled" }); }} + /> + ); } else { body = ; } @@ -273,12 +326,17 @@ export function App({ {body} - - model {model} - · daemon {state} - · - - · /help + + + model {model} + · daemon {state} + · web {webReady ? "✓" : "✗ /web-search-support"} + + + + + · /help + ); diff --git a/src/tui/screens/webiq-key.tsx b/src/tui/screens/webiq-key.tsx new file mode 100644 index 0000000..c82022f --- /dev/null +++ b/src/tui/screens/webiq-key.tsx @@ -0,0 +1,26 @@ +import React, { useState } from "react"; +import { Box, Text, useInput } from "ink"; +import { theme } from "../theme.js"; + +// Masked single-line input for the WebIQ API key. Mirrors the Repl's end-of-line editing (append / +// backspace), but renders bullets instead of the secret. Enter submits a non-empty key; Esc cancels. +export function WebIqKeyScreen({ onSubmit, onCancel }: { onSubmit: (key: string) => void; onCancel: () => void }) { + const [value, setValue] = useState(""); + useInput((input, key) => { + if (key.escape) { onCancel(); return; } + if (key.return) { const k = value.trim(); if (k) onSubmit(k); else onCancel(); return; } + if (key.backspace || key.delete) { setValue((v) => v.slice(0, -1)); return; } + if (input && !key.ctrl && !key.meta) setValue((v) => v + input); + }); + return ( + + web search support — paste your WebIQ API key + enables web_search / web_fetch for connected clients · enter to save · esc to cancel + + {"key › "} + {"•".repeat(value.length)} + + + + ); +} diff --git a/src/tui/setup/codex-toml.ts b/src/tui/setup/codex-toml.ts index e2a31ae..61cb148 100644 --- a/src/tui/setup/codex-toml.ts +++ b/src/tui/setup/codex-toml.ts @@ -4,14 +4,16 @@ import { join, dirname } from "node:path"; // Codex reads ~/.codex/config.toml. copilot-reverse writes a managed provider block there (model, // provider, context window) while preserving the user's other top-level keys. Mirrors -// agent-maestro's `configureCodex`, but uses wire_api="chat" since our proxy is chat/completions. +// agent-maestro's `configureCodex`. Codex removed wire_api="chat" (codex#7782), so we write +// "responses" and serve the OpenAI Responses API at /openai/responses (Codex appends /responses to +// base_url verbatim — no /v1 auto-added). export const PROVIDER_ID = "copilot-reverse"; export function codexTomlPath(home = homedir()): string { return join(home, ".codex", "config.toml"); } -export interface CodexTomlOpts { home?: string; baseUrl: string; model: string; contextWindow?: number } +export interface CodexTomlOpts { home?: string; baseUrl: string; model: string; contextWindow?: number; apiKey?: string } // The top-level keys we own (so re-applying replaces them instead of duplicating). const MANAGED_TOP_KEYS = ["model", "model_provider", "model_context_window"]; @@ -20,33 +22,57 @@ export function applyCodexToml(opts: CodexTomlOpts): { path: string; changed: st const path = codexTomlPath(opts.home); if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true }); - // Read existing top-level lines, dropping our managed keys and any prior managed provider table, - // but keeping everything else (approval_policy, other providers, etc.) verbatim. + // Parse existing content into top-level (pre-table) bare keys vs. table blocks, dropping our + // managed keys and any prior managed provider table. We MUST keep top-level keys and tables + // separate: in TOML a bare `key = value` after a `[table]` header belongs to that table, so + // appending our `model_provider` at the end (after the user's [windows]/[marketplaces] tables) + // silently nested it under the last table — Codex then couldn't see it and fell back to "openai". const existing = existsSync(path) ? readFileSync(path, "utf8") : ""; - const kept: string[] = []; - let inOurTable = false; + const keptTopKeys: string[] = []; // bare key=value lines before any table + const keptTables: string[] = []; // everything from the first [table] onward (preserved verbatim) + let inTable = false; // have we passed the first table header? + let inOurTable = false; // are we inside our own [model_providers.copilot-reverse] block? for (const line of existing.split(/\r?\n/)) { - const tableMatch = /^\s*\[/.test(line); - if (tableMatch) inOurTable = line.trim() === `[model_providers.${PROVIDER_ID}]`; - if (inOurTable) continue; // skip our previously-written provider table + if (/^\s*\[/.test(line)) { + inTable = true; + inOurTable = line.trim() === `[model_providers.${PROVIDER_ID}]`; + } + if (inOurTable) continue; // skip our previously-written provider table entirely const keyMatch = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line); - if (keyMatch && MANAGED_TOP_KEYS.includes(keyMatch[1])) continue; // skip our managed top keys - kept.push(line); + // Drop our managed top keys wherever they appear. They belong at the top level, but a previous + // buggy version wrote them AFTER tables (where TOML nests them) — so filter them in the table + // region too, otherwise the rewrite would duplicate them. + if (keyMatch && MANAGED_TOP_KEYS.includes(keyMatch[1])) continue; + (inTable ? keptTables : keptTopKeys).push(line); } - const head = kept.join("\n").replace(/\n{3,}/g, "\n\n").trim(); - const managed = [ + // Reassemble in valid TOML order: ALL top-level keys (ours + the user's) first, then all table + // blocks (the user's preserved tables, then our managed provider table last). + const topKeys = [ `model = "${opts.model}"`, `model_provider = "${PROVIDER_ID}"`, ...(opts.contextWindow ? [`model_context_window = ${opts.contextWindow}`] : []), - "", + ...keptTopKeys.filter((l) => l.trim()), // the user's other top-level keys (approval_policy, etc.) + ]; + const ourTable = [ `[model_providers.${PROVIDER_ID}]`, `name = "copilot-reverse"`, `base_url = "${opts.baseUrl}"`, - `wire_api = "chat"`, - ].join("\n"); + `wire_api = "responses"`, + // Auth: inline a static bearer token so Codex talks to our local proxy instead of falling back + // to the OpenAI login flow. env_key is unreliable here (a standalone Codex CLI won't see our + // .env), so we embed the placeholder directly — the worker ignores the key value anyway. + `requires_openai_auth = false`, + `experimental_bearer_token = "${opts.apiKey ?? "copilot-reverse-local"}"`, + ]; + const userTables = keptTables.join("\n").replace(/\n{3,}/g, "\n\n").trim(); + const managed = [ + topKeys.join("\n"), + ...(userTables ? [userTables] : []), + ourTable.join("\n"), + ].join("\n\n"); - const body = (head ? `${head}\n\n` : "") + managed + "\n"; + const body = managed + "\n"; writeFileSync(path, body); return { path, changed: MANAGED_TOP_KEYS }; } diff --git a/src/tui/slash/commands.ts b/src/tui/slash/commands.ts index 4c5fc58..92f3ed2 100644 --- a/src/tui/slash/commands.ts +++ b/src/tui/slash/commands.ts @@ -53,6 +53,7 @@ export function buildRegistry(ctx: SlashContext, endpoint: Endpoint, opts: Regis reg.add({ name: "/login", describe: "sign in to GitHub (device-code)", run: async () => opts.login ? opts.login() : ["login not available"] }); reg.add({ name: "/logout", describe: "sign out — remove the stored GitHub token", run: async () => opts.logout ? opts.logout() : ["logout not available"] }); reg.add({ name: "/model", describe: "switch the chat model", run: async () => ["opening model picker…"] }); + reg.add({ name: "/web-search-support", describe: "enable web search/fetch (set WebIQ API key)", run: async () => ["opening web-search-support…"] }); reg.add({ name: "/config", describe: "view & change configuration", run: async () => ["opening config panel…"] }); reg.add({ name: "/dashboard", describe: "open the web dashboard in your browser", run: async () => { if (!opts.dashboardUrl) return ["dashboard URL not available"]; diff --git a/src/tui/status-summary.ts b/src/tui/status-summary.ts new file mode 100644 index 0000000..e291af2 --- /dev/null +++ b/src/tui/status-summary.ts @@ -0,0 +1,37 @@ +import type { WorkerState } from "../shared/control-types.js"; + +// Status overview shown on startup and reflected in the HUD. GitHub's device-flow OAuth token has no +// real expiry (GitHub returns no expires_in for this app), so we report a LOGIN STATE, not a +// countdown: "connected" means the stored token still exchanges for a Copilot token, "expired" means +// it no longer does (revoked / re-auth needed), "signed-out" means there's no token at all. +export type GithubLoginState = "connected" | "expired" | "signed-out"; +export type WebSearchState = "ready" | "not-configured"; + +export interface StatusInputs { + hasToken: boolean; // a GitHub token is stored + tokenValid: boolean; // that token still exchanges for a Copilot token (network-checked upstream) + webSearchReady: boolean; // a WebIQ key is configured (env or data dir) + worker: WorkerState; + clients: { claude: boolean; codex: boolean }; +} + +export interface StatusSummary { + github: GithubLoginState; + webSearch: WebSearchState; + worker: WorkerState; + clients: { claude: boolean; codex: boolean }; +} + +export function githubLoginState(hasToken: boolean, tokenValid: boolean): GithubLoginState { + if (!hasToken) return "signed-out"; + return tokenValid ? "connected" : "expired"; +} + +export function summarizeStatus(i: StatusInputs): StatusSummary { + return { + github: githubLoginState(i.hasToken, i.tokenValid), + webSearch: i.webSearchReady ? "ready" : "not-configured", + worker: i.worker, + clients: i.clients, + }; +} diff --git a/src/worker/anthropic-server.ts b/src/worker/anthropic-server.ts index 2b4c2b4..e1f67e1 100644 --- a/src/worker/anthropic-server.ts +++ b/src/worker/anthropic-server.ts @@ -6,10 +6,17 @@ import { anthropicRequestToCanonical, canonicalToAnthropicResponse } from "../co import { estimateTokens } from "../core/tokens.js"; import { errorHint } from "./errors.js"; import { CopilotAuthError } from "../providers/copilot/token.js"; +import { isGatewayTool, type GatewayToolRunner } from "../core/server-tools.js"; +import type { ContentBlock } from "../core/canonical.js"; const frame = (event: string, data: unknown) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; +const safeJson = (s: string): unknown => { try { return JSON.parse(s); } catch { return {}; } }; -export function mountAnthropic(app: Express, router: Router, onMetric: MetricSink): void { +// Bounds the gateway tool loop so a model that calls web_search every turn (or a runner that always +// returns "search more") can never spin forever inside one request. +const MAX_TOOL_ITERS = 5; + +export function mountAnthropic(app: Express, router: Router, onMetric: MetricSink, runner?: GatewayToolRunner): void { // Model discovery — Anthropic list shape. Claude Desktop / Anthropic-protocol clients GET this // before chatting; without it they 404 on the connection test. app.get("/anthropic/v1/models", (_req, res) => { @@ -41,54 +48,99 @@ export function mountAnthropic(app: Express, router: Router, onMetric: MetricSin const estInput = estimateTokens(canon); res.write(frame("message_start", { type: "message_start", message: { id, type: "message", role: "assistant", model: canon.model, content: [], stop_reason: null, usage: { input_tokens: estInput, output_tokens: 0, cache_read_input_tokens: 0 } } })); - // D3 (interface-freeze §5.4) + mixed text+tool fix (architect, 2026-06-17): the endpoint owns - // open/stop bookkeeping with DYNAMIC SEQUENTIAL allocation. We do NOT pre-open an index-0 text block, - // and we do NOT map the Copilot tool index straight to the Anthropic block index (that collides with a - // text preamble on a mixed turn). Instead, whichever block opens FIRST claims Anthropic index 0, the - // next claims 1, etc. This keeps indices contiguous-from-0 in all three cases: pure-text (text@0), - // pure-tool (tool@0), and mixed preamble+tool (text@0, tool@1). + // D3 (interface-freeze §5.4) + mixed text+tool fix (architect, 2026-06-17) + gateway tool loop + // (2026-06): the endpoint owns block open/stop bookkeeping with DYNAMIC SEQUENTIAL allocation, + // and `next` spans ALL loop iterations so block indices stay contiguous-from-0 across turns. + // Within a turn, text streams live (transparent progress) but tool calls are BUFFERED: only + // after the turn ends do we know whether they're gateway tools (run here, then loop) or client + // tools (forwarded to the client, exactly as before). Whichever block opens first claims index 0. let next = 0; - let textIndex: number | undefined; // Anthropic index of the (single) text block, once opened - const toolIndex = new Map(); // Copilot tool index -> Anthropic block index - const openedOrder: number[] = []; // Anthropic indices in allocation order - let stopReason: "stop" | "length" | "tool_use" | "error" = "stop"; - let usage: { promptTokens: number; completionTokens: number; cachedTokens?: number } | undefined; + let lastPrompt = estInput, lastCached = 0, sumCompletion = 0; + let finalStop: "stop" | "length" | "tool_use" | "error" = "stop"; + + for (let iter = 0; iter < MAX_TOOL_ITERS; iter++) { + let textIndex: number | undefined; // Anthropic index of this turn's text block + const byCopilotIdx = new Map(); + const buffered: { id: string; name: string; args: string }[] = []; // tool calls seen this turn, in order + let turnStop: "stop" | "length" | "tool_use" | "error" = "stop"; - for await (const chunk of provider.stream(canon)) { - if (chunk.done) { stopReason = chunk.finishReason ?? "stop"; usage = chunk.usage; break; } - if (chunk.kind === "text") { - if (textIndex === undefined) { - textIndex = next++; - openedOrder.push(textIndex); - res.write(frame("content_block_start", { type: "content_block_start", index: textIndex, content_block: { type: "text", text: "" } })); + for await (const chunk of provider.stream(canon)) { + if (chunk.done) { + turnStop = chunk.finishReason ?? "stop"; + if (chunk.usage) { lastPrompt = chunk.usage.promptTokens ?? lastPrompt; lastCached = chunk.usage.cachedTokens ?? 0; sumCompletion += chunk.usage.completionTokens ?? 0; } + break; } - res.write(frame("content_block_delta", { type: "content_block_delta", index: textIndex, delta: { type: "text_delta", text: chunk.delta } })); - } else if (chunk.kind === "tool_use_start") { - if (!toolIndex.has(chunk.index)) { - const index = next++; - toolIndex.set(chunk.index, index); - openedOrder.push(index); - res.write(frame("content_block_start", { type: "content_block_start", index, content_block: { type: "tool_use", id: chunk.id, name: chunk.name, input: {} } })); + if (chunk.kind === "text") { + if (textIndex === undefined) { + textIndex = next++; + res.write(frame("content_block_start", { type: "content_block_start", index: textIndex, content_block: { type: "text", text: "" } })); + } + res.write(frame("content_block_delta", { type: "content_block_delta", index: textIndex, delta: { type: "text_delta", text: chunk.delta } })); + } else if (chunk.kind === "tool_use_start") { + if (!byCopilotIdx.has(chunk.index)) { const t = { id: chunk.id, name: chunk.name, args: "" }; byCopilotIdx.set(chunk.index, t); buffered.push(t); } + } else if (chunk.kind === "tool_use_delta") { + const t = byCopilotIdx.get(chunk.index); if (t) t.args += chunk.argsDelta; } - } else if (chunk.kind === "tool_use_delta") { - const index = toolIndex.get(chunk.index); - if (index !== undefined) res.write(frame("content_block_delta", { type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: chunk.argsDelta } })); } + if (textIndex !== undefined) res.write(frame("content_block_stop", { type: "content_block_stop", index: textIndex })); + + const gatewayCalls = buffered.filter((t) => isGatewayTool(t.name)); + + // Invariant: a gateway tool (web_search/web_fetch) must NEVER reach the client — the client + // has no handler for it and would stall. So whenever the model calls gateway tools (and a + // runner is wired), run them here and loop, feeding results back. Any client tools called in + // the SAME turn are deliberately NOT forwarded yet: we drop them this turn and let the model + // re-issue them on the next turn, now informed by the search result. (Forwarding them now + // would end the turn as tool_use and strand the gateway result with nowhere to go.) + if (runner && gatewayCalls.length) { + canon.messages.push({ role: "assistant", content: gatewayCalls.map((t): ContentBlock => ({ type: "tool_use", id: t.id, name: t.name, input: safeJson(t.args) })) }); + const results: ContentBlock[] = []; + for (const t of gatewayCalls) results.push({ type: "tool_result", toolUseId: t.id, content: await runner(t.name, safeJson(t.args)) }); + canon.messages.push({ role: "tool", content: results }); + continue; + } + + // Terminal turn (no gateway tools, or no runner): forward any buffered tool calls to the + // client (open/delta/close each at its own freshly-allocated index), then finish. + for (const t of buffered) { + const index = next++; + res.write(frame("content_block_start", { type: "content_block_start", index, content_block: { type: "tool_use", id: t.id, name: t.name, input: {} } })); + if (t.args) res.write(frame("content_block_delta", { type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: t.args } })); + res.write(frame("content_block_stop", { type: "content_block_stop", index })); + } + finalStop = buffered.length ? "tool_use" : turnStop; + break; } - // Close every opened block (ascending Anthropic index) before the terminal frames. - for (const index of [...openedOrder].sort((a, b) => a - b)) res.write(frame("content_block_stop", { type: "content_block_stop", index })); // Report real usage (agent-maestro shape): split cached tokens out of input so Claude Code's - // context bar is accurate. Falls back to zeros if Copilot didn't return usage. - const cached = usage?.cachedTokens ?? 0; - const inputTokens = Math.max(0, (usage?.promptTokens ?? estInput) - cached); // fall back to the estimate - const deltaUsage = { input_tokens: inputTokens, output_tokens: usage?.completionTokens ?? 0, cache_read_input_tokens: cached }; - res.write(frame("message_delta", { type: "message_delta", delta: { stop_reason: stopReason === "tool_use" ? "tool_use" : stopReason === "length" ? "max_tokens" : "end_turn" }, usage: deltaUsage })); + // context bar is accurate. promptTokens is the last turn's (largest, includes tool results); + // output is summed across turns. + const inputTokens = Math.max(0, lastPrompt - lastCached); + const deltaUsage = { input_tokens: inputTokens, output_tokens: sumCompletion, cache_read_input_tokens: lastCached }; + res.write(frame("message_delta", { type: "message_delta", delta: { stop_reason: finalStop === "tool_use" ? "tool_use" : finalStop === "length" ? "max_tokens" : "end_turn" }, usage: deltaUsage })); res.write(frame("message_stop", { type: "message_stop" })); res.end(); metric(200); } else { - res.json(canonicalToAnthropicResponse(await provider.complete(canon))); + // Non-stream: same gateway loop without SSE — run gateway tools and re-complete until the + // model answers with text (or a client tool), capped identically. + let resp = await provider.complete(canon); + for (let iter = 0; runner && iter < MAX_TOOL_ITERS; iter++) { + const toolUses = resp.content.filter((b): b is Extract => b.type === "tool_use"); + const gatewayUses = toolUses.filter((b) => isGatewayTool(b.name)); + if (!gatewayUses.length) break; // no gateway work left — client tools / text are terminal + // Run the gateway tools, feed results back, and continue. Any client tools in the SAME turn + // ride along in the assistant message and remain in the final resp for the client to handle. + canon.messages.push({ role: "assistant", content: resp.content }); + const results: ContentBlock[] = []; + for (const u of gatewayUses) results.push({ type: "tool_result", toolUseId: u.id, content: await runner(u.name, u.input) }); + canon.messages.push({ role: "tool", content: results }); + resp = await provider.complete(canon); + } + // Invariant: never forward a gateway tool_use to the client (it can't handle it). If the cap + // was hit with gateway calls still pending, strip them — better a partial answer than a stall. + if (runner) resp = { ...resp, content: resp.content.filter((b) => b.type !== "tool_use" || !isGatewayTool((b as Extract).name)) }; + res.json(canonicalToAnthropicResponse(resp)); metric(200); } } catch (err) { diff --git a/src/worker/index.ts b/src/worker/index.ts index 8407b67..91aa330 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -4,6 +4,8 @@ import { CopilotAdapter } from "../providers/copilot/adapter.js"; import { CopilotTokenStore } from "../providers/copilot/token.js"; import { fetchCopilotModels } from "../providers/copilot/models.js"; import { readGhToken } from "../shared/creds.js"; +import { readWebIqKey } from "../shared/webiq-key.js"; +import { makeGatewayRunner } from "../core/server-tools.js"; import { dataDir } from "../shared/paths.js"; import { defaultConfig } from "../shared/config.js"; import type { WorkerToSupervisor } from "../shared/ipc.js"; @@ -21,7 +23,10 @@ const tokenStore = new CopilotTokenStore(gh); const router = new Router([new CopilotAdapter(tokenStore)], cfg.modelMap); // Load the live model list so the router can fuzzy-match near-miss ids (e.g. dated Anthropic ids). void tokenStore.get().then((t) => fetchCopilotModels(t)).then((ids) => router.setAvailableModels(ids)).catch(() => {}); -const app = createWorkerApp(router, (m) => send({ type: "request-metric", ...m })); +// Gateway-run web_search / web_fetch: reads the WebIQ key lazily per call (env or data dir), so +// setting it via /web-search-support takes effect without restarting the worker. +const gatewayRunner = makeGatewayRunner(() => readWebIqKey(dataDir())); +const app = createWorkerApp(router, (m) => send({ type: "request-metric", ...m }), gatewayRunner); const server = app.listen(port, host, () => send({ type: "ready", port })); const hb = setInterval(() => send({ type: "heartbeat", ts: Date.now() }), 5_000); diff --git a/src/worker/openai-server.ts b/src/worker/openai-server.ts index 80201f6..c529804 100644 --- a/src/worker/openai-server.ts +++ b/src/worker/openai-server.ts @@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto"; import type { Router } from "./router.js"; import type { MetricSink } from "./server.js"; import { openaiRequestToCanonical, canonicalToOpenAIResponse, canonicalChunkToOpenAISSE } from "../core/openai-inbound.js"; +import { responsesRequestToCanonical, canonicalToResponsesResponse, ResponsesSSE } from "../core/responses-inbound.js"; import { errorHint } from "./errors.js"; import { CopilotAuthError } from "../providers/copilot/token.js"; @@ -47,4 +48,50 @@ export function mountOpenAI(app: Express, router: Router, onMetric: MetricSink): metric(status, message); } }); + + // OpenAI Responses API — Codex speaks ONLY this after codex#7782 removed wire_api="chat". Codex + // POSTs {base_url}/responses, so with base_url …/openai the route is /openai/responses. Same + // canonical pipeline as chat/completions; the Responses translator handles the item-centric shape. + app.post("/openai/responses", async (req, res) => { + const start = Date.now(); + const canon = responsesRequestToCanonical(req.body); + canon.model = router.resolveModel(canon.model); + const provider = router.pick(canon.model); + const metric = (status: number, error?: string) => onMetric({ endpoint: "/openai/responses", model: canon.model, status, latencyMs: Date.now() - start, error }); + try { + if (canon.stream) { + res.setHeader("content-type", "text/event-stream"); + res.setHeader("cache-control", "no-cache"); + const sse = new ResponsesSSE(`resp_${randomUUID().replace(/-/g, "")}`, canon.model); + res.write(sse.start()); + const argsByIdx = new Map(); + let usage: { promptTokens: number; completionTokens: number } | undefined; + let finish = "stop"; + for await (const chunk of provider.stream(canon)) { + if (chunk.done) { finish = chunk.finishReason ?? "stop"; usage = chunk.usage; break; } + if (chunk.kind === "text") for (const f of sse.text(chunk.delta)) res.write(f); + else if (chunk.kind === "tool_use_start") for (const f of sse.toolStart(chunk.index, chunk.id, chunk.name)) res.write(f); + else if (chunk.kind === "tool_use_delta") { argsByIdx.set(chunk.index, (argsByIdx.get(chunk.index) ?? "") + chunk.argsDelta); for (const f of sse.toolArgs(chunk.index, chunk.argsDelta)) res.write(f); } + } + for (const f of sse.finish(usage, finish, argsByIdx)) res.write(f); + res.end(); + metric(200); + } else { + res.json(canonicalToResponsesResponse(await provider.complete(canon))); + metric(200); + } + } catch (err) { + const raw = err instanceof Error ? err.message : String(err); + const hint = errorHint(raw); + const message = hint ? `${raw}\n${hint}` : raw; + const status = err instanceof CopilotAuthError ? 401 : 502; + if (!res.headersSent) { + res.status(status).json({ error: { type: "error", message } }); + } else { + res.write(`data: ${JSON.stringify({ type: "error", message })}\n\n`); + res.end(); + } + metric(status, message); + } + }); } diff --git a/src/worker/server.ts b/src/worker/server.ts index 6fb0e4a..cf3cb7b 100644 --- a/src/worker/server.ts +++ b/src/worker/server.ts @@ -2,14 +2,15 @@ import express, { type Express } from "express"; import type { Router } from "./router.js"; import { mountOpenAI } from "./openai-server.js"; import { mountAnthropic } from "./anthropic-server.js"; +import type { GatewayToolRunner } from "../core/server-tools.js"; export type MetricSink = (m: { endpoint: string; model: string; status: number; latencyMs: number; error?: string }) => void; -export function createWorkerApp(router: Router, onMetric: MetricSink): Express { +export function createWorkerApp(router: Router, onMetric: MetricSink, gatewayRunner?: GatewayToolRunner): Express { const app = express(); app.use(express.json({ limit: "20mb" })); app.get("/healthz", (_req, res) => res.json({ ok: true })); mountOpenAI(app, router, onMetric); - mountAnthropic(app, router, onMetric); + mountAnthropic(app, router, onMetric, gatewayRunner); return app; } diff --git a/tests/core/anthropic-inbound.test.ts b/tests/core/anthropic-inbound.test.ts index 567f5a4..669fda8 100644 --- a/tests/core/anthropic-inbound.test.ts +++ b/tests/core/anthropic-inbound.test.ts @@ -58,16 +58,25 @@ describe("anthropic inbound", () => { expect(blocks[2]).toEqual({ type: "image", dataUrl: "https://x/y.jpg" }); }); - it("drops Anthropic server-side tools that have no input_schema (prevents client hang)", () => { + it("converts web_search/web_fetch server tools to function tools, still drops others (bash/computer)", () => { const c = anthropicRequestToCanonical({ model: "claude-opus-4-8", max_tokens: 100, messages: [{ role: "user", content: "hi" }], tools: [ { name: "get_weather", description: "w", input_schema: { type: "object", properties: {} } }, { type: "web_search_20250305", name: "web_search", max_uses: 5 } as any, + { type: "web_fetch_20250910", name: "web_fetch", max_uses: 5 } as any, { type: "bash_20250124", name: "bash" } as any, ], }); - expect(c.tools?.map((t) => t.name)).toEqual(["get_weather"]); + const names = c.tools?.map((t) => t.name) ?? []; + // Custom tool kept, both web_* tools converted (now carry a real schema), bash dropped. + expect(names).toContain("get_weather"); + expect(names).toContain("web_search"); + expect(names).toContain("web_fetch"); + expect(names).not.toContain("bash"); + const ws = c.tools?.find((t) => t.name === "web_search"); + expect((ws?.parameters as any)?.type).toBe("object"); + expect((ws?.parameters as any)?.properties?.query).toBeTruthy(); }); }); diff --git a/tests/core/responses-inbound.test.ts b/tests/core/responses-inbound.test.ts new file mode 100644 index 0000000..d8acebd --- /dev/null +++ b/tests/core/responses-inbound.test.ts @@ -0,0 +1,93 @@ +import { describe, it, expect } from "vitest"; +import { responsesRequestToCanonical, canonicalToResponsesResponse, ResponsesSSE } from "../../src/core/responses-inbound.js"; +import type { CanonicalResponse } from "../../src/core/canonical.js"; + +describe("responsesRequestToCanonical", () => { + it("flattens instructions to a system message and a string input to a user message", () => { + const c = responsesRequestToCanonical({ model: "gpt-5-mini", instructions: "be terse", input: "hello", stream: false }); + expect(c.model).toBe("gpt-5-mini"); + expect(c.messages[0]).toEqual({ role: "system", content: [{ type: "text", text: "be terse" }] }); + expect(c.messages[1]).toEqual({ role: "user", content: [{ type: "text", text: "hello" }] }); + }); + + it("maps input items: message / function_call / function_call_output", () => { + const c = responsesRequestToCanonical({ + model: "gpt-5", stream: false, + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "what time" }] }, + { type: "function_call", call_id: "fc1", name: "now", arguments: '{"tz":"utc"}' }, + { type: "function_call_output", call_id: "fc1", output: "12:00" }, + ], + }); + expect(c.messages[0]).toEqual({ role: "user", content: [{ type: "text", text: "what time" }] }); + expect(c.messages[1].content[0]).toEqual({ type: "tool_use", id: "fc1", name: "now", input: { tz: "utc" } }); + expect(c.messages[2]).toEqual({ role: "tool", content: [{ type: "tool_result", toolUseId: "fc1", content: "12:00" }] }); + }); + + it("maps function tools to canonical tools and ignores non-function tools", () => { + const c = responsesRequestToCanonical({ + model: "gpt-5", stream: false, input: "hi", + tools: [ + { type: "function", name: "search", description: "d", parameters: { type: "object", properties: {} } }, + { type: "web_search" }, + ] as any, + }); + expect(c.tools).toHaveLength(1); + expect(c.tools![0]).toMatchObject({ name: "search" }); + }); +}); + +describe("canonicalToResponsesResponse", () => { + it("wraps text in an output_text message item with usage", () => { + const r: CanonicalResponse = { id: "r1", model: "gpt-5", content: [{ type: "text", text: "hi there" }], finishReason: "stop", usage: { promptTokens: 10, completionTokens: 3 } }; + const out = canonicalToResponsesResponse(r); + expect(out.object).toBe("response"); + expect(out.status).toBe("completed"); + const msg = out.output.find((o: any) => o.type === "message"); + expect(msg.content[0]).toMatchObject({ type: "output_text", text: "hi there" }); + expect(out.usage).toMatchObject({ input_tokens: 10, output_tokens: 3, total_tokens: 13 }); + }); + + it("emits function_call items for tool_use blocks", () => { + const r: CanonicalResponse = { id: "r1", model: "gpt-5", content: [{ type: "tool_use", id: "fc1", name: "search", input: { q: "x" } }], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }; + const out = canonicalToResponsesResponse(r); + const fc = out.output.find((o: any) => o.type === "function_call"); + expect(fc).toMatchObject({ type: "function_call", call_id: "fc1", name: "search" }); + expect(JSON.parse(fc.arguments)).toEqual({ q: "x" }); + }); +}); + +describe("ResponsesSSE emitter", () => { + it("emits the ordered text event sequence with monotonic sequence_number", () => { + const sse = new ResponsesSSE("resp_1", "gpt-5"); + const out: string[] = []; + out.push(sse.start()); + out.push(...[sse.text("Hel"), sse.text("lo")].flat()); + out.push(...sse.finish({ promptTokens: 1, completionTokens: 1 }, "stop")); + const events = out.join("").split("\n\n").filter(Boolean).map((b) => JSON.parse(b.replace(/^data: /, ""))); + const types = events.map((e) => e.type); + expect(types[0]).toBe("response.created"); + expect(types).toContain("response.output_item.added"); + expect(types).toContain("response.content_part.added"); + expect(types.filter((t) => t === "response.output_text.delta")).toHaveLength(2); + expect(types).toContain("response.output_text.done"); + expect(types.at(-1)).toBe("response.completed"); + // sequence_number is present and strictly increasing + const seqs = events.map((e) => e.sequence_number); + expect(seqs.every((n, i) => i === 0 || n > seqs[i - 1])).toBe(true); + }); + + it("emits function_call argument events for a tool call", () => { + const sse = new ResponsesSSE("resp_2", "gpt-5"); + const out: string[] = []; + out.push(sse.start()); + out.push(...sse.toolStart(0, "fc1", "search")); + out.push(...sse.toolArgs(0, '{"q":1}')); + out.push(...sse.finish({ promptTokens: 1, completionTokens: 1 }, "tool_use")); + const text = out.join(""); + expect(text).toContain("response.output_item.added"); + expect(text).toContain("response.function_call_arguments.delta"); + expect(text).toContain("response.function_call_arguments.done"); + expect(text).toContain("response.completed"); + }); +}); diff --git a/tests/core/server-tools.test.ts b/tests/core/server-tools.test.ts new file mode 100644 index 0000000..227749f --- /dev/null +++ b/tests/core/server-tools.test.ts @@ -0,0 +1,67 @@ +import { describe, it, expect, vi } from "vitest"; +import { GATEWAY_TOOL_DEFS, isGatewayTool, makeGatewayRunner } from "../../src/core/server-tools.js"; + +describe("GATEWAY_TOOL_DEFS", () => { + it("defines web_search and web_fetch as real function tools with JSON-Schema params", () => { + const names = GATEWAY_TOOL_DEFS.map((t) => t.name); + expect(names).toContain("web_search"); + expect(names).toContain("web_fetch"); + for (const t of GATEWAY_TOOL_DEFS) { + expect(t.parameters).toBeTypeOf("object"); + expect((t.parameters as any).type).toBe("object"); + } + }); +}); + +describe("isGatewayTool", () => { + it("matches the gateway tool names", () => { + expect(isGatewayTool("web_search")).toBe(true); + expect(isGatewayTool("web_fetch")).toBe(true); + }); + it("rejects client/other tools", () => { + expect(isGatewayTool("Read")).toBe(false); + expect(isGatewayTool("bash")).toBe(false); + }); +}); + +describe("makeGatewayRunner", () => { + it("dispatches web_search to the WebIQ client and returns formatted text", async () => { + const search = vi.fn(async () => ({ ok: true as const, results: [{ title: "T", url: "https://a", content: "C" }] })); + const fetchPage = vi.fn(); + const run = makeGatewayRunner(() => "KEY", { search, fetchPage } as any); + const out = await run("web_search", { query: "hello" }); + expect(search).toHaveBeenCalledWith("KEY", expect.objectContaining({ query: "hello" })); + expect(out).toMatch(/T/); + expect(out).toMatch(/https:\/\/a/); + }); + + it("dispatches web_fetch to the WebIQ client", async () => { + const search = vi.fn(); + const fetchPage = vi.fn(async () => ({ ok: true as const, title: "P", url: "https://b", content: "BODY" })); + const run = makeGatewayRunner(() => "KEY", { search, fetchPage } as any); + const out = await run("web_fetch", { url: "https://b" }); + expect(fetchPage).toHaveBeenCalledWith("KEY", expect.objectContaining({ url: "https://b" })); + expect(out).toMatch(/BODY/); + }); + + it("returns the WebIQ error string (not a throw) when the call fails", async () => { + const search = vi.fn(async () => ({ ok: false as const, error: "web search unavailable: key missing" })); + const run = makeGatewayRunner(() => "KEY", { search, fetchPage: vi.fn() } as any); + const out = await run("web_search", { query: "x" }); + expect(out).toMatch(/key missing/); + }); + + it("tells the model when no key is configured, without calling the client", async () => { + const search = vi.fn(); + const run = makeGatewayRunner(() => null, { search, fetchPage: vi.fn() } as any); + const out = await run("web_search", { query: "x" }); + expect(search).not.toHaveBeenCalled(); + expect(out).toMatch(/web-search-support/); + }); + + it("guards against a malformed input (missing query)", async () => { + const run = makeGatewayRunner(() => "KEY", { search: vi.fn(), fetchPage: vi.fn() } as any); + const out = await run("web_search", {}); + expect(out).toMatch(/query/i); + }); +}); diff --git a/tests/providers/copilot/models.test.ts b/tests/providers/copilot/models.test.ts new file mode 100644 index 0000000..e7689d0 --- /dev/null +++ b/tests/providers/copilot/models.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect, vi } from "vitest"; +import { fetchModelEndpoints } from "../../../src/providers/copilot/models.js"; + +const json = (b: unknown) => new Response(JSON.stringify(b), { status: 200, headers: { "content-type": "application/json" } }); + +describe("fetchModelEndpoints", () => { + it("maps model id -> supported_endpoints", async () => { + const f = vi.fn(async () => json({ data: [ + { id: "gpt-5.5", supported_endpoints: ["/responses", "ws:/responses"] }, + { id: "gpt-4o", supported_endpoints: undefined }, + { id: "gpt-5-mini", supported_endpoints: ["/chat/completions", "/responses"] }, + ] })); + const out = await fetchModelEndpoints("tok", f as unknown as typeof fetch); + expect(out["gpt-5.5"]).toEqual(["/responses", "ws:/responses"]); + expect(out["gpt-5-mini"]).toContain("/chat/completions"); + expect(out["gpt-4o"]).toBeUndefined(); // no field -> omitted + }); + + it("returns {} when the endpoint fails", async () => { + const f = vi.fn(async () => new Response("", { status: 500 })); + expect(await fetchModelEndpoints("tok", f as unknown as typeof fetch)).toEqual({}); + }); +}); diff --git a/tests/providers/webiq/client.test.ts b/tests/providers/webiq/client.test.ts new file mode 100644 index 0000000..a2ca720 --- /dev/null +++ b/tests/providers/webiq/client.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, vi } from "vitest"; +import { webSearch, webFetch, formatSearchResults, formatFetchResult } from "../../../src/providers/webiq/client.js"; + +const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { "content-type": "application/json" } }); + +describe("webSearch", () => { + it("posts the query with the api key and returns parsed results", async () => { + const f = vi.fn(async () => json({ webResults: [{ title: "T1", url: "https://a", content: "C1" }], traceId: "tid" })); + const out = await webSearch("KEY", { query: "llm rag" }, f as unknown as typeof fetch); + expect(out.ok).toBe(true); + if (!out.ok) throw new Error("expected ok"); + expect(out.results).toHaveLength(1); + expect(out.results[0]).toMatchObject({ title: "T1", url: "https://a", content: "C1" }); + // Verify the wire call: endpoint, method, x-apikey header, query in body. + const [url, init] = f.mock.calls[0] as [string, RequestInit]; + expect(url).toBe("https://api.microsoft.ai/v3/search/web"); + expect(init.method).toBe("POST"); + expect((init.headers as Record)["x-apikey"]).toBe("KEY"); + expect(JSON.parse(init.body as string)).toMatchObject({ query: "llm rag" }); + }); + + it("maps a 401 to a readable, non-throwing error", async () => { + const f = vi.fn(async () => json({}, 401)); + const out = await webSearch("BAD", { query: "x" }, f as unknown as typeof fetch); + expect(out.ok).toBe(false); + if (out.ok) throw new Error("expected error"); + expect(out.error).toMatch(/key/i); + }); + + it("maps a 429 to a rate-limit message", async () => { + const f = vi.fn(async () => json({}, 429)); + const out = await webSearch("KEY", { query: "x" }, f as unknown as typeof fetch); + expect(out.ok).toBe(false); + if (out.ok) throw new Error("expected error"); + expect(out.error).toMatch(/rate limit/i); + }); + + it("never throws on a network failure — returns an error result", async () => { + const f = vi.fn(async () => { throw new Error("ECONNRESET"); }); + const out = await webSearch("KEY", { query: "x" }, f as unknown as typeof fetch); + expect(out.ok).toBe(false); + }); +}); + +describe("webFetch", () => { + it("posts the url and returns the page content", async () => { + const f = vi.fn(async () => json({ title: "Page", url: "https://b", content: "BODY" })); + const out = await webFetch("KEY", { url: "https://b" }, f as unknown as typeof fetch); + expect(out.ok).toBe(true); + if (!out.ok) throw new Error("expected ok"); + expect(out.title).toBe("Page"); + expect(out.content).toBe("BODY"); + const [url, init] = f.mock.calls[0] as [string, RequestInit]; + expect(url).toBe("https://api.microsoft.ai/v3/browse"); + expect(JSON.parse(init.body as string)).toMatchObject({ url: "https://b" }); + }); + + it("maps a 404 to a not-found message", async () => { + const f = vi.fn(async () => json({}, 404)); + const out = await webFetch("KEY", { url: "https://missing" }, f as unknown as typeof fetch); + expect(out.ok).toBe(false); + if (out.ok) throw new Error("expected error"); + expect(out.error).toMatch(/not found/i); + }); +}); + +describe("formatters produce model-readable tool_result text", () => { + it("formatSearchResults lists numbered title/url/content", () => { + const s = formatSearchResults([ + { title: "T1", url: "https://a", content: "C1" }, + { title: "T2", url: "https://b", content: "C2" }, + ]); + expect(s).toMatch(/T1/); + expect(s).toMatch(/https:\/\/a/); + expect(s).toMatch(/C1/); + expect(s).toMatch(/T2/); + }); + it("formatSearchResults handles an empty list", () => { + expect(formatSearchResults([])).toMatch(/no results/i); + }); + it("formatFetchResult includes title, url, and content", () => { + const s = formatFetchResult({ title: "Page", url: "https://b", content: "BODY" }); + expect(s).toMatch(/Page/); + expect(s).toMatch(/https:\/\/b/); + expect(s).toMatch(/BODY/); + }); +}); diff --git a/tests/shared/webiq-key.test.ts b/tests/shared/webiq-key.test.ts new file mode 100644 index 0000000..ca7d7a1 --- /dev/null +++ b/tests/shared/webiq-key.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readWebIqKey, writeWebIqKey, clearWebIqKey } from "../../src/shared/webiq-key.js"; + +describe("webiq-key", () => { + const prev = process.env.WEBIQ_API_KEY; + beforeEach(() => { delete process.env.WEBIQ_API_KEY; }); + afterEach(() => { if (prev === undefined) delete process.env.WEBIQ_API_KEY; else process.env.WEBIQ_API_KEY = prev; }); + + it("round-trips a key", () => { + const d = mkdtempSync(join(tmpdir(), "m-")); + writeWebIqKey("k_abc", d); + expect(readWebIqKey(d)).toBe("k_abc"); + }); + it("null when absent", () => { + expect(readWebIqKey(mkdtempSync(join(tmpdir(), "m-")))).toBeNull(); + }); + it("clearWebIqKey removes the key (and is a no-op when absent)", () => { + const d = mkdtempSync(join(tmpdir(), "m-")); + writeWebIqKey("k_abc", d); + clearWebIqKey(d); + expect(readWebIqKey(d)).toBeNull(); + expect(() => clearWebIqKey(d)).not.toThrow(); + }); + it("env WEBIQ_API_KEY overrides the file", () => { + const d = mkdtempSync(join(tmpdir(), "m-")); + writeWebIqKey("from_file", d); + process.env.WEBIQ_API_KEY = "from_env"; + expect(readWebIqKey(d)).toBe("from_env"); + }); +}); diff --git a/tests/tui/app-interaction.test.tsx b/tests/tui/app-interaction.test.tsx index 62c7b74..3e71dab 100644 --- a/tests/tui/app-interaction.test.tsx +++ b/tests/tui/app-interaction.test.tsx @@ -167,6 +167,86 @@ describe("TUI: /login surfaces the device code before the poll resolves", () => }); }); +describe("TUI: /web-search-support key entry", () => { + it("opens a masked key screen and persists the typed key via saveWebIqKey", async () => { + const saved: string[] = []; + const saveWebIqKey = (k: string) => { saved.push(k); }; + const { stdin, lastFrame } = render(); + await tick(); + stdin.write("/web-search-support"); + await tick(); + stdin.write("\r"); // run the command -> opens the screen + await tick(60); + expect(lastFrame()).toMatch(/WebIQ API key/i); + // type a key (should render masked, not echoed) + stdin.write("secret-key-123"); + await tick(); + expect(lastFrame()).not.toContain("secret-key-123"); + expect(lastFrame()).toMatch(/•/); + stdin.write("\r"); // submit + await tick(60); + expect(saved).toEqual(["secret-key-123"]); + }); +}); + +describe("TUI: /status command shows the live status card", () => { + it("renders the GitHub/web/worker overview when /status is run", async () => { + const { stdin, lastFrame } = render( + "connected"} + webSearchReady={() => true} />, + ); + await tick(); + stdin.write("/status"); + await tick(); + stdin.write("\r"); + await tick(80); + const f = lastFrame() ?? ""; + expect(f).toMatch(/GitHub login.*connected/); + expect(f).toMatch(/web search.*✓ ready/); + }); + + it("steers to /web-search-support in the card when web search is unconfigured", async () => { + const { stdin, lastFrame } = render( + "connected"} + webSearchReady={() => false} />, + ); + await tick(); + stdin.write("/status"); + await tick(); + stdin.write("\r"); + await tick(80); + expect(lastFrame()).toMatch(/web search.*not configured.*\/web-search-support/); + }); +}); + +describe("TUI: startup status card", () => { + it("renders the GitHub/web-search/worker overview on startup", () => { + const startupStatus = { github: "connected" as const, webSearch: "not-configured" as const, worker: "ready" as const, clients: { claude: true, codex: false } }; + const { lastFrame } = render(); + const f = lastFrame() ?? ""; + expect(f).toMatch(/status/); + expect(f).toMatch(/GitHub login.*connected/); + expect(f).toMatch(/web search.*not configured.*\/web-search-support/); + expect(f).toMatch(/worker.*ready/); + }); +}); + +describe("TUI: HUD web search indicator", () => { + it("shows web ✗ with the command hint when no WebIQ key is configured", () => { + const { lastFrame } = render( false} />); + const f = lastFrame() ?? ""; + expect(f).toMatch(/web .*✗/); + expect(f).toContain("/web-search-support"); + }); + it("shows web ✓ when a WebIQ key is configured", () => { + const { lastFrame } = render( true} />); + const f = lastFrame() ?? ""; + expect(f).toMatch(/web .*✓/); + }); +}); + describe("TUI: model picker", () => { it("/model opens the picker and lists models with context windows", async () => { const loadModels = async () => ["gpt-4o", "claude-opus-4.8"]; diff --git a/tests/tui/codex-toml.test.ts b/tests/tui/codex-toml.test.ts index 1ea0f47..d4f709d 100644 --- a/tests/tui/codex-toml.test.ts +++ b/tests/tui/codex-toml.test.ts @@ -17,7 +17,42 @@ describe("applyCodexToml", () => { expect(toml).toContain("model_context_window = 1050000"); expect(toml).toContain("[model_providers.copilot-reverse]"); expect(toml).toContain('base_url = "http://127.0.0.1:7891/v1"'); - expect(toml).toContain('wire_api = "chat"'); + expect(toml).toContain('wire_api = "responses"'); + // Auth: a static bearer token inlined so Codex uses our local proxy instead of falling back to + // the OpenAI login flow. The worker ignores the key value. + expect(toml).toContain('requires_openai_auth = false'); + expect(toml).toContain('experimental_bearer_token = "copilot-reverse-local"'); + }); + + it("places top-level keys BEFORE any table (TOML: a bare key after [table] belongs to that table)", () => { + const home = tmp(); + mkdirSync(join(home, ".codex"), { recursive: true }); + // Pre-existing config that has tables (like a real ~/.codex/config.toml with [marketplaces] etc). + writeFileSync(codexTomlPath(home), '[windows]\nsandbox = "unelevated"\n\n[tui.x]\na = 1\n'); + applyCodexToml({ home, baseUrl: "http://127.0.0.1:7891/openai", model: "gpt-5.5", contextWindow: 1_050_000 }); + const toml = readFileSync(codexTomlPath(home), "utf8"); + const lines = toml.split("\n"); + const providerLine = lines.findIndex((l) => /^model_provider\s*=/.test(l)); + const firstTable = lines.findIndex((l) => /^\s*\[/.test(l)); + // model_provider must be a TRUE top-level key — appear before the first [table], else Codex + // parses it into that table and falls back to provider "openai". + expect(providerLine).toBeGreaterThanOrEqual(0); + expect(firstTable).toBeGreaterThanOrEqual(0); + expect(providerLine).toBeLessThan(firstTable); + // pre-existing table content is still preserved + expect(toml).toContain('sandbox = "unelevated"'); + }); + + it("de-duplicates managed keys left in the table region by a previous buggy write", () => { + const home = tmp(); + mkdirSync(join(home, ".codex"), { recursive: true }); + // Simulate the old broken output: managed keys sitting AFTER a table (TOML-nested). + writeFileSync(codexTomlPath(home), '[windows]\nsandbox = "x"\n\nmodel = "old"\nmodel_provider = "old-prov"\n'); + applyCodexToml({ home, baseUrl: "http://x/openai", model: "gpt-5.5" }); + const toml = readFileSync(codexTomlPath(home), "utf8"); + expect(toml.match(/^model_provider = /gm)?.length).toBe(1); // exactly one, at the top + expect(toml.match(/^model = /gm)?.length).toBe(1); + expect(toml).not.toContain('"old-prov"'); // stale value gone }); it("preserves unrelated existing keys and is idempotent", () => { diff --git a/tests/tui/status-summary.test.ts b/tests/tui/status-summary.test.ts new file mode 100644 index 0000000..88a1c90 --- /dev/null +++ b/tests/tui/status-summary.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect } from "vitest"; +import { githubLoginState, summarizeStatus, type StatusInputs } from "../../src/tui/status-summary.js"; + +describe("githubLoginState", () => { + it("signed-out when there is no token", () => { + expect(githubLoginState(false, false)).toBe("signed-out"); + }); + it("expired when a token exists but no longer exchanges", () => { + expect(githubLoginState(true, false)).toBe("expired"); + }); + it("connected when the token exchanges for a Copilot token", () => { + expect(githubLoginState(true, true)).toBe("connected"); + }); +}); + +describe("summarizeStatus", () => { + const base: StatusInputs = { + hasToken: true, tokenValid: true, webSearchReady: true, + worker: "ready", clients: { claude: true, codex: false }, + }; + it("maps a fully-configured environment", () => { + const s = summarizeStatus(base); + expect(s.github).toBe("connected"); + expect(s.webSearch).toBe("ready"); + expect(s.worker).toBe("ready"); + expect(s.clients).toEqual({ claude: true, codex: false }); + }); + it("reports web search as not configured when no key is present", () => { + expect(summarizeStatus({ ...base, webSearchReady: false }).webSearch).toBe("not-configured"); + }); + it("reports github expired when token present but invalid", () => { + expect(summarizeStatus({ ...base, tokenValid: false }).github).toBe("expired"); + }); + it("reports github signed-out when no token", () => { + expect(summarizeStatus({ ...base, hasToken: false, tokenValid: false }).github).toBe("signed-out"); + }); +}); diff --git a/tests/worker/anthropic-server.test.ts b/tests/worker/anthropic-server.test.ts index b5fd67c..a6e035b 100644 --- a/tests/worker/anthropic-server.test.ts +++ b/tests/worker/anthropic-server.test.ts @@ -267,3 +267,177 @@ describe("worker Anthropic endpoint", () => { expect(res.body.has_more).toBe(false); }); }); + +describe("worker Anthropic endpoint — gateway tool loop (web_search/web_fetch)", () => { + // A provider that calls web_search on turn 1, then answers with text on turn 2. Tracks how many + // times stream() ran so we can assert the gateway looped (ran the tool) rather than forwarding it. + function twoTurnProvider(): { adapter: ProviderAdapter; turns: () => number } { + let turn = 0; + const adapter: ProviderAdapter = { + name: "copilot", + complete: async () => ({ id: "c", model: "m", content: [{ type: "text", text: "final" }], finishReason: "stop", usage: { promptTokens: 1, completionTokens: 1 } }), + async *stream(): AsyncIterable { + turn++; + if (turn === 1) { + yield { kind: "tool_use_start", index: 0, id: "tu1", name: "web_search", done: false }; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"query":"node lts"}', done: false }; + yield { kind: "done", done: true, finishReason: "tool_use" }; + } else { + yield { kind: "text", delta: "Node 24 is LTS", done: false }; + yield { kind: "done", done: true, finishReason: "stop" }; + } + }, + }; + return { adapter, turns: () => turn }; + } + + const appWithRunner = (p: ProviderAdapter, runner: (name: string, input: unknown) => Promise) => + createWorkerApp(new Router([p], { "*": "gpt-4o" }), () => {}, runner); + + it("runs web_search internally and streams only the final text (transparent to the client)", async () => { + const { adapter, turns } = twoTurnProvider(); + const calls: { name: string; input: any }[] = []; + const runner = async (name: string, input: unknown) => { calls.push({ name, input }); return "RESULT: Node 24.x is the current LTS"; }; + const res = await request(appWithRunner(adapter, runner)) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, stream: true, messages: [{ role: "user", content: "what is node lts" }] }); + const frames = parseFrames(res.text); + + // gateway ran the tool once, with the model's args, and looped (2 provider turns) + expect(calls).toHaveLength(1); + expect(calls[0].name).toBe("web_search"); + expect(calls[0].input).toMatchObject({ query: "node lts" }); + expect(turns()).toBe(2); + + // client never sees the web_search tool_use block — only the final text + const toolStarts = frames.filter((f) => f.event === "content_block_start" && f.data.content_block?.type === "tool_use"); + expect(toolStarts).toHaveLength(0); + expect(res.text).toContain("Node 24 is LTS"); + // finishes as a normal end_turn, not tool_use (the tool was consumed internally) + expect(frames.find((f) => f.event === "message_delta")?.data.delta.stop_reason).toBe("end_turn"); + expect(frames.at(-1)?.event).toBe("message_stop"); + }); + + it("still forwards CLIENT tools (Read/Bash) to the client unchanged", async () => { + const clientToolProvider: ProviderAdapter = { + name: "copilot", + complete: async () => ({ id: "c", model: "m", content: [], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }), + async *stream(): AsyncIterable { + yield { kind: "tool_use_start", index: 0, id: "tu1", name: "Read", done: false }; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"path":"a.ts"}', done: false }; + yield { kind: "done", done: true, finishReason: "tool_use" }; + }, + }; + const runner = async () => "should not be called"; + const res = await request(appWithRunner(clientToolProvider, runner)) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, stream: true, messages: [{ role: "user", content: "read a.ts" }] }); + const frames = parseFrames(res.text); + const toolStarts = frames.filter((f) => f.event === "content_block_start" && f.data.content_block?.type === "tool_use"); + expect(toolStarts).toHaveLength(1); + expect(toolStarts[0].data.content_block.name).toBe("Read"); + expect(frames.find((f) => f.event === "message_delta")?.data.delta.stop_reason).toBe("tool_use"); + }); + + it("caps the loop so a tool-call-forever provider can't run unbounded", async () => { + const loopForever: ProviderAdapter = { + name: "copilot", + complete: async () => ({ id: "c", model: "m", content: [], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }), + async *stream(): AsyncIterable { + yield { kind: "tool_use_start", index: 0, id: "tu1", name: "web_search", done: false }; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"query":"x"}', done: false }; + yield { kind: "done", done: true, finishReason: "tool_use" }; + }, + }; + let n = 0; + const runner = async () => { n++; return "more"; }; + const res = await request(appWithRunner(loopForever, runner)) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, stream: true, messages: [{ role: "user", content: "go" }] }); + // bounded: the runner is invoked a small, finite number of times, and the stream still terminates + expect(n).toBeGreaterThan(0); + expect(n).toBeLessThanOrEqual(5); + expect(parseFrames(res.text).at(-1)?.event).toBe("message_stop"); + }); + + it("a web_search that hits the loop cap must NOT leak a tool_use block to the client (stream)", async () => { + const loopForever: ProviderAdapter = { + name: "copilot", + complete: async () => ({ id: "c", model: "m", content: [], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }), + async *stream(): AsyncIterable { + yield { kind: "tool_use_start", index: 0, id: "tu1", name: "web_search", done: false }; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"query":"x"}', done: false }; + yield { kind: "done", done: true, finishReason: "tool_use" }; + }, + }; + const res = await request(appWithRunner(loopForever, async () => "more")) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, stream: true, messages: [{ role: "user", content: "go" }] }); + // even when the cap is hit, a gateway tool is never forwarded to the client + expect(res.text).not.toContain('"name":"web_search"'); + expect(parseFrames(res.text).at(-1)?.event).toBe("message_stop"); + }); + + it("mixed gateway + client tools in one turn: runs the gateway tool, forwards ONLY the client tool", async () => { + let turn = 0; + const mixed: ProviderAdapter = { + name: "copilot", + complete: async () => ({ id: "c", model: "m", content: [], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }), + async *stream(): AsyncIterable { + turn++; + if (turn === 1) { + yield { kind: "tool_use_start", index: 0, id: "g1", name: "web_search", done: false }; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"query":"q"}', done: false }; + yield { kind: "tool_use_start", index: 1, id: "c1", name: "Read", done: false }; + yield { kind: "tool_use_delta", index: 1, argsDelta: '{"path":"a.ts"}', done: false }; + yield { kind: "done", done: true, finishReason: "tool_use" }; + } else { + // after the gateway result is fed back, the model re-issues just the client tool + yield { kind: "tool_use_start", index: 0, id: "c2", name: "Read", done: false }; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"path":"a.ts"}', done: false }; + yield { kind: "done", done: true, finishReason: "tool_use" }; + } + }, + }; + const calls: string[] = []; + const res = await request(appWithRunner(mixed, async (name) => { calls.push(name); return "RESULT"; })) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, stream: true, messages: [{ role: "user", content: "go" }] }); + const frames = parseFrames(res.text); + // the gateway tool ran and was NOT forwarded; the client tool WAS forwarded + expect(calls).toContain("web_search"); + expect(res.text).not.toContain('"name":"web_search"'); + const toolStarts = frames.filter((f) => f.event === "content_block_start" && f.data.content_block?.type === "tool_use"); + expect(toolStarts.every((f) => f.data.content_block.name === "Read")).toBe(true); + expect(toolStarts.length).toBeGreaterThan(0); + }); + + it("non-stream: runs web_search internally and returns the final text (no tool_use leaked)", async () => { + let turn = 0; + const twoTurn: ProviderAdapter = { + name: "copilot", + async complete() { + turn++; + return turn === 1 + ? { id: "c", model: "m", content: [{ type: "tool_use", id: "g1", name: "web_search", input: { query: "q" } }], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } } + : { id: "c", model: "m", content: [{ type: "text", text: "grounded answer" }], finishReason: "stop", usage: { promptTokens: 2, completionTokens: 1 } }; + }, + async *stream(): AsyncIterable { yield { kind: "done", done: true, finishReason: "stop" }; }, + }; + const calls: string[] = []; + const res = await request(appWithRunner(twoTurn, async (n) => { calls.push(n); return "RESULT"; })) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, messages: [{ role: "user", content: "go" }] }); + expect(res.status).toBe(200); + expect(calls).toEqual(["web_search"]); + expect(res.body.content.some((b: any) => b.type === "tool_use")).toBe(false); + expect(res.body.content[0].text).toBe("grounded answer"); + expect(res.body.stop_reason).toBe("end_turn"); + }); + + it("non-stream: a web_search that hits the cap must NOT leak a tool_use block to the client", async () => { + const loopForever: ProviderAdapter = { + name: "copilot", + async complete() { return { id: "c", model: "m", content: [{ type: "tool_use", id: "g1", name: "web_search", input: { query: "x" } }], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }; }, + async *stream(): AsyncIterable { yield { kind: "done", done: true, finishReason: "stop" }; }, + }; + const res = await request(appWithRunner(loopForever, async () => "more")) + .post("/anthropic/v1/messages").send({ model: "claude-opus-4-8", max_tokens: 100, messages: [{ role: "user", content: "go" }] }); + expect(res.status).toBe(200); + expect(res.body.content.some((b: any) => b.type === "tool_use")).toBe(false); + }); +}); diff --git a/tests/worker/openai-server.test.ts b/tests/worker/openai-server.test.ts index 257a58e..6631d2f 100644 --- a/tests/worker/openai-server.test.ts +++ b/tests/worker/openai-server.test.ts @@ -45,3 +45,42 @@ describe("worker OpenAI endpoint", () => { expect(typeof res.body.data[0].id).toBe("string"); }); }); + +describe("worker OpenAI Responses endpoint (/openai/responses — Codex)", () => { + it("non-stream: returns an output_text message item", async () => { + const res = await request(app()).post("/openai/responses").send({ model: "gpt-5", input: "hi" }); + expect(res.status).toBe(200); + expect(res.body.object).toBe("response"); + expect(res.body.status).toBe("completed"); + const msg = res.body.output.find((o: any) => o.type === "message"); + expect(msg.content[0]).toMatchObject({ type: "output_text", text: "hello" }); + }); + + it("stream: begins with response.created and ends with response.completed", async () => { + const res = await request(app()).post("/openai/responses").send({ model: "gpt-5", stream: true, input: "hi" }); + const events = res.text.split("\n\n").filter(Boolean).map((b) => JSON.parse(b.replace(/^data: /, ""))); + expect(events[0].type).toBe("response.created"); + expect(events.some((e) => e.type === "response.output_text.delta" && e.delta === "he")).toBe(true); + expect(events.at(-1).type).toBe("response.completed"); + }); + + it("surfaces a function tool call as a function_call output item", async () => { + const toolProvider: ProviderAdapter = { + name: "copilot", + complete: async () => ({ id: "c", model: "gpt-5", content: [{ type: "tool_use", id: "fc1", name: "search", input: { q: "x" } }], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } }), + async *stream() { yield { kind: "done", done: true, finishReason: "stop" } as const; }, + }; + const res = await request(createWorkerApp(new Router([toolProvider], { "*": "gpt-5" }), () => {})) + .post("/openai/responses").send({ model: "gpt-5", input: "go", tools: [{ type: "function", name: "search", parameters: { type: "object", properties: {} } }] }); + const fc = res.body.output.find((o: any) => o.type === "function_call"); + expect(fc).toMatchObject({ type: "function_call", call_id: "fc1", name: "search" }); + }); + + it("returns 502 with the upstream message when the provider fails", async () => { + const fail: ProviderAdapter = { name: "copilot", complete: async () => { throw new Error("boom: responses bad"); }, async *stream() { throw new Error("x"); } }; + const res = await request(createWorkerApp(new Router([fail], { "*": "gpt-5" }), () => {})) + .post("/openai/responses").send({ model: "gpt-5", input: "hi" }); + expect(res.status).toBe(502); + expect(res.body.error.message).toMatch(/boom: responses bad/); + }); +});