Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(engine): title recovery and Anthropic tool schemas on the 2.x engine's own hooks

Samrat Talukdar88ac0c6d0e12
diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.ts
index 81ba3e14..9fb16356 100644
--- a/apps/server/src/engine2/facade.ts
+++ b/apps/server/src/engine2/facade.ts
@@ -599,7 +599,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
};
// ---- events -------------------------------------------------------------
- type Subscriber = { directory: string | null; global: boolean; write: (event: V1Event, directory: string | null) => void };
+ type Subscriber = { directory: string | null; global: boolean; write: (event: V1Event, directory: string | null) => void; end: () => void };
const subscribers = new Set<Subscriber>();
const streamController = new AbortController();
let streamStarted = false;
@@ -673,7 +673,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
res.write(`data: ${JSON.stringify(payload)}\n\n`);
};
write({ type: "server.connected", properties: {} }, null);
- const subscriber: Subscriber = { directory, global, write };
+ const subscriber: Subscriber = { directory, global, write, end: () => res.end() };
subscribers.add(subscriber);
const heartbeat = setInterval(() => {
const beat = { type: "server.heartbeat", properties: {} };
@@ -1283,10 +1283,18 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
refreshConfig,
close: async () => {
streamController.abort();
- for (const subscriber of subscribers) subscribers.delete(subscriber);
+ // Event streams stay open until ended; end them so the server can close.
+ for (const subscriber of subscribers) {
+ subscribers.delete(subscriber);
+ try {
+ subscriber.end();
+ } catch {
+ // already closed
+ }
+ }
const closed = new Promise<void>((resolve) => server.close(() => resolve()));
server.closeAllConnections?.();
- await closed;
+ await Promise.race([closed, new Promise<void>((resolve) => setTimeout(resolve, 3_000).unref?.())]);
},
};
}
diff --git a/apps/server/src/engine2/plugin-bridge.e2e.test.ts b/apps/server/src/engine2/plugin-bridge.e2e.test.ts
new file mode 100644
index 00000000..072247f6
--- /dev/null
+++ b/apps/server/src/engine2/plugin-bridge.e2e.test.ts
@@ -0,0 +1,189 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../managed-opencode.js";
+
+/**
+ * OmniRush plugins that used to patch the global fetch, on the real 2.x
+ * engine (the bundled sidecar, started as the app starts it, with the plugin
+ * bridge) against a mock provider:
+ *
+ * - title recovery: the private x-omnirush-title-attempt header never
+ * reaches the provider, and a rejected optional title parameter
+ * (`reasoning_effort`) is retried without it, so the session still gets its title;
+ * - Anthropic tool schemas: an MCP tool whose input schema has a top-level
+ * `anyOf` reaches the Anthropic Messages API flattened.
+ *
+ * Skipped when the sidecar binary is not present (prepare:sidecar not run).
+ */
+
+const repoRoot = resolve(import.meta.dir, "../../../..");
+const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");
+function findSidecar(): string | null {
+ const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
+ const name = process.platform === "darwin" ? `opencode-${arch}-apple-darwin` : process.platform === "linux" ? `opencode-${arch}-unknown-linux-gnu` : "";
+ const candidate = join(sidecarDir, name);
+ return name && existsSync(candidate) ? candidate : null;
+}
+const enginePath = findSidecar();
+const describeMaybe = enginePath ? describe : describe.skip;
+
+const HEADER = "x-omnirush-title-attempt";
+const TITLE = "Recovered title from the mock";
+
+type Seen = { path: string; headers: Record<string, string>; body: Record<string, any> };
+
+function chatStream(content: string): Response {
+ const chunk = (delta: object, finish: string | null = null) => `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`;
+ const body = chunk({ role: "assistant", content: "" }) + chunk({ content }) + chunk({}, "stop")
+ + `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m", choices: [], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } })}\n\ndata: [DONE]\n\n`;
+ return new Response(body, { headers: { "content-type": "text/event-stream" } });
+}
+
+function chatJson(content: string): Response {
+ return Response.json({ id: "c", object: "chat.completion", created: 1, model: "m", choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: "stop" }], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } });
+}
+
+describeMaybe("OmniRush plugins on the 2.x engine's own hooks (mock provider)", () => {
+ let engine: ManagedOpencodeServer;
+ let provider: ReturnType<typeof Bun.serve>;
+ let work = "";
+ let data = "";
+ const seen: Seen[] = [];
+
+ const engineFetch = async (path: string, init?: RequestInit) => {
+ const headers = new Headers(init?.headers);
+ headers.set("authorization", `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}`);
+ headers.set("x-opencode-directory", encodeURIComponent(work));
+ return fetch(`${engine.url}${path}`, { ...init, headers });
+ };
+ const waitFor = async <T>(read: () => Promise<T | null | undefined | false>, label: string, ms = 60_000): Promise<T> => {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) {
+ const value = await read().catch(() => null);
+ if (value) return value as T;
+ await Bun.sleep(250);
+ }
+ throw new Error(`timed out waiting for ${label}; seen=${JSON.stringify(seen.map((s) => [s.path, Object.keys(s.body)]))}`);
+ };
+ const prompt = async (model: { providerID: string; modelID: string }, text: string, variant?: string) => {
+ const session = (await (await engineFetch("/session", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).json()) as { id: string };
+ const sent = await engineFetch(`/session/${session.id}/prompt_async`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ model, ...(variant ? { variant } : {}), parts: [{ type: "text", text }] }),
+ });
+ expect(sent.status).toBe(204);
+ return session.id;
+ };
+
+ beforeAll(async () => {
+ work = mkdtempSync(join(tmpdir(), "plugin-bridge-ws-"));
+ data = mkdtempSync(join(tmpdir(), "plugin-bridge-data-"));
+ provider = Bun.serve({
+ port: 0,
+ async fetch(request) {
+ const url = new URL(request.url);
+ const body = request.method === "POST" ? ((await request.json().catch(() => ({}))) as Record<string, any>) : {};
+ // The OmniRush server endpoints the plugins call (policy allows everything here).
+ if (url.pathname.startsWith("/managed-policy")) return Response.json({ allowed: true, approvalMode: "full" });
+ if (!url.pathname.startsWith("/v1/")) return Response.json({});
+ seen.push({ path: url.pathname, headers: Object.fromEntries(request.headers), body });
+ if (url.pathname === "/v1/messages") {
+ return Response.json({ type: "error", error: { type: "invalid_request_error", message: "stop here" } }, { status: 400 });
+ }
+ const titleRequest = !Array.isArray(body.tools) || body.tools.length === 0;
+ if (titleRequest && "reasoning_effort" in body) {
+ return Response.json({ error: { code: "unsupported_parameter", param: "reasoning_effort", message: "Unsupported parameter: reasoning_effort" } }, { status: 400 });
+ }
+ if (titleRequest) return body.stream ? chatStream(TITLE) : chatJson(TITLE);
+ return body.stream ? chatStream("Done.") : chatJson("Done.");
+ },
+ });
+ const base = `http://127.0.0.1:${provider.port}`;
+ // A local MCP server with one tool whose input schema has a top-level anyOf.
+ const mcpScript = join(data, "anyof-mcp.mjs");
+ writeFileSync(mcpScript, `import readline from "node:readline";
+const rl = readline.createInterface({ input: process.stdin });
+const send = (m) => process.stdout.write(JSON.stringify(m) + "\\n");
+rl.on("line", (line) => {
+ let m; try { m = JSON.parse(line); } catch { return; }
+ if (m.id === undefined) return;
+ if (m.method === "initialize") return send({ jsonrpc: "2.0", id: m.id, result: { protocolVersion: m.params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "anyof", version: "1.0.0" } } });
+ if (m.method === "tools/list") return send({ jsonrpc: "2.0", id: m.id, result: { tools: [{ name: "export_batch", description: "Export a batch", inputSchema: { type: "object", anyOf: [{ properties: { id: { type: "string" } }, required: ["id"] }, { properties: { name: { type: "string" } }, required: ["name"] }] } }] } });
+ send({ jsonrpc: "2.0", id: m.id, result: { content: [{ type: "text", text: "ok" }] } });
+});
+`);
+ const configPath = join(data, "runtime-opencode-config.json");
+ writeFileSync(configPath, JSON.stringify({
+ model: "mock/mock-model",
+ permission: { "*": "allow" },
+ provider: {
+ mock: { name: "Mock", npm: "@ai-sdk/openai-compatible", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "mock-model": { name: "Mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },
+ anth: { name: "Anth", npm: "@ai-sdk/anthropic", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "claude-mock": { name: "Claude mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },
+ },
+ mcp: { anyof: { type: "local", command: ["node", mcpScript], enabled: true } },
+ }));
+ engine = await createManagedOpencodeServer({
+ bin: enginePath!,
+ cwd: work,
+ env: {
+ OPENCODE_CONFIG: configPath,
+ OPENCODE_DISABLE_MODELS_FETCH: "1",
+ OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),
+ OMNIRUSH_SERVER_URL: base,
+ OMNIRUSH_POLICY_TOKEN: "policy",
+ OMNIRUSH_SERVER_TOKEN: "server",
+ HOME: join(data, "home"),
+ OPENCODE_TEST_HOME: join(data, "home"),
+ XDG_DATA_HOME: join(data, "xdg-data"),
+ XDG_CONFIG_HOME: join(data, "xdg-config"),
+ XDG_STATE_HOME: join(data, "xdg-state"),
+ XDG_CACHE_HOME: join(data, "xdg-cache"),
+ },
+ });
+ await waitFor(async () => (await engineFetch("/mcp")).ok, "engine");
+ }, 120_000);
+
+ afterAll(async () => {
+ await engine?.close();
+ provider?.stop(true);
+ rmSync(work, { recursive: true, force: true });
+ rmSync(data, { recursive: true, force: true });
+ }, 30_000);
+
+ test("the title marker never reaches the provider, and a rejected reasoning effort is retried without it", async () => {
+ seen.length = 0;
+ const sessionID = await prompt({ providerID: "mock", modelID: "mock-model" }, "Say done.", "high");
+ const titled = await waitFor(async () => {
+ const info = (await (await engineFetch(`/session/${sessionID}`)).json()) as { title?: string };
+ return info.title?.startsWith(TITLE) ? info : null;
+ }, "the recovered title");
+ expect(titled.title).toStartWith(TITLE);
+ // The turn itself (with tools) goes out too.
+ await waitFor(async () => seen.some((request) => Array.isArray(request.body.tools) && request.body.tools.length > 0), "the turn's request");
+ const chat = seen.filter((request) => request.path === "/v1/chat/completions");
+ for (const request of chat) expect(request.headers[HEADER]).toBeUndefined();
+ const titles = chat.filter((request) => !Array.isArray(request.body.tools) || request.body.tools.length === 0);
+ // The session's variant gives the title request a reasoning effort the mock rejects.
+ expect(titles.map((request) => "reasoning_effort" in request.body)).toEqual([true, false]);
+ }, 90_000);
+
+ test("an MCP tool with a top-level anyOf reaches the Anthropic API flattened", async () => {
+ seen.length = 0;
+ await waitFor(async () => {
+ const status = (await (await engineFetch("/mcp")).json()) as Record<string, { status: string }>;
+ return status.anyof?.status === "connected";
+ }, "the MCP server");
+ await prompt({ providerID: "anth", modelID: "claude-mock" }, "Use the export tool.");
+ const request = await waitFor(async () => seen.find((entry) => entry.path === "/v1/messages" && Array.isArray(entry.body.tools) && entry.body.tools.length > 0), "an Anthropic request with tools");
+ const tool = (request.body.tools as Array<{ name: string; input_schema: Record<string, unknown> }>).find((entry) => entry.name.endsWith("export_batch"));
+ expect(tool).toBeDefined();
+ expect(tool!.input_schema.anyOf).toBeUndefined();
+ expect(tool!.input_schema.type).toBe("object");
+ expect(Object.keys(tool!.input_schema.properties as object).sort()).toEqual(["id", "name"]);
+ for (const entry of seen) expect(entry.headers[HEADER]).toBeUndefined();
+ }, 90_000);
+});
diff --git a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts
index d29f753d..30b1fab6 100644
--- a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts
@@ -123,3 +123,43 @@ describe("OmniRushAnthropicToolSchema fetch patch", () => {
expect(Object.keys(mod)).toEqual(["OmniRushAnthropicToolSchema"]);
});
});
+
+describe("tool schema transform on the 2.x engine's context hook", () => {
+ const anthropicModel = { id: "claude-sonnet-5", api: { npm: "@opencode/ai/providers/anthropic" } };
+ const openaiModel = { id: "gpt-6-astra", api: { npm: "@opencode/ai/providers/openai" } };
+
+ async function transform(model: unknown, tools: Record<string, { description: string; input: Record<string, unknown> }>) {
+ const hooks = (await OmniRushAnthropicToolSchema()) as unknown as Record<string, (input: unknown, output: unknown) => Promise<void>>;
+ await hooks["omnirush.tools.transform"]!({ model }, { tools });
+ return tools;
+ }
+
+ test("flattens a top-level anyOf for an Anthropic model, in place", async () => {
+ const tools = await transform(anthropicModel, {
+ export_batch: { description: "Export", input: structuredClone(topLevelAnyOf) },
+ plain: { description: "Plain", input: { type: "object", properties: { a: { type: "string" } } } },
+ });
+ expect(tools.export_batch!.input.anyOf).toBeUndefined();
+ expect(tools.export_batch!.input.type).toBe("object");
+ expect(Object.keys(tools.export_batch!.input.properties as object).sort()).toEqual(["file", "name", "url"]);
+ expect(tools.plain!.input).toEqual({ type: "object", properties: { a: { type: "string" } } });
+ });
+
+ test("flattens oneOf and allOf, and Messages-protocol and Claude models too", async () => {
+ for (const model of [{ id: "x", api: { npm: "@opencode/ai/providers/google-vertex/messages" } }, { id: "claude-4", api: { npm: "@opencode/ai/providers/amazon-bedrock" } }]) {
+ const tools = await transform(model, {
+ one: { description: "", input: { oneOf: [{ type: "object", properties: { a: { type: "string" } }, required: ["a"] }, { type: "object", properties: { b: { type: "number" } }, required: ["b"] }] } },
+ all: { description: "", input: { allOf: [{ type: "object", properties: { a: { type: "string" } }, required: ["a"] }, { type: "object", properties: { b: { type: "number" } }, required: ["b"] }] } },
+ });
+ expect(tools.one!.input.oneOf).toBeUndefined();
+ expect(tools.all!.input.allOf).toBeUndefined();
+ expect(tools.all!.input.required).toEqual(["a", "b"]);
+ }
+ });
+
+ test("leaves other providers' schemas unchanged", async () => {
+ const input = structuredClone(topLevelAnyOf);
+ const tools = await transform(openaiModel, { export_batch: { description: "Export", input } });
+ expect(tools.export_batch!.input).toEqual(topLevelAnyOf);
+ });
+});
diff --git a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts
index 98286cdf..be407aa9 100644
--- a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts
+++ b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts
@@ -119,9 +119,38 @@ function installAnthropicFetchPatch(): void {
globalThis.fetch = Object.assign(patched, base);
}
+/**
+ * Whether a model is served over the Anthropic Messages API: its AI SDK
+ * package (the catalog's `api.npm`) is an Anthropic or Messages-protocol one,
+ * or it is a Claude model.
+ */
+function speaksAnthropicMessages(model: unknown): boolean {
+ if (!isRecord(model)) return false;
+ const api = isRecord(model.api) ? model.api : {};
+ const npm = typeof api.npm === "string" ? api.npm : "";
+ const id = typeof model.id === "string" ? model.id : "";
+ return /anthropic|\/messages$/i.test(npm) || /claude/i.test(id);
+}
+
// Single export: the OpenCode plugin loader treats every export of a plugin
// module as a plugin factory, so helpers must stay module-private.
export const OmniRushAnthropicToolSchema = async () => {
+ // The 1.x engine sends model requests through the global fetch.
installAnthropicFetchPatch();
- return {};
+ return {
+ // The 2.x engine does not use the global fetch: the plugin bridge
+ // (omnirush-engine2.ts) calls this with the tool definitions of every
+ // model request before it is sent (the engine's session "context" hook).
+ "omnirush.tools.transform": async (
+ input: { model?: unknown },
+ output: { tools: Record<string, { input?: unknown }> },
+ ) => {
+ if (!speaksAnthropicMessages(input?.model) || !isRecord(output?.tools)) return;
+ for (const tool of Object.values(output.tools)) {
+ if (!isRecord(tool) || !isRecord(tool.input)) continue;
+ const flattened = flattenTopLevelCombinators(tool.input);
+ if (flattened !== tool.input) tool.input = flattened;
+ }
+ },
+ };
};
diff --git a/apps/server/src/opencode-plugins/omnirush-engine2.ts b/apps/server/src/opencode-plugins/omnirush-engine2.ts
index 8e380957..a28f77d8 100644
--- a/apps/server/src/opencode-plugins/omnirush-engine2.ts
+++ b/apps/server/src/opencode-plugins/omnirush-engine2.ts
@@ -385,6 +385,29 @@ export default {
});
}
+ // Hooks OmniRush plugins offer for the 2.x engine only (the 1.x engine has no counterpart):
+ // the real outgoing model request and its response, and each request's tool definitions.
+ const httpRequestHooks = hooks("omnirush.http.request");
+ const httpResponseHooks = hooks("omnirush.http.response");
+ if (httpRequestHooks.length) {
+ await ctx.session.hook("http.request", async (event: any) => {
+ for (const hook of httpRequestHooks) await hook(event, event);
+ });
+ }
+ if (httpResponseHooks.length) {
+ await ctx.session.hook("http.response", async (event: any) => {
+ for (const hook of httpResponseHooks) await hook(event, event);
+ });
+ }
+ const toolSchemaHooks = hooks("omnirush.tools.transform");
+ if (toolSchemaHooks.length) {
+ await ctx.session.hook("context", async (event: any) => {
+ if (!isRec(event.tools)) return;
+ const input = await hookInput(event);
+ for (const hook of toolSchemaHooks) await hook({ sessionID: input.sessionID, model: input.model }, { tools: event.tools });
+ });
+ }
+
const headerHooks = hooks("chat.headers");
if (headerHooks.length) {
await ctx.session.hook("model.request", async (event: any) => {
diff --git a/apps/server/src/opencode-plugins/omnirush-title-recovery.test.ts b/apps/server/src/opencode-plugins/omnirush-title-recovery.test.ts
new file mode 100644
index 00000000..1cb656d7
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-title-recovery.test.ts
@@ -0,0 +1,82 @@
+import { afterAll, describe, expect, test } from "bun:test";
+
+import { OmniRushTitleRecovery } from "./omnirush-title-recovery.js";
+
+/**
+ * The 2.x engine's side of title recovery: the plugin bridge hands the
+ * plugin the real outgoing request ("omnirush.http.request") and its response
+ * ("omnirush.http.response"). The private marker header never leaves, and an
+ * optional parameter the provider rejects is retried without it.
+ */
+
+const HEADER = "x-omnirush-title-attempt";
+const seen: Array<{ headers: Headers; body: Record<string, unknown> }> = [];
+const provider = Bun.serve({
+ port: 0,
+ async fetch(request) {
+ const body = (await request.json()) as Record<string, unknown>;
+ seen.push({ headers: request.headers, body });
+ if ("temperature" in body) {
+ return Response.json({ error: { code: "unsupported_parameter", param: "temperature", message: "temperature is not supported" } }, { status: 400 });
+ }
+ return Response.json({ ok: true });
+ },
+});
+afterAll(() => provider.stop(true));
+
+type Hooks = Record<string, (...args: any[]) => Promise<void>>;
+async function plugin(): Promise<{ hooks: Hooks; logs: Array<{ outcome: string; parameter?: string }> }> {
+ const logs: Array<{ outcome: string; parameter?: string }> = [];
+ const hooks = (await OmniRushTitleRecovery({
+ client: { app: { log: async (input) => { logs.push(input.body.extra); } } },
+ })) as unknown as Hooks;
+ return { hooks, logs };
+}
+
+/** What the engine does around one model request: headers from chat.headers, then the http hooks. */
+async function send(hooks: Hooks, agent: string, body: Record<string, unknown>): Promise<Response> {
+ const headers: Record<string, string> = { "content-type": "application/json", authorization: "Bearer k" };
+ await hooks["chat.headers"]!({ sessionID: "ses_1", agent, model: { id: "m", providerID: "p" } }, { headers });
+ const event = { request: new Request(`http://127.0.0.1:${provider.port}/v1/chat/completions`, { method: "POST", headers, body: JSON.stringify(body) }) } as { request: Request; response?: Response };
+ await hooks["omnirush.http.request"]!(event);
+ const response = await fetch(event.request);
+ const after = { request: event.request, response };
+ await hooks["omnirush.http.response"]!(after);
+ return after.response;
+}
+
+describe("title recovery on the 2.x engine's http hooks", () => {
+ test("the marker never reaches the provider; a rejected temperature is retried without it", async () => {
+ seen.length = 0;
+ const { hooks, logs } = await plugin();
+ const response = await send(hooks, "title", { model: "m", temperature: 0.5, messages: [] });
+ expect(response.status).toBe(200);
+ expect(seen.length).toBe(2);
+ for (const request of seen) expect(request.headers.get(HEADER)).toBeNull();
+ expect(seen[0]!.headers.get("authorization")).toBe("Bearer k");
+ expect("temperature" in seen[0]!.body).toBe(true);
+ expect("temperature" in seen[1]!.body).toBe(false);
+ expect(seen[1]!.headers.get("authorization")).toBe("Bearer k");
+ expect(logs.map((log) => log.outcome)).toEqual(["started", "request_rejected", "retrying_parameter", "accepted_after_recovery"]);
+ expect(logs[2]!.parameter).toBe("temperature");
+ });
+
+ test("an accepted title request goes out once, without the marker", async () => {
+ seen.length = 0;
+ const { hooks, logs } = await plugin();
+ const response = await send(hooks, "title", { model: "m", messages: [] });
+ expect(response.status).toBe(200);
+ expect(seen.length).toBe(1);
+ expect(seen[0]!.headers.get(HEADER)).toBeNull();
+ expect(logs.map((log) => log.outcome)).toEqual(["started", "accepted"]);
+ });
+
+ test("other agents' requests are left alone (no retry, no rewrite)", async () => {
+ seen.length = 0;
+ const { hooks } = await plugin();
+ const response = await send(hooks, "build", { model: "m", temperature: 0.5, messages: [] });
+ expect(response.status).toBe(400);
+ expect(seen.length).toBe(1);
+ expect(seen[0]!.headers.get(HEADER)).toBeNull();
+ });
+});
diff --git a/apps/server/src/opencode-plugins/omnirush-title-recovery.ts b/apps/server/src/opencode-plugins/omnirush-title-recovery.ts
index 6d9bd2b7..b32e3d9d 100644
--- a/apps/server/src/opencode-plugins/omnirush-title-recovery.ts
+++ b/apps/server/src/opencode-plugins/omnirush-title-recovery.ts
@@ -159,7 +159,58 @@ export const OmniRushTitleRecovery = async (input: {
service: "omnirush.title", level, message: "Automatic title generation", extra: diagnostic,
} }).catch(() => undefined);
};
+ /** Requests the 2.x hooks stripped the marker from: the marker and the body as sent. */
+ const sent = new WeakMap<Request, { id: string; body: string | undefined }>();
return {
+ // The 2.x engine does not use the global fetch: the plugin bridge
+ // (omnirush-engine2.ts) hands these the real outgoing request and its
+ // response (the engine's session "http.request" / "http.response" hooks).
+ // The marker never reaches a provider, and a rejected optional title
+ // parameter is retried without it, as the fetch patch does for 1.x.
+ "omnirush.http.request": async (event: { request: Request }) => {
+ const request = event?.request;
+ const id = request?.headers.get(HEADER);
+ if (!request || !id) return;
+ const headers = new Headers(request.headers);
+ headers.delete(HEADER);
+ const body = request.body ? await request.clone().text() : undefined;
+ const next = new Request(request.url, { method: request.method, headers, body, signal: request.signal });
+ sent.set(next, { id, body });
+ event.request = next;
+ },
+ "omnirush.http.response": async (event: { request: Request; response: Response }) => {
+ const entry = event?.request ? sent.get(event.request) : undefined;
+ if (!entry) return;
+ sent.delete(event.request);
+ const attempt = attempts.get(entry.id);
+ if (!attempt) return;
+ const response = event.response;
+ if (response.ok) {
+ report(attempt, "accepted", response.status);
+ return;
+ }
+ report(attempt, failure(response.status), response.status);
+ if (attempt.retried || response.status !== 400 || entry.body === undefined) return;
+ const recovered = correction(entry.body, await errorBody(response));
+ if (!recovered || attempts.get(entry.id) !== attempt || event.request.signal.aborted) return;
+ attempt.retried = true;
+ report(attempt, "retrying_parameter", response.status, recovered.parameter);
+ const headers = new Headers(event.request.headers);
+ headers.delete("content-length");
+ try {
+ const retry = await globalThis.fetch(event.request.url, {
+ method: event.request.method,
+ headers,
+ body: recovered.body,
+ signal: AbortSignal.any([event.request.signal, AbortSignal.timeout(DEADLINE_MS)]),
+ });
+ report(attempt, retry.ok ? "accepted_after_recovery" : failure(retry.status), retry.status);
+ void response.body?.cancel().catch(() => undefined);
+ event.response = retry;
+ } catch {
+ report(attempt, event.request.signal.aborted ? "cancelled" : "transport_failed");
+ }
+ },
"chat.headers": async (request: {
sessionID: string; agent: string; model: { id: string; providerID: string };
}, output: { headers: Record<string, string> }) => {