merge(ai-profiles): integrate 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 17:04:58 +01:00
25 changed files with 5755 additions and 2 deletions

View File

@ -9,6 +9,8 @@ exports `activate(ctx)`.
## Start Here
- [Manifest](docs/manifest.md): required fields, capabilities and contribution ids.
- [AI Adapters And Profile Presets](docs/ai-profiles.md): packaged session bridges,
configuration schemas, optional model display and host-owned profile instances.
- [Activation And Context](docs/activation-context.md): `activate(ctx)`, lifecycle, logging, storage and subscriptions.
- [Menus](docs/menus.md): top-level menus, native menu insertion and command registration.
- [Commands And Feedback](docs/commands-and-feedback.md): command return values, skipped work and background tasks.
@ -48,6 +50,9 @@ npm install
npm run build
```
Validate agent adapter and AI profile manifest contributions with
`npm run test:ai-profile-manifest`.
## Validate The Example
```sh

153
docs/ai-profiles.md Normal file
View File

@ -0,0 +1,153 @@
# AI Adapters And Profile Presets
Plugins can declare `contributes.agentAdapters` and `contributes.aiProfiles` in
manifest version 1. Both arrays are optional. An adapter supplies a packaged
process implementing the IdeA agent-session protocol; a preset supplies initial
configuration from which the host creates a durable profile instance.
The SDK exports `IdeAPluginAgentAdapterContribution`,
`IdeAPluginAgentAdapterConfigSchema`, `IdeAPluginAgentAdapterConfigField` and
`IdeAPluginAiProfileContribution` from `@idea/plugin-sdk`.
## Manifest Example
```json
{
"ideaPluginManifestVersion": 1,
"id": "com.example.ai",
"displayName": "Example AI",
"version": "1.0.0",
"main": "dist/index.js",
"trustLevel": "full",
"contributes": {
"agentAdapters": [{
"id": "example.session",
"displayName": "Example Session",
"protocol": "idea-agent-session",
"protocolVersion": 1,
"command": "bin/example-session",
"args": ["--stdio"],
"env": { "EXAMPLE_LOG_LEVEL": "warn" },
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {
"endpoint": {
"type": "string",
"title": "Endpoint",
"format": "uri",
"default": "https://api.example.com/v1"
},
"model": { "type": "string", "title": "Model" },
"apiKey": { "type": "string", "title": "API key", "format": "secret" },
"maxRetries": { "type": "integer", "default": 2, "enum": [0, 1, 2] },
"stream": { "type": "boolean", "default": true }
},
"required": ["endpoint", "apiKey"]
}
}],
"aiProfiles": [{
"id": "example.assistant",
"adapterId": "example.session",
"displayName": "Example Assistant",
"profileType": "generalAssistant",
"providerLabel": "Example",
"modelField": "model",
"description": "Assistant using the Example session bridge.",
"configDefaults": { "model": "example-model", "maxRetries": 1 }
}]
}
}
```
## Contribution Rules
Adapter and preset ids are unique in the plugin contribution namespace. Each
`adapterId` references an adapter in the same manifest. `displayName` and
`providerLabel` are nonempty. `profileType` is `codingAgent`, `generalAssistant`
or `custom`.
Adapters require `protocol: "idea-agent-session"`, `protocolVersion: 1` and a
package-relative `command`. Absolute paths and parent traversal are rejected.
The host starts the executable directly, without a shell; `args` are literal
tokens and `env` contains static non-secret string values. Package the executable
and its runtime dependencies; do not rely on a shell command line or host PATH
lookup. The adapter command has no `allowAbsoluteCommand` escape hatch.
`modelField` is **optional**. When supplied it names a declared non-secret string
property, allowing the host to display the configured model. A preset without a
model selector omits `modelField`; its catalogue model is nullable. `description`
is optional and `configDefaults` is a required object, which can be empty.
## Configuration Schema
This is a closed scalar subset of JSON Schema, not arbitrary JSON Schema:
- Root keys: `type: "object"`, `properties`, `additionalProperties: false`, and
optional `required`, containing unique declared property names.
- Field keys: `type`, optional `title`, `description`, `default`, `enum`, `format`.
- Field types: `string`, `number`, `integer`, `boolean`. Numbers must be finite;
integers must have no fractional part.
- Formats: `uri` (absolute URI) and `secret`, both restricted to string fields.
- Enums are nonempty arrays of distinct values matching the field type/format.
- Defaults must match the field type, format and enum. Secret fields cannot have
a default, including an explicit `null`.
- Preset `configDefaults` only includes declared, non-secret fields whose values
match the schema. It may omit required fields, which are configured later.
Unknown schema keywords, nested objects/arrays, references, composition and
unsupported type/format combinations are rejected. Secret values must never
appear in `configDefaults`, environment entries, command arguments or logs.
`validatePluginManifest`, `isPluginManifest` and `assertPluginManifest` validate
these contributions as well as the existing manifest fields. Host validation
remains authoritative for installation and runtime configuration.
## Session Protocol v1
The host owns profile/session lifecycle. The process exchanges UTF-8 JSON Lines
over stdin/stdout; stdout is protocol-only and stderr is drained as bounded
diagnostics. Request/response frames carry `v: 1`, `type`, `id` and
`method`/`params` or `result`/`error`. Event frames carry `v: 1`, `type: "event"`,
`name`, and `data` with `sessionId`/`turnId` correlation.
- `initialize` receives `adapterRef: {pluginId, adapterId, pluginVersion}` and
`profileRef: {profileId, presetId?}`. All five v1 capabilities are mandatory:
`streaming`, `resume`, `cancel`, `hostTools`, `probe`.
- `probe({config, secrets})` checks readiness without creating or persisting a
session. `open({sessionId, sessionPlan, config, secrets, context})` handles
none/assign/resume and returns an opaque engine conversation id.
- `send({sessionId, turnId, prompt})` acknowledges with `{accepted: true}` and
streams correlated events: `progress`, `textDelta`, `toolActivity`,
`announcement`, `heartbeat`, `availability`, `rateLimited`, `final`, `error`.
Successful generation has one terminal `final`; failed generation has a
terminal `error`. Accepted cancellation terminates without a final response.
- `cancel` returns `{outcome: "cancelled" | "alreadyCancelled" | "alreadyCompleted"}`;
`close` is idempotent. Errors use `{code, message, retryable}`.
- The process invokes `host/tool.call`. The host supplies the effective tool
catalogue and checks current project/requester permissions on every call.
Plugin-supplied identity never authorizes a tool call.
Limits are 8 MiB per frame and 1 MiB per prompt/config/tool argument or result.
Deadlines: initialize 10 s; probe/open 30 s; send at most 4 h; cancel/close 5 s.
Tool calls use the host deadline. Shutdown escalates to process-group kill after
2 s. The host cleans the process environment and caps stderr diagnostics at
64 KiB. Malformed protocol or premature closure fails the session closed.
## Profile Ownership And Secrets
Persisted profiles keep plugin provenance
`{pluginId, adapterId, presetId?, sourcePluginVersion, config, secretRefs}`;
they never store adapter commands or installed package paths. Runtime resolution
uses the currently installed manifest. The provider/resume key is
`plugin:<pluginId>:<adapterId>`.
The host secret store owns secret values. Configuration UI sees only
`{field, configured, masked: true}`; updates use keep/set/clear operations.
Values reach the adapter only in `probe`/`open`, never in profile JSON or logs.
Profile instances and assignments survive plugin removal or incompatibility.
The unified host catalogue exposes profile/preset origin, provider, nullable model
and availability: `missing`, `incompatible`, `needsConfiguration` or `ready`.
`ready` means configuration is complete, not that a remote connection was tested.
Selectors retain unavailable instances and display the host-provided reason.

View File

@ -119,7 +119,9 @@ development loop.
"menus": [],
"menuItems": [],
"layouts": [],
"mcpServers": []
"mcpServers": [],
"agentAdapters": [],
"aiProfiles": []
}
}
```
@ -177,6 +179,12 @@ semantics to IdeA.
## Contributions
`contributes.agentAdapters` declares packaged AI session bridge processes;
`contributes.aiProfiles` declares presets referencing those adapters in the same
plugin. Both collections are optional, so existing manifests remain valid without
changes. See [AI Adapters And Profile Presets](ai-profiles.md) for their public
types, closed configuration schema and session protocol v1 contract.
`contributes.skills` declares read-only agent skills shipped inside the IdeA
plugin package. These skills are IdeA-native: IdeA can expose them in project
plugin settings, assign them to agents, inject them into the agent skill

3
examples/cline-ai-plugin/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules/
build/
.idea-cline/

View File

@ -0,0 +1 @@
24.15.0

View 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.

View 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();
}

View 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

File diff suppressed because it is too large Load Diff

View 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" }
}

View 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;
}

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() {}

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");
}
});

View File

@ -19,10 +19,11 @@
"scripts": {
"build": "tsc -p tsconfig.json",
"test:manifest": "npm run build && node scripts/check-manifest-tools.mjs",
"test:ai-profile-manifest": "npm run build && node scripts/check-manifest-ai-profiles.mjs",
"build:hello-plugin": "tsc -p examples/hello-plugin/tsconfig.build.json",
"package:hello-plugin": "npm run build && npm run build:hello-plugin && node scripts/package-hello-plugin.mjs",
"typecheck:examples": "tsc -p examples/hello-plugin/tsconfig.json --noEmit",
"check": "npm run test:manifest && npm run typecheck:examples && npm run package:hello-plugin"
"check": "npm run test:manifest && npm run test:ai-profile-manifest && npm run typecheck:examples && npm run package:hello-plugin"
},
"keywords": [
"idea",

View File

@ -0,0 +1,52 @@
import assert from "node:assert/strict";
import test from "node:test";
import { validatePluginManifest } from "../dist/index.js";
function valid(args, env) {
return validatePluginManifest({
ideaPluginManifestVersion: 1, id: "test.limits", displayName: "Limits", version: "1.0.0",
main: "dist/index.js", trustLevel: "full", contributes: { agentAdapters: [{
id: "adapter", displayName: "Adapter", protocol: "idea-agent-session", protocolVersion: 1,
command: "bin/adapter", args, env,
configSchema: { type: "object", properties: {}, additionalProperties: false },
}] },
}).success;
}
const environment = (count, value) => Object.fromEntries(Array.from({ length: count }, (_, i) => [`FIELD_${i}`, value]));
test("argv count 128 inclusive", () => {
assert.equal(valid(Array(128).fill("x"), {}), true);
assert.equal(valid(Array(129).fill("x"), {}), false);
});
test("argv token 4096 UTF8 bytes inclusive", () => {
assert.equal(valid(["é".repeat(2048)], {}), true);
assert.equal(valid(["é".repeat(2048) + "a"], {}), false);
});
test("argv aggregate includes terminators", () => {
const args = Array(8).fill("x".repeat(4095));
assert.equal(valid(args, {}), true);
args[0] += "x";
assert.equal(valid(args, {}), false);
});
test("environment count 64 inclusive", () => {
assert.equal(valid([], environment(64, "x")), true);
assert.equal(valid([], environment(65, "x")), false);
});
test("environment name 128 bytes inclusive", () => {
assert.equal(valid([], { ["A".repeat(128)]: "x" }), true);
assert.equal(valid([], { ["A".repeat(129)]: "x" }), false);
});
test("environment value 4096 UTF8 bytes inclusive", () => {
assert.equal(valid([], { FIELD: "é".repeat(2048) }), true);
assert.equal(valid([], { FIELD: "é".repeat(2048) + "a" }), false);
});
test("environment aggregate includes equals and terminators", () => {
const env = environment(8, "x".repeat(4087));
assert.equal(valid([], env), true);
env.FIELD_0 += "x";
assert.equal(valid([], env), false);
});
test("NUL cannot be truncated in argv or env", () => {
assert.equal(valid(["x\0y"], {}), false);
assert.equal(valid([], { FIELD: "x\0y" }), false);
});

View File

@ -0,0 +1,80 @@
import assert from "node:assert/strict";
import { validatePluginManifest } from "../dist/index.js";
const base = {
ideaPluginManifestVersion: 1,
id: "dev.example.agent",
displayName: "Agent",
version: "1.0.0",
main: "dist/index.js",
trustLevel: "full",
contributes: {
agentAdapters: [{
id: "session",
displayName: "Session",
protocol: "idea-agent-session",
protocolVersion: 1,
command: "bin/agent",
configSchema: { type: "object", properties: {}, additionalProperties: false }
}],
aiProfiles: [{
id: "default",
adapterId: "session",
displayName: "Default",
profileType: "codingAgent",
providerLabel: "Example",
configDefaults: {}
}]
}
};
assert.equal(
validatePluginManifest(base).success,
true,
"valid agent adapter and AI profile contributions are accepted"
);
const unknownAdapter = structuredClone(base);
unknownAdapter.contributes.aiProfiles[0].adapterId = "missing";
assert.equal(
validatePluginManifest(unknownAdapter).success,
false,
"AI profiles cannot reference an unknown adapter"
);
const unsupportedProtocol = structuredClone(base);
unsupportedProtocol.contributes.agentAdapters[0].protocolVersion = 2;
assert.equal(
validatePluginManifest(unsupportedProtocol).success,
false,
"only agent session protocol version 1 is supported"
);
const protectedEnv = structuredClone(base);
protectedEnv.contributes.agentAdapters[0].env = { PATH: "/tmp/plugin-bin", API_TOKEN: "literal" };
const acceptance = [];
acceptance.push(["runtime-rejected env names", validatePluginManifest(protectedEnv).success]);
const excessiveArgs = structuredClone(base);
excessiveArgs.contributes.agentAdapters[0].args = Array.from({ length: 257 }, () => "x");
acceptance.push(["257 adapter args", validatePluginManifest(excessiveArgs).success]);
const excessiveArgBytes = structuredClone(base);
excessiveArgBytes.contributes.agentAdapters[0].args = ["x".repeat(64 * 1024 + 1)];
acceptance.push(["adapter args over 64 KiB", validatePluginManifest(excessiveArgBytes).success]);
const excessiveEnvEntries = structuredClone(base);
excessiveEnvEntries.contributes.agentAdapters[0].env = Object.fromEntries(
Array.from({ length: 129 }, (_, index) => [`PLUGIN_VALUE_${index}`, "x"]),
);
acceptance.push(["129 adapter env entries", validatePluginManifest(excessiveEnvEntries).success]);
const excessiveEnvBytes = structuredClone(base);
excessiveEnvBytes.contributes.agentAdapters[0].env = { PLUGIN_VALUE: "x".repeat(64 * 1024 + 1) };
acceptance.push(["adapter env over 64 KiB", validatePluginManifest(excessiveEnvBytes).success]);
assert.deepEqual(
acceptance,
acceptance.map(([label]) => [label, false]),
"SDK must reject runtime-incompatible env and oversized adapter args/env"
);

View File

@ -2,6 +2,10 @@ export type {
IdeAPluginActivationScope,
IdeAPluginCapability,
IdeAPluginManifest,
IdeAPluginAgentAdapterContribution,
IdeAPluginAgentAdapterConfigSchema,
IdeAPluginAgentAdapterConfigField,
IdeAPluginAiProfileContribution,
IdeAPluginPermissions,
IdeAPluginWorkspaceExecEffect,
IdeAPluginWorkspaceExecRule,
@ -15,6 +19,13 @@ export type {
IdeAPluginTopLevelMenuContribution
} from "./manifest.js";
export {
PLUGIN_AI_MAX_ARGS,
PLUGIN_AI_MAX_ARG_BYTES,
PLUGIN_AI_MAX_ARGS_BYTES,
PLUGIN_AI_MAX_ENV_VARS,
PLUGIN_AI_MAX_ENV_NAME_BYTES,
PLUGIN_AI_MAX_ENV_VALUE_BYTES,
PLUGIN_AI_MAX_ENV_BYTES,
isPluginManifest,
assertPluginManifest,
validatePluginManifest

View File

@ -1,3 +1,45 @@
/** Host transport bounds; UTF-8 bytes include argument terminators / env separators. */
export const PLUGIN_AI_MAX_ARGS = 128;
export const PLUGIN_AI_MAX_ARG_BYTES = 4096;
export const PLUGIN_AI_MAX_ARGS_BYTES = 32768;
export const PLUGIN_AI_MAX_ENV_VARS = 64;
export const PLUGIN_AI_MAX_ENV_NAME_BYTES = 128;
export const PLUGIN_AI_MAX_ENV_VALUE_BYTES = 4096;
export const PLUGIN_AI_MAX_ENV_BYTES = 32768;
const pluginAiEncoder = new TextEncoder();
const pluginAiHostEnvNames = ["PATH", "HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "SYSTEMROOT"];
function validAgentArguments(value: unknown): boolean {
if (value === undefined) return true;
if (!Array.isArray(value) || value.length > PLUGIN_AI_MAX_ARGS) return false;
let total = 0;
for (const arg of value) {
if (typeof arg !== "string" || arg.includes("\0")) return false;
const bytes = pluginAiEncoder.encode(arg).length;
total += bytes + 1;
if (bytes > PLUGIN_AI_MAX_ARG_BYTES || total > PLUGIN_AI_MAX_ARGS_BYTES) return false;
}
return true;
}
function validAgentEnvironment(value: unknown): boolean {
if (value === undefined) return true;
if (!isRecord(value)) return false;
const entries = Object.entries(value);
if (entries.length > PLUGIN_AI_MAX_ENV_VARS) return false;
let total = 0;
for (const [name, entry] of entries) {
if (typeof entry !== "string" || entry.includes("\0") || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||
pluginAiHostEnvNames.includes(name) || name.startsWith("LD_") || name.startsWith("DYLD_") ||
["PYTHONPATH", "PYTHONHOME", "NODE_OPTIONS", "NODE_PATH", "BASH_ENV", "ENV", "SHELLOPTS", "CDPATH", "IFS"].includes(name) ||
["SECRET", "TOKEN", "PASSWORD", "CREDENTIAL", "API_KEY", "AUTHORIZATION"].some((part) => name.toUpperCase().includes(part))) return false;
const nameBytes = pluginAiEncoder.encode(name).length;
const valueBytes = pluginAiEncoder.encode(entry).length;
total += nameBytes + valueBytes + 2;
if (nameBytes > PLUGIN_AI_MAX_ENV_NAME_BYTES || valueBytes > PLUGIN_AI_MAX_ENV_VALUE_BYTES || total > PLUGIN_AI_MAX_ENV_BYTES) return false;
}
return true;
}
export interface IdeAPluginManifest {
ideaPluginManifestVersion: 1;
id: string;
@ -21,6 +63,8 @@ export interface IdeAPluginManifest {
slashCommands?: IdeAPluginSlashCommandContribution[];
layouts?: IdeAPluginLayoutContribution[];
mcpServers?: IdeAPluginMcpServerContribution[];
agentAdapters?: IdeAPluginAgentAdapterContribution[];
aiProfiles?: IdeAPluginAiProfileContribution[];
};
}
@ -125,6 +169,53 @@ export interface IdeAPluginMcpToolMetadata {
description?: string;
}
/** Closed scalar subset of JSON Schema supported by agent-session protocol v1. */
export interface IdeAPluginAgentAdapterConfigSchema {
type: "object";
properties: Record<string, IdeAPluginAgentAdapterConfigField>;
additionalProperties: false;
/** Required at runtime; presets may leave these fields unconfigured. */
required?: string[];
}
/** Secret values have no manifest default and are supplied by the host at runtime. */
export type IdeAPluginAgentAdapterConfigField = {
title?: string;
description?: string;
} & (
| { type: "string"; format?: "uri"; default?: string; enum?: string[] }
| { type: "string"; format: "secret"; default?: never; enum?: string[] }
| { type: "number" | "integer"; default?: number; enum?: number[] }
| { type: "boolean"; default?: boolean; enum?: boolean[] }
);
export interface IdeAPluginAgentAdapterContribution {
id: string;
displayName: string;
protocol: "idea-agent-session";
protocolVersion: 1;
/** Executable relative to the installed package; no shell or host PATH lookup. */
command: string;
args?: string[];
/** Static non-secret environment entries. Secrets travel in probe/open only. */
env?: Record<string, string>;
configSchema: IdeAPluginAgentAdapterConfigSchema;
}
export interface IdeAPluginAiProfileContribution {
id: string;
/** Adapter contribution id in this same plugin. */
adapterId: string;
displayName: string;
profileType: "codingAgent" | "generalAssistant" | "custom";
providerLabel: string;
/** Optional non-secret string property used for model display; omit if absent. */
modelField?: string;
description?: string;
/** Partial initial configuration; secret fields are forbidden. */
configDefaults: Record<string, string | number | boolean>;
}
export type PluginManifestValidationResult =
| { success: true; data: IdeAPluginManifest; errors: [] }
| { success: false; data?: undefined; errors: string[] };
@ -365,6 +456,150 @@ function validateContributes(value: unknown, errors: string[]): void {
});
}
});
validateAgentContributions(value, errors);
}
function validateAgentContributions(value: Record<string, unknown>, errors: string[]): void {
const ids = new Set<unknown>();
// Agent contribution ids share the existing plugin-local contribution namespace.
for (const key of ["skills", "menus", "menuItems", "mcpServers"]) {
if (Array.isArray(value[key])) {
for (const item of value[key]) if (isRecord(item)) ids.add(item.id);
}
}
if (Array.isArray(value.layouts)) {
for (const item of value.layouts) if (isRecord(item)) ids.add(item.type);
}
const validateId = (item: Record<string, unknown>, label: string): void => {
if (typeof item.id !== "string" || !/^[A-Za-z0-9._:-]{3,}$/.test(item.id)) {
errors.push(`${label}.id must contain at least three ASCII letters, digits, dots, underscores, colons or dashes`);
}
if (ids.has(item.id)) errors.push(`${label}.id must be unique within the plugin`);
ids.add(item.id);
};
const adapters = new Map<string, Record<string, unknown>>();
validateArray(value, "agentAdapters", errors, (adapter, index) => {
const label = `contributes.agentAdapters[${index}]`;
validateId(adapter, label);
requireString(adapter, "displayName", errors, `${label}.displayName`);
if (adapter.protocol !== "idea-agent-session" || adapter.protocolVersion !== 1) {
errors.push(`${label} requires idea-agent-session protocol version 1`);
}
if (typeof adapter.command !== "string" || !isSafeWorkspaceCwd(adapter.command) ||
adapter.command === "." || adapter.command.includes("\0")) {
errors.push(`${label}.command must be a package-relative executable path`);
}
optionalStringArray(adapter, "args", errors, `${label}.args`);
if (!validAgentArguments(adapter.args)) {
errors.push(`${label}.args is invalid or exceeds the host transport limit`);
}
optionalStringRecord(adapter, "env", errors, `${label}.env`);
if (!validAgentEnvironment(adapter.env)) {
errors.push(`${label}.env is invalid or exceeds the host transport limit`);
}
validateAgentConfigSchema(adapter.configSchema, `${label}.configSchema`, errors);
if (typeof adapter.id === "string") adapters.set(adapter.id, adapter);
});
validateArray(value, "aiProfiles", errors, (profile, index) => {
const label = `contributes.aiProfiles[${index}]`;
validateId(profile, label);
for (const key of ["adapterId", "displayName", "providerLabel"]) {
requireString(profile, key, errors, `${label}.${key}`);
}
if (typeof profile.profileType !== "string" || !["codingAgent", "generalAssistant", "custom"].includes(profile.profileType)) {
errors.push(`${label}.profileType must be codingAgent, generalAssistant or custom`);
}
optionalString(profile, "description", errors, `${label}.description`);
const adapter = typeof profile.adapterId === "string" ? adapters.get(profile.adapterId) : undefined;
if (!adapter) errors.push(`${label}.adapterId must reference an adapter in this plugin`);
const properties = adapter && isRecord(adapter.configSchema) && isRecord(adapter.configSchema.properties)
? adapter.configSchema.properties : undefined;
if (profile.modelField !== undefined) {
const field = typeof profile.modelField === "string" && properties && Object.hasOwn(properties, profile.modelField)
? properties[profile.modelField] : undefined;
if (!isRecord(field) || field.type !== "string" || field.format === "secret") {
errors.push(`${label}.modelField must reference a non-secret string property`);
}
}
if (!isRecord(profile.configDefaults)) {
errors.push(`${label}.configDefaults must be an object`);
} else if (properties) {
for (const [name, entry] of Object.entries(profile.configDefaults)) {
const field = Object.hasOwn(properties, name) ? properties[name] : undefined;
if (!isRecord(field) || field.format === "secret" || !agentConfigAccepts(field, entry)) {
errors.push(`${label}.configDefaults.${name} must match a declared non-secret property`);
}
}
}
});
}
function validateAgentConfigSchema(value: unknown, label: string, errors: string[]): void {
if (!isRecord(value)) {
errors.push(`${label} must be an object`);
return;
}
rejectUnknownKeys(value, ["type", "properties", "additionalProperties", "required"], label, errors);
if (value.type !== "object" || value.additionalProperties !== false) {
errors.push(`${label} requires type object and additionalProperties false`);
}
if (!isRecord(value.properties)) {
errors.push(`${label}.properties must be an object`);
return;
}
const properties = value.properties;
if (value.required !== undefined && (!Array.isArray(value.required) ||
value.required.some((name) => typeof name !== "string" || !Object.hasOwn(properties, name)) ||
new Set(value.required).size !== value.required.length)) {
errors.push(`${label}.required must contain unique declared property names`);
}
for (const [name, field] of Object.entries(properties)) {
const fieldLabel = `${label}.properties.${name}`;
if (!name || name.includes("\0")) errors.push(`${fieldLabel} has an invalid property name`);
if (!isRecord(field)) {
errors.push(`${fieldLabel} must be a scalar field schema`);
continue;
}
rejectUnknownKeys(field, ["type", "title", "description", "default", "enum", "format"], fieldLabel, errors);
if (typeof field.type !== "string" || !["string", "number", "integer", "boolean"].includes(field.type)) {
errors.push(`${fieldLabel}.type must be string, number, integer or boolean`);
}
optionalString(field, "title", errors, `${fieldLabel}.title`);
optionalString(field, "description", errors, `${fieldLabel}.description`);
if (field.format !== undefined && (field.type !== "string" || (field.format !== "uri" && field.format !== "secret"))) {
errors.push(`${fieldLabel}.format must be uri or secret on a string field`);
}
if (field.enum !== undefined && (!Array.isArray(field.enum) || field.enum.length === 0 ||
new Set(field.enum).size !== field.enum.length || field.enum.some((entry) => !agentConfigMatches(field, entry)))) {
errors.push(`${fieldLabel}.enum must contain distinct values matching the field type and format`);
}
if (Object.hasOwn(field, "default") && (field.format === "secret" || !agentConfigAccepts(field, field.default))) {
errors.push(`${fieldLabel}.default must match the field and cannot contain a secret`);
}
}
}
function rejectUnknownKeys(value: Record<string, unknown>, allowed: string[], label: string, errors: string[]): void {
for (const key of Object.keys(value)) {
if (!allowed.includes(key)) errors.push(`${label}.${key} is an unsupported schema keyword`);
}
}
function agentConfigAccepts(field: Record<string, unknown>, value: unknown): boolean {
return agentConfigMatches(field, value) && (field.enum === undefined ||
(Array.isArray(field.enum) && field.enum.includes(value)));
}
function agentConfigMatches(field: Record<string, unknown>, value: unknown): boolean {
switch (field.type) {
case "string":
return typeof value === "string" && (field.format !== "uri" ||
/^[A-Za-z][A-Za-z0-9+.-]*:(?:[A-Za-z0-9:/?#\[\]@!$&'()*+,;=._~-]|%[0-9A-Fa-f]{2})*$/.test(value));
case "number": return typeof value === "number" && Number.isFinite(value);
case "integer": return typeof value === "number" && Number.isInteger(value);
case "boolean": return typeof value === "boolean";
default: return false;
}
}
function validateArray(