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 })]); },
};
}