Skip to content

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

feat(advisor): add an in-process panel gateway to createProxyServer

Jack Rudenko7c1f31f3919e
diff --git a/packages/cli/src/handlers/advisor-panel-gateway.ts b/packages/cli/src/handlers/advisor-panel-gateway.ts
new file mode 100644
index 00000000..97d30c9e
--- /dev/null
+++ b/packages/cli/src/handlers/advisor-panel-gateway.ts
@@ -0,0 +1,198 @@
+/**
+ * The advisor panel gateway: one in-process request per routed panel or
+ * collector call, through the chain startup built for it.
+ *
+ * A facade of two functions over Context building, chain lookup, the call's
+ * deadline, its signing lease, redaction and hop attribution:
+ *
+ * - `plan(spec, role)` reads the startup plan map only. There is no lazy
+ * planning: a spec the map lacks is a refused plan ("advisor runtime not
+ * planned for this launch").
+ * - `call(req)` never rejects. It POSTs the payload to a never-served Hono app
+ * whose one route installs the call's abort signal, hop log and signing
+ * secrets on a real `Context` and hands it to the startup-built chain. The
+ * app is never passed to `Bun.serve` and never goes through the session's
+ * `resolveHandlerForRequest`, so the monitor branch, the serve slot map and
+ * the `--model` remap cannot touch a panel call, and no advisor wrapper is
+ * ever applied (no recursion).
+ *
+ * The synthetic request carries NO auth header, and `ComposedHandler` forwards
+ * no inbound `authorization`, so Claude Code's bearer cannot reach a panel hop.
+ * `x-claudish-no-recovery: advisor` skips the tier-1 hold ladder: a 60 s budget
+ * cannot use a multi-minute hold.
+ */
+
+import { type Context, Hono } from "hono";
+import { log } from "../logger.js";
+import { redactExactValues, redactForClient } from "../redact.js";
+import {
+ type AdvisorChainBuild,
+ type AdvisorModelPlan,
+ type AdvisorPanelCall,
+ type AdvisorPanelGateway,
+ type AdvisorPanelResult,
+ type AdvisorRole,
+ advisorChainKey,
+ planHopForTransport,
+} from "./advisor-route-plan.js";
+import { wrapAnthropicError } from "./shared/anthropic-error.js";
+import {
+ CALL_ABORT_SIGNAL_KEY,
+ HOP_LOG_KEY,
+ type HopAttempt,
+ SIGNING_SECRETS_KEY,
+ type SigningSecrets,
+ createSigningSecrets,
+} from "./shared/call-context.js";
+import { isStreamFailureResponse } from "./shared/recovery-marker.js";
+import type { ModelHandler } from "./types.js";
+
+/** What startup hands the proxy: every member's plan and every routed member's built chain. */
+export interface AdvisorRuntime {
+ /** Keyed `"<role>:<spec>"` (`advisorChainKey`). */
+ plans: ReadonlyMap<string, AdvisorModelPlan>;
+ chains: ReadonlyMap<string, AdvisorChainBuild>;
+}
+
+/** The URL of the synthetic request. Never resolved: the app is called in process. */
+const ADVISOR_INTERNAL_URL = "http://claudish.advisor.internal/v1/messages";
+
+interface PendingCall {
+ handler: ModelHandler;
+ signal: AbortSignal;
+ hops: HopAttempt[];
+ secrets: SigningSecrets;
+}
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+/** The answer the app gives for a call it cannot run or a handler that threw. */
+function proxyErrorResponse(c: Context, message: string): Response {
+ return c.json(wrapAnthropicError(500, redactForClient(`Proxy error: ${message}`)), 500);
+}
+
+export function createAdvisorPanelGateway(runtime: AdvisorRuntime): AdvisorPanelGateway {
+ const pendingCalls = new WeakMap<Request, PendingCall>();
+ const app = new Hono();
+
+ app.onError((err, c) => {
+ log(`[advisor] panel gateway error: ${errorMessage(err)}`);
+ return proxyErrorResponse(c, errorMessage(err));
+ });
+
+ app.post("/v1/messages", async (c) => {
+ // Hono keeps the Request's identity, so the entry `call()` registered is
+ // found by the very object it passed to `app.fetch`.
+ const entry = pendingCalls.get(c.req.raw);
+ if (!entry)
+ return proxyErrorResponse(c, "advisor gateway: no call registered for this request");
+ c.set(CALL_ABORT_SIGNAL_KEY, entry.signal);
+ c.set(HOP_LOG_KEY, entry.hops);
+ c.set(SIGNING_SECRETS_KEY, entry.secrets);
+ try {
+ return await entry.handler.handle(c, await c.req.json());
+ } catch (err) {
+ log(`[advisor] panel call threw: ${errorMessage(err)}`);
+ return proxyErrorResponse(c, errorMessage(err));
+ }
+ });
+
+ const plan = (spec: string, role: AdvisorRole): AdvisorModelPlan =>
+ runtime.plans.get(advisorChainKey(role, spec)) ?? {
+ kind: "refused",
+ spec,
+ role,
+ cause: "no-callable-hop",
+ reason: "advisor runtime not planned for this launch",
+ };
+
+ const call = async (req: AdvisorPanelCall): Promise<AdvisorPanelResult> => {
+ const started = performance.now();
+ const latencyMs = () => Math.round(performance.now() - started);
+ const build = runtime.chains.get(advisorChainKey(req.plan.role, req.plan.spec));
+ const hops: HopAttempt[] = [];
+ const snapshot = (): AdvisorPanelResult["hops"] =>
+ hops.slice().map((h) => {
+ const hop = build ? planHopForTransport(req.plan, build, h.provider) : null;
+ return { ...h, uid: hop?.provider ?? null, displayName: hop?.displayName ?? h.provider };
+ });
+ if (!build?.handler) {
+ return {
+ status: null,
+ bodyText: "",
+ streamFailure: false,
+ hops: [],
+ failure: { kind: "internal", message: `no hop could be built for ${req.plan.spec}` },
+ latencyMs: latencyMs(),
+ };
+ }
+
+ const secrets = createSigningSecrets();
+ const controller = new AbortController();
+ const request = new Request(ADVISOR_INTERNAL_URL, {
+ method: "POST",
+ body: JSON.stringify(req.payload),
+ signal: controller.signal,
+ headers: { "content-type": "application/json", "x-claudish-no-recovery": "advisor" },
+ });
+ pendingCalls.set(request, { handler: build.handler, signal: controller.signal, hops, secrets });
+
+ // The body is read INSIDE the work, so the deadline covers it, and redacted
+ // while the lease still holds every value the chain signed with.
+ const work = (async () => {
+ const res = await app.fetch(request);
+ const text = redactExactValues(redactForClient(await res.text()), secrets.values);
+ return { res, text };
+ })();
+ // The lease lives as long as the work: released when it settles, which for
+ // a timed-out call is after its aborted work has unwound (and could still log).
+ work.finally(() => secrets.lease.release()).catch(() => {});
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<"timeout">((resolve) => {
+ timer = setTimeout(() => resolve("timeout"), req.timeoutMs);
+ });
+ try {
+ const outcome = await Promise.race([work, deadline]);
+ if (outcome === "timeout") {
+ controller.abort();
+ return {
+ status: null,
+ bodyText: "",
+ streamFailure: false,
+ hops: snapshot(),
+ failure: {
+ kind: "timeout",
+ message: `timed out after ${Math.round(req.timeoutMs / 1000)}s`,
+ },
+ latencyMs: latencyMs(),
+ };
+ }
+ return {
+ status: outcome.res.status,
+ bodyText: outcome.text,
+ streamFailure: isStreamFailureResponse(outcome.res),
+ hops: snapshot(),
+ latencyMs: latencyMs(),
+ };
+ } catch (err) {
+ return {
+ status: null,
+ bodyText: "",
+ streamFailure: false,
+ hops: snapshot(),
+ failure: {
+ kind: "internal",
+ message: redactExactValues(redactForClient(errorMessage(err)), secrets.values),
+ },
+ latencyMs: latencyMs(),
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+ };
+
+ return { plan, call };
+}
diff --git a/packages/cli/src/handlers/advisor-route-plan.ts b/packages/cli/src/handlers/advisor-route-plan.ts
index b4cd2cde..48368865 100644
--- a/packages/cli/src/handlers/advisor-route-plan.ts
+++ b/packages/cli/src/handlers/advisor-route-plan.ts
@@ -45,7 +45,7 @@ import { ANTHROPIC_API_HOST, claudeAdvisorModelFor } from "./advisor-claude-rout
import { ComposedHandler } from "./composed-handler.js";
import { type FallbackCandidate, FallbackHandler, isRetryableError } from "./fallback-handler.js";
import type { HandlerSet } from "./handler-set.js";
-import type { HopBilling } from "./shared/call-context.js";
+import type { HopAttempt, HopBilling } from "./shared/call-context.js";
import { isSubscriptionProvider } from "./shared/remote-provider-types.js";
import type { ModelHandler } from "./types.js";
@@ -650,3 +650,64 @@ export function describeAdvisorPlan(plan: AdvisorModelPlan, build?: AdvisorChain
}
return parts.join("");
}
+
+// ---------------------------------------------------------------------------
+// The panel gateway's contract (implemented in advisor-panel-gateway.ts)
+// ---------------------------------------------------------------------------
+
+/** One turn of the conversation a panel member is asked about, flattened to text. */
+export interface AdvisorTurn {
+ role: "user" | "assistant";
+ content: string;
+}
+
+/** The Anthropic-shaped body a routed panel call sends through its chain. */
+export interface AdvisorPanelPayload {
+ model: string;
+ system: string;
+ messages: AdvisorTurn[];
+ max_tokens: number;
+ stream: false;
+}
+
+/**
+ * The body of a routed advisor call. Deliberately nothing but these keys: no
+ * `tools`, `tool_choice`, `metadata`, `thinking` or `output_config`. Without
+ * tools and a session id, code mode stays off (`decideCodeMode`), Layer 4 has
+ * no session to drain, and the panel cannot call back into the advisor.
+ */
+export function buildAdvisorPanelPayload(
+ hop0ModelSpec: string,
+ system: string,
+ turns: AdvisorTurn[],
+ maxTokens: number
+): AdvisorPanelPayload {
+ return { model: hop0ModelSpec, system, messages: turns, max_tokens: maxTokens, stream: false };
+}
+
+export interface AdvisorPanelCall {
+ plan: RoutedPlan;
+ payload: AdvisorPanelPayload;
+ /** 60 000 for a panel member, 30 000 for the collector. */
+ timeoutMs: number;
+}
+
+export interface AdvisorPanelResult {
+ /** The answer's HTTP status; null on timeout or an internal error. */
+ status: number | null;
+ /** The WHOLE body, read inside the deadline and redacted by value. */
+ bodyText: string;
+ /** `isStreamFailureResponse(response)`: a 200 whose stream ended on an error. */
+ streamFailure: boolean;
+ /** Snapshot of the hop log: every hop whose `handle()` was entered, in order. */
+ hops: Array<HopAttempt & { uid: string | null; displayName: string }>;
+ failure?: { kind: "timeout" | "internal"; message: string };
+ latencyMs: number;
+}
+
+export interface AdvisorPanelGateway {
+ /** The startup plan for a spec; a spec the startup map lacks is a refused plan. */
+ plan(spec: string, role: AdvisorRole): AdvisorModelPlan;
+ /** Run one routed call through its startup-built chain. Never rejects. */
+ call(req: AdvisorPanelCall): Promise<AdvisorPanelResult>;
+}
diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.ts
index 90f02ef7..0a23aaad 100644
--- a/packages/cli/src/proxy-server.ts
+++ b/packages/cli/src/proxy-server.ts
@@ -15,6 +15,11 @@ import {
createAdvisorPresenceMonitor,
withAdvisorSwap,
} from "./handlers/advisor-decorator.js";
+import {
+ type AdvisorRuntime,
+ createAdvisorPanelGateway,
+} from "./handlers/advisor-panel-gateway.js";
+import { shutdownAdvisorChains } from "./handlers/advisor-route-plan.js";
import type { ComposedHandlerOptions } from "./handlers/composed-handler.js";
import { FallbackHandler } from "./handlers/fallback-handler.js";
import type { FallbackCandidate } from "./handlers/fallback-handler.js";
@@ -160,6 +165,13 @@ export interface ProxyServerOptions {
* Absent ⇒ `DEFAULT_CODE_MODE_SETTING` (`auto`).
*/
codeMode?: CodeModeSetting;
+ /**
+ * Every `--advisor` member's startup plan and every routed member's chain,
+ * built before the port was bound (advisor-route-plan.ts). Present ⇒ the
+ * proxy exposes `advisorPanel` and owns the chains: `shutdown` shuts them
+ * down. Absent ⇒ no gateway; nothing is planned lazily.
+ */
+ advisorRuntime?: AdvisorRuntime;
}
/**
@@ -1052,6 +1064,14 @@ export async function createProxyServer(
}
});
+ // The advisor panel gateway: an in-process Hono app that is never served,
+ // over the chains startup built from the advisor plans. It shares nothing
+ // with `app` above — no lease middleware (the gateway owns one lease per
+ // call), no `resolveHandlerForRequest` (no monitor branch, slot map or
+ // `--model` remap), no advisor wrapper.
+ const advisorRuntime = options.advisorRuntime;
+ const advisorPanel = advisorRuntime ? createAdvisorPanelGateway(advisorRuntime) : undefined;
+
// Bun's NATIVE server — not @hono/node-server.
//
// claudish only ever runs under Bun (bin/claudish.cjs is a Node bootstrapper
@@ -1098,10 +1118,13 @@ export async function createProxyServer(
port: resolvedPort,
url: `http://127.0.0.1:${resolvedPort}`,
modelRequestCount: () => modelRequestCount,
+ ...(advisorPanel ? { advisorPanel } : {}),
shutdown: async () => {
// `true` = close active connections too, so a streamed request in flight
// can't keep the port alive after shutdown resolves.
await server.stop(true);
+ // The advisor chains were handed over at startup; the proxy owns them.
+ if (advisorRuntime) await shutdownAdvisorChains(advisorRuntime.chains.values());
// "No episode may outlive the process that owns its timers" —
// `closeAllEpisodes`'s own doc, which until now nothing but tests
// invoked. `server.stop(true)` aborts the client signals, so waiters
diff --git a/packages/cli/src/redact.ts b/packages/cli/src/redact.ts
index cafcf1ba..b30d0f57 100644
--- a/packages/cli/src/redact.ts
+++ b/packages/cli/src/redact.ts
@@ -206,6 +206,27 @@ export function redactSigningValues(text: string): string {
return out;
}
+/**
+ * Replace every form of every value in `values` with `[redacted]`, longest
+ * first: the same forms and the same minimum length as the registry, for a
+ * holder that keeps its own set and must redact after its lease is released
+ * (the advisor gateway's result). Exact substring matching, no regex.
+ */
+export function redactExactValues(text: string, values: Iterable<string>): string {
+ if (!text) return text;
+ const forms = new Set<string>();
+ for (const value of values) {
+ if (typeof value !== "string" || value.length < SIGNING_VALUE_MIN_LENGTH) continue;
+ for (const form of signingValueForms(value)) forms.add(form);
+ }
+ if (forms.size === 0) return text;
+ let out = text;
+ for (const form of [...forms].sort((a, b) => b.length - a.length)) {
+ if (out.includes(form)) out = out.split(form).join(SIGNING_MASK);
+ }
+ return out;
+}
+
/**
* The registry pass for text sent back to Claude Code (an error body, an SSE
* error frame). A response body is not a log line, so it never passes through
diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.ts
index 873058a3..ddf796f6 100644
--- a/packages/cli/src/types.ts
+++ b/packages/cli/src/types.ts
@@ -1,6 +1,7 @@
// Claudish type definitions
import type { CodeModeSetting } from "./code-mode/policy.js";
+import type { AdvisorPanelGateway } from "./handlers/advisor-route-plan.js";
// Model ID type - any valid OpenRouter model string
export type OpenRouterModel = string;
@@ -229,6 +230,13 @@ export interface ProxyServer {
* mask the very case this measures.
*/
modelRequestCount: () => number;
+ /**
+ * The in-process advisor panel gateway, present only when the launch handed
+ * the proxy an advisor runtime (`ProxyServerOptions.advisorRuntime`). The
+ * advisor decorator calls routed panel members through it; tests drive it
+ * directly.
+ */
+ advisorPanel?: AdvisorPanelGateway;
}
// Model Handler interface