Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

feat(advisor): build advisor requests from the connection's wire

Jack Rudenko9baf6421a449
diff --git a/packages/cli/src/advisor-startup.test.ts b/packages/cli/src/advisor-startup.test.ts
index 1e5153c7..3e50f0b0 100644
--- a/packages/cli/src/advisor-startup.test.ts
+++ b/packages/cli/src/advisor-startup.test.ts
@@ -35,6 +35,7 @@ function config(overrides: Partial<ClaudishConfig> = {}): ClaudishConfig {
const openAiRoute: AdvisorRoute = {
kind: "openai",
+ api: "chat-completions",
host: "api.openai.com",
url: "https://api.openai.com/v1/chat/completions",
credential: "openai",
@@ -43,6 +44,7 @@ const openAiRoute: AdvisorRoute = {
const googleRoute: AdvisorRoute = {
kind: "google",
+ api: "chat-completions",
host: "generativelanguage.googleapis.com",
url: "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
credential: "google",
@@ -51,6 +53,7 @@ const googleRoute: AdvisorRoute = {
const anthropicRoute: AdvisorRoute = {
kind: "anthropic",
+ api: "anthropic-messages",
host: "api.anthropic.com",
url: "https://api.anthropic.com/v1/messages",
credential: "anthropic",
diff --git a/packages/cli/src/handlers/advisor-routing-and-state.test.ts b/packages/cli/src/handlers/advisor-routing-and-state.test.ts
index 6c8e83a3..d0e05ef5 100644
--- a/packages/cli/src/handlers/advisor-routing-and-state.test.ts
+++ b/packages/cli/src/handlers/advisor-routing-and-state.test.ts
@@ -247,55 +247,7 @@ describe("OpenRouter advisor wire-model resolution", () => {
});
});
-describe("advisor request token parameter routing", () => {
- // resolveConnection inside the advisor has no cache-path argument. Import it
- // in an isolated child so its default path cannot reach the user's cache.
- async function captureRequest(
- model: string,
- cache?: DiskCacheV3
- ): Promise<{ url: URL; body: Record<string, unknown> }> {
- const dir = mkdtempSync(join(tmpdir(), "advisor-wire-"));
- try {
- if (cache) {
- mkdirSync(join(dir, ".claudish"));
- writeFileSync(
- join(dir, ".claudish", "cloud-models-catalog-v3.json"),
- JSON.stringify(cache)
- );
- }
- const script = `
- const { runAdvisorCall } = await import(${JSON.stringify(new URL("./native-handler-advisor.ts", import.meta.url).pathname)});
- let captured;
- globalThis.fetch = async (input, init) => {
- captured = { url: String(input), body: JSON.parse(String(init.body)) };
- return Response.json({ choices: [{ message: { content: "ok" } }] });
- };
- await runAdvisorCall({ toolUseId: "advisor-wire-test", messages: [{role: "user", content: "Review this fixture."}],
- models: [${JSON.stringify(model)}], collector: null,
- apiKeys: {openai: "test-key", google: "test-key", openrouter: "test-key"},
- fetchImpl: globalThis.fetch, warn: () => {} });
- if (!captured) throw new Error("Advisor issued no request");
- console.log(JSON.stringify(captured));
- `;
- const child = Bun.spawnSync([process.execPath, "--eval", script], {
- env: {
- PATH: process.env.PATH,
- HOME: dir,
- CLAUDISH_DISABLE_KEYCHAIN: "1",
- CLAUDISH_DISABLE_OP: "1",
- CLAUDISH_DISABLE_CATALOG_WARM: "1",
- },
- stdout: "pipe",
- stderr: "pipe",
- });
- expect(child.exitCode, child.stderr.toString()).toBe(0);
- const captured = JSON.parse(child.stdout.toString());
- return { url: new URL(captured.url), body: captured.body };
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- }
-
+describe("advisor request wire routing", () => {
const fixture: DiskCacheV3 = JSON.parse(
readFileSync(
new URL(
@@ -305,75 +257,140 @@ describe("advisor request token parameter routing", () => {
"utf8"
)
);
- it.each(["max_tokens", "max_completion_tokens"] as const)(
- "reads %s from the OpenAI chat connection",
- async (tokenParam) => {
- const cache = structuredClone(fixture);
- const entry = cache.entries.find((entry) => entry.modelId === "gpt-6.1-sol")!;
- const connection = entry.aggregators!.find(
- (connection) =>
- connection.route?.routeId === "openai" && connection.route.routeProfileId === "direct-api"
- )!;
- if (connection.wire?.status !== "known") throw new Error("missing fixture wire");
- // Change only the API and limit field of a real connection to exercise a
- // chat wire; this fixture's OpenAI connections currently all use Responses.
- connection.wire.api = "chat-completions";
- connection.wire.tokenParam = tokenParam;
- const request = await captureRequest("[email protected]", cache);
- expect(request.body).toHaveProperty(tokenParam);
- expect(request.body).not.toHaveProperty(
- tokenParam === "max_tokens" ? "max_completion_tokens" : "max_tokens"
+ function capture(
+ models: string[],
+ collector: string | null = null,
+ cache: DiskCacheV3 | null = fixture
+ ) {
+ const home = mkdtempSync(join(tmpdir(), "advisor-wire-"));
+ try {
+ if (cache) {
+ mkdirSync(join(home, ".claudish"));
+ writeFileSync(join(home, ".claudish/cloud-models-catalog-v3.json"), JSON.stringify(cache));
+ }
+ const child = Bun.spawnSync(
+ [
+ process.execPath,
+ "--eval",
+ `
+ const { advisorRouteFor, runAdvisorCall } = await import(${JSON.stringify(new URL("./native-handler-advisor.ts", import.meta.url).pathname)});
+ const models = ${JSON.stringify(models)}, collector = ${JSON.stringify(collector)};
+ const routes = models.map(m => advisorRouteFor(m, "panel"));
+ if (collector) routes.push(advisorRouteFor(collector, "collector"));
+ const calls = [];
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url, init) => {
+ calls.push({ url: String(url), method: init.method, headers: Object.fromEntries(new Headers(init.headers)), body: JSON.parse(init.body) });
+ if (String(url).endsWith("/responses")) return Response.json({ output: [{ type: "reasoning", summary: [] }, { type: "message", content: [{ type: "output_text", text: "Responses advice" }] }] });
+ if (String(url).includes(":generateContent")) return Response.json({ candidates: [{ content: { parts: [{ text: "Gemini advice" }] } }] });
+ if (String(url).endsWith("/messages")) return Response.json({ content: [{type: "text", text: "Messages synthesis"}] });
+ return Response.json({ choices: [{ message: { content: "Chat advice" } }] });
+ };
+ try {
+ const outcome = await runAdvisorCall({ toolUseId: "wire-advisor", messages: [{role: "user", content: "Review this design"}], models, collector,
+ apiKeys: { openai: "openai-fake", google: "google-fake", openrouter: "openrouter-fake", anthropic: "anthropic-fake" }, fetchImpl: globalThis.fetch, warn: () => {} });
+ console.log(JSON.stringify({ routes, calls, outcome }));
+ } finally { globalThis.fetch = originalFetch; }
+ `,
+ ],
+ {
+ env: {
+ PATH: process.env.PATH,
+ HOME: home,
+ CLAUDISH_DISABLE_CATALOG_WARM: "1",
+ CLAUDISH_DISABLE_KEYCHAIN: "1",
+ CLAUDISH_DISABLE_OP: "1",
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ }
);
- expect(request.body).not.toHaveProperty("max_output_tokens");
+ expect(child.exitCode, child.stderr.toString()).toBe(0);
+ return JSON.parse(child.stdout.toString());
+ } finally {
+ rmSync(home, { recursive: true, force: true });
}
- );
-
- it("does not copy the Responses token field into advisor Chat Completions", async () => {
- const request = await captureRequest("[email protected]", fixture);
- expect(request.body).toHaveProperty("max_completion_tokens");
- expect(request.body).not.toHaveProperty("max_output_tokens");
+ }
+ it("OpenAI panel follows Responses wire and extracts output_text", () => {
+ const { routes, calls, outcome } = capture(["[email protected]"]);
+ expect(routes[0]).toMatchObject({
+ api: "responses",
+ url: "https://api.openai.com/v1/responses",
+ wire: { status: "known" },
+ });
+ const wire = routes[0].wire;
+ const effort = wire.reasoning.effort;
+ expect(typeof effort.default).toBe("string");
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({
+ method: "POST",
+ url: routes[0].url,
+ headers: { authorization: "Bearer openai-fake" },
+ body: {
+ stream: false,
+ max_output_tokens: 2048,
+ reasoning: { effort: effort.values[effort.default] },
+ },
+ });
+ expect(calls[0].body.instructions).toBeString();
+ expect(calls[0].body.input).toContainEqual({ role: "user", content: "Review this design" });
+ expect(calls[0].body).not.toHaveProperty("messages");
+ expect(calls[0].body).not.toHaveProperty("max_tokens");
+ expect(outcome.result).toEqual({ text: "Responses advice", isError: false });
});
-
- it.each(["max_output_tokens", { status: "unknown" }, { status: "not_applicable" }] as const)(
- "uses the chat default for token field %j",
- async (tokenParam) => {
- const cache = structuredClone(fixture);
- const entry = cache.entries.find((entry) => entry.modelId === "gpt-6.1-sol")!;
- const connection = entry.aggregators!.find(
- (connection) =>
- connection.route?.routeId === "openai" && connection.route.routeProfileId === "direct-api"
- )!;
- if (connection.wire?.status !== "known") throw new Error("missing fixture wire");
- connection.wire.api = "chat-completions";
- connection.wire.tokenParam = tokenParam;
- const request = await captureRequest("[email protected]", cache);
- expect(request.body).toHaveProperty("max_completion_tokens");
- expect(request.body).not.toHaveProperty("max_tokens");
- expect(request.body).not.toHaveProperty("max_output_tokens");
- }
- );
-
- it("uses max_completion_tokens on the direct OpenAI route", async () => {
- const request = await captureRequest("openai@some-model");
-
- expect(request.url.host).toBe("api.openai.com");
- expect(request.body).toHaveProperty("max_completion_tokens");
- expect(request.body).not.toHaveProperty("max_tokens");
+ it("Google panel follows native Gemini wire and extracts candidate text", () => {
+ const { routes, calls, outcome } = capture(["[email protected]"]);
+ expect(routes[0]).toMatchObject({
+ api: "gemini",
+ url: "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent",
+ wire: { status: "known" },
+ });
+ expect(calls[0]).toMatchObject({
+ url: routes[0].url,
+ headers: { "x-goog-api-key": "google-fake" },
+ body: { generationConfig: { maxOutputTokens: 2048 } },
+ });
+ expect(calls[0].body.systemInstruction.parts[0].text).toBeString();
+ expect(calls[0].body.contents).toContainEqual({
+ role: "user",
+ parts: [{ text: "Review this design" }],
+ });
+ expect(calls[0].body).not.toHaveProperty("messages");
+ expect(outcome.result).toEqual({ text: "Gemini advice", isError: false });
});
-
- it("uses max_tokens on the OpenRouter route", async () => {
- const request = await captureRequest("openrouter@acme/some-model");
-
- expect(request.url.host).toBe("openrouter.ai");
- expect(request.body).toHaveProperty("max_tokens");
- expect(request.body).not.toHaveProperty("max_completion_tokens");
+ it("Anthropic collector uses Messages body, required limit and credential headers", () => {
+ const { routes, calls, outcome } = capture(
+ "anthropic@claude-opus-5-5"
+ );
+ expect(routes[2]).toMatchObject({
+ api: "anthropic-messages",
+ url: "https://api.anthropic.com/v1/messages",
+ });
+ expect(calls).toHaveLength(3);
+ expect(calls[2]).toMatchObject({
+ url: routes[2].url,
+ headers: { "x-api-key": "anthropic-fake", "anthropic-version": "2023-06-01" },
+ body: { model: "claude-opus-5-5", max_tokens: 2048 },
+ });
+ expect(calls[2].body.system).toBeString();
+ expect(calls[2].body.messages[0].content).toContain("Responses advice");
+ expect(calls[2].body.messages[0].content).toContain("Gemini advice");
+ expect(outcome.result).toEqual({ text: "Messages synthesis", isError: false });
});
-
- it("uses max_tokens on the direct Google route", async () => {
- const request = await captureRequest("google@gemini-fixture");
-
- expect(request.url.host).toBe("generativelanguage.googleapis.com");
- expect(request.body).toHaveProperty("max_tokens");
- expect(request.body).not.toHaveProperty("max_completion_tokens");
+ it.each([
+ ["openai@unpublished", "https://api.openai.com/v1/chat/completions"],
+ [
+ "google@unpublished",
+ "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
+ ],
+ ["openrouter@acme/unpublished", "https://openrouter.ai/api/v1/chat/completions"],
+ ])("cold catalog uses documented chat endpoint for %s", (model, url) => {
+ const { routes, calls, outcome } = capture([model!], null, null);
+ expect(routes[0]).toMatchObject({ api: "chat-completions", url });
+ expect(routes[0]).not.toHaveProperty("wire");
+ expect(calls[0].body.messages).toBeArray();
+ expect(calls[0].body).not.toHaveProperty("input");
+ expect(outcome.result).toEqual({ text: "Chat advice", isError: false });
});
});
diff --git a/packages/cli/src/handlers/native-handler-advisor.ts b/packages/cli/src/handlers/native-handler-advisor.ts
index f65f0473..5bad9527 100644
--- a/packages/cli/src/handlers/native-handler-advisor.ts
+++ b/packages/cli/src/handlers/native-handler-advisor.ts
@@ -40,8 +40,10 @@ import { getAlwaysOnLogPath, getLogFilePath, log, logStderr } from "../logger.js
import { type SlimModelEntry, readAllModelsCache } from "../providers/all-models-cache.js";
import { getCatalogEntries, latestAnthropicTierModelId } from "../providers/catalog-client.js";
import { findEntryByAlias } from "../providers/catalog-query.js";
-import { resolveConnection } from "../providers/connection-resolver.js";
+import { resolveConnection, resolveRouteProfile } from "../providers/connection-resolver.js";
+import { type KnownWire, type WireApi, wireRequestUrl } from "../providers/connection-wire.js";
import { parseModelSpec } from "../providers/model-parser.js";
+import { mergeWireHeaders, shapeRequestFromWire } from "../providers/wire-request.js";
import { extractProviderMessage, extractUpstreamStatus } from "./shared/anthropic-error.js";
const ADVISOR_SERVER_TOOL_TYPE = "advisor_20260301";
@@ -1509,6 +1511,13 @@ export interface AdvisorRoute {
credential: AdvisorRouteKind;
/** The model id placed in the request body, after catalog resolution. */
wireModel: string;
+ /**
+ * The API this request is built for: the connection's `wire.api` (catalog
+ * 3.7.0), or the profile's Chat Completions when the wire is not known.
+ */
+ api: WireApi;
+ /** The connection's known wire, when the catalog publishes one. */
+ wire?: KnownWire;
/**
* Set to the ALIAS when `wireModel` is one the live catalog could not resolve
* to an id the endpoint accepts — `haiku` with a cold catalog. Such a route
@@ -1519,16 +1528,59 @@ export interface AdvisorRoute {
unresolvedAlias?: string;
}
-const ADVISOR_ENDPOINTS: Readonly<Record<AdvisorRouteKind, string>> = Object.freeze({
+/**
+ * The provider documentation's endpoints, used ONLY when no route registry is
+ * cached (a cold catalog): every other request takes its URL from the
+ * connection's registry profile, like any claudish request.
+ */
+const ADVISOR_COLD_CATALOG_ENDPOINTS: Readonly<Record<AdvisorRouteKind, string>> = Object.freeze({
google: "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
openai: "https://api.openai.com/v1/chat/completions",
openrouter: "https://openrouter.ai/api/v1/chat/completions",
anthropic: "https://api.anthropic.com/v1/messages",
});
+/** The claudish provider whose catalog connection an advisor route uses. */
+const ADVISOR_CATALOG_PROVIDER: Readonly<Record<AdvisorRouteKind, string>> = Object.freeze({
+ google: "google",
+ openai: "openai",
+ openrouter: "openrouter",
+ anthropic: "anthropic",
+});
+
function routeOf(kind: AdvisorRouteKind, wireModel: string): AdvisorRoute {
- const url = ADVISOR_ENDPOINTS[kind];
- return { kind, host: new URL(url).host, url, credential: kind, wireModel };
+ const provider = ADVISOR_CATALOG_PROVIDER[kind];
+ const resolution = resolveConnection(provider, wireModel);
+ let api: WireApi | undefined;
+ let wire: KnownWire | undefined;
+ let baseUrl: string | undefined;
+ if (resolution.ok && resolution.connection.wire.status === "known") {
+ wire = resolution.connection.wire;
+ api = wire.api;
+ baseUrl = resolution.connection.profile.apis[api]?.baseUrl;
+ } else {
+ // Not published for this provider, or its wire unknown: the profile's
+ // Chat Completions (Messages for Anthropic), with nothing else sent.
+ const profile = resolveRouteProfile(provider)?.profile;
+ api = kind === "anthropic" ? "anthropic-messages" : "chat-completions";
+ baseUrl = profile?.apis[api]?.baseUrl;
+ }
+ const url = baseUrl
+ ? wireRequestUrl(baseUrl, api, wireModel, false)
+ : ADVISOR_COLD_CATALOG_ENDPOINTS[kind];
+ if (!baseUrl) {
+ api = kind === "anthropic" ? "anthropic-messages" : "chat-completions";
+ log(`[Advisor] no route registry for ${provider}; using the documented endpoint ${url}`);
+ }
+ return {
+ kind,
+ host: new URL(url).host,
+ url,
+ credential: kind,
+ wireModel,
+ api,
+ ...(wire ? { wire } : {}),
+ };
}
/**
@@ -1871,66 +1923,83 @@ export async function resolveAdvisorCredential(
const ADVISOR_MAX_OUTPUT_TOKENS = 2048;
/**
- * The output-token parameter THIS ROUTE accepts, and the budget to put in it.
- *
- * Per ROUTE, because the parameter belongs to the endpoint, not to the model:
- *
- * - `openrouter` and `google` keep `max_tokens`. Both normalise it for every
- * model they serve, and run D proves it live (deepseek-v4-pro, HTTP 200).
- * - `openai` (api.openai.com) reads the `openai/direct-api` connection's
- * `wire.tokenParam`, when that wire is Chat Completions. A Responses wire's
- * field (`max_output_tokens`) is never a chat field: the advisor always POSTs
- * `/v1/chat/completions`, so there it becomes `max_completion_tokens` — the
- * spelling OpenAI's own 400 asked for:
- * "Unsupported parameter: 'max_tokens' is not supported with this model.
- * Use 'max_completion_tokens' instead."
- * (observed twice for gpt-5.6-sol, runs phase7b-B and phase7b-C).
- *
- * An unknown model on the openai route defaults to `max_completion_tokens`,
- * the current chat-completions spelling; `max_tokens` is the deprecated one and
- * is precisely what the newer models reject.
- */
-function advisorTokenParamFor(route: AdvisorRoute): string {
- if (route.kind !== "openai") return "max_tokens";
- // The connection's own wire, and only when that wire is Chat Completions —
- // the API this request uses. Since catalog 3.7.0 the model-level
- // `tokenParam` describes the owner's direct connection, which for a
- // Responses model is `max_output_tokens`: not a chat field at all.
- const resolution = resolveConnection("openai", route.wireModel);
- const wire = resolution.ok ? resolution.connection.wire : undefined;
- if (wire?.status === "known" && wire.api === "chat-completions") {
- if (wire.tokenParam === "max_tokens" || wire.tokenParam === "max_completion_tokens") {
- return wire.tokenParam;
- }
- }
- return "max_completion_tokens";
-}
-
-/** Builds an OpenAI chat-completions request for a non-Anthropic route. */
+ * One advisor or collector request, built for the route's API and shaped by
+ * its connection's wire — the same step a session request takes (output-limit
+ * field, reasoning encoding), so the advisor never sends a field the catalog
+ * did not publish for that connection. Without a known wire, no output limit
+ * and no reasoning field is sent.
+ */
function buildAdvisorRequest(
route: AdvisorRoute,
messages: any[],
apiKeys: AdvisorApiKeys,
- systemPrompt: string = ADVISOR_SYSTEM_PROMPT
-): { headers: Record<string, string>; body: any } {
- if (route.kind === "anthropic") {
- // The Messages API has its own request shape; only the collector uses it.
- throw new Error(`${route.wireModel}: the Anthropic route is collector-only`);
- }
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- Authorization: `Bearer ${apiKeys[route.credential] ?? ""}`,
- };
+ systemPrompt: string = ADVISOR_SYSTEM_PROMPT,
+ userText?: string
+): { headers: Record<string, string>; body: any; extractText: (data: any) => string | undefined } {
+ const key = apiKeys[route.credential] ?? "";
+ const headers: Record<string, string> = { "Content-Type": "application/json" };
if (route.kind === "openrouter") {
headers["HTTP-Referer"] = "https://claudish.com";
headers["X-Title"] = "Claudish Advisor";
}
- const body: Record<string, unknown> = {
- model: route.wireModel,
- messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAIMessages(messages)],
- };
- body[advisorTokenParamFor(route)] = ADVISOR_MAX_OUTPUT_TOKENS;
- return { headers, body };
+ const turns: Array<{ role: string; content: string }> =
+ userText !== undefined
+ ? [{ role: "user", content: userText }]
+ : convertToOpenAIMessages(messages).map((m: any) => ({
+ role: m.role,
+ content: typeof m.content === "string" ? m.content : extractBlocksAsText(m.content),
+ }));
+
+ let body: Record<string, unknown>;
+ let extractText: (data: any) => string | undefined;
+ switch (route.api) {
+ case "anthropic-messages":
+ headers["x-api-key"] = key;
+ headers["anthropic-version"] = "2023-06-01";
+ // The Messages API REQUIRES `max_tokens` (it is the protocol's only limit
+ // field); a known wire writes the same field again below.
+ body = {
+ model: route.wireModel,
+ system: systemPrompt,
+ messages: turns,
+ max_tokens: ADVISOR_MAX_OUTPUT_TOKENS,
+ };
+ extractText = extractAnthropicText;
+ break;
+ case "responses":
+ headers.Authorization = `Bearer ${key}`;
+ body = { model: route.wireModel, instructions: systemPrompt, input: turns, stream: false };
+ extractText = extractResponsesText;
+ break;
+ case "gemini":
+ headers["x-goog-api-key"] = key;
+ body = {
+ systemInstruction: { parts: [{ text: systemPrompt }] },
+ contents: turns.map((t) => ({
+ role: t.role === "assistant" ? "model" : "user",
+ parts: [{ text: t.content }],
+ })),
+ generationConfig: { maxOutputTokens: ADVISOR_MAX_OUTPUT_TOKENS },
+ };
+ extractText = extractGeminiText;
+ break;
+ default:
+ headers.Authorization = `Bearer ${key}`;
+ body = {
+ model: route.wireModel,
+ messages: [{ role: "system", content: systemPrompt }, ...turns],
+ };
+ extractText = extractChatCompletionText;
+ }
+
+ if (route.wire) {
+ const shaped = shapeRequestFromWire(body, route.wire, {
+ maxTokens: ADVISOR_MAX_OUTPUT_TOKENS,
+ hasTools: false,
+ });
+ mergeWireHeaders(headers, shaped.headers);
+ }
+ return { headers, body, extractText };
}
/**
@@ -2183,6 +2252,27 @@ function extractChatCompletionText(data: any): string | undefined {
return undefined;
}
+/** Advice text from a Responses body: its output_text parts, joined. */
+function extractResponsesText(data: any): string | undefined {
+ if (typeof data?.output_text === "string" && data.output_text) return data.output_text;
+ const parts = (Array.isArray(data?.output) ? data.output : [])
+ .flatMap((item: any) => (Array.isArray(item?.content) ? item.content : []))
+ .filter((c: any) => c?.type === "output_text" && typeof c.text === "string")
+ .map((c: any) => c.text);
+ return parts.length > 0 ? parts.join("") : undefined;
+}
+
+/** Advice text from a Gemini generateContent body: its first candidate's text parts. */
+function extractGeminiText(data: any): string | undefined {
+ const parts = data?.candidates?.[0]?.content?.parts;
+ if (!Array.isArray(parts)) return undefined;
+ const text = parts
+ .filter((p: any) => typeof p?.text === "string" && !p.thought)
+ .map((p: any) => p.text)
+ .join("");
+ return text || undefined;
+}
+
/** Advice text from an Anthropic messages body: its first text block. */
function extractAnthropicText(data: any): string | undefined {
const blocks = data?.content;
@@ -2204,7 +2294,7 @@ async function callAdvisorModel(
let plan: AdvisorFetchPlan;
try {
const route = advisorRouteFor(modelSpec, "panel");
- const { headers, body } = buildAdvisorRequest(route, messages, apiKeys);
+ const { headers, body, extractText } = buildAdvisorRequest(route, messages, apiKeys);
plan = {
role: "panel",
requestedModel: modelSpec,
@@ -2212,7 +2302,7 @@ async function callAdvisorModel(
headers,
body,
timeoutMs: ADVISOR_PANEL_TIMEOUT_MS,
- extractText: extractChatCompletionText,
+ extractText,
emptyStubPath: ADVISOR_STUB_PATHS.PANEL_EMPTY,
errorStubPath: ADVISOR_STUB_PATHS.PANEL_ERROR,
};
@@ -2251,34 +2341,6 @@ function isAnthropicModel(parsed: ReturnType<typeof parseModelSpec>): boolean {
);
}
-function planAnthropicCollector(
- requestedModel: string,
- route: AdvisorRoute,
- adviceText: string,
- apiKey?: string
-): AdvisorFetchPlan {
- return {
- role: "collector",
- requestedModel,
- route,
- headers: {
- "Content-Type": "application/json",
- "x-api-key": apiKey ?? "",
- "anthropic-version": "2023-06-01",
- },
- body: {
- model: route.wireModel,
- max_tokens: 1024,
- system: COLLECTOR_SYSTEM_PROMPT,
- messages: [{ role: "user", content: adviceText }],
- },
- timeoutMs: ADVISOR_COLLECTOR_TIMEOUT_MS,
- extractText: extractAnthropicText,
- emptyStubPath: ADVISOR_STUB_PATHS.ANTHROPIC_COLLECTOR_EMPTY,
- errorStubPath: ADVISOR_STUB_PATHS.COLLECTOR_FAILED,
- };
-}
-
async function callCollectorModel(
collectorSpec: string,
advice: Array<{ model: string; text: string }>,
@@ -2306,28 +2368,27 @@ async function callCollectorModel(
);
}
- if (route.kind === "anthropic") {
- plan = planAnthropicCollector(collectorSpec, route, adviceText, apiKeys.anthropic);
- } else {
- // External collector via OpenRouter/Google/OpenAI
- const { headers, body } = buildAdvisorRequest(route, [], apiKeys, COLLECTOR_SYSTEM_PROMPT);
- // Override messages since buildAdvisorRequest would try to convert
- body.messages = [
- { role: "system", content: COLLECTOR_SYSTEM_PROMPT },
- { role: "user", content: adviceText },
- ];
- plan = {
- role: "collector",
- requestedModel: collectorSpec,
- route,
- headers,
- body,
- timeoutMs: ADVISOR_COLLECTOR_TIMEOUT_MS,
- extractText: extractChatCompletionText,
- emptyStubPath: ADVISOR_STUB_PATHS.COLLECTOR_EMPTY,
- errorStubPath: ADVISOR_STUB_PATHS.COLLECTOR_FAILED,
- };
- }
+ const { headers, body, extractText } = buildAdvisorRequest(
+ route,
+ [],
+ apiKeys,
+ COLLECTOR_SYSTEM_PROMPT,
+ adviceText
+ );
+ plan = {
+ role: "collector",
+ requestedModel: collectorSpec,
+ route,
+ headers,
+ body,
+ timeoutMs: ADVISOR_COLLECTOR_TIMEOUT_MS,
+ extractText,
+ emptyStubPath:
+ route.kind === "anthropic"
+ ? ADVISOR_STUB_PATHS.ANTHROPIC_COLLECTOR_EMPTY
+ : ADVISOR_STUB_PATHS.COLLECTOR_EMPTY,
+ errorStubPath: ADVISOR_STUB_PATHS.COLLECTOR_FAILED,
+ };
} catch (err) {
const base = {
role: "collector" as const,