feat(ai-profiles): add plugin profile SDK and Cline demo (#342)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 16:30:49 +01:00
parent 2a3c582ec8
commit 8faa860676
25 changed files with 5755 additions and 2 deletions

View File

@ -0,0 +1,14 @@
import { fakeProvider } from "./fake-provider.mjs";
import { runAdapter } from "../../src/adapter.mjs";
globalThis.fetch = async () => { throw new Error("live network is forbidden in child QA"); };
const provider = fakeProvider({ text: process.argv[3] });
await runAdapter({
input: process.stdin, output: process.stdout, storageRoot: process.argv[2],
fetch: async (...args) => {
const response = await provider.fetch(...args);
process.send?.({ kind: "providerCall", call: provider.calls.at(-1) });
return response;
},
});
process.disconnect?.();

View File

@ -0,0 +1,46 @@
import assert from "node:assert/strict";
export const endpoint = "https://fixture.invalid/v1";
export function fakeProvider({ text = "hello from fixture", holdFirst = false, toolCall = false, advertisedToolNames = false, forbiddenCredential } = {}) {
const calls = [];
const attempts = [];
const failures = [];
let holding = false;
let entered;
const held = new Promise((resolve) => { entered = resolve; });
const fetch = async (input, init = {}) => {
const url = typeof input === "string" || input instanceof URL ? String(input) : input.url;
attempts.push({ url, bodyType: typeof init.body });
try {
assert.equal(url, `${endpoint}/chat/completions`, "unexpected provider/metadata network request");
const body = JSON.parse(init.body ?? await input.clone().text());
const headers = new Headers(init.headers ?? input.headers);
assert.ok(!forbiddenCredential || ![...headers.values()].some((value) => value.includes(forbiddenCredential)), "inherited credential reached provider headers");
calls.push({ url, body });
if (holdFirst && calls.length === 1) {
holding = true;
const signal = init.signal ?? input.signal;
entered();
return await new Promise((_, reject) => {
const aborted = () => reject(new DOMException("fixture abort", "AbortError"));
if (signal?.aborted) aborted(); else signal?.addEventListener("abort", aborted, { once: true });
});
}
const toolNames = advertisedToolNames ? body.tools.map((tool) => tool.function.name) : ["host_echo", "host_echo"];
const choices = toolCall && calls.length === 1 ? [
{ delta: { role: "assistant", tool_calls: [
{ index: 0, id: "fixture-tool-1", type: "function", function: { name: toolNames[0], arguments: '{"value":"fixture argument"}' } },
{ index: 1, id: "fixture-tool-2", type: "function", function: { name: toolNames[1] ?? toolNames[0], arguments: '{"value":"second argument"}' } },
] }, finish_reason: null },
{ delta: {}, finish_reason: "tool_calls" },
] : [
{ delta: { role: "assistant", content: text.slice(0, 6) }, finish_reason: null },
{ delta: { content: text.slice(6) }, finish_reason: null },
{ delta: {}, finish_reason: "stop" },
];
const chunks = choices.map((choice) => `data: ${JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: 0, model: body.model, choices: [{ index: 0, ...choice }] })}\n\n`).join("") + "data: [DONE]\n\n";
return new Response(chunks, { status: 200, headers: { "content-type": "text/event-stream" } });
} catch (error) { failures.push({ name: error.name, message: error.message }); throw error; }
};
return { calls, fetch, held, attempts, failures, get holding() { return holding; } };
}

View File

@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { PassThrough } from "node:stream";
import { setTimeout } from "node:timers/promises";
import { endpoint } from "./fake-provider.mjs";
import { fork } from "node:child_process";
export const profileId = "35000000-0000-4000-8000-000000000001";
export const hostSessionId = "35000000-0000-4000-8000-000000000002";
export const config = { model: "gpt-4.1-mini", endpoint };
export async function wire({ fetch, storageRoot, projectRoot, childText }) {
const { runAdapter } = await import("../../src/adapter.mjs");
assert.equal(typeof runAdapter, "function");
const child = childText === undefined ? undefined : fork(new URL("./adapter-child.mjs", import.meta.url), [storageRoot, childText], { stdio: ["pipe", "pipe", "pipe", "ipc"] });
const input = child?.stdin ?? new PassThrough();
const output = child?.stdout ?? new PassThrough();
const providerCalls = [];
child?.on("message", (message) => { if (message.kind === "providerCall") providerCalls.push(message.call); });
const frames = [];
let buffer = "";
let failure;
let id = 0;
output.setEncoding("utf8");
output.on("data", (chunk) => {
buffer += chunk;
while (buffer.includes("\n")) {
const end = buffer.indexOf("\n");
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
try { frames.push(JSON.parse(line)); } catch { failure = new Error("adapter emitted non-JSON stdout"); }
}
});
const done = child ? new Promise((resolve) => { child.on("error", (error) => { failure = error; resolve(); }); child.on("exit", (code) => { if (code !== 0) failure = new Error(`child adapter exit ${code}`); resolve(); }); }) : runAdapter({ input, output, fetch, storageRoot }).catch((error) => { failure = error; });
const write = (value) => input.write(`${JSON.stringify(value)}\n`);
const wait = async (predicate) => {
const expires = Date.now() + 8_000;
while (Date.now() < expires) {
if (failure) throw failure;
const found = frames.find(predicate);
if (found) return found;
const error = frames.find((frame) => frame.type === "event" && frame.name === "error");
if (error) throw new Error(`adapter error: ${JSON.stringify(error.data)}`);
await setTimeout(2);
}
throw new Error("adapter did not produce the expected public protocol frame");
};
const request = async (method, params) => {
const requestId = `qa-${++id}`;
write({ v: 1, type: "request", id: requestId, method, params });
return await wait((frame) => frame.type === "response" && frame.id === requestId);
};
return {
frames, done, write, raw: (chunk) => input.write(chunk), wait, request, providerCalls,
async initialize(version = 1) {
return await request("initialize", { protocolVersion: version,
adapterRef: { pluginId: "idea.cline-demo", adapterId: "cline-sdk", pluginVersion: "0.1.0" },
profileRef: { profileId, presetId: "cline-openai" } });
},
async open(sessionPlan = { kind: "none" }, tools = [], secrets = {}) {
return await request("open", { sessionId: hostSessionId, sessionPlan, config, secrets,
context: { content: "# Host context", relativePath: "AGENTS.md", projectRoot }, tools });
},
async close(sessionId = hostSessionId) {
const reply = await request("close", { sessionId });
input.end();
await Promise.race([done, setTimeout(5_000, undefined, { ref: false }).then(() => { throw new Error("close did not await SDK disposal"); })]);
if (failure) throw failure;
return reply;
},
async cleanup() { input.end(); await Promise.race([done, setTimeout(5_000, undefined, { ref: false })]); },
};
}

View File

@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import { readFile, stat } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const readJson = async (name) => JSON.parse(await readFile(resolve(root, name), "utf8"));
test("demo owns an exact SDK pin and reproducible lock", async () => {
const pkg = await readJson("package.json");
assert.equal(pkg.dependencies["@cline/sdk"], "0.2.0");
assert.equal(pkg.engines.node, "24.15.0");
const lock = await readJson("package-lock.json");
assert.equal(lock.packages[""].dependencies["@cline/sdk"], "0.2.0");
assert.equal(lock.packages["node_modules/@cline/sdk"].version, "0.2.0");
assert.equal(lock.packages["node_modules/@cline/core"].version, "0.2.0");
});
test("installable manifest declares public v1 adapter and a matching preset", async () => {
const manifest = await readJson("idea-plugin.json");
assert.equal(manifest.ideaPluginManifestVersion, 1);
assert.equal(manifest.id, "idea.cline-demo");
assert.equal(manifest.contributes.agentAdapters.length, 1);
const adapter = manifest.contributes.agentAdapters[0];
assert.equal(adapter.protocol, "idea-agent-session");
assert.equal(adapter.protocolVersion, 1);
assert.equal(adapter.command, "bin/idea-cline-adapter.mjs");
assert.equal(adapter.id, "cline-sdk");
assert.equal(adapter.configSchema.additionalProperties, false);
assert.deepEqual(adapter.configSchema.required, ["model", "endpoint"]);
assert.equal(adapter.configSchema.properties.apiKey.format, "secret");
assert.deepEqual(Object.keys(adapter.configSchema.properties).sort(), ["apiKey", "endpoint", "model"]);
assert.ok(manifest.contributes.aiProfiles.some((preset) => preset.adapterId === adapter.id));
assert.ok(manifest.contributes.aiProfiles.every((preset) => !("apiKey" in preset.configDefaults)));
assert.ok((await stat(resolve(root, manifest.main))).isFile());
});
test("public process entry and runtime modules are real package files", async () => {
const entry = await stat(resolve(root, "bin/idea-cline-adapter.mjs"));
assert.ok(entry.isFile());
assert.ok(entry.mode & 0o111, "host must be able to execute the adapter entry");
for (const name of ["src/adapter.mjs", "src/cline-runtime.mjs"]) {
assert.ok((await stat(resolve(root, name))).isFile());
}
});

View File

@ -0,0 +1,234 @@
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");
}
});