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:
3
examples/cline-ai-plugin/.gitignore
vendored
Normal file
3
examples/cline-ai-plugin/.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
build/
|
||||
.idea-cline/
|
||||
1
examples/cline-ai-plugin/.node-version
Normal file
1
examples/cline-ai-plugin/.node-version
Normal file
@ -0,0 +1 @@
|
||||
24.15.0
|
||||
89
examples/cline-ai-plugin/README.md
Normal file
89
examples/cline-ai-plugin/README.md
Normal file
@ -0,0 +1,89 @@
|
||||
# Cline AI profile demo
|
||||
|
||||
This is an IdeA plugin package, with an AI adapter and a coding-agent preset.
|
||||
The process uses the public agent-session JSONL v1 protocol and the real
|
||||
`ClineCore` from `@cline/sdk`. There is no Cline-specific host backend.
|
||||
|
||||
## Pinned setup
|
||||
|
||||
The tested runtime is **Node.js 24.15.0**, npm **11.12.1**, and
|
||||
`@cline/sdk` / `@cline/core` **0.2.0**. The lockfile pins transitive dependencies.
|
||||
No Cline CLI or VS Code extension is required. Install that exact Node version
|
||||
on the Linux host and start IdeA with that version first in its trusted PATH.
|
||||
The host resolves the script's `env node` shebang to one
|
||||
canonical interpreter before confinement. The adapter refuses other Node/SDK
|
||||
versions. Dependencies are installed during setup, never by the adapter.
|
||||
|
||||
From this directory:
|
||||
|
||||
```sh
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run check
|
||||
npm test
|
||||
npm run package
|
||||
```
|
||||
|
||||
Use an explicit npm cache under a writable worktree/managed-temp directory when
|
||||
the host's default cache is read-only. The package command produces
|
||||
`build/cline-ai-plugin-0.1.0.zip` and a symlink-free `build/package` directory.
|
||||
Install that archive or prepared directory through IdeA's plugin installer;
|
||||
do not install the source directory containing npm's `.bin` symlinks.
|
||||
The archive includes runtime dependencies and third-party license files;
|
||||
`node_modules` and build artifacts are not committed.
|
||||
|
||||
## Host policy and configuration
|
||||
|
||||
Linux v1 requires explicit network **Allow**, a filesystem **Deny** fallback and
|
||||
successful strict Landlock ABI v3 enforcement. Configure a host read grant for
|
||||
the installed package and its runtime modules, plus a write grant for the
|
||||
launch directory's `.idea-cline` data directory. The adapter never adds grants.
|
||||
The installed root is `<IdeA app-data>/plugins/installed/idea.cline-demo`.
|
||||
On the tested Linux host, Node also requires an explicit read grant for the
|
||||
canonical `/etc/ssl/openssl.cnf` file before JavaScript starts. If the host's
|
||||
OpenSSL configuration includes other files or provider modules, grant only the
|
||||
specific required files. The demo keeps the host crypto configuration intact;
|
||||
it does not replace `OPENSSL_CONF` or grant the whole `/etc` directory.
|
||||
The host grants EXEC only to the exact adapter, Node interpreter and ELF loader.
|
||||
Unavailable/degraded enforcement refuses launch.
|
||||
|
||||
Enable the plugin for the project, create a profile from `cline-openai`, and
|
||||
set the model and OpenAI-compatible HTTP(S) endpoint. The optional `apiKey`
|
||||
is a host SecretStore value supplied in `open`/`probe` only. Configure a key if
|
||||
the endpoint requires one. No credential belongs in this package, environment,
|
||||
manifest, config defaults, command arguments or setup commands.
|
||||
|
||||
IdeA owns profile assignments and credentials. Cline's private `.idea-cline`
|
||||
directory holds its session history for resume. It does not use `~/.cline`,
|
||||
inherited provider credentials or hub discovery. Keep this directory stable
|
||||
across adapter restarts and within the same project; normal close retains
|
||||
history. Keep this private history directory out of version control.
|
||||
Resume refuses missing history, another project or another model.
|
||||
|
||||
## Lifecycle and tools
|
||||
|
||||
- `initialize` validates protocol/runtime identity.
|
||||
- `probe` validates local runtime/configuration only. It makes no provider call,
|
||||
creates no Cline session and does not prove authentication or connectivity.
|
||||
- `open` starts an interactive ClineCore session without a prompt.
|
||||
- `send` acknowledges before generation, maps SDK streaming events, and emits
|
||||
one final only when the SDK reports completion.
|
||||
- `cancel` uses SDK abort and drains the active turn; `close` awaits stop/dispose.
|
||||
- Native file/shell/web/MCP tools, spawn, teams, checkpoints, automation and
|
||||
config/plugin discovery are disabled. Only the host's supplied tool catalogue
|
||||
becomes SDK tools. Their callbacks invoke `host/tool.call`; host identity,
|
||||
current permissions and deadlines remain authoritative.
|
||||
|
||||
Stdout is JSONL only. Errors are static and credential-free. API keys are supplied
|
||||
only to the SDK's in-memory connection configuration; the adapter never calls
|
||||
Cline settings/auth persistence APIs. Cline intentionally persists conversation
|
||||
history and tool results in its private data directory.
|
||||
One adapter/runtime per process is supported because SDK storage setters are
|
||||
process-global. Environment isolation is restored after cleanup.
|
||||
|
||||
## Deterministic verification
|
||||
|
||||
QA tests import `runAdapter({input, output, fetch, storageRoot})` with Node streams,
|
||||
temporary storage and an injected fake OpenAI-compatible provider. They use the
|
||||
real published ClineCore, not a fake session service. Tests require no real
|
||||
credentials and make no live provider requests. No production fake-provider flag
|
||||
or network-test command is provided. Live provider validation is not part of CI.
|
||||
11
examples/cline-ai-plugin/bin/idea-cline-adapter.mjs
Executable file
11
examples/cline-ai-plugin/bin/idea-cline-adapter.mjs
Executable file
@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
import { runAdapter } from "../src/adapter.mjs";
|
||||
|
||||
try {
|
||||
await runAdapter({ input: process.stdin, output: process.stdout });
|
||||
} catch {
|
||||
process.stderr.write("Cline adapter stopped safely.\n");
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
process.stdin.destroy();
|
||||
}
|
||||
63
examples/cline-ai-plugin/idea-plugin.json
Normal file
63
examples/cline-ai-plugin/idea-plugin.json
Normal file
@ -0,0 +1,63 @@
|
||||
{
|
||||
"ideaPluginManifestVersion": 1,
|
||||
"id": "idea.cline-demo",
|
||||
"displayName": "Cline AI",
|
||||
"publisher": "IdeA Examples",
|
||||
"version": "0.1.0",
|
||||
"description": "ClineCore over the public IdeA agent-session v1 protocol.",
|
||||
"main": "src/plugin.mjs",
|
||||
"engines": {
|
||||
"idea": ">=0.1.0"
|
||||
},
|
||||
"trustLevel": "full",
|
||||
"contributes": {
|
||||
"agentAdapters": [
|
||||
{
|
||||
"id": "cline-sdk",
|
||||
"displayName": "ClineCore session",
|
||||
"protocol": "idea-agent-session",
|
||||
"protocolVersion": 1,
|
||||
"command": "bin/idea-cline-adapter.mjs",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"model": {
|
||||
"type": "string",
|
||||
"title": "Model"
|
||||
},
|
||||
"endpoint": {
|
||||
"type": "string",
|
||||
"title": "OpenAI-compatible endpoint",
|
||||
"format": "uri"
|
||||
},
|
||||
"apiKey": {
|
||||
"type": "string",
|
||||
"title": "API key (if required by the endpoint)",
|
||||
"format": "secret"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"model",
|
||||
"endpoint"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"aiProfiles": [
|
||||
{
|
||||
"id": "cline-openai",
|
||||
"adapterId": "cline-sdk",
|
||||
"displayName": "Cline coding agent",
|
||||
"profileType": "codingAgent",
|
||||
"providerLabel": "Cline SDK / OpenAI-compatible",
|
||||
"modelField": "model",
|
||||
"description": "ClineCore with host-owned tool callbacks; native file, shell, web and MCP tools disabled.",
|
||||
"configDefaults": {
|
||||
"model": "gpt-4.1-mini",
|
||||
"endpoint": "https://api.openai.com/v1"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
4107
examples/cline-ai-plugin/package-lock.json
generated
Normal file
4107
examples/cline-ai-plugin/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
14
examples/cline-ai-plugin/package.json
Normal file
14
examples/cline-ai-plugin/package.json
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "idea-cline-ai-plugin",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": { "node": "24.15.0" },
|
||||
"packageManager": "npm@11.12.1",
|
||||
"scripts": {
|
||||
"check": "node --check src/adapter.mjs && node --check src/cline-runtime.mjs",
|
||||
"test": "node --test tests/*.test.mjs",
|
||||
"package": "node scripts/package.mjs"
|
||||
},
|
||||
"dependencies": { "@cline/sdk": "0.2.0" }
|
||||
}
|
||||
74
examples/cline-ai-plugin/scripts/package.mjs
Normal file
74
examples/cline-ai-plugin/scripts/package.mjs
Normal file
@ -0,0 +1,74 @@
|
||||
import { mkdir, readdir, readFile, rm, writeFile, chmod, lstat } from "node:fs/promises";
|
||||
import { dirname, join, resolve, relative } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { deflateRawSync } from "node:zlib";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const manifest = JSON.parse(await readFile(join(root, "idea-plugin.json"), "utf8"));
|
||||
const stage = join(root, "build", "package");
|
||||
const archive = join(root, "build", `cline-ai-plugin-${manifest.version}.zip`);
|
||||
await rm(join(root, "build"), { recursive: true, force: true });
|
||||
await mkdir(stage, { recursive: true });
|
||||
const entries = [];
|
||||
|
||||
async function collect(path) {
|
||||
const name = relative(root, path).split("\\").join("/");
|
||||
const info = await lstat(path);
|
||||
if (info.isSymbolicLink()) throw new Error(`Package source symlink is unsupported: ${name}`);
|
||||
if (info.isDirectory()) {
|
||||
for (const child of (await readdir(path)).sort()) {
|
||||
if (child === ".bin" || child === ".cache" || child === "tests" || child === "test" || child === "__tests__") continue;
|
||||
await collect(join(path, child));
|
||||
}
|
||||
} else if (info.isFile()) {
|
||||
if (name.endsWith(".map") || name.endsWith(".d.ts") || name.endsWith(".d.mts") || name.endsWith(".tsbuildinfo")) return;
|
||||
const data = await readFile(path);
|
||||
const mode = name === manifest.contributes.agentAdapters[0].command ? 0o100755 : 0o100644;
|
||||
const target = join(stage, name);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await writeFile(target, data);
|
||||
await chmod(target, mode & 0o777);
|
||||
entries.push({ name, data: deflateRawSync(data, { level: 9 }), length: data.length, crc: crc32(data), mode });
|
||||
}
|
||||
}
|
||||
for (const name of ["idea-plugin.json", "package.json", "package-lock.json", "README.md", "bin", "src", "node_modules"]) {
|
||||
await collect(join(root, name));
|
||||
}
|
||||
entries.sort((a, b) => a.name.localeCompare(b.name, "en"));
|
||||
const body = [], directory = [];
|
||||
let offset = 0;
|
||||
for (const entry of entries) {
|
||||
const name = Buffer.from(entry.name, "utf8");
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50);
|
||||
local.writeUInt16LE(20, 4); local.writeUInt16LE(0x800, 6); local.writeUInt16LE(8, 8);
|
||||
local.writeUInt16LE(33, 12);
|
||||
local.writeUInt32LE(entry.crc, 14);
|
||||
local.writeUInt32LE(entry.data.length, 18); local.writeUInt32LE(entry.length, 22);
|
||||
local.writeUInt16LE(name.length, 26);
|
||||
const central = Buffer.alloc(46);
|
||||
central.writeUInt32LE(0x02014b50); central.writeUInt16LE(0x314, 4);
|
||||
central.writeUInt16LE(20, 6); central.writeUInt16LE(0x800, 8); central.writeUInt16LE(8, 10);
|
||||
central.writeUInt16LE(33, 14); central.writeUInt32LE(entry.crc, 16);
|
||||
central.writeUInt32LE(entry.data.length, 20); central.writeUInt32LE(entry.length, 24);
|
||||
central.writeUInt16LE(name.length, 28);
|
||||
central.writeUInt32LE((entry.mode * 65536) >>> 0, 38); central.writeUInt32LE(offset, 42);
|
||||
body.push(local, name, entry.data); directory.push(central, name);
|
||||
offset += local.length + name.length + entry.data.length;
|
||||
}
|
||||
if (entries.length > 65535 || offset > 0xffffffff) throw new Error("Package exceeds ZIP v1 limits.");
|
||||
const central = Buffer.concat(directory);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10);
|
||||
end.writeUInt32LE(central.length, 12); end.writeUInt32LE(offset, 16);
|
||||
await writeFile(archive, Buffer.concat([...body, central, end]));
|
||||
console.log(`Created ${relative(root, archive)} (${entries.length} files); directory install: build/package`);
|
||||
|
||||
function crc32(data) {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of data) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
262
examples/cline-ai-plugin/src/adapter.mjs
Normal file
262
examples/cline-ai-plugin/src/adapter.mjs
Normal 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; }
|
||||
}
|
||||
}
|
||||
121
examples/cline-ai-plugin/src/cline-runtime.mjs
Normal file
121
examples/cline-ai-plugin/src/cline-runtime.mjs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
50
examples/cline-ai-plugin/src/contract.mjs
Normal file
50
examples/cline-ai-plugin/src/contract.mjs
Normal 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.");
|
||||
}
|
||||
2
examples/cline-ai-plugin/src/plugin.mjs
Normal file
2
examples/cline-ai-plugin/src/plugin.mjs
Normal file
@ -0,0 +1,2 @@
|
||||
// This example contributes a process adapter and preset, with no UI activation.
|
||||
export function activate() {}
|
||||
14
examples/cline-ai-plugin/tests/helpers/adapter-child.mjs
Normal file
14
examples/cline-ai-plugin/tests/helpers/adapter-child.mjs
Normal 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?.();
|
||||
46
examples/cline-ai-plugin/tests/helpers/fake-provider.mjs
Normal file
46
examples/cline-ai-plugin/tests/helpers/fake-provider.mjs
Normal 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; } };
|
||||
}
|
||||
71
examples/cline-ai-plugin/tests/helpers/wire.mjs
Normal file
71
examples/cline-ai-plugin/tests/helpers/wire.mjs
Normal 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 })]); },
|
||||
};
|
||||
}
|
||||
46
examples/cline-ai-plugin/tests/package-contract.test.mjs
Normal file
46
examples/cline-ai-plugin/tests/package-contract.test.mjs
Normal 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());
|
||||
}
|
||||
});
|
||||
234
examples/cline-ai-plugin/tests/runtime-protocol.test.mjs
Normal file
234
examples/cline-ai-plugin/tests/runtime-protocol.test.mjs
Normal 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");
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user