Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
docs(plugins): reconcile developer documentation with current contracts
vastsa84a389b7731d
diff --git a/apps/desktop/resources/skills/plugin-development.md b/apps/desktop/resources/skills/plugin-development.mdindex 71a17ce27..5e36eb066 100644--- a/apps/desktop/resources/skills/plugin-development.md+++ b/apps/desktop/resources/skills/plugin-development.md@@ -5,7 +5,8 @@ description: the user is writing, checking, packaging or debugging a PI-DesktopYou are working inside a PI-Desktop plugin. Use the `PluginScaffold`, `PluginCheck` and`PluginPack` tools instead of hand-rolling files or shell commands — they enforce the same-rules the installer does, so anything they accept will install.+authoring and package-safety rules. A clean check is preparation, not proof of+runtime compatibility, permission grants, successful loading, or marketplace approval.## Development loop@@ -34,16 +35,17 @@ Templates: `panel-basic` (a webview panel), `agent-tool-basic` (a tool the agent"ui": { "panel": "renderer/index.html" },"contributes": {"commands": [{ "id": "my-plugin.hello", "title": "Say hello" }],- "agentTools": [{ "name": "echo_text", "description": "Echo the input" }],- "skills": ["skills/my-plugin.md"],- "settings": [{ "key": "greeting", "type": "string", "default": "Hello" }]+ "settings": [{ "key": "greeting", "title": "Greeting", "type": "string", "default": "Hello" }]}}````schemaVersion`, `id`, `name`, `version` and `main` are required. `id` must match-`[a-zA-Z0-9][a-zA-Z0-9._-]*`; prefix personal plugins with `local.`. Every path is relative to-the plugin directory and may not escape it.+`^[a-z0-9]+(\.[a-z0-9_-]+)+$`; prefix personal plugins with `local.`. Entry, view, and skill paths are relative to the plugin directory and may not+escape it; declared theme assets have a separately validated external-path route.+`activationEvents` is metadata, not a lazy-loading scheduler. `engines.piDesktop`+does not replace testing on the oldest supported host. Export callbacks from the+entry module; there is no `entrypoints` manifest dispatcher.## Entry point@@ -69,9 +71,13 @@ async function onUnload() {module.exports = { onLoad, onUnload };```-`onLoad` must finish within 15s, other hooks within 5s, agent tools within 110s. An+Module evaluation plus `onLoad` has 15s; `onUnload` has 5s (1.5s on quit); agent+tools and Composer transforms have 110s. Anuncaught error during load rolls the whole load back and leaves the plugin in `load_error`.-Only `onLoad` and `onUnload` are fired today.+Only `onLoad` and `onUnload` are lifecycle hooks today. `onPanelInvoke`,+`onRendererCall`, `onComposerTransform`, and `onProviderOAuth` are separate+operation callbacks; `onInstall`, `onEnable`, `onDisable`, and `onUninstall`+are not called.## Panel UI@@ -79,8 +85,10 @@ PI-Desktop hosts every panel in a frameless window. The host reserves exactly atransparent 46px drag band and renders only a minimal fixed capsule in thetop-right with minimize, maximize/restore, and close controls. The panel title,toolbar, background, and every other visible surface belong to the plugin.-Normal-flow content is offset automatically, so do not add another 46px top-padding. The drag band is not clickable outside the capsule; development+New pages declare `<meta name="pi-plugin-chrome" content="v2">` and apply+`var(--pi-plugin-titlebar-height, 0px)` as page-owned top spacing once. Pages+without the marker retain the legacy additive offset; do not add another 46px+spacer there. Widgets and docked views use 0px. The drag band is not clickable outside the capsule; developmentpanels show a reminder for this constraint.For `position: fixed` or `position: sticky` top UI, use the host variable rather@@ -104,10 +112,16 @@ Account for the same 46px value in viewport-height calculations:The panel receives `window.pluginBridge`, not `pi`. Use the fixed bridge channels such as`ui.showToast`, `ui.closePanel`, `ui.getNotificationPermission`,`ui.requestNotificationPermission`, `ui.showNativeNotification`, `plugin.getSettings`,-`workspace.get`, `fs.readText`, `fs.stat`, `fs.readRange`, `fs.writeText`, `fs.glob`, `clipboard.readText`,-`clipboard.getHistory`, `clipboard.writeText`, `shell.openExternal`, and `net.fetch`.-Arbitrary Electron IPC and-general custom panel RPC are not exposed.+`workspace.get`, `session.getActive`, `ui.revealView`, `fs.readText`, `fs.stat`,+`fs.readRange`, `fs.readPreview`, `fs.openDefault`, `fs.openInBrowser`, `fs.reveal`,+`fs.list`, `fs.requestDirectory`, `fs.writeText`, `fs.glob`, `clipboard.readText`,+`clipboard.getHistory`, `clipboard.writeText`, `shell.openExternal`, `app.getAppearance`, `app.setTheme`, `themes.*`,+`models.list`, `net.getCapabilities`, and `net.fetch`. The bridge does not expose+`plugin.setSettings`, `fs.remove`, `agent.complete`, or general process APIs.+Unknown channels are forwarded to this plugin's `onPanelInvoke(channel, payload)`;+validate their payloads yourself. Arbitrary Electron IPC is not exposed.+Read `app.getAppearance` through the bridge for locale and react to+`appearance:changed`; plugin-owned UI must localize itself.## Renderer slots@@ -158,12 +172,27 @@ Every permission is declared in the manifest and granted at install time; an undfails at runtime. Ask for the least you need — the plugins page shows the risk tier to theuser.-- High risk: `net.fetch`, `fs.write`, `fs.delete`, `agent.prompt.inject`,- `agent.tool.register`, `agent.complete`, `renderer.extension`, `session.read`,- `mcp.server.local`, `mcp.server.remote`-- Medium: `fs.read`, `clipboard.read`, `clipboard.write`, `shell.openExternal`,- `background.service`, `bus.publish`, `bus.subscribe`, `models.list`, `usage.read`-- Low: `ui.panel`, `ui.theme`, `notify` (Toast and best-effort native notifications)+Use the complete matrix in `docs/spec/07-plugins/13-plugin-permissions-matrix.md`+when working in the host repository. Major gates include:++- `ui.panel` / `ui.view` for isolated pages; `renderer.extension` for trusted code+ in the host document; `agent.extension` for trusted code in the Agent sidecar.+- `agent.tool.register` for runtime tool registration; `agent.prompt.inject` for+ skill catalogs/bodies; `agent.complete` for quota-spending one-shot completions.+- `models.list`, `usage.read`, `session.read`, and the separate ownership-scoped+ `session.import`, `session.read.own`, `session.update.own`, `session.delete.own`.+- `provider.register` for manifest providers, `provider.oauth` for OAuth callbacks,+ `composer.transform` for draft transformations, `composer.suggest` for one+ dismissible placeholder line; these do not implicitly grant transcript reads.+- `ui.theme` for CSS/runtime themes/typed variables; `ui.settings` plus `ui.theme`+ for data-only `scenicThemes`; `ui.window.appearance` for native appearance.+- `net.fetch` / `net.websocket` for host egress, and separately reviewed+ `net.anyHost` if user-entered endpoints cannot be declared beforehand.+- `keyboard.globalShortcut` for host-owned system shortcuts; local `shortcut`+ settings remain application-scoped.+- `desktop.control`, `browser.cdp`, `project.create`, and `session.autoTitle` for+ their separate reviewed host operations. Dangerous desktop operations need+ `confirm: true` plus the user's host-owned native confirmation.### File and network range@@ -188,7 +217,8 @@ broadly but leak nothing". `manifest.fs` says which paths each file mode may toumanifest validation.- An absent or empty declaration grants nothing. A file access outside the scope reaches theuser as a native confirmation (allow once / allow this session / deny); an empty- `net.domains` means no egress at all, whatever `net.fetch` says.+ `net.domains` means no egress unless the user separately grants `net.anyHost`.+ That exception still refuses cloud metadata and grants no API permission itself.- Credentials are refused whatever the manifest says: `.env*`, `.ssh/`, `.aws/`, `.git/`,`*.pem`, and the app's own data directory. Symlinks are resolved first, so a link out of theworkspace does not get through.@@ -214,10 +244,68 @@ notification permission query. Native plugin notifications do not enter thedurable task notification inbox. Clicking a delivered notification restores andfocuses the main window but does not activate a session.-Supported host API groups are `app`, `plugin`, `commands`, `ui`, `workspace`, `fs`, `agent`,-`services`, `bus`, `clipboard`, `shell`, `net`, and `events`. There is no host archive,-arbitrary process, or network-server API. Skills, themes, and MCP servers are declarative-manifest contributions rather than runtime registration APIs.+Host API groups are `app`, `themes`, `plugin`, `commands`, `speech`, `composer`,+`ui`, `project`, `providers.oauth`, `workspace`, `desktop`, `audio`, `keyboard`,+`fs`, `agent`, `models`, `session`, `usage`, `services`, `bus`, `clipboard`,+`shell`, `browser`, `net`, and `events`. This is not the panel API or the renderer+API. There is no host archive, arbitrary process, or network-server API.+Skills, MCP servers, and providers are manifest-owned; themes additionally have+`pi.themes.upsert` / `remove` / `list` / `setVariables` runtime APIs.++## Tool, session, and async boundaries++Register tools in `onLoad` with the same descriptor as `contributes.agentTools`.+Tools are deferred behind `ToolSearch`. Plan/Goal hides and denies them by+default; opt in only read-only `action` values through `planSafeActions` on the+runtime registration. The runner checks `args.action` before execution. A low+risk label, session grant, or auto mode does not replace the allowlist.+Use the tool context's `signal`, `sessionId`, and `turnId`; cancel side work and+never replace the invoking session with whichever session is visible.++`pi.session.getActive()` and `session:activated` expose the selected session+snapshot without transcript access. Recheck session identity after an await.+`session:turnEnded` carries `{ sessionId, turnId, reason }`, once per settled+host turn to live listeners, without replay; late tools can still be running.+`pi.ui.revealView` needs `ui.view` and may reveal only your own declared view+for the session still on screen. Subscribe/unsubscribe with matching handlers.++`pi.session.getLlmContext()` and `includeSessionContext` completions need+`session.read` and an active invocation of this plugin's Agent tool. A service,+Composer callback, or selected-session snapshot does not grant this context.+`pi.models.list()` returns ready model keys without secrets. `pi.agent.complete`+uses the user's model, no tools, a 90s budget and eight calls per rolling minute.+Handle timeout/rate-limit/provider failures without infinite retries.++Imported sessions need declared `sessionSources`; operations are scoped to the+calling plugin. Historical project/model strings do not bind a live session;+use an explicit `projectId` with `project.create` when needed. Auto titles use+bounded first-turn context and compare-and-set `expectedTitle`; manual names win.++## Composer, providers, and real-time capabilities++`contributes.composerTransforms` invokes `onComposerTransform({ id, text,+modelKey? })` only after the user's action. Return a string (100,000-character+input/output cap). The host handles file-reference preservation, stale drafts,+session changes, and undo. No history or attachment payload is supplied.+`pi.composer.suggest({ sessionId, turnId?, text, ttlMs? })` needs+`composer.suggest`: one folded line, 200 characters, 120s default, 1..600s TTL.+It appears only for an empty visible Composer; Tab accepts, Esc dismisses. Normal+refusals are `{ shown: false, reason }`; it never sends a message. Prefer the+triggering turn-ended event's `turnId` to protect against late completions.++Providers are manifest-owned native rows. API-key providers can use Add Service;+empty models require `baseUrl` and discover after key save. OAuth needs both+provider grants and `onProviderOAuth(request, { signal })` for login/refresh.+Use host prompt/notify helpers; only this provider's refresh callback receives+its existing credential. Never log or copy it into settings or bus messages.++`pi.keyboard` registers at most eight own-command global shortcuts; inspect+`registered`/`error` instead of assuming a conflict throws. `pi.net.websocket`+provides four host-owned sockets, 1 MiB frames, 4 MiB queued sends, with per-socket+`net:websocket:*` events and unload cleanup. `ui.microphone` is panel audio only.+All ten background `pi.audio.*` methods exist but have no device backend:+authorized calls still return/throw `UNSUPPORTED`. Speech adapters use the+separate `speech.adapter.register` gate.Prefer these host APIs over raw Node file or network APIs. The permission gateway covers thehost API surface; the separate Node plugin process is not yet an operating-system capability@@ -254,5 +342,14 @@ bus payloads.A `.piplug` is a **store-only (uncompressed) zip** — the installer rejects deflated entries.Always produce one with `PluginPack`, never with `zip` or `tar`. `.git`, `node_modules` and-`dist` are excluded automatically; the package must stay under 2000 files and 50 MB, and may+`dist` and credential files (`.env`, `.env.*`, `.npmrc`, `*.pem`, `*.key`) are+excluded automatically; the package must stay under 2000 files and 50 MB, and maynot contain symlinks.+++`pi-plugin publish` in the repository CLI prepares a local `.submission.json`+and `.piplug`; it does not upload. Ignore `dist/` before its clean-worktree check.+Publish through the official plugin center (`plugins.aiuo.net`); the distribution+mirror does not host plugin source. Full author guide: `docs/plugin-development.md`+and its Chinese mirror. Do not treat draft pages under `docs/plugin-plan` as+implemented SDK exports.diff --git a/docs/plugin-development.md b/docs/plugin-development.mdindex 54e68ccb7..8f06c95ab 100644--- a/docs/plugin-development.md+++ b/docs/plugin-development.md@@ -2,7 +2,8 @@This guide is the shortest complete path from an empty folder to a tested`.piplug` package. It describes the plugin runtime that PI-Desktop ships today.-The files under [`docs/spec/07-plugins`](spec/07-plugins/README.md) remain the+The SDK types, host validators, runtime dispatch, and executable tests are the+implementation evidence. The files under [`docs/spec/07-plugins`](spec/07-plugins/README.md) remain thenormative contract when this guide and a specification differ.## 1. What a plugin can add@@ -25,6 +26,15 @@ A plugin can contribute one or more of these capabilities:| Message bus | Typed-by-convention events between plugins | `contributes.bus`, bus permissions || Renderer slot | UI drawn inside the app's own window: composer controls, message action bars, blocks below a reply, tool cards, code-block renderers, corner layers | `renderer`, `renderer.extension` permission, `packages/plugin-sdk/src/renderer.ts` || Composer suggestion | One dismissible line offered to the input box, taken with Tab | `pi.composer.suggest`, `composer.suggest` permission |+| Provider | API-key, no-auth, or OAuth model service | `contributes.providers`, `provider.register`; OAuth also needs `provider.oauth` |+| Session import | Import, read, rename, and delete this plugin's own history | `contributes.sessionSources`, matching `session.*` grants |+| Usage facts | Compute your own usage dashboard | `pi.usage.listTurns`, `usage.read` |+| Composer transform | An explicit draft-text action with undo | `contributes.composerTransforms`, `onComposerTransform`, `composer.transform` |+| Global shortcut | Invoke your command while the app is unfocused | `contributes.globalShortcuts`, `pi.keyboard`, `keyboard.globalShortcut` |+| Trusted agent extension | pi ExtensionAPI hooks, tools, commands, and custom agents | `contributes.agentExtensions`, `agent.extension` |+| Real-time connection | Host-owned, bounded WebSockets | `pi.net.websocket`, `net.websocket` |+| Browser / desktop control | Reviewed browser or app operations | `pi.browser`, `browser.cdp`; `pi.desktop`, `desktop.control` |+| Speech adapter | Add a speech protocol handled by the plugin process | `pi.speech`, `speech.adapter.register` |Plugin entry code runs in a dedicated Node process. Panels run in sandboxed,context-isolated Electron windows with no Node integration. Calls from either@@ -45,8 +55,9 @@ For the recommended app-first path, you need:- a text editor.- To import a pi extension directory with npm dependencies, a system `npm` executable must be on `PATH`. Release builds ship no standalone Node/npm; without it, PI-Desktop reports a warning and the imported dependency cannot load.-For the repository CLI path, you also need Node.js 22.19 or newer, pnpm 10 or-newer, and a checkout of this repository. The devkit and SDK are currently+For the repository CLI path, use the Node.js and pnpm versions declared in the+root `package.json` (`engines` and `packageManager`) and a checkout of this+repository. The devkit and SDK are currentlyprivate workspace packages, so do not assume that `npm install@pi-desktop/plugin-devkit` works outside this repository.@@ -158,9 +169,13 @@ The following three files show the complete command-to-panel path.}```-`schemaVersion`, `id`, `name`, `version`, and `main` are required. Every file-path is relative to the plugin root and must stay inside it. Declare only the-permissions the plugin actually needs.+`schemaVersion`, `id`, `name`, `version`, and `main` are required. Entry, view,+and skill paths are relative to the plugin root and must stay+inside it. Theme assets have a separately validated external-path route (§6.7).+Plugin ids must match `^[a-z0-9]+(\.[a-z0-9_-]+)+$`; uppercase and undotted+ids are rejected. `activationEvents` is descriptive metadata today, not a lazy+activation scheduler: enabled plugins load at startup or explicit enable/load.+Declare only the permissions the plugin actually needs.### `main.js`@@ -190,8 +205,11 @@ ES module. Module evaluation plus `onLoad` has a 15-second budget. `onUnload`has a 5-second budget and is best-effort, so release timers and subscriptionspromptly.-Only `onLoad` and `onUnload` are fired today. Other lifecycle names in the-manifest are reserved for the planned full lifecycle.+Only `onLoad` and `onUnload` are lifecycle hooks today. Export them from the+entry module; there is no `entrypoints` manifest dispatcher. `onPanelInvoke`,+`onRendererCall`, `onComposerTransform`, and `onProviderOAuth` are operation+callbacks. `onInstall`, `onEnable`, `onDisable`, and `onUninstall` are not called.+During app quit the unload budget is shortened to 1.5 seconds.`onProviderOAuth` is a separate operation callback for OAuth providercontributions, not a lifecycle hook. It handles login and refresh only for its@@ -208,8 +226,10 @@ PI-Desktop hosts the panel in a frameless window on every platform. The hostreserves exactly a transparent 46 CSS px drag band and renders a minimal fixedcapsule in the top-right corner with minimize, maximize/restore, and closebuttons. The panel title, toolbar, and all other visible UI belong to the-plugin. Normal-flow content is automatically offset below the drag band, so do-not add another 46px top padding to compensate. The drag band is not clickable+plugin. New pages should declare `<meta name="pi-plugin-chrome" content="v2">` and+apply `var(--pi-plugin-titlebar-height, 0px)` to their own top spacing once.+Without this marker the host retains the legacy additive offset; do not add a+second 46px spacer to those pages. The drag band is not clickableoutside the capsule; development panels show a reminder for this constraint.If a panel uses `position: fixed` or `position: sticky` for a top toolbar,@@ -258,7 +278,9 @@ permissions, settings, is identical to a panel.<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="pi-plugin-chrome" content="v2" /><title>My First Plugin</title>+ <style>body { padding-top: var(--pi-plugin-titlebar-height, 0px); }</style></head><body><h1>My First Plugin</h1>@@ -327,8 +349,15 @@ await pi.agent.registerTool({Unregister it in `onUnload`. The host exposes it to the model under aplugin-namespaced name, applies the normal Agent permission policy, audits-execution, and enforces a 110-second plugin-side timeout. Plugin tools are not-available in Plan mode.+execution, and enforces a 110-second plugin-side timeout. Tools are deferred+behind `ToolSearch`. By default they are hidden and denied in Plan/Goal. A tool+may opt in with `planSafeActions` on its **runtime registration**, naming its+read-only `action` values; keep the manifest descriptor in sync. Registration+checks the list against a schema action enum when present, and execution in+Plan/Goal requires `args.action` to be in that list. Risk `low`, a session grant,+or `auto` cannot substitute for it. See [the API contract](spec/07-plugins/03-plugin-api.md#agent).+Use `context.signal` for cancellation and `context.sessionId` / `turnId` to+associate async work with the invoking turn. Never substitute the visible session.### 6.2 Skill@@ -405,7 +434,9 @@ page generates controls for `string`, `number`, `boolean`, `select`, `json`, and```Plugin shortcuts run only in the focused PI-Desktop window and are checked-against the app shortcut map. Global registration is not supported yet. The+against the app shortcut map. For OS-global bindings use the separate+`contributes.globalShortcuts` and+`pi.keyboard` surface with `keyboard.globalShortcut` (§6.17). Theplugin receives `plugin:settingsChanged` after a user edit. Do not putcredentials in `manifest.json` or source control.@@ -415,7 +446,7 @@ These APIs require explicit permissions:| Permission | Plugin-process API | Panel bridge channel ||---|---|---|-| `fs.read` | `pi.fs.readText`, `pi.fs.glob`, `pi.fs.list`, `pi.fs.requestDirectory` | `fs.readText`, `fs.glob`, `fs.list` |+| `fs.read` | `pi.fs.readText`, `stat`, `readRange`, `readPreview`, `openDefault`, `openInBrowser`, `reveal`, `glob`, `list`, `requestDirectory` | The same `fs.*` names; dropped-file grants use `fs.registerDropped` || `fs.write` | `pi.fs.writeText` | `fs.writeText` || `fs.delete` | `pi.fs.remove` | Not exposed || `clipboard.read` | `pi.clipboard.readText`, `pi.clipboard.getHistory` | `clipboard.readText`, `clipboard.getHistory` |@@ -430,11 +461,14 @@ what they want instead of waiting on a whole-repo walk that is capped at 500matches. Both obey the same read scope.A file permission is only half the declaration: `manifest.fs` says which paths-each mode may touch (see §6.5). Paths are relative to the mode's root. Absolute+each mode may touch (see §6.5). Paths are relative to the mode's root. An Agent tool uses its calling session's+project root; a panel uses the visible workspace or its view's browsed folder.+Registered project-group roots support reviewed absolute-path file actions;+this does not make arbitrary absolute paths valid for general file I/O. Absolutepaths and `..` escapes are rejected, as is a symlink that leaves the root.`fs.remove` is non-recursive, moves the path to the OS trash, and cannot remove-the root itself. `net.fetch` accepts HTTP(S) and only reaches hosts listed in-`manifest.net.domains`; `openExternal` accepts HTTP(S) and `mailto:` URLs.+the root itself. `net.fetch` accepts HTTP(S) and only reaches hosts allowed by+`manifest.net.domains` or the separately reviewed `net.anyHost` grant; `openExternal` accepts HTTP(S) and `mailto:` URLs.`pi.ui.notify` shows an in-app Toast. Native notifications are opt-in: call`pi.ui.requestNotificationPermission()` before@@ -518,8 +552,12 @@ loads answer to it too (a sandboxed panel still has a network stack), as doremote HTTP MCP servers you declare. `window.open` from a panel is refusedoutright.-An omitted, empty, or malformed `net.domains` means **no egress at all**, even-with `net.fetch` granted. Redirects are followed by hand and re-checked, so an+Without `net.anyHost`, an omitted or empty `net.domains` means **no egress**,+even with `net.fetch` granted; malformed declarations fail validation.+`net.anyHost` is an install-time high-risk exception for user-entered endpoints,+not a request-time prompt. It also covers WebSockets, panel traffic, and remote+MCP, but still blocks cloud-metadata destinations and grants no fetch/socket API+by itself. Redirects are followed by hand and re-checked, so anallowed host cannot bounce a request to one you did not declare. Bundle assetsinto the plugin rather than loading them from a CDN you would otherwise have todeclare.@@ -529,7 +567,7 @@ host never retries a request your plugin makes, so backoff after a rate limit isyour own policy rather than a hidden host behaviour. A call that comes back`>= 400` is still audited, as `ok: false` with the delay the response advertised.-### Fetch redirect policy (unreleased)+### Fetch redirect policyCheck host support before relying on a policy; old hosts can ignore unknownrequest fields. Never fall back to a raw network request.@@ -590,7 +628,7 @@ For a light-base theme, explicitly use `:root[data-theme="light"]`.The host sanitizes CSS, rejects `@import` and `url()` targets other than `data:`URIs or declared theme assets,-caps each stylesheet at 256 KiB, and allows eight themes per plugin. Optional+caps each stylesheet at 256 KiB, and imposes no per-plugin theme-count cap. Optional`assets` accepts `png`, `jpg`, `jpeg`, `webp`, `avif`, `svg`, and `woff2` files,with a summed limit of 4 MiB. Paths may be package-relative (inside the pluginroot, without traversal or `node_modules`) or absolute. Matching CSS URLs are@@ -600,14 +638,27 @@ revokes them. The renderer never receives the raw filesystem path.Optional `contributes.windowAppearance.backgroundColor` supplies `light`/`dark`colors in `#rrggbb` or `#rrggbbaa` form and requires `ui.window.appearance` inaddition to `ui.theme`. It applies only while that plugin's theme is selected;-switching away restores the host background. macOS retains its vibrancy.+switching away restores the host background. On macOS the default translucent+window ignores the color; turning off **Translucent window** applies it to the+opaque native surface. `cornerRadius` accepts integer 0..24 DIP: Windows 11+uses square corners for 0 and its system-rounded preference for positive values.+macOS keeps native corners.See the [manifest contract](spec/07-plugins/02-plugin-manifest-schema.md) forall theme and window-appearance fields.++Runtime theme changes do not require reload: `pi.themes.upsert`, `remove`,+`list`, and `pi.app.setTheme` use `ui.theme`. `pi.themes.setVariables(themeId,+values)` accepts only that theme's declared typed variables (`length`, `number`,+`color`, `select`), not arbitrary CSS or host-reserved tokens.+`contributes.scenicThemes` adds a host-rendered Settings card selector with+1..12 cards and requires both `ui.settings` and `ui.theme`. Arbitrary+`settingsDestinations` HTML/JS entries are not a public contribution.+### 6.8 Work panel view-A view is an interface docked in the app's right work panel, next to Review,-Terminal, Browser, and Files. It is the same isolated page as `ui.panel` — you+A view is an interface docked in the app's right work panel, alongside the+host's other tool and resource tabs. It is the same isolated page as `ui.panel` — youcan reuse the same HTML — but it is shown inside the main window instead of aseparate one, which suits anything the user consults while reading theconversation: a change list, a file tree, an issue queue.@@ -662,8 +713,9 @@ plugin restricted to certain projects does not offer its views in others.PI-Desktop's own file view is a bundled plugin built the same way —`apps/desktop/resources/plugins/pi.file-manager` is a complete, non-toy exampleof a view that reaches the workspace over the public bridge: `fs.openDefault`-and `fs.reveal` for the two actions only the host can perform, and the plugin's-own `onPanelInvoke` channels for everything it reads and writes itself.+and `fs.reveal` for the two actions only the host can perform, and its plugin-owned+`onPanelInvoke` operations. Custom channels must validate their own payloads;+they are not automatically converted into permission-gated `pi.fs` calls.### 6.9 MCP server@@ -673,6 +725,10 @@ remote server requires `mcp.server.remote`:```json{"contributes": {+ "settings": [+ { "key": "docsMode", "title": "Docs mode", "type": "string", "default": "public" },+ { "key": "clientName", "title": "Client name", "type": "string", "default": "my-plugin" }+ ],"mcpServers": [{"id": "docs",@@ -681,7 +737,7 @@ remote server requires `mcp.server.remote`:"command": "bin/docs-server","args": ["--stdio"],"env": {- "DOCS_TOKEN": { "setting": "docsToken" }+ "DOCS_MODE": { "setting": "docsMode" }}},{@@ -689,12 +745,13 @@ remote server requires `mcp.server.remote`:"transport": "http","url": "https://mcp.example.com/tools","headers": {- "Authorization": { "setting": "issuesAuthorization" }+ "X-Client-Name": { "setting": "clientName" }}}]},- "permissions": ["mcp.server.local", "mcp.server.remote"]+ "permissions": ["mcp.server.local", "mcp.server.remote"],+ "net": { "domains": ["mcp.example.com"] }}```@@ -706,7 +763,9 @@ a real interpreter on `PATH`, falling back to `py -3`. Remote URLs may useHTTP or HTTPS, and the host must be listed in `net.domains`; non-loopback HTTP is unencrypted, so use it only on a trustednetwork. Setting references read only this plugin's settings—the hostenvironment and provider secrets are never forwarded. MCP tools follow the-same Agent-only policy and namespacing as hand-written plugin tools.+same deferred tool catalog and namespacing as hand-written plugin tools.+Plugin MCP tools default to medium risk and are not Plan-safe merely because+the server describes them as read-only.### 6.10 Resident service and message bus@@ -757,8 +816,7 @@ subscription; never put secrets in the payload.### 6.11 Agent extension (pi ExtensionAPI module)A plugin can ship code that runs inside the agent process itself: a module-written against the pi CLI `ExtensionAPI`, the same contract pi extensions-use. It registers tools, slash commands, and hooks on every turn, tool call,+written against the pi CLI `ExtensionAPI`, an explicit subset of the pi extension contract. It registers tools, slash commands, and hooks on every turn, tool call,and provider request. Declare the modules and the `agent.extension`permission:@@ -816,7 +874,7 @@ What to know before you use it:ones (`setWidget`, `registerMessageRenderer`, `navigateTree`, and theother terminal-only surfaces) are inert and reported in the plugin row'sdetails, never thrown.-- **Existing pi extensions** need no changes: Plugins → overflow menu →+- **Import existing pi extensions** against the supported-member table in spec 16: Plugins → overflow menu →"Import pi extension" wraps a file or directory in a generated plugin. Ifthe directory declares production or optional dependencies, PI-Desktop firstruns `npm install --package-lock-only --omit=dev --legacy-peer-deps --no-audit@@ -902,6 +960,226 @@ only to code you trust.`examples/plugins/ui-slots-lab` mounts a sample on every slot.`packages/plugin-sdk/src/renderer.ts` carries the types and each slot's props,and the manifest side is [spec 07-plugins/02 §3.2](spec/07-plugins/02-plugin-manifest-schema.md).+### 6.13 Model providers and OAuth++Declare providers with `provider.register`. The host owns the provider row,+API-key form, encrypted secret storage, and model requests; a plugin never+receives a key entered into Add Service. The provider id becomes+`plugin:<pluginId>:<id>`. Categories and descriptions accept strings or+`{ en, "zh-CN" }` labels.++```json+{+ "permissions": ["provider.register"],+ "contributes": {+ "providers": [{+ "id": "example",+ "name": "Example AI",+ "category": "Example services",+ "description": "Models from your Example account.",+ "baseUrl": "https://api.example.com/v1",+ "apiStyle": "chat_completions",+ "authKind": "api_key",+ "models": []+ }]+ }+}+```++An empty model list is allowed only for an API-key provider with `baseUrl`:+after key save the host discovers the endpoint's models. Otherwise declare+1..64 models per provider. There is no per-plugin provider-count cap. Supported+API styles are `chat_completions`, `opencode_go`, `responses`,+`anthropic_messages`, `google_generative_ai`, `openai_codex_responses`, and+`pi_messages`; auth kinds are `api_key`, `none`, and `oauth`.++OAuth additionally requires `provider.oauth`, `baseUrl`, and+`onProviderOAuth(request, { signal })`. Handle `login` and `refresh`, returning+`{ accessToken, refreshToken?, expiresAt?, accountLabel?, headers? }`. Only a+refresh receives that contribution's existing credential. Use+`pi.providers.oauth.prompt(loginId, input)` / `.notify(loginId, event)` for+host-rendered interaction; respond to cancellation. The host keeps refresh+tokens out of the renderer and Agent Runtime. Use the host network gateway+with separate `net.fetch` and egress declarations for token requests.+Disabling a plugin retains and disables its provider rows; removing a provider+declaration or uninstalling deletes its row and stored credential.++### 6.14 Follow sessions, import history, and read usage++Use `pi.session.getActive()` and `session:activated` for the selected session.+No new permission is required, but activation scope still applies. The answer+is `null` away from chat, or `{ sessionId, projectPath, activeTurn }`, where+`activeTurn` is `null` or `{ turnId, startedAt }`. Treat snapshots as values+that can become stale across an `await`.++`session:turnEnded` carries `{ sessionId, turnId, reason }` with `completed`,+`aborted`, or `error`. Delivery is once per settled host turn to a live plugin,+without acknowledgement or replay. It does not prove every late tool has+exited. Subscribe and unsubscribe with the same function reference.++```js+function onSession(snapshot) {+ if (!snapshot) return;+ console.log("Selected session", snapshot.sessionId);+}++async function onLoad() {+ pi.events.on("session:activated", onSession);+ onSession(await pi.session.getActive());+}++function onUnload() {+ pi.events.off("session:activated", onSession);+}++module.exports = { onLoad, onUnload };+```++History management is a separate ownership boundary. Declare+`contributes.sessionSources: [{ id: "archive", label: "Archive" }]`, then use:++| Task | Methods | Permission |+|---|---|---|+| Import history | `session.import`, `session.importBatch` | `session.import` |+| Read imported history | `session.list`, `get`, `listMessages` | `session.read.own` |+| Rename imported session | `session.rename` | `session.update.own` |+| Trash or purge imported session | `session.delete` | `session.delete.own` |+| Create/reuse an explicit project binding | `project.create`; import with `projectId` | `project.create` |+| Generate a default title | `session.getAutoTitleContext`, `setAutoTitle` | `session.autoTitle` |+| Read completed-turn usage facts | `usage.listTurns` | `usage.read` |++Import is idempotent on `(pluginId, source, externalId)`. Use strict RFC3339+timestamps, monotonic message times, and the host-generated ids returned by+import. Imported provider/model/path strings are historical metadata, not live+bindings. Supply an existing `projectId` to bind a project; creating it does not+activate the workspace. Host-owned `sessionsChanged` refreshes the UI.++Reads and mutations address only this plugin's imported sessions. Batch `skip`+continues per item; `fail` is atomic. `trash` preserves transcript/origin and+`purge` deletes both. There is no general message-mutation or arbitrary+session-rebinding API. Auto-title exposes only the bounded first prompt/reply+for default-titled sessions and uses compare-and-set `expectedTitle`; a manual+rename wins. Usage facts contain counters and identifiers, never message bodies.+See [session contracts](spec/07-plugins/03-plugin-api.md) for payloads and limits.++### 6.15 Model catalog and one-shot completions++`pi.models.list()` (`models.list`) returns ready model bindings without+credentials. Pass the returned `key` unchanged to `pi.agent.complete`+(`agent.complete`); do not split a model id that may itself contain `/`.++```js+const models = await pi.models.list();+const model = models.find((item) => item.isDefault) ?? models[0];+if (!model) throw new Error("Configure a model first");+const answer = await pi.agent.complete({+ modelKey: model.key,+ system: "Answer briefly.",+ messages: [{ role: "user", content: "Explain this plugin's purpose." }],+});+await pi.ui.showToast(answer.text);+```++This spends the user's provider quota and uses no tools. The host owns auth,+provider error classification, and bounded provider retries. It enforces a 90s+budget and eight calls per plugin per rolling minute. `includeSessionContext`+also needs `session.read` and an active invocation of this plugin's Agent tool;+`session.getLlmContext()` has the same invocation-only rule. A background+service, Composer transform, or selected-session snapshot does not grant a+transcript read. Handle `TIMEOUT`, `RATE_LIMITED`, and classified provider+failures rather than retrying indefinitely.++### 6.16 Composer transforms and suggestions++A transform is invoked by the user and receives only `{ id, text, modelKey? }`.+Declare `contributes.composerTransforms` and `composer.transform`, then export:++```js+function onComposerTransform({ id, text }) {+ if (id !== "trim") throw new Error("Unknown transform");+ return text.trim();+}++module.exports = { onComposerTransform };+```++Declare `{ "id": "trim", "title": "Trim draft", "undoTitle": "Undo trim" }`+in that contribution. Input and output each allow 100,000 characters. The host+preserves file references, rejects stale edit/session results, and offers undo.+The callback gets no transcript, attachment data, or separate file-path metadata.++A suggestion is a separate `pi.composer` process API with `composer.suggest`.+It offers a placeholder line while the draft is empty; it never sends text.++```js+const active = await pi.session.getActive();+if (active) {+ const result = await pi.composer.suggest({+ sessionId: active.sessionId,+ turnId: active.activeTurn?.turnId,+ text: "Add a regression test for this change",+ ttlMs: 120_000,+ });+ if (!result.shown) console.log("Suggestion refused", result.reason);+}+// On your own cancellation path:+await pi.composer.clearSuggestion();+```++Text is folded to one line and cut at 200 characters; TTL defaults to 120s+and clamps to 1..600s. The user takes it with Tab or dismisses it with Esc.+Typing, pasting, adding an attachment, sending, switching session, a new turn,+unload, renderer reload, and window close clear it. Normal refusals return+`{ shown: false, reason }` (`session-not-visible`, `draft-not-empty`,+`stale-turn`, `replaced`, `unsupported`); malformed input or a missing grant+still throws. For work triggered by `session:turnEnded`, pass that event's+`turnId` so a late completion cannot suggest for a newer turn.++### 6.17 Global shortcuts, WebSockets, microphone, and speech++Global shortcuts are separate from app-local `shortcut` settings. Declare an+id and your own command under `contributes.globalShortcuts`, grant+`keyboard.globalShortcut`, and register the command in `onLoad`. A `default`+accelerator is registered after load; use `pi.keyboard.registerGlobalShortcut`+for runtime changes. Check `registered` and `error` in the result; conflicts+are returned as `registered: false`, not thrown. The host releases bindings on+unload, disable, and crash. There are at most eight per plugin.++WebSockets require `net.websocket` and the same egress policy as fetch. Use+`pi.net.websocket.connect` / `send` / `close` and `pi.events` events+`net:websocket:open`, `message`, `close`, `error` (each with the full prefix and+owning `socketId`). Four sockets, 1 MiB frames, and 4 MiB queued sends are the+host bounds. The host closes them with the plugin.++`ui.microphone` grants audio-only `getUserMedia` inside an isolated panel;+camera remains denied. Background `pi.audio.*` has types and permission gates+but **no device backend**: authorized calls return/throw `UNSUPPORTED`.+Do not build a working background recorder on that declaration alone.++`pi.speech.registerAdapter` / `unregisterAdapter` (`speech.adapter.register`)+adds a protocol handler. Return text, audio, or a host-executed HTTP plan.+Built-in ids `openai_audio` and `openai_chat_audio` are reserved; a plan carrying+a bound provider key must stay on that provider origin.++### 6.18 Browser and desktop operations++`fs.openInBrowser(path)` needs only `fs.read`, opens an existing readable HTML+file in a work-panel resource tab, and grants no browser automation. Use+`browser.cdp` only for `pi.browser.*` automation. Those calls are bound to the+invoking tool session; a background session cannot retarget the visible page.+CDP is allowlisted, and cookie/storage/target/network-interception methods stay+denied. `browser.reveal()` is explicit presentation and need not precede a+background navigation. Full-page captures are scaled to at most 1280×2048 and+have a 30s capture deadline.++`desktop.control` exposes `pi.desktop.listOperations()` and+`pi.desktop.invoke({ operation, args, confirm? })` over a reviewed catalog,+never arbitrary IPC. Dangerous operations require `confirm: true` **and** the+user's answer in a host-owned native dialog. Session collaboration `spawn` and+`send` additionally require an active plugin Agent tool invocation; the host+supplies source session/turn identity. Read the [desktop-control contract](spec/07-plugins/03-plugin-api.md)+before using operations that create, prompt, cancel, or delete sessions.+## 7. Permission designPermissions are both declared in `manifest.json` and granted by the user.@@ -909,9 +1187,9 @@ Undeclared or ungranted API calls fail with `PERMISSION_DENIED`.| Risk | Permissions ||---|---|-| Low | `ui.panel`, `ui.view`, `ui.theme`, `notify` |-| Medium | `clipboard.read`, `clipboard.write`, `fs.read`, `shell.openExternal`, `background.service`, `bus.publish`, `bus.subscribe`, `audio.playback.background`, `keyboard.globalShortcut` |-| High | `fs.write`, `fs.delete`, `agent.tool.register`, `agent.prompt.inject`, `renderer.extension`, `net.fetch`, `mcp.server.local`, `mcp.server.remote`, `audio.capture.background`, `net.websocket` |+| Low | `ui.panel`, `ui.view`, `ui.theme`, `ui.settings`, `ui.window.appearance`, `notify` |+| Medium | `ui.microphone`, `clipboard.read`, `clipboard.write`, `fs.read`, `composer.transform`, `composer.suggest`, `models.list`, `session.read.own`, `session.update.own`, `usage.read`, `shell.openExternal`, `background.service`, `bus.publish`, `bus.subscribe`, `audio.playback.background`, `keyboard.globalShortcut` |+| High | `fs.write`, `fs.delete`, `agent.tool.register`, `agent.prompt.inject`, `agent.complete`, `agent.extension`, `renderer.extension`, `provider.register`, `provider.oauth`, `desktop.control`, `project.create`, `session.read`, `session.import`, `session.delete.own`, `session.autoTitle`, `net.fetch`, `net.anyHost`, `mcp.server.local`, `mcp.server.remote`, `browser.cdp`, `audio.capture.background`, `speech.adapter.register`, `net.websocket` |`keyboard.globalShortcut` and `net.websocket` are implemented. `pi.audio.*`exists and is callable, and its methods keep their permission gate, but this@@ -922,12 +1200,14 @@ the refusal with real capture and playback.Two permissions carry a declared range as well as a name, and the user is shownboth: `manifest.fs` for the file modes (§6.5) and `manifest.net.domains` for-egress (§6.6). Both fail closed — an absent or empty declaration grants nothing,-so a plugin that says nothing about them reaches nothing.+egress (§6.6). Without the separately reviewed `net.anyHost` exception, an absent network+range grants no egress. An absent file scope grants no standing reach;+out-of-scope file operations still require host-owned consent.Ask for the smallest set possible. Adding a permission to a loaded development-plugin does not take effect through hot reload: PI-Desktop stops the reload and-asks the user to load the folder again so the new grant can be reviewed. Widening+plugin does not take effect through hot reload: PI-Desktop stops automatic reload so the new grant can be reviewed. Use the+plugin row's **More → Reload** action to explicitly review/reload the registered+folder, or load the development folder again. Widening`manifest.fs` counts as adding a permission for this purpose. Removingpermissions takes effect on reload.@@ -979,7 +1259,8 @@ pnpm pi-plugin check ../my-first-plugin`check` reports blocking errors and non-blocking warnings. It validates themanifest, referenced files, permissions, path containment, symlinks, package-size, and file count using the same rules as installation. Review warnings too,+size, and file count before packing. A clean result does not prove runtime loading, compatibility,+permission grants, or plugin-center approval; test the packed artifact too. Review warnings too,especially unused and high-risk permissions.Pack only with the devkit:@@ -996,7 +1277,8 @@ The result is:The command prints the package SHA-256. A `.piplug` is a store-only(uncompressed) ZIP; normal `zip` defaults usually produce an archive the-installer rejects. The devkit excludes `.git`, `node_modules`, and `dist`,+installer rejects. The devkit excludes `.git`, `node_modules`, and root `dist`, and omits+credential files (`.env`, `.env.*`, `.npmrc`, `*.pem`, `*.key`) with a warning. Itrejects symlinks, and enforces a maximum of 2,000 files and 50 MiB.To test the exact artifact users receive:@@ -1022,6 +1304,10 @@ from, so the plugin center can rebuild and compare the artifact:pnpm pi-plugin publish ../my-first-plugin [--out <dir>] [--ref <ref>] [--channel stable|beta] [--allow-dirty]```+`publish` prepares files locally; it does not upload or publish a version.+Ignore `dist/` in the plugin repository before running it, because packing+happens before the clean-worktree check.+The command runs the same `check` and `pack` steps, then reads the `origin`remote and `HEAD` of the plugin's repository. SSH remotes are rewritten to thecanonical `https://` form; remotes with embedded credentials or a non-HTTPS@@ -1083,7 +1369,7 @@ for roadmap details.| `pluginBridge` is unavailable | HTML opened in a normal browser | Test bridge calls inside the PI-Desktop panel || Tool never appears | Missing contribution, registration, or grant | Align `agentTools`, `registerTool`, and `agent.tool.register`; use Agent mode || Skill never applies | Missing permission or weak metadata | Add `agent.prompt.inject` and specific `name`/`description` front matter |-| Save reports `PERMISSION_DENIED` | Manifest widened permissions | Load the development folder again and review the new grant |+| Save reports `PERMISSION_DENIED` | Manifest widened permissions or file scope | Use More → Reload or load the folder again to review the new grant || Hot reload stops after a syntax error | Broken plugin is unloaded | Save the corrected file; the watcher remains active || Package install rejects compression | Archive was made with a generic ZIP tool | Rebuild it with `pi-plugin pack` || MCP server does not start | Invalid transport fields, command, URL, setting, or permission | Run `pi-plugin check`, then inspect logs by plugin id |@@ -1100,3 +1386,63 @@ for roadmap details.- [Developer experience](spec/07-plugins/10-plugin-devex.md)- [Permissions](spec/07-plugins/13-plugin-permissions-matrix.md)- [Hello reference plugin](https://github.com/vastsa/PI-Desktop/tree/main/examples/plugins/hello)++## 13. Complete SDK surface and source map++This inventory follows `PluginHostApi` in `packages/plugin-sdk/src/index.ts`.+It is a method index, not a blanket grant. The permission matrix, invocation+context, and availability restrictions above still apply; `pi.audio` remains+unsupported. The panel bridge is a smaller surface listed in API spec §6.++| Namespace | Methods |+|---|---|+| `pi.app` | `getVersion`, `getLocale`, `getAppearance`, `setTheme` |+| `pi.themes` | `upsert`, `remove`, `list`, `setVariables` |+| `pi.plugin` | `getId`, `getManifest`, `getSettings`, `setSettings`, `getDataPath` |+| `pi.commands` | `register`, `unregister` |+| `pi.speech` | `registerAdapter`, `unregisterAdapter` |+| `pi.composer` | `suggest`, `clearSuggestion` |+| `pi.ui` | `openPanel`, `closePanel`, `showToast`, `notify`, `getNotificationPermission`, `requestNotificationPermission`, `showNativeNotification`, `revealView` |+| `pi.project` | `create` |+| `pi.providers.oauth` | `prompt`, `notify` |+| `pi.workspace` | `get` |+| `pi.desktop` | `listOperations`, `invoke` |+| `pi.audio` | `getInputDevices`, `openInput`, `closeInput`, `getCaptureState`, `onInputFrame`, `offInputFrame`, `openOutput`, `writeOutput`, `stopOutput`, `closeOutput` |+| `pi.keyboard` | `registerGlobalShortcut`, `unregisterGlobalShortcut`, `listGlobalShortcuts` |+| `pi.fs` | `readText`, `stat`, `readRange`, `readPreview`, `openDefault`, `openInBrowser`, `reveal`, `writeText`, `glob`, `list`, `remove`, `requestDirectory` |+| `pi.agent` | `registerTool`, `unregisterTool`, `complete` |+| `pi.models` | `list` |+| `pi.session` | `getLlmContext`, `getActive`, `getAutoTitleContext`, `setAutoTitle`, `list`, `get`, `listMessages`, `import`, `importBatch`, `rename`, `delete` |+| `pi.usage` | `listTurns` |+| `pi.services` | `register`, `unregister` |+| `pi.bus` | `publish`, `subscribe` |+| `pi.clipboard` | `readText`, `writeText`, `getHistory` |+| `pi.shell` | `openExternal` |+| `pi.browser` | `reveal`, `navigate`, `action`, `setBounds`, `setVisible`, `getState`, `openExternal`, `snapshot`, `screenshot`, `click`, `fill`, `evaluate`, `console`, `cdp` |+| `pi.net` | `getCapabilities`, `fetch` |+| `pi.net.websocket` | `connect`, `send`, `close` |+| `pi.events` | `on`, `off` |++Renderer modules use a different `pi`: `plugin.id` / `version`,+`slots.register`, `ui.injectStyle`, `ui.openLayer`, `composer.subscribeDraft`,+and `dispatch`. Draft subscriptions require `composer.readDraft` in+`rendererActions`. Draft replacements use the captured `generation` as `expectedGeneration`,+require a user input event while the Composer is unfocused, and preserve every+host chip; inspect `renderer-composer.ts` rather than writing+host store state. No renderer action sends a message.++| Code / tests | What to verify |+|---|---|+| `packages/plugin-sdk/src/index.ts`, `renderer.ts`, `renderer-composer.ts` | Public types, contributions, permission vocabulary, renderer actions |+| `packages/plugin-sdk/src/{fs-policy,net-policy,theme-css,theme-variables,mcp-config}.ts` | Scope, egress, CSS, variable, and MCP validation |+| `packages/plugin-devkit/src/{templates,check,walk,pack,publish,cli}.ts` | Template files, checks, exclusions, archive format, submission preparation |+| `crates/host-core/src/plugins/{manifest,validation,install,registry}.rs` | Actual install, persistence, compatibility, and uninstall rules |+| `apps/desktop/electron/main/plugin-runtime.ts`, `plugin-host-process.mjs` | Broker dispatch, process callbacks, lifecycle, events, audit, and limits |+| `apps/desktop/electron/preload/plugin-panel.ts` | Actual panel bridge and page-owned chrome |+| `apps/desktop/test/plugin-*.test.mjs` | Host API, lifecycle, invocation scope, and representative plugin paths |+| `examples/plugins/hello`, `ui-slots-lab`, `fetch-redirect`, `roundtable` | Working contributions and focused probes |++`docs/plugin-plan` contains slot/API review pages and proposed runtime hooks.+A draft page is not an implemented SDK export. Start with the current SDK and+runtime when deciding whether a capability exists. The built-in authoring+instructions are shipped at `apps/desktop/resources/skills/plugin-development.md`.diff --git a/docs/spec/07-plugins/01-plugin-system.md b/docs/spec/07-plugins/01-plugin-system.mdindex e65f74c07..dcd8793fe 100644--- a/docs/spec/07-plugins/01-plugin-system.md+++ b/docs/spec/07-plugins/01-plugin-system.md@@ -12,11 +12,15 @@- user MCP tools use the prefix `mcp_<serverId>_<toolName>`, disjoint from D015'splugin namespace (D193)-Plan policy: plugin agent tools, plugin skills that register tools, and any-unknown plugin contribution are not visible or executable in Plan. This deny-is enforced by host-core before generic plugin permission evaluation and cannot-be bypassed by a low-risk manifest, a session grant, or `auto`. Plugin tools-remain available to the same Agent after an approved Plan → Agent transition.+Plugin tools are hidden and denied in Plan/Goal by default. A runtime tool+registration may opt in with non-empty `planSafeActions`; only an `args.action`+in that list may execute in those modes. The list is checked against the schema's+action enum when present. Keep the manifest descriptor and runtime registration+in sync: the runtime registration drives the executable tool. Risk `low`, session+grants, and `auto` do not substitute for the declaration. Host policy and the+plugin runner both check it; a disallowed runner action is `PERMISSION_DENIED`.+The declaration is an author assertion of read-only behavior, not a side-effect+sandbox (ADR 0211).## 1. Goals@@ -48,7 +52,8 @@ In one sentence:- Session commands- Settings- High-risk capabilities must go through the permission framework-- Plugins cannot directly obtain arbitrary Node/Electron privileges by default+- Brokered host APIs require declared grants; raw Node code in the plugin process+ is trusted user-privileged code, while isolated panels have no Node integration## 3. What plugins can do@@ -84,8 +89,7 @@ Each plugin is a directory:my-plugin/├── manifest.json # required├── package.json # optional (if it carries build artifacts / dependency metadata)-├── main.js # plugin runtime extension entry (restricted API)-├── preload.js # optional, plugin panel bridge+├── main.js # plugin entry; host injects the brokered pi API├── renderer/ # plugin UI (static assets)│ ├── index.html│ └── assets/@@ -99,7 +103,7 @@ my-plugin/### Install location```text-~/.pi-desktop/plugins/+<dataRoot>/plugins/├── installed/│ └── <plugin-id>/├── disabled/@@ -158,6 +162,8 @@ Developer mode can load a local path directly, without copying it into `installe]},"permissions": [+ "ui.panel",+ "agent.prompt.inject","clipboard.read","clipboard.write","notify",@@ -171,10 +177,6 @@ Developer mode can load a local path directly, without copying it into `installe},"engines": {"piDesktop": ">=0.1.0"- },- "entrypoints": {- "onLoad": "main.js#onLoad",- "onUnload": "main.js#onUnload"}}```@@ -205,14 +207,16 @@ Host Main (PI-Desktop)- Authorization management- Route command and tool calls-### 6.2 Plugin Runtime (restricted)-Plugin logic runs in a restricted environment; it is not equivalent to full Electron main privileges.+### 6.2 Plugin Runtime (separate process)+The plugin has no live Electron Main objects. Its `pi.*` calls are brokered,+but raw Node built-ins run with the user account's privileges; process isolation+is not an OS capability sandbox.**Implemented today (ADR 0008):** each plugin's main module runs in its own`utilityProcess` (`electron/main/plugin-host-process.mjs`) and reaches the hostonly through JSON RPC to the broker in `electron/main/plugin-runtime.ts`, whichenforces the API allowlist and the permission gateway. Plugin code never gets a-host object and cannot `require` host modules.+host object. Importing private host modules is not a supported plugin contract.Still open: capability sandboxing inside the plugin process (raw Node built-insare reachable there) and CPU/memory limits.@@ -271,7 +275,8 @@ are reachable there) and CPU/memory limits.## 7. Host API (callable by plugins)-Namespace: `pi.plugin.*`+Injected global: `pi`; `plugin` is one namespace within it. The complete method+index is in the [development guide](../../plugin-development.md#13-complete-sdk-surface-and-source-map).### Basics- `pi.app.getVersion()`@@ -281,7 +286,7 @@ Namespace: `pi.plugin.*`- `pi.commands.register(command)`- `pi.ui.openPanel(options?)`- `pi.ui.showToast(message)`-- `pi.ui.notify(title, body)`+- `pi.ui.notify({ title, body })`- `pi.ui.getNotificationPermission()`- `pi.ui.requestNotificationPermission()`- `pi.ui.showNativeNotification({ title, body? })`@@ -310,8 +315,8 @@ Namespace: `pi.plugin.*`Skills are contributed declaratively (`contributes.skills` + `agent.prompt.inject`),not invoked by the plugin: the host puts the catalog in the system prompt and the-model loads a body through the built-in `Skill` tool (D174). Planned, not-currently exposed: `pi.agent.appendSystemHint(text)`. When the body is loaded,+model loads a body through the built-in `Skill` tool (D174). There is no+imperative `appendSystemHint` host API. When the body is loaded,the tool result also identifies the `SKILL.md` location and the directory to usewhen resolving relative references; the catalog remains metadata-only.@@ -393,7 +398,8 @@ load and are downgraded to the minimum safe equivalent (ADR 0088).3. Users can revoke permissions on the plugin management page; a reload isrequired for a running plugin to observe the changed grant set-Per-call confirmation and any policy for direct Node access are not implemented.+Out-of-scope filesystem calls and dangerous desktop-control operations use+host-owned per-call consent. Raw Node API access has no OS capability sandbox.## 9. Command palette@@ -487,7 +493,6 @@ Status indicators:- error- dev-loaded-### 12.1 The activation-scope control### 12.1 The activation-scope controlOne control serves all three kinds (D192). It is a three-segment track ordereddiff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex 04927bcf1..1db8d94f8 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -52,7 +52,7 @@ type PluginManifestV1 = {};repository?: string;icon?: string; // relative path- main?: string; // plugin runtime entry+ main: string; // required plugin runtime entryrenderer?: string; // module the host evaluates to mount UI slots (§3.2)rendererActions?: string[]; // actions a renderer component may dispatch, at most 16rendererCallMethods?: string[]; // onRendererCall methods plugin.call may reach, at most 32@@ -64,14 +64,6 @@ type PluginManifestV1 = {engines?: {piDesktop?: string; // semver range};- entrypoints?: {- onInstall?: string;- onLoad?: string;- onEnable?: string;- onDisable?: string;- onUnload?: string;- onUninstall?: string;- };activationEvents?: string[]; // e.g. onCommand:xxx / onStartup/*** First-registration default for bundled plugins. Omitted means enabled.@@ -82,6 +74,13 @@ type PluginManifestV1 = {};```+The SDK author type accepts a string or contact object, but the current Rust+installer deserializes `author` as a string. Use a display string for installable+packages. SDK validation is not an exact mirror of host installation: `main`+is mandatory in both, while schema-version/metadata checks differ. Write+`schemaVersion: 1` and use `check` plus actual artifact installation; do not+interpret a permissive low-level parser as a supported compatibility contract.+## 3. UI config```ts@@ -89,6 +88,8 @@ type PluginUiConfig = {panel?: string; // html entrywidth?: number;height?: number;+ shape?: "panel" | "widget";+ alwaysOnTop?: boolean;resizable?: boolean;title?: string | {en: string;@@ -208,17 +209,14 @@ type PluginCommandContrib = {title: string;keywords?: string[];category?: string;- icon?: string;- requires?: PluginPermission[]; // extra per-command perms};type PluginAgentToolContrib = {name: string; // tool name exposed to agentdescription: string;- risk: "low" | "medium" | "high";- schema: Record<string, unknown>; // JSON schema object- timeoutMs?: number;- permissions?: PluginPermission[];+ risk?: "low" | "medium" | "high";+ schema?: unknown; // JSON schema object+ planSafeActions?: readonly string[]; // read-only action names for Plan/Goal};type PluginComposerTransformContrib = {@@ -236,7 +234,7 @@ type PluginSettingContrib = {enum?: Array<{ label: string; value: string | number | boolean }>;/** Required for shortcut settings; invokes a declared plugin command. */command?: string;- /** Fixed to plugin for now; global shortcut registration is not supported. */+ /** App-local setting scope; OS-global shortcuts use globalShortcuts instead. */scope?: "plugin";secret?: boolean;};@@ -571,24 +569,26 @@ grant the permission only to code you trust. See[03-plugin-api.md](03-plugin-api.md) and[13-plugin-permissions-matrix.md](13-plugin-permissions-matrix.md).-## 6. activationEvents (optional)--Examples:+## 6. activationEvents (optional metadata)-- `onStartup`-- `onCommand:demo.hello.say`-- `onAgentMode`-- `onWorkspaceOpen`+`activationEvents` may document intent such as `onStartup` or+`onCommand:demo.hello.say`. The current runtime eagerly loads enabled plugins+at restore/enable/development-load time; it does not implement an activation-event+scheduler. Do not rely on this field to defer initialization or constrain scope.+Use the host's activation-scope control for project eligibility.-MVP may implement only:-- `onStartup`-- `onCommand:*`+`engines.piDesktop` is author compatibility metadata; the marketplace catalog+also carries host-version constraints. A local directory passing `check` does+not prove runtime API availability. Feature-detect additive methods and test on+the oldest host you claim. Export `onLoad` / `onUnload` from `main`; there is no+`entrypoints` manifest contract.## 7. Validation rules1. `schemaVersion` must be `1`2. `id` / `name` / `version` are required-3. Whether a manifest that declares `ui.panel` needs the `ui.panel` permission implicitly (auto-filled) or by explicit declaration is an **open question** (tracked in [08-meta/open-questions.md](../08-meta/open-questions.md))+3. Opening `ui.panel` requires the explicit declared and granted `ui.panel`+ permission; a panel path does not implicitly grant it4. If `agentTools` are present, `agent.tool.register` must be declared5. Path fields must not use absolute paths or `..`6. `main` / `ui.panel` / skills / `views[].entry` paths must existdiff --git a/docs/spec/07-plugins/03-plugin-api.md b/docs/spec/07-plugins/03-plugin-api.mdindex 28eefe320..ed6f70961 100644--- a/docs/spec/07-plugins/03-plugin-api.md+++ b/docs/spec/07-plugins/03-plugin-api.md@@ -21,7 +21,7 @@ selectors, images, fonts, or arbitrary property names.Inside the plugin runtime, a global is available:```ts-declare const pi: PiPluginHostApi;+declare const pi: PluginHostApi;```## 3. API overview (MVP)@@ -98,8 +98,8 @@ pi.themes.list(): Promise<Array<{ id: string; themeId: string; label: string; ba### plugin```tspi.plugin.getId(): string-pi.plugin.getManifest(): PluginManifestV1-pi.plugin.getSettings<T=Record<string, unknown>>(): Promise<T>+pi.plugin.getManifest(): PluginManifest+pi.plugin.getSettings(): Promise<Record<string, unknown>>pi.plugin.setSettings(partial: Record<string, unknown>): Promise<void>pi.plugin.getDataPath(): Promise<string> // plugin-private directory```@@ -109,8 +109,10 @@ persists edits in the plugin's private settings file. Supported generatedcontrols are `string`, `number`, `boolean`, `select`, `json`, and `shortcut`.Generated `title` / `description` / `enum[].label` are author-language strings;the host does not resolve locale maps on them. A plugin that needs a localized-settings surface ships `settingsDestinations` and reads `pi.app.getLocale`-(ADR 0280). Shortcut settings are plugin-local: they invoke the declared+settings surface uses its own panel/view and reads `pi.app.getLocale`.+The data-only `scenicThemes` contribution has a host-rendered Settings surface;+`settingsDestinations` is not an implemented public contribution (ADR 0287).+Shortcut settings are plugin-local: they invoke the declared`command` only while the PI-Desktop app window is focused and while the plugin'sactivation scope matches the current project. They are never registered asOS-global shortcuts in this release. The host emits `plugin:settingsChanged`@@ -444,18 +446,22 @@ pi.agent.registerTool(tool: {description: stringrisk: "low"|"medium"|"high"schema: unknown+ planSafeActions?: readonly string[]execute: (args: unknown, ctx: ToolExecContext) => Promise<unknown>}): Promise<void>pi.agent.unregisterTool(name: string): Promise<void>```-Registered plugin agent tools are Agent-only contributions. During Plan the-host filters them out of the model tool list and rejects direct execution with-`PLUGIN_DISABLED_IN_PLAN`, including when the manifest risk is `low`, the user-has an `allow-session` grant, or the session permission mode is `auto`. A-successful plan approval makes the same registered tools eligible again under-the selected Agent permission policy.+Plugin tools are hidden and denied in Plan/Goal by default. A runtime tool+registration may opt in with non-empty `planSafeActions`; only an `args.action`+in that list may execute in those modes. The list is checked against the schema's+action enum when present. Keep the manifest descriptor and runtime registration+in sync: the runtime registration drives the executable tool. Risk `low`, session+grants, and `auto` do not substitute for the declaration. Host policy and the+plugin runner both check it; a disallowed runner action is `PERMISSION_DENIED`.+The declaration is an author assertion of read-only behavior, not a side-effect+sandbox (ADR 0211).```tstype ToolExecContext = {@@ -482,6 +488,9 @@ type PluginModelInfo = {providerName: stringmodelId: stringlabel: string+ alias?: string+ availableForSubagents?: boolean+ isDefault?: booleansupportsReasoning: booleanthinkingLevels: ThinkingLevel[]}@@ -1094,7 +1103,7 @@ the desired mode. This read-only query needs no network permission and performsno network I/O. A missing method, rejected query, or absent mode meansunsupported: do not send the request. Older hosts may silently ignore unknownfetch options, so passing `redirect` alone is **not** capability detection.-This API is unreleased; released 0.17.0 and older do not advertise it.+Current source implements this query; older hosts may not advertise it.No same-origin-only mode is introduced by this change.`fetch` answers with the upstream response unchanged — `status`, `headers`, and@@ -1364,9 +1373,8 @@ Delivered today:in-flight tool of that turn has exited — late results can still arrive — so aplugin must serialise or otherwise scope its cleanup by `turnId`. The eventalso needs no new permission: it travels on the existing event channel, and- subscribing to an unknown event name does not error. No published host emits it- yet — 0.14.8 does not include it — so a plugin that depends on it must require- the release that actually ships it rather than assume 0.14.7 or 0.14.8.+ subscribing to an unknown event name does not error. A plugin that depends on it must verify the host version it supports;+ historical hosts may not emit this additive event.- `session:activated` — payload is the `PluginActiveSession` object or `null`,sent whenever that snapshot changes: the user selected another session (or@@ -1438,7 +1446,8 @@ is not discarded; re-opening the same location does nothing. The payload isopaque to the host — each plugin decides what its `location` means — and itneeds no permission and adds no SDK method.-The host-owned preload forwards only fixed channels to the plugin runtime:+The host validates the sender and forwards calls to the plugin runtime,+which handles these built-in channels before falling back to `onPanelInvoke`:| Channel | Required permission ||---|---|@@ -1446,14 +1455,15 @@ The host-owned preload forwards only fixed channels to the plugin runtime:| `ui.notify` | `notify` || `ui.getNotificationPermission`, `ui.requestNotificationPermission`, `ui.showNativeNotification` | `notify` || `plugin.getSettings`, `workspace.get`, `app.getAppearance` | None |-| `app.setTheme`, `themes.upsert`, `themes.remove`, `themes.list` | `ui.theme` |+| `app.setTheme`, `themes.upsert`, `themes.remove`, `themes.list`, `themes.setVariables` | `ui.theme` || `models.list` | `models.list` |-| `fs.readText`, `fs.stat`, `fs.readRange`, `fs.readPreview`, `fs.openDefault`, `fs.openInBrowser`, `fs.reveal`, `fs.glob`, `fs.list` | `fs.read` |+| `fs.readText`, `fs.stat`, `fs.readRange`, `fs.readPreview`, `fs.openDefault`, `fs.openInBrowser`, `fs.reveal`, `fs.glob`, `fs.list`, `fs.requestDirectory`, `fs.registerDropped` | `fs.read` || `fs.writeText` | `fs.write` || `clipboard.readText`, `clipboard.getHistory` | `clipboard.read` || `clipboard.writeText` | `clipboard.write` || `shell.openExternal` | `shell.openExternal` || `net.fetch` | `net.fetch` |+| `net.getCapabilities` | None || `session.getActive` | None || `ui.revealView` | `ui.view` |@@ -1461,8 +1471,9 @@ The host-owned preload forwards only fixed channels to the plugin runtime:channel the host does not implement itself is forwarded to the plugin's`onPanelInvoke(channel, payload)`, so a plugin may define its own panel ↔ mainchannels; a plugin that exports no `onPanelInvoke` gets `UNSUPPORTED` from its own-process. The host-supported channels include `skill.list`, `skill.read`,-`skill.create`, `skill.update`, `skill.remove`, and `skill.setEnabled`.+process. The `skill.list` / `read` / `create` / `update` / `remove` / `setEnabled`+operations used by the bundled skill manager are plugin-owned `onPanelInvoke`+channels, not general host bridge APIs.### Panel events (host -> panel)@@ -1525,10 +1536,12 @@ Log fields:## 8. Versioning strategy-- The API surface is managed by `apiVersion`-- MVP `apiVersion = 1`-- A deprecated API is retained for at least one major version cycle-+The manifest authoring contract uses `schemaVersion: 1`; the current injected+API has no `apiVersion` property or negotiation call. Prefer additive APIs,+feature-detect optional methods, query `net.getCapabilities` for redirect modes,+and handle `UNSUPPORTED` on older hosts. Public SDK types and runtime dispatch+are the current callable surface; planned names do not become callable by being+listed in a document.## 9. Implementation status@@ -1562,9 +1575,10 @@ Native plugin notifications use the Electron main-process notification surface;they do not create durable rows in the task notification inbox and do notactivate a session on click.-Declarative contributions have no `pi.*` counterpart on purpose: skills, themes,-and MCP servers are read from the manifest by the host, so a plugin cannot add-one at runtime.+Skills and MCP servers are manifest contributions with no general runtime+registration API. Themes also support the permission-gated `pi.themes` runtime+registry, and providers remain manifest-owned. Composer, session import/read/+update/delete, usage, project, and desktop APIs follow their separate grants.All high-risk entry points assert declared+granted permissions and emit audit log lines.Plugin panels no longer receive the full `pi` object; they use `window.pluginBridge.invoke`.diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.mdindex d26f652f1..a44704731 100644--- a/docs/spec/07-plugins/04-plugin-security.md+++ b/docs/spec/07-plugins/04-plugin-security.md@@ -91,9 +91,9 @@ transcript replacement and regeneration.## 3.1 Contributed theme CSS-A theme contribution (`ui.theme`) is the one case where plugin-authored content-runs inside the host renderer, so it crosses a sanitizer in the main process-before it is ever sent to the UI:+A theme contribution (`ui.theme`) sends CSS into the host renderer through a+main-process sanitizer. The separate high-risk `renderer.extension` evaluates+trusted plugin JavaScript in the host renderer and is not a sandbox:- Only CSS the browser applies is inspected: comment bodies and string literalsare blanked first, with one space per masked character so any offset still@@ -104,7 +104,7 @@ before it is ever sent to the UI:declared theme asset, a `url(` the parser cannot resolve, `javascript:`,`expression(`, and markup sequences (`<style`, `</style`, `<!--`); an emptysheet is refused too-- Capped at 256KB per file, 8 themes per plugin+- Capped at 256 KiB per file; no per-plugin theme-count cap- A theme may declare `assets` using whitelisted image/font extensions: eitherpackage-relative paths (resolved inside the plugin root; traversal and `node_modules`references are rejected) or absolute paths. The total is capped at 4MB.@@ -118,7 +118,8 @@ before it is ever sent to the UI:`ui.window.appearance` and applies only while one of that plugin's themes isthe selected one; leaving the theme restores the host background, because theappearance is derived from the live catalog rather than remembered. macOS- keeps `vibrancy` and its native corner behavior; Linux retains native corner+ keeps native corners; its translucent vibrancy surface ignores the color,+ while turning off Translucent window applies it to the opaque surface; Linux retains native cornerbehavior. Windows defaults to a 12 DIP corner request. On Windows 11 (build22000+), radius 0 requests square corners and positive values use the samesystem-rounded preference, while the OS chooses the actual radius; alpha@@ -314,16 +315,15 @@ self-declared risk level. A server's catalog is registered whole — the count ibounded only by the protocol guards in §8.1 — while at most 8 servers per pluginare admitted.-Plan is an additional host policy boundary for agent tools:--- no plugin tool is visible or executable in Plan;-- the deny precedes manifest risk, declared/granted permissions, session- grants, and the `auto` permission mode;-- a direct forged `tools.execute` call returns `PLUGIN_DISABLED_IN_PLAN` and is- audited; it is not forwarded to the plugin runtime;-- plugin commands and panels may remain usable as explicit user UI actions,- but they cannot become model-callable Plan tools or silently mutate Plan- state.+Plugin tools are hidden and denied in Plan/Goal by default. A runtime tool+registration may opt in with non-empty `planSafeActions`; only an `args.action`+in that list may execute in those modes. The list is checked against the schema's+action enum when present. Keep the manifest descriptor and runtime registration+in sync: the runtime registration drives the executable tool. Risk `low`, session+grants, and `auto` do not substitute for the declaration. Host policy and the+plugin runner both check it; a disallowed runner action is `PERMISSION_DENIED`.+The declaration is an author assertion of read-only behavior, not a side-effect+sandbox (ADR 0211).## 8. Network and external links@@ -509,7 +509,8 @@ The host should be able to:9. An MCP server declared with an absolute `command` fails manifest validation;a non-loopback plain-HTTP URL is accepted only when its host is declared in`manifest.net.domains` and the UI shows the unencrypted-connection warning-10. A low-risk or granted plugin tool still fails closed in Plan+10. A plugin tool without plan-safe actions, or an action outside its list,+ still fails closed in Plan/Goal regardless of risk or grants## 11. Implementation statusdiff --git a/docs/spec/07-plugins/05-plugin-lifecycle.md b/docs/spec/07-plugins/05-plugin-lifecycle.mdindex 5e43e8b03..5b2f61bd3 100644--- a/docs/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/spec/07-plugins/05-plugin-lifecycle.md@@ -41,7 +41,7 @@ discovered## 3. Lifecycle hooks-**Implemented today:** the runtime (`apps/desktop/electron/main/plugin-runtime.ts`) invokes `onLoad` (when a plugin is loaded on load/enable) and `onUnload` (dispatched into the plugin process on unload/disable/reload/app quit, 5s budget — 1.5s on quit — then the process is stopped); unloading tears down the plugin's registered commands and tools. The other hooks below are declared in the API but not yet fired.+**Implemented today:** the runtime (`apps/desktop/electron/main/plugin-runtime.ts`) invokes `onLoad` (when a plugin is loaded on load/enable) and `onUnload` (dispatched into the plugin process on unload/disable/reload/app quit, 5s budget — 1.5s on quit — then the process is stopped); unloading tears down the plugin's registered commands and tools. The other lifecycle names below are proposals, not members of the current `PluginModule` type.`onProviderOAuth` is a provider operation callback, not a lifecycle hook. Thehost invokes it only for an enabled plugin's declared OAuth provider during@@ -59,7 +59,8 @@ unload, and timeout.7. `onUninstall`### Invocation constraints-- Hooks must be able to time out (default 5s, configurable)+- Module evaluation plus `onLoad`: 15s; `onUnload`: 5s, shortened to 1.5s on quit.+ These are host budgets, not manifest-configurable timeouts- A hook exception must not crash the host- If `onLoad` fails, enter `load_error` and automatically roll back the contribution points already registered@@ -135,7 +136,7 @@ never be the reason the app appears to hang on quit.- Close panel- Stop resident services and disconnect MCP servers- Cancel any pending restart backoff-- Call `onUnload` / `onDisable`+- Call `onUnload`; `onDisable` is not invoked- Persist as disabled## 5. Startup recovery@@ -213,10 +214,12 @@ Fields:Before uninstall:1. disable + unload-2. Call `onUninstall`+2. No `onUninstall` callback is invoked in the current runtime3. Delete installed files-4. Clean up plugin-private data (may ask the user whether to keep it)+4. Delete plugin-private data by default; no keep-data option is implementedDefault recommendation:- Clean up settings/data on uninstall (D016: uninstall deletes plugin data by default)-- Provide a "keep data" advanced option (can be deferred)+- A keep-data option is a future proposal, not a current uninstall guarantee.+ Development source directories are not deleted; bundled plugin ids cannot be+ uninstalled and may be disabled insteaddiff --git a/docs/spec/07-plugins/06-plugin-packaging.md b/docs/spec/07-plugins/06-plugin-packaging.mdindex 00c13db37..7570dc33e 100644--- a/docs/spec/07-plugins/06-plugin-packaging.md+++ b/docs/spec/07-plugins/06-plugin-packaging.md@@ -1,120 +1,103 @@# 06. Plugin Packaging-## 1. Goals--Define how plugins are packaged, distributed, and installed, ensuring reproducibility across machines.--## 2. Package formats--### 2.1 Directory package (development/local)-A plain directory containing `manifest.json`.--### 2.2 Distribution package (recommended)-Extension: `.piplug` (essentially a zip)--```text-demo.hello-0.1.0.piplug-└─ (zip)- ├─ manifest.json- ├─ main.js- ├─ renderer/...- ├─ skills/...- ├─ themes/...- └─ checksums.json # optional, in-package manifest+## 1. Formats and ownership++Development loading references a local directory whose root contains+`manifest.json`; it does not copy the source. Installed directories and+marketplace packages are managed by Rust host-core. The desktop runtime loads+an entry only after the install/load path has reviewed the manifest and grants.++A distribution `.piplug` is a **store-only ZIP (compression method 0)**.+The installer also reads store-only `.zip` input; a generic ZIP tool's deflated+entries are rejected. Use `pi-plugin pack` or the Agent's `PluginPack`, never+assume a renamed archive is compatible.++## 2. Package contents++The devkit writes the manifest at archive root. Include executable JavaScript,+HTML/CSS, skills, renderer modules, and all referenced assets. The installer+can discover a manifest at root or one directory below it, but the devkit's+root layout is the supported authoring path.++There is no installer-managed dependency or TypeScript build for ordinary+packages. Bundle runtime dependencies; `node_modules` never enters the package.+Agent extension modules have their own TypeScript loader, and the explicit+Import pi extension flow has bounded registry-only npm preparation; see+[16-trusted-extensions.md](16-trusted-extensions.md). Neither exception makes+ordinary package loading run arbitrary install scripts.++## 3. Enforced bounds and exclusions++| Surface | Current rule |+|---|---|+| Package content | At most 2,000 files and 50 MiB; marketplace download bytes are also bounded |+| Filesystem paths | Reject traversal and symlinks; referenced entries must remain in the plugin root except the separately declared theme-asset route |+| Always skipped by devkit walk | `.git` and `node_modules` directories |+| Also excluded from devkit package | Root `dist/`, `.env`, `.env.*`, `.npmrc`, `*.pem`, `*.key` |+| Credential exclusions | Warn with skipped paths; do not rely on exclusions as a secret scanner |+| Archive encoding | Store-only entries in deterministic code-unit order; package SHA-256 is printed |++`check` applies authoring/package checks, reports blocking errors and advisory+warnings, and `pack` refuses errors. A successful check does not execute the+entry, grant permissions, prove compatibility with every host, or pass a+plugin-center review. Install and exercise the actual artifact before release.++## 4. Integrity++Marketplace installs require the catalog/resolve package SHA-256 and check+announced size when supplied. A mismatch is `PLUGIN_INTEGRITY` and prevents+installation. Local directory loading has no download digest.+`checksums.json` is not a verified per-file integrity protocol in the current+installer. It may be an ordinary bundled file, but provides no host trust gate.+Signatures remain planned; a publisher badge is catalog metadata, not signing.++## 5. Install and upgrade++The host stages input under `plugins/cache/download`, validates archive safety+and manifest references, computes the permission difference, writes the managed+`plugins/installed/<id>` directory, persists the registry, and enables according+to the chosen grants/options. Marketplace downloads reuse this installer.++An existing id with a different version is reported as an upgrade; local+installation does not itself require that version to be newer. Marketplace+selection performs version comparison separately. Existing-version code is+copied to `plugins/cache/backup/<id>/<version>` before replacement. Backup+creation is not a promise of transactional rollback after every later I/O or+runtime-load failure; do not advertise guaranteed automatic rollback.++Upgrades retain the plugin id and private data. Added permissions require+review; automatic update must not silently expand them. Refer to+[08-plugin-signing-updates.md](08-plugin-signing-updates.md) for update policy.++## 6. Uninstall++The runtime first unloads the plugin and withdraws its contributions. Host-core+removes the registry row, managed installed code, private data, and legacy+per-plugin log file by default. A development source directory is retained.+Bundled plugin ids cannot be uninstalled, including after a marketplace update;+disable them instead. There is no implemented keep-data toggle or uninstall+lifecycle callback.++## 7. CLI and publisher handoff++Run these commands from the PI-Desktop repository root after its normal setup:++```bash+pnpm pi-plugin check ../my-plugin+pnpm pi-plugin pack ../my-plugin+pnpm pi-plugin publish ../my-plugin --channel stable```-> During implementation, `.zip` may be supported first, but at the product level everything is identified as `.piplug`.--## 3. In-package constraints--1. The root must contain `manifest.json`-2. Absolute-path symlinks are not allowed-3. Path traversal (`../`) is not allowed-4. Default max size after extraction for a single package (recommended 50MB, configurable)-5. Max file count (recommended 2000, configurable)--## 4. checksums.json (optional but recommended)--```json-{- "algorithm": "sha256",- "files": {- "manifest.json": "hex...",- "main.js": "hex..."- }-}-```--The host can verify at install time.--## 5. Install flow--```text-select package/dir- → verify archive safety- → extract to temp- → validate manifest + files- → permission review UX- → move to installed/<id>- → registry write- → optional auto enable-```--On failure, clean up temp and leave no half-installed directory.--## 6. Versioning and overwrite--- Installing a new version with the same id: upgrade-- Back up the old version to `cache/backup/<id>/<version>` before upgrade-- Rollback on upgrade failure (P2)--Semantics:-- `install`: id does not exist-- `upgrade`: id exists and version is newer-- `reinstall`: force reinstall of the same version--## 7. Uninstall and cleanup--Delete:-- `plugins/installed/<id>`-- registry entry--Optionally delete:-- `plugins/data/<id>`-- plugin logs--## 8. Development packages--Development loading does not go through `.piplug` packaging; instead:--```text-Load Development Plugin → choose directory → validate → register(source=dev)-```--## 9. Build recommendations (developers)--Minimal spec:--- Source can be TypeScript-- Compile to directly loadable js/html/css before distribution-- Do not rely on the host to run `npm install` for ordinary `.piplug` or development plugins (MVP does not pull dependencies at install time). The explicit Plugins → Import pi extension flow is the documented exception; its bounded npm behavior is defined in `16-trusted-extensions.md` §3.2.--If a plugin needs third-party libraries:-- Bundle them into the plugin directory yourself--## 10. Acceptance--1. Can install from a directory-2. Can install from `.piplug` / `.zip` (per milestone during implementation)-3. A bad package fails to install and leaves no residue-4. After upgrade, the id stays the same and the new version takes effect---## 11. Implementation status+`publish` creates a local `.piplug` and `.submission.json`; it does not upload.+It records repository/ref/commit/path and artifact digest/size. It requires a+git repository with `origin`, rejects credential-bearing remotes, and refuses+a dirty tree unless `--allow-dirty` is explicit. Ignore `dist/` first because+packing precedes that clean-tree check. A tag at HEAD is preferred; `--ref` is+recorded but does not replace the recorded HEAD commit or make it reproducible.+The plugin center independently resolves and verifies the source claim.-Implemented in host-core + desktop shell:+## 8. Implementation evidence-1. Directory install via `plugins.installFromPath`-2. `.piplug` / store-compressed zip install via `plugins.installFromPackage`-3. Marketplace download installs reuse the same package installer-4. Traversal / symlink / size / file-count guards are enforced before commit to `plugins/installed/<id>`+- `packages/plugin-devkit/src/{check,walk,pack,publish,cli}.ts` and their tests+- `crates/host-core/src/plugins/{install,manifest,validation,registry}.rs`+- [Author release workflow](../../plugin-development.md#9-check-pack-and-install)diff --git a/docs/spec/07-plugins/08-plugin-signing-updates.md b/docs/spec/07-plugins/08-plugin-signing-updates.mdindex a4eabece2..8775f7a9c 100644--- a/docs/spec/07-plugins/08-plugin-signing-updates.md+++ b/docs/spec/07-plugins/08-plugin-signing-updates.md@@ -37,7 +37,7 @@ On failure:- Show "Integrity check failed"- Record an audit entry-## 4. Signature scheme (implementation details to be frozen later)+## 4. Signature scheme (planned, not enforced)Recommended:@@ -64,7 +64,12 @@ type PluginSignature = {A failed verification rejects the install / update.-## 5. Publisher trust+Sections 4–5 describe proposed signing/key management. The current client+verifies package SHA-256 and reads catalog trust/provenance metadata; it has no+plugin-signing CLI, signature-verification gate, built-in signing key, or+user-managed trusted-key store. A verified badge is not a cryptographic signature.++## 5. Publisher trust (planned key management)```tstype PublisherTrust = {diff --git a/docs/spec/07-plugins/09-plugin-command-palette.md b/docs/spec/07-plugins/09-plugin-command-palette.mdindex 9cf7a4a4f..657d92d54 100644--- a/docs/spec/07-plugins/09-plugin-command-palette.md+++ b/docs/spec/07-plugins/09-plugin-command-palette.md@@ -20,16 +20,14 @@ Also configurable:## 3. Command model```ts-type PaletteCommand = {- id: string // e.g. builtin.session.new / plugin.demo.hello.open+type CommandItem = {+ id: stringtitle: string- keywords: string[]category?: string- source: "builtin" | "plugin"+ keywords?: string[]+ source: "builtin" | "plugin" | "extension"pluginId?: string- icon?: string- enabled: boolean- risk?: "low" | "medium" | "high"+ extensionId?: string}```@@ -39,19 +37,22 @@ type PaletteCommand = {- New task- Compact conversation context- Switch to Agent / Plan / Goal-2. Plugin `contributes.commands`-3. Later: skill shortcuts / marketplace search entry+2. Loaded plugin runtime registrations (`pi.commands.register`), filtered by+ activation scope; the manifest provides declaration metadata+3. Trusted agent-extension commands (`source: "extension"`)++The Composer `/` catalog is separate and also includes skill and MCP entries;+not every Composer entry is a global-search command.## 5. Search rules-- Match by title / keywords / category / pluginName-- Support prefix and substring matching-- Chinese keywords are supported-- Result ordering:- 1. Recently used- 2. Exact prefix- 3. Built-in priority or user weighting (configurable)- 4. Alphabetical+The current `commandPaletteSearch` IPC lowercases the query and performs a+substring match over title, category, and joined keywords. Chinese keywords+are matched as text. An empty query returns the eligible list. Ordering is+built-in commands, loaded project-eligible plugin commands in registry order,+then trusted-extension commands. There is no command-specific recently-used+ranking, prefix score, configurable weighting, or plugin-name search field.+Do not depend on those earlier design suggestions as implemented behavior.## 6. Execution flow@@ -91,12 +92,12 @@ Enter to run · Esc to closeEach item shows:- Title-- Source badge (builtin/plugin)-- Shortcut hint (optional)+- Plugin badge for `source: "plugin"`; the current row does not promise a+ per-command shortcut hint## 8. Empty state / errors-- No match: show "No commands, try installing a plugin"+- No match: use the global search empty state after all result groups are empty- Plugin command execution failed: toast + log- Disabled plugin: its commands do not appear@@ -114,4 +115,6 @@ Possible command to support:2. Built-in and plugin commands are searchable3. Executing a plugin command succeeds4. Commands disappear after a plugin is disabled-5. Recently-used ordering takes effect+5. Substring matching and stable built-in/plugin/extension ordering follow+ `apps/desktop/electron/main/ipc/market-ipc.ts`; `CommandItem` comes from+ `packages/shared/src/types/composer.ts`diff --git a/docs/spec/07-plugins/10-plugin-devex.md b/docs/spec/07-plugins/10-plugin-devex.mdindex 9205bca90..0bdadab98 100644--- a/docs/spec/07-plugins/10-plugin-devex.md+++ b/docs/spec/07-plugins/10-plugin-devex.md@@ -54,13 +54,12 @@ Current repo example:## 4. SDK and devkit-`@pi-desktop/plugin-sdk` is imported by plugin code itself and stays-dependency-free and Node-free. It provides:-- manifest types-- permission enums-- API types (`PiPluginHostApi`)-- manifest validation function-- test helper (mock host)+`@pi-desktop/plugin-sdk` is a private workspace package, not a runtime that+plugins must install. It has a `typebox` dependency, uses no Node host APIs,+and provides `PluginManifest`, `PluginHostApi`, `PluginModule`, renderer types,+permission/constants, and pure validators. It does not export a mock-host+factory. The host injects `pi`; runtime plugin bundles need no SDK import just+to access it. Use your own external-edge fakes to test plugin code.The SDK's clipboard surface includes `pi.clipboard.getHistory()`, whichreturns bounded, newest-first text and image entries through the existing@@ -70,7 +69,7 @@ clipboard-history features instead of polling `readText()` and maintaining asecond store.`@pi-desktop/plugin-devkit` is tooling, not runtime, and may use Node. It owns-`scaffold` / `check` / `pack` and the `pi-plugin` CLI. All three developer+`scaffold` / `check` / `pack` / `publish` and the `pi-plugin` CLI. All three developersurfaces (CLI, agent tools, plugins page) call it, so a rule enforced once holdseverywhere.@@ -89,20 +88,22 @@ pnpm --filter @pi-desktop/plugin-devkit... buildpnpm pi-plugin init full-demo /tmp/my-plugin# validate manifest and package contents-pnpm pi-plugin check .+pnpm pi-plugin check /tmp/my-plugin# pack-pnpm pi-plugin pack .+pnpm pi-plugin pack /tmp/my-plugin# outputs dist/demo.hello-0.1.0.piplug# pack and pin the version to the commit that produced it-pnpm pi-plugin publish .+pnpm pi-plugin publish /tmp/my-plugin# also writes dist/demo.hello-0.1.0.submission.json```-`publish` is for distributing through the plugin center. It packs, then records+`publish` prepares a local submission file for the plugin center; it performs+no upload or remote publication. Ignore `dist/` in the plugin repository so+packing does not dirty it before the clean-tree check. It packs, then recordsthe canonical repository URL, the tag or commit ref, the resolved commit, andthe plugin subdirectory alongside the package checksum, so the artifact and thesource it claims to come from describe one moment. It refuses a dirty worktree@@ -110,8 +111,10 @@ and a git remote carrying credentials, and warns when no tag points at HEAD.The center re-resolves everything itself; a submission is a claim to be checked.See [15-plugin-center.md](15-plugin-center.md).-`check` reproduces every rule the installer enforces, so `check` passing implies-install will pass. It reports errors — a missing or unparseable `manifest.json`,+`check` runs authoring and package-safety checks before packing. Passing is+necessary preparation, not proof that loading, host-version compatibility,+permission grants, provider access, or plugin-center review will succeed. The+Rust installer and runtime remain independent enforcement layers. It reports errors — a missing or unparseable `manifest.json`,missing `main` / `ui.panel` / `manifest.renderer` / skill files, a skill path escaping the plugindirectory, an unknown permission, a symlink, more than 2000 files, more than50 MB — and warnings, which do not block: high-risk permissions (every@@ -121,7 +124,7 @@ declared but never used by the code, `contributes.skills` without`agent.prompt.inject` (the skills would be inert), and an empty `contributes`.`pack` writes `dist/<id>-<version>.piplug`, skipping `.git` and `node_modules`-exactly as the installer's copy does, and prints the sha256. It runs `check`+and root `dist/`, omits credential files with warnings, and prints the sha256. It runs `check`first and refuses to pack a plugin with errors. **Entries are storeduncompressed (method 0)**: the installer accepts nothing else, so a `.piplug`must never be built with `zip` or another shell tool.diff --git a/docs/spec/07-plugins/11-plugin-storage-isolation.md b/docs/spec/07-plugins/11-plugin-storage-isolation.mdindex 889d5bc38..b46c5ca10 100644--- a/docs/spec/07-plugins/11-plugin-storage-isolation.md+++ b/docs/spec/07-plugins/11-plugin-storage-isolation.md@@ -1,128 +1,94 @@# 11. Plugin Storage Isolation-## 1. Goals+## 1. Ownership and layout-Isolate plugin data from the host's core data to avoid cross-contamination and unauthorized reads.--## 2. Directory layout--```text-~/.pi-desktop/- ├── pi.sqlite # host DB (03-runtime/04); plugins never open it- ├── plugins/- │ ├── installed/<plugin-id>/- │ ├── disabled/ # optional- │ ├── data/<plugin-id>/- │ ├── logs/<plugin-id>.log- │ ├── cache/download/- │ └── registry.json- └── ...-```--Bundled marketplace fallback packages use the owning plugin manager's data-root (`plugins/market/packages`), just like its catalog and download cache.-Catalog construction never re-reads the process-wide `PI_DESKTOP_DATA_DIR`;-independent host instances must not share package paths through that mutable-default. Package size and checksum validation remain mandatory.--## 3. registry.json (logical model)--```ts-type PluginRegistry = {- schemaVersion: 1- plugins: Array<{- id: string- version: string- enabled: boolean- source: "installed" | "dev" | "marketplace"- path: string- installedAt: string- updatedAt: string- permissionsGranted: string[]- marketplace?: {- providerId: string- shasum?: string- publisherId?: string- }- }>-}-```--## 4. Plugin private data--`pi.plugin.getDataPath()` points to:+Rust host-core owns the plugin registry, managed installation files, and all+SQLite access. Electron Main's plugin broker owns plugin settings files and+runtime bookkeeping. Plugins use public APIs, never host database handles.+The data root belongs to the owning host instance; do not hard-code+`~/.pi-desktop` or reread a process-global override to locate another instance's+catalog/cache. Development code remains at the loaded source directory.```text-~/.pi-desktop/plugins/data/<plugin-id>/+<dataRoot>/plugins/+├── registry.json+├── installed/<plugin-id>/+├── data/<plugin-id>/+│ └── settings.json+├── logs/ # legacy per-plugin log location+├── cache/download/+├── cache/backup/<plugin-id>/<version>/+└── market/+ ├── catalog.json+ └── packages/```-Uses:-- cache-- local index-- large plugin config files--Prohibited:-- Using this API to obtain another pluginId's path--## 5. Settings storage--Plugin settings can be stored in:--- The host DB's `kv` table under the plugin's namespace (03-runtime/04 §4.1)-- Or settings.json under the plugin data directory--Storing centrally in the host is recommended for easier backup and uninstall cleanup.--```ts-// kv: ns = `plugin:<plugin-id>`, key, value_json, updated_at-// uninstall cleanup = DELETE FROM kv WHERE ns = 'plugin:<plugin-id>'-```--## 6. Log isolation--Each plugin has its own log channel:-- File: `plugins/logs/<plugin-id>.log`-- UI: filterable by plugin--Host core logs are not written into plugin files.--## 7. Session and secret isolation--Plugins cannot directly access:-- pi.sqlite (sessions, settings, any host table)-- secrets-- provider key-- other plugins' private registry data--The reviewed `desktop.control` gateway now offers the bounded session-collaboration projection and mutation catalog. It does not expose host tables,-transcript files, credentials, Electron IPC, or the MCP bearer token. The host-derives source identity from the active Agent tool invocation, persists the-delivery and provenance ledger in host-core, and audits the plugin operation;-plugin-private state is never treated as authorization or session identity.--## 8. Uninstall cleanup policy--Default:-- Delete installed code-- Delete data-- Delete logs (or keep the most recent one)--Advanced:-- Keep data--## 9. Backup suggestions--A future export/backup can be split into:-- Host config only-- Host config + plugin list-- Full (including plugin data)--The MVP does not implement a full backup protocol; it only reserves directory boundaries.--## 10. Acceptance--1. A plugin can only write to its own data directory-2. Data is cleaned up per policy after uninstall-3. The registry can restore the installed list-4. Plugin logs can be viewed separately+## 2. Registry++`plugins/registry.json` records installed/development/marketplace entries,+enabled state, activation scope, granted permissions, path/version, update+preferences, and marketplace provenance. The host reads and writes it; it is+not a plugin API or a file plugins should edit. The registry restores the list+on restart. Runtime load/service state is a projection, not a substitute for+this durable ownership record.++## 3. Private settings and files++`pi.plugin.getDataPath()` returns only the calling plugin's private data+directory. `pi.plugin.getSettings()` merges declared defaults with its stored+`settings.json`; `setSettings(partial)` merges a patch. Settings are not stored+in the host SQLite `kv` table by this implementation. Theme variable values+share a host-reserved private settings namespace managed through+`pi.themes.setVariables`; do not overwrite it yourself.++Settings are ordinary JSON, not a secret store. `secret: true` generated+settings are rejected. Provider API keys stay in the host secret store; the+separate `provider.oauth` callback can receive only its contribution's OAuth+credential. No generic plugin-secret read/write API exists.++## 4. Filesystem and process trust++`pi.fs.*` operates on the declared workspace/user-selected scope; it is not a+generic private-data filesystem API. File actions use the calling tool session+or the appropriate view/workspace root. The broker refuses host-reserved data+and protected credentials and prevents escaping a root through symlinks.++These are **brokered API** guarantees. A plugin's Node entry process currently+retains raw Node filesystem/network access under the user's OS account. Its+private path is namespacing, not an OS sandbox. A trusted `renderer.extension`+likewise shares the host document. Isolated panel/view pages have no Node+integration and cannot open the host database through the preload.++## 5. Sessions, usage, and collaboration++`session.read` returns only the invoking tool session's bounded model-facing+context. `session.read.own` / `update.own` / `delete.own` address only sessions+imported by the calling plugin. `session.autoTitle` is a bounded first-turn+projection and compare-and-set write. `usage.read` returns completed-turn facts,+not message bodies. These are separate permissions, not broad database access.++The reviewed `desktop.control` collaboration gateway injects source invocation+identity and keeps its durable ledger in host-core. Plugin-private JSON is+never authorization, a host Session ID, or a replacement for that ledger.+The gateway exposes neither SQLite nor arbitrary Electron IPC/MCP bearer tokens.++## 6. Logs and cleanup++Use Settings → Info → Logs and filter by plugin id. The runtime emits audit+records into the categorized application log service; it does not promise one+live `plugins/logs/<id>.log` per plugin. Never log credentials or transcripts.++Uninstall removes the registry row, managed installed code, plugin-private data,+and any legacy per-plugin log file by default. It preserves development source+and refuses bundled ids. No keep-data option is implemented. Disable/reload+withdraws runtime resources but retains settings and private files.++## 7. Implementation evidence and acceptance++- `crates/host-core/src/plugins/registry.rs`: paths, registry and uninstall+- `apps/desktop/electron/main/plugin-runtime.ts`: settings, private paths, scopes+- `apps/desktop/electron/main/plugin-session-scope.ts`: invocation ownership+- Verify restart recovery, settings defaults/patches, cross-plugin read refusal,+ scope/deny-list enforcement, and uninstall cleanup using existing plugin tests.+- Backup/portable configuration has its own host contract; this layout does not+ promise export of arbitrary plugin-private data.diff --git a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex b64d3e21e..2df66f9cd 100644--- a/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -119,8 +119,8 @@ handler is logged, never fatal. This is the same channel that finally makes### Query- The command palette only queries contributions that are enabled + loaded successfully-- Agent sees registered tools; Plan receives no plugin tools regardless of risk- or grant state+- Agent sees registered tools; Plan/Goal sees only tools with non-empty+ runtime `planSafeActions`, and execution rechecks `args.action` against them### Deregistration- Remove everything on disable/unload/uninstall, including stopping resident@@ -254,9 +254,10 @@ permission gate and result envelope stay in host-core:`{ executionId, sessionId, toolCallId, toolName, args, turnId }`. `turnId` isthe runtime turn identity, forwarded unchanged so the plugin tool context canbe matched against the `session:turnEnded` event.-3. Plan calls fail at the host policy step with `PLUGIN_DISABLED_IN_PLAN`; they- never reach Electron or the plugin runtime. Agent calls continue with- Electron main executing the registered plugin tool JS and answering via RPC+3. Plan/Goal calls without `planSafeActions` fail at the host policy gate.+ Admitted calls carry mode and the allowed actions; the desktop plugin runner+ rejects missing or unlisted `args.action` before plugin code. Agent calls+ use the normal permission flow. Electron answers through RPC`plugins.resolveExecution` `{ executionId, ok, content, errorCode? }`.4. host-core resolves the pending execution and returns a standard`ToolsExecuteResult` to the sidecar. Dispatch waits up to 150sdiff --git a/docs/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/spec/07-plugins/13-plugin-permissions-matrix.mdindex e124de0ab..320bcbd48 100644--- a/docs/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/spec/07-plugins/13-plugin-permissions-matrix.md@@ -11,7 +11,7 @@ Provide a permission–capability–risk–default-policy reference table for re| `ui.panel` | low | Open the plugin panel | Granted at install | Needed by almost all UI plugins || `ui.view` | low | `contributes.views` are listed in the work panel and may be opened | Granted at install | Same isolation as a panel window: sandboxed page, per-plugin partition, `net.domains` egress. Filtered by activation scope || `ui.theme` | low | `contributes.themes` CSS is loaded and offered in Settings; runtime `pi.themes.upsert` / `remove` / `list` and `pi.app.setTheme` (ADR 0260) | Granted at install | CSS is sanitized by the host; it cannot script. Declared `assets` are served over the host's read-only `plugin-asset:` scheme. `setTheme` may only select a built-in preference or a currently registered plugin theme. There is no per-plugin theme count cap |-| `ui.settings` | low | `contributes.settingsDestinations` adds a sandboxed Settings entry in Extensions | Granted at install | Rendered only in host Extensions group; isolated view host with same sandbox as panel views (ADR 0261) |+| `ui.settings` | low | `contributes.scenicThemes` adds a host-rendered data-only Settings entry | Granted at install | Also needs `ui.theme`; no plugin Settings HTML, CSS, JavaScript, or bridge (ADR 0287) || `ui.window.appearance` | low | `contributes.windowAppearance` sets the native window background and Windows main-window corner request while one of the plugin's themes is selected | Granted at install | `#rrggbb` / `#rrggbbaa` background and integer `cornerRadius` 0..24 DIP; restores host background and the 12 DIP default request when the theme is gone. Windows 11 maps 0 to square and positive values to the system-rounded preference (not exact DIP radii); alpha is composited over the built-in theme color on its opaque window. Earlier Windows builds retain the requested DIP radius. macOS keeps native corners; its default translucent vibrancy surface ignores the colour, and the `Translucent window` switch turned off applies it to the opaque native surface (ADR 0332) || `clipboard.read` | medium | `clipboard.readText`, `clipboard.getHistory` | Confirm on first use | May read sensitive information and retained clipboard history || `clipboard.write` | medium | `clipboard.writeText` | Confirm on first use | Prevents clipboard pollution |@@ -23,7 +23,7 @@ Provide a permission–capability–risk–default-policy reference table for re| `fs.write.workspace` | high | — | Downgraded on load to `fs.write` with **no** scope | Legacy name; every write asks the user until the manifest declares scope || `fs.delete.workspace` | high | — | Downgraded on load to `fs.delete` with `own: true` | Legacy name; only the plugin's own output goes without asking || `agent.tool.register` | high | Register an agent tool | Confirm at install | Tool execution is audited separately |-| `agent.prompt.inject` | high | Inject a system prompt; activates `contributes.skills` | Deny by default / strong confirmation | Easily leads to behavior hijacking |+| `agent.prompt.inject` | high | Activate the catalog and on-demand bodies from `contributes.skills` | Deny by default / strong confirmation | Easily leads to behavior hijacking || `composer.transform` | medium | `contributes.composerTransforms` and `onComposerTransform` | Confirm at install | Runs only after an explicit Composer action. Receives the draft and optional model key, not session history or separate attachment/file-reference metadata; request and result are capped at 100,000 characters and audited || `composer.suggest` | medium | `pi.composer.suggest` / `pi.composer.clearSuggestion` | Confirm at install | Writes one dismissible line into the placeholder layer of the Composer for the session on screen, only while the draft is empty and only for the turn the plugin names. The user takes it with Tab, drops it with Esc, and typing, sending, a session switch, a new turn, the plugin stopping, a reload or a window close all end it. The plugin never sends it and never reads the draft. Text is folded to one line and cut at 200 characters; the lifetime defaults to 120 s and is capped at 10 minutes. Audited; a place that will not show it answers `{ shown: false, reason }` instead of throwing || `agent.extension` | high | Run `contributes.agentExtensions` modules inside the agent process | Explicit confirmation; local imports and development plugins only in v1.1 | Same access as the agent's own tools; the plugin sandbox does not apply (spec 16) |@@ -120,11 +120,15 @@ plugin, so it carries three bounds the other modes do not:## 3A. Plan operating-state rule-Every `agentTools` contribution is denied in Plan, regardless of this matrix's-risk or default policy. `agent.tool.register` authorizes registration for-Agent, not visibility in Plan. The host returns `PLUGIN_DISABLED_IN_PLAN` for a-direct Plan call and records the denial. Plugin tools become eligible only-after the same Agent is approved into Agent mode.+Plugin tools are hidden and denied in Plan/Goal by default. A runtime tool+registration may opt in with non-empty `planSafeActions`; only an `args.action`+in that list may execute in those modes. The list is checked against the schema's+action enum when present. Keep the manifest descriptor and runtime registration+in sync: the runtime registration drives the executable tool. Risk `low`, session+grants, and `auto` do not substitute for the declaration. Host policy and the+plugin runner both check it; a disallowed runner action is `PERMISSION_DENIED`.+The declaration is an author assertion of read-only behavior, not a side-effect+sandbox (ADR 0211).## 4. Permission display copydiff --git a/docs/spec/07-plugins/14-plugin-roadmap.md b/docs/spec/07-plugins/14-plugin-roadmap.mdindex a07d15efd..770a5a7f2 100644--- a/docs/spec/07-plugins/14-plugin-roadmap.md+++ b/docs/spec/07-plugins/14-plugin-roadmap.md@@ -30,7 +30,8 @@ Local plugins usable → developer-friendly → marketplace distribution → sig- Unified namespace and audit ✅- Per-plugin settings API and generated settings UI are implemented. The UIsupports string/number/boolean/select/json fields and plugin-local command- shortcuts; OS-global plugin shortcuts remain out of scope.+ shortcuts. OS-global bindings are implemented separately through+ `keyboard.globalShortcut`, `contributes.globalShortcuts`, and `pi.keyboard`.- Plugin log panel remains planned; runtime audit logs exist without a dedicatedplugin-log surface@@ -67,6 +68,18 @@ Local plugins usable → developer-friendly → marketplace distribution → sigsummaries and reviews anonymously and links out to the centre to write;accounts, writing, voting, and reporting live on the centre's web page)+### Current additive capabilities++- Renderer slots and reviewed draft/attachment dispatch (`renderer.extension`)+- Manifest-owned providers, Add Service categories, and host-owned OAuth login+- Composer transforms with undo and dismissible Composer suggestions+- Plugin-owned session import/read/rename/delete and compare-and-set auto titles+- Completed-turn usage facts; model catalog and host-owned one-shot completion+- Selected-session snapshots and host-owned work-panel view reveal+- Runtime themes, typed theme variables, and data-only scenic Settings cards+- Bounded WebSockets and host-owned global shortcuts+- Background audio remains callable but returns `UNSUPPORTED`; no device backend+### R7 — Agent extensions (v1.1 ✅, D387 / D388)- v1: ExtensionAPI adapter in the Agent sidecar; tools, commands, lifecycle andprovider hooks, basic UI prompts@@ -103,5 +116,5 @@ Local plugins usable → developer-friendly → marketplace distribution → sig|---|---|| Building the marketplace too early destabilizes the core | Defer the marketplace; R1 does local first || Plugin security incident | Deny by default + audit + mandatory signing later |-| Frequent API breakage | apiVersion / schemaVersion |+| Frequent API breakage | Additive SDK contracts, capability detection, schemaVersion || High developer barrier | Templates + hello example + SDK |diff --git a/docs/spec/07-plugins/15-plugin-center.md b/docs/spec/07-plugins/15-plugin-center.mdindex 83de7b144..a0ded1f03 100644--- a/docs/spec/07-plugins/15-plugin-center.md+++ b/docs/spec/07-plugins/15-plugin-center.md@@ -1,7 +1,7 @@# 15. Plugin Center> Management repository: [vastsa/pi-plugin-center](https://github.com/vastsa/pi-plugin-center)-> Distribution repository: [vastsa/pi-desktop-plugins](https://github.com/vastsa/pi-desktop-plugins)+> Distribution repository: [AIUO-Net/pi-desktop-plugins](https://github.com/AIUO-Net/pi-desktop-plugins)> Decision record: [ADR 0102](../../adr/0102-publisher-owned-plugin-source-and-git-hosted-artifacts.md)> Client contract: [07-plugin-marketplace.md](07-plugin-marketplace.md)@@ -9,6 +9,14 @@ This document defines the distribution system that replaces the single-repositormarketplace. It is the normative plan for the center service; the marketplacedocument remains the normative contract for what the desktop client consumes.+Implementation scope: this repository contains the desktop client and+`packages/plugin-devkit/src/publish.ts`, which prepares local package/submission+files and does not upload. Center API, worker, identity, and signing sections+below describe the separate service's design, not SDK methods or proof of a+running server. The current client defaults to `https://plugins.aiuo.net/catalog.json`+and uses the documented `/api/v1` resolve/review routes; see the marketplace+contract and `crates/host-core/src/plugins/marketplace`, `reviews.rs`, and `resolve.rs`.+## 1. PositioningThe plugin center is the publishing side of plugin distribution. It answers three@@ -29,8 +37,8 @@ machine that the client would not otherwise accept.| Plugin source | Publisher | Publisher's own GitHub repository || Build inputs (commit, tree, path) | Center (pinned copy) | Center database + snapshot store || Registry and review evidence | Center | `vastsa/pi-plugin-center` |-| `.piplug` artifact | Center (published) | `vastsa/pi-desktop-plugins/packages/` |-| Catalog | Center (generated) | `vastsa/pi-desktop-plugins/catalog.json` |+| `.piplug` artifact | Center (published) | `AIUO-Net/pi-desktop-plugins/packages/` |+| Catalog | Center (generated) | `AIUO-Net/pi-desktop-plugins/catalog.json` || Distribution mirror | Center | CNB Git mirror of the distribution repository || Install decision | User | Desktop permission review |@@ -52,7 +60,7 @@ vastsa/pi-plugin-center # management├─ scripts/ # catalog generation and verification└─ api/ db/ # service contract and migrations-vastsa/pi-desktop-plugins # distribution, unchanged addresses+AIUO-Net/pi-desktop-plugins # distribution, unchanged addresses├─ catalog.json # generated by the center├─ packages/<pluginId>-<version>.piplug # published by the center└─ plugins/ # removed — sources live in publisher repositories@@ -75,7 +83,7 @@ the base the catalog names, whichever host served it:```textcenter catalog artifactBaseUrl = raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main-distribution repo raw.githubusercontent.com/vastsa/pi-desktop-plugins/main+distribution repo raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/mainCNB mirror cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/…```diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.mdindex 6b1d18653..05e0e288b 100644--- a/docs/spec/07-plugins/16-trusted-extensions.md+++ b/docs/spec/07-plugins/16-trusted-extensions.md@@ -522,7 +522,11 @@ The Plugins page shows agent extensions on the owning plugin's row:| v1.1 | Modules become `contributes.agentExtensions` with the `agent.extension` grant; import of pi CLI extensions as development plugins; the standalone registry and settings tab are removed | Shipped (D388) || v1.1 amendment | Plugin-owned custom agents via `registerAgent`, provider compatibility alias, redacted model registry, idle-only session binding and restore through `extension-agent:` ids | Implemented (D426 / ADR 0258) || v2 | Custom session entries (`sendMessage`, `appendEntry`) with a schema bump and a generic renderer, `sessionManager` read shim, `switchSession`, editor read and write, autocomplete providers, `registerShortcut`, markdown transformers | Planned, needs a decision on entry persistence and compaction |-| v3 | `pi` package manifests and installation, read-only hints from the pi CLI's `settings.json`, unified skill and prompt discovery, remote-control routing for prompts, marketplace listing | Not scheduled |+| v3 | Read-only hints from the pi CLI's `settings.json`, unified skill and prompt discovery, remote-control routing for prompts, marketplace listing | Not scheduled |++Explicit local package import, including `pi.extensions` / `pi.skills` and bounded+registry-only dependency preparation, is already implemented in §3.2. It is not+a promise of a general pi package manager or automatic settings discovery.v1 delivery order: bundling spike (E2E-245), shared protocol types, then theruntime, main, and renderer tracks in parallel.diff --git a/docs/spec/07-plugins/README.md b/docs/spec/07-plugins/README.mdindex 3e7fe6944..dfbe2c22d 100644--- a/docs/spec/07-plugins/README.md+++ b/docs/spec/07-plugins/README.md@@ -24,3 +24,27 @@ this directory define the normative contracts and implementation boundaries.| [14-plugin-roadmap.md](14-plugin-roadmap.md) | Plugin roadmap || [15-plugin-center.md](15-plugin-center.md) | Plugin center (publishing side) || [16-trusted-extensions.md](16-trusted-extensions.md) | Trusted extensions (in-sidecar extension surface) |++## Read the code behind the contract++Use the [complete SDK index](../../plugin-development.md#13-complete-sdk-surface-and-source-map)+for every callable method and the permission matrix for its gate. The SDK,+installer, and runtime are independent enforcement layers; the guide calls out+known differences instead of treating a permissive parser as authorization.++| Area | Implementation evidence |+|---|---|+| Manifest, permission vocabulary, host API | `packages/plugin-sdk/src/index.ts` |+| Renderer slots, actions, drafts, attachments | `packages/plugin-sdk/src/renderer.ts`, `renderer-composer.ts` |+| File/network/theme/MCP rules | SDK policy helpers and their unit tests |+| Templates, checks, packing, submission preparation | `packages/plugin-devkit/src` and its tests |+| Install, registry, marketplace, ownership | `crates/host-core/src/plugins` |+| Broker dispatch, callbacks, cleanup, events | `apps/desktop/electron/main/plugin-runtime.ts`, `plugin-host-process.mjs` |+| Panel bridge and command search | `apps/desktop/electron/preload/plugin-panel.ts`, `apps/desktop/electron/main/ipc/market-ipc.ts` |+| Trusted extension subset | `packages/agent-runtime/src/extensions` and spec 16 |+| Representative host/user paths | `apps/desktop/test/plugin-*.test.mjs`, repository example plugins |++Lifecycle proposals, background-audio types without a device backend, signing+plans, and center-server architecture are explicitly distinguished from shipped+runtime APIs. Review pages under `docs/plugin-plan` may describe unimplemented+hooks; they are not an additional public API.diff --git a/docs/zh-CN/plugin-development.md b/docs/zh-CN/plugin-development.mdindex df61177ca..27f1a210b 100644--- a/docs/zh-CN/plugin-development.md+++ b/docs/zh-CN/plugin-development.md@@ -12,18 +12,31 @@插件可以提供以下一项或多项功能:-| 能力 | 用它来 | 主要构建模块 |+| 能力 | 用途 | 主要 API 与声明 ||---|---|---|-| 命令 | 全局搜索中的显式操作 | `contributes.commands`、`pi.commands.register` |-| 面板 | 一个小的独立的 HTML 界面 | `ui.panel`、`ui.panel` 权限、`window.pluginBridge` |-| 悬浮挂件 | 透明无边框的小挂件窗口——例如一个圆形球体 | `ui.panel` 权限、`"ui": { "shape": "widget" }`、`window.pluginBridge` |-| Agent 工具 | Agent 可以调用的函数 | `contributes.agentTools`、`pi.agent.registerTool` |-| 技能 | Agent 按需加载指令 | `contributes.skills`、`agent.prompt.inject` 权限 |-| 主题 | 设计令牌覆盖 | `contributes.themes`、`ui.theme` 权限 |-| MCP 服务器 | 从本地或远程 MCP 服务器发现的工具 | `contributes.mcpServers`,MCP 权限 |-| 服务 | 驻地工作由主人监督 | `contributes.services`、`background.service` 权限 |-| 消息总线 | 插件之间按约定类型化事件 | `contributes.bus`,总线权限 |-| 渲染器插槽 | 在应用自身窗口内绘制界面:输入区控件、消息操作栏、回复下方区块、工具卡、代码块渲染器、角落浮层 | `renderer`、`renderer.extension` 权限、`packages/plugin-sdk/src/renderer.ts` |+| 命令 | An explicit action in global search | `contributes.commands`, `pi.commands.register` |+| 独立面板 | A small isolated HTML interface | `ui.panel`, `ui.panel` permission, `window.pluginBridge` |+| 悬浮挂件 | A transparent, frameless companion window — a round orb, not a rectangle | `ui.panel` permission, `"ui": { "shape": "widget" }`, `window.pluginBridge` |+| 工作面板视图 | An interface docked in the app's right work panel | `contributes.views`, `ui.view` permission, `window.pluginBridge` |+| Agent 工具 | A function the Agent can call | `contributes.agentTools`, `pi.agent.registerTool` |+| OAuth Provider | A provider row with host-owned sign-in and encrypted credentials | `contributes.providers`, `provider.oauth`, `onProviderOAuth` |+| 单次补全 | A host-owned completion against the user's models | `pi.models.list`, `pi.session.getLlmContext`, `pi.agent.complete` |+| 技能 | Instructions loaded by the Agent on demand | `contributes.skills`, `agent.prompt.inject` permission |+| 主题 | Design-token overrides | `contributes.themes`, `ui.theme` permission |+| MCP 服务器 | Tools discovered from a local or remote MCP server | `contributes.mcpServers`, an MCP permission |+| 常驻服务 | Resident work supervised by the host | `contributes.services`, `background.service` permission |+| 消息总线 | Typed-by-convention events between plugins | `contributes.bus`, bus permissions |+| 渲染器插槽 | UI drawn inside the app's own window: composer controls, message action bars, blocks below a reply, tool cards, code-block renderers, corner layers | `renderer`, `renderer.extension` permission, `packages/plugin-sdk/src/renderer.ts` |+| 输入框建议 | One dismissible line offered to the input box, taken with Tab | `pi.composer.suggest`, `composer.suggest` permission |+| 模型 Provider | API-key, no-auth, or OAuth model service | `contributes.providers`, `provider.register`; OAuth also needs `provider.oauth` |+| 会话导入 | Import, read, rename, and delete this plugin's own history | `contributes.sessionSources`, matching `session.*` grants |+| 用量事实 | Compute your own usage dashboard | `pi.usage.listTurns`, `usage.read` |+| 输入框转换 | An explicit draft-text action with undo | `contributes.composerTransforms`, `onComposerTransform`, `composer.transform` |+| 系统快捷键 | Invoke your command while the app is unfocused | `contributes.globalShortcuts`, `pi.keyboard`, `keyboard.globalShortcut` |+| 受信任 Agent 扩展 | pi ExtensionAPI hooks, tools, commands, and custom agents | `contributes.agentExtensions`, `agent.extension` |+| 实时连接 | Host-owned, bounded WebSockets | `pi.net.websocket`, `net.websocket` |+| 浏览器与桌面控制 | Reviewed browser or app operations | `pi.browser`, `browser.cdp`; `pi.desktop`, `desktop.control` |+| 语音适配器 | Add a speech protocol handled by the plugin process | `pi.speech`, `speech.adapter.register` |插件入口代码在专用的 Node 进程中运行。面板在沙盒中运行,上下文隔离的 Electron 窗口,没有 Node 集成。来自任一方的呼叫@@ -35,7 +48,7 @@> 当您信任其来源并使用主机 API 而不是直接 Node 文件时> 或网络访问。请参阅[安全规范](/zh-CN/spec/07-plugins/04-plugin-security)。-## 2.先决条件+## 2. 先决条件对于推荐的应用优先路径,您需要:@@ -44,8 +57,8 @@- 文本编辑器。- 若要导入带 npm 依赖的 pi 扩展目录,`PATH` 中必须有系统 `npm` 可执行文件。发布版不附带独立 Node/npm;缺少 npm 时,PI-Desktop 会报告警告,导入扩展的依赖无法加载。-对于存储库 CLI 路径,您还需要 Node.js 22.19 或更高版本、pnpm 10 或-较新,并签出此存储库。 devkit 和 SDK 目前已+仓库 CLI 路径使用根目录 `package.json` 中 `engines` 和 `packageManager`+声明的 Node.js、pnpm 版本,并需要本仓库的检出副本。 devkit 和 SDK 目前已私有工作空间包,所以不要假设`npm install@pi-desktop/plugin-devkit` 在此存储库之外工作。@@ -93,7 +106,7 @@ pnpm pi-plugin init panel-basic ../my-first-plugin \私人插件。保持 ID 稳定:设置、数据、授权、更新和包名称由它作为键。-## 4.了解生成的文件+## 4. 了解生成的文件`panel-basic` 模板生成:@@ -183,23 +196,23 @@ async function onUnload() {module.exports = { onLoad, onUnload };```-主机将 `pi` 作为全局注入。 `onLoad` 和 `onUnload` 不接收任何参数。-CommonJS是最简单的入口格式;当条目是-ES 模块。模块评估加上 `onLoad` 有 15 秒预算。 `onUnload`-有 5 秒预算并且尽力而为,因此释放计时器和订阅-及时。+宿主注入全局 `pi`;主进程的 `onLoad` 和 `onUnload` 不接收参数。支持 CommonJS 和 ESM。+模块求值与 `onLoad` 共用 15 秒预算;`onUnload` 为 5 秒,应用退出时缩短至 1.5 秒。+只有这两个生命周期钩子会执行。`onPanelInvoke`、`onRendererCall`、`onComposerTransform`、+`onProviderOAuth` 是操作回调;`onInstall`、`onEnable`、`onDisable`、`onUninstall` 不会执行,+也没有 `entrypoints` 清单分发器。-今天仅解雇 `onLoad` 和 `onUnload`。中的其他生命周期名称-清单是为计划的完整生命周期保留的。+OAuth 回调只处理自己声明的 Provider,凭证由宿主加密保存。`provider.oauth` 是高风险权限;+通过宿主 API 请求令牌仍需 `net.fetch` 和相应出网范围,详见 §6.13。### `renderer/index.html`PI-Desktop 在 macOS、Windows 和 Linux 上都使用无边框窗口承载面板。主机精确保留透明的 46 CSS 像素拖拽带,并只在右上角渲染最简胶囊,其中包含最小化、最大化/还原和关闭三个按钮。面板标题、工具栏、背景-以及其他所有可见界面都由插件实现。普通流内容会由主机自动偏移到拖拽带-下方,不要再额外添加 46px 顶部内边距。拖拽带除胶囊外不可点击;开发面板-会显示这一限制的提醒。+以及其他可见界面都由插件实现。新页面应声明 `<meta name="pi-plugin-chrome" content="v2">`,+并用 `var(--pi-plugin-titlebar-height, 0px)` 自行添加一次顶部间距。没有此标记的旧页面+由宿主自动偏移,不要再加第二份 46px 间距。拖拽带除胶囊外不可点击,开发面板会提示。如果面板使用 `position: fixed` 或 `position: sticky` 实现顶部界面,不要使用 `top: 0`,而应使用主机变量:@@ -242,7 +255,9 @@ PI-Desktop 在 macOS、Windows 和 Linux 上都使用无边框窗口承载面板<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="pi-plugin-chrome" content="v2" /><title>My First Plugin</title>+ <style>body { padding-top: var(--pi-plugin-titlebar-height, 0px); }</style></head><body><h1>My First Plugin</h1>@@ -309,10 +324,13 @@ await pi.agent.registerTool({});```-在 `onUnload` 中取消注册。主机将其暴露给模型-插件命名空间名称,应用正常的 Agent 权限策略,审核-执行,并强制执行 110 秒的插件端超时。插件工具不是-在 Plan 模式下可用。+在 `onUnload` 中注销工具。宿主使用命名空间名称、正常权限策略和审计,插件侧超时为 110 秒。+工具通过 `ToolSearch` 按需加载,默认在 Plan/Goal 中隐藏并拒绝。+只有运行时注册描述符明确提供 `planSafeActions`,且 `args.action` 在该列表中时,才允许在这些+模式执行。声明应只列只读操作,并与清单保持一致;有 schema action enum 时会校验取值。+`risk: "low"`、会话授权和 `auto` 都不能代替该声明。+通过 `context.signal` 处理取消,用 `context.sessionId` / `turnId` 关联发起调用的会话和轮次,+不能替换成当前可见会话。### 6.2 技能@@ -387,7 +405,8 @@ const dataPath = await pi.plugin.getDataPath();}```-插件快捷键只在聚焦的 PI-Desktop 窗口中生效,并会避让应用快捷键;暂不支持全局注册。+插件快捷键只在聚焦的 PI-Desktop 窗口中生效,并会避让应用快捷键;系统级快捷键使用独立的 `contributes.globalShortcuts`、`pi.keyboard` 和+`keyboard.globalShortcut` 权限(§6.17)。用户编辑后插件会收到 `plugin:settingsChanged`。请勿将凭据放入 `manifest.json` 或源代码管理。### 6.4 工作区文件、剪贴板、网络和通知@@ -485,15 +504,33 @@ root 本身。`net.fetch` 接受 HTTP(S),并且只能到达 `manifest.net.doma(沙箱面板依然有网络栈),你声明的远程 HTTP MCP 服务器也一样。面板里的 `window.open` 一律拒绝。-`net.domains` 缺失、为空或非法就意味着**完全不放行出网**,即使 `net.fetch`-已被授予。重定向由主机手工跟随并重新检查,所以被允许的主机没法把请求弹到-一个你没声明的主机上。请把资源打进插件包,而不是从一个你还得额外声明的 CDN+没有 `net.anyHost` 时,缺失或空的 `net.domains` 不提供出网权限,即使已授予 `net.fetch`;+非法声明会校验失败。重定向由宿主手工跟随并逐跳检查,不能跳到授权范围之外。请把资源打进插件包,而不是从一个你还得额外声明的 CDN上加载。`fetch` 返回服务器实际给出的内容,`429` 和 `Retry-After` 都在内:宿主从不重试你的插件发出的请求,所以遇到限流之后的退避是你自己的策略,而不是主机隐藏的行为。返回 `>= 400` 的调用依然会进审计,记为 `ok: false` 并带上它通告的延迟。+`net.anyHost` 是安装时单独确认的高风险权限,用于用户输入的自建端点。+它放宽域名列表,覆盖 fetch、WebSocket、面板和远端 MCP,但仍拒绝云元数据地址,+也不会单独授予 fetch 或 socket API。++### Fetch redirect policy++依赖重定向策略前,必须先查询能力。旧宿主可能忽略未知字段,不能回退到原始网络请求。++```js+if (typeof pi.net.getCapabilities !== "function") throw new Error("Upgrade PI-Desktop");+const capabilities = await pi.net.getCapabilities();+if (!capabilities.fetchRedirectModes.includes("error")) throw new Error("Unsupported host");+const response = await pi.net.fetch({ url: endpoint, redirect: "error" });+```++`error` 在访问 Location 前拒绝所有 3xx,错误为 `REDIRECT_DISALLOWED`。+`manual` 返回首个响应;省略或 `follow` 最多跟随 5 次,每跳重新校验出网策略。+非法值在 I/O 前拒绝,所有模式都不会扩权。+### 6.7 主题声明 CSS 文件和 `ui.theme`:@@ -518,35 +555,69 @@ root 本身。`net.fetch` 接受 HTTP(S),并且只能到达 `manifest.net.doma}```-`base` 选择覆盖样式所基于的内置 `light` 或 `dark` 调色板;省略时默认-为 `dark`。用户在“设置”中选择插件贡献的主题。--覆盖设计令牌时,应使用与基础调色板相同的选择器:+`base` 选择底层的 `light` 或 `dark` 调色板,省略时为 `dark`。用户在设置中选择主题。+覆盖设计令牌时,应匹配宿主调色板选择器:```css:root[data-theme="dark"] { --ds-bg-primary: #141a24; }:root[data-theme="light"] { --ds-bg-primary: #f5f7fa; }```-主题样式表追加在宿主样式之后,但只有选择器特异度相同时,后写的声明才胜出。-宿主调色板使用 `:root[data-theme="dark"]` 和 `:root[data-theme="light"]`;-单独的 `:root` 特异度较低,不能保证覆盖这些声明。浅色基础主题应显式使用-`:root[data-theme="light"]`。+样式表在宿主样式之后追加,但后写的声明只有在特异度相同时才胜出。单独的 `:root`+特异度低于 `:root[data-theme="dark"]` 和 `:root[data-theme="light"]`,因此不能保证覆盖。++CSS 会经过清理:拒绝 `@import`,`url()` 仅允许 `data:` 或已声明的资源。+每份 CSS 上限 256 KiB;不限制每个插件的主题数量。每份主题资源总量上限 4 MiB,+支持 `png`、`jpg`、`jpeg`、`webp`、`avif`、`svg`、`woff2`。资源路径可以是插件内相对路径+或经过单独验证的绝对路径;匹配的 URL 会被重写为只读的 `plugin-asset://` 地址,+卸载后失效,渲染器不会收到原始文件系统路径。-宿主清理 CSS,拒绝 `@import`,`url()` 目标仅允许 `data:` URI 或已声明的主题资源;每份-样式表上限 256 KiB,每个插件最多八个主题。可选 `assets` 接受 `png`、`jpg`、-`jpeg`、`webp`、`avif`、`svg`、`woff2` 文件,总大小上限 4 MiB。路径可以是插件包内-相对路径(不得逃出插件根目录或引用 `node_modules`),也可以是绝对路径。-匹配的 CSS URL 会改写为已注册、只读的 `plugin-asset://` URL;卸载插件时撤销-注册,渲染器不会收到原始文件系统路径。+`windowAppearance.backgroundColor` 支持 `#rrggbb` 或 `#rrggbbaa`,需要+`ui.window.appearance`,仅在本插件主题选中时生效。macOS 默认透明窗口会忽略该颜色,+关闭 **Translucent window** 后才应用到不透明窗口。`cornerRadius` 接受 0..24 DIP 整数;+Windows 11 的 0 表示直角,正数使用系统圆角,macOS 保持原生圆角。+完整字段见[清单规范](/zh-CN/spec/07-plugins/02-plugin-manifest-schema)。-可选的 `contributes.windowAppearance.backgroundColor` 为 `light`/`dark` 提供-`#rrggbb` 或 `#rrggbbaa` 颜色,除 `ui.theme` 外还需要 `ui.window.appearance`。-它仅在该插件的主题被选中时生效,切换到其他主题后恢复宿主背景;macOS 保留-系统 vibrancy。完整主题与窗口外观字段参见-[清单契约](spec/07-plugins/02-plugin-manifest-schema.md)。-### 6.8 MCP 服务器+运行时改主题无需重载:`pi.themes.upsert`、`remove`、`list`、`pi.app.setTheme` 使用 `ui.theme`。+`pi.themes.setVariables(themeId, values)` 只接受本主题已声明的类型变量+(`length`、`number`、`color`、`select`),不接受任意 CSS 或宿主保留变量。+`contributes.scenicThemes` 通过宿主渲染 1..12 张设置卡片,需要 `ui.settings` 与 `ui.theme`。+任意 HTML/JS 形式的 `settingsDestinations` 不是公开贡献点。++### 6.8 工作面板视图++`contributes.views` 声明停靠在工作面板中的隔离 HTML 页面,需要 `ui.view`。+可以和独立面板共用 HTML;停靠时没有窗口控制条,`--pi-plugin-titlebar-height` 为 `0px`。++```json+{+ "contributes": {+ "views": [+ {+ "id": "changes",+ "title": { "en": "Changes", "zh-CN": "改动" },+ "icon": "diff",+ "entry": "views/changes.html",+ "order": 10+ }+ ]+ },+ "permissions": ["ui.view"]+}+```++标题支持字符串或 `{ en, "zh-CN" }`。图标使用 SDK 的 `PLUGIN_VIEW_ICONS` 列表,+未知名称显示字母方块,检查器会给出警告。激活范围不匹配的项目不会显示该视图。+用 `pi.ui.revealView({ viewId, sessionId, location })` 显示自己的视图;指定已不在前台的+会话会被拒绝。首次位置通过 URL 参数 `piViewOpen` 传入,加载后的新位置通过+`view:open` 事件 `{ path }` 传入,不重载页面,也不丢弃未保存状态。++`examples/plugins/hello/views/greetings.html` 是最小示例,+`apps/desktop/resources/plugins/pi.file-manager` 是完整实现。+自定义 `onPanelInvoke` 操作必须自行验证输入;宿主不会自动把它们变成受 `pi.fs` 权限控制的调用。++### 6.9 MCP 服务器MCP 服务器是声明性的。本地服务器需要 `mcp.server.local`;一个远程服务器需要 `mcp.server.remote`:@@ -554,6 +625,10 @@ MCP 服务器是声明性的。本地服务器需要 `mcp.server.local`;一个```json{"contributes": {+ "settings": [+ { "key": "docsMode", "title": "Docs mode", "type": "string", "default": "public" },+ { "key": "clientName", "title": "Client name", "type": "string", "default": "my-plugin" }+ ],"mcpServers": [{"id": "docs",@@ -562,7 +637,7 @@ MCP 服务器是声明性的。本地服务器需要 `mcp.server.local`;一个"command": "bin/docs-server","args": ["--stdio"],"env": {- "DOCS_TOKEN": { "setting": "docsToken" }+ "DOCS_MODE": { "setting": "docsMode" }}},{@@ -570,12 +645,13 @@ MCP 服务器是声明性的。本地服务器需要 `mcp.server.local`;一个"transport": "http","url": "https://mcp.example.com/tools","headers": {- "Authorization": { "setting": "issuesAuthorization" }+ "X-Client-Name": { "setting": "clientName" }}}]},- "permissions": ["mcp.server.local", "mcp.server.remote"]+ "permissions": ["mcp.server.local", "mcp.server.remote"],+ "net": { "domains": ["mcp.example.com"] }}```@@ -584,9 +660,9 @@ stdio 命令必须是 `PATH` 上的裸命令或插件相对路径的可执行文默认 uv 安装位置)。远程 URL 可以使用 HTTP 或 HTTPS,并且主机必须列在`net.domains` 中;非回环 HTTP 不加密,因此只应在可信网络中使用。设置引用仅读取该插件的设置——主机环境和提供商密钥永远不会被转发。MCP 工具遵循与手写插件工具-相同的仅 Agent 策略和命名空间。+相同的按需工具目录与命名空间。MCP 工具默认中风险,不会因服务器声称只读就自动获得 Plan 权限。-### 6.9 常驻服务和消息总线+### 6.10 常驻服务和消息总线声明服务 ID 和允许的主题:@@ -632,7 +708,7 @@ unsubscribe = await pi.bus.subscribe("example.build.*", async (message) => {消息。将主题视为对任何已安装的具有匹配插件的公共主题订阅;切勿将秘密放入有效负载中。-### 6.10 Agent 扩展(pi ExtensionAPI 模块)+### 6.11 Agent 扩展(pi ExtensionAPI 模块)插件可以携带直接在 agent 进程内运行的代码:一个面向 pi CLI `ExtensionAPI` 编写的模块,与 pi 扩展使用同一契约。它可以注册工具、斜杠命令,以及每个回合、每次工具调用@@ -695,7 +771,7 @@ export default function (pi) {Electron 头重建(`npx @electron/rebuild -v <electron 版本>`)即可修复。安装失败会清理部分依赖并显示警告 toast,不会阻塞导入;只有扩展实际加载失败时插件行才显示 load error。-### 6.11 渲染器插槽+### 6.12 渲染器插槽上面每一种界面都是插件自己拥有的窗口或页面。**渲染模块**则绘制在 PI-Desktop 自己的窗口里:输入区工具栏上的控件、消息操作栏上的条目、助手回复下方的区块、自有 Agent 工具的卡片、@@ -754,16 +830,200 @@ export function onLoad(pi) {`packages/plugin-sdk/src/renderer.ts` 里有类型和各插槽的 props,manifest 侧见[规格 07-plugins/02 §3.2](spec/07-plugins/02-plugin-manifest-schema.md)。-## 7.权限设计+### 6.13 模型 Provider 与 OAuth++通过 `provider.register` 和清单声明 Provider。宿主持有 Provider 行、API key 表单、+加密凭证和模型请求;插件不会收到用户在 Add Service 输入的 key。+完整 id 为 `plugin:<pluginId>:<id>`。分类和简介支持字符串或 `{ en, "zh-CN" }`。++```json+{+ "permissions": ["provider.register"],+ "contributes": {+ "providers": [{+ "id": "example",+ "name": "Example AI",+ "category": "Example services",+ "description": "Models from your Example account.",+ "baseUrl": "https://api.example.com/v1",+ "apiStyle": "chat_completions",+ "authKind": "api_key",+ "models": []+ }]+ }+}+```++空模型列表仅适用于提供 `baseUrl` 的 API-key Provider,宿主在保存 key 后发现模型。+其他情况应声明 1..64 个模型;不限制每个插件的 Provider 数量。支持的 API style 为+`chat_completions`、`opencode_go`、`responses`、`anthropic_messages`、+`google_generative_ai`、`openai_codex_responses`、`pi_messages`;认证类型为+`api_key`、`none`、`oauth`。++OAuth 还需要 `provider.oauth`、`baseUrl` 以及 `onProviderOAuth(request, { signal })`。+处理 `login` / `refresh`,返回 `{ accessToken, refreshToken?, expiresAt?, accountLabel?, headers? }`。+只有 refresh 会收到本项现有凭证。使用 `pi.providers.oauth.prompt` / `.notify` 展示宿主交互,+并响应取消。refresh token 不会进入渲染器或 Agent Runtime。令牌请求若走宿主网络 API,+仍需单独的 `net.fetch` 与出网声明。禁用插件保留并关闭 Provider 行;移除声明或卸载会删除行及凭证。++### 6.14 跟随会话、导入历史、读取用量++用 `pi.session.getActive()` 与 `session:activated` 跟随当前选择的会话,无需新增权限,+但仍受项目激活范围限制。离开聊天时返回 `null`,否则为 `{ sessionId, projectPath, activeTurn }`;+`activeTurn` 为 `null` 或 `{ turnId, startedAt }`。快照可能在 `await` 期间失效。++`session:turnEnded` 提供 `{ sessionId, turnId, reason }`,原因为 `completed`、`aborted`、`error`。+存活的插件每轮收到一次,事件不确认、不重放,也不保证所有迟到的工具已退出。+订阅与取消订阅应使用同一个函数引用。++```js+function onSession(snapshot) {+ if (!snapshot) return;+ console.log("Selected session", snapshot.sessionId);+}++async function onLoad() {+ pi.events.on("session:activated", onSession);+ onSession(await pi.session.getActive());+}++function onUnload() {+ pi.events.off("session:activated", onSession);+}++module.exports = { onLoad, onUnload };+```++历史管理使用独立的所有权边界。声明+`contributes.sessionSources: [{ id: "archive", label: "Archive" }]` 后,按需使用:++| 任务 | 方法 | 权限 |+|---|---|---|+| 导入历史 | `session.import`、`session.importBatch` | `session.import` |+| 读取自己导入的历史 | `session.list`、`get`、`listMessages` | `session.read.own` |+| 重命名自己导入的会话 | `session.rename` | `session.update.own` |+| 移入回收站或清除自己导入的会话 | `session.delete` | `session.delete.own` |+| 创建或复用显式项目绑定 | `project.create`;导入传 `projectId` | `project.create` |+| 生成默认标题 | `session.getAutoTitleContext`、`setAutoTitle` | `session.autoTitle` |+| 读取已完成轮次用量 | `usage.listTurns` | `usage.read` |++导入以 `(pluginId, source, externalId)` 幂等。时间必须为严格 RFC3339,消息时间单调递增,+后续调用使用宿主返回的 id。导入的 Provider、模型、路径只是历史元数据,不会自动建立实时绑定。+传现有 `projectId` 才绑定项目;创建项目不会切换工作区。宿主用 `sessionsChanged` 刷新界面。++读取与修改仅限自己导入的会话。批量 `skip` 逐项继续,`fail` 原子提交。+`trash` 保留正文和来源,`purge` 删除两者。没有通用消息修改或任意会话重绑定 API。+自动标题只暴露默认标题会话的首条提示词和回复摘要,通过 `expectedTitle` 比较更新,手动改名优先。+用量只含计数和标识,不含正文。载荷与上限见[会话 API 规范](/zh-CN/spec/07-plugins/03-plugin-api)。++### 6.15 模型目录与单次补全++`pi.models.list()`(`models.list`)返回已就绪的模型绑定,不含凭证。+将返回的 `key` 原样传给 `pi.agent.complete`(`agent.complete`),模型 id 自身可能包含 `/`。++```js+const models = await pi.models.list();+const model = models.find((item) => item.isDefault) ?? models[0];+if (!model) throw new Error("Configure a model first");+const answer = await pi.agent.complete({+ modelKey: model.key,+ system: "Answer briefly.",+ messages: [{ role: "user", content: "Explain this plugin's purpose." }],+});+await pi.ui.showToast(answer.text);+```++该 API 会消耗用户的 Provider 配额,不启用工具。认证、错误分类和有界重试由宿主持有。+上限为 90 秒、每插件滚动一分钟 8 次。`includeSessionContext` 还需 `session.read`,+且必须处于本插件 Agent 工具的有效调用中;`session.getLlmContext()` 同样如此。+后台服务、输入框转换、当前会话快照都不授予读取正文的能力。+处理 `TIMEOUT`、`RATE_LIMITED` 及 Provider 分类错误,避免无限重试。++### 6.16 输入框转换与建议++转换由用户主动触发,只收到 `{ id, text, modelKey? }`。声明+`contributes.composerTransforms` 和 `composer.transform` 后导出:++```js+function onComposerTransform({ id, text }) {+ if (id !== "trim") throw new Error("Unknown transform");+ return text.trim();+}++module.exports = { onComposerTransform };+```++在该贡献中声明 `{ "id": "trim", "title": "Trim draft", "undoTitle": "Undo trim" }`。+输入与输出各限 100,000 字符。宿主保留文件引用,丢弃编辑或切换会话后的过时结果,并提供撤销。+回调不会收到历史正文、附件数据或单独的文件路径元数据。++建议使用独立的主进程 API `pi.composer`,需要 `composer.suggest`,只在空草稿时显示占位提示,+不会发送消息。++```js+const active = await pi.session.getActive();+if (active) {+ const result = await pi.composer.suggest({+ sessionId: active.sessionId,+ turnId: active.activeTurn?.turnId,+ text: "Add a regression test for this change",+ ttlMs: 120_000,+ });+ if (!result.shown) console.log("Suggestion refused", result.reason);+}+// On your own cancellation path:+await pi.composer.clearSuggestion();+```++文本合并成一行并截为 200 字符;默认存活 120 秒,范围限制为 1..600 秒。+Tab 接受、Esc 忽略。输入、粘贴、附件、发送、切换会话、新轮次、卸载、渲染器重载或关窗都会清除。+正常拒绝返回 `{ shown: false, reason }`,原因为 `session-not-visible`、`draft-not-empty`、+`stale-turn`、`replaced`、`unsupported`;非法输入或缺少权限仍抛错。+若由 `session:turnEnded` 触发生成,传该事件的 `turnId`,避免迟到的补全干扰新轮次。++### 6.17 系统快捷键、WebSocket、麦克风与语音++系统快捷键独立于应用内 `shortcut` 设置。在 `contributes.globalShortcuts` 中声明 id 与自己的命令,+申请 `keyboard.globalShortcut`,并在 `onLoad` 注册命令。`default` 在加载后注册;运行时通过+`pi.keyboard.registerGlobalShortcut` 修改。检查返回的 `registered` / `error`,冲突返回+`registered: false` 而非抛错。卸载、禁用、崩溃都会释放,最多每插件 8 条。++WebSocket 需要 `net.websocket`,使用与 fetch 相同的出网策略。通过+`pi.net.websocket.connect` / `send` / `close` 操作,订阅完整名称+`net:websocket:open`、`net:websocket:message`、`net:websocket:close`、`net:websocket:error`,+事件包含所属 `socketId`。上限为 4 个连接、1 MiB 帧、4 MiB 待发送队列,随插件释放。++`ui.microphone` 仅允许隔离面板用 `getUserMedia` 获取音频,摄像头仍拒绝。+后台 `pi.audio.*` 有类型和权限门,但**尚无设备后端**,授权后仍返回或抛出 `UNSUPPORTED`。+不能仅凭清单声明实现后台录音。++`pi.speech.registerAdapter` / `unregisterAdapter`(`speech.adapter.register`)添加协议处理器,+返回文本、音频或宿主执行的 HTTP 计划。`openai_audio`、`openai_chat_audio` 是保留 id;+携带绑定 Provider key 的 HTTP 计划只能访问该 Provider origin。++### 6.18 浏览器与桌面操作++`fs.openInBrowser(path)` 只需 `fs.read`,将现有可读 HTML 打开为工作面板资源页,不授予浏览器自动化。+自动化使用 `browser.cdp` 与 `pi.browser.*`;工具调用绑定发起会话,后台会话不能重定向前台页面。+CDP 使用允许列表,Cookie、存储、目标管理、网络拦截仍拒绝。`browser.reveal()` 只负责显式展示,+后台导航无需先调用它。整页截图按比例缩至最多 1280×2048,捕获超时 30 秒。++`desktop.control` 通过 `pi.desktop.listOperations()` 与+`pi.desktop.invoke({ operation, args, confirm? })` 访问审定目录,不开放任意 IPC。+危险操作同时需要 `confirm: true` 和宿主原生对话框中的用户确认。+会话协作的 `spawn` / `send` 还要求有效的插件 Agent 工具调用,来源会话与轮次由宿主注入。+在创建、发消息、取消或删除会话前,请读[桌面控制契约](/zh-CN/spec/07-plugins/03-plugin-api)。++## 7. 权限设计权限均在 `manifest.json` 中声明并由用户授予。未声明或未授予的 API 调用失败并显示 `PERMISSION_DENIED`。| 风险 | 权限 ||---|---|-| 低 | `ui.panel`、`ui.theme`、`notify` |-| 中等 | `clipboard.read`、`clipboard.write`、`fs.read`、`shell.openExternal`、`background.service`、`bus.publish`、`bus.subscribe`、`audio.playback.background`、`keyboard.globalShortcut` |-| 高 | `fs.write`、`fs.delete`、`agent.tool.register`、`agent.prompt.inject`、`renderer.extension`、`net.fetch`、`mcp.server.local`、`mcp.server.remote`、`audio.capture.background`、`net.websocket` |+| 低 | `ui.panel`, `ui.view`, `ui.theme`, `ui.settings`, `ui.window.appearance`, `notify` |+| 中等 | `ui.microphone`, `clipboard.read`, `clipboard.write`, `fs.read`, `composer.transform`, `composer.suggest`, `models.list`, `session.read.own`, `session.update.own`, `usage.read`, `shell.openExternal`, `background.service`, `bus.publish`, `bus.subscribe`, `audio.playback.background`, `keyboard.globalShortcut` |+| 高 | `fs.write`, `fs.delete`, `agent.tool.register`, `agent.prompt.inject`, `agent.complete`, `agent.extension`, `renderer.extension`, `provider.register`, `provider.oauth`, `desktop.control`, `project.create`, `session.read`, `session.import`, `session.delete.own`, `session.autoTitle`, `net.fetch`, `net.anyHost`, `mcp.server.local`, `mcp.server.remote`, `browser.cdp`, `audio.capture.background`, `speech.adapter.register`, `net.websocket` |`keyboard.globalShortcut` 与 `net.websocket` 已实现。`pi.audio.*` 已经存在并且可以调用,其方法仍由权限把关,但当前宿主还没有设备后端:获得授权的调用会以@@ -784,6 +1044,9 @@ export function onLoad(pi) {完整的映射和策略位于[权限矩阵](/zh-CN/spec/07-plugins/13-plugin-permissions-matrix)。+自动重载不会扩大授权或文件范围。若保存后被权限门拒绝,可在插件行的 **More → Reload**+中显式审核并重新加载已登记目录,或再次加载开发目录。删除权限会立即生效。+## 8. 开发和调试### 热重载@@ -819,7 +1082,7 @@ export function onLoad(pi) {`LIMIT_EXCEEDED` 或 `RATE_LIMITED`。捕获可选操作的错误并将代码包含在诊断中而不记录秘密。-## 9.检查、打包、安装+## 9. 检查、打包、安装从存储库根运行验证:@@ -863,11 +1126,17 @@ Agent 还可以在每种操作模式下运行 `PluginCheck`。 `PluginScaffold`和 `PluginPack` 是代理模式工具,仅限于当前工作区。+打包还会跳过凭证文件(`.env`、`.env.*`、`.npmrc`、`*.pem`、`*.key`)并给出警告。+产物仍必须检查和实际安装,`check` 不证明运行时、兼容版本、授权、网络或中心审核一定成功。+### 用 `pi-plugin publish` 准备插件中心提交`publish` 会打包插件,并把包固定到构建它的 git 提交上,以便插件中心能够重新构建并比对工件:+`publish` 仅在本地准备包和提交 JSON,不会上传或发布。先将 `dist/` 加入插件仓库的+`.gitignore`,因为打包发生在干净工作区检查之前。+```bashpnpm pi-plugin publish ../my-first-plugin [--out <dir>] [--ref <ref>] [--channel stable|beta] [--allow-dirty]```@@ -908,8 +1177,8 @@ SHA-256 并发布该版本,再把目录与安装包同步到[AIUO-Net/pi-desktop-plugins](https://github.com/AIUO-Net/pi-desktop-plugins) 作为 GitHub 备用通道。分发仓库不托管插件源码,向它提交「新增插件源码」的 PR 会被关闭。-签名不是当前的信任原语。包 SHA-256 和显式-许可审查是实施的基线;遵循+当前使用包 SHA-256 和显式+权限审核作为信任基线,后续规划见[签署和更新规范](/zh-CN/spec/07-plugins/08-plugin-signing-updates)了解路线图详细信息。@@ -929,7 +1198,7 @@ SHA-256 并发布该版本,再把目录与安装包同步到| MCP 服务器未启动 | 传输字段、命令、URL、设置或权限无效 | 运行 `pi-plugin check`,然后通过插件 ID 检查日志 || 服务反复重启 | `start` 抛出异常或插件进程退出 | 使 `start` 幂等,在 `stop` 中进行清理,并检查重新启动日志 |-## 12.参考图+## 12. 参考索引- [示例插件](https://github.com/vastsa/PI-Desktop/tree/main/examples/plugins)- [插件系统概述](/zh-CN/spec/07-plugins/01-plugin-system)@@ -941,21 +1210,53 @@ SHA-256 并发布该版本,再把目录与安装包同步到- [权限](/zh-CN/spec/07-plugins/13-plugin-permissions-matrix)- [Hello 参考插件](https://github.com/vastsa/PI-Desktop/tree/main/examples/plugins/hello)-### Fetch redirect policy (unreleased)--Check host support before relying on a policy; old hosts can ignore unknown-request fields. Never fall back to a raw network request.+## 13. 完整 SDK 接口与源码索引-```js-if (typeof pi.net.getCapabilities !== "function") throw new Error("Upgrade PI-Desktop");-const capabilities = await pi.net.getCapabilities();-if (!capabilities.fetchRedirectModes.includes("error")) throw new Error("Unsupported host");-const response = await pi.net.fetch({ url: endpoint, redirect: "error" });-```+下表逐项对应 `packages/plugin-sdk/src/index.ts` 的 `PluginHostApi`,是方法索引,不代表已授权。+权限、调用上下文和可用性限制仍适用,`pi.audio` 仍未实现设备后端。+面板桥是较小的接口集合,见 API 规范 §6。-`error` rejects every 3xx with `REDIRECT_DISALLOWED` before accessing Location.-`manual` returns the original status, headers and body. Omitted/`follow` retains-the existing bounded, per-hop egress-checked behavior. Invalid modes are rejected-before I/O. No mode expands network permissions. See the-[complete contract](/spec/07-plugins/03-plugin-api.md#net) and the-local-only test plugin at `examples/plugins/fetch-redirect/README.md` in the repository.+| 命名空间 | 方法 |+|---|---|+| `pi.app` | `getVersion`, `getLocale`, `getAppearance`, `setTheme` |+| `pi.themes` | `upsert`, `remove`, `list`, `setVariables` |+| `pi.plugin` | `getId`, `getManifest`, `getSettings`, `setSettings`, `getDataPath` |+| `pi.commands` | `register`, `unregister` |+| `pi.speech` | `registerAdapter`, `unregisterAdapter` |+| `pi.composer` | `suggest`, `clearSuggestion` |+| `pi.ui` | `openPanel`, `closePanel`, `showToast`, `notify`, `getNotificationPermission`, `requestNotificationPermission`, `showNativeNotification`, `revealView` |+| `pi.project` | `create` |+| `pi.providers.oauth` | `prompt`, `notify` |+| `pi.workspace` | `get` |+| `pi.desktop` | `listOperations`, `invoke` |+| `pi.audio` | `getInputDevices`, `openInput`, `closeInput`, `getCaptureState`, `onInputFrame`, `offInputFrame`, `openOutput`, `writeOutput`, `stopOutput`, `closeOutput` |+| `pi.keyboard` | `registerGlobalShortcut`, `unregisterGlobalShortcut`, `listGlobalShortcuts` |+| `pi.fs` | `readText`, `stat`, `readRange`, `readPreview`, `openDefault`, `openInBrowser`, `reveal`, `writeText`, `glob`, `list`, `remove`, `requestDirectory` |+| `pi.agent` | `registerTool`, `unregisterTool`, `complete` |+| `pi.models` | `list` |+| `pi.session` | `getLlmContext`, `getActive`, `getAutoTitleContext`, `setAutoTitle`, `list`, `get`, `listMessages`, `import`, `importBatch`, `rename`, `delete` |+| `pi.usage` | `listTurns` |+| `pi.services` | `register`, `unregister` |+| `pi.bus` | `publish`, `subscribe` |+| `pi.clipboard` | `readText`, `writeText`, `getHistory` |+| `pi.shell` | `openExternal` |+| `pi.browser` | `reveal`, `navigate`, `action`, `setBounds`, `setVisible`, `getState`, `openExternal`, `snapshot`, `screenshot`, `click`, `fill`, `evaluate`, `console`, `cdp` |+| `pi.net` | `getCapabilities`, `fetch` |+| `pi.net.websocket` | `connect`, `send`, `close` |+| `pi.events` | `on`, `off` |++渲染器模块的 `pi` 是另一套接口:`plugin.id` / `version`、`slots.register`、+`ui.injectStyle`、`ui.openLayer`、`composer.subscribeDraft`、`dispatch`。+订阅草稿需要在 `rendererActions` 声明 `composer.readDraft`;替换草稿需使用捕获的+`generation` 作为 `expectedGeneration` 防止过时写入,要求用户输入事件、Composer 未聚焦,并保留全部宿主 chip。具体载荷见 `renderer-composer.ts`,不能访问宿主 store。+没有用于直接发送消息的 renderer action。++源码核对入口:`packages/plugin-sdk/src`(类型与校验)、`packages/plugin-devkit/src`+(模板、检查、打包、提交准备)、`crates/host-core/src/plugins`(安装与持久化)、+`apps/desktop/electron/main/plugin-runtime.ts` 与 `plugin-host-process.mjs`(实际分发与生命周期)、+`apps/desktop/electron/preload/plugin-panel.ts`(面板桥)、`apps/desktop/test/plugin-*.test.mjs`(验证)。+示例位于 `examples/plugins/{hello,ui-slots-lab,fetch-redirect,roundtable}`。++`docs/plugin-plan` 包含评审材料和规划中的运行时钩子,draft 页面不是已实现的 SDK 导出。+判断能力是否存在时,以 SDK 与实际运行时为准。应用内置开发说明位于+`apps/desktop/resources/skills/plugin-development.md`。diff --git a/docs/zh-CN/spec/07-plugins/01-plugin-system.md b/docs/zh-CN/spec/07-plugins/01-plugin-system.mdindex 44e13ef1e..c1d02816f 100644--- a/docs/zh-CN/spec/07-plugins/01-plugin-system.md+++ b/docs/zh-CN/spec/07-plugins/01-plugin-system.md@@ -15,11 +15,11 @@- 用户 MCP 工具使用前缀 `mcp_<serverId>_<toolName>`,与 D015 不相交插件命名空间 (D193)-Plan 策略:插件代理工具、注册工具的插件技能以及任何-未知的插件贡献在 Plan 中不可见或可执行。这否认-在通用插件权限评估之前由 host-core 强制执行,并且不能-可以被低风险清单、会话授权或 `auto` 绕过。插件工具-在批准的 Plan → Agent 转换后,对同一 Agent 仍然可用。+插件工具默认在 Plan/Goal 中隐藏并拒绝。运行时工具注册可通过非空 `planSafeActions`+显式加入,只有 `args.action` 位于该列表时才允许执行。有 schema action enum 时会校验取值。+清单描述符应与运行时注册保持一致,真正执行的工具由运行时注册决定。+`risk: "low"`、会话授权和 `auto` 不能代替该声明。宿主策略与插件执行器都会校验,+执行器对越界 action 返回 `PERMISSION_DENIED`。该列表是作者的只读承诺,不是副作用沙盒(ADR 0211)。## 1. 目标@@ -51,7 +51,7 @@ Plan 策略:插件代理工具、注册工具的插件技能以及任何- 会话命令- 设置- 高风险能力必须经过权限框架-- 插件默认无法直接获取任意Node/Electron权限+- 宿主 API 需要声明与授权;插件主进程的原始 Node 代码仍以用户权限运行,隔离面板没有 Node 集成## 3. 插件可以做什么@@ -87,8 +87,7 @@ Plan 策略:插件代理工具、注册工具的插件技能以及任何my-plugin/├── manifest.json # required├── package.json # optional (if it carries build artifacts / dependency metadata)-├── main.js # plugin runtime extension entry (restricted API)-├── preload.js # optional, plugin panel bridge+├── main.js # plugin entry; host injects the brokered pi API├── renderer/ # plugin UI (static assets)│ ├── index.html│ └── assets/@@ -102,7 +101,7 @@ my-plugin/### 安装位置```text-~/.pi-desktop/plugins/+<dataRoot>/plugins/├── installed/│ └── <plugin-id>/├── disabled/@@ -161,6 +160,8 @@ my-plugin/]},"permissions": [+ "ui.panel",+ "agent.prompt.inject","clipboard.read","clipboard.write","notify",@@ -174,10 +175,6 @@ my-plugin/},"engines": {"piDesktop": ">=0.1.0"- },- "entrypoints": {- "onLoad": "main.js#onLoad",- "onUnload": "main.js#onUnload"}}```@@ -294,8 +291,7 @@ Host Main (PI-Desktop)技能以声明方式贡献(`contributes.skills` + `agent.prompt.inject`),不由插件调用:主机将目录放在系统提示符中,并且-模型通过内置的 `Skill` 工具 (D174) 加载主体。有计划,没有-目前曝光:`pi.agent.appendSystemHint(text)`。+模型通过内置 `Skill` 工具 (D174) 按需加载正文;没有命令式 `appendSystemHint` 宿主 API。### 后台服务(需要 `background.service`)- `pi.services.register({ id, start, stop? })`@@ -374,7 +370,7 @@ Electron 主进程通知 API 并共享清单 `notify`3、用户可以在插件管理页面撤销权限;重新加载是正在运行的插件需要观察更改的授权集-未实施每次调用确认和直接 Node 访问的任何策略。+越界文件访问和危险桌面操作使用宿主原生确认,原始 Node API 仍没有操作系统能力沙盒。## 9. 命令面板diff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.mdindex 1c16423f5..8546a54cf 100644--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md@@ -22,9 +22,12 @@ type PluginManifestV1 = {name: string;version: string; // semverdescription?: string;+ author?: string | { name: string; url?: string; email?: string };+ homepage?: string;/**- * 展示文案的多语言表:当应用语言命中其中某个 locale 时用它替换- * `name` / `description`(见 §3.1)。扁平字段仍是作者自己的语言,也是最终回退。+ * Display strings per locale, shown in place of `name`/`description` when the+ * shell's language matches one of the declared locales (see §3.1). The flat+ * fields stay the author's own language and remain the fallback.*/i18n?: {[locale: string]: {@@ -33,39 +36,35 @@ type PluginManifestV1 = {safetyNotes?: string;};};- author?: string | { name: string; url?: string; email?: string };- homepage?: string;repository?: string;icon?: string; // relative path- main?: string; // plugin runtime entry- renderer?: string; // 宿主求值以挂载 UI 插槽的模块(§3.2)- rendererActions?: string[]; // 渲染组件可派发的动作,最多 16 个- rendererCallMethods?: string[]; // plugin.call 可触达的 onRendererCall 方法,最多 32 个+ main: string; // required plugin runtime entry+ renderer?: string; // module the host evaluates to mount UI slots (§3.2)+ rendererActions?: string[]; // actions a renderer component may dispatch, at most 16+ rendererCallMethods?: string[]; // onRendererCall methods plugin.call may reach, at most 32ui?: PluginUiConfig;contributes?: PluginContributes;permissions?: PluginPermission[];- fs?: PluginFsPolicy; // 每个文件权限可以触碰哪些路径(§5.2)- net?: { domains?: string[] }; // 出网白名单(§5.3)+ fs?: PluginFsPolicy; // which paths each file permission may touch (§5.2)+ net?: { domains?: string[] }; // egress allowlist (§5.3)engines?: {piDesktop?: string; // semver range};- entrypoints?: {- onInstall?: string;- onLoad?: string;- onEnable?: string;- onDisable?: string;- onUnload?: string;- onUninstall?: string;- };activationEvents?: string[]; // e.g. onCommand:xxx / onStartup/**- * 随应用打包插件的首次注册默认值。省略表示启用。- * 市场安装和开发加载仍在用户授权后启用。+ * First-registration default for bundled plugins. Omitted means enabled.+ * Marketplace and development installs still enable after the user grants+ * permissions.*/enabledByDefault?: boolean;};```+SDK 的 `author` 接受字符串或联系对象,但当前 Rust 安装器把它反序列化为字符串,+可安装的包应使用显示字符串。SDK 与宿主校验不完全相同:两者都要求 `main`,+但 schema 版本和元数据检查有差异。编写 `schemaVersion: 1`,先 `check` 再安装实际包,+不能把底层解析器较宽松的行为当成兼容性承诺。+## 3. 用户界面配置```ts@@ -73,8 +72,13 @@ type PluginUiConfig = {panel?: string; // html entrywidth?: number;height?: number;+ shape?: "panel" | "widget";+ alwaysOnTop?: boolean;resizable?: boolean;- title?: string;+ title?: string | {+ en: string;+ "zh-CN": string;+ }; // localized native panel identity; both locales are required for an object};```@@ -153,18 +157,19 @@ type PluginContributes = {commands?: PluginCommandContrib[];agentTools?: PluginAgentToolContrib[];skills?: Array<string | PluginSkillContrib>; // relative paths, or metadata overrides- agentExtensions?: string[]; // 在 agent sidecar 内运行的 ExtensionAPI 模块;需要 `agent.extension`(规格 16)- providers?: PluginProviderContrib[]; // 宿主拥有的 provider 行;需要 `provider.register`(规格 13)+ agentExtensions?: string[]; // ExtensionAPI modules run in the agent sidecar; needs `agent.extension` (spec 16)+providers?: PluginProviderContrib[]; // Host-owned provider rows; needs `provider.register`; OAuth also needs `provider.oauth` (spec 13)settings?: PluginSettingContrib[];themes?: PluginThemeContrib[];- windowAppearance?: PluginWindowAppearanceContrib; // 原生窗口背景;需要 `ui.window.appearance`- composerTransforms?: PluginComposerTransformContrib[]; // 用户主动触发的输入框文本操作;需要 `composer.transform`+ scenicThemes?: PluginScenicThemesContrib;+ windowAppearance?: PluginWindowAppearanceContrib; // native window background and Windows corner request; needs `ui.window.appearance`+ composerTransforms?: PluginComposerTransformContrib[]; // explicit Composer text actions; needs `composer.transform`mcpServers?: PluginMcpServerContrib[];- services?: PluginServiceContrib[];+ services?: PluginServiceContrib[];bus?: PluginBusContrib;views?: PluginViewContrib[];sessionSources?: PluginSessionSourceContrib[];- globalShortcuts?: PluginGlobalShortcutContrib[]; // 需要 `keyboard.globalShortcut`+ globalShortcuts?: PluginGlobalShortcutContrib[]; // needs `keyboard.globalShortcut`};type PluginCommandContrib = {@@ -172,55 +177,54 @@ type PluginCommandContrib = {title: string;keywords?: string[];category?: string;- icon?: string;- requires?: PluginPermission[]; // extra per-command perms};type PluginAgentToolContrib = {name: string; // tool name exposed to agentdescription: string;- risk: "low" | "medium" | "high";- schema: Record<string, unknown>; // JSON schema object- timeoutMs?: number;- permissions?: PluginPermission[];+ risk?: "low" | "medium" | "high";+ schema?: unknown; // JSON schema object+ planSafeActions?: readonly string[]; // read-only action names for Plan/Goal};type PluginComposerTransformContrib = {- id: string; // 插件内唯一;[A-Za-z][A-Za-z0-9_-]{0,63}+ id: string; // plugin-local; [A-Za-z][A-Za-z0-9_-]{0,63}title: string | { en: string; "zh-CN": string };undoTitle?: string | { en: string; "zh-CN": string };};type PluginSettingContrib = {key: string;- title: string; // 作者语言;生成式设置面板不做本地化+ title: string; // author language; the generated sheet does not localizedescription?: string;type: "string" | "number" | "boolean" | "select" | "json" | "shortcut";default?: unknown;enum?: Array<{ label: string; value: string | number | boolean }>;- command?: string; // shortcut 设置调用这个已声明的插件命令- scope?: "plugin"; // 暂不支持全局插件快捷键+ /** Required for shortcut settings; invokes a declared plugin command. */+ command?: string;+ /** App-local setting scope; OS-global shortcuts use globalShortcuts instead. */+ scope?: "plugin";secret?: boolean;};type PluginViewContrib = {- id: string; // ^[a-zA-Z][a-zA-Z0-9_-]{0,63}$,插件内唯一+ id: string; // ^[a-zA-Z][a-zA-Z0-9_-]{0,63}$, unique within the plugintitle: string | { en: string; "zh-CN": string };- icon?: string; // 宿主图标集中的 token;未知 token 渲染为字母瓷砖- entry: string; // 视图 HTML 入口的相对路径- order?: number; // 插件视图分组内的升序排序键,默认 0+ icon?: string; // token from the host icon set; unknown tokens draw a letter tile+ entry: string; // relative path to the view's HTML entry+ order?: number; // ascending sort key in the plugin-views menu group, default 0};type PluginSessionSourceContrib = {- id: string; // ^[a-zA-Z][a-zA-Z0-9._-]{0,63}$,插件内唯一- label?: string | { en: string; "zh-CN": string };+ id: string; // ^[a-zA-Z][a-zA-Z0-9._-]{0,63}$, unique within the plugin+ label?: string | { en: string; "zh-CN": string };};-/** 插件声明的一个系统级快捷键(`keyboard.globalShortcut`)。 */+/** One system-wide accelerator a plugin declares (`keyboard.globalShortcut`). */type PluginGlobalShortcutContrib = {- id: string; // ^[a-zA-Z][a-zA-Z0-9._-]{0,63}$,插件内唯一- command: string; // 必须声明在 contributes.commands 里- default?: string; // 宿主在加载后注册的加速键;省略则由 `pi.keyboard` 稍后注册+ id: string; // ^[a-zA-Z][a-zA-Z0-9._-]{0,63}$, unique within the plugin+ command: string; // must be declared in contributes.commands+ default?: string; // accelerator the host registers after load; omitted means `pi.keyboard` registers it later};type PluginThemeContrib = {@@ -228,15 +232,40 @@ type PluginThemeContrib = {label: string;path: string; // relative `.css` filebase?: "light" | "dark"; // palette the overrides layer on, default `dark`- assets?: string[]; // 插件包内相对路径或绝对路径;png/jpg/jpeg/webp/avif/svg/woff2 白名单,总和上限 4 MB;- // 相对路径在插件根目录内解析,拒绝路径穿越和 `node_modules`;- // 命中的 `url()` 改写为 `plugin-asset://`+ assets?: string[]; // package-relative or absolute png/jpg/jpeg/webp/avif/svg/woff2, 4 MB summed;+ // relative paths resolve inside plugin root; traversal/node_modules are rejected;+ // each matching `url()` is rewritten to `plugin-asset://`+};++type PluginScenicThemesContrib = {+ id: string;+ label: { en: string; "zh-CN": string };+ description: { en: string; "zh-CN": string };+ keywords?: Array<{ en: string; "zh-CN": string }>;+ icon: "palette";+ themes: Array<{+ themeId: string;+ label: { en: string; "zh-CN": string };+ description: { en: string; "zh-CN": string };+ previewAsset: string;+ }>;};type PluginWindowAppearanceContrib = {backgroundColor?: { light?: string; dark?: string }; // #rrggbb | #rrggbbaa+ cornerRadius?: number; // integer 0..24 DIP, Windows main window only; default 12};+`cornerRadius` belongs to the contributing plugin and applies while any of its+declared themes is selected. It does not change macOS/Linux native corners.+Removing the theme or its `ui.window.appearance` grant restores the Windows+main-window default of 12 DIP (`--radius-md`). Invalid or fractional values+reject the manifest. On Windows build 22000 and later, 0 requests square+corners and every positive value requests the same native DWM rounded+preference; Windows chooses the exact radius. Earlier Windows builds retain the+requested DIP radius. On Windows 11, an 8-digit background is composited over+the resolved built-in theme color so the top-level window remains opaque.+type PluginSkillContrib = {id?: string; // defaults to the file name without its extensionpath: string; // relative path to the skill document@@ -252,8 +281,8 @@ type PluginMcpServerContrib = {command?: string; // bare PATH name, or plugin-relative executableargs?: string[];env?: Record<string, string | { setting: string }>;- // 远程 HTTP 传输- url?: string; // 绝对 http(s) 端点;HTTP 可以指向可信的局域网主机+ // remote HTTP transport+ url?: string; // absolute http(s) endpoint; HTTP may target a trusted LAN hostheaders?: Record<string, string | { setting: string }>;};@@ -269,13 +298,15 @@ type PluginBusContrib = {};type PluginProviderContrib = {- id: string; // ^[a-zA-Z][a-zA-Z0-9_-]{0,63}$,插件内唯一- name: string; // 原生 provider 列表中的显示名- vendorKey?: string; // models.dev 供应商键,默认 `custom`- baseUrl?: string; // 绝对 http(s) URL- apiStyle?: PluginProviderApiStyle; // 线路风格,默认 `chat_completions`- authKind?: "api_key" | "none"; // 默认 `api_key`;`oauth` 暂被拒绝- models: PluginProviderModelContrib[]; // 1..64 条+ id: string; // ^[a-zA-Z][a-zA-Z0-9_-]{0,63}$, unique within the plugin+ name: string; // display name in the native provider list+ category?: string | { en: string; "zh-CN": string }; // Add Service group; defaults to plugin name+ vendorKey?: string; // models.dev vendor key, default `custom`+ baseUrl?: string; // absolute http(s) URL+ apiStyle?: PluginProviderApiStyle; // wire style, default `chat_completions`+ authKind?: "api_key" | "none" | "oauth"; // default `api_key`+ oauth?: { loginLabel?: string; isSubscription?: boolean }; // only with `authKind: "oauth"`+ models: PluginProviderModelContrib[]; // 1..64 entries};type PluginProviderApiStyle =@@ -288,14 +319,14 @@ type PluginProviderApiStyle =| "pi_messages";type PluginProviderModelContrib = {- id: string; // 1..256 个字符,provider 内唯一- name?: string; // 模型绑定的显示标签+ id: string; // 1..256 characters, unique within the provider+ name?: string; // display label for the model bindingcontextWindow?: number;maxTokens?: number;supportsImages?: boolean;- /** 模型可提供的规范思考档位,按声明顺序保留。 */+ /** Canonical thinking levels offered by this model, in declaration order. */thinkingLevels?: string[];- /** 当该值存在于 `thinkingLevels` 时,新会话使用它。 */+ /** New sessions use this level when it is present in `thinkingLevels`. */defaultThinkingLevel?: string;};```@@ -326,6 +357,7 @@ type PluginPermission =| "composer.suggest"| "renderer.extension"| "provider.register"+ | "provider.oauth"| "net.fetch"| "net.anyHost"| "shell.openExternal"@@ -366,9 +398,9 @@ type PluginFsPolicy = {};type PluginFsRule = {- root?: "workspace" | "userSelected"; // 默认 `workspace`- scope?: string[]; // 相对 root 的 glob- own?: boolean; // 仅删除:这个插件写过的路径+ root?: "workspace" | "userSelected"; // default `workspace`+ scope?: string[]; // globs relative to the root+ own?: boolean; // delete only: paths this plugin wrote};```@@ -396,7 +428,7 @@ glob 里 `*` 匹配一个路径段,`**` 跨分隔符匹配,并以大小写## 5.3 net —— 出网白名单```ts-type PluginNetDomains = string[]; // "api.example.com" 或 "*.example.com"+type PluginNetDomains = string[]; // "api.example.com" or "*.example.com"```主机掌握的每一条出网路径 —— 面板 session、`pi.net.fetch`、远程 HTTP MCP@@ -468,24 +500,18 @@ OAuth 登录使用宿主自有的账号界面和加密凭据存储。宿主通自身 provider 的凭据。刷新令牌保留在 Electron 主进程与宿主密钥库内,Agent Runtime只接收请求所需的访问令牌。每个 provider 声明目前只支持一个账号;宿主插件进程不是操作系统沙箱,因此授予 `provider.oauth` 表示信任该插件处理此 provider 的凭据。-## 6. activationEvents(可选)--示例:--- `onStartup`-- `onCommand:demo.hello.say`-- `onAgentMode`-- `onWorkspaceOpen`+## 6. activationEvents(可选元数据)-MVP 只能实现:-- `onStartup`-- `onCommand:*`+`activationEvents` 可描述 `onStartup` 等意图;当前运行时在启动恢复、启用和加载开发目录时直接加载,+没有延迟激活调度器。项目资格由宿主激活范围控制。+`engines.piDesktop` 是作者兼容元数据,不能代替最低版本测试与新增方法检测。+从 `main` 导出生命周期函数,没有 `entrypoints` 清单分发器。## 7. 验证规则1. `schemaVersion` 必须是 `1`2. 需要 `id` / `name` / `version`-3. 声明 `ui.panel` 的清单是否需要隐式(自动填充)或通过显式声明获得 `ui.panel` 权限是一个 **悬而未决的问题**(在 [08-meta/open-questions.md](/zh-CN/spec/08-meta/open-questions) 中跟踪)+3. 打开 `ui.panel` 需要显式声明和用户授予 `ui.panel`,路径不会隐式授权4. 如果存在 `agentTools`,则必须声明 `agent.tool.register`。`composerTransforms` 需要 `composer.transform`;每个操作 id 必须匹配`[A-Za-z][A-Za-z0-9_-]{0,63}`,并在插件内保持唯一diff --git a/docs/zh-CN/spec/07-plugins/03-plugin-api.md b/docs/zh-CN/spec/07-plugins/03-plugin-api.mdindex ad5808c5e..e6d27c634 100644--- a/docs/zh-CN/spec/07-plugins/03-plugin-api.md+++ b/docs/zh-CN/spec/07-plugins/03-plugin-api.md@@ -16,7 +16,7 @@在插件运行时内部,有一个全局可用:```ts-declare const pi: PiPluginHostApi;+declare const pi: PluginHostApi;```## 3. API 概述(MVP)@@ -34,9 +34,9 @@ pi.app.setTheme(themeId: "system" | "light" | "dark" | `plugin:${string}`): Prom```tstype PluginAppearance = {- theme: string // 原始偏好:"light" | "dark" | "system" | "plugin:<pluginId>:<themeId>"- base: "light" | "dark" | "system" // 该偏好解析出的调色板- locale: string // 当前语言标签(例如 "en"、"zh-CN")+ theme: string // raw preference: "light" | "dark" | "system" | "plugin:<pluginId>:<themeId>"+ base: "light" | "dark" | "system" // palette the preference resolves to+ locale: string // active language tag (e.g. "en", "zh-CN")pluginTheme: { id: string; base: "light" | "dark"; css: string } | null}```@@ -62,10 +62,10 @@ type PluginAppearance = {```tspi.themes.upsert(input: {- id: string; // 本地 id,规则同 contributes.themes[].id+ id: string; // local id, same rules as contributes.themes[].idlabel: string;base: "light" | "dark";- css: string; // 使用 sanitizeThemeCss 消毒+ css: string; // sanitized with sanitizeThemeCss}): Promise<void>pi.themes.remove(themeId: string): Promise<void>@@ -81,8 +81,8 @@ pi.themes.list(): Promise<Array<{ id: string; themeId: string; label: string; ba### 插件```tspi.plugin.getId(): string-pi.plugin.getManifest(): PluginManifestV1-pi.plugin.getSettings<T=Record<string, unknown>>(): Promise<T>+pi.plugin.getManifest(): PluginManifest+pi.plugin.getSettings(): Promise<Record<string, unknown>>pi.plugin.setSettings(partial: Record<string, unknown>): Promise<void>pi.plugin.getDataPath(): Promise<string> // plugin-private directory```@@ -90,7 +90,8 @@ pi.plugin.getDataPath(): Promise<string> // plugin-private directory插件页面会渲染 `contributes.settings` 中声明的字段,并将修改持久化到插件私有设置文件。支持生成字符串、数字、布尔、枚举、JSON 和 `shortcut` 控件。生成式 `title` /`description` / `enum[].label` 是作者语言纯字符串,宿主不会在这些字段上解析 locale-map。需要本地化设置页的插件应贡献 `settingsDestinations` 并读取 `pi.app.getLocale`+map。需要本地化设置页的插件使用自己的面板/视图并读取 `pi.app.getLocale`,+主题设置通过数据型 `scenicThemes` 交给宿主渲染;`settingsDestinations` 不是已实现的公开贡献(ADR 0280)。快捷键仅属于插件域:只有在 PI-Desktop 窗口聚焦且插件激活范围匹配当前项目时,才会调用声明的命令;本版本不会注册操作系统全局快捷键。用户编辑后,主机会向插件发送`plugin:settingsChanged`,便于刷新内存中的配置。@@ -117,7 +118,7 @@ pi.commands.unregister(id: string): Promise<void>type PluginComposerTransformInput = {id: string;text: string;- modelKey?: string; // 当前 Composer 提供商/模型 key;不含凭据+ modelKey?: string; // current Composer provider/model key; no credentials};type PluginModule = {@@ -157,18 +158,18 @@ type PluginModule = {```tspi.composer.suggest(input: {- sessionId: string; // 来自 session:turnEnded 的会话- turnId?: string; // 这段文本对应的轮次;已被新轮次取代则拒绝- text: string; // 单行;折行空白并截断到 200 字符- ttlMs?: number; // 默认 120000;限制在 1000..600000+ sessionId: string; // the session from session:turnEnded+ turnId?: string; // the turn the text answers; an overtaken turn is refused+ text: string; // one line; folded and cut at 200 characters+ ttlMs?: number; // default 120000; clamped to 1000..600000}): Promise<{ shown: true } | {shown: false;reason:- | "session-not-visible" // 该会话不是当前显示的会话- | "draft-not-empty" // 草稿里已有文本或附件- | "stale-turn" // 该会话已经跑了更新的轮次- | "replaced" // 更新的建议先占用了位置- | "unsupported"; // 没有窗口、没有输入框,或未及时答复+ | "session-not-visible" // that session is not on screen+ | "draft-not-empty" // the user has text or an attachment in the draft+ | "stale-turn" // the session ran a newer turn+ | "replaced" // a newer suggestion took the slot first+ | "unsupported"; // no window, no composer, or no answer in time}>pi.composer.clearSuggestion(input?: { sessionId?: string }): Promise<{ ok: true }>@@ -195,7 +196,7 @@ pi.events.on("session:turnEnded", async (event) => {if (event.reason !== "completed") return;const active = await pi.session.getActive();if (active?.sessionId !== event.sessionId) return;- const text = await writeNextLine(active); // 插件自己的模型请求+ const text = await writeNextLine(active); // the plugin's own model requestif (!text) return;await pi.composer.suggest({sessionId: event.sessionId,@@ -249,11 +250,11 @@ type PluginNotificationPermission = "granted" | "denied" | "unknown" | "unsuppor### 项目(需要 `project.create`)```ts-pi.project.create(input: { path: string }): Promise<{- projectId: number- path: string- name: string-}>+pi.ui.revealView(input?: {+ viewId?: string // one of contributes.views; omittable when there is one+ location?: string // the same opaque subject a view already receives+ sessionId?: string // the session whose panel shows it; defaults to the active one+}): Promise<void>```该方法创建或复用宿主持久项目记录,但不会切换当前工作区。返回的@@ -266,11 +267,11 @@ pi.project.create(input: { path: string }): Promise<{这是替代插件直接读写宿主导航的受支持接口:```ts-pi.ui.revealView(input?: {- viewId?: string // contributes.views 之一;只声明一个视图时可省略- location?: string // 视图已经收到的那个不透明主体- sessionId?: string // 用哪个会话的面板显示;默认当前选中会话-}): Promise<void>+pi.project.create(input: { path: string }): Promise<{+ projectId: number+ path: string+ name: string+}>```和视图本身一样需要 `ui.view`。宿主解析视图并拒绝不能唯一对应一个已声明视图的@@ -294,6 +295,16 @@ pi.workspace.get(): Promise<{} | null>pi.fs.readText(pathFromRoot: string): Promise<string>+pi.fs.stat(pathFromRoot: string, grantId?: string): Promise<{+ size: number;+ mtimeMs: number;+}>+pi.fs.readRange(+ pathFromRoot: string,+ byteOffset: number,+ length: number,+ grantId?: string,+): Promise<{ bytes: Uint8Array; totalSize: number }>pi.fs.readPreview(pathFromRoot: string): Promise<{kind: "text" | "image" | "binary" | "tooLarge"content?: string // UTF-8 when kind is "text"@@ -301,14 +312,16 @@ pi.fs.readPreview(pathFromRoot: string): Promise<{size: number}>pi.fs.openDefault(pathFromRoot: string): Promise<void>+pi.fs.openInBrowser(pathFromRoot: string): Promise<void>pi.fs.reveal(pathFromRoot: string): Promise<void>pi.fs.writeText(pathFromRoot: string, content: string): Promise<void>pi.fs.glob(pattern: string): Promise<string[]>pi.fs.list(pathFromRoot: string): Promise<Array<{name: string;- path: string; // 相对 root,可直接用于 readText / list+ path: string; // root-relative, usable directly with readText / listisDirectory: boolean;- size?: number; // 仅文件+ size?: number; // files only+ mtimeMs?: number; // files only; Unix epoch milliseconds}>>pi.fs.remove(pathFromRoot: string): Promise<void>pi.fs.requestDirectory(): Promise<{ path: string; name: string } | null>@@ -357,24 +370,24 @@ pi.agent.registerTool(tool: {description: stringrisk: "low"|"medium"|"high"schema: unknown+ planSafeActions?: readonly string[]execute: (args: unknown, ctx: ToolExecContext) => Promise<unknown>}): Promise<void>pi.agent.unregisterTool(name: string): Promise<void>```-注册的插件代理工具是仅代理的贡献。在 Plan 期间-主机将它们从模型工具列表中过滤出来并拒绝直接执行-`PLUGIN_DISABLED_IN_PLAN`,包括当明显风险为 `low` 时,用户-具有 `allow-session` 授予,或者会话权限模式为 `auto`。一个-成功的计划批准使相同的注册工具再次符合资格-所选的 Agent 权限策略。+插件工具默认在 Plan/Goal 中隐藏并拒绝。运行时工具注册可通过非空 `planSafeActions`+显式加入,只有 `args.action` 位于该列表时才允许执行。有 schema action enum 时会校验取值。+清单描述符应与运行时注册保持一致,真正执行的工具由运行时注册决定。+`risk: "low"`、会话授权和 `auto` 不能代替该声明。宿主策略与插件执行器都会校验,+执行器对越界 action 返回 `PERMISSION_DENIED`。该列表是作者的只读承诺,不是副作用沙盒(ADR 0211)。```tstype ToolExecContext = {sessionId: stringturnId?: string- /** 本会话执行模型,`providerId/modelId`。这是配置,不是转录。 */+ /** Executor model for this session, `providerId/modelId`. Configuration, not transcript. */modelKey?: stringthinkingLevel?: ThinkingLevelsignal?: AbortSignal@@ -390,11 +403,14 @@ type ToolExecContext = {pi.models.list(): Promise<PluginModelInfo[]>type PluginModelInfo = {- key: string // `${providerId}/${modelId}` — 第一个斜杠切开+ key: string // `${providerId}/${modelId}` — first slash splitsproviderId: stringproviderName: stringmodelId: stringlabel: string+ alias?: string+ availableForSubagents?: boolean+ isDefault?: booleansupportsReasoning: booleanthinkingLevels: ThinkingLevel[]}@@ -412,15 +428,15 @@ provider 调用该回调:```tstype PluginProviderOAuthRequest = {operation: "login" | "refresh"- providerId: string // 插件本地 provider 声明 id- loginId?: string // 仅登录时提供;传给 prompt/notify- credential?: PluginProviderOAuthCredential // 仅刷新时提供;属于该 provider 的凭据+ providerId: string // plugin-local contribution id+ loginId?: string // login only; pass to prompt/notify+ credential?: PluginProviderOAuthCredential // refresh only; this provider's credential}type PluginProviderOAuthCredential = {accessToken: stringrefreshToken?: string- expiresAt?: number // Unix epoch 毫秒+ expiresAt?: number // Unix epoch millisecondsaccountLabel?: stringheaders?: Record<string, string>}@@ -466,6 +482,20 @@ const code = await pi.providers.oauth.prompt(loginId, {### session(需要 `session.read`)```tspi.session.getLlmContext(): Promise<PluginLlmContext>++type PluginLlmMessage = {+ role: "user" | "assistant" | "tool" | "system"+ content: string+ toolName?: string+}++type PluginLlmContext = {+ sessionId: string+ modelKey: string | null+ thinkingLevel?: ThinkingLevel+ messages: PluginLlmMessage[]+ truncated: boolean+}```插件不能传入 session id。身份来自进行中的 `plugins.execute` 会话(D333 / D336)。@@ -483,7 +513,7 @@ pi.session.getActive(): Promise<PluginActiveSession | null>type PluginActiveSession = {sessionId: string- projectPath: string | null // 该会话所属项目的工作目录+ projectPath: string | null // working directory of the session's projectactiveTurn: { turnId: string; startedAt: number } | null}```@@ -510,9 +540,9 @@ type PluginActiveSession = {type PluginAutoTitleContext = {sessionId: stringexpectedTitle: string- userPrompt: string // 第一条用户消息,最多 1,000 个字符- assistantReply?: string // 第一条助手回复,最多 500 个字符- modelKey?: string // 来自会话配置的 providerId/modelId+ userPrompt: string // first user message, at most 1,000 characters+ assistantReply?: string // first assistant reply, at most 500 characters+ modelKey?: string // providerId/modelId from the session configuration}pi.session.getAutoTitleContext(input: {@@ -550,16 +580,16 @@ pi.session.import(input: {source: stringexternalId: stringtitle: string- projectId?: number | null // 来自 pi.project.create;省略即未绑定+ projectId?: number | null // explicit id from pi.project.create; omitted is unboundprojectPath?: string | nullmodelId?: string | nullproviderId?: string | null- createdAt: string // RFC3339+ createdAt: string // strict RFC3339updatedAt: string // >= createdAtmessages: Array<{role: "user" | "assistant" | "tool"content: string- createdAt: string // 会话内单调递增+ createdAt: string // monotonic within the sessionmodelId?: stringproviderId?: stringtoolName?: string@@ -619,12 +649,12 @@ SDK 的破坏性变更。```tspi.usage.listTurns(input?: {- fromMs?: number // 含端点的窗口起点(epoch ms);默认 toMs - 30 天- toMs?: number // 含端点的窗口终点(epoch ms);默认当前时间+ fromMs?: number // inclusive window start, epoch ms; default toMs - 30 days+ toMs?: number // inclusive window end, epoch ms; default nowprojectId?: number | nullsessionId?: string- cursor?: string // 上一次 nextCursor 返回的不透明分页游标- limit?: number // 1..=500 行;默认 200+ cursor?: string // opaque page cursor from the previous nextCursor+ limit?: number // 1..=500 rows; default 200}): Promise<{turns: Array<{turnId: string; sessionId: string; sessionTitle: string | null@@ -656,11 +686,12 @@ pi.usage.listTurns(input?: {type SessionCollaborationOperation =| "session/collaboration/spawn"| "session/collaboration/send"+ | "session/collaboration/list"| "session/collaboration/status"| "session/collaboration/result"| "session/collaboration/cancel"-// 所有调用均使用 pi.desktop.invoke({ operation, args: [input] })。+// All calls use pi.desktop.invoke({ operation, args: [input] }).type SpawnInput = {task: stringtitle?: string@@ -675,6 +706,7 @@ type SendInput = {notifyOnCompletion?: booleanidempotencyKey?: string}+type ListInput = {}type StatusInput = { sessionId: string }type ResultInput = { sessionId: string; messageId?: string; turnId?: string }type CancelInput = { sessionId: string; messageId?: string }@@ -745,6 +777,7 @@ pi.shell.openExternal(url: string): Promise<void>### browser(需要 `browser.cdp`)```ts+pi.browser.reveal(): Promise<void>pi.browser.navigate(input: { url?: string; path?: string }): Promise<BrowserState | null>pi.browser.action(input: { action: "back" | "forward" | "reload" | "stop" }): Promise<void>pi.browser.setBounds(hole: { x: number; y: number; width: number; height: number }): Promise<unknown>@@ -1106,31 +1139,31 @@ window.pluginBridge.on(event, handler)什么也不做。该载荷对主机是不透明的——每个插件自行决定 `location` 的含义——它不需要新权限,也不新增 SDK 方法。-主机拥有的 preload 仅将固定通道转发到插件运行时:+宿主验证来源后把调用转给插件运行时,先处理下表内置通道,再回退到 `onPanelInvoke`:-| 频道 | 所需许可 |+| 通道 | 所需权限 ||---|---|-| `ui.showToast`、`ui.closePanel` | 没有超出加载的面板 |+| `ui.showToast`, `ui.closePanel` | 已加载面板之外无需新增权限 || `ui.notify` | `notify` |-| `ui.getNotificationPermission`、`ui.requestNotificationPermission`、`ui.showNativeNotification` | `notify` |-| `plugin.getSettings`、`workspace.get`、`app.getAppearance` | 无 |-| `app.setTheme`、`themes.upsert`、`themes.remove`、`themes.list` | `ui.theme` |+| `ui.getNotificationPermission`, `ui.requestNotificationPermission`, `ui.showNativeNotification` | `notify` |+| `plugin.getSettings`, `workspace.get`, `app.getAppearance` | 无 |+| `app.setTheme`, `themes.upsert`, `themes.remove`, `themes.list`, `themes.setVariables` | `ui.theme` || `models.list` | `models.list` |-| `fs.readText`、`fs.readPreview`、`fs.openDefault`、`fs.reveal`、`fs.glob`、`fs.list` | `fs.read` |+| `fs.readText`, `fs.stat`, `fs.readRange`, `fs.readPreview`, `fs.openDefault`, `fs.openInBrowser`, `fs.reveal`, `fs.glob`, `fs.list`, `fs.requestDirectory`, `fs.registerDropped` | `fs.read` || `fs.writeText` | `fs.write` |-| `clipboard.readText`、`clipboard.getHistory` | `clipboard.read` |+| `clipboard.readText`, `clipboard.getHistory` | `clipboard.read` || `clipboard.writeText` | `clipboard.write` || `shell.openExternal` | `shell.openExternal` || `net.fetch` | `net.fetch` |+| `net.getCapabilities` | 无 || `session.getActive` | 无 || `ui.revealView` | `ui.view` |`plugin.setSettings`、`fs.remove` 和任意 Electron IPC 未暴露。主机自己没有实现的通道会被转发到插件的 `onPanelInvoke(channel, payload)`,因此插件可以自定义面板 ↔ 主进程通道;没有导出 `onPanelInvoke` 的插件-会从自己的进程收到 `UNSUPPORTED`。主机支持的通道包括-`skill.list`、`skill.read`、`skill.create`、`skill.update`、`skill.remove`-和 `skill.setEnabled`。+会从自己的进程收到 `UNSUPPORTED`。内置技能管理器使用的 `skill.list` / `read` /+`create` / `update` / `remove` / `setEnabled` 是它自己的 `onPanelInvoke` 操作,不是通用宿主桥 API。### 面板事件(主机 -> 面板)@@ -1185,12 +1218,11 @@ window.pluginBridge.on(event, handler)- status / retryAfter(仅 `net.fetch`:已完成调用的上游状态码,以及失败调用所声明的 `Retry-After` —— 绝不记录整个头部集合或响应体)-## 8. 版本控制策略--- API 表面由 `apiVersion` 管理-- MVP `apiVersion = 1`-- 已弃用的 API 至少保留一个主要版本周期+## 8. 版本策略+清单编写契约使用 `schemaVersion: 1`,当前注入 API 没有 `apiVersion` 属性或协商方法。+新增能力优先保持兼容;检测可选方法,通过 `net.getCapabilities` 查询重定向能力,+对旧宿主处理 `UNSUPPORTED`。SDK 类型与实际运行时分发定义可调用接口,文档中的规划名称不会自动成为 API。## 9. 实施情况diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.mdindex 947ed43e4..ddeb6c432 100644--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md@@ -49,9 +49,8 @@## 3. 1 贡献主题CSS-主题贡献 (`ui.theme`) 是插件创作内容的一种情况-在主机渲染器内部运行,因此它会在主进程中穿过消毒剂-在发送到 UI 之前:+主题贡献(`ui.theme`)通过主进程清理器把 CSS 发送到宿主渲染器。+另一个高风险权限 `renderer.extension` 会直接运行受信任的渲染器 JavaScript,不是沙盒:- 只检查浏览器实际生效的 CSS:先按等长空白遮蔽注释体与字符串字面量(每个被遮蔽字符对应一个空格,偏移仍指向原文),`url(...)` 参数按原样保留@@ -59,7 +58,7 @@- 拒绝:`@import`、既非 `data:` URI 也非已声明主题资源的 `url()` 目标、解析器无法解析的 `url(`、`javascript:`、`expression(` 和标记序列(`<style`、`</style`、`<!--`);空样式表也会被拒绝-- 每个文件上限为 256KB,每个插件 8 个主题+- 每个文件上限为 256 KiB,不限制每插件主题数量- 主题可声明 `assets`,使用白名单图片/字体扩展名:插件包内相对路径(在插件根目录内解析,拒绝路径穿越和 `node_modules`)或绝对路径;所有资源总量上限为 4MB。命中的 `url()`会被改写为 `plugin-asset://<pluginId>/<path>`,由宿主处理器提供;该处理器@@ -68,8 +67,8 @@原始路径不会到达渲染器- `contributes.windowAppearance`(`#rrggbb` / `#rrggbbaa`)需要`ui.window.appearance`,且只在该插件的某个主题被选中时生效;离开该主题即恢复- 宿主背景,因为颜色由实时主题目录推导而非记忆。macOS 保持 `vibrancy`,- 永不下发颜色+ 宿主背景,因为颜色由实时主题目录推导。macOS 保持原生圆角,默认透明振动效果忽略颜色;+ 关闭 Translucent window 后会把颜色应用到不透明窗口- CSS 在加载时从磁盘读取并通过 IPC 整体交付;的渲染器将其注入到附加在后面的单个专用 `<style>` 元素中应用程序自己的样式表,因此它可以覆盖令牌但从不注入标记。@@ -209,16 +208,11 @@ CSS 无法脚本化,但它可能会产生误导:主题仍然是第三方代自我声明的风险水平。服务器的目录被完整注册——数量只受 §8.1 中的协议护栏约束——而每个插件最多接入 8 个服务器。-Plan 是代理工具的附加主机策略边界:--- Plan 中没有可见或可执行的插件工具;-- 拒绝先于明显风险、declared/granted 权限、会话- grants,以及 `auto` 权限模式;-- 直接伪造的 `tools.execute` 调用返回 `PLUGIN_DISABLED_IN_PLAN` 并且是- 已审核;它不会转发到插件运行时;-- 插件命令和面板仍可用作显式用户 UI 操作,- 但它们不能成为模型可调用的 Plan 工具或默默地改变 Plan- 状态。+插件工具默认在 Plan/Goal 中隐藏并拒绝。运行时工具注册可通过非空 `planSafeActions`+显式加入,只有 `args.action` 位于该列表时才允许执行。有 schema action enum 时会校验取值。+清单描述符应与运行时注册保持一致,真正执行的工具由运行时注册决定。+`risk: "low"`、会话授权和 `auto` 不能代替该声明。宿主策略与插件执行器都会校验,+执行器对越界 action 返回 `PERMISSION_DENIED`。该列表是作者的只读承诺,不是副作用沙盒(ADR 0211)。## 8. 网络和外部链接@@ -370,7 +364,7 @@ PI-Desktop 自己当前占用(默认是 `Alt+Space` 与 `Alt+Shift+W`;用户9. 声明绝对路径 `command` 的 MCP 服务器会在 manifest 校验时失败;非回环的明文 HTTP URL 只有在主机声明于 `manifest.net.domains` 且 UI 显示未加密连接警告时才可接受-10. 低风险或授予的插件工具在 Plan 中仍然无法关闭+10. 未声明 Plan 安全操作或 action 越界的插件工具,无论风险或授权如何,都在 Plan/Goal 中拒绝## 11. 实施情况@@ -422,7 +416,7 @@ PI-Desktop 自己当前占用(默认是 `Alt+Space` 与 `Alt+Shift+W`;用户- 声明的清单权限在加载时自动授予- `userSelected` root 不跨重启保留,插件每个会话都得重新问一次-### Fetch redirect policy (unreleased)+### Fetch redirect policyThe host owns the same redirect loop for default and injected single-hoptransports. `error` refuses every 3xx with REDIRECT_DISALLOWED; `manual` returnsdiff --git a/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md b/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.mdindex 472326ac5..30dba9d27 100644--- a/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md@@ -44,7 +44,7 @@ discovered## 3. 生命周期挂钩-**今天实现:**运行时(`apps/desktop/electron/main/plugin-runtime.ts`)调用`onLoad`(当在load/enable上加载插件时)和`onUnload`(在unload/disable/reload/应用退出上调度到插件进程,预算5s——退出时为1.5s,然后进程停止);卸载会删除插件注册的命令和工具。下面的其他挂钩在 API 中声明但尚未触发。+**今天实现:**运行时(`apps/desktop/electron/main/plugin-runtime.ts`)调用`onLoad`(当在load/enable上加载插件时)和`onUnload`(在unload/disable/reload/应用退出上调度到插件进程,预算5s——退出时为1.5s,然后进程停止);卸载会删除插件注册的命令和工具。下面的其他生命周期名称是提案,不是当前 `PluginModule` 的成员。**计划:**一旦完整生命周期落地,钩子将按以下顺序触发:@@ -57,7 +57,7 @@ discovered7.`onUninstall`### 调用约束-- Hooks 必须能够超时(默认 5 秒,可配置)+- 模块求值加 `onLoad` 共 15 秒;`onUnload` 为 5 秒,退出时为 1.5 秒。预算由宿主持有,不能通过清单修改- 钩子异常不得使主机崩溃- 如果`onLoad`失败,请输入`load_error`并自动回滚已注册的贡献点@@ -126,7 +126,7 @@ discovered- 关闭面板- 停止常驻服务并断开 MCP 服务器的连接- 取消任何挂起的重启退避-- 致电 `onUnload` / `onDisable`+- 调用 `onUnload`,不会调用 `onDisable`- 继续作为残疾人## 5. 启动恢复@@ -204,10 +204,10 @@ rollback all registrations from this plugin卸载前:1.禁用+卸载-2. 调用`onUninstall`+2. 当前运行时不会调用 `onUninstall`3.删除已安装的文件-4.清理插件私有数据(可能会询问用户是否保留)+4. 默认清理插件私有数据,当前没有保留数据选项默认推荐:- 卸载时清理 settings/data(D016:卸载默认删除插件数据)-- 提供“保留数据”高级选项(可以推迟)+- 保留数据是未来提案;开发源码不删除,内置插件只能禁用,不能卸载diff --git a/docs/zh-CN/spec/07-plugins/06-plugin-packaging.md b/docs/zh-CN/spec/07-plugins/06-plugin-packaging.mdindex 57d1811f9..93755cdda 100644--- a/docs/zh-CN/spec/07-plugins/06-plugin-packaging.md+++ b/docs/zh-CN/spec/07-plugins/06-plugin-packaging.md@@ -1,123 +1,80 @@# 06. 插件打包-> **翻译说明:** 本页是与 [英文源规格](/spec/07-plugins/06-plugin-packaging) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。+> **翻译说明:** 本页对应 [英文源规格](/spec/07-plugins/06-plugin-packaging),代码与字段保持原文。+## 1. 格式与所有权-## 1. 目标+开发加载直接引用根目录有 `manifest.json` 的本地文件夹,不复制源码。+安装目录和市场包由 Rust host-core 管理,桌面运行时在清单与授权审核后才加载入口。-定义插件的打包、分发和安装方式,确保跨机器的可重复性。+`.piplug` 是 **store-only ZIP(压缩方法 0)**。安装器也读取这种 `.zip`,+但拒绝通用 ZIP 工具默认生成的 deflate 条目。使用 `pi-plugin pack` 或 Agent 的 `PluginPack`。-## 2. 包格式+## 2. 包内容-### 2. 1 目录包(development/local)-包含 `manifest.json` 的普通目录。+devkit 把清单写在包根目录。包含可执行 JavaScript、HTML/CSS、技能、渲染器模块与引用资源。+安装器能发现根目录或下一层目录的清单,但推荐使用 devkit 的根目录格式。-### 2. 2 分发包(推荐)-扩展名:`.piplug`(本质上是一个 zip)+普通包不会自动安装依赖或编译 TypeScript,应自行打包依赖;`node_modules` 不进入包。+Agent 扩展有独立 TypeScript 加载器,显式导入 pi 扩展另有受限的 registry-only npm 准备流程,+详见 [16-trusted-extensions.md](16-trusted-extensions.md),两者都不代表普通安装会运行任意安装脚本。-```text-demo.hello-0.1.0.piplug-└─ (zip)- ├─ manifest.json- ├─ main.js- ├─ renderer/...- ├─ skills/...- ├─ themes/...- └─ checksums.json # optional, in-package manifest-```--> 在实施过程中,可能首先支持 `.zip`,但在产品级别,所有内容都被标识为 `.piplug`。--## 3. 包内限制--1.根必须包含`manifest.json`-2. 不允许使用绝对路径符号链接-3. 不允许路径遍历(`../`)-4、单个包解压后默认最大大小(建议50MB,可配置)-5.最大文件数(建议2000,可配置)+## 3. 上限与排除项-## 4. checksums.json (可选但推荐)+| 表面 | 当前规则 |+|---|---|+| 包内容 | 最多 2,000 文件、50 MiB;市场下载字节另有同类上限 |+| 路径 | 拒绝穿越和符号链接;引用入口必须在插件目录内,主题资源的独立声明机制除外 |+| devkit 遍历跳过 | `.git`、`node_modules` 目录 |+| devkit 打包还排除 | 根 `dist/`、`.env`、`.env.*`、`.npmrc`、`*.pem`、`*.key` |+| 凭证排除 | 警告列出跳过路径,不能代替秘密扫描 |+| 归档编码 | store-only 条目,按确定的 code-unit 顺序生成并打印 SHA-256 |-```json-{- "algorithm": "sha256",- "files": {- "manifest.json": "hex...",- "main.js": "hex..."- }-}-```--主机可以在安装时验证。+`check` 检查编写与包约束,区分阻断错误和建议警告,`pack` 拒绝错误。+通过检查不代表入口可执行、已获授权、兼容所有宿主或通过中心审核,发布前仍需安装实际包验证。-## 5. 安装流程--```text-select package/dir- → verify archive safety- → extract to temp- → validate manifest + files- → permission review UX- → move to installed/<id>- → registry write- → optional auto enable-```+## 4. 完整性-失败时,清理 temp 并不要留下半安装的目录。+市场安装必须校验目录或 resolve 提供的 SHA-256,有声明大小时也核对大小。+不匹配返回 `PLUGIN_INTEGRITY` 并停止安装。本地目录没有下载摘要。+`checksums.json` 不是当前安装器校验的逐文件协议,随包携带它不会增加信任门。+签名尚在规划中,发布者徽章是目录元数据。-## 6. 版本控制和覆盖+## 5. 安装与升级-- 安装具有相同 ID 的新版本:升级-- 升级前将旧版本备份到`cache/backup/<id>/<version>`-- 升级失败回滚(P2)+宿主在 `plugins/cache/download` 暂存输入,检查归档与清单引用,计算权限差异,+写入 `plugins/installed/<id>`,保存 registry,并按授权和选项启用。市场下载复用该安装器。-语义:-- `install`:id不存在-- `upgrade`:id 存在并且版本较新-- `reinstall`:强制重新安装相同版本+已有 id 的版本不同即报告升级,本地安装不要求一定更新;市场版本选择另行比较。+替换前将原代码备份到 `plugins/cache/backup/<id>/<version>`。+备份不等于保证每种后续 I/O 或加载失败都能事务回滚,不能宣传为无条件自动回滚。-## 7. 卸载和清理+升级保留 id 与私有数据,新增权限需审核,自动更新不能静默扩权。+更新策略见 [08-plugin-signing-updates.md](08-plugin-signing-updates.md)。-删除:-- `plugins/installed/<id>`-- 注册表项+## 6. 卸载-可选择删除:-- `plugins/data/<id>`-- 插件日志+运行时先停止插件并撤销贡献。host-core 默认删除 registry 行、受管代码、私有数据和旧式插件日志文件。+开发源码目录保留。内置插件即使被市场版本更新也不能卸载,应使用禁用。+当前没有保留数据开关,也没有卸载生命周期回调。-## 8. 开发包+## 7. CLI 与发布交接-开发加载不经过`.piplug`打包;相反:+完成仓库常规配置后,从 PI-Desktop 仓库根目录运行:-```text-Load Development Plugin → choose directory → validate → register(source=dev)+```bash+pnpm pi-plugin check ../my-plugin+pnpm pi-plugin pack ../my-plugin+pnpm pi-plugin publish ../my-plugin --channel stable```-## 9. 构建建议(开发人员)--最低规格:--- 来源可以是 TypeScript-- 分发前编译为可直接加载的 js/html/css-- 不要依赖主机为普通 `.piplug` 或开发插件当场运行 `npm install`(MVP 不会在安装时拉取依赖项)。明确的“插件 → 导入 pi 扩展”流程是文档规定的例外;其有界 npm 行为见 `16-trusted-extensions.md` §3.2。--如果插件需要第三方库:-- 自己将它们捆绑到插件目录中--## 10. 验收--1.可以从目录安装-2. 可以从 `.piplug` / `.zip` 安装(实施期间的每个里程碑)-3. 坏包无法安装且不留任何残留-4.升级后id不变,新版本生效---## 11. 实施情况+`publish` 仅生成本地 `.piplug` 与 `.submission.json`,不会上传,记录仓库/ref/commit/path 与制品摘要/大小。+需要带 `origin` 的 Git 仓库,拒绝带凭证的 remote;有改动时拒绝,除非显式 `--allow-dirty`。+打包先于干净工作区检查,应先忽略 `dist/`。推荐 HEAD 上有 tag;`--ref` 不会改变记录的 HEAD commit,+也不能让脏工作区变得可复现。中心独立解析并核验来源。-在 host-core + 桌面 shell 中实现:+## 8. 实现依据-1.通过`plugins.installFromPath`目录安装-2. `.piplug` / 通过 `plugins.installFromPackage` 存储压缩的 zip 安装-3. 市场下载安装重复使用相同的软件包安装程序-4. 在提交 `plugins/installed/<id>` 之前强制执行遍历/符号链接/大小/文件计数保护+- `packages/plugin-devkit/src/{check,walk,pack,publish,cli}.ts` 及测试+- `crates/host-core/src/plugins/{install,manifest,validation,registry}.rs`+- [发布流程](../../plugin-development.md#9-check-pack-and-install)diff --git a/docs/zh-CN/spec/07-plugins/08-plugin-signing-updates.md b/docs/zh-CN/spec/07-plugins/08-plugin-signing-updates.mdindex cd2d971f9..3b62ad892 100644--- a/docs/zh-CN/spec/07-plugins/08-plugin-signing-updates.md+++ b/docs/zh-CN/spec/07-plugins/08-plugin-signing-updates.md@@ -61,6 +61,9 @@ type PluginSignature = {验证失败将拒绝安装/更新。+第 4–5 节的签名与公钥管理属于规划。当前客户端校验包 SHA-256,读取目录的 trust/provenance,+没有签名 CLI、签名校验门、内置签名公钥或用户可信公钥库;认证徽章不是密码学签名。+## 5. 发布者信任```ts@@ -154,11 +157,11 @@ P2目标:```tstype PluginProvenance = {- sourceRepository: string // 规范化的 https 仓库 URL- sourceRef: string // refs/tags/<tag> 或 40 位 commit- sourceCommit: string // 解析后的 40 位 commit- sourcePath?: string // 插件在仓库中的目录- builder?: string // 构建器标识与版本+ sourceRepository: string // canonical https repository URL+ sourceRef: string // refs/tags/<tag> or a 40-hex commit+ sourceCommit: string // resolved 40-hex commit+ sourcePath?: string // plugin directory inside the repository+ builder?: string // builder identity and versionbuiltAt?: string}```diff --git a/docs/zh-CN/spec/07-plugins/09-plugin-command-palette.md b/docs/zh-CN/spec/07-plugins/09-plugin-command-palette.mdindex 7dc99bf91..9dc09f8b2 100644--- a/docs/zh-CN/spec/07-plugins/09-plugin-command-palette.md+++ b/docs/zh-CN/spec/07-plugins/09-plugin-command-palette.md@@ -23,16 +23,14 @@## 3. 命令模型```ts-type PaletteCommand = {- id: string // e.g. builtin.session.new / plugin.demo.hello.open+type CommandItem = {+ id: stringtitle: string- keywords: string[]category?: string- source: "builtin" | "plugin"+ keywords?: string[]+ source: "builtin" | "plugin" | "extension"pluginId?: string- icon?: string- enabled: boolean- risk?: "low" | "medium" | "high"+ extensionId?: string}```@@ -42,19 +40,16 @@ type PaletteCommand = {- 新建任务- 压缩对话上下文- 切换到 Agent / Plan / Goal-2. 插件 `contributes.commands`-3.后期:技能快捷键/市场搜索入口+2. 已加载的 `pi.commands.register` 运行时命令,按项目激活范围过滤+3. 受信任 Agent 扩展命令(`source: "extension"`)++Composer `/` 目录独立,还包含技能和 MCP 条目,不是所有条目都进入全局命令搜索。## 5. 搜索规则-- 按标题/关键字/类别/插件名称匹配-- 支持前缀和子串匹配-- 支持中文关键词-- 结果排序:- 1.最近使用过- 2. 精确前缀- 3.内置优先级或用户权重(可配置)- 4. 按字母顺序+当前 `commandPaletteSearch` 将查询转为小写,在标题、分类、合并关键词中做子串匹配,+中文作为文本参与匹配,空查询返回符合条件的列表。顺序为内置命令、已加载且符合项目范围的+插件命令、受信任扩展命令。不提供命令专属的最近使用排序、前缀评分、可配置权重或插件名字段搜索。## 6. 执行流程@@ -117,4 +112,4 @@ Enter to run · Esc to close2.内置和插件命令可搜索3.执行插件命令成功4. 插件禁用后命令消失-5.最近使用的订单生效+5. 子串匹配与内置/插件/扩展顺序符合 `market-ipc.ts`diff --git a/docs/zh-CN/spec/07-plugins/10-plugin-devex.md b/docs/zh-CN/spec/07-plugins/10-plugin-devex.mdindex d16d95732..ac6f9753b 100644--- a/docs/zh-CN/spec/07-plugins/10-plugin-devex.md+++ b/docs/zh-CN/spec/07-plugins/10-plugin-devex.md@@ -52,13 +52,10 @@ Create from template (the folder opens as the project)## 4. SDK 和 devkit-`@pi-desktop/plugin-sdk` 由插件代码本身导入并保留-无依赖且无节点。它提供:-- 清单类型-- 权限枚举-- API 类型 (`PiPluginHostApi`)-- 清单验证功能-- 测试助手(模拟主机)+`@pi-desktop/plugin-sdk` 是私有工作区包,不是插件必须安装的运行时。它依赖 `typebox`,+不使用 Node 宿主 API,提供 `PluginManifest`、`PluginHostApi`、`PluginModule`、渲染器类型、+权限常量和纯校验器,没有导出 mock-host 工厂。宿主注入 `pi`,仅为访问它无需打包 SDK;+测试时可在真实外部边界提供自己的 fake。SDK 的剪贴板接口包含 `pi.clipboard.getHistory()`,通过现有的 `clipboard.read` 权限返回有界、按最新优先排列的文本和图片条目。主机只记录明确的写入和 Composer 粘贴事件,@@ -66,7 +63,7 @@ SDK 的剪贴板接口包含 `pi.clipboard.getHistory()`,通过现有的 `clip第二份存储。`@pi-desktop/plugin-devkit` 是工具,而不是运行时,并且可以使用 Node。它拥有-`scaffold` / `check` / `pack` 和 `pi-plugin` CLI。三位开发商+`scaffold` / `check` / `pack` / `publish` 和 `pi-plugin` CLI。三位开发商表面(CLI、代理工具、插件页面)调用它,因此一旦成立就会强制执行规则无处不在。@@ -85,15 +82,15 @@ pnpm --filter @pi-desktop/plugin-devkit... buildpnpm pi-plugin init full-demo /tmp/my-plugin# validate manifest and package contents-pnpm pi-plugin check .+pnpm pi-plugin check /tmp/my-plugin# pack-pnpm pi-plugin pack .+pnpm pi-plugin pack /tmp/my-plugin# outputs dist/demo.hello-0.1.0.piplug# pack and pin the version to the commit that produced it-pnpm pi-plugin publish .+pnpm pi-plugin publish /tmp/my-plugin# also writes dist/demo.hello-0.1.0.submission.json```@@ -104,8 +101,8 @@ pnpm pi-plugin publish .没有 tag 时给出警告。插件中心会自行重新解析这些值;一次提交只是一个待核验的声明。见 [15-plugin-center.md](15-plugin-center.md)。-`check` 重现安装程序强制执行的每条规则,因此 `check` 传递意味着-安装会通过。它报告错误 - 丢失或无法解析的 `manifest.json`,+`check` 执行编写和包安全检查,通过不代表加载、宿主版本兼容、授权、Provider 或中心审核一定成功。+Rust 安装器与运行时仍是独立校验层。它报告错误 - 丢失或无法解析的 `manifest.json`,缺少 `main` / `ui.panel` / `manifest.renderer` / 技能文件,转义插件的技能路径目录,未知权限,符号链接,超过 2000 个文件,超过50 MB — 以及警告,不会阻止:高风险权限([13-plugin-permissions-matrix.md](13-plugin-permissions-matrix.md)diff --git a/docs/zh-CN/spec/07-plugins/11-plugin-storage-isolation.md b/docs/zh-CN/spec/07-plugins/11-plugin-storage-isolation.mdindex 13e741dd3..e47760831 100644--- a/docs/zh-CN/spec/07-plugins/11-plugin-storage-isolation.md+++ b/docs/zh-CN/spec/07-plugins/11-plugin-storage-isolation.md@@ -1,129 +1,72 @@# 11. 插件存储隔离-> **翻译说明:** 本页是与 [英文源规格](/spec/07-plugins/11-plugin-storage-isolation) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。+> **翻译说明:** 本页对应 [英文源规格](/spec/07-plugins/11-plugin-storage-isolation),代码与字段保持原文。+## 1. 所有权与目录-## 1. 目标--将插件数据与主机核心数据隔离,避免交叉污染和未经授权的读取。--## 2. 目录布局+Rust host-core 持有 registry、受管安装目录和所有 SQLite 访问;Electron Main 插件代理持有+插件设置文件与运行时记录。插件使用公开 API,不能获取宿主数据库句柄。+数据根目录属于相应宿主实例,不能硬编码 `~/.pi-desktop` 或重新读取全局覆盖变量寻找其他实例目录。+开发代码保留在加载的源码目录。```text-~/.pi-desktop/- ├── pi.sqlite # host DB (03-runtime/04); plugins never open it- ├── plugins/- │ ├── installed/<plugin-id>/- │ ├── disabled/ # optional- │ ├── data/<plugin-id>/- │ ├── logs/<plugin-id>.log- │ ├── cache/download/- │ └── registry.json- └── ...-```--Bundled marketplace fallback packages use the owning plugin manager's data-root (`plugins/market/packages`), just like its catalog and download cache.-Catalog construction never re-reads the process-wide `PI_DESKTOP_DATA_DIR`;-independent host instances must not share package paths through that mutable-default. Package size and checksum validation remain mandatory.--## 3. registry.json(逻辑模型)--```ts-type PluginRegistry = {- schemaVersion: 1- plugins: Array<{- id: string- version: string- enabled: boolean- source: "installed" | "dev" | "marketplace"- path: string- installedAt: string- updatedAt: string- permissionsGranted: string[]- marketplace?: {- providerId: string- shasum?: string- publisherId?: string- }- }>-}+<dataRoot>/plugins/+├── registry.json+├── installed/<plugin-id>/+├── data/<plugin-id>/+│ └── settings.json+├── logs/ # legacy per-plugin log location+├── cache/download/+├── cache/backup/<plugin-id>/<version>/+└── market/+ ├── catalog.json+ └── packages/```-## 4. 插件私有数据--`pi.plugin.getDataPath()` 指向:--```text-~/.pi-desktop/plugins/data/<plugin-id>/-```+## 2. Registry-用途:-- 缓存-- 本地索引-- 大型插件配置文件--禁止:-- 使用这个API来获取另一个pluginId的路径--## 5. 设置存储--插件设置可以存储在:--- 插件命名空间下主机数据库的 `kv` 表 (03-runtime/04 §4.1)-- 或者插件数据目录下的settings.json--建议在主机中集中存储,以便于备份和卸载清理。--```ts-// kv: ns = `plugin:<plugin-id>`, key, value_json, updated_at-// uninstall cleanup = DELETE FROM kv WHERE ns = 'plugin:<plugin-id>'-```+`plugins/registry.json` 记录安装/开发/市场条目、启用状态、激活范围、授权、路径、版本、更新偏好与来源。+该文件由宿主读写,不是插件 API,插件不应直接修改。它用于重启恢复;运行时加载和服务状态只是投影。-## 6. 日志隔离+## 3. 私有设置与文件-每个插件都有自己的日志通道:-- 文件:`plugins/logs/<plugin-id>.log`-- UI:可通过插件过滤+`pi.plugin.getDataPath()` 仅返回调用插件的私有目录。`getSettings()` 合并清单默认值与+`settings.json`,`setSettings(partial)` 合并补丁,当前实现不把这些设置存入 SQLite `kv`。+主题变量使用宿主管理的保留设置命名空间,应通过 `pi.themes.setVariables` 更新,不能自行覆盖。-主机核心日志不会写入插件文件。+设置是普通 JSON,不是机密存储,生成字段拒绝 `secret: true`。API key 留在宿主密钥库;+独立的 `provider.oauth` 回调只能取得自己的 OAuth 凭证,没有通用插件机密读写 API。-## 7. 会话和秘密隔离+## 4. 文件与进程信任-插件无法直接访问:-- pi.sqlite(会话、设置、任何主机表)-- 秘密-- 提供商密钥-- 其他插件的私有注册表数据+`pi.fs.*` 操作已声明的工作区或用户选择范围,不是通用私有数据文件 API。+根目录来自工具调用会话或相应视图/工作区;代理拒绝宿主保留目录、受保护凭证和越界符号链接。-如果将来提供“受控会话摘要 API”,则它必须:-- 拥有单独的许可-- 默认禁用-- 可审计+这些是**宿主代理 API** 保证。插件 Node 入口仍能以用户 OS 权限访问原始文件和网络 API,+私有目录是命名空间,不是操作系统沙盒。受信任的 `renderer.extension` 也共享宿主文档。+隔离面板/视图没有 Node 集成,preload 不开放宿主数据库。-## 8. 卸载清理策略+## 5. 会话、用量、协作-默认值:-- 删除已安装的代码-- 删除数据-- 删除日志(或保留最新的日志)+`session.read` 只返回工具调用会话的有界模型上下文;`session.read.own` / `update.own` /+`delete.own` 仅操作自己导入的会话。`session.autoTitle` 提供首轮摘要与比较更新,`usage.read`+只有已完成轮次事实而无正文。这些独立权限都不是数据库通行证。-高级:-- 保留数据+`desktop.control` 协作网关注入来源调用身份,持久账本留在 host-core。私有 JSON 不能充当授权、+宿主会话 id 或账本。网关不暴露 SQLite、任意 Electron IPC 或 MCP bearer token。-## 9. 备份建议+## 6. 日志与清理-未来的 export/backup 可以分为:-- 仅主机配置-- 主机配置+插件列表-- 完整(包括插件数据)+在 Settings → Info → Logs 按插件 id 筛选。运行时写入分类应用日志,不承诺每插件一个实时+`plugins/logs/<id>.log`。不要记录凭证或正文。-MVP 未实现完整备份协议;它只保留目录边界。+卸载默认删除 registry 行、受管代码、私有数据与旧式插件日志,保留开发源码,拒绝内置 id。+没有保留数据选项。禁用和重载撤销运行时资源,但保留设置与私有文件。-## 10. 验收+## 7. 实现与验收依据-1.插件只能写入自己的数据目录-2.卸载后按照策略清理数据-3.注册表可以恢复已安装列表-4.可以单独查看插件日志+- `crates/host-core/src/plugins/registry.rs`:路径、登记与卸载+- `apps/desktop/electron/main/plugin-runtime.ts`:设置、私有路径、范围+- `apps/desktop/electron/main/plugin-session-scope.ts`:调用所有权+- 通过现有测试验证重启恢复、默认值与补丁、跨插件拒绝、路径范围、拒绝列表和卸载清理。+- 备份与可移植配置另有宿主契约,该布局不保证导出任意插件私有文件。diff --git a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.mdindex 4141cc02d..97e400e38 100644--- a/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md+++ b/docs/zh-CN/spec/07-plugins/12-plugin-ipc-and-host-services.md@@ -106,7 +106,7 @@ PluginManager### 查询- 命令面板仅查询已启用+加载成功的贡献-- Agent 查看已注册的工具;无论风险如何,Plan 均不会收到任何插件工具+- Agent 可使用已注册工具;Plan/Goal 仅暴露运行时 `planSafeActions` 非空的工具,执行前再次校验 `args.action`或授予状态### 注销@@ -212,10 +212,9 @@ toast 加上 `pluginChanged` 到渲染器。`{ executionId, sessionId, toolCallId, toolName, args, turnId }`。`turnId` 是运行时回合身份,原样转发,以便插件工具上下文能与`session:turnEnded` 事件对应。-3. Plan 调用在主机策略步骤失败并显示 `PLUGIN_DISABLED_IN_PLAN`;他们- 永远不会达到 Electron 或插件运行时。 Agent 呼叫继续- Electron主要执行注册的插件工具JS并通过RPC应答- `plugins.resolveExecution` `{ executionId, ok, content, errorCode? }`。+3. Plan/Goal 未声明 `planSafeActions` 时在宿主策略门拒绝;已允许的调用携带模式和操作列表,+ 桌面插件执行器在进入插件代码前拒绝缺失或未列出的 `args.action`。Agent 使用正常权限流程。+ Electron 通过 `plugins.resolveExecution` `{ executionId, ok, content, errorCode? }` 返回。4. host-core 解析待执行并返回一个标准`ToolsExecuteResult` 到 sidecar。调度最多等待 150 秒(`DESKTOP_TOOL_DISPATCH_TIMEOUT_MS`,高于 110 秒的插件工具预算,也高于最宽的diff --git a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.mdindex 73e7fd57a..d9860049d 100644--- a/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md+++ b/docs/zh-CN/spec/07-plugins/13-plugin-permissions-matrix.md@@ -14,7 +14,7 @@| `ui.panel` | 低 | 打开插件面板 | 安装时授予 | 几乎所有 UI 插件都需要 || `ui.view` | 低 | `contributes.views` 在工作面板中列出并可打开 | 安装时授予 | 与面板窗口同级隔离:沙箱页面、按插件划分的会话分区、`net.domains` 出口限制。按激活范围过滤 || `ui.theme` | 低 | `contributes.themes` CSS 已在“设置”中加载并提供 | 安装时授予 | CSS 由主机清理;它无法编写脚本。已声明的 `assets` 通过主机的只读 `plugin-asset:` 协议提供 |-| `ui.settings` | 低 | `contributes.settingsDestinations` 在“扩展”中添加沙盒设置项 | 安装时授予 | 仅在宿主“扩展”分组中呈现;使用与面板视图相同沙箱的隔离视图宿主(ADR 0261) |+| `ui.settings` | 低 | `contributes.scenicThemes` 在“扩展”中添加沙盒设置项 | 安装时授予 | 仅在宿主“扩展”分组中呈现;使用与面板视图相同沙箱的隔离视图宿主(ADR 0261) || `ui.window.appearance` | 低 | 该插件主题被选中时,用 `contributes.windowAppearance` 设置原生窗口背景 | 安装时授予 | 仅接受 `#rrggbb` / `#rrggbbaa`;按解析后的明暗生效,主题消失后回到宿主默认值。macOS 保持 vibrancy || `clipboard.read` | 中等 | `clipboard.readText`、`clipboard.getHistory` | 首次使用时确认 | 可能会读取敏感信息和保留的剪贴板历史 || `clipboard.write` | 中等 | `clipboard.writeText` | 首次使用时确认 | 防止剪贴板污染 |@@ -114,13 +114,13 @@ manifest 里的字段负责回答「能做到多远」。两个字段都由主`session:turnEnded` 和 `plugin:settingsChanged` 走既有的插件事件通道,订阅未知的事件名也不会报错-## 3A。 Plan 操作状态规则+## 3A. Plan 操作状态规则-每个 `agentTools` 贡献都会在 Plan 中被拒绝,无论此矩阵的值如何-风险或违约政策。 `agent.tool.register` 授权注册-Agent,在 Plan 中不可见。主机返回 `PLUGIN_DISABLED_IN_PLAN`-直接 Plan 调用并记录拒绝。仅插件工具符合资格-在同一个 Agent 被批准进入 Agent 模式后。+插件工具默认在 Plan/Goal 中隐藏并拒绝。运行时工具注册可通过非空 `planSafeActions`+显式加入,只有 `args.action` 位于该列表时才允许执行。有 schema action enum 时会校验取值。+清单描述符应与运行时注册保持一致,真正执行的工具由运行时注册决定。+`risk: "low"`、会话授权和 `auto` 不能代替该声明。宿主策略与插件执行器都会校验,+执行器对越界 action 返回 `PERMISSION_DENIED`。该列表是作者的只读承诺,不是副作用沙盒(ADR 0211)。## 4. 权限显示副本@@ -187,9 +187,9 @@ assertPermission(pluginId, perm) {```tsassertFsAccess(pluginId, mode, requestedPath, sessionId) {- assertPermission(pluginId, `fs.${mode}`) // 已声明且已授予+ assertPermission(pluginId, `fs.${mode}`) // declared AND grantedfull = realpathWithinRoot(root(pluginId, mode, sessionId), requestedPath)- if (!full) throw NOT_FOUND | INVALID_ARGUMENT // 先解析软链+ if (!full) throw NOT_FOUND | INVALID_ARGUMENT // symlinks resolved firstif (isDenied(full) || isHostReserved(full)) throw ERROR_PERMISSION_DENIEDif (!inScope(full, declaredScope(pluginId, mode))) await confirmWithUser(...)}diff --git a/docs/zh-CN/spec/07-plugins/14-plugin-roadmap.md b/docs/zh-CN/spec/07-plugins/14-plugin-roadmap.mdindex ec57d65f0..f695a037d 100644--- a/docs/zh-CN/spec/07-plugins/14-plugin-roadmap.md+++ b/docs/zh-CN/spec/07-plugins/14-plugin-roadmap.md@@ -26,8 +26,8 @@ Local plugins usable → developer-friendly → marketplace distribution → sig通过 `Skill` 工具按需加载主体 ✅ (ADR 0039, D174)- 统一命名空间和审计 ✅- 每个插件设置 API 和生成式设置 UI 已实现。UI 支持字符串、数字、布尔、枚举、JSON- 字段与插件域命令快捷键;操作系统全局插件快捷键暂不在范围内。- 已实施+ 字段与插件域命令快捷键。系统级绑定已通过 `keyboard.globalShortcut`、+ `contributes.globalShortcuts` 与 `pi.keyboard` 独立实现。- 插件日志面板仍在计划中;运行时审计日志的存在没有专用的插件日志表面@@ -62,6 +62,18 @@ Local plugins usable → developer-friendly → marketplace distribution → sig- 企业私人资源(仍在计划中)- 市场评论/质量评分(可选,仍在计划中)+### 当前新增能力++- 渲染器插槽与审定的草稿/附件分发(`renderer.extension`)+- 清单 Provider、Add Service 分类、宿主 OAuth 登录+- 带撤销的输入框转换与可忽略的输入框建议+- 插件会话导入、读取、重命名、删除及比较更新的自动标题+- 已完成轮次用量、模型目录、宿主持有的单次补全+- 当前会话快照与工作面板视图展示+- 运行时主题、类型化变量与数据型主题设置卡片+- 有界 WebSocket 与宿主系统快捷键+- 后台音频仍返回 `UNSUPPORTED`,尚无设备后端+### R7 — Agent 扩展(v1.1 ✅,D387 / D388)- v1:Agent sidecar 中的 ExtensionAPI 适配层;工具、命令、生命周期与 provider hooks、基础 UI 提示diff --git a/docs/zh-CN/spec/07-plugins/15-plugin-center.md b/docs/zh-CN/spec/07-plugins/15-plugin-center.mdindex bd45e0ade..55ada4be0 100644--- a/docs/zh-CN/spec/07-plugins/15-plugin-center.md+++ b/docs/zh-CN/spec/07-plugins/15-plugin-center.md@@ -3,13 +3,18 @@> **翻译说明:** 本页是与 [英文源规格](/spec/07-plugins/15-plugin-center) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。> 管理仓库:[vastsa/pi-plugin-center](https://github.com/vastsa/pi-plugin-center)-> 分发仓库:[vastsa/pi-desktop-plugins](https://github.com/vastsa/pi-desktop-plugins)+> 分发仓库:[AIUO-Net/pi-desktop-plugins](https://github.com/AIUO-Net/pi-desktop-plugins)> 决策记录:[ADR 0102](../../../adr/0102-publisher-owned-plugin-source-and-git-hosted-artifacts.md)> 客户端契约:[07-plugin-marketplace.md](07-plugin-marketplace.md)本文定义取代单仓库市场的分发系统,是插件中心服务的规范性方案;桌面客户端消费什么,仍以市场规范为准。+实现范围:本仓库包含桌面客户端与 `packages/plugin-devkit/src/publish.ts`,后者只准备本地包和提交文件,+不会上传。下文中心 API、worker、身份和签名描述独立服务的设计,不代表 SDK 方法或服务器运行证明。+当前客户端默认读取 `https://plugins.aiuo.net/catalog.json`,并使用已记录的 `/api/v1` resolve/review 路由。+源码见 `crates/host-core/src/plugins/marketplace`, `reviews.rs`, and `resolve.rs`。+## 1. 定位插件中心是插件分发的发布侧。它回答三个客户端自己无法回答的问题:@@ -28,8 +33,8 @@| 插件源码 | 发布者 | 发布者自己的 GitHub 仓库 || 构建输入(commit、tree、path) | 插件中心(固定副本) | 中心数据库 + 快照存储 || registry 与审查证据 | 插件中心 | `vastsa/pi-plugin-center` |-| `.piplug` 制品 | 插件中心(发布) | `vastsa/pi-desktop-plugins/packages/` |-| 目录 | 插件中心(生成) | `vastsa/pi-desktop-plugins/catalog.json` |+| `.piplug` 制品 | 插件中心(发布) | `AIUO-Net/pi-desktop-plugins/packages/` |+| 目录 | 插件中心(生成) | `AIUO-Net/pi-desktop-plugins/catalog.json` || 分发镜像 | 插件中心 | 分发仓库的 CNB Git 镜像 || 安装决定 | 用户 | 桌面端权限审查 |@@ -50,7 +55,7 @@ vastsa/pi-plugin-center # 管理面├─ scripts/ # 目录生成与校验└─ api/ db/ # 服务契约与迁移-vastsa/pi-desktop-plugins # 分发面,地址完全不变+AIUO-Net/pi-desktop-plugins # 分发面,地址完全不变├─ catalog.json # 由插件中心生成├─ packages/<pluginId>-<version>.piplug # 由插件中心发布└─ plugins/ # 已移除——源码归发布者所有@@ -71,7 +76,7 @@ https://raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main/packages/<plu```text中心目录 artifactBaseUrl = raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/main-本分发仓库 raw.githubusercontent.com/vastsa/pi-desktop-plugins/main+本分发仓库 raw.githubusercontent.com/AIUO-Net/pi-desktop-plugins/mainCNB 镜像 cnb.cool/aixk/pi-desktop-plugins/-/git/raw/main/…```diff --git a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.mdindex f984db023..247131a08 100644--- a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md+++ b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md@@ -320,6 +320,9 @@ main 在 `logs/app/plugin.log` 审计每个提示 id。注册、处理器超时。- 页面溢出菜单中的“导入 pi 扩展”,前置一个说明授权含义的确认。+显式本地包导入已支持 `pi.extensions` / `pi.skills` 与受限 registry-only 依赖准备,见 §3.2。+这不等于通用 pi 包管理器或自动读取 CLI settings 的能力。+## 12. 分阶段| 阶段 | 内容 | 承诺 |@@ -328,7 +331,7 @@ main 在 `logs/app/plugin.log` 审计每个提示 id。| v1.1 | 模块成为带 `agent.extension` 授权的 `contributes.agentExtensions`;把 pi CLI 扩展导入为开发插件;独立注册表和设置标签移除 | 已交付(D388) || v2 | 自定义会话条目(`sendMessage`、`appendEntry`)含 schema 升版和通用渲染、`sessionManager` 只读 shim、`switchSession`、编辑器读写、补全 provider、`registerShortcut`、markdown 转换器 | 已规划,需先决定条目持久化与压缩 || v2 | 自定义会话条目(`sendMessage`、`appendEntry`)与一次 schema 升级及通用渲染层、`sessionManager` 只读 shim、`switchSession`、编辑器读写、自动补全 provider、`registerShortcut`、markdown 转换器 | 计划中,需要就条目持久化与压缩作出决定 |-| v3 | `pi` 包 manifest 与安装、pi CLI `settings.json` 的只读提示、统一 skill 与提示发现、提示的远程控制路由、市场列出 | 未排期 |+| v3 | Read-only hints from the pi CLI's `settings.json`, unified skill and prompt discovery, remote-control routing for prompts, marketplace listing | Not scheduled |v1 交付顺序:打包 spike(E2E-245)、shared 协议类型,然后运行时、main、渲染层三条线并行。diff --git a/docs/zh-CN/spec/07-plugins/README.md b/docs/zh-CN/spec/07-plugins/README.mdindex 2c5c9d577..9b5649735 100644--- a/docs/zh-CN/spec/07-plugins/README.md+++ b/docs/zh-CN/spec/07-plugins/README.md@@ -27,3 +27,23 @@| [14-plugin-roadmap.md](/zh-CN/spec/07-plugins/14-plugin-roadmap) | 插件路线图 || [15-plugin-center.md](/zh-CN/spec/07-plugins/15-plugin-center) | 插件中心(发布侧) || [16-trusted-extensions.md](/zh-CN/spec/07-plugins/16-trusted-extensions) | 受信任扩展(sidecar 内扩展面) |++## 从契约回查代码++每个可调用方法见[完整 SDK 索引](../../plugin-development.md#13-complete-sdk-surface-and-source-map),+授权见权限矩阵。SDK、安装器和运行时是独立校验层,指南明确指出差异,不能把宽松解析当成授权。++| 范围 | 实现依据 |+|---|---|+| Manifest, permission vocabulary, host API | `packages/plugin-sdk/src/index.ts` |+| Renderer slots, actions, drafts, attachments | `packages/plugin-sdk/src/renderer.ts`, `renderer-composer.ts` |+| File/network/theme/MCP rules | SDK policy helpers and their unit tests |+| Templates, checks, packing, submission preparation | `packages/plugin-devkit/src` and its tests |+| Install, registry, marketplace, ownership | `crates/host-core/src/plugins` |+| Broker dispatch, callbacks, cleanup, events | `apps/desktop/electron/main/plugin-runtime.ts`, `plugin-host-process.mjs` |+| Panel bridge and command search | `apps/desktop/electron/preload/plugin-panel.ts`, `apps/desktop/electron/main/ipc/market-ipc.ts` |+| Trusted extension subset | `packages/agent-runtime/src/extensions` and spec 16 |+| Representative host/user paths | `apps/desktop/test/plugin-*.test.mjs`, repository example plugins |++生命周期提案、无设备后端的后台音频、签名规划、中心服务架构,都与已实现的运行时 API 区分。+`docs/plugin-plan` 的评审页可能包含尚未实现的钩子,不是额外公开 API。diff --git a/examples/plugins/README.md b/examples/plugins/README.mdindex d21e1e086..216be6d5b 100644--- a/examples/plugins/README.md+++ b/examples/plugins/README.md@@ -59,27 +59,27 @@ with `mode: "crash"`, and a chart whose first line is `crash` or `tall`Covered by `apps/desktop/test/plugin-ui-slots-lab.test.mjs` and the ElectronE2E.-## Planned examples--- `panel-basic`-- `agent-tool-basic`-- `skill-pack`-- `marketplace-mock-publisher`--## Official marketplace repository--Published plugins live in [`vastsa/pi-desktop-plugins`](https://github.com/vastsa/pi-desktop-plugins).--Local examples here remain useful for development loading (`Load dev plugin`).-Marketplace installs should come from that repository's `catalog.json` + `packages/*.piplug`.---## Practical template--Prefer the official warehouse template:--- https://github.com/vastsa/pi-desktop-plugins/tree/main/plugins/demo.workspace-summary-- Contribution guide: https://github.com/vastsa/pi-desktop-plugins/blob/main/CONTRIBUTING.md+## Templates and additional examples++`panel-basic`, `agent-tool-basic`, `skill-pack`, and `full-demo` are implemented+in `packages/plugin-devkit/src/templates.ts`; generate them with the app or+`pi-plugin init` rather than looking for separate example folders.++`roundtable` demonstrates model catalog/one-shot completion and an agent tool.+`fetch-redirect` is a local-only network-policy probe, not a marketplace package.+Load repository examples with **Load development plugin** and inspect their+manifest grants before exercising them. Source maps and the complete SDK method+inventory are in the [development guide](../../docs/plugin-development.md).++## Distribution++The official catalog is the plugin center's+[`catalog.json`](https://plugins.aiuo.net/catalog.json). Plugin sources remain+in publisher-owned repositories. The+[GitHub distribution mirror](https://github.com/AIUO-Net/pi-desktop-plugins)+contains distribution artifacts/catalog data, not the source warehouse or a+mandatory plugin template. `pi-plugin publish` prepares local submission files;+it does not upload. See the guide's release workflow before publishing.## Fetch redirect probe