From 2643ade75a80262dd49bf9228c7e85ff99cabc55 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 14:59:26 +0800 Subject: [PATCH 1/8] design(content-owners): target contracts for MCP, Hooks, Skills and PluginManager --- docs/design/plugins/Hooks.md | 186 +++++++++++++++++++++ docs/design/plugins/Mcp.md | 234 +++++++++++++++++++++++++++ docs/design/plugins/PluginManager.md | 161 ++++++++++++++++++ docs/design/plugins/README.md | 5 +- docs/design/plugins/Skills.md | 197 ++++++++++++++++++++++ 5 files changed, 781 insertions(+), 2 deletions(-) create mode 100644 docs/design/plugins/Mcp.md diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 7f10a66063..65a28e9926 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -2,6 +2,192 @@ Status: Ready ([#143](https://github.com/arcships/dim/issues/143)); maintainer decisions of 2026-10-22 and 2026-10-31 are applied (§10). Overall design: [overview](../overview.md) (Hooks). Phase: M1 (user, project and plugin sources). Language: Rust. Scope: [ADR 002](../../adr/002-plugin-scope.md) (process + Session + branch). +## Target contract + +Scope: process, Session and branch. Issue: #2022. + +The owners are `HooksSettings` (process), `HooksSession` (Session) and `HooksBranch` (branch). `HooksRuntime` is a private Session service; `HookSourcesHost` is the agent-crate port that binds the owner's one reader. The feature's event points, document shape and script protocol stay as this document describes; this section replaces the public-surface decisions. + +### Use and scope: responsibility split + +`HooksSettings` owns: + +- **Sources.** The Settings documents `hooks` (user), `hooks-projects` and `hooks-plugins`; `.dimcode/hooks.json` is read through FileStorage under the project root Settings authorizes. +- **Content registration.** The hook document a plugin package carries, the holding plugin and its refusal. +- **One reader.** `sources(cwd)` resolves the user, project and plugin sources into the value a hook point reads. The management methods and the agent-crate port use this same reader. +- **Client operations.** `hooks.catalog`, `hooks.save` and `hooks.set_enabled`. + +`HooksSession` owns: + +- **Command execution.** The Session's `HooksRuntime`, the command processes, their stdin payloads, timeouts, cancellation and settlement. +- **Submit check.** The `hooks` check registered with `submitChecks` for operator input. The check writes no input; it returns the context or a block. +- **Source read.** It calls the `HookSourcesHost` binding; it does not build a second reader. + +`HooksBranch` owns: + +- **Hook decisions.** Folding the public events into the six hook points, the Permission advisor, the Approval answers and the branch input that carries hook context or diagnostics. +- **Observed state.** The branch-input writes are the only state it adds; the decision itself is the owner's. + +Callers keep: + +- The hook document's business meaning and the command scripts. +- The admission, approval and input operations: Permission, Approval and the operator-input entries own them; Hooks only registers a check or advice and answers through their operations. +- The context the model reads; `HooksSession`/`HooksBranch` contribute through the owners' inputs and tool results. + +| Requirement (callers) | Compose from existing operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Register a package's hook document | No: the content registry and refusal are `HooksSettings`' state | `register`, `withdraw`, `plugins`, `refusal` | +| Client reads and edits hooks | No: the merged catalog and the revision write are the owner's state | `hooks.catalog`, `hooks.save`, `hooks.set_enabled` | +| A hook point reads the current sources | No: the project file read and the source merge are the owner's knowledge | `sources(cwd)` | +| The Session runs a hook command | No: the process, timeout and settlement are the Session's resource | `HooksSession`'s runner; the command is private | +| Operator input is checked before it is written | No: the check must run before the entry writes, and the entry owner provides the registration point | `submitChecks.register("hooks")`; the check returns a value | +| A tool call gets hook advice | No: Permission owns the admission; Hooks contributes through its advisor registration | `Permission.registerAdvice`; the advisor returns deny/ask/allow | +| Hooks answers an approval | No: Approval owns the question and the decision | `Approval.respond` | +| Hook context or diagnostics reaches the branch | No: branch input is the branch owner's entry | `Branch.input` with source `hooks` | + +### Caller example + +`PluginManager` registers a package's hook document: + +```rust +hooks.register(ctx, plugin, dir, document).await?; // refusal is a value +``` + +The local client: + +```rust +let catalog = hooks.catalog(project, cancelled.clone()).await?; +hooks.save(revision, document, cancelled).await?; // conflict -> re-read +``` + +`HooksSession` registers the submit check and runs a command: + +```rust +submit_checks.register(ctx, "hooks", move |input, cancelled| { + let sources = host.read(cwd, cancelled.clone()); + run_user_prompt_submit(sources, input, cancelled) +}); +``` + +`HooksBranch` registers advice, answers an approval and writes an observation: + +```rust +permission.register_advice(ctx, "hooks", move |call, cancelled| advise(hook_sources(), call, cancelled)); +approval.respond(approval_id, decision); +branch.input(source, HookInput::observation(text)); +``` + +### Own contract + +#### Dependencies + +`HooksSettings` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`) and FileStorage (`read` for `.dimcode/hooks.json`). `HooksSession` uses SessionScope (`config`, `identity`, `activated`, `closing`, `withHold`), the agent-crate `HookSourcesHost` binding, `submitChecks` and HostPlatform (`spawn`, `wait`, `kill`, `settle`). `HooksBranch` uses the branch's `HooksRuntime`, `Permission.registerAdvice`, `Approval.respond`, `Branch.input`, and the public events it folds. `HooksRuntime` is not a public service; the Session and branch parts are the same feature. + +#### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `hooksService.register` | Register a package's hooks document | `{plugin, dir, document}` | `{}` or `{refusal}` | Accepted write is not cancelled | `invalid_document`, `settings_write`, `settings_conflict`, `closed` | +| `hooksService.withdraw` | Withdraw a package's document | `{plugin}` | `{}` | Accepted write is not cancelled | `closed` | +| `hooksService.plugins` | The packages holding hook content | `{}` | `{plugins}` | None | `closed` | +| `hooksService.refusal` | The refusal of a package | `{plugin}` | `{reason?}` | None | `closed` | +| `hooksService.sources` | The merged hook sources for a cwd | `{cwd}` | `{sources, project?}` | The read can be cancelled | `unreadable`, `closed`, `cancelled` | +| `hooks.catalog` | The client's hook catalog | `{project?}` | `{sources, entries}` | The read can be cancelled | `invalid`, `closed`, `cancelled` | +| `hooks.save` | Save the user document at a revision | `{revision, document}` | `{revision}` | Accepted write is not cancelled | `invalid`, `conflict`, `settings_write`, `closed` | +| `hooks.set_enabled` | Enable or disable a project source | `{project, enabled}` | `{}` | Accepted write is not cancelled | `invalid`, `conflict`, `closed` | +| `HooksSession` runner | Run one hook command with a payload | `{hook, payload}` | `{decision, output}` | The Session's cancel kills the process tree; the owner settles | `failed`, `timeout`, `block`, `cancelled`, `closed` | +| `HooksSession` submit check | Check operator input before it is written | `{input}` | `{context?}` or block | The entry's call cancel stops the check and its command | `block`, `warnings`, `proceed` | +| `HooksBranch` advice | Advise a tool admission | `{call, source}` | deny/ask/allow | The admission's cancel stops the advisor | `deny`, `ask`, `allow`; failures map to allow/ask | +| `HooksBranch` approval | Answer an approval question | `{approvalId, decision}` | `{}` | The live answer's cancel | `Approval`'s errors | +| `HooksBranch` observation | Write hook context or diagnostics to the branch | `{input}` | `{}` | The branch close cancels the write; the owner rechecks | none; only diagnostics | + +The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` use it directly. The `HookSourcesHost` port is the agent-crate binding of `hooksService.sources`; the port and the data face share one reader. The `SettingsHookSources` duplicate is deleted. + +#### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid_document`, `invalid`, `conflict` | Fix the document or re-read the revision; nothing was written | +| `unreadable` | The project file cannot be read; report the source error; the user document still applies | +| `settings_write`, `settings_conflict` | Retry after Settings is available, or report the conflict | +| `failed` | The hook command failed; apply `onFailure` | +| `timeout` | The handler exceeded its timeout; apply `onFailure` | +| `block` | The hook blocked the operation; report its reason | +| `cancelled` | The operation stopped; nothing was written | +| `closed` | The Session or owner is unloading; use the replacement generation | + +#### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| Content register/withdraw | Validate, write the Settings document, update the content registry | The accepted write completes | The plugin row unloads; its content is withdrawn | New registrations refused; the next generation reads the documents | Settings write by `HooksSettings`; registry by `HooksSettings` | +| `sources` | Resolve the user document, the project file under the authorized root, and plugin content; return a snapshot | The read stops; no partial source | The caller's row unload drops the read | The next call reads the new generation | Source read by `HooksSettings`; project file by FileStorage | +| Command | Build the payload, spawn through HostPlatform, write stdin, wait with the handler timeout, settle the process tree | The cancel kills the process tree and settles it | The Session's row unload cancels its commands | Pending commands end `closed`; every process is settled | Command process by `HooksSession`; the work's future by the calling row | +| Submit check | Read the sources, run the `UserPromptSubmit` handler, return context or block | The entry's cancel stops the check | The check registration is withdrawn with the Session row | The entry does not write after a closed check | Check by `HooksSession`; input write by the entry owner | +| Advice | Read the sources, run the `PreToolUse` handler, return deny/ask/allow | The admission's cancel stops the advisor | The advisor registration is withdrawn with the branch | Permission's admission sees the failure mapping | Advice by `HooksBranch`; admission by Permission | +| Approval answer | Run the `PermissionRequest` handler, call `Approval.respond` | The live answer's cancel ends the answer | The branch row unload drops the answer | Approval's own errors | Approval by Approval; answer by `HooksBranch` | +| Observation | Write `Branch.input` with source `hooks` | The branch close stops the write | The branch row unload ends writes | The branch's input entry decides | Input by the branch owner; the hook result by `HooksBranch` | + +### Exceptions with reasons + +- `HooksRuntime` is the Session's private runner. `HooksSession` and `HooksBranch` are one feature; the command processes and their settlement stay in the Session part; the runtime has no public name. +- `HookSourcesHost` is the agent-crate port. It binds `HooksSettings.sources`; the port and the data face share the one reader; the project file is read through FileStorage. +- Hook commands run because they are configured; they need no host-local approval (AGENTS rule 11). `PreToolUse` only advises Permission; the tool call's approval stays with Approval. +- `UserPromptSubmit` runs only at the operator-input entries, before the write; other inputs do not run it. +- `HooksBranch` writes observations through `Branch.input`; it does not write the Timeline directly. +- The `hooks.*` methods are management methods (#2095), not a second `hooksService` face. + +### Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | `HooksSettings` process; `HooksSession` Session; `HooksBranch` branch. The branch part folds public events and writes branch input; it is a Capability. | +| §2 scopes | Configuration is process; command execution and the submit check are Session; decisions and observations are branch. | +| §3 orthogonality | The branch part uses Permission, Approval and Branch input operations; the Session part uses the Settings source through the port. | +| §4 rule 1 | Hook commands are configuration-run commands, not agent commands; no Timeline command event. | +| §4 rule 2 | No handoff: the runner and command processes stay in the Session; the branch uses the Session's service. | +| §4 rule 3 | Commands wait in Hooks' tasks, never in a Dispatcher handler or under the commit lock. | +| §4 rule 4 | The vocabulary is hook points, sources, handlers and decisions; no caller business appears. | +| §4 rule 5 | No batches. | +| §4 rule 6 | Hook context reaches the model only through adopted inputs or tool results. | +| §4 rule 7 | Callers use `hooksService`, `hooks.*`, the port, the check, the advisor, Approval and Branch input; no caller holds `SettingsHookSources` or a command process. | +| §4 rule 8 | Requirements to #2026, #2027/#2028, #2032, #2094, #2080, #2093 are listed below. | +| §4 rule 9 | The branch input is written after the command's decision; the Timeline commit is the branch owner's. | +| §7 callbacks and ids | The submit check and the Permission advisor are callbacks by reference; no object or handle crosses. | +| §7 one change | The two readers are merged into one; the old `SettingsHookSources` and the session-port duplicate are deleted with the caller migration. | +| ADR 002 D1 | Process `HooksSettings`; Session `HooksSession`; branch `HooksBranch`. | +| ADR 002 D2 | No wrapper: `hooksService` is on `HooksSettings`; the port is a host binding, not a facade. | +| ADR 002 D3 | Extensions depend on the Hooks owner; the agent crate uses the port. | +| ADR 002 D4 | The hook documents are Settings sources and a FileStorage project file; no assembly business setting. | +| ADR 002 D5 | Operations, values and callbacks are language-neutral; the Rust binding is the appendix. | + +### Requirements raised to mechanism owners + +- #2026: `submitChecks.register` must accept the `hooks` check with a value result; the operator-input entries must call it before writing. +- #2027/#2028: `Permission.registerAdvice` must give the advisor the call source and the admission decision; `Approval.respond` must accept a decision; `Branch.input` must accept `hooks` observations. +- #2032: HostPlatform `spawn`, `wait`, `kill`, `settle` must carry stdin, a handler timeout and tree cancellation for hook commands. +- #2094: Settings `register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`; no new operation. +- #2080: FileStorage `read` for `.dimcode/hooks.json`; no new operation. +- #2093: SessionScope `config`, `identity`, `activated`, `closing`, `withHold`; no new operation. + +### Binding appendix + +`hooksService` is on `HooksSettings`; the `hooks.*` methods are registered through #2095; `HookSourcesHost` is the agent-crate port. `HooksRuntime` is `pub(crate)`. + +```rust +#[rutis::service(name = "hooksService")] +impl HooksSettings { + pub async fn register(&self, ctx: &Ctx, plugin: String, dir: String, document: HooksDocument, cancelled: CancelledFn) -> Result, HooksContentError>; + pub async fn withdraw(&self, ctx: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), HooksContentError>; + pub fn plugins(&self) -> Vec; + pub fn refusal(&self, plugin: &str) -> Option; + pub async fn sources(&self, cwd: String, cancelled: CancelledFn) -> Result; +} +``` + +The Session and branch parts keep their internal types; the port's request and reply are `{cwd}` and `HookSources`. + + Hooks runs user-configured commands at fixed points of a Session's **business operations** and hands each command's decision to the owner of that operation. Dim reads only its own hooks configuration; it does not load Claude Code or Codex hook files. For easy migration, the document shape (event names, matcher groups, command handlers, `timeout`, `onFailure`) and the script protocol (stdin JSON, exit codes, decision and output fields) follow Claude Code and Codex, so existing scripts and pasted configuration work (Appendix G). Hooks never hooks infrastructure. The withdrawn design ([#21](https://github.com/arcships/dim/issues/21)) made Timeline `before` callbacks asynchronous so a command could hold a write; that is not done, and Hooks registers no before callback. Timeline, Dispatcher, the event envelope and assembly are unchanged. Each hook point instead attaches to the business owner that already decides the operation, through that owner's public events or services: diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md new file mode 100644 index 0000000000..8457a2fbdd --- /dev/null +++ b/docs/design/plugins/Mcp.md @@ -0,0 +1,234 @@ +# Mcp + +Scope: process and Session. Issue: #2022. + +`Mcp` owns the process's MCP configuration, content, connection definitions and OAuth credentials. `McpSession` owns one Session's MCP connection generations and tool source. `TemporaryMcp` owns the client-supplied temporary bindings of one Session. `McpPublication` and `McpAuth` are private parts of `Mcp`; neither has a public surface. The current implementation is described in [mcp-management](../appserver/mcp-management.md), [mcp-apps](../appserver/mcp-apps.md), [mcp-oauth](../appserver/mcp-oauth.md) and [TemporaryMcp](TemporaryMcp.md). + +## Use and scope: responsibility split + +`Mcp` owns: + +- **Configuration documents.** The Settings sources `mcp`, `mcp-projects`, `mcp-plugins` and `mcp-secrets`; `.mcp.json` is the project file of `mcp-projects` under a project Settings authorizes. +- **Content registration.** The MCP document a plugin package carries, the holding plugin, and the refusal reason. +- **Connection definitions and credentials.** The resolved server definitions, the OAuth records and refresh, and the disposable probe connection. +- **Client operations.** `mcp.catalog`, `mcp.configuration`, `mcp.update`, `mcp.save`, `mcp.remove`, `mcp.set_enabled`, `mcp.move`, `mcp.import.preview`, `mcp.import.apply`, `mcp.test`, `mcp.inspect`, `mcp.disconnect` and `mcp.auth.*`. +- **Session-facing values and commands.** The selection, definition and credential reference a Session reads; the connection-state registry that Sessions report into; the disconnect command a Session observes. + +`McpSession` owns: + +- **Connection generations.** The child `McpServer` rows it mounts with `SessionScope.mount`, the connection id it binds to its own row, and the tools, resources and views read from that generation. +- **Session view.** `state`, `refresh`, `widget` and `call`; the tool source it registers with `toolRegistry`; the result files it writes through `sessionFiles`. +- **Lifecycle.** It mounts generations after `sessionLifecycle.activated`, closes them on `closing`, and settles every generation on Session close or its own row unload. + +`TemporaryMcp` owns: + +- **Temporary bindings.** The client's server definitions, the binding id, the 30 s lease, the child `McpServer` instances and their tool source. A binding ends on detach, lease expiry, Session close or client disconnect. + +Callers keep: + +- The MCP protocol payloads and the model-visible tool results; `McpSession` carries the result content. +- Which entry a client edits, the client's own confirmation, and the UI around `mcp.catalog` and `mcpSession.state`. +- The plugin package's manifest; `PluginManager` passes the MCP document to `Mcp.register`. +- The MCP Apps view render; the client calls `mcpSession.widget` and renders the returned value. +- The approval of an MCP tool call: `Permission`/`Approval` decide it; MCP does not. + +| Requirement (callers) | Compose from existing operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Register or withdraw a plugin package's MCP content | No: the content registry and its refusal are `Mcp`'s state | `register`, `withdraw`, `plugins`, `refusal` | +| Read and edit MCP entries, enablement, order and imports | No: the merged catalog and the atomic write are `Mcp`'s state | `mcp.catalog`, `mcp.configuration`, `mcp.save`, `mcp.update`, `mcp.remove`, `mcp.set_enabled`, `mcp.move`, `mcp.import.*` | +| Test a server definition before saving it | No: the probe connection is a resource `Mcp` owns and settles | `mcp.test` | +| Read the MCP view of one Session | No: the view is the Session's owned generation state | `mcpSession.state`, `mcpSession.refresh`, `mcpSession.widget`, `mcpSession.call` | +| Run one MCP tool from the Session | No: the tool handler needs the connection generation and its settlement | `mcpSession`'s tool source; the handler calls the owner's internal `call(connectionId, tool, args)` | +| Mount a temporary client binding | No: the child rows and the lease belong to the Session | `session.mcp_temporary.attach`, `renew`, `detach` | +| Inspect every Session's connection state | No: the process registry is the value `Mcp` owns; a Session cannot read another Session's rows | `mcp.inspect` reads the registry; `McpSession` reports its own state | +| Disconnect a source or server everywhere | No: `Mcp` owns the command value; each `McpSession` owns its connection | `mcp.disconnect` writes the command; `McpSession` observes and closes | +| Sign in to an OAuth server | No: credentials and refresh are `Mcp`'s state | `mcp.auth.start`, `complete`, `cancel`, `logout` | + +## Caller example + +`PluginManager` registers a package's MCP content: + +```rust +let refusal = mcp.register(ctx, plugin, dir, document).await?; +if let Some(reason) = refusal { + record_refusal(plugin, reason); // the package is installed; MCP content is refused +} +``` + +The local client edits one entry: + +```rust +let catalog = mcp.catalog(project, cancelled.clone()).await?; +let revision = catalog.entry(id).revision; +mcp.save(id, revision, entry, cancelled).await?; // conflict -> re-read the catalog +``` + +`McpSession` mounts one generation and registers its tool source: + +```rust +let definition = mcp.definition(entry_id, cancelled.clone()).await?; +let instance = session_scope.mount("mcp-server", definition.id, definition.data, cancelled).await?; +let connection = connection_id.new(); // bound to this McpSession row +let tools = server_tools(instance).await?; +tool_registry.register(ctx, "mcp", tools, handler(connection)); +``` + +The tool handler calls the owner's internal operation; the handler holds only the id: + +```rust +let result = session.call_connection(ctx, connection, tool, args, cancelled).await?; +``` + +`McpSession` reports its state to the process registry, and observes the disconnect command: + +```rust +mcp.report_connections(session_id, entries).await?; +if mcp.disconnect_version() > seen { + for entry in entries { close(entry.connection); } +} +``` + +`TemporaryMcp` attaches a binding: + +```rust +let binding = temporary.attach(ctx, server, cancelled).await?; +// binding.id; renew before the 30 s lease; detach removes the child rows and tools +``` + +## Own contract + +### Dependencies + +`Mcp` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`), FileStorage (`read` for `.mcp.json` through the project root), and the management-methods and connection mechanisms of #2095. `McpSession` uses SessionScope (`mount`, `unmount`, `withHold`, `activated`, `closing`, `config`, `identity`), `toolRegistry` and `sessionFiles` (#2026/#2018), and `Mcp`'s values and registry operations. `TemporaryMcp` uses SessionScope, `sessionMethods` (#2026), `toolRegistry` and the `Mcp` definition values. `McpAuth` is a private process service of `Mcp`; the child rows that need a credential receive the service name and the entry id, not the credential value. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `mcpService.register` | Register a package's MCP document | `{plugin, dir, document}` | `{}` or `{refusal}` | Accepted write is not cancelled | `invalid_document`, `settings_conflict`, `settings_write`, `closed` | +| `mcpService.withdraw` | Withdraw a package's MCP document | `{plugin}` | `{}` | Accepted write is not cancelled | `closed` | +| `mcpService.plugins` | List the packages holding MCP content | `{}` | `{plugins}` | None | `closed` | +| `mcpService.refusal` | The refusal reason of a package | `{plugin}` | `{reason?}` | None | `closed` | +| `mcp.catalog` | The merged entries and their revisions | `{project?}` | `{entries, invalid, application}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | +| `mcp.configuration` | One entry's declared and effective view | `{id, project?}` | `{entry}` | Read can be cancelled | `missing`, `closed`, `cancelled` | +| `mcp.save` | Create or replace one entry at a revision | `{id?, revision?, entry}` | `{entry, revision}` | Accepted write is not cancelled | `invalid`, `conflict`, `user_scope`, `settings_write`, `closed` | +| `mcp.update` | Change selected fields at a revision | `{id, revision, patch}` | `{entry, revision}` | Accepted write is not cancelled | `invalid`, `missing`, `conflict`, `closed` | +| `mcp.remove` | Remove an entry | `{id, revision}` | `{}` | Accepted write is not cancelled | `missing`, `conflict`, `closed` | +| `mcp.set_enabled` | Enable or disable an entry | `{id, enabled, project?}` | `{}` | Accepted write is not cancelled | `invalid`, `missing`, `closed` | +| `mcp.move` | Move an entry in its source | `{id, before?}` | `{}` | Accepted write is not cancelled | `invalid`, `missing`, `conflict`, `closed` | +| `mcp.import.preview` | Parse an import payload without writing | `{document, project?}` | `{entries, invalid}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | +| `mcp.import.apply` | Write the selected imported entries | `{document, selection, project?}` | `{applied, invalid}` | Accepted write is not cancelled | `invalid`, `conflict`, `closed` | +| `mcp.test` | Probe one server definition with a disposable connection | `{config, timeout?}` | `{status, latency, tools, reason}` | Timeout stops the probe; the owner settles the probe | `invalid`, `timeout`, `refused`, `closed` | +| `mcp.inspect` | The connection states reported by Sessions | `{}` | `{sessions: [{sessionId, entries}]}` | None | `closed` | +| `mcp.disconnect` | Ask every Session to close one source or server | `{source?, server?}` | `{}` | None; the command is a value | `closed` | +| `mcp.auth.start` | Start an OAuth flow | `{id, project?}` | `{authUrl?}` | Flow can be cancelled | `missing`, `unsupported`, `refused`, `closed`, `cancelled` | +| `mcp.auth.complete` | Finish an OAuth flow with the callback | `{id, callback}` | `{credentialState}` | Flow can be cancelled | `missing`, `invalid`, `refused`, `cancelled`, `closed` | +| `mcp.auth.cancel` | Cancel an OAuth flow | `{id}` | `{}` | None | `missing`, `closed` | +| `mcp.auth.logout` | Remove an entry's OAuth records | `{id, project?}` | `{}` | Accepted write is not cancelled | `missing`, `user_scope`, `closed` | +| `mcpSession.state` | The Session's MCP view | `{}` | `{servers, error?}` | None; the value is read | `closed` | +| `mcpSession.refresh` | Ask the owner to rediscover the enabled entries | `{}` | `{}` | None; the signal is a value | `closed` | +| `mcpSession.widget` | The view for one published tool | `{publishedTool}` | `{view}` or absent | The client dropping the call cancels the read | `absent`, `unsupported`, `not_callable`, `unknown_server`, `unavailable`, `refused`, `unknown`, `closed` | +| `mcpSession.call` | One MCP Apps call | `{server, tool, args}` | `{result}` | The client dropping the call cancels the resource read | `unknown_server`, `unavailable`, `refused`, `unknown`, `closed` | +| `session.mcp_temporary.attach` | Mount a client temporary binding | `{server}` | `{binding, tools}` | The caller dropping the call shuts the half-made binding | `invalid`, `mount_failed`, `closed` | +| `session.mcp_temporary.renew` | Extend the binding lease | `{binding}` | `{}` | None | `invalid`, `missing`, `closed` | +| `session.mcp_temporary.detach` | Remove the binding and its children | `{binding}` | `{}` | None; the owner completes the removal | `missing`, `closed` | + +The internal `McpSession` connection operations (`open`, `tools`, `observe`, `close`) are on the owner type and are called only by its own tool source and view handlers; they carry `connectionId`. `Mcp`'s `definition`, `selection`, `report_connections`, `disconnect_version` and `config_version` are internal operations or values used by `McpSession`; they are not public names. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid`, `invalid_document` | Fix the document or the entry; the write did not happen | +| `missing` | Re-read the catalog; the entry or binding is gone | +| `conflict` | Re-read the revision and decide again; the write did not happen | +| `user_scope` | The credential belongs to the user scope; ask the user or use the user project | +| `settings_write`, `settings_conflict` | Retry after the Settings row is available, or report the conflict | +| `refused`, `unsupported`, `not_callable`, `unknown_server`, `unavailable`, `unknown`, `absent` | Report the MCP view or tool error; the generation is unchanged | +| `timeout` | The probe did not finish; the owner settled it; report the result | +| `mount_failed` | The child rows did not activate; the owner shut them down; report the binding failure | +| `cancelled` | Nothing was committed; the read or the flow stopped | +| `closed` | The owner is unloading; use the replacement generation | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `McpSession` generation | Read the selection and definition, mount the `McpServer` child after `activated`, bind a connection id to the row, register the tool source | A dropped `open` unmounts the half-made child | The row's generations close and unmount; the tool source is withdrawn | New generations are refused; every child is unmounted; the state reports unavailable/closed | Child by `McpSession` through `SessionScope.unmount`; connection id by the row | +| Tool call | The handler resolves the connection id, calls the child, writes the result through `sessionFiles` | The cancel stops the request and settles the child's process | The handler's row unload stops its calls | Pending calls end `closed`; the child settles | Connection by `McpSession`; result file by `McpSession`/`sessionFiles` | +| `mcp.inspect` | `Mcp` reads the registry of values reported by Sessions | None; the value is read | The Session's last report remains until its row unloads | The registry is a process generation value | Registry by `Mcp`; entries by each `McpSession` | +| `mcp.disconnect` | `Mcp` writes a command version; each `McpSession` observes and closes the matching connection | None; the command is a value | The Session's connections close with the row | New Sessions read the current command version; old generations do not | Command by `Mcp`; connections by each `McpSession` | +| `mcp.test` | `Mcp` opens a disposable connection, probes, lists tools, closes it | The timeout or cancel closes the probe | The probe is closed with the owner | The owner closes every probe | Probe by `Mcp` | +| `mcp.auth.start/complete` | `Mcp` starts the flow, stores the pending state, completes and writes the credential | The flow cancels; the pending state is removed | The flow ends with the owner | Pending flows are dropped on reload; credentials stay | Flow and credential by `Mcp`/`McpAuth` | +| `TemporaryMcp.attach` | The Session mounts the child, registers tools, returns the binding id and lease | A dropped attach unmounts the child | The binding's children close; tools are withdrawn | New binds refused; every child unmounts | Child by `TemporaryMcp`; lease by the binding | + +## Exceptions with reasons + +- `McpAuth` is a private process service. Its instance key and unload are part of the MCP plugin assembly; the Session child receives the service name and an entry id, never a credential value. The MCP plugin's assembly is the shared lifecycle design for the service and its child rows. +- `McpServer` is a private child row of the MCP feature. `McpSession` and `TemporaryMcp` mount it through `SessionScope`; its tools are published through the Session's `toolRegistry`. The child has no public name. +- `mcpSession.call` and `mcpSession.widget` express cancellation by the client dropping the call; the cross-language face has no cancel parameter, and the owner stops the resource read when the call is dropped. +- `mcp.inspect` returns values reported by Sessions. `Mcp` owns the registry, each `McpSession` owns and reports its entries; `Mcp` does not read a Session's loader or child rows. +- `mcp.disconnect` is a command value. `Mcp` does not close a Session's connection; each `McpSession` observes the command and closes its own generation. +- `mcp.test` owns a disposable probe connection. It is not a Session generation and does not appear in `mcp.inspect`. +- The `mcp.*` methods are management methods (#2095), not a second `mcpService` face. The owner's operations are the same operations; the client binding is the management-methods mechanism. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | `Mcp` is one process part; `McpSession` and `TemporaryMcp` are Session parts. None folds Timeline state; they are not Capabilities. | +| §2 scopes | Process configuration and credentials; Session connection generations and views; branch tool calls through the Session's tool source. | +| §3 orthogonality | Each owner uses the other's operations: `McpSession` reads `Mcp`'s values and reports its state; no Session reads another Session. | +| §4 rule 1 | No MCP command Timeline event. | +| §4 rule 2 | No handoff: the connection id stays with `McpSession`; `Mcp` gets values. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | The owner's vocabulary is MCP entries, servers, connections and views; no client or plugin business appears. | +| §4 rule 5 | No batches. | +| §4 rule 6 | Tool results reach the model through the Session's tool source; `McpSession` writes the result. | +| §4 rule 7 | Callers use `mcpService`, `mcp.*`, `mcpSession` and `session.mcp_temporary`; no caller holds `McpConnection`, `McpOwner`, `McpPublication` or `McpAuth`. | +| §4 rule 8 | Requirements to #2018, #2026, #2093, #2095 are listed below. | +| §4 rule 9 | No Timeline fact. | +| §7 callbacks and ids | Connection ids and Session ids cross; credentials and child instances stay with the owner. Drop-cancel is the data-face cancellation for view calls. | +| §7 one change | The old `McpServiceBinding`, `McpConnection`, `McpOwner`, `McpPublication` table and `mcpSession.subscribe` are removed in the same change that migrates every caller. | +| ADR 002 D1 | Process `Mcp`; Session `McpSession`/`TemporaryMcp`; the connection is per Session. | +| ADR 002 D2 | No wrapper: `mcpService` is on `Mcp`, `mcpSession` on `McpSession`; no binding type. | +| ADR 002 D3 | Extensions depend on the process MCP owner; `McpSession` is the Session child of the same feature. | +| ADR 002 D4 | The configuration documents are Settings sources; no assembly business setting is added. | +| ADR 002 D5 | Operations, values and ids are language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- #2018: `sessionFiles` needs `write`, `read` and `remove` for MCP tool results; the Session owner writes result files. +- #2026: `toolRegistry.register` must accept a Session-owned tool source with a handler that holds a connection id; `sessionMethods.register` must accept `session.mcp_temporary.*`. +- #2093: `SessionScope.mount`/`unmount` must accept the `mcp-server` group and a definition value; `withHold`, `activated` and `closing` are used as defined. +- #2095: `ManagementMethods.register` must host the `mcp.*` namespace; `Connection` calls `mcpSession.state/refresh/widget/call`. +- #2080: FileStorage `read` for `.mcp.json` under the project root; no new operation. +- #2094: Settings `register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`; no new operation. + +## Binding appendix + +`mcpService` is on `Mcp`; `mcpSession` on `McpSession`; `session.mcp_temporary` on `TemporaryMcp`. `McpServiceBinding`, `McpConnection`, `McpOwner` and `McpPublication` do not exist. The management methods are registered through #2095. + +```rust +#[rutis::service(name = "mcpService")] +impl Mcp { + pub async fn register(&self, ctx: &Ctx, plugin: String, dir: String, document: McpDocument, cancelled: CancelledFn) -> Result, McpContentError>; + pub async fn withdraw(&self, ctx: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), McpContentError>; + pub fn plugins(&self) -> Vec; + pub fn refusal(&self, plugin: &str) -> Option; +} +``` + +`McpSession`'s data face: + +```rust +#[rutis::service(name = "mcpSession")] +impl McpSession { + pub fn state(&self) -> McpSessionState; + pub fn refresh(&self) -> Result<(), McpSessionError>; + pub async fn widget(&self, ctx: &Ctx, published_tool: PublishedTool) -> Result, McpAppError>; + pub async fn call(&self, ctx: &Ctx, server: String, tool: String, args: Value) -> Result; +} +``` + +`TemporaryMcp`'s methods are registered with `sessionMethods`; the request, reply and error types are the typed structures in `mcp/temporary.rs` and the management module. `McpServiceBinding` and the `McpConnection` methods are deleted. diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index ce2a57ab21..3ea68a995b 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -2,6 +2,167 @@ Status: Draft, aligned with the maintainer on 2026-10-27. Requirements: [plugin management](../plugin-management.md) ([#432](https://github.com/arcships/dim/issues/432)). Issues: [#3](https://github.com/arcships/dim/issues/3), [#384](https://github.com/arcships/dim/issues/384). Scope: [ADR 002](../../adr/002-plugin-scope.md) (process: installation is per host). Language: Rust. Milestone: M1 for the parts marked in §0. +## Target contract + +Scope: process, with a Session tool part. Issue: #2022. + +The owners are `PluginManager` (process) and `PluginTools` (Session). `Owners` and the in-memory content refusals are private parts of `PluginManager`. The loader's rows are rutis-loader's state and are outside this contract; `UiExtensions` owns the UI content and is outside this contract. The feature's manifest, `plugins.json` format, default configuration and install/update/remove behavior stay as this document describes. + +### Use and scope: responsibility split + +`PluginManager` owns: + +- **Package records.** `plugins.json`, the default configuration, the plugin directories, the installed name/version/source and the enabled/disabled state. +- **Package operations.** `plugin.list`, `plugin.install`, `plugin.enable`, `plugin.disable`, `plugin.reload`, `plugin.update`, `plugin.remove`. +- **Content registration.** The manifest's MCP, Hooks and Skills content is given to those owners; the UI content is given to `UiExtensions`. The refusal is a value from the content owner and is kept for the package. +- **Code rows.** The plugin code rows it creates, turns on, replaces and removes through rutis-loader; the loader is a separate owner and its data face is not part of this contract. +- **Runtime acquisition.** The Node and Python runtimes a plugin declares are requested from `RuntimeManager`; the package record does not own the runtime. + +`PluginTools` owns: + +- **The `plugin` tool.** It maps the model's command to one process operation and returns the tool result. It holds the process owner's operation or callback, not the `Manager` object. + +Callers keep: + +- The plugin package's manifest, files and lock; `PluginManager` installs and records them. +- The content owners' documents and refusal rules; `PluginManager` passes the manifest content and reports the refusal. +- The model's choice to use the `plugin` tool and the client's choice to install or enable a package. +- The loader's row state and reloads; rutis-loader owns them. + +| Requirement (callers) | Compose from existing operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| List, install, update, remove, enable, disable or reload a package | No: the records, directory, lock and content registration are `PluginManager`'s state | `plugin.*` operations | +| Install a package's code and content atomically | No: the loader rows, package record and content registration must be settled together | the install/update/remove operations; the owner rolls back the package record when the content is refused | +| Read or change a package's content | No: the content belongs to the MCP, Hooks, Skills or UI owner | the content owners' operations; `PluginManager` only registers and withdraws | +| Run a plugin command from the model | No: the tool needs the process owner's operation, not a package record | the `plugin` tool; `PluginTools` calls the operation | +| Start the runtime a package declares | No: the runtime is another owner's resource | `RuntimeManager`; `PluginManager` records the requirement | + +### Caller example + +The local client installs and enables a package: + +```rust +let listed = plugin.list().await?; +let installed = plugin.install(source, cancelled).await?; // progress is an owner value +plugin.enable(installed.name, cancelled).await?; +``` + +The model's tool: + +```rust +let result = plugin_tool.call("enable", args, cancelled).await?; +// the owner records the change; the tool returns the owner's value +``` + +`PluginManager` registers content during install: + +```rust +let refusal = mcp.register(ctx, plugin, dir, document).await?; +if let Some(reason) = refusal { + rollback_package_record(plugin, reason); +} +``` + +### Own contract + +#### Dependencies + +`PluginManager` uses FileStorage or PluginFiles for `plugins.json` and the package files (#2080/#2016), `RuntimeManager` for the npm/Python runtime (#2019), rutis-loader for the code rows (out of scope), MCP/Hooks/Skills/UiExtensions for content, and the management-methods mechanism of #2095. `PluginTools` uses `ToolRegistry` (#2026) and the process owner's operation or callback. + +#### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `plugin.list` | The installed packages and their state | `{}` | `{packages}` | None | `closed` | +| `plugin.install` | Install a local path or Git source | `{source, name?, lock?}` | `{package, progress?}` | Accepted install settles or rolls back | `invalid_source`, `invalid_manifest`, `exists`, `load_failed`, `content_refused`, `restart_required`, `write_failed`, `closed` | +| `plugin.enable` | Make one installed package the name's active package | `{name, version?}` | `{}` | Accepted operation settles | `missing`, `load_failed`, `content_refused`, `restart_required`, `closed` | +| `plugin.disable` | Turn a package name off | `{name}` | `{}` | Accepted operation settles | `missing`, `restart_required`, `closed` | +| `plugin.reload` | Reload a package's rows | `{name}` | `{}` | Accepted operation settles | `missing`, `load_failed`, `content_refused`, `closed` | +| `plugin.update` | Update a package to a source revision | `{name, source?, lock?}` | `{package, progress?}` | Accepted update settles or rolls back | `missing`, `invalid_source`, `load_failed`, `content_refused`, `write_failed`, `closed` | +| `plugin.remove` | Remove a package | `{name, version?}` | `{}` | Accepted remove settles or restores | `missing`, `load_failed`, `write_failed`, `closed` | +| Startup reconcile | Remove directories and records that are not installed; restore the default configuration | internal | — | None | `record_read`, `record_write`, `cleanup` | +| Content registration | Register or withdraw a package's MCP, Hooks, Skills and UI content | internal | `refusal` | The owner's content call can be cancelled | the content owners' refusals are values | +| `plugin` tool | Map one model command to a process operation | `{command, args}` | tool result content | The tool call's cancel stops the operation | `usage`, the owner's errors | + +#### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid_source`, `invalid_manifest` | Fix the source or manifest; nothing was installed | +| `exists`, `missing` | Re-read the list; choose another name/version or install first | +| `load_failed`, `restart_required` | The package record is written but the rows did not load; report the required restart/reload | +| `content_refused` | The content owner refused; the package record is rolled back or the content is left out as the owner states | +| `write_failed` | The record or files could not settle; report the partial state and its recovery | +| `usage` | Fix the tool command | +| `closed` | The owner is unloading; use the replacement generation | + +#### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| Install/update | Fetch, validate, write the package directory, register content, write the record, load the rows | Accepted work settles or rolls back; no half record | The caller's row unload does not undo an accepted package | In-flight work settles; the next generation reads the records | Files and records by `PluginManager`; rows by rutis-loader; content by the owners | +| Enable/disable/reload | Write the record, replace or reload the loader rows, withdraw/register content | Accepted operation settles | The caller's row unload leaves the package state | New calls refused; the next generation reads the records | Record by `PluginManager`; rows by rutis-loader | +| Remove | Withdraw content, remove the rows, remove the directory, remove the record | Accepted remove settles or restores | The caller's row unload leaves the package state | In-flight removes settle | Content by the owners; rows by rutis-loader; files/record by `PluginManager` | +| `plugin` tool | Dispatch the command to the process operation and return its value | The tool call's cancel stops the operation | The Session row unload stops its tool | Pending calls end `closed` | Operation by `PluginManager`; tool result by `PluginTools` | + +### Exceptions with reasons + +- The loader's rows are rutis-loader's state; this contract does not define its data face. The loader is outside the plugin board's scope. +- `UiExtensions` owns the UI content; `PluginManager` only gives it the manifest content. It is outside this contract. +- `Owners` is a private object of `PluginManager`; its content refusals are values kept by the owner. +- `PluginTools` holds the process owner's operation or callback, not the `Manager` object. The Session part is registered by the process row and withdrawn with it; the operation is the shared lifecycle boundary. +- The `plugin.*` methods are management methods (#2095), not a second `pluginService` face. +- The package's code rows are loaded by rutis-loader; `PluginManager` does not hold a row handle. The loader returns row values/status. + +### Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | `PluginManager` is one process part; `PluginTools` is a Session part. Neither folds Timeline state; they are not Capabilities. | +| §2 scopes | Package records and operations are process; the tool is Session. | +| §3 orthogonality | The content owners decide content; the loader decides rows; `PluginManager` composes their operations and owns the package record. | +| §4 rule 1 | No plugin command Timeline event. | +| §4 rule 2 | No handoff: the `Manager` object does not reach the Session; the content and row values are data. | +| §4 rule 3 | Installs run in the owner's tasks; the model tool runs in the Session's tool task. | +| §4 rule 4 | The vocabulary is packages, records, content refusals and rows; no client or model business appears. | +| §4 rule 5 | No batches. | +| §4 rule 6 | The tool result is the only text the model reads; the owner's install output is a value. | +| §4 rule 7 | Callers use `plugin.*`, the `plugin` tool and the content owners; no caller holds `Manager` or `Owners`. | +| §4 rule 8 | Requirements to #2016, #2019, #2026, #2027, #2032, #2095 are listed below. | +| §4 rule 9 | No Timeline fact. | +| §7 callbacks and ids | Package names/versions and progress values cross; the `Manager` object does not. The tool gets an operation/callback. | +| §7 one change | The `Manager` handoff and the public `PluginTools` field are removed in the same change that migrates the tool. | +| ADR 002 D1 | Process `PluginManager`; Session `PluginTools`. | +| ADR 002 D2 | No wrapper: `plugin.*` are management methods of the owner; no facade. | +| ADR 002 D3 | Extensions depend on the plugin manager; the loader and content owners are separate. | +| ADR 002 D4 | `plugins.json` and the default configuration are the owner's structural configuration. | +| ADR 002 D5 | Operations, values and ids are language-neutral; the Rust binding is the appendix. | + +### Requirements raised to mechanism owners + +- #2016: `PluginFiles` must provide the package file reads/writes and the `plugins.json` record operations the owner uses; if the record stays a FileStorage `update`, the FileStorage contract covers it. +- #2019: `RuntimeManager` must provide the npm/Python runtime install/start/settle operations the package declares; the plugin manager records the requirement. +- #2026: `ToolRegistry.register` must accept the `plugin` tool source with a process operation/callback. +- #2027: the `plugin` tool's call is an ordinary tool call; Permission decides it; no plugin-specific approval is added. +- #2032: HostPlatform must provide the git source fetch with cancellation; npm is RuntimeManager's. +- #2095: `ManagementMethods.register` must host the `plugin.*` namespace; the local client and the `dimcode plugin` commands use it. + +### Binding appendix + +`plugin.*` are management methods (#2095) on `PluginManager`; `PluginTools` registers the `plugin` tool through #2026. The `Manager` is `pub(crate)`; the Session tool holds an operation/callback. + +```rust +tool_registry.register( + ctx, + "plugin", + plugin_tool_spec(), + move |call, cancelled| manager.call(call.command, call.args, cancelled), +); +``` + +`manager` is the process owner's operation/callback, not the `Manager` object. The request, reply and error types are the typed structures in `plugin_manager.rs` and the management module. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. + + PluginManager keeps the plugin configuration of a host: which plugins are installed, where they came from, which plugin each name uses, and which names are turned off. It keeps this configuration in its own file, `plugins.json`, in Dim's own format. It keeps no runtime state, except, in memory, the content it refused itself (§3.7). Whether a plugin is loaded, running or failed is rutis' state, read from rutis-loader. What content an owner holds (skills, MCP servers, hooks, client UI) is that owner's state. PluginManager carries out a configuration change by giving commands to the owners: rutis-loader for plugin code, and SkillsCatalog, Mcp, Hooks and UiExtensions for content. Each owner decides and keeps its own state. A plugin is a directory with a manifest. It may carry code (a rutis plugin in TypeScript or Python), content (skills, MCP configuration, hooks, client UI), or both. Plugins are identified by **name**. Several plugins with the same name may be installed, but only one of them is used at a time. Turning another one on replaces the one in use. This is how a built-in plugin is replaced. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..b6d001529a 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -45,12 +45,13 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [light-ocr](LightOcr.md) | optional plugin: the `ocrHelper` description and the out-of-process helper, supplying Modality's `local/pp-ocr` target | — | — | P3; [#1158](https://github.com/arcships/dim/issues/1158) | | [Skills](Skills.md) (installation) | existing SkillsCatalog: preview of a local or Git source, selective installation into the user root, update and confirmed removal of loose Skills | — (discovery, enablement and the `skill` tool already belong to the Skills capability) | — | #740 | | [PluginManager](PluginManager.md) | plugin configuration (`plugins.json`), install, loader rows of plugin code, content registration | `PluginTools` (`plugin` tool) | — | M1 | +| [MCP](Mcp.md) | `Mcp`: MCP configuration and content, connection definitions, OAuth credentials and client operations | `McpSession`: connection generations, tools and views; `TemporaryMcp`: temporary bindings | — | #2022 | | [RuntimeManager](RuntimeManager.md) | the Node and Python runtimes of plugin code: pinned download, verification, start; `runtime.*` | — | — | M1 (#476) | ## By scope | Scope | Parts | | --- | --- | -| Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | -| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | +| Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, MCP, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | +| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, MCP (`McpSession`, temporary bindings), Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | | Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index 6b5e13b864..adbe13eb4a 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -2,6 +2,203 @@ Status: Draft. Delivery status is tracked in the issue, not here. +## Target contract + +Scope: process, Session and branch. Issue: #2022. + +The owners are `SkillsCatalog` (process), `Skills` (Session), `SkillsBranch` (branch), `SkillContent` (Session content instance) and `SkillContentInstances` (the group template). The existing installation design below is `SkillsCatalog`'s current behavior; the discovery, enablement and Session view sections of the Skills capability stay as [Skills](../../architecture/rust-agent/plugins/Skills.md) describes. + +### Use and scope: responsibility split + +`SkillsCatalog` owns: + +- **Roots and enablement.** The user, plugin and project Skill roots, the enabled set, the project table, the Settings sources `skills` and `skills-projects` (through the Settings owner), and the `catalog_changed` generation. +- **Installation.** Preview, install, update, remove and the install records and files; the source fetch and the user root. +- **Content registration.** The Skill root a plugin package carries, the holding plugin and the issues value. +- **Reads.** The Session view value `query(cwd)` and the management methods `skills.catalog`, `skills.set_enabled`, `skills.refresh`, `skills.preview`, `skills.install`, `skills.update`, `skills.remove`, `skills.installations`. + +`Skills` owns: + +- **The Session view.** The list, descriptions and errors folded from `SkillsCatalog.query`, published as `SessionSkills`. +- **Content instances.** The `SkillContent` rows it mounts and unmounts through `SessionScope`, and the `skill` tool, prompt source and `skills` submit check registered with the Session's registries. + +`SkillsBranch` owns: + +- **The list.** `skillsBranch.list` returns the Session's published `SessionSkills` value; the branch part does not re-query the catalog. +- **The Prompt adoption.** When the list changes, it asks the Prompt owner to adopt the current list; it does not own the Prompt state. + +`SkillContent` is one immutable content instance; `SkillContentInstances` is the group template. Neither has a public surface. + +Callers keep: + +- The Skill's text, its source format and its repository selection; the installation selects and writes files, it does not author content. +- The model's `skill` tool use and the prompt composition; the Session part contributes the tool and the prompt source. +- The client UI around the catalog and the install preview. +- Permission and approval of a tool call; the `skill` tool is an ordinary tool. + +| Requirement (callers) | Compose from existing operations without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Register a package's Skills root | No: the root registry and issues are `SkillsCatalog`'s state | `register`, `withdraw`, `plugins`, `issues` | +| Edit the catalog, enablement or projects | No: the merged view and the Settings write are the owner's state | `skills.catalog`, `skills.set_enabled`, `skills.refresh` | +| Preview, install, update or remove a Skill | No: the fetch, selection, files and records are the owner's state | `skills.preview`, `skills.install`, `skills.update`, `skills.remove` | +| Read the Session's Skills view | No: the Session owns the folded view and its generation | `SkillsCatalog.query` + `catalog_changed`; `Skills` folds `SessionSkills` | +| Mount a Skill's content in a Session | No: the instance is a Session resource with its own lifecycle | `SessionScope.mount` with the `skill-content` group; `Skills` owns the instance | +| List the current Skills on a branch | No: the branch must read the Session's published value, not re-query the catalog | `skillsBranch.list` | +| Adopt a changed list into the Prompt | No: the Prompt owner owns the composition; the branch requests it | the Prompt owner's configure operation | +| Load a Skill from the `skill` tool | No: the tool result and the content lookup are the Session's view | the `skill` tool registered by `Skills` | + +### Caller example + +`PluginManager` registers a package's Skills root: + +```rust +let issues = skills_catalog.register(ctx, plugin, dir, document).await?; +report_issues(plugin, issues); // the package is installed; the root is refused or partly scanned +``` + +The local client previews and installs: + +```rust +let preview = skills.preview(source, selection, cancelled.clone()).await?; +let installed = skills.install(preview.token, selection, cancelled).await?; +``` + +`Skills` mounts one content instance: + +```rust +let content = skills_catalog.content(skill_id).await?; +let instance = session_scope.mount("skill-content", content.id, content.data, cancelled).await?; +tool_registry.register(ctx, "skill", skill_tool(instance)); +prompt_registry.register(ctx, "skills", skill_source(instance)); +``` + +`SkillsBranch` reads the list and asks the Prompt owner to adopt it: + +```rust +let list = session_skills.list(); // the published value +if list.generation != seen { + prompt.configure(list); +} +``` + +### Own contract + +#### Dependencies + +`SkillsCatalog` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`), FileStorage (`root_path`, `write`, `remove`, `list` for install files), HostPlatform (the source fetch and the user home), and the management-methods mechanism of #2095. `Skills` uses SessionScope (`mount`, `unmount`, `config`, `identity`, `activated`, `closing`), `ToolRegistry`, `PromptRegistry` and `SubmitChecks` (#2026), and the SkillsCatalog's private `query`/`catalog_changed` operations. `SkillsBranch` uses the branch's Prompt owner and the Session's published value. `SkillContent` is mounted through SessionScope; `SkillContentInstances` is its group template. + +#### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `skillsCatalog.register` | Register a package's Skill root | `{plugin, dir, document}` | `{}` or `{issues}` | Accepted write is not cancelled | `invalid_manifest`, `unreadable`, `settings_write`, `settings_conflict`, `closed` | +| `skillsCatalog.withdraw` | Withdraw a package's root | `{plugin}` | `{}` | Accepted write is not cancelled | `closed` | +| `skillsCatalog.plugins` | The packages holding Skill roots | `{}` | `{plugins}` | None | `closed` | +| `skillsCatalog.issues` | The scan issues of a package | `{plugin}` | `{issues}` | None | `closed` | +| `skillsCatalog.query` | The Session's view source for a cwd | `{cwd}` | `{skills, generation, errors}` | The read can be cancelled | `unavailable`, `closed`, `cancelled` | +| `skills.catalog` | The client catalog | `{project?}` | `{skills, projects, invalid}` | The read can be cancelled | `invalid`, `closed`, `cancelled` | +| `skills.set_enabled` | Enable or disable a Skill or project | `{id, enabled, project?}` | `{}` | Accepted write is not cancelled | `missing`, `invalid`, `conflict`, `closed` | +| `skills.refresh` | Rescan the roots | `{}` | `{generation}` | None; the scan is the owner's | `closed` | +| `skills.preview` | Preview a local or Git source | `{source, selection}` | `{token, entries, invalid}` | The read can be cancelled; the token expires | `invalid_source`, `fetch_failed`, `too_large`, `cancelled`, `closed` | +| `skills.install` | Install the selected entries | `{token, selection}` | `{installed}` | Accepted work is not cancelled; it settles or restores | `expired`, `invalid_selection`, `exists`, `conflict`, `write_failed`, `closed` | +| `skills.update` | Update installed entries | `{id, revision?}` | `{installed}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `conflict`, `write_failed`, `closed` | +| `skills.remove` | Remove installed entries | `{id}` | `{}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `delete_failed`, `closed` | +| `skills.installations` | The install records | `{}` | `{installations}` | None | `closed` | +| `Skills` view | The `SessionSkills` value and its generation | `{}` | `{list, generation}` | The Session close stops the read | `unavailable`, `closed` | +| `skill` tool | Read one Skill's content for the model | `{name}` | tool result content | The tool call's cancel | `unknown`, `disabled`, `unavailable`, `invalid` | +| `skills` check | Check operator input before it is written | `{input}` | context or block | The entry's cancel | `block`, `warnings`, `proceed` | +| `skillsBranch.list` | The branch's current list | `{}` | `{skills}` | The branch close stops the read | `unavailable`, `closed` | +| Prompt adoption | Ask the Prompt owner to adopt the list | `{list}` | `{}` | The branch close stops the request | the Prompt owner's errors | + +The `SkillsCatalog`'s management methods are registered through #2095; the `skillsCatalog` data face carries the four content operations. The `query` and `catalog_changed` are the private Session-facing read; no other owner calls them. The `Skills` Session part has no public service. + +#### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid_manifest`, `invalid_source`, `invalid_selection` | Fix the package, source or selection; nothing was written | +| `unreadable`, `fetch_failed`, `too_large` | Report the source error; the catalog is unchanged | +| `missing`, `expired`, `unmanaged` | Re-read the catalog or preview; the entry is gone or not owned | +| `exists`, `conflict` | Re-read and decide; the write did not happen | +| `write_failed`, `delete_failed` | The accepted work could not settle; report the partial state and its recovery | +| `settings_write`, `settings_conflict` | Retry after Settings is available, or report the conflict | +| `unknown`, `disabled`, `unavailable` | Report the Skill view or tool error | +| `block`, `warnings`, `proceed` | The check's result; `block` stops the input | +| `cancelled` | Nothing was committed; the read or preview stopped | +| `closed` | The owner is unloading; use the replacement generation | + +#### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| Content register/withdraw | Validate the root, scan it within the limit, write the Settings document, update the registry | Accepted write completes | The plugin row unloads; its root is withdrawn | New registrations refused; the next generation reads the documents | Settings write and registry by `SkillsCatalog`; scan by `SkillsCatalog` | +| `query` / `Skills` view | Scan the roots, fold the enabled list, publish `SessionSkills` and its generation | The read stops; the last value stays | The Session's view ends; the branch sees unavailable | The Session's view is rebuilt from the next catalog generation | Scan by `SkillsCatalog`; view by `Skills` | +| Preview | Fetch to a bounded staging area, parse, return a token and entries | The fetch and staging stop; the token is discarded | The preview token expires with the caller | Staging is cleaned up | Staging by `SkillsCatalog` | +| Install/update/remove | Validate the selection, write the files and records, settle the batch | Accepted work is not cancelled; it finishes or restores | The caller's row unload does not undo an accepted batch | In-flight batches settle; the next generation reads the records | Files and records by `SkillsCatalog` | +| Content instance | `Skills` mounts the `SkillContent` child after `activated`, registers the tool and prompt source | A dropped mount unmounts the child | The Session's instances unmount | New mounts refused; every instance unmounts | Instance by `Skills` through `SessionScope.unmount` | +| `skill` tool | Resolve the content instance and return the text | The tool call's cancel stops the read | The row unload stops its tool | Pending calls end `closed` | Content by the instance; result by the tool caller | +| Branch list | Read the published `SessionSkills`; no catalog query | The read stops | The branch's row unload stops it | The next value is published by `Skills` | Value by `Skills`; read by `SkillsBranch` | +| Prompt adoption | The branch asks the Prompt owner to configure the list | The branch close stops the request | The branch row unload ends the adoption | The Prompt owner's state decides | Prompt by the Prompt owner; request by `SkillsBranch` | + +### Exceptions with reasons + +- `SkillContent` is an immutable content instance mounted through `SessionScope`; its lifecycle is the Session's. `SkillContentInstances` is the group template; neither has a public name. +- Install/update/remove do not cancel after acceptance: the files and records must finish or restore; the caller sees the batch settle or the recovery error. The design §6 wording about cancellation is corrected by this contract. +- `SkillsCatalog.query` and `catalog_changed` are a private Session-facing read, not a public face. `Skills` owns the folded view; `SkillsBranch.list` is the public list. +- `SkillsBranch` asks the Prompt owner's configure operation; the old `ConfigureControl` interface is deleted. The branch part does not own the Prompt state. +- `skills.install`'s token is a value with an expiry; it is not a handle and carries no authority. +- The `skills.*` methods are management methods (#2095), not a second `skillsCatalog` face. + +### Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | `SkillsCatalog` process; `Skills` Session; `SkillsBranch` branch. The branch part folds the published list and writes no Timeline event; it is not a Capability. | +| §2 scopes | Installation and enablement are process; the view, content instances and tool are Session; the list read is branch. | +| §3 orthogonality | The Session part reads the catalog's private value; the branch reads the Session's published value; no catalog re-query in the branch. | +| §4 rule 1 | No install or catalog command event; the Settings and install records are the owners' state. | +| §4 rule 2 | No handoff: content instances are mounted by `Skills`; tokens and records are values. | +| §4 rule 3 | Installs and previews run in the owner's tasks; the Session's view is published as a value. | +| §4 rule 4 | The vocabulary is roots, entries, installations, generations and views; no client or package business appears. | +| §4 rule 5 | No batches. | +| §4 rule 6 | Skill text reaches the model only through the `skill` tool result or the prompt source; no other path. | +| §4 rule 7 | Callers use `skillsCatalog`, `skills.*`, `skill`, `skillsBranch.list` and the Prompt configure; no caller holds `SkillContent`, `SkillContentInstances` or the catalog's private state. | +| §4 rule 8 | Requirements to #2080, #2026, #2027, #2032, #2093, #2094 are listed below. | +| §4 rule 9 | No Timeline fact. | +| §7 callbacks and ids | The view generation, install token and installation id cross as values; content instances stay with the Session. | +| §7 one change | The old `SkillsCatalogBinding`, `ConfigureControl` and public Rust-only management methods are removed in the same change that migrates every caller. | +| ADR 002 D1 | Process `SkillsCatalog`; Session `Skills`/`SkillContent`; branch `SkillsBranch`. | +| ADR 002 D2 | No wrapper: `skillsCatalog` is on `SkillsCatalog`; `skillsBranch` on `SkillsBranch`. | +| ADR 002 D3 | Extensions depend on the SkillsCatalog; the Session part owns its content. | +| ADR 002 D4 | Roots and Settings sources are structural; no assembly business setting. | +| ADR 002 D5 | Operations, values and ids are language-neutral; the Rust binding is the appendix. | + +### Requirements raised to mechanism owners + +- #2080: FileStorage `root_path`, `write`, `remove` and `list` for the install files under the user root; no new operation. +- #2026: `ToolRegistry.register` must accept the `skill` tool source; `PromptRegistry.register` must accept the Skills prompt source; `SubmitChecks.register` must accept the `skills` check. +- #2027: the Prompt owner's configure operation must replace `ConfigureControl`; the branch passes the current `SessionSkills` value. +- #2032: HostPlatform must provide the user home value and the source fetch command (git/HTTP) with cancellation. +- #2093: SessionScope `mount`/`unmount` with the `skill-content` group and the `config`/`identity`/`activated`/`closing` values. +- #2094: Settings `skills`/`skills-projects` sources and `SkillSettingsHost`; the existing operations cover the read and write. + +### Binding appendix + +`skillsCatalog` is on `SkillsCatalog`; `skillsBranch.list` on `SkillsBranch`; the `skills.*` methods are registered through #2095. `SkillsCatalogBinding` does not exist. `Skills`' tool, prompt source and check are private registrations; `SkillContent` is a private instance mounted through SessionScope. + +```rust +#[rutis::service(name = "skillsCatalog")] +impl SkillsCatalog { + pub async fn register(&self, ctx: &Ctx, plugin: String, dir: String, document: SkillDocument, cancelled: CancelledFn) -> Result; + pub async fn withdraw(&self, ctx: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), SkillContentError>; + pub fn plugins(&self) -> Vec; + pub fn issues(&self, plugin: &str) -> SkillIssues; +} +``` + +`SkillsBranch`'s list is a data face; the request is empty and the reply is the current `SessionSkills` value. The install and management operations are the typed requests and replies in `skills/catalog.rs`; the install token and installation id are values. + + Scope: process. Issue: [#740](https://github.com/arcships/dim/issues/740). Rules: [design rules](../../architecture/rust-agent/principles.md), [ADR 002](../../adr/002-plugin-scope.md). From fceb9ce31ee6cd213939aa2dcd8d22a0e41949b2 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 15:16:49 +0800 Subject: [PATCH 2/8] design(content-owners): align Hooks with #2028 and defer undefined owner contracts --- docs/design/plugins/Hooks.md | 16 ++++++++-------- docs/design/plugins/Mcp.md | 3 ++- docs/design/plugins/PluginManager.md | 10 +++++----- docs/design/plugins/Skills.md | 4 ++-- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 65a28e9926..ae8bb73d20 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -41,8 +41,8 @@ Callers keep: | A hook point reads the current sources | No: the project file read and the source merge are the owner's knowledge | `sources(cwd)` | | The Session runs a hook command | No: the process, timeout and settlement are the Session's resource | `HooksSession`'s runner; the command is private | | Operator input is checked before it is written | No: the check must run before the entry writes, and the entry owner provides the registration point | `submitChecks.register("hooks")`; the check returns a value | -| A tool call gets hook advice | No: Permission owns the admission; Hooks contributes through its advisor registration | `Permission.registerAdvice`; the advisor returns deny/ask/allow | -| Hooks answers an approval | No: Approval owns the question and the decision | `Approval.respond` | +| A tool call gets hook advice | No: Permission owns the admission; Hooks contributes through its advisor registration | `Permission.advise`; the advisor returns deny/ask/allow | +| Hooks answers an approval | No: Approval owns the question and the decision | `Approval.decide` | | Hook context or diagnostics reaches the branch | No: branch input is the branch owner's entry | `Branch.input` with source `hooks` | ### Caller example @@ -72,8 +72,8 @@ submit_checks.register(ctx, "hooks", move |input, cancelled| { `HooksBranch` registers advice, answers an approval and writes an observation: ```rust -permission.register_advice(ctx, "hooks", move |call, cancelled| advise(hook_sources(), call, cancelled)); -approval.respond(approval_id, decision); +permission.advise(ctx, "hooks", move |call, cancelled| advise(hook_sources(), call, cancelled)); +approval.decide(approval_id, decision); branch.input(source, HookInput::observation(text)); ``` @@ -81,7 +81,7 @@ branch.input(source, HookInput::observation(text)); #### Dependencies -`HooksSettings` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`) and FileStorage (`read` for `.dimcode/hooks.json`). `HooksSession` uses SessionScope (`config`, `identity`, `activated`, `closing`, `withHold`), the agent-crate `HookSourcesHost` binding, `submitChecks` and HostPlatform (`spawn`, `wait`, `kill`, `settle`). `HooksBranch` uses the branch's `HooksRuntime`, `Permission.registerAdvice`, `Approval.respond`, `Branch.input`, and the public events it folds. `HooksRuntime` is not a public service; the Session and branch parts are the same feature. +`HooksSettings` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`) and FileStorage (`read` for `.dimcode/hooks.json`). `HooksSession` uses SessionScope (`config`, `identity`, `activated`, `closing`, `withHold`), the agent-crate `HookSourcesHost` binding and `submitChecks`. HostPlatform (#2032) has no target contract; the command-execution dependency is recorded on #2032 and no interface is defined here. `HooksBranch` uses the branch's `HooksRuntime`, `Permission.advise`, `Approval.decide`, `Branch.input`, and the public events it folds. `HooksRuntime` is not a public service; the Session and branch parts are the same feature. #### Operations @@ -125,7 +125,7 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u | Command | Build the payload, spawn through HostPlatform, write stdin, wait with the handler timeout, settle the process tree | The cancel kills the process tree and settles it | The Session's row unload cancels its commands | Pending commands end `closed`; every process is settled | Command process by `HooksSession`; the work's future by the calling row | | Submit check | Read the sources, run the `UserPromptSubmit` handler, return context or block | The entry's cancel stops the check | The check registration is withdrawn with the Session row | The entry does not write after a closed check | Check by `HooksSession`; input write by the entry owner | | Advice | Read the sources, run the `PreToolUse` handler, return deny/ask/allow | The admission's cancel stops the advisor | The advisor registration is withdrawn with the branch | Permission's admission sees the failure mapping | Advice by `HooksBranch`; admission by Permission | -| Approval answer | Run the `PermissionRequest` handler, call `Approval.respond` | The live answer's cancel ends the answer | The branch row unload drops the answer | Approval's own errors | Approval by Approval; answer by `HooksBranch` | +| Approval answer | Run the `PermissionRequest` handler, call `Approval.decide` | The live answer's cancel ends the answer | The branch row unload drops the answer | Approval's own errors | Approval by Approval; answer by `HooksBranch` | | Observation | Write `Branch.input` with source `hooks` | The branch close stops the write | The branch row unload ends writes | The branch's input entry decides | Input by the branch owner; the hook result by `HooksBranch` | ### Exceptions with reasons @@ -164,8 +164,8 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u ### Requirements raised to mechanism owners - #2026: `submitChecks.register` must accept the `hooks` check with a value result; the operator-input entries must call it before writing. -- #2027/#2028: `Permission.registerAdvice` must give the advisor the call source and the admission decision; `Approval.respond` must accept a decision; `Branch.input` must accept `hooks` observations. -- #2032: HostPlatform `spawn`, `wait`, `kill`, `settle` must carry stdin, a handler timeout and tree cancellation for hook commands. +- #2027/#2028: `Permission.advise` registers the advisor with the call source and the admission decision; `Approval.decide` accepts a decision; `Branch.input` must accept `hooks` observations. +- #2032: HostPlatform's target contract is pending; the requirement comment records the intent (command execution with stdin, handler timeout and tree cancellation); no interface is defined here. - #2094: Settings `register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`; no new operation. - #2080: FileStorage `read` for `.dimcode/hooks.json`; no new operation. - #2093: SessionScope `config`, `identity`, `activated`, `closing`, `withHold`; no new operation. diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md index 8457a2fbdd..12b70cc5c8 100644 --- a/docs/design/plugins/Mcp.md +++ b/docs/design/plugins/Mcp.md @@ -99,7 +99,7 @@ let binding = temporary.attach(ctx, server, cancelled).await?; ### Dependencies -`Mcp` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`), FileStorage (`read` for `.mcp.json` through the project root), and the management-methods and connection mechanisms of #2095. `McpSession` uses SessionScope (`mount`, `unmount`, `withHold`, `activated`, `closing`, `config`, `identity`), `toolRegistry` and `sessionFiles` (#2026/#2018), and `Mcp`'s values and registry operations. `TemporaryMcp` uses SessionScope, `sessionMethods` (#2026), `toolRegistry` and the `Mcp` definition values. `McpAuth` is a private process service of `Mcp`; the child rows that need a credential receive the service name and the entry id, not the credential value. +`Mcp` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`), FileStorage (`read` for `.mcp.json` through the project root), and the management-methods and connection mechanisms of #2095. `McpSession` uses SessionScope (`mount`, `unmount`, `withHold`, `activated`, `closing`, `config`, `identity`), `toolRegistry` and `sessionFiles` (#2026/#2018), and `Mcp`'s values and registry operations. The `McpServer` child's process uses HostPlatform (#2032), whose target contract is pending; the requirement is recorded on #2032 and no interface is defined here. `TemporaryMcp` uses SessionScope, `sessionMethods` (#2026), `toolRegistry` and the `Mcp` definition values. `McpAuth` is a private process service of `Mcp`; the child rows that need a credential receive the service name and the entry id, not the credential value. ### Operations @@ -202,6 +202,7 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl - #2026: `toolRegistry.register` must accept a Session-owned tool source with a handler that holds a connection id; `sessionMethods.register` must accept `session.mcp_temporary.*`. - #2093: `SessionScope.mount`/`unmount` must accept the `mcp-server` group and a definition value; `withHold`, `activated` and `closing` are used as defined. - #2095: `ManagementMethods.register` must host the `mcp.*` namespace; `Connection` calls `mcpSession.state/refresh/widget/call`. +- #2032: HostPlatform's target contract is pending; the `McpServer` child uses its process operations; the requirement comment records the intent and no interface is defined here. - #2080: FileStorage `read` for `.mcp.json` under the project root; no new operation. - #2094: Settings `register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`; no new operation. diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index 3ea68a995b..a5878de3d4 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -16,7 +16,7 @@ The owners are `PluginManager` (process) and `PluginTools` (Session). `Owners` a - **Package operations.** `plugin.list`, `plugin.install`, `plugin.enable`, `plugin.disable`, `plugin.reload`, `plugin.update`, `plugin.remove`. - **Content registration.** The manifest's MCP, Hooks and Skills content is given to those owners; the UI content is given to `UiExtensions`. The refusal is a value from the content owner and is kept for the package. - **Code rows.** The plugin code rows it creates, turns on, replaces and removes through rutis-loader; the loader is a separate owner and its data face is not part of this contract. -- **Runtime acquisition.** The Node and Python runtimes a plugin declares are requested from `RuntimeManager`; the package record does not own the runtime. +- **Runtime acquisition.** The Node and Python runtimes a plugin declares are requested from `RuntimeManager`; the runtime operations are pending #2019's contract; the package record does not own the runtime. `PluginTools` owns: @@ -67,7 +67,7 @@ if let Some(reason) = refusal { #### Dependencies -`PluginManager` uses FileStorage or PluginFiles for `plugins.json` and the package files (#2080/#2016), `RuntimeManager` for the npm/Python runtime (#2019), rutis-loader for the code rows (out of scope), MCP/Hooks/Skills/UiExtensions for content, and the management-methods mechanism of #2095. `PluginTools` uses `ToolRegistry` (#2026) and the process owner's operation or callback. +`PluginManager` uses FileStorage's defined operations for a record document (#2080); `PluginFiles` (#2016), `RuntimeManager` (#2019) and HostPlatform (#2032) have no target contracts. Their operations are to be defined by their contracts; the #2022 requirement comments record the intent only; no interface is invented here. rutis-loader owns the code rows (out of scope); MCP/Hooks/Skills/UiExtensions own content; #2095 owns management methods. `PluginTools` uses `ToolRegistry` (#2026) and the process owner's operation or callback. #### Operations @@ -140,11 +140,11 @@ if let Some(reason) = refusal { ### Requirements raised to mechanism owners -- #2016: `PluginFiles` must provide the package file reads/writes and the `plugins.json` record operations the owner uses; if the record stays a FileStorage `update`, the FileStorage contract covers it. -- #2019: `RuntimeManager` must provide the npm/Python runtime install/start/settle operations the package declares; the plugin manager records the requirement. +- #2016: `PluginFiles` has no target contract; the requirement comment records the intent (package files and `plugins.json` record), not an interface; the interface is to be defined by #2016. +- #2019: `RuntimeManager` has no target contract; the requirement comment records the intent (runtime install/start/settle), not an interface. - #2026: `ToolRegistry.register` must accept the `plugin` tool source with a process operation/callback. - #2027: the `plugin` tool's call is an ordinary tool call; Permission decides it; no plugin-specific approval is added. -- #2032: HostPlatform must provide the git source fetch with cancellation; npm is RuntimeManager's. +- #2032: HostPlatform has no target contract; the requirement comment records the intent (git source fetch with cancellation), not an interface; npm is RuntimeManager's. - #2095: `ManagementMethods.register` must host the `plugin.*` namespace; the local client and the `dimcode plugin` commands use it. ### Binding appendix diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index adbe13eb4a..b51d7cfd8b 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -85,7 +85,7 @@ if list.generation != seen { #### Dependencies -`SkillsCatalog` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`), FileStorage (`root_path`, `write`, `remove`, `list` for install files), HostPlatform (the source fetch and the user home), and the management-methods mechanism of #2095. `Skills` uses SessionScope (`mount`, `unmount`, `config`, `identity`, `activated`, `closing`), `ToolRegistry`, `PromptRegistry` and `SubmitChecks` (#2026), and the SkillsCatalog's private `query`/`catalog_changed` operations. `SkillsBranch` uses the branch's Prompt owner and the Session's published value. `SkillContent` is mounted through SessionScope; `SkillContentInstances` is its group template. +`SkillsCatalog` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`), FileStorage (`root_path`, `write`, `remove`, `list` for install files), and the management-methods mechanism of #2095. HostPlatform (#2032) has no target contract; the source-fetch and user-home dependency is recorded on #2032 and no interface is defined here. `Skills` uses SessionScope (`mount`, `unmount`, `config`, `identity`, `activated`, `closing`), `ToolRegistry`, `PromptRegistry` and `SubmitChecks` (#2026), and the SkillsCatalog's private `query`/`catalog_changed` operations. `SkillsBranch` uses the branch's Prompt owner and the Session's published value. `SkillContent` is mounted through SessionScope; `SkillContentInstances` is its group template. #### Operations @@ -178,7 +178,7 @@ The `SkillsCatalog`'s management methods are registered through #2095; the `skil - #2080: FileStorage `root_path`, `write`, `remove` and `list` for the install files under the user root; no new operation. - #2026: `ToolRegistry.register` must accept the `skill` tool source; `PromptRegistry.register` must accept the Skills prompt source; `SubmitChecks.register` must accept the `skills` check. - #2027: the Prompt owner's configure operation must replace `ConfigureControl`; the branch passes the current `SessionSkills` value. -- #2032: HostPlatform must provide the user home value and the source fetch command (git/HTTP) with cancellation. +- #2032: HostPlatform's target contract is pending; the requirement comment records the intent (user home value and source fetch with cancellation); no interface is defined here. - #2093: SessionScope `mount`/`unmount` with the `skill-content` group and the `config`/`identity`/`activated`/`closing` values. - #2094: Settings `skills`/`skills-projects` sources and `SkillSettingsHost`; the existing operations cover the read and write. From 4e73d32eb6485b898925eca69c31f9879770ea42 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 19:37:17 +0800 Subject: [PATCH 3/8] design(content-owners): remove superseded designs and the HookSourcesHost port --- docs/design/plugins/Hooks.md | 534 +-------------------------- docs/design/plugins/PluginManager.md | 349 +---------------- docs/design/plugins/Skills.md | 325 +--------------- 3 files changed, 14 insertions(+), 1194 deletions(-) diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index ae8bb73d20..d746644d88 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -6,7 +6,7 @@ Status: Ready ([#143](https://github.com/arcships/dim/issues/143)); maintainer d Scope: process, Session and branch. Issue: #2022. -The owners are `HooksSettings` (process), `HooksSession` (Session) and `HooksBranch` (branch). `HooksRuntime` is a private Session service; `HookSourcesHost` is the agent-crate port that binds the owner's one reader. The feature's event points, document shape and script protocol stay as this document describes; this section replaces the public-surface decisions. +The owners are `HooksSettings` (process), `HooksSession` (Session) and `HooksBranch` (branch). `HooksRuntime` is a private Session service. The feature's event points, document shape and script protocol stay as this document describes; this section replaces the public-surface decisions. ### Use and scope: responsibility split @@ -21,7 +21,7 @@ The owners are `HooksSettings` (process), `HooksSession` (Session) and `HooksBra - **Command execution.** The Session's `HooksRuntime`, the command processes, their stdin payloads, timeouts, cancellation and settlement. - **Submit check.** The `hooks` check registered with `submitChecks` for operator input. The check writes no input; it returns the context or a block. -- **Source read.** It calls the `HookSourcesHost` binding; it does not build a second reader. +- **Source read.** It calls `hooksService.sources`; the data face is the only reader. `HooksBranch` owns: @@ -81,7 +81,7 @@ branch.input(source, HookInput::observation(text)); #### Dependencies -`HooksSettings` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`) and FileStorage (`read` for `.dimcode/hooks.json`). `HooksSession` uses SessionScope (`config`, `identity`, `activated`, `closing`, `withHold`), the agent-crate `HookSourcesHost` binding and `submitChecks`. HostPlatform (#2032) has no target contract; the command-execution dependency is recorded on #2032 and no interface is defined here. `HooksBranch` uses the branch's `HooksRuntime`, `Permission.advise`, `Approval.decide`, `Branch.input`, and the public events it folds. `HooksRuntime` is not a public service; the Session and branch parts are the same feature. +`HooksSettings` uses Settings (`register`, `read`, `change`, `authorize_project`, `authorized_projects`, `declared_sources`) and FileStorage (`read` for `.dimcode/hooks.json`). `HooksSession` uses SessionScope (`config`, `identity`, `activated`, `closing`, `withHold`), `hooksService.sources` and `submitChecks`. HostPlatform (#2032) has no target contract; the command-execution dependency is recorded on #2032 and no interface is defined here. `HooksBranch` uses the branch's `HooksRuntime`, `Permission.advise`, `Approval.decide`, `Branch.input`, and the public events it folds. `HooksRuntime` is not a public service; the Session and branch parts are the same feature. #### Operations @@ -101,7 +101,7 @@ branch.input(source, HookInput::observation(text)); | `HooksBranch` approval | Answer an approval question | `{approvalId, decision}` | `{}` | The live answer's cancel | `Approval`'s errors | | `HooksBranch` observation | Write hook context or diagnostics to the branch | `{input}` | `{}` | The branch close cancels the write; the owner rechecks | none; only diagnostics | -The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` use it directly. The `HookSourcesHost` port is the agent-crate binding of `hooksService.sources`; the port and the data face share one reader. The `SettingsHookSources` duplicate is deleted. +The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` use it directly. `hooksService.sources` is the only source read; the `SettingsHookSources` duplicate is deleted. #### Errors @@ -131,7 +131,6 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u ### Exceptions with reasons - `HooksRuntime` is the Session's private runner. `HooksSession` and `HooksBranch` are one feature; the command processes and their settlement stay in the Session part; the runtime has no public name. -- `HookSourcesHost` is the agent-crate port. It binds `HooksSettings.sources`; the port and the data face share the one reader; the project file is read through FileStorage. - Hook commands run because they are configured; they need no host-local approval (AGENTS rule 11). `PreToolUse` only advises Permission; the tool call's approval stays with Approval. - `UserPromptSubmit` runs only at the operator-input entries, before the write; other inputs do not run it. - `HooksBranch` writes observations through `Branch.input`; it does not write the Timeline directly. @@ -150,11 +149,11 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u | §4 rule 4 | The vocabulary is hook points, sources, handlers and decisions; no caller business appears. | | §4 rule 5 | No batches. | | §4 rule 6 | Hook context reaches the model only through adopted inputs or tool results. | -| §4 rule 7 | Callers use `hooksService`, `hooks.*`, the port, the check, the advisor, Approval and Branch input; no caller holds `SettingsHookSources` or a command process. | +| §4 rule 7 | Callers use `hooksService`, `hooks.*`, the check, the advisor, Approval and Branch input; no caller holds `SettingsHookSources` or a command process. | | §4 rule 8 | Requirements to #2026, #2027/#2028, #2032, #2094, #2080, #2093 are listed below. | | §4 rule 9 | The branch input is written after the command's decision; the Timeline commit is the branch owner's. | | §7 callbacks and ids | The submit check and the Permission advisor are callbacks by reference; no object or handle crosses. | -| §7 one change | The two readers are merged into one; the old `SettingsHookSources` and the session-port duplicate are deleted with the caller migration. | +| §7 one change | The two readers are merged into one; the old `SettingsHookSources` duplicate is deleted with the caller migration. | | ADR 002 D1 | Process `HooksSettings`; Session `HooksSession`; branch `HooksBranch`. | | ADR 002 D2 | No wrapper: `hooksService` is on `HooksSettings`; the port is a host binding, not a facade. | | ADR 002 D3 | Extensions depend on the Hooks owner; the agent crate uses the port. | @@ -172,7 +171,7 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u ### Binding appendix -`hooksService` is on `HooksSettings`; the `hooks.*` methods are registered through #2095; `HookSourcesHost` is the agent-crate port. `HooksRuntime` is `pub(crate)`. +`hooksService` is on `HooksSettings`; the `hooks.*` methods are registered through #2095. `HooksRuntime` is `pub(crate)`. ```rust #[rutis::service(name = "hooksService")] @@ -185,7 +184,7 @@ impl HooksSettings { } ``` -The Session and branch parts keep their internal types; the port's request and reply are `{cwd}` and `HookSources`. +The Session and branch parts keep their internal types; `hooksService.sources`' request and reply are `{cwd}` and `HookSources`. Hooks runs user-configured commands at fixed points of a Session's **business operations** and hands each command's decision to the owner of that operation. Dim reads only its own hooks configuration; it does not load Claude Code or Codex hook files. For easy migration, the document shape (event names, matcher groups, command handlers, `timeout`, `onFailure`) and the script protocol (stdin JSON, exit codes, decision and output fields) follow Claude Code and Codex, so existing scripts and pasted configuration work (Appendix G). @@ -194,244 +193,14 @@ Hooks never hooks infrastructure. The withdrawn design ([#21](https://github.com | Hook point | Business operation | Owner that decides | How the hook's decision reaches the owner | | --- | --- | --- | --- | -| `PreToolUse` | Admission of a tool call | Permission (called by Approval's `admit`) | During the admission decision, Permission calls the advisors registered with it; `HooksBranch` registers `hooks` (new generic advice registration, A.6.1) | +| `PreToolUse` | Admission of a tool call | Permission (called by Approval's `admit`) | During the admission decision, Permission calls the advisors registered with it; `HooksBranch` registers `hooks` through `Permission.advise` | | `PermissionRequest` | An approval question | Approval | Hooks answers through Approval's public `respond`, like a client (existing) | -| `UserPromptSubmit` | Submission of operator input | The operator-input entries: Rpc `session.submit` and `session.branch_create`, and InputQueue's `session.input.withdraw {steer}` | Before it writes, the entry calls the checks registered with the Session's `submitChecks`; `HooksSession` registers `hooks` (new generic submit-check table, A.6.2) | +| `UserPromptSubmit` | Submission of operator input | The operator-input entries: Rpc `session.submit` and `session.branch_create`, and InputQueue's `session.input.withdraw {steer}` | Before it writes, the entry calls the checks registered with the Session's `submitChecks`; `HooksSession` registers `hooks` through `submitChecks` | | `PostToolUse`, `PostToolUseFailure`, `Stop`, `SessionStart` | Context after a tool result, after a turn, at Session start | InputQueue (inputs) | Hooks writes branch input with source `hooks` (existing) | | `Notification` | An approval waiting for the user | — (observation) | Nothing reaches an owner (existing) | `UserPromptSubmit` is not a Timeline hook point: Session input is not necessarily the user's (Goal, Scheduler, Collaboration, ShellInput and Hooks itself write inputs), so the command runs only where operator input enters, before anything is written. Commands run through HostPlatform (the Session's resource node); a hook command waits only in Hooks' own tasks or in the caller's own task (Permission's admission decision runs in ToolExecutor's per-call admission task; a submit check runs in the Rpc call), never in a Dispatcher handler or under the commit lock. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is Appendix H. -### Owner check - -Each hook point was checked against what its owner exposes on `main`: - -| Hook point | Owner today | Gap | Resolution | -| --- | --- | --- | --- | -| `PreToolUse` | `Approval::admit(AdmitCall {source, call}, risk, cancel)` calls `Permission::decide(call, risk, cancel)` for the admission and again for the recheck after an allow; `decide` already awaits the command-rules port; a Deny becomes `HostError::failed(reason)`, the error text of the call's result | `decide` cannot ask anyone else, does not receive `source` (the call id is only in `AdmitCall.source`), and cannot tell the admission from the recheck | A.6.1: Approval passes `source` to the admission decision only; Permission calls its registered advisors there. ToolExecutor needs no change | -| `PermissionRequest` | `approval/request {approval_id, source, call, reason}`; `Approval::respond(approval_id, decision)` accepts the first consumed response, else `Unknown`/`Cancelled`/`Closed`; `approval/respond {approval_id, decision}` has no reason | No reason on a deny | Usable as is; a hook deny shows Approval's generic text (decision 7) | -| `UserPromptSubmit` | Rpc `session.submit {sessionId, submissionId?, branchId?, text? \| user?, mode?}` builds `InputMessageData` and calls `Session::input`; Rpc `session.branch_create {sessionId, parentBranchId, at, prompt}` creates a host branch whose first Queue input is the prompt, as the operator's words (TimelineTree `first_input`); InputQueue's `session.input.withdraw {…, steer?}` follows [Session access A.4](../contracts/session-access.md#a4-withdrawal). Other inputs (Goal, Scheduler, Collaboration, ShellInput, Hooks) enter through `Branch::input` from their owners | No entry asks anyone before writing. An input with `user` content whose first raw block is a `` marker reads as a source input (Goal A5), and history renders raw blocks before the user content, so context cannot be a raw block of the operator's input | A.6.2: the three entries call the checks registered with `submitChecks` first and append the returned context to the input's `user` content after the operator's own content, so the input stays operator input and needs no history or convention change | -| `PostToolUse(Failure)` | `step/tool-result {turn_id, request_id, call_event_id?, results: [{call_id, result}]}`, `ToolResult.is_error` | None | Dispatcher subscription | -| `Stop` | `turn/end {turn_id, status: completed \| failed \| cancelled}` | None | Dispatcher subscription, `completed` only | -| `SessionStart` | No Session-start fact; `branch/start` and the absence of `turn/start` on `main` | None needed | Derived from history (§3.4) | -| `Notification` | `approval/request` | None | Dispatcher subscription | -| `PreCompact`, `PostCompact` | `context/compaction-start {trigger}` (the strategy is already called), `context/compaction {outcome}` | Blocking would need a compaction-admission port in ContextCompaction | Unsupported (decision 6) | -| `SessionEnd` | Session close is lifecycle, not a Timeline fact; work must settle before services are removed (AGENTS rule 8) | A command at close would delay close | Unsupported (decision 6) | -| Configuration | Settings `BusinessDocument` sources with a user file and an optional project file; both are plain filenames (`validate_file` rejects any path separator), so a project file sits at the authorized project root (MCP: `mcp` with `.mcp.json`, enablement in `mcp-projects`). Project files in a directory, such as Workflow's `.dimcode/workflows/*.yaml`, are not Settings sources: their owners read them through FileStorage under the root Settings authorizes ([overview](../overview.md), Configuration). Rust sources have no generic client write, so each Rust owner keeps its management methods | `.dimcode/hooks.json` cannot be the project file of a Settings source | `HooksSettings` in App Server, as MCP (decision 5; §1, A.7): the user document is the Settings source `hooks`, and `HooksSettings` reads `.dimcode/hooks.json` through FileStorage under the project root Settings authorizes for the `cwd` (A.2) | - -## 1. Structure - -```mermaid -flowchart LR - subgraph PROC["Process (App Server)"] - HSet["HooksSettings: sources hooks, hooks-projects, hooks-plugins; hooks.* methods; plugin registration; HookSources port"]:::new - PMg["PluginManager"] - Settings["Settings"] - FS["FileStorage"] - Rpc["Rpc session.submit, session.branch_create"] - HP["HostPlatform (resource node)"] - end - subgraph SESS["Session"] - HS["HooksSession: catalog, runner, check hooks"]:::new - IM["InputQueue Session part: submitChecks, session.input.withdraw"] - end - subgraph BR["Branch"] - HB["HooksBranch: advisor hooks, observation"]:::new - AP["Approval"] - PM["Permission"] - TL["Timeline"] - DP["Dispatcher"] - end - PMg -->|"register / withdraw / plugins()"| HSet - HSet --> Settings - HSet -->|".dimcode/hooks.json under the authorized root"| FS - HS -->|"HookSources.read(cwd)"| HSet - HS -->|"spawn, terminate"| HP - HS -->|"submitChecks.register(hooks)"| IM - Rpc -->|"registered checks before Session::input or the branch"| HS - IM -->|"registered checks before the withdrawal command"| HS - HB --> HS - HB -->|"permission.registerAdvice(hooks)"| PM - AP -->|"admission decision with source"| PM - PM -->|"registered advisors, at each admission"| HB - HB -->|"respond(approval_id, decision)"| AP - HB -->|"Branch::input, source hooks"| TL - DP -->|"step/tool-result, turn/end, approval/*, stop/interrupt, input/*, context/configured"| HB - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -| Part | Scope | Depends on | Provides | -| --- | --- | --- | --- | -| `HooksSettings` | Process, App Server (where Settings and MCP's management live) | Settings (`BusinessDocument` sources `hooks`, user scope only, `hooks-projects` and `hooks-plugins`; the project root it authorizes for a `cwd`); FileStorage (reads `/.dimcode/hooks.json` under that root) | Management methods `hooks.catalog`, `hooks.save`, `hooks.set_enabled` (A.7); the owner operations `register`, `withdraw` and `plugins()` for plugin hook documents ([PluginManager §3.7](PluginManager.md#37-content-registration)); the Session port `HookSources` that returns the effective sources for a `cwd` (A.2) | -| `HooksSession` | Session (optional; registered by the Hooks plugin while it is enabled) | `HookSources`; HostPlatform; `SessionConfig.cwd`; `submitChecks` (InputQueue's Session part) | Registers the submit check `hooks` with `submitChecks`, which the operator-input entries call (A.6.2); a private catalog and command runner used by `HooksBranch` | -| `HooksBranch` | Branch (optional; registered by the Hooks plugin while it is enabled) | `HooksSession`'s runner; `Dispatcher`, `Approval`, `Permission`, `Branch::input` | Registers the advisor `hooks` with the branch's Permission (A.6.1); observation and context hooks | - -`HookSources` follows the existing host-port pattern of `CommandRules` and `SkillSettingsHost`: the agent-side parts never name Settings or App Server. Hooks' parts register with their owners: `HooksBranch` with Permission, `HooksSession` with `submitChecks`. Permission and the entries depend on no advisor or check ([ADR 002 D3](../../adr/002-plugin-scope.md#d3-dependencies-follow-scope-and-point-from-extensions-to-the-core)): with none registered, Permission decides from policy and command rules alone, and the entries write operator input unchecked. - -**Reload.** Enabling, disabling or upgrading Hooks reloads only the Hooks plugin (D3). Open Sessions and branches mount or unmount its parts as its registrations change ([ADR 006 D3](../../adr/006-plugin-contract.md#d3-a-plugin-is-one-row-each-instance-mounts-the-parts-registered-for-it)). Before its parts unload they settle accepted work (AGENTS rule 8): running commands are terminated, and each pending submit check is answered by the `onFailure` of the hooks that were running (A.5). Their registrations are withdrawn with them. Calls whose advice was pending see that advice dropped, counted as none, and Permission decides without it; approvals Hooks was answering stay with the user. Submissions and calls while Hooks' parts are not mounted pass without Hooks (A9). Editing hook documents, enablement or `disableAllHooks` is business configuration, read at the next hook point, and never reloads ([D4](../../adr/002-plugin-scope.md#d4-structural-configuration-and-business-configuration-are-separate)). - -**Node.** On an offline resource node, spawning fails with `node_unavailable`; each hook point treats that as a hook failure (Appendix C). - -**Contracts depended on:** `Approval::admit` and `AdmitCall.source`, `Permission::decide` and `permission.registerAdvice` (A.6.1); `Approval::respond` and the `approval/request`, `approval/respond`, `approval/cancelled` facts; Rpc `session.submit` and `session.branch_create`, and InputQueue's `session.input.withdraw {steer}`, with the Session table `submitChecks` (A.6.2); `InputMessageData.user` (context appended after the operator's own content); `step/tool-result`, `turn/start`, `turn/end`, `stop/interrupt`, `context/configured` (read only); source input conventions ([session access A.2](../contracts/session-access.md#a2-source-input-conventions)); Settings `BusinessDocument`, `settings.changed` and the authorized project root; FileStorage reads; App Server `ManagementMethods`; HostPlatform `build_process_spec`, process supervision and a process start whose stdin carries the given bytes (A.6.3). **Contracts defined here:** the hook document format, the command protocol, the advice and check replies of Hooks' `hooks` registrations, the `hooks.*` methods, `HookSources`, source name `hooks` (marker `dim-hooks`, key namespace `hooks:`). Hooks declares no event. - -## 2. Data and state - -```mermaid -flowchart TB - User["Settings source hooks, user scope: hooks, disableAllHooks"] - Proj["Project file /.dimcode/hooks.json, read through FileStorage"] - Enable["Settings source hooks-projects (user-local): enabled workspaces"] - Plug["Settings source hooks-plugins: one {dir, hooks} per plugin id, written by PluginManager"] - Cat["Catalog (computed per hook point)"] - TL["Branch Timeline: approval/respond, dim-hooks inputs, hook context blocks on operator inputs"] - User --> Cat - Enable --> Cat - Proj -->|"read per hook point"| Cat - Plug --> Cat - Cat --> TL -``` - -Hooks owns no `StateCell`, declares no event and caches nothing. The catalog is recomputed from `HookSources` at each hook point (A6). The one thing Hooks keeps is what PluginManager registered: the Settings source `hooks-plugins`, as Mcp keeps `mcp-plugins` (A.2), so plugin documents survive Hooks' own reload. Hooks receives new approval requests, tool results, turns and interrupts through Dispatcher; a triggered point reads the specific public facts it needs as specified in §3.5. A blocked submission writes nothing, so it leaves no state. A reloaded `HooksBranch` has no open work to rebuild; commands are side effects and are never re-run. - -## 3. Flows - -### 3.1 PreToolUse through Permission - -```mermaid -sequenceDiagram - participant TE as ToolExecutor (admission task) - participant AP as Approval - participant PM as Permission - participant HB as HooksBranch (advisor hooks) - participant HP as HostPlatform - TE->>AP: admit({source, call}, risk, batch cancel) - AP->>PM: admission decision (call, source, risk) - PM->>PM: policy and command rules - alt policy Deny - PM-->>AP: Deny (no advice asked) - else Allow or Ask - PM->>HB: advise {source, name, input, risk, decision} - HB->>HP: matching PreToolUse hooks, concurrently - HP-->>HB: deny / ask / allow / no opinion / failure (onFailure) - HB-->>PM: {advice: none | allow | ask | deny, reason?} - PM-->>AP: Deny{reason} if deny; Ask if ask; Allow if allow; else policy decision - end - AP->>AP: Ask: approval/request as today - AP-->>TE: admitted or error result -``` - -The wait happens inside Permission's asynchronous decision, which already runs in ToolExecutor's per-call admission task and already awaits a host port (command rules). Nothing on the Timeline or Dispatcher waits. `deny` makes Permission deny with `Hook : `, which Approval returns as `HostError::failed` and ToolExecutor writes as the call's error text in its batch `step/tool-result`. `ask` turns an Allow into an approval question. `allow` turns an Ask into an Allow, so the call runs without a question (decision 1; §7). A hook never overrides a policy or command-rule Deny, because advice is not asked then. Approval's recheck after a user response is a plain decision and does not ask for advice again. An interrupt cancels the batch token, Permission drops the advice call, and Hooks terminates the commands. A call whose tool is unknown to the request's binding fails before `admit` and runs no hook. - -### 3.2 PermissionRequest through Approval - -```mermaid -sequenceDiagram - participant AP as Approval - participant TL as Timeline - participant HB as HooksBranch - participant HP as HostPlatform - participant C as Client - AP->>TL: approval/request {approval_id, source, call, reason} - TL-->>HB: through the Dispatcher (handler enqueues, returns) - TL-->>C: through the Session broadcast - HB->>HP: matching PermissionRequest hooks - alt a hook allows or denies - HB->>AP: respond(approval_id, allow | deny) - AP->>TL: approval/respond, consumed by Approval as from a client - else no opinion, failure or timeout - HB->>HB: nothing; the user answers - end -``` - -This uses Approval exactly as Rpc's `approval.respond` does. Approval decides: it accepts the first response it consumes, answers a later one `Unknown`, and rechecks policy after an allow. If the user answers first, or Approval writes `approval/cancelled` (interrupt, close), Hooks consumes that and terminates the commands. Clients see the request and then the hook's `approval/respond` like any other response. - -### 3.3 UserPromptSubmit at the operator-input entries - -```mermaid -sequenceDiagram - participant C as Client (CLI, AcpGateway, RemoteGateway) - participant E as Entry (Rpc session.submit or session.branch_create, or session.input.withdraw steer) - participant HS as HooksSession (check hooks) - participant HP as HostPlatform - participant S as Session::input / InputQueue - C->>E: session.submit {user, mode, …} - E->>E: validate the input as it came: session_invalid_input, no check - E->>HS: check {branchId, user, mode} - HS->>HP: matching UserPromptSubmit hooks, concurrently - alt every hook proceeds (or none match) - HS-->>E: {decision: proceed, blocks?, warnings?} - E->>S: input/message with the context after the user content - S-->>E: committed event - E-->>C: {event} - else a hook blocks - HS-->>E: {decision: block, message} - E-->>C: error input_blocked, message "Hook : " - end -``` - -The entry runs the check in its own Rpc call before anything is written; the call waits for the hooks, bounded by their timeouts (default 30 seconds for `UserPromptSubmit`). On proceed, the hooks' contexts become text blocks with marker ``, one per hook in catalog order, appended to the same `input/message`'s `user` content after the operator's own content; the operator's own content is never edited. Before any check runs, the entry validates the input as the operator sent it with the existing `InputMessageData::validate`: an input it refuses, one with no content at all or with `user` content of empty text blocks only, fails with `session_invalid_input` before the checks. So no hook runs, nothing is written, nothing is titled and no preview is decided. A check's context can therefore never be what makes an invalid input valid, and never becomes the input's first block, which every reader of the content takes for the operator's words. `append_blocks` asks the same predicate, so even an entry that skipped validation never puts a context where the operator's words belong. Every block a check returns must be one runtime marker element, tested by the same `dim_agent_types::markup::runtime_context` the readers use: `append_blocks` drops a block that is not one, with a diagnostic, instead of appending it. So a bare string from a check can never be read as the operator's words. The input has no raw blocks, so it stays operator input and Goal still restarts its count on it (Goal A5). Consumers of the input's `user` content (clients rendering it) see these blocks after the operator's text. `dim_agent_types::markup::runtime_element` is the one vocabulary: a reader that only wants the operator's words leaves a marker block after the first out, as SessionTitle does for its title text ([SessionTitle §0.1](SessionTitle.md#01-fields-read-for-one-title-attempt)), and one that shows different elements differently dispatches on the name. The checks A.6.2 registers write only `dim-hooks` (Hooks) and `dim-skill` (Skills) blocks into `user.content`. The readers that link `dim_agent_types` and show only the operator's words (the native CLI and its plain log, and the AcpGateway) leave every block after the first that opens one of the vocabulary's names out of the operator's text, so a name a capability starts writing later is never shown there as the operator's words. The Web workspace cannot link the crate and names only those two, so a check that starts writing another name adds it to the Web reader's list in the same change; until then the Web shows that block as text. The native CLI draws one muted status row per `dim-hooks` block after the message row (`Hook context · N lines`), its body behind the tool-detail setting's `expanded` and a click; its plain log prints the same line. `dimcode session export --format markdown` writes each `dim-hooks` block under its own `### Hook context` heading and keeps the others in the operator's section, and the AcpGateway replays no `user_message_chunk` for a `dim-hooks` block; the Web workspace leaves both names out of the message text, reporting a `dim-hooks` block as the row's hook count and a `dim-skill` block as a loaded Skill; a reader of any of them never takes hook context for the operator's words. The model still reads the block verbatim, and the stored Session keeps it. **A hook that did not finish is reported to the caller.** With `onFailure: continue` (§A.5) the input proceeds without the failed hook's context, and the entry's reply carries one warning per unfinished handler: `{check: "hooks", message: "Hook did not finish: "}`, where `` is the run's own (`exited with exit status: 3`, `timed out after 30s`, `spawn failed: …`). A Hooks unload settles only the handlers still running: each one answers the same warning with the reason `Hooks was unloaded`, while a handler that had already finished keeps its own outcome — its context, its failure with its real reason, or its block — and the first `onFailure: block` in catalog order decides across the finished and unfinished handlers together. A handler whose process has not started when Hooks unloads never starts it. The warnings are the caller's to show; they never enter `user.content` and the model never reads them. `session.submit` and `session.branch_create` return them on the reply's optional `warnings` field, absent when empty; `session.input.withdraw {steer}` returns the same field beside `status` and `steer`. A warning describes the write the call itself made. `session.submit` accepts a `submissionId` once: a resubmission writes nothing and answers the input the branch already holds, so its reply carries none of the retry's warnings. The entry learns which of the two happened from the append that decides it, under the branch's commit lock, so two concurrent duplicates cannot both claim the input. `session.input.withdraw` writes its Steer in the same batch as the withdrawal command, and [session access A.4](../contracts/session-access.md#a4-withdrawal) accepts the replacement only together with the deletion, so the warnings ride with the `steer` receipt the reply carries: a reply that wrote no replacement carries neither. Protocol v1 and v2 encodings are frozen, so a built-in served there fills no warnings: `session.submit` on v1/v2, and `session.branch_create` on v2. `session.input.withdraw` is a Session method, served from v3 on. A block discards them: the error already names the hook that stopped the input. A dropped context block (`append_blocks`, and the table's own check before the write) is **not** a warning: it is a producer defect the operator cannot act on, and it stays a diagnostic naming the check. On block, nothing is written: no `input/message`, no event and no turn; the call fails with the app error `input_blocked` (code `-32000`, `data.appError` `input_blocked`) whose message is `Hook : `. `input_blocked` joins the `session.submit` errors that guarantee nothing was committed, so the CLI reports the block instead of an outcome that may already be queued. A `session.input.withdraw` whose `steer` is blocked writes neither the withdrawal nor the Steer input, so the old input stays queued. A `session.branch_create` whose prompt is blocked creates no branch; when it proceeds, the hooks' contexts are dropped with a diagnostic, because a branch's first input is built from the prompt alone. A blocked submission's `submissionId` stays unknown to `session.input_lookup`, so a retry runs the hooks again. A client's disconnect cancels nothing, as for any accepted call ([session-boundary A.1](../contracts/session-boundary.md#a1-method-contributions)): the check finishes and the entry writes or refuses the input as for a connected client. Only an interruption of the entry's own call ends the check early (the Rpc load or the entry's provider unloads, or the Session closes): the commands are terminated, nothing is written, and the call fails with that interruption's existing error. The AcpGateway reports a `session.submit` that fails with `input_blocked` as the ACP stop reason `refusal`, with the message as an `agent_message_chunk` (decision 9). -### 3.4 Observation and context hooks - -```mermaid -sequenceDiagram - participant DP as Branch Dispatcher - participant HB as HooksBranch - participant HP as HostPlatform - participant TL as Timeline - DP->>HB: step/tool-result, turn/end, approval/request, stop/interrupt, input/*, context/configured - HB->>HB: advance consumed view, enqueue, return - HB->>HP: run matching hooks after the triggering batch - HB->>HB: recheck against consumed events - alt still valid - HB->>TL: Branch::input: Append (PostToolUse, SessionStart) or Queue (Stop follow-up) - else interrupt, newer operator input consumed, or a started turn at SessionStart - HB->>HB: drop output, diagnostic - end -``` - -`PostToolUse` runs per matching call of a `step/tool-result` batch whose result is not an error, `PostToolUseFailure` per matching call whose result has `is_error`; one batch writes one Append input. `Stop` runs on `turn/end` with status `completed`; a block writes a Queue follow-up carrying the reason, at most 3 consecutive (A8). The native CLI draws that input as one muted status row where it was written (`Stop hook follow-up · N lines`), its body behind the tool-detail setting's `expanded` and a click, exactly as it draws a hook context; its plain log prints the same line and no body. `dimcode session export --format markdown` keeps the raw block under `### Runtime input`, and the AcpGateway replays no chunk for it (§5). The model reads it at the start of the turn it drives. `SessionStart` runs on `main` when it has no `turn/start` and no current unconsumed, undeleted ordinary input carries a `hooks:session-start/*` keyed block; its Append input waits, as any idle Append does, for the first driving input. `SessionStart` output is also dropped once a turn has started on the branch, because its block must come before the first turn. `Notification` runs on `approval/request` and writes nothing. Handlers with `async: true` run on any of these points and nothing waits for or reads their output. `HooksBranch` resolves the migration alias of each tool event from the declaration in force on the branch (G.2). - -### 3.5 Loading and reads at hook points - -Hooks registers the Dispatcher handover at the current committed position without querying history. It does not rebuild commands, approvals, tool arguments, pending-input identities or continuation progress. Commands start only after branch activation. Historical trigger events never start commands; a tool result marked `settlement: capability_reloading` is recovery settlement and does not trigger `PostToolUseFailure`. Other results in the same batch retain their ordinary behavior. - -| Decision | Read and boundary | -| --- | --- | -| SessionStart | Read sources first. With a matching handler on main, test whether `turn/start` exists at the consumed cutoff. If it does, stop. Otherwise inspect only current, unconsumed and undeleted ordinary inputs for a `hooks:session-start/` key. A startup contribution has not been consumed before the first turn, so completed input history is unnecessary. This exceptional check can visit the current K inputs; the marker has no independent index. | -| PostToolUse / PostToolUseFailure | With an enabled handler for a real result, locate its one `step/tool-call` by `call_event_id`, then match calls by `call_id`. An absent `call_event_id` means the calls were never dispatched and opens no post-tool point. No subscription retains call arguments. | -| Tool matcher alias | At the hook point's fixed consumed position, read the last `context/configured` and project only tool names, risks and MCP alias metadata. With no adopted tool part, use ToolRegistry as in G.2. A queued result keeps its triggering position even when configuration changes before its commands run. The selected inline configuration may still require JSON parsing; projection does not promise zero body I/O. | -| Output still valid | Keep only this generation's interruption and input-consumption positions. If inputs were consumed after the trigger, read `input/consumed.input_id` in that interval, then point-read those input identities with the operator predicate in §3.4. Do not return operator content. If more inputs were consumed during the read, check the new suffix before appending under the consumed-view lock. A queued but unconsumed input invalidates nothing. | -| Stop continuation round | With a matching Stop handler, locate this turn's start and its first `step/model-start`. Read consumption identities only between those positions, then point-read matching follow-up inputs and their tags. A live `turn/start` supplies the lower position; a part mounted mid-turn obtains the last start before this turn's end. Do not search all turns by `turn_id` or replay prior turns. | - -A Stop follow-up keeps the existing unkeyed `` block and carries exactly one private envelope tag, `hooks:stop-follow-up:1`, `hooks:stop-follow-up:2` or `hooks:stop-follow-up:3`. A turn consuming no follow-up has round zero; a turn consuming follow-ups uses their maximum round. A blocking Stop writes round plus one; at round three it starts no Stop commands and writes no further follow-up. These tags use the existing envelope and change neither the event type nor native storage format. They are not keyed context blocks and are not replayed as persistent prompt content. - -An already-queued legacy follow-up without a round tag remains accepted work: its queued turn runs, but ends that automatic continuation chain. No historical count is inferred. Part reload in a running turn uses the same current-turn read; Session resume does not restart an old script or automatically finish an old hook point. - -```text -mount -> subscribe at committed cutoff -> ready (no historical query) -activated -> configured SessionStart check, if any -new trigger -> read matching configuration -> identity/current-turn reads - -> run commands -> check newly consumed inputs -> original input/message -``` - -Mount writes no event and performs no Timeline query. With SessionStart configured, an already-started main needs one existence query after activation. No enabled handler for the event kind means no tool-argument, alias or Stop-round query. Each actual follow-up remains one existing input event; its tag adds no event. No recovery snapshot, schema change, new service or query operation is required. All reads use Timeline's existing query contract (§5.4 of the [plugin contract](../plugin-contract.md#54-the-event-query)); the existing service faces and bindings remain those in Appendix H and [service faces](../service-faces.md). - -SQL acceptance checks the complete statement plans and instruction counts, not just `LIMIT 1` or an index name. Consumption windows use the kind/position range and original inputs use identity seeks in separate queries. The Stop start and first-request reads use kind/position bounds. A correlated existence query over the whole branch, or a first-by-turn query that scans earlier turns, does not satisfy this contract. - -## 4. Timing and conflicts - -| Scenario | Sequence order | Outcome | Owner | -| --- | --- | --- | --- | -| Interrupt while PreToolUse runs | batch cancelled | Permission drops advice; commands terminated; call settles as cancelled | ToolExecutor, Permission | -| User answers before a PermissionRequest hook | `approval/respond` (user) < hook's respond | Hook's respond gets `Unknown`; commands terminated when the user's response is consumed | Approval | -| Two submissions on one branch while hooks run | — | Each call waits for its own check; inputs are written in the order their checks finish | Entries | -| Interrupt during a submit check | nothing written yet | No effect on the check; the input is written afterwards like any input arriving after the interrupt | Entries, InputQueue | -| Client disconnects during a submit check | — | Nothing is cancelled: the check finishes and the input is written or refused as for a connected client | Entries | -| Stop follow-up vs newer operator input | `turn/end` < input consumed < write | Follow-up not written | Hooks | -| Hooks reload during a submit check | — | Answered by the running hooks' `onFailure` before unload; later submissions pass without Hooks (A9) | Hooks, Lifecycle | -| Resource node offline | per call | `node_unavailable` = hook failure → `onFailure` | Hooks | - -Full table: Appendix B. ## 5. Context mapping @@ -449,111 +218,7 @@ Full table: Appendix B. The model never sees hook configuration, commands, exit codes, diagnostics, a `UserPromptSubmit` block reason or a `UserPromptSubmit` warning. -## 6. Interfaces (summary) - -| Interface | Kind | Purpose | -| --- | --- | --- | -| Advisor `hooks` (`permission.registerAdvice`) | Registered by `HooksBranch` with the branch's Permission while it runs; Permission calls it at each admission (A.6.1) | `PreToolUse` decision | -| Check `hooks` (`submitChecks.register`) | Registered by `HooksSession` with the Session's `submitChecks` (InputQueue) while it runs; the operator-input entries call it before writing (A.6.2) | `UserPromptSubmit` decision, and the warnings a failed run leaves | -| `Approval.respond` | Existing branch service | `PermissionRequest` outcome | -| `input_blocked` | Rpc app error of `session.submit`, `session.branch_create` and `session.input.withdraw`; message `Hook : ` | A blocked submission | -| `warnings` | Additive optional field of the `session.submit` and `session.branch_create` replies and of the `session.input.withdraw` reply; each element is `{check, message}` | Work a check did not do (A.6.2) | -| `hooks.catalog`, `hooks.save`, `hooks.set_enabled` | App Server management methods (namespace `hooks`), like `mcp.*` | Effective hooks, user document writes, project enablement (A.7) | -| `HookSources` | Session port bound by App Server | Effective sources for a `cwd` (A.2) | -| `hooks` (user scope), `hooks-projects` | Settings sources (`BusinessDocument`) | The user's hook document; user-local project enablement (A.1, A.2) | -| `.dimcode/hooks.json` | Project file read by `HooksSettings` through FileStorage | The project's hook document (A.1, A.2) | -| Hook document format, command protocol | Defined here | A.1, A.3 | - -## 7. Security - -Hook commands run because of configuration, not an agent decision, so they need no approval and run when enabled ([ADR 003](../../adr/003-approval-scope.md) D2, AGENTS rule 11). The user's hooks are enabled as the user writes them. The project source `.dimcode/hooks.json` starts disabled: a repository runs nothing until the user enables project hooks for that workspace (D3). The enablement lives in the user-local source `hooks-projects`, written only through `hooks.set_enabled`, so a project file cannot enable itself. After enabling, edits in the file take effect at the next hook point (D4). There are no grants, fingerprints, hashes or trust prompts. - -**`PreToolUse` `allow` widens authority, and this is accepted (decision 1).** An `allow` admits a call that Permission's policy would have asked about. That authority comes from configuration the user enabled, not from the agent: a user hook is the user's own rule, like an allow command rule, and a project hook can do it only after the user enabled that workspace's project hooks, which under ADR 003 D3/D4 means trusting that project's configuration. It never overrides a Deny (policy, disallowed tool or command rule), because advice is not asked then, and a `deny` or `ask` from any hook wins over `allow`. Approval and Permission still govern only agent decisions: the call is still the agent's, and the admission is still Permission's decision with the advice it asked for. - -`PermissionRequest` answers a question Approval asked, through the same path as the user; Approval still rechecks policy and records the answer as `approval/respond`. `UserPromptSubmit` only blocks a submission or adds attributed blocks; it never edits the user's text. No hook edits tool input (`updatedInput` is ignored). A hook command is a configuration command ([ADR 003](../../adr/003-approval-scope.md) D2): HostPlatform starts it on the Session's resource node without the agent sandbox, as an MCP stdio server is started. The sandbox setting governs agent-decided commands, `exec` and the persistent shell, not configuration ([ADR 010](../../adr/010-sandbox-opt-in.md) D1). stdin contains prompts and tool input; diagnostics keep only source, event, exit status, duration and a bounded stderr excerpt. - -## 8. Rule check - -Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [ADR 002](../../adr/002-plugin-scope.md) D1–D5, AGENTS rule 11 and [ADR 003](../../adr/003-approval-scope.md). - -| Rule | How this document complies | -| --- | --- | -| §4.1 Command events for others' state | Hooks changes no other owner's state: approvals only through Approval's `respond` (Approval writes `approval/respond`), tool admission is decided by Permission from advice it asked for, and a submission is written by its entry. Hooks writes only its own inputs. | -| §4.2 No recall after handoff | `UserPromptSubmit` decides before the input exists; tool advice is part of admission, before execution; after a handoff Hooks only writes new inputs. | -| §4.3 Before callbacks only transform synchronously; entries validate only shape and authorization | Hooks registers no before callback. The entries do not check prompts themselves: they call the checks registered with the generic table `submitChecks` and write what they answer. Running at the entry, not on the Timeline, is the maintainer's decision (2026-10-22), because only entry input is known to be the operator's. | -| §4.4 No business meaning in core | Timeline, Dispatcher and before are unchanged; Permission's advisors and the Session's `submitChecks` are generic registrations with no Hooks semantics. | -| §4.5 Read the whole batch | Observation hooks and rechecks run after the whole triggering batch; `PostToolUse(Failure)` writes one input per result batch. | -| §4.6 Context only from handed-off events | A blocked submission is never written; prompt context enters as part of the adopted operator input; deny reasons enter through ToolExecutor's result; other output enters as adopted Hooks inputs. | -| §4.7 Public events and services only | Hooks reads public events and calls `Approval.respond` and `Branch::input`; Permission and the entries call the advisors and checks registered with them. No internal state is read. | -| §4.8 Infrastructure unchanged | No change to Timeline, Dispatcher, envelope, assembly, lifecycle or facades. Needs from business owners are in A.6 in this rule's format. | -| §4.9 Only decision facts in the Timeline | Hooks adds no event type or snapshot. The necessary Stop input carries its continuation round in an existing envelope tag (§3.5); configuration lives in Settings, diagnostics in the catalog. | -| §1 Capability and App Server boundary | `HooksSession` and `HooksBranch` are Capabilities in their own crate; `HooksSettings` lives in App Server next to Settings, like MCP's management, and binds `HookSources`. | -| ADR 002 D1 Scope | Configuration and its methods are per host (process); catalog, runner and the submit check follow the Session; advice and observation follow the branch whose facts they use. | -| ADR 002 D2 No wiring modules | Hooks attaches to owners through their own registrations and services; `HookSources` is the agent-side port of Hooks' own configuration owner, not an adapter for others. | -| ADR 002 D3 Dependencies | Hooks depends on core parts (Approval, Permission, InputQueue's `submitChecks`, Timeline) and registers with them; Permission and the entries depend on no advisor or check and work without Hooks. | -| ADR 002 D4 Configuration | Hook documents and enablement are business data in Settings sources, read at use; no reload. | -| ADR 002 D5 Language-neutral contracts | Document format, command protocol, `permission.registerAdvice`, `submitChecks`, `HookSources` and `hooks.*` are neutral; Rust binding is Appendix H. | -| AGENTS 11 / ADR 003 | Hook commands need no approval and run when enabled; the project source starts disabled and only the user-local `hooks-projects` enables it; Approval and Permission keep governing only tool calls, and `allow` advice is authority from user-enabled configuration (§7). | - -## 9. Requirements raised to mechanism owners - -None to the runtime or rutis: Hooks needs no infrastructure change, new event type, schema, query operation or service. It needs three generic capabilities from their owners, stated in A.6 in the five items of §4 rule 8 and listed in [overview Appendix B.1](../overview.md#b1-session-and-branch-capabilities): - -- Permission and Approval: advisors registered with the branch's Permission (`permission.registerAdvice`) and called during the admission decision, with Approval passing the call's `source` (A.6.1). -- InputQueue (the Session table `submitChecks` and `InputMethods` for `session.input.withdraw {steer}`), Rpc (`session.submit`, `session.branch_create`) and the native CLI: checks registered with `submitChecks` and called before operator input is written, the `input_blocked` error, and its place among the `session.submit` errors that guarantee nothing was committed (A.6.2). -- HostPlatform: a process start whose stdin receives the given bytes and is then closed (A.6.3). - -AcpGateway's own design reports a Hooks `input_blocked` rejection from `session.submit` as the rejection's message plus the stop reason `refusal` ([AcpGateway §4.2](AcpGateway.md#42-prompt-and-cancellation)), so Hooks raises no requirement for it (decision 9). Not requirements: the Settings sources `hooks` (user scope only), `hooks-projects` and `hooks-plugins` are `BusinessDocument` sources (existing mechanism, additive `user/` rows in v13), and `hooks-plugins` is written only by the owner operations, never by a `hooks.*` method; `.dimcode/hooks.json` is a project file in a directory, which its owner reads through FileStorage under the root Settings authorizes, as Workflow's definition files are read ([overview](../overview.md), Configuration); the `hooks.*` methods use the existing `ManagementMethods`; HostPlatform's shell-form `build_process_spec` covers `command` (exec-form `args` is unsupported, Appendix G). - -## 10. Decisions - -### 10.1 Maintainer decisions - -#### 2026-10-22 - -| # | Decision | -| --- | --- | -| — | Dim reads only its own hooks configuration: no import of Claude or Codex files; the document shape and script protocol stay compatible for migration (Appendix G) | -| — | Project hooks: Dim's own `.dimcode/hooks.json`, disabled by default, enabled per workspace in the user's local configuration (ADR 003) | -| — | `UserPromptSubmit` runs at the operator-input entries, not on the Timeline; no `hold`, no `input/release`, no before callback, no prompt-hold flag, no persistence change | -| 1 | `PreToolUse` `allow` admits the call (§7) | -| 2 | `onFailure` defaults to `continue` | -| 5 | Configuration owner: `HooksSettings` in App Server with sources `hooks`, `hooks-projects` and `hooks.*` methods, as MCP | -| 6 | The eight events of the summary table are supported; all others are unsupported (the reasons are in Appendix G.1) | -| 7 | A `PermissionRequest` deny shows Approval's generic text; `approval/respond` is unchanged | -| 8 | stdin `permission_mode` carries Dim's preset value; there is no `transcript_path` | -| 9 | AcpGateway reports a hook block as `refusal` | - -#### 2026-10-31 - -| # | Decision | -| --- | --- | -| — | The phase is M1 and covers user, project and plugin sources; A.6.1 and A.6.2 are accepted (§10.2) | -| — | A hook command is a configuration command: HostPlatform starts it on the Session's resource node without the agent sandbox, as an MCP stdio server is started (§7) | -| — | Plugin hooks: PluginManager calls Hooks' owner operations `register`, `withdraw` and `plugins()`; Hooks keeps the documents in `hooks-plugins`, lists them in `hooks.catalog` and gives their commands `DIM_PLUGIN_ROOT` (A.2, A.7) | -| — | The event's stdin object (A.3) goes to a process HostPlatform starts for it, whose stdin is closed after the bytes; the environment adds `DIMCODE_HOME` and `DIM_PLUGIN_ROOT` (A.6.3) | -| — | A hook reads the Session's Timeline with `dimcode export "$DIM_SESSION_ID"`; there is no `transcript_path` (A.3) | -| — | `PreCompact`/`PostCompact`, `SessionEnd` and `SubagentStart`/`SubagentStop` stay unsupported, for the reasons in G.1 | -| — | The native CLI gets `dimcode hooks list`, `dimcode hooks enable\|disable`, `dimcode hooks edit` and `dimcode hooks set PATH` ([CLI commands](../cli-commands.md#commands)) | - -#### 2026-11-06 - -| # | Decision | -| --- | --- | -| — | The common payload carries `collaboration_role` (`leader` or `member`), taken from `SessionConfig.collaboration_role`. In Dim a subagent is a Collaboration member, so subagent identity goes into the member's own lifecycle — its `SessionStart` and `Stop` payloads — and not into new `SubagentStart`/`SubagentStop` events (G.1) | - -### 10.2 Accepted owner changes - -| Item | Owner | Issue | -| --- | --- | --- | -| A.6.1: advisors registered with the branch's Permission and called during the admission decision, `allow` included | Permission, Approval | [#758](https://github.com/arcships/dim/issues/758) | -| A.6.2: the `submitChecks` table, `input_blocked` and its place among the `session.submit` errors that guarantee nothing was committed | Rpc (App Server), InputQueue, CLI | [#757](https://github.com/arcships/dim/issues/757) | -| Plugin source: the owner operations, `hooks-plugins`, `DIM_PLUGIN_ROOT` ([PluginManager §3.7](PluginManager.md#37-content-registration)) | Hooks, PluginManager | [#756](https://github.com/arcships/dim/issues/756) | - -No question in this document is waiting for a maintainer answer. - ## Appendix A. Interface details - ### A.1 Hook document format The user's document is the Settings source `hooks` (user scope only); the project document is `/.dimcode/hooks.json`, which `HooksSettings` reads through FileStorage under the project root Settings authorizes and validates with the same document type. Both use the Claude Code / Codex shape: an object keyed by event name, each holding matcher groups with command handlers. @@ -596,31 +261,7 @@ Project enablement is the user-local source `hooks-projects`: `{ "enabled": [" did not finish`. Observation hooks: diagnostic only | | Cancellation | `PreToolUse`: Permission drops the advice call (batch cancelled, branch closing). `PermissionRequest`: the request is answered or `approval/cancelled` is consumed. `UserPromptSubmit`: the entry drops the check only when its own call is interrupted (the Rpc load or the entry's provider unloads, the Session closes); a client disconnect cancels nothing. Unload: the handlers still running are answered by their `onFailure` (§1); one that already finished keeps its own result. Processes always end through `ctx.effect` | -### A.6 Changes to other plugins - -#### A.6.1 Tool advice in Permission - -| Item | Content | -| --- | --- | -| Blocked by | §4 rule 3 forbids waiting in a before callback, and rule 8 keeps Timeline unchanged, so a `PreToolUse` command cannot hold `step/tool-call`. Rule 7 forbids deciding for Permission. Permission is the owner of "may this call run" for every call, including calls its preset allows without asking. Today `Permission::decide(call, risk, cancel)` asks only its command-rules port, receives no call identity, and is called identically for the admission and for Approval's recheck after an allow. | -| Existing mechanisms considered | Async before on `step/tool-call` (withdrawn, #21); a Dispatcher subscription to `step/tool-call` (runs after the handoff to ToolExecutor, races execution, rule 2); answering `approval/request` (only exists for calls that already ask); `CommandRules` (one Session port bound by the profile, only for commands of `execute_process` calls, and it decides by static rules). Registration with an owner, as tools register with ToolRegistry ([rutis usage R6](../rutis-usage.md#r6-contributions-register-with-their-owner)): reused for the advisors. | -| Generic capability | Approval's `admit` passes `AdmitCall.source` to Permission for the admission decision; the recheck stays a plain `decide`. Permission keeps the branch's advisors. A branch part registers an advisor with the branch's Permission while it runs: `permission.registerAdvice(name, advise)`. The registration belongs to the calling part and is withdrawn when it unloads; a second advisor of the same name fails. `HooksBranch` registers `hooks`. In the admission decision, after policy and command rules and only when the result is not Deny, Permission calls each advisor registered at that moment, in name order: `advise {source, name, input, risk, decision: "allow" \| "ask"}` → `{advice: "none" \| "allow" \| "ask" \| "deny", reason?}` (async; cancellation = Permission drops the call). Any deny → `Deny {reason}`; else any ask → `Ask {reason}`; else any allow → `Allow`; else Permission's own decision. A provider error counts as `none`. Permission depends on no advisor; `HooksBranch` depends on Permission. No business meaning: any branch part may register an advisor. Advice never overrides a Deny, since it is not asked then. ToolExecutor is unchanged: it already puts the call id in `AdmitCall.source`. | -| Effect on sequence, batch, interrupt, reload | Sequence and batch: no new event; a denied call's error text is in ToolExecutor's existing batch result; an allowed call writes no `approval/request`. Interrupt: the batch token cancels the decision and so the advice call. Reload: an advisor withdrawn mid-call has its pending advice dropped, counted as `none`; with no advisor registered, Permission decides from policy and command rules alone. Latency of a call's admission grows by the advice time. | -| Owner and issue | Permission and Approval (`dim-agent-capabilities`); [#758](https://github.com/arcships/dim/issues/758) (§10.2). | - -#### A.6.2 Submit check at the operator-input entries - -| Item | Content | -| --- | --- | -| Blocked by | A `UserPromptSubmit` command must decide before the operator's input is written: once committed, InputQueue applies a Steer, Append or idle Queue input in the same Dispatcher step (rule 2), and §4 rule 3 forbids waiting in a before callback. Session input is not necessarily the operator's (Goal, Scheduler, Collaboration, ShellInput, Hooks write inputs too), so a Timeline-level hook cannot tell a user prompt from other input. Only the entries where operator input arrives know it. Today `session.submit`, `session.branch_create {prompt}` (whose prompt becomes the new branch's first input, as the operator's words) and `session.input.withdraw {steer}` write without asking anyone. | -| Existing mechanisms considered | Async before (withdrawn, #21); a synchronous before callback holding the input with a new `hold` field and an `input/release` command (the previous revision: needs InputQueue, history and a persistence-format change, and cannot tell operator input from other inputs except by the absence of a marker); `input/withdraw` after the fact (unreliable once applied); a check inside the client (CLI, gateways: every client would need it and none could be relied on). Registration with an owner, as tools register with ToolRegistry ([rutis usage R6](../rutis-usage.md#r6-contributions-register-with-their-owner)): reused for the checks. | -| Generic capability | The Session's submit checks are the Session table `submitChecks`, a Session service of InputQueue's Session part, which the operator-input entries read. A Session part registers a check with it while it runs: `submitChecks.register(name, check)`. The registration belongs to the calling part and is withdrawn when it unloads; a second check of the same name fails. `HooksSession` registers `hooks`, and the Skills Session part registers `skills` (Skills §9). Before writing operator input, `session.submit` and `session.branch_create` (Rpc) and `session.input.withdraw` with `steer` (InputQueue's `InputMethods`) call each check registered at that moment, in name order: `check {entry: "submit" \| "branch" \| "steer", branchId, user, mode}` → `{decision: "proceed", blocks?: [text], warnings?: [text]} \| {decision: "block", message}` (async; the entry's call waits). The first block ends the call: the checks after it in name order are not called. `session.branch_create` checks its prompt as `{entry: "branch", branchId: parentBranchId, user: {content: [prompt]}, mode: "queue"}`. A caller's disconnect cancels nothing, as for any accepted call ([session-boundary A.1](../contracts/session-boundary.md#a1-method-contributions)); only an interruption of the entry's own call (the Rpc load or the entry's provider unloads, the Session closes) cancels the check, and then nothing is written and the call fails with that interruption's existing error. Any block → the call fails with the app error `input_blocked` (`-32000`, `data.appError` `input_blocked`, message = the reply's `message`) and nothing is written (with `steer`, neither the withdrawal nor the new input; with `branch`, no branch). `input_blocked` joins the protocol v3 `session.submit` errors that guarantee nothing was committed (the App Server README's submission errors and the native CLI's matching list, which otherwise prints that the input may already be queued). Else the entry appends to the input's `user` content, in name order and after the operator's own content, each of the `blocks` that is one runtime marker element (`dim_agent_types::markup::runtime_context`); a block that is not one is dropped with a diagnostic, because both readers would take it for the operator's words. The input carries no raw blocks for them, so it stays operator input. Each entry validates the input as the operator sent it with `InputMessageData::validate` before any check runs: an input without operator content fails the call with `session_invalid_input` and no check runs (§3.3), and a context is never appended to an input without operator content. `session.branch_create` cannot attach them, since the branch's first input is built from the prompt alone, and creates the branch without them. A provider error counts as proceed. A check may also answer, with `warnings`, the work it did not do: the table keeps each warning beside the registration that raised it, in name order, and the entry returns them to the caller as `{check, message}` on the reply's optional `warnings` list — `session.submit` and `session.branch_create` on the reply, `session.input.withdraw {steer}` beside `status`. They describe the write the entry made, read from the append that decided it: a duplicate submission wrote nothing, so its reply carries none, and the withdraw entry points the list only at the reply that carries the `steer` receipt. The field is absent when empty and is not filled for protocol v1 or v2. Warning text is never model context: it enters no `user` content and no block. The first block discards every warning collected so far, because the error already names the hook that stopped the input. A block a check returns must be one runtime marker element (`dim_agent_types::markup::runtime_context`): the table drops one that is not, with a diagnostic naming the check, and `append_blocks` repeats the test at the write. The entries depend on no check; `HooksSession` and Skills depend on `submitChecks`. No business meaning: any Session part may register a check. | -| Effect on sequence, batch, interrupt, reload | Sequence: the input takes its sequence when written, after the check; inputs from other sources are unaffected. Withdrawal admission and conditional result batches follow [Session access A.4](../contracts/session-access.md#a4-withdrawal). Interrupt: no effect on a running check. Reload: a check withdrawn mid-call answers before it is withdrawn, or its answer is dropped and counts as proceed. While the `submitChecks` table itself is absent, because InputQueue's Session part is between generations, `session.submit` and `session.branch_create` answer `service_reloading` and write nothing, and `session.input.withdraw {steer}` answers `service_reloading` too, because its `session.input` namespace is withdrawn with that part (`service_unavailable` once the part failed); no entry writes unchecked then. With the table present and no check registered, because Hooks is unloaded, the entries write operator input unchecked (A9). Persistence: none; text blocks in `user` content are an existing form. Latency of a submission grows by the check time. | -| Owner and issue | App Server Rpc (`session.submit`, `session.branch_create`), InputQueue (`submitChecks`, `InputMethods`) and the native CLI (`dim-app-server`, `dim-agent-capabilities`, `dim-cli`); `input_blocked` joins the Rpc error table and the did-not-commit set; [#757](https://github.com/arcships/dim/issues/757) (§10.2). | - -#### A.6.3 Process start with an initial stdin - -| Item | Content | -| --- | --- | -| Blocked by | A hook command receives one JSON object on stdin, then EOF (A.3). HostPlatform's `spawn` starts a process with its stdin closed, and `ProcessTree` exposes no stdin, so a command cannot be handed the object. | -| Existing mechanisms considered | A command-line argument: it is visible in the process list, and each shell's quoting changes it. A temporary file the command reads: the protocol changes, and the command needs its path, permissions and cleanup, so a pasted Claude/Codex script is no longer portable (G.3). HostPlatform's `spawn_pty` (`crates/dim-agent-capabilities/src/host_platform.rs:1913`): a terminal, not a pipe, so echo and line discipline alter the bytes and there is no plain EOF. | -| Generic capability | HostPlatform's process start takes optional stdin bytes: it starts the process, writes the bytes to the child's stdin and closes it. A caller that passes none gets today's behaviour, with stdin closed at start. No business meaning: any caller may start a process with an initial stdin. | -| Effect on sequence, batch, interrupt, reload | No event, batch or lock is involved; the write happens in the caller's own process task, never in a Dispatcher handler or under the commit lock. A hook's write is bounded by the same wait and cancellation as the run, and terminating the process tree ends it. | -| Owner and issue | HostPlatform (`dim-agent-capabilities`); part of the core implementation ([#755](https://github.com/arcships/dim/issues/755)). | - -### A.7 Management methods - -`HooksSettings` registers the namespace `hooks` with App Server's `managementMethods`, like `mcp.*`; never served to paired remote devices. - -| Method | Parameters | Result | -| --- | --- | --- | -| `hooks.catalog` (not mutating) | `{cwd?}` | `userRevision`, `userDocument` (the user's document as stored, which `hooks.save` replaces with that revision), `projectsRevision`; per source: `source`, `path` (`dir` for a plugin source), `enabled`, `state` (`ok`, `missing`, `invalid` with message); per handler: `event`, `matcher`, `command`, `timeout`, `onFailure`, `async`, `state` (`ok`, `unsupported`, `invalid`); `disableAllHooks` | -| `hooks.save` | `{expectedRevision, document}` | `{revision}`; CAS write of the user scope of `hooks`, validated by its `BusinessDocument` | -| `hooks.set_enabled` | `{cwd, enabled, expectedRevision}` | `{revision}`; CAS write of `hooks-projects` for the project root Settings authorizes for `cwd` | - -The project file is edited in the repository, not through these methods. `hooks-plugins` is written only by the owner operations (§1), never by a method here. Hooks has no tool and no agent-reachable path that writes configuration. The native client's management surfaces are the client surface for `hooks.catalog`, `hooks.save` and `hooks.set_enabled`: the `/hooks` panel, `dimcode hooks list|enable|disable`, `dimcode hooks edit` and `dimcode hooks set PATH` ([CLI commands](../cli-commands.md#commands)). - -## Appendix B. Full conflict table - -| Scenario | Sequence order | Outcome | Owner | -| --- | --- | --- | --- | -| PreToolUse deny for one call of a batch | one batch | That call's admission fails with the hook reason; others run; one batch result | Permission, ToolExecutor | -| PreToolUse allow under the `workspace-write` preset for a call the preset asks about (`exec`) | — | Admitted; no `approval/request` | Permission | -| PreToolUse allow under the `read-only` preset for a write or `exec` call | — | The preset denies it (read-only never asks); no advice asked; denied | Permission | -| PreToolUse allow for a disallowed tool or a command-rule deny | — | No advice asked; denied | Permission | -| PreToolUse allow and ask from two hooks | — | Ask | Permission | -| PreToolUse ask under a permissive preset | — | `approval/request`; the user (or a PermissionRequest hook) answers | Approval | -| Two PreToolUse denies finish in reverse order | — | Earlier handler awaited; its reason is used | Hooks | -| Interrupt during PreToolUse | batch cancelled | Advice dropped, tree terminated, call cancelled | ToolExecutor | -| Policy tightened while an approved call is rechecked | after `approval/respond` | Recheck decides; no advice asked again | Approval, Permission | -| PermissionRequest hook allows, user denies later | hook respond < user respond | Hook's answer stands; user's gets `Unknown` | Approval | -| `approval/cancelled` during PermissionRequest | — | Commands terminated, nothing written | Approval, Hooks | -| PermissionRequest in a non-interactive Session | — | Same; a hook may answer what no user would | Approval | -| Prompt blocked | — | `input_blocked`; no event; no turn | Entry, Hooks | -| Prompt allowed with context | — | One `input/message` with the context as text blocks after the operator's own content; Goal restarts its count on it | Entry | -| `session.branch_create` prompt blocked | — | `input_blocked`; no `branch/create`, no branch | Rpc, Hooks | -| `session.branch_create` prompt allowed with context | — | Branch created from the prompt alone; the context is dropped with a diagnostic | Rpc, Hooks | -| Steer re-submission blocked | — | Neither withdrawal nor Steer written; the old input stays queued | InputQueue `InputMethods` | -| Retry with the same `submissionId` after a block | — | Hooks run again; lookup was `unknown` | Entry | -| Two prompts on one branch | checks concurrent | Written in the order their checks finish; each caller gets its own event | Entries | -| Source input (Goal, Hooks, Scheduler, Workflow, Collaboration, ShellInput) | — | No submit check | — | -| Client disconnects during a check | — | Nothing cancelled; the check finishes and the input is written or refused | Entry | -| Rpc or entry provider unloads, or the Session closes, during a check | — | Commands terminated; nothing written; the call fails with the interruption's existing error | Entry, Hooks | -| PostToolUse output vs following interrupt | result < interrupt consumed < write | Not written | Hooks | -| Stop follow-up vs user input | `turn/end` < input consumed < write | Not written | Hooks | -| Stop follow-up limit | 3 consecutive follow-ups | No further follow-up; diagnostic | Hooks | -| Stop follow-up vs Goal continuation | both after `turn/end` | Both Queue inputs stand, in order | InputQueue | -| Child branch | — | Its own `HooksBranch`; `session.submit {branchId}` to a child is checked like `main` | Hooks | -| Compaction | — | Session-start keyed blocks replayed; others through the summary; no compaction hook runs | History projection | -| Hooks or Settings reload | — | Hooks parts settle pending checks and reload; document edits never reload | Lifecycle, Hooks | -| Session restore before the first turn | — | `SessionStart` runs if no current startup contribution remains (§3.5) | Hooks | -| Session fork | copied turns | No `SessionStart` | Hooks | -| `cwd` outside any project | — | User source only | HooksSettings | -| Project file edited after enabling | — | New content applies at the next hook point | Hooks | -| Resource node offline | — | Hook failures → `onFailure` | Hooks | -| Client detach | — | No effect on tool and observation hooks or on a check running in that client's call | — | - -## Appendix C. Errors and recovery - -| Case | Result | -| --- | --- | -| Timeout, spawn failure, bad exit, oversized output, `node_unavailable` | Hook failure → `onFailure` (A.5); diagnostic | -| Invalid document or matcher | Listed `invalid`; none of its hooks run | -| Unsupported event, handler type or handler field (`args`, `if`) | Listed `unsupported`; never runs | -| Branch input rejected (branch closed) | Output dropped; diagnostic | -| Timeline query fails | Observation or approval processing faults the Hooks consumer and writes no output; PreToolUse returns the read error through Permission. Hook command `onFailure` does not decide storage errors. | -| `Approval.respond` returns `Unknown`, `Cancelled` or `Closed` | Ignored | -| `HookSources` read fails | Every source `invalid`; the hook point runs no hooks | -| Project file read through FileStorage fails or does not parse | The project source is listed `invalid`; the user source still runs | -| Unload with pending checks | Answered by `onFailure` before services are removed | - -## Appendix D. Acceptance - -1. Each exit-code and stdout case of A.3/A.4 per event, including timeout and `onFailure`. -2. Under a full-access preset, a `PreToolUse` deny for one call of three: no `approval/request`, no execution of that call, its error text in the one batch `step/tool-result`; Hooks writes no `step/tool-result`. -3. Under a preset that asks for `exec`, a `PreToolUse` `allow` runs the call with no `approval/request`; an `ask` from another hook at the same point produces an ordinary `approval/request`; a command-rule deny is not overridden; Approval's recheck after an answer runs no hook. -4. A `PermissionRequest` hook allow writes `approval/respond` through Approval and the call runs after the policy recheck; a user answer first makes the hook's answer `Unknown`. -5. `UserPromptSubmit` block: `session.submit` fails with `input_blocked`, message `Hook : `, and the branch has no new event; the native CLI reports the block, not an uncertain outcome. Allow with context: one `input/message` whose context text blocks follow the operator's own content in the model request, and Goal restarts its count on it. A `session.branch_create` whose prompt is blocked creates no branch. A client that disconnects during the check still gets its input written or refused. A Goal or Scheduler input runs no prompt hook. -6. `session.input.withdraw` with a blocked `steer` writes nothing; the old input is still applied later. -7. Through AcpGateway, a blocked prompt ends with `refusal` and the reason as text. -8. A repository with `.dimcode/hooks.json` runs nothing until `hooks.set_enabled` enables that workspace; a later edit of the file takes effect at the next hook point without asking. Claude or Codex files in the repository or home are never read. -9. A pasted Claude `PreToolUse` group with matcher `Bash` runs for `exec` and reads `tool_input.command`. -10. Two denying `PreToolUse` handlers that finish in reverse catalog order yield the first handler's reason. -11. Timeline, Dispatcher, the before mechanism and the event formats are unchanged; no write waits for a hook command. - -## Appendix E. Assumptions - -| # | Assumption | Basis | Effect if rejected | -| --- | --- | --- | --- | -| A1 | Claude/Codex document shape is the native format | Migration by copy and paste; one parser | A Dim format and a converter | -| A2 | Handlers of one point run concurrently; combined in catalog order | Claude behavior; bounded latency | Serial, summed latency | -| A3 | Documents are re-read at each hook point | No watcher and no cache | A watcher | -| A4 | Project enablement is per workspace | One project source (decision) | Per handler ids | -| A5 | Matcher aliases cover names only; `tool_name` and `tool_input` stay Dim's | Input schemas differ | Per-tool input translation | -| A6 | Prompt hooks see text only | Images are not text | Pass attachment paths | -| A7 | `SessionStart` runs only `startup`, for every Session whose `main` has no turn | Dim has no resume/clear/compact start; keyed blocks already survive compaction | More sources | -| A8 | At most 3 consecutive Stop follow-ups | Goal precedent; Claude's `stop_hook_active` | Unbounded loops | -| A9 | Submissions and calls while Hooks is unloaded pass without Hooks | Rare structural operation (D3); calls still pass Permission and Approval | Entries refusing input while Hooks reloads | -| A10 | Reading the Session with `dimcode export` needs the product home on the resource node's host, or a `--database` path the hook passes (A.3) | The node runs the Session and the hook processes | A remote resource node has no such home, and a hook there cannot read the Session | - -## Appendix F. Open questions - -| Question | Description | -| --- | --- | -| Questions as a notification | Questions asks through the `ask_user` tool call ([Questions](Questions.md)); a Claude `Notification` `elicitation_dialog` analogue would observe that call. Questions is Ready; this analogue is not designed and stays unsupported | -| pi extensions | pi hooks are TypeScript extension handlers, not commands; running them needs a TypeScript plugin runtime (#4), outside this mechanism | - -Neither is part of this design, and both stay unsupported. - ## Appendix G. Migrating from Claude Code and Codex Dim does not read Claude or Codex files and has no import command. To migrate, copy the `hooks` object: from `~/.claude/settings.json` or `~/.codex/hooks.json` into the user document (`dimcode hooks edit`, `dimcode hooks set PATH`, or Ctrl+E in `/hooks`, which call `hooks.save`), and from a repository's `.claude/settings.json`, `.claude/settings.local.json` or `.codex/hooks.json` into `.dimcode/hooks.json`, then enable that workspace (`hooks.set_enabled`). Codex `[hooks]` tables in `config.toml` are rewritten as JSON. Scripts keep working when they use only the compatible parts below. @@ -865,20 +370,3 @@ Codex `apply_patch` has no alias: its input is a patch, while Dim's `write` and | `PermissionRequest` deny | Claude/Codex show `message` | Approval's generic text | | `UserPromptSubmit` block | Prompt erased, reason shown | `session.submit` fails with `input_blocked`; ACP `refusal` | | Output fields | `continue`, `stopReason`, `systemMessage`, `suppressOutput`, … | Ignored with a diagnostic (A.4) | - -## Appendix H. Rust binding - -| Neutral | Rust | -| --- | --- | -| Admission decision | `Permission::admit_decision(call, source: &BranchSource, risk, cancel)` used by `Approval::admit`; `decide` stays for the recheck | -| `permission.registerAdvice` | Trait `AdviseTool` with `advise(ToolAdviceRequest, CancellationToken) -> HostFuture`; `Permission::register_advice(ctx, name, Arc)` on the branch's `Keyed`, kept in a `Registrations` table and withdrawn with the caller; `HooksBranch` registers `hooks`; Permission calls the advisors it holds at each admission (A.6.1) | -| `submitChecks` | Session service `SubmitChecks`, a name registered in the Session group and a `PublicService`, so Rpc reads it through `Session::session_service::()`; provided by InputQueue's Session part; `SubmitChecks::register(ctx, name, Arc)` with `check(SubmitCheckRequest, CancellationToken) -> HostFuture`, kept in a `Registrations` table and withdrawn with the caller; `HooksSession` registers `hooks` and Skills registers `skills` through `Keyed`; `Connection::submit`, `Connection::create_branch` and `InputMethods` call the registered checks before `Session::input`, `Session::branch` / admitting the withdrawal command (A.6.2) | -| `input_blocked` | `RpcError::app(-32000, "input_blocked", message)`; `data` is `{appError}` only | -| `warnings` | `SubmitWarning { check: String, message: String }` in `dim_agent_types::input`, serialized as `{check, message}` with no rename; carried by `SubmitResult` and `tree_protocol::CreateResult`, and set on the withdraw reply's `serde_json` object | -| `Approval.respond` | `Approval::respond(approval_id, ApprovalDecision)` from `Keyed` | -| `HookSources` | Session port `HookSourcesHost(Arc)`, bound by App Server as `CommandRules` and `SkillSettingsHost` are | -| `hooks`, `hooks-projects`, `hooks-plugins` | `BusinessDocument` types in App Server (`hooks`: `USER_FILE` `hooks.json`, no `PROJECT_FILE`; `hooks-projects`: `USER_FILE` `hooks-projects.json`; `hooks-plugins`: `USER_FILE` `hooks-plugins.json`, one `{dir, hooks}` entry per plugin id, as `McpPluginServers` in `mcp/config.rs`) | -| `.dimcode/hooks.json` | Read by `HooksSettings` through `FileStorage::path(root, ".dimcode/hooks.json")` and `read_limited`, `root` from `SettingsService::project_root(cwd)`, parsed into the `hooks` document type | -| `register`, `withdraw`, `plugins()` | `HooksService::register_plugin(plugin: String, dir: PathBuf, document: serde_json::Value, cancel: &CancellationToken) -> Result<()>`, `withdraw_plugin(plugin: String, cancel: &CancellationToken) -> Result<()>`, `plugins(cancel: &CancellationToken) -> Result>` and `plugin_refusal(&self, plugin: &str) -> Option<(String, Option<&'static str>)>`, as `McpService`'s (`crates/dim-app-server/src/mcp.rs`): a refused document leaves no entry, and `plugin_refusal` reports its error text with the static reason its cause carries, both read under one lock; PluginManager reads the service through `names.key()` in its `Owners`, its `Kind::Hooks` added to `OWNERS` and `CONTENT` ([PluginManager §3.7](PluginManager.md#37-content-registration)) | -| `hooks.*` | `Keyed`; `methods.register(ctx, "hooks", …)` | -| Runner | Session service `HooksRuntime`, private to Hooks; processes from `HostPlatform::build_process_spec` and `spawn`, with the event's stdin object (A.3) as the initial stdin (A.6.3), owned by `ctx.effect` | diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index a5878de3d4..a0407cbce4 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -163,56 +163,7 @@ tool_registry.register( `manager` is the process owner's operation/callback, not the `Manager` object. The request, reply and error types are the typed structures in `plugin_manager.rs` and the management module. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. -PluginManager keeps the plugin configuration of a host: which plugins are installed, where they came from, which plugin each name uses, and which names are turned off. It keeps this configuration in its own file, `plugins.json`, in Dim's own format. It keeps no runtime state, except, in memory, the content it refused itself (§3.7). Whether a plugin is loaded, running or failed is rutis' state, read from rutis-loader. What content an owner holds (skills, MCP servers, hooks, client UI) is that owner's state. PluginManager carries out a configuration change by giving commands to the owners: rutis-loader for plugin code, and SkillsCatalog, Mcp, Hooks and UiExtensions for content. Each owner decides and keeps its own state. - -A plugin is a directory with a manifest. It may carry code (a rutis plugin in TypeScript or Python), content (skills, MCP configuration, hooks, client UI), or both. Plugins are identified by **name**. Several plugins with the same name may be installed, but only one of them is used at a time. Turning another one on replaces the one in use. This is how a built-in plugin is replaced. - -## 0. Implementation boundary - -| Part | M1 (2026-11-01) | Later | -| --- | --- | --- | -| `plugins.json`, the default configuration file, the startup layer (§2, §3.1) | yes | | -| Install from a local path or Git, update, remove, list (§3.2–§3.6) | yes | marketplace | -| Optional plugins from the default configuration file, and a plugin's locked npm dependencies (§2.3, §3.2, §7) | yes | | -| Plugin code: create, turn on/off, replace, reload loader rows (§3) | yes, TypeScript and Python, once their runtimes are supplied (§2.5) | | -| `plugin.*` management methods and `dimcode plugin` commands (§6, A.1) | yes | client notifications of changes | -| Agent tools through a Session part (§6) | yes | | -| The default CLI loads the built-in SessionTitle, Scheduler, Goal and Web and the configured default plugin (plugin-authoring) | yes | | -| Settings sources registered at run time by every plugin itself (§9 R1) | yes, built-in and TypeScript plugins together | | -| Content kinds: skills, MCP configuration, hooks (§3, §9 R2) | skills and MCP if their owners land in time; hooks (Hooks is M1) | | - -M1's acceptance is: a user or the agent writes a TypeScript plugin, installs it from a local path, uses its tools, edits it and reloads it, and the change takes effect without a restart; the default CLI starts with the default plugins loaded. Plugin code needs its runtime, which [#476](https://github.com/arcships/dim/issues/476) supplies. - -## 1. Structure - -```mermaid -flowchart LR - subgraph AS["App Server process"] - PM["PluginManager
plugins.json, plugin.* methods"]:::new - LOADER["rutis-loader
rows: built-in, default, installed"] - RPC["Rpc"] - OWN["Content owners
SkillsCatalog, Mcp, Hooks, UiExtensions"] - SET["Settings"] - CODE["Plugin code rows"] - PT["PluginTools (Session part)
plugin tool"]:::new - end - RPC -->|"plugin.* (managementMethods)"| PM - PM -->|"reconcile derived layer, reload"| LOADER - LOADER --> CODE - PM -->|"register / withdraw (if present)"| OWN - CODE -->|"register own Settings sources"| SET - PT -->|"same operations"| PM - PT -->|"config: read, update"| SET - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -- PluginManager is one process row. It is locked (§2.3): it cannot be turned off or replaced, because nothing could turn it back on. -- It injects the loader handle and `managementMethods`. It reads the content owners only if present (`Option>`, not a gate): a missing owner skips only that kind of content. -- It registers a Session part, `PluginTools`, with `partRegistry`. The part registers the `plugin` tool with the Session's `toolRegistry`; each call goes to PluginManager's process service, and `config` goes to Settings (§6). -- Owners never look for plugins and never read `plugins.json`. - ## 2. Data - ### 2.1 The plugin directory and its manifest A plugin is a directory with `dim-plugin.json` at its root. The keys present say which kinds the plugin carries. @@ -362,111 +313,9 @@ Shipped with Dim, read-only, given to the App Server with `--defaults PATH` (the - A name cannot appear in both `plugins` and `optional`, and an optional plugin's name cannot be a built-in plugin's: each is a startup error naming both. An optional plugin's item has no candidates (§3.6), so it would hide the plugin shipped under that name. - `locked` lists names that cannot be turned off and whose plugin cannot be switched. Other plugins of a locked name may still be installed. Locking is product configuration; PluginManager applies it. -### 2.4 State PluginManager does not keep - -| State | Owner | Read through | -| --- | --- | --- | -| Which rows exist and their `EntryStatus` | rutis-loader | `Loader::entries()`, `Loader::get(id)`, `Loader::waits`; shown as in A.1 | -| Which built-in rutis plugins exist | the App Server's assembly | rows of the `assembly` layer in `Loader::entries()`; the row id is the plugin's name | -| Skills, MCP servers, hooks registered from a plugin | SkillsCatalog, Mcp, Hooks | the owner's own methods | -| A plugin's business configuration | the plugin's Settings sources | Settings | - -### 2.5 Runtimes - -Plugin code runs in the Node or Python rutis runtime. Supplying them is not PluginManager's business: how runtimes are acquired, pinned and verified, and how plugin rows start once a runtime is available, is [RuntimeManager](RuntimeManager.md) ([#476](https://github.com/arcships/dim/issues/476), M1). PluginManager only creates rows; a row whose runtime is not there is `pending` in `plugin.list`, waiting for the runtime's connection row (`session-node` or `py`). How far the runtime itself got (acquiring, failed, starting, down) is `runtime.list`'s. Reload re-imports only the entry module ([requirement 3](../plugin-management.md)). - -A TypeScript row is named by its entry file's absolute path. A Python plugin is imported through a link PluginManager keeps: `/plugins/.python/` points to the plugin directory, where `` is its id (a default plugin's name) with `-` as `_`; its row is named `py:.`, and the plugin uses relative imports inside its package. PluginManager creates the link when the plugin is turned on, points it at the new directory after an update, and removes it when the plugin is removed. The Python runtime imports from `/plugins/.python/` (#476). - -Turning a name on never installs its runtime on PluginManager's own authority, and startup never does: a runtime is requested only inside a client's `plugin.install`, `plugin.enable` or `plugin.update` call, and inside the background re-acquisition of an optional plugin (§3.1). It is never requested in the startup reconcile, an owner-on reconcile or a reload, and never for a name that is in its shipped state. When such a call turns on a plugin with code whose runtime is off, PluginManager asks RuntimeManager for it — `RuntimeService::install("node")` or `install("python")` (§9 R5) — and replies with the row `pending`, `waitingFor` its connection row. It does not wait for acquisition there; the runtime's progress is read from `runtime.list`. A dependency install is the one place PluginManager waits for Node, and RuntimeManager's `installPackages` owns that wait (§3.2). - -## 3. Flows - -How PluginManager's configuration maps onto rutis-loader. The loader has two layers. `assembly` holds the built-in rows. `plugins` is derived from `plugins.json` and the default configuration file; rutis keeps no copy of it beyond the running tree. It holds the rows of default and installed plugins in use and the `disabled` overrides of built-in rows. PluginManager's rows have the row id `plugin:`: one row per name, which cannot collide with a built-in row id, since the built-in row of that name stays in the composed tree when it is disabled. - -| Name N in `plugins.json` | In the derived `plugins` layer | -| --- | --- | -| Uses a default or installed plugin P with code | The row `plugin:N` from P's manifest | -| Uses its built-in | Nothing: the built-in row runs | -| Off, or uses a plugin other than its built-in | `disabled: true` on the built-in row N, if there is one | - -A configuration change writes `plugins.json`, derives the `plugins` layer again and gives the loader `reconcile([assembly, plugins])`. A row rutis refuses stays in the loader and `plugin.list` shows rutis' status and reason, as after a restart. A reload is `Loader::reload("plugin:N")` when the row's fields are unchanged. rutis lets a layer disable a built-in row and override its fields, but not rename or remove it, so replacing a built-in disables its row and adds a row for the new plugin. rutis reloads the dependents of the rows that change. - -Content follows the same switch: when name N stops using P, PluginManager withdraws P's content from each present owner; when N starts using P, it registers P's content with each present owner (§3.7). - -### 3.1 Startup - -1. The App Server calls PluginManager's startup function with the home and the default configuration file. Reading `plugins.json` is also the process's one cleanup: leftover staging directories and every directory under `/plugins//` that no installed entry refers to — Git copies and optional copies alike — are deleted there, before any row or acquisition exists, so it never deletes a directory that was renamed into place whose record is not written yet, and a reload of PluginManager's row deletes nothing. The function reads each used plugin's manifest and returns: - - the initial `plugins` layer: the rows of the default and installed plugins that are on, and `disabled: true` for each built-in name that is off or uses another plugin; - - the names whose `instanceNames` the catalog needs (§4); - - the built-in rows that are off, which the App Server drops from the rows it requires to become Active. -2. The App Server reconciles `[assembly, plugins]`. A built-in that is off never starts. -3. PluginManager's row applies and registers `plugin` with `managementMethods` and `PluginTools` with `partRegistry`. -4. After the process rows are up and content startup has run, an installed `{optional}` plugin whose recorded `version` differs from the shipped manifest's is re-acquired in the background, as `plugin.update` does for Git: the new copy is staged, its dependencies installed, renamed to `+`, the record switched and the layer reconciled, and the old directory left in place for the next start's cleanup. Until that succeeds the old copy stays in use. A failure keeps it, records `update.error` for `plugin.list`, and is retried at the next start or by `plugin.update {id}`. A shipped directory or manifest that cannot be read, or one without a version, is not re-acquired and offers no `update`: it is logged at `warn` naming the plugin and the path. The re-acquisition does not block client admission. It starts once per process start and belongs to the generation of PluginManager's row: an unload cancels it, which also cancels a running npm through the cancellation `installPackages` takes. A reload of the row does not start another one; the retry is the next start or `plugin.update {id}`. - -A default or installed plugin whose row fails does not fail startup; `plugin.list` shows it as failed with rutis' error. A used plugin whose manifest cannot be read runs nothing: it gets no row, and its content of every kind is withdrawn from every present owner. Once the process rows are up, before clients are admitted, the App Server calls PluginManager's content startup, which brings every present owner to the record (§3.7). - -### 3.2 Install - -`plugin.install {source, id?, enable?}`. `enable` defaults to `true` ([requirement 2](../plugin-management.md): installed means usable). - -1. When the caller gives `id`, check it (§7) and refuse an `id` already installed (`plugin_exists`) before acquiring anything, whatever its source. For `{optional}`, refuse a name the default configuration file does not ship (`optional_not_found`) before acquiring anything. -2. Acquire (§7): a local path is checked in place; a Git source is cloned into a staging directory and its manifest read; an optional source is copied — without `node_modules` — into a staging directory and its manifest read. Without a given `id`, the id is the manifest name lowercased, checked and refused if installed in the same way. -3. Dependencies: when the manifest declares `dependencies`, PluginManager calls RuntimeManager's `installPackages(staging, cancel)` once (§7, §9 R5), and the call's progress sink reports the `dependencies` phase meanwhile. That call turns Node on and waits for its acquisition when Node is off, and runs npm only once Node is usable. A failure deletes the staging directory and changes nothing: `node_unavailable` with the acquisition's reason when Node could not be supplied, `dependencies_failed` with npm's message otherwise. -4. Rename the staging directory to `/plugins//+`, where `` is the Git commit or the optional plugin's `version` and `` is 16 lowercase hex characters drawn from a random source for this acquisition. The name must not exist; if it does, draw a new suffix. No acquisition ever replaces or reuses an existing directory. Any failure deletes the staging directory. -5. Write `plugins.json` with the new entry, and, when `enable` is true and the name is not locked, `names..use = id`. -6. If it was turned on: reconcile the derived layer (§3). The reply carries the row's status and any content an owner refused. - -A local-path plugin is used in place and its declared dependencies are not installed: they are the user's own, as the authoring guide's packaging section says. Installing a plugin whose name is locked records it without turning it on, and says so in the reply. - -### 3.3 Turn on, turn off, switch - -- `plugin.enable {name, use?}`: `use` is an installed id, `"builtin"` or `"default"`; absent, the name's current `use`. Refused for a locked name when `use` changes (`plugin_locked`). Writes `names.` (clears `off`, sets `use`), then reconciles the derived layer (§3). When this call turns on a plugin whose runtime is off, it requests the runtime (§2.5); the startup reconcile never does. -- `plugin.disable {name}`: refused for a locked name. Writes `off: true`, then reconciles the derived layer. -- `plugin.enable`, `plugin.disable` and `plugin.reload` naming a name with no candidate — no installed entry, no default plugin and no built-in plugin — are refused with `plugin_not_found`, as for an unknown name; when the name is an uninstalled optional plugin's, the message names `plugin.install {source: {optional: ""}}`. That concrete form stays in the message the model-facing `plugin` tool and the log see: the client RPC boundary keeps one static description per code (A.2), so a client learns from `plugin.list` that the item is optional and offers Install. Nothing is installed and the call requests no runtime: installing is always an explicit `plugin.install`, and `enable` turns on what is installed; it never acquires (§2.5). A name that has a candidate — built-in, default or installed — is not affected. - -When a content owner itself is turned on (Hooks, for example), PluginManager registers the content of every plugin in use that carries that kind (§3.7). - -### 3.4 Reload - -`plugin.reload {name}` reloads the plugin the name uses. The host watches no files; the call is the signal that something changed. - -1. Read the manifest again. A read that fails refuses the reload (`invalid_manifest`) and withdraws its UI snapshot. The plugin keeps its last good code row and other content until the next change of the record, from any command, or a restart. Both read the manifest again and run none of the plugin's content while it cannot be read (§3.1). If its name changed, refuse (`name_changed`); the user installs it again under the new name. -2. Code: `Loader::reload("plugin:")`, and nothing else: there is no resolver cache to clear, since the runtime describes the module again at every resolution. rutis re-imports the plugin's entry module (modules it imports are not re-imported; [requirement 3](../plugin-management.md)) and starts a new generation; its parts in Sessions and branches are replaced and its dependents reload. If the manifest's `code` fields changed, PluginManager reconciles the derived layer, which carries the row with the new fields. -3. Content: register each kind again with its present owner; the new document replaces the old one. A kind the manifest no longer carries is withdrawn. -4. Update `kinds` in `plugins.json` if they changed. - -A name using a built-in Rust plugin cannot be reloaded (`not_reloadable`): it needs a rebuild; it can be replaced (§3.3). -### 3.5 Update +## Command protocol -`plugin.update {id, ref?}` for a Git plugin: fetch and check the new commit into a new directory as in §3.2, install its declared dependencies there before the record changes, write the new `commit` and `dir` (`+`), then, if the plugin is in use, reconcile the derived layer (its row carries the new entry path). A failed dependency install deletes the new directory, keeps the old commit and changes nothing. The old directory is left in place and the next start's cleanup deletes it. For an `{optional}` plugin, `plugin.update {id}` re-copies the shipped directory at its current version — repairing a failed re-acquisition and picking up a new shipped version — and does the same: stage, install dependencies, rename to `+`, switch the record, reconcile if in use, and leave the old directory to the next start's cleanup; a failure keeps the old copy and records `update.error`, while a cancelled attempt records no `update.error`. At an unchanged version the new copy therefore gets its own `+` directory instead of replacing the one in use. A local-path plugin has nothing to update (`not_updatable`); reload it. Asking the user to confirm an update is the client's business. - -### 3.6 Remove and list - -- `plugin.remove {id}`: if a name uses it, the name stops using it: when the name has a built-in or default plugin, `names..use` is dropped and the name goes back to that plugin (still `off` if it was off); otherwise the `names.` entry is removed and nothing runs under that name. Remove the entry from `plugins.json`; its Git or optional directory is left in place and the next start's cleanup deletes it (`/plugins//` keeps no more than the copies one process's history produced). A local directory is never deleted. Built-in and default plugins cannot be removed (`not_removable`); they can be turned off. -- `plugin.list {}`: one item per name, built from `plugins.json`, the default configuration file (`plugins` and `optional`) and the `assembly` rows, with each candidate and the one in use; status comes from `Loader::get` at the time of the call. An optional plugin that is not installed has its own item: `{name, use: null, off: true, locked: false, candidates: [], optional: true}`, with no status, so a client can offer it. `off` is a report, not a recorded state — nothing runs under the name and `plugins.json` holds nothing for it (§2.3) — and `off: true` keeps a client that does not know `optional` honest: with `off: false` it would render the name as running and offer Disable and Reload, which fail, while `off: true` renders it inert. A client that knows `optional` offers Install instead; the TUI's toggle shows the install hint itself rather than calling `plugin.enable` (§3.3). Once installed, its item is like any installed name's. The `optional` marker is the plugin's provenance: it is present when the name is in the shipped `optional` map or when any installed entry of the name came from an `{optional}` source, so a copy keeps it after a later release drops the name from the map. `update` follows the entry a re-acquisition would act on: the `{optional}` entry the name uses when it is the one in use, otherwise the name's last installed `{optional}` entry in record order, so an off name, or one using another candidate, still carries it. An installed optional plugin whose shipped version differs carries `update: {version, error?}`: `version` is the shipped version it is moving to, and `error` is the last re-acquisition failure. - -### 3.7 Content registration - -For each kind P carries and each owner present, PluginManager calls the owner's `register({plugin, dir, document})` and, to withdraw, `withdraw({plugin})`, where `plugin` is the plugin's id: its installed id, or a default plugin's name (§7), so it is safe in server ids and file names. When a name switches from one plugin to another, the old plugin's content is withdrawn; a kind the plugin no longer carries is withdrawn. The owner keeps registrations and restores them after its own reload. UiExtensions retains the validated source declarations across process-row generations and rebuilds its transient snapshots; process restart obtains registrations from PluginManager. Other content owners persist their own documents. PluginManager does not watch owners and registers nothing again on their behalf. An owner that is absent when PluginManager would call it is skipped; the reply names the skipped kinds. An owner reports the plugin ids it holds. At startup, and when PluginManager turns an owner's name on, PluginManager registers that kind of content of every plugin in use and withdraws it for every other id the owner holds; owners never look for plugins. So content restored by an owner for a plugin removed while the owner was off, or left by a process that stopped between writing `plugins.json` and commanding the owner, does not run again, and a refusal is reported again after a restart. - -An owner validates what it is given. Content it refuses (an MCP document that fails Mcp's validation, a Skill whose `SKILL.md` does not parse) does not stop the plugin's other content or code: the reply names it under `refused`, and `plugin.list` shows what the owners report for the plugin at the time of the call. PluginManager refuses a JSON content file it cannot read or that is not JSON. It keeps that refusal in memory, keyed by plugin id and kind, only while the last read of that kind failed: any later handling of the kind that reads nothing or reads it successfully clears it (the document handed over, the manifest no longer naming the kind, the kind skipped because its owner is absent), as do withdrawing the kind and removing the plugin. `plugin.list` shows it in the same `refused` entry, in place of the owner's, and only while the kind's owner is present; the replies of `plugin.install`, `plugin.enable`, `plugin.reload` and `plugin.update` name it under `refused`. A refusal in the startup or owner-on reconcile is logged at `warn` with the plugin id, the kind and the error. - -## 4. Timing and conflicts - -- PluginManager changes `plugins.json` in one step on its in-memory table, then writes the file, then reconciles the layer derived from it and gives owners their commands. A second operation on the same id or name sees the first one's change (`plugin_exists`, or it acts on the new state). Deriving the layer and reconciling it run one at a time, each from the record as it is then, so the layer reconciled last is the latest record's. rutis-loader runs its own operations one at a time. -- Every file system change for a plugin — staging, clone, copy, rename, dependency install, and the startup cleanup — runs one at a time, in one queue. The cleanup therefore never runs between an acquisition's rename and its record write, and it never deletes a directory another operation is about to name. -- A row that rutis or a command that an owner refuses leaves the configuration as written; the item shows the refusal in `plugin.list` (for example, the new plugin failed because another plugin of a different name provides the same service). -- `instanceNames`: rutis needs the names a plugin's parts provide in Sessions and branches in the catalog before the runtime starts ([rutis usage §2](../rutis-usage.md#2-plugins-are-rows-instances-mount-their-parts)). Installing, switching or reloading to a plugin whose `instanceNames` are not in the running catalog records the change and replies `restartRequired`; the row is created at the next start. Plugins that only register tools, methods or prompt sources do not have this limit. -- A reload or replacement in use: the old generation unloads, rutis cancels its running calls, and in-flight turns using it may fail ([ADR 002](../../adr/002-plugin-scope.md) consequences). This is documented, not prevented. - -## 5. Context mapping - -PluginManager adds no text of its own to model context beyond the `plugin` tool. A plugin's tools and prompt sources reach the model through their own registrations ([ADR 006 D4](../../adr/006-plugin-contract.md)). The tool's texts are marked by [model-facing prompts §4](../model-prompts.md#4-protocol-and-policy). The declaration's schema is protocol, and so is "Manage Dim plugins.", which states the tool's reach; the one-line command list it carries, with the command names and each command's argument grammar, is protocol too, because the tool parses them exactly. "Run `help ` for a command's details." is policy guidance, with `help ` protocol because it names the command to call; that sentence has no factory member yet, and gets one in the change that first evaluates a candidate for it. In a usage text the `Usage:` line is protocol, and the sentences after it, and in `help`, that say what a command does or does not touch are policy. A malformed command's error result carries the command list or that command's usage, and a refused call's error carries its code (A.2) — both protocol. A completed call's result says what changed, the status, and `restartRequired` when it applies; that is protocol too, because the model decides its next step by it. - -## 6. Interfaces (summary) - -- Management methods, namespace `plugin` (A.1): `list`, `install`, `enable`, `disable`, `reload`, `update`, `remove`. - CLI: `dimcode plugin list | install [--ref R] [--id ID] [--no-enable] | install --optional [--id ID] [--no-enable] | enable [--use ID|builtin|default] | disable | reload | update | remove `. - Agent tool from `PluginTools`: one tool, `plugin`, with one string parameter `command`, written like the CLI's arguments: whitespace separates words, single or double quotes group one (a path with spaces is quoted), and a backslash is an ordinary character, so a Windows path is written as is: @@ -478,9 +327,6 @@ PluginManager adds no text of its own to model context beyond the `plugin` tool. | `help [command]` | The command list, or one command's usage and details. | The tool's description carries only the one-line command list; `help` gives the details, and a malformed command's error result carries that command's usage. The tool is a tool call: Permission decides each one ([requirement 5](../plugin-management.md), [ADR 003](../../adr/003-approval-scope.md)). Its declared risk is `persistent_configuration`; `list` and `help` are admitted as `read_filesystem` (R3); `config`, whose documents may hold secrets and user content, is admitted at the declared risk, as the sources' own tools are. -- Plugin authoring: the default plugin `plugin-authoring` carries one Skill, `plugin-authoring`, which teaches the agent to write a TypeScript plugin and install it with this tool. It is content only (§2.1) and can be turned off like any default plugin. -- Owner operations PluginManager calls: `register` / `withdraw` on SkillsCatalog, Mcp and Hooks (§9 R2). - ## 7. Security Installing and turning on are host configuration done through management methods or tool calls; enabled plugin code runs without host-local approval ([ADR 003](../../adr/003-approval-scope.md)). PluginManager adds no scope, approval or trust step ([requirements](../plugin-management.md)). What it guards is the acquisition itself: @@ -494,196 +340,3 @@ Installing and turning on are host configuration done through management methods - `plugins.json` is written atomically (§2.2). The acquisition and link-check code behind these rules is one crate-internal implementation, `crates/dim-app-server/src/plugin_manager/acquire.rs`, shared with the Skills installation ([Skills](Skills.md) §4), which reads a local directory or clones a repository for its own destination, staging directory and record. The rules above are stated once because there is one implementation. - -## 8. Rule check - -PluginManager is not a Capability: it has no Timeline state, writes no Timeline event and has no branch part. - -| Rule | How this document complies | -| --- | --- | -| Principles §4 rule 1 (commands for others' state) | Loader rows are rutis' state and content is its owners' state; PluginManager only gives them commands and reads their state when asked. | -| Principles §4 rule 2 (handover) | Not applicable: no input or Timeline handover. | -| Principles §4 rule 3 (before callbacks only) | No intervention before a write. | -| Principles §4 rule 4 (no business meaning in core) | The owner `register`/`withdraw` operations and Settings registration (§9) carry no plugin-management meaning; any caller may use them. | -| Principles §4 rule 5 (batch) | Not applicable. | -| Principles §4 rule 6 (context from handed-over events) | Nothing enters model context except tool results (§5). | -| Principles §4 rule 7 (public events and services only) | rutis-loader's public `Loader` API, `managementMethods`, `partRegistry`, `toolRegistry` and the owners' public services. | -| Principles §4 rule 8 (requirements to mechanism owners) | §9: Settings, SkillsCatalog, Mcp, Hooks, ToolExecutor and Permission; none to rutis. | -| Principles §4 rule 9 (only facts later decisions use) | Configuration lives in `plugins.json`, the only record; runtime state is read from its owners. | -| Principles §1 (Capability and App Server boundary) | A process plugin of the App Server; no Capability. | -| ADR 002 D1 (scope follows state) | Process: installation is per host. `PluginTools` is a Session part only because tools are registered per Session. | -| ADR 002 D2 (no wiring modules) | No wiring: owners are called through their registration operations. | -| ADR 002 D3 (dependencies follow scope) | Process dependencies only; owners are optional reads, so their reload does not reload PluginManager. | -| ADR 002 D4 (structural vs business configuration) | Structural configuration (installed, used, off) is `plugins.json`; business configuration stays in each plugin's Settings sources, registered by the plugin. | -| ADR 002 D5 (language-neutral contracts) | Methods and owner operations are JSON contracts. | -| ADR 006 D3 as corrected by ADR 007 (a plugin's code is one row) | Each plugin with code is one process row, created, turned off and reloaded by PluginManager's commands; content is not a row ([ADR 007](../../adr/007-plugin-configuration.md)). | - -## 9. Requirements raised to mechanism owners - -None to rutis: every loader operation used exists in rutis-loader 0.23.0. - -**R1. Settings: sources registered at run time (M1).** - -| Item | Content | -| --- | --- | -| Blocked by | Settings sources are fixed when the App Server builds Settings: built-in Rust owners are listed in code (`.reserve::()`), TypeScript rows' `settings` members are read at startup (`.declare()`). A plugin installed, replaced or removed at run time cannot add or withdraw its sources. | -| Existing mechanisms considered | PluginManager registering sources from the manifest (business configuration is not plugin management, ADR 002 D4); a restart per install (violates requirement 3). | -| Generic capability | `settings.register(declaration)` on the named `settings` service, with the declaration of today's `settings` member (`source`, `userFile`, `projectFile?`, `schema`, `userOnly`). The registration belongs to the caller and is withdrawn when it unloads; a second registration of the same source name fails. Every owner, built-in Rust and TypeScript alike, registers its sources in its `apply`. The stored documents stay in the home whether or not a source is registered. The hard-coded `.reserve::()` and `.declare()` paths are removed. | -| Effect on sequence, batch, interrupt, reload | No Timeline effect. A reload registers again from the new generation. | -| Owner and issue | Settings (App Server); to be filed with #384. | - -**R2. SkillsCatalog, Mcp, Hooks: register plugin content and keep it (M1 for all three; SkillsCatalog and Mcp if they land in time).** - -| Item | Content | -| --- | --- | -| Blocked by | Owners read only user and project sources; there is no way to hand them a plugin's content. | -| Existing mechanisms considered | A `pluginContents` service owners read (owners would look for plugins; rejected); content as loader rows (Dim product state in rutis; rejected). | -| Generic capability | A process operation `register({plugin, dir, document})` that adds or replaces the content of `plugin` (a plugin id, §3.7), and `withdraw({plugin})`, plus a read of what the owner refused for `plugin`. The owner keeps registered content as its own state, persists it in its own storage, and restores it after its own reload. Mcp prefixes server ids with `plugin` (`:`); Hooks names the source `plugin:` and gives commands `DIM_PLUGIN_ROOT = dir`; SkillsCatalog reads Skills under `dir`. | -| Effect on sequence, batch, interrupt, reload | As each owner's existing sources: a change is a data update the owner announces its own way. | -| Owner and issue | SkillsCatalog, Mcp, Hooks ([Hooks](Hooks.md)). | - -**R3. ToolExecutor and Permission: the risk of one call (M1).** - -| Item | Content | -| --- | --- | -| Blocked by | A tool's risk is fixed in its definition, so one tool with read-only and changing commands is admitted at its highest risk: `plugin list` would ask for approval under workspace-write and be denied under read-only. | -| Existing mechanisms considered | One tool per operation (the seven tools this replaces; too many for the model); `execute_process` with a `command` input (Permission would apply shell command rules to plugin commands). | -| Generic capability | A tool handler may name the risk of one call; Approval and Permission admit the call under it, and a handler that names none is admitted under its definition's risk. | -| Effect on sequence, batch, interrupt, reload | None: admission order and events are unchanged. | -| Owner and issue | ToolExecutor and Permission (capabilities); with #384. | - -**R4. Settings: the sources a plugin registered (M1).** - -| Item | Content | -| --- | --- | -| Blocked by | Settings knows each source's name and schema but not which plugin registered it, so `plugin config ` cannot find a plugin's sources. | -| Existing mechanisms considered | Listing sources in the manifest (business configuration is not plugin management, R1); naming sources after plugins (not a rule; one plugin may register several). | -| Generic capability | Settings keeps, with each registration, the identity of the registering plugin's fiber, and lists the declared sources one fiber registered. PluginManager finds the fiber of the row a name uses through the loader. | -| Effect on sequence, batch, interrupt, reload | None. A reloaded row keeps its fiber identity and registers again. | -| Owner and issue | Settings (App Server); with #384. | - -**R5. RuntimeManager: a plugin's npm dependencies and its runtime request (M1).** - -| Item | Content | -| --- | --- | -| Blocked by | `RuntimeService` offers `list` and `install` only: PluginManager cannot run npm over a plugin's lock, and the runtime request exists only for Python's links ([RuntimeManager](RuntimeManager.md) §4, §9 R1). | -| Existing mechanisms considered | PluginManager running npm itself (duplicates RuntimeManager's registry, package and failure rules; rejected); requiring the user to install Node first (the Python path already asks for its runtime). | -| Generic capability | `installPackages(dir, cancel)` on the process `RuntimeService`: turns Node on and waits for its acquisition when Node is off, using RuntimeManager's own state, then runs the managed (or `system`) Node's own npm inside `dir` over `dir/package-lock.json` with `npm ci --omit=dev --ignore-scripts --no-audit --no-fund --workspaces=false --registry `, the registry chosen from `DIMCODE_NPM_REGISTRY` and then `npmRegistries`, and returns when npm exits. Errors: `node_unavailable` with the acquisition's reason when Node could not be supplied, `npm_unavailable`, `install_failed {reason}`, `cancelled`. The `install(name)` request the Python path already gets is extended to `node` for the client calls that turn a plugin on while Node is off and for the background re-acquisition of an optional plugin — never for startup, an owner-on reconcile, a reload or a name in its shipped state. | -| Effect on sequence, batch, interrupt, reload | None on rows: the install finishes before the directory is renamed into place, and a cancelled or failed install deletes it. | -| Owner and issue | RuntimeManager (App Server); with #476. | - -## Appendix A. Interface details - -### A.1 Methods (`managementMethods`, namespace `plugin`) - -| Method | Params | Result | -| --- | --- | --- | -| `plugin.list` | `{}` | `[{name, use?, off, locked, optional?, update?: {version, error?}, candidates: [{id \| "builtin" \| "default", source?, kinds}], status?, error?, waitingFor?, refused?}]` | -| `plugin.install` | `{source: {path} \| {git, ref?} \| {optional: ""}, id?, enable?}` | `{id, name, enabled, status?, skipped?: [kind], refused?: [{kind, error}], restartRequired?}` | -| `plugin.enable` | `{name, use?}` | `{status?, skipped?, refused?, restartRequired?}` | -| `plugin.disable` | `{name}` | `{}` | -| `plugin.reload` | `{name}` | `{status?, skipped?, refused?, restartRequired?}` | -| `plugin.update` | `{id, ref?}` | `{commit?, version?, status?, skipped?, refused?, restartRequired?}` | -| `plugin.remove` | `{id}` | `{}` | - -`status`, for a name whose plugin in use has code, is the row's `EntryStatus` from `Loader::get`: `Inactive` → `pending` (with `waitingFor`, the services of `Loader::waits`; a row waiting for its runtime names the runtime's connection row, `session-node` or `py`), `Unresolved` → `failed` (with `error`), `Running` → `running`, `Stopped` → `stopped`. A name that is off has no plugin in use and shows `off` instead of a status. `install` and `update` report the phases `fetch`, `check`, `dependencies` and `load` through the call's progress sink; `dependencies` is absent when the plugin declares none. A `plugin.update` reply carries `commit` for a Git source and `version` for an `{optional}` one; a local-path plugin has neither. - -The client RPC boundary's projection of sources, status errors and content -refusals, and every reason a refusal can carry, is in A.2. - -### A.2 Errors - -`plugin_exists`, `plugin_not_found`, `invalid_id`, `path_outside_plugins` (both before any file system change, §7), `plugin_locked`, `not_removable`, `not_reloadable`, `not_updatable`, `name_changed`, `invalid_manifest` (with the field and reason), `invalid_source` (scheme or argument refused), `acquire_failed` (Git's message), `optional_not_found` (the default configuration file ships no optional plugin of that name), `node_unavailable` (Node could not be supplied for a dependency install), `dependencies_failed` (npm's message), `record_unreadable` (startup). A loader or owner refusal after the configuration was written is not an error of the call: it is reported in the result and in `plugin.list`. - -The codes are stable across clients. Client RPC errors identify their code with a -stable, actionable description without including the owner's raw diagnostic message -or echoing request fields; the descriptions above identify the owner's error, not a -permission to publish secrets. - -The client RPC boundary omits Git source userinfo, query and fragment, preserving -the repository path, ref and commit. The persisted source is unchanged and remains -available to update. Only catalog candidate sources, top-level status errors and -direct content-refusal errors are projected; plugin-owned settings are not traversed. -Status errors carry a generic message at this boundary, including in mutation replies: -arbitrary Git, loader and manifest text can contain credentials. - -A content refusal reaches the client with the static reason its cause carries — -its owner's, or PluginManager's own for a content file it reads itself — and as -the generic "Plugin content was refused" otherwise. A reason never carries a -source position or the raw text, and the raw text, with the paths and URLs in it, -stays in the server's logs and in the model-facing `plugin` tool. - -| Owner | Kind | Cause | Reason | -| --- | --- | --- | --- | -| PluginManager | `mcp` | The content file is not valid JSON | the file is not valid JSON | -| PluginManager | `mcp` | The content file could not be read | the file could not be read | -| PluginManager | `hooks` | The content file is not valid JSON | the file is not valid JSON | -| PluginManager | `hooks` | The content file could not be read | the file could not be read | -| McpSettings | `mcp` | The document is not a JSON object | MCP document must be a JSON object | -| McpSettings | `mcp` | The document has no `mcpServers` object | MCP document must contain an mcpServers object | -| McpSettings | `mcp` | `mcpServers` is not a JSON object | mcpServers must be a JSON object | -| McpSettings | `mcp` | A server entry id is empty | MCP server entry id is empty | -| McpSettings | `mcp` | A stdio entry `cwd` is not a directory inside the plugin | MCP plugin cwd must be a directory inside the plugin | -| HooksSettings | `hooks` | The document is not a valid hooks document | invalid hook document | - -The table is the contract: a client matches a refusal by its exact message. The -skills and UI kinds have no reasons, because their refusals name files and paths. -A missing content file is not in the table: `Manifest::read` resolves every -content path and refuses a missing one as `invalid_manifest` before PluginManager -reads it. The table lists every reason a plugin's own content can produce; the -wire can also carry a static message from Dim's own registration state — such as -`invalid hook plugin registration` for a damaged `hooks-plugins.json` — which is -outside this table, and a client must show any message it does not know as it -shows the generic one. - -## Appendix B. Conflict table - -| Scenario | Outcome | Who decides | -| --- | --- | --- | -| Two installs of one id | The second sees the first entry: `plugin_exists` | PluginManager | -| Plugin of a different name provides a service already provided | rutis fails the new row; `plugin.list` shows the error | rutis | -| Replace a built-in that others depend on | The built-in row turns off, the new row starts; rutis reloads the dependents | rutis | -| Reload while a Session uses the plugin's tools | Old generation unloads, calls cancelled, new parts mounted | rutis, the instance's mounters | -| Content owner absent at install | That kind is skipped and reported; registered when PluginManager turns the owner on | PluginManager, owner | -| Content owner reloads | It restores its own registered content | owner | -| Plugin removed while its owner is off | Its content is withdrawn when the owner is turned on or at the next start | PluginManager | -| `instanceNames` not in the running catalog | Configuration recorded, `restartRequired`; row created at next start | PluginManager | -| Process stops during a Git install | Staging directory deleted at next start; `plugins.json` was not written | PluginManager | -| Install of an optional plugin the file does not ship | `optional_not_found`; nothing is created | PluginManager | -| Enable, disable or reload a name with no candidate | `plugin_not_found`, as for an unknown name; for an uninstalled optional plugin the message names `plugin.install {source: {optional: }}`; nothing is installed and no runtime is requested | PluginManager | -| An installed optional plugin's shipped version changes | Re-acquired in the background; the record switches only when the new copy is ready, the old copy serves and stays on disk until the next start's cleanup | PluginManager | -| Background re-acquisition or an optional `plugin.update` fails | Old copy stays and serves; `plugin.list` shows `update.error`; retried at the next start or by `plugin.update {id}` | PluginManager | -| Update or remove while a task holds a description | The old directory stays until the next start; the task keeps reading it | PluginManager | -| New acquisition names an existing directory | Draw a new ``; never replace or reuse | PluginManager | -| Process stops during a dependency install | Staging directory deleted at next start; `plugins.json` was not written | PluginManager | -| Dependency install fails during an update | New directory deleted, old commit, old directory and the record kept | PluginManager | -| Process stops after `plugins.json` was written, before the loader or owner command | Next start builds rows from `plugins.json` and brings the owners to it | PluginManager startup | - -## Appendix C. Acceptance (M1) - -1. With an isolated home, `dimcode` starts with plugin-authoring loaded. `dimcode plugin list` shows it and the built-in plugins, including SessionTitle, Scheduler, Goal and Web. Workflow is absent until it is explicitly installed and enabled. -2. `dimcode plugin install ./my-tool` (a TypeScript plugin registering one tool) makes the tool visible to the model in a new turn without a restart. -3. Editing `index.ts` and running `dimcode plugin reload my-tool` changes the tool's behavior in the open Session. -4. The agent does steps 2–3 through the `plugin` tool, each call decided by Permission; `plugin config goal set maxContinuations 5` changes goal's setting without a restart. -5. `dimcode plugin disable web` removes web's tools; `enable web` brings them back; the state survives a restart. -6. Installing a plugin named like a built-in and enabling it replaces the built-in; `enable --use builtin` switches back. -7. `disable PluginManager` is refused with `plugin_locked`. -8. A Git install with a `file://` URL is refused; a failed clone leaves nothing under `/plugins`; an install with the id `../x` is refused with `invalid_id` and creates nothing. -9. `dimcode plugin install ` of a fixture repository installs and turns on its plugin; after a second commit, `dimcode plugin update ` loads the new commit into a new `+` directory; the old directory remains until the next start, whose cleanup deletes it. -10. A default plugin's Settings source appears when it starts and disappears when it is turned off. -11. A Python plugin installed from a local path registers its tool, and reload picks up an edit to its entry module (with the Python runtime supplied by [#476](https://github.com/arcships/dim/issues/476)). -12. In a new Session the agent lists the `plugin-authoring` Skill and, asked to write a plugin with an echo tool and install it, does so without reading Dim's source. -13. An optional plugin the default configuration file ships appears in `plugin.list` with `optional: true` and no status; `dimcode plugin install --optional ` (a fixture plugin) copies its directory to `/plugins//+`, installs its locked npm dependencies there, and turns it on; the shipped directory carries no `node_modules` and is unchanged; `disable` and `enable` work as for any installed plugin; remove leaves the copy until the next start, whose cleanup deletes it, and leaves the shipped directory. -14. A Node plugin turned on by `plugin.enable` or `plugin.install` while Node is off requests the runtime and replies `pending` with `waitingFor`; when the runtime starts, the row runs without another command. A plain start of the same configuration, and a reload, request no runtime. -15. A Git plugin declaring `dependencies` gets them installed in its clone before the record changes; a failing install keeps the old commit and leaves no new directory; a manifest declaring them without `package-lock.json` fails `invalid_manifest`. -16. `dimcode plugin install --optional ` fails `optional_not_found` and creates nothing. -17. The shipped version of an installed optional fixture changes between two starts: the second start re-acquires it in the background into a new `+` directory, the record and `dir` switch, and the plugin keeps serving from the old copy; both directories exist until the next start, whose cleanup deletes the old one; with a failing dependency install the old copy stays and `plugin.list` shows `update.error` until the next start or `plugin.update ` repairs it. -18. `plugin.update ` of an optional fixture at an unchanged version creates a second `+` directory and switches the record; the old directory is untouched until the next start's cleanup. -19. A remove followed in the same process by an install of the same version gets a new `+` directory; both exist until the next start, whose cleanup deletes only the one no entry refers to. -20. `plugin.enable`, `plugin.disable` and `plugin.reload` naming an uninstalled optional fixture are refused with `plugin_not_found`; the message names `plugin.install {source: {optional: ""}}` while the client sees today's static description; nothing is installed and no runtime is requested. A default fixture name with no installed entry can still be disabled and enabled. -21. The Phase 2 `dim-cli` test deserializes a `plugin.list` response carrying the uninstalled optional fixture's item — `{name, use: null, off: true, locked: false, candidates: [], optional: true}` — into today's `PluginItem`, proving the shape stays decodable. -22. The TUI `/plugins` panel and the web settings page offer an Install action for an item with `optional: true`, calling `plugin.install {source: {optional: ""}}`; the TUI's toggle on such an item shows the install hint instead of calling `plugin.enable`; Desktop decodes the same additive fields and needs no change. - -## Appendix D. Open questions - -None in this design. Runtime acquisition, including how a Python plugin's module is imported from its directory, is [#476](https://github.com/arcships/dim/issues/476). diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index b51d7cfd8b..70a6089eac 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -203,45 +203,8 @@ Scope: process. Issue: [#740](https://github.com/arcships/dim/issues/740). Rules: [design rules](../../architecture/rust-agent/principles.md), [ADR 002](../../adr/002-plugin-scope.md). -This document owns one part of the Skills owner: how a Skill source that is not a Dim plugin -package is previewed, installed into the user scope, updated and removed. Skill discovery, -precedence, enablement, the Session view and the `skill` tool are the Skills capability's -existing contract ([Skills](../../architecture/rust-agent/plugins/Skills.md)); plugin packages -that carry Skills are PluginManager's ([PluginManager §3.7](PluginManager.md#37-content-registration)). -How an operator's `/skill:` token loads a Skill with the same input is §9. - -## 1. Scope and non-goals - -The owner is SkillsCatalog, the process part that already scans the user `.agents/skills` root, -the roots plugins registered and the project root. It gains one thing: a *Skill installation* — -a record of a source the user chose, the Skills taken from it, and the files it owns under the -user root. - -- **Preview** reads a local directory or a Git repository and returns the Skills it contains, - without writing anything. -- **Install** copies only the selected Skills into the user skills root, records the source and - publishes the result to the catalog. -- **Update** re-acquires the recorded source with the recorded selection. -- **Remove** deletes exactly what the record owns. - -There is no manifest requirement, no second store and no second plugin. The record is a field of -the Skills business document (`skills.json`), the files live in the user root the catalog already -scans, and publication is the catalog's existing version advance. - -Non-goals: - -| Not done here | Why | -| --- | --- | -| Project-scope installation | Project Skills come from the project source tree; the project content it carries starts disabled and only the local user configuration can enable it ([ADR 003](../../adr/003-approval-scope.md)). The user scope is the only destination. | -| Executable plugin code, MCP configuration, hooks | They belong to plugin packages (PluginManager) and are enabled and removed there. A source that also contains code installs only its Skills. | -| A Skill editor | The browser never edits Skill files ([web workspace §4.3](../web-workspace.md#43-settings-and-account-management-on-the-local-web-entry)). | -| A market or a source index | Later (plugin management requirements). | -| A filesystem watcher | Refresh stays an explicit operation, as it is today. | -| Per-Skill installations of one source | One installation per source and installation id; its selection is recorded once. Removing one Skill of the selection is a reinstall with the smaller selection. | -| Server-side preview state | The preview is stateless: the caller keeps the preview and passes its revision back. | - -## 2. Own contract +## Installation format and behavior ### 2.1 Source and revision A source is a local directory or a Git repository, acquired exactly as PluginManager acquires a @@ -273,68 +236,6 @@ grow the process. An installation's revision is the digest over its ordered sele source-relative path and per-Skill revision, so the same tree yields the same installation revision whether it came from a path or a clone, and an unchanged branch is not stale. -### 2.2 Reads - -`skills.preview {source, id?, cwd?}` takes a source and the installation id it would install as -(the caller derives it from the source when the user names none), and answers what installing it -could add. It writes nothing. `cwd` is the project directory the caller has open, as -`skills.catalog` takes it: its project root is read for `shadows` and nothing else. - -```json -{ - "source": {"git": "https://example.com/acme/skills", "ref": "main", "commit": "1a2b3c4d"}, - "skills": [ - {"path": "writing/review", "name": "review", "description": "Reviews a change against its spec.", - "revision": "sha256:…"} - ], - "conflicts": [], - "shadows": [ - {"path": "tooling/lint", "name": "lint", "by": "plugin:kit:tooling/lint"} - ], - "issues": [{"path": "broken/SKILL.md", "message": "missing description"}] -} -``` - -- `skills` lists every Skill the scan found, in scan order, by its source-relative directory - (`path`), the `name` and `description` its frontmatter declares, and the `revision` of its - files. `path` is the selection identity: a name may repeat across sources, a path cannot within - one tree. The revision is what the install compares against, so a caller cannot install content - it did not see. -- `source` echoes what was read, projected like every other reply: a canonical path, or the Git - URL with the commit that was acquired, so the caller can show what the selection belongs to. -- `conflicts` are reasons the install would be refused with this selection: a Skill whose name is - already provided by another Skill in the *user* root, where the winner would depend on - traversal order rather than on a defined precedence. The Skills of the installation named by - `id` are not conflicts: a replace excludes its own. -- `shadows` is information: the user root precedes plugin and project roots, so installing the - Skill hides a Skill of that name from those roots. The catalog reports it after the fact as - `shadowedBy`; before the install the user decides. -- `issues` are the scan's per-file problems, in the shape `skills.catalog` already returns. A tree - with issues can still be installed; the selected paths must exist in `skills`. -- There is no pagination and no cursor: the list is bounded by the scan limits the catalog already - applies (1000 `SKILL.md` files, depth 10, 4000-character metadata budget applies to model lists - only), and the caller filters the list it holds. A source that exceeds the limit reports - `ScanLimitReached` and the Skills found so far. - -`skills.installations` reads what was installed and from where: - -```json -{ - "installations": [ - { - "id": "acme-skills", - "source": {"git": "https://example.com/acme/skills", "ref": "main", "commit": "1a2b3c4d"}, - "revision": "sha256:…", - "skills": [{"path": "writing/review", "id": "user:acme-skills/writing/review"}] - } - ] -} -``` - -The read carries no `name`, `enabled` or `shadowedBy`: those are catalog facts, and the caller -joins by Skill id. A recorded Skill that the catalog does not list is simply absent from the -catalog until the installation is updated or removed. - ### 2.3 Install ```json @@ -365,7 +266,7 @@ Order: the existing `/`, when there is one, to `old`; rename `place` to `/`. A replacing install keeps its id and replaces the selection as a whole; the previous directory is deleted with the operation directory. -6. Commit the record through the Skills storage port, which writes the Skills business document +6. Commit the record through the SkillsCatalog's record (the Settings document), which writes the Skills business document with revision-conflict retry. 7. Rescan the user root, advance the catalog version and announce it, so a Session sees the Skills before the reply. @@ -408,228 +309,6 @@ If deleting the files fails, the record is kept and the reply says so, whether o was removed: the record is the only proof of what the installation owns, so it cannot be dropped first. The user retries; the next update reinstalls the files. -### 2.6 Ownership boundary with PluginManager - -A Skill installation is not a plugin: it has no manifest, no loader row, no enablement state of -its own, and no `plugin.*` operation accepts it. `skills.install` creates an installation, or -replaces one the record holds when the user confirms `overwrite`; an id that matches a plugin's -name is simply a new installation, and installing it changes no plugin state. `skills.update` and -`skills.remove` accept only ids the Skills record holds, and answer `skills_install_unknown` for -anything else, a plugin id included. -Plugin packages that carry Skills stay visible in the same settings page and keep their lifecycle -(`plugin.enable`, `plugin.disable`, `plugin.update`, `plugin.remove`), and their Skills keep the -`plugin::` ids and the `pluginSkills` roots SkillsCatalog already holds. - -### 2.7 Errors - -| Code | When | Recovery | -| --- | --- | --- | -| `skills_source_invalid` | the source is not an absolute directory, is not an `https://`/`ssh://` URL, or a link in the tree leaves it | correct the source | -| `skills_acquire_failed` | the clone or the staging directory failed | retry; check access to the repository | -| `skills_preview_stale` | a selected Skill's files changed since the preview, bundled files included | preview again and reselect | -| `skills_selection_invalid` | an install id that is not `[a-z0-9_-]{1,64}`, an empty or repeated selection, a path the scan did not find, a repeated name in the selection, a link inside a selected Skill, or a Skill file larger than the digest limit | correct the request | -| `skills_install_exists` | the id is recorded and `overwrite` is false | confirm overwrite or choose another id | -| `skills_install_unknown` | update or remove of an id the record does not hold, or an update whose record was removed or replaced while its source was acquired | refresh `skills.installations` and retry | -| `skills_install_unmanaged` | `/` exists but no record owns it; the reply names the Skills found there | choose another id, or move that directory | -| `skills_install_conflict` | a selected name is already provided by a user-root Skill outside this installation | remove or rename the other Skill, or drop the selection | -| `skills_install_failed` | copying or swapping the files failed; the previous state was restored | retry | -| `skills_write_failed`, `skills_conflict` | the record could not be written; the previous state was restored | retry; when the document changed, read it again and retry | -| `skills_remove_failed` | deleting the recorded files failed; the record was kept | retry; fix permissions | -| `skill_unknown`, `skills_sync_failed`, `skills_unavailable` | unchanged, from the existing catalog and enablement contract | unchanged | - -## 3. Events and state - -The installation record is part of the Skills business document in the user scope: one map from -installation id to its source, revision and selected paths. It is written only through the Skills -storage port (`SkillSettings`), the same path that already carries the disabled ids and the plugin -roots, with the same revision-conflict retry. Fields this version does not know are preserved, so -a newer document read by an older process is not lost, and no format version is introduced: the -document has always tolerated unknown members and the new field is additive. - -The record is business memory that survives a reload; nothing else is stored. The preview is not -kept, not on the host and not in the browser's persistence. - -No Timeline event and no new bus event: publication is `skills.catalog_changed {version}`, which -SkillsCatalog already emits when its version advances, and the Session and branch views react to -it as they do today. The version advances only after the record is committed, so a listener never -observes files the record does not own. - -`skills.json` after one git installation and one hand-written Skill: - -```json -{ - "disabledSkillIds": ["user:archive"], - "installations": { - "acme-skills": { - "source": {"git": "https://example.com/acme/skills", "ref": "main", "commit": "1a2b3c4d"}, - "revision": "sha256:…", - "skills": ["writing/review", "writing/edit"] - } - } -} -``` - -## 4. Dependencies - -| Service | Purpose | -| --- | --- | -| `P:HostPlatform` | The user skills root and the home the staging directory hangs under. | -| `P:SkillSettingsHost` | Read and write the Skills document: disabled ids, plugin roots and installations. | -| `P:ManagementMethods` | Register the five methods under the `skills` namespace, which the App Server's SkillsCatalog plugin already owns. | -| `P:PartRegistry` | Unchanged; the Session and branch parts these methods do not touch. | - -The App Server's SkillsCatalog plugin keeps the wire boundary: it acquires a source, projects -replies, and calls the owner. The catalog keeps everything after acquisition: validation, files, -record and publication. Route management methods behind the existing local-transport admission; -paired and legacy clients see `local_transport_required` exactly as for `skills.catalog`. - -Acquisition and the link check are the crate's existing implementation -(`crates/dim-app-server/src/plugin_manager/acquire.rs`), used here and by PluginManager: one place -states the rules, and the two callers differ only in the destination they own, the staging -directory they use and the record they write. Skills states none of them again. - -## 5. Cross-module requirements - -**R1. Web workspace: separate installed-skill management from installation ([§4.3](../web-workspace.md#43-settings-and-account-management-on-the-local-web-entry)).** - -| Field | Content | -| --- | --- | -| Problem | Installed-skill management and source installation are different operator tasks. Admitting installation methods on the authenticated local Web entry does not require installation forms on its Skills page. | -| Why existing mechanisms do not suffice | `plugin.install` installs a whole package and requires a manifest; it cannot replace Skills' source-installation contract. Browser-side filesystem or Git writes would duplicate the owner. | -| Required capability and ordering | The Skills page manages installed skills through catalog, enablement and refresh operations only, following the Web workspace interaction contract. Source preview, selective installation, update, removal and installation records remain Skills-owned operations, admitted on the authenticated local Web entry and advertised only when the server provides them; admission does not require this page to render them. Plugin-package installation and activation remain on Plugins. | -| Owner and issue | Web workspace ([WebEntry](../web-workspace.md)); #740. | - -**R2. Settings: none.** The installations field is Skills' own document content and needs no new -Settings capability; the source stays registered by the same plugin that registers it today. - -## 6. Rule check - -| Rule | How this design complies | -| --- | --- | -| §1 Capability and App Server boundary; ADR 002 D1 | The owner of the state is the process: the record is Skills' business document, the files are in Skills' user root, and the catalog version is the publication. No new process, Session or branch part, no wiring module, and the App Server keeps only acquisition and the wire boundary. | -| §4.1 split by state owner | Discovery, enablement and installations are one state owner and one part; PluginManager keeps plugin rows and plugin content, and neither part reads the other's state. | -| §4.2 commands, not direct control | Skills is asked for an operation by a typed method call; it writes its own record and advances its own version. Nothing else writes `skills.json`, and the browser writes nothing. | -| §4.3 handlers register work and return | The methods are ordinary provider calls with `Interruption::Report`; acquisition and copying run inside the call, a cancelled call settles before the reply, and no handler writes a Timeline event. | -| §4.4 state and rebuild | The record is business memory read back from Settings after a reload; filesystem state is the installation's own I/O resource and is settled to a terminal state (present, or recorded and repaired by update). Producible facts stay out of the Timeline because nothing outside Skills decides on them. | -| §4.7 public events and services | The only observable signal is the existing `skills.catalog_changed {version}`; no new service, event or port. | -| §4.8 requirements raised | R1 and R2 above, in the §4 rule 8 format; acquisition adds none, because it is the same crate-internal implementation (§4). | -| §4.9 ordering | The record commits before the version advances; a removal deletes files before the record, because the record is what proves ownership. | -| ADR 002 D4 configuration | No structural configuration: no loader row, no enablement flag of its own. `skills.json` stays business configuration. | -| ADR 002 D5 language-neutral contract | §2 is stated as source, revision, selection, id and outcomes in neutral terms; the Rust and JSON spellings are in the appendix. | -| ADR 003 / file-root authorization | Installation grants no authority: an installed Skill is an instruction file the model loads like any other, and a source is read only where the operation names it. | - -Ablation: no preview cache, no preview registry, no second root kind, no second store, no second -plugin, no per-Skill record, no new event, no pagination cursor, no progress declaration (the Web -renders a busy state; acquisition phases have no consumer today). The preview is stateless and the -install re-acquires, so the only added state is the record plus one staging directory that is -removed when the operation settles. - -## 7. Binding appendix - -Method declarations, in the App Server's `SkillsCatalog` plugin (Rust), `mutating` and -`Interruption::Report` as shown; `skills.preview` and `skills.installations` are not mutating: - -```text -skills.preview read -skills.install mutating, no progress -skills.update mutating, no progress -skills.remove mutating, no progress -skills.installations read -``` - -Owner-side additions (Rust, `dim-agent-capabilities`): - -```rust -pub struct SkillInstallation { - pub source: SkillInstallSource, - /// Revision of the installed selection, in install order. - pub revision: String, - /// Source-relative Skill directories, in install order. - pub skills: Vec, -} - -/// One selected Skill. `revision` is what the caller reviewed: `Some` must -/// match the tree, `None` accepts whatever the source holds (an update). -pub struct SelectedSkill { - pub path: String, - pub revision: Option, -} - -pub enum SkillInstallSource { - Path { path: PathBuf }, - /// `reference` is serialized as `ref`, as in `plugins.json`. - Git { git: String, reference: Option, commit: String }, -} - -/// What an install may replace at `/`. -pub enum Replace { - /// Create it; a recorded id is `InstallationExists`. - Create, - /// Replace what the record holds now, or create it (`overwrite`). - Recorded, - /// Replace exactly this record; anything else is `UnknownInstallation`. - Expected(SkillInstallation), -} - -// SkillSettings gains, next to set_plugin: -fn set_installation( - self: Arc, id: String, installation: Option, - cancel: CancellationToken, -) -> BoxFuture<'static, Result>; -``` - -Owner operations on the catalog: `preview(root, id, cwd)`, `install(id, source, root, -operation_dir, skills, replace)`, `uninstall(id)`, `installation(id)` and `installations()`. The -first two return the previous record and the new catalog version. - -`SkillSettingsSnapshot` gains `installations: BTreeMap`, and -`SkillDocument` in the App Server serializes it under `installations` with unknown members -preserved. New `SkillsError` variants: `InstallationExists`, `UnknownInstallation`, -`StalePreview { expected, found }`, `SelectionInvalid(String)`, `InstallConflict(String)`, -`UnmanagedDirectory(String)`, `InstallIo(String)`; the App Server maps them to the codes in §2.7. -`SourceInvalid` and `AcquireFailed` stay on the App Server side, where acquisition happens. - -## 8. Acceptance - -Owner flows, in [skills.rs](../../../tests/integration/tests/skills.rs), over a disposable home -and a source directory with several Skills and no manifest: - -- preview lists every Skill with its source path, description, revision and issues, and writes - nothing; a change to a bundled file under a selected Skill changes its revision; -- install copies only the selected Skill directories, leaves other files in the home and the - project untouched, and the catalog lists them under `user:/…` before the reply; -- a `SKILL.md` or a bundled file changed between preview and install refuses with - `skills_preview_stale` and writes nothing; -- a name already provided in the user root, a repeated name in the selection, a `..` or absolute - selection path, and a source whose link leaves it are each refused, with nothing written; -- install over an existing installation needs `overwrite`, and with it replaces the selection - without touching another installation or a hand-written Skill; a directory or file at - `/` that the record does not own is refused with the Skills it holds, left - as it is, and `overwrite` does not change that; -- a bundled file larger than the digest limit is a preview issue and refuses the install; a record - write that fails after the swap restores the previous directory and record; -- update keeps the selection, refuses a selected path that disappeared, reports the previous - revision and commit, repairs a directory removed by hand, and refuses when its record was removed - or replaced while the source was acquired; -- remove deletes only `/` and its record, and removes a record whose - directory is already gone; -- the record survives a catalog reload and a process restart. - -App Server flows, in [transport_flow](../../../crates/dim-app-server/tests/transport_flow/), over -a disposable home and a local Git fixture: preview, install, catalog, update to a new commit and -remove through the real protocol; the Web entry advertises the five methods while a remote and a -legacy connection refuse them; a credential-bearing URL and a failing clone produce replies and -errors without the URL or Git's stderr; a source whose link leaves it, a directory no record owns -and a path source's preview write nothing outside the expected places; the staging root an -abnormal end leaves behind is gone after a restart; `skills.json` keeps unrelated fields and a -document written before this field existed still loads. - -Rendered verification follows the [Web workspace's Skills interaction](../web-workspace.md#skills-interaction): -desktop and compact layouts, installed catalog, search, scope, collapsed details, enablement, -shadowed entries, reload, empty lists and failure recovery. Source preview, selective installation, -overwrite, update and removal are verified through the owner and App Server flows above, not -through installation forms on the Skills page. - ## 9. References load with the operator's input An operator names a Skill with a `/skill:` token in the input. That reference loads the From 42f5fa01c831388a80c252c1037961ae83a8659f Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 21:32:24 +0800 Subject: [PATCH 4/8] design(content-owners): self-check A-G and align existing owner paragraphs --- .../contracts/resource-owner-operations.md | 6 +-- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/Hooks.md | 20 +++++++--- docs/design/plugins/Mcp.md | 40 +++++++++++-------- docs/design/plugins/PluginManager.md | 10 ++++- docs/design/plugins/README.md | 8 ++-- docs/design/plugins/Skills.md | 16 ++++++-- docs/design/service-faces.md | 10 ++--- 8 files changed, 74 insertions(+), 38 deletions(-) diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5b2be8c345..6c116228f6 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -11,7 +11,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | -| `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction. SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | +| `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction; its target contract is [PluginManager.md](plugins/PluginManager.md#target-contract). SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | | Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info and fsHost resolution and reads. | ## Additional public bindings @@ -133,11 +133,11 @@ serves declared sources and excludes the native `mcp-secrets` document. | Caller → Settings | Current operation and contract | | --- | --- | -| PluginManager; declared-source consumers | Filter declarations by live loader instance using declaredBy above. Reuse settings.read/update/projects for owner edits and reads. SettingsMethods uses its client path and lists only declared sources. | +| PluginManager ([contract](plugins/PluginManager.md#target-contract)); declared-source consumers | Filter declarations by live loader instance using declaredBy above. Reuse settings.read/update/projects for owner edits and reads. SettingsMethods uses its client path and lists only declared sources. | | Agents create/restore, Hooks and MCP management | authorize_project(cwd,cancelled) → root registers the authorized root and publishes the existing notice. It is a write performed at trusted admission. project_root/path/sources are reads covered by settings.projects. | | PermissionRules and CommandRules; CollaborationModelPolicy and optional Collaboration runtime | User permission and collaboration policy reads/writes. Expose the existing commandRules.read projection to rule consumers; use the policy owner's read returning {revision,policy} for Collaboration. Preserve absent-profile fallback. | | HooksSettings and HookSources | hooks, hooks-projects and hooks-plugins. The runtime consumes sources(cwd,cancelled) → HookSourcesSnapshot. Source resolution, revisions and enablement belong to Hooks. | -| Mcp and McpPublication | mcp, mcp-projects, mcp-plugins and mcp-secrets. Publication reads effective server configuration and constructs live connections. Keep partial decoding of individual server entries and credential use at the MCP owner. | +| Mcp ([contract](plugins/Mcp.md#target-contract)) | mcp, mcp-projects, mcp-plugins and mcp-secrets. McpPublication is private; McpSession owns the connection generation and Mcp publishes definitions and credentials. Keep partial decoding of individual server entries and credential use at the MCP owner. | | SkillsCatalog, Scheduler, Modality | Each registers and reads/updates its own native source. Keep the existing SkillDocument, ScheduleDocument and ModalitySettings behavior, including duplicate-job checks and validated model defaults. Their public management methods run at the feature owner. | | Settings → sqliteStorage in the native user profile | Read the existing row; on first use import validated content and provenance atomically; replace at expected revision and publish after commit. File-backed and project settings keep their existing file path and lease behavior. | | Sources using a declared schema → Settings | `settings.register/read/update`. | diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 0bbd6f4f3c..5e711ff3f1 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -543,7 +543,7 @@ existing wire shape. 4. On a RemoteGateway test entry, `session.permission.update` and `session.exec.stop` succeed. 5. A tool that a non-Rust plugin registers through `toolRegistry` is declared to the model and executed through ToolExecutor like a Rust tool; a Session without a mount list declares it with no configuration edit. A tool the Session's mount list names that no part has registered is omitted and reported in diagnostics, the Session still starts, and the tool is declared from the next request once a part registers it. 6. Progress precedes the response; progress the connection cannot take is dropped without closing the connection or losing the response; `notify` reports `gone` after disconnect. -7. With an enabled management provider that is Pending, `hello` succeeds and every other namespace works. Its names return `unknown_method` until it first registers; once its namespace is withdrawn they return `service_reloading` while its row starts or reloads and `service_unavailable` once the row is Failed or Unresolved; with a disabled row they return `unknown_method`. Once PluginManager provides `plugin.disable` (not implemented), it can turn the provider off unless its name is locked, as PluginManager's own is. Reloading a management provider neither reloads Rpc nor closes connections. +7. With an enabled management provider that is Pending, `hello` succeeds and every other namespace works. Its names return `unknown_method` until it first registers; once its namespace is withdrawn they return `service_reloading` while its row starts or reloads and `service_unavailable` once the row is Failed or Unresolved; with a disabled row they return `unknown_method`. Once `plugin.disable` ([PluginManager contract](plugins/PluginManager.md#target-contract)) is used, it can turn the provider off unless its name is locked, as PluginManager's own is. Reloading a management provider neither reloads Rpc nor closes connections. 8. A tool's effect declarations are carried unchanged in the result the executor records on `step/tool-result`, and a result of a tool that declares nothing carries none. A declaration of an unknown kind or an invalid shape is refused at the boundary that decodes it. `ToolResult` decodes strictly, so a reader built before the field refuses the result rather than ignoring it; A.6's format decision states what each reader does. ## Appendix E. Assumptions diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index d746644d88..09e74af557 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -136,6 +136,10 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u - `HooksBranch` writes observations through `Branch.input`; it does not write the Timeline directly. - The `hooks.*` methods are management methods (#2095), not a second `hooksService` face. +### Client-visible changes + +None. `hooks.*` and the six hook points keep their client-visible behavior; `hooksService.sources` is a plugin-facing owner operation, `HookSourcesHost` was agent-crate-private, and `Permission.advise`/`Approval.decide` are #2028's contract names. + ### Rule check | Rule | Application | @@ -171,19 +175,21 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u ### Binding appendix -`hooksService` is on `HooksSettings`; the `hooks.*` methods are registered through #2095. `HooksRuntime` is `pub(crate)`. +`hooksService` is on `HooksSettings`; the `hooks.*` methods are registered through #2095. `HooksRuntime` is `pub(crate)`. A branch part may call any data face of the branch group with `line_owner::(line)`, except registration and lifecycle services (ADR 027); `HooksBranch` calls Permission and Approval that way. ```rust #[rutis::service(name = "hooksService")] impl HooksSettings { - pub async fn register(&self, ctx: &Ctx, plugin: String, dir: String, document: HooksDocument, cancelled: CancelledFn) -> Result, HooksContentError>; - pub async fn withdraw(&self, ctx: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), HooksContentError>; + pub async fn register(&self, caller: &Ctx, plugin: String, dir: String, document: HooksDocument, cancelled: CancelledFn) -> Result, HooksContentError>; + pub async fn withdraw(&self, caller: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), HooksContentError>; pub fn plugins(&self) -> Vec; - pub fn refusal(&self, plugin: &str) -> Option; - pub async fn sources(&self, cwd: String, cancelled: CancelledFn) -> Result; + pub fn refusal(&self, plugin: &str) -> Option; + pub async fn sources(&self, caller: &Ctx, cwd: String, cancelled: CancelledFn) -> Result; } ``` +`HooksDocument`, `HooksRefusal`, `HookSources` and `HookSourceError` are the types in `hooks_settings.rs` and `hooks/sources.rs`; `HooksContentError` and `HookSourceError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. + The Session and branch parts keep their internal types; `hooksService.sources`' request and reply are `{cwd}` and `HookSources`. @@ -202,6 +208,10 @@ Hooks never hooks infrastructure. The withdrawn design ([#21](https://github.com `UserPromptSubmit` is not a Timeline hook point: Session input is not necessarily the user's (Goal, Scheduler, Collaboration, ShellInput and Hooks itself write inputs), so the command runs only where operator input enters, before anything is written. Commands run through HostPlatform (the Session's resource node); a hook command waits only in Hooks' own tasks or in the caller's own task (Permission's admission decision runs in ToolExecutor's per-call admission task; a submit check runs in the Rpc call), never in a Dispatcher handler or under the commit lock. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is Appendix H. +## Supersedes + +Replaces the old Hooks.md Structure, Flows, Rule check, Requirements, Appendix A.2.1/A.6/A.7/H and Owner check (deleted); the `hooksService` rows in [service-faces.md](../service-faces.md); the Hooks rows in [resource-owner-operations.md](../contracts/resource-owner-operations.md), [runtime-owner-operations.md](../contracts/runtime-owner-operations.md) and [session-boundary.md](../contracts/session-boundary.md); the `HookSourcesHost` port and the two-reader design. Rules: [§7 所有者与操作](https://github.com/arcships/dim/pull/2029). Dependencies are defined by [FileStorage #2080](https://github.com/arcships/dim/pull/2080), [Settings #2094](https://github.com/arcships/dim/pull/2094), [SessionScope #2093](https://github.com/arcships/dim/pull/2093) and the branch contracts #2102/#2100; HostPlatform is pending #2032. + ## 5. Context mapping | Source | What the model sees | Placement | Compaction | Child branches | diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md index 12b70cc5c8..8c037a9a7a 100644 --- a/docs/design/plugins/Mcp.md +++ b/docs/design/plugins/Mcp.md @@ -4,6 +4,10 @@ Scope: process and Session. Issue: #2022. `Mcp` owns the process's MCP configuration, content, connection definitions and OAuth credentials. `McpSession` owns one Session's MCP connection generations and tool source. `TemporaryMcp` owns the client-supplied temporary bindings of one Session. `McpPublication` and `McpAuth` are private parts of `Mcp`; neither has a public surface. The current implementation is described in [mcp-management](../appserver/mcp-management.md), [mcp-apps](../appserver/mcp-apps.md), [mcp-oauth](../appserver/mcp-oauth.md) and [TemporaryMcp](TemporaryMcp.md). +## Supersedes + +Replaces the public-surface sections of [mcp-management.md](../appserver/mcp-management.md) §8 (`mcpService` content face and the `mcp.*` connection/lease decisions), [mcp-apps.md](../appserver/mcp-apps.md) §4.4 (`mcpSession`), [mcp-oauth.md](../appserver/mcp-oauth.md) (credential operations) and [TemporaryMcp.md](TemporaryMcp.md) (temporary bindings); the MCP rows in [service-faces.md](../service-faces.md), [resource-owner-operations.md](../contracts/resource-owner-operations.md) and [session-boundary.md](../contracts/session-boundary.md); and the old `McpServiceBinding`, `McpConnection`, `McpOwner`, `McpPublication` connection table and `mcpSession.subscribe`. Rules: [§7 所有者与操作](https://github.com/arcships/dim/pull/2029). Dependencies are defined by [FileStorage #2080](https://github.com/arcships/dim/pull/2080), [Settings #2094](https://github.com/arcships/dim/pull/2094), [SessionScope #2093](https://github.com/arcships/dim/pull/2093), [Connection/ManagementMethods #2095](https://github.com/arcships/dim/pull/2095) and the Session registries #2103/#2102/#2100; HostPlatform, SessionFiles and SessionStore are pending #2032/#2018. + ## Use and scope: responsibility split `Mcp` owns: @@ -118,7 +122,7 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcp.move` | Move an entry in its source | `{id, before?}` | `{}` | Accepted write is not cancelled | `invalid`, `missing`, `conflict`, `closed` | | `mcp.import.preview` | Parse an import payload without writing | `{document, project?}` | `{entries, invalid}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | | `mcp.import.apply` | Write the selected imported entries | `{document, selection, project?}` | `{applied, invalid}` | Accepted write is not cancelled | `invalid`, `conflict`, `closed` | -| `mcp.test` | Probe one server definition with a disposable connection | `{config, timeout?}` | `{status, latency, tools, reason}` | Timeout stops the probe; the owner settles the probe | `invalid`, `timeout`, `refused`, `closed` | +| `mcp.test` | Probe one server definition with a disposable connection | `{config, timeout?}` | `{status, latency, tools, reason}` | Cancel or timeout stops the probe; the owner settles it | `invalid`, `timeout`, `refused`, `cancelled`, `closed` | | `mcp.inspect` | The connection states reported by Sessions | `{}` | `{sessions: [{sessionId, entries}]}` | None | `closed` | | `mcp.disconnect` | Ask every Session to close one source or server | `{source?, server?}` | `{}` | None; the command is a value | `closed` | | `mcp.auth.start` | Start an OAuth flow | `{id, project?}` | `{authUrl?}` | Flow can be cancelled | `missing`, `unsupported`, `refused`, `closed`, `cancelled` | @@ -128,8 +132,8 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcpSession.state` | The Session's MCP view | `{}` | `{servers, error?}` | None; the value is read | `closed` | | `mcpSession.refresh` | Ask the owner to rediscover the enabled entries | `{}` | `{}` | None; the signal is a value | `closed` | | `mcpSession.widget` | The view for one published tool | `{publishedTool}` | `{view}` or absent | The client dropping the call cancels the read | `absent`, `unsupported`, `not_callable`, `unknown_server`, `unavailable`, `refused`, `unknown`, `closed` | -| `mcpSession.call` | One MCP Apps call | `{server, tool, args}` | `{result}` | The client dropping the call cancels the resource read | `unknown_server`, `unavailable`, `refused`, `unknown`, `closed` | -| `session.mcp_temporary.attach` | Mount a client temporary binding | `{server}` | `{binding, tools}` | The caller dropping the call shuts the half-made binding | `invalid`, `mount_failed`, `closed` | +| `mcpSession.call` | One MCP Apps call | `{server, tool, args}` | `{result}` | The client dropping the call cancels the resource read | `unknown_server`, `unavailable`, `refused`, `unknown`, `cancelled`, `closed` | +| `session.mcp_temporary.attach` | Mount a client temporary binding | `{server}` | `{binding, tools}` | The caller dropping the call shuts the half-made binding | `invalid`, `mount_failed`, `cancelled`, `closed` | | `session.mcp_temporary.renew` | Extend the binding lease | `{binding}` | `{}` | None | `invalid`, `missing`, `closed` | | `session.mcp_temporary.detach` | Remove the binding and its children | `{binding}` | `{}` | None; the owner completes the removal | `missing`, `closed` | @@ -162,6 +166,10 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl | `mcp.auth.start/complete` | `Mcp` starts the flow, stores the pending state, completes and writes the credential | The flow cancels; the pending state is removed | The flow ends with the owner | Pending flows are dropped on reload; credentials stay | Flow and credential by `Mcp`/`McpAuth` | | `TemporaryMcp.attach` | The Session mounts the child, registers tools, returns the binding id and lease | A dropped attach unmounts the child | The binding's children close; tools are withdrawn | New binds refused; every child unmounts | Child by `TemporaryMcp`; lease by the binding | +## Client-visible changes + +`mcp.inspect` returns the connection states reported by `McpSession` parts instead of reading `McpPublication`. The client field `sessions` and the per-entry shape stay the same; the change is where the value comes from, and the local MCP management client and the App Server `session.mcp` path need only refresh after the next report. `mcp.disconnect` publishes the same command and returns; `mcpSession.state/refresh/widget/call` keep their request and reply shapes. The removed `mcpSession.subscribe` is Rust-only and never crossed the client protocol. No client error code, field name or notification changes. + ## Exceptions with reasons - `McpAuth` is a private process service. Its instance key and unload are part of the MCP plugin assembly; the Session child receives the service name and an entry id, never a credential value. The MCP plugin's assembly is the shared lifecycle design for the service and its child rows. @@ -211,24 +219,24 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl `mcpService` is on `Mcp`; `mcpSession` on `McpSession`; `session.mcp_temporary` on `TemporaryMcp`. `McpServiceBinding`, `McpConnection`, `McpOwner` and `McpPublication` do not exist. The management methods are registered through #2095. ```rust -#[rutis::service(name = "mcpService")] -impl Mcp { - pub async fn register(&self, ctx: &Ctx, plugin: String, dir: String, document: McpDocument, cancelled: CancelledFn) -> Result, McpContentError>; - pub async fn withdraw(&self, ctx: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), McpContentError>; - pub fn plugins(&self) -> Vec; - pub fn refusal(&self, plugin: &str) -> Option; +#[rutis::service(name = "mcpSession")] +impl McpSession { + pub fn state(&self) -> McpSessionState; + pub fn refresh(&self) -> Result<(), McpSessionError>; + pub async fn widget(&self, caller: &Ctx, published_tool: PublishedTool, cancelled: CancelledFn) -> Result, McpAppError>; + pub async fn call(&self, caller: &Ctx, server: String, tool: String, args: serde_json::Value, cancelled: CancelledFn) -> Result; } ``` -`McpSession`'s data face: +`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. `McpDocument`, `McpRefusal`, `PublishedTool`, `McpView`, `McpSessionState` and the request/reply structures are the types in `mcp/management.rs`, `mcp/session.rs` and `mcp/temporary.rs`; `McpContentError`, `McpSessionError`, `McpAppError` and `McpTemporaryError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error tables. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. ```rust -#[rutis::service(name = "mcpSession")] -impl McpSession { - pub fn state(&self) -> McpSessionState; - pub fn refresh(&self) -> Result<(), McpSessionError>; - pub async fn widget(&self, ctx: &Ctx, published_tool: PublishedTool) -> Result, McpAppError>; - pub async fn call(&self, ctx: &Ctx, server: String, tool: String, args: Value) -> Result; +#[rutis::service(name = "mcpService")] +impl Mcp { + pub async fn register(&self, caller: &Ctx, plugin: String, dir: String, document: McpDocument, cancelled: CancelledFn) -> Result, McpContentError>; + pub async fn withdraw(&self, caller: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), McpContentError>; + pub fn plugins(&self) -> Vec; + pub fn refusal(&self, plugin: &str) -> Option; } ``` diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index a0407cbce4..431906de0c 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -114,6 +114,10 @@ if let Some(reason) = refusal { - The `plugin.*` methods are management methods (#2095), not a second `pluginService` face. - The package's code rows are loaded by rutis-loader; `PluginManager` does not hold a row handle. The loader returns row values/status. +### Client-visible changes + +None. `plugin.*` and the `plugin` tool keep their commands, results and errors; the `Manager` handoff was a Session-part implementation detail. + ### Rule check | Rule | Application | @@ -160,8 +164,12 @@ tool_registry.register( ); ``` -`manager` is the process owner's operation/callback, not the `Manager` object. The request, reply and error types are the typed structures in `plugin_manager.rs` and the management module. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. +`manager` is the process owner's operation/callback, not the `Manager` object. The request, reply and error types are the typed structures in `plugin_manager.rs` and the management module; `PluginError` is a `#[serde(rename_all = "snake_case")]` enum serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. + + +## Supersedes +Replaces the old PluginManager.md §0/§1/§3-§5/§8/§9/Appendix, the `PluginTools` `Manager` handoff and the content-registration interfaces; the `plugin.*` rows in [service-faces.md](../service-faces.md); the PluginManager rows in [resource-owner-operations.md](../contracts/resource-owner-operations.md) and [session-boundary.md](../contracts/session-boundary.md). Keeps the manifest, `plugins.json`, default configuration and command protocol. Rules: [§7 所有者与操作](https://github.com/arcships/dim/pull/2029). FileStorage is #2080; ManagementMethods is #2095; the Session tool registry is #2103; PluginFiles, RuntimeManager and HostPlatform are pending #2016/#2019/#2032. ## 2. Data ### 2.1 The plugin directory and its manifest diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index b6d001529a..a7ee366a06 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -43,7 +43,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [RemoteGateway](RemoteGateway.md) | remote entry, devices | — | — | P3 | | [Modality](Modality.md) | tasks, realtime connections | — | — | P3 | | [light-ocr](LightOcr.md) | optional plugin: the `ocrHelper` description and the out-of-process helper, supplying Modality's `local/pp-ocr` target | — | — | P3; [#1158](https://github.com/arcships/dim/issues/1158) | -| [Skills](Skills.md) (installation) | existing SkillsCatalog: preview of a local or Git source, selective installation into the user root, update and confirmed removal of loose Skills | — (discovery, enablement and the `skill` tool already belong to the Skills capability) | — | #740 | +| [Skills](Skills.md) | `SkillsCatalog`: source preview, install/update/remove, enablement and content | `Skills`: view, `SkillContent` instances, `skill` tool and `skills` check; `SkillContentInstances` template | `SkillsBranch`: `skillsBranch.list` and Prompt adoption | #740, #2022 | | [PluginManager](PluginManager.md) | plugin configuration (`plugins.json`), install, loader rows of plugin code, content registration | `PluginTools` (`plugin` tool) | — | M1 | | [MCP](Mcp.md) | `Mcp`: MCP configuration and content, connection definitions, OAuth credentials and client operations | `McpSession`: connection generations, tools and views; `TemporaryMcp`: temporary bindings | — | #2022 | | [RuntimeManager](RuntimeManager.md) | the Node and Python runtimes of plugin code: pinned download, verification, start; `runtime.*` | — | — | M1 (#476) | @@ -52,6 +52,6 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | -| Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, MCP, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | -| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, MCP (`McpSession`, temporary bindings), Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | -| Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | +| Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, MCP, Hooks (`HooksSettings`), RuntimeManager, RemoteGateway, Skills (`SkillsCatalog`), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | +| Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks (`HooksSession`), MCP (`McpSession`, temporary bindings), Skills (`Skills`, content instances), PluginManager (`PluginTools`), Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | +| Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks (`HooksBranch`), Skills (`SkillsBranch`), Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index 70a6089eac..c813bd4977 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -149,6 +149,10 @@ The `SkillsCatalog`'s management methods are registered through #2095; the `skil - `skills.install`'s token is a value with an expiry; it is not a handle and carries no authority. - The `skills.*` methods are management methods (#2095), not a second `skillsCatalog` face. +### Client-visible changes + +None. `skills.*` keep their client-visible behavior; `skills.install/update/remove` already never cancel after acceptance and settle or restore; `SkillsCatalogBinding` and `ConfigureControl` were plugin-facing; the `Skills` view and `skillsBranch.list` keep their values. + ### Rule check | Rule | Application | @@ -189,14 +193,16 @@ The `SkillsCatalog`'s management methods are registered through #2095; the `skil ```rust #[rutis::service(name = "skillsCatalog")] impl SkillsCatalog { - pub async fn register(&self, ctx: &Ctx, plugin: String, dir: String, document: SkillDocument, cancelled: CancelledFn) -> Result; - pub async fn withdraw(&self, ctx: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), SkillContentError>; + pub async fn register(&self, caller: &Ctx, plugin: String, dir: String, document: SkillDocument, cancelled: CancelledFn) -> Result; + pub async fn withdraw(&self, caller: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), SkillContentError>; pub fn plugins(&self) -> Vec; pub fn issues(&self, plugin: &str) -> SkillIssues; } ``` -`SkillsBranch`'s list is a data face; the request is empty and the reply is the current `SessionSkills` value. The install and management operations are the typed requests and replies in `skills/catalog.rs`; the install token and installation id are values. +`SkillDocument` and `SkillIssues` are the types in `skills/catalog.rs`; `SkillContentError` and `SkillListError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. `skillsBranch.list` takes `caller: &Ctx` and returns the current `SessionSkills` value. + +`SkillsBranch`'s list is a data face; the request is empty and the reply is the current `SessionSkills` value. A branch part may call any data face of the branch group with `line_owner::(line)`, except registration and lifecycle services (ADR 027); `SkillsBranch` calls the Prompt owner that way. The install and management operations are the typed requests and replies in `skills/catalog.rs`; the install token and installation id are values. Scope: process. @@ -204,6 +210,10 @@ Issue: [#740](https://github.com/arcships/dim/issues/740). Rules: [design rules](../../architecture/rust-agent/principles.md), [ADR 002](../../adr/002-plugin-scope.md). +## Supersedes + +Replaces the old Skills.md §2 public operations and errors, §3-§8 and the installation API; the `skillsCatalog` and `skillsBranch` rows in [service-faces.md](../service-faces.md); the Skills rows in [resource-owner-operations.md](../contracts/resource-owner-operations.md) and [session-boundary.md](../contracts/session-boundary.md); `SkillsCatalogBinding`, `ConfigureControl` and the public Rust-only management methods. Keeps the source/revision format, install/update/remove behavior and `/skill:` input. Rules: [§7 所有者与操作](https://github.com/arcships/dim/pull/2029). Dependencies are defined by [FileStorage #2080](https://github.com/arcships/dim/pull/2080), [Settings #2094](https://github.com/arcships/dim/pull/2094), [SessionScope #2093](https://github.com/arcships/dim/pull/2093) and the Session registries #2103; Prompt is #2102; HostPlatform is pending #2032. + ## Installation format and behavior ### 2.1 Source and revision diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..14cdcb6309 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -155,7 +155,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `mcpSession` | `state()`、`refresh()`、`widget(published)`、`call(server, tool, arguments)` | 连接代次、已发布工具、发现与重连 | | `backgroundExec` | `output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)` | 任务表、活进程、输出采集与唤醒 | -形状与错误由所有者文档定义:[MCP Apps](appserver/mcp-apps.md#44-the-mcpsession-data-face)(`mcpSession`)和 +形状与错误由所有者文档定义:[Mcp contract](plugins/Mcp.md#target-contract)(`mcpSession`)和 [WorkspaceTools](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)(`backgroundExec`)。 `backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 @@ -188,7 +188,7 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow ### 3.6 入口、凭据与宿主资源 -按 #1292 逐批确定各项的公共操作,并按 §2.6 迁移登记。状态、资源和凭据留在各自的 owner。`managedSearch` 的搜索操作见 §4.6。`skillsCatalog` 的插件内容操作见 [Skills owner 契约](../architecture/rust-agent/plugins/Skills.md#plugin-content-data-face)。 +按 #1292 逐批确定各项的公共操作,并按 §2.6 迁移登记。状态、资源和凭据留在各自的 owner。`managedSearch` 的搜索操作见 §4.6。`skillsCatalog` 的插件内容操作见 [Skills owner 契约](plugins/Skills.md#target-contract)。 | 名字 | scope | provider | reason | | --- | --- | --- | --- | @@ -375,16 +375,16 @@ providerService.resolve({explicit?: ModelId, cwd?}) -> ModelSelection ### Skills Session 列表 -`skillsBranch` 的 `list({})` 与 Session 内部视图的边界由 [Skills owner](../architecture/rust-agent/plugins/Skills.md#data-face) 定义。Rust binding 与 wire 使用同一 owner;`SessionSkills` 保留为 Session 实例内的私有类型 key,不再有目录名字。 +`skillsBranch` 的 `list({})` 与 Session 内部视图的边界由 [Skills owner](plugins/Skills.md#target-contract) 定义。Rust binding 与 wire 使用同一 owner;`SessionSkills` 保留为 Session 实例内的私有类型 key,不再有目录名字。 ### MCP 插件内容 -`mcpService` 的四个既有插件文档操作与取消、错误、私有资源边界由 [MCP owner](appserver/mcp-management.md#81-plugin-content-data-face) 定义。 +`mcpService` 的四个既有插件文档操作与取消、错误、私有资源边界由 [MCP owner](plugins/Mcp.md#target-contract) 定义。 ### 4.11 `hooksService` 插件内容登记、撤回、列表和拒绝原因读取使用同一个 Hooks owner;原生与跨语言绑定保持其持久化、 -启用及已接纳工作结算语义。操作与错误由 [Hooks A.2.1](plugins/Hooks.md#a21-plugin-content-data-face) 定义。 +启用及已接纳工作结算语义。操作与错误由 [Hooks owner](plugins/Hooks.md#target-contract) 定义。 ## 5. 验证 From 964c6b536f335286e5f0b7f1dccc8fbafed5d15e Mon Sep 17 00:00:00 2001 From: eric8810 Date: Tue, 24 Nov 2026 11:22:51 +0800 Subject: [PATCH 5/8] design(content-owners): keep client shapes, restore anchors and align types --- docs/design/appserver/mcp-apps.md | 2 + docs/design/appserver/mcp-management.md | 2 + docs/design/appserver/mcp-oauth.md | 2 + .../contracts/resource-owner-operations.md | 8 +-- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/Hooks.md | 51 +++++++++++---- docs/design/plugins/Mcp.md | 16 +++-- docs/design/plugins/PluginManager.md | 62 ++++++++++++++----- docs/design/plugins/Skills.md | 14 ++--- docs/design/plugins/TemporaryMcp.md | 2 + 10 files changed, 117 insertions(+), 44 deletions(-) diff --git a/docs/design/appserver/mcp-apps.md b/docs/design/appserver/mcp-apps.md index 2faf9d8153..f343aded20 100644 --- a/docs/design/appserver/mcp-apps.md +++ b/docs/design/appserver/mcp-apps.md @@ -1,3 +1,5 @@ +> **Superseded public surface.** The `mcpSession` data face in §4.4 is replaced by [Mcp.md](../../design/plugins/Mcp.md#target-contract); its client request and reply shapes stay as recorded there. + # MCP Apps host contract Status: Draft. diff --git a/docs/design/appserver/mcp-management.md b/docs/design/appserver/mcp-management.md index aa3895a93f..7cc182450f 100644 --- a/docs/design/appserver/mcp-management.md +++ b/docs/design/appserver/mcp-management.md @@ -1,3 +1,5 @@ +> **Superseded public surface.** The `mcpService` content face and the `mcp.*` connection/lease descriptions in this document are replaced by [Mcp.md](../../design/plugins/Mcp.md#target-contract). The client methods keep their current requests, replies and error codes; the old face descriptions are historical. + # MCP configuration management Status: Draft. diff --git a/docs/design/appserver/mcp-oauth.md b/docs/design/appserver/mcp-oauth.md index 42e226f36b..aef18a40e0 100644 --- a/docs/design/appserver/mcp-oauth.md +++ b/docs/design/appserver/mcp-oauth.md @@ -1,3 +1,5 @@ +> **Superseded public surface.** The credential operations are replaced by [Mcp.md](../../design/plugins/Mcp.md#target-contract); `McpAuth` is private. + # MCP OAuth Status: Implemented on the daemon side (maintainer review on [#111](https://github.com/arcships/dim/pull/111)) and in the native CLI (§13). Roadmap item F4 diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 6c116228f6..e612107aeb 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -11,7 +11,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | -| `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction; its target contract is [PluginManager.md](plugins/PluginManager.md#target-contract). SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | +| `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction; its target contract is [PluginManager.md](../plugins/PluginManager.md#target-contract). SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | | Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info and fsHost resolution and reads. | ## Additional public bindings @@ -133,11 +133,11 @@ serves declared sources and excludes the native `mcp-secrets` document. | Caller → Settings | Current operation and contract | | --- | --- | -| PluginManager ([contract](plugins/PluginManager.md#target-contract)); declared-source consumers | Filter declarations by live loader instance using declaredBy above. Reuse settings.read/update/projects for owner edits and reads. SettingsMethods uses its client path and lists only declared sources. | +| PluginManager ([contract](../plugins/PluginManager.md#target-contract)); declared-source consumers | Filter declarations by live loader instance using declaredBy above. Reuse settings.read/update/projects for owner edits and reads. SettingsMethods uses its client path and lists only declared sources. | | Agents create/restore, Hooks and MCP management | authorize_project(cwd,cancelled) → root registers the authorized root and publishes the existing notice. It is a write performed at trusted admission. project_root/path/sources are reads covered by settings.projects. | | PermissionRules and CommandRules; CollaborationModelPolicy and optional Collaboration runtime | User permission and collaboration policy reads/writes. Expose the existing commandRules.read projection to rule consumers; use the policy owner's read returning {revision,policy} for Collaboration. Preserve absent-profile fallback. | -| HooksSettings and HookSources | hooks, hooks-projects and hooks-plugins. The runtime consumes sources(cwd,cancelled) → HookSourcesSnapshot. Source resolution, revisions and enablement belong to Hooks. | -| Mcp ([contract](plugins/Mcp.md#target-contract)) | mcp, mcp-projects, mcp-plugins and mcp-secrets. McpPublication is private; McpSession owns the connection generation and Mcp publishes definitions and credentials. Keep partial decoding of individual server entries and credential use at the MCP owner. | +| HooksSettings | hooks, hooks-projects and hooks-plugins. `hooksService.sources(cwd)` is the only reader; the agent-crate port is removed. Source resolution, revisions and enablement belong to Hooks. Target: [Hooks.md](../plugins/Hooks.md#target-contract). | +| Mcp ([contract](../plugins/Mcp.md#target-contract)) | mcp, mcp-projects, mcp-plugins and mcp-secrets. McpPublication is private; McpSession owns the connection generation and Mcp publishes definitions and credentials. Keep partial decoding of individual server entries and credential use at the MCP owner. | | SkillsCatalog, Scheduler, Modality | Each registers and reads/updates its own native source. Keep the existing SkillDocument, ScheduleDocument and ModalitySettings behavior, including duplicate-job checks and validated model defaults. Their public management methods run at the feature owner. | | Settings → sqliteStorage in the native user profile | Read the existing row; on first use import validated content and provenance atomically; replace at expected revision and publish after commit. File-backed and project settings keep their existing file path and lease behavior. | | Sources using a declared schema → Settings | `settings.register/read/update`. | diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 5e711ff3f1..531703234a 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -543,7 +543,7 @@ existing wire shape. 4. On a RemoteGateway test entry, `session.permission.update` and `session.exec.stop` succeed. 5. A tool that a non-Rust plugin registers through `toolRegistry` is declared to the model and executed through ToolExecutor like a Rust tool; a Session without a mount list declares it with no configuration edit. A tool the Session's mount list names that no part has registered is omitted and reported in diagnostics, the Session still starts, and the tool is declared from the next request once a part registers it. 6. Progress precedes the response; progress the connection cannot take is dropped without closing the connection or losing the response; `notify` reports `gone` after disconnect. -7. With an enabled management provider that is Pending, `hello` succeeds and every other namespace works. Its names return `unknown_method` until it first registers; once its namespace is withdrawn they return `service_reloading` while its row starts or reloads and `service_unavailable` once the row is Failed or Unresolved; with a disabled row they return `unknown_method`. Once `plugin.disable` ([PluginManager contract](plugins/PluginManager.md#target-contract)) is used, it can turn the provider off unless its name is locked, as PluginManager's own is. Reloading a management provider neither reloads Rpc nor closes connections. +7. With an enabled management provider that is Pending, `hello` succeeds and every other namespace works. Its names return `unknown_method` until it first registers; once its namespace is withdrawn they return `service_reloading` while its row starts or reloads and `service_unavailable` once the row is Failed or Unresolved; with a disabled row they return `unknown_method`. Once `plugin.disable` ([PluginManager contract](../plugins/PluginManager.md#target-contract)) is used, it can turn the provider off unless its name is locked, as PluginManager's own is. Reloading a management provider neither reloads Rpc nor closes connections. 8. A tool's effect declarations are carried unchanged in the result the executor records on `step/tool-result`, and a result of a tool that declares nothing carries none. A declaration of an unknown kind or an invalid shape is refused at the boundary that decodes it. `ToolResult` decodes strictly, so a reader built before the field refuses the result rather than ignoring it; A.6's format decision states what each reader does. ## Appendix E. Assumptions diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 09e74af557..1743d3becf 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -1,6 +1,6 @@ # Hooks -Status: Ready ([#143](https://github.com/arcships/dim/issues/143)); maintainer decisions of 2026-10-22 and 2026-10-31 are applied (§10). Overall design: [overview](../overview.md) (Hooks). Phase: M1 (user, project and plugin sources). Language: Rust. Scope: [ADR 002](../../adr/002-plugin-scope.md) (process + Session + branch). +Status: Ready ([#143](https://github.com/arcships/dim/issues/143)); maintainer decisions of 2026-10-22 and 2026-10-31 are applied (the target contract). Overall design: [overview](../overview.md) (Hooks). Phase: M1 (user, project and plugin sources). Language: Rust. Scope: [ADR 002](../../adr/002-plugin-scope.md) (process + Session + branch). ## Target contract @@ -12,7 +12,7 @@ The owners are `HooksSettings` (process), `HooksSession` (Session) and `HooksBra `HooksSettings` owns: -- **Sources.** The Settings documents `hooks` (user), `hooks-projects` and `hooks-plugins`; `.dimcode/hooks.json` is read through FileStorage under the project root Settings authorizes. +- **Sources.** The Settings documents `hooks` (user), `hooks-projects` and `hooks-plugins`; `.dimcode/hooks.json` is read through FileStorage under the project root Settings authorizes. The `hooksService.sources` data face is the only reader; there is no agent-crate port. - **Content registration.** The hook document a plugin package carries, the holding plugin and its refusal. - **One reader.** `sources(cwd)` resolves the user, project and plugin sources into the value a hook point reads. The management methods and the agent-crate port use this same reader. - **Client operations.** `hooks.catalog`, `hooks.save` and `hooks.set_enabled`. @@ -92,9 +92,9 @@ branch.input(source, HookInput::observation(text)); | `hooksService.plugins` | The packages holding hook content | `{}` | `{plugins}` | None | `closed` | | `hooksService.refusal` | The refusal of a package | `{plugin}` | `{reason?}` | None | `closed` | | `hooksService.sources` | The merged hook sources for a cwd | `{cwd}` | `{sources, project?}` | The read can be cancelled | `unreadable`, `closed`, `cancelled` | -| `hooks.catalog` | The client's hook catalog | `{project?}` | `{sources, entries}` | The read can be cancelled | `invalid`, `closed`, `cancelled` | -| `hooks.save` | Save the user document at a revision | `{revision, document}` | `{revision}` | Accepted write is not cancelled | `invalid`, `conflict`, `settings_write`, `closed` | -| `hooks.set_enabled` | Enable or disable a project source | `{project, enabled}` | `{}` | Accepted write is not cancelled | `invalid`, `conflict`, `closed` | +| `hooks.catalog` | The client's hook catalog | `{cwd?}` | `{userRevision, userDocument, projectsRevision, disableAllHooks, sources, hooks}` | The read can be cancelled | `hooks_invalid`, `hooks_failed`, `closed`, `cancelled` | +| `hooks.save` | Save the user document at a revision | `{expectedRevision, document}` | `{revision}` | Accepted write is not cancelled | `hooks_invalid`, `hooks_conflict`, `hooks_failed`, `closed` | +| `hooks.set_enabled` | Enable or disable a project source | `{cwd, enabled, expectedRevision}` | `{}` | Accepted write is not cancelled | `hooks_invalid`, `hooks_conflict`, `hooks_failed`, `closed` | | `HooksSession` runner | Run one hook command with a payload | `{hook, payload}` | `{decision, output}` | The Session's cancel kills the process tree; the owner settles | `failed`, `timeout`, `block`, `cancelled`, `closed` | | `HooksSession` submit check | Check operator input before it is written | `{input}` | `{context?}` or block | The entry's call cancel stops the check and its command | `block`, `warnings`, `proceed` | | `HooksBranch` advice | Advise a tool admission | `{call, source}` | deny/ask/allow | The admission's cancel stops the advisor | `deny`, `ask`, `allow`; failures map to allow/ask | @@ -112,7 +112,8 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u | `settings_write`, `settings_conflict` | Retry after Settings is available, or report the conflict | | `failed` | The hook command failed; apply `onFailure` | | `timeout` | The handler exceeded its timeout; apply `onFailure` | -| `block` | The hook blocked the operation; report its reason | +| `deny`, `ask`, `allow` | Permission's advice result; `deny` blocks the call, `ask` asks the user, `allow` lets it run | +| `block`, `warnings`, `proceed` | The submit check's result; `block` stops the input, `warnings` and `proceed` continue | | `cancelled` | The operation stopped; nothing was written | | `closed` | The Session or owner is unloading; use the replacement generation | @@ -138,7 +139,7 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u ### Client-visible changes -None. `hooks.*` and the six hook points keep their client-visible behavior; `hooksService.sources` is a plugin-facing owner operation, `HookSourcesHost` was agent-crate-private, and `Permission.advise`/`Approval.decide` are #2028's contract names. +None. `hooks.*` and the six hook points keep their client-visible behavior; `hooksService.sources` is a plugin-facing owner operation, `HookSourcesHost` was agent-crate-private, and `Permission.advise`/`Approval.decide` are #2100's contract names. ### Rule check @@ -188,7 +189,7 @@ impl HooksSettings { } ``` -`HooksDocument`, `HooksRefusal`, `HookSources` and `HookSourceError` are the types in `hooks_settings.rs` and `hooks/sources.rs`; `HooksContentError` and `HookSourceError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. +Current types: `HookRefusal`, `HookSourcesSnapshot`, `HooksContentError` and the `hooks_settings.rs`/`hooks/sources.rs` structs; the target uses the same names and adds `Serialize` to the wire values. The target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check was blocked by the workspace rust-version (`dim-agent-runtime` requires rustc 1.100; the environment has 1.97.1), not by the appendix spelling. The Session and branch parts keep their internal types; `hooksService.sources`' request and reply are `{cwd}` and `HookSources`. @@ -205,7 +206,7 @@ Hooks never hooks infrastructure. The withdrawn design ([#21](https://github.com | `PostToolUse`, `PostToolUseFailure`, `Stop`, `SessionStart` | Context after a tool result, after a turn, at Session start | InputQueue (inputs) | Hooks writes branch input with source `hooks` (existing) | | `Notification` | An approval waiting for the user | — (observation) | Nothing reaches an owner (existing) | -`UserPromptSubmit` is not a Timeline hook point: Session input is not necessarily the user's (Goal, Scheduler, Collaboration, ShellInput and Hooks itself write inputs), so the command runs only where operator input enters, before anything is written. Commands run through HostPlatform (the Session's resource node); a hook command waits only in Hooks' own tasks or in the caller's own task (Permission's admission decision runs in ToolExecutor's per-call admission task; a submit check runs in the Rpc call), never in a Dispatcher handler or under the commit lock. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is Appendix H. +`UserPromptSubmit` is not a Timeline hook point: Session input is not necessarily the user's (Goal, Scheduler, Collaboration, ShellInput and Hooks itself write inputs), so the command runs only where operator input enters, before anything is written. Commands run through HostPlatform (the Session's resource node); a hook command waits only in Hooks' own tasks or in the caller's own task (Permission's admission decision runs in ToolExecutor's per-call admission task; a submit check runs in the Rpc call), never in a Dispatcher handler or under the commit lock. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is the binding appendix above. ## Supersedes @@ -299,7 +300,7 @@ Event fields: `DIMCODE_HOME` is the product home the App Server that runs the Session is configured with, not the daemon's inherited environment: a product daemon always has one and sets it, while a development profile (`--model-config`, `--mock-model`) has no product home and sets none, so a hook that archives there passes `dimcode export --database PATH` itself. `DIM_PLUGIN_ROOT` is the `dir` a plugin source was registered with (A.2); user and project sources have none. -**Archiving.** A hook that needs the Session's history reads the Session's Timeline with `dimcode export "$DIM_SESSION_ID"` ([Timeline export](../appserver/timeline-export.md)), which reads the home `DIMCODE_HOME` names ([ADR 005](../../adr/005-observability.md) D3). There is no `transcript_path` (decision 8). +**Archiving.** A hook that needs the Session's history reads the Session's Timeline with `dimcode export "$DIM_SESSION_ID"` ([Timeline export](../appserver/timeline-export.md)), which reads the home `DIMCODE_HOME` names ([ADR 005](../../adr/005-observability.md) D3). There is no `transcript_path` (the target contract). ### A.4 Outcomes @@ -343,7 +344,7 @@ Dim does not read Claude or Codex files and has no import command. To migrate, c | `PostToolUse` | `PostToolUse` | `PostToolUse` | Non-error results; `updatedToolOutput` ignored | | `PostToolUseFailure` | — | `PostToolUseFailure` | Error results | | `UserPromptSubmit` | `UserPromptSubmit` | `UserPromptSubmit` at the submit entries | Text only; a block is an `input_blocked` error | -| `Stop` | `Stop` | `Stop` → Queue follow-up | Bounded (A8) | +| `Stop` | `Stop` | `Stop` → Queue follow-up | Bounded (the target contract) | | `SessionStart` | `SessionStart` | `SessionStart` → keyed Append | `startup` only | | `Notification` | — | `Notification` on `approval/request` | `permission_prompt` only | | `PreCompact`, `PostCompact`, `SessionEnd`, `Subagent*`, others | `PreCompact`, `PostCompact`, `SessionEnd`, `Interrupt`, `Subagent*` | Unsupported | Listed `unsupported` in the catalog. `PreCompact`/`PostCompact`: blocking would need a compaction-admission port in ContextCompaction; an observation-only form needs no owner change and can be added later. Compaction removes nothing from the Timeline, and `Stop` runs after every completed turn, so archiving loses nothing. `SessionEnd`: Session close is lifecycle, including idle unload, and work must settle before services are removed (AGENTS rule 8); a command at close would delay close. `SubagentStart`/`SubagentStop`: a Collaboration member is its own Session, which gets its own `SessionStart` and `Stop`, with `collaboration_role: "member"` on their stdin (A.3) | @@ -380,3 +381,31 @@ Codex `apply_patch` has no alias: its input is a patch, while Dim's `write` and | `PermissionRequest` deny | Claude/Codex show `message` | Approval's generic text | | `UserPromptSubmit` block | Prompt erased, reason shown | `session.submit` fails with `input_blocked`; ACP `refusal` | | Output fields | `continue`, `stopReason`, `systemMessage`, `suppressOutput`, … | Ignored with a diagnostic (A.4) | + +## Superseded anchors + +These headings are kept so inbound links resolve; the content is replaced by the target contract above. + +### 3.1 PreToolUse through Permission +See `Permission.advise` in the target contract. + +### 3.5 Loading and reads at hook points +See `hooksService.sources` in the target contract. + +### A.6.1 Tool advice in Permission +See `Permission.advise` (target, pending #2100). + +### A.6.2 Submit check at the operator-input entries +See `submitChecks` (target, pending #2103). + +### A.6.3 Process start with an initial stdin +See HostPlatform (target, pending #2032). + +### A.7 Management methods +See `hooks.*` in the target contract. + +## 10. Decisions +See the target contract's responsibility split. + +## Appendix H. Rust binding +See the binding appendix above. diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md index 8c037a9a7a..9ed5419e7c 100644 --- a/docs/design/plugins/Mcp.md +++ b/docs/design/plugins/Mcp.md @@ -6,6 +6,8 @@ Scope: process and Session. Issue: #2022. ## Supersedes +## Target contract + Replaces the public-surface sections of [mcp-management.md](../appserver/mcp-management.md) §8 (`mcpService` content face and the `mcp.*` connection/lease decisions), [mcp-apps.md](../appserver/mcp-apps.md) §4.4 (`mcpSession`), [mcp-oauth.md](../appserver/mcp-oauth.md) (credential operations) and [TemporaryMcp.md](TemporaryMcp.md) (temporary bindings); the MCP rows in [service-faces.md](../service-faces.md), [resource-owner-operations.md](../contracts/resource-owner-operations.md) and [session-boundary.md](../contracts/session-boundary.md); and the old `McpServiceBinding`, `McpConnection`, `McpOwner`, `McpPublication` connection table and `mcpSession.subscribe`. Rules: [§7 所有者与操作](https://github.com/arcships/dim/pull/2029). Dependencies are defined by [FileStorage #2080](https://github.com/arcships/dim/pull/2080), [Settings #2094](https://github.com/arcships/dim/pull/2094), [SessionScope #2093](https://github.com/arcships/dim/pull/2093), [Connection/ManagementMethods #2095](https://github.com/arcships/dim/pull/2095) and the Session registries #2103/#2102/#2100; HostPlatform, SessionFiles and SessionStore are pending #2032/#2018. ## Use and scope: responsibility split @@ -113,7 +115,7 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcpService.withdraw` | Withdraw a package's MCP document | `{plugin}` | `{}` | Accepted write is not cancelled | `closed` | | `mcpService.plugins` | List the packages holding MCP content | `{}` | `{plugins}` | None | `closed` | | `mcpService.refusal` | The refusal reason of a package | `{plugin}` | `{reason?}` | None | `closed` | -| `mcp.catalog` | The merged entries and their revisions | `{project?}` | `{entries, invalid, application}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | +| `mcp.catalog` | The merged servers and their revisions | `{project?}` | `{servers, userRevision, projectRevision, userApplication, pluginApplication, projectApplication, invalid}` | Read can be cancelled | `mcp_invalid_config`, `service_reloading`, `operation_interrupted`, `closed`, `cancelled` | | `mcp.configuration` | One entry's declared and effective view | `{id, project?}` | `{entry}` | Read can be cancelled | `missing`, `closed`, `cancelled` | | `mcp.save` | Create or replace one entry at a revision | `{id?, revision?, entry}` | `{entry, revision}` | Accepted write is not cancelled | `invalid`, `conflict`, `user_scope`, `settings_write`, `closed` | | `mcp.update` | Change selected fields at a revision | `{id, revision, patch}` | `{entry, revision}` | Accepted write is not cancelled | `invalid`, `missing`, `conflict`, `closed` | @@ -122,18 +124,20 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcp.move` | Move an entry in its source | `{id, before?}` | `{}` | Accepted write is not cancelled | `invalid`, `missing`, `conflict`, `closed` | | `mcp.import.preview` | Parse an import payload without writing | `{document, project?}` | `{entries, invalid}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | | `mcp.import.apply` | Write the selected imported entries | `{document, selection, project?}` | `{applied, invalid}` | Accepted write is not cancelled | `invalid`, `conflict`, `closed` | +| `mcp.import.sources` | Discover import sources | `{cwd?}` | `{sources}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | +| `mcp.temporary.capabilities` | The temporary binding capabilities ACP reads | `{}` | `{capabilities}` | None | `closed` | | `mcp.test` | Probe one server definition with a disposable connection | `{config, timeout?}` | `{status, latency, tools, reason}` | Cancel or timeout stops the probe; the owner settles it | `invalid`, `timeout`, `refused`, `cancelled`, `closed` | -| `mcp.inspect` | The connection states reported by Sessions | `{}` | `{sessions: [{sessionId, entries}]}` | None | `closed` | +| `mcp.inspect` | One entry's enabled state, configuration and live connections, read from the report registry | `{cwd?, id, source}` | `{enabled, configuration, connections}` | None | `mcp_invalid_config`, `closed` | | `mcp.disconnect` | Ask every Session to close one source or server | `{source?, server?}` | `{}` | None; the command is a value | `closed` | | `mcp.auth.start` | Start an OAuth flow | `{id, project?}` | `{authUrl?}` | Flow can be cancelled | `missing`, `unsupported`, `refused`, `closed`, `cancelled` | | `mcp.auth.complete` | Finish an OAuth flow with the callback | `{id, callback}` | `{credentialState}` | Flow can be cancelled | `missing`, `invalid`, `refused`, `cancelled`, `closed` | | `mcp.auth.cancel` | Cancel an OAuth flow | `{id}` | `{}` | None | `missing`, `closed` | | `mcp.auth.logout` | Remove an entry's OAuth records | `{id, project?}` | `{}` | Accepted write is not cancelled | `missing`, `user_scope`, `closed` | -| `mcpSession.state` | The Session's MCP view | `{}` | `{servers, error?}` | None; the value is read | `closed` | +| `mcpSession.state` | The Session's MCP view | `{}` | `{servers, catalogError, closed}` | None; the value is read | `closed` | | `mcpSession.refresh` | Ask the owner to rediscover the enabled entries | `{}` | `{}` | None; the signal is a value | `closed` | | `mcpSession.widget` | The view for one published tool | `{publishedTool}` | `{view}` or absent | The client dropping the call cancels the read | `absent`, `unsupported`, `not_callable`, `unknown_server`, `unavailable`, `refused`, `unknown`, `closed` | | `mcpSession.call` | One MCP Apps call | `{server, tool, args}` | `{result}` | The client dropping the call cancels the resource read | `unknown_server`, `unavailable`, `refused`, `unknown`, `cancelled`, `closed` | -| `session.mcp_temporary.attach` | Mount a client temporary binding | `{server}` | `{binding, tools}` | The caller dropping the call shuts the half-made binding | `invalid`, `mount_failed`, `cancelled`, `closed` | +| `session.mcp_temporary.attach` | Mount a client temporary binding | `{sessionId, bindingId, servers}` | `{}` | The caller dropping the call shuts the half-made binding | `invalid`, `mount_failed`, `cancelled`, `closed` | | `session.mcp_temporary.renew` | Extend the binding lease | `{binding}` | `{}` | None | `invalid`, `missing`, `closed` | | `session.mcp_temporary.detach` | Remove the binding and its children | `{binding}` | `{}` | None; the owner completes the removal | `missing`, `closed` | @@ -168,7 +172,7 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl ## Client-visible changes -`mcp.inspect` returns the connection states reported by `McpSession` parts instead of reading `McpPublication`. The client field `sessions` and the per-entry shape stay the same; the change is where the value comes from, and the local MCP management client and the App Server `session.mcp` path need only refresh after the next report. `mcp.disconnect` publishes the same command and returns; `mcpSession.state/refresh/widget/call` keep their request and reply shapes. The removed `mcpSession.subscribe` is Rust-only and never crossed the client protocol. No client error code, field name or notification changes. +None. `mcp.inspect` keeps `{cwd?, id, source}` and `{enabled, configuration, connections}`, now re-sourced from the report registry; `mcp.catalog`, `mcpSession.state`, `session.mcp_temporary.attach`, `mcp.import.sources` and `mcp.temporary.capabilities` keep their current requests, replies and codes. The removed `mcpSession.subscribe` is Rust-only and never crossed the client protocol. ## Exceptions with reasons @@ -228,7 +232,7 @@ impl McpSession { } ``` -`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. `McpDocument`, `McpRefusal`, `PublishedTool`, `McpView`, `McpSessionState` and the request/reply structures are the types in `mcp/management.rs`, `mcp/session.rs` and `mcp/temporary.rs`; `McpContentError`, `McpSessionError`, `McpAppError` and `McpTemporaryError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error tables. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. +`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. Current types: `McpPluginDocument`, `McpPluginRefusal`, `McpWidgetResult` and the `mcp/management.rs`/`mcp/session.rs` request and reply structs; `PublishedTool` is private, so the target exposes a public `PublishedToolRef` value instead. Target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. The current `McpAppError` is a non-serializable `thiserror` enum and is marked target. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check was blocked by the workspace rust-version (`dim-agent-runtime` requires rustc 1.100; the environment has 1.97.1), not by the appendix spelling. ```rust #[rutis::service(name = "mcpService")] diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index 431906de0c..1b15989ad0 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -1,6 +1,6 @@ # PluginManager -Status: Draft, aligned with the maintainer on 2026-10-27. Requirements: [plugin management](../plugin-management.md) ([#432](https://github.com/arcships/dim/issues/432)). Issues: [#3](https://github.com/arcships/dim/issues/3), [#384](https://github.com/arcships/dim/issues/384). Scope: [ADR 002](../../adr/002-plugin-scope.md) (process: installation is per host). Language: Rust. Milestone: M1 for the parts marked in §0. +Status: Draft. Requirements: [plugin management](../plugin-management.md) ([#432](https://github.com/arcships/dim/issues/432)). Issues: [#3](https://github.com/arcships/dim/issues/3), [#384](https://github.com/arcships/dim/issues/384). Scope: process and Session (the `plugin` tool); installation is per host. Language: Rust. ## Target contract @@ -73,13 +73,13 @@ if let Some(reason) = refusal { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `plugin.list` | The installed packages and their state | `{}` | `{packages}` | None | `closed` | -| `plugin.install` | Install a local path or Git source | `{source, name?, lock?}` | `{package, progress?}` | Accepted install settles or rolls back | `invalid_source`, `invalid_manifest`, `exists`, `load_failed`, `content_refused`, `restart_required`, `write_failed`, `closed` | -| `plugin.enable` | Make one installed package the name's active package | `{name, version?}` | `{}` | Accepted operation settles | `missing`, `load_failed`, `content_refused`, `restart_required`, `closed` | -| `plugin.disable` | Turn a package name off | `{name}` | `{}` | Accepted operation settles | `missing`, `restart_required`, `closed` | -| `plugin.reload` | Reload a package's rows | `{name}` | `{}` | Accepted operation settles | `missing`, `load_failed`, `content_refused`, `closed` | -| `plugin.update` | Update a package to a source revision | `{name, source?, lock?}` | `{package, progress?}` | Accepted update settles or rolls back | `missing`, `invalid_source`, `load_failed`, `content_refused`, `write_failed`, `closed` | -| `plugin.remove` | Remove a package | `{name, version?}` | `{}` | Accepted remove settles or restores | `missing`, `load_failed`, `write_failed`, `closed` | +| `plugin.list` | The installed packages and their state | `{}` | bare array of package status maps `{id, name, enabled, locked, skipped, refused, restartRequired}` | None | `plugin_not_found`, `closed` | +| `plugin.install` | Install a local path or Git source | `{source, name?, lock?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted install settles or rolls back | `plugin_exists`, `invalid_params`, `invalid_id`, `path_outside_plugins`, `load_failed`, `content_refused`, `restart_required`, `closed` | +| `plugin.enable` | Make one installed package the name's active package | `{name, version?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `load_failed`, `content_refused`, `restart_required`, `closed` | +| `plugin.disable` | Turn a package name off | `{name}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `restart_required`, `closed` | +| `plugin.reload` | Reload a package's rows | `{name}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `load_failed`, `content_refused`, `closed` | +| `plugin.update` | Update a package to a source revision | `{name, source?, lock?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted update settles or rolls back | `plugin_not_found`, `plugin_locked`, `invalid_params`, `load_failed`, `content_refused`, `closed` | +| `plugin.remove` | Remove a package | `{name, version?}` | `{}` | Accepted remove settles or restores | `plugin_not_found`, `plugin_locked`, `load_failed`, `closed` | | Startup reconcile | Remove directories and records that are not installed; restore the default configuration | internal | — | None | `record_read`, `record_write`, `cleanup` | | Content registration | Register or withdraw a package's MCP, Hooks, Skills and UI content | internal | `refusal` | The owner's content call can be cancelled | the content owners' refusals are values | | `plugin` tool | Map one model command to a process operation | `{command, args}` | tool result content | The tool call's cancel stops the operation | `usage`, the owner's errors | @@ -164,7 +164,7 @@ tool_registry.register( ); ``` -`manager` is the process owner's operation/callback, not the `Manager` object. The request, reply and error types are the typed structures in `plugin_manager.rs` and the management module; `PluginError` is a `#[serde(rename_all = "snake_case")]` enum serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. +`manager` is the process owner's operation/callback, not the `Manager` object. The current `PluginError` is a struct; the target replaces it with `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`, one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. The temporary-crate check was blocked by the workspace rust-version (`dim-agent-runtime` requires rustc 1.100; the environment has 1.97.1), not by the appendix spelling. ## Supersedes @@ -198,7 +198,7 @@ A plugin is a directory with `dim-plugin.json` at its root. The keys present say | `name` | — | The plugin's name. Plugins with the same name replace each other. | | `version` | — | The plugin's own version, three dot-separated numbers, each one or more digits. Optional, and required for an optional plugin (§2.3), where it names the install directory. | | `code` | code | The rutis row fields ([rutis usage §2](../rutis-usage.md#2-plugins-are-rows-instances-mount-their-parts)) except `id` and `name`: `entry` is a path inside the directory; `inject`, `provides` and `instanceNames` are copied into the row; `config` is the row's configuration, with the host's patch for that plugin name deep-merged over it (below). | -| `dependencies` | code | The package manager whose dependencies the plugin declares. The only value today is `"npm"`: the directory carries `package.json` and `package-lock.json`, and the locked dependencies are installed into the plugin's own directory at acquisition (§3.2, §7). A manifest declaring it without either file is refused `invalid_manifest`. | +| `dependencies` | code | The package manager whose dependencies the plugin declares. The only value today is `"npm"`: the directory carries `package.json` and `package-lock.json`, and the locked dependencies are installed into the plugin's own directory at acquisition (§7 and the target install flow). A manifest declaring it without either file is refused `invalid_manifest`. | | `skills` | skills | A directory inside the plugin of Skill documents, registered with SkillsCatalog. | | `mcp` | MCP | A file inside the plugin holding MCP server entries, registered with Mcp. | | `hooks` | hooks | A file inside the plugin holding a hooks document, registered with Hooks. | @@ -210,7 +210,7 @@ Code, skills, MCP and hooks paths are relative, resolved inside the directory af **Data directory.** The plugin files root is the root an embedding host names, else the product home, else the execution home the host was started with (`--home`). A host started with only a database file has none of them, so it has no plugin files root and runs no PluginManager; the root is never the database's directory or the working directory. When a plugin with code is turned on, PluginManager creates `//` if it does not exist: `` is the installed id, or a default plugin's name, both checked by the id rule (§7). It never deletes the directory, on turning off or on remove, as Settings documents stay in the home. An existing entry is used only if it is a directory, not a symbolic link, that resolves to itself inside the root; otherwise nothing is created and the plugin's file operations fail as they would without it. A plugin writes only under its own id directory through `pluginFiles` ([process TypeScript §5.2](../process-typescript.md#52-public-pluginfiles-binding)). -A plugin's business configuration (its Settings sources) is not in the manifest: the plugin's code registers its sources with Settings when it starts (§9 R1). The `settings` member of today's TypeScript rows goes away. +A plugin's business configuration (its Settings sources) is not in the manifest: the plugin's code registers its sources with Settings when it starts (the target requirements). The `settings` member of today's TypeScript rows goes away. The repository's own TypeScript plugins (`runtime/plugins/*`) get a `dim-plugin.json` in place of their row files (`web.json`, `process.json`, `settings.json`). SessionTitle is a built-in plugin, not a TypeScript package. @@ -266,7 +266,7 @@ new manifest readable by an old binary. | `installed[].id` | Unique among installed plugins; the key of the record and the name of the clone directory. Matches `[a-z0-9_-]{1,64}` (lowercase, so two ids never name one directory on a case-insensitive file system) and is not `builtin` or `default` (§7). When the caller gives none, the id is the manifest name lowercased (`Hooks` → `hooks`); a collision after lowercasing is `plugin_exists`, and the caller then gives another id. The example's `hooks-plus` was given by the caller (`--id hooks-plus`). | | `installed[].name` | The manifest name at install or last reload. | | `installed[].source` | `{path}` for a local directory, used in place and never copied; `{git, ref?, commit}` for Git; `{optional}` for a plugin the default configuration file ships optionally (§2.3), copied from its shipped directory. | -| `installed[].dir` | The directory that is loaded: the local path itself, the clone under `/plugins//+`, or the copy under `/plugins//+` (§3.2, §7). A record written before suffixes existed names its directory without one; nothing is migrated. | +| `installed[].dir` | The directory that is loaded: the local path itself, the clone under `/plugins//+`, or the copy under `/plugins//+` (§7 and the target install flow). A record written before suffixes existed names its directory without one; nothing is migrated. | | `installed[].kinds` | The kinds the manifest carried at install or last reload. | | `installed[].version` | The installed version of an `{optional}` source, from its manifest; absent for other sources. | | `names..use` | Which plugin the name uses: an installed id, `"builtin"` or `"default"`. Absent: the built-in plugin of that name if there is one, else the default plugin of that name. | @@ -316,7 +316,7 @@ Shipped with Dim, read-only, given to the App Server with `--defaults PATH` (the ``` - `plugins` maps each default plugin's name to its directory, relative to this file. A default plugin is a plugin directory like any other (§2.1). -- `optional` maps an optional plugin's name to its directory, relative to this file. An optional plugin is shipped but is not installed and not turned on: nothing reads it until the user installs it, and `plugin.list` shows it so a client can offer it (§3.6). `plugin.install {source: {optional: ""}}` copies the directory — never `node_modules` — into `/plugins//+` and installs its declared dependencies there (§3.2, §7); the shipped directory stays untouched and read-only. A newer release ships a new `version`: at the next start an installed copy is re-acquired in the background (§3.1), the old copy stays in use and on disk until that succeeds, and the next start after the switch deletes it. `enable` defaults to true, `plugin.enable` and `plugin.disable` then work as for any installed plugin, and an optional plugin's name records no `off` state until it is installed: `plugin.list` reports it off (§3.6). +- `optional` maps an optional plugin's name to its directory, relative to this file. An optional plugin is shipped but is not installed and not turned on: nothing reads it until the user installs it, and `plugin.list` shows it so a client can offer it (§3.6). `plugin.install {source: {optional: ""}}` copies the directory — never `node_modules` — into `/plugins//+` and installs its declared dependencies there (§7 and the target install flow); the shipped directory stays untouched and read-only. A newer release ships a new `version`: at the next start an installed copy is re-acquired in the background (§3.1), the old copy stays in use and on disk until that succeeds, and the next start after the switch deletes it. `enable` defaults to true, `plugin.enable` and `plugin.disable` then work as for any installed plugin, and an optional plugin's name records no `off` state until it is installed: `plugin.list` reports it off (§3.6). - Built-in SessionTitle, Scheduler and Goal are installed by the native product profile and have no entry in this file. - A name cannot appear in both `plugins` and `optional`, and an optional plugin's name cannot be a built-in plugin's: each is a startup error naming both. An optional plugin's item has no candidates (§3.6), so it would hide the plugin shipped under that name. - `locked` lists names that cannot be turned off and whose plugin cannot be switched. Other plugins of a locked name may still be installed. Locking is product configuration; PluginManager applies it. @@ -343,8 +343,42 @@ Installing and turning on are host configuration done through management methods - **Paths.** One rule covers every operation that touches the file system for a plugin: install (staging, clone, rename), update, remove and the startup cleanup. Before any file system change, PluginManager checks that the id, whether the caller gave it or it came from the manifest name, matches `[a-z0-9_-]{1,64}` and is not `builtin` or `default`, and that every directory it is about to create, rename or delete resolves to exactly one of `/plugins/.staging/`, `/plugins/.python`, `/plugins/`, `/plugins//` or `/plugins//+<16 lowercase hex characters>` (`.staging` and `.python` cannot be ids, since an id has no dot). A `` without a suffix is accepted only as a directory an existing record names and for the cleanup. The Python links in `.python` are replaced or removed as links; what they point to is never touched. A failed check refuses the operation with `invalid_id` or `path_outside_plugins` and changes nothing: no directory, no `plugins.json` write, no loader command. A local-path plugin's own directory is never created, renamed or deleted, so the rule does not apply to it. - **No copy is deleted while the process runs.** Install, update, the background re-acquisition and remove leave every replaced directory in place; only the startup cleanup deletes a directory no installed entry refers to, and it runs before any acquisition in that start (§3.1). A task that read a description therefore names a directory that exists until the process exits, even when the plugin was updated or removed after it started. The cost is disk: replaced copies stay until the next start. A lease from Modality to PluginManager was rejected: Modality would have to address PluginManager's state, which [principles §4 rule 7](../../architecture/rust-agent/principles.md) forbids, and a crash would still leave the copy to the startup cleanup. - A clone goes to `/plugins/.staging/` and is renamed into place only after its manifest and paths are checked. A failure deletes the staging directory; startup deletes leftovers and clones or copies no entry refers to. -- A plugin's dependencies come only from its own `package-lock.json`, installed by RuntimeManager in the staging directory with `npm ci --omit=dev --ignore-scripts --no-audit --no-fund --workspaces=false`, so no package lifecycle script runs and no dependency outside the lock is resolved. The registry is RuntimeManager's rule (`DIMCODE_NPM_REGISTRY`, then `npmRegistries`, §9 R5). The shipped optional directory is never installed in place and is never modified. +- A plugin's dependencies come only from its own `package-lock.json`, installed by RuntimeManager in the staging directory with `npm ci --omit=dev --ignore-scripts --no-audit --no-fund --workspaces=false`, so no package lifecycle script runs and no dependency outside the lock is resolved. The registry is RuntimeManager's rule (`DIMCODE_NPM_REGISTRY`, then `npmRegistries`, the target requirements). The shipped optional directory is never installed in place and is never modified. - No manifest path may leave the plugin directory after following symbolic links; a symbolic link inside a Git clone that points outside it is refused. - `plugins.json` is written atomically (§2.2). The acquisition and link-check code behind these rules is one crate-internal implementation, `crates/dim-app-server/src/plugin_manager/acquire.rs`, shared with the Skills installation ([Skills](Skills.md) §4), which reads a local directory or clones a repository for its own destination, staging directory and record. The rules above are stated once because there is one implementation. + +## Superseded anchors + +These headings are kept so inbound links resolve; the content is replaced by the target contract above. + +### 2.4 State PluginManager does not keep +See the target contract's responsibility split. + +### 2.5 Runtimes +See RuntimeManager (target, pending #2019). + +### 3. Flows +See the target contract's flows. + +### 3.1 Startup +See the target contract's startup reconcile. + +### 3.2 Install +See `plugin.install` in the target contract. + +## 4. Timing and conflicts +See the target contract's flows. + +## 6. Interfaces (summary) +See the target contract's operations. + +## 9. Requirements raised to mechanism owners +See the target contract's requirements. + +### A.1 Methods (managementMethods, namespace plugin) +See `plugin.*` in the target contract. + +## Appendix C. Acceptance (M1) +See the delivery comment's acceptance. diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index c813bd4977..fe74e43f67 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -91,7 +91,7 @@ if list.generation != seen { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `skillsCatalog.register` | Register a package's Skill root | `{plugin, dir, document}` | `{}` or `{issues}` | Accepted write is not cancelled | `invalid_manifest`, `unreadable`, `settings_write`, `settings_conflict`, `closed` | +| `skillsCatalog.register` | Register a package's Skill root | `{plugin, dir}` | `{issues}` | Accepted write is not cancelled | `invalid_manifest`, `unreadable`, `settings_write`, `settings_conflict`, `closed` | | `skillsCatalog.withdraw` | Withdraw a package's root | `{plugin}` | `{}` | Accepted write is not cancelled | `closed` | | `skillsCatalog.plugins` | The packages holding Skill roots | `{}` | `{plugins}` | None | `closed` | | `skillsCatalog.issues` | The scan issues of a package | `{plugin}` | `{issues}` | None | `closed` | @@ -99,8 +99,8 @@ if list.generation != seen { | `skills.catalog` | The client catalog | `{project?}` | `{skills, projects, invalid}` | The read can be cancelled | `invalid`, `closed`, `cancelled` | | `skills.set_enabled` | Enable or disable a Skill or project | `{id, enabled, project?}` | `{}` | Accepted write is not cancelled | `missing`, `invalid`, `conflict`, `closed` | | `skills.refresh` | Rescan the roots | `{}` | `{generation}` | None; the scan is the owner's | `closed` | -| `skills.preview` | Preview a local or Git source | `{source, selection}` | `{token, entries, invalid}` | The read can be cancelled; the token expires | `invalid_source`, `fetch_failed`, `too_large`, `cancelled`, `closed` | -| `skills.install` | Install the selected entries | `{token, selection}` | `{installed}` | Accepted work is not cancelled; it settles or restores | `expired`, `invalid_selection`, `exists`, `conflict`, `write_failed`, `closed` | +| `skills.preview` | Preview a local or Git source | `{source, skills}` | `{source, skills, conflicts, shadows, issues}` | The read can be cancelled | `skills_invalid_source`, `skills_fetch_failed`, `skills_too_large`, `cancelled`, `closed` | +| `skills.install` | Install the selected entries | `{source, id?, skills, overwrite}` | `{installation, previous?}` | Accepted work is not cancelled; it settles or restores | `skills_preview_stale`, `skills_install_exists`, `skills_install_unmanaged`, `skills_install_unknown`, `skills_write_failed`, `closed` | | `skills.update` | Update installed entries | `{id, revision?}` | `{installed}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `conflict`, `write_failed`, `closed` | | `skills.remove` | Remove installed entries | `{id}` | `{}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `delete_failed`, `closed` | | `skills.installations` | The install records | `{}` | `{installations}` | None | `closed` | @@ -200,14 +200,12 @@ impl SkillsCatalog { } ``` -`SkillDocument` and `SkillIssues` are the types in `skills/catalog.rs`; `SkillContentError` and `SkillListError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. `skillsBranch.list` takes `caller: &Ctx` and returns the current `SessionSkills` value. +`SkillIssue` and `SkillsError` are the current types; `SkillDocument` is the catalog's private installation record. The target type names are marked in `skills/catalog.rs`; `SkillContentError` and `SkillListError` are `#[serde(rename_all = "snake_case")]` enums serialized as `{code, data}` with `message` in `data`; the wire `code` is the variant name and matches the error table. `From` keeps the callback's own `code` and `message`. `CancelledFn` is the binding's cancellation argument, never a request field. `skillsBranch.list` takes `caller: &Ctx` and returns the current `SessionSkills` value. + +`SkillsBranch`'s list is a data face; the request is empty and the reply is the current `SessionSkills` value. A branch part may call any data face of the branch group with `line_owner::(line)` (target, pending #2093; mechanism #2127), except registration and lifecycle services (ADR 027); `SkillsBranch` calls the Prompt owner that way. The install and management operations are the typed requests and replies in `skills/catalog.rs`; the install token and installation id are values. -`SkillsBranch`'s list is a data face; the request is empty and the reply is the current `SessionSkills` value. A branch part may call any data face of the branch group with `line_owner::(line)`, except registration and lifecycle services (ADR 027); `SkillsBranch` calls the Prompt owner that way. The install and management operations are the typed requests and replies in `skills/catalog.rs`; the install token and installation id are values. -Scope: process. -Issue: [#740](https://github.com/arcships/dim/issues/740). -Rules: [design rules](../../architecture/rust-agent/principles.md), [ADR 002](../../adr/002-plugin-scope.md). ## Supersedes diff --git a/docs/design/plugins/TemporaryMcp.md b/docs/design/plugins/TemporaryMcp.md index 37141c57a5..404ccea1d2 100644 --- a/docs/design/plugins/TemporaryMcp.md +++ b/docs/design/plugins/TemporaryMcp.md @@ -1,3 +1,5 @@ +> **Superseded public surface.** The temporary-binding operations are replaced by [Mcp.md](Mcp.md#target-contract); the client `session.mcp_temporary.attach` request and reply keep their current shape. + # Temporary MCP Scope: Session. Owner: the MCP feature. A separate `TemporaryMcp` part accepts From e39c8d4d2bb99dc1f5c88ec8ea80e970d62d49fb Mon Sep 17 00:00:00 2001 From: eric8810 Date: Tue, 24 Nov 2026 11:45:15 +0800 Subject: [PATCH 6/8] design(content-owners): compile appendix and close review links --- docs/design/plugins/Hooks.md | 8 +++++++- docs/design/plugins/Mcp.md | 5 ++++- docs/design/plugins/PluginManager.md | 7 ++++++- docs/design/plugins/Skills.md | 4 ++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 1743d3becf..affe664eb9 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -115,6 +115,9 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u | `deny`, `ask`, `allow` | Permission's advice result; `deny` blocks the call, `ask` asks the user, `allow` lets it run | | `block`, `warnings`, `proceed` | The submit check's result; `block` stops the input, `warnings` and `proceed` continue | | `cancelled` | The operation stopped; nothing was written | +| `hooks_invalid` | Fix the hook document; the client sees the current invalid code | +| `hooks_conflict` | Re-read the revision and retry | +| `hooks_failed` | Report the failed write; retry after the owner is available | | `closed` | The Session or owner is unloading; use the replacement generation | #### Flows @@ -189,7 +192,7 @@ impl HooksSettings { } ``` -Current types: `HookRefusal`, `HookSourcesSnapshot`, `HooksContentError` and the `hooks_settings.rs`/`hooks/sources.rs` structs; the target uses the same names and adds `Serialize` to the wire values. The target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check was blocked by the workspace rust-version (`dim-agent-runtime` requires rustc 1.100; the environment has 1.97.1), not by the appendix spelling. +Current types: `HookRefusal`, `HookSourcesSnapshot`, `HooksContentError` and the `hooks_settings.rs`/`hooks/sources.rs` structs; the target uses the same names and adds `Serialize` to the wire values. The target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. The Session and branch parts keep their internal types; `hooksService.sources`' request and reply are `{cwd}` and `HookSources`. @@ -389,6 +392,9 @@ These headings are kept so inbound links resolve; the content is replaced by the ### 3.1 PreToolUse through Permission See `Permission.advise` in the target contract. +### 3.3 UserPromptSubmit at the operator-input entries +See `submitChecks` and `hooksService.sources` in the target contract. + ### 3.5 Loading and reads at hook points See `hooksService.sources` in the target contract. diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md index 9ed5419e7c..26cf397deb 100644 --- a/docs/design/plugins/Mcp.md +++ b/docs/design/plugins/Mcp.md @@ -156,6 +156,9 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl | `timeout` | The probe did not finish; the owner settled it; report the result | | `mount_failed` | The child rows did not activate; the owner shut them down; report the binding failure | | `cancelled` | Nothing was committed; the read or the flow stopped | +| `mcp_invalid_config` | Fix the MCP document or entry; the client sees the current invalid-config code | +| `mcp_settings_read` | Retry after Settings is readable, or report the failure | +| `service_reloading`, `operation_interrupted` | Retry after the row is active, or re-read the current state | | `closed` | The owner is unloading; use the replacement generation | ### Flows @@ -232,7 +235,7 @@ impl McpSession { } ``` -`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. Current types: `McpPluginDocument`, `McpPluginRefusal`, `McpWidgetResult` and the `mcp/management.rs`/`mcp/session.rs` request and reply structs; `PublishedTool` is private, so the target exposes a public `PublishedToolRef` value instead. Target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. The current `McpAppError` is a non-serializable `thiserror` enum and is marked target. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check was blocked by the workspace rust-version (`dim-agent-runtime` requires rustc 1.100; the environment has 1.97.1), not by the appendix spelling. +`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. Current types: `McpPluginDocument`, `McpPluginRefusal`, `McpWidgetResult` and the `mcp/management.rs`/`mcp/session.rs` request and reply structs; `PublishedTool` is private, so the target exposes a public `PublishedToolRef` value instead. Target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. The current `McpAppError` is a non-serializable `thiserror` enum and is marked target. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. ```rust #[rutis::service(name = "mcpService")] diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index 1b15989ad0..e30fa0de2a 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -94,6 +94,11 @@ if let Some(reason) = refusal { | `content_refused` | The content owner refused; the package record is rolled back or the content is left out as the owner states | | `write_failed` | The record or files could not settle; report the partial state and its recovery | | `usage` | Fix the tool command | +| `plugin_not_found` | Re-read the list; the package is gone | +| `plugin_exists` | Choose another name/version | +| `plugin_locked` | Use another name or unlock the package | +| `invalid_params` | Fix the install/update parameters | +| `invalid_id`, `path_outside_plugins` | Fix the id or path; the path check failed | | `closed` | The owner is unloading; use the replacement generation | #### Flows @@ -164,7 +169,7 @@ tool_registry.register( ); ``` -`manager` is the process owner's operation/callback, not the `Manager` object. The current `PluginError` is a struct; the target replaces it with `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`, one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. The temporary-crate check was blocked by the workspace rust-version (`dim-agent-runtime` requires rustc 1.100; the environment has 1.97.1), not by the appendix spelling. +`manager` is the process owner's operation/callback, not the `Manager` object. The current `PluginError` is a struct; the target replaces it with `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`, one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. ## Supersedes diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index fe74e43f67..26c5bcb33f 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -125,6 +125,10 @@ The `SkillsCatalog`'s management methods are registered through #2095; the `skil | `unknown`, `disabled`, `unavailable` | Report the Skill view or tool error | | `block`, `warnings`, `proceed` | The check's result; `block` stops the input | | `cancelled` | Nothing was committed; the read or preview stopped | +| `skills_invalid_source`, `skills_fetch_failed`, `skills_too_large` | Fix the source or retry the fetch | +| `skills_preview_stale` | Re-preview; the source moved | +| `skills_install_exists`, `skills_install_unmanaged`, `skills_install_unknown` | Re-read the record and choose an id/selection | +| `skills_write_failed` | Report the partial state; retry update/remove | | `closed` | The owner is unloading; use the replacement generation | #### Flows From eca395a8d406a3ea1cfa3a3e79745d4a1c68ce74 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Tue, 24 Nov 2026 13:30:20 +0800 Subject: [PATCH 7/8] design(content-owners): align client shapes and wire-code mapping --- docs/design/plugins/Hooks.md | 10 +++++----- docs/design/plugins/Mcp.md | 14 +++++++------- docs/design/plugins/PluginManager.md | 27 +++++++++++++++------------ docs/design/plugins/Skills.md | 17 +++++++++-------- 4 files changed, 36 insertions(+), 32 deletions(-) diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index affe664eb9..521848d5f0 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -12,9 +12,9 @@ The owners are `HooksSettings` (process), `HooksSession` (Session) and `HooksBra `HooksSettings` owns: -- **Sources.** The Settings documents `hooks` (user), `hooks-projects` and `hooks-plugins`; `.dimcode/hooks.json` is read through FileStorage under the project root Settings authorizes. The `hooksService.sources` data face is the only reader; there is no agent-crate port. +- **Sources.** The Settings documents `hooks` (user), `hooks-projects` and `hooks-plugins`; `.dimcode/hooks.json` is read through FileStorage under the project root Settings authorizes. The `hooksService.sources` data face is the only reader; `HooksSettings` and the management methods use it, and `HooksSession`/`HooksBranch` read it through the process face. There is no agent-crate port. - **Content registration.** The hook document a plugin package carries, the holding plugin and its refusal. -- **One reader.** `sources(cwd)` resolves the user, project and plugin sources into the value a hook point reads. The management methods and the agent-crate port use this same reader. +- **One reader.** `sources(cwd)` resolves the user, project and plugin sources into the value a hook point reads. The management methods and the Session/branch parts use this same reader; the port is removed. - **Client operations.** `hooks.catalog`, `hooks.save` and `hooks.set_enabled`. `HooksSession` owns: @@ -94,7 +94,7 @@ branch.input(source, HookInput::observation(text)); | `hooksService.sources` | The merged hook sources for a cwd | `{cwd}` | `{sources, project?}` | The read can be cancelled | `unreadable`, `closed`, `cancelled` | | `hooks.catalog` | The client's hook catalog | `{cwd?}` | `{userRevision, userDocument, projectsRevision, disableAllHooks, sources, hooks}` | The read can be cancelled | `hooks_invalid`, `hooks_failed`, `closed`, `cancelled` | | `hooks.save` | Save the user document at a revision | `{expectedRevision, document}` | `{revision}` | Accepted write is not cancelled | `hooks_invalid`, `hooks_conflict`, `hooks_failed`, `closed` | -| `hooks.set_enabled` | Enable or disable a project source | `{cwd, enabled, expectedRevision}` | `{}` | Accepted write is not cancelled | `hooks_invalid`, `hooks_conflict`, `hooks_failed`, `closed` | +| `hooks.set_enabled` | Enable or disable a project source | `{cwd, enabled, expectedRevision}` | `{revision}` | Accepted write is not cancelled | `hooks_invalid`, `hooks_conflict`, `hooks_failed`, `closed` | | `HooksSession` runner | Run one hook command with a payload | `{hook, payload}` | `{decision, output}` | The Session's cancel kills the process tree; the owner settles | `failed`, `timeout`, `block`, `cancelled`, `closed` | | `HooksSession` submit check | Check operator input before it is written | `{input}` | `{context?}` or block | The entry's call cancel stops the check and its command | `block`, `warnings`, `proceed` | | `HooksBranch` advice | Advise a tool admission | `{call, source}` | deny/ask/allow | The admission's cancel stops the advisor | `deny`, `ask`, `allow`; failures map to allow/ask | @@ -142,7 +142,7 @@ The `HooksRuntime` runner is Session-private; `HooksSession` and `HooksBranch` u ### Client-visible changes -None. `hooks.*` and the six hook points keep their client-visible behavior; `hooksService.sources` is a plugin-facing owner operation, `HookSourcesHost` was agent-crate-private, and `Permission.advise`/`Approval.decide` are #2100's contract names. +None. `hooks.*` and the six hook points keep their client-visible behavior; `hooksService.sources` is a plugin-facing owner operation, the removed source port was private, and `Permission.advise`/`Approval.decide` are #2100's contract names. ### Rule check @@ -192,7 +192,7 @@ impl HooksSettings { } ``` -Current types: `HookRefusal`, `HookSourcesSnapshot`, `HooksContentError` and the `hooks_settings.rs`/`hooks/sources.rs` structs; the target uses the same names and adds `Serialize` to the wire values. The target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. +Current types: `HookRefusal`, `HookSourcesSnapshot`, `HooksContentError` and the `hooks_settings.rs`/`hooks/sources.rs` structs; the target uses the same names and adds `Serialize` to the wire values. The target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. Wire-code mapping (internal variant -> published code): hooks_invalid, hooks_conflict, hooks_failed. The Session and branch parts keep their internal types; `hooksService.sources`' request and reply are `{cwd}` and `HookSources`. diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md index 26cf397deb..c299a5fc9a 100644 --- a/docs/design/plugins/Mcp.md +++ b/docs/design/plugins/Mcp.md @@ -17,7 +17,7 @@ Replaces the public-surface sections of [mcp-management.md](../appserver/mcp-man - **Configuration documents.** The Settings sources `mcp`, `mcp-projects`, `mcp-plugins` and `mcp-secrets`; `.mcp.json` is the project file of `mcp-projects` under a project Settings authorizes. - **Content registration.** The MCP document a plugin package carries, the holding plugin, and the refusal reason. - **Connection definitions and credentials.** The resolved server definitions, the OAuth records and refresh, and the disposable probe connection. -- **Client operations.** `mcp.catalog`, `mcp.configuration`, `mcp.update`, `mcp.save`, `mcp.remove`, `mcp.set_enabled`, `mcp.move`, `mcp.import.preview`, `mcp.import.apply`, `mcp.test`, `mcp.inspect`, `mcp.disconnect` and `mcp.auth.*`. +- **Client operations.** `mcp.catalog`, `mcp.configuration`, `mcp.update`, `mcp.save`, `mcp.remove`, `mcp.set_enabled`, `mcp.move`, `mcp.import.sources`, `mcp.import.preview`, `mcp.import.apply`, `mcp.test`, `mcp.inspect`, `mcp.disconnect`, `mcp.temporary.capabilities` and `mcp.auth.*`. - **Session-facing values and commands.** The selection, definition and credential reference a Session reads; the connection-state registry that Sessions report into; the disconnect command a Session observes. `McpSession` owns: @@ -115,9 +115,9 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcpService.withdraw` | Withdraw a package's MCP document | `{plugin}` | `{}` | Accepted write is not cancelled | `closed` | | `mcpService.plugins` | List the packages holding MCP content | `{}` | `{plugins}` | None | `closed` | | `mcpService.refusal` | The refusal reason of a package | `{plugin}` | `{reason?}` | None | `closed` | -| `mcp.catalog` | The merged servers and their revisions | `{project?}` | `{servers, userRevision, projectRevision, userApplication, pluginApplication, projectApplication, invalid}` | Read can be cancelled | `mcp_invalid_config`, `service_reloading`, `operation_interrupted`, `closed`, `cancelled` | +| `mcp.catalog` | The merged servers and their revisions | `{cwd?}` | `{servers, userRevision, projectRevision, userApplication, pluginApplication, projectApplication, invalid}` | Read can be cancelled | `mcp_invalid_config`, `service_reloading`, `operation_interrupted`, `closed`, `cancelled` | | `mcp.configuration` | One entry's declared and effective view | `{id, project?}` | `{entry}` | Read can be cancelled | `missing`, `closed`, `cancelled` | -| `mcp.save` | Create or replace one entry at a revision | `{id?, revision?, entry}` | `{entry, revision}` | Accepted write is not cancelled | `invalid`, `conflict`, `user_scope`, `settings_write`, `closed` | +| `mcp.save` | Create or replace one entry at a revision | `{cwd?, id, source, expectedVersion, configuration}` | `{}` | Accepted write is not cancelled | `mcp_invalid_config`, `mcp_settings_read`, `service_reloading`, `operation_interrupted`, `closed` | | `mcp.update` | Change selected fields at a revision | `{id, revision, patch}` | `{entry, revision}` | Accepted write is not cancelled | `invalid`, `missing`, `conflict`, `closed` | | `mcp.remove` | Remove an entry | `{id, revision}` | `{}` | Accepted write is not cancelled | `missing`, `conflict`, `closed` | | `mcp.set_enabled` | Enable or disable an entry | `{id, enabled, project?}` | `{}` | Accepted write is not cancelled | `invalid`, `missing`, `closed` | @@ -125,7 +125,7 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcp.import.preview` | Parse an import payload without writing | `{document, project?}` | `{entries, invalid}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | | `mcp.import.apply` | Write the selected imported entries | `{document, selection, project?}` | `{applied, invalid}` | Accepted write is not cancelled | `invalid`, `conflict`, `closed` | | `mcp.import.sources` | Discover import sources | `{cwd?}` | `{sources}` | Read can be cancelled | `invalid`, `closed`, `cancelled` | -| `mcp.temporary.capabilities` | The temporary binding capabilities ACP reads | `{}` | `{capabilities}` | None | `closed` | +| `mcp.temporary.capabilities` | The temporary binding capabilities ACP reads | `{}` | `{transports, leaseSeconds}` | None | `closed` | | `mcp.test` | Probe one server definition with a disposable connection | `{config, timeout?}` | `{status, latency, tools, reason}` | Cancel or timeout stops the probe; the owner settles it | `invalid`, `timeout`, `refused`, `cancelled`, `closed` | | `mcp.inspect` | One entry's enabled state, configuration and live connections, read from the report registry | `{cwd?, id, source}` | `{enabled, configuration, connections}` | None | `mcp_invalid_config`, `closed` | | `mcp.disconnect` | Ask every Session to close one source or server | `{source?, server?}` | `{}` | None; the command is a value | `closed` | @@ -137,7 +137,7 @@ let binding = temporary.attach(ctx, server, cancelled).await?; | `mcpSession.refresh` | Ask the owner to rediscover the enabled entries | `{}` | `{}` | None; the signal is a value | `closed` | | `mcpSession.widget` | The view for one published tool | `{publishedTool}` | `{view}` or absent | The client dropping the call cancels the read | `absent`, `unsupported`, `not_callable`, `unknown_server`, `unavailable`, `refused`, `unknown`, `closed` | | `mcpSession.call` | One MCP Apps call | `{server, tool, args}` | `{result}` | The client dropping the call cancels the resource read | `unknown_server`, `unavailable`, `refused`, `unknown`, `cancelled`, `closed` | -| `session.mcp_temporary.attach` | Mount a client temporary binding | `{sessionId, bindingId, servers}` | `{}` | The caller dropping the call shuts the half-made binding | `invalid`, `mount_failed`, `cancelled`, `closed` | +| `session.mcp_temporary.attach` | Mount a client temporary binding | `{sessionId, bindingId, servers}` | `{}` | The caller dropping the call shuts the half-made binding | `invalid_params`, `mcp_binding_failed`, `mcp_binding_conflict`, `mcp_binding_missing`, `cancelled`, `closed` | | `session.mcp_temporary.renew` | Extend the binding lease | `{binding}` | `{}` | None | `invalid`, `missing`, `closed` | | `session.mcp_temporary.detach` | Remove the binding and its children | `{binding}` | `{}` | None; the owner completes the removal | `missing`, `closed` | @@ -230,12 +230,12 @@ None. `mcp.inspect` keeps `{cwd?, id, source}` and `{enabled, configuration, con impl McpSession { pub fn state(&self) -> McpSessionState; pub fn refresh(&self) -> Result<(), McpSessionError>; - pub async fn widget(&self, caller: &Ctx, published_tool: PublishedTool, cancelled: CancelledFn) -> Result, McpAppError>; + pub async fn widget(&self, caller: &Ctx, published_tool: PublishedToolRef, cancelled: CancelledFn) -> Result, McpAppError>; pub async fn call(&self, caller: &Ctx, server: String, tool: String, args: serde_json::Value, cancelled: CancelledFn) -> Result; } ``` -`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. Current types: `McpPluginDocument`, `McpPluginRefusal`, `McpWidgetResult` and the `mcp/management.rs`/`mcp/session.rs` request and reply structs; `PublishedTool` is private, so the target exposes a public `PublishedToolRef` value instead. Target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. The current `McpAppError` is a non-serializable `thiserror` enum and is marked target. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. +`session.mcp_temporary.attach/renew/detach` are `SessionMethods` registrations; `attach` takes `caller: &Ctx` and the binding id is bound to the caller's Session row. Current types: `McpPluginDocument`, `McpPluginRefusal`, `McpWidgetResult` and the `mcp/management.rs`/`mcp/session.rs` request and reply structs; `PublishedTool` is private, so the target exposes a public `PublishedToolRef` value instead. Target error enums use `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`; one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. The current `McpAppError` is a non-serializable `thiserror` enum and is marked target. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. Wire-code mapping (internal variant -> published code): mcp_invalid_config, mcp_settings_read, service_reloading, operation_interrupted. ```rust #[rutis::service(name = "mcpService")] diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index e30fa0de2a..13dd5fa38f 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -73,13 +73,13 @@ if let Some(reason) = refusal { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `plugin.list` | The installed packages and their state | `{}` | bare array of package status maps `{id, name, enabled, locked, skipped, refused, restartRequired}` | None | `plugin_not_found`, `closed` | -| `plugin.install` | Install a local path or Git source | `{source, name?, lock?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted install settles or rolls back | `plugin_exists`, `invalid_params`, `invalid_id`, `path_outside_plugins`, `load_failed`, `content_refused`, `restart_required`, `closed` | -| `plugin.enable` | Make one installed package the name's active package | `{name, version?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `load_failed`, `content_refused`, `restart_required`, `closed` | -| `plugin.disable` | Turn a package name off | `{name}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `restart_required`, `closed` | -| `plugin.reload` | Reload a package's rows | `{name}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `load_failed`, `content_refused`, `closed` | -| `plugin.update` | Update a package to a source revision | `{name, source?, lock?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted update settles or rolls back | `plugin_not_found`, `plugin_locked`, `invalid_params`, `load_failed`, `content_refused`, `closed` | -| `plugin.remove` | Remove a package | `{name, version?}` | `{}` | Accepted remove settles or restores | `plugin_not_found`, `plugin_locked`, `load_failed`, `closed` | +| `plugin.list` | The installed packages and their state | `{}` | bare array of items `{name, use, off, locked, candidates, optional?, update?}` | None | `plugin_not_found`, `closed` | +| `plugin.install` | Install a local path or Git source | `{source, id?, enable?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted install settles or rolls back | `plugin_exists`, `invalid_params`, `invalid_source`, `invalid_manifest`, `acquire_failed`, `optional_not_found`, `node_unavailable`, `dependencies_failed`, `not_updatable`, `not_removable`, `name_changed`, `invalid_id`, `path_outside_plugins`, `closed` | +| `plugin.enable` | Make one installed package the name's active package | `{name, use?}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `not_reloadable`, `node_unavailable`, `closed` | +| `plugin.disable` | Turn a package name off | `{name}` | `{}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `closed` | +| `plugin.reload` | Reload a package's rows | `{name}` | status map `{id, name, enabled, locked, skipped, refused, restartRequired}` | Accepted operation settles | `plugin_not_found`, `plugin_locked`, `not_reloadable`, `closed` | +| `plugin.update` | Update a package to a source revision | `{id, ref?}` | `{commit}` or `{version}` plus content outcomes | Accepted update settles or rolls back | `plugin_not_found`, `not_updatable`, `name_changed`, `invalid_source`, `acquire_failed`, `closed` | +| `plugin.remove` | Remove a package | `{id, ref?}` | `{}` | Accepted remove settles or restores | `plugin_not_found`, `not_removable`, `plugin_locked`, `closed` | | Startup reconcile | Remove directories and records that are not installed; restore the default configuration | internal | — | None | `record_read`, `record_write`, `cleanup` | | Content registration | Register or withdraw a package's MCP, Hooks, Skills and UI content | internal | `refusal` | The owner's content call can be cancelled | the content owners' refusals are values | | `plugin` tool | Map one model command to a process operation | `{command, args}` | tool result content | The tool call's cancel stops the operation | `usage`, the owner's errors | @@ -169,7 +169,7 @@ tool_registry.register( ); ``` -`manager` is the process owner's operation/callback, not the `Manager` object. The current `PluginError` is a struct; the target replaces it with `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`, one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. +`manager` is the process owner's operation/callback, not the `Manager` object. The current `PluginError` is a struct; the target replaces it with `#[derive(Debug, serde::Serialize, thiserror::Error)]` and `#[serde(tag = "code", rename_all = "snake_case")]`, one variant per error table code; a callback failure is `Rejected { reason, message }` with wire code `rejected`. `From` is implemented where a callback failure must propagate. `CancelledFn` is the binding's cancellation argument, never a request field. The `PluginTools` `manager` field is deleted; the install/update/remove result values remain. The temporary-crate check with rustc 1.100.0 passed; every target error enum carries `#[error("...")]` for `Display`. Wire-code mapping (internal variant -> published code): plugin_not_found, plugin_exists, plugin_locked, invalid_params, invalid_id, path_outside_plugins, not_updatable, not_removable, not_reloadable, name_changed, invalid_source, invalid_manifest, acquire_failed, optional_not_found, node_unavailable, dependencies_failed. ## Supersedes @@ -203,7 +203,7 @@ A plugin is a directory with `dim-plugin.json` at its root. The keys present say | `name` | — | The plugin's name. Plugins with the same name replace each other. | | `version` | — | The plugin's own version, three dot-separated numbers, each one or more digits. Optional, and required for an optional plugin (§2.3), where it names the install directory. | | `code` | code | The rutis row fields ([rutis usage §2](../rutis-usage.md#2-plugins-are-rows-instances-mount-their-parts)) except `id` and `name`: `entry` is a path inside the directory; `inject`, `provides` and `instanceNames` are copied into the row; `config` is the row's configuration, with the host's patch for that plugin name deep-merged over it (below). | -| `dependencies` | code | The package manager whose dependencies the plugin declares. The only value today is `"npm"`: the directory carries `package.json` and `package-lock.json`, and the locked dependencies are installed into the plugin's own directory at acquisition (§7 and the target install flow). A manifest declaring it without either file is refused `invalid_manifest`. | +| `dependencies` | code | The package manager whose dependencies the plugin declares. The only value today is `"npm"`: the directory carries `package.json` and `package-lock.json`, and the locked dependencies are installed into the plugin's own directory at acquisition (§7 and the install/update behavior in §2.1-§2.3). A manifest declaring it without either file is refused `invalid_manifest`. | | `skills` | skills | A directory inside the plugin of Skill documents, registered with SkillsCatalog. | | `mcp` | MCP | A file inside the plugin holding MCP server entries, registered with Mcp. | | `hooks` | hooks | A file inside the plugin holding a hooks document, registered with Hooks. | @@ -271,7 +271,7 @@ new manifest readable by an old binary. | `installed[].id` | Unique among installed plugins; the key of the record and the name of the clone directory. Matches `[a-z0-9_-]{1,64}` (lowercase, so two ids never name one directory on a case-insensitive file system) and is not `builtin` or `default` (§7). When the caller gives none, the id is the manifest name lowercased (`Hooks` → `hooks`); a collision after lowercasing is `plugin_exists`, and the caller then gives another id. The example's `hooks-plus` was given by the caller (`--id hooks-plus`). | | `installed[].name` | The manifest name at install or last reload. | | `installed[].source` | `{path}` for a local directory, used in place and never copied; `{git, ref?, commit}` for Git; `{optional}` for a plugin the default configuration file ships optionally (§2.3), copied from its shipped directory. | -| `installed[].dir` | The directory that is loaded: the local path itself, the clone under `/plugins//+`, or the copy under `/plugins//+` (§7 and the target install flow). A record written before suffixes existed names its directory without one; nothing is migrated. | +| `installed[].dir` | The directory that is loaded: the local path itself, the clone under `/plugins//+`, or the copy under `/plugins//+` (§7 and the install/update behavior in §2.1-§2.3). A record written before suffixes existed names its directory without one; nothing is migrated. | | `installed[].kinds` | The kinds the manifest carried at install or last reload. | | `installed[].version` | The installed version of an `{optional}` source, from its manifest; absent for other sources. | | `names..use` | Which plugin the name uses: an installed id, `"builtin"` or `"default"`. Absent: the built-in plugin of that name if there is one, else the default plugin of that name. | @@ -321,9 +321,9 @@ Shipped with Dim, read-only, given to the App Server with `--defaults PATH` (the ``` - `plugins` maps each default plugin's name to its directory, relative to this file. A default plugin is a plugin directory like any other (§2.1). -- `optional` maps an optional plugin's name to its directory, relative to this file. An optional plugin is shipped but is not installed and not turned on: nothing reads it until the user installs it, and `plugin.list` shows it so a client can offer it (§3.6). `plugin.install {source: {optional: ""}}` copies the directory — never `node_modules` — into `/plugins//+` and installs its declared dependencies there (§7 and the target install flow); the shipped directory stays untouched and read-only. A newer release ships a new `version`: at the next start an installed copy is re-acquired in the background (§3.1), the old copy stays in use and on disk until that succeeds, and the next start after the switch deletes it. `enable` defaults to true, `plugin.enable` and `plugin.disable` then work as for any installed plugin, and an optional plugin's name records no `off` state until it is installed: `plugin.list` reports it off (§3.6). +- `optional` maps an optional plugin's name to its directory, relative to this file. An optional plugin is shipped but is not installed and not turned on: nothing reads it until the user installs it, and `plugin.list` shows it so a client can offer it (content registration). `plugin.install {source: {optional: ""}}` copies the directory — never `node_modules` — into `/plugins//+` and installs its declared dependencies there (§7 and the install/update behavior in §2.1-§2.3); the shipped directory stays untouched and read-only. A newer release ships a new `version`: at the next start an installed copy is re-acquired in the background (§3.1), the old copy stays in use and on disk until that succeeds, and the next start after the switch deletes it. `enable` defaults to true, `plugin.enable` and `plugin.disable` then work as for any installed plugin, and an optional plugin's name records no `off` state until it is installed: `plugin.list` reports it off (content registration). - Built-in SessionTitle, Scheduler and Goal are installed by the native product profile and have no entry in this file. -- A name cannot appear in both `plugins` and `optional`, and an optional plugin's name cannot be a built-in plugin's: each is a startup error naming both. An optional plugin's item has no candidates (§3.6), so it would hide the plugin shipped under that name. +- A name cannot appear in both `plugins` and `optional`, and an optional plugin's name cannot be a built-in plugin's: each is a startup error naming both. An optional plugin's item has no candidates (content registration), so it would hide the plugin shipped under that name. - `locked` lists names that cannot be turned off and whose plugin cannot be switched. Other plugins of a locked name may still be installed. Locking is product configuration; PluginManager applies it. @@ -382,6 +382,9 @@ See the target contract's operations. ## 9. Requirements raised to mechanism owners See the target contract's requirements. +### 3.7 Content registration +See the target content registration and the four content owners. + ### A.1 Methods (managementMethods, namespace plugin) See `plugin.*` in the target contract. diff --git a/docs/design/plugins/Skills.md b/docs/design/plugins/Skills.md index 26c5bcb33f..d4b0f827e7 100644 --- a/docs/design/plugins/Skills.md +++ b/docs/design/plugins/Skills.md @@ -52,15 +52,15 @@ Callers keep: `PluginManager` registers a package's Skills root: ```rust -let issues = skills_catalog.register(ctx, plugin, dir, document).await?; +let issues = skills_catalog.register(ctx, plugin, dir).await?; report_issues(plugin, issues); // the package is installed; the root is refused or partly scanned ``` The local client previews and installs: ```rust -let preview = skills.preview(source, selection, cancelled.clone()).await?; -let installed = skills.install(preview.token, selection, cancelled).await?; +let preview = skills.preview(source, id, cwd, cancelled.clone()).await?; +let installed = skills.install(source, id, skills, overwrite, cancelled).await?; ``` `Skills` mounts one content instance: @@ -99,10 +99,10 @@ if list.generation != seen { | `skills.catalog` | The client catalog | `{project?}` | `{skills, projects, invalid}` | The read can be cancelled | `invalid`, `closed`, `cancelled` | | `skills.set_enabled` | Enable or disable a Skill or project | `{id, enabled, project?}` | `{}` | Accepted write is not cancelled | `missing`, `invalid`, `conflict`, `closed` | | `skills.refresh` | Rescan the roots | `{}` | `{generation}` | None; the scan is the owner's | `closed` | -| `skills.preview` | Preview a local or Git source | `{source, skills}` | `{source, skills, conflicts, shadows, issues}` | The read can be cancelled | `skills_invalid_source`, `skills_fetch_failed`, `skills_too_large`, `cancelled`, `closed` | -| `skills.install` | Install the selected entries | `{source, id?, skills, overwrite}` | `{installation, previous?}` | Accepted work is not cancelled; it settles or restores | `skills_preview_stale`, `skills_install_exists`, `skills_install_unmanaged`, `skills_install_unknown`, `skills_write_failed`, `closed` | -| `skills.update` | Update installed entries | `{id, revision?}` | `{installed}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `conflict`, `write_failed`, `closed` | -| `skills.remove` | Remove installed entries | `{id}` | `{}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `delete_failed`, `closed` | +| `skills.preview` | Preview a local or Git source | `{source, id?, cwd?}` | `{source, skills, conflicts, shadows, issues}` | The read can be cancelled | `skills_invalid_source`, `skills_fetch_failed`, `skills_too_large`, `cancelled`, `closed` | +| `skills.install` | Install the selected entries | `{source, id, skills, overwrite}` | `{installation, previous?, version, issues}` | Accepted work is not cancelled; it settles or restores | `skills_preview_stale`, `skills_install_exists`, `skills_install_unmanaged`, `skills_install_unknown`, `skills_write_failed`, `closed` | +| `skills.update` | Update installed entries | `{id}` | `{installation, previous?, version, issues}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `conflict`, `write_failed`, `closed` | +| `skills.remove` | Remove installed entries | `{id}` | `{version}` | Accepted work is not cancelled; it settles or restores | `missing`, `unmanaged`, `delete_failed`, `closed` | | `skills.installations` | The install records | `{}` | `{installations}` | None | `closed` | | `Skills` view | The `SessionSkills` value and its generation | `{}` | `{list, generation}` | The Session close stops the read | `unavailable`, `closed` | | `skill` tool | Read one Skill's content for the model | `{name}` | tool result content | The tool call's cancel | `unknown`, `disabled`, `unavailable`, `invalid` | @@ -129,6 +129,7 @@ The `SkillsCatalog`'s management methods are registered through #2095; the `skil | `skills_preview_stale` | Re-preview; the source moved | | `skills_install_exists`, `skills_install_unmanaged`, `skills_install_unknown` | Re-read the record and choose an id/selection | | `skills_write_failed` | Report the partial state; retry update/remove | +| `skills_selection_invalid`, `skills_install_conflict`, `skills_install_failed`, `skills_remove_failed` | Fix the selection or retry the write/remove | | `closed` | The owner is unloading; use the replacement generation | #### Flows @@ -197,7 +198,7 @@ None. `skills.*` keep their client-visible behavior; `skills.install/update/remo ```rust #[rutis::service(name = "skillsCatalog")] impl SkillsCatalog { - pub async fn register(&self, caller: &Ctx, plugin: String, dir: String, document: SkillDocument, cancelled: CancelledFn) -> Result; + pub async fn register(&self, caller: &Ctx, plugin: String, dir: String, cancelled: CancelledFn) -> Result, SkillsError>; pub async fn withdraw(&self, caller: &Ctx, plugin: String, cancelled: CancelledFn) -> Result<(), SkillContentError>; pub fn plugins(&self) -> Vec; pub fn issues(&self, plugin: &str) -> SkillIssues; From 18d5e4f076c82e25d0235f325abbcaaabced4e3a Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:10:23 +0800 Subject: [PATCH 8/8] docs(content-owners): map the new kinds onto the existing client codes --- docs/design/plugins/Mcp.md | 4 ++-- docs/design/plugins/PluginManager.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/design/plugins/Mcp.md b/docs/design/plugins/Mcp.md index c299a5fc9a..8a41b6d615 100644 --- a/docs/design/plugins/Mcp.md +++ b/docs/design/plugins/Mcp.md @@ -154,7 +154,7 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl | `settings_write`, `settings_conflict` | Retry after the Settings row is available, or report the conflict | | `refused`, `unsupported`, `not_callable`, `unknown_server`, `unavailable`, `unknown`, `absent` | Report the MCP view or tool error; the generation is unchanged | | `timeout` | The probe did not finish; the owner settled it; report the result | -| `mount_failed` | The child rows did not activate; the owner shut them down; report the binding failure | +| `mount_failed` (wire code `mcp_binding_failed`) | The child rows did not activate; the owner shut them down; report the binding failure in the code clients already receive | | `cancelled` | Nothing was committed; the read or the flow stopped | | `mcp_invalid_config` | Fix the MCP document or entry; the client sees the current invalid-config code | | `mcp_settings_read` | Retry after Settings is readable, or report the failure | @@ -175,7 +175,7 @@ The internal `McpSession` connection operations (`open`, `tools`, `observe`, `cl ## Client-visible changes -None. `mcp.inspect` keeps `{cwd?, id, source}` and `{enabled, configuration, connections}`, now re-sourced from the report registry; `mcp.catalog`, `mcpSession.state`, `session.mcp_temporary.attach`, `mcp.import.sources` and `mcp.temporary.capabilities` keep their current requests, replies and codes. The removed `mcpSession.subscribe` is Rust-only and never crossed the client protocol. +None. `mcp.inspect` keeps `{cwd?, id, source}` and `{enabled, configuration, connections}`, now re-sourced from the report registry; `mcp.catalog`, `mcpSession.state`, `session.mcp_temporary.attach`, `mcp.import.sources` and `mcp.temporary.capabilities` keep their current requests, replies and codes. Internal kinds map onto the codes clients already receive: `mount_failed` is `mcp_binding_failed`, `invalid` is `invalid_params` where the method answered it before, and `missing` is the existing not-found code of each method. The removed `mcpSession.subscribe` is Rust-only and never crossed the client protocol. ## Exceptions with reasons diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index 13dd5fa38f..c2b8818fe1 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -121,7 +121,7 @@ if let Some(reason) = refusal { ### Client-visible changes -None. `plugin.*` and the `plugin` tool keep their commands, results and errors; the `Manager` handoff was a Session-part implementation detail. +None. `plugin.*` and the `plugin` tool keep their commands, results and errors; the `Manager` handoff was a Session-part implementation detail. The owner's kinds map onto the codes clients receive today: `exists` is `plugin_exists`, `missing` is `plugin_not_found`, `load_failed` and `restart_required` are `acquire_failed`, `content_refused` is `refused`, `write_failed` is `record_unreadable`, `usage` is `invalid_params`, and `invalid_source`, `invalid_manifest`, `invalid_id`, `path_outside_plugins`, `plugin_locked` and `invalid_params` keep their names. ### Rule check