import assert from "node:assert/strict"; import { test } from "node:test"; import dgram from "node:dgram"; import { createServer } from "node:http"; import { createServer as createHttpsServer } from "node:https"; import { connect, createServer as createTcpServer } from "node:net"; import { execFileSync, spawn } from "node:child_process"; import { once } from "node:events"; import { mkdtemp, rm, readFile, readdir, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import { fileURLToPath } from "node:url"; import { SessionManager } from "@earendil-works/pi-coding-agent"; import { isDomesticModelHost, isFakeIpAddress, isLocalClientProxy, isLoopbackOrPrivateHost, isPreResponseConnectError, normalizeProxyUrl, parseDarwinScutilProxy, parseWindowsRegProxy, resolveEnvProxySettings, } from "../dist/network.js"; import { RecordReader } from "../dist/protocol.js"; test("JSONL preserves Unicode separators and fragmented UTF-8", () => { const body = Buffer.from(JSON.stringify({ text: "中文\u2028\u2029" }) + "\n"); const reader = new RecordReader(); const values = []; for (const byte of body) values.push(...reader.push(Buffer.from([byte]))); reader.finish(); assert.deepEqual(values, [{ text: "中文\u2028\u2029" }]); }); async function startFixture(t, reply) { const requests = []; const server = createServer(async (req, res) => { const chunks = []; for await (const c of req) chunks.push(c); const body = JSON.parse(Buffer.concat(chunks)); requests.push(body); await reply(body, res, requests.length); }); server.listen(0, "127.0.0.1"); await once(server, "listening"); t.after(() => { server.closeAllConnections(); server.close(); }); return { requests, url: "http://127.0.0.1:" + server.address().port + "/v1" }; } function sse(res, delta, reason) { res.writeHead(200, { "Content-Type": "text/event-stream" }); const chunk = (d, finish_reason) => ({ id: "test", object: "chat.completion.chunk", model: "fixture", choices: [{ index: 0, delta: d, finish_reason }] }); res.write("data: " + JSON.stringify(chunk(delta, null)) + "\n\n"); res.write("data: " + JSON.stringify(chunk({}, reason)) + "\n\n"); res.end("data: [DONE]\n\n"); } const fixtureEnv = { ...process.env, NO_PROXY: "127.0.0.1", no_proxy: "127.0.0.1" }; const workerPath = fileURLToPath(new URL("../dist/worker.js", import.meta.url)); async function invoke(t, request, onRecord = () => {}, env = fixtureEnv) { const worker = spawn(process.execPath, [workerPath], { stdio: ["pipe", "pipe", "pipe"], env }); t.after(() => { worker.kill(); }); const exit = once(worker, "exit"); const records = []; let stderr = ""; worker.stderr.on("data", c => stderr += c); const reader = new RecordReader(); const send = record => worker.stdin.write(JSON.stringify(record) + "\n"); worker.stdout.on("data", chunk => { for (const r of reader.push(chunk)) { records.push(r); if (r.type === "ready") send({ type: "run", version: 1, request }); onRecord(r, send); } }); const [code] = await exit; assert.equal(code, 0, stderr + JSON.stringify(records)); const result = records.find(r => r.type === "result")?.result; assert.ok(result, stderr + JSON.stringify(records)); return { records, result }; } function request(url, sessionDir) { return { runId: "run-1", conversationId: "conversation-1", systemPrompt: "Use the provided echo tool then answer.", message: "echo hello", history: [], model: { provider: "openai", id: "fixture", baseUrl: url, apiKey: "test-key", contextWindow: 32000, maxTokens: 1024, thinking: "off" }, tools: [{ name: "echo", description: "Return text", parameters: { type: "object", properties: { text: { type: "string" } }, required: ["text"] } }], maxTurns: 8, sessionDir }; } function userTexts(body) { return body.messages.filter(m => m.role === "user").map(m => typeof m.content === "string" ? m.content : m.content.map(block => block.text).join("")); } test("split and legacy requests send the same system text", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (_body, res) => sse(res, { content: "done" }, "stop")); const dir = await mkdtemp(join(tmpdir(), "csai-pi-prompt-test-")); t.after(() => rm(dir, { recursive: true, force: true })); const req = { ...request(fixture.url), workingDir: dir }; const dynamic = "\n\n[[CSAI_DATA:fixture field=project_blackboard]]\nReviewed project notes\n"; for (const generateOnly of [false, true]) { const legacy = { ...req, generateOnly, systemPrompt: req.systemPrompt + dynamic }; await invoke(t, legacy); await invoke(t, { ...req, generateOnly, systemPromptDynamic: dynamic }); const [before, after] = fixture.requests.slice(-2); const systemMessages = body => body.messages.filter(m => m.role === "system" || m.role === "developer"); assert.ok(JSON.stringify(systemMessages(after)).includes("Reviewed project notes")); assert.deepEqual(systemMessages(after), systemMessages(before)); } }); test("native chat images reach image-capable models without appearing in host events", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (_body, res) => { sse(res, { role: "assistant", content: "done" }, "stop"); }); const image = { mimeType: "image/png", data: "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKElEQVR4nO3NsQ0AAAzCMP5/un0CNkuZ41wybXsHAAAAAAAAAAAAxR4yw/wuPL6QkAAAAABJRU5ErkJggg==", }; for (const capability of [true, false, undefined]) { const req = request(fixture.url); req.tools = []; req.images = [image]; req.model.imageInput = capability; const { result, records } = await invoke(t, req); assert.equal(result.status, "completed", result.error); const user = fixture.requests.at(-1).messages.find(m => m.role === "user"); const content = Array.isArray(user.content) ? user.content : [{ type: "text", text: user.content }]; assert.ok(content.some(block => block.type === "text" && block.text.includes(req.message)), JSON.stringify(content.filter(block => block.type === "text"))); assert.equal(content.filter(block => block.type === "image_url").length, capability ? 1 : 0); assert.ok(!JSON.stringify(records).includes(image.data)); } }); test("real Pi SDK streams, invokes only host tools and restores persisted sessions", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (body, res, count) => { if (count === 1) sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "call-1", type: "function", function: { name: "echo", arguments: '{"text":"hello"}' } }] }, "tool_calls"); else sse(res, { role: "assistant", content: "verified hello" }, "stop"); }); const dir = await mkdtemp(join(tmpdir(), "csai-pi-test-")); t.after(() => rm(dir, { recursive: true, force: true })); let calls = 0; const req = request(fixture.url, dir); const first = await invoke(t, { ...req, profile: { enabled: true, instruction: "Retired guidance" } }, (r, send) => { if (r.type === "tool_call") { calls++; send({ type: "tool_result", id: r.call.id, result: { content: "hello", executionId: "exec-1" } }); } }); assert.equal(first.result.status, "completed", first.result.error); assert.equal(first.result.response, "verified hello"); assert.equal(calls, 1); assert.equal(fixture.requests.length, 2); const systemPrompt = fixture.requests[0].messages.filter(m => m.role === "system").map(m => m.content).join("\n"); assert.ok(systemPrompt.startsWith(req.systemPrompt)); assert.doesNotMatch(systemPrompt, /CyberStrikeAI execution protocol|Retired guidance/); assert.deepEqual(fixture.requests[0].tools.map(t => t.function.name), ["echo"]); assert.ok(fixture.requests[1].messages.some(m => m.role === "tool" && m.content === "hello")); assert.ok(first.records.some(r => r.event?.type === "message_update")); assert.ok(first.records.filter(r => r.event?.type === "message_update").every(r => !Object.hasOwn(r.event.data.assistantMessageEvent, "partial"))); const second = await invoke(t, { ...request(fixture.url, dir), runId: "run-2", message: "summarize prior result", workingDir: tmpdir() }); assert.equal(second.result.status, "completed", second.result.error); assert.equal(second.result.sessionFile, first.result.sessionFile); assert.deepEqual(await readdir(dir), [basename(first.result.sessionFile)]); assert.ok(fixture.requests[2].messages.some(m => m.role === "tool" && m.content === "hello")); }); test("legacy Pi sessions resume in place without invalidating saved evidence paths", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "resumed" }, "stop")); const dir = await mkdtemp(join(tmpdir(), "csai-pi-legacy-")); t.after(() => rm(dir, { recursive: true, force: true })); const legacy = SessionManager.create(process.cwd(), dir); const entryId = legacy.appendMessage({ role: "user", content: "legacy conversation history", timestamp: Date.now() }); const path = legacy.getSessionFile(); await writeFile(join(dir, "current-session"), basename(path)); const { result } = await invoke(t, { ...request(fixture.url, dir), history: [{ role: "user", content: "database fallback" }] }); assert.equal(result.status, "completed", result.error); assert.equal(result.sessionFile, path); assert.ok(SessionManager.open(path).getEntry(entryId)); assert.deepEqual(userTexts(fixture.requests[0]), ["legacy conversation history", "echo hello"]); }); test("Pi accepts steering while the worker is still preparing its session", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "received" }, "stop")); const req = request(fixture.url); const { result } = await invoke(t, req, (r, send) => { if (r.type === "ready") send({ type: "steer", message: "early steering" }); }); assert.equal(result.status, "completed", result.error); assert.equal(fixture.requests.length, 1); assert.deepEqual(userTexts(fixture.requests[0]), [req.message, "early steering"]); }); 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) => { if (r.type === "tool_call") send({ type: "cancel" }); }); assert.equal(result.status, "canceled"); assert.equal(fixture.requests.length, 1); }); test("native virtual model routes a transient retry to the configured fallback", { timeout: 30000 }, async t => { const primary = await startFixture(t, (_, res) => { res.writeHead(503, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: { message: "server overloaded" } })); }); const backup = await startFixture(t, (_, res) => sse(res, { role: "assistant", content: "backup verified" }, "stop")); const req = request(primary.url); const { result, records } = await invoke(t, { ...req, fallbackModels: [{ ...req.model, id: "backup", baseUrl: backup.url }] }); assert.equal(result.status, "completed", result.error); assert.equal(result.response, "backup verified"); assert.equal(backup.requests.length, 1); assert.ok(records.some(r => r.event?.type === "model_failover")); }); test("process loss preserves the session and marks uncertain tools without replaying them", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (_, res, count) => { if (count === 1) sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "uncertain", type: "function", function: { name: "echo", arguments: '{"text":"unknown"}' } }] }, "tool_calls"); else sse(res, { role: "assistant", content: "recovered" }, "stop"); }); const dir = await mkdtemp(join(tmpdir(), "csai-pi-crash-")); t.after(() => rm(dir, { recursive: true, force: true })); const worker = spawn(process.execPath, [workerPath], { stdio: ["pipe", "pipe", "ignore"], env: fixtureEnv }); t.after(() => worker.kill()); const ended = once(worker, "exit"); const reader = new RecordReader(); worker.stdout.on("data", chunk => { for (const r of reader.push(chunk)) { if (r.type === "ready") worker.stdin.write(JSON.stringify({ type: "run", version: 1, request: request(fixture.url, dir) }) + "\n"); if (r.type === "tool_call") worker.kill("SIGKILL"); } }); await ended; const { result } = await invoke(t, { ...request(fixture.url, dir), runId: "after-crash", message: "Inspect the prior result before continuing" }); assert.equal(result.status, "completed", result.error); assert.equal(fixture.requests.length, 2); assert.ok(fixture.requests[1].messages.some(m => m.role === "tool" && /effects are unknown/.test(m.content))); }); test("native tool search loads a deferred host tool without exposing the full catalog", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (body, res, count) => { const names = body.tools.map(t => t.function.name); if (count === 1) { assert.deepEqual(names, ["tool_search"]); sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "search-1", type: "function", function: { name: "tool_search", arguments: '{"query":"echo","limit":1}' } }] }, "tool_calls"); } else if (count === 2) { assert.ok(names.includes("echo"), JSON.stringify(body.messages)); sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "echo-1", type: "function", function: { name: "echo", arguments: '{"text":"found"}' } }] }, "tool_calls"); } else sse(res, { role: "assistant", content: "discovery verified" }, "stop"); }); const req = request(fixture.url); req.tools.push(...Array.from({ length: 45 }, (_, i) => ({ name: "unrelated_" + i, description: "Unrelated operation", parameters: { type: "object", properties: {} } }))); let hostCalls = 0; const { result } = await invoke(t, { ...req, toolSearch: true }, (r, send) => { if (r.type === "tool_call") { hostCalls++; assert.equal(r.call.name, "echo"); send({ type: "tool_result", id: r.call.id, result: { content: "found" } }); } }); assert.equal(result.status, "completed", result.error); assert.equal(result.response, "discovery verified"); assert.equal(hostCalls, 1); }); test("economy compacts persisted tool JSON while preserving reasoning and original session evidence", { timeout: 30000 }, async t => { const raw = '{\n "id": 9007199254740993,\n "evidence": "keep spaces\\n"\n}'; const fixture = await startFixture(t, (_, res, count) => { if (count === 1) sse(res, { role: "assistant", reasoning_content: "inspect fixture", tool_calls: [{ index: 0, id: "inspect", type: "function", function: { name: "echo", arguments: '{"text":"fixture"}' } }] }, "tool_calls"); else sse(res, { role: "assistant", content: "evidence inspected" }, "stop"); }); const dir = await mkdtemp(join(tmpdir(), "csai-pi-economy-")); t.after(() => rm(dir, { recursive: true, force: true })); const req = request(fixture.url, dir); req.tools.push(...Array.from({ length: 30 }, (_, i) => ({ name: "old_unused_" + i, description: "Unused fixture operation", parameters: { type: "object", properties: {} } }))); req.model.thinking = "high"; req.model.compat = { thinkingFormat: "deepseek", requiresReasoningContentOnAssistantMessages: true }; req.model.extraFields = { thinking: { type: "enabled" }, reasoning_effort: "high" }; const first = await invoke(t, req, (r, send) => { if (r.type === "tool_call") send({ type: "tool_result", id: r.call.id, result: { content: raw } }); }); assert.equal(first.result.status, "completed", first.result.error); assert.equal(fixture.requests[1].messages.find(m => m.role === "tool").content, raw); req.model.compactToolJSON = true; const resumed = await invoke(t, { ...req, toolSearch: true, alwaysVisibleTools: ["echo"], runId: "economy-resume", message: "Continue" }); assert.equal(resumed.result.status, "completed", resumed.result.error); const body = fixture.requests[2]; assert.equal(fixture.requests[0].tools.length, 31); assert.deepEqual(body.tools.map(t => t.function.name).sort(), ["echo", "tool_search"]); assert.equal(body.messages.find(m => m.role === "tool").content, '{"id":9007199254740993,"evidence":"keep spaces\\n"}'); assert.ok(body.messages.some(m => m.reasoning_content === "inspect fixture")); assert.equal(body.reasoning_effort, "high"); assert.equal(resumed.result.history.find(m => m.role === "tool").content, raw); const entries = (await readFile(first.result.sessionFile, "utf8")).trim().split("\n").map(line => JSON.parse(line)); assert.ok(entries.some(e => e.message?.role === "toolResult" && e.message.content.some(b => b.text === raw))); }); 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); }); test('assessment uses native settle continuation and persists typed checkpoints', { timeout: 30000 }, async t => { const dir = await mkdtemp(join(tmpdir(), 'csai-assessment-native-')); t.after(() => rm(dir, { recursive: true, force: true })); const fixture = await startFixture(t, (body, res, count) => { if (count === 1) sse(res, { role: 'assistant', content: 'I have more work to record.' }, 'stop'); else { assert.ok(JSON.stringify(body.messages).includes('has not submitted')); sse(res, { role: 'assistant', tool_calls: [{ index: 0, id: 'result', type: 'function', function: { name: 'assessment_result', arguments: '{"status":"blocked","summary":"fixture complete"}' } }] }, 'tool_calls'); } }); const req = request(fixture.url, dir); req.tools = [{ name: 'assessment_result', description: 'Submit result', parameters: {type:'object',properties:{status:{type:'string'},summary:{type:'string'}},required:['status','summary']}, outputSchema: {type:'object',properties:{saved:{type:'boolean'}},required:['saved']}, exposure:'direct', namespace:'assessment', annotations:{readOnlyHint:false} }]; req.nativeWorkflow = { completionTool:'assessment_result', checkpointTool:'assessment_checkpoint', context:'Goal and current evidence: fixture only' }; const { result, records } = await invoke(t, req, (r, send) => { if (r.type === 'tool_call') send({type:'tool_result',id:r.call.id,result:{content:'fixture complete',structuredContent:{saved:true},terminate:true}}); }); assert.equal(result.status,'completed',result.error); assert.equal(fixture.requests.length,2); const entries = (await readFile(result.sessionFile,'utf8')).trim().split('\n').map(JSON.parse); assert.ok(entries.some(e => e.type === 'custom' && e.customType === 'assessment-checkpoint' && e.data.data.saved === true)); assert.ok(entries.some(e => e.type === 'message' && e.message.role === 'toolResult' && e.message.details?.structuredContent?.saved === true)); assert.equal(records.filter(r=>r.event?.type==='agent_settled').length,1); assert.ok(records.some(r=>r.event?.type==='session_metrics' && r.event.data.sessionId)); }); test('assessment segment yields at a native turn boundary and resumes the same session', { timeout:30000 }, async t => { const dir=await mkdtemp(join(tmpdir(),'csai-assessment-segment-'));t.after(()=>rm(dir,{recursive:true,force:true})); const fixture=await startFixture(t,(body,res,count)=>{ if(count===1) sse(res,{role:'assistant',tool_calls:[{index:0,id:'work',type:'function',function:{name:'echo',arguments:'{"text":"first segment evidence"}'}}]},'tool_calls'); else {assert.ok(body.messages.some(m=>m.role==='tool'&&m.content.includes('first segment evidence')));sse(res,{role:'assistant',tool_calls:[{index:0,id:'finish',type:'function',function:{name:'assessment_result',arguments:'{}'}}]},'tool_calls');} }); const req=request(fixture.url,dir);req.maxTurns=1;req.nativeWorkflow={completionTool:'assessment_result',context:'Same persistent assessment step'};req.tools.push({name:'assessment_result',description:'Finish',parameters:{type:'object',properties:{}}}); const host=(r,send)=>{if(r.type==='tool_call')send({type:'tool_result',id:r.call.id,result:{content:r.call.name==='echo'?'first segment evidence':'verified',terminate:r.call.name==='assessment_result'}})}; const first=await invoke(t,req,host);assert.equal(first.result.status,'yielded',first.result.error);assert.equal(fixture.requests.length,1); const second=await invoke(t,{...req,runId:'next-segment'},host);assert.equal(second.result.status,'completed',second.result.error);assert.equal(first.result.sessionFile,second.result.sessionFile); }); test('assessment native skills disclose only configured metadata before file reads', {timeout:30000}, async t=>{ const dir=await mkdtemp(join(tmpdir(),'csai-assessment-skills-'));t.after(()=>rm(dir,{recursive:true,force:true})); await writeFile(join(dir,'SKILL.md'),'---\nname: fixture-skill\ndescription: Read isolated fixture evidence\n---\nPRIVATE_SKILL_BODY_ONLY_AFTER_READ\n'); const fixture=await startFixture(t,(body,res)=>{ const system=body.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n'); assert.match(system,/fixture-skill/);assert.match(system,/Read isolated fixture evidence/);assert.doesNotMatch(system,/PRIVATE_SKILL_BODY_ONLY_AFTER_READ/); sse(res,{role:'assistant',tool_calls:[{index:0,id:'finish',type:'function',function:{name:'assessment_result',arguments:'{}'}}]},'tool_calls'); }); const req=request(fixture.url);req.nativeWorkflow={completionTool:'assessment_result',skillPaths:[dir]};req.tools=[{name:'assessment_result',description:'Finish',parameters:{type:'object',properties:{}}}]; const {result}=await invoke(t,req,(r,send)=>{if(r.type==='tool_call')send({type:'tool_result',id:r.call.id,result:{content:'done',terminate:true}})}); assert.equal(result.status,'completed',result.error); }); test('assessment refuses to resume missing native history before contacting the model', {timeout:30000},async t=>{ const dir=await mkdtemp(join(tmpdir(),'csai-assessment-missing-'));t.after(()=>rm(dir,{recursive:true,force:true})); const fixture=await startFixture(t,(_,res)=>{res.writeHead(500);res.end('should not call');}); const req=request(fixture.url,dir);req.nativeWorkflow={completionTool:'assessment_result',resumeRequired:true}; const {result}=await invoke(t,req);assert.equal(result.status,'failed');assert.match(result.error,/Saved Pi session is missing/);assert.equal(fixture.requests.length,0); }); test('assessment repairs the host-receipt / Pi-transcript crash gap without replay', {timeout:30000},async t=>{ const dir=await mkdtemp(join(tmpdir(),'csai-assessment-receipt-gap-'));t.after(()=>rm(dir,{recursive:true,force:true})); const fixture=await startFixture(t,(body,res,count)=>{ if(count===1){sse(res,{role:'assistant',tool_calls:[{index:0,id:'reused-provider-id',type:'function',function:{name:'echo',arguments:'{"text":"fixture"}'}}]},'tool_calls');return;} const output=JSON.stringify(body.messages); assert.match(output,/durable-success/);assert.doesNotMatch(output,/effects are unknown/); sse(res,{role:'assistant',tool_calls:[{index:0,id:'finish',type:'function',function:{name:'assessment_result',arguments:'{}'}}]},'tool_calls'); }); const req=request(fixture.url,dir);req.nativeWorkflow={completionTool:'assessment_result'};req.tools.push({name:'assessment_result',description:'Finish',parameters:{type:'object',properties:{}}}); const worker=spawn(process.execPath,[workerPath],{stdio:['pipe','pipe','pipe'],env:fixtureEnv}); t.after(()=>worker.kill());const exited=once(worker,'exit');const reader=new RecordReader();let call; worker.stdout.on('data',chunk=>{for(const r of reader.push(chunk)){if(r.type==='ready')worker.stdin.write(JSON.stringify({type:'run',version:1,request:req})+'\n');if(r.type==='tool_call'){call=r.call;worker.kill('SIGKILL');}}}); await exited;assert.ok(call?.sessionEntryId,'missing native assistant entry identity'); let repeated=0; const {result}=await invoke(t,{...req,runId:'after-gap',nativeWorkflow:{...req.nativeWorkflow,resumeRequired:true,receipts:[{sessionEntryId:call.sessionEntryId,providerId:call.providerId,name:call.name,content:'durable-success',executionId:'execution-receipt',isError:false}]}},(r,send)=>{ if(r.type==='tool_call'){if(r.call.name==='echo')repeated++;send({type:'tool_result',id:r.call.id,result:{content:'verified existing evidence',terminate:true}});} }); assert.equal(result.status,'completed',result.error);assert.equal(repeated,0); const entries=(await readFile(result.sessionFile,'utf8')).trim().split('\n').map(JSON.parse); assert.ok(entries.some(e=>e.message?.role==='toolResult'&&e.message.details?.recovered===true&&e.message.details.executionId==='execution-receipt')); }); test("truncated assistant text stays in history and the resumed session", { timeout: 30000 }, async t => { const dir = await mkdtemp(join(tmpdir(), "csai-pi-truncated-")); t.after(() => rm(dir, { recursive: true, force: true })); const fixture = await startFixture(t, (_body, res, count) => { if (count === 1) sse(res, { role: "assistant", content: "Alpha-" }, "length"); else sse(res, { role: "assistant", content: "Beta." }, "stop"); }); const first = await invoke(t, { ...request(fixture.url, dir), tools: [], message: "Write the notes." }); assert.equal(first.result.status, "output_truncated", first.result.error); assert.equal(first.result.response, "Alpha-"); assert.ok(first.result.history.some(message => message.role === "assistant" && message.content === "Alpha-"), JSON.stringify(first.result.history)); const second = await invoke(t, { ...request(fixture.url, dir), tools: [], runId: "run-2", message: "Continue from the truncated sentence." }); assert.equal(second.result.status, "completed", second.result.error); assert.ok(JSON.stringify(fixture.requests[1].messages).includes("Alpha-"), JSON.stringify(fixture.requests[1].messages)); }); test("assessment segment wrapup steers writeback before yielding", { timeout: 30000 }, async t => { const dir = await mkdtemp(join(tmpdir(), "csai-assessment-wrapup-")); t.after(() => rm(dir, { recursive: true, force: true })); const fixture = await startFixture(t, (body, res, count) => { if (count === 1) { sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "t1", type: "function", function: { name: "echo", arguments: '{"text":"obs-1"}' } }] }, "tool_calls"); } else if (count === 2) { sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "t2", type: "function", function: { name: "echo", arguments: '{"text":"obs-2"}' } }] }, "tool_calls"); } else { assert.ok(JSON.stringify(body.messages).includes("WRAPUP_WRITEBACK_NOW"), "missing wrapup prompt in steered turn"); sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "finish", type: "function", function: { name: "assessment_result", arguments: "{}" } }] }, "tool_calls"); } }); const req = request(fixture.url, dir); req.maxTurns = 2; req.nativeWorkflow = { completionTool: "assessment_result", wrapupPrompt: "WRAPUP_WRITEBACK_NOW", wrapupTurns: 1, }; req.tools.push({ name: "assessment_result", description: "Finish", parameters: { type: "object", properties: {} } }); let sawWrapupEvent = false; const out = await invoke(t, req, (r, send) => { if (r.type === "event" && r.event?.type === "segment_wrapup_start") sawWrapupEvent = true; if (r.type === "tool_call") { send({ type: "tool_result", id: r.call.id, result: { content: "ok", terminate: r.call.name === "assessment_result" } }); } }); assert.equal(out.result.status, "completed", out.result.error); assert.equal(sawWrapupEvent, true, "expected segment_wrapup_start event"); assert.equal(fixture.requests.length, 3); }); test('ordinary sessions disclose configured skills through native loadSkills', { timeout: 30000 }, async t => { const dir = await mkdtemp(join(tmpdir(), 'csai-chat-skills-')); t.after(() => rm(dir, { recursive: true, force: true })); await writeFile(join(dir, 'SKILL.md'), '---\nname: chat-fixture-skill\ndescription: Read chat fixture evidence\n---\nCHAT_PRIVATE_SKILL_BODY_ONLY_AFTER_READ\n'); const fixture = await startFixture(t, (body, res) => { const system = body.messages.filter(m => m.role === 'system' || m.role === 'developer').map(m => m.content).join('\n'); assert.match(system, /chat-fixture-skill/); assert.match(system, /Read chat fixture evidence/); assert.doesNotMatch(system, /CHAT_PRIVATE_SKILL_BODY_ONLY_AFTER_READ/); sse(res, { role: 'assistant', content: 'skill disclosed' }, 'stop'); }); const req = { ...request(fixture.url), tools: [], skillPaths: [dir] }; const { result } = await invoke(t, req); assert.equal(result.status, 'completed', result.error); assert.equal(result.response, 'skill disclosed'); // Skill metadata is stable and must stay ahead of per-run context for prompt caching. const dynamic = '\n\n[[CSAI_DATA:fixture field=project_blackboard]]\nRun specific notes\n'; const split = await invoke(t, { ...req, runId: 'run-2', skillToolName: 'custom_skill_loader', tools: [ { name: 'read_file', description: 'read', parameters: { type: 'object', properties: {} } }, { name: 'custom_skill_loader', description: 'skill', parameters: { type: 'object', properties: {} } }, ], systemPromptDynamic: dynamic, }); assert.equal(split.result.status, 'completed', split.result.error); const system = fixture.requests.at(-1).messages.filter(m => m.role === 'system' || m.role === 'developer').map(m => m.content).join('\n'); assert.ok(system.includes('Load matching skill files with custom_skill_loader.'), system); assert.ok(system.includes('Run specific notes')); assert.ok(system.indexOf('chat-fixture-skill') < system.indexOf('Run specific notes'), system); }); test('host tool images reach vision models natively and stay out of host events', { timeout: 30000 }, async t => { const image = { mimeType: 'image/png', data: 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKElEQVR4nO3NsQ0AAAzCMP5/un0CNkuZ41wybXsHAAAAAAAAAAAAxR4yw/wuPL6QkAAAAABJRU5ErkJggg==', }; for (const capability of [true, false]) { const fixture = await startFixture(t, (body, res, count) => { if (count === 1) { sse(res, { role: 'assistant', tool_calls: [{ index: 0, id: 'shot', type: 'function', function: { name: 'echo', arguments: '{"text":"capture"}' } }] }, 'tool_calls'); return; } const wire = JSON.stringify(body.messages); assert.equal(wire.includes(image.data), capability, wire); if (capability) { assert.ok(body.messages.some(m => m.role === 'user' && Array.isArray(m.content) && m.content.some(b => b.type === 'image_url')), wire); } sse(res, { role: 'assistant', content: 'image inspected' }, 'stop'); }); const req = request(fixture.url); req.model.imageInput = capability; const { result, records } = await invoke(t, req, (r, send) => { if (r.type === 'tool_call') send({ type: 'tool_result', id: r.call.id, result: { content: 'captured', images: [image] } }); }); assert.equal(result.status, 'completed', result.error); assert.equal(result.response, 'image inspected'); assert.ok(!JSON.stringify(records).includes(image.data), 'host events carried raw image bytes'); assert.ok(!JSON.stringify(result.history).includes(image.data), 'exported history carried raw image bytes'); } }); test("codemode batches host tools in one sandboxed turn and keeps large intermediates out of the model", { timeout: 60000 }, async t => { const bulkA = "A".repeat(120000); const bulkB = "B".repeat(90000); const dir = await mkdtemp(join(tmpdir(), "csai-pi-codemode-")); t.after(() => rm(dir, { recursive: true, force: true })); const fixture = await startFixture(t, (body, res, count) => { if (count === 1) { assert.deepEqual(body.tools.map(tool => tool.function.name), ["echo", "codemode"]); const code = [ 'const [a, b] = await Promise.all([tools.echo({ text: "alpha" }), tools.echo({ text: "beta" })]);', 'store("cursor", { marker: "CURSOR-STATE-42", total: a.length + b.length });', 'return "filtered:" + (a.length + b.length);', ].join("\n"); sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "cm-1", type: "function", function: { name: "codemode", arguments: JSON.stringify({ code }) } }] }, "tool_calls"); } else if (count === 2) { const wire = JSON.stringify(body.messages); assert.ok(!wire.includes(bulkA) && !wire.includes(bulkB), "large intermediate tool output leaked into the model request"); assert.ok(wire.includes("filtered:" + (bulkA.length + bulkB.length)), wire); sse(res, { role: "assistant", content: "batch verified" }, "stop"); } else if (count === 3) { const code = 'const c = load("cursor"); return "loaded:" + c.marker + ":" + c.total;'; sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "cm-2", type: "function", function: { name: "codemode", arguments: JSON.stringify({ code }) } }] }, "tool_calls"); } else { const wire = JSON.stringify(body.messages); assert.ok(wire.includes("loaded:CURSOR-STATE-42:" + (bulkA.length + bulkB.length)), wire); assert.ok(!wire.includes(bulkA) && !wire.includes(bulkB), "resumed session leaked large intermediates"); sse(res, { role: "assistant", content: "resume verified" }, "stop"); } }); const hostCalls = []; const host = (r, send) => { if (r.type === "tool_call") { hostCalls.push(r.call.name); assert.equal(r.call.name, "echo"); send({ type: "tool_result", id: r.call.id, result: { content: r.call.arguments.text === "alpha" ? bulkA : bulkB } }); } }; const first = await invoke(t, { ...request(fixture.url, dir), codemode: true }, host); assert.equal(first.result.status, "completed", first.result.error); assert.equal(first.result.response, "batch verified"); assert.deepEqual(hostCalls, ["echo", "echo"]); const second = await invoke(t, { ...request(fixture.url, dir), runId: "codemode-resume", message: "Continue from stored state", codemode: true }, host); assert.equal(second.result.status, "completed", second.result.error); assert.equal(second.result.response, "resume verified"); assert.equal(fixture.requests.length, 4); assert.deepEqual(hostCalls, ["echo", "echo"]); }); test("codemode and tool search coexist without a tool list validation conflict", { timeout: 60000 }, async t => { const fixture = await startFixture(t, (body, res, count) => { const names = body.tools.map(tool => tool.function.name); if (count === 1) { assert.deepEqual(names, ["tool_search", "codemode"]); const code = 'const r = await tools.echo({ text: "deferred" }); return "search+" + r;'; sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "cm-search", type: "function", function: { name: "codemode", arguments: JSON.stringify({ code }) } }] }, "tool_calls"); } else { assert.ok(JSON.stringify(body.messages).includes("search+deferred")); sse(res, { role: "assistant", content: "coexistence verified" }, "stop"); } }); const req = request(fixture.url); req.tools.push(...Array.from({ length: 45 }, (_, i) => ({ name: "unrelated_" + i, description: "Unrelated operation", parameters: { type: "object", properties: {} } }))); let hostCalls = 0; const { result } = await invoke(t, { ...req, toolSearch: true, codemode: true, codemodeMode: "on", codemodeInlineBudget: 2000 }, (r, send) => { if (r.type === "tool_call") { hostCalls++; assert.equal(r.call.name, "echo"); send({ type: "tool_result", id: r.call.id, result: { content: "deferred" } }); } }); assert.equal(result.status, "completed", result.error); assert.equal(result.response, "coexistence verified"); assert.equal(hostCalls, 1); }); test("keepAlive worker serves sequential runs with isolated state and exits on stdin end", { timeout: 60000 }, async t => { const fixture = await startFixture(t, (body, res, count) => { if (count === 1) sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "e1", type: "function", function: { name: "echo", arguments: '{"text":"one"}' } }] }, "tool_calls"); else if (count === 2) sse(res, { role: "assistant", content: "first done" }, "stop"); else if (count === 3) { assert.deepEqual(body.tools.map(tool => tool.function.name), ["shout"]); assert.ok(!JSON.stringify(body.messages).includes("ECHO-ONE"), "run 2 leaked run 1 tool state"); sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "s1", type: "function", function: { name: "shout", arguments: '{"text":"two"}' } }] }, "tool_calls"); } else sse(res, { role: "assistant", content: "second done" }, "stop"); }); const worker = spawn(process.execPath, [workerPath], { stdio: ["pipe", "pipe", "pipe"], env: fixtureEnv }); t.after(() => worker.kill()); const exit = once(worker, "exit"); let stderr = ""; worker.stderr.on("data", c => stderr += c); const reader = new RecordReader(); const send = record => worker.stdin.write(JSON.stringify(record) + "\n"); const results = []; const hostCalls = []; const base = request(fixture.url); const run1 = { ...base, runId: "ka-1", message: "first" }; const run2 = { ...base, runId: "ka-2", message: "second", model: { ...base.model, id: "fixture-two" }, tools: [{ name: "shout", description: "Return text", parameters: { type: "object", properties: { text: { type: "string" } }, required: ["text"] } }] }; worker.stdout.on("data", chunk => { for (const r of reader.push(chunk)) { if (r.type === "ready") send({ type: "run", version: 1, keepAlive: true, request: run1 }); else if (r.type === "tool_call") { hostCalls.push(r.call.name); send({ type: "tool_result", id: r.call.id, result: { content: r.call.name === "echo" ? "ECHO-ONE" : "SHOUT-TWO" } }); } else if (r.type === "result") { results.push(r.result); if (results.length === 1) send({ type: "run", version: 1, keepAlive: true, request: run2 }); else worker.stdin.end(); } } }); const [code] = await exit; assert.equal(code, 0, stderr + JSON.stringify(results)); assert.equal(results.length, 2); assert.equal(results[0].status, "completed", results[0].error); assert.equal(results[0].response, "first done"); assert.equal(results[1].status, "completed", results[1].error); assert.equal(results[1].response, "second done"); assert.deepEqual(hostCalls, ["echo", "shout"]); assert.equal(fixture.requests.length, 4); }); test("pre-TLS connect classifier matches handshake ECONNRESET and excludes certificate errors", () => { const tlsReset = new TypeError("fetch failed", { cause: Object.assign(new Error("Client network socket disconnected before secure TLS connection was established"), { code: "ECONNRESET" }), }); assert.equal(isPreResponseConnectError(tlsReset), true); assert.equal(isPreResponseConnectError(Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:443"), { code: "ECONNREFUSED" })), true); assert.equal(isPreResponseConnectError(Object.assign(new Error("self-signed certificate in certificate chain"), { code: "SELF_SIGNED_CERT_IN_CHAIN" })), false); }); test("generateOnly retries transient socket resets and fails over to backup channel", { timeout: 30000 }, async t => { let primaryHits = 0; const primary = createServer((req, res) => { primaryHits++; req.socket.destroy(); void res; }); primary.listen(0, "127.0.0.1"); await once(primary, "listening"); t.after(() => { primary.closeAllConnections(); primary.close(); }); const backup = await startFixture(t, (_body, res) => sse(res, { role: "assistant", content: "single-shot recovered" }, "stop")); const req = { ...request("http://127.0.0.1:" + primary.address().port + "/v1"), generateOnly: true, tools: [], retryMax: 2, retryMaxDelayMs: 500, fallbackModels: [{ provider: "openai", id: "backup", baseUrl: backup.url, apiKey: "test-key", contextWindow: 32000, maxTokens: 1024, thinking: "off" }], }; const { result, records } = await invoke(t, req); assert.equal(result.status, "completed", result.error); assert.equal(result.response, "single-shot recovered"); assert.ok(primaryHits >= 1); assert.equal(backup.requests.length, 1); assert.ok(records.some(r => r.event?.type === "auto_retry_start")); assert.ok(records.some(r => r.event?.type === "model_failover")); }); test("proxy normalization covers ALL_PROXY, socks5h, schemeless host:port, and OS proxy parsers", () => { assert.equal(normalizeProxyUrl("socks5h://127.0.0.1:7890"), "socks5://127.0.0.1:7890"); assert.equal(normalizeProxyUrl("127.0.0.1:7890"), "http://127.0.0.1:7890"); const envResolved = resolveEnvProxySettings({ ALL_PROXY: "socks5h://127.0.0.1:7890" }); assert.equal(envResolved.httpsProxy, "socks5://127.0.0.1:7890"); assert.equal(envResolved.source, "env"); assert.equal(isLoopbackOrPrivateHost("localhost"), true); assert.equal(isLoopbackOrPrivateHost("192.168.1.10"), true); assert.equal(isLoopbackOrPrivateHost("api.openai.com"), false); const darwin = parseDarwinScutilProxy("{\n HTTPEnable : 1\n HTTPPort : 7890\n HTTPProxy : 127.0.0.1\n HTTPSEnable : 1\n HTTPSPort : 7890\n HTTPSProxy : 127.0.0.1\n}\n"); assert.equal(darwin?.httpsProxy, "http://127.0.0.1:7890"); const win = parseWindowsRegProxy("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\n ProxyEnable REG_DWORD 0x1\n ProxyServer REG_SZ 127.0.0.1:7890\n"); assert.equal(win?.httpsProxy, "http://127.0.0.1:7890"); }); test("TLS handshake keeps single-packet ClientHello, falls back to IPv4 on IPv6 TLS reset, and supports ALL_PROXY socks5h", { timeout: 45000 }, async t => { const certDir = await mkdtemp(join(tmpdir(), "csai-pi-tls-cert-")); t.after(() => rm(certDir, { recursive: true, force: true })); const keyPath = join(certDir, "key.pem"); const certPath = join(certDir, "cert.pem"); execFileSync("openssl", [ "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-keyout", keyPath, "-out", certPath, "-days", "1", "-nodes", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", ], { stdio: "ignore" }); const key = await readFile(keyPath); const cert = await readFile(certPath); const httpsOrigin = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "tls-verified" }, "stop")); httpsOrigin.listen(0, "127.0.0.1"); await once(httpsOrigin, "listening"); t.after(() => { httpsOrigin.closeAllConnections(); httpsOrigin.close(); }); const originPort = httpsOrigin.address().port; // 1) Middlebox that sends TCP RST if ClientHello exceeds 600 bytes (rejects 1.6KB PQ ClientHello). let clientHelloBytes = 0; const middlebox = createTcpServer(client => { client.once("data", firstChunk => { clientHelloBytes = firstChunk.length; if (firstChunk.length > 600) { client.resetAndDestroy(); return; } const upstream = connect(originPort, "127.0.0.1", () => { upstream.write(firstChunk); client.pipe(upstream).pipe(client); }); client.on("error", () => upstream.destroy()); upstream.on("error", () => client.destroy()); }); }); middlebox.listen(0, "127.0.0.1"); await once(middlebox, "listening"); t.after(() => middlebox.close()); const tlsEnv = { ...fixtureEnv, NODE_EXTRA_CA_CERTS: certPath, NO_PROXY: "localhost,127.0.0.1", no_proxy: "localhost,127.0.0.1" }; const compactRun = await invoke(t, { ...request(`https://localhost:${middlebox.address().port}/v1`), generateOnly: true, tools: [] }, undefined, tlsEnv); assert.equal(compactRun.result.status, "completed", compactRun.result.error); assert.equal(compactRun.result.response, "tls-verified"); assert.ok(clientHelloBytes > 0 && clientHelloBytes <= 600, `expected compact ClientHello <=600B, got ${clientHelloBytes}B`); // 2) Dual-stack localhost where IPv6 (::1) accepts TCP then resets TLS, while IPv4 (127.0.0.1) serves HTTPS. const v6Reset = createTcpServer(sock => sock.once("data", () => sock.resetAndDestroy())); let ipv6Bound = true; try { v6Reset.listen(0, "::1"); await once(v6Reset, "listening"); } catch { ipv6Bound = false; } if (ipv6Bound) { t.after(() => v6Reset.close()); const dualPort = v6Reset.address().port; const v4Https = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "ipv4-fallback-ok" }, "stop")); v4Https.listen(dualPort, "127.0.0.1"); await once(v4Https, "listening"); t.after(() => { v4Https.closeAllConnections(); v4Https.close(); }); const dualRun = await invoke(t, { ...request(`https://localhost:${dualPort}/v1`), generateOnly: true, tools: [] }, undefined, tlsEnv); assert.equal(dualRun.result.status, "completed", dualRun.result.error); assert.equal(dualRun.result.response, "ipv4-fallback-ok"); } // 3) Minimal SOCKS5 server exercised via ALL_PROXY=socks5h://127.0.0.1: over HTTPS. let socksConnections = 0; const socksServer = createTcpServer(sock => { socksConnections++; sock.once("data", greeting => { assert.equal(greeting[0], 0x05); sock.write(Buffer.from([0x05, 0x00])); sock.once("data", cmd => { assert.equal(cmd[0], 0x05); assert.equal(cmd[1], 0x01); // CONNECT const atyp = cmd[3]; let offset = 4; if (atyp === 0x01) offset += 4; else if (atyp === 0x03) offset += 1 + cmd[4]; else if (atyp === 0x04) offset += 16; const targetPort = cmd.readUInt16BE(offset); const upstream = connect(targetPort, "127.0.0.1", () => { sock.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0])); sock.pipe(upstream).pipe(sock); }); sock.on("error", () => upstream.destroy()); upstream.on("error", () => sock.destroy()); }); }); }); socksServer.listen(0, "127.0.0.1"); await once(socksServer, "listening"); t.after(() => socksServer.close()); const socksEnv = { ...process.env, NODE_EXTRA_CA_CERTS: certPath, HTTP_PROXY: "", http_proxy: "", HTTPS_PROXY: "", https_proxy: "", ALL_PROXY: `socks5h://127.0.0.1:${socksServer.address().port}`, all_proxy: `socks5h://127.0.0.1:${socksServer.address().port}`, NO_PROXY: "", no_proxy: "", }; const socksRun = await invoke(t, { ...request(`https://localhost:${originPort}/v1`), generateOnly: true, tools: [] }, undefined, socksEnv); assert.equal(socksRun.result.status, "completed", socksRun.result.error); assert.equal(socksRun.result.response, "tls-verified"); assert.ok(socksConnections >= 1); }); test("domestic DeepSeek endpoint recovers via clean DNS + direct fallback when local proxy is closed", { timeout: 45000 }, async t => { assert.equal(isFakeIpAddress("198.18.0.45"), true); assert.equal(isFakeIpAddress("198.19.255.1"), true); assert.equal(isFakeIpAddress("8.8.8.8"), false); assert.equal(isDomesticModelHost("api.deepseek.com"), true); assert.equal(isDomesticModelHost("open.bigmodel.cn"), true); assert.equal(isDomesticModelHost("api.openai.com"), false); assert.equal(isLocalClientProxy({ httpsProxy: "http://192.168.33.1:7890", source: "env" }), true); assert.equal(isLocalClientProxy({ httpsProxy: "http://proxy.corp.example.com:8080", source: "env" }), false); const certDir = await mkdtemp(join(tmpdir(), "csai-pi-deepseek-cert-")); t.after(() => rm(certDir, { recursive: true, force: true })); const keyPath = join(certDir, "key.pem"); const certPath = join(certDir, "cert.pem"); execFileSync("openssl", [ "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-keyout", keyPath, "-out", certPath, "-days", "1", "-nodes", "-subj", "/CN=api.deepseek.com", "-addext", "subjectAltName=DNS:api.deepseek.com,IP:127.0.0.1", ], { stdio: "ignore" }); const key = await readFile(keyPath); const cert = await readFile(certPath); const deepseekOrigin = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "deepseek-direct-ok" }, "stop")); deepseekOrigin.listen(0, "127.0.0.1"); await once(deepseekOrigin, "listening"); t.after(() => { deepseekOrigin.closeAllConnections(); deepseekOrigin.close(); }); // Local UDP DNS server answering A queries with 127.0.0.1. let dnsQueries = 0; const udpDns = dgram.createSocket("udp4"); udpDns.on("message", (msg, rinfo) => { dnsQueries++; const id = msg.subarray(0, 2); let qEnd = 12; while (qEnd < msg.length && msg[qEnd] !== 0) qEnd += 1 + msg[qEnd]; qEnd += 5; // null label + QTYPE(2) + QCLASS(2) const question = msg.subarray(12, qEnd); const header = Buffer.from([ id[0], id[1], 0x81, 0x80, // QR=1, RD=1, RA=1, NOERROR 0x00, 0x01, // QDCOUNT=1 0x00, 0x01, // ANCOUNT=1 0x00, 0x00, 0x00, 0x00, ]); const answer = Buffer.from([ 0xc0, 0x0c, // pointer to QNAME 0x00, 0x01, // TYPE A 0x00, 0x01, // CLASS IN 0x00, 0x00, 0x00, 0x3c, // TTL 60s 0x00, 0x04, // RDLENGTH 4 127, 0, 0, 1, ]); udpDns.send(Buffer.concat([header, question, answer]), rinfo.port, rinfo.address); }); udpDns.bind(0, "127.0.0.1"); await once(udpDns, "listening"); t.after(() => udpDns.close()); // Closed local proxy port (bind then immediately close so connect gets ECONNREFUSED). const closedProxyProbe = createTcpServer(); closedProxyProbe.listen(0, "127.0.0.1"); await once(closedProxyProbe, "listening"); const deadProxyPort = closedProxyProbe.address().port; await new Promise(r => closedProxyProbe.close(r)); const env = { ...process.env, NODE_EXTRA_CA_CERTS: certPath, HTTP_PROXY: `http://127.0.0.1:${deadProxyPort}`, http_proxy: `http://127.0.0.1:${deadProxyPort}`, HTTPS_PROXY: `http://127.0.0.1:${deadProxyPort}`, https_proxy: `http://127.0.0.1:${deadProxyPort}`, NO_PROXY: "", no_proxy: "", CYBERSTRIKE_CLEAN_DNS_SERVERS: `127.0.0.1:${udpDns.address().port}`, }; const { result } = await invoke( t, { ...request(`https://api.deepseek.com:${deepseekOrigin.address().port}/v1`), generateOnly: true, tools: [] }, undefined, env, ); assert.equal(result.status, "completed", result.error); assert.equal(result.response, "deepseek-direct-ok"); assert.ok(dnsQueries >= 1); });