Skip to content
Merged
4 changes: 4 additions & 0 deletions .changes/web-search-support.md
Original file line number Diff line number Diff line change
@@ -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.
24 changes: 24 additions & 0 deletions e2e/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 28 additions & 5 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -112,19 +114,21 @@ async function launchTui(): Promise<void> {

// 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) };

Expand All @@ -150,6 +154,17 @@ async function launchTui(): Promise<void> {

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,
Expand All @@ -171,6 +186,14 @@ async function launchTui(): Promise<void> {
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";
},
}),
);
}
Expand Down
33 changes: 26 additions & 7 deletions src/core/anthropic-inbound.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> }
// 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<string, unknown> }
interface AnthropicRequest {
model: string; max_tokens: number; stream?: boolean; temperature?: number;
system?: string | AnthropicBlock[]; tools?: AnthropicTool[]; messages: AnthropicMsg[];
Expand Down Expand Up @@ -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<CanonicalRequest["tools"]> = [];
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 } :
Expand Down
146 changes: 146 additions & 0 deletions src/core/responses-inbound.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> }
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<number, { outputIndex: number; itemId: string }>();
constructor(private responseId: string, private model: string) {}

private ev(type: string, extra: Record<string, unknown>): 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<number, string>): 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;
}
}
Loading
Loading