From 056164157f34ea779ed6cf51199909082345eca4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A5=87?= <16399091+binaricat@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:09:48 +0000 Subject: [PATCH] feat(plugin-agent): define source-bound global session authority and contract --- docs/plugin-platform/global-agent-wip.md | 107 +++++ domain/pluginPermissionDescriptions.cjs | 2 + electron/plugins/agent/contract.test.cjs | 47 ++ electron/plugins/agent/conversationStore.cjs | 122 ++++++ .../plugins/agent/conversationStore.test.cjs | 68 +++ electron/plugins/agent/delegatedScope.cjs | 162 +++++++ .../plugins/agent/delegatedScope.test.cjs | 158 +++++++ .../generated/plugin-contract.schema.json | 400 ++++++++++++++++++ electron/plugins/globalAgent.test.cjs | 4 + .../schema/plugin-contract.schema.json | 400 ++++++++++++++++++ .../src/generated/plugin-contract.ts | 98 ++++- packages/plugin-contract/src/index.ts | 1 + packages/plugin-sdk/src/index.ts | 14 + 13 files changed, 1581 insertions(+), 2 deletions(-) create mode 100644 docs/plugin-platform/global-agent-wip.md create mode 100644 electron/plugins/agent/contract.test.cjs create mode 100644 electron/plugins/agent/conversationStore.cjs create mode 100644 electron/plugins/agent/conversationStore.test.cjs create mode 100644 electron/plugins/agent/delegatedScope.cjs create mode 100644 electron/plugins/agent/delegatedScope.test.cjs create mode 100644 electron/plugins/globalAgent.test.cjs diff --git a/docs/plugin-platform/global-agent-wip.md b/docs/plugin-platform/global-agent-wip.md new file mode 100644 index 000000000..e3c4adf83 --- /dev/null +++ b/docs/plugin-platform/global-agent-wip.md @@ -0,0 +1,107 @@ +# Global Agent plugin bridge (work in progress) + +This stack starts from `integration/plugin-ask-routing-acceptance` at +`2433cf0130d1c3274c56c39e5765349c2945de01`. The parent confirmed this dependency; +its native Ask acceptance and integrated CI are still pending. This branch does +not modify the frozen candidate, #3986, #3998, or #4002. + +The user approved a global conversation independent of a terminal or workspace, +with a plugin-provided chat UI and selectable existing Agent backends. Core owns +Agent execution, history, target authority, native approvals, credentials and +audit. Global is not unrestricted inventory access or a background service. + +## Stage 1: dispatch authority + +`electron/plugins/agent/delegatedScope.cjs` is a host-only authority. It does not +register plugin APIs, start an Agent or implement an orchestration loop. + +- `issue(context, hostSnapshot)` authenticates with the existing source binding. + Host snapshots contain backend identity/revision, target kind/id/owner/revision, + synchronous current-owner checks, and a supported capability subset. The public + result contains only an opaque handle and expiry. Plugin parameters must never + be used as `hostSnapshot`. +- `begin(handle, context)` returns an internal turn ticket and AbortController. +- `dispatch(ticket, context, resolvedAction, execute)` runs the common host policy + adapter once, checks current target revisions after any approval wait, invokes + the real dispatcher, and rejects late results. `resolvedAction` must come from + canonical host capability/argument resolution, not an unchecked plugin object. +- `assertTurn` guards outgoing events. `finish` and `stop` invalidate the exact + ticket. Runtime/plugin release, lock/hide invalidation and shutdown abort work. +- Handles expire in five minutes. There are at most eight per runtime owner and + 64 overall, with at most 32 explicit resources per scope. Expiry never silently + refreshes a selection or revives an old turn. + +The focused tests use the actual `PluginAISourceBinding` with synthetic host +registries, two terminal owners representing different workspaces, controlled +time, and deferred approval/native completion. They cover source/runtime/target +substitution, focus changes, revision changes across approval, policy denial, +Stop, release, lock, late completion and bounds. They do not yet prove actual MCP +or AgentRuntime dispatch; those remain integration gates. + +Initial execution failed before test discovery because the new worktree has no +dependencies (`ajv/dist/2020` missing). Running with the existing local worktree's +read-only CommonJS dependency path passes all 12 cases. No provider, CLI Agent, +paid credentials or GUI was used. + +The adjacent run then passed 49 tests and failed one installed-entrypoint test +because ESM could not resolve `@netcatty/plugin-cli` from the new worktree. Standard +`npm ci --ignore-scripts` and `build:plugin-runtime-deps` repaired the setup. These +failures are setup evidence, not failed-before product regressions. + +The core conversation repository stores the existing global `AISession` document +shape in a host-only directory, namespaced by the hash of source/private-owner. +Native session identity and compaction remain private. Commits serialize a cloned +snapshot, revalidate provenance before atomic rename, and retain previous history +when that check fails. Files use mode 0600 and no-follow reads. The repository +does not register a plugin storage API or change the source database schema. + +The canonical schema and SDK now declare the proposed session interface and +permissions. Runtime methods and the supported-feature advertisement are not yet +registered. This stage must not be described as an installable working Agent +bridge. Focused scope/history/wire and permission-copy tests pass 20 cases; +contract/SDK/CLI tests pass 91. Focused lint and generated drift checks pass. + +## Planned public contract and adapters + +The proposed feature is `ai.agent-sessions`, with `ai.agent.use` for conversation +operations and `ai.agent.actions` for actual Agent tool actions. Permission mode +comes from the existing source-bound Allow/Ask/Deny engine. These are additive +names, separate from the existing tools-disabled `ai.invoke` broker. + +The API will provide backend listing, explicit target selection, owned chat +listing/opening, sending, bounded event reads, history, Stop and close. Backend +references are opaque host-issued configuration revisions. Conversation references +identify only histories owned by the calling source/private-owner; runtime handles +are separate and cannot substitute builtin chat IDs or native SDK resume IDs. +Messages cannot supply permissionMode, CLI/env/MCP configuration or owner fields. + +Core will reuse `AISession`, `AgentRuntime`, both existing turn drivers, event and +compaction handling, SDK resume identity validation, and `stopAgentTurn`. The first +eligible backends are Catty and configured Claude Code in MCP mode. Other backend +entries must return explicit unsupported/unconfigured status until their native +tool and approval boundaries are verified. Codex SDK's current unrestricted native +configuration must not be treated as eligible merely because it has a driver. + +The terminal worker already exposes a suitable main-owned resource binding: +`getPluginSessionBinding(sessionId, ownerWebContentsId)` returns worker epoch and +session generation. Use this for dispatch-time targets; do not use menu IDs, +focused tab, display labels, or a renderer-provided session ID as authority. + +The MCP dispatcher and Catty direct execution route need the same delegated +session guard. A delegated call must not update process-global permission mode, +or request both an Agent approval and a plugin approval for the same action. +Policy changes, disable/restart/source replacement, lock and host disconnection +must cancel scoped native work and invalidate outgoing event tickets. Existing +Agent trace and plugin audit/log facilities will receive redacted correlation +metadata, not credentials, provider diagnostics or full unreviewed tool payloads. + +## Remaining acceptance gates + +- Canonical schema/SDK/runtime registration and the installed default host path. +- Host-owned durable history and backend references, including backend switching. +- Actual Catty and Claude MCP dispatch, policy and worker lifecycle regressions. +- Synthetic streaming/cancellation fixtures; these are not real inference or + actual authenticated Claude service acceptance. +- Installable minimal chat UI with backend and explicit target choice. +- Standard CI, independent review and parent-scheduled native evidence. No GUI + ownership, merge or release is granted to this executor. diff --git a/domain/pluginPermissionDescriptions.cjs b/domain/pluginPermissionDescriptions.cjs index ec25610b4..10ac2444d 100644 --- a/domain/pluginPermissionDescriptions.cjs +++ b/domain/pluginPermissionDescriptions.cjs @@ -3,6 +3,8 @@ // Presentation only. Admission and grants remain owned by the canonical schema // and permission engine. Tests require exact coverage of its permission enum. const PERMISSION_DESCRIPTIONS = { + "ai.agent.use": [true, "Agent conversations", "Use configured host Agents and read this plugin's own chat history. Model or Agent service usage may incur costs.", "Agent 会话", "使用宿主已配置的 Agent,并读取此插件自己的聊天历史;模型或 Agent 服务可能产生费用。"], + "ai.agent.actions": [true, "Agent actions", "Authorize Agent tools against explicitly selected targets under this plugin's policy. Commands can change remote systems.", "Agent 操作", "根据插件策略授权 Agent 工具操作明确选中的目标;命令可能更改远程系统。"], storage: [false, "Plugin storage", "Save and read this plugin's local data.", "插件存储", "保存和读取此插件自己的本地数据。"], "runtime.advanced": [true, "Full device access", "Run Node code with filesystem and network access outside broker restrictions. Developer mode only.", "完整设备访问", "运行 Node 代码,可直接访问文件系统和网络,不受代理权限限制。仅限开发者模式。"], "settings.read": [false, "Read plugin settings", "Read this plugin's configured preferences.", "读取插件设置", "读取此插件自己的设置。"], diff --git a/electron/plugins/agent/contract.test.cjs b/electron/plugins/agent/contract.test.cjs new file mode 100644 index 000000000..a21cbb08c --- /dev/null +++ b/electron/plugins/agent/contract.test.cjs @@ -0,0 +1,47 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { randomUUID } = require("node:crypto"); +const { createDefinitionValidator } = require("../contractValidator.cjs"); + +test("Agent wire accepts only opaque host configuration/scope refs, never raw backend authority", () => { + const open = createDefinitionValidator("PluginAgentOpenParams"); + const params = { backendRef: randomUUID(), selectionHandle: randomUUID() }; + assert.equal(open(params), true); + for (const [key, value] of Object.entries({ permissionMode: "auto", owner: "source:forged", privateOwner: "forged", + source: "official", model: "chosen", agentId: "claude", apiKey: "synthetic-not-a-key", cli: "node", + env: {}, mcpServers: {}, sessionIds: ["focused-session"], externalSessionId: "native-session" })) { + assert.equal(open({ ...params, [key]: value }), false, key); + } + for (const key of ["backendRef", "selectionHandle", "conversationRef"]) { + assert.equal(open({ ...params, [key]: "internal-or-path-id" }), false, key); + } +}); + +test("Agent messages and events are bounded and do not serialize raw tools/configuration", () => { + const send = createDefinitionValidator("PluginAgentSendParams"); + const params = { chatHandle: randomUUID(), text: "Synthetic user instruction" }; + assert.equal(send(params), true); + assert.equal(send({ ...params, text: "x".repeat(16_385) }), false); + assert.equal(send({ ...params, text: "a\0b" }), false); + assert.equal(send({ ...params, turnId: "builtin" }), false); + const event = createDefinitionValidator("PluginAgentEvent"); + assert.equal(event({ kind: "activity", capabilityId: "terminal.execute", state: "started" }), true); + assert.equal(event({ kind: "activity", capabilityId: "terminal.execute", state: "started", args: { command: "raw" } }), false); + assert.equal(event({ kind: "usage", inputTokens: 2, outputTokens: 4 }), true); + assert.equal(event({ kind: "usage", inputTokens: -1, outputTokens: 4 }), false); + assert.equal(event({ kind: "text", text: "x".repeat(4097) }), false); + assert.equal(event({ kind: "provider-error", message: "private diagnostics" }), false); +}); + +test("public chat/history summaries do not contain backend/native identifiers, prompts or tool results", () => { + const chats = createDefinitionValidator("PluginAgentChatsResult"); + const chat = { conversationRef: randomUUID(), title: "Synthetic chat", backend: "claude", updatedAt: 1 }; + assert.equal(chats({ items: [chat] }), true); + assert.equal(chats({ items: [{ ...chat, externalSessionId: "native" }] }), false); + const history = createDefinitionValidator("PluginAgentHistoryResult"); + assert.equal(history({ items: [{ role: "assistant", text: "Summary" }] }), true); + assert.equal(history({ items: [{ role: "tool", text: "Raw tool result" }] }), false); + assert.equal(history({ items: [{ role: "assistant", text: "Summary", apiKey: "synthetic" }] }), false); +}); diff --git a/electron/plugins/agent/conversationStore.cjs b/electron/plugins/agent/conversationStore.cjs new file mode 100644 index 000000000..4a8e54372 --- /dev/null +++ b/electron/plugins/agent/conversationStore.cjs @@ -0,0 +1,122 @@ +"use strict"; + +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { createHash, randomUUID } = require("node:crypto"); + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u; +const MAX_BYTES = 1_048_576; +const MAX_CONVERSATIONS = 64; + +// Core-owned AISession documents, outside plugin filesystem/storage roots. +// The caller must authenticate provenance before supplying the opaque owner. +// Native resume identity, compaction and tool history stay in this repository; +// only a separate public projection is returned through the plugin API. +class PluginAgentConversationStore { + constructor(directory) { + if (!path.isAbsolute(directory)) throw new TypeError("Absolute host history directory required"); + this.directory = directory; + this.pending = new Map(); + } + + #ownerDirectory(owner) { + if (!owner || typeof owner.privateOwner !== "string" || !owner.privateOwner + || typeof owner.sourceKey !== "string" || !owner.sourceKey) throw new TypeError("Host provenance required"); + return path.join(this.directory, createHash("sha256").update(JSON.stringify([owner.sourceKey, owner.privateOwner])).digest("hex")); + } + + #filename(owner, id) { + if (typeof id !== "string" || !UUID.test(id)) throw new TypeError("Invalid owned conversation reference"); + return path.join(this.#ownerDirectory(owner), `${id}.json`); + } + + async #prepare(owner) { + await fs.mkdir(this.directory, { recursive: true, mode: 0o700 }); + if (!(await fs.lstat(this.directory)).isDirectory() || (await fs.lstat(this.directory)).isSymbolicLink()) throw Error("History root unavailable"); + const directory = this.#ownerDirectory(owner); + await fs.mkdir(directory, { recursive: true, mode: 0o700 }); + const stat = await fs.lstat(directory); + if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error("History owner unavailable"); + return directory; + } + + #validate(record) { + if (!record || typeof record !== "object" || !UUID.test(record.conversationRef) + || typeof record.id !== "string" || !record.id.startsWith("plugin-agent:") + || record.scope?.type !== "global" || record.scope.targetId !== undefined + || typeof record.agentId !== "string" || typeof record.title !== "string" || record.title.length > 160 + || !Array.isArray(record.messages) || record.messages.length > 200 + || !Number.isSafeInteger(record.createdAt) || !Number.isSafeInteger(record.updatedAt)) throw new TypeError("Invalid core Agent history"); + const text = JSON.stringify(record); + if (Buffer.byteLength(text) > MAX_BYTES) throw new RangeError("Agent history budget exceeded"); + return text; + } + + async #serial(owner, operation) { + const key = this.#ownerDirectory(owner); + const previous = this.pending.get(key) ?? Promise.resolve(); + const current = previous.catch(() => {}).then(operation); + this.pending.set(key, current); + try { return await current; } + finally { if (this.pending.get(key) === current) this.pending.delete(key); } + } + + async list(owner, assertCurrent) { + await assertCurrent(); + const directory = await this.#prepare(owner); + const files = await fs.readdir(directory); + const records = []; + for (const file of files) { + const id = file.slice(0, -5); + if (!file.endsWith(".json") || !UUID.test(id)) continue; + if (records.length >= MAX_CONVERSATIONS) break; + const record = await this.read(owner, id, assertCurrent); + if (record) records.push(record); + } + await assertCurrent(); + return records.sort((a, b) => b.updatedAt - a.updatedAt); + } + + async read(owner, id, assertCurrent) { + await assertCurrent(); + const filename = this.#filename(owner, id); + await this.#prepare(owner); + let file; + try { + // O_NOFOLLOW avoids following a replaced final path. Core owns ancestors. + const { constants } = require("node:fs"); + file = await fs.open(filename, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + const stat = await file.stat(); + if (!stat.isFile() || stat.size > MAX_BYTES) throw Error("Agent history unavailable"); + const record = JSON.parse(await file.readFile("utf8")); + this.#validate(record); + if (record.conversationRef !== id) throw Error("Agent history identity mismatch"); + await assertCurrent(); + return record; + } catch (error) { + if (error.code === "ENOENT") { await assertCurrent(); return null; } + throw error; + } finally { await file?.close(); } + } + + async save(owner, record, assertCurrent) { + // Clone/serialize before any await so caller mutation cannot change commit. + const text = this.#validate(record); + const id = record.conversationRef; + return this.#serial(owner, async () => { + await assertCurrent(); + const directory = await this.#prepare(owner); + const filename = this.#filename(owner, id); + const entries = (await fs.readdir(directory)).filter((name) => name.endsWith(".json")); + if (!entries.includes(`${id}.json`) && entries.length >= MAX_CONVERSATIONS) throw new RangeError("Agent conversation budget exceeded"); + const temporary = path.join(directory, `.${randomUUID()}.tmp`); + try { + await fs.writeFile(temporary, text, { encoding: "utf8", mode: 0o600, flag: "wx" }); + await assertCurrent(); + await fs.rename(temporary, filename); + } finally { await fs.rm(temporary, { force: true }); } + }); + } +} + +module.exports = { PluginAgentConversationStore }; diff --git a/electron/plugins/agent/conversationStore.test.cjs b/electron/plugins/agent/conversationStore.test.cjs new file mode 100644 index 000000000..e36fa4f3d --- /dev/null +++ b/electron/plugins/agent/conversationStore.test.cjs @@ -0,0 +1,68 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const os = require("node:os"); +const path = require("node:path"); +const { randomUUID } = require("node:crypto"); +const { PluginAgentConversationStore } = require("./conversationStore.cjs"); + +const owner = (source) => ({ privateOwner: `opaque:${source}:same-plugin-id`, sourceKey: `source:${source}` }); +const current = async () => {}; +function record() { + const conversationRef = randomUUID(); + return { conversationRef, id: `plugin-agent:${randomUUID()}`, title: "Synthetic chat", agentId: "catty", + scope: { type: "global" }, messages: [{ id: randomUUID(), role: "user", content: "Synthetic only", timestamp: 1 }], createdAt: 1, updatedAt: 1 }; +} +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "netcatty-agent-history-test-")); + t.after(() => fs.rm(root, { recursive: true, force: true })); + return { root, store: new PluginAgentConversationStore(path.join(root, "core-history")) }; +} + +test("core history survives reopening, uses existing AISession shape and isolates the same plugin ID across sources", async (t) => { + const { root, store } = await fixture(t); const chat = record(); + await store.save(owner("a"), chat, current); + assert.deepEqual(await store.read(owner("a"), chat.conversationRef, current), chat); + const [directory] = await fs.readdir(path.join(root, "core-history")); + assert.doesNotMatch(directory, /opaque|same-plugin/); + const mode = (await fs.stat(path.join(root, "core-history", directory, `${chat.conversationRef}.json`))).mode; + if (process.platform !== "win32") assert.equal(mode & 0o777, 0o600); + assert.equal(await store.read(owner("b"), chat.conversationRef, current), null); + assert.deepEqual(await store.list(owner("b"), current), []); + const reopened = new PluginAgentConversationStore(path.join(root, "core-history")); + assert.deepEqual(await reopened.list(owner("a"), current), [chat]); +}); + +test("source revoked before async rename leaves previous history intact and cleans temporary files", async (t) => { + const { store, root } = await fixture(t); const chat = record(); await store.save(owner("a"), chat, current); + const next = { ...chat, title: "Must not commit" }; let checks = 0; + await assert.rejects(store.save(owner("a"), next, async () => { if (++checks === 2) throw Error("Revoked"); })); + assert.equal((await store.read(owner("a"), chat.conversationRef, current)).title, chat.title); + const [directory] = await fs.readdir(path.join(root, "core-history")); + assert.deepEqual(await fs.readdir(path.join(root, "core-history", directory)), [`${chat.conversationRef}.json`]); +}); + +test("history snapshots cannot mutate across await, and traversal/builtin IDs/oversized records are rejected", async (t) => { + const { store } = await fixture(t); const chat = record(); const savedTitle = chat.title; + const saved = store.save(owner("a"), chat, current); chat.title = "Changed after call"; await saved; + assert.equal((await store.read(owner("a"), chat.conversationRef, current)).title, savedTitle); + for (const id of ["../outside", "builtin-chat", "source:owner", ""]) await assert.rejects(store.read(owner("a"), id, current)); + await assert.rejects(store.save({ privateOwner: "bare-plugin" }, record(), current)); + await assert.rejects(store.save(owner("a"), { ...record(), id: "builtin-chat" }, current)); + await assert.rejects(store.save(owner("a"), { ...record(), scope: { type: "workspace", targetId: "active" } }, current)); + await assert.rejects(store.save(owner("a"), { ...record(), messages: Array(201).fill({}) }, current)); + await assert.rejects(store.save(owner("a"), { ...record(), messages: [{ content: "x".repeat(1_048_576) }] }, current)); +}); + +test("symlinked history roots and files do not become history authority", async (t) => { + const { root, store } = await fixture(t); const chat = record(); await store.save(owner("a"), chat, current); + const history = path.join(root, "core-history"); const [directory] = await fs.readdir(history); + const filename = path.join(history, directory, `${chat.conversationRef}.json`); + const unrelated = path.join(root, "unrelated.json"); await fs.writeFile(unrelated, JSON.stringify(chat)); + await fs.rm(filename); await fs.symlink(unrelated, filename); + await assert.rejects(store.read(owner("a"), chat.conversationRef, current)); + const linked = path.join(root, "linked"); await fs.symlink(history, linked, "dir"); + await assert.rejects(new PluginAgentConversationStore(linked).list(owner("a"), current)); +}); diff --git a/electron/plugins/agent/delegatedScope.cjs b/electron/plugins/agent/delegatedScope.cjs new file mode 100644 index 000000000..c80ab7e48 --- /dev/null +++ b/electron/plugins/agent/delegatedScope.cjs @@ -0,0 +1,162 @@ +"use strict"; + +const { randomUUID } = require("node:crypto"); +const { PluginRpcError, RPC_ERRORS } = require("../rpcRouter.cjs"); + +const fail = (code) => new PluginRpcError(RPC_ERRORS[code], "Delegated Agent scope is unavailable"); +const key = (target) => JSON.stringify([target.kind, target.id]); + +// Host-only authority, not a plugin RPC interface or an Agent engine. The host +// supplies snapshots after resolving configured backends and choosing targets. +// Plugins never supply owner, revision, capability policy or executable adapters. +class DelegatedAgentScopes { + constructor({ resolveOwner, assertHostActive, authorizeAction, clock = Date.now }) { + for (const fn of [resolveOwner, assertHostActive, authorizeAction, clock]) { + if (typeof fn !== "function") throw new TypeError("Host scope adapters are required"); + } + this.resolveOwner = resolveOwner; + this.assertHostActive = assertHostActive; + this.authorizeAction = authorizeAction; + this.clock = clock; + this.scopes = new Map(); + this.closed = false; + } + + async #owner(context) { + if (this.closed) throw fail("unavailable"); + const owner = await this.resolveOwner(context); + await this.assertHostActive(context); + context.signal?.throwIfAborted(); + if (this.closed || await this.resolveOwner(context) !== owner) throw fail("permissionDenied"); + return owner; + } + + // The snapshot is host-owned. A public schema must only accept returned handles. + async issue(context, { backend, targets, capabilities }) { + const owner = await this.#owner(context); + if (!backend || typeof backend.key !== "string" || typeof backend.revision !== "string" + || typeof backend.isCurrent !== "function" || !Array.isArray(targets) || targets.length > 32 + || !Array.isArray(capabilities) || capabilities.length > 128 + || capabilities.some((id) => typeof id !== "string" || !id || id.length > 160)) throw fail("invalidArgument"); + const captured = new Map(); + for (const target of targets) { + if (!target || !["terminal", "host", "note"].includes(target.kind) + || typeof target.id !== "string" || !target.id || target.id.length > 256 + || typeof target.revision !== "string" || !target.revision + || typeof target.owner !== "string" || !target.owner + || typeof target.isCurrent !== "function" || captured.has(key(target))) throw fail("invalidArgument"); + captured.set(key(target), Object.freeze({ ...target })); + } + const scope = { handle: randomUUID(), owner, backend: Object.freeze({ ...backend }), targets: captured, + capabilities: new Set(capabilities), expiresAt: this.clock() + 300_000, activeTurn: null }; + this.#assertSnapshots(scope); + if (await this.#owner(context) !== owner) throw fail("permissionDenied"); + this.#assertSnapshots(scope); + for (const entry of this.scopes.values()) if (entry.expiresAt <= this.clock()) this.#revoke(entry); + const existing = [...this.scopes.values()].filter((entry) => entry.owner === owner); + if (existing.length >= 8 || this.scopes.size >= 64) throw fail("resourceExhausted"); + this.scopes.set(scope.handle, scope); + return Object.freeze({ handle: scope.handle, expiresAt: scope.expiresAt }); + } + + #assertSnapshots(scope) { + // Current-owner/revision checks are synchronous registry lookups, so the + // final dispatch check and native call have no asynchronous focus gap. + if (scope.backend.isCurrent(scope.backend) !== true) throw fail("failedPrecondition"); + for (const target of scope.targets.values()) { + if (target.isCurrent(target) !== true) throw fail("failedPrecondition"); + } + } + + async #resolve(handle, context) { + const owner = await this.#owner(context); + const scope = this.scopes.get(handle); + if (!scope || scope.owner !== owner) throw fail("permissionDenied"); + if (scope.expiresAt <= this.clock()) { this.#revoke(scope); throw fail("permissionDenied"); } + try { + if (await this.#owner(context) !== owner || this.scopes.get(handle) !== scope + || scope.expiresAt <= this.clock()) throw fail("permissionDenied"); + this.#assertSnapshots(scope); + } catch (error) { + this.#revoke(scope); + throw error; + } + return scope; + } + + async begin(handle, context) { + const scope = await this.#resolve(handle, context); + if (scope.activeTurn) throw fail("alreadyExists"); + const ticket = Object.freeze({ scope, controller: new AbortController(), id: randomUUID() }); + scope.activeTurn = ticket; + return ticket; + } + + async assertTurn(ticket, context) { + if (!ticket?.scope || ticket.controller.signal.aborted) throw fail("cancelled"); + const scope = await this.#resolve(ticket.scope.handle, context); + if (scope.activeTurn !== ticket) throw fail("cancelled"); + ticket.controller.signal.throwIfAborted(); + return scope; + } + + // Called inside the actual tool dispatcher, after canonical argument/target + // resolution. It must not be used merely when displaying the model tool list. + async dispatch(ticket, context, action, execute) { + const scope = await this.assertTurn(ticket, context); + if (!action || !scope.capabilities.has(action.capabilityId) || !Array.isArray(action.targets) + || action.targets.length > 32 || typeof execute !== "function") throw fail("permissionDenied"); + const targets = action.targets.map((target) => { + const captured = target && scope.targets.get(key(target)); + if (!captured || target.revision !== captured.revision || target.owner !== captured.owner) throw fail("permissionDenied"); + return captured; + }); + const request = Object.freeze({ capabilityId: action.capabilityId, targets: Object.freeze(targets) }); + // The adapter combines plugin policy and native Agent restrictions once. + // No caller can select a process-global permission mode through this API. + await this.authorizeAction(context, scope.owner, request, ticket.controller.signal); + await this.assertTurn(ticket, context); + this.#assertSnapshots(scope); + ticket.controller.signal.throwIfAborted(); + const result = await execute(Object.freeze({ signal: ticket.controller.signal, + assertCurrent: () => this.assertTurn(ticket, context) })); + await this.assertTurn(ticket, context); + return result; + } + + finish(ticket) { + if (!ticket || ticket.scope?.activeTurn !== ticket) return false; + ticket.scope.activeTurn = null; + ticket.controller.abort(); + return true; + } + + async stop(handle, context) { + const scope = await this.#resolve(handle, context); + return this.finish(scope.activeTurn); + } + + #revoke(scope) { + this.finish(scope.activeTurn); + this.scopes.delete(scope.handle); + } + + releaseRuntime(runtimeId) { + for (const scope of this.scopes.values()) if (scope.owner.runtimeId === runtimeId) this.#revoke(scope); + } + + releasePlugin(pluginId) { + for (const scope of this.scopes.values()) if (scope.owner.pluginId === pluginId) this.#revoke(scope); + } + + releaseAll() { + for (const scope of this.scopes.values()) this.#revoke(scope); + } + + shutdown() { + this.closed = true; + this.releaseAll(); + } +} + +module.exports = { DelegatedAgentScopes }; diff --git a/electron/plugins/agent/delegatedScope.test.cjs b/electron/plugins/agent/delegatedScope.test.cjs new file mode 100644 index 000000000..7a6d93698 --- /dev/null +++ b/electron/plugins/agent/delegatedScope.test.cjs @@ -0,0 +1,158 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { DelegatedAgentScopes } = require("./delegatedScope.cjs"); +const { PluginAISourceBinding } = require("../ai/sourceBinding.cjs"); + +function deferred() { + let resolve; + const promise = new Promise((finish) => { resolve = finish; }); + return { promise, resolve }; +} + +function fixture() { + let time = 1; let locked = false; let focus = "terminal-a"; + let source = { id: "source-a", kind: "third-party", origin: "https://example.invalid" }; + let privateOwner = "source:opaque-owner-a:com.example.assistant"; + let identity = { pluginId: "com.example.assistant", pluginVersion: "1", runtimeId: "r1", runtimeKind: "browser" }; + let authorize = async () => {}; + const context = { ...identity, assertActive: async () => {} }; + const database = { + getActivePlugin: () => ({ source, enabled: true, activeVersion: "1", runtime: { status: "running" } }), + getRetainedPluginSource: () => source, + privateOwner: () => privateOwner, + publicPluginId: (value) => value === privateOwner ? identity.pluginId : null, + }; + const binding = new PluginAISourceBinding({ database, getRuntimeIdentity: () => identity }); + let backendRevision = "configured-1"; + const currentTargets = new Map([ + ["terminal-a", { owner: "window-1", revision: "session-a-v1" }], + ["terminal-b", { owner: "window-2", revision: "session-b-v1" }], + ]); + const backend = { key: "host-configured-claude", revision: backendRevision, + isCurrent: (snapshot) => snapshot.revision === backendRevision }; + const target = (id) => ({ kind: "terminal", id, ...currentTargets.get(id), + isCurrent: (snapshot) => { const current = currentTargets.get(snapshot.id); + return current?.owner === snapshot.owner && current?.revision === snapshot.revision; } }); + const scopes = new DelegatedAgentScopes({ resolveOwner: (ctx) => binding.resolve(ctx), + assertHostActive: async () => { if (locked) throw Error("Locked"); }, + authorizeAction: (...args) => authorize(...args), clock: () => time }); + return { scopes, context, target, targets: currentTargets, + issue: (targets = [target("terminal-a"), target("terminal-b")]) => scopes.issue(context, + { backend, targets, capabilities: ["terminal.execute", "session.environment"] }), + action: (id = "terminal-a") => ({ capabilityId: "terminal.execute", targets: [target(id)] }), + tick: (ms) => { time += ms; }, lock: () => { locked = true; scopes.releaseAll(); }, + focusTo: (id) => { focus = id; }, focus: () => focus, + authorize: (fn) => { authorize = fn; }, backendTo: (value) => { backendRevision = value; }, + replaceSource: () => { source = { ...source, id: "source-b" }; privateOwner = "source:opaque-owner-b:com.example.assistant"; }, + runtimeTo: (id) => { identity = { ...identity, runtimeId: id }; }, + }; +} + +test("host-issued scope exposes only opaque identity and expiry; cross-workspace focus does not change explicit targets", async () => { + const f = fixture(); const ref = await f.issue(); + assert.deepEqual(Object.keys(ref).sort(), ["expiresAt", "handle"]); + assert.doesNotMatch(JSON.stringify(ref), /window-|terminal-|source:|configured/); + const ticket = await f.scopes.begin(ref.handle, f.context); + f.focusTo("unselected-terminal"); + let calls = 0; + assert.equal(await f.scopes.dispatch(ticket, f.context, f.action("terminal-b"), async () => ++calls), 1); + assert.equal(f.focus(), "unselected-terminal"); + await assert.rejects(f.scopes.dispatch(ticket, f.context, + { capabilityId: "terminal.execute", targets: [{ kind: "terminal", id: f.focus(), revision: "1", owner: "window-1" }] }, async () => ++calls)); + assert.equal(calls, 1); +}); + +test("forged runtime, cross-runtime session and source replacement cannot use a scope", async () => { + const f = fixture(); const ref = await f.issue(); + await assert.rejects(f.scopes.begin(ref.handle, { ...f.context, runtimeId: "forged" })); + f.runtimeTo("r2"); + await assert.rejects(f.scopes.begin(ref.handle, { ...f.context, runtimeId: "r2" })); + f.runtimeTo("r1"); f.replaceSource(); + await assert.rejects(f.scopes.begin(ref.handle, f.context)); +}); + +test("one host policy decision; target owner/revision is revalidated after approval waits", async () => { + const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context); + const entered = deferred(); const release = deferred(); let decisions = 0; let effects = 0; + f.authorize(async (_context, owner, action) => { + decisions++; assert.equal(owner.privateOwner, "source:opaque-owner-a:com.example.assistant"); + assert.equal(action.targets[0].id, "terminal-a"); entered.resolve(); await release.promise; + }); + const result = f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++); + await entered.promise; + f.targets.set("terminal-a", { owner: "new-window", revision: "session-a-v2" }); + release.resolve(); await assert.rejects(result); + assert.equal(decisions, 1); assert.equal(effects, 0); assert.equal(ticket.controller.signal.aborted, true); +}); + +test("copied target ID with substituted owner or revision and undelegated capabilities fail before policy/execute", async () => { + const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context); + let decisions = 0; let effects = 0; f.authorize(async () => { decisions++; }); + for (const patch of [{ owner: "attacker" }, { revision: "old" }]) { + await assert.rejects(f.scopes.dispatch(ticket, f.context, + { capabilityId: "terminal.execute", targets: [{ ...f.target("terminal-a"), ...patch }] }, async () => effects++)); + } + await assert.rejects(f.scopes.dispatch(ticket, f.context, + { capabilityId: "vault.host.delete", targets: [] }, async () => effects++)); + assert.equal(decisions, 0); assert.equal(effects, 0); +}); + +test("Deny and revoked source during authorization never dispatch a tool", async () => { + const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context); + let effects = 0; + f.authorize(async () => { throw Error("Denied"); }); + await assert.rejects(f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++)); + f.authorize(async () => { f.replaceSource(); }); + await assert.rejects(f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++)); + assert.equal(effects, 0); +}); + +test("Stop while approval waits cancels the exact turn and prevents invocation", async () => { + const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context); + const entered = deferred(); const release = deferred(); let effects = 0; + f.authorize(async (_context, _owner, _action, signal) => { + assert.equal(signal, ticket.controller.signal); entered.resolve(); await release.promise; + }); + const result = f.scopes.dispatch(ticket, f.context, f.action(), async () => effects++); + await entered.promise; assert.equal(await f.scopes.stop(ref.handle, f.context), true); + release.resolve(); await assert.rejects(result); assert.equal(effects, 0); + const next = await f.scopes.begin(ref.handle, f.context); + assert.equal(f.scopes.finish(ticket), false); assert.equal(next.controller.signal.aborted, false); +}); + +for (const reason of ["runtime", "plugin", "lock", "stop"]) { + test(`${reason} cancellation drops late native results and invalidates the old event ticket`, async () => { + const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context); + const entered = deferred(); const release = deferred(); + const result = f.scopes.dispatch(ticket, f.context, f.action(), async ({ signal }) => { + assert.equal(signal, ticket.controller.signal); entered.resolve(); await release.promise; return "late"; + }); + await entered.promise; + if (reason === "runtime") f.scopes.releaseRuntime(f.context.runtimeId); + else if (reason === "plugin") f.scopes.releasePlugin(f.context.pluginId); + else if (reason === "lock") f.lock(); + else await f.scopes.stop(ref.handle, f.context); + release.resolve(); await assert.rejects(result); await assert.rejects(f.scopes.assertTurn(ticket, f.context)); + assert.equal(ticket.controller.signal.aborted, true); + }); +} + +test("backend config changes and expiry invalidate scopes; host snapshots cannot silently refresh them", async () => { + const f = fixture(); const ref = await f.issue(); const ticket = await f.scopes.begin(ref.handle, f.context); + f.backendTo("new-config"); await assert.rejects(f.scopes.assertTurn(ticket, f.context)); + assert.equal(ticket.controller.signal.aborted, true); + const g = fixture(); const next = await g.issue(); const active = await g.scopes.begin(next.handle, g.context); + g.tick(300_000); await assert.rejects(g.scopes.assertTurn(active, g.context)); + assert.equal(active.controller.signal.aborted, true); assert.equal(g.scopes.scopes.size, 0); +}); + +test("bounded host scopes reject malformed snapshots without registering partial targets", async () => { + const f = fixture(); await assert.rejects(f.issue([null])); assert.equal(f.scopes.scopes.size, 0); + await assert.rejects(f.issue([f.target("terminal-a"), f.target("terminal-a")])); + for (let i = 0; i < 8; i++) await f.issue(); + await assert.rejects(f.issue()); + f.tick(300_000); await f.issue(); assert.equal(f.scopes.scopes.size, 1); + f.scopes.shutdown(); await assert.rejects(f.issue()); +}); diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json index d6d71c40a..05da0eb2e 100644 --- a/electron/plugins/generated/plugin-contract.schema.json +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -1771,6 +1771,8 @@ "enum": [ "storage", "ai.invoke", + "ai.agent.use", + "ai.agent.actions", "context.selected.list", "context.selected.read", "runtime.advanced", @@ -1815,6 +1817,8 @@ "enum": [ "storage", "ai.invoke", + "ai.agent.use", + "ai.agent.actions", "context.selected.list", "context.selected.read", "runtime.advanced", @@ -7186,6 +7190,402 @@ } }, "additionalProperties": false + }, + "PluginAgentFeature": { + "const": "ai.agent-sessions" + }, + "PluginAgentBackendKind": { + "enum": [ + "catty", + "claude", + "codex", + "copilot", + "cursor", + "codebuddy", + "opencode", + "grok", + "mimo" + ] + }, + "PluginAgentBackend": { + "type": "object", + "required": [ + "backendRef", + "label", + "backend", + "status", + "reason" + ], + "properties": { + "backendRef": { + "type": "string", + "format": "uuid" + }, + "label": { + "type": "string", + "maxLength": 160 + }, + "backend": { + "$ref": "#/$defs/PluginAgentBackendKind" + }, + "status": { + "enum": [ + "supported", + "unsupported", + "unavailable" + ] + }, + "reason": { + "enum": [ + "ready", + "not-configured", + "native-boundary-unverified", + "configuration-unavailable" + ] + } + }, + "additionalProperties": false + }, + "PluginAgentBackendsResult": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/PluginAgentBackend" + } + } + }, + "additionalProperties": false + }, + "PluginAgentTargetSummary": { + "type": "object", + "required": [ + "title", + "kind" + ], + "properties": { + "title": { + "type": "string", + "maxLength": 160 + }, + "kind": { + "const": "terminal" + } + }, + "additionalProperties": false + }, + "PluginAgentTargetsResult": { + "type": "object", + "required": [ + "selectionHandle", + "expiresAt", + "items" + ], + "properties": { + "selectionHandle": { + "type": "string", + "format": "uuid" + }, + "expiresAt": { + "type": "integer", + "minimum": 0 + }, + "items": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/PluginAgentTargetSummary" + } + } + }, + "additionalProperties": false + }, + "PluginAgentOpenParams": { + "type": "object", + "required": [ + "backendRef", + "selectionHandle" + ], + "properties": { + "backendRef": { + "type": "string", + "format": "uuid" + }, + "selectionHandle": { + "type": "string", + "format": "uuid" + }, + "conversationRef": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "PluginAgentChatRef": { + "type": "object", + "required": [ + "chatHandle" + ], + "properties": { + "chatHandle": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "PluginAgentChatResult": { + "type": "object", + "required": [ + "chatHandle", + "conversationRef", + "backendLabel", + "expiresAt" + ], + "properties": { + "chatHandle": { + "type": "string", + "format": "uuid" + }, + "conversationRef": { + "type": "string", + "format": "uuid" + }, + "backendLabel": { + "type": "string", + "maxLength": 160 + }, + "expiresAt": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "PluginAgentChatSummary": { + "type": "object", + "required": [ + "conversationRef", + "title", + "backend", + "updatedAt" + ], + "properties": { + "conversationRef": { + "type": "string", + "format": "uuid" + }, + "title": { + "type": "string", + "maxLength": 160 + }, + "backend": { + "$ref": "#/$defs/PluginAgentBackendKind" + }, + "updatedAt": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "PluginAgentChatsResult": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "maxItems": 64, + "items": { + "$ref": "#/$defs/PluginAgentChatSummary" + } + } + }, + "additionalProperties": false + }, + "PluginAgentSendParams": { + "type": "object", + "required": [ + "chatHandle", + "text" + ], + "properties": { + "chatHandle": { + "type": "string", + "format": "uuid" + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "pattern": "^[^\\u0000]*$" + } + }, + "additionalProperties": false + }, + "PluginAgentTurnRef": { + "type": "object", + "required": [ + "turnHandle" + ], + "properties": { + "turnHandle": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "PluginAgentTurnResult": { + "type": "object", + "required": [ + "turnHandle", + "expiresAt" + ], + "properties": { + "turnHandle": { + "type": "string", + "format": "uuid" + }, + "expiresAt": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "PluginAgentMessage": { + "type": "object", + "required": [ + "role", + "text" + ], + "properties": { + "role": { + "enum": [ + "user", + "assistant" + ] + }, + "text": { + "type": "string", + "maxLength": 32768 + } + }, + "additionalProperties": false + }, + "PluginAgentHistoryResult": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "maxItems": 200, + "items": { + "$ref": "#/$defs/PluginAgentMessage" + } + } + }, + "additionalProperties": false + }, + "PluginAgentEvent": { + "oneOf": [ + { + "type": "object", + "required": [ + "kind", + "text" + ], + "properties": { + "kind": { + "const": "text" + }, + "text": { + "type": "string", + "maxLength": 4096 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "capabilityId", + "state" + ], + "properties": { + "kind": { + "const": "activity" + }, + "capabilityId": { + "type": "string", + "maxLength": 160 + }, + "state": { + "enum": [ + "started", + "completed", + "denied" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "inputTokens", + "outputTokens" + ], + "properties": { + "kind": { + "const": "usage" + }, + "inputTokens": { + "type": "integer", + "minimum": 0 + }, + "outputTokens": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "reason" + ], + "properties": { + "kind": { + "const": "end" + }, + "reason": { + "enum": [ + "completed", + "cancelled", + "unavailable", + "budget-exceeded" + ] + } + }, + "additionalProperties": false + } + ] } } } diff --git a/electron/plugins/globalAgent.test.cjs b/electron/plugins/globalAgent.test.cjs new file mode 100644 index 000000000..c98bb8df8 --- /dev/null +++ b/electron/plugins/globalAgent.test.cjs @@ -0,0 +1,4 @@ +"use strict"; +require("./agent/delegatedScope.test.cjs"); +require("./agent/conversationStore.test.cjs"); +require("./agent/contract.test.cjs"); diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index b4194c8e5..97b3048ee 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -1698,6 +1698,8 @@ "enum": [ "storage", "ai.invoke", + "ai.agent.use", + "ai.agent.actions", "context.selected.list", "context.selected.read", "runtime.advanced", @@ -1742,6 +1744,8 @@ "enum": [ "storage", "ai.invoke", + "ai.agent.use", + "ai.agent.actions", "context.selected.list", "context.selected.read", "runtime.advanced", @@ -5004,6 +5008,402 @@ } }, "additionalProperties": false + }, + "PluginAgentFeature": { + "const": "ai.agent-sessions" + }, + "PluginAgentBackendKind": { + "enum": [ + "catty", + "claude", + "codex", + "copilot", + "cursor", + "codebuddy", + "opencode", + "grok", + "mimo" + ] + }, + "PluginAgentBackend": { + "type": "object", + "required": [ + "backendRef", + "label", + "backend", + "status", + "reason" + ], + "properties": { + "backendRef": { + "type": "string", + "format": "uuid" + }, + "label": { + "type": "string", + "maxLength": 160 + }, + "backend": { + "$ref": "#/$defs/PluginAgentBackendKind" + }, + "status": { + "enum": [ + "supported", + "unsupported", + "unavailable" + ] + }, + "reason": { + "enum": [ + "ready", + "not-configured", + "native-boundary-unverified", + "configuration-unavailable" + ] + } + }, + "additionalProperties": false + }, + "PluginAgentBackendsResult": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/PluginAgentBackend" + } + } + }, + "additionalProperties": false + }, + "PluginAgentTargetSummary": { + "type": "object", + "required": [ + "title", + "kind" + ], + "properties": { + "title": { + "type": "string", + "maxLength": 160 + }, + "kind": { + "const": "terminal" + } + }, + "additionalProperties": false + }, + "PluginAgentTargetsResult": { + "type": "object", + "required": [ + "selectionHandle", + "expiresAt", + "items" + ], + "properties": { + "selectionHandle": { + "type": "string", + "format": "uuid" + }, + "expiresAt": { + "type": "integer", + "minimum": 0 + }, + "items": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/PluginAgentTargetSummary" + } + } + }, + "additionalProperties": false + }, + "PluginAgentOpenParams": { + "type": "object", + "required": [ + "backendRef", + "selectionHandle" + ], + "properties": { + "backendRef": { + "type": "string", + "format": "uuid" + }, + "selectionHandle": { + "type": "string", + "format": "uuid" + }, + "conversationRef": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "PluginAgentChatRef": { + "type": "object", + "required": [ + "chatHandle" + ], + "properties": { + "chatHandle": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "PluginAgentChatResult": { + "type": "object", + "required": [ + "chatHandle", + "conversationRef", + "backendLabel", + "expiresAt" + ], + "properties": { + "chatHandle": { + "type": "string", + "format": "uuid" + }, + "conversationRef": { + "type": "string", + "format": "uuid" + }, + "backendLabel": { + "type": "string", + "maxLength": 160 + }, + "expiresAt": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "PluginAgentChatSummary": { + "type": "object", + "required": [ + "conversationRef", + "title", + "backend", + "updatedAt" + ], + "properties": { + "conversationRef": { + "type": "string", + "format": "uuid" + }, + "title": { + "type": "string", + "maxLength": 160 + }, + "backend": { + "$ref": "#/$defs/PluginAgentBackendKind" + }, + "updatedAt": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "PluginAgentChatsResult": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "maxItems": 64, + "items": { + "$ref": "#/$defs/PluginAgentChatSummary" + } + } + }, + "additionalProperties": false + }, + "PluginAgentSendParams": { + "type": "object", + "required": [ + "chatHandle", + "text" + ], + "properties": { + "chatHandle": { + "type": "string", + "format": "uuid" + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 16384, + "pattern": "^[^\\u0000]*$" + } + }, + "additionalProperties": false + }, + "PluginAgentTurnRef": { + "type": "object", + "required": [ + "turnHandle" + ], + "properties": { + "turnHandle": { + "type": "string", + "format": "uuid" + } + }, + "additionalProperties": false + }, + "PluginAgentTurnResult": { + "type": "object", + "required": [ + "turnHandle", + "expiresAt" + ], + "properties": { + "turnHandle": { + "type": "string", + "format": "uuid" + }, + "expiresAt": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "PluginAgentMessage": { + "type": "object", + "required": [ + "role", + "text" + ], + "properties": { + "role": { + "enum": [ + "user", + "assistant" + ] + }, + "text": { + "type": "string", + "maxLength": 32768 + } + }, + "additionalProperties": false + }, + "PluginAgentHistoryResult": { + "type": "object", + "required": [ + "items" + ], + "properties": { + "items": { + "type": "array", + "maxItems": 200, + "items": { + "$ref": "#/$defs/PluginAgentMessage" + } + } + }, + "additionalProperties": false + }, + "PluginAgentEvent": { + "oneOf": [ + { + "type": "object", + "required": [ + "kind", + "text" + ], + "properties": { + "kind": { + "const": "text" + }, + "text": { + "type": "string", + "maxLength": 4096 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "capabilityId", + "state" + ], + "properties": { + "kind": { + "const": "activity" + }, + "capabilityId": { + "type": "string", + "maxLength": 160 + }, + "state": { + "enum": [ + "started", + "completed", + "denied" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "inputTokens", + "outputTokens" + ], + "properties": { + "kind": { + "const": "usage" + }, + "inputTokens": { + "type": "integer", + "minimum": 0 + }, + "outputTokens": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "kind", + "reason" + ], + "properties": { + "kind": { + "const": "end" + }, + "reason": { + "enum": [ + "completed", + "cancelled", + "unavailable", + "budget-exceeded" + ] + } + }, + "additionalProperties": false + } + ] } } } diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index d14323069..6205935c8 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -486,7 +486,7 @@ export type MenuLocation = "commandPalette" | "application" | "host/context" | " export type NetworkCredentialLeaseFeature = "network.credential-lease"; -export type NonResourceScopedPermission = "storage" | "ai.invoke" | "context.selected.list" | "context.selected.read" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "secrets" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer" | "terminal.selection.read" | "terminal.input.propose"; +export type NonResourceScopedPermission = "storage" | "ai.invoke" | "ai.agent.use" | "ai.agent.actions" | "context.selected.list" | "context.selected.read" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "secrets" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer" | "terminal.selection.read" | "terminal.input.propose"; export type NullableRpcId = (RpcId) | (null); @@ -554,6 +554,100 @@ export type PermissionSet = { optional?: Array; }; +export type PluginAgentBackend = { + backendRef: string; + label: string; + backend: PluginAgentBackendKind; + status: "supported" | "unsupported" | "unavailable"; + reason: "ready" | "not-configured" | "native-boundary-unverified" | "configuration-unavailable"; +}; + +export type PluginAgentBackendKind = "catty" | "claude" | "codex" | "copilot" | "cursor" | "codebuddy" | "opencode" | "grok" | "mimo"; + +export type PluginAgentBackendsResult = { + items: Array; +}; + +export type PluginAgentChatRef = { + chatHandle: string; +}; + +export type PluginAgentChatResult = { + chatHandle: string; + conversationRef: string; + backendLabel: string; + expiresAt: number; +}; + +export type PluginAgentChatsResult = { + items: Array; +}; + +export type PluginAgentChatSummary = { + conversationRef: string; + title: string; + backend: PluginAgentBackendKind; + updatedAt: number; +}; + +export type PluginAgentEvent = ({ + kind: "text"; + text: string; +}) | ({ + kind: "activity"; + capabilityId: string; + state: "started" | "completed" | "denied"; +}) | ({ + kind: "usage"; + inputTokens: number; + outputTokens: number; +}) | ({ + kind: "end"; + reason: "completed" | "cancelled" | "unavailable" | "budget-exceeded"; +}); + +export type PluginAgentFeature = "ai.agent-sessions"; + +export type PluginAgentHistoryResult = { + items: Array; +}; + +export type PluginAgentMessage = { + role: "user" | "assistant"; + text: string; +}; + +export type PluginAgentOpenParams = { + backendRef: string; + selectionHandle: string; + conversationRef?: string; +}; + +export type PluginAgentSendParams = { + chatHandle: string; + text: string; +}; + +export type PluginAgentTargetsResult = { + selectionHandle: string; + expiresAt: number; + items: Array; +}; + +export type PluginAgentTargetSummary = { + title: string; + kind: "terminal"; +}; + +export type PluginAgentTurnRef = { + turnHandle: string; +}; + +export type PluginAgentTurnResult = { + turnHandle: string; + expiresAt: number; +}; + export type PluginAIBooleanResult = { ok: boolean; }; @@ -839,7 +933,7 @@ export type PluginNetworkResponse = { }; }; -export type PluginPermission = "storage" | "ai.invoke" | "context.selected.list" | "context.selected.read" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "network" | "network.stream" | "filesystem.read" | "filesystem.write" | "secrets" | "companion.execute" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer" | "terminal.selection.read" | "terminal.input.propose"; +export type PluginPermission = "storage" | "ai.invoke" | "ai.agent.use" | "ai.agent.actions" | "context.selected.list" | "context.selected.read" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "network" | "network.stream" | "filesystem.read" | "filesystem.write" | "secrets" | "companion.execute" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer" | "terminal.selection.read" | "terminal.input.propose"; export type PluginSelectedContextContent = { handle: string; diff --git a/packages/plugin-contract/src/index.ts b/packages/plugin-contract/src/index.ts index 3b42b9b0c..515b6a3b9 100644 --- a/packages/plugin-contract/src/index.ts +++ b/packages/plugin-contract/src/index.ts @@ -55,6 +55,7 @@ export { inspectPluginBrandIcon, PLUGIN_BRAND_ICON_FEATURE, PLUGIN_BRAND_ICON_MA export const PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE = "network.credential-lease" as const satisfies import("./generated/plugin-contract.js").NetworkCredentialLeaseFeature; export const PLUGIN_BYTE_STREAM_FEATURE = "network.byte-streams" as const satisfies import("./generated/plugin-contract.js").ByteStreamFeature; export const PLUGIN_AI_MODEL_INVOCATION_FEATURE = "ai.model-invocation" as const satisfies import("./generated/plugin-contract.js").PluginAIModelInvocationFeature; +export const PLUGIN_AGENT_SESSIONS_FEATURE = "ai.agent-sessions" as const satisfies import("./generated/plugin-contract.js").PluginAgentFeature; export const PLUGIN_SELECTED_CONTEXT_FEATURE = "context.selected-read" as const satisfies import("./generated/plugin-contract.js").PluginSelectedContextFeature; export const PLUGIN_HOST_INTERACTION_FEATURE = "host.interactions" as const satisfies import("./generated/plugin-contract.js").HostInteractionFeature; diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 6fc52f531..2d710a3af 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -685,6 +685,19 @@ export interface PluginSelectedContextClient { read(params: import("@netcatty/plugin-contract").PluginSelectedContextRef): Promise; } +/** Configurations, targets and native resume IDs stay in the trusted host. */ +export interface PluginAgentClient { + listBackends(params: import("@netcatty/plugin-contract").PluginAIEmptyParams): Promise; + selectTargets(params: import("@netcatty/plugin-contract").PluginAIEmptyParams): Promise; + listChats(params: import("@netcatty/plugin-contract").PluginAIEmptyParams): Promise; + openChat(params: import("@netcatty/plugin-contract").PluginAgentOpenParams): Promise; + send(params: import("@netcatty/plugin-contract").PluginAgentSendParams): Promise; + read(params: import("@netcatty/plugin-contract").PluginAgentTurnRef): Promise; + history(params: import("@netcatty/plugin-contract").PluginAgentChatRef): Promise; + stop(params: import("@netcatty/plugin-contract").PluginAgentTurnRef): Promise; + closeChat(params: import("@netcatty/plugin-contract").PluginAgentChatRef): Promise; +} + export interface PluginByteConnection extends Disposable { readonly endpoint: string; readonly readable: PluginReadableByteStream; @@ -784,6 +797,7 @@ export interface PluginContext { readonly credentials: PluginCredentialBroker; readonly network: PluginNetworkClient; readonly ai: PluginAIClient; + readonly agent: PluginAgentClient; readonly selectedContext: PluginSelectedContextClient; readonly filesystem: PluginFilesystemClient; readonly companions: PluginCompanionService;