Compare commits

..

8 Commits

Author SHA1 Message Date
5a38b204b6 merge(ai-profiles): integrate plugin profile SDK and Cline demo — #342
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-19 17:04:58 +01:00
8faa860676 feat(ai-profiles): add plugin profile SDK and Cline demo (#342)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-19 16:30:49 +01:00
2a3c582ec8 merge(sdk): fix #329 — feedbacks menu host génériques et doc SDK alignée (QA verte: npm run check, git diff --check) — docs only, aucun push 2026-09-19 00:33:57 +02:00
32d33b330f docs(sdk): feedbacks menu host génériques — #329 ; README + docs commands-and-feedback/menus/services : failed/skipped sans message Git codé en dur ni payload brut, opened/alreadyOpen succès silencieux, logs host pluginId/commandId/status/reason/message, vue de diagnostic reste accessible quand Git/ADB/Gradle ou autre outil optionnel manque, workspace.execTool rappelé ; QA verte : npm run check, git diff --check 2026-09-19 00:33:57 +02:00
8ff0f475de feat(sdk): contrat permissions.workspaceExec pour l'exécution contrôlée via l'hôte — #346
Cadrage capacités plugin SCM (#346): le manifeste plugin gagne
permissions.workspaceExec.allow — règles d'exécution contrôlée par l'hôte
(commande bare ASCII résolue sans shell, argv exact avec jeton `*` en
suffixe, cwd project-relative sûr, effect read/write/network/destructive,
64 règles max) — au lieu de lectures ad hoc du store interne .git.
Validation manifeste + exports runtime/index + docs README/manifest/
services + auto-check script étendu (règles valides acceptées, règles
unsafe rejetées).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-13 12:07:56 +02:00
720cd53924 merge(sdk): fix #336 — contrat docs commandes/menus apres hot reload (erreur retryable, feedback host-owned, contrat manifest/registration, reload sans refresh auto)
# Conflicts:
#	docs/menus.md
2026-09-12 14:06:54 +02:00
9efb781636 docs(sdk): rejet de promesse windows.open remonte au handler + rejet des commandes stale d'un runtime remplace (identite plugin) — #336 (docs only, aucun push) 2026-09-12 14:06:00 +02:00
116b75a024 docs(sdk): contrat commandes/menus apres reload — handler manquant = erreur retryable jamais no-op silencieux, feedback skipped/failed host-owned, pas de contributes.commands separe, reload sans refresh auto par le plugin — #336 (docs only, aucun push) 2026-09-12 14:05:52 +02:00
32 changed files with 6034 additions and 22 deletions

View File

@ -9,12 +9,15 @@ 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.
- [Layouts With React](docs/layouts-react.md): React/JSX/hooks layout authoring with host-provided React.
- [Windows](docs/windows.md): opening plugin layouts in detached OS windows.
- [Services](docs/services.md): workspace, tasks, tooling, events, config, terminal and windows facades.
- [Services](docs/services.md): workspace files and bounded `workspace.execTool`, tasks,
tooling, events, config, terminal and windows facades.
- [Packaging And Distribution](docs/packaging-distribution.md): build output, archive layout, hot reload and dependency rules.
- [Codex Skills And IdeA Plugins](docs/codex-skills-and-idea-plugins.md): separate IdeA-native plugin skills from Codex plugin discovery.
- [Project Plugin Assignments](docs/project-plugin-assignments.md): enable plugins per project and assign skills and MCP tools to agents.
@ -23,6 +26,18 @@ The installable example lives in [`examples/hello-plugin`](examples/hello-plugin
It demonstrates a menu command, storage, background-task feedback, a React layout
component and `services.windows.open(...)`.
For short project-scoped external tools, use
`ctx.services.workspace.execTool()` with an explicit manifest
`permissions.workspaceExec` allow rule. See [Services](docs/services.md) and
[Manifest](docs/manifest.md). The primitive is generic and does not expose a
native Git/SCM API.
Menu commands that open or focus a plugin view return `status: "opened"`
(including `alreadyOpen: true`) and remain UI-silent on success. Keep diagnostic
views accessible when optional tools are missing, and use the structured
`skipped`/`failed` feedback contract for genuinely impossible actions; see
[Commands And Feedback](docs/commands-and-feedback.md) and [Menus](docs/menus.md).
## Install
```sh
@ -35,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

@ -1,7 +1,7 @@
# Commands And Feedback
This document is the normative SDK contract for plugin commands that may launch
background work.
This document is the normative SDK contract for plugin commands, including
commands that open a view or launch background work.
## Contract
@ -25,14 +25,17 @@ manifest contribution -> command id -> registered command handler -> optional ta
not by a fake task.
- Feedback objects must be stable enough for agents and programmatic callers to
parse, and their messages must be readable by humans.
- The current human menu-click UI does not guarantee display of a command
handler return value. When a human must see feedback from a menu action, open
or focus a plugin layout/window from the handler with
- The human menu-click UI presents minimal host-owned feedback for `skipped`
and `failed` results. It intentionally does not expose the raw result payload
or assume which tool (Git, ADB, Gradle, and so on) the plugin uses.
For successful actions and richer status, open or focus a plugin layout/window
from the handler with
`ctx.services.windows.open({ layoutType, state })`.
## Preconditions
Check preconditions before calling `runCommand()`:
Check preconditions before calling `runCommand()`. These are task-launch
preconditions, not prerequisites for opening an explanatory view:
- `ctx.services` exists. Plugins need the `ui` or `tooling` capability for the
service facade.
@ -49,6 +52,12 @@ Check preconditions before calling `runCommand()`:
- Do not use `ctx.pluginRoot` as `cwd`; `cwd` remains relative to the project root.
- `command` and `args` are separate values. Do not shell-join user input.
A command whose purpose is to open or focus a diagnostic/configuration view
should call `services.windows.open(...)` before probing optional executables.
Missing Git, ADB, Gradle, or another tool must not block that view when the view
can explain the degraded state and the next step. Probe tools from the view (or
from its data loader) and render the degraded state there.
If any required precondition fails, return a skipped result:
```ts
@ -66,21 +75,30 @@ with equivalent fields:
```ts
type CommandFeedback =
| { status: "opened"; message?: string; alreadyOpen: boolean }
| { status: "skipped"; reason: string; message: string }
| { status: "failed"; reason?: string; message?: string }
| { status: "launched"; taskId: string; state: string; message: string };
```
Use the same `status` vocabulary consistently:
- `opened`: the requested view was opened or focused. `alreadyOpen: true` is a
successful focus operation, not a failure or skip.
- `skipped`: no background task was created.
- `launched`: a task was created; inspect the task state for later progress.
- `failed`: the handler itself failed before it could return normally.
- `failed`: the handler caught a failure and returned structured failure
feedback. An uncaught/rejected handler is also treated as a failure by the
host.
Visible surfaces are intentionally distinct:
- Command return value: immediate feedback for programmatic callers, agents and
future host surfaces. It is not a guaranteed visible UI surface for current
human menu clicks.
- Command return value: immediate feedback for programmatic callers and agents.
The human menu host maps `skipped` and `failed` results to concise feedback;
plugin-specific fields and messages are not displayed verbatim. `opened`
results, including `alreadyOpen: true`, succeed without an alert. The host
logs structured diagnostics with `pluginId`, `commandId`, `status`, `reason`
and `message`; raw objects, stack traces and internal ids are not user-facing.
- Plugin layout/window: the normative visible feedback surface for menu actions
that need to show status, results or next steps to a human. The layout must be
declared in `idea-plugin.json` and registered during activation.
@ -145,6 +163,11 @@ const plugin: IdeAPluginModule = {
export default plugin;
```
The `opened` branch above must remain successful even when an optional tool
diagnosed by `HealthView` is absent. If `windows.open(...)` itself rejects, log
the technical cause and either let the promise reject or return `failed`; the
host will show generic, plugin-neutral feedback rather than the raw message.
Background task feedback:
```ts

View File

@ -119,7 +119,9 @@ development loop.
"menus": [],
"menuItems": [],
"layouts": [],
"mcpServers": []
"mcpServers": [],
"agentAdapters": [],
"aiProfiles": []
}
}
```
@ -141,9 +143,48 @@ development loop.
- `activationScope`: `"app"` by default, or `"project"` when activation needs a
focused project immediately.
- `capabilities`: `"ui"`, `"tooling"` and/or `"mcp"`.
- `permissions.workspaceExec`: explicit generic executable rules used by
`ctx.services.workspace.execTool()`.
## Workspace execution permissions
Short project-scoped executable access is denied unless the active plugin
manifest contains a matching rule:
```json
{
"permissions": {
"workspaceExec": {
"allow": [
{
"command": "tool",
"args": ["status", "*"],
"cwd": ".",
"effect": "read"
}
]
}
}
}
```
`command` is a bare ASCII executable name; paths and shell command lines are
rejected. `args` is an argv pattern: literal tokens match exactly, `*` matches
one token, and a final `*` matches the remaining suffix (including no token).
`cwd` is an exact normalized project-relative directory; `*` permits any cwd
that the host still proves is under the project root. `effect` is one of
`read`, `write`, `network`, or `destructive` and drives sandbox/audit policy.
The manifest declares generic process access only; it does not add native SCM
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
@ -243,7 +284,9 @@ public id used by both `ctx.layouts.register({ type, component })` and
Contribution ids are part of the runtime contract:
- commands can only register ids declared by `contributes.menuItems[*].command`;
- there is no separate `contributes.commands` collection; commands can only
register ids declared by `contributes.menuItems[*].command` or
`contributes.slashCommands[*].command`;
- layouts can only register `type` values declared by `contributes.layouts`;
- `services.windows.open({ layoutType })` only accepts a layout type declared by
the calling plugin.

View File

@ -33,7 +33,10 @@ Then register the command id:
```ts
export function activate(ctx: ActivateContext): void {
const disposable = ctx.commands?.registerCommand("hello-plugin.open", async () => {
await ctx.services?.windows.open({ layoutType: "hello-plugin.dashboard" });
const win = await ctx.services?.windows.open({ layoutType: "hello-plugin.dashboard" });
return win
? { status: "opened", alreadyOpen: win.alreadyOpen }
: { status: "skipped", reason: "ui-service-unavailable", message: "UI service unavailable." };
});
if (disposable) ctx.subscriptions.push(disposable);
}
@ -41,9 +44,22 @@ export function activate(ctx: ActivateContext): void {
## Rules
- A command can only be registered if at least one manifest menu item declares
that exact `command` id.
- Missing command handlers are a no-op when the user clicks the menu item.
- There is no separate `contributes.commands` collection. A command can only be
registered if at least one manifest `menuItems[].command` or
`slashCommands[].command` entry declares that exact id.
- A missing command handler is surfaced by the host as a retryable reload error;
menu clicks must never fail silently.
- A registered handler's rejected promise is not swallowed: the host logs the
plugin id, command id, status, reason and message, then presents a generic
retryable error without raw payloads. In
particular, return/await `services.windows.open(...)` so native-window
failures follow this path.
- An open/focus handler returns `status: "opened"` whether `alreadyOpen` is
`false` (new window) or `true` (existing window focused). Neither success
produces an alert.
- Keep diagnostic views reachable when optional executables such as Git, ADB or
Gradle are missing. Let the view explain that degraded state instead of
skipping the menu action before opening it.
- A handler owns precondition checks and feedback. See
[Commands And Feedback](commands-and-feedback.md).
- Menu item `when` expressions are evaluated by the host; unsupported or false

View File

@ -150,6 +150,8 @@ These actions solve different problems:
- Reload the plugin after rebuilding or replacing its installed package. Reload
refreshes the plugin manifest, runtime bundle, contributions, and packaged
skill Markdown. It does not change project activation or agent assignments.
Plugins do not call a contribution-refresh API themselves: rebuild or replace
the installed package, then use the host reload action.
- Relaunch the agent after enabling or disabling a project plugin, changing its
skill/tool assignments, or manually editing `.ideai/project-plugins.json`.
Agent capabilities are resolved into a launch-time snapshot, so an already

View File

@ -29,6 +29,38 @@ Key APIs:
- `stat(path, projectId?)`
- `watch(path, handler, projectId?)`
- `queryStructure(query?)`
- `execTool(request)`
### Short external tools
`services.workspace.execTool()` runs a short external executable already available
to the host. It is generic: IdeA does not expose Git, SVN, formatter, or linter
semantics. The plugin owns the arguments and parses the returned output.
```ts
const result = await ctx.services!.workspace.execTool({
projectId,
command: "tool",
args: ["status", "--short"],
cwd: ".",
timeoutMs: 5_000,
maxStdoutBytes: 256_000,
maxStderrBytes: 64_000
});
```
The host passes `command` and `args` directly without a shell. The plugin must
declare a matching `permissions.workspaceExec.allow` rule, be active for the
project, and use a project-relative `cwd`. IdeA canonicalizes the cwd, bounds
time/stdin/output/concurrency, exposes only an allowlisted environment, applies
the project filesystem sandbox where supported, and audits metadata without
captured stdout/stderr contents. This API returns output directly and never
creates a visible Work/background-task entry.
Current host maxima are 30 seconds, 1,000,000 stdout bytes, 256,000 stderr bytes,
and 64,000 stdin bytes. Requested output/time values above a maximum are clamped;
zero is rejected. Output is returned as lossy UTF-8 with explicit truncation
flags.
## Tasks
@ -93,6 +125,13 @@ locations. Use it for configuration the user expects to review/version.
one of the calling plugin's declared layout contributions. See
[Windows](windows.md).
Resolving this promise means the window was opened or focused. Its
`alreadyOpen` flag reports which happened; both outcomes are successful and a
menu handler should return `status: "opened"`. Do not gate a diagnostic window
on optional tool availability when that window can present the unavailable
state. A rejection means the window operation itself was impossible and may be
logged or returned as `status: "failed"`; do not expose its raw error to users.
## Scheduled tasks
Project scheduled tasks are exposed through native Tauri/HTTP commands and the

View File

@ -24,6 +24,13 @@ do not currently guarantee that return value is displayed.
existing `contributes.layouts` layout.
- The host validates the plugin is runtime-active and the layout exists before
opening or focusing the window.
- The calling plugin package must still be installed, enabled globally and
enabled for the focused project. A stale command from a replaced runtime is
rejected instead of opening a window under another plugin's identity.
- `windows.open(...)` rejects its promise when any validation or native-window
operation fails. Let that rejection reach the command handler (or catch it,
log it and return explicit failed feedback); the IdeA menu host logs the
rejection and shows a retryable error to the user.
- Reopening the same plugin/layout pair focuses the existing window.
- `state` is JSON-serializable initial window state. The mounted component can
later call `setState(next)` to update its local host state.
@ -47,13 +54,14 @@ The returned `label` is a host-owned window identity. Treat it as opaque.
```ts
ctx.commands?.registerCommand("hello-plugin.open-dashboard", async () => {
const win = await ctx.services?.windows.open({
if (!ctx.services) {
return { status: "skipped", reason: "ui-service-unavailable", message: "UI service unavailable." };
}
const win = await ctx.services.windows.open({
layoutType: "hello-plugin.dashboard",
state: { source: "menu" }
});
return win
? { status: "opened", message: "Opened dashboard.", alreadyOpen: win.alreadyOpen }
: { status: "skipped", reason: "ui-service-unavailable", message: "UI service unavailable." };
return { status: "opened", message: "Opened dashboard.", alreadyOpen: win.alreadyOpen };
});
```

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

@ -36,3 +36,26 @@ duplicate.contributes.mcpServers[0].tools.push({ name: "read_scene" });
const duplicateResult = validatePluginManifest(duplicate);
assert.equal(duplicateResult.success, false, "duplicate tool metadata is rejected");
assert.ok(duplicateResult.errors.some((error) => error.includes("must be unique")));
const withWorkspaceExec = structuredClone(base);
withWorkspaceExec.permissions = {
workspaceExec: {
allow: [{ command: "tool", args: ["status", "*"], cwd: ".", effect: "read" }]
}
};
assert.equal(
validatePluginManifest(withWorkspaceExec).success,
true,
"valid generic workspace execution permissions are accepted"
);
for (const invalidRule of [
{ command: "sh -c", args: [], cwd: ".", effect: "read" },
{ command: "tool", args: ["sta*"], cwd: ".", effect: "read" },
{ command: "tool", args: [], cwd: "../outside", effect: "read" },
{ command: "tool", args: [], cwd: ".", effect: "git" }
]) {
const invalid = structuredClone(base);
invalid.permissions = { workspaceExec: { allow: [invalidRule] } };
assert.equal(validatePluginManifest(invalid).success, false, "unsafe workspace exec rule is rejected");
}

View File

@ -2,6 +2,13 @@ export type {
IdeAPluginActivationScope,
IdeAPluginCapability,
IdeAPluginManifest,
IdeAPluginAgentAdapterContribution,
IdeAPluginAgentAdapterConfigSchema,
IdeAPluginAgentAdapterConfigField,
IdeAPluginAiProfileContribution,
IdeAPluginPermissions,
IdeAPluginWorkspaceExecEffect,
IdeAPluginWorkspaceExecRule,
IdeAPluginEngineConstraints,
IdeAPluginLayoutContribution,
IdeAPluginMcpServerContribution,
@ -12,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
@ -78,6 +92,8 @@ export type {
WorkspaceBinaryFile,
WorkspaceDirEntry,
WorkspaceDirectoryListing,
WorkspaceExecToolRequest,
WorkspaceExecToolResult,
WorkspaceFileChangedEvent,
WorkspaceProject,
WorkspaceResolvedPath,

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;
@ -13,6 +55,7 @@ export interface IdeAPluginManifest {
* Defaults to "app". Use "project" when activate(ctx) requires a focused project.
*/
activationScope?: IdeAPluginActivationScope;
permissions?: IdeAPluginPermissions;
contributes?: {
skills?: IdeAPluginSkillContribution[];
menus?: IdeAPluginTopLevelMenuContribution[];
@ -20,6 +63,26 @@ export interface IdeAPluginManifest {
slashCommands?: IdeAPluginSlashCommandContribution[];
layouts?: IdeAPluginLayoutContribution[];
mcpServers?: IdeAPluginMcpServerContribution[];
agentAdapters?: IdeAPluginAgentAdapterContribution[];
aiProfiles?: IdeAPluginAiProfileContribution[];
};
}
export type IdeAPluginWorkspaceExecEffect = "read" | "write" | "network" | "destructive";
export interface IdeAPluginWorkspaceExecRule {
/** Bare executable name resolved by the host without a shell. */
command: string;
/** Exact argv tokens. `*` matches one token, or the remaining suffix when last. */
args?: string[];
/** Exact project-relative cwd; `*` permits any host-confined cwd. Defaults to `.`. */
cwd?: string;
effect: IdeAPluginWorkspaceExecEffect;
}
export interface IdeAPluginPermissions {
workspaceExec?: {
allow: IdeAPluginWorkspaceExecRule[];
};
}
@ -106,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[] };
@ -145,6 +255,7 @@ export function validatePluginManifest(input: unknown): PluginManifestValidation
validateEngines(input.engines, errors);
validateCapabilities(input.capabilities, errors);
validateActivationScope(input.activationScope, errors);
validatePermissions(input.permissions, errors);
validateContributes(input.contributes, errors);
if (errors.length > 0) {
@ -154,6 +265,56 @@ export function validatePluginManifest(input: unknown): PluginManifestValidation
return { success: true, data: input as unknown as IdeAPluginManifest, errors: [] };
}
function validatePermissions(value: unknown, errors: string[]): void {
if (value === undefined) return;
if (!isRecord(value)) {
errors.push("permissions must be an object when provided");
return;
}
const workspaceExec = value.workspaceExec;
if (workspaceExec === undefined) return;
if (!isRecord(workspaceExec) || !Array.isArray(workspaceExec.allow)) {
errors.push("permissions.workspaceExec.allow must be an array");
return;
}
if (workspaceExec.allow.length > 64) {
errors.push("permissions.workspaceExec.allow must contain at most 64 rules");
}
workspaceExec.allow.forEach((rule, index) => {
const label = `permissions.workspaceExec.allow[${index}]`;
if (!isRecord(rule)) {
errors.push(`${label} must be an object`);
return;
}
requireString(rule, "command", errors, `${label}.command`);
if (typeof rule.command === "string" && !/^[A-Za-z0-9._+-]{1,128}$/.test(rule.command)) {
errors.push(`${label}.command must be a bare ASCII executable name`);
}
optionalStringArray(rule, "args", errors, `${label}.args`);
if (Array.isArray(rule.args)) {
if (rule.args.length > 64 || rule.args.some((arg) =>
typeof arg === "string" && (arg.length === 0 || arg.length > 4096 || (arg.includes("*") && arg !== "*")))) {
errors.push(`${label}.args contains an invalid token`);
}
}
optionalString(rule, "cwd", errors, `${label}.cwd`);
if (typeof rule.cwd === "string" && rule.cwd !== "*" && !isSafeWorkspaceCwd(rule.cwd)) {
errors.push(`${label}.cwd must be project-relative without empty, dot, or parent segments`);
}
if (!["read", "write", "network", "destructive"].includes(String(rule.effect))) {
errors.push(`${label}.effect must be "read", "write", "network" or "destructive"`);
}
});
}
function isSafeWorkspaceCwd(value: string): boolean {
if (value === ".") return true;
if (value.length === 0 || value.startsWith("/") || value.startsWith("\\") || value.includes(":")) {
return false;
}
return value.replaceAll("\\", "/").split("/").every((part) => part !== "" && part !== "." && part !== "..");
}
export function isPluginManifest(input: unknown): input is IdeAPluginManifest {
return validatePluginManifest(input).success;
}
@ -295,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(

View File

@ -137,6 +137,31 @@ export interface WorkspaceService {
watch(path: string, handler: WorkspaceWatchHandler, projectId?: string): Promise<WorkspaceWatch>;
/** Queries a bounded, generic project structure read model. */
queryStructure(query?: WorkspaceStructureQuery): Promise<ProjectStructure>;
/** Runs one manifest-allowlisted binary directly, without a visible task. */
execTool(request: WorkspaceExecToolRequest): Promise<WorkspaceExecToolResult>;
}
export interface WorkspaceExecToolRequest {
projectId?: string;
command: string;
args?: string[];
cwd?: string;
env?: Record<string, string>;
timeoutMs?: number;
maxStdoutBytes?: number;
maxStderrBytes?: number;
stdin?: string;
}
export interface WorkspaceExecToolResult {
exitCode: number | null;
signal?: string;
timedOut: boolean;
stdout: string;
stderr: string;
stdoutTruncated: boolean;
stderrTruncated: boolean;
durationMs: number;
}
export interface WorkspaceResolvedPath {