Add the Claude SDK sidecar: framing, the closed schema converter, the query
`sidecar/claude-sdk` is the repo's second TypeScript package, wired to the root only through `npm --prefix`. It reads length-prefixed MessagePack frames on stdin, runs one SDK query, forwards every tool call to Rust, and returns Rust's answer to the model verbatim. It computes no tool result, reads no credential, logs no prompt, argument, or result, and writes nothing outside its own stdout. The query is opened with a custom system prompt, `settingSources: []`, `tools: []`, `strictMcpConfig`, `persistSession: false`, and `alwaysLoad` on every tool, so no CLAUDE.md, settings file, output style, built-in tool, or persisted transcript reaches a caller-derived prompt. `schema.ts` converts exactly the grammar `tool_schema.rs` emits and throws on anything else, so an emitter that outgrows it fails a test rather than registering a looser tool. Two Rust tests publish the fixtures the sidecar tests read — the frame bytes and every real `parameters_json` — so the halves cannot drift apart silently. Dependencies are exact-pinned: @anthropic-ai/claude-agent-sdk 0.3.261, @msgpack/msgpack 3.1.3, zod 4.5.4, and dev typescript 5.9.3 with @types/node 24.13.3. `engines.node` is the installed major. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
parent
b150b5e38e
commit
2ff1d435d8
13 changed files with 2911 additions and 0 deletions
158
sidecar/claude-sdk/src/frames.ts
Normal file
158
sidecar/claude-sdk/src/frames.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
// The wire between Rust and this sidecar: a 4-byte big-endian length prefix
|
||||
// followed by MessagePack with string keys, matching `rmp_serde::to_vec_named`.
|
||||
// Rust owns the shapes; this file only encodes and decodes them.
|
||||
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
/** The connector's own frame cap. Rust refuses anything larger on its side too. */
|
||||
export const MAX_FRAME_BYTES = 1_052_672;
|
||||
|
||||
export interface SidecarTool {
|
||||
name: string;
|
||||
description: string;
|
||||
parameters_json: string;
|
||||
}
|
||||
|
||||
export type SidecarEvent =
|
||||
| { kind: "text"; text: string }
|
||||
| {
|
||||
kind: "tool_call";
|
||||
call_id: string;
|
||||
name: string;
|
||||
arguments: string;
|
||||
dispatched: boolean;
|
||||
};
|
||||
|
||||
export interface SdkModelUsage {
|
||||
model: string;
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
cache_read_input_tokens: number;
|
||||
cache_creation_input_tokens: number;
|
||||
}
|
||||
|
||||
export interface SdkResultMaterial {
|
||||
session_id: string;
|
||||
result_uuid: string;
|
||||
subtype: string;
|
||||
stop_reason: string | null;
|
||||
num_turns: number;
|
||||
assistant_message_uuids: string[];
|
||||
assistant_request_ids: string[];
|
||||
usage: SdkModelUsage[];
|
||||
total_cost_usd_estimate: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The closed set of failures this sidecar may name. It reports a reason; Rust
|
||||
* assigns the disposition, so nothing here can quarantine the world.
|
||||
*/
|
||||
export type SidecarFaultReason =
|
||||
| "rate_limited"
|
||||
| "overloaded"
|
||||
| "server_error"
|
||||
| "api_timeout"
|
||||
| "authentication_failed"
|
||||
| "org_not_allowed"
|
||||
| "billing_error"
|
||||
| "invalid_request"
|
||||
| "model_not_found"
|
||||
| "max_output_tokens"
|
||||
| "max_budget_usd"
|
||||
| "execution_error"
|
||||
| "unknown"
|
||||
| "protocol_violation"
|
||||
| "tool_registration_failed"
|
||||
| "turn_cap_refused";
|
||||
|
||||
export type SidecarFrame =
|
||||
| {
|
||||
kind: "query";
|
||||
query_id: number;
|
||||
model: string;
|
||||
instructions: string;
|
||||
prompt: string;
|
||||
transcript: string[];
|
||||
tools: SidecarTool[];
|
||||
effort: string | null;
|
||||
max_output_tokens: number | null;
|
||||
turn_cap: number;
|
||||
}
|
||||
| {
|
||||
kind: "tool_call";
|
||||
query_id: number;
|
||||
call_id: string;
|
||||
name: string;
|
||||
arguments: string;
|
||||
}
|
||||
| {
|
||||
kind: "tool_result";
|
||||
query_id: number;
|
||||
call_id: string;
|
||||
output: string;
|
||||
}
|
||||
| {
|
||||
kind: "output";
|
||||
query_id: number;
|
||||
events: SidecarEvent[];
|
||||
receipt: SdkResultMaterial;
|
||||
}
|
||||
| {
|
||||
kind: "fault";
|
||||
query_id: number;
|
||||
reason: SidecarFaultReason;
|
||||
detail: string;
|
||||
};
|
||||
|
||||
export function encodeFrame(frame: SidecarFrame): Uint8Array {
|
||||
const body = encode(frame, { useBigInt64: false });
|
||||
if (body.length > MAX_FRAME_BYTES) {
|
||||
throw new Error(`frame of ${body.length} bytes exceeds ${MAX_FRAME_BYTES}`);
|
||||
}
|
||||
const framed = new Uint8Array(4 + body.length);
|
||||
new DataView(framed.buffer).setUint32(0, body.length, false);
|
||||
framed.set(body, 4);
|
||||
return framed;
|
||||
}
|
||||
|
||||
export function decodeFrameBody(body: Uint8Array): SidecarFrame {
|
||||
const value = decode(body);
|
||||
if (typeof value !== "object" || value === null || !("kind" in value)) {
|
||||
throw new Error("a sidecar frame decoded to something without a kind");
|
||||
}
|
||||
return value as SidecarFrame;
|
||||
}
|
||||
|
||||
/** Reassembles frames from an arbitrarily chunked byte stream. */
|
||||
export class FrameReader {
|
||||
#buffer = new Uint8Array(0);
|
||||
|
||||
push(chunk: Uint8Array): void {
|
||||
const grown = new Uint8Array(this.#buffer.length + chunk.length);
|
||||
grown.set(this.#buffer, 0);
|
||||
grown.set(chunk, this.#buffer.length);
|
||||
this.#buffer = grown;
|
||||
}
|
||||
|
||||
/** The next whole frame, or null while one is still arriving. */
|
||||
next(): SidecarFrame | null {
|
||||
if (this.#buffer.length < 4) {
|
||||
return null;
|
||||
}
|
||||
const length = new DataView(
|
||||
this.#buffer.buffer,
|
||||
this.#buffer.byteOffset,
|
||||
4,
|
||||
).getUint32(0, false);
|
||||
if (length === 0 || length > MAX_FRAME_BYTES) {
|
||||
throw new Error(`frame length ${length} is outside 1..=${MAX_FRAME_BYTES}`);
|
||||
}
|
||||
if (this.#buffer.length < 4 + length) {
|
||||
return null;
|
||||
}
|
||||
const body = this.#buffer.subarray(4, 4 + length);
|
||||
const frame = decodeFrameBody(body);
|
||||
this.#buffer = this.#buffer.slice(4 + length);
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
491
sidecar/claude-sdk/src/main.ts
Normal file
491
sidecar/claude-sdk/src/main.ts
Normal file
|
|
@ -0,0 +1,491 @@
|
|||
// Ghostlight's Claude Agent SDK sidecar.
|
||||
//
|
||||
// One query at a time, one child process for many queries. Every tool call is
|
||||
// forwarded to Rust and answered by Rust: this process computes no tool result,
|
||||
// reads no credential, logs no prompt, argument, or result, and writes nothing
|
||||
// outside its own stdout.
|
||||
//
|
||||
// Operator prerequisites, none of which Ghostlight performs: install the Claude
|
||||
// Code CLI, sign in with `/login` or mint a token with `claude setup-token`,
|
||||
// verify with one plain `claude -p` query, then `npm --prefix sidecar/claude-sdk
|
||||
// install` and `npm run sdk:build`. The SDK finds that login on its own through
|
||||
// the ambient environment. Nothing in this repository reads, copies, forwards,
|
||||
// or logs the credential.
|
||||
//
|
||||
// Runtime binding: `GHOSTLIGHT_SDK_SIDECAR` is this file's built path
|
||||
// (`sidecar/claude-sdk/dist/main.js`) and `GHOSTLIGHT_SDK_MODEL_PREFIX`
|
||||
// (default `claude`) is the model-name prefix that routes a lane here.
|
||||
|
||||
import {
|
||||
createSdkMcpServer,
|
||||
query,
|
||||
tool,
|
||||
type Options,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
FrameReader,
|
||||
encodeFrame,
|
||||
type SdkModelUsage,
|
||||
type SdkResultMaterial,
|
||||
type SidecarEvent,
|
||||
type SidecarFaultReason,
|
||||
type SidecarFrame,
|
||||
type SidecarTool,
|
||||
} from "./frames.ts";
|
||||
import { toolRawShape } from "./schema.ts";
|
||||
import { resolve } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const SERVER_NAME = "ghostlight";
|
||||
const QUALIFIED_PREFIX = `mcp__${SERVER_NAME}__`;
|
||||
/** The header a prior round's rendered transcript is folded under. */
|
||||
const TRANSCRIPT_HEADER =
|
||||
"Earlier turns in this same request, as they happened:";
|
||||
/** No deadline tighter than the Rust side's own response timeout. */
|
||||
const RENDEZVOUS_TIMEOUT_MS = 900_000;
|
||||
/** The largest round budget any Ghostlight lane carries. */
|
||||
const MAX_TURN_CAP = 24;
|
||||
|
||||
export class SidecarFault extends Error {
|
||||
readonly reason: SidecarFaultReason;
|
||||
|
||||
constructor(reason: SidecarFaultReason, detail: string) {
|
||||
super(detail);
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
interface Dispatch {
|
||||
call_id: string;
|
||||
name: string;
|
||||
arguments: string;
|
||||
}
|
||||
|
||||
/** One in-flight query's rendezvous with Rust. */
|
||||
export class QuerySession {
|
||||
readonly dispatches: Dispatch[] = [];
|
||||
readonly queryId: number;
|
||||
readonly #pending = new Map<string, (output: string) => void>();
|
||||
readonly #write: (frame: SidecarFrame) => void;
|
||||
#nextCall = 0;
|
||||
|
||||
constructor(queryId: number, write: (frame: SidecarFrame) => void) {
|
||||
this.queryId = queryId;
|
||||
this.#write = write;
|
||||
}
|
||||
|
||||
/** Sends one call to Rust and resolves when Rust answers it. */
|
||||
async ask(name: string, args: unknown): Promise<string> {
|
||||
const call_id = `c${this.#nextCall++}`;
|
||||
const argumentsJson = JSON.stringify(args ?? {});
|
||||
this.dispatches.push({ call_id, name, arguments: argumentsJson });
|
||||
const answer = new Promise<string>((resolve) => {
|
||||
this.#pending.set(call_id, resolve);
|
||||
});
|
||||
this.#write({
|
||||
kind: "tool_call",
|
||||
query_id: this.queryId,
|
||||
call_id,
|
||||
name,
|
||||
arguments: argumentsJson,
|
||||
});
|
||||
return answer;
|
||||
}
|
||||
|
||||
answer(call_id: string, output: string): void {
|
||||
const resolve = this.#pending.get(call_id);
|
||||
if (!resolve) {
|
||||
throw new SidecarFault(
|
||||
"protocol_violation",
|
||||
`a tool result arrived for the unissued call ${call_id}`,
|
||||
);
|
||||
}
|
||||
this.#pending.delete(call_id);
|
||||
resolve(output);
|
||||
}
|
||||
}
|
||||
|
||||
function apiRetryReason(category: unknown): SidecarFaultReason {
|
||||
switch (category) {
|
||||
case "rate_limit":
|
||||
return "rate_limited";
|
||||
case "overloaded":
|
||||
return "overloaded";
|
||||
case "server_error":
|
||||
return "server_error";
|
||||
case "authentication_failed":
|
||||
return "authentication_failed";
|
||||
case "oauth_org_not_allowed":
|
||||
return "org_not_allowed";
|
||||
case "billing_error":
|
||||
return "billing_error";
|
||||
case "invalid_request":
|
||||
return "invalid_request";
|
||||
case "model_not_found":
|
||||
return "model_not_found";
|
||||
case "max_output_tokens":
|
||||
return "max_output_tokens";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function resultReason(subtype: string, apiErrorStatus: unknown): SidecarFaultReason {
|
||||
if (typeof apiErrorStatus === "number") {
|
||||
if (apiErrorStatus === 429) {
|
||||
return "rate_limited";
|
||||
}
|
||||
if (apiErrorStatus >= 500) {
|
||||
return "server_error";
|
||||
}
|
||||
}
|
||||
switch (subtype) {
|
||||
case "error_max_budget_usd":
|
||||
return "max_budget_usd";
|
||||
case "error_during_execution":
|
||||
case "error_max_structured_output_retries":
|
||||
return "execution_error";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function usageRows(modelUsage: unknown): SdkModelUsage[] {
|
||||
if (typeof modelUsage !== "object" || modelUsage === null) {
|
||||
return [];
|
||||
}
|
||||
return Object.entries(modelUsage as Record<string, Record<string, unknown>>).map(
|
||||
([model, row]) => ({
|
||||
model,
|
||||
input_tokens: Number(row?.inputTokens ?? row?.input_tokens ?? 0),
|
||||
output_tokens: Number(row?.outputTokens ?? row?.output_tokens ?? 0),
|
||||
cache_read_input_tokens: Number(
|
||||
row?.cacheReadInputTokens ?? row?.cache_read_input_tokens ?? 0,
|
||||
),
|
||||
cache_creation_input_tokens: Number(
|
||||
row?.cacheCreationInputTokens ?? row?.cache_creation_input_tokens ?? 0,
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `query()` options one frame lowers to. Exported so a test can assert the
|
||||
* hygiene — no CLAUDE.md, no settings, no built-in tools, no persisted session
|
||||
* — against a stub instead of a live query.
|
||||
*/
|
||||
export function lowerQuery(
|
||||
frame: Extract<SidecarFrame, { kind: "query" }>,
|
||||
session: QuerySession,
|
||||
): { prompt: string; options: Options } {
|
||||
if (frame.turn_cap < 1 || frame.turn_cap > MAX_TURN_CAP) {
|
||||
throw new SidecarFault(
|
||||
"turn_cap_refused",
|
||||
`turn cap ${frame.turn_cap} is outside 1..=${MAX_TURN_CAP}`,
|
||||
);
|
||||
}
|
||||
const tools = frame.tools.map((entry: SidecarTool) => {
|
||||
let shape;
|
||||
try {
|
||||
shape = toolRawShape(entry.parameters_json, entry.name);
|
||||
} catch (error) {
|
||||
throw new SidecarFault("tool_registration_failed", String(error));
|
||||
}
|
||||
return tool(
|
||||
entry.name,
|
||||
entry.description,
|
||||
shape,
|
||||
async (args: unknown) => ({
|
||||
content: [
|
||||
{ type: "text" as const, text: await session.ask(entry.name, args) },
|
||||
],
|
||||
}),
|
||||
{ alwaysLoad: true },
|
||||
);
|
||||
});
|
||||
const prompt = frame.transcript.length
|
||||
? `${frame.prompt}\n\n${TRANSCRIPT_HEADER}\n${frame.transcript.join("\n")}`
|
||||
: frame.prompt;
|
||||
const options: Record<string, unknown> = {
|
||||
systemPrompt: { type: "custom", prompt: frame.instructions },
|
||||
// No CLAUDE.md, no settings.json, no output styles, no built-in tools.
|
||||
settingSources: [],
|
||||
tools: [],
|
||||
strictMcpConfig: true,
|
||||
model: frame.model,
|
||||
maxTurns: frame.turn_cap,
|
||||
includePartialMessages: false,
|
||||
persistSession: false,
|
||||
};
|
||||
if (frame.effort) {
|
||||
options.effort = frame.effort;
|
||||
}
|
||||
if (tools.length) {
|
||||
options.mcpServers = {
|
||||
[SERVER_NAME]: createSdkMcpServer({
|
||||
name: SERVER_NAME,
|
||||
tools,
|
||||
alwaysLoad: true,
|
||||
timeout: RENDEZVOUS_TIMEOUT_MS,
|
||||
}),
|
||||
};
|
||||
options.allowedTools = [`${QUALIFIED_PREFIX}*`];
|
||||
}
|
||||
return { prompt, options: options as unknown as Options };
|
||||
}
|
||||
|
||||
function strip(name: string): string {
|
||||
return name.startsWith(QUALIFIED_PREFIX)
|
||||
? name.slice(QUALIFIED_PREFIX.length)
|
||||
: name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks the assistant messages in order and pairs each registered tool_use
|
||||
* block with the dispatch it caused, so the ids Rust answered and the ids
|
||||
* reported here are the same ids.
|
||||
*/
|
||||
export function assembleEvents(
|
||||
messages: { content: unknown }[],
|
||||
registered: Set<string>,
|
||||
dispatches: Dispatch[],
|
||||
): SidecarEvent[] {
|
||||
const events: SidecarEvent[] = [];
|
||||
let taken = 0;
|
||||
let undispatched = 0;
|
||||
for (const message of messages) {
|
||||
const blocks = Array.isArray(message.content) ? message.content : [];
|
||||
for (const block of blocks as Record<string, unknown>[]) {
|
||||
if (block.type === "text" && typeof block.text === "string") {
|
||||
events.push({ kind: "text", text: block.text });
|
||||
continue;
|
||||
}
|
||||
if (block.type !== "tool_use") {
|
||||
continue;
|
||||
}
|
||||
const name = strip(String(block.name ?? ""));
|
||||
if (registered.has(name)) {
|
||||
const dispatch = dispatches[taken++];
|
||||
if (!dispatch || dispatch.name !== name) {
|
||||
throw new SidecarFault(
|
||||
"protocol_violation",
|
||||
`a registered tool_use block for ${name} has no matching dispatch`,
|
||||
);
|
||||
}
|
||||
events.push({ kind: "tool_call", ...dispatch, dispatched: true });
|
||||
continue;
|
||||
}
|
||||
events.push({
|
||||
kind: "tool_call",
|
||||
call_id: `u${undispatched++}`,
|
||||
name,
|
||||
arguments: JSON.stringify(block.input ?? {}),
|
||||
dispatched: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (taken !== dispatches.length) {
|
||||
throw new SidecarFault(
|
||||
"protocol_violation",
|
||||
"more tool calls were dispatched than the assistant messages report",
|
||||
);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
async function runQuery(
|
||||
frame: Extract<SidecarFrame, { kind: "query" }>,
|
||||
write: (frame: SidecarFrame) => void,
|
||||
session: QuerySession,
|
||||
): Promise<void> {
|
||||
const registered = new Set(frame.tools.map((entry) => entry.name));
|
||||
const { prompt, options } = lowerQuery(frame, session);
|
||||
const assistant: { content: unknown }[] = [];
|
||||
const material: SdkResultMaterial = {
|
||||
session_id: "",
|
||||
result_uuid: "",
|
||||
subtype: "",
|
||||
stop_reason: null,
|
||||
num_turns: 0,
|
||||
assistant_message_uuids: [],
|
||||
assistant_request_ids: [],
|
||||
usage: [],
|
||||
total_cost_usd_estimate: "0",
|
||||
};
|
||||
let sawResult = false;
|
||||
const stream = query({ prompt, options });
|
||||
try {
|
||||
for await (const message of stream as AsyncIterable<Record<string, unknown>>) {
|
||||
if (message.type === "assistant") {
|
||||
const inner = message.message as Record<string, unknown> | undefined;
|
||||
assistant.push({ content: inner?.content });
|
||||
if (typeof message.uuid === "string") {
|
||||
material.assistant_message_uuids.push(message.uuid);
|
||||
}
|
||||
if (typeof message.request_id === "string") {
|
||||
material.assistant_request_ids.push(message.request_id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (message.type === "system" && message.subtype === "api_retry") {
|
||||
// The harness owns its own retries; only an exhausted one reaches a
|
||||
// result, so this is recorded and not raised.
|
||||
continue;
|
||||
}
|
||||
if (message.type !== "result") {
|
||||
continue;
|
||||
}
|
||||
sawResult = true;
|
||||
const subtype = String(message.subtype ?? "");
|
||||
material.session_id = String(message.session_id ?? "");
|
||||
material.result_uuid = String(message.uuid ?? "");
|
||||
material.subtype = subtype;
|
||||
material.stop_reason =
|
||||
typeof message.stop_reason === "string" ? message.stop_reason : null;
|
||||
material.num_turns = Number(message.num_turns ?? 0);
|
||||
material.usage = usageRows(message.modelUsage);
|
||||
material.total_cost_usd_estimate = String(message.total_cost_usd ?? 0);
|
||||
// `error_max_turns` is not a fault: the cap is the lane's own remaining
|
||||
// round budget, so reaching it means the model spent turns the evaluator
|
||||
// would also have allowed. The lane sees one ordinary round.
|
||||
if (subtype !== "success" && subtype !== "error_max_turns") {
|
||||
const errors = Array.isArray(message.errors)
|
||||
? (message.errors as unknown[]).map(String).join("; ")
|
||||
: "";
|
||||
const category = Array.isArray(message.errors)
|
||||
? undefined
|
||||
: (message as Record<string, unknown>).error;
|
||||
const reason =
|
||||
category === undefined
|
||||
? resultReason(subtype, message.api_error_status)
|
||||
: apiRetryReason(category);
|
||||
throw new SidecarFault(reason, `${subtype}: ${errors}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// The TS SDK throws after yielding an error result. A result already
|
||||
// collected for `error_max_turns` is the normal path, so only an
|
||||
// unaccounted throw becomes a fault.
|
||||
if (error instanceof SidecarFault) {
|
||||
throw error;
|
||||
}
|
||||
if (!sawResult) {
|
||||
throw new SidecarFault("execution_error", String(error));
|
||||
}
|
||||
}
|
||||
if (!sawResult) {
|
||||
throw new SidecarFault("execution_error", "the SDK query produced no result");
|
||||
}
|
||||
write({
|
||||
kind: "output",
|
||||
query_id: frame.query_id,
|
||||
events: assembleEvents(assistant, registered, session.dispatches),
|
||||
receipt: material,
|
||||
});
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const reader = new FrameReader();
|
||||
const write = (frame: SidecarFrame) => {
|
||||
process.stdout.write(encodeFrame(frame));
|
||||
};
|
||||
let live: QuerySession | null = null;
|
||||
let running: Promise<void> = Promise.resolve();
|
||||
|
||||
for await (const chunk of process.stdin) {
|
||||
reader.push(chunk as Uint8Array);
|
||||
for (;;) {
|
||||
let frame: SidecarFrame | null;
|
||||
try {
|
||||
frame = reader.next();
|
||||
} catch (error) {
|
||||
write({
|
||||
kind: "fault",
|
||||
query_id: live?.queryId ?? 0,
|
||||
reason: "protocol_violation",
|
||||
detail: String(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!frame) {
|
||||
break;
|
||||
}
|
||||
if (frame.kind === "query") {
|
||||
if (live) {
|
||||
write({
|
||||
kind: "fault",
|
||||
query_id: frame.query_id,
|
||||
reason: "protocol_violation",
|
||||
detail: "a second query arrived while one was in flight",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const opening = frame;
|
||||
const session = new QuerySession(opening.query_id, write);
|
||||
live = session;
|
||||
running = (async () => {
|
||||
try {
|
||||
await runQuery(opening, write, session);
|
||||
} catch (error) {
|
||||
const fault =
|
||||
error instanceof SidecarFault
|
||||
? error
|
||||
: new SidecarFault("execution_error", String(error));
|
||||
write({
|
||||
kind: "fault",
|
||||
query_id: opening.query_id,
|
||||
reason: fault.reason,
|
||||
detail: fault.message,
|
||||
});
|
||||
} finally {
|
||||
live = null;
|
||||
}
|
||||
})();
|
||||
void running;
|
||||
continue;
|
||||
}
|
||||
if (frame.kind === "tool_result") {
|
||||
if (!live || live.queryId !== frame.query_id) {
|
||||
write({
|
||||
kind: "fault",
|
||||
query_id: frame.query_id,
|
||||
reason: "protocol_violation",
|
||||
detail: "a tool result arrived outside its query",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
live.answer(frame.call_id, frame.output);
|
||||
} catch (error) {
|
||||
const fault =
|
||||
error instanceof SidecarFault
|
||||
? error
|
||||
: new SidecarFault("protocol_violation", String(error));
|
||||
write({
|
||||
kind: "fault",
|
||||
query_id: frame.query_id,
|
||||
reason: fault.reason,
|
||||
detail: fault.message,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
write({
|
||||
kind: "fault",
|
||||
query_id: 0,
|
||||
reason: "protocol_violation",
|
||||
detail: `frame kind ${frame.kind} is not one this sidecar accepts`,
|
||||
});
|
||||
}
|
||||
}
|
||||
await running;
|
||||
}
|
||||
|
||||
// Only run the loop when this file is the entry point, so the tests can import
|
||||
// its pure halves without starting a stdin reader.
|
||||
if (
|
||||
process.argv[1] &&
|
||||
import.meta.url === pathToFileURL(resolve(process.argv[1])).href
|
||||
) {
|
||||
await main();
|
||||
}
|
||||
134
sidecar/claude-sdk/src/schema.ts
Normal file
134
sidecar/claude-sdk/src/schema.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// The JSON Schema grammar Ghostlight's one emitter produces, converted to the
|
||||
// Zod raw shape the SDK's `tool()` takes. It is closed on purpose: anything
|
||||
// outside the grammar throws, so an emitter that grows a construct fails a test
|
||||
// here rather than silently registering a looser tool.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
const FORBIDDEN = ["oneOf", "allOf", "not", "$ref"] as const;
|
||||
|
||||
function isObject(value: unknown): value is Json {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function convert(node: unknown, at: string): z.ZodTypeAny {
|
||||
if (!isObject(node)) {
|
||||
throw new Error(`${at}: schema node is not an object`);
|
||||
}
|
||||
for (const forbidden of FORBIDDEN) {
|
||||
if (forbidden in node) {
|
||||
throw new Error(`${at}: \`${forbidden}\` is outside the emitted grammar`);
|
||||
}
|
||||
}
|
||||
if ("anyOf" in node) {
|
||||
const branches = node.anyOf;
|
||||
if (!Array.isArray(branches) || branches.length === 0) {
|
||||
throw new Error(`${at}: anyOf must be a nonempty array`);
|
||||
}
|
||||
// The nullable shape the emitter uses for an optional argument.
|
||||
if (
|
||||
branches.length === 2 &&
|
||||
isObject(branches[1]) &&
|
||||
branches[1].type === "null"
|
||||
) {
|
||||
return convert(branches[0], `${at}/anyOf/0`).nullable();
|
||||
}
|
||||
const converted = branches.map((branch, index) =>
|
||||
convert(branch, `${at}/anyOf/${index}`),
|
||||
);
|
||||
if (converted.length === 1) {
|
||||
return converted[0]!;
|
||||
}
|
||||
return z.union(converted as [z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]);
|
||||
}
|
||||
const kind = node.type;
|
||||
if (typeof kind !== "string") {
|
||||
throw new Error(`${at}: schema node names no type`);
|
||||
}
|
||||
switch (kind) {
|
||||
case "object":
|
||||
return z.object(rawShape(node, at)).strict();
|
||||
case "string": {
|
||||
if ("const" in node) {
|
||||
if (typeof node.const !== "string") {
|
||||
throw new Error(`${at}: a string const must be a string`);
|
||||
}
|
||||
return z.literal(node.const);
|
||||
}
|
||||
if ("enum" in node) {
|
||||
const values = node.enum;
|
||||
if (
|
||||
!Array.isArray(values) ||
|
||||
values.length === 0 ||
|
||||
values.some((value) => typeof value !== "string")
|
||||
) {
|
||||
throw new Error(`${at}: enum must be a nonempty array of strings`);
|
||||
}
|
||||
return z.enum(values as [string, ...string[]]);
|
||||
}
|
||||
return z.string();
|
||||
}
|
||||
case "integer": {
|
||||
let schema = z.number().int();
|
||||
if (typeof node.minimum === "number") {
|
||||
schema = schema.min(node.minimum);
|
||||
}
|
||||
if (typeof node.maximum === "number") {
|
||||
schema = schema.max(node.maximum);
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
case "boolean":
|
||||
return z.boolean();
|
||||
case "null":
|
||||
return z.null();
|
||||
case "array":
|
||||
return z.array(convert(node.items, `${at}/items`));
|
||||
default:
|
||||
throw new Error(`${at}: type \`${kind}\` is outside the emitted grammar`);
|
||||
}
|
||||
}
|
||||
|
||||
function rawShape(node: Json, at: string): Record<string, z.ZodTypeAny> {
|
||||
if (node.additionalProperties !== false) {
|
||||
throw new Error(`${at}: every emitted object is closed`);
|
||||
}
|
||||
const properties = node.properties;
|
||||
if (!isObject(properties)) {
|
||||
throw new Error(`${at}: object without properties`);
|
||||
}
|
||||
const names = Object.keys(properties).sort();
|
||||
const required = Array.isArray(node.required)
|
||||
? [...(node.required as unknown[])].map(String).sort()
|
||||
: [];
|
||||
if (names.length !== required.length || names.some((name, index) => name !== required[index])) {
|
||||
throw new Error(`${at}: every emitted property is required`);
|
||||
}
|
||||
const shape: Record<string, z.ZodTypeAny> = {};
|
||||
for (const name of names) {
|
||||
shape[name] = convert(properties[name], `${at}/${name}`);
|
||||
}
|
||||
return shape;
|
||||
}
|
||||
|
||||
/**
|
||||
* One tool's `parameters_json` as the raw shape `tool()` takes. Throws on any
|
||||
* node outside the grammar the emitter produces.
|
||||
*/
|
||||
export function toolRawShape(
|
||||
parametersJson: string,
|
||||
at: string,
|
||||
): Record<string, z.ZodTypeAny> {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(parametersJson);
|
||||
} catch (error) {
|
||||
throw new Error(`${at}: parameters_json is not JSON (${String(error)})`);
|
||||
}
|
||||
if (!isObject(parsed) || parsed.type !== "object") {
|
||||
throw new Error(`${at}: a tool's parameters must be an object schema`);
|
||||
}
|
||||
return rawShape(parsed, at);
|
||||
}
|
||||
Loading…
Reference in a new issue