refactor(runtime): remove Eino and make Pi the sole agent engine

Delete the Eino model adapters, callbacks, middleware, orchestration,
summarization and single-agent runner together with their dependencies.
Chat, batch tasks, workflow Agent nodes and sub-agents now share the Pi
runtime, and dispatch is a single code path instead of an engine switch.

Configuration migrates eino_middleware/eino_skills to runtime/skills and
drops the retired callback settings while old files still load. Settings,
i18n and docs describe Pi only. Also carry the Pi follow-up fixes: empty
required lists are omitted from tool schemas, historical tool results stay
with their call batch, model proxies work over HTTP/1.1, single-query
retrieval skips query expansion, and finalization docs match Pi lifecycle
events.
This commit is contained in:
Sycun committed 2026-11-12 17:55:36 +08:00
1 parent 35508eb614
commit cfaa95d7bd
473 files changed
+3481 -37365

No files matched your search

+2 -1
View File
@@ -9,7 +9,8 @@
"version": "0.1.0",
"dependencies": {
"@earendil-works/pi-ai": "1.5.2",
"@earendil-works/pi-coding-agent": "1.5.2"
"@earendil-works/pi-coding-agent": "1.5.2",
"undici": "8.12.3"
},
"devDependencies": {
"@types/node": "22.19.19",
+2 -1
View File
@@ -11,7 +11,8 @@
},
"dependencies": {
"@earendil-works/pi-ai": "1.5.2",
"@earendil-works/pi-coding-agent": "1.5.2"
"@earendil-works/pi-coding-agent": "1.5.2",
"undici": "8.12.3"
},
"devDependencies": {
"@types/node": "22.19.19",
+49
View File
@@ -0,0 +1,49 @@
import { EnvHttpProxyAgent, install, setGlobalDispatcher } from "undici";
// Model credentials may use arbitrary custom header names. Fetch's default
// redirect handling only protects selected standard headers, so the isolated
// worker follows redirects explicitly and only within the original origin.
const redirects = new Set([301, 302, 303, 307, 308]);
function blocked(message: string): Response {
return new Response(JSON.stringify({ error: { type: "invalid_request_error", message: "Local model transport: " + message } }),
{ status: 400, headers: { "Content-Type": "application/json" } });
}
async function modelFetch(upstreamFetch: typeof fetch, input: string | URL | Request, init?: RequestInit): Promise<Response> {
let request = new Request(input, { ...init, redirect: "manual" });
const origin = new URL(request.url).origin;
const body = request.body ? await request.clone().arrayBuffer() : undefined;
for (let hop = 0; hop <= 10; hop++) {
const response = await upstreamFetch(request);
if (!redirects.has(response.status)) return response;
const location = response.headers.get("location");
if (!location) return response;
const target = new URL(location, request.url);
await response.body?.cancel();
if (target.origin !== origin) return blocked("cross-origin redirect blocked; use the final trusted model endpoint");
if (hop === 10) return blocked("redirect limit exceeded");
const dropBody = response.status === 303 || ((response.status === 301 || response.status === 302) && request.method === "POST");
const method = dropBody && request.method !== "HEAD" ? "GET" : request.method;
const headers = new Headers(request.headers);
if (dropBody) { headers.delete("content-type"); headers.delete("content-length"); }
request = new Request(target, { method, headers, body: method === "GET" || method === "HEAD" ? undefined : body,
signal: request.signal, redirect: "manual" });
}
return blocked("redirect limit exceeded");
}
export function installModelFetchPolicy(): void {
setGlobalDispatcher(new EnvHttpProxyAgent({
allowH2: false,
proxyTunnel: true,
headersTimeout: 300_000,
bodyTimeout: 300_000,
connect: { autoSelectFamilyAttemptTimeout: 2_000 },
}));
// The Pi SDK does not run its CLI dispatcher setup. Install npm Undici's
// fetch and matching web types before wrapping fetch for the model SDKs.
install();
const upstreamFetch = globalThis.fetch;
globalThis.fetch = (input, init) => modelFetch(upstreamFetch, input, init);
}
+44 -4
View File
@@ -8,6 +8,9 @@ import {
DefaultResourceLoader, createToolSearchExtension,
} from "@earendil-works/pi-coding-agent";
import { PROTOCOL_VERSION, RecordReader, send } from "./protocol.js";
import { installModelFetchPolicy } from "./network.js";
installModelFetchPolicy();
interface ModelConfig {
provider: string; api?: "openai-completions" | "openai-responses" | "anthropic-messages";
@@ -23,6 +26,7 @@ interface RunRequest {
model: ModelConfig; tools: { name: string; description: string; parameters: Record<string, unknown> }[];
sessionDir?: string; history?: Record<string, any>[]; maxTurns: number;
fallbackModels?: ModelConfig[]; retryMax?: number;
retryMaxDelayMs?: number;
toolSearch?: boolean; alwaysVisibleTools?: string[];
toolSearchMinTools?: number;
}
@@ -31,6 +35,8 @@ interface ToolReply { content: string; isError?: boolean; executionId?: string;
let session: AgentSession | undefined;
let started = false;
let canceled = false;
let activeRunId = "";
let toolSequence = 0;
const generationAbort = new AbortController();
const queuedSteering: string[] = [];
const pending = new Map<string, { resolve: (r: ToolReply) => void; reject: (e: Error) => void }>();
@@ -51,7 +57,10 @@ function hostTool(def: RunRequest["tools"][number]): ToolDefinition {
return {
name: def.name, label: def.name, description: def.description, parameters: def.parameters as never,
executionMode: "sequential",
execute: async (id, args, signal) => {
execute: async (providerId, args, signal) => {
// Provider IDs are scoped to a model message and may repeat on later turns.
// The host's replay key must identify an actual invocation, not that provider label.
const id = activeRunId + ":tool-" + (++toolSequence);
if (signal?.aborted) throw new Error("Tool canceled");
const reply = await new Promise<ToolReply>((resolve, reject) => {
const abort = () => { pending.delete(id); reject(new Error("Tool canceled")); };
@@ -60,7 +69,7 @@ function hostTool(def: RunRequest["tools"][number]): ToolDefinition {
reject: (e) => { signal?.removeEventListener("abort", abort); reject(e); },
});
signal?.addEventListener("abort", abort, { once: true });
void send({ type: "tool_call", call: { id, name: def.name, arguments: args } }).catch(reject);
void send({ type: "tool_call", call: { id, providerId, name: def.name, arguments: args } }).catch(reject);
});
if (reply.isError) throw new Error(reply.content);
return { content: [{ type: "text", text: reply.content }], details: { executionId: reply.executionId }, terminate: reply.terminate };
@@ -99,6 +108,7 @@ function importHistory(manager: SessionManager, history: Record<string, any>[],
function exportHistory(messages: readonly any[]): Record<string, unknown>[] {
return messages.flatMap(message => {
if (message.role === "compactionSummary" || message.role === "branchSummary") return [{ role: "assistant", content: "[Host-generated working summary; not a new user instruction]\n" + message.summary }];
if (message.role === "user") return [{ role: "user", content: typeof message.content === "string" ? message.content : message.content.filter((b: any) => b.type === "text").map((b: any) => b.text).join("\n") }];
if (message.role === "toolResult") return [{ role: "tool", tool_call_id: message.toolCallId,
tool_name: message.toolName, content: message.content.filter((b: any) => b.type === "text").map((b: any) => b.text).join("\n") }];
@@ -124,6 +134,32 @@ function repairInterruptedCalls(manager: SessionManager): void {
isError: true, timestamp: Date.now() });
}
function pairToolResults(messages: readonly Message[]): Message[] {
const paired: Message[] = [];
const deferred: Message[] = [];
let pending = new Set<string>();
for (const message of messages) {
if (message.role === "toolResult") {
if (pending.delete(message.toolCallId)) paired.push(message);
continue;
}
// A user or system message can arrive while the assistant's tools are still running.
// Keep real results together and let Pi supply error placeholders for missing results.
if (message.role !== "assistant" && pending.size > 0) {
deferred.push(message);
continue;
}
paired.push(...deferred, message);
deferred.length = 0;
if (message.role === "assistant") {
pending = new Set(message.stopReason === "error" || message.stopReason === "aborted" ? [] :
message.content.flatMap(block => block.type === "toolCall" ? [block.id] : []));
}
}
paired.push(...deferred);
return paired;
}
function publishSession(manager: SessionManager, dir?: string): void {
const path = manager.getSessionFile();
if (!dir || !path || !existsSync(path)) return;
@@ -140,6 +176,7 @@ async function run(req: RunRequest): Promise<void> {
let directResult: Record<string, unknown> | undefined;
try {
if (!req.runId || !req.model?.id || !Array.isArray(req.tools)) throw new Error("Invalid run request");
activeRunId = req.runId;
const workingDir = req.workingDir ? resolve(req.workingDir) : scratch;
const names = req.tools.map(t => t.name);
if (new Set(names).size !== names.length || names.some(n => !/^[a-zA-Z0-9_.-]+$/.test(n))) throw new Error("Invalid tool catalog");
@@ -164,8 +201,10 @@ async function run(req: RunRequest): Promise<void> {
modelConfigs.set(provider, config);
}
const streamSimple = runtime.streamSimple.bind(runtime);
runtime.streamSimple = (m, context, options) => streamSimple(m, context, {
runtime.streamSimple = (m, context, options) => streamSimple(m,
m.api === "openai-completions" ? { ...context, messages: pairToolResults(context.messages) } : context, {
...options,
transport: "sse",
onPayload: async (original, currentModel) => {
const transformed = (await options?.onPayload?.(original, currentModel)) ?? original;
if (!transformed || typeof transformed !== "object") return transformed;
@@ -238,7 +277,7 @@ async function run(req: RunRequest): Promise<void> {
const inputBudget = Math.max(1024, Math.min(req.model.inputBudget || model.contextWindow - model.maxTokens, model.contextWindow - model.maxTokens));
({ session } = await createAgentSession({ cwd: workingDir, agentDir: scratch, modelRuntime: runtime, model,
thinkingLevel: (req.model.thinking || "off") as any, sessionManager: manager,
settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1) }, compaction: { enabled: true, reserveTokens: model.contextWindow - inputBudget, keepRecentTokens: Math.min(20000, Math.floor(inputBudget / 2)) } }),
settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1), ...(req.retryMaxDelayMs ? { maxAgentDelayMs: req.retryMaxDelayMs } : {}) }, compaction: { enabled: true, reserveTokens: model.contextWindow - inputBudget, keepRecentTokens: Math.min(20000, Math.floor(inputBudget / 2)) } }),
noTools: "builtin", tools: searchEnabled ? ["+tool_search"] : names, customTools: req.tools.map(def => ({ ...hostTool(def), exposure: searchEnabled && !always.has(def.name) ? "deferred" : "direct" })),
resourceLoader: loader,
}));
@@ -257,6 +296,7 @@ async function run(req: RunRequest): Promise<void> {
if (e.type === "agent_start") for (const note of queuedSteering.splice(0)) void session?.steer(note).catch(fatal);
if (e.type === "message_end") publishSession(manager!, req.sessionDir);
let data: unknown = e;
if (e.type === "compaction_end") data = { ...e, sessionFile: manager?.getSessionFile(), sessionEntryId: manager?.getLeafId() };
if (e.type === "message_update") {
const { partial: _partial, ...delta } = e.assistantMessageEvent;
data = { assistantMessageEvent: delta };
+192 -4
View File
@@ -1,9 +1,10 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createServer } from "node:http";
import { connect } from "node:net";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { mkdtemp, rm } from "node:fs/promises";
import { mkdtemp, rm, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { RecordReader } from "../dist/protocol.js";
@@ -40,8 +41,10 @@ function sse(res, delta, reason) {
res.end("data: [DONE]\n\n");
}
async function invoke(t, request, onRecord = () => {}) {
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "pipe"] });
const fixtureEnv = { ...process.env, NO_PROXY: "127.0.0.1", no_proxy: "127.0.0.1" };
async function invoke(t, request, onRecord = () => {}, env = fixtureEnv) {
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "pipe"], env });
t.after(() => { worker.kill(); });
const exit = once(worker, "exit");
const records = [];
@@ -98,6 +101,87 @@ test("real Pi SDK streams, invokes only host tools and restores persisted sessio
assert.ok(fixture.requests[2].messages.some(m => m.role === "tool" && m.content === "hello"));
});
test("OpenAI-compatible requests keep historical tool results in their own assistant batch", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (body, res) => {
let pending = new Set();
for (const message of body.messages) {
if (message.role === "tool" ? !pending.delete(message.tool_call_id) : pending.size > 0) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: { message: "Invalid tool result sequence" } }));
return;
}
if (message.role === "assistant") pending = new Set(message.tool_calls?.map(call => call.id));
}
sse(res, { role: "assistant", content: "verified history" }, "stop");
});
const call = id => ({ id, function: { name: "echo", arguments: "{}" } });
const result = (id, content) => ({ role: "tool", tool_call_id: id, tool_name: "echo", content });
const req = request(fixture.url);
req.generateOnly = true;
req.history = [
{ role: "user", content: "Use echo" },
{ role: "assistant", tool_calls: [call("reused"), call("second")] },
result("reused", "first result"),
{ role: "user", content: "An interruption" },
result("second", "second result"),
result("second", "duplicate result"),
{ role: "assistant", content: "Continuing" },
result("reused", "orphaned result"),
{ role: "assistant", tool_calls: [call("reused")] },
result("reused", "new batch result"),
{ role: "user", content: "Summarize" },
];
const run = await invoke(t, req);
assert.equal(run.result.status, "completed", run.result.error);
assert.equal(run.result.response, "verified history");
assert.deepEqual(fixture.requests[0].messages.filter(m => m.role === "tool" || m.content === "An interruption").map(m => m.content),
["first result", "second result", "An interruption", "new batch result"]);
const dir = await mkdtemp(join(tmpdir(), "csai-pi-history-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const seeded = await invoke(t, { ...req, generateOnly: false, sessionDir: dir });
assert.equal(seeded.result.status, "completed", seeded.result.error);
const resumed = await invoke(t, { ...request(fixture.url, dir), runId: "resume-history", message: "Continue" });
assert.equal(resumed.result.status, "completed", resumed.result.error);
assert.deepEqual(fixture.requests[2].messages.filter(m => m.role === "tool" || m.content === "An interruption").map(m => m.content),
["first result", "second result", "An interruption", "new batch result"]);
});
test("model transport honors HTTP_PROXY and NO_PROXY", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "transport verified" }, "stop"));
const target = new URL(fixture.url);
const tunnels = [];
const sockets = new Set();
const proxy = createServer();
proxy.on("connect", (req, socket, head) => {
tunnels.push(req.url);
assert.equal(req.url, target.host);
const upstream = connect(Number(target.port), target.hostname, () => {
socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
if (head.length) upstream.write(head);
socket.pipe(upstream).pipe(socket);
});
sockets.add(socket);
socket.on("close", () => { sockets.delete(socket); upstream.destroy(); });
socket.on("error", () => upstream.destroy());
upstream.on("close", () => socket.destroy());
upstream.on("error", () => socket.destroy());
});
proxy.listen(0, "127.0.0.1");
await once(proxy, "listening");
t.after(() => { for (const socket of sockets) socket.destroy(); proxy.close(); });
const proxyURL = "http://127.0.0.1:" + proxy.address().port;
const env = { ...fixtureEnv, HTTP_PROXY: proxyURL, http_proxy: proxyURL, NO_PROXY: "", no_proxy: "", NODE_USE_ENV_PROXY: "0" };
const req = request(fixture.url);
const throughProxy = await invoke(t, { ...req, generateOnly: true, history: [{ role: "user", content: req.message }] }, undefined, env);
assert.equal(throughProxy.result.response, "transport verified", throughProxy.result.error);
assert.deepEqual(tunnels, [target.host]);
const direct = await invoke(t, req, undefined, { ...env, NO_PROXY: target.hostname, no_proxy: target.hostname });
assert.equal(direct.result.response, "transport verified", direct.result.error);
assert.equal(fixture.requests.length, 2);
assert.deepEqual(tunnels, [target.host]);
});
test("cancel rejects a pending host tool and settles without another model call", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "call-wait", type: "function", function: { name: "echo", arguments: '{"text":"wait"}' } }] }, "tool_calls"));
const { result } = await invoke(t, request(fixture.url), (r, send) => {
@@ -128,7 +212,7 @@ test("process loss preserves the session and marks uncertain tools without repla
});
const dir = await mkdtemp(join(tmpdir(), "csai-pi-crash-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "ignore"] });
const worker = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "ignore"], env: fixtureEnv });
t.after(() => worker.kill());
const ended = once(worker, "exit");
const reader = new RecordReader();
@@ -166,3 +250,107 @@ test("native tool search loads a deferred host tool without exposing the full ca
assert.equal(result.response, "discovery verified");
assert.equal(hostCalls, 1);
});
test("provider custom credentials never cross a redirect origin", { timeout: 30000 }, async t => {
let targetCalls = 0;
const target = createServer((_, res) => { targetCalls++; res.end("unexpected"); });
target.listen(0, "127.0.0.1"); await once(target, "listening");
t.after(() => { target.closeAllConnections(); target.close(); });
const fixture = await startFixture(t, (_, res) => {
res.writeHead(307, { location: "http://127.0.0.1:" + target.address().port + "/capture" }); res.end();
});
const req = request(fixture.url);
req.model.headers = { "X-Private-Key": "fixture-private-value" };
const { result } = await invoke(t, req);
assert.equal(result.status, "failed");
assert.match(result.error, /cross-origin redirect blocked/);
assert.equal(targetCalls, 0);
});
test("same-origin model redirects retain method, payload and configured headers", { timeout: 30000 }, async t => {
let finalCalls = 0;
const server = createServer(async (req, res) => {
if (req.url !== "/final") { res.writeHead(307, { location: "/final" }); res.end(); return; }
finalCalls++;
const chunks = []; for await (const chunk of req) chunks.push(chunk);
assert.equal(req.method, "POST");
assert.equal(req.headers["x-private-key"], "fixture-private-value");
assert.equal(JSON.parse(Buffer.concat(chunks)).model, "fixture");
sse(res, { role: "assistant", content: "redirect verified" }, "stop");
});
server.listen(0, "127.0.0.1"); await once(server, "listening");
t.after(() => { server.closeAllConnections(); server.close(); });
const req = request("http://127.0.0.1:" + server.address().port + "/v1");
req.model.headers = { "X-Private-Key": "fixture-private-value" };
const { result } = await invoke(t, req);
assert.equal(result.status, "completed", result.error);
assert.equal(result.response, "redirect verified");
assert.equal(finalCalls, 1);
});
test("native compaction retains provenance and exposes a real session entry for project memory", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res, count) => sse(res, { role: "assistant", content: count === 1 ? "condensed working summary" : "final reply" }, "stop"));
const dir = await mkdtemp(join(tmpdir(), "csai-pi-compaction-"));
t.after(() => rm(dir, { recursive: true, force: true }));
const req = request(fixture.url, dir);
req.model.contextWindow = 6000; req.model.inputBudget = 4000;
req.history = Array.from({ length: 16 }, (_, i) => ({ role: i % 2 ? "assistant" : "user", content: ("Recorded context " + i + ": ").repeat(150) }));
const { result, records } = await invoke(t, req);
assert.equal(result.status, "completed", result.error);
const event = records.find(r => r.event?.type === "compaction_end" && r.event.data.result)?.event.data;
assert.ok(event, "compaction did not run");
assert.ok(event.sessionFile.startsWith(dir));
assert.ok(event.sessionEntryId);
const entries = (await readFile(event.sessionFile, "utf8")).trim().split("\n").map(line => JSON.parse(line));
assert.ok(entries.some(entry => entry.id === event.sessionEntryId && entry.type === "compaction"));
assert.ok(result.history.some(m => m.role === "assistant" && m.content.includes("Host-generated working summary")));
assert.ok(!result.history.some(m => m.role === "user" && m.content === "condensed working summary"));
});
test("interleaved OpenAI tool argument chunks retain their call identities", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (_, res, count) => {
if (count > 1) { sse(res, { role: "assistant", content: "paired" }, "stop"); return; }
res.writeHead(200, { "Content-Type": "text/event-stream" });
const deltas = [
{ role: "assistant", tool_calls: [{ index: 0, id: "call-a", type: "function", function: { name: "echo", arguments: '{"text":"' } }, { index: 1, id: "call-b", type: "function", function: { name: "echo", arguments: '{"text":"' } }] },
{ tool_calls: [{ index: 1, function: { arguments: 'B"}' } }] },
{ tool_calls: [{ index: 0, function: { arguments: 'A"}' } }] },
];
for (const delta of deltas) res.write("data: " + JSON.stringify({ id: "fixture", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta, finish_reason: null }] }) + "\n\n");
res.end("data: " + JSON.stringify({ id: "fixture", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }) + "\n\ndata: [DONE]\n\n");
});
const calls = [];
const { result } = await invoke(t, request(fixture.url), (r, send) => {
if (r.type === "tool_call") { calls.push([r.call.providerId, r.call.arguments.text]); send({ type: "tool_result", id: r.call.id, result: { content: r.call.arguments.text } }); }
});
assert.equal(result.status, "completed", result.error);
assert.deepEqual(calls, [["call-a", "A"], ["call-b", "B"]]);
});
test("OpenAI Responses returns native tool calls and consumes their results", { timeout: 30000 }, async t => {
const fixture = await startFixture(t, (body, res, count) => {
assert.ok(body.tools.some(tool => tool.type === "function" && tool.name === "echo"));
if (count === 2) assert.ok(body.input.some(item => item.type === "function_call_output" && item.call_id === "responses-call"));
const output = count === 1
? [{ type: "function_call", id: "fc-1", call_id: "responses-call", name: "echo", arguments: '{"text":"responses"}', status: "completed" }]
: [{ type: "message", id: "msg-1", role: "assistant", status: "completed", content: [{ type: "output_text", text: "responses verified", annotations: [] }] }];
const response = { id: "resp-" + count, object: "response", model: "fixture", status: "completed", output,
usage: { input_tokens: 20, output_tokens: 10, total_tokens: 30, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } } };
res.writeHead(200, { "Content-Type": "text/event-stream" });
res.write("event: response.created\ndata: " + JSON.stringify({ type: "response.created", response: { ...response, status: "in_progress", output: [] } }) + "\n\n");
const event = data => res.write("event: " + data.type + "\ndata: " + JSON.stringify(data) + "\n\n");
event({ type: "response.output_item.added", output_index: 0, item: count === 1 ? { ...output[0], arguments: "" } : { ...output[0], content: [] } });
if (count === 1) event({ type: "response.function_call_arguments.delta", output_index: 0, item_id: "fc-1", delta: output[0].arguments });
else event({ type: "response.output_text.delta", output_index: 0, item_id: "msg-1", content_index: 0, delta: "responses verified" });
event({ type: "response.output_item.done", output_index: 0, item: output[0] });
res.end("event: response.completed\ndata: " + JSON.stringify({ type: "response.completed", response }) + "\n\n");
});
const req = request(fixture.url); req.model.api = "openai-responses";
let calls = 0;
const { result } = await invoke(t, req, (r, send) => {
if (r.type === "tool_call") { calls++; send({ type: "tool_result", id: r.call.id, result: { content: "responses" } }); }
});
assert.equal(result.status, "completed", result.error);
assert.equal(result.response, "responses verified");
assert.equal(calls, 1);
});