diff --git a/crates/dim-agent-scheduler/src/loops.rs b/crates/dim-agent-scheduler/src/loops.rs index 0d930de643..1bc941db03 100644 --- a/crates/dim-agent-scheduler/src/loops.rs +++ b/crates/dim-agent-scheduler/src/loops.rs @@ -1,6 +1,6 @@ //! The loop file `scheduler/loops.json`: one inner v1 JSON document inside the //! host's `{version, text}` envelope, kept by the same -//! [`PluginFileTransactions`] withLock and replace transactions as the run +//! [`FileScope`](dim_app_server::plugin_files::FileScope) withLock and replace transactions as the run //! history and the wakeups (design §12). A loop is a session-scoped record //! whose rounds are ordinary `input/message` inputs of one branch. //! @@ -297,21 +297,21 @@ fn encode(loops: Vec) -> String { /// Reads the records. A file that is not valid v1 is an error, not an empty /// list. pub async fn read( - files: &dim_app_server::plugin_files::PluginFileTransactions, + files: &dim_app_server::plugin_files::FileScope, ) -> Result, SchedulerError> { files - .transact(LOOPS_FILE, |current| (None, decode(current))) + .with_lock(LOOPS_FILE, |current| (None, decode(current))) .await? } /// Applies `change` to the records under the file lock. `change` returns /// whether it modified them; an unmodified list is not written back. async fn update( - files: &dim_app_server::plugin_files::PluginFileTransactions, + files: &dim_app_server::plugin_files::FileScope, change: impl FnOnce(&mut Vec) -> Result<(bool, R), SchedulerError> + Send + 'static, ) -> Result { files - .transact(LOOPS_FILE, move |current| { + .with_lock(LOOPS_FILE, move |current| { let mut loops = match decode(current) { Ok(loops) => loops, Err(error) => return (None, Err(error)), diff --git a/crates/dim-agent-scheduler/src/methods.rs b/crates/dim-agent-scheduler/src/methods.rs index b02203195b..eb61e482fc 100644 --- a/crates/dim-agent-scheduler/src/methods.rs +++ b/crates/dim-agent-scheduler/src/methods.rs @@ -18,7 +18,7 @@ use dim_agent_types::InputMode; use dim_app_server::{ ProcessActivity, methods::ManagementMethods, - plugin_files::PluginFileTransactions, + plugin_files::FileScope, settings::{BusinessDocument, SettingsError, SettingsService}, }; use jiff::{SignedDuration, Timestamp}; @@ -44,7 +44,7 @@ pub struct SchedulerPlugin { activity: Key, pub(crate) deliveries: DeliveryHolds, settings: Key, - files: Key, + files: Key, methods: Key, sessions: Key, parts: Key, @@ -110,7 +110,7 @@ impl DynPlugin for SchedulerPlugin { )) })?); let settings = ctx.require_at(&self.settings)?; - let files = ctx.require_at(&self.files)?; + let files = ctx.require_at(&self.files)?.open(ctx)?; let methods = ctx.require_at(&self.methods)?; let sessions = ctx.require_at(&self.sessions)?; settings.register::(ctx)?; @@ -353,7 +353,7 @@ pub(crate) struct Shared { pub(crate) deliveries: DeliveryHolds, pub(crate) sessions: Arc, pub(crate) settings: Arc, - pub(crate) files: Arc, + pub(crate) files: Arc, /// Serializes retention passes, so a pass never deletes what another reads. pub(crate) pruning: tokio::sync::Mutex<()>, /// Serializes lookup passes over `delivering` records (A.6). diff --git a/crates/dim-agent-scheduler/src/runs.rs b/crates/dim-agent-scheduler/src/runs.rs index 1560069117..1d780affa2 100644 --- a/crates/dim-agent-scheduler/src/runs.rs +++ b/crates/dim-agent-scheduler/src/runs.rs @@ -1,9 +1,9 @@ //! The delivery history file `scheduler/runs.json` (A.1, A.7): one inner v1 //! JSON document inside the host's `{version, text}` envelope, which -//! [`PluginFileTransactions`] reads and writes. +//! [`FileScope`] reads and writes. use crate::document::{canonical_instant, format_instant}; use dim_agent_types::PermissionPolicy; -use dim_app_server::plugin_files::{PluginFileError, PluginFileTransactions}; +use dim_app_server::plugin_files::{FileScope, PluginFileError}; use jiff::Timestamp; use serde::{Deserialize, Serialize}; @@ -347,20 +347,20 @@ fn encode(runs: Vec) -> String { /// Reads the history. A file that is not valid v1 is an error, not an empty /// history. -pub async fn read(files: &PluginFileTransactions) -> Result, SchedulerError> { +pub async fn read(files: &FileScope) -> Result, SchedulerError> { files - .transact(RUNS_FILE, |current| (None, decode(current))) + .with_lock(RUNS_FILE, |current| (None, decode(current))) .await? } /// Applies `change` to the history under the file lock. `change` returns /// whether it modified the runs; an unmodified history is not written back. pub async fn update( - files: &PluginFileTransactions, + files: &FileScope, change: impl FnOnce(&mut Vec) -> Result<(bool, R), SchedulerError> + Send + 'static, ) -> Result { files - .transact(RUNS_FILE, move |current| { + .with_lock(RUNS_FILE, move |current| { let mut runs = match decode(current) { Ok(runs) => runs, Err(error) => return (None, Err(error)), diff --git a/crates/dim-agent-scheduler/src/wakeups.rs b/crates/dim-agent-scheduler/src/wakeups.rs index 1e272fc0d2..8d30b3fe8f 100644 --- a/crates/dim-agent-scheduler/src/wakeups.rs +++ b/crates/dim-agent-scheduler/src/wakeups.rs @@ -1,6 +1,6 @@ //! The wakeup file `scheduler/wakeups.json`: one inner v1 JSON document //! inside the host's `{version, text}` envelope, kept by the same -//! [`PluginFileTransactions`] withLock and replace transactions as the run +//! [`FileScope`](dim_app_server::plugin_files::FileScope) withLock and replace transactions as the run //! history ([design §10, A.7]). A wakeup is a one-shot scheduled `input/message` //! into an existing Session: it captures no policy, launches nothing, has no //! deadline, and never appears in `schedule.list` or in the run history. @@ -150,21 +150,21 @@ fn encode(wakeups: Vec) -> String { /// Reads the records. A file that is not valid v1 is an error, not an empty /// list. pub async fn read( - files: &dim_app_server::plugin_files::PluginFileTransactions, + files: &dim_app_server::plugin_files::FileScope, ) -> Result, SchedulerError> { files - .transact(WAKEUPS_FILE, |current| (None, decode(current))) + .with_lock(WAKEUPS_FILE, |current| (None, decode(current))) .await? } /// Applies `change` to the records under the file lock. `change` returns /// whether it modified them; an unmodified list is not written back. async fn update( - files: &dim_app_server::plugin_files::PluginFileTransactions, + files: &dim_app_server::plugin_files::FileScope, change: impl FnOnce(&mut Vec) -> Result<(bool, R), SchedulerError> + Send + 'static, ) -> Result { files - .transact(WAKEUPS_FILE, move |current| { + .with_lock(WAKEUPS_FILE, move |current| { let mut wakeups = match decode(current) { Ok(wakeups) => wakeups, Err(error) => return (None, Err(error)), diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index 9d088e2ebc..32f4d9a3ee 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -23,7 +23,7 @@ impl DynPlugin for Probe { TypeKey::of::(), TypeKey::of::(), TypeKey::of::(), - TypeKey::of::(), + TypeKey::of::(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { @@ -151,13 +151,15 @@ impl Rig { async fn hold_loops_file(&self) -> (std::sync::mpsc::Sender<()>, tokio::task::JoinHandle<()>) { let files = self .ctx - .require::() + .require::() + .unwrap() + .open(&self.ctx) .unwrap(); let (release, held) = std::sync::mpsc::channel(); let (entered, entered_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(async move { files - .transact("scheduler/loops.json", move |_| { + .with_lock("scheduler/loops.json", move |_| { entered.send(()).unwrap(); held.recv_timeout(Duration::from_secs(30)).unwrap(); (None, ()) @@ -172,13 +174,15 @@ impl Rig { async fn hold_wakeup_file(&self) -> (std::sync::mpsc::Sender<()>, tokio::task::JoinHandle<()>) { let files = self .ctx - .require::() + .require::() + .unwrap() + .open(&self.ctx) .unwrap(); let (release, held) = std::sync::mpsc::channel(); let (entered, entered_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(async move { files - .transact("scheduler/wakeups.json", move |_| { + .with_lock("scheduler/wakeups.json", move |_| { entered.send(()).unwrap(); held.recv_timeout(Duration::from_secs(30)).unwrap(); (None, ()) diff --git a/crates/dim-agent-scheduler/tests/lifecycle_flow.rs b/crates/dim-agent-scheduler/tests/lifecycle_flow.rs index acffbb0281..8357315289 100644 --- a/crates/dim-agent-scheduler/tests/lifecycle_flow.rs +++ b/crates/dim-agent-scheduler/tests/lifecycle_flow.rs @@ -610,14 +610,18 @@ async fn branch_events(client: &mut dim_client::Client, session_id: &str) -> Vec async fn hold_runs_file( server: &dim_app_server::RunningServer, ) -> (std::sync::mpsc::Sender<()>, tokio::task::JoinHandle<()>) { + use rutis::host::CtxHost; + let caller = rutis::Ctx::root().unwrap(); let files = server - .service::() - .expect("the App Server provides the file transactions"); + .service::() + .expect("the App Server provides pluginFiles") + .open(&caller) + .unwrap(); let (release, held) = std::sync::mpsc::channel(); let (entered, entered_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(async move { files - .transact("scheduler/runs.json", move |_| { + .with_lock("scheduler/runs.json", move |_| { entered.send(()).unwrap(); held.recv_timeout(std::time::Duration::from_secs(30)) .unwrap(); @@ -625,6 +629,7 @@ async fn hold_runs_file( }) .await .unwrap(); + caller.shutdown().await.unwrap(); }); entered_rx.await.unwrap(); (release, task) diff --git a/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs b/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs index 4b728b5b1a..360ed88ae3 100644 --- a/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs +++ b/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs @@ -3,7 +3,7 @@ //! is refused without changing its bytes. use dim_agent_capabilities::defaults; use dim_agent_runtime::{AgentBuilder, AgentConfig, Names}; -use dim_app_server::{ServerConfig, plugin_files::PluginFileTransactions, serve}; +use dim_app_server::{ServerConfig, serve}; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use serde_json::{Value, json}; @@ -13,7 +13,7 @@ use std::{ }; struct Probe { - files: Key, + files: Key, observed: Arc>, } @@ -26,21 +26,21 @@ impl DynPlugin for Probe { } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let files = ctx.require_at(&self.files)?; + let files = ctx.require_at(&self.files)?.open(ctx)?; let observed = self.observed.clone(); tokio::spawn(async move { let created = files - .transact("scheduler/runs.json", |current| { + .with_lock("scheduler/runs.json", |current| { (Some("first".to_owned()), current.map(str::to_owned)) }) .await; let read = files - .transact("scheduler/runs.json", |current| { + .with_lock("scheduler/runs.json", |current| { (None, current.map(str::to_owned)) }) .await; let refused = files - .transact("scheduler/invalid.json", |_| (Some("never".to_owned()), ())) + .with_lock("scheduler/invalid.json", |_| (Some("never".to_owned()), ())) .await; let _ = observed.set(json!({ "created": format!("{created:?}"), diff --git a/crates/dim-agent-scheduler/tests/watch_flow.rs b/crates/dim-agent-scheduler/tests/watch_flow.rs index 4757d6b948..abf525e07b 100644 --- a/crates/dim-agent-scheduler/tests/watch_flow.rs +++ b/crates/dim-agent-scheduler/tests/watch_flow.rs @@ -363,7 +363,7 @@ async fn a_reload_answers_the_open_call_and_a_new_watch_starts_at_zero() { wait_watching(&mut client, first).await; // The Scheduler reloads when a row it injects restarts: PluginFiles - // provides its PluginFileTransactions. The restart is the row's own, so + // provides its FileScope. The restart is the row's own, so // the test drives it through the probe's runtime context. let generation = scheduler_generation(&server); let files = server diff --git a/crates/dim-app-server/README.md b/crates/dim-app-server/README.md index 8a25e5dcee..20804fb606 100644 --- a/crates/dim-app-server/README.md +++ b/crates/dim-app-server/README.md @@ -530,7 +530,7 @@ The embedding host must provision each consumer's parent directories before enabling it: `withLock` returns `io` for a missing parent and does not create it. A host without a product home names its plugin root in `ServerConfig.plugin_files`. The `dimcode` development profile (`--model-config`) uses its `--home` directory, so the root and its `scheduler/` directory are provisioned there. -A plugin declares `inject: ['pluginFiles']` and opens a fresh scope during each `apply`. Register `scope.close()` with `ctx.effect` immediately after opening, then register business cleanup. The host chooses the authorized product root; the plugin supplies relative file paths only. This is a trusted-plugin API, not a sandbox for untrusted Node code. +A plugin with a row-bound scope declares `inject: ['pluginFiles']` and opens a fresh scope during each `apply`. Register `scope.close()` with `ctx.effect` immediately after opening, then register business cleanup. The host chooses the authorized product root; the plugin supplies relative file paths only. This is a trusted-plugin API, not a sandbox for untrusted Node code. A scope offers `withLock(name, callback, cancelled?)`, `list(prefix)`, `remove(name)`, `directory(name)`, `openRead(name)` and `writeStream(name, next)`; a lease offers `read()`, `replace(text)`, `backup(suffix)`, `readBytes()` and `replaceBytes(bytes)`. Every name is a path relative to the authorized root, resolved through FileStorage: `..`, an absolute path and this module's reserved names fail `invalid_path`. @@ -538,14 +538,14 @@ A scope offers `withLock(name, callback, cancelled?)`, `list(prefix)`, `remove(n Every file is either a text envelope or raw bytes. `read()` and `replace(text)` use the envelope below. `readBytes()` returns the file's bytes whole, so a text file returns its stored envelope; `replaceBytes(bytes)` writes raw bytes with no envelope. A text read of a raw file fails `invalid_data` and leaves it untouched. Both byte operations are whole-buffer and capped at [`MAX_WHOLE_FILE_BYTES`](src/plugin_files.rs) (8 MiB): the runtime channel's frame is 16 MiB and carries bytes base64-encoded, four bytes for every three, so 12 MiB is the raw ceiling before any envelope and 8 MiB leaves the envelope and both sides' copies room while bounding one allocation. A file over the cap fails `invalid_data` before it is read, and a replacement over it fails `invalid_data` without writing. A buffer large enough that its call message would exceed the runtime's 16 MiB frame never reaches the host: the plugin's own runtime refuses that call before sending it, with a `RangeError` coded `bad-value` naming the argument and the limit, and neither the plugin row nor the file store is affected — the same holds for any call argument, a large text `replace` included. For larger files use a pinned reader or a streamed replacement as described below. -A Rust process plugin uses the typed `PluginFileTransactions` service (`names.key::()`) instead. `transact(name, change)` runs `change` on the inner text under the file's lock. `change` receives `None` for a missing file and returns the replacement text (`None` keeps the file as it is) together with its own result. The host writes and checks the same `{version: 1, text}` envelope. An envelope that is not version 1 fails with `InvalidData` before `change` runs, and its bytes stay unchanged. +`PluginFiles::open(ctx)` ties a Rust scope to its row. EventHub uses `PluginFiles::scope(Some(ctx.clone()))` so admitted publishes can finish their writes across a row restart. The caller releases its last `Arc` after those operations settle. Stopping the file provider cancels and drains its active operations. The scope’s `with_lock(name, change)` runs `change` on the inner text under the file's lock. `change` receives `None` for a missing file and returns the replacement text (`None` keeps the file as it is) together with its own result. The host writes and checks the same `{version: 1, text}` envelope. An envelope that is not version 1 fails with `InvalidData` before `change` runs, and its bytes stay unchanged. -Besides `transact`, the service offers: +The file scope also provides these operations. | Method | Value | | --- | --- | | `read_bytes(name)` | the whole file, envelope included, or `None` when absent; over the cap is `InvalidData` | -| `open_read(name)` | a `FileReader` pinning the file for offset reads of at most 64 KiB, or `None` when absent | +| `open_read(name)` | `OpenRead { read_id, size }` for `FsHost::read_at` and `close_read`, or `None` when absent | | `write_stream(name, source)` | replaces the file from a reader under its lock; no envelope and no size bound | | `list(prefix)` | one level under `prefix`, each a `PluginFileEntry { name, kind }` | | `remove(name)` | a file or a directory tree; `Locked` while a lease holds it or a file beneath it | diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 2feea9c229..e892c17b0b 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1439,7 +1439,6 @@ pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCata catalog.register_shared(dim_agent_runtime::names::name_of::< collaboration::CollaborationDirectory, >()); - register::(catalog, None); register::(catalog, None); catalog.register_shared(dim_agent_runtime::names::name_of::()); register::(catalog, None); @@ -1508,7 +1507,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("mentionIndex", "host-resource"), ("modelHost", "owner-api"), ("openAICodexOAuthService", "secret"), - ("pluginFileTransactions", "host-resource"), ("prepareContextHost", "hot-path"), ("prepareModelHost", "hot-path"), ("prompt", "hot-path"), diff --git a/crates/dim-app-server/src/plugin_files.rs b/crates/dim-app-server/src/plugin_files.rs index 30dcf12ccc..8f064848a8 100644 --- a/crates/dim-app-server/src/plugin_files.rs +++ b/crates/dim-app-server/src/plugin_files.rs @@ -1,7 +1,7 @@ //! Generic, host-owned file transactions for an explicitly authorized plugin root. //! No account formats or provider policy belong at this boundary. use dim_agent_capabilities::file_storage::{ - DirectoryEntry, EntryKind, FileLease, FilePath, FileReader, FileStorage, FileStorageError, + DirectoryEntry, EntryKind, FileLease, FilePath, FileStorage, FileStorageError, OpenRead, }; use dim_agent_runtime::Names; use rutis::Ctx; @@ -77,13 +77,13 @@ struct Files { stopping: CancellationToken, tasks: TaskTracker, } -struct Scope { +pub struct FileScope { caller: Option, files: Arc, stopping: CancellationToken, tasks: TaskTracker, } -impl Scope { +impl FileScope { fn quiesce(&self) { let _admission = self.files.admission.lock().unwrap(); self.stopping.cancel(); @@ -101,27 +101,27 @@ impl Scope { [ ( "withLock".into(), - Value::callback(move |args| transaction.with_lock(args)), + Value::callback(move |args| transaction.dispatch_with_lock(args)), ), ( "directory".into(), - Value::callback(move |args| directory.directory(args)), + Value::callback(move |args| directory.dispatch_directory(args)), ), ( "openRead".into(), - Value::callback(move |args| reader.open_read(args)), + Value::callback(move |args| reader.dispatch_open_read(args)), ), ( "writeStream".into(), - Value::callback(move |args| writer.write_stream(args)), + Value::callback(move |args| writer.dispatch_write_stream(args)), ), ( "list".into(), - Value::callback(move |args| listing.list(args)), + Value::callback(move |args| listing.dispatch_list(args)), ), ( "remove".into(), - Value::callback(move |args| removal.remove(args)), + Value::callback(move |args| removal.dispatch_remove(args)), ), ( "quiesce".into(), @@ -145,7 +145,7 @@ impl Scope { .into(), ) } - fn directory(self: &Arc, args: Value) -> Reply { + fn dispatch_directory(self: &Arc, args: Value) -> Reply { self.operation(args, |files, _, path, cancel| { Box::pin(async move { let result = files @@ -165,7 +165,7 @@ impl Scope { }) } - fn open_read(self: &Arc, args: Value) -> Reply { + fn dispatch_open_read(self: &Arc, args: Value) -> Reply { let caller = self .caller .clone() @@ -187,7 +187,7 @@ impl Scope { }) } - fn write_stream(self: &Arc, args: Value) -> Reply { + fn dispatch_write_stream(self: &Arc, args: Value) -> Reply { let [name, next]: [Value; 2] = args.list()?.try_into().map_err(|_| invalid())?; let next = next.reference()?; self.operation(Value::List(vec![name]), move |files, _, path, cancel| { @@ -211,7 +211,7 @@ impl Scope { /// The value of the named directory's entries, one level, relative to the /// authorized root. - fn list(self: &Arc, args: Value) -> Reply { + fn dispatch_list(self: &Arc, args: Value) -> Reply { self.operation(args, |files, prefix, path, cancel| { Box::pin(async move { Ok(match files.storage.list(&path, &cancel).await { @@ -222,7 +222,7 @@ impl Scope { }) } /// The value of removing `name`, a file or a directory tree. - fn remove(self: &Arc, args: Value) -> Reply { + fn dispatch_remove(self: &Arc, args: Value) -> Reply { self.operation(args, |files, _, path, cancel| { Box::pin(async move { Ok(match files.storage.remove(&path, &cancel).await { @@ -275,7 +275,7 @@ impl Scope { .unwrap_or_else(|error| Ok(failure(FileStorageError::Worker(error)))) })) } - fn with_lock(self: &Arc, args: Value) -> Reply { + fn dispatch_with_lock(self: &Arc, args: Value) -> Reply { let mut args = args.list()?.into_iter(); let name: String = serde_json::from_value(args.next().ok_or_else(invalid)?.json()?) .map_err(|_| invalid())?; @@ -304,18 +304,7 @@ impl Scope { let owner = self.files.tasks.token(); let task = self.tasks.spawn(async move { let _owner = owner; - let acquire = async { - loop { - match scope.files.storage.lock(&path, &acquisition).await { - Ok(lease) => return Ok(lease), - Err(FileStorageError::Locked) => tokio::select! { - _ = acquisition.cancelled() => return Err(FileStorageError::Closed), - _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}, - }, - Err(error) => return Err(error), - } - } - }; + let acquire = acquire(&scope.files.storage, &path, &acquisition); let cancelled = async { match cancelled { Some(reference) => { @@ -416,24 +405,9 @@ fn lease_value(lease: Arc>>, tasks: TaskTra }; let cancel = CancellationToken::new(); let result = match (method, argument) { - ("read", LeaseArgument::None) => match lease.read(&cancel).await { - Ok(bytes) => match serde_json::from_slice::(&bytes) - { - Ok(StoredFile { - version: FORMAT_VERSION, - text, - }) => Ok(json!(text).into()), - _ => Err(FileStorageError::Io( - io::ErrorKind::InvalidData.into(), - )), - }, - Err(FileStorageError::Io(error)) - if error.kind() == io::ErrorKind::NotFound => - { - Ok(json!(null).into()) - } - Err(error) => Err(error), - }, + ("read", LeaseArgument::None) => read_text(lease, &cancel) + .await + .map(|value| json!(value).into()), ("readBytes", LeaseArgument::None) => { match lease.read_limited(MAX_WHOLE_FILE_BYTES, &cancel).await { Ok(bytes) => Ok(Value::Bytes(bytes)), @@ -445,18 +419,11 @@ fn lease_value(lease: Arc>>, tasks: TaskTra Err(error) => Err(error), } } - ("replace", LeaseArgument::Text(text)) => lease - .replace( - serde_json::to_vec(&StoredFile { - version: FORMAT_VERSION, - text, - }) - .expect("text records contain only serializable fields"), - private_permissions(), - &cancel, - ) - .await - .map(|_| json!(null).into()), + ("replace", LeaseArgument::Text(text)) => { + replace_text(lease, text, &cancel) + .await + .map(|()| json!(null).into()) + } ("replaceBytes", LeaseArgument::Bytes(bytes)) if bytes.len() <= MAX_WHOLE_FILE_BYTES => { @@ -513,7 +480,7 @@ pub enum PluginFileError { Io(String), } -/// One entry of a [`PluginFileTransactions::list`] result. +/// One entry of a [`FileScope::list`] result. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PluginFileEntry { /// The entry's path relative to the authorized root, ready to pass to @@ -556,19 +523,42 @@ fn join_name(prefix: &Path, leaf: &str) -> String { name } -/// Typed transactions on files under the authorized root, for process plugins -/// written in Rust. The host's `{version, text}` envelope is read and written -/// here; a caller sees and returns only the inner text, as the JSON -/// `pluginFiles` scope exposes it. -pub struct PluginFileTransactions(Arc); -impl PluginFileTransactions { +/// Plugin-owned files under the configured root. +pub struct PluginFiles(Arc); + +impl PluginFiles { + /// Opens a caller-managed scope. Admitted work can retain it across a row + /// restart. Release the last scope reference after admitted work settles. + /// All operations still end when the file service stops. + pub fn scope(&self, caller: Option) -> Arc { + Arc::new(FileScope { + caller, + files: self.0.clone(), + stopping: self.0.stopping.child_token(), + tasks: TaskTracker::new(), + }) + } + + pub fn open(&self, caller: &Ctx) -> rutis::Result> { + let scope = self.scope(Some(caller.clone())); + let cleanup = scope.clone(); + caller.effect(move || async move { + cleanup.quiesce(); + cleanup.tasks.wait().await; + Ok(()) + })?; + Ok(scope) + } +} + +impl FileScope { /// Runs `change` on the inner text of `name` under its file lock. `change` /// receives `None` for a missing file. It returns the replacement text /// (`None` keeps the file as it is) and its own result, which the /// transaction returns. An envelope that is not version 1 fails with /// [`PluginFileError::InvalidData`] before `change` runs, and the bytes are /// left as they were. - pub async fn transact( + pub async fn with_lock( &self, name: &str, change: impl FnOnce(Option<&str>) -> (Option, R) + Send + 'static, @@ -604,10 +594,11 @@ impl PluginFileTransactions { /// Opens `name` for streaming reads, or `None` when it is absent. The /// reader pins the file: reads take explicit offsets and return at most /// 64 KiB each, and replacing the name does not change an open reader. - pub async fn open_read(&self, name: &str) -> Result, PluginFileError> { - self.run(name, |storage, path, stopping| { + pub async fn open_read(&self, name: &str) -> Result, PluginFileError> { + let caller = self.caller.clone().ok_or(PluginFileError::Closed)?; + self.run(name, move |storage, path, stopping| { Box::pin(async move { - match storage.open_read(&path, &stopping).await { + match storage.open_reader(&caller, &path, &stopping).await { Ok(reader) => Ok(Some(reader)), Err(FileStorageError::Io(error)) if error.kind() == io::ErrorKind::NotFound => { Ok(None) @@ -708,19 +699,19 @@ impl PluginFileTransactions { + Send + 'static, ) -> Result { - let files = self.0.clone(); + let files = &self.files; let path = files .storage .path(files.root, name) .map_err(|_| PluginFileError::InvalidPath)?; let admission = files.admission.lock().unwrap(); - if files.stopping.is_cancelled() { + if self.stopping.is_cancelled() { return Err(PluginFileError::Closed); } - let stopping = files.stopping.child_token(); + let stopping = self.stopping.child_token(); let storage = files.storage.clone(); let owner = files.tasks.token(); - let task = files.tasks.spawn(async move { + let task = self.tasks.spawn(async move { let _owner = owner; action(storage, path, stopping).await }); @@ -739,32 +730,46 @@ async fn transact_file( let mut lease = acquire(&storage, &path, &stopping) .await .map_err(file_error)?; - let current = match lease.read(&stopping).await { - Ok(bytes) => match serde_json::from_slice::(&bytes) { - Ok(StoredFile { - version: FORMAT_VERSION, - text, - }) => Some(text), - _ => return Err(PluginFileError::InvalidData), - }, - Err(FileStorageError::Io(error)) if error.kind() == io::ErrorKind::NotFound => None, - Err(error) => return Err(file_error(error)), - }; + let current = read_text(&mut lease, &stopping).await.map_err(file_error)?; let (next, result) = change(current.as_deref()); if let Some(text) = next { - let bytes = serde_json::to_vec(&StoredFile { - version: FORMAT_VERSION, - text, - }) - .expect("text records contain only serializable fields"); - lease - .replace(bytes, private_permissions(), &stopping) + replace_text(&mut lease, text, &stopping) .await .map_err(file_error)?; } Ok(result) } +async fn read_text( + lease: &mut FileLease, + cancel: &CancellationToken, +) -> Result, FileStorageError> { + match lease.read(cancel).await { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(StoredFile { + version: FORMAT_VERSION, + text, + }) => Ok(Some(text)), + _ => Err(FileStorageError::Io(io::ErrorKind::InvalidData.into())), + }, + Err(FileStorageError::Io(error)) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +async fn replace_text( + lease: &mut FileLease, + text: String, + cancel: &CancellationToken, +) -> Result<(), FileStorageError> { + let bytes = serde_json::to_vec(&StoredFile { + version: FORMAT_VERSION, + text, + }) + .expect("text records contain only serializable fields"); + lease.replace(bytes, private_permissions(), cancel).await +} + fn callback_reader( next: rutis_bridge::session::Reference, cancel: CancellationToken, @@ -821,8 +826,7 @@ async fn acquire( } } -struct Dispatch(Arc); -impl HostDispatch for Dispatch { +impl HostDispatch for PluginFiles { fn methods(&self) -> Option { Some(json!({"open":"async"})) } @@ -830,12 +834,7 @@ impl HostDispatch for Dispatch { if method != "open" || !args.list()?.is_empty() { return Err(invalid()); } - let scope = Arc::new(Scope { - caller: rutis_bridge::session::caller_row().map(|row| row.ctx().clone()), - files: self.0.clone(), - stopping: self.0.stopping.child_token(), - tasks: TaskTracker::new(), - }); + let scope = self.scope(rutis_bridge::session::caller_row().map(|row| row.ctx().clone())); Ok(Value::future(async move { Ok(scope.value()) })) } } @@ -881,11 +880,12 @@ impl DynPlugin for PluginFilesPlugin { owner.tasks.wait().await; Ok(()) })?; + let service = Arc::new(PluginFiles(files)); ctx.provide_at( host_key("pluginFiles"), - Arc::new(Dispatch(files.clone())) as Arc, + service.clone() as Arc, )?; - ctx.provide_as::(Arc::new(PluginFileTransactions(files)))?; + ctx.provide_as::(service)?; Ok(Effect::Done) }) } diff --git a/crates/dim-app-server/tests/plugin_files_flow.rs b/crates/dim-app-server/tests/plugin_files_flow.rs index 92b362c490..a80136447b 100644 --- a/crates/dim-app-server/tests/plugin_files_flow.rs +++ b/crates/dim-app-server/tests/plugin_files_flow.rs @@ -2,8 +2,7 @@ use dim_agent_capabilities::file_storage::{EntryKind, FileStorage, FileStoragePlugin}; use dim_agent_runtime::Names; use dim_app_server::plugin_files::{ - MAX_WHOLE_FILE_BYTES, PluginFileEntry, PluginFileError, PluginFileTransactions, - PluginFilesPlugin, + FileScope, MAX_WHOLE_FILE_BYTES, PluginFileEntry, PluginFileError, PluginFilesPlugin, }; use rutis::Ctx; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; @@ -63,13 +62,18 @@ async fn call(value: &Value, name: &str, args: Vec) -> Value { ) .await } -type Services = (Arc, Arc); +type Services = ( + Arc, + Arc, + Arc, +); struct Capture { captured: Arc>>, services: Arc>, files: Key, - transactions: Key, + transactions: Key, storage: Key, + fs: Key, } impl DynPlugin for Capture { fn name(&self) -> &str { @@ -80,15 +84,18 @@ impl DynPlugin for Capture { self.files.erase(), self.transactions.erase(), self.storage.erase(), + self.fs.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { let files = ctx.require_at(&self.files)?; let _ = self.captured.set(files); - let transactions = ctx.require_at(&self.transactions)?; + let transactions = ctx.require_at(&self.transactions)?.open(ctx)?; let storage = ctx.require_at(&self.storage)?; - let _ = self.services.set((transactions, storage)); + let _ = self + .services + .set((transactions, storage, ctx.require_at(&self.fs)?)); Ok(Effect::Done) }) } @@ -113,6 +120,7 @@ async fn mount(path: &Path) -> (Ctx, Value, Services) { files: key, transactions: names.key().unwrap(), storage: names.key().unwrap(), + fs: names.key().unwrap(), })) .await .unwrap(); @@ -510,7 +518,7 @@ async fn concurrent_stale_lock_reclaimers_serialize_through_native_ownership() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn binary_files_round_trip_and_stream_without_an_envelope() { let directory = Directory::new(); - let (root, _, (files, _)) = mount(&directory.0).await; + let (root, scope, (files, _, fs)) = mount(&directory.0).await; let cancel = CancellationToken::new(); files.directory("media").await.unwrap(); @@ -530,11 +538,16 @@ async fn binary_files_round_trip_and_stream_without_an_envelope() { assert_eq!(files.read_bytes("media/missing.bin").await.unwrap(), None); let reader = files.open_read("media/blob.bin").await.unwrap().unwrap(); - assert_eq!(reader.len(), bytes.len() as u64); + assert_eq!(reader.size, bytes.len() as u64); let mut streamed = Vec::new(); loop { - let chunk = reader - .read_at(streamed.len() as u64, usize::MAX, &cancel) + let chunk = fs + .read_at( + reader.read_id.clone(), + streamed.len() as u64, + usize::MAX, + &cancel, + ) .await .unwrap(); if chunk.is_empty() { @@ -542,6 +555,7 @@ async fn binary_files_round_trip_and_stream_without_an_envelope() { } streamed.extend_from_slice(&chunk); } + fs.close_read(reader.read_id).await.unwrap(); assert_eq!(streamed, bytes); assert!( files @@ -552,16 +566,34 @@ async fn binary_files_round_trip_and_stream_without_an_envelope() { ); files - .transact("media/text.json", |_| (Some("inner".to_owned()), ())) + .with_lock("media/text.json", |_| (Some("inner".to_owned()), ())) .await .unwrap(); + let read = call( + &scope, + "withLock", + vec![ + json!("media/text.json").into(), + Value::callback(|args| { + let lease = args.list()?.remove(0); + Ok(Value::future(async move { + Ok(call(&lease, "read", vec![]).await) + })) + }), + ], + ) + .await; + assert_eq!( + read.json().unwrap(), + json!({"ok": true, "value": {"ok": true, "value": "inner"}}) + ); assert_eq!( files.read_bytes("media/text.json").await.unwrap().unwrap(), br#"{"version":1,"text":"inner"}"# ); assert_eq!( files - .transact("media/blob.bin", |current| ( + .with_lock("media/blob.bin", |current| ( None, current.map(str::to_owned) )) @@ -592,7 +624,7 @@ async fn binary_files_round_trip_and_stream_without_an_envelope() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_cancelled_streaming_write_keeps_the_old_file_and_leaves_no_temporary() { let directory = Directory::new(); - let (root, _, (files, _)) = mount(&directory.0).await; + let (root, _, (files, _, _)) = mount(&directory.0).await; files.directory("media").await.unwrap(); files .write_stream("media/blob.bin", std::io::Cursor::new(b"original".to_vec())) @@ -665,7 +697,7 @@ async fn a_cancelled_streaming_write_keeps_the_old_file_and_leaves_no_temporary( #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn list_remove_and_work_directories_follow_the_root_and_its_leases() { let directory = Directory::new(); - let (root, _, (files, storage)) = mount(&directory.0).await; + let (root, _, (files, storage, _)) = mount(&directory.0).await; let cancel = CancellationToken::new(); let work = files.directory("media/tasks/a1/result").await.unwrap(); @@ -711,7 +743,7 @@ async fn list_remove_and_work_directories_follow_the_root_and_its_leases() { .await .unwrap(); files - .transact("media/tasks/a1/task.json", |_| { + .with_lock("media/tasks/a1/task.json", |_| { (Some("record".to_owned()), ()) }) .await @@ -774,7 +806,7 @@ async fn list_remove_and_work_directories_follow_the_root_and_its_leases() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_backslash_in_a_listed_name_stays_inside_its_component() { let directory = Directory::new(); - let (root, _, (files, _)) = mount(&directory.0).await; + let (root, _, (files, _, _)) = mount(&directory.0).await; std::fs::create_dir_all(directory.0.join("a\\b")).unwrap(); std::fs::create_dir_all(directory.0.join("a/b")).unwrap(); diff --git a/crates/dim-event-hub/src/lib.rs b/crates/dim-event-hub/src/lib.rs index 35aa1efe18..cd23c9287b 100644 --- a/crates/dim-event-hub/src/lib.rs +++ b/crates/dim-event-hub/src/lib.rs @@ -21,7 +21,6 @@ mod subscriptions; mod text; use dim_agent_runtime::{AgentBuilder, Names, PartRegistry, PartScope}; -use dim_app_server::plugin_files::PluginFileTransactions; use dim_app_server::{ProcessActivity, methods::ManagementMethods}; use hub::Shared; use rutis::Ctx; @@ -118,7 +117,7 @@ pub fn install_with(builder: &mut AgentBuilder, texts: EventHubTexts) { } pub struct EventHubPlugin { - files: Key, + files: Key, methods: Key, sessions: Key, parts: Key, @@ -166,7 +165,7 @@ impl DynPlugin for EventHubPlugin { } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let files = ctx.require_at(&self.files)?; + let files = ctx.require_at(&self.files)?.scope(Some(ctx.clone())); let sessions = ctx.require_at(&self.sessions)?; let store = Arc::new(store::Store::new(files, self.state.clone())); // The file is read once, into the install's view; a corrupt one diff --git a/crates/dim-event-hub/src/store.rs b/crates/dim-event-hub/src/store.rs index 3cf7cdee9f..1c0b91d291 100644 --- a/crates/dim-event-hub/src/store.rs +++ b/crates/dim-event-hub/src/store.rs @@ -1,6 +1,6 @@ //! The subscription file `eventhub/subscriptions.json` (design §2.2, A.5): //! one inner v1 JSON document inside the host's `{version, text}` envelope, -//! which [`PluginFileTransactions`] reads and writes. The part reads the file +//! which [`FileScope`] reads and writes. The part reads the file //! once when it applies; the subscriptions and the guide records live in the //! install's state, and every change writes the file through the running //! generation's handle under the install's change lock and then replaces that @@ -11,7 +11,7 @@ use crate::{ state::InstanceState, }; use dim_agent_types::InputMode; -use dim_app_server::plugin_files::{PluginFileError, PluginFileTransactions}; +use dim_app_server::plugin_files::{FileScope, PluginFileError}; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, HashSet}, @@ -236,12 +236,12 @@ fn encode(document: &Document) -> String { /// a detached publish still runs after its generation ended lands where the /// next generation reads it (design §2.1, A.5). pub(crate) struct Store { - files: Arc, + files: Arc, state: Arc, } impl Store { - pub(crate) fn new(files: Arc, state: Arc) -> Self { + pub(crate) fn new(files: Arc, state: Arc) -> Self { Self { files, state } } @@ -254,7 +254,7 @@ impl Store { let _guard = self.state.change_lock().await; let document = self .files - .transact(SUBSCRIPTIONS_FILE, |current| (None, decode(current))) + .with_lock(SUBSCRIPTIONS_FILE, |current| (None, decode(current))) .await .map_err(|error| error.to_string())??; self.state.replace_subscriptions(document); @@ -288,7 +288,7 @@ impl Store { let _guard = self.state.change_lock().await; let outcome = self .files - .transact(SUBSCRIPTIONS_FILE, move |current| { + .with_lock(SUBSCRIPTIONS_FILE, move |current| { let mut document = match decode(current) { Ok(document) => document, Err(error) => { diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 1e2e41a7f4..4aa75f4af7 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -17,7 +17,7 @@ use crate::task::{ }; use crate::{Evaluation, catalog_category, host_target, is_understand}; use base64::{Engine, engine::general_purpose::STANDARD}; -use dim_agent_capabilities::file_storage::{EntryKind, FileReader}; +use dim_agent_capabilities::file_storage::{EntryKind, FsHost, OpenRead}; use dim_agent_capabilities::host::{ ModalityConnection, ModalityConnectionHost, ModalityTarget, ModelSelectionHost, SelectableModelsHost, @@ -27,7 +27,7 @@ use dim_agent_capabilities::host_platform::{ }; use dim_agent_capabilities::methods::{Progress, RpcError}; use dim_agent_types::ModelId; -use dim_app_server::plugin_files::PluginFileTransactions; +use dim_app_server::plugin_files::FileScope; use dim_app_server::settings::SettingsService; use jiff::{SignedDuration, Timestamp}; use rutis::Ctx; @@ -465,7 +465,8 @@ pub struct TaskResultReply { /// The plugin's shared state: everything the scheduler, the methods and the /// running tasks read. pub(crate) struct Shared { - pub(crate) files: Arc, + pub(crate) files: Arc, + fs: Arc, pub(crate) settings: Arc, pub(crate) selection: Arc, pub(crate) selectable: Arc, @@ -490,7 +491,8 @@ impl Shared { reason = "one parameter per host handle the modality part is assembled from" )] pub(crate) fn new( - files: Arc, + files: Arc, + fs: Arc, settings: Arc, selection: Arc, selectable: Arc, @@ -501,6 +503,7 @@ impl Shared { ) -> Self { Self { files, + fs, settings, selection, selectable, @@ -1431,25 +1434,34 @@ impl ModalityTasks { else { return Err(not_found(format!("Unknown result file {}", params.name))); }; - let length = reader.len().min(file.bytes); - let mut cursor = params.offset; - let mut data = Vec::new(); - while cursor < length && (data.len() as u64) < params.length { - let want = (params.length - data.len() as u64).min(length - cursor); - let chunk = reader - .read_at(cursor, want as usize, cancel) - .await - .map_err(|error| storage_error(error.to_string()))?; - if chunk.is_empty() { - break; + let result: Result = async { + let length = reader.size.min(file.bytes); + let mut cursor = params.offset; + let mut data = Vec::new(); + while cursor < length && (data.len() as u64) < params.length { + let want = (params.length - data.len() as u64).min(length - cursor); + let chunk = self + .shared + .fs + .read_at(reader.read_id.clone(), cursor, want as usize, cancel) + .await + .map_err(|error| storage_error(error.to_string()))?; + if chunk.is_empty() { + break; + } + cursor += chunk.len() as u64; + data.extend(chunk); } - cursor += chunk.len() as u64; - data.extend(chunk); + Ok(TaskResultReply { + data_base64: STANDARD.encode(&data), + eof: cursor >= length, + }) } - Ok(TaskResultReply { - data_base64: STANDARD.encode(&data), - eof: cursor >= length, - }) + .await; + let closed = self.shared.fs.close_read(reader.read_id).await; + let reply = result?; + closed.map_err(|error| storage_error(error.to_string()))?; + Ok(reply) } /// The per-client submission lock. @@ -2478,7 +2490,7 @@ impl Shared { &self, work_name: &str, name: &str, - ) -> Result, String> { + ) -> Result, String> { self.files .open_read(&format!("{work_name}/{name}")) .await @@ -2637,9 +2649,9 @@ impl Shared { } }; if let Some(limit) = cap { - total = total.saturating_add(source.len()); + total = total.saturating_add(source.size); if total > limit { - drop(source); + let _ = self.fs.close_read(source.read_id).await; self.discard_results(&record.task_id, &written).await; self.fail_settled( slot, @@ -2652,13 +2664,21 @@ impl Shared { } self.artifacts.after_count(&work, &file.name); } - let (bytes, sha256) = match task::write_result( + let read_id = source.read_id; + let result = task::write_result( &self.files, &record.task_id, &file.name, - ReaderSource::new(source), + ReaderSource::new(self.fs.clone(), read_id.clone()), ) - .await + .await; + if result.is_ok() { + written.push(file.name.clone()); + } + let closed = self.fs.close_read(read_id).await; + let (bytes, sha256) = match result + .map_err(|e| e.to_string()) + .and_then(|result| closed.map(|()| result).map_err(|e| e.to_string())) { Ok(result) => result, Err(error) => { @@ -2668,7 +2688,6 @@ impl Shared { return; } }; - written.push(file.name.clone()); results.push(ResultFile { name: file.name, media_type: file.media_type, @@ -2733,10 +2752,15 @@ impl Shared { .await .map_err(|error| error.to_string())? .ok_or_else(|| "The OCR helper wrote no readable result".to_owned())?; - let parsed = tokio::task::spawn_blocking(move || { - dim_ocr::read_pages(ReaderSource::new(reader), MAX_DATA_TEXT_BYTES) - }) - .await; + let read_id = reader.read_id; + let source = ReaderSource::new(self.fs.clone(), read_id.clone()); + let parsed = + tokio::task::spawn_blocking(move || dim_ocr::read_pages(source, MAX_DATA_TEXT_BYTES)) + .await; + self.fs + .close_read(read_id) + .await + .map_err(|e| e.to_string())?; let Ok(Ok(pages)) = parsed else { return Err("The OCR helper wrote no readable result".to_owned()); }; @@ -2864,20 +2888,22 @@ enum OutputData { ResultJson, } -/// A synchronous [`Read`] over a pinned [`FileReader`]: each read blocks the +/// A synchronous [`Read`] over a pinned file: each read blocks the /// calling thread on the storage's asynchronous read. Only used inside /// `spawn_blocking`, never on a runtime worker. struct ReaderSource { - reader: FileReader, + fs: Arc, + read_id: String, handle: tokio::runtime::Handle, cancel: CancellationToken, offset: u64, } impl ReaderSource { - fn new(reader: FileReader) -> Self { + fn new(fs: Arc, read_id: String) -> Self { Self { - reader, + fs, + read_id, handle: tokio::runtime::Handle::current(), cancel: CancellationToken::new(), offset: 0, @@ -2892,7 +2918,12 @@ impl Read for ReaderSource { } let chunk = self .handle - .block_on(self.reader.read_at(self.offset, buffer.len(), &self.cancel)) + .block_on(self.fs.read_at( + self.read_id.clone(), + self.offset, + buffer.len(), + &self.cancel, + )) .map_err(|error| std::io::Error::other(error.to_string()))?; let count = chunk.len().min(buffer.len()); buffer[..count].copy_from_slice(&chunk[..count]); diff --git a/crates/dim-modality/src/lib.rs b/crates/dim-modality/src/lib.rs index 8102f7d0fb..6a4d0365fe 100644 --- a/crates/dim-modality/src/lib.rs +++ b/crates/dim-modality/src/lib.rs @@ -50,7 +50,6 @@ use dim_agent_runtime::{AgentBuilder, Names}; use dim_agent_types::{ModalityModelSnapshot, ModelCapabilitySnapshot, ModelId}; use dim_app_server::{ methods::ManagementMethods, - plugin_files::PluginFileTransactions, protocol::Empty, settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}, }; @@ -1200,7 +1199,8 @@ pub struct ModalityPlugin { methods: Key, selection: Key, selectable: Key, - files: Key, + files: Key, + fs: Key, options: InstallOptions, } impl ModalityPlugin { @@ -1211,6 +1211,7 @@ impl ModalityPlugin { selection: names.key()?, selectable: names.key()?, files: names.key()?, + fs: names.key()?, options, }) } @@ -1226,6 +1227,7 @@ impl DynPlugin for ModalityPlugin { self.selection.erase(), self.selectable.erase(), self.files.erase(), + self.fs.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { @@ -1234,12 +1236,13 @@ impl DynPlugin for ModalityPlugin { let methods = ctx.require_at(&self.methods)?; let selection = ctx.require_at(&self.selection)?; let selectable = ctx.require_at(&self.selectable)?; - let files = ctx.require_at(&self.files)?; + let files = ctx.require_at(&self.files)?.open(ctx)?; settings.register::(ctx)?; // The task layer: one state for the methods, the scheduler and // `modalityTasks` (A.3, A.6). let shared = Arc::new(engine::Shared::new( files, + ctx.require_at(&self.fs)?, settings.clone(), selection.clone(), selectable.clone(), diff --git a/crates/dim-modality/src/task.rs b/crates/dim-modality/src/task.rs index e41a8a1baf..371de85d2a 100644 --- a/crates/dim-modality/src/task.rs +++ b/crates/dim-modality/src/task.rs @@ -8,7 +8,7 @@ //! wins and a later outcome is discarded. use crate::adapter::AdapterProgress; use dim_agent_types::ModelId; -use dim_app_server::plugin_files::{PluginFileError, PluginFileTransactions}; +use dim_app_server::plugin_files::{FileScope, PluginFileError}; use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest as _, Sha256}; @@ -220,12 +220,9 @@ fn parse(text: &str) -> Result { /// Reads a task record, or `None` when it does not exist. The file's lock is /// taken and the bytes are left unchanged. -pub async fn load( - files: &PluginFileTransactions, - task_id: &str, -) -> Result, StoreError> { +pub async fn load(files: &FileScope, task_id: &str) -> Result, StoreError> { let parsed = files - .transact(&record_name(task_id), |text| { + .with_lock(&record_name(task_id), |text| { (None, text.map(parse).transpose()) }) .await?; @@ -233,10 +230,7 @@ pub async fn load( } /// Writes the first revision of a new record. The file must not exist yet. -pub async fn create( - files: &PluginFileTransactions, - record: TaskRecord, -) -> Result { +pub async fn create(files: &FileScope, record: TaskRecord) -> Result { match write(files, record, Expect::Revision(0)).await? { Write::Written(record) => Ok(record), Write::Discarded(_) => Err(StoreError::Invalid("task id already exists".into())), @@ -246,13 +240,13 @@ pub async fn create( /// Writes `record` under the file's lock when `expect` accepts the current /// record; `record.revision` becomes one more than the current revision. pub async fn write( - files: &PluginFileTransactions, + files: &FileScope, mut record: TaskRecord, expect: Expect, ) -> Result { let name = record_name(&record.task_id); let outcome = files - .transact(&name, move |text| { + .with_lock(&name, move |text| { let current = match text { Some(text) => match parse(text) { Ok(current) => Some(current), @@ -296,7 +290,7 @@ pub async fn write( /// Writes an inline input file of `task_id`. pub async fn write_input( - files: &PluginFileTransactions, + files: &FileScope, task_id: &str, name: &str, bytes: Vec, @@ -364,7 +358,7 @@ pub fn sha256(bytes: &[u8]) -> String { /// Streams `source` into the result file `name` of `task_id`, returning the /// bytes written and their SHA-256. pub async fn write_result( - files: &PluginFileTransactions, + files: &FileScope, task_id: &str, name: &str, source: impl Read + Send + 'static, @@ -377,23 +371,19 @@ pub async fn write_result( } /// Removes one result file of `task_id`, if it exists. -pub async fn remove_result( - files: &PluginFileTransactions, - task_id: &str, - name: &str, -) -> Result<(), StoreError> { +pub async fn remove_result(files: &FileScope, task_id: &str, name: &str) -> Result<(), StoreError> { files.remove(&result_name(task_id, name)).await?; Ok(()) } /// Removes the task's work directory, if it exists. -pub async fn remove_work(files: &PluginFileTransactions, task_id: &str) -> Result<(), StoreError> { +pub async fn remove_work(files: &FileScope, task_id: &str) -> Result<(), StoreError> { files.remove(&work_name(task_id)).await?; Ok(()) } /// Removes the whole task directory with its inputs and results. -pub async fn remove_task(files: &PluginFileTransactions, task_id: &str) -> Result<(), StoreError> { +pub async fn remove_task(files: &FileScope, task_id: &str) -> Result<(), StoreError> { files.remove(&task_dir(task_id)).await?; Ok(()) } diff --git a/docs/architecture/rust-agent/generated/app-server/services.json b/docs/architecture/rust-agent/generated/app-server/services.json index 863f5ed91c..e5709a60db 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.json +++ b/docs/architecture/rust-agent/generated/app-server/services.json @@ -169,7 +169,7 @@ "status": "Ready" }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "scope": null, "status": "Ready" }, @@ -199,7 +199,7 @@ "generation": 1 }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "scope": null, "provider": 14, "generation": 1 @@ -231,7 +231,7 @@ "external": true }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "provider": 14, "declared": true, "external": true @@ -290,7 +290,7 @@ "status": "Ready" }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "scope": null, "status": "Ready" }, @@ -325,7 +325,7 @@ "generation": 1 }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "scope": null, "provider": 14, "generation": 1 @@ -363,7 +363,7 @@ "external": true }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "provider": 14, "declared": true, "external": true @@ -479,6 +479,11 @@ "state": "Active", "generation": 1, "injects": [ + { + "service": "dim_agent_capabilities::file_storage::face::FsHost", + "scope": null, + "status": "Ready" + }, { "service": "dim_agent_capabilities::host::ModelSelectionHost", "scope": null, @@ -495,7 +500,7 @@ "status": "Ready" }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "scope": null, "status": "Ready" }, @@ -506,6 +511,12 @@ } ], "resolved": [ + { + "service": "dim_agent_capabilities::file_storage::face::FsHost", + "scope": null, + "provider": 4, + "generation": 1 + }, { "service": "dim_agent_capabilities::host::ModelSelectionHost", "scope": null, @@ -525,7 +536,7 @@ "generation": 1 }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "scope": null, "provider": 14, "generation": 1 @@ -538,6 +549,12 @@ } ], "reads": [ + { + "service": "dim_agent_capabilities::file_storage::face::FsHost", + "provider": 4, + "declared": true, + "external": true + }, { "service": "dim_agent_capabilities::host::ModelSelectionHost", "provider": 17, @@ -557,7 +574,7 @@ "external": true }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "provider": 14, "declared": true, "external": true @@ -3590,7 +3607,7 @@ "removing": false }, { - "service": "dim_app_server::plugin_files::PluginFileTransactions", + "service": "dim_app_server::plugin_files::PluginFiles", "provider": 14, "generation": 1, "removing": false diff --git a/docs/architecture/rust-agent/generated/app-server/services.md b/docs/architecture/rust-agent/generated/app-server/services.md index 7742e8a427..b51f2577af 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.md +++ b/docs/architecture/rust-agent/generated/app-server/services.md @@ -92,22 +92,23 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p73 p3 -->|"dim_app_server::control::ProcessActivity"| p73 p10 -->|"dim_app_server::methods::ManagementMethods"| p73 - p14 -->|"dim_app_server::plugin_files::PluginFileTransactions"| p73 + p14 -->|"dim_app_server::plugin_files::PluginFiles"| p73 p38 -->|"dyn rutis_bridge::session::services::HostDispatch#sessions"| p73 p73 -->|"dim_event_hub::bridge::EventHub"| p77 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p72 p3 -->|"dim_app_server::control::ProcessActivity"| p72 p10 -->|"dim_app_server::methods::ManagementMethods"| p72 - p14 -->|"dim_app_server::plugin_files::PluginFileTransactions"| p72 + p14 -->|"dim_app_server::plugin_files::PluginFiles"| p72 p18 -->|"dim_app_server::settings::SettingsService"| p72 p38 -->|"dyn rutis_bridge::session::services::HostDispatch#sessions"| p72 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p71 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p70 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p69 + p4 -->|"dim_agent_capabilities::file_storage::face::FsHost"| p68 p17 -->|"dim_agent_capabilities::host::ModelSelectionHost"| p68 p17 -->|"dim_agent_capabilities::host::SelectableModelsHost"| p68 p10 -->|"dim_app_server::methods::ManagementMethods"| p68 - p14 -->|"dim_app_server::plugin_files::PluginFileTransactions"| p68 + p14 -->|"dim_app_server::plugin_files::PluginFiles"| p68 p18 -->|"dim_app_server::settings::SettingsService"| p68 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p67 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p66 diff --git a/docs/architecture/rust-agent/generated/app-server/services.mmd b/docs/architecture/rust-agent/generated/app-server/services.mmd index 79b3df9cdd..85105c8a0f 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.mmd +++ b/docs/architecture/rust-agent/generated/app-server/services.mmd @@ -87,22 +87,23 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p73 p3 -->|"dim_app_server::control::ProcessActivity"| p73 p10 -->|"dim_app_server::methods::ManagementMethods"| p73 - p14 -->|"dim_app_server::plugin_files::PluginFileTransactions"| p73 + p14 -->|"dim_app_server::plugin_files::PluginFiles"| p73 p38 -->|"dyn rutis_bridge::session::services::HostDispatch#sessions"| p73 p73 -->|"dim_event_hub::bridge::EventHub"| p77 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p72 p3 -->|"dim_app_server::control::ProcessActivity"| p72 p10 -->|"dim_app_server::methods::ManagementMethods"| p72 - p14 -->|"dim_app_server::plugin_files::PluginFileTransactions"| p72 + p14 -->|"dim_app_server::plugin_files::PluginFiles"| p72 p18 -->|"dim_app_server::settings::SettingsService"| p72 p38 -->|"dyn rutis_bridge::session::services::HostDispatch#sessions"| p72 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p71 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p70 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p69 + p4 -->|"dim_agent_capabilities::file_storage::face::FsHost"| p68 p17 -->|"dim_agent_capabilities::host::ModelSelectionHost"| p68 p17 -->|"dim_agent_capabilities::host::SelectableModelsHost"| p68 p10 -->|"dim_app_server::methods::ManagementMethods"| p68 - p14 -->|"dim_app_server::plugin_files::PluginFileTransactions"| p68 + p14 -->|"dim_app_server::plugin_files::PluginFiles"| p68 p18 -->|"dim_app_server::settings::SettingsService"| p68 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p67 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p66 diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index 95485f170e..d2481d5fb9 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -39,7 +39,6 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `modelSelectionHost` | process | Provider | data | `resolve` async | | `openAICodexOAuthService` | process | OpenAICodexOAuth | internal(secret) | — | | `partRegistry` | process | PartRegistry | data | `registerDefinition` async | -| `pluginFileTransactions` | process | PluginFiles | internal(host-resource) | — | | `pluginFiles` | process | PluginFiles | data | `open` async | | `processActivity` | process | ServerControl | data | `activated` async, `hold` async, `release` async | | `promptSuggestionSettingsHost` | process | PromptSuggestionSettings | data | `read` async | diff --git a/docs/architecture/rust-agent/generated/modules.json b/docs/architecture/rust-agent/generated/modules.json index ae21677b57..a0aabdb269 100644 --- a/docs/architecture/rust-agent/generated/modules.json +++ b/docs/architecture/rust-agent/generated/modules.json @@ -22897,7 +22897,7 @@ "from": "dim_agent_scheduler::loops", "to": "dim_app_server::plugin_files", "references": [ - "path dim_app_server::plugin_files::PluginFileTransactions" + "path dim_app_server::plugin_files::FileScope" ] }, { @@ -23103,8 +23103,9 @@ "from": "dim_agent_scheduler::methods", "to": "dim_app_server::plugin_files", "references": [ - "path PluginFileTransactions", - "use dim_app_server::plugin_files::PluginFileTransactions" + "path FileScope", + "path dim_app_server::plugin_files::PluginFiles", + "use dim_app_server::plugin_files::FileScope" ] }, { @@ -23152,15 +23153,15 @@ "from": "dim_agent_scheduler::runs", "to": "dim_app_server::plugin_files", "references": [ + "path FileScope", "path PluginFileError", "path PluginFileError::Closed", "path PluginFileError::InvalidData", "path PluginFileError::InvalidPath", "path PluginFileError::Io", "path PluginFileError::Locked", - "path PluginFileTransactions", - "use dim_app_server::plugin_files::PluginFileError", - "use dim_app_server::plugin_files::PluginFileTransactions" + "use dim_app_server::plugin_files::FileScope", + "use dim_app_server::plugin_files::PluginFileError" ] }, { @@ -23575,7 +23576,7 @@ "from": "dim_agent_scheduler::wakeups", "to": "dim_app_server::plugin_files", "references": [ - "path dim_app_server::plugin_files::PluginFileTransactions" + "path dim_app_server::plugin_files::FileScope" ] }, { @@ -24515,7 +24516,6 @@ "references": [ "mod plugin_files", "path plugin_files", - "path plugin_files::PluginFileTransactions", "path plugin_files::PluginFilesPlugin::new" ] }, @@ -30739,7 +30739,6 @@ "path EntryKind", "path FileLease", "path FilePath", - "path FileReader", "path FileStorage", "path FileStorageError", "path FileStorageError::Cancelled", @@ -30752,11 +30751,18 @@ "use dim_agent_capabilities::file_storage::EntryKind", "use dim_agent_capabilities::file_storage::FileLease", "use dim_agent_capabilities::file_storage::FilePath", - "use dim_agent_capabilities::file_storage::FileReader", "use dim_agent_capabilities::file_storage::FileStorage", "use dim_agent_capabilities::file_storage::FileStorageError" ] }, + { + "from": "dim_app_server::plugin_files", + "to": "dim_agent_capabilities::file_storage::face", + "references": [ + "path OpenRead", + "use dim_agent_capabilities::file_storage::OpenRead" + ] + }, { "from": "dim_app_server::plugin_files", "to": "dim_agent_runtime::names", @@ -54787,6 +54793,13 @@ "use crate::TaskReport" ] }, + { + "from": "dim_modality", + "to": "dim_agent_capabilities::file_storage::face", + "references": [ + "path dim_agent_capabilities::file_storage::FsHost" + ] + }, { "from": "dim_modality", "to": "dim_agent_capabilities::host", @@ -54893,8 +54906,7 @@ "from": "dim_modality", "to": "dim_app_server::plugin_files", "references": [ - "path PluginFileTransactions", - "use dim_app_server::plugin_files::PluginFileTransactions" + "path dim_app_server::plugin_files::PluginFiles" ] }, { @@ -55082,9 +55094,17 @@ "to": "dim_agent_capabilities::file_storage", "references": [ "path EntryKind::Directory", - "path FileReader", - "use dim_agent_capabilities::file_storage::EntryKind", - "use dim_agent_capabilities::file_storage::FileReader" + "use dim_agent_capabilities::file_storage::EntryKind" + ] + }, + { + "from": "dim_modality::engine", + "to": "dim_agent_capabilities::file_storage::face", + "references": [ + "path FsHost", + "path OpenRead", + "use dim_agent_capabilities::file_storage::FsHost", + "use dim_agent_capabilities::file_storage::OpenRead" ] }, { @@ -55167,8 +55187,8 @@ "from": "dim_modality::engine", "to": "dim_app_server::plugin_files", "references": [ - "path PluginFileTransactions", - "use dim_app_server::plugin_files::PluginFileTransactions" + "path FileScope", + "use dim_app_server::plugin_files::FileScope" ] }, { @@ -55482,10 +55502,10 @@ "from": "dim_modality::task", "to": "dim_app_server::plugin_files", "references": [ + "path FileScope", "path PluginFileError", - "path PluginFileTransactions", - "use dim_app_server::plugin_files::PluginFileError", - "use dim_app_server::plugin_files::PluginFileTransactions" + "use dim_app_server::plugin_files::FileScope", + "use dim_app_server::plugin_files::PluginFileError" ] }, { diff --git a/docs/architecture/rust-agent/generated/modules.mmd b/docs/architecture/rust-agent/generated/modules.mmd index 42e14f2cf6..ed47b3f8b1 100644 --- a/docs/architecture/rust-agent/generated/modules.mmd +++ b/docs/architecture/rust-agent/generated/modules.mmd @@ -2905,6 +2905,7 @@ flowchart LR m296 --> m306 m296 --> m333 m298 --> m58 + m298 --> m59 m298 --> m176 m299 --> m85 m299 --> m116 @@ -5176,6 +5177,7 @@ flowchart LR m719 --> m306 m719 --> m705 m720 --> m705 + m721 --> m59 m721 --> m72 m721 --> m73 m721 --> m85 @@ -5198,6 +5200,7 @@ flowchart LR m722 --> m72 m722 --> m223 m723 --> m58 + m723 --> m59 m723 --> m72 m723 --> m73 m723 --> m74 diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 772c955137..5b2be8c345 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -10,7 +10,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | `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. | | `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). | -| `pluginFileTransactions` | Scheduler and EventHub use pluginFiles.open(), scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | +| `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. | @@ -18,9 +18,9 @@ directly. The rutis binding dispatches its data arguments and returns its result | Target and signature | Existing operation and consumer | | --- | --- | -| FileScope.directory(name) → FileResult of node-absolute path | PluginFileTransactions.directory already 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 | PluginFileTransactions.open_read already 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.writeStream(name, next) → FileResult of null | PluginFileTransactions.write_stream already 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. | +| 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.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 diff --git a/docs/design/plugins/EventHub.md b/docs/design/plugins/EventHub.md index d6b53ca6f4..39c6ce0eac 100644 --- a/docs/design/plugins/EventHub.md +++ b/docs/design/plugins/EventHub.md @@ -592,6 +592,6 @@ The contract is §6, A.1 to A.4; this section is its spelling ([rutis usage appe - **An optional read.** A Rust producer keeps `Key` and reads it per call with `ctx.get_at(&key)`, which answers `None` while EventHub is not installed, Pending or reloading, so the dependency gates nothing ([rutis usage A.3](../rutis-usage.md#a3-settled-questions)). A `definePlugin` row injects the name instead (2.1). The same pattern reads `sessionFiles` (`Key`, `crates/dim-agent-capabilities/src/host.rs:1002-1038`) and `sessions` (`Key` at `host_key("sessions")`, `crates/dim-agent-scheduler/src/methods.rs:44,56`). - **The declaration notice.** A Rust or Cordis producer listens before it reads: `ctx.listen::()`, the public `Event` whose name is `eventhub/ready`, then `ctx.get_at(&key)`; on the notice it reads the key again and declares (2.1). A `definePlugin` row needs no notice: it injects the name and declares at `apply` (2.1). The listener holds a type, not a running EventHub, so a producer that applied before EventHub still hears the first `apply` that provides it. The notice comes from a dependent row of the process part, not from inside its `apply`: a part's services are readable to other rows only while the part is active, and a part becomes active when its `apply` returns. Declaring on every notice adds no effect, because a repeated declaration replaces in place (A.1). - **Delivery.** `sessions.input` is one `invoke("input", json!([args]))` over `Key` (`crates/dim-agent-scheduler/src/engine.rs:611-633`); the reply is `{inputId, sequence}` and the error codes are [session access A.6](../contracts/session-access.md#a6-errors). -- **Storage.** The subscription file uses `PluginFileTransactions` (`dim_app_server::plugin_files::PluginFileTransactions`, `crates/dim-agent-scheduler/src/runs.rs:7,221-240`). +- **Storage.** Subscription updates use `scope.withLock` on a caller-managed pluginFiles scope. An admitted publish retains that scope until settlement, including across a row restart. - **The Session part** injects `guideEntries`, `toolRegistry`, `sessionIdentity` and `eventSubscriptions`, and registers the entry and the `events` tool from `apply` as Scheduler's part does (`crates/dim-agent-scheduler/src/session.rs:147-201`). - **TypeScript.** `npm/plugin.d.ts` declares the service beside `sessions`: `EventHub` with `declare` and `publish`, the request and reply types of A.1 and A.2, and `EventHubErrorThrown` with every code of Appendix C. A `definePlugin` row injects `eventHub` and reads it with `ctx.use('eventHub')`; it declares at `apply`. A raw Cordis row reads it with `ctx.get('eventHub')` instead ([rutis usage §3.5](../rutis-usage.md#35-how-each-runtime-resolves-a-name)). diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 7c133cc65d..9dcf21c377 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` (extended: UTF-8 and binary); 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 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` | | 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/plugins/Scheduler.md b/docs/design/plugins/Scheduler.md index 13088f4dff..e0badbddb2 100644 --- a/docs/design/plugins/Scheduler.md +++ b/docs/design/plugins/Scheduler.md @@ -924,9 +924,9 @@ no `schedule.*` methods or `schedule` tool. The process part is added with | Tool `schedule` registered with `toolRegistry` | Session part keys `ToolRegistry` from `names.key()` and calls `tools.register(ctx, ToolContribution {definition, handler})` in `apply`, as `dim-agent-questions` does | | Namespace `schedule` registered with `managementMethods` | Process part keys `ManagementMethods` and calls `methods.register(ctx, "schedule", declarations, handler)`; Rpc looks it up per call and holds no dependency on Scheduler | | `scheduleJobs`, `wakeups`, `loops` | Process-group data faces registered shared and provided at their `host_key`. Native `ScheduleJobs`, `Wakeups` and `Loops` are bindings to the same owner operations, provided under their type keys. The native Session part declares them with `names.key()` and calls them directly. Wire projection happens only at the bridge boundary. `loops` serves `start`, `next`, `list` and `stop`; the delivery pass, recovery and `settle_delivering` stay internal (§12.6) | -| `settings`, `pluginFiles` | Typed App Server services (`SettingsService`, `PluginFileTransactions`) keyed with `names.key()`; the crate depends on `dim-app-server`, which `xtask check` allows | +| `settings`, `pluginFiles` | Typed App Server services (`SettingsService`, `PluginFiles`) keyed with `names.key()`; the crate depends on `dim-app-server`, which `xtask check` allows | | `sessions` | The shared host-dispatch name, called with its JSON envelope; its native request types are private to App Server | -| Process storage | The typed `PluginFileTransactions` service of App Server ([trusted plugin storage](../../../crates/dim-app-server/README.md#trusted-plugin-storage)). The host writes the `{version: 1, text}` envelope; Scheduler supplies the inner v1 text, the same bytes the TypeScript version wrote. | +| Process storage | The typed `PluginFiles` service of App Server ([trusted plugin storage](../../../crates/dim-app-server/README.md#trusted-plugin-storage)). The host writes the `{version: 1, text}` envelope; Scheduler supplies the inner v1 text, the same bytes the TypeScript version wrote. | | Timer, delivery writes and the stop timer | Owned by the process part: the timer, delivery tasks and retention run in its task tracker and start after its methods and services are registered and the process is published (§9 R1). On unload (`ctx.cancellation_token()`), new work stops, waits end, and cleanup joins the tracker before the storage scope closes; an admitted `sessions` call settles first. A record still `delivering` is left in the file for the next generation's recovery. The Session tools return the unloading results of §1.3 and their own `schedule: cancelled before handover` or `wakeup: cancelled before handover`. | | Policy text | `install_with(builder, SchedulerTexts {description})`; `install` uses the built-in text. The description is protocol only, so no evaluation member is carried and no validation is needed. | | Guide entry | The Session part keys `GuideEntries` and registers the §5.2 entry, session-scoped, order 110 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 50ac14aab7..de466837b4 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -197,7 +197,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | --- | --- | --- | --- | | `serverControl` | process | ServerControl | control | | `connectionHub` | process | Connection | control | -| `pluginFileTransactions` | process | PluginFiles | host-resource | | `grokOAuthService` | process | GrokOAuth | secret | | `openAICodexOAuthService` | process | OpenAICodexOAuth | secret | | `uiHost` | process | UiHost | control | diff --git a/docs/zh/design/plugins/EventHub.md b/docs/zh/design/plugins/EventHub.md index d86196e220..0157a7d5ec 100644 --- a/docs/zh/design/plugins/EventHub.md +++ b/docs/zh/design/plugins/EventHub.md @@ -587,6 +587,6 @@ Session 部件为标记 `dim-event` 与 `dim-event-guide` 在 Session 作用域 - **可选读取。** Rust 生产方持有 `Key`,每次调用用 `ctx.get_at(&key)` 读取;EventHub 未安装、Pending 或重载时它回答 `None`,所以依赖不门控任何东西,见 [rutis 用法 A.3](../rutis-usage.md#a3-已定的问题)。`definePlugin` 行则 inject 该名字,见 2.1。同一形式用于读取 `sessionFiles`,即 `Key`,见 `crates/dim-agent-capabilities/src/host.rs:1002-1038`,以及 `sessions`,即在 `host_key("sessions")` 上的 `Key`,见 `crates/dim-agent-scheduler/src/methods.rs:44,56`。 - **声明通知。** Rust 或 Cordis 生产方先监听再读取:`ctx.listen::()`,即名字为 `eventhub/ready` 的公开 `Event` 类型,然后 `ctx.get_at(&key)`;收到通知时再次读取该 key 并声明,见 2.1。`definePlugin` 行不需要这条通知:它 inject 该名字并在 `apply` 里声明,见 2.1。监听器持有一个类型,而不是一个运行中的 EventHub,所以在 EventHub 之前装载的生产方也能听到第一次提供它的那次 `apply`。通知本身由进程部件的一个依赖行发出,而不是在它的 `apply` 里:一行的服务只在部件活跃时才可被其他行读取,而部件在 `apply` 返回时才变为活跃。每次通知都声明不会增加 effect,因为重复声明是原地替换,见 A.1。 - **投递。** `sessions.input` 就是在 `Key` 上的一次 `invoke("input", json!([args]))`,见 `crates/dim-agent-scheduler/src/engine.rs:611-633`;回复是 `{inputId, sequence}`,错误码见 [session access A.6](../contracts/session-access.md#a6-错误)。 -- **存储。** 订阅文件使用 `PluginFileTransactions`,即 `dim_app_server::plugin_files::PluginFileTransactions`,见 `crates/dim-agent-scheduler/src/runs.rs:7,221-240`。 +- **存储。** 订阅更新通过调用方持有的 pluginFiles scope 调用 `scope.withLock`。已经受理的发布持有该 scope 直到结算完成,即使期间发生行重启。 - **Session 部件** 注入 `guideEntries`、`toolRegistry`、`sessionIdentity` 与 `eventSubscriptions`,并在 `apply` 中登记条目与 `events` 工具,与 Scheduler 的部件相同,见 `crates/dim-agent-scheduler/src/session.rs:147-201`。 - **TypeScript。** `npm/plugin.d.ts` 在 `sessions` 旁边声明这个服务:`EventHub`(`declare` 与 `publish`)、A.1 与 A.2 的请求和回复类型,以及列出附录 C 全部码的 `EventHubErrorThrown`。用 `definePlugin` 写成的行 inject `eventHub`,并用 `ctx.use('eventHub')` 读取它,在 `apply` 里声明;原始 Cordis 行则用 `ctx.get('eventHub')` 读取,见 [rutis 用法 §3.5](../rutis-usage.md#35-各运行时如何解析名字)。 diff --git a/docs/zh/design/plugins/Modality.md b/docs/zh/design/plugins/Modality.md index ecb8566747..86427dd056 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 与二进制);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 与二进制),已打开的读取器使用 `fsHost.readAt/closeRead`;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))。 diff --git a/docs/zh/design/plugins/Scheduler.md b/docs/zh/design/plugins/Scheduler.md index 61005bf350..3d89fcda45 100644 --- a/docs/zh/design/plugins/Scheduler.md +++ b/docs/zh/design/plugins/Scheduler.md @@ -871,9 +871,9 @@ Scheduler 是原生 Rust,无 TypeScript 包、Node 进程或回退。上面的 | 注册到 `toolRegistry` 的工具 `schedule` | Session 部分经 `names.key()` 取得 `ToolRegistry`,并在 `apply` 中调用 `tools.register(ctx, ToolContribution {definition, handler})`,与 `dim-agent-questions` 相同 | | 注册到 `managementMethods` 的命名空间 `schedule` | 进程部分取得 `ManagementMethods` 并调用 `methods.register(ctx, "schedule", declarations, handler)`;Rpc 每次调用查找它,不持有对 Scheduler 的依赖 | | `scheduleJobs`、`wakeups`、`loops` | 注册为 shared 的进程组数据面,在各自的 `host_key` 提供 dispatcher。原生 `ScheduleJobs`、`Wakeups`、`Loops` 是同一 owner 操作的绑定,在类型键提供。原生 Session 部分用 `names.key()` 声明这些依赖并直接调用;wire 投影仅在 bridge 边界发生。`loops` 提供 `start`、`next`、`list`、`stop`;投递 pass、恢复与 `settle_delivering` 保持内部(§12.6) | -| `settings`、`pluginFiles` | 用 `names.key()` 键入的 App Server 类型化服务(`SettingsService`、`PluginFileTransactions`);该 crate 依赖 `dim-app-server`,`xtask check` 允许 | +| `settings`、`pluginFiles` | 用 `names.key()` 键入的 App Server 类型化服务(`SettingsService`、`PluginFiles`);该 crate 依赖 `dim-app-server`,`xtask check` 允许 | | `sessions` | 共享的宿主分发名称,以其 JSON 信封调用;其原生请求类型对 App Server 私有 | -| 进程存储 | App Server 的类型化 `PluginFileTransactions` 服务([可信插件存储](../../../../crates/dim-app-server/README.md#trusted-plugin-storage))。宿主写入 `{version: 1, text}` 信封;Scheduler 提供内层 v1 文本,即 TypeScript 版本写下的同一批字节。 | +| 进程存储 | App Server 的类型化 `PluginFiles` 服务([可信插件存储](../../../../crates/dim-app-server/README.md#trusted-plugin-storage))。宿主写入 `{version: 1, text}` 信封;Scheduler 提供内层 v1 文本,即 TypeScript 版本写下的同一批字节。 | | 定时器、投递写入与停止定时器 | 由进程部分拥有:定时器、投递任务与保留期在其任务跟踪器中运行,并在其方法与服务注册之后、进程发布之后启动(§9 R1)。卸载时(`ctx.cancellation_token()`),新工作停止、等待结束,清理在关闭存储作用域之前等待跟踪器;已准入的 `sessions` 调用先结算。仍为 `delivering` 的记录留在文件中,交给下一代的恢复。Session 工具返回 §1.3 的卸载结果及其自己的 `schedule: cancelled before handover` 或 `wakeup: cancelled before handover`。 | | 策略文本 | `install_with(builder, SchedulerTexts {description})`;`install` 使用内置文本。描述只含协议,因此不携带评估成员,也不需要校验。 | | guide 条目 | Session 部分取得 `GuideEntries` 并注册 §5.2 的条目,作用域为 Session,order 110 | diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index 6068bf42f3..39f04bea3a 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -303,7 +303,29 @@ pub async fn serve_home( pub async fn graph() -> Result { let dir = scratch("server")?; let server = serve_product(&dir, |_| {}).await?; - let snapshot = process_layer(server.diagnostics()); + let mut snapshot = process_layer(server.diagnostics()); + let mut ids: Vec<_> = snapshot.plugins.iter().map(|plugin| plugin.id).collect(); + ids.sort_unstable(); + let graph_id = |mut id: rutis::host::PluginId| { + id.0 = ids + .binary_search(&id) + .expect("provider in the process graph") as u64 + + 1; + id + }; + for plugin in &mut snapshot.plugins { + plugin.id = graph_id(plugin.id); + plugin.parent = plugin.parent.map(graph_id); + for dep in &mut plugin.resolved_dependencies { + dep.provider = graph_id(dep.provider); + } + for read in &mut plugin.accesses { + read.provider = read.provider.map(graph_id); + } + } + for binding in &mut snapshot.bindings { + binding.provider = graph_id(binding.provider); + } let graph = crate::diagnostics(snapshot, &[]); server.shutdown(); server.join().await?;