diff --git a/docs/design/appserver/management-methods.md b/docs/design/appserver/management-methods.md index 9b7a9bee27..554cebefc6 100644 --- a/docs/design/appserver/management-methods.md +++ b/docs/design/appserver/management-methods.md @@ -56,7 +56,8 @@ the profile enables account methods. Settings supplies generic BusinessDocument persistence and the declared sources of [the settings service](settings-service.md), not approvals, a method contribution or a configuration namespace; SettingsMethods, which depends on it, owns -`settings.read`/`settings.update`/`settings.sources`/`settings.projects`. +`settings.read`/`settings.update` for declared sources ([SettingsMethods](../plugins/SettingsMethods.md)); a Rust source is +served by its owner's own namespace. StorageMethods serves `storage.report` through the native binding of the same SQLite owner operation exposed as `sqliteStorage.storageReport({})`. MCP owns its configuration types in `mcp/config.rs`; the Skills owner supplies the existing `SkillSettingsHost`. App Server's SkillsCatalog mounts the reusable catalog diff --git a/docs/design/appserver/model-log.md b/docs/design/appserver/model-log.md index 0c7d4b3484..4eae049b46 100644 --- a/docs/design/appserver/model-log.md +++ b/docs/design/appserver/model-log.md @@ -8,9 +8,9 @@ aimux's RFC-0023 JSONL (`aimux-core`'s `recording.rs`). | Owner | Responsibility | | --- | --- | -| ModelLog, process | Register the `model-log` Settings source, start and stop the recorder, follow its changes | -| Aimux, process | Bind a request to the recorder that is on when the request is built, and close the recording when its stream ends | -| Settings service | Validate and persist `model-log.json`, user scope only | +| ModelLog, process | Register the `model-log` Settings source and answer its `recording` value ([ModelLog](../plugins/ModelLog.md)) | +| Aimux, process | Read the recording value when a request is built and close the recording when its stream ends | +| Settings | Validate and persist `model-log.json`, user scope only | The switch is user scope only: recordings hold prompts, code and tool output, so project content must not turn them on. diff --git a/docs/design/appserver/permission-command-rules.md b/docs/design/appserver/permission-command-rules.md index b7fabf37eb..00ac5e0e5b 100644 --- a/docs/design/appserver/permission-command-rules.md +++ b/docs/design/appserver/permission-command-rules.md @@ -109,23 +109,15 @@ restore and fork neither restore nor widen them. ### 4.1 Language-neutral (ADR 002 D5) -**Session service `commandRules`**, Session scope, no instance key, provided by the profile. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `read` | async | `{}` | `{rules: CommandRule[]}` | - -`CommandRule = {command: string, match: "exact" | "prefix", decision: "allow" | "deny"}`. Errors -are data: `unavailable` (the source could not be read, including an invalid persisted file), -`cancelled` (the caller dropped the call or the provider is unloading). +**Session service `commandRules`** is deleted. Rule consumers call [PermissionRules](../plugins/PermissionRules.md)'s `permissionRules.rules` (`{}` → `{rules}`); `CommandRule = {command: string, match: "exact" | "prefix", decision: "allow" | "deny"}`. **Management methods**, namespace `permission`, which the process part registers with `managementMethods` (overview §6.2 rule 9; never served to paired devices). | Method | Request | Reply | Errors | | --- | --- | --- | --- | -| `permission.rules` | `{}` | `{revision, commandRules}` | `permission_rules_failed` | -| `permission.set_rules` | `{expectedRevision, commandRules}` | `{revision}` | invalid params (validation), `permission_rules_conflict` (stale revision), `permission_rules_failed` | +| `permission.rules` | `{}` | `{revision, commandRules}` | `permission_rules_failed`, `operation_interrupted` | +| `permission.set_rules` | `{expectedRevision, commandRules}` | `{revision}` | invalid params (validation), `permission_rules_conflict` (stale revision), `permission_rules_failed`, `operation_interrupted` | `set_rules` replaces the whole list. The reply's `revision` is the Settings revision. Settings emits its existing `settings.changed` event for the write; F2 adds no listener. diff --git a/docs/design/appserver/prompt-overrides.md b/docs/design/appserver/prompt-overrides.md index b24e17b073..38839d49be 100644 --- a/docs/design/appserver/prompt-overrides.md +++ b/docs/design/appserver/prompt-overrides.md @@ -36,14 +36,14 @@ adopted. ```text App Server process row: PromptSettings registers Settings source "prompts" - provides three ports from the same document + owns one promptSettings service | - +--------------------------+--------------------------+ - | | | - BasePromptSettingsHost SkillsInstructionsSettingsHost SummaryPromptSettingsHost - | | | - PromptSources part Skills part ProductSummaryStrategy part - (dim/base) (dim/skills/instructions) (summary prompt) + +------------------+------------------+ + | | | + base() skills() summary() + | | | + PromptSources part Skills part ProductSummaryStrategy part + (dim/base) (dim/skills/instructions) (summary prompt) \ | / read once while the Session part applies ``` @@ -80,13 +80,10 @@ are its normal surface; in the file-backed profile it is `prompts.json` under th ## 3. Host ports and precedence -Each owner declares its own port, so a capability depends only on its own text: - -| Owner | Port | Reads | -| --- | --- | --- | -| PromptSources | `BasePromptSettingsHost` | `base` | -| Skills | `SkillsInstructionsSettingsHost` | `skills` | -| ContextCompaction | `SummaryPromptSettingsHost` | `summary` | +Each capability reads only its own text. The owner service is [PromptSettings](../plugins/PromptSettings.md); a +capability outside the App Server depends on the port trait in `dim-agent-capabilities` for its text: +`BasePromptSettings` for PromptSources, `SkillsInstructionsSettings` for Skills and +`SummaryPromptSettings` for ContextCompaction. - The port is optional (`Option>`): an assembly that does not register the name, such as the capability tests or a host without Settings, injects nothing and keeps its built-in text. @@ -100,30 +97,13 @@ Each owner declares its own port, so a capability depends only on its own text: ### 3.1 Data operations -The same three read ports are available to plugins of any language: - -| Service | Async operation | Request | Reply | -| --- | --- | --- | --- | -| `basePromptSettingsHost` | `base` | `{}` | string or `null` | -| `skillsInstructionsSettingsHost` | `instructions` | `{}` | string or `null` | -| `summaryPromptSettingsHost` | `systemPrompt` | `{}` | string or `null` | - -Each reply is that port's existing override text; `null` means no user override. -The ports read through the same PromptSettings owner and source. They add no cache, -extra source read, configuration field or change to the precedence above. - -Errors are `{code, message}`. The product owner reports `failed` for a settings read -error, including a settings read ended by cancellation, retaining its existing error -text. Malformed wire requests are `invalid_request`. Dropping a wire call cancels -its read token and abandons its reply; this does not introduce a new product error -code. Native callers retain their existing cancellation token and error behavior; -a failed port read does not change the source. +Superseded by [PromptSettings](../plugins/PromptSettings.md): one service `promptSettings` with `base`, `summary` and `skills`, each answering `{text}` or none. The precedence above and the client entry below stay in force. ## 4. Client entry The settings methods are the primitive: `settings.read` and `settings.update` with -`source: "prompts"`, `scope: "user"`. `settings.sources` publishes the schema, and both methods -are management methods, so only a local connection can edit the texts. +`source: "prompts"`, `scope: "user"`. The client knows the three member names; `settings.sources` +is deleted. Both methods are management methods, so only a local connection can edit the texts. The native client presents each field as plain text rather than JSON: @@ -189,37 +169,18 @@ Rules: [design rules](../../architecture/rust-agent/principles.md) §1 and §4, | Rule | How this design complies | | --- | --- | -| §1 Plugins and capabilities bounded | Each text stays in its owner; the App Server owns only the Settings document and the ports | +| §1 Plugins and capabilities bounded | Each text stays in its owner; the App Server owns the document and the one service, and each capability depends on its own port trait | | §4 rule 4 No business meaning in core | No core type gains a prompt text; the ports are capability-level contracts | | §4 rule 6 Context from consumed events | The text reaches the model through the existing adopted prompt sources; no new context path | -| §4 rule 7 Public events and services | No new event, client method or Timeline fact; the existing Settings methods and three optional process services are used | +| §4 rule 7 Public events and services | No new event, client method or Timeline fact; the existing Settings methods and one optional process service are used | | §4 rule 8 Infrastructure unchanged | No change to Timeline, Dispatcher, rutis or the assembly mechanism | | ADR 002 D1 Scope | The document and ports live at the process scope where the shared configuration is; the texts live in their Session parts | | ADR 002 D4 Configuration | Business configuration stays with its owner; the document is the App Server's source, as `execution` and `prompt-suggestion` are | | ADR 007 D5 Owner registration | A dedicated App Server row registers the source; Settings and the assembly declare none | | ADR 008 D2 No delivery status | This document states the design; the issue tracks delivery | -| ADR 008 D3 Own scope only | The owner documents state their own port; this page states the product setting and the client entry | +| ADR 008 D3 Own scope only | The owner contract states the service and the ports; this page states the product setting and the client entry | ## 7. Binding appendix -```rust -pub trait BasePromptSettings: Send + Sync + 'static { - fn base(&self, cancel: CancellationToken) -> HostFuture<'_, Option>>; -} -pub struct BasePromptSettingsHost(pub Arc); - -pub trait SkillsInstructionsSettings: Send + Sync + 'static { - fn instructions(&self, cancel: CancellationToken) -> HostFuture<'_, Option>>; -} -pub struct SkillsInstructionsSettingsHost(pub Arc); - -pub trait SummaryPromptSettings: Send + Sync + 'static { - fn system_prompt(&self, cancel: CancellationToken) -> HostFuture<'_, Option>>; -} -pub struct SummaryPromptSettingsHost(pub Arc); -``` - -The App Server row registers the `prompts` declaration and provides the three hosts from one -`PromptDocument`; each host reads only its field. Each binding is provided at its Rust type key and -`host_key` for its service name. Its dispatcher calls the same owner method; native -callers invoke that method directly without JSON conversion. +Superseded by the binding appendix of [PromptSettings](../plugins/PromptSettings.md); the three +`*SettingsHost` types are deleted. diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 86c50ac553..00676a1e0e 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -50,7 +50,7 @@ with its existing owner; management never writes another owner's state. | Account namespaces | Account owners provide login, usage and logout. The [ChatGPT plan provider](chatgpt-plan.md) owns `account.chatgpt`. | | `ProviderConnectionResolver`, `ModelSelectionHost` | Provider implements catalog/route decisions through existing types; no new core port | | `auxiliaryModel.complete` | Existing caller-selected S4 contract, unchanged | -| `provider` Settings source, user scope (`provider.json`) | The Provider part registers it; it holds `userAgent`, the User-Agent override (§2, Model request identity), so a user's choice is a declared, validated document rather than a request-local input | +| `provider` Settings source, user scope (`provider.json`) | [ProviderSettings](../plugins/ProviderSettings.md) owns it; it holds `userAgent`, the User-Agent override (§2, Model request identity), and publishes it as a value a model request reads | | Native CLI Provider flows | Migrate discovery, create, update and disconnect together with the new owner methods | Business logic stays in Provider, not `connection.rs`, `protocol.rs` or a wiring @@ -101,7 +101,7 @@ default identity like any other Provider. | Override | Where | Notes | | --- | --- | --- | -| `provider` settings source, `userAgent` | `provider.json`, user scope, owned by the Provider part | Replaces the whole User-Agent string; 1–512 printable ASCII characters, refused by the source's schema otherwise. The part serving one App Server holds it, so two Servers in one process keep theirs apart | +| `provider` settings source, `userAgent` | `provider.json`, user scope ([ProviderSettings](../plugins/ProviderSettings.md)) | Replaces the whole User-Agent string; 1–512 printable ASCII characters, refused by the source's schema otherwise. A model request reads the value from ProviderSettings at request time, so two Servers in one process keep theirs apart | | `DIM_USER_AGENT` | Environment of the process that hosts models | The same validation; wins over the setting. Read once by the App Server command line, beside the other startup inputs, and passed to each Server it builds, so a value a request cannot carry fails that process's startup | `DIM_USER_AGENT` wins over the setting because it is set for one run of the diff --git a/docs/design/appserver/settings-service.md b/docs/design/appserver/settings-service.md index 10ad7b029e..125f31e3f3 100644 --- a/docs/design/appserver/settings-service.md +++ b/docs/design/appserver/settings-service.md @@ -17,10 +17,12 @@ each source with Settings when it starts ([ADR 007](../../adr/007-plugin-configu the source name, its files, a JSON Schema (with `default` values) and its user-only fields (§3.1). Settings then offers three things over JSON documents: -- the process service `settings`, which the owner uses: `register`, `read`, `update` (CAS on - the revision) and `projects`; -- the client management methods `settings.read`, `settings.update`, `settings.sources` and - `settings.projects`; +- the process service `settings`, which the owner uses: `register` (with its `userOnly` list), + `read`, `change`, `read_user`, `replace_user`, `agent_read`, `agent_set`, `declared_sources`, + `authorize_project` and `authorized_projects` (the target shapes are in + [Settings](../plugins/Settings.md)); +- the client management methods `settings.read` and `settings.update` for declared sources + ([SettingsMethods](../plugins/SettingsMethods.md)); - the same rutis events as S8a, `settings.changed` and `settings.project_authorized`. Their payloads become serializable. There is no `subscribe(source)`. @@ -38,10 +40,9 @@ way (§4.5). Rust sources keep their owners' management methods. F2's `permissio No new plugin, no Timeline event, no change to Timeline, Dispatcher, rutis or assembly. -The same Settings provider supplies generated `workflowFiles` for definition -directories. It reads the existing project authorization map and the original -process caller’s declared package scope, without exporting FileStorage or raw -root indices. See the [native definition-file contract](../p6-p7-bindings.md#3-workflow-definition-files). +Workflow definition files are not a Settings operation: Workflow composes the project's cwd +from `authorized_projects` with FileStorage's path operations +([#2033](https://github.com/arcships/dim/issues/2033)). ### 1.1 What this does not do @@ -49,8 +50,9 @@ root indices. See the [native definition-file contract](../p6-p7-bindings.md#3-w event bus (issue comment). Settings keeps no watch channel of its own. - No generic client access to Rust sources (`mcp`, `mcp-projects`, `mcp-plugins`, `skills`, `permission`). Their validation is Rust code that Settings cannot run on client JSON. -- Source discovery is `settings.sources` (§4.3): local connections can list the declared - sources and their schemas, never their documents. There is still no settings UI. +- Source discovery is by name: a local client reads and writes the declared sources it knows + through `settings.read`/`settings.update`; no method lists every declaration (`settings.sources` + is deleted in [#2017](https://github.com/arcships/dim/issues/2017)). There is still no settings UI. - No secret store, credential service or field-name rule (§1.2). The one marker is the schema's `writeOnly` annotation. - MCP's inline tokens, `env` and `headers` stay where they are (ADR 004 D4). @@ -95,17 +97,17 @@ depended on a store nobody owned. That service and the `*Ref` rule are withdrawn Process scope +-------------------------------------------------------------------------+ | Settings (existing plugin) | - | SettingsService | + | one service and the source registry | | registered sources, each until its registering plugin unloads: | | BusinessDocument types (Rust owners) | | declared sources: schema, defaults, files, user-only pointers | - | named service `settings` (HostDispatch) <-- owner writes | - | managementMethods `settings` <-- client writes | + | service `settings` <-- owner operations | + | managementMethods `settings.*` <-- client operations | | emits settings.changed on settings/, | | settings.project_authorized on settings/projects | +------^-------------------------------^----------------------------------+ - | register/read/update/projects | settings.read / settings.update - | | settings.sources / settings.projects + | register/read/change/... | settings.read / settings.update + | | (declared sources only) | | TypeScript owner (rutis runtime row) Rpc <-- local client ``` @@ -119,7 +121,7 @@ owner depends on `settings`. Every owner, built-in Rust and TypeScript alike, registers its sources from its own process row's `apply`. Declared sources use `settings.register(declaration)` through their language binding -(§4.2, §4.5); native `BusinessDocument` sources use `SettingsService::register::` (§4.5). Neither the App Server's assembly nor PluginManager +(§4.2, §4.5); native `BusinessDocument` sources use `Settings::register_typed::` (§4.5). Neither the App Server's assembly nor PluginManager declares sources. A registration belongs to the plugin that made it and is withdrawn when that plugin unloads (turned off, removed or reloaded); a reload registers again from the new generation. The stored documents stay in the home whether or not their source is registered: an @@ -198,87 +200,15 @@ plugin unloads. Nothing else is new. Nothing enters the Timeline. ### 4.1 Common shapes -| Shape | JSON | -| --- | --- | -| `Scope` | `"user"` or `{"project": }`. `root` is the project root number Settings assigns in this process (`SettingsScope::Project`). It is not a durable identity and is never persisted | -| `Snapshot` | `{revision: string, document: object}` | -| `Error` | `{code, message}` | -| `Sources` | The `settings.sources` reply (§4.3): `{dialect: string, sources: [{source, schema, scopes, userOnly, writeOnly}]}`. `dialect` is exactly `https://json-schema.org/draft/2020-12/schema`, the draft every `schema` is compiled in (§3.1). `schema` is the registered schema verbatim, `default` members included. `scopes` is `["user"]`, or `["user", "project"]` when the source declares a project file. `userOnly` is the registered pointer list. `writeOnly` hints that the schema root itself or a member reachable through `properties` is marked `writeOnly: true`. A root-level `writeOnly` counts for this hint but is not a hidden member: the redaction (§1.2) removes members reached through `properties` only, so such a source lists `writeOnly: true` and hides nothing. Neither rule scans `items`, `$defs` or `anyOf`, so a client reads `schema` itself for the rest. No item carries a document, a file name or an owner | +Superseded by the Data and binding sections of [Settings](../plugins/Settings.md): `Scope`, `Document`, the declarations, the project table and the error shapes are defined there. ### 4.2 Service `settings` (owner path) -Process scope, no instance key, provided by Settings. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `register` | async | a declaration (§3.1) | nothing; rejects when refused | -| `read` | async | `{source, scope: Scope}` | `Snapshot` | -| `update` | async | `{source, scope: Scope, expectedRevision, document}` | `Snapshot` (the stored document) | -| `declaredBy` | sync | `{instanceId: string}` (the live loader instance ID in decimal) | The JSON Schema declarations registered by that instance, ordered by source name. An instance with no live declarations returns an empty array. | -| `projects` | sync | `{}` | `{projects: [{root, cwd}]}`: the authorized project roots now | - -- `register` is a registration of the calling row, withdrawn when that row unloads. It is called - from the row's own `apply`; a refusal (§3.1) rejects the call rather than returning an - envelope, so it fails that `apply` as every owner's `register` does. -- `update` is CAS: it fails with `conflict` unless `expectedRevision` is the current revision. -- `update` is an owner write. It fails with `user_only_field` when the stored document and the new - one differ at any `userOnly` pointer (a value changed, added or removed). The comparison uses - the documents after defaults. -- `projects` is what an owner reads first. Afterwards it follows `settings/projects` (§4.4). -- Cancellation: the caller drops the call. A write that has already committed stays committed, - as in S8a. -- Errors of `read`, `update` and `projects` (§6): `unknown_source`, `invalid_scope`, - `invalid_document`, `user_only_field`, `conflict`, `unsynced`, `failed`, `closed`, `cancelled`. - -Only `register` uses the caller's identity, to withdraw the registration with the calling row. -Ownership comes from the registering row: each source has one owner, and only that package is -written against it. This is the trust model of in-process plugins -(AGENTS.md rule 11): dependency declarations are not a sandbox. +Superseded by [Settings](../plugins/Settings.md): one service on the `Settings` type, one source id per registration, a value read, a change callback, the user draft path and the agent path. §4.4 stays in force. ### 4.3 Management methods `settings.*` (client path) -Namespace `settings`, which `SettingsMethods`, a process part that depends on Settings, registers -with `managementMethods` (§4.5). They are never served to paired devices (overview §6.2 rule 9). - -| Method | Request | Reply | Errors | -| --- | --- | --- | --- | -| `settings.read` | `{source, scope}` | `{revision, document}` | invalid params (bad scope), `settings_unknown_source`, `settings_failed` | -| `settings.update` | `{source, scope, expectedRevision, document}` | `{revision, document}` | invalid params (bad scope, schema violation), `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed` | -| `settings.sources` | `{}` | `{dialect, sources: [...]}` (`Sources`, §4.1) | invalid params | -| `settings.projects` | `{}` | `{projects: [{root, cwd}]}`: the authorized project roots now, as the service's `projects` answers them (§4.2) | invalid params | - -- Only registered declared sources are served. A Rust source (for example `mcp`) is - `settings_unknown_source`. - Its owner's methods stay the way to change it. -- A client write may change user-only fields. There is no other difference from the owner path. -- `closed` maps to the existing retryable reloading error. -- `settings.sources` lists every registered declared source in source-name order, and never a - Rust source; an empty registry is an empty `sources` array, not an error. An item is the - declaration without its file names or its owner (§4.1). The `schema` member round-trips what - the owner registered, and the schema's own `title`/`description` annotations are the display - metadata, if the owner added them. -- A client reads the declarations here, through a public method, rather than from a plugin - package or manifest (§9, §4 rule 7: public interfaces only). The agent-side counterpart stays - the `plugin` tool's `config` command, which additionally returns the user document with - `writeOnly` members redacted and listed in `writeOnlySet` (PluginManager §6). -- `schedule` is not a declared source. `ScheduleDocument` is a Rust `BusinessDocument`, - registered with `settings.register::`, validated by its own `validate()`, - served by `schedule.*`, and `settings_unknown_source` on every `settings.*` path. A Rust - source keeps its own typed methods and is out of a schema-driven surface; `settings.sources` - lists declared sources only and therefore never lists it. -- `settings.sources` is never served to paired devices (§4.3 opening) and is absent from the - Web entry's allowlist, so the Web entry answers `unknown_method` (§11 items 7–8): discovery - is local-only like the rest of the namespace. -- `settings.projects` is the read a client needs before it can pass `{project: root}`: it - answers the same `{projects: [{root, cwd}]}` as the owner-facing `projects` service (§4.2), - in cwd order, and the same Web-entry and paired-device rule applies (absent from the - allowlist, so `unknown_method`). **`root` is a process-local number** (§4.1): it holds for the - life of the daemon process, is not a durable identity, and a client re-reads - `settings.projects` after it reconnects to a restarted daemon rather than storing a root. The - list only grows while the process runs — authorizing the same cwd again adds no item and - emits nothing (§4.4) — so no event or push carries it; the client reads it when it opens a - project-scoped form. A `{project: root}` this process has not authorized is invalid params, - the same answer as for a source without project scope. +Superseded by [SettingsMethods](../plugins/SettingsMethods.md): `settings.read` and `settings.update` serve declared sources only, keep their request and reply shapes, and admit a write that survives a dropped client wait. `settings.sources` and `settings.projects` are deleted; the Web entry is served for its allowlisted sources. ### 4.4 Events @@ -312,161 +242,15 @@ Permission does). ### 4.5 Rust binding -The `Settings` binding exposes the owner operations of the public `settings` data face. -It provides `register(ctx, declaration)`, `read(source, scope, cancel)`, -`update(source, scope, expected, document, cancel)` and `projects()`. -The dispatcher calls these same operations, and native consumers call them directly -without JSON conversion. Registration retains the caller's lifetime; updates are owner -writes and preserve user-only fields. The existing Settings owner still supplies the -source registry, validation and persistence. - -`SettingsService` retains the native `BusinessDocument` and client management paths below. -PluginManager's declared-source tools also use it for reads and owner writes. -This binding does not make native sources visible through declared-source operations or -change the local-client boundary in §4.3 and §7. - -In `dim-app-server::settings` (S8a types, changed only where noted): - -```rust -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum SettingsScope { User, Project(usize) } // + Serialize/Deserialize - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SettingsChanged { pub source: String, // was &'static str - pub scope: SettingsScope, pub revision: String } - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ProjectAuthorized { pub root: usize, pub cwd: PathBuf } // + Serialize/Deserialize - -/// A declaration (§3.1), as `register` receives it. -pub struct SourceDeclaration { pub source: String, pub user_file: String, - pub project_file: Option, pub schema: serde_json::Value, - pub user_only: Vec } - -pub enum Writer { Owner, Client } - -impl SettingsService { - /// Registers `D` (or a declaration) until the plugin owning `ctx` unloads. - pub fn register(&self, ctx: &Ctx) -> rutis::Result<()>; - pub fn register_declared(&self, ctx: &Ctx, declaration: SourceDeclaration) -> rutis::Result<()>; - pub fn declarations(&self) -> Vec; - pub async fn read_declared(&self, source: &str, scope: SettingsScope, - cancel: &CancellationToken) -> Result>; - pub async fn update_declared(self: &Arc, source: &str, scope: SettingsScope, - expected: &str, document: Value, writer: Writer, - cancel: &CancellationToken) -> Result>; -} -``` +Superseded by the binding appendix of [Settings](../plugins/Settings.md). §4.4 events, §7 security, §8.1 and §9 stay in force. -- `declarations()` is the registry-wide listing behind `settings.sources` (§4.3): every - registered declared source in name order, never a Rust source. Unlike `declared_by`, it does - not filter to one registering fiber. -- Both registrations are effects of the plugin owning `ctx`, withdrawn when it unloads, and are - checked under one registry state (§3.1). `register_declared` compiles the schema with - `jsonschema`. The process owners register in their `apply`: Mcp (`mcp`, `mcp-projects`, `mcp-plugins`), - SkillsCatalog (`skills`), PermissionRules (`permission`), CollaborationModelPolicy - (`collaboration`) and the App Server's ExecutionSettings (`execution`). Readers in other plugins - only read; `read::`/`update::` of a type that is not the registered one for its name is - `UnknownSource`. The `settings` service's `register` calls `register_declared` with the calling - row's context. -- `execution` is user scope only: it declares no project file, so a project-scope read or write is - refused. It holds two booleans, `sandbox` and `network`, both defaulting to `false`, and its - revisions are the ordinary CAS ones. The TUI's `Process isolation` control and any local management client use - `settings.read`/`settings.update`; the owner's reader reaches the document through the - `ExecutionSettingsHost` port, which is an in-process read contract and not a management method - ([ADR 011](../../adr/011-execution-settings.md) D1). The visible choices map to these existing - booleans as defined by [process isolation](../host-platform-isolation.md#process-isolation); - Permission presets and tool lists do not write this source. -- The file and native paths are shared with `BusinessDocument`, keyed by source name instead of - `D::NAMESPACE`. CAS, the gate, leases, the unsynced case and `publish` stay as they are. -- `SettingsError` gains `UnknownSource`, `UserOnlyField(pointer)`, `InvalidScope`, - `Document(message)` and `DocumentShape { reason, position }`. A written document that - breaks the schema or is not an object is `Document` with the validator's message (the - instance path, never the value). `DocumentShape` is how `McpSettings` refuses an MCP - document as a whole — not an object, no `mcpServers` object, `mcpServers` not an object, - an empty server entry id, a file that is not JSON: the owner's static `reason`, which a - client may see, and `position` when the document was read from bytes. Its `Display` is - byte for byte what `Document` printed for the same text. No other owner has adopted it: - HooksSettings refuses a hook document as `Invalid("invalid hook document")`, and a - persisted file that the default `BusinessDocument` decode or a declared source cannot - parse is `Invalid("invalid settings document")`. `reason()` reports the static message of `Invalid` and of `DocumentShape`, and - `None` for every other variant, `Document` included, whose text is arbitrary. The - client path maps `Document` and `DocumentShape` to invalid params. A persisted document - that breaks the schema stays `Invalid` (`invalid_document` / `settings_failed`). -- The `settings` service is a `HostDispatch` under `host_key("settings")`, and assembly registers - `settings` in the `ServiceCatalog`, as `pluginFiles` is done today. Replies use - the envelope of `sessions`: `{ok: true, value}` or `{ok: false, error: {code, message}}`. -- The `ManagementMethods` for `settings` come from `SettingsMethods`, a process part that depends - on Settings (module `settings_methods`), the way PermissionRules owns `permission`. Settings - itself cannot own a namespace: Rpc reaches Settings through Agents, Rpc may not reach a - management owner (methods contract §3.2), and the module boundary keeps Settings persistence - infrastructure (ADR 004 D4, `xtask check`). Assembly lists the `SettingsMethods` row as the - owner of `settings`. ## 5. Flows -### 5.1 Owner reads and updates - -``` - TS owner settings (HostDispatch) SettingsService storage - | read {web, "user"} ---->| decode request | | - | | read_declared ---------->| file / user/web row ---->| - | | | defaults, schema check | - |<-- {revision r1, document} -------------------------| | - | update {web, "user", r1, doc'} ->| update_declared(Owner) | - | | | defaults, schema | - | | | user-only diff vs current| - | | | differs: user_only_field - | | | CAS r1 ------------------>| replace - | | | emit settings.changed {web, "user", r2} - |<-- {revision r2, document} -------------------------| | -``` - -The user-only diff is checked under the same lease (or native transaction) as CAS, against the -document it replaces. - -### 5.2 Client edits a user-only field - -``` - Client Rpc Settings (managementMethods) - | settings.read {web, "user"} ---->| {r2, doc} - | settings.update {web, "user", r2, doc with searchService} -> update_declared(Client) - |<-- {r3, doc} | emit settings.changed {web, "user", r3} - TS owner (its tool asks to change searchService) - | update {web, "user", r3, doc with another searchService} -> user_only_field, nothing written -``` - -### 5.3 Registration - -``` - owner row apply settings (HostDispatch) SettingsService - | register(declaration) ------->| caller = calling row | - | | register_declared -------->| parse (unknown fields rejected) - | | | check name, files, pointers - | | | compile schema; {} with defaults valid - | | | name or file registered? refuse - | | | record; withdrawal = caller's unload - |<-- resolved (or rejected: the row's apply fails) ----------| - owner row unloads -> its sources are withdrawn; their documents stay in the home -``` - -Settings is built whenever there is a product or target home, as before; a plugin that registers -a source needs it. +Superseded by the Flows and Exceptions sections of [Settings](../plugins/Settings.md). The persistence profiles' behavior in §3 stays in force. ## 6. Errors -| Code (service / wire) | When | Retry | -| --- | --- | --- | -| `unknown_source` / `settings_unknown_source` | No source of that name is registered, or (on these paths) it is a Rust source | After its owner registers it | -| `invalid_scope` / invalid params | Project scope for a source without `projectFile`, or a root not authorized | After authorizing the project | -| `invalid_document` / invalid params | Schema violation or a non-object document | No; nothing written | -| `invalid_document` / `settings_failed` | The persisted file or row is invalid (on read) | After the user repairs it | -| `user_only_field` | An owner write changes a user-only field | No; the user changes it through the client | -| `conflict` / `settings_conflict` | Stale `expectedRevision` | Read and retry | -| `unsynced` / `settings_unsynced` | The new content is in place and announced, but could not be synced | Read before retrying | -| `failed` / `settings_failed` | Storage, persistence or worker failure | Read before retrying | -| `closed` / reloading | Settings is unloading | Yes | -| `cancelled` | Call dropped or cancelled | Caller's choice | +Superseded by the Errors table of [Settings](../plugins/Settings.md): `user_only`, `invalid`, `failed` and the other kinds are defined there, with what the caller does next. ## 7. Security @@ -525,7 +309,7 @@ F2 left open whether to fold its methods into `settings.read/update`. They stay: | §4 rule 4 (core has no business meaning) | Settings validates against declared schemas and names no owner | | §4 rule 5 (batches) | No Timeline writes | | §4 rule 6 (context) | Nothing enters model context. A tool's view of settings is its owner's business | -| §4 rule 7 (public interfaces only) | Owners use the `settings` service; clients use management methods, and read the declarations through `settings.sources`, never from a plugin package | +| §4 rule 7 (public interfaces only) | Owners use the `settings` service; clients use management methods for the declared sources they know by name, never a plugin package | | §4 rule 8 (infrastructure unchanged) | No change to Timeline, Dispatcher, event envelope, rutis, loader, Agent assembly or Session facade. Existing `HostDispatch`, `ServiceCatalog`, `managementMethods` and rutis events are used as they are | | §4 rule 9 (only needed facts in Timeline) | No event is added; settings are not Timeline facts | | ADR 002 D1 (scope) | Settings is a process plugin; the sources outlive Sessions | @@ -547,50 +331,17 @@ question 2); that is no new requirement on dim runtime or rutis. plugin itself (§3.1), so installing, replacing or removing a plugin does not reload Settings. 4. ~~**Which plugin provides `credentials` in the product.**~~ Withdrawn with the service: each owner handles its own secrets (§1.2). -5. ~~**Source discovery for a settings UI.**~~ Settled 2026-11-05: discovery is - `settings.sources` (§4.3), a management method served to local connections only that lists - each declared source, its schema and its scopes, never a document. The question was whether - a generic `/settings` page would need the declared sources and their schemas (for example a - `settings.sources` method); nothing required it for S8b, so it stayed with the CLI settings - design until now. +5. ~~**Source discovery for a settings UI.**~~ Settled 2026-11-05, then superseded by + [#2017](https://github.com/arcships/dim/issues/2017): `settings.sources` is deleted. A client + reads the declared sources it knows by name; an out-of-repo page that needs the list would + have to be given it again through its owner's namespace. 6. **User-only fields for Rust sources.** No Rust owner writes its source on behalf of a tool today. If one does (Scheduler, Workflow), it needs a user-only declaration on its `BusinessDocument`. That is decided with that owner's design. ## 11. Acceptance (flow tests) -App Server flow tests (`crates/dim-app-server/tests/settings_flow.rs` and a TypeScript row loaded -through C4's path): - -1. A TypeScript test package registers source `example` (user file, project file, schema with a - `default`, one user-only pointer). Its first `read` returns the default document with revision - `missing`. An `update` with that revision stores the document and returns a new revision. A - stale revision fails with `conflict`. A schema violation fails and writes nothing. -2. A client `settings.update` changes the user-only field. The owner's next `update` that changes - it fails with `user_only_field`; one that keeps it succeeds. -3. A Rust listener on `settings_changes("example")` receives `{source, scope, revision}` after - each successful write on both paths, and none after a rejected one. The payload serializes to - the §4.4 JSON shape. -4. Native profile: the user scope persists in row `user/example`; existing v13 rows are unchanged. - Project scope on an unauthorized root fails with `invalid_scope`. -5. `settings.read` of `mcp` returns `settings_unknown_source`. A row registering `mcp`, a second - registration of one source, or a malformed declaration fails the registering row. A source - appears when its owner registers it and is `unknown_source` once the owner unloads, while its - document stays in the home. -6. ~~Credential references through a shared `credentials` store.~~ Withdrawn (§1.2). -7. A paired-device connection is not served `settings.read` or `settings.sources`. -8. An authenticated Web entry connection is answered `unknown_method` for `settings.sources` - and is served the allowlisted `settings.read` for `model-log`. -9. `settings.sources` replies `{dialect, sources: []}` when nothing is registered, lists a - registered declared source with its schema verbatim, its scopes, its user-only pointers and - its `writeOnly` hint, never lists a Rust source, and drops a declared source's entry the - moment its owner unloads, when `settings.read` answers `settings_unknown_source` again. -10. `settings.projects` replies `{projects: []}` before anything is authorized, then lists the - root `session.create` authorized with its canonical cwd, and that root serves - `settings.read` with `{project: root}`; a second authorization of the same cwd adds no item, - a root this process never authorized is invalid params, and a root a client authorized - through `hooks.catalog` for a cwd with no Session is listed too. The list starts empty again - after a daemon restart on the same home. +Superseded by the delivery's flow tests on [#2017](https://github.com/arcships/dim/issues/2017): the owner read/change path, the user draft path, the agent path, the project table and the declared registry are tested there instead of against the deleted `settings.sources`/`settings.projects` methods. ## 12. Implementation status diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5b2be8c345..cf8ea4b569 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -131,21 +131,4 @@ serves declared sources and excludes the native `mcp-secrets` document. ## Settings -| 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. | -| 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. | -| 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`. | -| Native non-secret sources with custom decoding → Settings | `settings.registerDocument({source,userFile,projectFile?},codec) → {read,update}`. The source-bound operations are `read(scope) → {revision,document}` and `update(scope,expectedRevision,document) → {revision,document}`. Registration ends on owner unload. | - -The source codec has two operations. `decode(bytes or null) → document` uses the source's -existing decoder for stored bytes, its default for absence, and validates the result. -`validate(document) → void` applies BusinessDocument write validation before admitting a -replacement. Settings performs serialization, version checks and persistence. Both calls -propagate the original Settings error and end with the registration generation. Foreign codec -calls occur outside SQLite transactions. Declared-schema sources reuse their existing codec. +The Settings operations, the authorized-project table and each source's own contract are defined by [Settings](../plugins/Settings.md) and [SettingsMethods](../plugins/SettingsMethods.md). The `settingsService` owner API and the `registerDocument` operation are replaced by the one `settings` service: a source id per registration, a value read, a change callback, the user draft path and the agent path. diff --git a/docs/design/overview.md b/docs/design/overview.md index 1ab2c8d9e4..004c640120 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -100,7 +100,7 @@ Plugins never add wiring plugins (ADR 002 D2). Each need maps to a mechanism tha | Put content into the model context | Branch input (raw blocks, keyed blocks) or tool results ([session access](contracts/session-access.md#a2-source-input-conventions)) | Goal, Hooks, ShellInput, Scheduler, Workflow | | Act on a write before it is committed | A synchronous Timeline before callback registered by a branch-scoped plugin ([single-tree](../architecture/rust-agent/single-tree.md)): it transforms the draft inside the commit lock, never blocks the write and never waits for external work; the original draft commits on failure ([principles §4 rule 3](../architecture/rust-agent/principles.md)) | None planned | | Client method about a Session | A namespace registered with the Session's `sessionMethods`, which Rpc dispatches through the Session ([A.1](contracts/session-boundary.md#a1-method-contributions)) | Questions, Goal, SessionTitle, Attachments, ShellInput, InputQueue (`session.input.withdraw`) | -| Host management method | A namespace a process plugin registers with `managementMethods`, looked up by Rpc per call | Existing management methods, Settings (business configuration, `settings.read`/`settings.update`/`settings.sources`/`settings.projects`, S8b, implemented), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RemoteGateway | +| Host management method | A namespace a process plugin registers with `managementMethods`, looked up by Rpc per call | Existing management methods, Settings (business configuration, `settings.read`/`settings.update`, S8b, implemented; the two methods serve declared sources), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RemoteGateway | | Reach other Sessions | Agents' `sessions` service (`launch`, `input`, `history`, `idle`, ...), as Collaboration does ([session access](contracts/session-access.md#a1-the-sessions-service)) | Scheduler, Workflow | | Hand an event to the Sessions that subscribed to it | The process service `eventHub`, which delivers each event through Agents' `sessions` service ([EventHub](plugins/EventHub.md)) | Producers: IM, SaaS and CI notifications, timers, other agents; a Session's `events` tool and clients' `eventhub.*` methods subscribe | @@ -331,7 +331,7 @@ The table in [§3](#3-integration-by-existing-mechanisms) is exhaustive. A new p 6. **Interrupt**: a plugin cancels in-flight work and releases resources before writing terminal facts ([interrupt](../architecture/rust-agent/interrupt.md)). 7. **Admission**: new tools declare a risk category. No new Permission category is added: a risk Permission does not know is unclassified, which ReadOnly denies, WorkspaceWrite asks about and FullAccess allows (`permission.rs`); a tool may still declare a descriptive risk such as `persistent_configuration`. Sessions started by automation use the starter's policy as an upper bound, which Scheduler jobs and Workflow definitions may narrow. Runs started by a management method default to read-only unless declared, capped by host configuration. `workflow` uses the `agent` tool's risk category. 8. **Dependency direction and reload cost**: core parts never depend on optional plugins; an optional plugin's reload or failure affects only its own features (D3). A reload that reaches its real dependents may fail their in-flight turns; this is accepted and documented in each plugin's conflict table, never prevented. -9. **Management plane**: management methods (`account.*`, `provider.*`, `mcp.*`, `skills.*`, `settings.read`/`settings.update`/`settings.sources`/`settings.projects`, and the methods of new process plugins) are registered by process plugins with `managementMethods`; a rutis session's far end reaches that service too ([rutis 0.19 upgrade M8](rutis-0.19-upgrade.md#m8-the-ui-leaf-is-a-plugin-whose-life-is-a-session)). Session methods have no level; `shell.*` is an ordinary Session method. Local RPC serves both kinds, RemoteGateway serves Session methods only, and a rutis session's far end reaches them through the exported `managementMethods` service (trusted local code). There are no identity tiers. `hello`, `daemon.*`, `agent.*` and the existing `session.*` methods stay Rpc built-ins; `daemon.shutdown` is a built-in never served to a paired device (a connection with a `deviceId`). +9. **Management plane**: management methods (`account.*`, `provider.*`, `mcp.*`, `skills.*`, `settings.read`/`settings.update`, and the methods of new process plugins) are registered by process plugins with `managementMethods`; a rutis session's far end reaches that service too ([rutis 0.19 upgrade M8](rutis-0.19-upgrade.md#m8-the-ui-leaf-is-a-plugin-whose-life-is-a-session)). Session methods have no level; `shell.*` is an ordinary Session method. Local RPC serves both kinds, RemoteGateway serves Session methods only, and a rutis session's far end reaches them through the exported `managementMethods` service (trusted local code). There are no identity tiers. `hello`, `daemon.*`, `agent.*` and the existing `session.*` methods stay Rpc built-ins; `daemon.shutdown` is a built-in never served to a paired device (a connection with a `deviceId`). 10. **Remote Session methods**: paired devices may call every Session method, including `session.permission.update` and `shell.*` (compatibility change, [methods A.4](contracts/session-boundary.md#a4-migration-and-compatibility)). 11. **In-flight work**: there is no shared registry. Each owner provides its own query and stop, and the CLI aggregates them. 12. **Withdrawal**: InputQueue owns the withdrawal and conditional queued-input Steer contract ([Session access A.4](contracts/session-access.md#a4-withdrawal)). Every pending-input derivation excludes deleted inputs, which never enter model context (their keyed blocks never take effect). @@ -506,7 +506,7 @@ A **supplement** adds services, methods or configuration. A **change** alters ex | Agents | Supplement | The `sessions` service ([sessions service](appserver/sessions-service.md)); `SessionConfig.interactive`; `launch` with a policy capped by the starter, `LaunchRequest.agent` optional (absent: Agents' default profile; request `model` over the profile's model); creation from another Session's cut ([deletion and fork](appserver/session-deletion-and-fork.md#6-fork)); `session.agent.update` and `session.agent.get` through Agents' Session entry, resolving an exact profile ID for prompt/model adoption and reading back the profile a branch adopted | Scheduler, Workflow, fork, `/agent` | | Collaboration | Change | Member model: the user's [subagent model policy](subagent-model-policy.md) (`agent`: the profile's model, else the default selection; `inherit`; `fixed`); [member permission inheritance and tool-approval routing](subagent-tool-approval.md): new native members sample the requesting branch's current policy; pending member approvals reach that branch as adopted inputs, with leader decision tools under its Approval and Permission and [user review of the original action](cli-commands.md#subagent-tool-approval) (#29, #257); member providers by kind (`collaborationMembers:`, looked up per call) for members that are not dim Sessions, whose asks use the same member-approval route; the `agent` tool keeps its existing risk classification ([ExternalAgent §9.2](plugins/ExternalAgent.md#92-collaboration-member-providers)) | ExternalAgent | | SessionStore | Supplement | Title metadata with revision checks, written only through `setTitle`, with a Session broadcast notice on change (owners of process-level state emit such notices) (S5b, implemented: the `sessionMetadata` service, [title metadata](appserver/session-title-metadata.md)); deletion and cleanup; fork (copies facts before the cut) (S5c, implemented: [deletion and fork](appserver/session-deletion-and-fork.md)); Session files on the resource node, shared on fork and deleted with the last owner (S5a, implemented: the `sessionFiles` service, [session files](appserver/session-files.md)); `session_grants` rows, removed with the Session and never copied to a fork ([ADR 012](../adr/012-session-grants.md)) | SessionTitle, Attachments, fork, SessionGrants | -| Settings | Supplement | S8a (Rust, implemented): one or more named business sources per owner, each holding one document type; no subscription API of its own: a committed write emits the rutis event `settings.changed` `{source, scope, revision}` on `settings/`, for user and project scope, without the body, and a newly authorized project emits `settings.project_authorized`; validation and defaults only at the Settings boundary; additive `user/` rows under the v13 `settings_documents` contract (D4). S8b (with C4, implemented): the language-neutral `settings` service with JSON Schema, defaults, allowed scopes and user-only fields declared on C4 rows; management methods `settings.read`/`settings.update`/`settings.sources`/`settings.projects`; no credential service (§6.4) | Every plugin with business configuration, including user-written Scheduler jobs (source `schedule`) and Workflow definitions (source `workflow`) | +| Settings | Supplement | S8a (Rust, implemented): one or more named business sources per owner, each holding one document type; no subscription API of its own: a committed write emits the rutis event `settings.changed` `{source, scope, revision}` on `settings/`, for user and project scope, without the body, and a newly authorized project emits `settings.project_authorized`; validation and defaults only at the Settings boundary; additive `user/` rows under the v13 `settings_documents` contract (D4). S8b (with C4, implemented): the language-neutral `settings` service with JSON Schema, defaults, allowed scopes and user-only fields declared on C4 rows; management methods `settings.read`/`settings.update` for declared sources; no credential service (§6.4). The target contract is [Settings](plugins/Settings.md) | Every plugin with business configuration, including user-written Scheduler jobs (source `schedule`) and Workflow definitions (source `workflow`) | | Provider | Supplement | Validation and mapping of advertised effort/tier preferences against the captured adopted model configuration; `AuxiliaryModel` service: `complete(model, request)`, one non-streaming call outside any Session, with the model passed by the caller from its own configuration ([design](appserver/auxiliary-model.md)); proposed [Desktop/CLI management supplement](appserver/provider-management.md) for safe connection edits, model lifecycle and client-only preferences; non-conversational connections per Modality category | `/effort`, `/fast`, SessionTitle, Modality | | `pluginFiles` (`PluginFilesPlugin`) | Supplement | Binary read and write and a format version ([trusted plugin storage](../../crates/dim-app-server/README.md#trusted-plugin-storage)); code location unchanged | Scheduler, Workflow, Modality, RemoteGateway, PluginManager, ExternalAgent | | Mcp, Provider, SkillsCatalog, ManagedProviders, OAuth plugins | Change | Register their existing management namespaces with `managementMethods` (wire-compatible); Mcp's `mcp.approve`/`mcp.revoke` are removed, servers run when enabled, and project entries start disabled until the user's local configuration enables them (§6.4 Approval scope) | Rpc migration | diff --git a/docs/design/plugins/AgentSettings.md b/docs/design/plugins/AgentSettings.md index 6620a64f97..8ab7bbb785 100644 --- a/docs/design/plugins/AgentSettings.md +++ b/docs/design/plugins/AgentSettings.md @@ -117,7 +117,7 @@ writable - The tool is registered with the existing `toolRegistry` and `ToolContribution`; it is admitted and executed like every tool. - The read handler calls the setting module's read port. A future write path adds a typed setter and separates the write risk. -Service faces follow the [owner catalog](../../architecture/rust-agent/generated/catalog.md#services): v1 consumes the process `executionSettingsHost` data face with asynchronous `read({})`, and the Session `toolRegistry` data face. The tool's input and result are data; its Rust part is not leaf-ready. +Service faces follow the [owner catalog](../../architecture/rust-agent/generated/catalog.md#services): v1 consumes the process `executionSettings` data face with asynchronous `read({})`, and the Session `toolRegistry` data face. The tool's input and result are data; its Rust part is not leaf-ready. ## 5. Permission diff --git a/docs/design/plugins/CollaborationModelPolicy.md b/docs/design/plugins/CollaborationModelPolicy.md new file mode 100644 index 0000000000..35a553e80d --- /dev/null +++ b/docs/design/plugins/CollaborationModelPolicy.md @@ -0,0 +1,150 @@ +# CollaborationModelPolicy + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Subagent model policy](../subagent-model-policy.md). + +CollaborationModelPolicy owns the `collaboration` document: which model a new Collaboration member runs. Collaboration asks this owner for the policy each time it creates a member. This document is the owner's target contract; it replaces the store read with the policy's own value read. + +## Use and scope: responsibility split + +CollaborationModelPolicy owns: + +- The `collaboration` source: its file, its document type and its validation — a `fixed` policy needs both a provider id and a model id. +- The value `policy`: `agent` (the profile's model, or the existing default), `inherit` (the requesting branch's adopted model) or `fixed {model}`. +- The `collaboration` management namespace: `collaboration.model_policy` and `collaboration.set_model_policy` for a local client. + +Callers keep: + +- What each policy means when a member starts: Collaboration's business, including the startup override that always inherits. +- When the policy is read: at each member creation. +- What an absent policy means: `agent`, as if the user had chosen it. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Collaboration needs the policy for a new member | No: the file, the type and its validation belong to this owner | `policy` | +| Collaboration uses `agent` when nothing is stored | Yes: the read answers the default document | Business | +| A local client reads the policy with a draft base | No: the client reaches this owner's namespace only | `collaboration.model_policy` | +| A local client replaces the policy at a revision | No: a stale draft is reported | `collaboration.set_model_policy` | +| A consumer reacts to a changed policy | Yes: follow the `settings/collaboration` fact and read again | Business | + +## Caller example + +Collaboration reads the policy when it creates a member. + +```rust +let policy = if startup { + ModelPolicy::Inherit +} else { + collaboration_policy.policy(cancelled.clone()).await?.policy +}; +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `collaboration` source and `read`/`change` for its value. +- `managementMethods`: the two client methods. +- Collaboration: the App Server's `Collaboration` calls `policy` directly in-process; it is in the same crate as this owner, so no port type is needed. The policy type stays in this owner's module. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `policy` | The policy in force now | `{}` | `{policy}` | The caller's token; nothing changes | `failed`, `cancelled` | +| `collaboration.model_policy` | The policy with the revision a draft starts from | `{}` | `{revision, policy}` | The call is dropped | `collaboration_model_policy_failed`, `operation_interrupted`, reloading | +| `collaboration.set_model_policy` | Replace the policy at the revision read | `{expectedRevision, policy}` | `{revision}` | The call is dropped | invalid params, `collaboration_model_policy_conflict`, `collaboration_model_policy_failed`, `operation_interrupted`, reloading | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Use the default policy (`agent`) for this member; the member still starts | +| `cancelled` | The member creation is abandoned with the call | +| invalid params | Fix the request: an unknown mode, or a `fixed` policy without a provider and a model | +| `collaboration_model_policy_conflict` | Read again; the user's draft is stale | +| `collaboration_model_policy_failed` | Read again before retrying | +| `operation_interrupted` | The call was cancelled or the owner is unloading; read again before retrying | +| reloading | The daemon is restarting; retry after it is back | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `policy` | Read the source through [Settings](Settings.md), return the policy | The call ends `cancelled` | The call ends `failed`; the member uses the default policy | Settings | +| `collaboration.model_policy`, `collaboration.set_model_policy` | [Settings](Settings.md) `read_user`/`replace_user`, map the reply and the errors | The call is dropped; a write before the commit does not happen | In-flight calls finish or end `reloading` | Settings | + +## Exceptions with reasons + +- The policy document is a Rust type rather than a JSON Schema: the closed mode set with a typed model is the owner's validation, so the client reaches it through this owner's namespace. + +## Supersedes + +- [Subagent model policy](../subagent-model-policy.md)'s row that persists and edits the policy through `SettingsService::read/update`; the `collaboration.*` management methods keep their shapes. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; not a Capability. | +| §2 scopes | Process: the policy applies to every new member of the process. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/collaboration` fact; this owner writes none. | +| §4 rule 6 | The policy never enters model context. | +| §4 rule 7 | Collaboration calls `policy`; the client calls the namespace; no caller names the file or the type. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The policy belongs to this owner; Collaboration asks this owner, not the store. | +| §7 one face | One service value read and one namespace; no second read path. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the type and the validation stay with this owner. | +| §7 one change | The new value read, Collaboration's migration and the store read's deletion are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | Collaboration depends on this owner's value; this owner depends on Settings. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a process part reading a process value. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::ModelId; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "mode", rename_all = "lowercase", deny_unknown_fields)] +pub enum ModelPolicy { + Agent {}, + Inherit {}, + Fixed { model: ModelId }, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Policy { + pub policy: ModelPolicy, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum CollaborationPolicyError { + #[error("{message}")] + Failed { message: String }, + #[error("{message}")] + Cancelled { message: String }, +} + +impl PublicService for CollaborationModelPolicy {} + +#[rutis::service(name = "collaborationPolicy")] +impl CollaborationModelPolicy { + pub async fn policy(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ContextCompaction.md b/docs/design/plugins/ContextCompaction.md index fe2dd23d6a..77fb478d06 100644 --- a/docs/design/plugins/ContextCompaction.md +++ b/docs/design/plugins/ContextCompaction.md @@ -1980,7 +1980,7 @@ otherwise — is pinned by `a_length_sentence_needs_one_target_placeholder` in **The product's user override.** The App Server may supply the operator's summary prompt from its `prompts` setting ([prompt overrides](../appserver/prompt-overrides.md)). The port is -`SummaryPromptSettingsHost`, optional and read while the Session's strategy part applies: the +`SummaryPromptSettings` (the port trait in `dim-agent-capabilities`), optional and read while the Session's strategy part applies: the factory `system_prompt` outranks it, a read failure keeps `SYSTEM`, and the value applies to Sessions loaded after the change. The length sentence and the target rule stay factory-only, so a user override changes the prompt and not the size rule. diff --git a/docs/design/plugins/ExecutionSettings.md b/docs/design/plugins/ExecutionSettings.md new file mode 100644 index 0000000000..38ee2e143f --- /dev/null +++ b/docs/design/plugins/ExecutionSettings.md @@ -0,0 +1,136 @@ +# ExecutionSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Decision: [ADR 011](../../adr/011-execution-settings.md). + +ExecutionSettings owns the `execution` document and the process execution switches it carries. The plugin also registers the `settings` tool ([AgentSettings](AgentSettings.md)) and the execution snapshot branch ([EnvironmentSettings](EnvironmentSettings.md)); those documents own the tool and the snapshot contract. This document is the owner's target contract; it replaces the `executionSettingsHost` name with `executionSettings`. + +## Use and scope: responsibility split + +ExecutionSettings owns: + +- The `execution` source: its file, its schema, and the two switches `sandbox` and `network`, both defaulting to `false` and declared as user-only members. This contract changes their authority: today the source declares no user-only member (`crates/dim-app-server/src/execution_settings.rs`), so an owner or agent write could change the switches; under this contract such a write is `user_only`, and the delivery lists the change. +- The value `{sandbox, network}`: the switches in force now, read at each use. + +Callers keep: + +- When the switches take effect: at process preparation; a running process, including the persistent shell, keeps the boundary it started with. +- What a switch means for a command: the sandbox and network properties of a spawn are HostPlatform's business. +- When to show the value to the model: the snapshot branch and the tool are their own designs. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A process part reads the boundary at process preparation | No: the file, its schema and the user-only rule belong to this owner | `read` | +| The model-facing tool lists and reads the switches | Yes: the tool calls the same read | AgentSettings | +| The branch shows a snapshot on open and on a change | Yes: the branch calls the same read and follows the fact | EnvironmentSettings | +| A user changes the switches | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | + +## Caller example + +HostPlatform reads the switches when it prepares a process. + +```rust +let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| { + HostError::failed(format!("execution settings: {error}")) +})?; +// A missing or unreadable source fails preparation; it never runs unsandboxed. +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `execution` source and `read` for its value. +- The Rust port, for consumers outside the App Server: the trait `ExecutionSettingsRead` and the reply type `Switches` live in `dim-agent-capabilities` ([`execution_settings`](../../../crates/dim-agent-capabilities/src/execution_settings.rs)). HostPlatform and the `settings` tool depend on the trait; the App Server's `ExecutionSettings` implements it and serves the same read on the wire. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `read` | The switches in force now | `{}` | `{sandbox, network}` | The caller's token; nothing changes | `failed` | + +`failed` covers a read that could not produce the document: an unreadable source, a cancelled read, or an absent registration. The reply is the document itself, so no member is invented. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Fail process preparation; never prepare a process without knowing the boundary | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `read` | Read the source through [Settings](Settings.md), return the two switches | The call ends `failed` | The call ends `failed`; the caller fails preparation | Settings | + +## Exceptions with reasons + +- A missing value fails preparation instead of defaulting to unsandboxed: the built-in default is already "off", and silently running unsandboxed is the one failure the feature exists to prevent. + +## Supersedes + +- [ADR 011](../../adr/011-execution-settings.md) D1's type `ExecutionSettingsHost` and its service name `executionSettingsHost`: the decision is unchanged. The type is replaced by the owner type `ExecutionSettings`, which implements the port trait `ExecutionSettingsRead`; the wire service is `executionSettings`. +- [Service faces](../service-faces.md) §3.2's and §4.10's `executionSettingsHost` entries. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | The process part owns the document. The snapshot branch writes one input at branch open and on a change, so that part is a Capability ([EnvironmentSettings](EnvironmentSettings.md)); the tool part is a Session tool registration, not a Capability. | +| §2 scopes | The document and the value are process state; the branch part reads the value and appends an input to its branch. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | The snapshot is an input message, not a command event. | +| §4 rule 6 | The value reaches the model as an appended input; no Prompt source and no second context path. | +| §4 rule 7 | HostPlatform calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The switches belong to this owner; consumers ask this owner. | +| §7 one face | One service with one read; the `executionSettingsHost` name is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | Nothing of the source, its file or the user-only rule reaches the caller. | +| §7 one change | The name change and its callers migrate in the same change. | +| ADR 002 D1 | Process scope: the switch applies to the process, not a Session. | +| ADR 002 D3 | HostPlatform depends on the port; the port has no Settings or file dependency. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumers are process or Session parts reading a process value. | + +## Requirements raised to mechanism owners + +None new. HostPlatform's read at process preparation is unchanged in shape; only the service name changes. + +## Binding appendix + +```rust +use dim_agent_capabilities::host::{CancelledFn, HostFuture}; +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Switches { + pub sandbox: bool, + pub network: bool, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ExecutionSettingsError { + #[error("{message}")] + Failed { message: String }, +} + +// The Rust port, in dim-agent-capabilities; the App Server's ExecutionSettings implements it. +pub trait ExecutionSettingsRead: Send + Sync + 'static { + fn read(&self, cancelled: CancelledFn) -> HostFuture<'_, Result>; +} + +impl PublicService for ExecutionSettings {} + +#[rutis::service(name = "executionSettings")] +impl ExecutionSettings { + pub async fn read(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ModelLog.md b/docs/design/plugins/ModelLog.md new file mode 100644 index 0000000000..104c719b32 --- /dev/null +++ b/docs/design/plugins/ModelLog.md @@ -0,0 +1,130 @@ +# ModelLog + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Model request log](../appserver/model-log.md). + +ModelLog owns the `model-log` document: whether the process records its model wire exchanges. The recorder itself is aimux's and writes the JSONL file under the home root. This document is the owner's target contract; it replaces the push into the recorder with a value read. + +## Use and scope: responsibility split + +ModelLog owns: + +- The `model-log` source: its file, its schema and the `enabled` switch, defaulting to `false`. +- The value `recording`: the directory the recorder writes to when the switch is on, or none when off. + +Callers keep: + +- The recording format, the file name and the write path: aimux's recorder. +- When the value is read: at each request, or after following the `settings/model-log` fact. +- Failing or not failing a request on a read error: a read error records nothing. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The request recorder needs its destination | No: the file and the switch belong to this owner | `recording` | +| The recorder is off when unset | Yes: the read answers none | Business | +| A user turns recording on or off | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | + +## Caller example + +The recorder reads the destination while it starts a request. + +```rust +let directory = model_log + .recording() + .await + .ok() + .and_then(|view| view.directory); +if let Some(directory) = directory { + // aimux owns the file under this directory; it is `/model-log`. +} +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `model-log` source and `read` for its value. +- The Rust port, for the consumer outside the App Server: the trait `RecordingDestination` lives in `dim-agent-aimux` where the recorder is, and the App Server's `ModelLog` implements it and serves the same read on the wire. +- [FileStorage](https://github.com/arcships/dim/pull/2080) at its head `7224c0cd4`: `root_path` for the home root. The assembly provides the home root id as a host value, and the recorder's destination is `/model-log`. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `recording` | Where the request recorder writes now | `{}` | `{directory}` or none | The caller's token; nothing changes | `failed` | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Record nothing for this request; the model request itself proceeds | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `recording` | Read the source through [Settings](Settings.md), answer the directory or none | Nothing changes; the caller records nothing | The call ends `failed`; the caller records nothing | Settings | + +## Exceptions with reasons + +- The directory is computed from the home root at each read instead of being pushed into the recorder: the recorder belongs to aimux, and a value read keeps the write inside its owner. + +## Supersedes + +- [Model request log](../appserver/model-log.md)'s sentence that ModelLog starts and stops the recorder by pushing a directory into it. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; not a Capability. | +| §2 scopes | Process: the switch applies to the whole process. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers and the home root FileStorage answers. | +| §4 rule 1 | Settings publishes the `settings/model-log` fact; this owner writes none. | +| §4 rule 6 | The switch never enters model context. | +| §4 rule 7 | The recorder calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | The reply is a value; no path crosses as a resource. | +| §7 no proxy | The switch and the destination belong to this owner. | +| §7 one face | One service with one read; the old push into the process recorder is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the switch and the home root stay with their owners. | +| §7 one change | The new read, aimux's migration and the deletion of the setter are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | The recorder depends on the value; ModelLog depends on Settings and FileStorage. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a process part reading a process value. | + +## Requirements raised to mechanism owners + +- **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** aimux's request recorder reads this value instead of receiving a process-global destination; a read error records nothing and never fails a request. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Recording { + pub directory: Option, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ModelLogError { + #[error("{message}")] + Failed { message: String }, +} + +impl PublicService for ModelLog {} + +#[rutis::service(name = "modelLog")] +impl ModelLog { + pub async fn recording(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/PermissionRules.md b/docs/design/plugins/PermissionRules.md new file mode 100644 index 0000000000..4677679f8a --- /dev/null +++ b/docs/design/plugins/PermissionRules.md @@ -0,0 +1,161 @@ +# PermissionRules + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Permission command rules](../appserver/permission-command-rules.md). + +PermissionRules owns the `permission` document: the user's command rules. The permission decision that applies the rules is the `CommandRules` capability; this owner answers the rules. This document is the owner's target contract; it replaces the `commandRules` Session service and the Session part that read the rules from the store. `permissionRules.rules` replaces `commandRules.read`: a consumer that read `commandRules` calls `permissionRules.rules` and handles this owner's errors. + +## Use and scope: responsibility split + +PermissionRules owns: + +- The `permission` source: its file, its document type (`command_rules`) and its validation — at least one word per rule, no shell separator. +- The value `rules`: the user's command rules as stored now. +- The `permission` management namespace: `permission.rules` and `permission.set_rules` for a local client. + +Callers keep: + +- The permission decision: whether a command is allowed, asked or denied, and how a rule matches a command. +- When the rules are read: at each decision. +- What a conflict means for the user's edit: the draft is stale; read again. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The permission decision needs the user's rules | No: the document, its type and its validation belong to this owner | `rules` | +| A local client reads the rules with a draft base | No: the client reaches this owner's namespace only | `permission.rules` | +| A local client replaces the rules at a revision | No: the whole list is replaced and a stale draft is reported | `permission.set_rules` | +| A consumer reacts to a changed rule set | Yes: follow the `settings/permission` fact and read again | Business | + +## Caller example + +The permission decision reads the rules once per call. + +```rust +let rules = permission_rules.rules(cancelled.clone()).await?; +let decision = decide(&rules.rules, &command); +``` + +The CLI replaces the list with the revision it read. + +```rust +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct SetRulesRequest<'a> { + expected_revision: &'a str, + command_rules: &'a [CommandRule], +} + +client + .typed( + "permission.set_rules", + serde_json::to_value(SetRulesRequest { + expected_revision: &revision, + command_rules: &rules, + })?, + ) + .await?; +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `permission` source and `read`/`change` for its value. +- `managementMethods`: the two client methods. +- The Rust port, for consumers outside the App Server: the trait `ReadCommandRules` stays in `dim-agent-capabilities` ([`permission`](../../../crates/dim-agent-capabilities/src/permission.rs)); the App Server binds it to this owner's `rules`, not to the store. The command rules' type stays in `dim-agent-types`. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `rules` | The user's command rules as stored now | `{}` | `{rules}` | The caller's token; nothing changes | `failed`, `cancelled` | +| `permission.rules` | The rules with the revision a draft starts from | `{}` | `{revision, commandRules}` | The call is dropped | `permission_rules_failed`, `operation_interrupted`, reloading | +| `permission.set_rules` | Replace the whole list at the revision read | `{expectedRevision, commandRules}` | `{revision}` | The call is dropped | invalid params, `permission_rules_conflict`, `permission_rules_failed`, `operation_interrupted`, reloading | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Deny or ask for the command; a rules read that failed never allows it | +| `cancelled` | The decision is abandoned with the call | +| invalid params | Fix the request: a rule without a command word, or with a shell separator | +| `permission_rules_conflict` | Read again; the user's draft is stale | +| `permission_rules_failed` | Read again before retrying | +| `operation_interrupted` | The call was cancelled or the owner is unloading; read again before retrying | +| reloading | The daemon is restarting; retry after it is back | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `rules` | Read the source through [Settings](Settings.md), return the list | The call ends `cancelled` | The call ends `failed`; the decision denies or asks | Settings | +| `permission.rules`, `permission.set_rules` | [Settings](Settings.md) `read_user`/`replace_user`, map the reply and the errors | The call is dropped; a write before the commit does not happen | In-flight calls finish or end `reloading` | Settings | + +## Exceptions with reasons + +- The rules' validation is Rust code rather than a JSON Schema: a shell separator and an empty command word are expressible only as code, so the source is a Rust document and the client reaches it through this owner's namespace instead of `settings.*`. + +## Supersedes + +- [Permission command rules](../appserver/permission-command-rules.md) §4.1's `commandRules` service; the `permission.*` management methods stay with the same shapes. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document. The `CommandRules` capability owns the decision and folds no rule state: it reads this owner's value. | +| §2 scopes | Process: the rules apply to every Session. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/permission` fact; this owner writes none. | +| §4 rule 6 | The rules never enter model context. | +| §4 rule 7 | The decision calls `rules`; the client calls the namespace; no caller names the file or the type. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The rules belong to this owner; the decision asks this owner, not the store, and the `commandRules` Session service is deleted. | +| §7 one face | One service for the value and one namespace for the client; no second read path. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the type and the validation stay with this owner. | +| §7 one change | The new value read, the decision's migration and the deletion of `commandRules` are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | The decision depends on this owner's value; this owner depends on Settings. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a Session part reading a process value. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::CommandRule; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Rules { + pub rules: Vec, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum PermissionRulesError { + #[error("{message}")] + Failed { message: String }, + #[error("{message}")] + Cancelled { message: String }, +} + +impl PublicService for PermissionRules {} + +#[rutis::service(name = "permissionRules")] +impl PermissionRules { + pub async fn rules(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` + +The client methods are registered with `managementMethods`; their request and reply types are the JSON shapes in the operations table. diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index ce2a57ab21..0cc6b36257 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -312,8 +312,8 @@ PluginManager adds no text of its own to model context beyond the `plugin` tool. | Command | Does | | --- | --- | | `list`, `install …`, `enable …`, `disable `, `reload `, `update `, `remove ` | The `plugin.*` method of the same name, with the CLI's arguments; a relative path is resolved against the Session's working directory. Same result and errors. | - | `config ` | The declared (JSON Schema) Settings sources the plugin that `` uses registered (R4); Rust typed sources, such as Mcp's, are not served here and are not listed: for each, its user document, revision, schema and user-only fields. A member the schema marks `writeOnly` (a secret, [settings-service §1.2](../appserver/settings-service.md#12-decision-secrets-belong-to-their-owner)) is left out of the document and listed in `writeOnlySet` when it holds a value. A plugin that is not running has registered none. Its client-side counterpart is `settings.sources` ([settings-service §4.3](../appserver/settings-service.md#43-management-methods-settings-client-path)), which lists the declarations only. | - | `config set ` | Replaces one top-level member of a source through Settings: reads the user document, sets `` (`.` when the plugin has several sources) to `` (JSON, else a string) and updates with the revision it read. Settings checks the revision and schema; the write is an owner write, so a user-only field is refused, and a member that is or contains a `writeOnly` member is refused too. The owner reads its source when it needs it, so the value takes effect without a restart. Structural row configuration is not edited here. | + | `config ` | The declared (JSON Schema) Settings sources the plugin that `` uses registered (R4); Rust typed sources, such as Mcp's, are not served here and are not listed. For each, [Settings](../plugins/Settings.md) `declared_sources {instance}` gives its id, schema, scopes, user-only pointers and write-only hint, and `agent_read` gives its user document with every `writeOnly` member left out and listed in `writeOnly`. The revision is not part of this path. A plugin that is not running has registered none. Its client-side counterpart is `settings.read` ([SettingsMethods](../plugins/SettingsMethods.md)), which serves declared sources only. | + | `config set ` | Replaces one top-level member of a source through Settings: `agent_set` with `` (`.` when the plugin has several sources) and `` (JSON, else a string). Settings checks the member and the schema; the agent path refuses a user-only or `writeOnly` member. The owner reads its source when it needs it, so the value takes effect without a restart. Structural row configuration is not edited here. | | `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. diff --git a/docs/design/plugins/PromptSettings.md b/docs/design/plugins/PromptSettings.md new file mode 100644 index 0000000000..09bbcd480a --- /dev/null +++ b/docs/design/plugins/PromptSettings.md @@ -0,0 +1,134 @@ +# PromptSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature design: [Prompt overrides](../appserver/prompt-overrides.md). + +PromptSettings owns the `prompts` document and the three model-facing texts it carries: the base identity and rules, the compaction summary prompt, and the Skills instructions. This document is the owner's target contract; it replaces the three `*PromptSettingsHost` services with one service. + +## Use and scope: responsibility split + +PromptSettings owns: + +- The `prompts` source: its file, its schema, and the rule that each of the three texts is non-empty and changed only by the user. +- The three values `base`, `summary` and `skills`: the text in force, or none when the user set no override. + +Callers keep: + +- The precedence: a factory configuration outranks the user's text, which outranks the built-in text. The consumer applies the precedence and keeps the built-in text on a missing value or a failed read. +- When the text is adopted: at the Session part's `apply`, fixed for that Session; a change applies to Sessions loaded after it. +- The text's meaning and how it is composed into the prompt. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A capability reads its own override text before a Session starts | No: the document belongs to this owner, and the consumer must not name another text's member | One read per text on the owner's service | +| A capability falls back when the user set nothing | Yes: the read answers none | Business | +| A user edits a text | Yes: the client edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | +| A capability reacts to a changed text mid-Session | Yes: the value is fixed at `apply`; a changed text applies to the next Session | Business | + +## Caller example + +PromptSources reads the base text once, while its Session part applies. + +```rust +// `prompt_settings` is the BasePromptSettings port; its read answers the text or none. +let base = prompt_settings.base(cancelled.child_token()).await.ok().flatten(); +let text = factory.base.or(base).unwrap_or_else(|| BUILT_IN.into()); +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `prompts` source and `read` for its value. PromptSettings registers the source from its own process row and keeps the source id. +- The Rust port, for consumers outside the App Server: the three traits `BasePromptSettings`, `SkillsInstructionsSettings` and `SummaryPromptSettings` stay in `dim-agent-capabilities` ([`prompt_sources`](../../../crates/dim-agent-capabilities/src/prompt_sources.rs), [`skills`](../../../crates/dim-agent-capabilities/src/skills/mod.rs), [`summary_strategy`](../../../crates/dim-agent-capabilities/src/summary_strategy.rs)), each covering one text. The App Server's `PromptSettings` implements all three and serves the same reads on the wire; a consumer in `dim-agent-capabilities` depends on the trait, never on the App Server. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `base` | The user's replacement of `dim/base`, when set | `{}` | `{text}` or none | The caller's token; nothing changes | `failed` | +| `summary` | The user's replacement of the compaction summary prompt, when set | `{}` | `{text}` or none | The caller's token; nothing changes | `failed` | +| `skills` | The user's replacement of the Skills instructions, when set | `{}` | `{text}` or none | The caller's token; nothing changes | `failed` | + +A read returns the member as stored after the schema check; an absent member is none, never an empty string. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Use the factory configuration or the built-in text; the Session opens. The message names the source, never the text. | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `base`, `summary`, `skills` | Read the source through [Settings](Settings.md), return the member or none | Nothing changes | The call ends `failed`; the consumer keeps its built-in text | Settings | + +## Exceptions with reasons + +- The three texts share one document and one registering row: a file has one owner, while each text belongs to a different capability; the schema keeps each member independent, and a user-only member cannot be changed by the owner. +- A read failure does not fail the Session: the text is policy with a safe default, and the consumer keeps the built-in text. + +## Supersedes + +- [Prompt overrides](../appserver/prompt-overrides.md) §3 and §3.1 (the three ports), §7 (the three-host binding appendix) and §4's `settings.sources` sentence: one `promptSettings` service and `{text}`, with each capability depending on its own port trait. The precedence rules above and the rest of §4 stay in force. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part that owns a document. It publishes facts through Settings and folds no state: not a Capability. | +| §2 scopes | Process: the document is shared by every Session; the values are read at a Session part's `apply`. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/prompts` fact; this owner writes none. | +| §4 rule 6 | The text reaches the model through the existing adopted prompt sources; no context path is added. | +| §4 rule 7 | Consumers call the three reads; no consumer names the other members. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The texts belong to this owner; the consumers ask this owner, not the store. | +| §7 one face | One service with three reads, one per text; the three `*SettingsHost` names are deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | Nothing of the store, the schema or the file name reaches the consumer. | +| §7 one change | The one service replaces the three names, and all three consumers migrate in the same change. | +| ADR 002 D1 | Process scope: the setting is shared configuration, not Session state. | +| ADR 002 D3 | The consumers' crates depend on the port traits, not on the App Server. | +| ADR 027 | Not applicable: the consumers are process or Session parts reading a process value. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None new. The consumers ([PromptSources](../../architecture/rust-agent/plugins/PromptSources.md), Skills and ContextCompaction) call one service name instead of three; each consumer's own contract records the fallback rule. + +## Binding appendix + +The three reads are one service on the owner type; the old `BasePromptSettingsHost`, `SkillsInstructionsSettingsHost` and `SummaryPromptSettingsHost` wrapper types are deleted, while the traits `BasePromptSettings`, `SkillsInstructionsSettings` and `SummaryPromptSettings` stay in `dim-agent-capabilities` and the owner implements them. + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PromptText { + pub text: Option, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum PromptSettingsError { + #[error("{message}")] + Failed { message: String }, +} + +impl PublicService for PromptSettings {} + +#[rutis::service(name = "promptSettings")] +impl PromptSettings { + pub async fn base(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn summary(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn skills(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/PromptSuggestionSettings.md b/docs/design/plugins/PromptSuggestionSettings.md new file mode 100644 index 0000000000..432ac9906b --- /dev/null +++ b/docs/design/plugins/PromptSuggestionSettings.md @@ -0,0 +1,129 @@ +# PromptSuggestionSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [PromptSuggestion](../../architecture/rust-agent/plugins/PromptSuggestion.md). + +PromptSuggestionSettings owns the `prompt-suggestion` document and the value the Session part reads at each decision. This document is the owner's target contract; it replaces the `promptSuggestionSettingsHost` name with `promptSuggestionSettings`. + +## Use and scope: responsibility split + +PromptSuggestionSettings owns: + +- The `prompt-suggestion` source: its file, its schema, the switch `enabled` and the length limit `maxChars` in `[10, 200]`, defaulting to `false` and `80`. +- The value `{enabled, maxChars}` as stored now. + +Callers keep: + +- When the feature offers a suggestion and how the reply is validated. +- That a missing port or a failed read turns the feature off. +- The text the model sees; the limit bounds the reply, not the instruction. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The Session part reads the switch and the limit at each decision | No: the file, the schema and the range belong to this owner | `read` | +| The Session part treats an absent port as "off" | Yes: the read is optional at assembly; a failed read is its own error | Business | +| A user changes the switch or the limit | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | + +## Caller example + +PromptSuggestion reads the value before it decides. + +```rust +let settings = prompt_suggestion_settings.read(token.clone()).await?; +if !settings.enabled { + return Ok(Decision::Refused("disabled")); +} +let max_chars = settings.max_chars; // the owner's schema already bounded it +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `prompt-suggestion` source and `read` for its value. +- The Rust port, for consumers outside the App Server: the trait `PromptSuggestionSettingsRead` and the reply type `SuggestionSettings` live in `dim-agent-capabilities` ([`prompt_suggestion`](../../../crates/dim-agent-capabilities/src/prompt_suggestion.rs)). The PromptSuggestion Session part depends on the trait; the App Server's `PromptSuggestionSettings` implements it and serves the same read on the wire. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `read` | The switch and the limit in force now | `{}` | `{enabled, maxChars}` | The caller's token; nothing changes | `failed` | + +The reply carries both members because the schema gives both a default; a document that misses one is invalid, not a value with a missing field. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Turn the feature off for this decision; the message names the source | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `read` | Read the source through [Settings](Settings.md), return both members | The call ends `failed`; the feature stays off for this decision | The call ends `failed`; the feature stays off | Settings | + +## Exceptions with reasons + +- The assembler may leave the port absent: an evaluation or a host without Settings then keeps the feature off, so the read is optional at assembly. + +## Supersedes + +- [Service faces](../service-faces.md) §3.2's and §4.10's `promptSuggestionSettingsHost` entries. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; the Session part that reads it is a Capability of the PromptSuggestion feature, designed in that plugin's page. | +| §2 scopes | The document and the value are process state; the Session part reads the value. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | No event from this owner. | +| §4 rule 6 | The value reaches the model through the feature's own request; no context path is added. | +| §4 rule 7 | The Session part calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Request and reply are data; no object or path crosses. | +| §7 no proxy | The value belongs to this owner. | +| §7 one face | One service with one read; `promptSuggestionSettingsHost` is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The range and the defaults stay in this owner's schema; the consumer does not clamp or fill them. | +| §7 one change | The name change and its caller migrate in the same change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | The Session part depends on the port type, not on the App Server. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a Session part reading a process value. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SuggestionSettings { + pub enabled: bool, + pub max_chars: u32, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum PromptSuggestionSettingsError { + #[error("{message}")] + Failed { message: String }, +} + +impl PublicService for PromptSuggestionSettings {} + +#[rutis::service(name = "promptSuggestionSettings")] +impl PromptSuggestionSettings { + pub async fn read(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ProviderSettings.md b/docs/design/plugins/ProviderSettings.md new file mode 100644 index 0000000000..dfd529a7ce --- /dev/null +++ b/docs/design/plugins/ProviderSettings.md @@ -0,0 +1,128 @@ +# ProviderSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Provider management](../appserver/provider-management.md) §2. + +ProviderSettings owns the `provider` document: the User-Agent dim puts on its model requests when the operator replaces the built-in one. The document holds no Provider record; a record's own `headers` stay that record's, and a User-Agent there still wins for that Provider alone. This document is the owner's target contract; it replaces the push into the process identity with a value read. + +## Use and scope: responsibility split + +ProviderSettings owns: + +- The `provider` source: its file, its schema, the `userAgent` member and the rule that only the user changes it. +- The value `userAgent`: the operator's replacement, or none when unset. The environment variable `DIM_USER_AGENT` still wins when set. + +Callers keep: + +- Which request carries which User-Agent: Provider's model request, including a record's own `headers`. +- When the value is read: at request time, or after following the `settings/provider` fact. +- Failing or not failing a request on a read error: a read error keeps the built-in User-Agent. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A model request needs the operator's User-Agent | No: the file and the user-only rule belong to this owner | `user_agent` | +| A model request keeps the built-in User-Agent when unset | Yes: the read answers none | Business | +| A user replaces the User-Agent | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | +| The request path learns of a change | Yes: follow the `settings/provider` fact and read again | Business | + +## Caller example + +Provider reads the value when it builds a request. + +```rust +let configured = provider_settings + .user_agent() + .await + .ok() + .and_then(|view| view.user_agent); +let user_agent = configured.unwrap_or_else(|| dim_user_agent()); +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `provider` source and `read` for its value. +- The Rust port, for the consumer outside the App Server: the trait `ProviderUserAgent` lives in `dim-agent-capabilities` where the model request is built, and the App Server's `ProviderSettings` implements it and serves the same read on the wire. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `user_agent` | The operator's User-Agent replacement, when set | `{}` | `{userAgent}` or none | The caller's token; nothing changes | `failed` | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Use the built-in User-Agent; never fail the model request for this setting | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `user_agent` | Read the source through [Settings](Settings.md), return the member or none | Nothing changes; the caller uses the built-in value | The call ends `failed`; the caller uses the built-in value | Settings | + +## Exceptions with reasons + +- The value is read per request instead of being published into the process identity: the identity belongs to Provider, and a value read keeps the write inside its owner. + +## Supersedes + +- [Provider management](../appserver/provider-management.md) §2's sentences that say the Provider part holds the value and pushes it into the model identity. + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; not a Capability. | +| §2 scopes | Process: the value applies to every request of this process. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/provider` fact; this owner writes none. | +| §4 rule 6 | The value never enters model context; it is a request header. | +| §4 rule 7 | Provider calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | The reply is a value; no object or path crosses. | +| §7 no proxy | The value belongs to this owner; Provider asks this owner, not the store. | +| §7 one face | One service with one read; the old registration-and-push shape is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the user-only rule and the fallback ordering stay with their owners; the caller sees a value or none. | +| §7 one change | The new read, Provider's migration and the deletion of the identity push are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | Provider depends on the value; ProviderSettings depends only on Settings. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a process part reading a process value. | + +## Requirements raised to mechanism owners + +- **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** the model request reads this value instead of receiving a pushed process identity; the request keeps its own `headers` precedence and its built-in fallback. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UserAgent { + pub user_agent: Option, +} + +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum ProviderSettingsError { + #[error("{message}")] + Failed { message: String }, +} + +impl PublicService for ProviderSettings {} + +#[rutis::service(name = "providerSettings")] +impl ProviderSettings { + pub async fn user_agent(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..4d3a1e354f 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,15 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [Settings](Settings.md) (owner contract) | sources, documents, revisions, change application, authorized projects and the change facts behind `settings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [SettingsMethods](SettingsMethods.md) (owner contract) | the local client's `settings.*` methods | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [PromptSettings](PromptSettings.md) (owner contract) | the `prompts` source and the base, summary and Skills texts behind `promptSettings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [ExecutionSettings](ExecutionSettings.md) (owner contract) | the `execution` source and its switches behind `executionSettings` | the `settings` tool ([AgentSettings](AgentSettings.md)) | the execution snapshot ([EnvironmentSettings](EnvironmentSettings.md)) | [#2017](https://github.com/arcships/dim/issues/2017) | +| [PromptSuggestionSettings](PromptSuggestionSettings.md) (owner contract) | the `prompt-suggestion` source and its value behind `promptSuggestionSettings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [ProviderSettings](ProviderSettings.md) (owner contract) | the `provider` source and the User-Agent value behind `providerSettings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [ModelLog](ModelLog.md) (owner contract) | the `model-log` source and the recording destination behind `modelLog` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [PermissionRules](PermissionRules.md) (owner contract) | the `permission` source, its rules value behind `permissionRules` and the `permission.*` methods | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [CollaborationModelPolicy](CollaborationModelPolicy.md) (owner contract) | the `collaboration` source, its policy value behind `collaborationPolicy` and the `collaboration.*` methods | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | @@ -51,6 +60,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, 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) | +| Process parts | Settings, SettingsMethods and the settings sections (PromptSettings, ExecutionSettings, PromptSuggestionSettings, ProviderSettings, ModelLog, PermissionRules, CollaborationModelPolicy), Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), `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) | | 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/Settings.md b/docs/design/plugins/Settings.md new file mode 100644 index 0000000000..f235794417 --- /dev/null +++ b/docs/design/plugins/Settings.md @@ -0,0 +1,512 @@ +# Settings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). + +Settings owns the process's configuration documents and the process's authorized projects. This document is the owner's target contract. Each source's meaning belongs to the plugin that registers it; those owners have their own contracts ([PromptSettings](PromptSettings.md), [ExecutionSettings](ExecutionSettings.md), [PermissionRules](PermissionRules.md), and so on). + +## Use and scope: responsibility split + +Settings owns: + +- **Sources.** The registry of named documents: each source's file names, project scope, the members only the user changes, and how its content is checked — a JSON Schema or a Rust document type. A registration belongs to the registering row and ends when that row unloads. +- **Documents and revisions.** The user document (a file, or a row in the native store) and the project document (a file under an authorized project); the opaque revision that changes on every committed write; one writer at a time per document. +- **Change application.** Running a caller's change against the current document under the owner's exclusion, checking the result, writing it, publishing the fact, and reporting whether durability is confirmed. +- **Authority.** An owner change and an agent change may not alter a user-only member; a user edit may. Every member marked `writeOnly` that is reachable through `properties` is withheld from the agent, and the agent may not set it; the rule does not scan `items`, `$defs` or `anyOf`. +- **Authorized projects.** The cwd → project table, the FileStorage root it registers with `add_root` for each authorized cwd, and the fact announcing a new one. +- **Facts.** `settings/` with `{source, scope, revision}` after a commit, and `settings/projects` with `{root, cwd}` after a new authorization. + +Callers keep: + +- Document meaning: the type, schema, defaults and validation rules of each source, and the business name of every member. +- Which source, member or project a business edits, and what a refused or conflicting edit means for that business. +- When a value is fresh enough: a reader reads at use time, or follows the fact and reads again. +- Permission and approval decisions; Settings never decides whether a write is allowed beyond the authority rules above. +- File bytes of non-Settings files, including workflow definitions: those are FileStorage's operations, requested by the file's owner. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A source owner reads its own document now | No: addressing by source name lets every row read every source, and makes the owner re-resolve its registration on each call | `register` answers the source id; `read` takes the id | +| A source owner changes its own document | No: a read-then-replace makes the caller hold the revision and retry a competing write — the owner's exclusion and revision are its own mechanism | `change` | +| A source owner reacts to a committed write | Yes: the `settings/` fact carries the revision; read again | Business | +| A user edits a declared document from a client | No: the client needs the current revision and a whole-document replace, and a refused write means the user's draft is stale | `read_user`, `replace_user` through [SettingsMethods](SettingsMethods.md), which resolves the source name and refuses a Rust source | +| A user's write is based on a revision | Yes: the client holds the revision it read; that revision is the client's business concurrency control between the user's read and write, not this owner's version — the owner's exclusion and revision stay inside `change` | Business; `read_user` returns the draft base and `replace_user` compares it | +| A user edits a Rust-typed source whose rules JSON Schema cannot express | Yes: the source owner's own management namespace performs the write with its source id | Business (the source owner's methods) | +| The agent reads one plugin's configuration | No: hiding `writeOnly` members is this owner's schema rule | `agent_read` | +| The agent sets one member of another plugin's configuration | No: refusing user-only and `writeOnly` members is this owner's rule, and a whole-document replace would overwrite members the agent did not read | `agent_set` | +| The plugin tool lists the sources a live row registered | No: the registry is this owner's state | `declared_sources` | +| A process part admits a cwd as a project root | No: the project table and the opened directory are this owner's state | `authorize_project` | +| A business learns the authorized projects | No: the table is this owner's state | `authorized_projects` | +| A business needs a project's cwd or number | Yes: `authorized_projects` is a value with `{root, cwd}` | Business | +| A business reads or writes a project's non-Settings files | Yes: compose the project's cwd with FileStorage's path operations | Business | +| A capability reads a text, switch or policy another part maintains | Yes, but not from Settings: the value's owner provides its own read | The value owner's contract | + +## Caller example + +ExecutionSettings declares its document in `apply` and keeps the source id for the life of its row. + +```rust +let execution: SourceId = settings.register( + ctx, + Register { + source: "execution".into(), + user_file: "execution.json".into(), + project_file: None, + schema: execution_schema(), + user_only: vec!["/sandbox".into(), "/network".into()], + }, +)?; + +// The value as stored now. +let snapshot = settings + .read(ctx, Read { id: execution.clone(), scope: Scope::User }, cancelled.clone()) + .await?; + +// A change sees the current document and returns the next one. Settings holds the document for +// the whole call, checks the result and writes it; a competing writer waits. +settings + .change( + ctx, + execution.clone(), + Scope::User, + Arc::new(|current: Option| { + Box::pin(async move { + let mut document = current.map(|document| document.0).unwrap_or_default(); + document["network"] = true.into(); + Ok(Document(document)) + }) + }), + cancelled.clone(), + ) + .await?; +``` + +A user edit is [SettingsMethods](SettingsMethods.md)'s caller example: the client names a declared source, keeps the draft revision it read, and only that path carries a revision. + +The plugin tool reads a plugin's configuration for the agent, and sets one member. + +```rust +let view = settings + .agent_read(AgentRead { source: "web".into() }, cancelled.clone()) + .await?; +// `view.write_only` lists the members withheld from the agent. +settings + .agent_set( + AgentSet { source: "web".into(), member: "/proxyDns".into(), value: true.into() }, + cancelled.clone(), + ) + .await?; +``` + +Workflow resolves its project and touches its own definition files through FileStorage. + +```rust +let projects = settings.authorized_projects(); +let project = projects + .projects + .iter() + .find(|project| project.cwd == cwd) + .ok_or(WorkflowError::WorkspaceNotAuthorized)?; +let definitions = format!("{}/.dimcode/workflows/{}", project.cwd, name); +let bytes = storage.read(definitions, None, None, cancelled).await?; // FileStorage's operation +``` + +## Own contract + +### Dependencies + +- [FileStorage](https://github.com/arcships/dim/pull/2080) at its head `7224c0cd4`: `add_root` for a project authorization, and `read` and `update` for a document stored as a file, with an absolute path. The host registers the roots it assembles with and each Session's workspace; a project cwd is made addressable with `add_root` and answers the same id when it is added again. Settings reads the home directory as a host value from the assembly, because the assembly already knows it; FileStorage also exposes `root_path` and `stat`, which Settings does not use — this is a choice, not a missing operation. Settings passes no path outside the home directory and an authorized cwd. +- The storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) as the native profile's crate-private implementation: it executes this owner's transactions over the `settings_documents` rows. The rows and their request, reply and error shapes are this contract's ([Native-profile row operations](#native-profile-row-operations)); the engine answers no Settings read or write on its public face. +- The caller's row: a source id and the registration are bound to the row that registered them. `read` and `change` check the caller's row and answer `invalid` for another row's id; the user path (`read_user`, `replace_user`) and the agent path (`agent_read`, `agent_set`) do not check the caller's row, and the user path is served to [SettingsMethods](SettingsMethods.md) and to a Rust owner's own namespace. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Make a document addressable under the calling row, checked once | `{source, userFile, projectFile?, schema, userOnly}` | a source id | None; a refusal fails the row's `apply` | `invalid` | +| `read` | The document a source id names, as stored now | `{id, scope}` | `{document}` | While the document is read | `invalid`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | +| `change` | Apply one change to a document under the owner's exclusion | `{id, scope}` and the change callback | `{}` | Before the write; the change's future is dropped | `invalid`, `invalid_document`, `user_only`, `rejected`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | +| `read_user` | The user's draft base for a document, by source id | `{id, scope}` | `{revision, document}` | While the document is read | `invalid`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | +| `replace_user` | Replace a document with the draft the user edited at the revision read | `{id, scope, expectedRevision, document}` | `{revision, document}` | Before the write; an admitted write still commits | `invalid`, `invalid_document`, `conflict`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | +| `agent_read` | A declared document for the agent, `writeOnly` members withheld | `{source}` | `{document, writeOnly}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | +| `agent_set` | Set one member of a declared document for the agent | `{source, member, value}` | `{document, writeOnly}` | Before the write | `unknown_source`, `invalid`, `user_only`, `invalid_document`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | +| `declared_sources` | The declared sources, by name: all of them, or those a live row registered | `{instance?}` | `{sources: [{id, source, schema, scopes, userOnly, writeOnlyHint}]}` | None; the owner completes the read | None | +| `authorize_project` | Admit a cwd as an authorized project; the same cwd answers the same number | `{cwd}` | `{root}` | Before the directory is opened or the entry appended | `invalid`, `closed`, `cancelled` | +| `authorized_projects` | The projects authorized in this process generation | `{}` | `{projects: [{root, cwd}]}` | None | None | + +Data: + +- `SourceId` is the id `register` assigns. `read` and `change` check that the calling row registered it; an id from another row is `invalid` there. The user path does not check the row: `SettingsMethods` reaches a declared source's id after resolving the client's name, and a Rust owner reaches its own id. `declared_sources` lists only declared sources; a Rust source's id is not listed. +- `Document` is one JSON object; a missing user document reads as its default document. +- `Scope` is `"user"` or `{"project": }`. The number is this process's project number, assigned by `authorize_project`; it is not durable and it is not FileStorage's root id. +- `userOnly` lists JSON Pointers to members only the user changes. Each pointer must name a member reachable through the schema's `properties`; otherwise `register` is `invalid`. +- `ChangeFn` is `Fn(Option) -> Result`: it is called once, under the document's exclusion, with the current document, and returns the next document or its own refusal. It must only compute; waiting on another owner or on I/O inside the change holds the document for that whole wait. +- `Revision` is an opaque value that changes on every committed write. Only the user path carries it, as the draft base the client holds: a business concurrency control between the user's read and write. An owner change carries no revision; the owner's exclusion and any waiting stay inside `change`. +- `writeOnly` lists the JSON Pointers of members, reachable through `properties`, that are withheld from the agent when they hold a value. `writeOnlyHint` in a declaration is true when the source declares at least one such member; it is a hint, not the pointer list. + +### Native-profile row operations + +The native profile stores each user document as a `settings_documents` row. These four operations belong to this contract and are crate-private to the storage crate: the engine executes each as one transaction and returns the stored form, and no caller outside Settings calls them. The file profile has no counterpart; it calls FileStorage's `read` and `update` instead. + +| Operation | Intent | Request | Reply | Errors | +| --- | --- | --- | --- | --- | +| `readUser` | One source's stored user document | `{source}` | `{version, document}` or none | `failed` | +| `importUserIfAbsent` | Import the validated file content when the row is absent, in one transaction, and return the winning row | `{source, document, importedRevision}` | `{version, document}` | `failed` | +| `changeUser` | Apply one change under the row's exclusion | `{source}` and the change callback | `{version, document}` | `rejected`, `failed` | +| `replaceUser` | Replace a user document at an expected version | `{source, expectedVersion, document}` | `{version}` | `conflict`, `missing`, `overflow`, `failed` | + +`change` in the public operations is `changeUser` on the native profile and FileStorage's `update` on the file profile; `replace_user` is `replaceUser` and FileStorage's `update`. On the file profile, Settings reads the current revision inside the FileStorage `update` callback and compares `expectedRevision` there; FileStorage holds only the file key and knows no version. `importUserIfAbsent` runs on the first read of a source whose file exists and whose row does not; a version is a positive integer that increases on every committed write, and the revision Settings publishes is derived from it. + +### Facts + +| Fact | Channel | Payload | +| --- | --- | --- | +| A document was written | `settings/` | `{source, scope, revision}` | +| A project was authorized | `settings/projects` | `{root, cwd}` | + +A fact is published after the commit and never carries a document. A failed fact delivery is recorded and does not undo the write. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | Fix the input: a declaration whose name or file is taken, whose schema is refused, or whose user-only pointer names no reachable member; a source id from another row; an unknown project; a project scope for a source without a project file; a member pointer that names no member | +| `unknown_source` | The declared source is not registered now, or it is a Rust source that the client and agent paths do not serve: retry after its owner registers it, or report that the feature is off | +| `invalid_document` | The document as stored, or the one the change produced, fails its check; repair the user's document or fix the change | +| `user_only` | The change or the agent named a member only the user changes, including a `writeOnly` member the agent tried to set; ask the user, or leave the member as it is | +| `rejected` | The change refused with its own `reason` and `message`; act on `reason` | +| `conflict` | The user's draft is stale; read again and let the user decide | +| `too_large` | The document exceeds the document limit; the caller must not treat the value as a document | +| `unsynced` | The document is in place but its durability is unconfirmed; read it and do not repeat a change without reading | +| `failed` | Storage or persistence failed: a FileStorage read or write, a row transaction, or a worker; read again before retrying | +| `closed` | This generation is unloading; call the replacement generation | +| `cancelled` | Nothing changed: the read stopped, or the change stopped before the write | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `change` | Take the document's exclusion, read the current document, call the change, check the result, write it, publish, release | Before the write: the change's future is dropped, the document is unchanged, the exclusion is released, `cancelled` | The row's `apply` future ends; the same release applies | New calls are refused; an in-flight change finishes or ends `closed`; the generation releases its exclusions | Exclusion by Settings; the change's future by the calling row | +| `replace_user` | Take the exclusion, read the current revision, refuse a stale base, check and write the document, publish, release | An admitted write still commits or ends `unsynced`; a wait dropped before admission changes nothing | The admitted write completes; the reply may be lost | In-flight calls finish or end `closed` | Exclusion by Settings; the admitted write by Settings | +| `read`, `read_user`, `agent_read` | Open the document through its profile, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings | +| `declared_sources`, `authorized_projects` | Read the registry or the project table and return the value; no cancellation and nothing to release | Not applicable | Not applicable | The generation answers from its own memory | Settings | +| `authorize_project` | Call `add_root` for the cwd, append the cwd → number entry when absent, publish the fact for a new one, return the number | Before the directory is opened or the entry is appended; a later call for the same cwd completes the authorization | The call ends `cancelled`; the append-only root table keeps the root | The table is generation state: a new generation starts empty and a cwd is authorized again at admission | The project table by Settings; the directory root by FileStorage | +| `register` | Check the declaration, insert under the calling row, return the id | Not cancellable; a failed `apply` ends the row | The registration is withdrawn with the row; its documents stay | The new generation starts with no registrations; the documents stay | Registration lifetime by the calling row | + +## Exceptions with reasons + +- The user path carries a draft revision and the owner path does not: the client's business decides whether a write still applies to the document the user read, while an owner change always applies to the current document; the revision is not a version the owner checks on the owner path. +- `unsynced` reports a write that is in place with unconfirmed durability: a read sees it, and a repeated change applies again, so the caller reads before repeating. +- On the native profile the first read imports the user file into the row when the row is absent: the import is internal state migration, not an operation, and the file stays where it is. +- The project table is process-generation state: the number is Settings' own, not FileStorage's root id, and not durable. FileStorage's `add_root` makes the cwd addressable and answers a root id that Settings keeps only inside the authorization; after a Settings reload the table starts empty and a cwd is authorized again at admission. +- Settings uses `add_root`, `read` and `update` from FileStorage; it does not use `root_path` or `stat`, which exist in the same contract. The home directory is a host value because the assembly owns it, and a Settings document is read whole, so neither is needed. +- A client write is admitted when it starts: a disconnected client does not undo it, so the reply may be lost while the document is written or `unsynced`. + +## Supersedes + +- [Settings service](../appserver/settings-service.md) §4.1 (common shapes: `Snapshot`, `Sources`, `SettingsScope`), §4.2 (the `settings` service), §4.5 (the Rust binding), §5 (the operations' flows), §6 (the error codes) and §11 (acceptance). §4.3 is [SettingsMethods](SettingsMethods.md)'s. The document's §3 state, §4.4 events, §7 security, §8.1, §9 and §10 stay in force; §4.4's `project_authorized` payload keeps `{root, cwd}`, and the new acceptance is the delivery's flow tests. +- [Settings service](../appserver/settings-service.md) §8.1's note that Rust owners keep their own methods stays; the methods' shapes are in each owner's contract. +- [Resource owner operations](../contracts/resource-owner-operations.md) §Settings. +- [Service faces](../service-faces.md) §3.3's `settingsService` row, §3.2's host-port sentence (`executionSettings`, `promptSuggestionSettings`), §4's prompt-ports paragraph, and §4.1's `settingsService` paragraph. +- [Management methods](../appserver/management-methods.md)'s `settings.read`/`update`/`sources`/`projects` list. +- [Prompt overrides](../appserver/prompt-overrides.md) §3.1 (the three prompt ports are one service; see [PromptSettings](PromptSettings.md)). +- [Permission command rules](../appserver/permission-command-rules.md) §4.1's `commandRules` service (see [PermissionRules](PermissionRules.md)). + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Settings is one process part. It publishes facts and folds no state, so it is not a Capability. | +| §2 scopes | Process: documents and the project table outlive Sessions. Session and branch parts read values or follow facts; none registers a source. | +| §3 orthogonality | Settings reads no other owner's state except through FileStorage's operations and the storage engine's transactions; no plugin's business appears in this contract. | +| §4 rule 1 | A committed write is a fact on `settings/`; a refused write publishes nothing. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No `before` callback. `change` runs under the document's exclusion, never inside the Timeline's commit lock. | +| §4 rule 4 | No document meaning, schema or business rule for a source in the core; each source owner keeps its own. | +| §4 rule 5 | No Timeline batch. Settings documents never enter the Timeline. | +| §4 rule 6 | Settings documents never enter model context; the agent path is the `plugin` tool's result, decided by PluginManager. | +| §4 rule 7 | Callers use these operations; no caller reads a file path, a lock or a stage. | +| §4 rule 8 | The storage engine executes this owner's crate-private row operations ([#2091](https://github.com/arcships/dim/pull/2091)); no new infrastructure. | +| §4 rule 9 | A revision fact is written only after the commit; no scratch state is persisted. | +| §7 objects | Only values cross: documents, source ids, project numbers, revisions and the change callback by reference. No object, handle or path crosses. | +| §7 no proxy | No operation answers another owner's data: a value is requested from the part that owns it, and workflow definition bytes come from FileStorage for the Workflow plugin. | +| §7 one face | One service on the `Settings` type; no facade, no wrapper type, no second name. | +| §7 cross-language | Every operation's request, reply and errors are data; the Rust binding is the appendix. | +| §7 caller complexity | The revision, exclusion, retry and durability stay inside Settings; the caller handles the business outcomes (`conflict`, `user_only`, `rejected`, `unsynced`) and the ordinary failures (`invalid`, `unknown_source`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled`). | +| §7 one change | The old `settings`/`settingsService` surfaces and their callers are migrated in one change; PluginManager, SettingsMethods and every source owner appear in the delivery table. | +| ADR 002 D1 | Process scope; documents and the project table outlive Sessions. | +| ADR 002 D2 | No wiring plugin; the service is on the owner type. | +| ADR 002 D3 | Dependencies point to FileStorage and the storage engine; the rows belong to Settings and no plugin depends on Settings' internals. | +| ADR 002 D4 | Business configuration lives in the owner's named source, read at use time; structural items stay in PluginManager. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: every caller is at the process scope or depends outward, so no cross-scope id resolution is involved. | +| §7.2 checks | Every caller need lands on one operation; no handle, object or proxy crosses; one face; no Rust-only method on the face; no caller mechanism; one change. | + +## Requirements raised to mechanism owners + +- **Storage engine, [#2018](https://github.com/arcships/dim/issues/2018) and [#2091](https://github.com/arcships/dim/pull/2091):** no requirement. The engine executes this owner's crate-private row operations as transactions; the rows, versions and conflicts are Settings', and the engine publishes none of them under `sqliteStorage`. +- **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** the model request's User-Agent is read from [ProviderSettings](ProviderSettings.md)'s value instead of being pushed into the process identity; the model-log recorder reads its destination from [ModelLog](ModelLog.md)'s value instead of a process-global setter. +- **Workflow, [#2033](https://github.com/arcships/dim/issues/2033):** definition files are read and replaced through FileStorage's path operations, with the project resolved from `authorized_projects`; `workflowFiles` is removed with no replacement face on Settings. + +## Binding appendix + +The service is marked on the owner type; the wire name stays `settings`. The `Settings` facade and the `SettingsService` type merge into this type. + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; +use rutis::Ctx; +use serde_json::Value; +use std::sync::Arc; + +pub type SourceId = String; +/// The process-local project number `authorize_project` assigns; it is not durable. +pub type ProjectId = u64; +pub type Revision = String; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Register { + pub source: String, + pub user_file: String, + pub project_file: Option, + pub schema: Value, + pub user_only: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct Document(pub Value); + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scope { + User, + Project(ProjectId), +} + +impl Scope { + fn project(&self) -> Option { + match self { + Self::User => None, + Self::Project(project) => Some(*project), + } + } +} + +/// One document's replacement from the change callback: its own `reason` and `message`. +#[derive(Debug, thiserror::Error)] +#[error("{reason}: {message}")] +pub struct ChangeRefused { + pub reason: String, + pub message: String, +} + +/// A callback's refusal arrives as the wire's own error; its code becomes `reason`. +impl From for ChangeRefused { + fn from(error: rutis::host::CallError) -> Self { + let reason = error + .raw() + .and_then(|raw| raw.downcast_ref::()) + .and_then(rutis_bridge::session::Error::code) + .unwrap_or("rejected") + .to_owned(); + Self { reason, message: error.to_string() } + } +} + +pub type ChangeFn = Arc< + dyn Fn(Option) -> BoxFuture<'static, Result> + Send + Sync, +>; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Read { + pub id: SourceId, + pub scope: Scope, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Snapshot { + pub document: Document, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UserSnapshot { + pub revision: Revision, + pub document: Document, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReplaceUser { + pub id: SourceId, + pub scope: Scope, + pub expected_revision: Revision, + pub document: Document, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentRead { + pub source: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentSnapshot { + pub document: Document, + pub write_only: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentSet { + pub source: String, + pub member: String, + pub value: Value, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ByInstance { + pub instance: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Declaration { + pub id: SourceId, + pub source: String, + pub schema: Value, + pub scopes: Vec, + pub user_only: Vec, + pub write_only_hint: bool, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Declarations { + pub sources: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizeProject { + pub cwd: String, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Authorized { + pub root: ProjectId, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Project { + pub root: ProjectId, + pub cwd: String, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedProjects { + pub projects: Vec, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum SettingsError { + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + UnknownSource { message: String }, + #[error("{message}")] + InvalidDocument { message: String }, + #[error("{message}")] + UserOnly { message: String }, + #[error("{reason}: {message}")] + Rejected { reason: String, message: String }, + #[error("{message}")] + Conflict { message: String }, + #[error("{message}")] + TooLarge { message: String }, + #[error("{message}")] + Unsynced { message: String }, + #[error("{message}")] + Failed { message: String }, + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Cancelled { message: String }, +} + +impl PublicService for Settings {} + +#[rutis::service(name = "settings")] +impl Settings { + pub fn register(&self, caller: &Ctx, request: Register) -> Result { /* ... */ } + pub async fn read( + &self, + caller: &Ctx, + request: Read, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub async fn change( + &self, + caller: &Ctx, + id: SourceId, + scope: Scope, + change: ChangeFn, + cancelled: CancelledFn, + ) -> Result<(), SettingsError> { /* ... */ } + pub async fn read_user( + &self, + request: Read, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub async fn replace_user( + &self, + request: ReplaceUser, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub async fn agent_read( + &self, + request: AgentRead, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub async fn agent_set( + &self, + request: AgentSet, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub fn declared_sources(&self, request: ByInstance) -> Declarations { /* ... */ } + pub async fn authorize_project( + &self, + request: AuthorizeProject, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub fn authorized_projects(&self) -> AuthorizedProjects { /* ... */ } +} + +// `CancelledFn` is the binding's cancellation argument, not a request field. + +/// The Rust binding of `register` for a Rust document type: the same operation, with the type as +/// its codec instead of a schema, and its `USER_ONLY` list as the user-only members. +impl Settings { + pub fn register_typed( + &self, + caller: &Ctx, + ) -> Result { /* ... */ } +} + +/// The Rust document binding gains the user-only rule its source declares. +pub trait BusinessDocument { + // ... `NAMESPACE`, `USER_FILE`, `PROJECT_FILE` as today + const USER_ONLY: &'static [&'static str] = &[]; +} +``` diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md new file mode 100644 index 0000000000..ccbbc93867 --- /dev/null +++ b/docs/design/plugins/SettingsMethods.md @@ -0,0 +1,156 @@ +# SettingsMethods + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). + +SettingsMethods registers the local client's `settings.*` management methods and calls [Settings](Settings.md)' user operations. The namespace serves **declared sources only**: a Rust source such as `mcp` is `settings_unknown_source`, and its owner's own namespace is the only way to edit it. + +## Use and scope: responsibility split + +SettingsMethods owns: + +- The `settings` management namespace: which methods exist, their request and reply data, and the mapping from Settings' errors to the client's error codes. +- The declared-only rule and the source-name resolution: the namespace maps the client's `source` name to the registered declared source's id, and refuses a name whose owner is a Rust document. +- Admission: paired devices are never served the namespace; the authenticated loopback Web entry is served `settings.read` and `settings.update` for its allowlisted sources (`WEB_SETTINGS_SOURCES` in `crates/dim-app-server/src/protocol.rs`: `model-log` and `execution`). + +Callers keep: + +- The user's draft, its editing flow and what a stale draft means in the client. +- Which declared source the client edits; the client never learns another owner's document, and a Rust source is not reachable here. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client reads a declared document to edit it | No: the client reaches management methods only, and the draft base is [Settings](Settings.md) `read_user` | `settings.read` | +| A client writes the draft it edited | No: the write must carry the draft's base revision, the client's business concurrency control between the user's read and write, and report a stale draft | `settings.update` | +| A client lists every declared source and its schema | Yes, and no client asks: the CLI reads five sources by name; the Web pages read their two allowlisted sources by name | Not an operation; `settings.sources` is deleted | +| A client lists authorized projects to pass a project scope | Yes, and no client asks: no declared source declares a project file | Not an operation; `settings.projects` is deleted | +| A client edits a Rust-typed source | Yes, through that owner's own namespace (`permission.*`, `collaboration.*`, and so on) | Business | + +Every caller of the namespace: the CLI reads `prompts` (`crates/dim-cli/src/prompt_command.rs`, `crates/dim-cli/src/session_host.rs`), `prompt-suggestion` and `execution` (`session_host.rs`), `model-log` (`crates/dim-cli/src/recording.rs`) and `workflow` (`crates/dim-cli/src/management/workflow.rs`); the Web `DiagnosticsSettings` and `PermissionsSettings` pages (`web/src/features/settings/`) read `model-log` and `execution`; the Workflow TypeScript plugin (`runtime/plugins/workflow/catalog.ts`) reads the plugin-face `settings` service, which is not this namespace. + +## Caller example + +The CLI edits the operator's prompts with the revision it read. + +```rust +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct ReadRequest<'a> { + source: &'a str, + scope: Scope, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct UpdateRequest<'a> { + source: &'a str, + scope: Scope, + expected_revision: &'a str, + document: &'a JsonObject, +} + +let snapshot: SettingsDraft = client + .typed( + "settings.read", + serde_json::to_value(ReadRequest { source: SOURCE, scope: Scope::User })?, + ) + .await?; +// The user edits one field; the write is the whole document at the revision read. +client + .typed( + "settings.update", + serde_json::to_value(UpdateRequest { + source: SOURCE, + scope: Scope::User, + expected_revision: &snapshot.revision, + document: &document, + })?, + ) + .await?; +``` + +The request is one typed struct, serialized at the client boundary; no request is assembled as an inline JSON literal. The reply keeps `{revision, document}`, the shape today's CLI and Web pages parse. + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `declared_sources` (no instance) to resolve the client's source name to a declared source id, then `read_user` and `replace_user` with that id. SettingsMethods adds no state of its own beyond the admitted-write task it owns. + +### Operations + +No service. Two management methods, registered with `managementMethods`: + +| Method | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `settings.read` | The user's draft base for one declared document | `{source, scope}` | `{revision, document}` | A cancelled call has no reply and changes nothing | invalid params, `settings_unknown_source`, `settings_failed`, `operation_interrupted`, reloading | +| `settings.update` | Replace a declared document with the draft at the revision read | `{source, scope, expectedRevision, document}` | `{revision, document}` | A cancelled wait changes nothing before admission; an admitted write commits or ends `settings_unsynced` | invalid params, `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed`, `operation_interrupted`, reloading | + +Invalid params covers a malformed request, an unknown field, a missing revision, a document that is not an object, and a document the source's schema refuses; for a schema refusal the message is the validator's, and the client shows it as an input error. + +`settings_conflict` means the draft is stale: the client reads again and lets the user decide. `settings_unsynced` means the bytes are in place with unconfirmed durability: read again instead of repeating the write. `operation_interrupted` means this part unloaded while the call was pending; a caller-cancelled call has no reply. The client re-reads before retrying. `reloading` means the daemon is restarting. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| invalid params | Fix the request or the draft: an unknown field, a missing revision, a document that is not an object, a schema violation (the message is the validator's) | +| `settings_unknown_source` | The source is not registered now, or it is a Rust source this namespace does not serve; report that the feature is off, or use that owner's namespace | +| `settings_conflict` | Read again; the user's draft is stale | +| `settings_unsynced` | Read again; the write is in place | +| `settings_failed` | Read again before retrying; the store failed without a code the client can act on | +| `operation_interrupted` | The part unloaded while the call was pending; read again before retrying | +| reloading | The daemon is restarting; retry after it is back | + +### Flows + +| Operation | Normal path | Caller cancels | Caller closes or the row unloads | Settled by | +| --- | --- | --- | --- | --- | +| `settings.read` | Resolve the declared source id, call [Settings](Settings.md) `read_user`, map the reply | Nothing changes; no reply | Pending calls end `operation_interrupted` | Settings | +| `settings.update` | Resolve the declared source id, admit the write into this part's task, call [Settings](Settings.md) `replace_user`, map the reply | An admitted write still commits or ends `settings_unsynced`; dropping the wait does not undo it | Admitted writes settle before the part closes | Settings owns the write; SettingsMethods holds the admitted task | + +## Supersedes + +- [Settings service](../appserver/settings-service.md) §4.3. +- [Management methods](../appserver/management-methods.md)'s list of four `settings.*` methods. + +## Client-visible changes + +- The management methods `settings.sources` and `settings.projects` are removed. No repository client calls them: the CLI reads five sources by name, the Web `DiagnosticsSettings` and `PermissionsSettings` pages read their two allowlisted sources by name, and no declared source has a project file. An out-of-repo client that listed sources or projects reads the sources it knows by name instead; its `settings.read` and `settings.update` requests and replies keep their shapes, including `scope` and the `{revision, document}` update reply. +- `settings.read` and `settings.update` keep the project scope field; the number is Settings' own process-local project number, which is what the request already carried. +- No error code, field name or notification name changes. + +## Exceptions with reasons + +- `managementMethods` is a mechanism registration point, not a forwarding facade: the namespace belongs to this part because Rpc reaches Settings through Agents and may not reach a management owner ([ADR 004](../../adr/004-loader-plugin-management.md) D4), and the declared-only rule and the client's error codes are this part's own contract. +- The client's request and reply shapes stay as today's protocol: existing CLI and Web callers send `{source, scope, expectedRevision, document}` and parse `{revision, document}`, and the redesign changes plugin-facing surfaces, not the client protocol. +- `settings.sources` and `settings.projects` are deleted, not moved: no client calls them (the CLI reads five sources by name, the Web pages two, and no declared source has a project file). + +## Rule check + +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part, no Timeline facts, no folded state: not a Capability. | +| §2 scopes | Process; the methods are client surfaces, not Session state. | +| §3 orthogonality | No state of its own; one dependency, [Settings](Settings.md), plus the admitted-write task it owns. | +| §4 rule 1 | No event. | +| §4 rule 7 | Clients use management methods; they learn no file name, path, id or lock. | +| §4 rule 8 | No infrastructure change; the existing `managementMethods` mechanism is used. | +| §7 objects | Request and reply are data; no object, handle or path crosses. | +| §7 no proxy | Settings answers the document; SettingsMethods owns the namespace, the declared-only rule and the error mapping. | +| §7 one face | The management namespace exists once; the service operations stay on [Settings](Settings.md). | +| §7 cross-language | Both methods are data. | +| §7 caller complexity | The revision reaches the client because the user's draft depends on it; the declared-only rule and the error mapping stay here. | +| §7 one change | `settings.sources` and `settings.projects` are deleted with this change; the CLI and the Web pages are migrated in the same change. | +| ADR 002 D2 | No wiring plugin: the namespace owner is a process part that depends on Settings, as PermissionRules owns `permission`. | +| ADR 002 D4 | Business configuration stays in Settings sources; the methods carry no structural item. | +| ADR 027 | Not applicable: the callers are clients of a process-scope service. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +No service and no Rust binding: the two methods are registered with `managementMethods`. The request and reply types are the client's JSON shapes in the operations table; the CLI's `ReadRequest` and `UpdateRequest` above are the Rust spelling of the same data. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..5bff26432d 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -92,7 +92,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `wakeups` | `wakeups.create/list/cancel` | 形状按 [Scheduler](plugins/Scheduler.md#102-methods-and-tool) §10.2。 | | `loops` | `loops.start/next/list/stop` | 形状按 [Scheduler](plugins/Scheduler.md#126-interfaces) §12.6;`start`、`next`、`stop` 是迁改,`list` 是读取。投递 pass、恢复与 `settle_delivering` 不在此面。 | | `sessionFiles` | `sessionFiles.put/import/read/register/owns/owned_paths` | 形状按 [Session files](appserver/session-files.md) §9.1,`SessionFiles` 是进程内绑定。 | -| `commandRules` | `commandRules.read` | Session 命令规则读取,按 [命令规则](appserver/permission-command-rules.md#41-language-neutral-adr-002-d5) §4.1。 | +| `commandRules` | 已删除 | 规则由 [PermissionRules](plugins/PermissionRules.md) 的 `permissionRules.rules` 提供。 | | `managedSearch` | `managedSearch.search` | 凭据由实现持有,见 §4.6。 | | `agentConfig` | `agentConfig.get()` | 形状见 §4.8。 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | @@ -101,7 +101,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `worktreeAssociations` | `store.associateWorktree` | 形状见 §4.8。 | | `toolSourcesView` | `toolSourcesView.get/observe` | 同一 ToolRegistry owner 的独立只读观察面;贡献注册仍由 `toolRegistry` 负责,见 [工具贡献 §7.5](../architecture/rust-agent/tool-contributions.md#75-服务接口)。 | -宿主读取端口的数据面(§4.10)包括 `executionSettingsHost`、`toolchainSourceHost`、`promptSuggestionSettingsHost`。模型选择与列表统一由 `providerService` 提供;调用方和配置见[进程操作](contracts/process-owner-operations.md);其余读取端口沿用现名。 +宿主读取端口的数据面(§4.10)包括 `executionSettings`、`toolchainSourceHost`、`promptSuggestionSettings`;前两者的操作由 [ExecutionSettings](plugins/ExecutionSettings.md) 与 [PromptSuggestionSettings](plugins/PromptSuggestionSettings.md) 定义。模型选择与列表统一由 `providerService` 提供;调用方和配置见[进程操作](contracts/process-owner-operations.md);其余读取端口沿用现名。 ### 3.3 所有者 API,已有数据兄弟 @@ -110,7 +110,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | 名字 | 数据兄弟 | 说明 | | --- | --- | --- | | `agentIndex` | `sessions` | 目录查询走 `sessions` | -| `settingsService` | `settings` | GoalBranch 的取消契约见 §4.1。 | +| `settingsService` | `settings` | 已由 [Settings](plugins/Settings.md) 取代:一个服务标注在所有者类型上,不保留 owner API 行。 | | `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | | `loader` | `rutis/loader` | 插件管理走数据面 | | `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 标题与 worktree 关联直接调 store | @@ -209,14 +209,11 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow 每批处理同一个 owner 的相关操作。 -PromptSettings 的三个只读端口按 [prompt overrides §3.1](appserver/prompt-overrides.md#31-data-operations) -提供 `basePromptSettingsHost.base({})`、`skillsInstructionsSettingsHost.instructions({})` 和 -`summaryPromptSettingsHost.systemPrompt({})`,回复为字符串或 `null`。它们共享现有 owner, -原生与跨语言入口调用同一读取方法;配置优先级、读取时机和失败回退保持 owner 契约。 +PromptSettings 的一个服务按 [PromptSettings](plugins/PromptSettings.md) 提供 `promptSettings.base({})`、`promptSettings.summary({})` 和 `promptSettings.skills({})`,回复为 `{text}` 或 none;capability 侧各依赖自己的端口 trait。配置优先级、读取时机和失败回退保持 owner 契约。 -### 4.1 `settingsService`:保留调用取消 +### 4.1 `settingsService`:已被 Settings 取代 -迁移前 `GoalBranch` 继续用类型化调用,读取随 branch stop token 取消。设置 owner 在 #1292 的批次内确定如何将调用方取消传递给读取操作,并验证 `settings.read` 的 `SettingsResult` 信封和现有错误语义。Goal 切到同一数据契约的 Rust 绑定时,覆盖分支停止中断设置读取的流程。 +已由 [Settings](plugins/Settings.md) 与 [SettingsMethods](plugins/SettingsMethods.md) 取代:所有者按 source id 读值,调用方的取消随读取结束;GoalBranch 的读取改走该绑定。 ### 4.2 `modelHost`:保留完整模型请求 @@ -355,11 +352,11 @@ eventSubscriptions.list {sessionId} -> reply 这些读取操作持有 owner 的闭包,Rust 绑定直接调用类型化操作;dispatcher 只在跨语言边界解码请求、调用同一个操作并编码回复,不写第二份业务逻辑。Rust 调用不经过 JSON,也不为读取另起桥接任务。每次异步调用持有独立的子取消 token:取消或丢弃调用会取消该次 owner 读取,不取消调用方的父 token。跨语言回复使用 `cancellable_future`,放弃等待会丢弃同一个读取;owner 的生命周期仍约束其工作。 ```text -executionSettingsHost.read({}) -> {sandbox, network} +executionSettings.read({}) -> {sandbox, network} -> error {code: failed, message} toolchainSourceHost.list({}) -> {toolchains: [{bin, root}]} # sync -> error {code: failed, message} -promptSuggestionSettingsHost.read({}) -> {enabled, maxChars} +promptSuggestionSettings.read({}) -> {enabled, maxChars} -> error {code: failed, message} providerService.selectableModels({}) -> {models: [ModelCapabilitySnapshot]} providerService.selectableForModality({}) -> {models: [ModalityModelSnapshot]} diff --git a/docs/design/subagent-model-policy.md b/docs/design/subagent-model-policy.md index b933a994f5..0dbe9812e3 100644 --- a/docs/design/subagent-model-policy.md +++ b/docs/design/subagent-model-policy.md @@ -53,7 +53,7 @@ decision by an LLM. `agent` means the existing request/profile selection behavio | Identify the requesting branch | `CollaborationSession::request` already receives `branch_id`; pass it within Collaboration, without changing an event or tool request | | Read the adopted leader model | `Session::get(branch_id)` while consuming `collaboration/request`, before starting its delivery task | | Resolve an explicit model | The existing `AgentIndex` model-selection host and configured/non-catalog profile paths | -| Persist and edit policy | Native `BusinessDocument`, `SettingsService::read/update`, source CAS and owner management methods, as used by `permission_rules.rs` | +| Persist and edit policy | [CollaborationModelPolicy](plugins/CollaborationModelPolicy.md): the `collaboration` source, its `policy` value read and the `collaboration.*` methods | | Start/restore and retain members | Existing Agents/Collaboration Session creation, usage holds and cleanup, including idle unloading | Do not use `leader.config().model` or `session.summaries` as the adopted leader model: