import assert from "node:assert/strict"; import { mkdtemp, mkdir, readFile, readdir, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, test } from "node:test"; import { fakeProvider } from "./helpers/fake-provider.mjs"; import { config, hostSessionId, profileId, wire } from "./helpers/wire.mjs"; const root = await mkdtemp(join(tmpdir(), "idea-cline350-")); const storageRoot = join(root, "sdk-state"); const projectRoot = join(root, "project"); await mkdir(projectRoot); after(() => rm(root, { recursive: true, force: true })); const originalFetch = globalThis.fetch; globalThis.fetch = async () => { throw new Error("live network is forbidden in Cline QA"); }; after(() => { globalThis.fetch = originalFetch; }); test("initialize/probe/close is local SDK readiness without provider call or conversation", { timeout: 20_000 }, async (t) => { const provider = fakeProvider(); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); const initialized = await bridge.initialize(); assert.equal(initialized.result.protocolVersion, 1); for (const cap of ["streaming", "resume", "cancel", "hostTools", "probe"]) assert.ok(initialized.result.capabilities.includes(cap)); const probe = await bridge.request("probe", { config, secrets: {} }); assert.equal(probe.result.ready, true); assert.match(probe.result.message, /local/i); assert.match(probe.result.message, /not tested/i); assert.equal(provider.calls.length, 0); const files = await readdir(storageRoot, { recursive: true }).catch((error) => error.code === "ENOENT" ? [] : Promise.reject(error)); assert.ok(files.every((name) => !String(name).includes("sessions/") && !String(name).endsWith("manifest.json")), "probe created SDK conversation artifacts"); assert.ok((await bridge.close(profileId)).result); }); test("real ClineCore open has no prompt; send streams one final with builtins disabled", { timeout: 20_000 }, async (t) => { const provider = fakeProvider(); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); const opened = await bridge.open(); assert.equal(opened.result.sessionId, hostSessionId); assert.ok(opened.result.conversationId); assert.equal(provider.calls.length, 0, "open must call interactive SDK start without a prompt"); const turnId = "qa-plain-turn"; const ack = await bridge.request("send", { sessionId: hostSessionId, turnId, prompt: "say hello" }); assert.equal(ack.result.accepted, true); let final; try { final = await bridge.wait((frame) => frame.type === "event" && frame.name === "final" && frame.data.turnId === turnId); } catch (error) { assert.fail(JSON.stringify({ message: error.message, frames: bridge.frames, attempts: provider.attempts, failures: provider.failures, requests: provider.calls.map(({ url, body }) => ({ url, model: body.model, stream: body.stream, tools: body.tools })) })); } assert.equal(final.data.sessionId, hostSessionId); assert.equal(final.data.content, "hello from fixture"); const events = bridge.frames.filter((frame) => frame.type === "event" && frame.data.turnId === turnId); assert.equal(events.filter((frame) => frame.name === "final").length, 1); assert.equal(events.filter((frame) => frame.name === "textDelta").map((frame) => frame.data.text).join(""), "hello from fixture"); assert.ok(bridge.frames.indexOf(ack) < bridge.frames.indexOf(events[0]), "stream output preceded accepted ACK"); assert.ok(provider.calls.length > 0, "test never reached the real SDK provider gateway"); for (const call of provider.calls) assert.equal(call.body.tools?.length ?? 0, 0, "native/MCP/spawn tools escaped the host allowlist"); await bridge.close(); }); test("cancel aborts an in-flight SDK fetch and keeps the session usable", { timeout: 20_000 }, async (t) => { const provider = fakeProvider({ holdFirst: true }); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); await bridge.open(); const turnId = "qa-cancel-turn"; assert.equal((await bridge.request("send", { sessionId: hostSessionId, turnId, prompt: "wait for cancel" })).result.accepted, true); await bridge.wait(() => provider.holding); const canceled = await bridge.request("cancel", { sessionId: hostSessionId, turnId }); assert.equal(canceled.result.outcome, "cancelled"); assert.equal((await bridge.request("cancel", { sessionId: hostSessionId, turnId })).result.outcome, "alreadyCancelled"); assert.equal(bridge.frames.filter((frame) => frame.type === "event" && frame.name === "final" && frame.data.turnId === turnId).length, 0); const next = "qa-after-cancel"; assert.equal((await bridge.request("send", { sessionId: hostSessionId, turnId: next, prompt: "after cancel" })).result.accepted, true); await bridge.wait((frame) => frame.type === "event" && frame.name === "final" && frame.data.turnId === next); await bridge.close(); }); test("only declared host tools execute through correlated public host/tool.call", { timeout: 20_000 }, async (t) => { const provider = fakeProvider({ toolCall: true }); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); const tools = [{ name: "host_echo", description: "Echo through the host", inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"], additionalProperties: false } }]; assert.ok((await bridge.open({ kind: "none" }, tools)).result); const turnId = "qa-tool-turn"; assert.equal((await bridge.request("send", { sessionId: hostSessionId, turnId, prompt: "use host_echo" })).result.accepted, true); const call = await bridge.wait((frame) => frame.type === "request" && frame.method === "host/tool.call"); assert.equal(call.params.sessionId, hostSessionId); assert.equal(call.params.turnId, turnId); assert.equal(call.params.name, "host_echo"); assert.deepEqual(call.params.arguments, { value: "fixture argument" }); assert.equal(typeof call.params.toolCallId, "string"); assert.ok(call.params.toolCallId.length > 0, "Rust host requires a nonempty toolCallId"); bridge.write({ v: 1, type: "response", id: call.id, result: { echoed: "fixture result" } }); const secondCall = await bridge.wait((frame) => frame.type === "request" && frame.method === "host/tool.call" && frame.id !== call.id); assert.equal(secondCall.params.sessionId, hostSessionId); assert.equal(secondCall.params.turnId, turnId); assert.equal(secondCall.params.name, "host_echo"); assert.deepEqual(secondCall.params.arguments, { value: "second argument" }); assert.equal(typeof secondCall.params.toolCallId, "string"); assert.ok(secondCall.params.toolCallId.length > 0); assert.notEqual(secondCall.params.toolCallId, call.params.toolCallId, "separate SDK calls must have distinct host correlation identities"); bridge.write({ v: 1, type: "response", id: secondCall.id, result: { echoed: "second result" } }); const final = await bridge.wait((frame) => frame.type === "event" && frame.name === "final" && frame.data.turnId === turnId); assert.equal(final.data.content, "hello from fixture"); for (const { body } of provider.calls) assert.deepEqual((body.tools ?? []).map((tool) => tool.function.name), ["host_echo"]); assert.ok(provider.calls.slice(1).some(({ body }) => body.messages.some((message) => message.role === "tool" && message.content.includes("fixture result"))), "host result was not returned to the real SDK provider turn"); await bridge.close(); }); test("cold adapter restart resumes the same real SDK history and refuses another project", { timeout: 30_000 }, async (t) => { const bridge = await wire({ childText: "persisted first answer", storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); const opened = await bridge.open({ kind: "assign", conversationId: "qa350-persisted-conversation" }); assert.equal(opened.result.conversationId, "qa350-persisted-conversation"); await bridge.request("send", { sessionId: hostSessionId, turnId: "qa-history-first", prompt: "remember first prompt" }); await bridge.wait((frame) => frame.type === "event" && frame.name === "final"); await bridge.close(); const resumed = await wire({ childText: "resumed answer", storageRoot, projectRoot }); t.after(() => resumed.cleanup()); await resumed.initialize(); assert.equal((await resumed.open({ kind: "resume", conversationId: opened.result.conversationId })).result.conversationId, opened.result.conversationId); await resumed.request("send", { sessionId: hostSessionId, turnId: "qa-history-next", prompt: "continue second prompt" }); await resumed.wait((frame) => frame.type === "event" && frame.name === "final"); const messages = resumed.providerCalls[0].body.messages; assert.ok(messages.some((message) => JSON.stringify(message.content).includes("remember first prompt"))); assert.ok(messages.some((message) => message.role === "assistant" && JSON.stringify(message.content).includes("persisted first answer"))); await resumed.close(); const otherProject = join(root, "other-project"); await mkdir(otherProject); const refusedProvider = fakeProvider(); const refused = await wire({ fetch: refusedProvider.fetch, storageRoot, projectRoot: otherProject }); t.after(() => refused.cleanup()); await refused.initialize(); assert.equal((await refused.open({ kind: "resume", conversationId: opened.result.conversationId })).error.code, "resumeNotFound"); assert.equal(refusedProvider.calls.length, 0); await refused.close(profileId); }); test("inherited provider credentials are isolated and restored without leaking into SDK files", { timeout: 20_000 }, async (t) => { const sentinel = "INERT-QA350-INHERITED-DO-NOT-USE"; const original = process.env.OPENAI_API_KEY; process.env.OPENAI_API_KEY = sentinel; t.after(() => { if (original === undefined) delete process.env.OPENAI_API_KEY; else process.env.OPENAI_API_KEY = original; }); const provider = fakeProvider({ forbiddenCredential: sentinel }); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); await bridge.open(); assert.equal(process.env.OPENAI_API_KEY, undefined); await bridge.request("send", { sessionId: hostSessionId, turnId: "qa-env-turn", prompt: "hello without inherited auth" }); await bridge.wait((frame) => frame.type === "event" && frame.name === "final"); await bridge.close(); assert.equal(process.env.OPENAI_API_KEY, sentinel); assert.ok(!JSON.stringify(bridge.frames).includes(sentinel)); for (const file of await readdir(storageRoot, { recursive: true, withFileTypes: true })) { if (file.isFile()) assert.ok(!(await readFile(join(file.parentPath, file.name))).includes(Buffer.from(sentinel)), "credential persisted in SDK storage"); } }); test("missing resume is explicit and concurrent adapters cannot mutate active isolation", { timeout: 20_000 }, async (t) => { const provider = fakeProvider(); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); const privateDir = process.env.CLINE_DIR; const second = await wire({ fetch: provider.fetch, storageRoot: join(root, "concurrent-must-not-own"), projectRoot }); t.after(() => second.cleanup()); await assert.rejects(second.initialize(), Error); assert.equal(process.env.CLINE_DIR, privateDir, "refused concurrent adapter mutated active SDK environment"); const missing = await bridge.open({ kind: "resume", conversationId: "qa350-no-such-conversation" }); assert.equal(missing.error.code, "resumeNotFound"); assert.equal(provider.calls.length, 0); await bridge.close(profileId); }); test("host tool aliases remain unique and preserve original names on callback", { timeout: 20_000 }, async (t) => { const provider = fakeProvider({ toolCall: true, advertisedToolNames: true }); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); const names = ["a.b", "idea_host_0"]; await bridge.open({ kind: "none" }, names.map((name) => ({ name, description: name, inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"] } }))); await bridge.request("send", { sessionId: hostSessionId, turnId: "qa-alias-turn", prompt: "call both tools" }); const first = await bridge.wait((frame) => frame.type === "request" && frame.method === "host/tool.call"); assert.equal(provider.calls[0].body.tools.length, 2); assert.equal(new Set(provider.calls[0].body.tools.map((tool) => tool.function.name)).size, 2, "SDK aliases collided before provider dispatch"); assert.ok(names.includes(first.params.name)); bridge.write({ v: 1, type: "response", id: first.id, result: { ok: true } }); const second = await bridge.wait((frame) => frame.type === "request" && frame.method === "host/tool.call" && frame.id !== first.id); assert.deepEqual([first.params.name, second.params.name].sort(), [...names].sort(), "SDK alias callback lost original host name"); bridge.write({ v: 1, type: "response", id: second.id, result: { ok: true } }); await bridge.wait((frame) => frame.type === "event" && frame.name === "final"); await bridge.close(); }); test("malformed UTF-8 rejects the stream and restores inherited environment", { timeout: 20_000 }, async (t) => { const sentinel = "INERT-QA350-FAILURE-RESTORE"; const original = process.env.OPENAI_API_KEY; process.env.OPENAI_API_KEY = sentinel; t.after(() => { if (original === undefined) delete process.env.OPENAI_API_KEY; else process.env.OPENAI_API_KEY = original; }); const provider = fakeProvider(); const bridge = await wire({ fetch: provider.fetch, storageRoot, projectRoot }); t.after(() => bridge.cleanup()); await bridge.initialize(); bridge.raw(Buffer.from([0xc3, 0x28, 0x0a])); await bridge.done; await assert.rejects(bridge.request("probe", { config, secrets: {} }), Error); assert.equal(process.env.OPENAI_API_KEY, sentinel); assert.equal(provider.calls.length, 0); assert.ok(!JSON.stringify(bridge.frames).includes(sentinel)); }); test("explicit inert API key is used only at the injected provider and never stored or echoed", { timeout: 20_000 }, async (t) => { const sentinel = "INERT-QA350-EXPLICIT-PROVIDER-KEY"; const provider = fakeProvider(); let authenticated = false; const bridge = await wire({ storageRoot, projectRoot, fetch: async (input, init = {}) => { const headers = new Headers(init.headers ?? input.headers); authenticated ||= headers.get("authorization") === `Bearer ${sentinel}`; return provider.fetch(input, init); } }); t.after(() => bridge.cleanup()); await bridge.initialize(); await bridge.open({ kind: "none" }, [], { apiKey: sentinel }); await bridge.request("send", { sessionId: hostSessionId, turnId: "qa-explicit-secret", prompt: "hello with explicitly supplied inert test auth" }); await bridge.wait((frame) => frame.type === "event" && frame.name === "final"); await bridge.close(); assert.ok(authenticated, "real provider gateway did not use explicitly supplied test auth"); assert.ok(!JSON.stringify(bridge.frames).includes(sentinel)); for (const file of await readdir(storageRoot, { recursive: true, withFileTypes: true })) { if (file.isFile()) assert.ok(!(await readFile(join(file.parentPath, file.name))).includes(Buffer.from(sentinel)), "explicit credential persisted in SDK storage"); } });