Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions crates/dim-agent-scheduler/src/loops.rs
Original file line number Diff line number Diff line change
@@ -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.
//!
Expand Down Expand Up @@ -297,21 +297,21 @@ fn encode(loops: Vec<Loop>) -> 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<Vec<Loop>, 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<R: Send + 'static>(
files: &dim_app_server::plugin_files::PluginFileTransactions,
files: &dim_app_server::plugin_files::FileScope,
change: impl FnOnce(&mut Vec<Loop>) -> Result<(bool, R), SchedulerError> + Send + 'static,
) -> Result<R, SchedulerError> {
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)),
Expand Down
8 changes: 4 additions & 4 deletions crates/dim-agent-scheduler/src/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -44,7 +44,7 @@ pub struct SchedulerPlugin {
activity: Key<ProcessActivity>,
pub(crate) deliveries: DeliveryHolds,
settings: Key<SettingsService>,
files: Key<PluginFileTransactions>,
files: Key<dim_app_server::plugin_files::PluginFiles>,
methods: Key<ManagementMethods>,
sessions: Key<dyn HostDispatch>,
parts: Key<PartRegistry>,
Expand Down Expand Up @@ -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::<crate::document::ScheduleDocument>(ctx)?;
Expand Down Expand Up @@ -353,7 +353,7 @@ pub(crate) struct Shared {
pub(crate) deliveries: DeliveryHolds,
pub(crate) sessions: Arc<dyn HostDispatch>,
pub(crate) settings: Arc<SettingsService>,
pub(crate) files: Arc<PluginFileTransactions>,
pub(crate) files: Arc<FileScope>,
/// 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).
Expand Down
12 changes: 6 additions & 6 deletions crates/dim-agent-scheduler/src/runs.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -347,20 +347,20 @@ fn encode(runs: Vec<Delivery>) -> 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<Vec<Delivery>, SchedulerError> {
pub async fn read(files: &FileScope) -> Result<Vec<Delivery>, 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<R: Send + 'static>(
files: &PluginFileTransactions,
files: &FileScope,
change: impl FnOnce(&mut Vec<Delivery>) -> Result<(bool, R), SchedulerError> + Send + 'static,
) -> Result<R, SchedulerError> {
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)),
Expand Down
10 changes: 5 additions & 5 deletions crates/dim-agent-scheduler/src/wakeups.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -150,21 +150,21 @@ fn encode(wakeups: Vec<Wakeup>) -> 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<Vec<Wakeup>, 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<R: Send + 'static>(
files: &dim_app_server::plugin_files::PluginFileTransactions,
files: &dim_app_server::plugin_files::FileScope,
change: impl FnOnce(&mut Vec<Wakeup>) -> Result<(bool, R), SchedulerError> + Send + 'static,
) -> Result<R, SchedulerError> {
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)),
Expand Down
14 changes: 9 additions & 5 deletions crates/dim-agent-scheduler/tests/data_faces_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl DynPlugin for Probe {
TypeKey::of::<ScheduleJobs>(),
TypeKey::of::<Wakeups>(),
TypeKey::of::<Loops>(),
TypeKey::of::<dim_app_server::plugin_files::PluginFileTransactions>(),
TypeKey::of::<dim_app_server::plugin_files::PluginFiles>(),
]
}
fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result<Effect>> {
Expand Down Expand Up @@ -151,13 +151,15 @@ impl Rig {
async fn hold_loops_file(&self) -> (std::sync::mpsc::Sender<()>, tokio::task::JoinHandle<()>) {
let files = self
.ctx
.require::<dim_app_server::plugin_files::PluginFileTransactions>()
.require::<dim_app_server::plugin_files::PluginFiles>()
.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, ())
Expand All @@ -172,13 +174,15 @@ impl Rig {
async fn hold_wakeup_file(&self) -> (std::sync::mpsc::Sender<()>, tokio::task::JoinHandle<()>) {
let files = self
.ctx
.require::<dim_app_server::plugin_files::PluginFileTransactions>()
.require::<dim_app_server::plugin_files::PluginFiles>()
.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, ())
Expand Down
11 changes: 8 additions & 3 deletions crates/dim-agent-scheduler/tests/lifecycle_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,21 +610,26 @@ 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::<dim_app_server::plugin_files::PluginFileTransactions>()
.expect("the App Server provides the file transactions");
.service::<dim_app_server::plugin_files::PluginFiles>()
.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();
(None, ())
})
.await
.unwrap();
caller.shutdown().await.unwrap();
});
entered_rx.await.unwrap();
(release, task)
Expand Down
12 changes: 6 additions & 6 deletions crates/dim-agent-scheduler/tests/plugin_file_transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -13,7 +13,7 @@ use std::{
};

struct Probe {
files: Key<PluginFileTransactions>,
files: Key<dim_app_server::plugin_files::PluginFiles>,
observed: Arc<OnceLock<Value>>,
}

Expand All @@ -26,21 +26,21 @@ impl DynPlugin for Probe {
}
fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result<Effect>> {
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:?}"),
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-agent-scheduler/tests/watch_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions crates/dim-app-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -530,22 +530,22 @@ 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`.

`list(prefix)` returns one level of the directory `prefix`, sorted by name, each entry its name relative to the authorized root and its kind (`file`, `directory`, or `other` for a link or special file, never followed). A returned name is the stored components joined by `/`, so it can be passed straight to another operation; on Unix a backslash is part of a name, and on Windows it is a separator. It does not recurse and does not enter a directory entry, and the root itself is not listed, so a prefix names a directory. An entry whose name is not valid UTF-8 is omitted: these operations address names as strings, so it could not be read either, but removing the directory removes it. `remove(name)` removes a file, or a directory and everything beneath it. A file a lease holds, and a directory with a lease held beneath it, fail `locked`; an absent entry counts as removed, so a retry is safe. Removal is not atomic: an error can leave part of a tree removed.

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::<PluginFileTransactions>()`) 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<FileScope>` 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 |
Expand Down
2 changes: 0 additions & 2 deletions crates/dim-app-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<plugin_files::PluginFileTransactions>(catalog, None);
register::<ConnectionHub>(catalog, None);
catalog.register_shared(dim_agent_runtime::names::name_of::<ListenAddresses>());
register::<ui_host::UiHost>(catalog, None);
Expand Down Expand Up @@ -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"),
Expand Down
Loading