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,262 @@
import { resolve } from "node:path";
import { randomUUID } from "node:crypto";
import { createClineRuntime } from "./cline-runtime.mjs";
import {
ADAPTER_ID, PLUGIN_ID, VERSION, CAPABILITIES, MAX_FRAME, MAX_VALUE,
AdapterError, bounded, invalid, object, string, validateConfig, verifyRuntime,
} from "./contract.mjs";
let running = false;
function isolateEnvironment(storageRoot) {
const original = new Map();
for (const name of Object.keys(process.env)) {
if (name.startsWith("CLINE_") || /API_KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTHORIZATION/i.test(name)) {
original.set(name, process.env[name]);
delete process.env[name];
}
}
for (const [name, value] of Object.entries({ CLINE_DIR: storageRoot, CLINE_DATA_DIR: resolve(storageRoot, "data") })) {
if (!original.has(name)) original.set(name, undefined);
process.env[name] = value;
}
return () => {
for (const [name, value] of original) {
if (value === undefined) delete process.env[name]; else process.env[name] = value;
}
};
}
/** Public JSONL boundary; fetch injection replaces only the provider transport. */
export async function runAdapter({ input, output, fetch = globalThis.fetch, storageRoot = resolve(process.cwd(), ".idea-cline") }) {
if (running) throw new AdapterError("notReady", "One Cline adapter per process is supported.");
running = true;
storageRoot = resolve(storageRoot);
const restoreEnvironment = isolateEnvironment(storageRoot);
let runtime, sessionId, active, initialized = false, opened = false, cancelled = false;
let stopping = false, shutdownPromise, writeQueue = Promise.resolve();
const pending = new Map();
const secrets = [];
const clean = (value) => {
let text = String(value);
for (const secret of secrets) text = text.split(secret).join("[redacted]");
return text;
};
const write = (frame) => {
bounded(frame, MAX_FRAME);
const line = JSON.stringify(frame) + "\n";
writeQueue = writeQueue.then(() => new Promise((resolve, reject) => {
output.write(line, (error) => error ? reject(error) : resolve());
}));
return writeQueue;
};
const result = (id, value) => {
bounded(value);
return write({ v: 1, type: "response", id, result: value });
};
const failure = (id, error) => write({
v: 1, type: "response", id,
error: { code: error instanceof AdapterError ? error.code : "internal",
message: error instanceof AdapterError ? error.message : "Cline adapter operation failed.", retryable: false },
});
const emit = (turn, name, data) => {
if (active !== turn || turn.cancelled || stopping) return Promise.resolve();
bounded(data);
return write({ v: 1, type: "event", name, data: { sessionId, turnId: turn.id, ...data } });
};
const cancelTools = () => {
for (const item of [...pending.values()]) item.reject(new AdapterError("cancelled", "Host tool call cancelled."));
};
async function cancelTurn() {
const turn = active;
if (!turn) return cancelled ? "alreadyCancelled" : "alreadyCompleted";
if (turn.cancelled) return "alreadyCancelled";
turn.cancelled = true;
cancelled = true;
cancelTools();
await runtime.cancel();
await turn.done;
return "cancelled";
}
async function shutdown() {
shutdownPromise ??= (async () => {
try {
if (active) await cancelTurn();
} finally {
cancelTools();
await runtime?.close();
}
})();
return shutdownPromise;
}
async function hostCall(name, args, { signal } = {}) {
const turn = active;
if (!turn || turn.cancelled || stopping || signal?.aborted) throw new AdapterError("cancelled", "No active host turn.");
bounded(args);
if (pending.size >= 16) throw new AdapterError("toolFailed", "Host tool budget exceeded.");
const id = `cline-tool-${randomUUID()}`;
return new Promise((resolveCall, rejectCall) => {
let timer;
const abort = () => settle(false, new AdapterError("cancelled", "Host tool call cancelled."));
const settle = (ok, value) => {
if (!pending.delete(id)) return;
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
(ok ? resolveCall : rejectCall)(value);
};
pending.set(id, { resolve: (value) => settle(true, value), reject: (error) => settle(false, error) });
timer = setTimeout(() => settle(false, new AdapterError("timeout", "Host tool deadline exceeded.")), 30_000);
signal?.addEventListener("abort", abort, { once: true });
write({ v: 1, type: "request", id, method: "host/tool.call",
params: { sessionId, turnId: turn.id, toolCallId: id, name, arguments: args } })
.catch(() => settle(false, new AdapterError("toolFailed", "Host tool transport failed.")));
});
}
function onCoreEvent(event) {
const turn = active;
if (!turn || turn.cancelled || stopping) return;
let sent;
if (event.type === "content_start" && event.contentType === "text" && event.text) {
sent = emit(turn, "textDelta", { text: clean(event.text) });
} else if (event.type === "content_start" && event.contentType === "tool") {
sent = emit(turn, "toolActivity", { label: clean(event.toolName ?? "Host tool") });
}
sent?.catch((error) => { turn.streamError = error; void runtime.cancel().catch(() => {}); });
}
async function handle(frame) {
const id = string(frame.id);
if (id.length > 1024) throw invalid();
const params = object(frame.params);
if (frame.method === "initialize") {
if (initialized || params.protocolVersion !== 1) throw new AdapterError("unsupportedVersion", "Only agent-session v1 is supported.");
const ref = object(params.adapterRef);
if (ref.pluginId !== PLUGIN_ID || ref.adapterId !== ADAPTER_ID || ref.pluginVersion !== VERSION) throw invalid();
string(object(params.profileRef).profileId);
await verifyRuntime();
initialized = true;
return result(id, { protocolVersion: 1, capabilities: CAPABILITIES });
}
if (!initialized) throw invalid();
if (frame.method === "probe") {
if (opened) throw invalid();
validateConfig(params.config, params.secrets);
await verifyRuntime();
return result(id, { ready: true, code: "ready", message: "Local runtime and configuration are ready; provider authentication/connectivity was not tested." });
}
if (frame.method === "open") {
if (opened) throw invalid();
validateConfig(params.config, params.secrets);
sessionId = string(params.sessionId);
if (params.secrets.apiKey) secrets.push(params.secrets.apiKey);
const tools = params.tools ?? [];
if (!Array.isArray(tools) || tools.length > 256) throw invalid();
const seen = new Set();
for (const tool of tools) {
object(tool); string(tool.name); object(tool.inputSchema);
if (tool.name.length > 1024 || seen.has(tool.name) || typeof tool.description !== "string") throw invalid();
seen.add(tool.name);
}
runtime = await createClineRuntime({ fetch, storageRoot, hostTools: { tools, call: hostCall } });
let conversationId;
try {
conversationId = await runtime.open({ ...params, context: object(params.context), onEvent: onCoreEvent });
} catch (error) {
try { await runtime.close(); } finally { runtime = undefined; }
throw error;
}
if (secrets.some((secret) => conversationId.includes(secret))) throw invalid();
opened = true;
return result(id, { sessionId, conversationId });
}
if (frame.method === "close") {
if (opened && params.sessionId !== sessionId) throw invalid();
stopping = true;
await shutdown();
await result(id, {});
return "closed";
}
if (!opened || params.sessionId !== sessionId) throw invalid();
if (frame.method === "cancel") {
if (active && params.turnId !== undefined && params.turnId !== active.id) throw invalid();
return result(id, { outcome: await cancelTurn() });
}
if (frame.method === "send") {
if (active) throw new AdapterError("notReady", "A Cline turn is already active.");
const prompt = string(params.prompt);
bounded(prompt);
const turn = { id: string(params.turnId), cancelled: false };
if (turn.id.length > 1024) throw invalid();
cancelled = false;
active = turn;
await result(id, { accepted: true });
turn.done = (async () => {
try {
const completed = await runtime.send(prompt);
if (turn.streamError) throw turn.streamError;
if (turn.cancelled) return;
if (completed?.finishReason !== "completed") throw new AdapterError("internal", "Cline did not complete the turn.");
if (typeof completed.text !== "string") throw invalid();
await emit(turn, "final", { content: clean(completed.text) });
} catch {
await emit(turn, "error", { code: "internal", message: "Cline generation failed.", retryable: false });
} finally {
if (active === turn) active = undefined;
}
})();
return;
}
throw invalid();
}
let buffer = Buffer.alloc(0), queue = Promise.resolve(), settled = false;
let onData, onEnd, onInputError, onOutputError;
try {
await new Promise((done, fail) => {
const finish = (error) => {
if (settled) return;
settled = true;
stopping = true;
error ? fail(error) : done();
};
const frame = (line) => {
const value = object(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line)));
if (value.v !== 1) throw invalid();
if (value.type === "response") {
const call = pending.get(string(value.id));
if (!call || ((value.result === undefined) === (value.error === undefined))) throw invalid();
if (value.error !== undefined) call.reject(new AdapterError("toolFailed", "Host rejected tool call."));
else call.resolve(bounded(value.result));
} else if (value.type === "request") {
queue = queue.then(async () => {
if (settled) return;
try { if (await handle(value) === "closed") finish(); }
catch (error) { await failure(string(value.id), error); }
}).catch(finish);
} else throw invalid();
};
onData = (chunk) => {
try {
buffer = Buffer.concat([buffer, Buffer.from(chunk)]);
let end;
while ((end = buffer.indexOf(10)) >= 0) {
if (end > MAX_FRAME) throw invalid();
const line = buffer.subarray(0, end);
buffer = buffer.subarray(end + 1);
frame(line);
}
if (buffer.length > MAX_FRAME) throw invalid();
} catch (error) { finish(error); }
};
onEnd = () => { queue.then(() => finish(buffer.length ? invalid() : undefined)).catch(finish); };
onInputError = finish;
onOutputError = finish;
input.on("data", onData); input.once("end", onEnd); input.once("error", onInputError);
output.once("error", onOutputError);
});
} finally {
stopping = true;
input.off("data", onData); input.off("end", onEnd); input.off("error", onInputError);
output.off("error", onOutputError);
try { await queue; await shutdown(); await writeQueue; }
finally { restoreEnvironment(); running = false; }
}
}

View File

@ -0,0 +1,121 @@
import { mkdir } from "node:fs/promises";
import { realpath } from "node:fs/promises";
import { resolve } from "node:path";
import { randomUUID } from "node:crypto";
import { AdapterError, string, validateConfig, verifyRuntime } from "./contract.mjs";
const ENGINE_PROVIDER_ID = "openai-compatible";
// Called only from open, never from the local readiness probe.
export async function createClineRuntime({ fetch, storageRoot, hostTools }) {
await verifyRuntime();
await mkdir(storageRoot, { recursive: true, mode: 0o700 });
const sdk = await import("@cline/sdk");
sdk.setClineDir(storageRoot);
sdk.setHomeDir(resolve(storageRoot, "home"));
const logger = sdk.noopBasicLogger;
const core = await sdk.ClineCore.create({
clientName: "idea-cline-demo", distinctId: "idea-cline-demo",
backendMode: "local", automation: false, fetch, logger,
capabilities: { requestToolApproval: async () => ({ approved: false }) },
});
let engineId;
let unsubscribe;
let disposed = false;
let started = false;
let previousProvider;
let registered = false;
return {
async open({ config, secrets, context, sessionPlan, onEvent }) {
validateConfig(config, secrets);
previousProvider = sdk.Llms.getProviderCollectionSync(ENGINE_PROVIDER_ID);
sdk.Llms.registerProvider({
provider: {
...previousProvider?.provider,
id: ENGINE_PROVIDER_ID, name: "IdeA Cline OpenAI-compatible",
defaultModelId: config.model, client: "openai-compatible",
protocol: "openai-chat", source: "file", env: [],
capabilities: ["streaming", "tools"],
},
models: { ...previousProvider?.models,
[config.model]: previousProvider?.models?.[config.model] ?? { id: config.model } },
});
registered = true;
const project = await realpath(string(context.projectRoot));
const kind = sessionPlan?.kind;
if (!["none", "assign", "resume"].includes(kind)) throw new AdapterError("invalidRequest", "Invalid session plan.");
engineId = kind === "none" ? randomUUID() : string(sessionPlan.conversationId);
if (!/^[A-Za-z0-9_-]{1,128}$/.test(engineId)) {
throw new AdapterError("resumeNotFound", "Cline conversation is unavailable.");
}
let initialMessages;
if (kind === "resume") {
const saved = await core.get(engineId);
if (!saved || saved.workspaceRoot !== project || saved.provider !== ENGINE_PROVIDER_ID || saved.model !== config.model) {
throw new AdapterError("resumeNotFound", "Cline conversation is unavailable for this project and model.");
}
initialMessages = await core.readMessages(engineId);
if (!Array.isArray(initialMessages)) throw new AdapterError("resumeNotFound", "Cline history is unavailable.");
} else if (kind === "assign" && await core.get(engineId)) {
throw new AdapterError("invalidRequest", "Assigned Cline conversation already exists.");
}
const policies = { "*": { enabled: false, autoApprove: false } };
const validToolName = (name) => /^[A-Za-z0-9_-]{1,64}$/.test(name);
const reserved = new Set(hostTools.tools.filter((tool) => validToolName(tool.name)).map((tool) => tool.name));
const tools = hostTools.tools.map((tool, index) => {
let alias = tool.name;
if (!validToolName(alias)) {
let suffix = index;
do { alias = `idea_host_${suffix++}`; } while (reserved.has(alias));
reserved.add(alias);
}
policies[alias] = { enabled: true, autoApprove: true };
return sdk.createTool({
name: alias, description: tool.description, inputSchema: tool.inputSchema,
retryable: false, maxRetries: 0,
execute: (args, context) => hostTools.call(tool.name, args, { signal: context.signal }),
});
});
unsubscribe = core.subscribe((event) => {
if (event.payload?.sessionId === engineId && event.type === "agent_event") onEvent(event.payload.event);
});
await core.start({
interactive: true, initialMessages,
config: {
sessionId: engineId, providerId: ENGINE_PROVIDER_ID, modelId: config.model,
baseUrl: config.endpoint, apiKey: secrets.apiKey,
cwd: project, workspaceRoot: project, systemPrompt: typeof context.content === "string" ? context.content : "",
enableTools: false, enableSpawnAgent: false, enableAgentTeams: false,
disableMcpSettingsTools: true, mcpApps: false,
checkpoint: { enabled: false }, compaction: { enabled: false },
pluginPaths: [], agentPluginPaths: [], extensions: [],
extraTools: tools, logger, maxIterations: 16,
},
toolPolicies: policies, plugins: { "*": { enabled: false } },
localRuntime: {
configExtensions: [],
modelCatalogDefaults: { loadLatestOnInit: false, loadPrivateOnAuth: false },
},
});
started = true;
return engineId;
},
send(prompt) { return core.send({ sessionId: engineId, prompt }); },
cancel() { return core.abort(engineId, "Host cancelled the turn."); },
async close() {
if (disposed) return;
disposed = true;
unsubscribe?.();
try { if (started) await core.stop(engineId); }
finally {
try { await core.dispose("IdeA adapter closed."); }
finally {
if (registered) {
if (previousProvider) sdk.Llms.registerProvider(previousProvider);
else sdk.Llms.unregisterProvider(ENGINE_PROVIDER_ID);
}
}
}
},
};
}

View File

@ -0,0 +1,50 @@
import { readFile } from "node:fs/promises";
export const PLUGIN_ID = "idea.cline-demo";
export const ADAPTER_ID = "cline-sdk";
export const VERSION = "0.1.0";
export const SDK_VERSION = "0.2.0";
export const NODE_VERSION = "24.15.0";
export const MAX_VALUE = 1024 * 1024;
export const MAX_FRAME = 8 * MAX_VALUE;
export const CAPABILITIES = ["streaming", "resume", "cancel", "hostTools", "probe"];
export class AdapterError extends Error {
constructor(code, message) { super(message); this.code = code; }
}
export const invalid = () => new AdapterError("invalidRequest", "Invalid adapter request.");
export function object(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid();
return value;
}
export function string(value) {
if (typeof value !== "string" || !value || value.includes("\0")) throw invalid();
return value;
}
export function bounded(value, maximum = MAX_VALUE) {
if (Buffer.byteLength(JSON.stringify(value), "utf8") > maximum) throw invalid();
return value;
}
export function validateConfig(config, secrets) {
object(config); object(secrets); bounded(config); bounded(secrets);
if (Object.keys(config).some((key) => !["model", "endpoint"].includes(key))
|| Object.keys(secrets).some((key) => key !== "apiKey")
|| typeof config.model !== "string" || !config.model.trim()
|| typeof config.endpoint !== "string"
|| (secrets.apiKey !== undefined && (typeof secrets.apiKey !== "string" || !secrets.apiKey))) {
throw new AdapterError("invalidProfileConfig", "Invalid Cline profile configuration.");
}
let url;
try { url = new URL(config.endpoint); } catch { throw invalid(); }
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
throw new AdapterError("invalidProfileConfig", "Invalid provider endpoint.");
}
}
export async function verifyRuntime() {
if (process.versions.node !== NODE_VERSION) {
throw new AdapterError("notReady", "Cline demo requires Node.js 24.15.0.");
}
const entry = import.meta.resolve("@cline/sdk");
const pkg = JSON.parse(await readFile(new URL("../package.json", entry), "utf8"));
if (pkg.version !== SDK_VERSION) throw new AdapterError("notReady", "Cline SDK version is incompatible.");
}

View File

@ -0,0 +1,2 @@
// This example contributes a process adapter and preset, with no UI activation.
export function activate() {}