diff --git a/crates/dim-app-server/README.md b/crates/dim-app-server/README.md index 063e2ab994..4df34f7e5b 100644 --- a/crates/dim-app-server/README.md +++ b/crates/dim-app-server/README.md @@ -513,7 +513,7 @@ dim_app_server::cli::process_entry( ) ``` -`ManagedProviderRow` registers the plugin's process row given the product root's FileStorage index and returns the row name; `ServerConfig.managed_provider` carries it for embedders. It is installed only with a product home, beside `ManagedProviderBinding`, which hands the provider to the managed provider implementation. The plugin owns its account schema, authentication, token refresh and catalog normalization; the host does not interpret supplier-specific responses. Files it keeps under the product root go through FileStorage; `auth.json` is plain JSON shared with the native subscription providers, each owning its own root fields. +`ManagedProviderRow` registers the plugin's process row given the product root's FileStorage root id and returns the row name; `ServerConfig.managed_provider` carries it for embedders. It is installed only with a product home, beside `ManagedProviderBinding`, which hands the provider to the managed provider implementation. The plugin owns its account schema, authentication, token refresh and catalog normalization; the host does not interpret supplier-specific responses. Files it keeps under the product root go through FileStorage; `auth.json` is plain JSON shared with the native subscription providers, each owning its own root fields. `process_entry` is the process entry: on Unix it closes every descriptor above standard error that the process inherited, then calls `run_with`, so a process `main` calls it before it opens anything. Linux closes the range in one `close_range` call; where that call is unavailable, and on the other Unix systems, the daemon lists `/proc/self/fd` (Linux) or `/dev/fd` and closes every number the listing names; when no listing can be read it closes 3 up to the process's descriptor limit, which is the soft limit, else the hard limit, else `sysconf(_SC_OPEN_MAX)`, else 65,536, so no inherited descriptor stays open. `run_with` and `run` do not touch the descriptors the process has open and are the entries for an embedder that keeps its own. `process_entry` and `run_with` take a native-profile installer, `fn(&mut AgentBuilder)`, called when the product-home or model-config execution profile is assembled. It contributes host-selected plugins through the existing builder API. `run` and the standalone server choose no additional native plugins; `dimcode` installs its product plugins from their own crates (`dim_session_title::install`, `dim_agent_scheduler::install`, `dim_goal::install`, `dim_report::install` and `dim_modality::install`) for both profiles. The Scheduler and the Goal are among those plugins and are no longer default TypeScript plugins, so a host that wants `schedule.*` and the `schedule` tool calls `dim_agent_scheduler::install` from its installer, one that wants `goal_update`, `session.goal.*` and continuation calls `dim_goal::install`, one that wants `modality.*` calls `dim_modality::install`, and the plain `dim-app-server` binary serves none of them. diff --git a/crates/dim-oauth/docs/runtime-contract.md b/crates/dim-oauth/docs/runtime-contract.md index 7505663e68..ad13aac541 100644 --- a/crates/dim-oauth/docs/runtime-contract.md +++ b/crates/dim-oauth/docs/runtime-contract.md @@ -27,13 +27,13 @@ terminal and returns `cancelled`. DimOAuth never writes Session metadata or choo ## Account record -`/auth.json` is the only persisted source of Dim credentials (`nextApiOauth`) and account state (`dimAccountState`, schema 1: `credentialEpoch`, `generation`, `credentialRevision`, `state`, and when authenticated `identity` and `tokenDigest`). It is plain JSON shared with the native subscription providers; other root fields belong to their owners and are preserved. Writes go through the product root's FileStorage lease, which also serializes concurrent processes, with Unix mode 0600. A lookup that finds a usable record reads the file atomically without that lease, so a fresh grant creates no `auth.json.lock` marker and no fsync; the lease is taken when a refresh, normalization or any other write is needed. The provider publishes whether the file stores a signed-in account as a watch, and moves it after every write. The startup initialization and the host's `observe_account` share one read-only observation. An observation whose validated state already equals the published one answers from the atomic read and publishes nothing; a missing `auth.json` is a home that never signed in, and the observation neither creates nor normalizes it. The first observation, or one whose state differs, takes the lease, rereads the file and publishes that validated read, whose `tokenDigest` must match its grant, before releasing the lease; a record this build cannot validate publishes nothing. The observation ends with its caller's wait: dropping the wait ends the lease wait, so a timed-out Session read leaves no retry behind. An `account.status` read whose result differs from the published state — including the first read after an uninitialized start — takes the lease and reads the file again, publishing that observation before releasing it, so a read that started earlier never overwrites a newer write or logout; an unchanged result answers from the atomic read without the lease. `tokenDigest` is the SHA-256 of the grant's RFC 8785 canonical JSON. +`/auth.json` is the only persisted source of Dim credentials (`nextApiOauth`) and account state (`dimAccountState`, schema 1: `credentialEpoch`, `generation`, `credentialRevision`, `state`, and when authenticated `identity` and `tokenDigest`). It is plain JSON shared with the native subscription providers; other root fields belong to their owners and are preserved. Writes go through FileStorage's `auth.json.lock` marker (the marker protocol in the [FileStorage contract](../../../docs/architecture/rust-agent/plugins/FileStorage.md)), which also serializes concurrent processes, with Unix mode 0600. A lookup that finds a usable record reads the file atomically without the marker, so a fresh grant creates no `auth.json.lock` marker and no fsync; the marker is taken when a refresh, normalization, observation or any other write is needed; a cancelled claim that has not returned its id removes the marker it created, and a refresh's claim is released only after the row's admitted `update_claimed` settles; a claim whose observation or normalization is cancelled or refused before its write releases the claim without writing. The provider publishes whether the file stores a signed-in account as a watch, and moves it after every write. The startup initialization and the host's `observe_account` share one read-only observation. An observation whose validated state already equals the published one answers from the atomic read and publishes nothing; a missing `auth.json` is a home that never signed in, and the observation neither creates nor normalizes it. The first observation, or one whose state differs, takes the marker, rereads the file and publishes that validated read, whose `tokenDigest` must match its grant, before releasing the marker; a record this build cannot validate publishes nothing. The observation ends with its caller's wait: dropping the wait ends the marker wait, so a timed-out Session read leaves no retry behind. An `account.status` read whose result differs from the published state — including the first read after an uninitialized start — takes the marker and reads the file again, publishing that observation before releasing it, so a read that started earlier never overwrites a newer write or logout; an unchanged result answers from the atomic read without the marker. `tokenDigest` is the SHA-256 of the grant's RFC 8785 canonical JSON. The TypeScript plugin (0.2.0) wrote this file as a PluginFiles record `{"version":1,"text":...}`. Reading accepts that record, keeping fields other owners wrote beside it; the next write stores plain JSON. Its digests verify unchanged, so a signed-in account survives the upgrade with the same epoch and generation. -JSON or root errors and an unknown schema remain errors and are never shown as signed out. Only an explicit login or logout resets a corrupt schema-1 record: the complete original bytes are first written exclusively to `auth.json.dim-reset-backup`, then only the Dim fields are replaced by a new signed-out state. An existing backup blocks another reset and is never overwritten or removed. Explicit recovery (`account.recover`) accepts a legacy grant or a digest mismatch, confirms the identity online and starts a new epoch at generation 1. +JSON or root errors and an unknown schema remain errors and are never shown as signed out. Only an explicit login or logout resets a corrupt schema-1 record: one `update` passes `keep_replaced_as = auth.json.dim-reset-backup` (a bare name the owner joins to the target's parent), so the owner copies the current bytes exclusively under the file's lock (the key, or the credential record's marker) before the change replaces only the Dim fields with a new signed-out state. An existing copy answers `rejected` with reason `backup_exists`; it is never overwritten or removed, and it blocks another reset until it is moved. A change that refuses or writes nothing leaves no copy. Explicit recovery (`account.recover`) accepts a legacy grant or a digest mismatch, confirms the identity online and starts a new epoch at generation 1. -Login captures the record's revision before starting and compares it when committing. Logout advances the signed-out generation, including when already signed out, and revokes the refresh token on a best-effort basis. Credentials are refreshed within a 30-second freshness window, under the account lock, and a rotated grant is persisted before the lock is released; 408, 429, 5xx and network failures keep the stored grant, and an explicit rejection signs out only the grant that holds the lock. Requests resolve their credential under this window, which is the correctness boundary: a fresh grant answers from the atomic read, and only a grant inside the window waits for the lock and refreshes. While the process runs, a background task also renews the grant as it enters the window, so an idle process does not let its refresh token lapse. It renews and persists a rotated grant and signs out a rejected one, but it never normalizes the record it reads; write-on-normalize stays with the explicit account operations. It retries a transient failure after 60 seconds, and stops after a sign-out or an unusable record until this process signs in again. Quiesce ends it. +Login captures the record's revision before starting and compares it when committing. Logout advances the signed-out generation, including when already signed out, and revokes the refresh token on a best-effort basis. Credentials are refreshed within a 30-second freshness window, under the account marker claim, and a rotated grant is persisted before the claim is released; 408, 429, 5xx and network failures keep the stored grant, and an explicit rejection signs out only the grant that holds the claim. Requests resolve their credential under this window, which is the correctness boundary: a fresh grant answers from the atomic read, and only a grant inside the window waits for the marker and refreshes. While the process runs, a background task also renews the grant as it enters the window, so an idle process does not let its refresh token lapse. It renews and persists a rotated grant and signs out a rejected one, but it never normalizes the record it reads; write-on-normalize stays with the explicit account operations. It retries a transient failure after 60 seconds, and stops after a sign-out or an unusable record until this process signs in again. Quiesce ends it. The public host contract (`ManagedProvider`, its DTOs, leases, quiesce and error mapping) is in the [App Server README](../../dim-app-server/README.md#managed-provider-contract). diff --git a/docs/INDEX.md b/docs/INDEX.md index 13b16e09be..fc47029dc1 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -14,7 +14,7 @@ This index is navigation. Delivery status lives in issues, not here. - [模型请求重试与任务续接方案](design/research/model-retry-recovery.md)(中文,#1210):请求重试的可见性、独立恢复能力的边界及所有者合同需求 - [服务面:跨语言形状的策略、盘点与第一批改造](design/service-faces.md)(中文,Draft),装配现状见[生成的服务目录](architecture/rust-agent/generated/catalog.md)。 - [插件远程化:可行性与落地路径](design/research/remote-plugins.md)(中文,研究稿):rutis 链路能跨什么、HostPlatform/exec/基础工具/存储各自能不能远程化、推荐拓扑与分阶段 -- [Resource and store data faces](design/resource-faces.md) (Draft): `execHost`, `fsHost` and `store` as the only public contracts for processes, files and Session state (#1295, #1296, #1297, #1298) +- [Resource and store data faces](design/resource-faces.md) (Draft): `execHost`, `fsHost` and `store` as the only public contracts for processes, files and Session state (#1295, #1296, #1297, #2016, #1298) - [Watch:任务观察与 side branch](design/research/side-eval.md)(中文,设计提案):Watch 与 Pursuit 的用户边界、分支切点、订阅与 prompt 的组合、管理与关注、采样开销 - [Overall design for undesigned features](design/overview.md)([中文](zh/design/overview.md)) - [Plugin designs index](design/plugins/README.md)([中文](zh/design/plugins/README.md)) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index a363b97931..da5798c8c8 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -19,7 +19,7 @@ Terminal / npm launcher Parts are rutis 0.23.0 plugins; a part that depends on services by name is a `host::DynPlugin` that keeps their keys ([How Dim uses rutis, appendix A](../design/rutis-usage.md#appendix-a-rust-binding)). Dependencies are declared once; the catalog keys each name for the instances a copy runs in. A managed provider is an optional Rust process plugin that an account build's own executable installs; without it, managed-provider requests fail explicitly while API-key providers remain available. -Plugin and part factories are pure and preserve plugin names and dependency keys. Configuration that must survive reload belongs to the captured plugin configuration; each `apply` acquires fresh I/O resources and registers their cleanup. FileStorage clones share the append-only authorized-root identities, while directory handles, operations and leases belong to one service generation. Rebuilding from the initial root list would let a later project reuse an earlier project's index. +Plugin and part factories are pure and preserve plugin names and dependency keys. Configuration that must survive reload belongs to the captured plugin configuration; each `apply` acquires fresh I/O resources and registers their cleanup. FileStorage clones share the append-only authorized-root identities, while directory handles, operations and keys belong to one service generation. Rebuilding from the initial root list would let a later project reuse an earlier project's index. The WorkspaceTools plugin holds one file-write coordinator for every Session it serves and keeps it across reloads. `write` and `edit` share per-path admission across Sessions, retain their lock through blocking I/O and binding publication, and stage complete bytes before atomic replacement. Existing revision, identity and metadata are checked immediately before commit; new targets use create-if-absent publication. This is not compare-and-swap against unrelated processes or parent-directory replacement. Native metadata is preserved (macOS ACL/xattrs/resource forks, Linux xattrs/ACL, Windows DACL). Unchanged Linux security labels are retained without rewriting them. Windows alternate streams or ownership/security that cannot be preserved fail unchanged. An error after installation reports that the target may already have changed. Re-read before retrying. diff --git a/docs/architecture/client-ui-extensions.md b/docs/architecture/client-ui-extensions.md index 1a57813fd5..a31110eae1 100644 --- a/docs/architecture/client-ui-extensions.md +++ b/docs/architecture/client-ui-extensions.md @@ -13,8 +13,8 @@ HTTP to these owners, while the Web client owns mounting and selection. | Part | Scope | Dependencies | Provides | | --- | --- | --- | --- | -| UiExtensions | process | managementMethods, partRegistry, fileStorage | uiExtensions | -| UiResources | Session | sessionIdentity, sessionLifecycle, fileStorage | uiResources | +| UiExtensions | process | managementMethods, partRegistry, fsHost | uiExtensions | +| UiResources | Session | sessionIdentity, sessionLifecycle, fsHost | uiResources | PluginManager registers UI content independently of code rows. UiExtensions copies regular files through FileStorage into a private generation directory, diff --git a/docs/architecture/rust-agent/plugins/FileStorage.md b/docs/architecture/rust-agent/plugins/FileStorage.md index a9b0942039..2d682f4434 100644 --- a/docs/architecture/rust-agent/plugins/FileStorage.md +++ b/docs/architecture/rust-agent/plugins/FileStorage.md @@ -2,14 +2,631 @@ Owner: [file_storage.rs](../../../../crates/dim-agent-capabilities/src/file_storage.rs) and [windows.rs](../../../../crates/dim-agent-capabilities/src/file_storage/windows.rs). -Provides authorized-root-relative file operations and leases with secure path -traversal and serialized mutation, plus directory creation, listing and removal. -## Dependencies +Target contract for [#2016](https://github.com/arcships/dim/issues/2016) and the current implementation. + +Scope: process. Issue: #2016. + +FileStorage owns byte storage under explicitly authorized roots. This document is the owner's target contract; the current implementation is described in [Current implementation](#current-implementation) below. PluginFiles is a separate owner under the same issue and is not covered here; its calls appear in the delivery tables on [#2016](https://github.com/arcships/dim/issues/2016). + +## Use and scope: responsibility split + +FileStorage owns: + +- **Roots.** The process's authorized directories and their open handles. The host registers the roots it assembles with and the workspace of each Session it creates. `add_root` lets a trusted process part make a runtime directory addressable (Settings' project authorization, the UI extension directories, the migration source); `root_path` answers a root's directory for a caller that was given its id. Both are values, and neither grants authority: FileStorage is not a sandbox, a root only says which directories are addressable, and the trusted-plugin boundary and Permission decide what may be read or written. +- **Generations.** One service instance admits calls, owns the descriptors it opened and releases them on close. +- **Exclusion.** Each file's lock key beside the file; a credential record's lock is its published marker instead. A replacement, removal or update holds that file's lock (the key, or the credential record's published marker); another process holds the same lock for the same file under every case and Unicode spelling the filesystem equates. FileStorage waits for the lock until the caller cancels or the owner closes. +- **Credential markers.** `auth.json`, `mcp-oauth.json` and `chatgpt-account.json` use the published marker `.lock` beside them: an exclusive file carrying the holder's process id, creation time and nonce. `claim` returns an id for one, `release` removes it, and a marker older than 30 seconds without a live process at its creation is reclaimed. Creation and reclamation of a marker are serialized by the private key for that file in the reserved directory; the key is held only while creating or reclaiming and is released before waiting, and it never crosses the face. Every operation that writes, removes or imports over a credential record takes its marker for the call, except `update_claimed`, which writes under the claim it is given; any holder, including the row that holds a claim, waits. A claim holder takes no other operation over that credential record that waits for the marker (`write`, `import`, `remove`, `update`); reads are taken while it holds the claim. A claim holder writes only through `update_claimed`; for a waiting operation it releases the claim first. An operation that takes the marker for its call removes it on cancellation, unload or owner close when it does not commit. If the replacement commits but removing the marker fails, the call answers `unsynced`, records the marker as abandoned, and this process's next `claim` reclaims it at once. +- **Atomic replacement.** A temporary file in the owner's namespace, flushed and renamed over the target, with the durability answer. +- **Reads and facts.** A whole document up to 8 MiB, one 64 KiB page at an offset, and a file's kind and size; reads are stateless, so no read id crosses. +- **Path validation.** Absolute paths inside a root, one validated component per open, no link followed, the owner's own resource names excluded. + +Callers keep: + +- Document formats and versions: settings documents, `auth.json`, `mcp-oauth.json`, `chatgpt-account.json`, the plugin envelope, JSONL records. +- Which root and file a business uses, and the file names. +- What a business conflict means and when to retry it. +- Permission and approval: FileStorage never decides whether a call may run. +- Workspace, system and worktree facts: FileAccess owns them; FileStorage answers only whether an absolute path is inside a root. +- Files a plugin creates and manages itself under a root, such as SQLite's database, the model-log recorder's JSONL and the UI extension cache. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Read one document: settings, accounts, plugin records, a project's hooks file | Yes: `read` without an offset reads the whole document and answers none when absent | Business composes | +| Read a large file in pages | No: the owner bounds one reply to a page, reports the end and the file's size, so the caller never holds an id or a page size of its own | `read` with `offset` and `length` | +| Learn a file's kind and size before reading or writing it (a permission fact, a publish) | No: existence, kind and length are one owner read, and a read cannot answer them without a file | `stat` | +| Replace a document's bytes atomically | Yes: `write` whose source yields the whole content once | Business composes | +| Write content that arrives in pieces, including a stream an adapter produces | No: holding it whole is unbounded; the temporary file and the key must stay inside the owner | `write` with a source | +| Read, decide and write back while other processes may replace the file | No: between a read and a write another writer replaces the file, so only the owner can hold the file across the caller's decision | `update` with a change | +| Keep the replaced bytes before a destructive rewrite | No: the copy must be created exclusively while the owner holds the file, and an existing entry at that path must block the rewrite | `update` or `update_claimed` with `keep_replaced_as` | +| Hold a credential record's marker across a token or refresh request | No: the marker is the published cross-process exclusion, and only the owner can create, reclaim and verify it | `claim`, `release`, and `update_claimed` | +| Refresh a credential | Yes: read the record, judge freshness, call the provider and write back inside the claim | Business | +| Hold a credential record's marker across a read and a publish without writing | No: the marker is the cross-process exclusion, and the read must see the record the holder later acts on | `claim`, `read`, `release`; a normalization write inside the hold uses `update_claimed` | +| Bring a host file the caller named into a root | No: the source is outside the roots and must be bounded and land atomically | `import` | +| Keep a document's file owner-only from creation (settings, accounts) | No: the mode is a file attribute the owner applies at creation and replacement | `permissions` on `write`, `import`, `update` and `update_claimed` | +| Write a Session file that `write` and `edit` may not modify | No: the read-only attribute is a file attribute the owner applies | `permissions` | +| Bound a host file import by the business limit (a Session attachment) | No: the caller's limit must stop the copy before it lands | `import` with `max_bytes` | +| Make a work directory tree and learn its absolute path | No: per-component link and alias validation is the owner's knowledge | `create_directory` | +| List one level and remove by a listed native name | No: the name's encoding and the single-component rule are the owner's knowledge | `list`, `remove` | +| Make a runtime-discovered directory addressable | No: the root set is the owner's state, and a root is a value other parts address | `add_root` | +| Hand a root's directory to another module: a process working directory, a path quoted in history, a log directory | No: the root set is the owner's state | `root_path` | +| Learn whether an optional file exists (a project hooks file, a Settings source) | Yes: `read` answers none; `stat` answers `missing`; `list` answers the parent's entries | Business composes | +| Decode or encode a document, choose its name and its root | Yes: formats and business paths stay with callers | Business | +| Append records to a log it owns (the model-log recorder) | Yes: the recorder owns the file; `root_path` gives it the directory | Business; the file is the recorder's, as SQLite's database is | +| Write a UI extension cache and then publish it | Yes: the cache belongs to UiExtensions; FileStorage reads it only on request | Business | +| Decide whether a read or write is allowed | Yes: Permission and Approval decide | Business | + +An operation or parameter exists only where its row says No. + +## Caller example + +Reading one document, one page, and a file's facts: + +```rust +// Whole document: none when absent, too_large above 8 MiB. +let Some(document) = storage.read(path.clone(), None, None, cancelled.clone()).await? else { + return Ok(None); +}; +let document = document.data; +// One 64 KiB page: size is the file length, eof says the page reached the end, +// and an offset past size is invalid rather than an empty page. +let page = storage.read(path.clone(), Some(offset), Some(PAGE), cancelled.clone()).await?; +// Existence, kind and size without reading the bytes. +let facts = storage.stat(path, cancelled).await?; +``` + +Settings' compare-and-set: the change runs under the owner's file key, sees the current content and returns the next content or a business refusal. + +```rust +storage.update( + path, + Arc::new(move |current: Option| { + Box::pin(async move { + let current = decode(current.as_ref().map(|bytes| bytes.0.as_slice()))?; // business format + let next = check_and_update(current, document.clone())?; // business rules, including the document's own revision + Ok(Some(Bytes(encode(next)?))) + }) + }), + None, + Some(Permissions::Private), + cancelled, +) +.await?; +``` + +SessionStore's write of bytes, and of a host path: + +```rust +// `once` is a source that yields the bytes once and then none. +let size = storage.write(path, once(bytes), Some(Permissions::PrivateReadOnly), cancelled.clone()).await?; +// A host file the caller named, without reading it first. +let size = storage.import(path, source, Some(MAX_FILE_BYTES), Some(Permissions::PrivateReadOnly), cancelled).await?; +``` + +DimOAuth's reset: keep the replaced bytes and rewrite the file in one `update`. The owner creates the copy exclusively under the file's lock (the key, or the credential record's marker) before the change runs; the change replaces the Dim fields and returns the next document. + +```rust +storage.update( + auth_path, + Arc::new(move |stored: Option| { + Box::pin(async move { + let mut document = parse(stored.as_ref().map(|bytes| bytes.0.as_slice()))?; // business format + document.remove(TOKENS); + document.insert(STATE.into(), signed_out()); + Ok(Some(Bytes(encode(document)?))) + }) + }), + Some(backup_path), // absolute or bare auth.json.dim-reset-backup; an existing entry answers rejected/backup_exists + Some(Permissions::Private), + cancelled, +) +.await?; +``` + +UiResources' publish and pages, with no id to release: + +```rust +// The size is checked at publish; a page request beyond it is the caller's invalid_params. +let facts = storage.stat(path.clone(), cancelled.clone()).await?; +let size = facts.size.unwrap_or(0); +let page = storage.read(path, Some(offset), Some(PAGE), cancelled).await?; +``` + +With the dispatch's `caller` in scope, a claimed change and the directory operations: + +```rust +let claim = storage.claim(caller, auth_path.clone(), cancelled.clone()).await?; +// Release on both the success and failure paths; a failed release is reported +// before the business error. +let outcome = async { + let _record = storage.read(auth_path.clone(), None, None, cancelled.clone()).await?; + storage.update_claimed( + caller, + auth_path, + change, + claim.claim_id.clone(), + None, + Some(Permissions::Private), + cancelled.clone(), + ).await +}.await; +let released = storage.release(caller, claim.claim_id).await; +released?; +outcome?; + +let directory = storage.create_directory(path, cancelled.clone()).await?; +let entries = storage.list(directory.clone(), cancelled.clone()).await?; +storage.remove(RemoveTarget::Path { path: directory }, cancelled).await?; +``` + +A module that needs a root's directory, such as the model-log recorder: + +```rust +let home = storage.root_path(home_root)?; +let directory = format!("{home}/model-log"); // the recorder owns this file +``` + +## Callers that hold work across an external wait + +The public face has no lease. Managed OAuth composes its exclusion from `claim`, `release` and `update_claimed`; Mcp does the same for its credential record; Migration and PluginFiles compose theirs from `update`, and the owner keeps the guarantee that one `update` is exclusive across processes. + +**Managed OAuth, with a rotating refresh token.** `auth.json.lock` is the one exclusive lock for `auth.json`; there is no separate file key exposed to callers. `claim` and a directory removal that meets the marker take the private `auth.json` key while they create or reclaim it, release it before waiting, and re-acquire it after the wait; `release` removes the marker by matching its owner record without the key. Two reclaimers therefore cannot both create a marker, and a waiter never blocks the holder's release. The caller claims it with `claim(caller, path, cancelled)`, which creates the marker with its process id, creation time and nonce and returns a claim id. The caller reads the record and judges freshness. The winner performs the HTTP refresh while it holds the marker, then writes the rotated record with one `update_claimed(caller, path, change, claim_id, keep_replaced_as?, permissions?, cancelled)`: the owner checks that the marker still carries this claim's nonce (a reclaimed claim answers `rejected` with reason `claim-lost`) and runs the change under that same hold without taking the lock again; the change compares the record's `credentialRevision` with the one it read, refusing with `rejected` reason `conflict` when another write advanced it. The caller then releases the claim. If the refresh fails, the caller releases the claim, re-reads the record and adopts it when `credentialRevision` advanced; otherwise it reports the failure. A waiter's `claim` waits for the marker; when it is released, the waiter re-reads the record, adopts it when `credentialRevision` advanced, and otherwise claims and refreshes itself. A `write` or `update` without a claim takes the same lock for its call, so another writer waits while the claim is held; a claim holder writes only through `update_claimed`; it releases the claim first for an operation that waits for the marker (`write`, `import`, `remove`, `update`). + +Managed OAuth owns the refresh it issued. Before unload it finishes admitted work, and a cancellation waits for the disk write before returning; an admitted `update_claimed` settles before the claim is released, while an unadmitted call ends `cancelled`. On row unload or owner close, FileStorage waits for this row's admitted `update_claimed` to settle (the write or an explicit failure) before releasing the claim, so a provider rotation cannot outlive the local claim. The flow tests assert `refreshes == 1` with two callers and a rotating token, a write attempted between claim and commit waits for the marker, an advanced `credentialRevision` is refused with `conflict`, a reclaimed claim answers `claim-lost`, a failed refresh with a waiting loser lets the waiter claim and refresh, an external marker-following writer blocked during the refresh, and a row unload between the refresh and its write that settles before the claim is released. + +If the refresh succeeds but its write-back does not, `io` or `closed` means the record was not written; `rejected` with reason `conflict` or `claim-lost` means the same. Managed OAuth returns the error, leaves the record as it was and releases the claim. `unsynced` means the content is written but durability is unconfirmed; the caller treats it as success. If the provider already rotated and the record still holds the older refresh token, the next refresh is rejected by the provider and the record becomes `rejected`; the user signs in again ([managed_oauth.rs:1073-1077](../../../../crates/dim-app-server/src/managed_oauth.rs)). Row unload ends the row's admitted refresh, HTTP and its last `update_claimed`, before the release; FileStorage's row-unload release is the fallback after that work settles ([managed_oauth.rs:245-273](../../../../crates/dim-app-server/src/managed_oauth.rs)). + +**DimOAuth refresh.** The DimOAuth store claims `auth.json.lock` before a refresh, observation or normalization, re-reads the record, calls the provider and writes the rotated grant with one `update_claimed`; the change compares `credentialRevision` and refuses an advanced one with `rejected` reason `conflict`. A rejected grant writes the signed-out state under the same claim. The claim is released after the write, successfully or not. A claim whose work is cancelled or refused before its write releases the claim without writing. + +**MCP credential record.** `mcp-oauth.json.lock` is the one exclusive lock for `mcp-oauth.json`, under the same marker protocol as `auth.json`. The file has one writer, but two daemons can share a home (for example `--product-home` with different `--database` paths), and the marker stops both from redeeming one rotating refresh token. Mcp claims the marker with `claim(caller, path, cancelled)` before a code exchange, refresh or revocation, re-reads the record under it, and holds it through the token request. The write-back is one `update_claimed` whose change replaces only the caller's key in the record; the owner checks the marker's nonce and runs the change under that hold. A failed request, or a request cancelled before its write, releases the claim without writing. Discovery and registration run outside the marker. Every token request, for any server, holds the one marker, so requests for different servers wait on each other; each is bounded by its 30-second timeout, and they are rare. A token request that has been sent is received and persisted on McpAuth's own task, whoever waits for it; Mcp's unload waits for it, and FileStorage's row-unload release waits for the row's admitted `update_claimed` to settle, so a rotated refresh token or a redeemed code is not lost. A code exchange whose attempt was superseded, or whose record cannot be written, is still received, but its tokens are revoked and discarded. The ending follows the error list above: `io` or `closed` means the record was not written, and `rejected` with reason `claim-lost` means the same; `unsynced` means the content is written and durability is unconfirmed; a claim asserted by another daemon makes the caller wait, not fail. + +**ChatGPT account record.** `chatgpt-account.json.lock` is the one exclusive lock for `chatgpt-account.json`; ManagedAccount is the file's only writer, and the marker serializes a refresh, a code exchange and a sign-out with any other writer of the record. Each of the three claims the marker before its network call, reads the record, calls the provider, and writes with one `update_claimed` whose change replaces the active profile's credentials or clears them. The claim is released after the write, successfully or not. A safe status read does not start a refresh and reads the file without the marker; startup never starts one. If the write fails, `io` or `closed` means the record was not written, `rejected` with reason `claim-lost` means the same, and `unsynced` means it was written and durability is unconfirmed. A claim from a previous account generation cannot refresh or invalidate the current one. + +**Migration snapshot run.** Migration defines its run claim in its own document; the FileStorage operation it uses is `update`. The claim is a file whose change writes the content only when the file is absent and otherwise refuses with a `rejected` error whose reason is `held`; a later run checks the recorded process with a credential marker's rule (the process id is alive and its start time is not later than the claim's creation) and replaces a stale claim inside the same `update`. No key is held while a run copies files. + +**PluginFiles.** PluginFiles is a separate owner under the same issue; it owns the record envelope and its callers' migration, and it composes its record transaction from one `update`. + +## Own contract + +### Dependencies + +None. FileStorage injects no service and reads no other owner's state. The host registers roots through the provider when it assembles the process and when it creates a Session; trusted process parts add runtime roots with `add_root` and read a root's directory with `root_path`. The provider is chosen by deployment ([resource faces §1](../../../design/resource-faces.md#1-scope)): whether a call reaches a local or a mounted instance is not a property of this name. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `add_root` | Make an existing absolute directory addressable | `{path}` | `root`; an existing root answers its id | Before the directory handle is opened | `invalid`, `io`, `closed`, `cancelled` | +| `root_path` | A root's absolute directory for another module | `{root}` | `path` | None; the owner completes the read | `invalid`, `closed` | +| `stat` | A path's kind and size | `{path}` | `Stat`; `missing` is a kind, not an error | Before the reply | `invalid`, `io`, `closed`, `cancelled` | +| `read` | Read a whole document, or one page of a file | `{path, offset?, length?}` | `ReadReply {data, eof, size}` or none | Before the reply; nothing changes | `invalid`, `too_large`, `io`, `closed`, `cancelled` | +| `claim` | Hold a credential record's published marker | `{path}` | `claimId`; the marker carries this caller's nonce | While waiting for the marker; no marker is created. If cancelled after creation but before the id is returned, the owner removes that marker | `invalid`, `io`, `closed`, `cancelled` | +| `release` | Remove the credential marker this caller holds | `{claimId}` | unit | None; the owner completes the removal | `invalid`, `rejected`, `io`, `closed` | +| `write` | Replace a file's bytes atomically from a source the owner pulls to its end | `{path, permissions?}` and the `source` callback | `size` | Before the replacement; the temporary file is removed | `invalid`, `missing_parent`, `rejected`, `io`, `unsynced`, `closed`, `cancelled` | +| `import` | Copy a regular host file into a root atomically | `{path, source, maxBytes?, permissions?}` | `size` | Before the replacement; the temporary file is removed | `invalid`, `too_large`, `missing_parent`, `io`, `unsynced`, `closed`, `cancelled` | +| `update` | Change a file's content while the owner holds the file across the caller's decision | `{path, keepReplacedAs?, permissions?}` and the `change` callback | `UpdateReply {applied}` | Before the replacement; the temporary file and any copy are removed | `invalid`, `missing_parent`, `too_large`, `rejected`, `io`, `unsynced`, `closed`, `cancelled` | +| `update_claimed` | The same change under the credential marker this row holds | `{path, claimId, keepReplacedAs?, permissions?}` and the `change` callback | `UpdateReply {applied}` | Before the replacement; the temporary file and any copy are removed | `invalid`, `missing_parent`, `too_large`, `rejected`, `io`, `unsynced`, `closed`, `cancelled` | +| `create_directory` | Make the path an existing directory tree | `{path}` | `path` | Between levels; created ancestors stay, a retry is safe | `invalid`, `io`, `unsynced`, `closed`, `cancelled` | +| `list` | One level of a directory; the owner's own resources, including equivalent spellings, never appear | `{path}` | `entries` or none when the directory is absent | Before the reply | `invalid`, `io`, `closed`, `cancelled` | +| `remove` | Make a file or a directory tree absent; an absent entry counts as removed | `{path}` or `{parent, name}` | unit | Before the entry is unlinked; a tree can be partly removed, a retry is safe | `invalid`, `io`, `unsynced`, `closed`, `cancelled` | + +Request fields use the wire's camelCase names; the Rust binding parameters below use snake_case (`keep_replaced_as`, `max_bytes`, `claim_id`). -No injected services (`Deps = ()`). +`read` without `offset` and `length` reads the whole document up to 8 MiB and answers `too_large` above it; with both, it reads one page of at most 64 KiB (`length` above the page is clamped), `size` is the file's length and `eof` is true when the page reaches the end; one of the two alone is `invalid`. An offset equal to `size` reads an empty page with `eof`; an offset above `size` is `invalid`, and a `length` of 0 is `invalid` (the client paging contract depends on the distinction). An absent file answers none, and so does a missing parent directory. A whole-document read reports `eof: true`. `Bytes` crosses as base64 text, so 8 MiB of bytes fits the 16 MiB bridge frame with the JSON envelope. -## Events and lifetime +`write`'s `source` and `update`/`update_claimed`'s `change` are direct method parameters, not request fields. `source` is called repeatedly until it returns none: each call yields the next chunk of at most 8 MiB of raw bytes, or a `Rejected` error that ends the write and leaves the target unchanged; a larger chunk is `invalid`. The parent is checked before `change`: a missing parent answers `missing_parent` and the change does not run. `change` is called once while the file's lock (the key, or the credential record's marker) is held, with the current content (at most 8 MiB) or none when the file is absent, and returns the next content (`Some`), no write (`None`) or a `Rejected` error. `None` leaves an existing file unchanged and does not create an absent file, still runs under the file's key and answers `applied: false`. A returned content above 8 MiB is `too_large`; `applied` is false when the content equals the current one, so a repeated write is idempotent. `update` takes no caller; `update_claimed` takes `caller: &Ctx` because the claim is bound to the row. `change` must only compute: waiting on another owner, on network I/O or on FileStorage itself inside `change` holds the file for that whole wait. §7 allows a callback by reference, and the change is never called inside the Timeline's commit lock. + +`keep_replaced_as` is either an absolute path in the target's parent or a bare name the owner joins to that parent. Under the file's lock (the key, or the credential record's marker) the owner reads the current content, copies it to the path exclusively before calling `change`: an existing entry at that path answers `rejected` with reason `backup_exists` and the change does not run; an absent target, an absolute path outside the target's parent, the target itself or a reserved name is `invalid`. The copy is `private` (0600). Any failure while creating, writing or syncing the copy removes the partial copy and syncs the parent before returning `io`. If `change` returns `None`, refuses, returns content equal to the current one (`applied: false`), returns content above 8 MiB (`too_large`), or the replacement fails before the rename, the owner removes the copy and syncs the parent, so a later call is not blocked by a stale copy. A committed replacement, including `unsynced`, leaves the copy. A crash between the copy and the replacement can leave a copy of bytes that are still the file; `backup_exists` reports it and the caller resolves it deliberately. `update_claimed` does the same under the held marker. + +`claim`'s `path` is a credential record: `auth.json`, `mcp-oauth.json` or `chatgpt-account.json`; the owner derives that file's published marker beside it and answers `invalid` for any other path. A claim is bound to the caller's row for ownership and cleanup: the row's unload releases it and `release` accepts only the claim that row holds. A second `claim` from the same row, including one for the same record, waits like any caller and can cancel; only one refresh or token request per row runs at a time. `release` takes the claim id. A row that still runs but lost the id recovers by unloading the row; a caller whose `update_claimed` answered `claim-lost` re-claims because the marker no longer carries its nonce. A claim whose work is cancelled or refused before its write releases the claim without writing. `update_claimed` checks the marker's nonce before the change runs; a reclaimed claim is `rejected` with reason `claim-lost`. A write or update of a credential record without a claim takes its marker for the call; a claim holder passes `claim_id` only to `update_claimed`; it releases the claim first for an operation that waits for the marker (`write`, `import`, `remove`, `update`). + +`permissions` is absent for "keep the existing mode; a new file gets `private`": `private` is owner-only (0600), `privateReadOnly` is owner-only and read-only (0400), the attribute Session files use. `max_bytes` is absent for the owner's 8 MiB default; a caller with a different business cap passes it. A listed name is passed back to `remove` unchanged. FileStorage waits for a file's key until the caller cancels or the owner closes; there is no fixed bound, so a call that must not wait ends with its cancellation. + +### Errors + +| Kind | Retry | What the caller does next | +| --- | --- | --- | +| `invalid` | After fixing the input | A relative path, a destination outside every root, a root's own path, an unknown root id, the owner's reserved names (the lock directory, its temporary directory and the credential markers, including filesystem-equivalent spellings), a name that is not one component, a directory where a file is required, a file where a directory is required, a link where a directory or a file is required, one of `offset` and `length` without the other, an offset above the file's size, a `length` of 0, a source chunk above 8 MiB, a claim path that is not a credential record, an unknown or other-row claim id (a previous-generation id answers `closed`), `keep_replaced_as` outside the target's parent, equal to the target or set when the target is absent; for `import`, a source that is relative, missing, not a regular file or a link | +| `missing_parent` | After creating the parent | Call `create_directory` or fix the path; the owner changed nothing | +| `too_large` | For `read`, yes in pages; for `import`, after fixing the source | `read`: use `offset` and `length`, or treat it as not a document; no partial bytes were returned. `import`: the source exceeds `max_bytes` or grew during the copy; nothing was published. `update` or `update_claimed`: the current or returned content is above the document limit; treat it as not a document | +| `rejected` | Depends on `reason` | The caller's own `change` or `source` refused with its `reason` and `message`, the claim was reclaimed (`claim-lost`), or `keep_replaced_as` found an existing entry (`backup_exists`); act on `reason`, for example re-read and retry the business step on `conflict`, re-claim after `claim-lost`, or move the retained copy before retrying `backup_exists`. A revoked callback is `cancelled`, not `rejected` | +| `io` | Yes, after fixing the environment | The filesystem refused the operation or the import source shrank while copying: a permission, a device, a network or an unsupported-filesystem error. The message and optional path say which; a `read` or `stat` shows whether the earlier call changed anything | +| `unsynced` | Not as an unchanged write | Durability is unconfirmed: after `write`, `import`, `update` or `update_claimed` the new bytes are in place; after `create_directory` the directory is; after `remove` the entry is absent. A read or stat shows the state, and a repeated call confirms. A committed replacement whose marker removal failed also answers `unsynced`; that marker is reclaimed as abandoned. | +| `cancelled` | Yes, the same call | `read`, `write`, `update`, `update_claimed` and `import` changed nothing before the replacement; `import` closes the source, `claim` creates no marker or removes one it created before returning the id, `create_directory` and `remove` follow their cancellation columns: created ancestors stay, a tree can be partly removed | +| `closed` | Yes, against the replacement generation | This generation is unloading. For `write` and `import` over a credential record, and `update` over a credential record, `closed` means the call ended before the replacement and the marker it took is removed; a non-credential `update` takes the key, and `update_claimed` writes under the caller's claim, which the caller releases. After the replacement the call succeeds or reports `unsynced`. For `remove` and `create_directory`, follow their cancellation columns. A `read` or `stat` answers which; an `add_root` either appended the root, so a later call answers its id, or did not; a `claim` either created no marker or the row's cleanup removes it; a `release` either removed the marker, or a previous-generation claim id answers `closed` and the caller re-claims. | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `add_root` | Open the directory handle, append the root; an existing root answers its id | Before the handle is opened or appended; nothing is appended | The call ends `cancelled` | New calls are refused; the append-only root table stays for the next generation, so a root id stays valid | Directory handle and root table by FileStorage | +| `root_path` | Read the root's directory from the root table | None; the call completes | The call completes | A later call is `closed`; a root id stays valid across the reload | Value by FileStorage | +| `update_claimed` | Check the marker's nonce and run under that hold without taking the lock again. Read the current content within the document limit; with `keep_replaced_as`, create the copy exclusively and sync it, then call `change`; `None` writes nothing and removes the copy, `Some` writes the temporary file, flush, rename, sync parent. The claim stays with the calling row | Before the rename: temporary file and copy removed, target unchanged, `cancelled`. After the rename: success or `unsynced`, the write is not undone and the copy stays | An admitted call settles (its change stays callable) before the row's claim is released; a copy this call created is removed when it does not commit | New calls are refused; in-flight calls finish or end `closed`; a copy this call created is removed when it does not commit | Marker, temporary file and copy by FileStorage; the claim by the calling row | +| `claim` | Take the private key for the record's file, then create its published marker exclusively with this process's id, creation time and nonce; a stale marker is unlinked and recreated under the same key and read back to verify its nonce. A live marker or a lost recreate race releases the key, waits for the marker to clear or change, then re-acquires the key and re-reads; a marker this row already holds releases the key, waits for the marker to clear or change, then re-acquires the key and re-reads; the winner never waits while holding the key | Before the marker is created; a waiter's wait ends `cancelled`; no key is held while waiting. After creation, cancellation removes the marker by its nonce before the id is returned | The row's admitted `update_claimed` calls settle first, then the claim is released and the marker removed | Pending claims end `closed`; after the row's admitted `update_claimed` calls settle, the marker is removed | Marker by FileStorage; the claim id's lifetime by the calling row | +| `release` | Remove the marker whose owner record matches the claim, without taking the private key; a marker another reclaimer now holds answers `rejected` with reason `claim-lost` | None; the owner completes the removal | The row's claim is released | A later call is `closed`; the marker is removed | Marker by FileStorage | +| `stat` | Open the parent and the entry without following links, read the kind and size, release | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | Descriptor by FileStorage | +| `read` | Open the parent and the file without following links, read the whole document or the page, report `size` and `eof`, release | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | Descriptor by FileStorage | +| `write` | Parent handle, the file's key (`auth.json`, `mcp-oauth.json` and `chatgpt-account.json` take their markers), temporary file, pull the source to its end, flush, rename, sync parent, release key; a credential record's marker is removed after the replacement | The pull stops, the temporary file is removed, the target is unchanged, `cancelled` | The source callback is revoked; the pull fails; the temporary file is removed, `cancelled` | New calls are refused; in-flight calls finish or end `closed`; the generation releases every key and temporary file | Temporary file and key by FileStorage; the source's future by the calling row | +| `import` | Open the source without following links, require a regular file at its initial length, copy into a temporary file, verify the source kept that length (growth is `too_large`, shrink is `io`, neither publishes), rename, sync parent; a credential record takes its marker, releases the private key once the marker is created, and after the rename removes the marker; a non-credential target takes its key; a claim holder releases the claim first | The temporary file is removed, the target is unchanged, the source closes | The call ends `cancelled` | Pending calls end `closed` | Source descriptor, temporary file and key by FileStorage | +| `update` | Take the file's key (`auth.json`, `mcp-oauth.json` and `chatgpt-account.json` take their markers) for the call. Read the current content within the document limit; with `keep_replaced_as`, create the copy exclusively and sync it, then call `change`; `None` writes nothing, removes the copy and releases the key, `Some` writes the temporary file, flush, rename, sync parent, release; a credential record's marker is removed after the replacement | Before the rename: temporary file and copy removed, target unchanged, key released, `cancelled`. After the rename: success or `unsynced`, the write is not undone and the copy stays | The callback is revoked and the call ends `cancelled`; a copy this call created is removed when it does not commit; the same release applies | New calls are refused; in-flight calls finish or end `closed`; the generation releases every key and temporary file and removes a copy this call created when it does not commit | Key, temporary file and copy by FileStorage; the change's future by the calling row | +| `create_directory` | Each missing level below the held parent, mode 0700, sync the parent | Between levels; created ancestors stay | The call ends `cancelled` | Pending calls end `closed` | Created directories by FileStorage | +| `list` | Open the directory, read one level, sort by name | Before the reply | The call ends `cancelled` | Pending calls end `closed` | Directory handle by FileStorage | +| `remove` | Parent handle, the entry's key; a credential record takes its marker (a claim holder releases the claim first), and a directory holding a credential marker is handled under that record's private key, released before waiting: a live marker waits, a stale one is reclaimed by `claim`'s rule, and the marker is never removed as a business entry; once the entry is absent, a credential record's marker and private key are removed, and a directory removal does the same for every credential marker under its private key; remove depth first without following links, sync the parent | Before the unlink: nothing removed; a tree can be partly removed, a retry is safe | The call ends `cancelled` | Pending waits end `closed`; the generation releases keys | Entry removal by FileStorage | + +## Exceptions with reasons + +- `import` reads a host path outside the roots: the caller names a file the user or model chose (an attachment); the owner checks that the source is a regular file, does not follow a link and enforces the byte limit, while the root constrains only the destination. +- The credential markers `auth.json.lock`, `mcp-oauth.json.lock` and `chatgpt-account.json.lock` are the published exclusions for `auth.json`, `mcp-oauth.json` and `chatgpt-account.json`: every writer of the file, in this process or another, holds the same marker. A marker is a file carrying the holder's process id, creation time and nonce; a marker older than 30 seconds without a live process at its creation is reclaimed, and a marker this process failed to release is reclaimed at once by its next claim. `auth.json.lock` coordinates the two Rust writers of `auth.json` — the DimOAuth store and managed OAuth; the TypeScript plugin no longer writes the file ([runtime contract](../../../../crates/dim-oauth/docs/runtime-contract.md) line 32), so it is not a cross-language protocol. `mcp-oauth.json.lock` coordinates daemons that share a home while Mcp is the file's only writer. `chatgpt-account.json.lock` coordinates the ChatGPT account's refresh with any other writer of the record. +- `Rejected` carries only `reason` and `message`: a callback error must cross languages, so it comes back as data; `From` recovers the wire error's own code into `reason`, and the caller keeps its business error type inside its own callback. + +## Client-visible changes + +None at the client protocol. This contract changes the plugin-facing `fsHost` surface: `read(path, offset, length)` replaces the pinned reader, `add_root` and `root_path` are operations returning addressability values, `update`/`update_claimed` take `keep_replaced_as`, a credential record's `claim`/`update_claimed` replaces a lease, and the `fileStorage` service name is removed: its consumers call `fsHost` on the `FileStorage` type. PluginFiles' `FileScope` changes are that owner's contract in the same issue ([#2016](https://github.com/arcships/dim/issues/2016)). Client protocol error codes, notification names, `session.ui.resources.read` (its request, `total` and `bytes`), Session file offset paging, the `sessionFiles.import` reply's `path`, model-visible text, and disconnect and progress behavior are unchanged. UiResources pages by path through `read`'s offset and length; its contract ([#2021](https://github.com/arcships/dim/issues/2021)) records the size at publish and requires a publisher to keep a published path unchanged. A rewrite under a published reference is a UiResources contract violation. The pinned reader is deleted in the same delivery as this contract; UiResources records the published `size` and compares each `ReadReply.size`, answering `resource_gone` when it changes. A same-size rewrite is undetectable by path paging, so the publisher's rule not to rewrite a published path is the only version guarantee; a rewrite is a UiResources contract violation. + +## Supersedes + +- `docs/design/resource-faces.md`: the status header, the `fsHost` row of §1, §2 rules 3–4, §3.2, §3.4, the §1 diagram and introduction (including the introduction that maps `fsHost`), the §4 heading, the storage-family table and the tool-family note, §4.2.1, §4.3, §4.6, §4.7, §6 (the `fileStorage` row and its §6 caller rows) and §10. +- `docs/design/contracts/resource-owner-operations.md`: the `fileStorage` row, the resource-caller row, the "OS path and input reader" paragraph and the file-backed Settings sentences. +- `docs/design/service-faces.md`: the `fileStorage` row of §3.4 and the `fileStorage` sentence in the paragraph after the table. +- `docs/design/appserver/session-files.md` and its `docs/zh` mirror: the overview line, the FileStorage bullet of §1, the §2 diagram and §3.1, §5.1, §5.4, §6, §7, §9.1, §10, §12, §13, §15, §14, the `create_directory` acceptance of §16 item 8, §17 D1 and Appendix A's `create_directory` signature and root-id paragraph. +- `docs/design/p6-p7-bindings.md`: the Workflow definitions row of §1, and the `createDirectory` row, root-registration paragraph, private-type sentence, definition-read paragraph and error distinctions of §3.1. +- `docs/architecture/rust-agent/plugins/README.md`: the FileStorage index row. +- `docs/INDEX.md`: the resource-faces row. +- `docs/architecture/README.md` and `docs/architecture/rust-agent/single-tree.md`: the lease sentences of the FileStorage generation. +- `docs/design/overview.md` and its `docs/zh` mirror: the B.1 FileStorage supplement row. +- `crates/dim-app-server/README.md`: the FileStorage root-id sentence. +- `docs/design/plugins/Modality.md` and its `docs/zh` mirror: the file-read clause of the dependency table. +- `crates/dim-oauth/docs/runtime-contract.md`: the account record and login paragraphs' lease, lock and reset-backup sentences. +- `docs/design/appserver/session-deletion-and-fork.md` and its `docs/zh` mirror: the FileStorage key and `replace` references, the Session-lease labels, the root-id sentence, §3.5, the error table, §4, §7's S6 paragraph, §12 and the §14 row. +- `docs/architecture/rust-agent/plugins/Hooks.md`: the `readBytes` sentence. +- `docs/design/plugins/Hooks.md` and its `docs/zh` mirror: the `.dimcode/hooks.json` binding row. +- `docs/architecture/rust-agent/plugins/HostPlatform.md`: the lease sentence. +- `docs/design/appserver/mcp-oauth.md` and its `docs/zh` mirror: the §1 basis row and the credential store's lock, write-path, sign-out and storage sentences. +- `docs/design/client-ui-extensions.md` and `docs/architecture/client-ui-extensions.md`: the UiExtensions and UiResources dependency rows, the reading-resource and read-handle sentences, the §9 implementation-order row, and R5. +- `docs/zh/design/appserver/session-files.md`: the ADR 013 link repair. + +Handed to PluginFiles in the same issue ([#2016](https://github.com/arcships/dim/issues/2016), batch 2): the `pluginFiles` row and the `FileScope.openRead`/`writeStream` rows of `docs/design/contracts/resource-owner-operations.md`, `docs/design/process-typescript.md` §5.2, `docs/typescript-plugin-authoring.md`, and the trusted-plugin storage section of `crates/dim-app-server/README.md`. + +## Verification + +The caller examples compile against the binding in a temporary crate outside the repository; the organizer runs that check. + +Flow tests on the owner: + +- `read` answers none for an absent file, `too_large` above 8 MiB for a whole read, `size` and `eof` for a page, an empty page at `offset == size`, and `invalid` at `offset > size`. +- A bridge flow test near 8 MiB: the whole-read reply crosses the 16 MiB frame, and a source chunk above 8 MiB answers `invalid`. +- `read` stays stateless: no id is issued, and a page read after a replace sees the replaced content. +- `stat` answers `file`, `directory`, `other` and `missing`, with the size for files and none for the others. +- `write` pulls a multi-chunk source, commits atomically, removes the temporary file when the source fails or is revoked, and leaves the target when cancelled. +- `update` calls the change under the key; a change that returns `Rejected` leaves the file unchanged; an identical result reports `applied: false`; a cancel before the rename removes the temporary file; a failed parent sync reports `unsynced`. `update_claimed` does the same under a held marker and answers `rejected` with reason `claim-lost` once the marker was reclaimed. +- `keep_replaced_as` copies the current bytes exclusively before the change; an existing entry answers `rejected`/`backup_exists` and the change does not run; a bare name is joined to the target's parent; a copy creation, write or sync failure removes the partial copy, syncs the parent and answers `io`; a change that returns `None`, `Rejected`, content equal to the current one, or an oversized `Some` (`too_large`), a cancellation before the rename, or a failed replacement removes the copy, so a later reset is not blocked; two concurrent resets leave one copy and one replacement; a concurrent `auth.json` write waits for the marker or is included in the copied bytes, and a refused change leaves no stale copy. +- `create_directory` creates each missing level below the root with mode 0700 and syncs the parent; an existing directory succeeds; a missing intermediate level is created, not an error; reserved names, their case aliases and an existing file or link at any level are `invalid` and create nothing; cancellation between levels leaves the created ancestors. +- `write`, `update`, `remove` or `import` over a credential record leaves no marker; a later `claim` proceeds without waiting. +- `import` over `max_bytes` copies nothing; a missing, non-regular or linked source is `invalid`; a destination outside every root is `invalid`. +- `list` answers one level sorted by name, omits the owner's lock, temporary and marker resources including case aliases, and answers none for an absent directory. +- `remove` of a tree with a file another writer holds waits, and cancelling ends the wait with `cancelled`; a retry after a partial removal finishes; a link is not followed. +- `add_root` answers the same id for the same path; `root_path` answers that directory; an unknown root id is `invalid`; a root id registered before a provider reload answers its directory after the reload. +- An `update` with a `None` replacement on an absent file creates nothing, answers `applied: false`, and a concurrent creator takes the key after it; an existing file stays unchanged with `applied: false`. +- The DimOAuth refresh tests: a refresh claims the marker, persists a rotated grant with one `update_claimed`, and a concurrent refresh waits and adopts it; a rejected grant writes the signed-out state under the same claim. +- A claim holder reads the record, calls `update_claimed` and only then releases; a `write`/`import`/`remove`/`update` attempted while the claim is held waits until release; a second `claim` waits. +- A claim cancelled after its id is returned but before its write releases the claim without writing. With a refresh in flight, an observation's `claim` waits, a second daemon's `claim` waits, and `refreshes == 1`. +- The managed OAuth flow tests: two concurrent callers and a rotating refresh token perform one refresh (`refreshes == 1`) and both read `rotated-1`; a write attempted between claim and commit waits for the marker; a change that sees an advanced `credentialRevision` refuses with `rejected` reason `conflict`; a reclaimed claim answers `rejected` with reason `claim-lost`; a failed refresh with a waiting loser lets the waiter claim and refresh; a writer that follows the marker waits while another caller holds the claim. +- The MCP credential flow tests: two daemons sharing a home perform one refresh while the marker is held; a write between claim and commit waits for the marker and then sees the rotated record; a sign-out holds the marker across revocation and removes only its own key's entry with `update_claimed`, leaving the file and other entries; a row unload between the token response and its write settles before the claim is released; a rejected refresh removes only its own key's record. +- The ChatGPT account flow tests: two concurrent refreshes with a rotating token perform one while the marker is held; a code exchange and a sign-out each hold the marker across their network call and persist with one `update_claimed`; a sign-out between a refresh's response and its write waits for the marker; a safe status read starts no refresh; a row unload between the response and its write settles before the claim is released; a claim from a previous account generation cannot refresh or invalidate the current one. + +Material uncertainty: a change that waits on another owner or on I/O holds the file's key for that wait. The contract forbids it; review checks each caller's change. + +## Rule check + +The rules are [design rules §7](../principles.md#7-所有者与操作) and §1–§6 of `docs/architecture/rust-agent/principles.md`. + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | FileStorage is one process part. It writes no Timeline event and folds no state, so it is not a Capability. It injects no service; the process assembly provides it. | +| §2 scopes | Process. Callers are process or Session parts and use the service as a process dependency. No branch or Session state is held. | +| §3 orthogonality | No other owner's state is read or changed. A caller that needs a new file operation gets a general operation here or composes one. | +| §4 rule 1 | No command event: FileStorage writes no Timeline fact. | +| §4 rule 2 | No handoff: the bytes and the key stay with FileStorage. | +| §4 rule 3 | No before callback: the `update` change runs under the file's own key, never inside the Timeline's commit lock. | +| §4 rule 4 | Core and assembly carry no business meaning; no document format, permission or approval appears in this contract. | +| §4 rule 5 | No batches. | +| §4 rule 6 | File content reaches the model only through tool results; the tools own that path, and FileStorage only returns bytes to the owner that asked. | +| §4 rule 7 | Callers use these operations; no caller reads a descriptor, a key or a generation. | +| §4 rule 8 | No infrastructure change and no requirement to a mechanism owner. | +| §4 rule 9 | No Timeline fact. | +| §7.1 resource and lifecycle | FileStorage owns the roots, keys, descriptors and generations; the host registers roots, the owner settles keys and temporary files on close and reload. | +| §7.1 operation granularity | One operation is one state transition or one consistent read; read ids, keys and temporary files never cross a call. | +| §7.1 owner granularity | One process owner for byte storage under roots; no second owner beside it. | +| §7.2 operations | Every cross-plugin call lands on an operation here; the sibling contracts' operations exist. | +| §7.2 handoff | Only values (paths, sizes, root ids, claim ids), read-only views (bytes, entries) and callbacks (source, change) cross; no object or handle. | +| §7.2 no proxying | FileStorage returns no other owner's resource or data. | +| §7.2 one face | One operation set on the owner type; no forwarding facade, command or host object. | +| §7.2 data face | No Rust-only method; caller-supplied arguments, replies and errors are data except the callbacks §7 allows, and `caller: &Ctx` is the dispatch's row identity, filled by the dispatch and not caller-supplied data. | +| §7.2 business boundary | No caller business concept on the face; each operation and parameter answers why it cannot be composed, in the table above. | +| §7.2 one change | The implementation task deletes the old surface, adds these operations and migrates every caller in one change. | +| ADR 002 D1 | Process scope: roots, descriptors, keys and generations outlive Sessions and are shared across them. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type; no adapter or facade exists beside it. | +| ADR 002 D3 | Dependencies point from extensions to the core; FileStorage depends on nothing and is a process service they may depend on. | +| ADR 002 D4 | Roots are structural: the host registers them, and a trusted business part may register a directory it owns; a root is addressability, and Permission decides what an agent action may do there. | +| ADR 002 D5 | The contract is language-neutral: operations, data and callbacks; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +The service is marked on the owner type; the wire name stays `fsHost`. The `FsHost` wrapper type no longer exists. `CancelledFn` is the binding's cancellation argument, not a request field. Error codes are the snake_case `code` values of the error table. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +/// Raw bytes of a whole read, an update, or one source chunk. Base64 on the wire, +/// so 8 MiB of bytes fits the 16 MiB bridge frame with the JSON envelope. +pub const DOCUMENT_LIMIT: u64 = 8 * 1024 * 1024; +pub const PAGE_LIMIT: u32 = 64 * 1024; +pub const CHUNK_LIMIT: u32 = 8 * 1024 * 1024; +pub const IMPORT_LIMIT: u64 = 8 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct Bytes(#[serde(with = "base64_bytes")] pub Vec); // a small local serde module; crosses as base64 text + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Permissions { + Private, + PrivateReadOnly, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadReply { + pub data: Bytes, + pub eof: bool, + pub size: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum StatKind { + File, + Directory, + Other, + Missing, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Stat { + pub kind: StatKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub size: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClaimReply { + pub claim_id: String, // claimId on the wire +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UpdateReply { + pub applied: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Entry { + pub name: Name, + pub kind: EntryKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EntryKind { + File, + Directory, + Other, +} + +/// A listed name is passed back unchanged: a string, or the native bytes. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum Name { + Text(String), + Unix { #[serde(rename = "Unix")] unix: Vec }, + Windows { #[serde(rename = "Windows")] windows: Vec }, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum RemoveTarget { + Path { path: String }, + Entry { parent: String, name: Name }, +} + +/// The caller's own refusal or failure from a source or a change, carried unchanged. +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[error("{reason}: {message}")] +pub struct Rejected { + pub reason: String, + pub message: String, +} + +impl Rejected { + pub fn new(reason: &str, message: &str) -> Self { + Self { reason: reason.to_owned(), message: message.to_owned() } + } +} + +/// A failed callback arrives as the wire's error; its own code becomes `reason`. +impl From for Rejected { + fn from(error: rutis::host::CallError) -> Self { + let (message, raw) = error.into_raw(); + let reason = raw + .and_then(|raw| raw.downcast::().ok()) + .and_then(|error| error.code().map(str::to_owned)) + .unwrap_or_else(|| "failed".to_owned()); + Self { reason, message } + } +} + +/// The next chunk of a write, or none at the end. +pub type SourceFn = + Arc BoxFuture<'static, Result, Rejected>> + Send + Sync>; + +/// The current content (none when absent); the next content, no write, or a refusal. +pub type ChangeFn = + Arc) -> BoxFuture<'static, Result, Rejected>> + Send + Sync>; + +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum FileError { + #[error("{message}")] + Invalid { + message: String, + #[serde(skip_serializing_if = "Option::is_none")] + path: Option, + }, + #[error("{message}")] + MissingParent { message: String, path: String }, + #[error("{message}")] + TooLarge { message: String, path: String, size: u64 }, + #[error("{reason}: {message}")] + Rejected { reason: String, message: String }, + #[error("{message}")] + Io { + message: String, + #[serde(skip_serializing_if = "Option::is_none")] + path: Option, + }, + #[error("{message}")] + Unsynced { message: String, path: String }, + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, +} + +impl PublicService for FileStorage {} + +#[rutis::service(name = "fsHost")] +impl FileStorage { + pub async fn add_root(&self, path: String, cancelled: CancelledFn) -> Result { + // ... + } + + pub fn root_path(&self, root: String) -> Result { + // ... + } + + pub async fn stat(&self, path: String, cancelled: CancelledFn) -> Result { + // ... + } + + pub async fn read( + &self, + path: String, + offset: Option, + length: Option, + cancelled: CancelledFn, + ) -> Result, FileError> { + // ... + } + + pub async fn claim( + &self, + caller: &Ctx, + path: String, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn release(&self, caller: &Ctx, claim_id: String) -> Result<(), FileError> { + // ... + } + + pub async fn write( + &self, + path: String, + source: SourceFn, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn import( + &self, + path: String, + source: String, + max_bytes: Option, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn update( + &self, + path: String, + change: ChangeFn, + keep_replaced_as: Option, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn update_claimed( + &self, + caller: &Ctx, + path: String, + change: ChangeFn, + claim_id: String, + keep_replaced_as: Option, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn create_directory( + &self, + path: String, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn list( + &self, + path: String, + cancelled: CancelledFn, + ) -> Result>, FileError> { + // ... + } + + pub async fn remove(&self, target: RemoveTarget, cancelled: CancelledFn) -> Result<(), FileError> { + // ... + } +} +``` + +`CancelledFn` is the crate's existing cancellation argument ([`host::CancelledFn`](../../../../crates/dim-agent-capabilities/src/host.rs)). `Bytes` crosses as base64 text; `Name` as a string or the native `{Unix: …}`/`{Windows: …}` object; root ids and sizes as strings and numbers. `claim`, `release` and `update_claimed` take `caller: &Ctx` because the claim is bound to the calling row; the dispatch fills it, and it is not a request field. Requests carry callbacks by reference only where the operation needs the caller's own step — the write source and the update change — plus the cancellation argument; every other argument and reply is data. + +## Current implementation + +The code at this head still exposes the lease surface that the contract above replaces. Where the two differ, the contract is authoritative and the delivery part on [#2016](https://github.com/arcships/dim/issues/2016) is the migration. The sections below record the behaviour that is not part of the contract: traversal, the account marker's wire format, creation, listing, removal and their tests. + +### Events and lifetime No Timeline events. Each `apply` opens fresh root-directory handles; blocking operations and leases are tracked by that generation. Close stops admission, @@ -26,61 +643,11 @@ opens leave `OBJECT_ATTRIBUTES.Attributes` at 0 so the actual directory's case-sensitivity setting governs lookup; forcing `OBJ_CASE_INSENSITIVE` or folding names would break case-sensitive directories and their aliases. -## Bounded reads - -`read_limited(path, limit, cancel)` preserves the same authorized-handle traversal and cancellation as `read`. It checks the opened file's length before allocating contents, then checks each chunk before extending the buffer to cover concurrent growth. Exceeding the byte limit returns `Io(InvalidData)` without partial bytes or a write. The lease's own `read_limited(limit, cancel)` applies the same rule under the held lock; `read` is its unbounded case. The business caller chooses its byte limit. - -## Filesystem data face - -`fsHost.createDirectory`, `list` and `remove` resolve absolute paths in the owner's -authorized roots. They use the directory creation, listing and removal contracts above. -Pass a listed name unchanged to `remove({parent, name})`. A Unicode name is a string. Other names carry the original Unix bytes (`{Unix: number[]}`) or Windows UTF-16 code units (`{Windows: number[]}`). The owner accepts a single component below the listed directory. - -`fsHost.stat({path})` returns the entry kind and the size of a regular file, without following links. An absent entry has kind `missing`. - -`fsHost.readBytes({path, limit, leaseId?})` returns base64 bytes and the length. A file over the limit fails with `too_large`. Hooks reads the authorized project settings path through this operation. `lock({path})` returns a lease ID for reads of that same file. `replace({path, bytes, permissions?, leaseId?})` accepts base64 bytes and atomically replaces the target under the supplied lease or a new lock. `backup({leaseId, suffix, permissions?})` creates an exclusive sibling copy under the same lease. Explicit `unlock({leaseId})` or caller unload releases the lease. +### The lease surface the contract replaces -### Pinned reads +The code's public `path`, `resolve`, `register_root`, `stat`, `lock`, `unlock`, `FileLease`, `read_limited`, `open_read`/`readAt`/`closeRead`, `replace`, `backup`, `import` with the old `PathBuf` source and required `limit`, `create_directories` and the `FsHost` wrapper are the surface the contract's `read`, `write`, `update`, `update_claimed`, `claim`, `release`, `stat`, `import` and `create_directory` replace; `add_root` and `root_path` stay on the face as named above. The code's `resolve` is this owner's path lookup; the file-tools face's `resolve` is a different operation under [#1297](https://github.com/arcships/dim/issues/1297). Their tests below stay until the migration lands. -The process `fsHost` name provides the pinned-reader operations from -[resource faces §4.1](../../../design/resource-faces.md#41-methods), using this -same FileStorage generation and reader registry. `openRead` resolves the supplied -absolute path through the existing authorized-root traversal and pins that exact -file. Replacing the path afterwards does not change the reader's bytes. - -The wire `openRead` operation requires a calling row to own retention; `readAt` -and `closeRead` require only the reader id. These are trusted-plugin operations: -an id identifies a reader, not caller authorization, and a plugin that receives -another row's id can read or close it. Readers opened through native -`FileStorage::open_read` have no caller retention to release through this face; attempting to close such an id returns `invalid` -without unregistering it. - -`readAt` keeps the existing maximum of 64 KiB and independent offsets. Zero limit -or an offset at/past the pinned length returns empty bytes. The wire encodes bytes -as base64; the native binding reads the same reader id directly. Unknown, closed -or prior-generation ids are `invalid`; unavailable storage is `node_unavailable`, -a missing file is `not_found`, cancellation is `cancelled`, and other existing -I/O failures are `io`. No extra read or normalization follows the owner's result. - -The calling row retains an opened reader until `closeRead` or that row's unload; -registration finishes before `openRead` returns. Close removes the id before -releasing retention, while reads already accepted finish under the owner's -existing operation tracking. Dropping close before it is polled does nothing; -once close removes the id, the existing context cleanup continues even if its -wait is dropped. FileStorage close drains those operations and -releases the same pinned handles, including readers retained by a caller. There -is one reader registry and no separate connection table or read queue. - -In the Rust binding, `FsHost::open_read` takes the calling part's `&Ctx` and -cancellation token along with the path. The context supplies the same cleanup -registration that the wire binding obtains from its calling row; it is not a -request field. Both return only `OpenRead {read_id, size}`. The public `FsHost` -binding has these three operations, no owner dereference or native file handle; -its methods directly return the existing owner's operation futures. Native -FileStorage readers outside this face retain their original weak-registry/RAII -lifetime while sharing the same generation's shutdown. - -## Leases and lock keys +### Lock keys A lease locks a key file with the target's name in the reserved `.dim-file-storage-locks` directory beside the target, so the filesystem's own @@ -126,9 +693,8 @@ A reused PID, a permission-denied process probe or a missing PID or creation time does not establish ownership. The exception is a marker this process failed to release: it keeps the owner record, whose nonce only that marker carries, and reclaims the marker at once, so removal and locking need -not wait for the process to exit. The marker is the external TypeScript wire -format: PID, milliseconds since the Unix epoch (`Date.now()` in TypeScript), -nonce and a trailing newline, with no other fields. Writers must use +not wait for the process to exit. The marker is the published marker format: PID, milliseconds since the Unix +epoch, nonce and a trailing newline, with no other fields. Writers must use milliseconds, not seconds. The start-time comparison on macOS, Linux, Android and Windows assumes wall-clock @@ -140,7 +706,9 @@ On Windows, releasing a `PhysicalLock` unlocks its byte range explicitly before release completes, because `CloseHandle` may defer the implicit unlock; a later generation would otherwise see a stale `Locked` lock. -## Directory creation +### Directory creation + +The contract's `create_directory` makes the whole path an existing tree; the code below creates one level per call and `create_directories` composes the levels. `create_directory` makes a path below an authorized root an existing business directory, one level at a time: its parent must exist and is reached as every @@ -183,7 +751,9 @@ fails `InvalidPath` and is left untouched, and so does an alias of a reserved resource; the returned path therefore names the result without a followed link. This is the primitive for handing a work directory to a helper process. -## Listing and removal +### Listing and removal + +The contract's `remove` waits for a held key; the code below answers `Locked`. `list` returns the entries of a directory below an authorized root, sorted by name, each a `File`, `Directory` or `Other` (a link, reparse point or special @@ -311,7 +881,7 @@ removal of its directory therefore resolves its key again or returns another removal of the same tree treats what the other deleted as removed, and starts again from its target if a directory it returns to was deleted. -## Tests +### Tests [file_storage_flow.rs](../../../../crates/dim-agent-capabilities/tests/file_storage_flow.rs): `late_roots_preserve_indices_and_generation_boundaries_on_reload`, @@ -343,27 +913,3 @@ public API cannot produce reliably. | 提供 | `P:FileStorage`、`P:FsHost`、`P:dyn HostDispatch#fsHost` | | 被注入于 | `HostPlatform` | - -## Native streaming reads - -`resolve(absolute)` identifies an existing authorized root without adding one; -paths use the root's canonical spelling. `open_read(path, cancel)` traverses held -directory handles and pins a regular file. Its `FileReader` reports the length -at open and reads at explicit offsets, at most 64 KiB per call. Concurrent reads -serialize access to the pinned descriptor; replacing a pathname does not change -an existing reader. The producer keeps published files unchanged in place. - -Readers belong to the storage generation. Closing refuses new work, drains -accepted reads and closes retained descriptors. Caller cancellation is checked -before and after each bounded read. This native interface does not export binary -callbacks through the language bridge. UiResources uses it for the protected -resource routes in the [client UI contract](../../../design/client-ui-extensions.md). - -## Path import - -`import(path, source, limit, permissions, cancel)` copies an authorized absolute -source file into the authorized destination using `replace_from`. It opens and -pins the source, requires a regular file within the caller's limit, and rejects -length changes during copying. On Unix the open is nonblocking and rejects a -terminal symlink. The destination follows the existing lease, atomic replacement, -permissions and cancellation contract. The operation returns the copied byte count. diff --git a/docs/architecture/rust-agent/plugins/Hooks.md b/docs/architecture/rust-agent/plugins/Hooks.md index e147caa8c6..5133b48700 100644 --- a/docs/architecture/rust-agent/plugins/Hooks.md +++ b/docs/architecture/rust-agent/plugins/Hooks.md @@ -45,7 +45,7 @@ The runtime reads sources when a hook point is evaluated, never at Session start: a change to the user's `hooks.json` or to a project document applies to the next hook point, and the catalog is recomputed rather than cached. Reading is a `S:HookSourcesHost` call, which the App Server binds to Settings and -`fsHost.readBytes`; a Session whose host binds no sources (the scripted model +FileStorage's [`read`](FileStorage.md); a Session whose host binds no sources (the scripted model assembly) sees an empty catalog. `DIMCODE_HOME` comes from the same port, so a Session started by a product daemon passes the daemon's product home into every hook command and a Session without one sets nothing. diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index e2dadab46a..b87c7ad118 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -67,7 +67,7 @@ the directory (ADR 013 D4). An absent directory counts as removed. detected shell choices, returning the byte revision, optional explicit executable and any parse error. `update_exec_shell_settings(expected_revision, executable_path, cancel)` validates the selection with the same resolver used by execution, then -replaces the preference atomically under a FileStorage lease if its byte revision +replaces the preference atomically with FileStorage's [`update`](FileStorage.md) if its byte revision still matches. An absent executable selects automatic detection; a malformed preference can be repaired using its current revision. Missing files have revision `absent`. App Server exposes these operations as trusted local management methods diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index 1fd80891c6..3f275a7da9 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -45,7 +45,7 @@ dependency is not necessarily a plugin with the same name. | [Loop](Loop.md) | — | [LoopMethods](LoopMethods.md) | Loop | | [ModelProvider](ModelProvider.md) | — | — | ModelProvider | | [HostPlatform](HostPlatform.md) | HostPlatform | — | — | -| [FileStorage](FileStorage.md) | FileStorage | — | — | +| [FileStorage](FileStorage.md) (owner contract) | FileStorage | — | — | | [Hooks](Hooks.md) | — | HooksSession, HookSources (App Server) | HooksBranch | App Server optional plugins are outside this local-execution profile. [Web](../../../design/plugins/Web.md) provides `web_search` and `web_fetch` through a Session part its `web` process row registers; it adds no service to the assembly recorded here. diff --git a/docs/architecture/rust-agent/single-tree.md b/docs/architecture/rust-agent/single-tree.md index eee6b1dcfc..2aec26e0ed 100644 --- a/docs/architecture/rust-agent/single-tree.md +++ b/docs/architecture/rust-agent/single-tree.md @@ -134,7 +134,7 @@ loader 的 `create_instance` 仍先等待行 settled;异步 apply 一直不返 | Plugin | 拥有 | 提供 | `Deps` | | --- | --- | --- | --- | | `ServerControlPlugin` | 就绪门闩、正常/强制关闭意图、监听器故障 | `ServerControl` | — | -| `FileStoragePlugin` | 文件操作准入、锁租约、在途 I/O 和原子替换清理 | `FileStorage` | — | +| `FileStoragePlugin` | 文件操作准入、锁与凭据 marker、在途 I/O 和原子替换清理 | `FileStorage` | — | | `SqliteStoragePlugin` | 共享数据库连接、事务、原生 schema 门禁、文件维护锁与关停 | `SqliteStorage` | —;启动参数固定数据库路径 | | `SessionStorePlugin` | 原生会话目录、Timeline 落盘/恢复及写入任务 | `store` 数据接口、`sessionFiles`、`sessionMetadata`、`worktreeAssociations`,以及原生 `SessionStore` / `TimelineStore` 绑定 | `SqliteStorage` | | `SettingsPlugin` | Generic BusinessDocument sources and per-source CAS; no domain interpretation, approvals, connections or discovery | `SettingsService` | `FileStorage`, `When` | diff --git a/docs/design/appserver/mcp-oauth.md b/docs/design/appserver/mcp-oauth.md index 42e226f36b..aed3f2af1d 100644 --- a/docs/design/appserver/mcp-oauth.md +++ b/docs/design/appserver/mcp-oauth.md @@ -36,7 +36,7 @@ flow, and the gaps rmcp leaves, three of them MUSTs of the specification (Append | [rmcp pin](../../../crates/dim-app-server/Cargo.toml), feature `auth` (`src/transport/auth.rs`) | The `auth` module covers metadata discovery, DCR and CIMD client selection, PKCE and `state`, code exchange with `resource` and `iss`, and refresh with rotation. The `CredentialStore` and `StateStore` traits are pluggable. It shares the reqwest 0.13 already used by the transport | The protocol engine; gaps in Appendix A | | Claude Code (`/mcp`, `claude mcp login`, [docs](https://code.claude.com/docs/en/mcp)) | The `oauth` object in `.mcp.json`: `clientId`, `callbackPort`, `authServerMetadataUrl`, `scopes`. Redirect `http://localhost:PORT/callback`; a switch to `127.0.0.1` broke servers that match the registered URI exactly and was reverted. Paste the callback URL when the redirect fails. The client secret is kept out of config. Refresh, then retry once, on `401` | The `oauth` field names and types, the redirect form, the paste fallback, the secret outside config | | MCP TypeScript and Python SDKs (`OAuthClientProvider`, `TokenStorage`) | Storage and redirect handling are injected by the host. Credentials carry an issuer stamp and are discarded on mismatch. `invalid_client` clears the registration and `invalid_grant` clears the tokens | Owner-supplied storage, issuer binding, clearing rules | -| Dim account login (`account.login.browser.begin/complete`, `managed_oauth.rs`, `dim-cli/src/login.rs`) | The daemon returns `{attemptId, authorizationUrl, expiresAt}`. The client sends back the pasted callback URL, read with hidden input. Tokens live in `auth.json` under the home root, through a FileStorage lease with atomic 0600 replace | The attempt shape, paste input, the storage pattern | +| Dim account login (`account.login.browser.begin/complete`, `managed_oauth.rs`, `dim-cli/src/login.rs`) | The daemon returns `{attemptId, authorizationUrl, expiresAt}`. The client sends back the pasted callback URL, read with hidden input. Tokens live in `auth.json` under the home root; a login commits with one `update`, and a refresh claims the marker and writes with `update_claimed`, with atomic 0600 replace | The attempt shape, paste input, the storage pattern | ## 3. Structure @@ -89,16 +89,8 @@ source or the Session (§10 D8). - **Self-contained.** The record carries the token and revocation endpoints and the client's authentication method, so refresh and sign-out need no new discovery. A record is written when an attempt completes, with its client and tokens; an abandoned attempt leaves nothing. -- **Write path.** A write takes the store's FileStorage lock, re-reads the file, replaces only its - own key's record and atomically replaces the file with mode 0600. On Windows the file keeps the - FileStorage DACL handling. A replace that is in place but whose sync failed counts as written: - readers already see it, and a crash that loses it ends like the kill in §7. -- **Token requests hold the lock.** A code exchange, refresh or revocation holds that lock from - the re-read through the request to the replace, as the managed OAuth host does. Two daemons - can share a home (for example `--product-home` with different `--database` paths), and the - lock stops both from redeeming one rotating refresh token. Token requests for different servers - therefore wait on each other, each bounded by its 30 s timeout; they are rare. Discovery and - registration run outside the lock. +- **Write path.** A write claims the file's marker with `claim(caller, path, cancelled)` ([FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md)), then runs one `update_claimed`: the change receives the current content and returns it with only its own key's entry replaced, and the owner atomically replaces the file with mode 0600 under the held marker. The claim is released after the write, successfully or not. On Windows the file keeps the FileStorage DACL handling. A replace that is in place but whose sync failed counts as written: readers already see it, and a crash that loses it ends like the kill in §7. +- **Token requests hold the claim.** A code exchange, refresh or revocation claims the marker before reading the current content and holds it through the request to the write-back, as the managed OAuth host does. Two daemons can share a home (for example `--product-home` with different `--database` paths), and the marker stops both from redeeming one rotating refresh token. Token requests for different servers therefore wait on each other, each bounded by its 30 s timeout; they are rare. Discovery and registration run outside the claim. - **Settled once sent.** A token request that has been sent is received and persisted on `McpAuth`'s own task, whoever is waiting for it, so neither the caller's departure nor an unload loses a rotated refresh token or a redeemed code. Mcp's unload waits for it. A code exchange @@ -117,11 +109,11 @@ source or the Session (§10 D8). | --- | --- | --- | | Challenge | Per key: the last `WWW-Authenticate` (`resource_metadata`, `scope`, `error`) seen by any connection | Until authorization succeeds, sign-out or Mcp reload | | Attempt | `attemptId`, key, PKCE verifier, `state`, expected `issuer`, metadata, client, redirect URI, scopes, `expiresAt` | At most one per key; ends on complete, expiry (10 min), sign-out or a new start for the same key (§7) | -| Attempts lock | One in-process async lock over every key's attempt and completed sign-outs: the single order of attempt state (§7). Its holders never wait for the store lock or a network request | Mcp generation | -| Store lock and change watch | One in-process async lock in front of the FileStorage lock, which admits or fails at once, so a lock held by another process is retried, as the managed OAuth host does; plus a watch per key, notified on every change to the key's record with whether it holds tokens: Sessions waiting in `auth_required` retry on any change, and ready Sessions react when the tokens are gone | Mcp generation | +| Attempts lock | One in-process async lock over every key's attempt and completed sign-outs: the single order of attempt state (§7). Its holders never wait for the store claim or a network request | Mcp generation | +| Store claim and change watch | One in-process async lock in front of FileStorage's `claim`/`update_claimed`: it admits one local token request or write per key at a time, and the marker excludes other daemons; a marker another daemon holds is waited for, not failed; plus a watch per key, notified on every change to the key's record with whether it holds tokens: Sessions waiting in `auth_required` retry on any change, and ready Sessions react when the tokens are gone | Mcp generation | The PKCE verifier and `state` are never persisted. A daemon restart abandons pending attempts. -There is no record cache: each request reads the file without the lock, which is safe because +There is no record cache: each request reads the file without the claim, which is safe because writes are atomic replaces, and sees a refresh made by another daemon on the same home. ### 4.3 Configuration (`mcp` business source) @@ -227,7 +219,7 @@ discovery, which follows the specification's order with the additions listed in authorization server, nothing recorded for the old one is used. A DCR or CIMD client is registered again. A configured `oauth.clientId` is refused with `mcp_auth_client_required`, since the specification asks for an error rather than mismatched credentials; signing out - deletes the record, and the next `start` binds the configured client to the new issuer. While a + removes the key's entry, and the next `start` binds the configured client to the new issuer. While a server stays signed in, a switch of authorization server shows up as `401` after refresh, so the record becomes `expired` and the next `start` finds the change. @@ -303,13 +295,13 @@ be retried: | | | | |-- lease(K) -------------------------------->| | | | | 30 s or more left: | - | | | reply; else lock store, | + | | | reply; else claim store, | | | | re-check, refresh | | |-- lease(K) --------->| | - | | | (waits for the lock) | + | | | (waits for the claim) | | | |-- refresh, resource -------->| | | |<-- access, rotated refresh --| - | | | persist, unlock | + | | | persist, release | |<-- lease r2 --------------------------------| | | |<-- lease r2 ---------| | | MCP: 401 on r2 | | | @@ -331,7 +323,7 @@ be retried: record still holds `rN`; otherwise another Session has already refreshed. The request is retried once. A rejected request was not processed by the server, so retrying it repeats no effect. - **Single flight.** One refresh runs per key at a time across all Sessions: a waiter that gets - the lock re-reads the record and finds the new token. + the claim re-reads the record and finds the new token. - **Rotation.** A new refresh token replaces the old one. If none is returned, the old one is kept. The new record is persisted before any lease uses the new access token. - **Reauthorization.** `invalid_grant`, `invalid_client`, a token without a refresh token that @@ -360,14 +352,18 @@ that carries the header to `InsufficientScope`. ### 5.8 Sign-out `mcp.auth.logout` revokes the refresh token, then the access token, through the authorization -server's `revocation_endpoint` (RFC 7009) when one is advertised. It then deletes the record, -including the registration and any client secret, whatever the revocation outcome. The reply -says whether revocation succeeded. Every Session on the key then reports `auth_required`. -From the moment it is accepted, sign-out closes the key's pending attempt, and it closes any -attempt started before it completes, so a sign-in already under way in the same daemon cannot -undo it (§7). +server's `revocation_endpoint` (RFC 7009) when one is advertised. It holds the store claim from +before the revocation, then removes only its own key's entry with one `update_claimed`, +including the registration and any client secret, whatever the revocation outcome. The file and +other keys' entries stay; an empty `credentials` array is valid, and deleting the file under the +claim would require releasing it first, so sign-out does not delete it. The claim is released +after the write, successfully or not. The reply says whether revocation succeeded. Every Session +on the key then reports `auth_required`. From the moment it is accepted, sign-out closes the key's +pending attempt, and it closes any attempt started before it completes, so a sign-in already under +way in the same daemon cannot undo it (§7). Sign-out is also allowed once an entry no longer uses OAuth (static credentials added, or a -cleartext URL), so a stored credential can always be removed. +cleartext URL), so a stored credential can always be removed. This sign-out decision is tracked by +[#2022](https://github.com/arcships/dim/issues/2022). `mcp.remove` does not touch credentials, because an entry of the same `id` and URL in another source may still use them; the CLI offers sign-out first (§13). An orphaned record is inert: its @@ -390,8 +386,8 @@ Each node is the catalog's `auth.status` for one key. `refreshing` is internal a +---- logout, from required, authorized or expired ``` -`absent`: Dim holds no record for the key and no recorded challenge. Sign-out deletes the record -and clears the challenge. The catalog then has no `auth` field. +`absent`: Dim holds no record for the key and no recorded challenge. Sign-out removes the key's +entry and clears the challenge. The catalog then has no `auth` field. ## 7. Timing and conflicts @@ -405,19 +401,19 @@ in another daemon sharing the home after a sign-out is a later sign-in. when it completes, `cancel` to close its named current attempt, `complete` to validate a callback, and the exchange for both currency checks. The exchange holds it from its final check until its outcome is published. Its holders never -wait for the store lock or a network request, so waiting for it takes at most one local store +wait for the store claim or a network request, so waiting for it takes at most one local store write, never a token request or a refresh. Every `start` and `logout` is therefore ordered either before an exchange's final check, which then finds its attempt superseded, or after its publication: a newer attempt that completes later replaces the stored credential, and a -sign-out deletes and revokes it. A superseded attempt never writes the store or wakes Sessions +sign-out revokes and removes it. A superseded attempt never writes the store or wakes Sessions after a newer `start` has returned. - **`start`** makes its attempt current when it returns, replacing the previous one. A publication under way holds the attempts lock, so the new attempt becomes current after it. If a sign-out completed after `start` read the record, `start` answers `mcp_auth_attempt_closed` - instead, because its attempt may reuse a client that the sign-out deleted. -- **`logout`** closes the current attempt when it is accepted, before it waits for the store lock. - It closes the attempt again once it has deleted the record, which ends an attempt started in + instead, because its attempt may reuse a client that the sign-out removed. +- **`logout`** closes the current attempt when it is accepted, before it waits for the store claim. + It closes the attempt again once it has removed the entry, which ends an attempt started in the meantime. - **`cancel`** closes only the named current attempt. It leaves an existing grant intact and does not interrupt a token request already sent; that exchange settles and revokes any tokens @@ -425,7 +421,7 @@ after a newer `start` has returned. closed without undoing the published grant. - **`complete`** ends the attempt when its exchange settles, except after a transport error (§5.4). An authorization server error in the callback, or expiry, ends it too. -- **The exchange** checks that its attempt is still current twice: after it takes the store lock, +- **The exchange** checks that its attempt is still current twice: after it takes the store claim, before it sends the token request, and when the response is in, before it writes the store. From the second check it holds the attempts lock until its outcome is published: the record written, the challenge and missing scopes cleared and the Sessions woken; after @@ -433,14 +429,14 @@ after a newer `start` has returned. - Superseded before the request: the code is never sent. - Superseded while the request was out: the request is still settled (§4.1). Tokens it obtained are revoked (RFC 7009, best effort, the refresh token first) and discarded. The - revocation runs while the store lock is still held, so it precedes any later token request. + revocation runs while the store claim is still held, so it precedes any later token request. Nothing is written to the store, whatever the response, and no Session is woken. - Either way `complete` answers `mcp_auth_attempt_closed`. - Current at the final check: the outcome is published before any later `start` or `logout` takes effect. The code is spent, so the attempt ends even if the record cannot be written; the tokens are then revoked once the attempts lock is released. -- **A refresh** needs no such check. It re-reads the record under the store lock, so it sees any - sign-in or sign-out that held the lock before it, and one that holds the lock after it +- **A refresh** needs no such check. It re-reads the record under the store claim, so it sees any + sign-in or sign-out that held the claim before it, and one that holds the claim after it replaces or deletes its result. | Race | Outcome | @@ -448,10 +444,10 @@ after a newer `start` has returned. | Two `start` calls for one key | The later to return replaces the earlier; completing the earlier is `mcp_auth_attempt_closed` | | `start` while a `complete` is under way | Until the old exchange's final check, the new attempt supersedes it: a code not yet sent is never sent, tokens already obtained are revoked and discarded, and `complete` answers `mcp_auth_attempt_closed`. After that check, `start` becomes current only once the old exchange has written its record and woken the Sessions; completing the new attempt replaces that record | | Two `complete` calls for one attempt | One exchange at a time: the second answers `mcp_auth_attempt_closed` at once. After a transport error the attempt is pending again | -| `logout` while an attempt is pending or under way | The attempt closes when `logout` is accepted. An exchange still waiting for the store lock sends nothing; one whose request is out discards its tokens; one past its final check publishes first, and `logout` is accepted after it. `logout` then deletes the record and revokes its tokens | +| `logout` while an attempt is pending or under way | The attempt closes when `logout` is accepted. An exchange still waiting for the store claim sends nothing; one whose request is out discards its tokens; one past its final check publishes first, and `logout` is accepted after it. `logout` then revokes its tokens and removes its entry | | `start` while `logout` runs | If the sign-out completes before `start` returns, `start` answers `mcp_auth_attempt_closed`; an attempt `start` made current before then closes when the sign-out completes | -| `complete` while a refresh runs | Both hold the store lock in turn: a refresh after `complete` finds fresh tokens and does nothing; `complete` after a refresh replaces the tokens | -| `logout` while a refresh runs | `logout` takes the store lock after it; the refreshed tokens are revoked and deleted. A refresh after `logout` finds no record | +| `complete` while a refresh runs | Both hold the store claim in turn: a refresh after `complete` finds fresh tokens and does nothing; `complete` after a refresh replaces the tokens | +| `logout` while a refresh runs | `logout` takes the store claim after it; the refreshed tokens are revoked and deleted. A refresh after `logout` finds no entry | | Two Sessions get `401` together | One refresh (§5.6); both retry with the new lease | | Entry URL edited | New key, so the new generation starts `absent` and becomes `required` on its first `401`; the old record is inert | | Entry disabled or removed during an attempt | The attempt may still complete and persist; nothing connects until the entry is enabled | @@ -541,15 +537,15 @@ callback URLs or authorization server `error_description` text from an unvalidat | D6 | The callback always returns through `mcp.auth.complete {attemptId, callbackUrl}`; the CLI captures it with a loopback listener, or the user pastes it | A loopback listener in the daemon is a new external entry inside a business owner and is unreachable over SSH anyway; one long call with progress would hold an RPC open for minutes and still need a listener; the device flow is not in the MCP specification | | D7 | Four methods, all `report`; explicit cancellation closes a pending attempt without undoing a published grant; no attempt-status polling | `drain` would hold Mcp's unload behind authorization-server calls and break the uniform `mcp.*` rule. Leaving the UI must not cancel a submitted exchange, but an explicit cancel must prevent a still-pending attempt from later publishing. Polling has nothing to poll, because no background party completes an attempt | | D8 | Credential key = server `id` + canonical URL, process-wide; the record binds `resource` and `issuer` | A URL-only key allows one account per server; `(source, id)` lets a token follow a name to a new URL; per-Session keys contradict process ownership (ADR 002 D1) | -| D9 | Store `mcp-oauth.json` under the home root through FileStorage, atomic 0600 replace, versioned; token requests hold the store lock and settle once sent. S8b adds no credential service, so nothing migrates: tokens are owner state that each refresh rewrites, and every owner handles its own secrets ([settings-service §1.2](settings-service.md#12-decision-secrets-belong-to-their-owner)); every other OAuth holder follows the same rule | The Settings rows in SQLite hold business documents, not secrets; `pluginFiles` is FileStorage's bridge API for non-Rust plugins, while a Rust owner uses FileStorage directly, as the managed OAuth host does; an OS keychain needs a host-wide secret-store decision that covers every OAuth owner; waiting for S8b blocks on an API that cannot hold rotating secrets | +| D9 | Store `mcp-oauth.json` under the home root through FileStorage, atomic 0600 replace, versioned; token requests hold the file's published marker claim and settle once sent. S8b adds no credential service, so nothing migrates: tokens are owner state that each refresh rewrites, and every owner handles its own secrets ([settings-service §1.2](settings-service.md#12-decision-secrets-belong-to-their-owner)); every other OAuth holder follows the same rule | The Settings rows in SQLite hold business documents, not secrets; `pluginFiles` is FileStorage's bridge API for non-Rust plugins, while a Rust owner uses FileStorage directly, as the managed OAuth host does; an OS keychain needs a host-wide secret-store decision that covers every OAuth owner; waiting for S8b blocks on an API that cannot hold rotating secrets | | D10 | Refresh on use with a 30 s margin, plus refresh and one retry on `401`; single flight per key; persist rotation before use | Background refresh timers wake the daemon for idle servers and rotate tokens nobody uses | | D11 | Step-up is user-initiated: the call fails with fixed text, and the next sign-in requests the union | Automatic re-authorization from a tool call needs a browser in the middle of a turn | -| D12 | Sign-out revokes (RFC 7009, best effort) then deletes the whole record; `mcp.remove` leaves credentials | Deleting on `mcp.remove` cannot know whether another source's entry with the same key still uses them | +| D12 | Sign-out revokes (RFC 7009, best effort) then removes the key's entry; the file and other keys' entries stay; `mcp.remove` leaves credentials | Deleting on `mcp.remove` cannot know whether another source's entry with the same key still uses them; deleting the file under a held claim is not expressible, and an empty `credentials` array is valid | | D13 | `session.mcp` gains `auth_required`, which clears by itself; the catalog gains `auth` | Reusing `failed` would require a manual refresh after sign-in and gives the CLI nothing to act on | | D14 | `start` requires an enabled entry; sign-out is always allowed; one key is shared across sources | Sign-in on a disabled project entry would contact a URL from project files before the user enabled it (ADR 003 D3) | | D15 | An entry with static credentials never uses OAuth; OAuth needs `https` or loopback `http` | Falling back to OAuth after a static credential fails mixes two credential sources; a bearer token over cleartext can be stolen | | D16 | Require same-origin PRM: the `resource_metadata` URL must be same-origin, and `resource` may be the server URL or a parent path on the same origin | RFC 9728 does not require a same-origin metadata URL; accepting another origin would let any `401` point discovery at another host. RFC 9728 asks for an identical `resource`; requiring it would mean replacing rmcp's validation, while the parent-path rule keeps the token audience inside the server's origin | -| D17 | Attempt currency (§7): the `attemptId` identifies an attempt, and only the key's current attempt redeems its code, checked after the store lock and again after the token response. One attempts lock orders every change of attempt state; the exchange holds it from the second check until its outcome is published, so a later `start` or sign-out takes effect after the publication. Sign-out closes attempts when it is accepted and when it completes; a `start` prepared before a completed sign-out is refused. A superseded request already sent is settled, and its tokens are revoked best effort under the store lock and discarded. Holding the store lock orders the revocation before a newer attempt's exchange: a server that revokes a whole session then refuses the newer code at sign-in, instead of leaving a stored credential that is already dead | Checking only before the request lets a response still in flight overwrite a newer attempt. Ending the attempt before the store write and publishing after it lets a newer `start` return while the write is pending, so a superseded attempt stores and wakes after the newer one is current. Writing first and rolling back when superseded lets lock-free readers use the tokens in between, and a failed rollback leaves them stored. Cancelling a request in flight breaks "settled once sent" (§4.1): a redeemed code would leave live tokens nobody knows about. Storing them and leaving cleanup to a later sign-out undoes a sign-out the user has already completed. Discarding without revocation leaves the tokens valid at the authorization server until they expire. Taking the store lock in `start` would queue each sign-in behind refreshes of up to 30 s. A generation counter per attempt would duplicate the `attemptId` | +| D17 | Attempt currency (§7): the `attemptId` identifies an attempt, and only the key's current attempt redeems its code, checked after the store claim and again after the token response. One attempts lock orders every change of attempt state; the exchange holds it from the second check until its outcome is published, so a later `start` or sign-out takes effect after the publication. Sign-out closes attempts when it is accepted and when it completes; a `start` prepared before a completed sign-out is refused. A superseded request already sent is settled, and its tokens are revoked best effort under the store claim and discarded. Holding the store claim orders the revocation before a newer attempt's exchange: a server that revokes a whole session then refuses the newer code at sign-in, instead of leaving a stored credential that is already dead | Checking only before the request lets a response still in flight overwrite a newer attempt. Ending the attempt before the store write and publishing after it lets a newer `start` return while the write is pending, so a superseded attempt stores and wakes after the newer one is current. Writing first and rolling back when superseded lets lock-free readers use the tokens in between, and a failed rollback leaves them stored. Cancelling a request in flight breaks "settled once sent" (§4.1): a redeemed code would leave live tokens nobody knows about. Storing them and leaving cleanup to a later sign-out undoes a sign-out the user has already completed. Discarding without revocation leaves the tokens valid at the authorization server until they expire. Taking the store claim in `start` would queue each sign-in behind refreshes of up to 30 s. A generation counter per attempt would duplicate the `attemptId` | | D18 | The OAuth HTTP client is built by the first operation that contacts an authorization server and kept for the Mcp generation. A build failure surfaces from that operation as `mcp_auth_unavailable`; Mcp's assembly succeeds | Building it at assembly allocates TLS and resolver state for entries that never sign in. A global HTTP service or a completed-request cache would own another part's resources and still need the same policy and budget at the point of use | ## 11. Security @@ -692,7 +688,7 @@ no second HTTP stack. The `xtask check` dependency rules are re-run with the cha | `configure_client` and `register_client` (DCR); CIMD is not used (§5.3) | Does not persist `client_secret` | The record keeps it and re-applies it per operation | | `get_authorization_url` (PKCE `S256`, `state`, `resource`; verifier, `state` and expected issuer kept in Mcp's in-memory `StateStore`) | Its own selection unions previously requested, challenged and PRM scopes, and falls back to the authorization server's `scopes_supported` when that is empty | Passes the scopes chosen per §5.5 | | Nothing | `AuthorizationCallback::from_redirect_url` ignores `error` and does not compare the redirect URI; `exchange_code_for_token_with_issuer` logs the code at `debug` | Mcp parses and validates the callback, `iss` included, and sends the code exchange itself (§5.4) | -| Nothing (`refresh_token` is not used, D1) | `refresh_token` takes `resource` from in-memory discovery state or the base URL and reports `invalid_client` only as text | Mcp's own refresh request under the store lock, with re-check and rotation (§5.6) | +| Nothing (`refresh_token` is not used, D1) | `refresh_token` takes `resource` from in-memory discovery state or the base URL and reports `invalid_client` only as text | Mcp's own refresh request under the store claim, with re-check and rotation (§5.6) | | `StreamableHttpClientTransport` | Its worker waits for the first message without observing cancellation, so closing a transport that never sent one does not finish | The handshake is polled once before cancellation is honored | | `StreamableHttpError::AuthRequired` and `InsufficientScope` | Any `403` that carries `WWW-Authenticate` is `InsufficientScope` | Mcp reads `error="insufficient_scope"` | | Nothing | No RFC 7009 revocation | One request per token in `mcp.auth.logout` | @@ -718,11 +714,13 @@ tests, using an isolated home: is persisted, and the old one is never sent again. A refresh in flight when Mcp unloads is still persisted. 4. **Shared refresh.** Two Sessions get `401` at the same time: the authorization server sees - exactly one refresh, and both requests succeed on retry. + exactly one refresh, and both requests succeed on retry. A second daemon on the same home + waits for the `mcp-oauth.json.lock` marker and adopts the rotated record instead of refreshing + again. 5. **Reauthorization.** A `401` after refresh, or `invalid_grant`, gives `expired` and `auth_required`. A new sign-in recovers both Sessions. -6. **Sign-out.** `logout` sends revocation, deletes the record and replies `revoked: true`. The - next request ends `auth_required`. +6. **Sign-out.** `logout` sends revocation, removes the key's entry and replies `revoked: true`; + the file and other keys' entries stay. The next request ends `auth_required`. 7. **Refusals.** None of these sends a token request: - a wrong `state`, redirect path or `iss` (the attempt stays pending); - metadata without `code_challenge_methods_supported`; @@ -742,10 +740,10 @@ tests, using an isolated home: 13. **Superseded attempts.** Each race is held open at the mock authorization server, or at the store write through the `testing` feature's hook, because FileStorage cannot be paused from outside: - - While a refresh holds the store lock, a sign-out closes the pending attempt and its + - While a refresh holds the store claim, a sign-out closes the pending attempt and its callback is refused. The code is never sent, nothing is stored, and the Sessions require sign-in. - - A newer `start` supersedes an attempt whose exchange waits for the lock; its code is never + - A newer `start` supersedes an attempt whose exchange waits for the claim; its code is never sent. A second callback for that attempt is refused while it waits. - A newer `start` supersedes an attempt whose token request is out; the tokens are revoked and never stored or used. diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index adad6399f9..879301d97a 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -90,7 +90,7 @@ are Rust methods over the native store, not services: only Agents calls them. | delete(S) ->| | | | | | 1 take S's admission gate | | | | | 2 loaded? close() ---------->| settle accepted work, write terminal facts, - | | | release processes, leases, member requests; + | | | release processes, keys and claims, member requests; | |<-------------- closed -------| | | | | delete_session(S) ------------------------------->| | | | | 3 remove command-output/S, parent synced ---->| @@ -122,7 +122,7 @@ are Rust methods over the native store, not services: only Agents calls them. `SessionHold`, a Scheduler run through the `sessions` service takes a lease) or appends after the close, which the branch refuses. 2. **Close.** If S is loaded, Agents closes it as `session.close` does: a business close, not an unload. Its - capabilities settle their accepted work, write their terminal facts and release processes, FileStorage leases and + capabilities settle their accepted work, write their terminal facts and release processes, FileStorage's keys, claims and in-flight calls, and member requests. A close that reports cleanup errors is logged and the delete continues: the facts it could not write are removed with the rest. From the close on, S's slot is closed: S does not load again in this process, whether or not its rows go (step 6). @@ -174,7 +174,7 @@ are Rust methods over the native store, not services: only Agents calls them. | Output ownership | Native store, `session_output_owners` rows (v29, [ADR 013](../../adr/013-command-output-ownership.md) D1) | Step 4, same transaction | | Worktree usage associations | Native store, `session_worktrees` rows ([worktree access §4](../worktree-access.md#4-持久使用关联与清理边界)) | Step 4, same transaction; directory records and worktree files remain | | Exec output, offloaded `read` results and persistent shell logs | `/command-output//` and every directory named by S's output rows | Step 3. A directory another Session in this database still names is kept | -| Loaded instance, leases, subscriptions, in-flight uses | Process memory | Step 2 | +| Loaded instance, Session leases, subscriptions, in-flight uses | Process memory | Step 2 | | Protocol version, admission slot, unavailable-Session entry | Agents, in memory | Step 6 | | Collaboration relations that name S, the member Sessions S leads and the Agents S owns | Durable: `agent_sessions.leader_session_id` and `agents.owner_session_id` ([Collaboration §6](../plugins/Collaboration.md#6-delegation-ownership-and-lifetime)); Collaboration's relations are rebuilt from them | Agents deletes a leader with its Team: each member's own delete, in which SessionStore removes that Session's rows, then the Agent records Agents owns, then S. Collaboration drops a relation when it observes a member's close ([collaboration.rs](../../../crates/dim-app-server/src/collaboration.rs) `session_ended`) or the delete of an unloaded member, and rebuilds the rest when it loads ([idle unload §7](idle-unload.md#7-races-and-interactions)) | @@ -210,12 +210,14 @@ Every step tolerates an absent target, so a delete can be retried after any fail | `session_protocol_version` | Only for a Session recorded by a *newer* protocol version than the connection speaks; a delete never answers it | Removed from this method | | `session_active` (-32000) | `requireInactive` and S, or a Session the delete would remove with it, is in use (§3.2 step 1) | Unchanged: nothing is removed and nothing is closed. The message says why: a turn is running, a background task holds it, or how many requests and subscriptions use it. A line that failed or is closing is not a reason: it keeps no Session | | `product_integration_pending` | The profile does not serve Session execution | Unchanged | -| `-32603` "Session operation failed" | Step 3 failed (`Locked`, `DirectoryNotEmpty`, `Unsynced`, I/O, node unavailable) or step 4 failed (SQLite) | If step 2 closed S, S is closed but not deleted, as after `session.close`: its rows remain, it is neither listed nor loaded again in this process, and the relations its close ended stay ended. After a restart it loads, possibly with part of its command output gone. A Session that was not loaded is unchanged. Retry | +| `-32603` "Session operation failed" | Step 3 failed (`cancelled`, `unsynced`, `io`, `closed`, node unavailable) or step 4 failed (SQLite) | If step 2 closed S, S is closed but not deleted, as after `session.close`: its rows remain, it is neither listed nor loaded again in this process, and the relations its close ended stay ended. After a restart it loads, possibly with part of its command output gone. A Session that was not loaded is unchanged. Retry | | No reply | The connection or Rpc ended before the reply | Either state. Retry | -`Locked` and `DirectoryNotEmpty` in step 3 come only from writers outside the closed Session, such as a PowerShell -child that outlived its shell or another process holding a file open. The delete fails and is retried once they are -gone. +A held key in step 3 comes only from a FileStorage writer outside the closed Session, such as a +PowerShell child that outlived its shell and still writes through FileStorage. On Windows, a process that +merely holds the file open without FileStorage produces `io`, not a key wait; on Unix an open file does not block the key. The removal waits +for the key; cancelling the delete ends that wait with `cancelled`. An `unsynced`, `io` or `closed` failure +leaves the delete failed and retried. ## 4. Crash convergence @@ -245,7 +247,7 @@ means no committed delete ever leaves one behind. A directory another Session in (ADR 013 D4): it is found again through that Session's rows, so the next delete removes it. S5a's files follow the opposite order because their rows record them and the sweep can find them. FileStorage removal was not synced ([S6](https://github.com/arcships/dim/pull/87)): after a power loss a removed directory could reappear while the later -commit, made with `synchronous=FULL`, stays. `remove` now syncs the parent before it returns (§14), which closes that +commit, made with `synchronous=FULL`, stays. `remove` now syncs the parent before it returns ([FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal)), which closes that gap; HostPlatform syncs the parent of a removed `.dim/exec` directory the same way. **Only an id with rows here.** For the same reason a delete removes the directory only while its own database has @@ -427,7 +429,7 @@ grows with `main`'s copied prefix, but no single transaction holds the writer fo | --- | --- | | `main` events after `at`, branches created after `at` | After the cut | | Events of child branches, and the branches below them | Not ordered against the cut, and a reload would run their pending work again (§6.3). Their work stays in S | -| The loaded instance, leases, subscriptions, attached clients, in-flight requests | Runtime state, not stored; F builds its own | +| The loaded instance, Session leases, subscriptions, attached clients, in-flight requests | Runtime state, not stored; F builds its own | | An input still being submitted | Not committed, so not a fact | | The command output directory | The bytes are not copied; F's `session_output_owners` rows name the same files under `command-output//` or `.dim/exec///` and keep them readable after S is deleted (ADR 013 D4, §6.6) | | Title metadata | SessionTitle A7 | @@ -563,11 +565,12 @@ delete against loading. | Delete of a member | The leader's requests to it settle as member closed, as today | | Two forks of one source | Independent Sessions, each owning the shared files | -**S6 review notes.** "SessionStore must close the Session and release its leases first": step 2 comes before any -removal. "`attachment.put` racing a delete should expect `Locked` or `DirectoryNotEmpty`": a put's directory belongs +**S6 review notes.** "SessionStore must close the Session and release its keys, claims and in-flight calls first": step 2 comes before any +removal. "`attachment.put` racing a delete should expect `cancelled`, `unsynced`, `io` or `closed`": a put's directory belongs to no Session (S5a), the delete never removes it, and S5a's sweep removes only unowned, non-pending files, so neither -meets a put's lease. The command output removal meets `Locked` or `DirectoryNotEmpty` only from a writer outside the -closed Session; the delete then fails and is retried (§3.5). "Put and delete must be serialized": the store's write +meets a put's key. The command output removal waits for a key held by a writer outside the +closed Session; cancelling the delete ends the wait with `cancelled`, and an `unsynced`, `io` or `closed` failure is retried +(§3.5). "Put and delete must be serialized": the store's write transactions order them (S5a §6); no in-memory lock is added. ## 8. Storage format @@ -644,7 +647,7 @@ unlike in a shared database directory, can attribute its entries. | [AcpGateway](../plugins/AcpGateway.md), [RemoteGateway](../plugins/RemoteGateway.md) | Their text said the preset is reset on fork, which #26 replaced: the preset is copied with the facts | | [Documentation index](../../INDEX.md) | Link to this page | | [Session files](session-files.md) | §5.3 and §12 said a delete commits while the node is offline. That holds for its Session-file step; the delete as a whole removes the command output on the node first (§11). §5.2, §5.4 and §6 are unchanged and are the steps this page runs; §5.4 notes that removal is now synced | -| [FileStorage](../../architecture/rust-agent/plugins/FileStorage.md) | Removal syncs the parent of the removed entry (§14) | +| [FileStorage](../../architecture/rust-agent/plugins/FileStorage.md) | This row is superseded by the FileStorage contract. | | [Single-tree assembly](../../architecture/rust-agent/single-tree.md) | The `Agents` reload row: reload settlement stops only members the reloading Session leads (#127) | | [Session access A.3](../contracts/session-access.md#a3-sessionconfig-fields) | Its status line: a fork copies the stored `SessionConfig` text, so `interactive`'s omission rule carries over | @@ -675,7 +678,7 @@ None to rutis. To the event format: the event kind `session/forked` (§13, rule | To | Requirement | Status | | --- | --- | --- | -| FileStorage | `remove` syncs the parent of the removed entry before it reports success, also when the entry was already absent, and returns `Unsynced` when that sync fails. Windows has no directory sync and relies on NTFS metadata journaling, as for `replace`. Needed so a delete's removal is durable before its commit (§4) | Implemented in S5c ([FileStorage](../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal)) | +| FileStorage | This row is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal). | Implemented in S5c | | Loop, InputQueue, BackgroundExec | A read-only rest-point check at a fixed cut: no open turn, no Queue or Steer input waiting to drive a turn, every background task ended with its wake posted (§6.2). A capability whose reload rule comes to start work from other facts adds them to the check, so a fork keeps starting nothing | Agents queries these capabilities' public facts through the Timeline face (§16 D1). Their owners extend the check in [agents/fork.rs](../../../crates/dim-app-server/src/agents/fork.rs) when a reload rule comes to start work from other facts. BackgroundExec owns the shared wake predicate, including generation boundaries | | Collaboration | When a branch rebuilds, a delivered request without a result is settled as failed without stopping its member unless the member's relation names this Session as its leader. In general, reload settlement acts only on resources its own Session holds. The rebuild stopped any loaded Session named in the fact ([collaboration.rs](../../../crates/dim-app-server/src/collaboration.rs) `rebuild`), so a fork of a leader would have stopped the source's member | Implemented ([#127](https://github.com/arcships/dim/issues/127)). Before #127 that reload stopped such a member if it was loaded. Now the member keeps whatever its own reload rules start, the leader has already settled the request as failed, and the member's `agent` messages to a fork of the leader are refused (`TeamMemberNotFound`) because no relation names the fork ([#97 review](https://github.com/arcships/dim/pull/97)). A restart keeps the Team: relations are rebuilt from the stored leaders ([Collaboration §6](../plugins/Collaboration.md#6-delegation-ownership-and-lifetime)). Acceptance 7 | | Goal (P5, [#69](https://github.com/arcships/dim/issues/69)) | A copied goal must not drive a turn in F or be F's goal. The fork writes `session/forked` after the copied facts in its transaction (§6.5); Goal folds `main` from after that fact and clears a copied live goal once ([Goal](../plugins/Goal.md) A11) | Implemented with Goal's acceptance ([#209](https://github.com/arcships/dim/pull/209)) | @@ -839,7 +842,7 @@ impl SessionStore { pub const COMMAND_OUTPUT_DIRECTORY: &str = "command-output"; ``` -`SessionStorePlugin` already takes the database directory's root index (S5a). SessionStore removes `command-output/` +`SessionStorePlugin` already takes the database directory's root id (S5a). SessionStore removes `command-output/` under that root, the directory the daemon gives WorkspaceTools as its output root ([main.rs](../../../crates/dim-app-server/src/main.rs)); `COMMAND_OUTPUT_DIRECTORY` is the one definition of its name. The creation rollback path (`TimelineStore::rollback_session`) calls the same row removal as `delete_session`. diff --git a/docs/design/appserver/session-files.md b/docs/design/appserver/session-files.md index 38532937c9..dd048fa038 100644 --- a/docs/design/appserver/session-files.md +++ b/docs/design/appserver/session-files.md @@ -2,7 +2,7 @@ Status: Implemented. Roadmap item S5a ([#59](https://github.com/arcships/dim/issues/59), [#95](https://github.com/arcships/dim/pull/95)), after S6 ([#51](https://github.com/arcships/dim/issues/51)). The fork and delete methods that use it are S5c's (§13); §17 lists what the implementation changed. -Overview: [Appendix B.2](../overview.md#b2-app-server-process-plugins), SessionStore and FileStorage rows. Scope: +Overview: [Appendix B.1](../overview.md#b1-session-and-branch-capabilities) (FileStorage) and [B.2](../overview.md#b2-app-server-process-plugins) (SessionStore). Scope: [ADR 002](../../adr/002-plugin-scope.md) process scope, inside the existing SessionStore plugin. Consumers: [Attachments](../plugins/Attachments.md) (P2) and Session fork and deletion (S5c). @@ -20,7 +20,7 @@ history quotes it and history never changes. rows instead of copying bytes. Deleting a Session removes its rows. - **Removal.** A background sweep removes files whose last owner row is gone, and anything in the directory that no row records. -- **FileStorage.** S5a adds one operation, `create_directory`. Sharing needs no link operation. +- **FileStorage.** This bullet is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md). Sharing needs no link operation. - **Format.** The native store moves to version 15, with two new tables. A v13 store is upgraded in place at startup. - **Interface.** Attachments reaches the store through the process service `sessionFiles`. @@ -46,7 +46,7 @@ No Timeline event, no new plugin, no change to the runtime, rutis or the Session +------------------------------------------------|-------------------------+ v Resource node (P1/P2: the control node) FileStorage: create_directory, - replace, list, remove + write, import, list, remove Session scope Attachments (Deps: SessionIdentity, sessionFiles) -- put(own sessionId, name, text) ``` @@ -82,7 +82,8 @@ depends on SessionStore, the core part; SessionStore names no consumer. `--database`. In the product profile that is `~/.dimcode/rust`, not the product home `~/.dimcode` that `native_home` names ([lib.rs](../../../crates/dim-app-server/src/lib.rs)). `serve` registers the database directory as a FileStorage root when it is not one already - (with `--home` it already is) and passes its index to `SessionStorePlugin`. SessionStore + (with `--home` it already is) and passes its root id to `SessionStorePlugin`; SessionStore + reads the directory with `root_path`. SessionStore provides `sessionFiles` wherever it is loaded; a host without native storage has no SessionStore and no Session files. - The returned path is `root_path(root)/.session-files//`. Roots are canonical @@ -183,7 +184,7 @@ Rejected alternatives: | | (file_id, node, writer = G) ->| | | | create_directory() ------------------------------------->| parent synced | | create_directory(/) -------------------------------->| parent synced - | | replace(//, content, read-only) -------------->| file and parent synced + | | write(//, content, read-only) ---------------->| file and parent synced | | cancelled? -> abandon | | | | txn 2: S exists, row still G? | | | | insert owner (S, id); | | @@ -192,7 +193,7 @@ Rejected alternatives: ``` The reply is sent only after the file and its directory entries are synced and txn 2 has -committed (`synchronous=FULL`). Windows has no directory sync. As for `replace`, durability +committed (`synchronous=FULL`). Windows has no directory sync. As for `write`, durability there rests on the file sync and NTFS metadata journaling. **Abandon.** Txn 1 is followed by a failure, a cancellation (checked right before txn 2), or @@ -247,7 +248,7 @@ also removes the Session's command output on the node first 2 remove: for each row on node N with writer IS NULL and no owner: FileStorage(N).remove(/) absent counts as removed ok -> txn: delete the row if it is still unowned - Locked, I/O error -> keep the row, record a diagnostic; the next sweep retries + cancelled, unsynced, io, closed -> keep the row, record a diagnostic; the next sweep retries node unavailable -> stop; the next sweep retries 3 list: FileStorage(N).list(), then read the rows for those names every entry with no row -> FileStorage(N).remove(/) @@ -275,12 +276,12 @@ safe because FileStorage removal can be retried. ## 6. Deletion, crash recovery and serialization -**Order against Session close and leases.** S5c closes the Session first, then commits its -delete transaction, then SessionStore sweeps. No FileStorage lease outlives a put: `replace` -holds its lease only while it writes. The sweep never removes a pending file of the live -generation. A deletion therefore never meets `Locked` or `DirectoryNotEmpty` because of a put. -If it meets them because of something outside SessionStore, the row stays and the next sweep -retries. +**Order against Session close and keys.** S5c closes the Session first, then commits its +delete transaction, then SessionStore sweeps. No FileStorage key outlives a put: `write` +holds its key only while it writes. The sweep never removes a pending file of the live +generation. A deletion never meets a key held by a put; if a writer outside SessionStore holds +one, `remove` waits, and cancelling the sweep ends the wait with `cancelled`, leaving the row for +the next sweep. **Serializing put against delete and fork.** All three decide at a write transaction of the one native store connection. Txn 2 checks that the Session still exists. S5c's delete removes the @@ -309,30 +310,7 @@ creates the fork. SQLite orders those transactions, so no in-memory lock is need ## 7. FileStorage additions -**`create_directory` is the only addition.** Sharing is by rows (§4), so FileStorage needs no -link or reference-count operation. Removal, listing and durable writes already exist: S6's -`remove` and `list`, and `replace` with its permissions parameter. The S6 review agreed to add -`create_directory` in S5a. - -`create_directory(path, cancel) -> ()`: makes `path`, below an authorized root, an existing -business directory. - -| Rule | Content | -| --- | --- | -| Parent | Every component but the last is opened as `open_directory` opens it: an existing directory reached without following links, never the reserved directory. A missing parent fails `Io` `NotFound`; there is no recursive creation, and callers create each level in order | -| Reserved names | `path` already rejects the reserved prefix `.dim-file-storage-` and `auth.json.lock` by name (`InvalidPath`) | -| Aliases | Aliases are checked the way `lock` checks them, before anything is created. The parent's reserved directory is ensured first, so any spelling the filesystem equates with it already exists. Then the key for `auth.json.lock` is ensured in that reserved directory and the key for the last component is opened if it exists; if they are the same file, the name is an alias of the account marker and the call fails `InvalidPath` | -| Create | An absent last component is created relative to the held parent handle: Unix `mkdirat` with mode `0700`; Windows `NtCreateFile` with `FILE_CREATE` and `FILE_DIRECTORY_FILE`, inheriting the parent's DACL | -| Present | An existing directory is opened as `open_directory` opens it, so an alias of the reserved directory fails `InvalidPath`. An existing business directory counts as created, just as S6's `remove` counts an absent entry as removed. Any other existing entry (file, link, reparse point, special file) fails `Io` and is left untouched; links are never followed | -| Durability | In both the created and the present case the parent is synced before the call returns, so a retry after `Unsynced` confirms durability. A sync failure returns `Unsynced` (the directory exists and is visible, durability unconfirmed); its message is generalized from "file replaced" to cover directories. Windows has no directory sync, as for `replace` | -| Roots | A root itself cannot be named: `path` requires a relative name | -| Cancellation | Checked up to the creation, which is the commit boundary. Once created, the sync result is reported | -| Errors | `InvalidPath`, `Io` (`NotFound` parent, an existing non-directory entry, other I/O), `Unsynced`, `Closed`, `Cancelled`, `Worker` | - -The alias check never creates a key for the new directory's name, so a put leaves no key behind -in `.session-files/.dim-file-storage-locks`, which is never removed (Design changes, D1). The -operation lives inside FileStorage's own module, beside `list` and `remove`, and holds the same -generation admission. FileStorage's plugin page documents it. +This section is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md). ## 8. Storage format @@ -421,6 +399,8 @@ like `session_file_owners`, so output stays readable after the source is deleted | `owns` | async | `{sessionId: string, path: string}` | `{owned: bool}` | | `owned_paths` | async | `{sessionId: string}` | `{paths: string[]}`, a Session file's directory and each output path | +`read` stats the file first: an offset at or past its size answers an empty page with `eof: true`; only an offset below the size calls FileStorage's `read` with `offset` and the 64 KiB page. This keeps the existing `sessionFiles.read` and `attachment.read` EOF paging while FileStorage's offset-above-size stays `invalid`. + `sessionFiles` is a data face: its catalog entry is shared and SessionStore publishes the same `SessionFiles` binding at its Rust type key and `host_key("sessionFiles")`. Native calls invoke the owner directly; wire calls decode and invoke the same operations. @@ -477,14 +457,14 @@ Limits, and who owns them: | Limit | Owner | Reason | | --- | --- | --- | -| One file at most 16 MiB | SessionStore | A put is one message, and `replace` holds the content in memory; the bound caps one call's memory | -| `name`: `[A-Za-z0-9._-]{1,64}`, no leading dot, not `auth.json` or `auth.json.lock` in any letter case, and accepted by the node's FileStorage as one path component (Windows device names) | SessionStore | The name becomes a path component under SessionStore's directory. `auth.json` would switch `replace` to FileStorage's account-marker protocol | +| One file at most 16 MiB | SessionStore | A put is one message, and FileStorage streams its bytes; the bound caps one call's memory | +| `name`: `[A-Za-z0-9._-]{1,64}`, no leading dot, not `auth.json`, `mcp-oauth.json` or `chatgpt-account.json`, or any of their `.lock` markers, in any letter case, and accepted by the node's FileStorage as one path component (Windows device names) | SessionStore | The name becomes a path component under SessionStore's directory. A credential record would switch `write` to its marker | | Content rules (non-empty text, 10 MiB, default `paste.txt`) | Each consumer (Attachments A.2) | Business rules of the feature | | No per-Session count or total quota | None | Disk use ends with Session deletion and cleanup (S5c); a quota would need a business owner, and none exists | **Immutability.** A path names the same bytes for the file's whole life, which ends only when the sweep removes an unowned file. The file is written once, read-only: Unix mode `0400`, -Windows read-only attribute, through `replace`'s permissions parameter. WorkspaceTools' `write` +Windows read-only attribute, through `write`'s permissions parameter. WorkspaceTools' `write` and `edit` therefore fail with `permission_denied`: their commit step opens the target for writing, and on Windows also checks the read-only attribute, before replacing it. This is a guard, not isolation. A daemon running as root on Unix is not stopped by the mode, a shell @@ -639,7 +619,7 @@ Rejected alternatives: | FileStorage reloads during a put | `node_unavailable` or `storage`; abandoned and swept | SessionStore | | SessionStore reloads during a put | Cancelled before txn 2 (abandoned), or already committed; Attachments reloads with it | SessionStore unload | | Process restart | Leftovers are swept on the first put or after the next delete | Sweep | -| Something outside SessionStore writes into the Session-files directory | A top-level entry is removed by step 3 of the sweep; an entry inside a file's directory goes with that directory when the file is unowned. `Locked` leaves it for the next sweep | FileStorage, sweep | +| Something outside SessionStore writes into the Session-files directory | A top-level entry is removed by step 3 of the sweep; an entry inside a file's directory goes with that directory when the file is unowned. A `cancelled`, `unsynced`, `io` or `closed` removal leaves it for the next sweep | FileStorage, sweep | | `read` after the last owner is deleted | File not found; no surviving Session quotes the path | — | ## 13. Changes to other documents @@ -647,7 +627,7 @@ Rejected alternatives: | Document | Change in this PR | | --- | --- | | [Attachments](../plugins/Attachments.md) | Layout `.session-files//` with `attachmentId = fileId`; A1 refined to a directory no single Session owns; fork and delete ordering rows point here; the offline rows no longer depend on the withdrawn #5, because SessionStore looks FileStorage up per call (#38). The client contract of `attachment.put` is unchanged here; its `storage_failed` code lands in P2's design review (§15). §7 points to §11 for how reads are admitted, instead of saying a fork reads only the files its history references | -| [Overview B.2](../overview.md#b2-app-server-process-plugins) | FileStorage row gains directory creation | +| [Overview B.1](../overview.md#b1-session-and-branch-capabilities) | The FileStorage row points at its owner contract | | [Native storage format](native-storage-format.md) | Planned v15 decision | S5c builds `session.fork` and `session.delete` on §5.2, §5.3 and §5.4 and covers them through @@ -664,7 +644,7 @@ RPC. S5a implements those steps and tests them at SessionStore's Rust API. | Principles §4 rule 5 (batch) | Not applicable: no event. | | Principles §4 rule 6 (context from handed-over events) | The model sees a path only in adopted user input, and file content only in a `read` result. | | Principles §4 rule 7 (public events and services only) | Attachments uses `sessionFiles`; SessionStore uses FileStorage's public operations and reads no plugin's internals. | -| Principles §4 rule 8 (requirements to mechanism owners) | No change to the Timeline, Dispatcher, event format, rutis, assembly or the Session facade, and nothing raised to rutis. The format change belongs to SessionStore's own store and is recorded as a format decision. `create_directory` is a FileStorage supplement inside its own module, agreed in the S6 review. Permission admits file-tool reads and writes through the fixed facts (§11.1); §11.2 is the generic requirement it implements, not a Session-files exception. | +| Principles §4 rule 8 (requirements to mechanism owners) | No change to the Timeline, Dispatcher, event format, rutis, assembly or the Session facade, and nothing raised to rutis. The format change belongs to SessionStore's own store and is recorded as a format decision. `create_directory` is a FileStorage operation defined by its [contract](../../architecture/rust-agent/plugins/FileStorage.md), agreed in the S6 review. Permission admits file-tool reads and writes through the fixed facts (§11.1); §11.2 is the generic requirement it implements, not a Session-files exception. | | Principles §4 rule 9 (only facts later decisions use) | No Timeline event. Ownership is process-level state in SessionStore's rows. | | Principles §1 (Capability and App Server boundary) | Session files are SessionStore data (overview B.2); no new plugin. The paste feature stays in Attachments' own crate. | | ADR 002 D1 (scope follows state) | Process scope: a file outlives the Session that put it and is shared across Sessions. | @@ -680,8 +660,8 @@ None to the runtime or rutis. Supplements and requirements to other owners: | To | Requirement | Status | | --- | --- | --- | -| FileStorage | `create_directory` (§7) | Added in S5a's implementation, agreed in the S6 review | -| App Server assembly (`serve` in lib.rs) | Register the database directory as a FileStorage root when it is not one, and pass its index to `SessionStorePlugin` (§3.1) | A few lines in S5a's implementation, appended after the assembly lane's work like other registrations | +| FileStorage | `create_directory` per its [contract](../../architecture/rust-agent/plugins/FileStorage.md) | Added in S5a's implementation, agreed in the S6 review | +| App Server assembly (`serve` in lib.rs) | Register the database directory as a FileStorage root when it is not one, and pass its root id to `SessionStorePlugin` (§3.1) | A few lines in S5a's implementation, appended after the assembly lane's work like other registrations | | Attachments (P2 design refinement) | Map `sessionFiles` `storage` to an `attachment.put` code. Attachments lists none today; SessionTitle maps SessionStore `storage` to `storage_failed` | Decided: `storage_failed`, recorded in [#66](https://github.com/arcships/dim/issues/66); applied in P2's design review | | S5c | Delete owner rows inside the delete transaction, after closing the Session and before `agent_sessions`; copy owner rows inside the fork transaction; schedule a sweep after a delete | Contract for S5c (§5.2, §5.3) | | The item that first scopes file access by path (F5 [#76](https://github.com/arcships/dim/issues/76) for processes; [ADR 014](../../adr/014-file-access-facts.md) for in-process file tools) | §11.2: a Session's owned files need no scope approval; ownership decides, never the Session-files directory as a whole, the database directory or the product home. Tool admission still follows the preset and tool lists | S5a needed none. ADR 014 reads `sessionFiles.owns` for reads and writes; §11.1 admits a file-tool read by path | @@ -705,11 +685,7 @@ None to the runtime or rutis. Supplements and requirements to other owners: schema with every business row unchanged, then reopens as v15. The upgrading open reports the upgrade, which the §8 log line comes from; the reopen does not. The branch-only v14 and unknown schemas are refused and preserved. -8. FileStorage flow: `create_directory` creates `0700` and syncs the parent; an existing - directory succeeds; a missing parent fails `NotFound`. Reserved names, a case alias of the - reserved directory, and a case alias of `auth.json.lock` (on a case-insensitive filesystem) - fail `InvalidPath` and create nothing. An existing file or link is refused and untouched. - Cancellation before creation creates nothing. +8. FileStorage flow: the `create_directory` and `write` steps of §5.1 pass the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md)'s verification, including the reserved names and their case aliases; a cancelled put creates nothing. 9. Read admission, through a Session's tool path: after `put`, the Session's `read` of the returned path, under the product default `workspace-write` and under `read-only`, returns the content; the branch writes no `approval/request`, and its permission state (version and @@ -737,7 +713,7 @@ only S5a. | # | Change | Why | | --- | --- | --- | -| D1 | `create_directory` ensures the key for `auth.json.lock` and only opens the key for the new name, instead of opening both keys with creation (§7) | Opening a key with creation leaves a key file named after the directory, and FileStorage unlinks keys only when it removes their parent. `.session-files` is never removed, so every put would have left one key there for good. An existing alias of the marker still resolves to the marker's key, so the check gives the same answer | +| D1 | The credential markers' key handling is defined by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md); `create_directory` creates no key for the new name (§7) | A key file named after a directory that is never removed would stay for good. The contract's marker and private key keep the same alias check without leaving a key for the directory name | | D2 | Before P3, a put reads no resource node. The Session's existence is decided by txn 1, after the FileStorage lookup, so an unknown Session gets `node_unavailable` while FileStorage is not active (§5.1) | `SessionConfig.resourceNode` does not exist yet, so a read before txn 1 would only repeat txn 1's check. P3 adds the node read before the lookup | | D3 | Every put schedules a sweep until one sweep of the generation has completed on its node, instead of only the first put (§5.4) | A first sweep stopped by an unavailable node would otherwise wait for an abandon or a release to retry; a completed sweep ends the extra requests | @@ -773,7 +749,7 @@ pub struct SessionFiles(pub Arc); in `.session-files//`. A query failure is an error that denies access. `owned_paths` lists the owned file-id directories and output paths. -`SessionStorePlugin` takes the database directory's root index, provides `SessionFiles`, and +`SessionStorePlugin` takes the database directory's root id, provides `SessionFiles`, and reads `FileStorage` with `ctx.get_as` on each call. The fork, release and sweep steps are SessionStore methods over the native store connection, used by S5c. @@ -781,8 +757,8 @@ FileStorage: ```rust impl FileStorage { - pub async fn create_directory(self: &Arc, path: &FilePath, cancel: &CancellationToken) - -> Result<()>; + pub async fn create_directory(&self, path: String, cancelled: CancelledFn) + -> Result; } ``` diff --git a/docs/design/client-ui-extensions.md b/docs/design/client-ui-extensions.md index 69de4c7b52..7436d6fb45 100644 --- a/docs/design/client-ui-extensions.md +++ b/docs/design/client-ui-extensions.md @@ -194,9 +194,9 @@ UiResources 提供通用的**已完成文件发布**:受信任的后端 Sessio - 发布只接受 App Server 所在文件系统可读的有限长度普通文件,不接受目录、设备、socket 或网络 URL。远端浏览器不需要访问该文件系统;不共享文件系统的后端执行节点不是首期文件发布来源。 - 发布参数 `path` 是 App Server 文件系统上的 canonical 绝对路径,且须位于 FileStorage 的既有授权根内。相对路径以 `invalid_params` 拒绝;绝对路径没有匹配的授权根、越界或指向链接时以 `resource_unavailable` 拒绝。UiResources 在可信后端发布边界解析到根相对路径,不因 UI 请求扩大授权。所需的原生文件读取能力见 R5。 - 发布调用是后端命名服务,不是浏览器 Session RPC。浏览器没有“路径换 URL”、任意文件读取、上传或 URL 代理方法。业务 owner 在自己的外部输入边界决定哪些文件可以发布,不能直接把客户端传来的路径当成发布许可。 -- 生产者必须在文件完成后发布,并保证发布期间字节不变。UiResources 打开文件,记录长度和 MIME,持有读取资源;它不复制业务缓存、不接管下载或转码。替换内容要发布新引用,不能修改已发布文件。 +- 生产者必须在文件完成后发布,并保证发布期间字节不变。UiResources 按路径分页读取文件,记录长度和 MIME,不持有读取资源;它不复制业务缓存、不接管下载或转码。替换内容要发布新引用,不能修改已发布文件;同尺寸改写无法由分页发现,发布者的这一规则是唯一的版本保证。 - 引用绑定 Session、发布者的本次注册与资源 ID。它不是 bearer 凭据,也不是持久业务 ID。一个资源可被同一 Session 的多个面板读取;每个客户端仍需通过服务入口和 Session 访问授权。 -- 注册属于发布者的生命周期;显式撤下、发布者卸载和 Session closing 都停止准入,取消在途读取并等待文件句柄释放。撤下完成后,生产者才可删除缓存文件。Session 未发布前不接受读取。 +- 注册属于发布者的生命周期;显式撤下、发布者卸载和 Session closing 都停止准入,取消在途读取并等待在途页结束。撤下完成后,生产者才可删除缓存文件。Session 未发布前不接受读取。 - UI 关闭只取消自己的读取,不撤下别的面板仍可能使用的资源。资源过期后由业务方法显式取得新引用,不自动下载或重放具有副作用的操作。 第一阶段的文件读取支持 GET/HEAD;Range 只对 GET 生效:完整读取为 200,合法单区间为 206,不可满足的区间为 416 并包含总长度。支持开放尾部与 suffix range;合法多区间请求及未支持的 range unit 忽略 Range 并返回完整 200,不实现 multipart。HEAD 忽略 Range,返回完整 GET 的元数据而不读 body。动态资源使用 `private, no-store`,不转换编码后再按原文件偏移处理 Range。 @@ -205,11 +205,11 @@ UiResources 提供通用的**已完成文件发布**:受信任的后端 Sessio 读取按传输背压拉取有界字节块,内存不随文件大小增长;客户端关闭连接、取消、Session closing 或资源撤下均停止文件读取。头部发出前失败返回结构化资源错误;发出后失败终止流,不能在媒体 body 后追加 JSON。 -没有字节流入口的宿主通过 Session 方法 `session.ui.resources.read` 分页读取已发布资源:请求 `{sessionId, id, offset?, limit?}`,返回与 §6.1 相同的页形状和边界(标准 base64、1 MiB 默认、4 MiB 上限、`offset + bytes == total` 结束、`offset > total` 为 `invalid_params`)。它是普通 Session 方法:由 UiResources part 注册,经 `session.methods` 发现,并按 Session 方法的规则服务到各入口。按 ADR 021 D3,客户端读取要求活动 Session:资源 id 只在发布它的那个 Session 实例内有效,Session 卸载或 daemon 重启后,之前的每个 id 都回答 `resource_gone`;读取随 Session 路由进入,不为回答旧 id 跳过 Session。撤下与在途页竞争时,客户端收到整页或 `resource_gone`,绝不会收到半页;Session closing 与发布者卸载同样停止新读取并取消在途读取。 +没有字节流入口的宿主通过 Session 方法 `session.ui.resources.read` 分页读取已发布资源:请求 `{sessionId, id, offset?, limit?}`,返回与 §6.1 相同的页形状和边界(标准 base64、1 MiB 默认、4 MiB 上限、`offset + bytes == total` 结束、`offset > total` 为 `invalid_params`)。它是普通 Session 方法:由 UiResources part 注册,经 `session.methods` 发现,并按 Session 方法的规则服务到各入口。按 ADR 021 D3,客户端读取要求活动 Session:资源 id 只在发布它的那个 Session 实例内有效,Session 卸载或 daemon 重启后,之前的每个 id 都回答 `resource_gone`;读取随 Session 路由进入,不为回答旧 id 跳过 Session。撤下与在途页竞争时,客户端收到整页或 `resource_gone`,绝不会收到半页;同一引用的后续页发现文件缺失或其长度与发布时不同时回答 `resource_gone`,不返回空页;Session closing 与发布者卸载同样停止新读取并取消在途读取。 Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文件位置的业务 owner 提供,例如后端插件使用 Node 文件 I/O 在已授权工作目录生成文件,或由现有业务服务返回绝对路径。`pluginFiles` 只提供相对文本文件接口,不提供绝对路径,因此它的相对路径不能直接传给发布服务,也不能通过猜测产品 home 拼接。 -[sessionFiles](appserver/session-files.md) 负责持久化不可变文件及 Session 所有权记录、fork 和删除;UiResources 只持有已有文件的临时展示引用与读取句柄,不写入该存储、不复制文件、不增加持久化所有权行。关闭展示引用不等于删除 Session 文件,故不把传输生命周期加入 sessionFiles。 +[sessionFiles](appserver/session-files.md) 负责持久化不可变文件及 Session 所有权记录、fork 和删除;UiResources 只持有已有文件的临时展示引用,读取按路径分页进行,不写入该存储、不复制文件、不增加持久化所有权行。关闭展示引用不等于删除 Session 文件,故不把传输生命周期加入 sessionFiles。 此服务不复用文本型 [pluginFiles](process-typescript.md#52-public-pluginfiles-binding) 的编码或事务格式。图片生成、网络抓取、媒体解密、转码与缓存策略属于发布资源的业务插件。 @@ -229,6 +229,7 @@ Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文 | 页读取的路径非法、`limit: 0` 或 `offset > total` | UiExtensions:`invalid_params`(-32602) | 修正参数 | | 页读取的 generation 未知或已替换、路径不在该快照内 | UiExtensions:`resource_gone` | 重新读取目录后取新 generation | | 页读取的文件 I/O 失败 | UiExtensions:`resource_unavailable` | 生产者修复资源;不返回空页成功 | +| 同一引用的后续页发现文件缺失,或其 `size` 与发布时记录的不同 | UiResources:`resource_gone` | 重新取得引用;不返回空页 | | 页读取时 Session 已关闭、不可用,或引用不属于该 Session | Rpc 的 Session 路由先回答(如 `session_closed`);UiResources 对不属于本 Session 的引用回答 `resource_gone` | 使用活动 Session 的新引用 | | 文件定位、打开或撤下清理失败 | UiResources:`ResourceError.code = resource_unavailable` | 生产者修复资源;不返回空文件成功结果 | | 内容 generation、文件或动态引用不可用 | WebEntry:HTTP 404,响应 `error.code = resource_gone` | 重新发现内容或取得新引用 | @@ -244,8 +245,8 @@ Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文 | 部分 | 声明的服务依赖 | 用途 | | --- | --- | --- | -| UiExtensions | `managementMethods`、`partRegistry`、`fileStorage` | 目录方法、Session 部分注册、内容快照与文件读取 | -| UiResources | `sessionIdentity`、`sessionLifecycle`、`fileStorage` | 固定 Session 身份、发布与关闭边界、文件读取资源 | +| UiExtensions | `managementMethods`、`partRegistry`、`fsHost` | 目录方法、Session 部分注册、内容快照与文件读取 | +| UiResources | `sessionIdentity`、`sessionLifecycle`、`fsHost` | 固定 Session 身份、发布与关闭边界、按路径分页的 `stat`/`read` | | PluginManager | 对 `uiExtensions` 的可选读取 | 与已有内容 owner 一样提交或撤下内容;owner 缺失不阻塞后端代码 | 具体装配按 [rutis 使用](rutis-usage.md) 声明,贡献使用既有调用者生命周期。面板宿主依赖现有 Session 公开协议,不引入后端任意命名服务访问。没有对 rutis、Timeline 或 Dispatcher 的需求。 @@ -282,13 +283,13 @@ Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文 - **时序影响:** 仅有类型与客户端调用边界,不改变业务准入、中断或重放。 - **Owner / issue:** 公共协议与 npm 类型发布 owner,[#1136](https://github.com/arcships/dim/issues/1136)。 -### R5. FileStorage:受授权根约束的原生只读流 +### R5. FileStorage:受授权根约束的按路径分页读 -- **阻塞与规则:** §3.2 和 §6 需要有界复制与按字节区间读取;[FileStorage](../architecture/rust-agent/plugins/FileStorage.md) 的整块读取/限长读取不提供随传输背压拉取的文件句柄。 +- **阻塞与规则:** §3.2 和 §6 需要有界复制与按字节区间读取;[FileStorage](../architecture/rust-agent/plugins/FileStorage.md) 的按路径偏移读满足分页(`read` 的 offset/length),不提供文件句柄或背压流;撤下与在途页竞争时只返回整页或 `resource_gone`。 - **考虑的机制:** 整块读取使内存随媒体大小增长;在 UI owner 中重写根约束和安全打开逻辑会复制文件边界;文本事务不能表达二进制流。 -- **所需通用能力:** FileStorage 接受已有授权根内的路径,返回只读文件长度和可定位读取资源;保留原有防越界打开、取消、generation 准入与收尾保证,不由读取请求扩大根授权。每个消费者有独立读取位置;读取资源随使用者释放,存储关闭等待其结束。这是 Rust 原生 I/O 能力,不把文件句柄或逐块字节回调导出给 TypeScript。 -- **时序影响:** 取得读取资源时固定文件对象;取消或 owner 关闭停止读取并释放。无 Timeline、格式或写事务变更。 -- **Owner / issue:** FileStorage,[#1136](https://github.com/arcships/dim/issues/1136);实现与根约束、关闭流程验证在 FileStorage 内完成。 +- **所需通用能力:** FileStorage 的 `stat` 返回只读文件长度,`read(path, offset, length)` 由调用方自己携带偏移分页读取;保留原有防越界打开、取消、generation 准入与收尾保证,不由读取请求扩大根授权。没有读取资源或文件句柄跨出所有者。 +- **时序影响:** UiResources 先 `stat`,再按记录的 `size` 分页;大小变化或分页因缩小到 `offset` 以下而返回 `invalid` 时回答 `resource_gone`;同尺寸改写无法由按路径分页发现,因此发布者不得改写已发布路径是唯一的版本保证,改写是 UiResources 的契约违规。取消或 owner 关闭停止读取。无 Timeline、格式或写事务变更。 +- **Owner / issue:** FileStorage,[#2016](https://github.com/arcships/dim/issues/2016);UiResources 对齐 [#2021](https://github.com/arcships/dim/issues/2021)。实现与根约束、关闭流程验证在 FileStorage 内完成。 ## 9. 实施顺序与波及面 @@ -298,7 +299,7 @@ Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文 | 内容 owner 与安装 | App Server 中新增 UiExtensions;复用注册表与文件 I/O;PluginManager 的 UI 内容分发、v2 安装记录迁移 | UI-only 包可安装、启停、重载;旧记录和失败恢复可验证 | | 目录与静态资源 | 精确的目录协议、通知和受保护资源入口;不可变内容快照 | 多客户端能发现同一内容并独立更新;未认证、越界和旧版本读取失败 | | Web 面板宿主 | 在 `web/` 增加加载/清理、固定公开接口和一个面板位置 | 安装即可出现入口;切换、断线、失败和重载不影响会话 | -| Session 文件资源 | FileStorage 原生只读流、UiResources 的发布/撤下与读取、Web 的流式资源响应 | 大文件、seek、背压、取消和关闭时句柄释放成立 | +| Session 文件资源 | FileStorage 的 `stat` 与按路径分页 `read`、UiResources 的发布/撤下与读取、Web 的流式资源响应 | 大文件分页、取消和撤下与在途页竞争(整页或 `resource_gone`)成立 | | 示例与真实场景 | 一个零构建的 HTML + CSS + JS 示例,演示挂载、公开数据访问与清理 | 同一套契约覆盖多种渲染技术,业务逻辑不进入核心 | | Desktop | 在其仓库实现相同浏览器绑定、公开能力和资源适配 | 同一个插件包和构建产物无需重建;没有能力时明确不可用 | diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index ce4052095c..203c1113f3 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -8,23 +8,23 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | | `hostPlatform` | Exec and Shell use the task and PTY operations in [execHost §3](../resource-faces.md#3-exechost). Hooks calls configured(request); OCR calls confined(request). Both return the result of that call. Process handles remain with the platform. | -| `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | +| `fileStorage` | This row is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md). File tools and workspace completion keep the tool family under [#1297](https://github.com/arcships/dim/issues/1297). | +| `mentionIndex` | Unchanged: workspace completion uses its existing operations. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | | `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction. SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | -| Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info and fsHost resolution and reads. | +| Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info, the file-tools face's resolution and FileStorage's reads. | ## Additional public bindings | Target and signature | Existing operation and consumer | | --- | --- | | FileScope.directory(name) → FileResult of node-absolute path | The file scope validates the scoped name, creates parents and returns the directory. Modality passes the node-local input filenames and work directory directly to its native adapter. OCR uses its current work/tmp/cache paths and grants. Existing exports use the recorded result filename. | -| FileScope.openRead(name) → FileResult of {readId,size} or null | The file scope opens a pinned file by relative name and returns None if missing. Bind that reader to the existing fsHost reader identity for the caller on the same node. Use fsHost.readAt/closeRead and the existing caller-unload cleanup. A scoped name never requires a caller-side root lookup. | +| FileScope.openRead(name) → FileResult of {readId,size} or null | This row is superseded by the PluginFiles contract (#2016, batch 2); the target reads a page by relative name, so no reader ID or `fsHost.readAt/closeRead` crosses. | | FileScope.writeStream(name, next) → FileResult of null | The file scope consumes a reader to EOF under the destination lease. A rutis callback supplies bytes or EOF for the native reader parameter. Preserve atomic replacement and cleanup on failure or caller shutdown. The existing bounded whole-file replaceBytes remains available for small files. | | settings.declaredBy({instanceId}) → SourceDeclaration[] | SettingsService.declared_by already selects live declarations by registering instance. PluginManager passes the loader's current instance ID. settings.sources lists declarations across owners and omits that identity. | -The OS path, pinned reader and input reader above use a path value, an existing reader ID -and a callback respectively. Existing local media submission/import, legacy node paths, +The OS path and input reader above are now a path and a callback: the pinned reader is gone, FileStorage's `read(path, offset, length)` pages by path, and its [contract](../../architecture/rust-agent/plugins/FileStorage.md) defines the operation. Existing local media submission/import, legacy node paths, result settlement and result paging keep the [Modality contract](../plugins/Modality.md). ## Persistent Agents → sqliteStorage @@ -77,7 +77,7 @@ An admitted round is drained on shutdown. Losing the reply does not authorize re Settings decodes and validates the document. The writer checks the expected version before applying the decision and enqueues the change notice in commit order on a successful replace. -First import emits no notice. File and project profiles retain their lease and notification paths. +First import emits no notice. File and project profiles use FileStorage's `read` and `update`; their notification paths stay. ### Provider → sqliteStorage @@ -139,7 +139,7 @@ serves declared sources and excludes the native `mcp-secrets` document. | 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. | +| 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 use FileStorage's `read` and `update`. | | 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. | diff --git a/docs/design/overview.md b/docs/design/overview.md index 7ad843b331..8538fcdae4 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -494,7 +494,7 @@ A **supplement** adds services, methods or configuration. A **change** alters ex | Prompt, PromptSources | Supplement | Prompt's published adopted model configuration; atomic adoption of a profile's prompt and optional model, using PromptSources' existing `dim/session` System entry | `/effort`, `/fast`, `/agent` | | PromptSources | Supplement | Prompt language source | The Session's reply language (`session.language.*`) | | ContextPreparation | Supplement | Usage query; manual compaction; production compaction host implementing `ResolveContextModel` | `/usage`, `/compact` | -| FileStorage | Supplement | Directory listing and removal under a root (S6); directory creation (S5a, [session files](appserver/session-files.md#7-filestorage-additions)) | Session files, cleanup | +| FileStorage | Supplement | The reads, writes, updates, credential markers and roots of its [owner contract](../architecture/rust-agent/plugins/FileStorage.md) | Session files, cleanup, settings, accounts, UI resources, migration | | HostPlatform | Supplement | OS isolation at process start for agent-decided commands (`exec` and the persistent shell; macOS seatbelt, Linux bubblewrap, Windows explicitly unavailable), per-node host-local configuration; a process start that writes the given bytes to the child's stdin and closes it, for configuration commands such as hook commands, which run without the agent sandbox as MCP stdio servers do ([ADR 003](../adr/003-approval-scope.md) D2, [Hooks A.6.3](plugins/Hooks.md#a63-process-start-with-an-initial-stdin)); exec-argv helper; a confined start for a host-owned helper with a timeout, bounded output and no network, independent of the user's switch; exec shell read per spawn (ADR 002); when the link to the control node drops, the node's HostPlatform ends the processes it started | Sandbox; ShellInput, Hooks, ExternalAgent | ### B.2 App Server process plugins diff --git a/docs/design/p6-p7-bindings.md b/docs/design/p6-p7-bindings.md index d7d3f1ef11..8878f434d0 100644 --- a/docs/design/p6-p7-bindings.md +++ b/docs/design/p6-p7-bindings.md @@ -20,7 +20,7 @@ owner's design; the storage binding does not implement either business package. | Consumer | Required behavior | Existing mechanism | Missing repository work | | --- | --- | --- | --- | | Scheduler launching under a preset | Cap the saved preset against the live host bound at launch | S2's `sessions.launch` admission takes `policy?`, caps it and replies with the effective policy ([S2 D4/D6](appserver/sessions-service.md#3-decisions)) | None: Scheduler stores the preset and reads no permission state ([Scheduler §3.3](plugins/Scheduler.md#33-permission-of-a-run)) | -| Workflow definitions | Read user, project and installed-package definitions; save project definitions within file authority | Settings owner reads/CAS and project authorization; `FileStorage` read/list/replace/create-directory | A native, row-scoped file binding restricted to definition directories | +| Workflow definitions | Read user, project and installed-package definitions; save project definitions within file authority | Settings owner reads/CAS and project authorization; FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | A native, row-scoped file binding restricted to definition directories | | Workflow report recovery | Retry a report whose reply was lost without writing it twice | S2 input with the branch accepting each `submissionId` once | Retain admitted native input work through settlement; verify resubmission across row and runtime replacement in actual Node flows | Creation configuration is not live Permission state. Published history is not a @@ -133,15 +133,14 @@ The four methods are asynchronous: | `read` | `{root, path}` | Bytes, received as `Uint8Array` by TypeScript | | `list` | `{root}` | Definition-directory entries `[{name, kind}]`, where `kind` is `file`, `directory` or `other` | | `replace` | `{root: {project: canonicalCwd}, path, bytes}` | `void`, after existing atomic replacement and durability check | -| `createDirectory` | `{root: {project: canonicalCwd}}` | `void`, after ensuring `.dimcode`, then `.dimcode/workflows`, through existing non-recursive creates | +| `createDirectory` | `{root: {project: canonicalCwd}}` | `void`, after one recursive `create_directory` for `/.dimcode/workflows` | The plain Rust methods take serde request types. `read` returns `std::result::Result`; `list` returns `std::result::Result, WorkflowFilesError>` (UTF-8 `name` and the `kind` above); `replace` and `create_directory` return `std::result::Result<(), WorkflowFilesError>`. Their generated TS methods use the -table's shapes; Bytes becomes `Uint8Array` and `()` becomes `void`. `FilePath`, -root indices and `CancellationToken` stay private. Dropping a call follows the +table's shapes; Bytes becomes `Uint8Array` and `()` becomes `void`. Project/package indices, resolved paths and `CancellationToken` stay private. Dropping a call follows the existing generated future cancellation; it does not undo a committed mutation. The native binding constructs fixed prefixes after checking the selector; it @@ -152,25 +151,28 @@ also an authorized FileStorage root. Directory creation ensures only the two fixed project ancestors, without creating siblings or replacing non-directories. These are new binding authorization checks, not existing FileStorage guarantees. -FileStorage has `register_root` and `root_path`, not a path-to-index lookup. Use +FileStorage's roots, `add_root` and `root_path` are defined by its [contract](../architecture/rust-agent/plugins/FileStorage.md); the binding exposes neither root lookup nor registration. Use the project indices Settings already owns and package indices from trusted -assembly; expose neither root lookup nor registration. Reserved resources, -symlinks, generation validity and mutation locking remain FileStorage's checks. -Root registration stays with the trusted host. Selectors and internal indices -are not persisted definition identities. +assembly. Reserved resources, symlinks, generation validity and mutation locking +remain FileStorage's checks. Root registration stays with the trusted host. +Selectors and internal indices are not persisted definition identities. Methods return values directly; `Err(WorkflowFilesError)` throws the generated `RustError` with `name: WorkflowFilesError`, its enum's snake-case `code`, Display `message` and serde `data`. Define the error as a serde-tagged enum, retaining -the native distinctions `invalid_path`, `closed`, `cancelled`, `locked`, +the native distinctions `invalid_path`, `closed`, `cancelled`, `unsupported`, `unsynced` and `io`, plus `not_found` and `invalid_data` at this file boundary. Unknown/unauthorized selectors, package mutations and invalid filenames throw `invalid_path` before I/O. Malformed request data, including a raw numeric root, is refused by generated decoding before the method runs. A name that cannot be represented as UTF-8 is `invalid_data`, never a lossy -alias. `unsynced` means a mutation may already be visible: do not retry it as an -unchanged write. `replace` keeps native permission behavior, with no chmod API. -`read` and `replace` reject definition files above 8 MiB as `invalid_data`. Reads use FileStorage's bounded read: check the opened handle's length before allocating contents and enforce the cap on each chunk to cover concurrent growth. An over-limit read returns no partial bytes; an over-limit replacement leaves the existing file untouched. This ceiling leaves room for base64 bytes and the JSON envelope within the existing 16 MiB bridge frame. Workflow checks serialized project-save bytes before issuing a binary call. Workflow's own decoded-definition admission (1 MiB compact JSON) and run-store payload (8 MiB) bounds apply after this port returns bytes; committed run snapshots keep their existing decoder. This port adds no chunking or shared transport change. +alias. `missing_parent`, `too_large` and `rejected` never cross this binding: a +missing parent is `invalid_path`, an over-limit definition is `invalid_data`, +and the binding passes no source or change callback that could reject. `locked` +is absent because FileStorage waits for the key instead of failing. `unsynced` means a mutation may +already be visible: do not retry it as an unchanged write. `replace` keeps native +permission behavior, with no chmod API. +`read` and `replace` reject definition files above 8 MiB as `invalid_data`. Reads take the length from FileStorage's `stat` before allocating and enforce the cap on each `read` page to cover concurrent growth. An over-limit read returns no partial bytes; an over-limit replacement leaves the existing file untouched. This ceiling leaves room for base64 bytes and the JSON envelope within the existing 16 MiB bridge frame. Workflow checks serialized project-save bytes before issuing a binary call. Workflow's own decoded-definition admission (1 MiB compact JSON) and run-store payload (8 MiB) bounds apply after this port returns bytes; committed run snapshots keep their existing decoder. The port uses FileStorage's page loop; it adds no separate chunking or shared transport change. No deletion, arbitrary root registration, lock API or S10 envelope is exported. diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 7f10a66063..3f4c56bd7f 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -692,7 +692,7 @@ Codex `apply_patch` has no alias: its input is a patch, while Dim's `write` and | `Approval.respond` | `Approval::respond(approval_id, ApprovalDecision)` from `Keyed` | | `HookSources` | Session port `HookSourcesHost(Arc)`, bound by App Server as `CommandRules` and `SkillSettingsHost` are | | `hooks`, `hooks-projects`, `hooks-plugins` | `BusinessDocument` types in App Server (`hooks`: `USER_FILE` `hooks.json`, no `PROJECT_FILE`; `hooks-projects`: `USER_FILE` `hooks-projects.json`; `hooks-plugins`: `USER_FILE` `hooks-plugins.json`, one `{dir, hooks}` entry per plugin id, as `McpPluginServers` in `mcp/config.rs`) | -| `.dimcode/hooks.json` | Read by `HooksSettings` through `FileStorage::path(root, ".dimcode/hooks.json")` and `read_limited`, `root` from `SettingsService::project_root(cwd)`, parsed into the `hooks` document type | +| `.dimcode/hooks.json` | Read by `HooksSettings` through FileStorage's `read`; `SettingsService::project_root(cwd)` gives the project's FileStorage root id, `SettingsService::project_path(root)` gives its absolute path, joined with `.dimcode/hooks.json`, and the bytes are parsed into the `hooks` document type | | `register`, `withdraw`, `plugins()` | `HooksService::register_plugin(plugin: String, dir: PathBuf, document: serde_json::Value, cancel: &CancellationToken) -> Result<()>`, `withdraw_plugin(plugin: String, cancel: &CancellationToken) -> Result<()>`, `plugins(cancel: &CancellationToken) -> Result>` and `plugin_refusal(&self, plugin: &str) -> Option<(String, Option<&'static str>)>`, as `McpService`'s (`crates/dim-app-server/src/mcp.rs`): a refused document leaves no entry, and `plugin_refusal` reports its error text with the static reason its cause carries, both read under one lock; PluginManager reads the service through `names.key()` in its `Owners`, its `Kind::Hooks` added to `OWNERS` and `CONTENT` ([PluginManager §3.7](PluginManager.md#37-content-registration)) | | `hooks.*` | `Keyed`; `methods.register(ctx, "hooks", …)` | | Runner | Session service `HooksRuntime`, private to Hooks; processes from `HostPlatform::build_process_spec` and `spawn`, with the event's stdin object (A.3) as the initial stdin (A.6.3), owned by `ctx.effect` | diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 9d5d97d89c..e636fe45e2 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -40,7 +40,7 @@ All dependencies are process services at the same scope ([ADR 002 D3](../../adr/ | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | -| `Modality` | Process (control node) | Provider model selection (`ModelSelectionHost`) and non-conversational connection resolution; `pluginFiles` (UTF-8 and binary), `fsHost.readAt/closeRead` for opened readers; Settings business source `modality`; the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, A.2); HostPlatform of the control node (OCR); diagnostics | `modalityTasks` and `modalityTargets` process services; registers `modality` (`modality.*`) with `managementMethods` | +| `Modality` | Process (control node) | Provider model selection (`ModelSelectionHost`) and non-conversational connection resolution; `pluginFiles` (UTF-8, binary and paged reads); Settings business source `modality`; the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, A.2); HostPlatform of the control node (OCR); diagnostics | `modalityTasks` and `modalityTargets` process services; registers `modality` (`modality.*`) with `managementMethods` | | Adapter plugins | Process | their own provider dependencies | `modalityAdapter` provider copies at their provider ids; the built-in supplies only the family fallback (A.2) | **Contracts depended on:** the [methods](../contracts/session-boundary.md) contract (namespaces registered with `managementMethods`, per-call progress sink, connection-bound notifications); the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, §1 and A.2); Provider's model selection (`ResolveModelSelection::resolve`, which rejects an unselectable explicit model; [AuxiliaryModel](../appserver/auxiliary-model.md)), its selectable-model read for the option list (§9.2), and, for every adapter operation and realtime session, its non-conversational connection resolution ([overview Appendix B.2](../overview.md#b2-app-server-process-plugins), §9.3); `pluginFiles` (extended) with binary atomic replace and a format version ([App Server README](../../../crates/dim-app-server/README.md#trusted-plugin-storage)); HostPlatform spawn with isolation ([HostPlatform](../../architecture/rust-agent/plugins/HostPlatform.md), isolation supplement in [overview Appendix B.1](../overview.md#b1-session-and-branch-capabilities)). diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index e5dd257f13..b6c1d01f51 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -2,7 +2,8 @@ Status: Draft. Issues: [#1295](https://github.com/arcships/dim/issues/1295) (`execHost`), [#1296](https://github.com/arcships/dim/issues/1296) (leaf identity and lifecycle), -[#1297](https://github.com/arcships/dim/issues/1297) (`fsHost`), +[#1297](https://github.com/arcships/dim/issues/1297) (the file tools), +[#2016](https://github.com/arcships/dim/issues/2016) (`fsHost`), [#1298](https://github.com/arcships/dim/issues/1298) (`store`); parent [#1292](https://github.com/arcships/dim/issues/1292). Policy: [service faces](service-faces.md). Background: [remote plugins §3–§4](research/remote-plugins.md). @@ -16,14 +17,15 @@ Resource and state operations use these public data faces: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | | `execHost` | `start`, `wait`, `kill`, `settle`, `output`, `tail`, `removeOutputDirectory`, `shell`, `write`, `resize`, `info`, `confined`, `configured` | the process owner | #1295 | -| `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | +| `fsHost` | This row is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). | the file-storage owner | #2016 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | | `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | +The tool family (`resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`) is the file-tools owner's operations and is not part of `fsHost`; [#1297](https://github.com/arcships/dim/issues/1297) tracks that design. `fsHost` is the storage face of the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). ```text control node resource leaf (mounted per #1296) - WorkspaceTools ── fsHost ─── data ──────► file operations on node files + WorkspaceTools ── file tools ─ data ─────► file operations on node files exec, ShellSession ── execHost ─ data ──────► processes, PTY, output files settings, auth, Hooks ── fsHost ─── data ──────► the same face, answered locally Permission and Approval never asked, never decides @@ -42,7 +44,7 @@ SQLite or PostgreSQL. Whether a face is reachable over a link is decided by depl classification on the name. The public contract and migration rules are in [service faces](service-faces.md) §2. -For these resource faces, §6 maps `hostPlatform`, `fileStorage`, `sqliteStorage` and `timelineStore` +For these resource faces, §6 maps `hostPlatform`, `fsHost`, `sqliteStorage` and `timelineStore` to their public operations and Rust bindings. What stays on the control side, in every case: Session and branch scope, admission @@ -60,13 +62,13 @@ whether a call may run, or consults who is calling. each; a traversal is one call, not one call per file. 3. **Paths are node paths.** A request carries a node-absolute resolved path; a reply returns node-absolute resolved paths only. A relative path in a request is `invalid`, with one - exception: **`fsHost.resolve` is the resolution entry point**, so it accepts the path as the + exception: **the file-tools face's `resolve` is the resolution entry point**, so it accepts the path as the model gave it — relative to the `cwd` the caller passes, starting with `~`, containing `..`, following symlinks — because only the node can resolve it. `cwd`, `workspace` and the confirmed roots it is given are node-absolute. Every other operation, `execHost.start` and `shell` included, takes a path a `resolve` reply or the caller's own record already returned. Returned paths are stable for history: the same file always resolves to the same path. -4. **Ids are values.** A task, read or lease id is a string the provider issues or the caller +4. **Ids are values.** A task, root or claim id is a string the provider issues or the caller assigns; ids carry no authority. 5. **Pages are bounded.** Large output and long results cross as pages with a cursor, never as a stream. No reply carries unbounded bytes. @@ -104,7 +106,7 @@ whether a call may run, or consults who is calling. ### 3.2 `start` and `wait` `start` accepts only `{taskId, command, cwd, workspace, roots}`. `cwd` is a resolved working -directory — the control side obtains it from `fsHost.resolve`, which is also what triggers +directory — the control side obtains it from the file-tools face's `resolve`, which is also what triggers [worktree recognition](#421-session-scoped-recognition-and-association) for a cwd outside the known range; an absent `cwd` is `workspace`. `workspace` is the Session's workspace root and `roots` the mapped subtree paths from the Session's confirmed worktrees. All are node-absolute. @@ -292,7 +294,7 @@ not an agent-reachable operation: no tool maps to it. `execHost.removeOutputDirectory {path}` for persistent-shell output. The provider validates that the directory is strictly below its `execRoot`, removes it and makes removal durable before replying, as required by [ADR 013 D4](../adr/013-command-output-ownership.md#d4-fork-delete-and-growth). - An absent directory counts as removed. SessionStore uses `fsHost.remove` for command-output + An absent directory counts as removed. SessionStore uses FileStorage's `remove` for command-output directories in the FileStorage root. - When the link drops, the node's own host ends the processes it started ([overview §6.3](overview.md#63-multiple-nodes)), and settlement is the connection's end. A @@ -339,11 +341,16 @@ client reads and writes them through the node's own management methods, not thro | `remove_failed` | Removing a persistent-shell output directory or making the removal durable failed | | `cancelled` | The call was cancelled before it changed anything | -## 4. `fsHost` +## 4. File storage (`fsHost`) and the file tools + +The storage family in §4.1 and the error table in §4.7 are superseded by the [FileStorage +contract](../architecture/rust-agent/plugins/FileStorage.md). The tool-family table in §4.1 and subsections §4.2–§4.5 +belong to the file-tools face, whose name [#1297](https://github.com/arcships/dim/issues/1297) +settles, and are not part of `fsHost`. ### 4.1 Methods -Tool family — the file tools' operations, one call each: +Tool family — the file-tools face's operations, one call each (not `fsHost`): | Method | Mode | Request | Reply | | --- | --- | --- | --- | @@ -355,49 +362,7 @@ Tool family — the file tools' operations, one call each: | `grep` | async | `{pattern, path, include?, outputMode?, lineNumbers?, limit?, multiline?, literal?, timeoutMs?}` | `{result: ToolResult}` | | `mentions` | async | `{path, query, limit?}` | `{candidates}` | -Storage family — the raw operations the other file owners use. They take absolute paths and no -tool semantics: no line numbers, no images, no effects. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `stat` | async | `{path}` | `{kind: "file" \| "directory" \| "missing" \| "other", size?}` | -| `readBytes` | async | `{path, limit, leaseId?}` | `{bytes, size}` | -| `openRead` | async | `{path}` | `{readId, size}` | -| `readAt` | async | `{readId, offset, limit}` | `{bytes}` | -| `closeRead` | async | `{readId}` | `{}` | -| `lock` | async | `{path}` | `{leaseId}` | -| `unlock` | async | `{leaseId}` | `{}` | -| `backup` | async | `{leaseId, suffix, permissions?}` | `{}` | -| `createDirectory` | async | `{path}` | `{}` | -| `replace` | async | `{path, bytes, permissions?, leaseId?}` | `{}` | -| `list` | async | `{path}` | `{entries: [{name, kind}]}` | -| `remove` | async | `{path}` / `{parent, name}` | `{}` | - -A listed name passes unchanged to `remove({parent, name})`: a Unicode string, `{Unix: number[]}` for native bytes, or `{Windows: number[]}` for native UTF-16 code units. The owner checks that the name is a single component. - -- `readBytes` is the bounded read: `limit` is required, a larger file is `too_large` without - partial bytes, and `bytes` is base64. `size` is the file's length, so a caller can tell "done" - from "cut". -- `readBytes` and `replace` accept a `leaseId`: they then read or write through that lease, so a - read-modify-write keeps one lock from read to replace. `backup` writes the lease's current bytes - to a durable sibling named `.`. `unlock` releases the lease; ending the caller's - connection releases every lease it held. `permissions` is data — `"private"` (owner-only, 0600 - on Unix) or `"preserve"` (the existing file's mode) — because the provider's own permission type - is an OS object and does not cross; absent means `"preserve"`, as today. `replace` also accepts - `"privateReadOnly"` for a newly written Session file (Unix mode `0400`, Windows read-only - attribute). -- `openRead` pins a file for several bounded random reads (`readAt`) and is closed by `closeRead` - or the caller's connection. `readAt` retains the existing 64 KiB maximum per - call; a larger requested limit is clamped, zero or an offset at/past the pinned - length returns empty bytes. UI resource streaming uses these bounded reads. Plugin-file - uploads and work directories stay with the host-local - [PluginFiles service](../../crates/dim-app-server/README.md#trusted-plugin-storage). -- `stat` is one path, never a traversal: existence and kind for configuration discovery (a - project rule file, a hooks file). It is not a `stat`/`open` primitive API; traversals stay - `glob`, `grep` and `mentions`. -- `createDirectory` creates one directory with the existing rules (mode 0700, an existing one - counts as created, the parent must exist), `list` and `remove` serve the Session-file sweep, and - `replace` without a lease is the atomic whole-file write. +Storage family — the raw operations the other file owners use: this section is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). Only `resolve` takes an unresolved `path`; every other operation takes the node-absolute `path` its caller holds (§2 rule 3). `resolve` is what the file facts owner and process preparation @@ -455,7 +420,7 @@ moves the Git probe away from the Session that has to persist the result. | Concern | Owner | | --- | --- | -| Git probe, repository identity, fixed-prefix mapping, root directory identity | `fsHost.resolve`, on the node holding the files | +| Git probe, repository identity, fixed-prefix mapping, root directory identity | the file-tools face's `resolve`, on the node holding the files | | Session view: confirmed roots with their identities, in-flight recognitions, "already known" answers, branch-independent cache | the file facts Session part — ADR 014's `fileAccessFacts` service — on the control node (worktree access §3) | | Worktree directory record and Session usage association, deduplicated and written atomically | `store.associateWorktree`, provided by SessionStore (worktree access §4, R2) | | Publishing the expanded range, and its revalidation | the Session part, after the store acknowledges (§4.2.2) | @@ -550,7 +515,7 @@ or changed one: - The control side records the returned binding in `FileReads` for the branch; that record stays branch memory on the control node and is not reconstructed from the node. - `write` and `edit` are admitted before they run, so their `path` is the resolved path `resolve` - returned. `ToolHost.resolve_write` asks `fsHost.resolve` for a remote Session instead of + returned. `ToolHost.resolve_write` asks the file-tools face's `resolve` for a remote Session instead of resolving locally; the resolved call is what approval and execution receive, as today. ### 4.4 `glob`, `grep` and `mentions` @@ -583,24 +548,13 @@ grant, and tool approval still follows the preset ### 4.6 Session files and exec output -`sessionFiles.put` uses `createDirectory` and `replace` with `permissions: "privateReadOnly"` to -store the file on the resource node. It returns a node path and owns the rows under the +Session files' FileStorage operations are superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). `sessionFiles.put` returns a node path and owns the rows under the [Session-file contract](appserver/session-files.md#31-on-disk). Command output stays on the node and is read through `execHost.output` and `execHost.tail` (§3.4–§3.5). ### 4.7 Errors -| Code | When | -| --- | --- | -| `node_unavailable` | The provider is not connected. Only this call fails | -| `invalid` | A relative path, an unbounded request, an id the provider does not hold | -| `not_found` | A storage operation on a missing path where one is required | -| `too_large` | A bounded read whose file exceeds `limit`; no partial bytes | -| `locked` | A `lock` whose lease is held by another call; the retry policy is the caller's | -| `cancelled` | The call was cancelled before it changed anything | - -Operation refusals are not in this table: they arrive as the tool result's own `isError` with the -code the operation already uses, so one code vocabulary serves the local and the remote path. +This section is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md#errors). Operation refusals arrive as the tool result's own `isError` with the code the operation already uses. The file-tools face ([#1297](https://github.com/arcships/dim/issues/1297)) keeps `node_unavailable` for a call whose node cannot be reached; FileStorage's error table has no such kind because the node binding answers it. ## 5. `store` and `timelineStore` @@ -844,7 +798,7 @@ original path argument and ownership exclusion. | Old name | Face | What the name is now | | --- | --- | --- | | `hostPlatform` | `execHost` | The provider and its Rust binding: `ProcessTree`, `PtyProcessTree`, temporary directories and shell preparation are its internals, reached through the operations | -| `fileStorage` | `fsHost` | The provider and its binding: roots, leases, generations and one validated path component per open are its internals | +| `fileStorage` | `fsHost` | This row is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). | | `sqliteStorage` | `sqliteStorage.storageReport({})` | SQLite file, WAL and reclaimable bytes ([native storage](appserver/native-storage-format.md)). Session repository operations belong to `store`. | | `timelineStore` | `timelineStore` | Session-scoped Timeline operations; the `TimelineStore` trait is its native binding | @@ -859,13 +813,13 @@ The owners that read node files or start node processes, and the operations they | Owner | Operations | | --- | --- | | WorkspaceTools file tools | `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions` | -| SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`, `execHost.removeOutputDirectory` | -| Settings sources and their CAS writes | `readBytes`, `stat`, `lock`, `readBytes {leaseId}`, `replace {leaseId}`, `unlock` | -| MCP auth store, managed OAuth and OAuth token stores | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | -| Hooks project file (`.dimcode/hooks.json`) | `stat`, `readBytes` | -| PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | -| UI extension resources | `stat`, `openRead`, `readAt`, `closeRead` | -| Migration ledger and snapshots | `createDirectory`, `list`, `remove` | +| SessionStore Session files and command output | `execHost.removeOutputDirectory`; FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| Settings sources and their CAS writes | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| MCP auth store, managed OAuth and OAuth token stores | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| Hooks project file (`.dimcode/hooks.json`) | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`); FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| UI extension resources | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| Migration ledger and snapshots | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | | Hooks configuration commands | `execHost.configured` | | Worktree association | `store.associateWorktree` | @@ -953,10 +907,7 @@ are the PTY primitives the shell already has; `info`, `confined` and `configured and starts the platform already performs, including the configuration command Hooks runs. `removeOutputDirectory` carries the existing HostPlatform cleanup across the face. Paging by a registered output path reuses `output` after the provider releases its task record. -`fsHost` adds no primitive file API and no per-file traversal: its storage family is the reads and -leases the node's storage already offers, needed because a path's facts and its bytes cannot be -read on a machine that does not hold the file; `resolve` is where resolution and the worktree -probe belong. `store` publishes the repository operations the state owner already has; +The [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md) adds no primitive file API and no per-file traversal: its operations are the reads, writes, keys and roots the node's storage already offers, needed because a path's facts and its bytes cannot be read on a machine that does not hold the file; `resolve` belongs to the file-tools face (#1297), where resolution and the worktree probe belong. `store` publishes the repository operations the state owner already has; `timelineStore` publishes its Timeline operations and completion notifications. StorageMethods reads database and WAL sizes through the native binding of `sqliteStorage.storageReport({})`; plugins can dispatch the same operation. SQLite owns the connections and SQL. `TimelineStore` is the native binding of `timelineStore`. Admission stays synchronous and completion keeps the callback's ordering as a notification. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..f75edcc398 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -124,12 +124,12 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 现在的对象 | 目标操作 | | --- | --- | --- | | `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 数据面 `execHost`:`start`/`wait`/`kill`/`settle`/`output`/`tail`/`removeOutputDirectory`/`shell`/`write`/`resize`/`info`/`confined`/`configured`([resource and store data faces](resource-faces.md) §3,#1295);`hostPlatform` 是提供方和它的 Rust binding | -| `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | +| `fileStorage` | `FilePath`、根与代次 | 本行由 [FileStorage 契约](../architecture/rust-agent/plugins/FileStorage.md) 取代。 | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | | `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | -这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 +这些行按当前对象形状分组。前四行的数据契约分别由 [resource and store data faces](resource-faces.md) 与 [FileStorage 契约](../architecture/rust-agent/plugins/FileStorage.md) 定义(#1295/#1297/#2016/#1298)。其余行按 #1292 逐批确定操作面。 这些对象服务由所有者提供操作面,Rust 绑定与跨语言调用使用同一实现: @@ -160,7 +160,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou `backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 -`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:数据面就是公开契约,`execHost`、`fsHost`、`store`、`timelineStore` 的操作就是它们的接口,旧名字是提供方和它的 Rust binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 +`hostPlatform`、`fileStorage`、`store`、`timelineStore` 的旧名字不按对象分类保留:`fileStorage` 这个名字被删除,`fsHost` 是 FileStorage 的数据面;`execHost`、`fsHost`、`store` 与 `timelineStore` 的操作就是接口,旧名字只是提供方的历史称法,Rust 类型是它的 binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fsHost` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 ### 3.5 热路径与顺序:待操作化 diff --git a/docs/zh/design/appserver/mcp-oauth.md b/docs/zh/design/appserver/mcp-oauth.md index a4864604b9..60658a5862 100644 --- a/docs/zh/design/appserver/mcp-oauth.md +++ b/docs/zh/design/appserver/mcp-oauth.md @@ -33,7 +33,7 @@ OAuth 协议步骤来自工作区里已有的官方 Rust SDK:rmcp 的 `auth` f | [rmcp 版本](../../../../crates/dim-app-server/Cargo.toml),feature `auth`(`src/transport/auth.rs`) | `auth` 模块覆盖元数据发现、DCR 与 CIMD 客户端选择、PKCE 与 `state`、带 `resource` 和 `iss` 的授权码交换,以及带轮换的刷新。`CredentialStore` 与 `StateStore` trait 可替换。它与传输层共用同一个 reqwest 0.13 | 协议引擎;缺口见附录 A | | Claude Code(`/mcp`、`claude mcp login`、[文档](https://code.claude.com/docs/en/mcp)) | `.mcp.json` 中的 `oauth` 对象:`clientId`、`callbackPort`、`authServerMetadataUrl`、`scopes`。重定向为 `http://localhost:PORT/callback`;曾改成 `127.0.0.1`,使按注册 URI 精确匹配的服务器失败,后已改回。重定向失败时粘贴回调 URL。客户端密钥不进配置。遇到 `401` 先刷新,再重试一次 | `oauth` 的字段名和类型、重定向形式、粘贴兜底、密钥不进配置 | | MCP TypeScript 与 Python SDK(`OAuthClientProvider`、`TokenStorage`) | 存储与重定向处理由宿主注入。凭据带 issuer 标记,不匹配时丢弃。`invalid_client` 清除注册,`invalid_grant` 清除令牌 | 所有者提供的存储、issuer 绑定、清除规则 | -| Dim 账号登录(`account.login.browser.begin/complete`、`managed_oauth.rs`、`dim-cli/src/login.rs`) | 守护进程返回 `{attemptId, authorizationUrl, expiresAt}`。客户端把粘贴的回调 URL 送回,输入时隐藏回显。令牌存于 home 根目录的 `auth.json`,经 FileStorage 租约原子替换为 0600 | 尝试的形状、粘贴输入、存储方式 | +| Dim 账号登录(`account.login.browser.begin/complete`、`managed_oauth.rs`、`dim-cli/src/login.rs`) | 守护进程返回 `{attemptId, authorizationUrl, expiresAt}`。客户端把粘贴的回调 URL 送回,输入时隐藏回显。令牌存于 home 根目录的 `auth.json`;登录用一次 `update` 提交,刷新先 claim marker 再用 `update_claimed` 写回,原子替换为 0600 | 尝试的形状、粘贴输入、存储方式 | ## 3. 结构 @@ -81,13 +81,12 @@ OAuth 协议步骤来自工作区里已有的官方 Rust SDK:rmcp 的 `auth` f - **唯一写入者。** 只有 Mcp 写这个文件。 - **自足。** 记录带有令牌端点、撤销端点和客户端的认证方式,因此刷新和登出不需要重新发现。 记录在尝试完成时连同客户端和令牌一起写入;放弃的尝试不留下任何东西。 -- **写入路径。** 写入时取存储的 FileStorage 锁,重读文件,只替换自己 key 的记录,再以 0600 - 原子替换文件。Windows 上沿用 FileStorage 的 DACL 处理。替换已经生效、只是同步失败的写入算作已 +- **写入路径。** 写入时先用 `claim(caller, path, cancelled)` 取得文件的 marker([FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md)),再执行一次 `update_claimed`:change 拿到当前内容,只替换自己 key 的条目后返回,owner 在持有的 marker 下以 0600 原子替换文件;写完释放 claim,成功与否都一样。Windows 上沿用 FileStorage 的 DACL 处理。替换已经生效、只是同步失败的写入算作已 写入:读者已经看到它,崩溃时丢失它的结果与 §7 中进程被杀相同。 -- **令牌请求持锁。** 授权码交换、刷新和撤销从重读开始,经过请求,到替换为止一直持有这把锁, +- **令牌请求持有 claim。** 授权码交换、刷新和撤销在读取当前内容之前 claim marker,并一直持有到写回, 与托管 OAuth 宿主相同。两个守护进程可能共用一个 home(例如 `--product-home` 相同而 - `--database` 不同),这把锁防止二者兑换同一个会轮换的刷新令牌。因此不同服务器的令牌请求 - 会互相等待,每个受 30 秒超时约束;这类请求很少。发现和注册在锁外进行。 + `--database` 不同),这个 marker 防止二者兑换同一个会轮换的刷新令牌。因此不同服务器的令牌请求 + 会互相等待,每个受 30 秒超时约束;这类请求很少。发现和注册在 claim 外进行。 - **发出即结算。** 已发出的令牌请求在 `McpAuth` 自己的任务中接收并持久化,不论谁在等待,所以 调用方离开或卸载都不会丢掉轮换后的刷新令牌或已兑换的授权码。Mcp 卸载时会等待它。若授权码交换 期间其尝试已被取代,或其记录无法写入,响应照样接收,但得到的令牌改为撤销并丢弃(§7)。 @@ -103,11 +102,11 @@ OAuth 协议步骤来自工作区里已有的官方 Rust SDK:rmcp 的 `auth` f | --- | --- | --- | | 质询 | 每个 key:任一连接最近一次看到的 `WWW-Authenticate`(`resource_metadata`、`scope`、`error`) | 到授权成功、登出或 Mcp 重载为止 | | 尝试 | `attemptId`、key、PKCE verifier、`state`、预期 `issuer`、元数据、客户端、重定向 URI、scope、`expiresAt` | 每个 key 至多一个;在 complete、过期(10 分钟)、登出或同一 key 再次 start 时结束(§7) | -| 尝试锁 | 覆盖所有 key 的尝试与已完成登出的一把进程内异步锁,是尝试状态唯一的顺序(§7)。持有者从不等待存储锁或网络请求 | Mcp 代 | -| 存储锁与变化通知 | FileStorage 锁前面的一把进程内异步锁;FileStorage 锁立即准入或失败,因此被另一进程持有时会重试,与托管 OAuth 宿主相同。另有每个 key 一个 watch,key 的记录每次变化时通知,并带上记录是否持有令牌:处于 `auth_required` 的 Session 在任何变化时重试,就绪的 Session 在令牌消失时作出反应 | Mcp 代 | +| 尝试锁 | 覆盖所有 key 的尝试与已完成登出的一把进程内异步锁,是尝试状态唯一的顺序(§7)。持有者从不等待存储 claim 或网络请求 | Mcp 代 | +| 存储 claim 与变化通知 | FileStorage 的 `claim`/`update_claimed` 前面的一把进程内异步锁:每个 key 同时只允许一个本地令牌请求或写入,marker 则排除其他守护进程;另一守护进程持有的 marker 只等待、不失败。另有每个 key 一个 watch,key 的记录每次变化时通知,并带上记录是否持有令牌:处于 `auth_required` 的 Session 在任何变化时重试,就绪的 Session 在令牌消失时作出反应 | Mcp 代 | PKCE verifier 与 `state` 从不持久化。守护进程重启会放弃待完成的尝试。没有记录缓存:每个请求 -不加锁地读取文件,这是安全的,因为写入都是原子替换;同一 home 上另一个守护进程做的刷新也能 +不加 claim 地读取文件,这是安全的,因为写入都是原子替换;同一 home 上另一个守护进程做的刷新也能 被看到。 ### 4.3 配置(`mcp` 业务来源) @@ -197,7 +196,7 @@ PKCE verifier 与 `state` 从不持久化。守护进程重启会放弃待完成 5. **issuer 绑定。** 记录把客户端和令牌绑定到记录的 `issuer`,这是规范对客户端凭据的要求。 `start` 发现 PRM 现在指向另一个授权服务器时,为旧服务器记录的任何东西都不再使用。DCR 或 CIMD 客户端重新注册。配置的 `oauth.clientId` 以 `mcp_auth_client_required` 拒绝,因为规范 - 要求报错,而不是使用不匹配的凭据;登出会删除记录,下一次 `start` 就把配置的客户端绑定到新的 + 要求报错,而不是使用不匹配的凭据;登出会移除该 key 的条目,下一次 `start` 就把配置的客户端绑定到新的 issuer。服务器保持登录期间,授权服务器的切换表现为刷新后仍 `401`,于是记录变为 `expired`, 下一次 `start` 发现这一变化。 @@ -260,13 +259,13 @@ PKCE verifier 与 `state` 从不持久化。守护进程重启会放弃待完成 | | | | |-- lease(K) -------------------------------->| | | | | 剩余不少于 30 秒: | - | | | 直接回复;否则锁存储, | + | | | 直接回复;否则 claim 存储, | | | | 复查后刷新 | | |-- lease(K) --------->| | - | | | (等待锁) | + | | | (等待 claim) | | | |-- refresh, resource -------->| | | |<-- access, rotated refresh --| - | | | 持久化,解锁 | + | | | 持久化,释放 | |<-- lease r2 --------------------------------| | | |<-- lease r2 ---------| | | MCP:r2 得到 401 | | | @@ -285,7 +284,7 @@ PKCE verifier 与 `state` 从不持久化。守护进程重启会放弃待完成 - **遇到 `401`。** 带不带 `WWW-Authenticate` 的 `401` 都算。用令牌 `rN` 发出的请求得到 `401` 时,连接把 `rN` 报告为被拒。只有记录仍为 `rN` 时 `McpAuth` 才刷新;否则另一个 Session 已经刷新过。请求重试一次。被拒的请求服务器没有 处理,重试不会重复任何效果。 -- **单飞。** 每个 key 同一时刻在所有 Session 中只有一次刷新:拿到锁的等待者重读记录,得到新令牌。 +- **单飞。** 每个 key 同一时刻在所有 Session 中只有一次刷新:拿到 claim 的等待者重读记录,得到新令牌。 - **轮换。** 新的刷新令牌取代旧的;没有返回新的就保留旧的。新记录在任何租约使用新访问令牌之前 持久化。 - **重新授权。** `invalid_grant`、`invalid_client`、没有刷新令牌的令牌过期或被拒,或刷新后仍 @@ -311,8 +310,7 @@ Mcp 自己检查 `error` 参数,因为 rmcp 把任何带该请求头的 `403` ### 5.8 登出 `mcp.auth.logout` 在授权服务器声明了 `revocation_endpoint`(RFC 7009)时,先撤销刷新令牌, -再撤销访问令牌。然后无论撤销结果如何都删除记录,包括注册和任何客户端密钥。回复说明撤销是否成功。 -该 key 上的每个 Session 随即报告 `auth_required`。登出一经接受就关闭该 key 待完成的尝试,并关闭 +再撤销访问令牌。它从撤销之前就持有存储 claim,然后只用一个 `update_claimed` 移除自己 key 的条目,包括注册和任何客户端密钥,无论撤销结果如何。文件和其他 key 的条目保留;空的 `credentials` 数组是合法的,而在持有 claim 时删除文件必须先释放 claim,所以登出不删除文件。写完释放 claim,成功与否都一样。回复说明撤销是否成功。该 key 上的每个 Session 随即报告 `auth_required`。登出一经接受就关闭该 key 待完成的尝试,并关闭 在它完成之前开始的尝试,因此同一守护进程中进行中的登录无法撤销登出(§7)。条目不再使用 OAuth 后(加了静态凭据, 或改为明文 URL)也允许登出,因此已存的凭据总能删除。 @@ -336,7 +334,7 @@ Mcp 自己检查 `error` 参数,因为 rmcp 把任何带该请求头的 `403` +---- logout,从 required、authorized 或 expired ``` -`absent`:Dim 对该 key 没有记录,也没有记下的质询。登出会删除记录并清除质询。此时目录没有 `auth` 字段。 +`absent`:Dim 对该 key 没有记录,也没有记下的质询。登出会移除该 key 的条目并清除质询。此时目录没有 `auth` 字段。 ## 7. 时序与冲突 @@ -346,28 +344,28 @@ Mcp 自己检查 `error` 参数,因为 rmcp 把任何带该请求头的 `403` **唯一的顺序。** 尝试锁(§4.2)是尝试状态唯一的线性化点。`start` 持有它使尝试成为当前尝试, `logout` 在被接受时和完成时持有它关闭尝试,`complete` 持有它校验回调,交换在两次时效检查时持有 -它。交换从最后一次检查起一直持有它,直到结果发布完毕。这把锁的持有者从不等待存储锁或网络请求, +它。交换从最后一次检查起一直持有它,直到结果发布完毕。这把锁的持有者从不等待存储 claim 或网络请求, 因此等它至多等一次本地存储写入,从不等待令牌请求或刷新。于是每个 `start` 和 `logout` 要么排在 交换的最后一次检查之前,交换随即发现其尝试已被取代;要么排在其发布之后:之后完成的新尝试替换存入 -的凭据,登出则删除并撤销它。被取代的尝试绝不会在更新的 `start` 返回之后写入存储或唤醒 Session。 +的凭据,登出则撤销并移除它。被取代的尝试绝不会在更新的 `start` 返回之后写入存储或唤醒 Session。 - **`start`** 返回时使其尝试成为当前尝试,取代之前的尝试。进行中的发布持有尝试锁,因此新尝试在 该发布之后才成为当前尝试。若 `start` 读取记录之后有登出完成,`start` 改为回答 - `mcp_auth_attempt_closed`,因为它的尝试可能复用登出已删除的客户端。 -- **`logout`** 在被接受时、等待存储锁之前关闭当前尝试;删除记录后再关闭一次,结束期间开始的尝试。 + `mcp_auth_attempt_closed`,因为它的尝试可能复用登出已移除的客户端。 +- **`logout`** 在被接受时、等待存储 claim 之前关闭当前尝试;移除条目后再关闭一次,结束期间开始的尝试。 - **`complete`** 在交换结算时结束尝试,传输错误除外(§5.4)。回调中带授权服务器错误,或过期,同样 结束尝试。 -- **交换**两次检查其尝试是否仍是当前尝试:取得存储锁之后、发送令牌请求之前;收到响应之后、写入 +- **交换**两次检查其尝试是否仍是当前尝试:取得存储 claim 之后、发送令牌请求之前;收到响应之后、写入 存储之前。从第二次检查起它一直持有尝试锁,直到结果发布完毕:写入记录、清除质询与缺失的 scope、 唤醒 Session;`invalid_client` 时清除注册;传输错误后尝试重新待完成。 - 在请求之前被取代:授权码从不发送。 - 在请求发出期间被取代:请求仍会结算(§4.1)。它取得的令牌被撤销(RFC 7009,尽力而为,先撤销 - 刷新令牌)并丢弃。撤销在仍持有存储锁时进行,因此先于之后的任何令牌请求。无论响应如何都不写 + 刷新令牌)并丢弃。撤销在仍持有存储 claim 时进行,因此先于之后的任何令牌请求。无论响应如何都不写 存储,也不唤醒 Session。 - 两种情况下 `complete` 都回答 `mcp_auth_attempt_closed`。 - 最后一次检查时仍是当前尝试:结果在之后任何 `start` 或 `logout` 生效之前发布。授权码已经用掉, 所以记录写不进去时尝试照样结束;令牌随后在释放尝试锁之后撤销。 -- **刷新**不需要这种检查。它在存储锁下重读记录,因此能看到在它之前持锁的登录或登出;在它之后持锁的 +- **刷新**不需要这种检查。它在存储 claim 下重读记录,因此能看到在它之前持 claim 的登录或登出;在它之后持 claim 的 登录或登出会替换或删除它的结果。 | 竞争 | 结果 | @@ -375,10 +373,10 @@ Mcp 自己检查 `error` 参数,因为 rmcp 把任何带该请求头的 `403` | 同一 key 两次 `start` | 后返回的取代先返回的;完成先返回的得到 `mcp_auth_attempt_closed` | | `complete` 进行中时 `start` | 旧交换的最后一次检查之前,新尝试取代旧尝试:尚未发送的授权码不再发送,已取得的令牌被撤销并丢弃,`complete` 回答 `mcp_auth_attempt_closed`。检查之后,`start` 要等旧交换写完记录、唤醒 Session 才成为当前尝试;完成新尝试会替换该记录 | | 同一尝试两次 `complete` | 一次只有一个交换:第二次立即回答 `mcp_auth_attempt_closed`。传输错误之后尝试重新待完成 | -| 尝试待完成或交换进行中时 `logout` | `logout` 被接受时尝试关闭。仍在等待存储锁的交换不发送任何东西;请求已发出的交换丢弃其令牌;已过最后一次检查的交换先发布,`logout` 在其之后被接受。随后 `logout` 删除记录并撤销其中的令牌 | +| 尝试待完成或交换进行中时 `logout` | `logout` 被接受时尝试关闭。仍在等待存储 claim 的交换不发送任何东西;请求已发出的交换丢弃其令牌;已过最后一次检查的交换先发布,`logout` 在其之后被接受。随后 `logout` 撤销其令牌并移除其条目 | | `logout` 进行中时 `start` | 若登出在 `start` 返回之前完成,`start` 回答 `mcp_auth_attempt_closed`;`start` 在此之前设为当前的尝试在登出完成时关闭 | -| 刷新进行中时 `complete` | 二者依次持有存储锁:`complete` 之后的刷新发现令牌新鲜而不做事;刷新之后的 `complete` 替换令牌 | -| 刷新进行中时 `logout` | `logout` 在刷新之后取得存储锁;刷新得到的令牌被撤销并删除。`logout` 之后的刷新找不到记录 | +| 刷新进行中时 `complete` | 二者依次持有存储 claim:`complete` 之后的刷新发现令牌新鲜而不做事;刷新之后的 `complete` 替换令牌 | +| 刷新进行中时 `logout` | `logout` 在刷新之后取得存储 claim;刷新得到的令牌被撤销并删除。`logout` 之后的刷新找不到记录 | | 两个 Session 同时得到 `401` | 只刷新一次(§5.6);两边都用新租约重试 | | 条目 URL 被修改 | key 改变,新的代从 `absent` 开始,第一次 `401` 时变为 `required`;旧记录不起作用 | | 尝试期间条目被禁用或删除 | 尝试仍可完成并持久化;条目启用之前不会连接 | @@ -459,15 +457,15 @@ Mcp 自己检查 `error` 参数,因为 rmcp 把任何带该请求头的 `403` | D6 | 回调总是经 `mcp.auth.complete {attemptId, callbackUrl}` 送回;CLI 用回环监听捕获,或由用户粘贴 | 守护进程中的回环监听是业务所有者内部的新外部入口,而且经 SSH 时本来就够不着;一次带进度的长调用会让 RPC 挂上几分钟,仍然需要监听;设备流不在 MCP 规范中 | | D7 | 三个方法,全部 `report`;没有取消方法,也不轮询尝试状态 | `drain` 会让 Mcp 的卸载等待授权服务器调用,并打破 `mcp.*` 统一的规则。取消方法无事可撤,因为待完成的尝试没有效果且会过期;轮询无物可轮,因为没有后台方会完成尝试 | | D8 | 凭据 key = 服务器 `id` + 规范化 URL,进程级;记录绑定 `resource` 与 `issuer` | 只用 URL 作 key 时,一个服务器只能有一个账号;`(source, id)` 会让令牌跟着名字去到新 URL;按 Session 作 key 与进程所有权相悖(ADR 002 D1) | -| D9 | 存储为 home 根目录下的 `mcp-oauth.json`,经 FileStorage 原子替换为 0600,带版本;令牌请求持有存储锁,发出即结算。S8b 不提供凭据服务,因此没有东西需要迁移:令牌是所有者状态,每次刷新都会重写,每个所有者自己处理密钥([settings-service §1.2](settings-service.md#12-决定密钥归其所有者));其他 OAuth 持有方照此办理 | SQLite 中的 Settings 行存放业务文档,不放密钥;`pluginFiles` 是 FileStorage 给非 Rust 插件的桥接 API,Rust 所有者直接用 FileStorage,托管 OAuth 宿主就是这样;OS 钥匙串需要一个覆盖所有 OAuth 所有者的宿主级密钥存储决定;等待 S8b 会卡在一个无法保存轮换密钥的 API 上 | +| D9 | 存储为 home 根目录下的 `mcp-oauth.json`,经 FileStorage 原子替换为 0600,带版本;令牌请求持有该文件发布的 marker claim,发出即结算。S8b 不提供凭据服务,因此没有东西需要迁移:令牌是所有者状态,每次刷新都会重写,每个所有者自己处理密钥([settings-service §1.2](settings-service.md#12-决定密钥归其所有者));其他 OAuth 持有方照此办理 | SQLite 中的 Settings 行存放业务文档,不放密钥;`pluginFiles` 是 FileStorage 给非 Rust 插件的桥接 API,Rust 所有者直接用 FileStorage,托管 OAuth 宿主就是这样;OS 钥匙串需要一个覆盖所有 OAuth 所有者的宿主级密钥存储决定;等待 S8b 会卡在一个无法保存轮换密钥的 API 上 | | D10 | 使用时刷新,余量 30 秒;`401` 时刷新并重试一次;每个 key 单飞;轮换在使用前持久化 | 后台刷新定时器会为空闲服务器唤醒守护进程,并轮换没人用的令牌 | | D11 | 提升授权由用户发起:调用以固定文本失败,下一次登录请求并集 | 从工具调用自动重新授权,需要在一轮中途打开浏览器 | -| D12 | 登出先撤销(RFC 7009,尽力而为),再删除整条记录;`mcp.remove` 不动凭据 | 在 `mcp.remove` 时删除,无法知道另一来源中同 key 的条目是否仍在使用 | +| D12 | 登出先撤销(RFC 7009,尽力而为),再移除该 key 的条目;文件和其他 key 的条目保留;`mcp.remove` 不动凭据 | 在 `mcp.remove` 时删除,无法知道另一来源中同 key 的条目是否仍在使用;持有 claim 时删除文件无法表达,且空的 `credentials` 数组合法 | | D13 | `session.mcp` 增加会自行消除的 `auth_required`;目录增加 `auth` | 复用 `failed` 会要求登录后手动刷新,CLI 也无从据以行动 | | D14 | `start` 要求条目已启用;登出总是允许;一个 key 在各来源之间共享 | 在禁用的项目条目上登录,会在用户启用之前访问项目文件中的 URL(ADR 003 D3) | | D15 | 带静态凭据的条目从不使用 OAuth;OAuth 需要 `https` 或回环 `http` | 静态凭据失败后退回 OAuth 会混用两种凭据来源;明文传输的 bearer 令牌可能被窃取 | | D16 | 要求 PRM 同源:`resource_metadata` URL 必须同源,`resource` 可以是服务器 URL 或同源下的父路径 | RFC 9728 不要求元数据 URL 同源;接受其他源会让任何 `401` 把发现引到别的主机。RFC 9728 要求 `resource` 完全相同;坚持这一点就得替换 rmcp 的校验,而父路径规则让令牌受众仍限于服务器的源 | -| D17 | 尝试的时效(§7):`attemptId` 标识尝试,只有该 key 的当前尝试兑换授权码,在取得存储锁之后和收到令牌响应之后各检查一次。一把尝试锁为尝试状态的每次变化排序;交换从第二次检查起一直持有它,直到结果发布完毕,因此之后的 `start` 或登出在发布之后生效。登出在被接受时和完成时关闭尝试;在一次已完成的登出之前准备的 `start` 被拒绝。已发出的被取代请求照样结算,其令牌在存储锁下尽力撤销后丢弃。持有存储锁使撤销排在更新尝试的交换之前:撤销整个会话的服务器会在登录时拒绝更新的授权码,而不是留下一份存入时就已失效的凭据 | 只在请求之前检查,会让仍在途中的响应覆盖更新的尝试。在写存储之前结束尝试、写完再发布,会让更新的 `start` 在写入期间返回,于是被取代的尝试在新尝试成为当前尝试之后仍存入令牌并唤醒 Session。先写入、被取代时再回滚,会让不加锁的读者在两次写入之间用上这些令牌,回滚失败还会把它们留在存储中。取消途中的请求违背“发出即结算”(§4.1):已兑换的授权码会留下无人知晓的有效令牌。先存入、留待之后的登出清理,会撤销用户已经完成的登出。不撤销就丢弃,令牌在授权服务器上一直有效到过期。在 `start` 中持有存储锁,会让每次登录排在最长 30 秒的刷新之后。每个尝试另设代计数,与 `attemptId` 重复 | +| D17 | 尝试的时效(§7):`attemptId` 标识尝试,只有该 key 的当前尝试兑换授权码,在取得存储 claim 之后和收到令牌响应之后各检查一次。一把尝试锁为尝试状态的每次变化排序;交换从第二次检查起一直持有它,直到结果发布完毕,因此之后的 `start` 或登出在发布之后生效。登出在被接受时和完成时关闭尝试;在一次已完成的登出之前准备的 `start` 被拒绝。已发出的被取代请求照样结算,其令牌在存储 claim 下尽力撤销后丢弃。持有存储 claim 使撤销排在更新尝试的交换之前:撤销整个会话的服务器会在登录时拒绝更新的授权码,而不是留下一份存入时就已失效的凭据 | 只在请求之前检查,会让仍在途中的响应覆盖更新的尝试。在写存储之前结束尝试、写完再发布,会让更新的 `start` 在写入期间返回,于是被取代的尝试在新尝试成为当前尝试之后仍存入令牌并唤醒 Session。先写入、被取代时再回滚,会让不加锁的读者在两次写入之间用上这些令牌,回滚失败还会把它们留在存储中。取消途中的请求违背“发出即结算”(§4.1):已兑换的授权码会留下无人知晓的有效令牌。先存入、留待之后的登出清理,会撤销用户已经完成的登出。不撤销就丢弃,令牌在授权服务器上一直有效到过期。在 `start` 中持有存储 claim,会让每次登录排在最长 30 秒的刷新之后。每个尝试另设代计数,与 `attemptId` 重复 | | D18 | OAuth HTTP 客户端由第一个联系授权服务器的操作创建,并在 Mcp 代内保留。创建失败由该操作以 `mcp_auth_unavailable` 报告;Mcp 组装成功 | 在组装时创建会为从不登录的条目分配 TLS 与解析器状态。全局 HTTP 服务或已完成请求缓存会持有其他部件的资源,且仍要在使用点落实同样的策略与时限 | ## 11. 安全 @@ -582,7 +580,7 @@ Ctrl-C 或到期会释放监听和隐藏输入状态。已经提交的 RPC 在 | `configure_client` 与 `register_client`(DCR);不使用 CIMD(§5.3) | 不持久化 `client_secret` | 记录保存它,每次操作重新应用 | | `get_authorization_url`(PKCE `S256`、`state`、`resource`;verifier、`state` 和预期 issuer 存于 Mcp 的内存 `StateStore`) | 它自己的选择取之前请求的、质询的和 PRM 的 scope 的并集,并集为空时退回授权服务器的 `scopes_supported` | 传入按 §5.5 选出的 scope | | 无 | `AuthorizationCallback::from_redirect_url` 忽略 `error`,也不比较重定向 URI;`exchange_code_for_token_with_issuer` 以 `debug` 级别记录授权码 | Mcp 自己解析并校验回调(含 `iss`),并自己发送授权码交换(§5.4) | -| 无(不使用 `refresh_token`,D1) | `refresh_token` 从内存发现状态或基础 URL 取 `resource`,`invalid_client` 只以文本报告 | Mcp 自己在存储锁下发送刷新请求,带复查和轮换(§5.6) | +| 无(不使用 `refresh_token`,D1) | `refresh_token` 从内存发现状态或基础 URL 取 `resource`,`invalid_client` 只以文本报告 | Mcp 自己在存储 claim 下发送刷新请求,带复查和轮换(§5.6) | | `StreamableHttpClientTransport` | 其 worker 等待第一条消息时不响应取消,因此关闭一个从未发送消息的传输不会结束 | 先轮询一次握手,再响应取消 | | `StreamableHttpError::AuthRequired` 与 `InsufficientScope` | 任何带 `WWW-Authenticate` 的 `403` 都是 `InsufficientScope` | Mcp 读取 `error="insufficient_scope"` | | 无 | 没有 RFC 7009 撤销 | `mcp.auth.logout` 中每个令牌一个请求 | @@ -604,10 +602,10 @@ Ctrl-C 或到期会释放监听和隐藏输入状态。已经提交的 RPC 在 即重连并发布工具,每个请求都带 bearer。 3. **刷新。** 临近过期的访问令牌在使用前刷新。轮换得到的刷新令牌被持久化,旧的不再发送。Mcp 卸载时 进行中的刷新仍会被持久化。 -4. **共享刷新。** 两个 Session 同时得到 `401`:授权服务器只看到一次刷新,两边的请求重试后都成功。 +4. **共享刷新。** 两个 Session 同时得到 `401`:授权服务器只看到一次刷新,两边的请求重试后都成功。同一 home 上的第二个守护进程等待 `mcp-oauth.json.lock` marker 并采用轮换后的记录,而不是再刷新一次。 5. **重新授权。** 刷新后仍 `401`,或 `invalid_grant`,得到 `expired` 与 `auth_required`。重新登录 后两个 Session 都恢复。 -6. **登出。** `logout` 发送撤销,删除记录,回复 `revoked: true`。下一个请求以 `auth_required` 结束。 +6. **登出。** `logout` 发送撤销,移除该 key 的条目,回复 `revoked: true`;文件和其他 key 的条目保留。下一个请求以 `auth_required` 结束。 7. **拒绝。** 以下情形都不发送令牌请求: - `state`、重定向路径或 `iss` 错误(尝试保持待完成); - 元数据没有 `code_challenge_methods_supported`; @@ -623,9 +621,9 @@ Ctrl-C 或到期会释放监听和隐藏输入状态。已经提交的 RPC 在 `mcp_auth_client_required` 拒绝配置的 `clientId`。 13. **被取代的尝试。** 每种竞争都在模拟授权服务器上保持打开;存储写入无法从外部暂停,因此经 `testing` 特性的钩子在写入处保持打开: - - 刷新持有存储锁时,登出关闭待完成的尝试,其回调被拒。授权码从不发送,不存储任何东西, + - 刷新持有存储 claim 时,登出关闭待完成的尝试,其回调被拒。授权码从不发送,不存储任何东西, Session 需要登录。 - - 新的 `start` 取代一个交换正在等锁的尝试,其授权码从不发送。等待期间,该尝试的第二次回调被拒。 + - 新的 `start` 取代一个交换正在等 claim 的尝试,其授权码从不发送。等待期间,该尝试的第二次回调被拒。 - 新的 `start` 取代一个令牌请求已发出的尝试,令牌被撤销,从不存储或使用。 - 已过最后一次检查的交换正在写入记录时完成发现的新 `start`,只在该发布之后返回。随后完成新 尝试会替换该记录。 diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index c9b49c8e05..dda9997e26 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -68,7 +68,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | delete(S) ->| | | | | | 1 取得 S 的准入门 | | | | | 2 已加载?close() ---------->| 结算已接受的工作,写终态事实, - | | | 释放进程、租约、成员请求; + | | | 释放进程、键与 claim、成员请求; | |<-------------- 已关闭 -------| | | | | delete_session(S) ------------------------------->| | | | | 3 移除 command-output/S,同步父目录 --------->| @@ -83,8 +83,8 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 1. **准入。** Agents 检查 id(D3),并取得 S 的准入门,即 `acquire` 恢复 Session 时持有、创建在其构建的 Session 发布之前一直持有的 `SessionSlot` 门(§7)。删除进行期间没有请求、订阅或分叉能加载 S,删除仍在构建的 Session 时会等构建结束。已经持有 S 使用权的请求继续持有,由第 2 步的关闭结束其工作。 设了 `requireInactive` 时,删除在移除任何东西之前检查:S 和它会一并移除的每个 Session(它领导的成员,递归)都没有被使用。检查在 S 的准入门下进行,并对每个 Session 分别读取。一个 Session 处于使用中,指持有 `SessionUse`(每个被接受的请求和每个订阅都持有,所以附着的客户端算),或存在 `SessionHold`(被接受的分离工作取得),或它已加载且任一条线有回合在运行、或其已接受的工作尚未被派发(`Session::in_use`,逐条线)。失败或正在关闭的线不让 Session 处于使用中:线上没有工作,删除自身的关闭会结算它持有的东西。卸载的 Session 没有线和 hold,只有使用数能让它处于使用中。拒绝为 `session_active`(§3.5),什么都不移除;消息说明是什么在用它。只有所有者能回答这件事:只有它看得到此刻的使用、hold 和线,而客户端读摘要只能读到删除之前的状态。准入门一直持有到 S 被忘记,所以检查之后不会再有对 S 的新使用被接纳。成员是在它自己的准入门之外读取的,因此客户端在检查与该成员删除之间附着到成员的情况不在保证之内。不持 `SessionUse` 就启动回合的调用方,要么在启动期间持有该 Session(后台任务的唤醒取得 `SessionHold`,Scheduler 经 `sessions` 服务的运行取得租约),要么在关闭之后追加,而分支会拒绝。 -2. **关闭。** 若 S 已加载,Agents 像 `session.close` 那样关闭它:业务关闭,不是卸载。各能力结算已接受的工作,写出终态事实,释放进程、FileStorage 租约和成员请求。关闭报告清理错误时记日志并继续删除:未能写出的事实会随其余部分一起删除。从关闭起 S 的槽位即关闭:无论行最终是否删除,S 在本进程内都不再加载(第 6 步)。 -3. **命令输出。** SessionStore 在改动任何行之前移除该 Session 的输出目录(ADR 013 D4):它自己的 `<数据库目录>/command-output//`,以及它每一行路径所在的目录,因此分叉复制来的 `command-output//` 和 `.dim/exec///` 目录也覆盖在内。另一个 Session 仍在该目录下有行时,目录保留。SessionStore 的所有权锁把这次移除与第 4 步的删行跨 Session 串行化:否则两个并发删除可能都看到对方的行,都保留共享目录,提交后目录没有所有者。分叉步骤在复制时持有同一把锁并复制当前的全部输出行;一致由锁保证,而不是靠检查文件是否存在,因此运行中的命令在写出文件之前登记的行也会被复制,该命令创建的文件归分叉所有。`command-output` 目录通过 S 的资源节点上的 FileStorage(与 S5a 一样每次调用时查找)移除;`.dim/exec` 目录由 HostPlatform 移除,HostPlatform 不读取所有权行。目录不存在视为已移除。每次移除必须在第 4 步之前落盘(§4),因此 FileStorage 的 `remove` 要同步被移除条目的父目录(§14)。失败时删除在改动任何行之前结束(§3.5)。只有本数据库有 S 的行时,SessionStore 才移除自己的 `command-output//`:`command-output/` 由同一目录下的所有数据库共用,本库没有行的 id,其目录可能属于另一个数据库的 Session(§4)。 +2. **关闭。** 若 S 已加载,Agents 像 `session.close` 那样关闭它:业务关闭,不是卸载。各能力结算已接受的工作,写出终态事实,释放进程、FileStorage 的键、claim 与在途调用和成员请求。关闭报告清理错误时记日志并继续删除:未能写出的事实会随其余部分一起删除。从关闭起 S 的槽位即关闭:无论行最终是否删除,S 在本进程内都不再加载(第 6 步)。 +3. **命令输出。** SessionStore 在改动任何行之前移除该 Session 的输出目录(ADR 013 D4):它自己的 `<数据库目录>/command-output//`,以及它每一行路径所在的目录,因此分叉复制来的 `command-output//` 和 `.dim/exec///` 目录也覆盖在内。另一个 Session 仍在该目录下有行时,目录保留。SessionStore 的所有权锁把这次移除与第 4 步的删行跨 Session 串行化:否则两个并发删除可能都看到对方的行,都保留共享目录,提交后目录没有所有者。分叉步骤在复制时持有同一把锁并复制当前的全部输出行;一致由锁保证,而不是靠检查文件是否存在,因此运行中的命令在写出文件之前登记的行也会被复制,该命令创建的文件归分叉所有。`command-output` 目录通过 S 的资源节点上的 FileStorage(与 S5a 一样每次调用时查找)移除;`.dim/exec` 目录由 HostPlatform 移除,HostPlatform 不读取所有权行。目录不存在视为已移除。每次移除必须在第 4 步之前落盘(§4),因此 FileStorage 的 `remove` 要同步被移除条目的父目录([FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal))。失败时删除在改动任何行之前结束(§3.5)。只有本数据库有 S 的行时,SessionStore 才移除自己的 `command-output//`:`command-output/` 由同一目录下的所有数据库共用,本库没有行的 id,其目录可能属于另一个数据库的 Session(§4)。 4. **行。** 一个 `IMMEDIATE` 事务删除使 S 可见的行:`session_file_owners`(S5a 释放其文件)、`session_output_owners`、`session_grants`、`session_worktrees`、S5b 的标题元数据(§14)、`session_catalog`([#556 的目录投影](../../../design/appserver/native-storage-format.md#556-v23-格式决定))、`session_owners`、`timeline_branches` 和 `agent_sessions`。`timeline_snapshots`、`timeline_events` 和 `timeline_content` 随后在复制连接上按有界事务删除,每个事务至多删除 256 行,其他 Session 的提交与发布因此能在其间进行(#599)。复制连接关闭外键,第一个事务才能先删掉其余删除所引用的行。该操作在 Timeline 写线程排空已为 S 排队的所有追加之后执行,并清除 S 记下的写入失败;删除与创建回滚共用它。见[存储格式 §SQLite 运行参数与空间回收](../../../design/appserver/native-storage-format.md#sqlite-运行参数与空间回收)。 5. **清扫。** SessionStore 安排 S5a 的清扫([Session 文件 §5.4](session-files.md#54-清扫))。最后一个所有者是 S 的文件在清扫中移除;仍有分叉拥有的文件保留。 6. **忘记。** Agents 删除 S 的协议版本和不可用 Session 条目,把 S 的槽位标为已关闭、已删除,并在没有其他东西持有它时移除它([空闲卸载 §6.4](idle-unload.md#64-准入槽))。仍在准入门处等待的调用方会看到槽位已关闭,之后的调用方会发现 S 既没有所有者也没有行:两种情况下 `acquire` 都回答 `session_closed`。在第 4 步之前失败的删除则释放准入门。被它关闭的 Session 保持 `session.close` 之后的状态:行还在,`session.summaries` 不列出它,本进程内不再加载,重试即可删除;重启后它照常加载。删除没有关闭的 Session 在下次使用时照常加载(§16 D5)。 @@ -99,7 +99,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 标题元数据 | 原生存储,S5b 的 `session_metadata` 行([标题元数据](session-title-metadata.md#9-生命周期)) | 第 4 步,同一事务 | | Worktree 使用关联 | 原生存储,`session_worktrees` 行([worktree access §4](../../../design/worktree-access.md#4-持久使用关联与清理边界)) | 第 4 步,同一事务;保留目录记录与 worktree 文件 | | exec 输出、转存的 `read` 结果和持久 shell 日志 | `<数据库目录>/command-output//` 及 S 的输出行命名的每个目录 | 第 3 步。本数据库另一个 Session 仍命名的目录保留 | -| 已加载实例、租约、订阅、在途使用 | 进程内存 | 第 2 步 | +| 已加载实例、Session 租约、订阅、在途使用 | 进程内存 | 第 2 步 | | 协议版本、准入槽位、不可用 Session 条目 | Agents 内存 | 第 6 步 | | 指向 S 的 Collaboration 关系、S 领导的成员 Session 与 S 拥有的 Agent | 持久:`agent_sessions.leader_session_id` 与 `agents.owner_session_id`([Collaboration §6](../plugins/Collaboration.md#6-委派的所有权与寿命));Collaboration 的关系由它们重建 | Agents 随 leader 一起删除 Team:每个成员自己的删除(其行由 SessionStore 删除)、Agents 拥有的 Agent 记录,最后是 S。Collaboration 在观察到成员关闭([collaboration.rs](../../../../crates/dim-app-server/src/collaboration.rs) 的 `session_ended`)或删除已卸载成员时移除关系,装载时重建其余([空闲卸载 §7](idle-unload.md#7-竞争与交互)) | @@ -128,10 +128,10 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | `session_protocol_version` | 仅在 Session 由比连接更新的协议版本创建时出现;删除不会回复它 | 本方法移除该行 | | `session_active`(-32000) | 设了 `requireInactive`,且 S 或它会一并移除的某个 Session 处于使用中(§3.2 第 1 步) | 不变:什么都不移除,也不关闭任何东西。消息说明原因:回合正在运行、后台任务持有它,或有几个请求与订阅在用它。失败或正在关闭的线不是原因:它不让 Session 处于使用中 | | `product_integration_pending` | 该配置不提供 Session 执行 | 不变 | -| `-32603` "Session operation failed" | 第 3 步失败(`Locked`、`DirectoryNotEmpty`、`Unsynced`、I/O、节点不可用)或第 4 步失败(SQLite) | 若第 2 步关闭了 S,S 已关闭但未删除,与 `session.close` 之后相同:行还在,本进程内不再列出、不再加载,关闭结束的关系也不恢复。重启后它照常加载,命令输出可能已部分移除。没有加载的 Session 不变。重试 | +| `-32603` "Session operation failed" | 第 3 步失败(`cancelled`、`unsynced`、`io`、`closed`、节点不可用)或第 4 步失败(SQLite) | 若第 2 步关闭了 S,S 已关闭但未删除,与 `session.close` 之后相同:行还在,本进程内不再列出、不再加载,关闭结束的关系也不恢复。重启后它照常加载,命令输出可能已部分移除。没有加载的 Session 不变。重试 | | 没有回复 | 回复之前连接或 Rpc 已结束 | 两种状态之一。重试 | -第 3 步的 `Locked` 和 `DirectoryNotEmpty` 只会来自已关闭 Session 之外的写入方,例如比 shell 活得更久的 PowerShell 子进程,或打开着文件的其他进程。删除失败,等它们退出后重试。 +第 3 步被持有的键只来自已关闭 Session 之外经 FileStorage 写入的进程,例如比 shell 活得更久的 PowerShell 子进程。在 Windows 上,仅打开文件而不经 FileStorage 的进程产生 `io`,不是等待键;在 Unix 上打开文件不阻塞键。移除会等待该键;取消删除则等待以 `cancelled` 结束。`unsynced`、`io` 或 `closed` 失败让删除失败并重试。 ## 4. 崩溃收敛 @@ -266,7 +266,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | --- | --- | | `at` 之后的 `main` 事件,`at` 之后创建的分支 | 在切点之后 | | 子分支的事件,以及其下的分支 | 与切点之间没有先后顺序,重载还会重新执行其中待处理的工作(§6.3)。它们的工作留在 S 中 | -| 已加载实例、租约、订阅、已附着的客户端、在途请求 | 运行时状态,不存储;F 自己建立 | +| 已加载实例、Session 租约、订阅、已附着的客户端、在途请求 | 运行时状态,不存储;F 自己建立 | | 正在提交中的输入 | 尚未提交,不是事实 | | 命令输出目录 | 不复制字节;F 的 `session_output_owners` 行命名 `command-output//` 或 `.dim/exec///` 下的同一批文件,S 删除后仍可读(ADR 013 D4,§6.6) | | 标题元数据 | SessionTitle A7 | @@ -362,7 +362,7 @@ S5c 中被否决:在 S 的分叉都删除之前保留 S 的命令输出。ADR | 删除成员 | leader 对它的请求像如今一样以成员已关闭结算 | | 对同一源的两次分叉 | 两个独立的 Session,各自拥有共享的文件 | -**S6 评审意见。** "SessionStore 要先关闭 Session、放掉租约":第 2 步在任何移除之前。"`attachment.put` 与删除竞争时要预期 `Locked` 或 `DirectoryNotEmpty`":写入的目录不属于任何 Session(S5a),删除从不移除它,S5a 的清扫只移除无所有者且不在写入中的文件,因此两者都不会碰到写入的租约。命令输出的移除只会因已关闭 Session 之外的写入方遇到 `Locked` 或 `DirectoryNotEmpty`,这时删除失败并重试(§3.5)。"需要把 put 和 delete 串行化":存储的写事务给它们排序(S5a §6),不另加内存锁。 +**S6 评审意见。** "SessionStore 要先关闭 Session、放掉键、claim 与在途调用":第 2 步在任何移除之前。"`attachment.put` 与删除竞争时要预期 `cancelled`、`unsynced`、`io` 或 `closed`":写入的目录不属于任何 Session(S5a),删除从不移除它,S5a 的清扫只移除无所有者且不在写入中的文件,因此两者都不会碰到写入的键。命令输出的移除会等待已关闭 Session 之外的写入方持有的键;取消删除时等待以 `cancelled` 结束,`unsynced`、`io` 或 `closed` 失败则重试(§3.5)。"需要把 put 和 delete 串行化":存储的写事务给它们排序(S5a §6),不另加内存锁。 ## 8. 存储格式 @@ -411,7 +411,7 @@ S5c 与 S5a 一样只实现控制节点。在控制节点上,FileStorage 正 | [AcpGateway](../plugins/AcpGateway.md)、[RemoteGateway](../plugins/RemoteGateway.md) | 原文说分叉时重置预设,#26 已改为:预设随事实一起复制 | | [文档索引](../../../INDEX.md) | 链接到本页 | | [Session 文件](session-files.md) | §5.3 和 §12 原说节点离线时删除照样提交。这对其中的 Session 文件步骤成立;整个删除还会先在节点上移除命令输出(§11)。§5.2、§5.4 和 §6 不变,就是本页执行的步骤;§5.4 注明移除现在会同步 | -| [FileStorage](../../../architecture/rust-agent/plugins/FileStorage.md) | 移除会同步被移除条目的父目录(§14) | +| [FileStorage](../../../architecture/rust-agent/plugins/FileStorage.md) | 本行由 FileStorage 契约取代。 | | [单树装配](../../../architecture/rust-agent/single-tree.md) | `Agents` 重载一行:重载结算只停止重载中的 Session 所领导的成员(#127) | | [Session 访问 A.3](../contracts/session-access.md#a3-sessionconfig-字段) | 状态说明:分叉复制存储的 `SessionConfig` 文本,`interactive` 的省略规则随之保留 | @@ -442,7 +442,7 @@ S5c 与 S5a 一样只实现控制节点。在控制节点上,FileStorage 正 | 对象 | 需求 | 状态 | | --- | --- | --- | -| FileStorage | `remove` 在报告成功之前同步被移除条目的父目录(条目原本就不存在时也同步),同步失败时返回 `Unsynced`。Windows 没有目录同步,与 `replace` 一样依赖 NTFS 元数据日志。用于让删除的移除在提交之前落盘(§4) | 已在 S5c 中实现([FileStorage](../../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal)) | +| FileStorage | 本节由 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal) 取代。 | 已在 S5c 中实现 | | Loop、InputQueue、BackgroundExec | 作用于固定切点的只读静止点检查:没有未结束的轮次,没有等着驱动轮次的 Queue 或 Steer 输入,每个后台任务都已结束且其唤醒已发出(§6.2)。某个能力的重载规则以后要从其他事实开始工作时,就把这些事实加入检查,分叉因此始终不会开始任何工作 | Agents 通过 Timeline 数据面查询这些能力的公开事实(§16 D1)。某条重载规则以后要从其他事实开始工作时,由其所有者扩展 [agents/fork.rs](../../../../crates/dim-app-server/src/agents/fork.rs) 中的检查。BackgroundExec 拥有包含代边界的共享唤醒谓词 | | Collaboration | 分支重建时,已送达但没有结果的请求以失败结算;只有成员关系指明本 Session 是 leader 时才停止该成员。一般地,重载结算只处理本 Session 持有的资源。原先重建会停止事实中指名的任何已加载 Session([collaboration.rs](../../../../crates/dim-app-server/src/collaboration.rs) 的 `rebuild`),因此分叉一个 leader 会停止源的成员 | 已实现([#127](https://github.com/arcships/dim/issues/127))。#127 之前,这种重载会停止已加载的该成员;现在成员自身重载规则启动的工作会继续运行,leader 已把请求结算为失败,成员发给 leader 分叉的 `agent` 消息因没有成员关系而被拒绝(`TeamMemberNotFound`)([#97 评审](https://github.com/arcships/dim/pull/97))。重启后 Team 保留:关系由存储的 leader 重建([Collaboration §6](../plugins/Collaboration.md#6-委派的所有权与寿命))。验收第 7 条 | | Goal(P5,[#69](https://github.com/arcships/dim/issues/69)) | 复制来的目标不得在 F 中驱动轮次,也不是 F 的目标。分叉在其事务中、复制来的事实之后写 `session/forked`(§6.5);Goal 从该事实之后折叠 `main`,并对复制来的生效目标清除一次([Goal](../plugins/Goal.md) A11) | 随 Goal 验收实现([#209](https://github.com/arcships/dim/pull/209)) | @@ -532,7 +532,7 @@ impl SessionStore { pub const COMMAND_OUTPUT_DIRECTORY: &str = "command-output"; ``` -`SessionStorePlugin` 已经接收数据库目录的根索引(S5a)。SessionStore 在该根下移除 `command-output/`,这就是守护进程交给 WorkspaceTools 作为输出根的目录([main.rs](../../../../crates/dim-app-server/src/main.rs));`COMMAND_OUTPUT_DIRECTORY` 是这个名字唯一的定义。创建回滚路径(`TimelineStore::rollback_session`)调用与 `delete_session` 相同的行删除。 +`SessionStorePlugin` 已经接收数据库目录的根 id(S5a)。SessionStore 在该根下移除 `command-output/`,这就是守护进程交给 WorkspaceTools 作为输出根的目录([main.rs](../../../../crates/dim-app-server/src/main.rs));`COMMAND_OUTPUT_DIRECTORY` 是这个名字唯一的定义。创建回滚路径(`TimelineStore::rollback_session`)调用与 `delete_session` 相同的行删除。 ### Worktree 关联端口 diff --git a/docs/zh/design/appserver/session-files.md b/docs/zh/design/appserver/session-files.md index 683a8799b7..ceeda6cf6d 100644 --- a/docs/zh/design/appserver/session-files.md +++ b/docs/zh/design/appserver/session-files.md @@ -1,7 +1,7 @@ # SessionStore Session 文件 状态:已实现。路线图工作项 S5a([#59](https://github.com/arcships/dim/issues/59)、[#95](https://github.com/arcships/dim/pull/95)),在 S6([#51](https://github.com/arcships/dim/issues/51))之后。使用它的分叉与删除方法属于 S5c(§13);§17 列出实现所做的变更。 -总体设计:[附录 B.2](../overview.md#b2-app-server-进程插件) 的 SessionStore 与 FileStorage 行。作用域: +总体设计:[附录 B.1](../overview.md#b1-session-与分支-capability)(FileStorage)与 [B.2](../overview.md#b2-app-server-进程插件)(SessionStore)。作用域: [ADR 002](../../adr/002-plugin-scope.md) 进程作用域,位于现有的 SessionStore 插件内。 使用方:[Attachments](../plugins/Attachments.md)(P2),以及 Session 的分叉与删除(S5c)。 @@ -12,7 +12,7 @@ SessionStore 为 Session 保存不可变文件。调用方为某个 Session 交 - **位置。** 文件位于原生数据库 ``(默认 `dimcode.sqlite`)旁边的 `.session-files//`。这个目录属于该数据库,不属于任何单个 Session。 - **所有权。** 所有权是控制节点原生存储中的一组行。分叉只增加行,不复制字节;删除 Session 就删除它的行。 - **移除。** 后台清扫移除最后一个所有者行已消失的文件,以及目录中没有任何行记录的东西。 -- **FileStorage。** S5a 只新增一个操作 `create_directory`。共享不需要建链接的操作。 +- **FileStorage。** 本条由 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md) 取代。共享不需要建链接的操作。 - **格式。** 原生存储升级到 15 版,新增两张表;v13 存储在启动时原地升级。 - **接口。** Attachments 通过进程服务 `sessionFiles` 使用它。 - **读取。** 模型像读其他文件一样用 `read` 读取这些文件:所有权无需授权即可满足文件范围,但不绕过工具准入(§11)。 @@ -36,7 +36,7 @@ SessionStore 为 Session 保存不可变文件。调用方为某个 Session 交 +------------------------------------------------|-------------------------+ v 资源节点(P1/P2 即控制节点) FileStorage: create_directory, - replace, list, remove + write, import, list, remove Session 作用域 Attachments(Deps: SessionIdentity, sessionFiles)-- put(自身 sessionId, name, text) ``` @@ -60,7 +60,7 @@ SessionStore 仍只依赖 SqliteStorage,不依赖 FileStorage:它在每次 ``` - 目录位于拥有它的那个数据库旁边,并以数据库文件命名,就像 SQLite 的 `-wal` 和 FileStorage 的 `.lock` 伴随文件一样。因此每个数据库都有自己的目录,即使两个数据库位于同一目录(两个 `--database` 文件)。复制数据库文件不会复制它的 Session 文件。 -- 控制节点上,数据库目录是 `--home` 目录,或 `--database` 所在的目录。产品配置中它是 `~/.dimcode/rust`,而不是 `native_home` 指向的产品 home `~/.dimcode`([lib.rs](../../../../crates/dim-app-server/src/lib.rs))。数据库目录还不是 FileStorage 根时,由 `serve` 注册(使用 `--home` 时已经是),并把索引交给 `SessionStorePlugin`。只要 SessionStore 已加载就提供 `sessionFiles`;没有原生存储的宿主没有 SessionStore,也就没有 Session 文件。 +- 控制节点上,数据库目录是 `--home` 目录,或 `--database` 所在的目录。产品配置中它是 `~/.dimcode/rust`,而不是 `native_home` 指向的产品 home `~/.dimcode`([lib.rs](../../../../crates/dim-app-server/src/lib.rs))。数据库目录还不是 FileStorage 根时,由 `serve` 注册(使用 `--home` 时已经是),并把根 id 交给 `SessionStorePlugin`;SessionStore 用 `root_path` 读取该目录。只要 SessionStore 已加载就提供 `sessionFiles`;没有原生存储的宿主没有 SessionStore,也就没有 Session 文件。 - 返回的路径是 `root_path(root)/.session-files//`。根都是规范化的绝对路径,所以 `read` 解析到同一个文件。 - 在 P3 的资源节点上,目录以同样的名字位于该节点 FileStorage 注册的 home 根下。按节点查找属于 P3(#38)。一个资源节点只服务一个控制节点,因为总体设计 §6.3 不设计跨控制节点的使用。S5a 只实现控制节点,因为 P3 之前没有 `SessionConfig.resourceNode`;但每个文件都记下节点,P3 不需要再改格式。 @@ -132,7 +132,7 @@ SELECT :fork, file_id FROM session_file_owners WHERE session_id = :source | | (file_id, node, writer = G) ->| | | | create_directory() ------------------------------------->| 同步父目录 | | create_directory(/) -------------------------------->| 同步父目录 - | | replace(//, content, 只读) ------------------->| 同步文件与父目录 + | | write(//, content, 只读) --------------------->| 同步文件与父目录 | | 已取消?-> 放弃 | | | | txn 2:S 存在且行仍为 G? | | | | 插入所有者 (S, id); | | @@ -140,7 +140,7 @@ SELECT :fork, file_id FROM session_file_owners WHERE session_id = :source |<-----------| {fileId, path, bytes} | | ``` -文件及其目录项同步完成、txn 2 提交(`synchronous=FULL`)之后才回复。Windows 没有目录同步;与 `replace` 一样,那里的持久性依靠文件同步和 NTFS 元数据日志。 +文件及其目录项同步完成、txn 2 提交(`synchronous=FULL`)之后才回复。Windows 没有目录同步;与 `write` 一样,那里的持久性依靠文件同步和 NTFS 元数据日志。 **放弃。** txn 1 之后发生失败、取消(紧挨 txn 2 之前检查),或 txn 2 发现 Session 已不存在、自己的行已不再以 G 处于 pending 时,SessionStore 执行 `UPDATE session_files SET writer = NULL WHERE file_id = ? AND writer = G`。文件变为无主,并安排一次清扫。如果这条更新也失败,该行以 G 保持 pending,由下一个代次清扫。 @@ -178,7 +178,7 @@ put 作为 SessionStore 自己的任务运行:调用方不再等待就会取 2 移除:对节点 N 上 writer IS NULL 且无所有者的每一行: FileStorage(N).remove(/) 不存在即视为已删除 成功 -> txn:若该行仍无主,删除它 - Locked、I/O 错误 -> 保留该行,记录诊断;下次清扫重试 + cancelled、unsynced、io、closed -> 保留该行,记录诊断;下次清扫重试 节点不可用 -> 停止;下次清扫重试 3 列目录:FileStorage(N).list(),再读取这些名字对应的行 没有行的每个条目 -> FileStorage(N).remove(/) @@ -197,7 +197,7 @@ put 作为 SessionStore 自己的任务运行:调用方不再等待就会取 ## 6. 删除、崩溃恢复与串行化 -**与 Session 关闭和租约的顺序。** S5c 先关闭 Session,再提交删除事务,然后 SessionStore 清扫。FileStorage 租约不会比一次写入活得更久:`replace` 只在写入期间持有租约。清扫从不移除当前代次的 pending 文件。因此删除不会因为写入而遇到 `Locked` 或 `DirectoryNotEmpty`;如果因为 SessionStore 以外的原因遇到,该行保留,下次清扫重试。 +**与 Session 关闭和键的顺序。** S5c 先关闭 Session,再提交删除事务,然后 SessionStore 清扫。FileStorage 键不会比一次写入活得更久:`write` 只在写入期间持有键。清扫从不移除当前代次的 pending 文件。删除不会遇到 put 持有的键;如果 SessionStore 之外的写入方持有键,`remove` 会等待,取消清扫则以 `cancelled` 结束等待,把该行留给下次清扫。 **写入与删除、分叉的串行化。** 三者都在同一个原生存储连接的写事务上做决定:txn 2 检查 Session 是否仍存在;S5c 的删除同时删除所有者行和 Session 行;分叉在创建它的事务里复制所有者行。SQLite 给这些事务排序,所以不需要内存锁: @@ -223,23 +223,7 @@ put 作为 SessionStore 自己的任务运行:调用方不再等待就会取 ## 7. FileStorage 新增操作 -**只新增 `create_directory`。** 共享靠行(§4),FileStorage 不需要建链接或引用计数的操作。删除、列目录和持久写入已经有了:S6 的 `remove` 和 `list`,以及带权限参数的 `replace`。S6 评审已同意在 S5a 中加入 `create_directory`。 - -`create_directory(path, cancel) -> ()`:让授权根目录下的 `path` 成为一个已存在的业务目录。 - -| 规则 | 内容 | -| --- | --- | -| 父目录 | 除最后一个之外的每个组成部分都按 `open_directory` 的方式打开:不跟随链接到达的已有目录,且不是保留目录。父目录缺失时以 `Io` `NotFound` 失败;不递归创建,调用方按层依次创建 | -| 保留名 | `path` 已经按名字拒绝保留前缀 `.dim-file-storage-` 和 `auth.json.lock`(`InvalidPath`) | -| 别名 | 在创建任何东西之前,按 `lock` 的方式检查别名。先确保父目录中的保留目录存在,这样文件系统视为等同的任何拼写都已存在。然后确保该保留目录中有 `auth.json.lock` 的锁键,并在最后一个组成部分的锁键存在时打开它;二者是同一个文件时,名字就是账户标记的别名,调用以 `InvalidPath` 失败 | -| 创建 | 最后一个组成部分不存在时,相对已持有的父目录句柄创建:Unix 用 `mkdirat`,模式 `0700`;Windows 用 `NtCreateFile` 加 `FILE_CREATE` 和 `FILE_DIRECTORY_FILE`,继承父目录的 DACL | -| 已存在 | 已存在的目录按 `open_directory` 的方式打开,所以保留目录的别名以 `InvalidPath` 失败。已存在的业务目录视为创建成功,正如 S6 的 `remove` 把不存在的条目视为已删除。其他已存在的条目(文件、链接、重解析点、特殊文件)以 `Io` 失败且不被改动;从不跟随链接 | -| 持久性 | 无论是新建还是已存在,返回前都同步父目录,所以 `Unsynced` 之后的重试能确认持久性。同步失败时返回 `Unsynced`(目录存在且可见,持久性未确认);它的消息从"file replaced"推广到也涵盖目录。Windows 没有目录同步,与 `replace` 相同 | -| 根目录 | 不能指名根目录本身:`path` 要求相对名称 | -| 取消 | 一直检查到创建为止,创建就是提交边界;创建之后报告同步结果 | -| 错误 | `InvalidPath`、`Io`(父目录 `NotFound`、已存在的非目录条目、其他 I/O)、`Unsynced`、`Closed`、`Cancelled`、`Worker` | - -别名检查从不为新目录的名字创建锁键,所以 put 不会在永不删除的 `.session-files/.dim-file-storage-locks` 中留下锁键(设计变更 D1)。该操作位于 FileStorage 自己的模块内,与 `list`、`remove` 并列,使用相同的代次准入。FileStorage 的插件页记录了它。 +本节由 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md) 取代。 ## 8. 存储格式 @@ -281,7 +265,7 @@ CREATE INDEX session_file_owners_by_file ON session_file_owners(file_id) **S5c 不需要为 Session 文件再改格式。** 它的分叉步骤只插入 `session_file_owners` 行(§4),删除步骤只删除这些行(§5.3),清扫读取 `session_files`;这些步骤读写的内容 v15 都已具备。v16 只可能来自 S5c 对它自己的 Session 记录的改动,不会来自 Session 文件。 -**宿主输出是 v29 的第二张表。** [ADR 013](../../adr/013-command-output-ownership.md) 为命令输出、转存的 `read` 结果和 shell 日志新增 `session_output_owners(session_id, path)` 及其索引。它不是 Session 文件表:这些路径没有 `session_files` 行或 id,目录由最后一个拥有它的 Session 删除时移除。分叉像复制 `session_file_owners` 一样复制它的行,因此源 Session 删除后输出仍可读。 +**宿主输出是 v29 的第二张表。** [ADR 013](../../../adr/013-command-output-ownership.md) 为命令输出、转存的 `read` 结果和 shell 日志新增 `session_output_owners(session_id, path)` 及其索引。它不是 Session 文件表:这些路径没有 `session_files` 行或 id,目录由最后一个拥有它的 Session 删除时移除。分叉像复制 `session_file_owners` 一样复制它的行,因此源 Session 删除后输出仍可读。 ## 9. 接口 @@ -341,12 +325,12 @@ Attachments([A.2](../plugins/Attachments.md#a2-attachmentput))在 `Deps` 中 | 限制 | 归属 | 原因 | | --- | --- | --- | -| 单个文件至多 16 MiB | SessionStore | 一次写入是一条消息,`replace` 把内容放在内存里;这个上限约束单次调用的内存 | -| `name`:`[A-Za-z0-9._-]{1,64}`,不以点开头,不论大小写都不是 `auth.json` 或 `auth.json.lock`,并且节点的 FileStorage 接受它作为一个路径组成部分(Windows 设备名) | SessionStore | 文件名会成为 SessionStore 目录下的路径组成部分。`auth.json` 会让 `replace` 改走 FileStorage 的账户标记协议 | +| 单个文件至多 16 MiB | SessionStore | 一次写入是一条消息,FileStorage 流式写入;这个上限约束单次调用的内存 | +| `name`:`[A-Za-z0-9._-]{1,64}`,不以点开头,不论大小写都不是 `auth.json`、`mcp-oauth.json` 或 `chatgpt-account.json`,也不是它们的 `.lock` marker,并且节点的 FileStorage 接受它作为一个路径组成部分(Windows 设备名) | SessionStore | 文件名会成为 SessionStore 目录下的路径组成部分。凭据记录会让 `write` 改走其 marker | | 内容规则(非空文本、10 MiB、默认 `paste.txt`) | 各使用方(Attachments A.2) | 功能的业务规则 | | 不设每个 Session 的数量或总量配额 | 无 | 磁盘占用随 Session 删除和清理(S5c)结束;配额需要一个业务所有者,目前没有 | -**不可变性。** 在文件存续期间,路径始终指向同样的字节;文件只在清扫移除无主文件时结束。文件只写一次,并且只读:Unix 模式 `0400`,Windows 只读属性,通过 `replace` 的权限参数设置。因此 WorkspaceTools 的 `write` 和 `edit` 会以 `permission_denied` 失败:它们的提交步骤在替换前先以写方式打开目标,Windows 上还会检查只读属性。这是一道防护,不是隔离:以 root 运行的守护进程在 Unix 上不受模式限制,shell 命令仍可以修改文件,FileStorage 也只是可信的宿主存储边界,不隔离同一用户的进程。移动数据库目录会破坏历史中的绝对路径,就像移动工作区会破坏指向其中的路径一样。 +**不可变性。** 在文件存续期间,路径始终指向同样的字节;文件只在清扫移除无主文件时结束。文件只写一次,并且只读:Unix 模式 `0400`,Windows 只读属性,通过 `write` 的权限参数设置。因此 WorkspaceTools 的 `write` 和 `edit` 会以 `permission_denied` 失败:它们的提交步骤在替换前先以写方式打开目标,Windows 上还会检查只读属性。这是一道防护,不是隔离:以 root 运行的守护进程在 Unix 上不受模式限制,shell 命令仍可以修改文件,FileStorage 也只是可信的宿主存储边界,不隔离同一用户的进程。移动数据库目录会破坏历史中的绝对路径,就像移动工作区会破坏指向其中的路径一样。 ## 11. 安全 @@ -431,7 +415,7 @@ SessionStore 从两张所有权表回答"S 拥有哪些文件"(ADR 013):Se | 写入期间 FileStorage 重载 | `node_unavailable` 或 `storage`;放弃并清扫 | SessionStore | | 写入期间 SessionStore 重载 | 在 txn 2 之前取消(放弃),或已提交;Attachments 随之重载 | SessionStore 卸载 | | 进程重启 | 遗留物在第一次写入时或下一次删除之后被清扫 | 清扫 | -| SessionStore 以外的东西写入 Session 文件目录 | 顶层条目由清扫的第 3 步移除;某个文件目录内的条目在该文件无主时随目录移除。遇到 `Locked` 则留给下次清扫 | FileStorage、清扫 | +| SessionStore 以外的东西写入 Session 文件目录 | 顶层条目由清扫的第 3 步移除;某个文件目录内的条目在该文件无主时随目录移除。遇到 `cancelled`、`unsynced`、`io` 或 `closed` 则留给下次清扫 | FileStorage、清扫 | | 最后一个所有者删除后 `read` | 文件不存在;没有存活的 Session 引用该路径 | — | ## 13. 对其他文档的修改 @@ -439,7 +423,7 @@ SessionStore 从两张所有权表回答"S 拥有哪些文件"(ADR 013):Se | 文档 | 本 PR 中的修改 | | --- | --- | | [Attachments](../plugins/Attachments.md) | 布局改为 `.session-files//`,`attachmentId = fileId`;A1 细化为不属于任何单个 Session 的目录;分叉与删除顺序的行指向本文;离线相关的行不再依赖已撤回的 #5,因为 SessionStore 每次调用时查找 FileStorage(#38)。`attachment.put` 的客户端契约在本 PR 中不变;它的 `storage_failed` 码在 P2 的设计复核中加入(§15)。§7 不再说分叉只读取其历史引用的文件,改为指向 §11 说明读取如何准入 | -| [总体设计 B.2](../overview.md#b2-app-server-进程插件) | FileStorage 行增加目录创建 | +| [总体设计 B.1](../overview.md#b1-session-与分支-capability) | FileStorage 行指向其所有者契约 | | [原生存储格式](../../../design/appserver/native-storage-format.md) | 计划中的 v15 决定 | S5c 在 §5.2、§5.3 和 §5.4 的基础上实现 `session.fork` 和 `session.delete`,并通过 RPC 覆盖它们。S5a 实现这些步骤,并在 SessionStore 的 Rust API 上测试。 @@ -455,7 +439,7 @@ S5c 在 §5.2、§5.3 和 §5.4 的基础上实现 `session.fork` 和 `session.d | 原则 §4 第 5 条(批次) | 不适用:没有事件。 | | 原则 §4 第 6 条(上下文来自交接后的事件) | 模型只在已采用的用户输入里看到路径,只在 `read` 结果里看到文件内容。 | | 原则 §4 第 7 条(只用公开的事件和服务) | Attachments 使用 `sessionFiles`;SessionStore 使用 FileStorage 的公开操作,不读任何插件的内部状态。 | -| 原则 §4 第 8 条(向机制所有者提需求) | 不改 Timeline、Dispatcher、事件格式、rutis、装配或 Session 门面,也不向 rutis 提需求。格式变化属于 SessionStore 自己的存储,记录为格式决定。`create_directory` 是 FileStorage 在自己模块内的补充,已在 S6 评审中同意。Permission 通过固定事实准入文件工具的读写(§11.1);§11.2 是它实现的通用需求,不是 Session 文件的例外。 | +| 原则 §4 第 8 条(向机制所有者提需求) | 不改 Timeline、Dispatcher、事件格式、rutis、装配或 Session 门面,也不向 rutis 提需求。格式变化属于 SessionStore 自己的存储,记录为格式决定。`create_directory` 是 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md) 定义的操作,已在 S6 评审中同意。Permission 通过固定事实准入文件工具的读写(§11.1);§11.2 是它实现的通用需求,不是 Session 文件的例外。 | | 原则 §4 第 9 条(只有后续决定要用的事实进 Timeline) | 没有 Timeline 事件。所有权是 SessionStore 行中的进程级状态。 | | 原则 §1(Capability 与 App Server 边界) | Session 文件是 SessionStore 的数据(总体设计 B.2);不新增插件。粘贴功能留在 Attachments 自己的 crate 中。 | | ADR 002 D1(作用域跟随状态) | 进程作用域:文件比写入它的 Session 活得更久,并在 Session 之间共享。 | @@ -471,8 +455,8 @@ S5c 在 §5.2、§5.3 和 §5.4 的基础上实现 `session.fork` 和 `session.d | 对象 | 需求 | 状态 | | --- | --- | --- | -| FileStorage | `create_directory`(§7) | 在 S5a 的实现中加入,已在 S6 评审中同意 | -| App Server 装配(lib.rs 中的 `serve`) | 数据库目录还不是 FileStorage 根时注册它,并把索引交给 `SessionStorePlugin`(§3.1) | S5a 实现中的几行改动,像其他登记一样在装配线的工作之后追加 | +| FileStorage | `create_directory`,按其[契约](../../../architecture/rust-agent/plugins/FileStorage.md) | 在 S5a 的实现中加入,已在 S6 评审中同意 | +| App Server 装配(lib.rs 中的 `serve`) | 数据库目录还不是 FileStorage 根时注册它,并把根 id 交给 `SessionStorePlugin`(§3.1) | S5a 实现中的几行改动,像其他登记一样在装配线的工作之后追加 | | Attachments(P2 设计细化) | 把 `sessionFiles` 的 `storage` 映射为 `attachment.put` 的某个码。Attachments 目前没有;SessionTitle 把 SessionStore 的 `storage` 映射为 `storage_failed` | 已决定:`storage_failed`,记录在 [#66](https://github.com/arcships/dim/issues/66);在 P2 的设计复核中落实 | | S5c | 在删除事务内、关闭 Session 之后、删除 `agent_sessions` 之前删除所有者行;在分叉事务内复制所有者行;删除后安排清扫 | S5c 的合同(§5.2、§5.3) | | 首先按路径限定文件访问的那一项(进程方面为 F5 [#76](https://github.com/arcships/dim/issues/76);进程内文件工具为 [ADR 014](../../../adr/014-file-access-facts.md)) | §11.2:Session 自有文件无需范围审批;由所有权决定,从不是整个 Session 文件目录、数据库目录或产品目录。工具审批仍独立 | S5a 不需要。ADR 014 为读写读取 `sessionFiles.owns`;§11.1 按路径准入文件工具读取 | @@ -486,7 +470,7 @@ S5c 在 §5.2、§5.3 和 §5.4 的基础上实现 `session.fork` 和 `session.d 5. FileStorage 未激活:`node_unavailable`;什么都不写;SessionStore 和 Attachments 保持加载。 6. 在 txn 2 之前取消:不拥有任何文件;目录被清扫。文件名无效(包括 `AUTH.JSON`)或内容超过 16 MiB:`invalid` 或 `too_large`;什么都不写。 7. 空库建为 v15。一次性 v13 库原地升级为精确的 v15 结构,所有业务行不变,再次打开时为 v15。执行升级的那次打开报告升级,§8 的日志行由此而来;再次打开不报告。分支专用 v14 和未知结构被拒绝并保留。 -8. FileStorage 流程:`create_directory` 以 `0700` 创建并同步父目录;已存在的目录成功;父目录缺失以 `NotFound` 失败。保留名、保留目录的大小写别名,以及(在大小写不敏感的文件系统上)`auth.json.lock` 的大小写别名,都以 `InvalidPath` 失败且不创建任何东西。已存在的文件或链接被拒绝且不改动。创建前取消则什么都不创建。 +8. FileStorage 流程:§5.1 的 `create_directory` 与 `write` 步骤通过 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md) 的验收,包括保留名及其大小写别名;取消的写入什么都不创建。 9. 读取准入,经由 Session 的工具路径:`put` 之后,在产品默认的 `workspace-write` 和 `read-only` 下,该 Session 对返回路径的 `read` 返回内容;分支不写 `approval/request`,它的权限状态(版本和策略)不变。拒绝读取另一个 Session 的文件或数据库目录属于 §11.1 事实之外读取询问的验收:两者都不在该 Session 的事实中。 测试:第 1、3(未知 Session)、5、6(名字、大小、已取消的调用)、4、9 项是经由 `sessionFiles` 的流程测试,位于 [session_files_flow.rs](../../../../crates/dim-app-server/tests/session_files_flow.rs);第 2 项,以及写入与 txn 2 之间的第 3、6 项,在 [files/tests.rs](../../../../crates/dim-app-server/src/storage/files/tests.rs) 中运行 S5c 的分叉步骤和该处的钩子;第 7 项是 [storage_flow.rs](../../../../crates/dim-app-server/tests/storage_flow.rs) 中的 `a_v13_store_upgrades_in_place_once`、`the_daemon_reports_a_v13_upgrade_on_stderr_once` 和拒绝用例;第 8 项是 [file_storage_flow.rs](../../../../crates/dim-agent-capabilities/tests/file_storage_flow.rs) 中的 `directory_creation_stays_inside_the_authorized_root`。 @@ -499,7 +483,7 @@ S5c 在 §5.2、§5.3 和 §5.4 的基础上实现 `session.fork` 和 `session.d | # | 变更 | 原因 | | --- | --- | --- | -| D1 | `create_directory` 确保 `auth.json.lock` 的锁键存在,对新名字的锁键只打开、不创建,不再带创建地打开两个锁键(§7) | 带创建地打开锁键会留下以目录命名的锁键文件,而 FileStorage 只在删除其父目录时才删除锁键。`.session-files` 永远不会被删除,所以每次 put 都会在那里永久留下一个锁键。已存在的账户标记别名仍会解析到标记的锁键,检查结果不变 | +| D1 | 凭据 marker 的锁键处理由 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md) 定义;`create_directory` 不为新名字创建锁键(§7) | 永远不会被删除的目录若留下以它命名的锁键文件,就会一直留着。契约的标记与私有锁键保留同样的别名检查,又不为目录名留下锁键 | | D2 | P3 之前,put 不读取资源节点。Session 是否存在由 txn 1 判定,它在 FileStorage 查找之后,所以 FileStorage 未激活时,未知 Session 得到 `node_unavailable`(§5.1) | `SessionConfig.resourceNode` 还不存在,txn 1 之前的读取只会重复 txn 1 的检查。P3 在查找之前加入节点读取 | | D3 | 在本代次的一次清扫在该节点上完成之前,每次 put 都安排清扫,而不只是第一次 put(§5.4) | 否则因节点不可用而中止的第一次清扫,要等到放弃或释放才会重试;完成一次清扫后便不再多发请求 | @@ -530,13 +514,13 @@ pub struct SessionFiles(pub Arc); `register` 保存解析后的输出路径;生产者已按自己的根检查过它。`owns` 接收解析后的绝对路径并读取两张所有权表:`session_output_owners` 的精确行,或路径位于 `.session-files//` 内且 `session_file_owners` 拥有该 fileId。查询失败是错误,会导致拒绝访问。`owned_paths` 列出拥有的 fileId 目录和输出路径。 -`SessionStorePlugin` 接收数据库目录的根索引,提供 `SessionFiles`,并在每次调用时用 `ctx.get_as` 读取 `FileStorage`。分叉、释放和清扫步骤是 SessionStore 基于原生存储连接的方法,供 S5c 使用。 +`SessionStorePlugin` 接收数据库目录的根 id,提供 `SessionFiles`,并在每次调用时用 `ctx.get_as` 读取 `FileStorage`。分叉、释放和清扫步骤是 SessionStore 基于原生存储连接的方法,供 S5c 使用。 FileStorage: ```rust impl FileStorage { - pub async fn create_directory(self: &Arc, path: &FilePath, cancel: &CancellationToken) - -> Result<()>; + pub async fn create_directory(&self, path: String, cancelled: CancelledFn) + -> Result; } ``` diff --git a/docs/zh/design/overview.md b/docs/zh/design/overview.md index 25c3171d17..55c5b8d886 100644 --- a/docs/zh/design/overview.md +++ b/docs/zh/design/overview.md @@ -493,7 +493,7 @@ ADR 002 中记录的 HostPlatform exec shell 变更(作为业务配置在每 | Prompt, PromptSources | 补充 | Prompt 发布的已采纳模型配置;使用 PromptSources 现有的 `dim/session` System 条目,原子采纳 profile 的提示词和可选模型 | `/effort`、`/fast`、`/agent` | | PromptSources | 补充 | 提示词语言来源 | Session 的回复语言(`session.language.*`) | | ContextPreparation | 补充 | 用量查询;手动压缩;实现 `ResolveContextModel` 的生产环境压缩宿主 | `/usage`、`/compact` | -| FileStorage | 补充 | 根目录下的目录列举与删除(S6);目录创建(S5a,[Session 文件](appserver/session-files.md#7-filestorage-新增操作)) | Session 文件、清理 | +| FileStorage | 补充 | 其[所有者契约](../../architecture/rust-agent/plugins/FileStorage.md)中的读取、写入、更新、凭据 marker 与根 | Session 文件、清理、Settings、账户、UI 资源、迁移 | | HostPlatform | 补充 | 进程启动时的 OS 隔离只用于 agent 决定的命令(`exec` 与持久 shell;macOS seatbelt、Linux bubblewrap、Windows 明确不可用)、按节点的宿主本地配置;把给定字节写入子进程 stdin 然后关闭的进程启动,用于 Hook 命令这类配置命令,它们不施加 agent 沙箱,与 MCP stdio 服务器相同([ADR 003](../adr/003-approval-scope.md) D2,[Hooks A.6.3](plugins/Hooks.md#a63-带初始-stdin-的进程启动));exec argv 辅助;宿主自有助手的受限启动(超时、受限输出、无网络,与用户的开关无关);每次 spawn 时读取 exec shell(ADR 002);到控制节点的链接断开时,该节点的 HostPlatform 结束它启动的进程 | 沙箱;ShellInput、Hooks、ExternalAgent | ### B.2 App Server 进程插件 diff --git a/docs/zh/design/plugins/Hooks.md b/docs/zh/design/plugins/Hooks.md index a5bd428a1a..aa891239c9 100644 --- a/docs/zh/design/plugins/Hooks.md +++ b/docs/zh/design/plugins/Hooks.md @@ -690,7 +690,7 @@ Codex 的 `apply_patch` 没有别名:它的输入是补丁,而 Dim 的 `writ | `Approval.respond` | 经 `Keyed` 调用 `Approval::respond(approval_id, ApprovalDecision)` | | `HookSources` | Session 端口 `HookSourcesHost(Arc)`,由 App Server 绑定,如同 `CommandRules` 与 `SkillSettingsHost` | | `hooks`、`hooks-projects`、`hooks-plugins` | App Server 中的 `BusinessDocument` 类型(`hooks`:`USER_FILE` 为 `hooks.json`,没有 `PROJECT_FILE`;`hooks-projects`:`USER_FILE` 为 `hooks-projects.json`;`hooks-plugins`:`USER_FILE` 为 `hooks-plugins.json`,每个插件 id 一条 `{dir, hooks}`,如同 `mcp/config.rs` 中的 `McpPluginServers`) | -| `.dimcode/hooks.json` | 由 `HooksSettings` 经 `FileStorage::path(root, ".dimcode/hooks.json")` 与 `read_limited` 读取,`root` 来自 `SettingsService::project_root(cwd)`,解析为 `hooks` 文档类型 | +| `.dimcode/hooks.json` | 由 `HooksSettings` 经 FileStorage 的 `read` 读取;`SettingsService::project_root(cwd)` 给出项目的 FileStorage 根 id,`SettingsService::project_path(root)` 给出其绝对路径,拼接 `.dimcode/hooks.json`,再解析为 `hooks` 文档类型 | | `register`、`withdraw`、`plugins()` | `HooksService::register_plugin(plugin: String, dir: PathBuf, document: serde_json::Value, cancel: &CancellationToken) -> Result<()>`、`withdraw_plugin(plugin: String, cancel: &CancellationToken) -> Result<()>`、`plugins(cancel: &CancellationToken) -> Result>` 与 `plugin_refusal(&self, plugin: &str) -> Option<(String, Option<&'static str>)>`,如同 `McpService` 的(`crates/dim-app-server/src/mcp.rs`):被拒绝的文档不留条目,`plugin_refusal` 报告其错误文本以及原因携带的静态 reason,两者在同一把锁下读取;PluginManager 在其 `Owners` 中经 `names.key()` 读取该服务,`Kind::Hooks` 加入 `OWNERS` 与 `CONTENT`([PluginManager §3.7](PluginManager.md#37-内容登记)) | | `hooks.*` | `Keyed`;`methods.register(ctx, "hooks", …)` | | 执行器 | Session 服务 `HooksRuntime`,Hooks 私有;进程来自 `HostPlatform::build_process_spec` 与 `spawn`,事件的 stdin 对象(A.3)作为初始 stdin(A.6.3),由 `ctx.effect` 持有 | diff --git a/docs/zh/design/plugins/Modality.md b/docs/zh/design/plugins/Modality.md index 9ba86fefe0..5012954d89 100644 --- a/docs/zh/design/plugins/Modality.md +++ b/docs/zh/design/plugins/Modality.md @@ -40,7 +40,7 @@ flowchart LR | 部分 | 作用域 | 依赖 | 提供 | | --- | --- | --- | --- | -| `Modality` | 进程(控制节点) | Provider 的模型选择(`ModelSelectionHost`)与非对话连接解析;`pluginFiles`(UTF-8 与二进制),已打开的读取器使用 `fsHost.readAt/closeRead`;Settings 业务来源 `modality`;按提供方适配器副本、并以家族名副本兜底的按调用读取([#40](https://github.com/arcships/dim/issues/40) 已决定,A.2);控制节点的 HostPlatform(OCR);诊断 | `modalityTasks` 与 `modalityTargets` 进程服务;把 `modality`(`modality.*`)注册到 `managementMethods` | +| `Modality` | 进程(控制节点) | Provider 的模型选择(`ModelSelectionHost`)与非对话连接解析;`pluginFiles`(UTF-8、二进制与分页读取);Settings 业务来源 `modality`;按提供方适配器副本、并以家族名副本兜底的按调用读取([#40](https://github.com/arcships/dim/issues/40) 已决定,A.2);控制节点的 HostPlatform(OCR);诊断 | `modalityTasks` 与 `modalityTargets` 进程服务;把 `modality`(`modality.*`)注册到 `managementMethods` | | 适配器插件 | 进程 | 各自的提供方依赖 | `modalityAdapter` 提供方专属副本(以该提供方的 id 为 key);内置适配器只提供服务没有专属副本的提供方的家族名副本(A.2) | **依赖的契约:**[方法](../contracts/session-boundary.md)契约(注册到 `managementMethods` 的命名空间、每次调用的进度接收器、绑定连接的通知);按提供方适配器副本、并以家族名副本兜底的按调用读取([#40](https://github.com/arcships/dim/issues/40) 已决定,§1 与 A.2);Provider 的模型选择(`ResolveModelSelection::resolve`,拒绝不可选的显式模型;[AuxiliaryModel](../appserver/auxiliary-model.md))、用于选项列表的可选模型读取(§9.2),以及每个适配器操作与实时会话所需的非对话连接解析([overview 附录 B.2](../overview.md#b2-app-server-进程插件),§9.3);`pluginFiles`(扩展),含二进制原子替换与格式版本([App Server README](../../../../crates/dim-app-server/README.md#trusted-plugin-storage));带隔离的 HostPlatform spawn([HostPlatform](../../../architecture/rust-agent/plugins/HostPlatform.md),隔离补充见 [overview 附录 B.1](../overview.md#b1-session-与分支-capability))。