diff --git a/crates/dim-agent-capabilities/src/hooks/sources.rs b/crates/dim-agent-capabilities/src/hooks/sources.rs index 92c1ee9c6a..63071fa57d 100644 --- a/crates/dim-agent-capabilities/src/hooks/sources.rs +++ b/crates/dim-agent-capabilities/src/hooks/sources.rs @@ -35,7 +35,8 @@ impl serde::Serialize for HookSourceId { } /// Whether a source's document was read, absent or refused. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] pub enum HookSourceState { Ok, Missing, @@ -43,7 +44,7 @@ pub enum HookSourceState { } /// One source as the port returns it. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, serde::Serialize)] pub struct HookSourceSnapshot { pub id: HookSourceId, /// Where the document lives: the user file, the project file, or a @@ -57,7 +58,7 @@ pub struct HookSourceSnapshot { } /// Every effective source of one working directory, in catalog order. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, serde::Serialize)] pub struct HookSourcesSnapshot { pub sources: Vec, } diff --git a/crates/dim-agent-scheduler/src/methods.rs b/crates/dim-agent-scheduler/src/methods.rs index 44d62d72bc..0df695aeba 100644 --- a/crates/dim-agent-scheduler/src/methods.rs +++ b/crates/dim-agent-scheduler/src/methods.rs @@ -19,7 +19,7 @@ use dim_app_server::{ ProcessActivity, methods::ManagementMethods, plugin_files::FileScope, - settings::{BusinessDocument, SettingsError, SettingsService}, + settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError}, }; use jiff::{SignedDuration, Timestamp}; use rutis::Ctx; @@ -43,7 +43,7 @@ pub(crate) type DeliveryHolds = pub struct SchedulerPlugin { activity: Key, pub(crate) deliveries: DeliveryHolds, - settings: Key, + settings: Key, files: Key, methods: Key, sessions: Key, @@ -113,7 +113,7 @@ impl DynPlugin for SchedulerPlugin { 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)?; + let settings = settings.register_document::(ctx)?; let shared = Arc::new(Shared { ctx: ctx.clone(), activity, @@ -352,7 +352,7 @@ pub(crate) struct Shared { pub(crate) clock: Arc, pub(crate) deliveries: DeliveryHolds, pub(crate) sessions: Arc, - pub(crate) settings: Arc, + pub(crate) settings: Arc>, pub(crate) files: Arc, /// Serializes retention passes, so a pass never deletes what another reads. pub(crate) pruning: tokio::sync::Mutex<()>, @@ -527,7 +527,7 @@ pub(crate) async fn read_document( > { shared .settings - .read::(SettingsScope::User, cancel) + .read(SettingsScope::User, cancel) .await .map_err(read_failure) } diff --git a/crates/dim-app-server/README.md b/crates/dim-app-server/README.md index be3d52b3b6..c51486f166 100644 --- a/crates/dim-app-server/README.md +++ b/crates/dim-app-server/README.md @@ -94,7 +94,7 @@ not add automatic retry or recovery. See the [CLI submission contract](../../doc SettingsService reads and updates generic `BusinessDocument` values with per-source CAS. Business owners define and validate their payloads: MCP types live in `mcp/config.rs`, and the Skills owner supplies the existing `SkillSettingsHost`. -Each owner registers its sources in its `apply` (`SettingsService::register`, or +Each owner registers its sources in its `apply` (`Settings::register_document` for a native `BusinessDocument`, or `register` on the named `settings` service); a source is served only while its owner is loaded, and its stored document stays when the owner unloads. Settings owns source persistence, not approvals or business management methods. diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 4edfb12ea9..266ab7ddf1 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1,7 +1,7 @@ use crate::{ ProcessActivity, ProcessHold, ServerConfig, protocol::{AgentInfo, CreateWorktree, SessionOrigin}, - settings::SettingsService, + settings::Settings, storage::{PreparedWorktree, SessionMetadataService, SessionStore, SqliteStorage, Store}, worktrees::{CreatedWorktree, ManagedWorktrees, WorktreeError}, }; @@ -393,7 +393,7 @@ pub struct AgentIndex { records: Option>, session_store: Option>, session_metadata: Option>, - settings: Option>, + settings: Option>, stopping: CancellationToken, /// Notified once an `idle` call on this generation is admitted and /// waiting on its branch. Feature `testing` only. @@ -2142,7 +2142,7 @@ pub(crate) struct AgentsPlugin { /// Native storage only with a database. stored: Option, /// Settings only with local execution. - settings: Option>, + settings: Option>, loader: Key, directory: Key, activity: Key, @@ -2163,7 +2163,7 @@ impl AgentsPlugin { .transpose()?, settings: config .local_execution() - .then(|| names.key::()) + .then(|| names.key::()) .transpose()?, loader: names.key()?, directory: Key::of(), diff --git a/crates/dim-app-server/src/cli.rs b/crates/dim-app-server/src/cli.rs index a69547337b..81ef71a268 100644 --- a/crates/dim-app-server/src/cli.rs +++ b/crates/dim-app-server/src/cli.rs @@ -585,7 +585,7 @@ pub fn run_with( dim_agent_capabilities::timeline_tree::BranchToolConfig::default(), ); permission_rules::install(&mut builder); - hooks_settings::install(&mut builder, config.product_home.clone()); + hooks_settings::install(&mut builder); dim_agent_capabilities::hooks::install(&mut builder); crate::session_grants::install(&mut builder); dim_agent_capabilities::file_access::install(&mut builder); diff --git a/crates/dim-app-server/src/collaboration.rs b/crates/dim-app-server/src/collaboration.rs index 97ef2b6136..ebf08497ac 100644 --- a/crates/dim-app-server/src/collaboration.rs +++ b/crates/dim-app-server/src/collaboration.rs @@ -14,9 +14,9 @@ mod pending; pub use approvals::ApprovalDestination; use crate::agents::{AgentIndex, AgentProfile, SessionRestored, UnloadedSessionDeleted}; -use crate::collaboration_model_policy::ModelPolicy; +use crate::collaboration_model_policy::{CollaborationModelPolicy, ModelPolicy}; use crate::protocol::SessionOrigin; -use crate::settings::{SettingsScope, SettingsService}; +use crate::settings::{Settings, SettingsError}; use dim_agent_capabilities::{ context_block, host::{ @@ -230,7 +230,7 @@ pub struct Collaboration { index: Arc, directory: Arc, /// The subagent model policy's source; local execution only. - settings: Option>, + policy_owner: Option, tasks: TaskTracker, stop: CancellationToken, #[cfg(feature = "testing")] @@ -279,14 +279,15 @@ impl Collaboration { .as_ref() .and_then(|model| model.metadata.as_ref()) .is_some_and(|metadata| metadata.startup.is_some()); - let policy = match &self.settings { + let policy = match &self.policy_owner { _ if startup => ModelPolicy::Inherit {}, - Some(settings) => { - settings - .read::(SettingsScope::User, &self.stop) + Some(ctx) => { + ctx.get::() + .ok_or_else(|| member_create_failed(SettingsError::UnknownSource.to_string()))? + .read(&self.stop) .await .map_err(|error| member_create_failed(error.to_string()))? - .document + .policy } None => ModelPolicy::Agent {}, }; @@ -719,7 +720,7 @@ impl Collaboration { /// with it, and the Session and branch parts it registers. pub(crate) struct CollaborationPlugin { /// The subagent model policy's source; local execution only, as Agents. - settings: Option>, + settings: Option>, index: Key, directory: Key, parts: Key, @@ -728,7 +729,7 @@ impl CollaborationPlugin { pub fn new(names: &Names<'_>, local_execution: bool) -> rutis::Result { Ok(Self { settings: local_execution - .then(|| names.key::()) + .then(|| names.key::()) .transpose()?, index: names.key()?, directory: names.key()?, @@ -754,14 +755,11 @@ impl DynPlugin for CollaborationPlugin { let index = ctx.require_at(&self.index)?; let directory = ctx.require_at(&self.directory)?; let parts = ctx.require_at(&self.parts)?; - let settings = match &self.settings { - Some(settings) => Some(ctx.require_at(settings)?), - None => None, - }; + let policy_owner = self.settings.as_ref().map(|_| ctx.clone()); let service = Arc::new(Collaboration { index, directory, - settings, + policy_owner, tasks: TaskTracker::new(), stop: CancellationToken::new(), #[cfg(feature = "testing")] diff --git a/crates/dim-app-server/src/collaboration_model_policy.rs b/crates/dim-app-server/src/collaboration_model_policy.rs index e6016c4c01..888e6728b3 100644 --- a/crates/dim-app-server/src/collaboration_model_policy.rs +++ b/crates/dim-app-server/src/collaboration_model_policy.rs @@ -4,7 +4,7 @@ use crate::{ methods::ManagementMethods, protocol::Empty, - settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}, + settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope}, }; use dim_agent_capabilities::methods::{ Interruption, MethodCall, MethodDecl, RpcError, params, reply, @@ -73,15 +73,65 @@ struct SetPolicy { policy: ModelPolicy, } #[derive(Serialize)] -struct PolicyView { +pub(crate) struct PolicyView { revision: String, - policy: ModelPolicy, + pub(crate) policy: ModelPolicy, } #[derive(Serialize)] struct Revision { revision: String, } +#[derive(Clone)] +pub(crate) struct CollaborationModelPolicy(Arc>); + +impl CollaborationModelPolicy { + pub(crate) async fn read( + &self, + cancel: &tokio_util::sync::CancellationToken, + ) -> crate::settings::Result { + let snapshot = self.0.read(SettingsScope::User, cancel).await?; + Ok(PolicyView { + revision: snapshot.revision, + policy: snapshot.document, + }) + } +} + +impl rutis_bridge::session::HostDispatch for CollaborationModelPolicy { + fn methods(&self) -> Option { + Some(serde_json::json!({"read":"async"})) + } + fn invoke( + &self, + method: &str, + args: rutis_bridge::session::Value, + ) -> rutis_bridge::session::Reply { + use rutis_bridge::session::{Error, Value}; + if method != "read" { + return Err(Error::value(format!( + "unknown collaborationModelPolicy method {method}" + ))); + } + let (_request,): (Empty,) = serde_json::from_value(args.json()?) + .map_err(|_| Error::value("expected one empty request"))?; + let owner = self.clone(); + Ok(Value::future(async move { + let cancel = tokio_util::sync::CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + let view = owner.read(&cancel).await.map_err(|error| { + rutis_bridge::exports::failure( + "collaborationModelPolicy", + error.code(), + error.to_string(), + None, + ) + })?; + rutis_bridge::session::arg(&view) + })) + } +} + fn error(error: SettingsError) -> RpcError { let kind = match &error { SettingsError::Closed => return RpcError::reloading(), @@ -95,7 +145,7 @@ fn error(error: SettingsError) -> RpcError { /// Process owner of the `collaboration` source and its management methods, /// apart from Collaboration so it reloads without unloading Rpc. pub struct CollaborationModelPolicyPlugin { - settings: Key, + settings: Key, methods: Key, } impl CollaborationModelPolicyPlugin { @@ -117,7 +167,13 @@ impl DynPlugin for CollaborationModelPolicyPlugin { Box::pin(async move { let settings = ctx.require_at(&self.settings)?; let methods = ctx.require_at(&self.methods)?; - settings.register::(ctx)?; + let settings = settings.register_document::(ctx)?; + let owner = Arc::new(CollaborationModelPolicy(settings)); + ctx.provide_as::(owner.clone())?; + ctx.provide_at::( + rutis_bridge::session::host_key("collaborationModelPolicy"), + owner.clone(), + )?; methods.register( ctx, "collaboration", @@ -140,26 +196,20 @@ impl DynPlugin for CollaborationModelPolicyPlugin { params: value, .. } = call; - let settings = settings.clone(); + let owner = owner.clone(); Box::pin(async move { match method.as_str() { "collaboration.model_policy" => { let _: Empty = params(value)?; - let snapshot = settings - .read::(SettingsScope::User, &stopping) - .await - .map_err(error)?; - reply(PolicyView { - revision: snapshot.revision, - policy: snapshot.document, - }) + reply(owner.read(&stopping).await.map_err(error)?) } "collaboration.set_model_policy" => { let p: SetPolicy = params(value)?; if let Err(SettingsError::Invalid(reason)) = p.policy.validate() { return Err(RpcError::invalid(reason)); } - let snapshot = settings + let snapshot = owner + .0 .update( SettingsScope::User, &p.expected_revision, diff --git a/crates/dim-app-server/src/hooks_settings.rs b/crates/dim-app-server/src/hooks_settings.rs index 06c7dc2829..151730eaa1 100644 --- a/crates/dim-app-server/src/hooks_settings.rs +++ b/crates/dim-app-server/src/hooks_settings.rs @@ -5,7 +5,10 @@ use crate::{ methods::{ManagementMethods, SelectionScope}, protocol::canonical_cwd, - settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService, SettingsSnapshot}, + settings::{ + BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope, + SettingsSnapshot, + }, }; use dim_agent_capabilities::{ file_storage::{FileStorageError, FsHost}, @@ -129,7 +132,10 @@ fn plugin_sources(documents: HooksPlugins) -> Vec { /// a Settings source; the project file is read through fsHost under the /// root Settings authorized for the workspace. struct SettingsHookSources { - settings: Arc, + settings: Arc, + user: Arc>, + projects: Arc>, + plugins: Arc>, files: Arc, home: Option, } @@ -159,25 +165,30 @@ impl ReadHookSources for SettingsHookSources { let cwd = cwd.to_path_buf(); Box::pin(async move { let user = self - .settings - .read::(SettingsScope::User, &cancel) + .user + .read(SettingsScope::User, &cancel) .await .map_err(host_error)?; let projects = self - .settings - .read::(SettingsScope::User, &cancel) + .projects + .read(SettingsScope::User, &cancel) .await .map_err(host_error)?; let plugins = self - .settings - .read::(SettingsScope::User, &cancel) + .plugins + .read(SettingsScope::User, &cancel) .await .map_err(host_error)?; let mut sources = vec![user_source(&user.revision, user.document)]; // A hook point reads; it never authorizes. The Session's own // creation registered its root. - if let Some(root) = self.settings.project_root(&cwd) { - sources.push(self.project(root, &projects.document, &cancel).await?); + if self + .settings + .projects() + .iter() + .any(|project| project.cwd == cwd) + { + sources.push(self.project(&cwd, &projects.document, &cancel).await?); } sources.extend(plugin_sources(plugins.document)); Ok(HookSourcesSnapshot { sources }) @@ -193,7 +204,7 @@ impl SettingsHookSources { /// The sources of a workspace whose root the caller authorized. async fn authorized( &self, - root: usize, + workspace: &Path, user: &SettingsSnapshot, projects: &SettingsSnapshot, plugins: &SettingsSnapshot, @@ -201,7 +212,7 @@ impl SettingsHookSources { ) -> Result { let mut sources = vec![ user_source(&user.revision, user.document.clone()), - self.project(root, &projects.document, cancel).await?, + self.project(workspace, &projects.document, cancel).await?, ]; sources.extend(plugin_sources(plugins.document.clone())); Ok(HookSourcesSnapshot { sources }) @@ -210,11 +221,10 @@ impl SettingsHookSources { /// The workspace's source, from the root Settings authorized for it. async fn project( &self, - root: usize, + workspace: &Path, projects: &HooksProjects, cancel: &CancellationToken, ) -> Result { - let workspace = self.settings.project_path(root).map_err(host_error)?; let workspace_key = workspace.to_string_lossy().into_owned(); let path = workspace.join(PROJECT_FILE); let state = match self @@ -272,52 +282,33 @@ fn host_error_message(message: String) -> dim_agent_capabilities::host::HostErro /// Registers the Session part that binds the hook sources; the host registers /// `HooksSettingsPlugin` with its Settings. -pub fn install(builder: &mut AgentBuilder, product_home: Option) { +pub fn install(builder: &mut AgentBuilder) { crate::register_names(builder.catalog_mut()); - builder.require_feature( - Feature::new("HookSources").session("HookSources", move |names| { - Ok(Box::new(HookSourcesPlugin::new( - names, - product_home.clone(), - )?)) - }), - ); + builder.require_feature(Feature::new("HookSources").session("HookSources", |names| { + Ok(Box::new(HookSourcesPlugin { + host: names.key()?, + owner: names.key()?, + })) + })); } struct HookSourcesPlugin { host: Key, - settings: Key, - files: Key, - home: Option, -} -impl HookSourcesPlugin { - fn new(names: &Names<'_>, home: Option) -> rutis::Result { - Ok(Self { - host: names.key()?, - settings: names.key()?, - files: names.key()?, - home, - }) - } + owner: Key, } impl DynPlugin for HookSourcesPlugin { fn name(&self) -> &str { "HookSources" } fn injects(&self) -> Vec { - vec![self.settings.erase(), self.files.erase()] + vec![self.owner.erase()] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let settings = ctx.require_at(&self.settings)?; - let files = ctx.require_at(&self.files)?; + let owner = ctx.require_at(&self.owner)?; ctx.provide_at( self.host.clone(), - Arc::new(HookSourcesHost(Arc::new(SettingsHookSources { - settings, - files, - home: self.home.clone(), - }))), + Arc::new(HookSourcesHost(owner.reader.clone())), )?; Ok(Effect::Done) }) @@ -396,19 +387,6 @@ fn error(error: SettingsError) -> RpcError { RpcError::app(-32000, kind, error.to_string()) } -/// The port over this host's Settings and files. -fn reader( - settings: &Arc, - files: &Arc, - home: Option, -) -> Arc { - Arc::new(SettingsHookSources { - settings: settings.clone(), - files: files.clone(), - home, - }) -} - /// A refused plugin document's error and optional credential-safe reason. pub type HookRefusal = (String, Option<&'static str>); @@ -417,7 +395,7 @@ pub type HookRefusal = (String, Option<&'static str>); /// `hooks-plugins`. #[derive(Clone)] pub struct HooksService { - settings: Arc, + reader: Arc, /// Why the last registration of a plugin was refused, by plugin id: the /// raw error, and its static reason when the cause has one /// (PluginManager A.2). @@ -441,6 +419,12 @@ struct PluginRequest { #[serde(deny_unknown_fields)] struct NoArguments {} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SourceRequest { + cwd: PathBuf, +} + fn face_request( args: rutis_bridge::session::Value, ) -> Result { @@ -480,7 +464,7 @@ fn face_reply(result: crate::settings::Result) -> rutis_bridge: impl rutis_bridge::session::HostDispatch for HooksService { fn methods(&self) -> Option { Some( - serde_json::json!({"register":"async", "withdraw":"async", "plugins":"async", "refusal":"sync"}), + serde_json::json!({"register":"async", "withdraw":"async", "plugins":"async", "refusal":"sync", "sources":"async"}), ) } @@ -522,6 +506,25 @@ impl rutis_bridge::session::HostDispatch for HooksService { face_reply(owner.plugins(&cancel).await) })) } + "sources" => { + let SourceRequest { cwd } = face_request(args)?; + Ok(Value::future(async move { + let _guard = cancel.clone().drop_guard(); + let sources = owner.sources(&cwd, cancel).await.map_err(|error| { + let code = match error { + dim_agent_capabilities::host::HostError::Cancelled(_) => "cancelled", + _ => "failed", + }; + rutis_bridge::exports::failure( + "hooksService", + code, + error.to_string(), + None, + ) + })?; + rutis_bridge::session::arg(&sources) + })) + } "refusal" => { let PluginRequest { plugin } = face_request(args)?; rutis_bridge::session::arg(&self.plugin_refusal(&plugin)) @@ -534,6 +537,14 @@ impl rutis_bridge::session::HostDispatch for HooksService { } impl HooksService { + pub async fn sources( + &self, + cwd: &Path, + cancel: CancellationToken, + ) -> Result { + self.reader.sources(cwd, cancel).await + } + /// Adds or replaces the hook document of `plugin` (a plugin id, §3.7), /// whose commands read `dir` as `DIM_PLUGIN_ROOT` (Hooks A.2, A.3). The /// registration is kept in `hooks-plugins.json` and survives Hooks' @@ -603,8 +614,9 @@ impl HooksService { cancel: &CancellationToken, ) -> crate::settings::Result> { Ok(self - .settings - .read::(SettingsScope::User, cancel) + .reader + .plugins + .read(SettingsScope::User, cancel) .await? .document .plugins @@ -623,8 +635,9 @@ impl HooksService { ) -> crate::settings::Result<()> { loop { let current = self - .settings - .read::(SettingsScope::User, cancel) + .reader + .plugins + .read(SettingsScope::User, cancel) .await?; let mut document = current.document; if document.plugins.get(&plugin) == registration.as_ref() { @@ -641,7 +654,8 @@ impl HooksService { } } match self - .settings + .reader + .plugins .update(SettingsScope::User, ¤t.revision, document, cancel) .await { @@ -655,7 +669,7 @@ impl HooksService { /// Process owner of the `hooks` sources and their management methods. pub struct HooksSettingsPlugin { - settings: Key, + settings: Key, files: Key, methods: Key, product_home: Option, @@ -686,11 +700,16 @@ impl DynPlugin for HooksSettingsPlugin { let settings = ctx.require_at(&self.settings)?; let files = ctx.require_at(&self.files)?; let methods = ctx.require_at(&self.methods)?; - settings.register::(ctx)?; - settings.register::(ctx)?; - settings.register::(ctx)?; - let service = Arc::new(HooksService { + let reader = Arc::new(SettingsHookSources { + user: settings.register_document::(ctx)?, + projects: settings.register_document::(ctx)?, + plugins: settings.register_document::(ctx)?, settings: settings.clone(), + files, + home: self.product_home.clone(), + }); + let service = Arc::new(HooksService { + reader: reader.clone(), refused: Arc::default(), }); ctx.provide_as::(service.clone())?; @@ -698,7 +717,6 @@ impl DynPlugin for HooksSettingsPlugin { rutis_bridge::session::host_key("hooksService"), service, )?; - let reader = reader(&settings, &files, self.product_home.clone()); methods.register( ctx, "hooks", @@ -720,27 +738,30 @@ impl DynPlugin for HooksSettingsPlugin { match method.as_str() { "hooks.catalog" => { let p: SelectionScope = params(value)?; - let user = settings - .read::(SettingsScope::User, &stopping) + let user = reader + .user + .read(SettingsScope::User, &stopping) .await .map_err(error)?; - let projects = settings - .read::(SettingsScope::User, &stopping) + let projects = reader + .projects + .read(SettingsScope::User, &stopping) .await .map_err(error)?; - let plugins = settings - .read::(SettingsScope::User, &stopping) + let plugins = reader + .plugins + .read(SettingsScope::User, &stopping) .await .map_err(error)?; let snapshot = match p.cwd { Some(cwd) => { let cwd = canonical_cwd(&cwd).await?; - let root = settings - .authorize_project(cwd, &stopping) + settings + .authorize_project(cwd.clone(), &stopping) .await .map_err(error)?; reader - .authorized(root, &user, &projects, &plugins, &stopping) + .authorized(&cwd, &user, &projects, &plugins, &stopping) .await .map_err(|error| { RpcError::app( @@ -776,7 +797,8 @@ impl DynPlugin for HooksSettingsPlugin { } "hooks.save" => { let p: SaveHooks = params(value)?; - let snapshot = settings + let snapshot = reader + .user .update( SettingsScope::User, &p.expected_revision, @@ -792,17 +814,14 @@ impl DynPlugin for HooksSettingsPlugin { "hooks.set_enabled" => { let p: SetHookProject = params(value)?; let cwd = canonical_cwd(&p.cwd).await?; - let root = settings - .authorize_project(cwd, &stopping) + settings + .authorize_project(cwd.clone(), &stopping) .await .map_err(error)?; - let workspace = settings - .project_path(root) - .map_err(error)? - .to_string_lossy() - .into_owned(); - let snapshot = settings - .read::(SettingsScope::User, &stopping) + let workspace = cwd.to_string_lossy().into_owned(); + let snapshot = reader + .projects + .read(SettingsScope::User, &stopping) .await .map_err(error)?; if snapshot.revision != p.expected_revision { @@ -819,7 +838,8 @@ impl DynPlugin for HooksSettingsPlugin { revision: snapshot.revision, }); } - let snapshot = settings + let snapshot = reader + .projects .update( SettingsScope::User, &snapshot.revision, @@ -884,13 +904,8 @@ mod tests { wait_active(&root, &views, Duration::from_secs(5), &cancel) .await .unwrap(); - let settings = root.get::().unwrap(); - let files = root.get::().unwrap(); - let sources = SettingsHookSources { - settings: settings.clone(), - files, - home: Some(home.clone()), - }; + let settings = root.get::().unwrap(); + let sources = root.get::().unwrap(); let snapshot = sources.sources(&project, cancel.clone()).await.unwrap(); assert_eq!( snapshot.sources.len(), @@ -898,7 +913,7 @@ mod tests { "an unauthorized workspace has no project source" ); assert!( - settings.project_root(&project).is_none(), + settings.projects().iter().all(|entry| entry.cwd != project), "a hook point authorized a project" ); diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index e892c17b0b..54867a655f 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1444,8 +1444,8 @@ pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCata register::(catalog, None); register::(catalog, None); register::(catalog, Some(SESSION_GROUP)); - register::(catalog, None); register::(catalog, None); + register::(catalog, None); register::(catalog, None); register::(catalog, None); register::(catalog, None); @@ -1474,6 +1474,7 @@ pub(crate) fn register_names(catalog: &mut dim_agent_runtime::names::ServiceCata "managedSearch", "auxiliaryModel", "settings", + "collaborationModelPolicy", "ocrHelper", ] { catalog.register_shared(name); @@ -1515,7 +1516,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("serverControl", "control"), ("sessionLoader", "control"), ("sessionStore", "owner-api"), - ("settingsService", "owner-api"), ("submitChecks", "hot-path"), ("timelineFactory", "control"), ("timelineTree", "owner-api"), diff --git a/crates/dim-app-server/src/mcp.rs b/crates/dim-app-server/src/mcp.rs index f2f4b01536..da2b7c7009 100644 --- a/crates/dim-app-server/src/mcp.rs +++ b/crates/dim-app-server/src/mcp.rs @@ -21,7 +21,9 @@ pub use session::{ McpWidgetResult, install, }; -use crate::settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}; +use crate::settings::{ + BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope, +}; use config::{ McpEntryError, McpPluginDocument, McpPluginServers, McpProjectEnablement, McpSecretEntry, McpSecrets, McpServerSettings, McpSettings, @@ -401,7 +403,7 @@ impl Drop for McpConnection { /// connection runs, and the credential key of that expansion. Every read and /// every path that contacts a server uses this one order. fn resolved_entry( - settings: &SettingsService, + settings: &McpDocuments, source: McpSource, id: &str, configuration: McpServerSettings, @@ -414,11 +416,17 @@ fn resolved_entry( McpSource::Plugins => config::Origin::Plugin, McpSource::Project(_) => config::Origin::Workspace { overlay: secret }, }; + let workspace = match source { + McpSource::Project(root) => Some(config::workspace( + &settings.authority, + SettingsScope::Project(root), + )?), + _ => None, + }; let expansion = config::connected( - settings, configuration.clone(), config::Connection { - scope: source.scope(), + workspace: workspace.as_deref(), id, secret, origin, @@ -427,14 +435,8 @@ fn resolved_entry( protected, }, )?; - let configuration = config::viewed( - settings, - source.scope(), - id, - configuration, - secret, - enablement, - )?; + let configuration = + config::viewed(workspace.as_deref(), id, configuration, secret, enablement)?; let credential = auth::credential_key(id, &expansion.configuration).map(|(key, _)| key); Ok(McpResolvedEntry { entry: McpServerEntry { @@ -452,8 +454,16 @@ fn resolved_entry( /// A plugin document's last refusal message and optional stable reason. pub type McpPluginRefusal = (String, Option<&'static str>); +struct McpDocuments { + authority: Arc, + servers: Arc>, + enablement: Arc>, + plugins: Arc>, + secrets: Arc>, +} + pub struct McpService { - settings: Arc, + settings: Arc, credentials: Arc, /// Why the last registration of a plugin was refused, by plugin id: the /// raw error, and its static reason when the cause has one @@ -596,7 +606,8 @@ impl McpService { pub async fn plugins(&self, cancel: &CancellationToken) -> Result> { self.run(cancel, move |settings, cancel| async move { Ok(settings - .read::(SettingsScope::User, &cancel) + .plugins + .read(SettingsScope::User, &cancel) .await? .document .plugins @@ -615,9 +626,7 @@ impl McpService { let changed = self .run(cancel, move |settings, cancel| async move { loop { - let current = settings - .read::(SettingsScope::User, &cancel) - .await?; + let current = settings.plugins.read(SettingsScope::User, &cancel).await?; let mut document = current.document; if document.plugins.get(&plugin) == registration.as_ref() { return Ok(false); @@ -633,6 +642,7 @@ impl McpService { } } match settings + .plugins .update(SettingsScope::User, ¤t.revision, document, &cancel) .await { @@ -674,7 +684,8 @@ impl McpService { let mut invalid: BTreeMap<(McpSource, String), McpEntryError> = BTreeMap::new(); let enablement = match project { Some(_) => settings - .read::(SettingsScope::User, &cancel) + .enablement + .read(SettingsScope::User, &cancel) .await .map(|snapshot| snapshot.document) .unwrap_or_default(), @@ -683,7 +694,8 @@ impl McpService { let secrets = match project { Some(_) => { settings - .read::(SettingsScope::User, &cancel) + .secrets + .read(SettingsScope::User, &cancel) .await? .document } @@ -691,9 +703,7 @@ impl McpService { }; for source in sources_in_precedence(project) { let Some(scope) = source.scope() else { - let plugins = settings - .read::(SettingsScope::User, &cancel) - .await?; + let plugins = settings.plugins.read(SettingsScope::User, &cancel).await?; let (entries, broken) = plugins.document.into_entries(); for (id, error) in broken { invalid.insert((source, id), error); @@ -714,10 +724,12 @@ impl McpService { continue; }; let workspace = match scope { - SettingsScope::Project(_) => Some(config::workspace(&settings, scope)?), + SettingsScope::Project(_) => { + Some(config::workspace(&settings.authority, scope)?) + } SettingsScope::User => None, }; - let snapshot = settings.read::(scope, &cancel).await?; + let snapshot = settings.servers.read(scope, &cancel).await?; match scope { SettingsScope::User => catalog.user_revision = snapshot.revision, SettingsScope::Project(_) => { @@ -784,7 +796,8 @@ impl McpService { let protected = credentials.variables().variables; let Some(scope) = source.scope() else { let (mut entries, mut invalid) = settings - .read::(SettingsScope::User, &cancel) + .plugins + .read(SettingsScope::User, &cancel) .await? .document .into_entries(); @@ -805,7 +818,7 @@ impl McpService { ); }; let source = scope; - let snapshot = settings.read::(source, &cancel).await?; + let snapshot = settings.servers.read(source, &cancel).await?; let document = snapshot.document; let Some(configuration) = document.get(&id).cloned() else { return match document.invalid_error(&id) { @@ -842,7 +855,8 @@ impl McpService { self.run(cancel, move |settings, cancel| async move { let Some(scope) = source.scope() else { let configuration = match settings - .read::(SettingsScope::User, &cancel) + .plugins + .read(SettingsScope::User, &cancel) .await? .document .declared(&id) @@ -852,10 +866,9 @@ impl McpService { Err(error) => return Err(McpError::InvalidEntry(error)), }; let expansion = config::connected( - &settings, configuration.clone(), config::Connection { - scope: None, + workspace: None, id: &id, secret: None, origin: config::Origin::Plugin, @@ -874,7 +887,7 @@ impl McpService { secret: None, }); }; - let snapshot = settings.read::(scope, &cancel).await?; + let snapshot = settings.servers.read(scope, &cancel).await?; let Some(mut configuration) = snapshot.document.get(&id).cloned() else { return match snapshot.document.invalid_error(&id) { Some(error) => Err(McpError::InvalidEntry(error.clone())), @@ -893,10 +906,9 @@ impl McpService { }, }; let expansion = config::connected( - &settings, configuration.clone(), config::Connection { - scope: None, + workspace: None, id: &id, secret: None, origin, @@ -909,7 +921,7 @@ impl McpService { SettingsScope::User => configuration.enabled(), SettingsScope::Project(_) => { let enablement = enablement(&settings, scope, &cancel).await; - let workspace = config::workspace(&settings, scope)?; + let workspace = config::workspace(&settings.authority, scope)?; enablement.contains(&workspace, &id) } }; @@ -957,7 +969,7 @@ impl McpService { return Err(McpError::InvalidId); } self.run(cancel, move |settings, cancel| async move { - let workspace = config::workspace(&settings, source)?; + let workspace = config::workspace(&settings.authority, source)?; remove_secret_if(&settings, &workspace, &id, &generation, &cancel).await }) .await @@ -984,11 +996,14 @@ impl McpService { overlay: overlay.as_ref(), }, }; + let workspace = match scope { + SettingsScope::Project(_) => Some(config::workspace(&settings.authority, scope)?), + SettingsScope::User => None, + }; Ok(config::connected( - &settings, configuration, config::Connection { - scope: Some(scope), + workspace: workspace.as_deref(), id: &id, secret: None, origin, @@ -1129,7 +1144,7 @@ impl McpService { cancel: &CancellationToken, ) -> Result { self.run(cancel, move |settings, cancel| async move { - let snapshot = settings.read::(source, &cancel).await?; + let snapshot = settings.servers.read(source, &cancel).await?; let overlays = overlays(&settings, source, &cancel).await?; Ok(import::preview( &document, @@ -1188,8 +1203,8 @@ impl McpService { } let into_project = matches!(to_scope, SettingsScope::Project(_)); self.run(cancel, move |settings, cancel| async move { - let from_snapshot = settings.read::(from_scope, &cancel).await?; - let to_snapshot = settings.read::(to_scope, &cancel).await?; + let from_snapshot = settings.servers.read(from_scope, &cancel).await?; + let to_snapshot = settings.servers.read(to_scope, &cancel).await?; let from_overlays = overlays(&settings, from_scope, &cancel).await?; let to_overlays = overlays(&settings, to_scope, &cancel).await?; if source_revision(from_scope, &from_snapshot.revision, &from_overlays) != expected_from @@ -1213,19 +1228,26 @@ impl McpService { config::merge_secret(&mut entry, secret)?; } let enablement = enablement(&settings, from_scope, &cancel).await; - let mut entry = config::effective(&settings, from_scope, &id, entry, &enablement)?; + let workspace = match from_scope { + SettingsScope::Project(_) => { + Some(config::workspace(&settings.authority, from_scope)?) + } + SettingsScope::User => None, + }; + let mut entry = config::effective(workspace.as_deref(), &id, entry, &enablement)?; let mut document = McpSettings::default(); document.insert(id.clone(), entry.clone()); document.validate()?; match to_scope { SettingsScope::Project(_) => { - let workspace = config::workspace(&settings, to_scope)?; + let workspace = config::workspace(&settings.authority, to_scope)?; let (skeleton, to_secret) = config::split_entry(&entry); set_project_enabled(&settings, to_scope, &id, false, &cancel).await?; let mut destination = to_snapshot.document; destination.insert(id.clone(), skeleton); settings + .servers .update(to_scope, &to_snapshot.revision, destination, &cancel) .await?; if let Some(secret) = to_secret { @@ -1242,12 +1264,13 @@ impl McpService { let mut source = from_snapshot.document; source.remove(&id); settings + .servers .update(from_scope, &from_snapshot.revision, source, &cancel) .await .map_err(|error| partial(error.into(), into_project))?; } SettingsScope::User => { - let workspace = config::workspace(&settings, from_scope)?; + let workspace = config::workspace(&settings.authority, from_scope)?; let enabled = enablement.contains(&workspace, &id); let (McpServerSettings::Stdio { enabled: field, .. } | McpServerSettings::Remote { enabled: field, .. }) = &mut entry; @@ -1255,6 +1278,7 @@ impl McpService { let mut destination = to_snapshot.document; destination.insert(id.clone(), entry); settings + .servers .update(to_scope, &to_snapshot.revision, destination, &cancel) .await?; if let Err(error) = @@ -1270,6 +1294,7 @@ impl McpService { let mut source = from_snapshot.document; source.remove(&id); settings + .servers .update(from_scope, &from_snapshot.revision, source, &cancel) .await .map_err(|error| partial(error.into(), into_project))?; @@ -1283,7 +1308,7 @@ impl McpService { async fn run(&self, cancel: &CancellationToken, operation: F) -> Result where T: Send + 'static, - F: FnOnce(Arc, CancellationToken) -> Fut + Send + 'static, + F: FnOnce(Arc, CancellationToken) -> Fut + Send + 'static, Fut: Future> + Send + 'static, { let task = { @@ -1316,14 +1341,15 @@ impl McpService { /// The user's enablement of project entries; empty for the user source, whose /// entries carry their own field. async fn enablement( - settings: &SettingsService, + settings: &McpDocuments, scope: SettingsScope, cancel: &CancellationToken, ) -> McpProjectEnablement { match scope { SettingsScope::User => McpProjectEnablement::default(), SettingsScope::Project(_) => settings - .read::(SettingsScope::User, cancel) + .enablement + .read(SettingsScope::User, cancel) .await .map(|snapshot| snapshot.document) .unwrap_or_default(), @@ -1332,7 +1358,7 @@ async fn enablement( /// One project entry's user-scope secret overlay, if it has one. async fn secret( - settings: &SettingsService, + settings: &McpDocuments, scope: SettingsScope, id: &str, cancel: &CancellationToken, @@ -1340,10 +1366,8 @@ async fn secret( let SettingsScope::Project(_) = scope else { return Ok(None); }; - let workspace = config::workspace(settings, scope)?; - let snapshot = settings - .read::(SettingsScope::User, cancel) - .await?; + let workspace = config::workspace(&settings.authority, scope)?; + let snapshot = settings.secrets.read(SettingsScope::User, cancel).await?; Ok(snapshot.document.get(&workspace, id).cloned()) } @@ -1364,7 +1388,7 @@ struct WriteOutcome { /// Writes one change to its source and returns the source's revision and the /// removal's captured record generation. async fn write( - settings: &Arc, + settings: &Arc, source: SettingsScope, expected: String, id: String, @@ -1376,7 +1400,7 @@ async fn write( // A disable does not need the project file, so an unreadable file // still withdraws the record. A readable file names a broken entry, // whose disable is refused. - let snapshot = settings.read::(source, cancel).await; + let snapshot = settings.servers.read(source, cancel).await; if let Ok(snapshot) = &snapshot && let Some(error) = snapshot.document.invalid_error(&id) { @@ -1389,7 +1413,7 @@ async fn write( entry_absent: false, }); } - let snapshot = settings.read::(source, cancel).await?; + let snapshot = settings.servers.read(source, cancel).await?; let overlays = overlays(settings, source, cancel).await?; if source_revision(source, &snapshot.revision, &overlays) != expected { return Err(SettingsError::Conflict.into()); @@ -1442,6 +1466,7 @@ async fn write( }; let Some(present) = removed else { let written = settings + .servers .update(source, &snapshot.revision, document, cancel) .await?; return Ok(WriteOutcome { @@ -1455,6 +1480,7 @@ async fn write( let captured = overlays.get(&id).map(|secret| secret.generation.clone()); let revision = if present { settings + .servers .update(source, &snapshot.revision, document, cancel) .await? .revision @@ -1482,14 +1508,14 @@ async fn write( /// source commit answers `ImportPartial`, and the source entries stay as /// written. async fn write_import( - settings: &Arc, + settings: &Arc, source: SettingsScope, expected: String, document: McpSettings, resolutions: BTreeMap, cancel: &CancellationToken, ) -> Result { - let snapshot = settings.read::(source, cancel).await?; + let snapshot = settings.servers.read(source, cancel).await?; let project = matches!(source, SettingsScope::Project(_)); let overlays = overlays(settings, source, cancel).await?; if source_revision(source, &snapshot.revision, &overlays) != expected { @@ -1511,11 +1537,12 @@ async fn write_import( target.insert(id, configuration); } let written = settings + .servers .update(source, &snapshot.revision, target, cancel) .await?; return Ok(source_revision(source, &written.revision, &overlays)); } - let workspace = config::workspace(settings, source)?; + let workspace = config::workspace(&settings.authority, source)?; // Every id the import writes, an import or a replace, has its // `mcp-projects` record withdrawn before the source write, so an imported // configuration never runs enabled and a replaced entry cannot run while @@ -1534,6 +1561,7 @@ async fn write_import( records.push((id, record)); } let revision = settings + .servers .update(source, &snapshot.revision, target, cancel) .await? .revision; @@ -1554,16 +1582,14 @@ async fn write_import( /// part removes the destination's record, so the pair the import leaves is /// exactly the configuration the document carried. async fn write_import_secrets( - settings: &Arc, + settings: &Arc, workspace: &str, records: &[(String, Option)], planned: &BTreeMap, cancel: &CancellationToken, ) -> Result<()> { loop { - let snapshot = settings - .read::(SettingsScope::User, cancel) - .await?; + let snapshot = settings.secrets.read(SettingsScope::User, cancel).await?; let current = snapshot .document .entries @@ -1590,6 +1616,7 @@ async fn write_import_secrets( } } match settings + .secrets .update(SettingsScope::User, &snapshot.revision, document, cancel) .await { @@ -1603,16 +1630,17 @@ async fn write_import_secrets( /// The `mcp-secrets` records of one project source's workspace, by id. A user /// source has no record. async fn overlays( - settings: &Arc, + settings: &Arc, source: SettingsScope, cancel: &CancellationToken, ) -> Result> { let SettingsScope::Project(_) = source else { return Ok(BTreeMap::new()); }; - let workspace = config::workspace(settings, source)?; + let workspace = config::workspace(&settings.authority, source)?; Ok(settings - .read::(SettingsScope::User, cancel) + .secrets + .read(SettingsScope::User, cancel) .await? .document .overlays(&workspace)) @@ -1662,7 +1690,7 @@ fn source_revision( /// already hold them. A source whose records cannot be read keeps the document /// revision: no caller can apply against it, so the fallback fails closed. async fn read_source_revision( - settings: &Arc, + settings: &Arc, source: SettingsScope, file: &str, cancel: &CancellationToken, @@ -1674,38 +1702,36 @@ async fn read_source_revision( } async fn write_secret( - settings: &Arc, + settings: &Arc, workspace: &str, id: &str, mut secret: McpSecretEntry, cancel: &CancellationToken, ) -> Result<()> { secret.generation = uuid::Uuid::new_v4().to_string(); - let snapshot = settings - .read::(SettingsScope::User, cancel) - .await?; + let snapshot = settings.secrets.read(SettingsScope::User, cancel).await?; let mut document = snapshot.document; document.set(workspace, id, secret); settings + .secrets .update(SettingsScope::User, &snapshot.revision, document, cancel) .await?; Ok(()) } async fn remove_secret( - settings: &Arc, + settings: &Arc, workspace: &str, id: &str, cancel: &CancellationToken, ) -> Result<()> { - let snapshot = settings - .read::(SettingsScope::User, cancel) - .await?; + let snapshot = settings.secrets.read(SettingsScope::User, cancel).await?; let mut document = snapshot.document; if !document.remove(workspace, id) { return Ok(()); } settings + .secrets .update(SettingsScope::User, &snapshot.revision, document, cancel) .await?; Ok(()) @@ -1714,16 +1740,14 @@ async fn remove_secret( /// Deletes the record only while it still carries `generation`; a replacement /// move writes a new generation for the same id, and that record is kept. async fn remove_secret_if( - settings: &Arc, + settings: &Arc, workspace: &str, id: &str, generation: &str, cancel: &CancellationToken, ) -> Result<()> { loop { - let snapshot = settings - .read::(SettingsScope::User, cancel) - .await?; + let snapshot = settings.secrets.read(SettingsScope::User, cancel).await?; let Some(current) = snapshot.document.get(workspace, id) else { return Ok(()); }; @@ -1733,6 +1757,7 @@ async fn remove_secret_if( let mut document = snapshot.document; document.remove(workspace, id); match settings + .secrets .update(SettingsScope::User, &snapshot.revision, document, cancel) .await { @@ -1747,22 +1772,24 @@ async fn remove_secret_if( /// entries commute, so a lost race on the shared record is retried rather /// than reported as a conflict the caller cannot observe. async fn set_project_enabled( - settings: &Arc, + settings: &Arc, source: SettingsScope, id: &str, enabled: bool, cancel: &CancellationToken, ) -> Result<()> { - let workspace = config::workspace(settings, source)?; + let workspace = config::workspace(&settings.authority, source)?; loop { let current = settings - .read::(SettingsScope::User, cancel) + .enablement + .read(SettingsScope::User, cancel) .await?; let mut record = current.document; if !record.set(&workspace, id, enabled) { return Ok(()); } match settings + .enablement .update(SettingsScope::User, ¤t.revision, record, cancel) .await { @@ -1778,7 +1805,7 @@ async fn set_project_enabled( /// Session part `McpSession`, which it registers. pub struct McpPlugin { home_root: usize, - settings: Key, + settings: Key, publication: Key, files: Key, methods: Key, @@ -1820,13 +1847,17 @@ impl DynPlugin for McpPlugin { let methods = ctx.require_at(&self.methods)?; let parts = ctx.require_at(&self.parts)?; let credentials = ctx.require_at(&self.credentials)?; - settings.register::(ctx)?; - settings.register::(ctx)?; - settings.register::(ctx)?; - settings.register::(ctx)?; + let documents = Arc::new(McpDocuments { + servers: settings.register_document::(ctx)?, + enablement: settings.register_document::(ctx)?, + plugins: settings.register_document::(ctx)?, + secrets: settings.register_document::(ctx)?, + authority: settings.clone(), + }); let auth = McpAuth::new(files, self.home_root).map_err(ErrorKind::PluginFailed)?; + *publication.documents.lock().unwrap() = Some(documents.clone()); let service = Arc::new(McpService { - settings, + settings: documents, credentials, refused: Mutex::default(), publication, @@ -1844,13 +1875,7 @@ impl DynPlugin for McpPlugin { closing.close().await; Ok(()) })?; - management::provide( - ctx, - &methods, - service.clone(), - service.settings.clone(), - auth.clone(), - )?; + management::provide(ctx, &methods, service.clone(), settings, auth.clone())?; ctx.provide_as::(auth)?; ctx.provide_at(owner_key(), service.clone())?; let binding = Arc::new(McpServiceBinding(service)); diff --git a/crates/dim-app-server/src/mcp/config.rs b/crates/dim-app-server/src/mcp/config.rs index b108234513..69d21263f5 100644 --- a/crates/dim-app-server/src/mcp/config.rs +++ b/crates/dim-app-server/src/mcp/config.rs @@ -1,5 +1,5 @@ //! Typed MCP documents and the effective configuration of each entry. -use crate::settings::{BusinessDocument, Result, SettingsError, SettingsScope, SettingsService}; +use crate::settings::{BusinessDocument, Result, Settings, SettingsError, SettingsScope}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::{ @@ -1801,12 +1801,16 @@ fn literal_scheme(value: &str) -> Option<&str> { /// The canonical workspace of an authorized project source, as the /// enablement key. -pub(crate) fn workspace(settings: &SettingsService, scope: SettingsScope) -> Result { +pub(crate) fn workspace(settings: &Settings, scope: SettingsScope) -> Result { let SettingsScope::Project(root) = scope else { return Err(SettingsError::Invalid("not a project MCP source")); }; settings - .project_path(root)? + .projects() + .into_iter() + .find(|project| project.root == root) + .ok_or(SettingsError::Invalid("unauthorized project"))? + .cwd .to_str() .map(str::to_owned) .ok_or(SettingsError::Invalid("project cwd must be UTF-8")) @@ -1816,7 +1820,7 @@ pub(crate) fn workspace(settings: &SettingsService, scope: SettingsScope) -> Res /// source it belongs to, the overlay to merge, who wrote each member, the /// user's project enablement, and the environment to expand from. pub(crate) struct Connection<'a> { - pub scope: Option, + pub workspace: Option<&'a str>, pub id: &'a str, pub secret: Option<&'a McpSecretEntry>, pub origin: Origin<'a>, @@ -1830,12 +1834,11 @@ pub(crate) struct Connection<'a> { /// `cwd` and enablement. Every caller uses this one order, so a probe and a /// published connection see the same values. pub(crate) fn connected( - settings: &SettingsService, configuration: McpServerSettings, connection: Connection<'_>, ) -> Result { let Connection { - scope, + workspace, id, secret, origin, @@ -1848,10 +1851,7 @@ pub(crate) fn connected( merge_secret(&mut configuration, secret)?; } let expansion = expand(&configuration, origin, environment, protected); - let configuration = match scope { - Some(scope) => effective(settings, scope, id, expansion.configuration, enablement)?, - None => expansion.configuration, - }; + let configuration = effective(workspace, id, expansion.configuration, enablement)?; Ok(Expanded { configuration, referenced: expansion.referenced, @@ -1863,8 +1863,7 @@ pub(crate) fn connected( /// the project workspace `cwd` joined, with references kept as written so a /// client can edit them. pub(crate) fn viewed( - settings: &SettingsService, - scope: Option, + workspace: Option<&str>, id: &str, configuration: McpServerSettings, secret: Option<&McpSecretEntry>, @@ -1874,29 +1873,24 @@ pub(crate) fn viewed( if let Some(secret) = secret { merge_secret(&mut configuration, secret)?; } - match scope { - Some(scope) => effective(settings, scope, id, configuration, enablement), - None => Ok(configuration), - } + effective(workspace, id, configuration, enablement) } /// The configuration an entry runs with. A project entry resolves its stdio /// cwd against the workspace and takes its enablement only from the user's /// record; its own `enabled` field is ignored. pub(crate) fn effective( - settings: &SettingsService, - scope: SettingsScope, + workspace: Option<&str>, id: &str, mut config: McpServerSettings, enablement: &McpProjectEnablement, ) -> Result { - if matches!(scope, SettingsScope::Project(_)) { - let workspace = workspace(settings, scope)?; + if let Some(workspace) = workspace { let (McpServerSettings::Stdio { enabled, .. } | McpServerSettings::Remote { enabled, .. }) = &mut config; - *enabled = Some(enablement.contains(&workspace, id)); + *enabled = Some(enablement.contains(workspace, id)); if let McpServerSettings::Stdio { cwd, .. } = &mut config { - let workspace = PathBuf::from(&workspace); + let workspace = PathBuf::from(workspace); let path = cwd .as_ref() .map_or(workspace.clone(), |cwd| workspace.join(cwd)); diff --git a/crates/dim-app-server/src/mcp/management.rs b/crates/dim-app-server/src/mcp/management.rs index 0fba6aab08..7ffb28c0ac 100644 --- a/crates/dim-app-server/src/mcp/management.rs +++ b/crates/dim-app-server/src/mcp/management.rs @@ -9,7 +9,7 @@ use super::{McpChange, McpError, McpService, McpSource}; use crate::{ methods::{ManagementMethods, SelectionScope}, protocol::{canonical_cwd, optional_non_null}, - settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}, + settings::{BusinessDocument, Settings, SettingsError, SettingsScope}, }; use dim_agent_capabilities::methods::{ Interruption, MethodCall, MethodDecl, RpcError, params, reply, @@ -553,7 +553,7 @@ pub(crate) fn error(error: McpError) -> RpcError { /// canonical path and the string the request named it by. Claude Code records /// its local store under either spelling, so both are carried. async fn authorized_workspace( - settings: &Arc, + settings: &Arc, cwd: Option, stopping: &CancellationToken, ) -> Result, RpcError> { @@ -573,7 +573,7 @@ async fn authorized_workspace( } async fn project( - settings: &Arc, + settings: &Arc, cwd: Option, stopping: &CancellationToken, ) -> Result, RpcError> { @@ -662,7 +662,7 @@ pub(super) fn provide( ctx: &Ctx, methods: &ManagementMethods, directory: Arc, - settings: Arc, + settings: Arc, auth: Arc, ) -> Result<(), Error> { let context = ctx.clone(); diff --git a/crates/dim-app-server/src/mcp/publication.rs b/crates/dim-app-server/src/mcp/publication.rs index 77ae5463ee..dbeb9b7dbc 100644 --- a/crates/dim-app-server/src/mcp/publication.rs +++ b/crates/dim-app-server/src/mcp/publication.rs @@ -1,14 +1,12 @@ //! Serialized host authority for source selection and cross-Session retirement. //! Connection resources and disposal belong exclusively to loader instances. -use super::config::{ - self, McpPluginServers, McpProjectEnablement, McpSecrets, McpServerSettings, McpSettings, -}; +use super::config::{self, McpProjectEnablement, McpSecrets, McpServerSettings}; use super::{ - McpAuth, McpConnection, McpError, McpSource, Result, daemon_environment, + McpAuth, McpConnection, McpDocuments, McpError, McpSource, Result, daemon_environment, server::{McpRuntime, McpServer, McpServerError, McpServerPlugin, McpServerState}, source_revision, sources_in_precedence, }; -use crate::settings::{SettingsScope, SettingsService}; +use crate::settings::{ProjectAuthorized, Settings, SettingsScope}; use dim_agent_capabilities::host::CredentialVariablesHost; use dim_agent_runtime::{ Modules, Names, SessionLifecycle, SessionLoader, SessionPhase, StateCell, @@ -136,6 +134,7 @@ enum Command { Settle { reply: oneshot::Sender> }, } pub struct Publication { + pub(super) documents: std::sync::Mutex>>, commands: mpsc::Sender, released: watch::Sender<()>, applications: StateCell>, @@ -218,7 +217,7 @@ impl Publication { } pub struct McpPublication { - settings: Key, + authority: Key, credentials: Key, } struct Worker { @@ -231,7 +230,7 @@ struct Worker { impl McpPublication { pub fn new(names: &Names<'_>) -> rutis::Result { Ok(Self { - settings: names.key()?, + authority: names.key()?, credentials: names.key()?, }) } @@ -258,7 +257,7 @@ impl McpPublication { } } impl Worker { - async fn run(mut self, settings: Arc, stop: CancellationToken) -> Result<()> { + async fn run(mut self, stop: CancellationToken) -> Result<()> { let mut projection = Projection { port: self.port.clone(), credentials: self.credentials.clone(), @@ -278,7 +277,10 @@ impl Worker { _ = self.released.changed() => None, _ = changes.changed() => None, }; - projection.refresh(&settings, &operation).await; + let settings = self.port.documents.lock().unwrap().clone(); + if let Some(settings) = &settings { + projection.refresh(settings, &operation).await; + } match command { Some(Command::Acquire { owner, @@ -289,9 +291,14 @@ impl Worker { if reply.is_closed() { continue; } - let result = projection - .acquire(&settings, owner, project, id, &operation) - .await; + let result = match &settings { + Some(settings) => { + projection + .acquire(settings, owner, project, id, &operation) + .await + } + None => Err(McpError::Closed), + }; if let Err(Ok(lease)) = reply.send(result) { let references = projection .generations @@ -343,15 +350,15 @@ impl DynPlugin for McpPublication { "McpPublication" } fn injects(&self) -> Vec { - vec![self.settings.erase(), self.credentials.erase()] + vec![self.authority.erase(), self.credentials.erase()] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let settings = ctx.require_at(&self.settings)?; let credentials = ctx.require_at(&self.credentials)?; let (commands, receiver) = mpsc::channel(64); let (released, releases) = watch::channel(()); let port = Arc::new(Publication { + documents: Default::default(), commands, released, applications: StateCell::new(BTreeMap::new()), @@ -366,7 +373,7 @@ impl DynPlugin for McpPublication { ctx.provide_as::(port)?; let stop = ctx.cancellation_token(); ctx.effect(move || { - let task = tokio::spawn(worker.run(settings, stop.clone())); + let task = tokio::spawn(worker.run(stop.clone())); async move { stop.cancel(); Ok(task.await??) @@ -417,16 +424,17 @@ impl Projection { fn withdrawn( &self, generation: &Generation, - projects: &[(usize, std::path::PathBuf)], + projects: &[ProjectAuthorized], enablement: &McpProjectEnablement, ) -> bool { // A project entry runs only while the user's record names it, and that // record is readable whenever the disable is: the source may be // unreadable, so its last `current` state is not consulted here. if let McpSource::Project(root) = generation.source - && !projects.iter().any(|(project, workspace)| { - *project == root - && workspace + && !projects.iter().any(|project| { + project.root == root + && project + .cwd .to_str() .is_some_and(|workspace| enablement.contains(workspace, &generation.id)) }) @@ -440,13 +448,14 @@ impl Projection { } }) } - async fn refresh(&mut self, settings: &SettingsService, cancel: &CancellationToken) { - let projects = settings.project_sources(); + async fn refresh(&mut self, settings: &McpDocuments, cancel: &CancellationToken) { + let projects = settings.authority.projects(); let enablement = if projects.is_empty() { Ok(McpProjectEnablement::default()) } else { settings - .read::(SettingsScope::User, cancel) + .enablement + .read(SettingsScope::User, cancel) .await .map(|snapshot| snapshot.document) }; @@ -456,15 +465,20 @@ impl Projection { Ok(McpSecrets::default()) } else { settings - .read::(SettingsScope::User, cancel) + .secrets + .read(SettingsScope::User, cancel) .await .map(|snapshot| snapshot.document) }; let secrets_unreadable = secrets.is_err(); let secrets = secrets.unwrap_or_default(); - for source in [McpSource::User, McpSource::Plugins] + for (source, workspace) in [(McpSource::User, None), (McpSource::Plugins, None)] .into_iter() - .chain(projects.iter().map(|(root, _)| McpSource::Project(*root))) + .chain( + projects + .iter() + .map(|project| (McpSource::Project(project.root), project.cwd.to_str())), + ) { if secrets_unreadable && matches!(source, McpSource::Project(_)) { let intent = self.sources.entry(source).or_insert_with(|| Source { @@ -479,11 +493,13 @@ impl Projection { } let read = match source.scope() { Some(scope) => settings - .read::(scope, cancel) + .servers + .read(scope, cancel) .await .map(|snapshot| (snapshot.revision, snapshot.document.into_parts().0)), None => settings - .read::(SettingsScope::User, cancel) + .plugins + .read(SettingsScope::User, cancel) .await .map(|snapshot| (snapshot.revision, snapshot.document.entries())), }; @@ -498,15 +514,12 @@ impl Projection { degraded: None, }); intent.error = Some("MCP source could not be read"); - if let McpSource::Project(root) = source { - let workspace = - config::workspace(settings, SettingsScope::Project(root)).ok(); + if matches!(source, McpSource::Project(_)) { for (id, config) in &mut intent.current { let (McpServerSettings::Stdio { enabled, .. } | McpServerSettings::Remote { enabled, .. }) = config; *enabled = Some( workspace - .as_deref() .is_some_and(|workspace| enablement.contains(workspace, id)), ); } @@ -514,10 +527,6 @@ impl Projection { continue; } }; - let workspace = match source.scope() { - Some(scope @ SettingsScope::Project(_)) => config::workspace(settings, scope).ok(), - _ => None, - }; // A project source is served from `.mcp.json` and the workspace's // withheld records, so its applied token names both (D5, D23). An // `appliedRevision` over the document alone would never match the @@ -554,10 +563,9 @@ impl Projection { McpSource::Project(_) => config::Origin::Workspace { overlay: secret }, }; let expansion = config::connected( - settings, config, config::Connection { - scope: source.scope(), + workspace, id: &id, secret, origin, @@ -665,7 +673,7 @@ impl Projection { } async fn acquire( &mut self, - settings: &SettingsService, + settings: &McpDocuments, owner: McpOwner, project: Option, id: String, diff --git a/crates/dim-app-server/src/mcp/session.rs b/crates/dim-app-server/src/mcp/session.rs index a7683bec27..9a4fad7c27 100644 --- a/crates/dim-app-server/src/mcp/session.rs +++ b/crates/dim-app-server/src/mcp/session.rs @@ -475,7 +475,13 @@ impl DynPlugin for McpSessionPlugin { let loader = ctx.require_at(&self.loader)?; let session = ctx.require_at(&self.lifecycle)?; let tools = ctx.require_at(&self.tools)?; - let project = directory.settings.project_root(Path::new(&config.cwd)); + let project = directory + .settings + .authority + .projects() + .into_iter() + .find(|project| project.cwd == Path::new(&config.cwd)) + .map(|project| project.root); let settings = super::config::settings_changes(ctx)?; let applied = directory.publication.applied(); let stopped = ctx.cancellation_token(); diff --git a/crates/dim-app-server/src/permission_rules.rs b/crates/dim-app-server/src/permission_rules.rs index 2b69b0eedf..33420eb87f 100644 --- a/crates/dim-app-server/src/permission_rules.rs +++ b/crates/dim-app-server/src/permission_rules.rs @@ -3,7 +3,7 @@ use crate::{ methods::ManagementMethods, protocol::Empty, - settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}, + settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope}, }; use dim_agent_capabilities::{ host::{HostError, HostFuture}, @@ -55,15 +55,15 @@ pub fn install(builder: &mut AgentBuilder) { } /// Reads the user source on each call; nothing is cached. -struct SettingsRules(Arc); +struct SettingsRules(Ctx); impl ReadCommandRules for SettingsRules { fn rules(&self, cancel: CancellationToken) -> HostFuture<'_, Vec> { Box::pin(async move { - match self + let document = self .0 - .read::(SettingsScope::User, &cancel) - .await - { + .get::>() + .ok_or_else(|| HostError::failed(SettingsError::UnknownSource.to_string()))?; + match document.read(SettingsScope::User, &cancel).await { Ok(snapshot) => Ok(snapshot.document.command_rules), Err(SettingsError::Cancelled) => { Err(HostError::Cancelled("command rules read cancelled".into())) @@ -77,7 +77,7 @@ impl ReadCommandRules for SettingsRules { struct CommandRulesPlugin { host: Key, face: Key, - settings: Key, + settings: Key, } impl CommandRulesPlugin { fn new(names: &Names<'_>) -> Result { @@ -97,8 +97,7 @@ impl DynPlugin for CommandRulesPlugin { } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - let settings = ctx.require_at(&self.settings)?; - let rules = Arc::new(CommandRules(Arc::new(SettingsRules(settings)))); + let rules = Arc::new(CommandRules(Arc::new(SettingsRules(ctx.clone())))); ctx.provide_at(self.host.clone(), rules.clone())?; ctx.provide_at( self.face.clone(), @@ -138,7 +137,7 @@ fn error(error: SettingsError) -> RpcError { /// Process owner of the `permission` source and its management methods. pub struct PermissionRulesPlugin { - settings: Key, + settings: Key, methods: Key, } impl PermissionRulesPlugin { @@ -160,7 +159,8 @@ impl DynPlugin for PermissionRulesPlugin { Box::pin(async move { let settings = ctx.require_at(&self.settings)?; let methods = ctx.require_at(&self.methods)?; - settings.register::(ctx)?; + let settings = settings.register_document::(ctx)?; + ctx.provide_as::>(settings.clone())?; methods.register( ctx, "permission", @@ -182,7 +182,7 @@ impl DynPlugin for PermissionRulesPlugin { "permission.rules" => { let _: Empty = params(value)?; let snapshot = settings - .read::(SettingsScope::User, &stopping) + .read(SettingsScope::User, &stopping) .await .map_err(error)?; reply(RulesView { diff --git a/crates/dim-app-server/src/settings.rs b/crates/dim-app-server/src/settings.rs index b34fcc233f..7ade454dc1 100644 --- a/crates/dim-app-server/src/settings.rs +++ b/crates/dim-app-server/src/settings.rs @@ -2,6 +2,7 @@ //! `BusinessDocument` sources and JSON Schema sources, each registered by //! the plugin that owns it (settings-service design). mod declared; +mod document; mod native; pub mod workflow_files; pub use workflow_files::WorkflowFiles; @@ -9,7 +10,7 @@ pub(crate) use workflow_files::WorkflowPackages; use crate::storage::SqliteStorage; use dim_agent_capabilities::file_storage::{FilePath, FileStorage, FileStorageError}; -use dim_agent_runtime::{Names, Registrations}; +use dim_agent_runtime::{Names, Registration, Registrations}; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, ErrorKind, Key, TypeKey}; use rutis::{Ctx, Event}; use serde::{Deserialize, Serialize, de::DeserializeOwned}; @@ -19,7 +20,7 @@ use std::{ collections::BTreeMap, marker::PhantomData, path::{Path, PathBuf}, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, Weak}, }; use tokio_util::{sync::CancellationToken, task::TaskTracker}; @@ -147,10 +148,19 @@ pub struct SettingsSnapshot { /// How one source's documents cross the persistence boundary, so Rust and /// declared sources share the file and native paths, keyed by source name. trait Format: Send + Sync + 'static { - type Document: Serialize + Send + 'static; + type Document: Serialize + Send + Sync + 'static; fn source(&self) -> &str; /// Decodes and checks a persisted document; `None` is a missing file. - fn decode(&self, bytes: Option<&[u8]>) -> Result; + fn decode<'a>( + &'a self, + bytes: Option<&'a [u8]>, + cancel: &'a CancellationToken, + ) -> BoxFuture<'a, Result>; + fn validate<'a>( + &'a self, + document: &'a Self::Document, + cancel: &'a CancellationToken, + ) -> BoxFuture<'a, Result<()>>; } struct Typed(PhantomData D>); impl Format for Typed { @@ -158,13 +168,26 @@ impl Format for Typed { fn source(&self) -> &str { D::NAMESPACE } - fn decode(&self, bytes: Option<&[u8]>) -> Result { - let document: D = match bytes { - Some(bytes) => D::decode(bytes)?, - None => D::default(), - }; - document.validate()?; - Ok(document) + fn validate<'a>( + &'a self, + document: &'a D, + _: &'a CancellationToken, + ) -> BoxFuture<'a, Result<()>> { + Box::pin(async move { document.validate() }) + } + fn decode<'a>( + &'a self, + bytes: Option<&'a [u8]>, + _: &'a CancellationToken, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let document: D = match bytes { + Some(bytes) => D::decode(bytes)?, + None => D::default(), + }; + document.validate()?; + Ok(document) + }) } } fn typed() -> Arc> { @@ -181,9 +204,95 @@ struct Source { } enum Kind { Rust(TypeId), + Custom, Declared(Arc), } +type CompareDocument = Box Result<()> + Send>; + +enum WriteCheck { + Registered(Weak>), + Compare(CompareDocument), +} + +fn current_registration( + settings: &SettingsService, + name: &str, + registration: &Weak>, +) -> Result>> { + settings + .sources + .get(name) + .filter(|entry| registration.ptr_eq(&Arc::downgrade(entry))) + .ok_or(SettingsError::UnknownSource) +} + +/// A custom source registered by one plugin generation. +pub struct RegisteredDocument { + settings: Arc, + registration: Weak>, + format: Arc>, +} + +impl RegisteredDocument { + fn register( + settings: Arc, + owner: &Ctx, + format: Arc>, + user_file: &str, + project_file: Option<&str>, + kind: Kind, + ) -> rutis::Result> { + let registration = + settings.register_source(owner, format.source(), user_file, project_file, kind)?; + Ok(Arc::new(Self { + settings, + registration: Arc::downgrade(®istration), + format, + })) + } + + fn path(&self, scope: SettingsScope) -> Result { + let entry = current_registration(&self.settings, self.format.source(), &self.registration)?; + self.settings.locate( + &entry.value.user_file, + entry.value.project_file.as_deref(), + scope, + ) + } + pub async fn read( + &self, + scope: SettingsScope, + cancel: &CancellationToken, + ) -> Result> { + self.settings.check_open(cancel)?; + self.settings + .read_source(self.format.clone(), self.path(scope)?, scope, cancel) + .await + } + pub async fn update( + &self, + scope: SettingsScope, + expected: &str, + document: D, + cancel: &CancellationToken, + ) -> Result> { + self.format.validate(&document, cancel).await?; + self.settings.check_open(cancel)?; + self.settings + .replace( + self.format.clone(), + self.path(scope)?, + scope, + expected, + document, + WriteCheck::Registered(self.registration.clone()), + cancel, + ) + .await + } +} + pub struct SettingsService { files: Arc, database: Option>, @@ -205,20 +314,38 @@ impl SettingsService { /// Registers the Rust source `D` for as long as the plugin that owns /// `ctx` is loaded. A source name or file registered already fails. pub fn register(&self, ctx: &Ctx) -> rutis::Result<()> { - let failed = |error: SettingsError| registration_failed(D::NAMESPACE, error.to_string()); - validate_namespace(D::NAMESPACE).map_err(failed)?; - validate_file(D::USER_FILE).map_err(failed)?; - if let Some(file) = D::PROJECT_FILE { + self.register_source( + ctx, + D::NAMESPACE, + D::USER_FILE, + D::PROJECT_FILE, + Kind::Rust(TypeId::of::()), + ) + .map(drop) + } + + fn register_source( + &self, + ctx: &Ctx, + name: &str, + user_file: &str, + project_file: Option<&str>, + kind: Kind, + ) -> rutis::Result>> { + let failed = |error: SettingsError| registration_failed(name, error.to_string()); + validate_namespace(name).map_err(failed)?; + validate_file(user_file).map_err(failed)?; + if let Some(file) = project_file { validate_file(file).map_err(failed)?; } self.insert( ctx, - D::NAMESPACE, + name, Source { owner: ctx.instance().to_string(), - user_file: D::USER_FILE.into(), - project_file: D::PROJECT_FILE.map(Into::into), - kind: Kind::Rust(TypeId::of::()), + user_file: user_file.into(), + project_file: project_file.map(Into::into), + kind, }, ) } @@ -244,6 +371,7 @@ impl SettingsService { kind: Kind::Declared(Arc::new(declared)), }, ) + .map(drop) } /// The declarations of every registered JSON Schema source, by source /// name, for the client's `settings.sources` listing. @@ -253,12 +381,17 @@ impl SettingsService { .iter() .filter_map(|registered| match ®istered.value.kind { Kind::Declared(declared) => Some(declared.declaration().clone()), - Kind::Rust(_) => None, + Kind::Rust(_) | Kind::Custom => None, }) .collect() } /// Two sources sharing a name or a file would share a persisted document. - fn insert(&self, ctx: &Ctx, name: &str, source: Source) -> rutis::Result<()> { + fn insert( + &self, + ctx: &Ctx, + name: &str, + source: Source, + ) -> rutis::Result>> { let _guard = self.registering.lock().unwrap(); let taken = self.sources.get(name).is_some() || self.sources.all().iter().any(|other| { @@ -272,8 +405,7 @@ impl SettingsService { "its name or file is registered already".into(), )); } - self.sources.register(ctx, name, source)?; - Ok(()) + self.sources.register(ctx, name, source) } pub async fn authorize_project( self: &Arc, @@ -404,12 +536,12 @@ impl SettingsService { scope, expected, document, - |_, _| Ok(()), + WriteCheck::Compare(Box::new(|_, _| Ok(()))), cancel, ) .await } - async fn read_source( + async fn read_source( &self, format: Arc, path: FilePath, @@ -422,7 +554,7 @@ impl SettingsService { .await .map(|(_, snapshot)| snapshot); } - snapshot(&*format, self.files.read(&path, cancel).await) + snapshot(&*format, self.files.read(&path, cancel).await, cancel).await } /// CAS on the revision. `check` sees the current and the new document /// under the file lease or at the expected native revision. @@ -430,14 +562,14 @@ impl SettingsService { clippy::too_many_arguments, reason = "one parameter per part of the compare-and-set write" )] - async fn replace( + async fn replace( self: &Arc, format: Arc, path: FilePath, scope: SettingsScope, expected: &str, document: F::Document, - check: impl FnOnce(&F::Document, &F::Document) -> Result<()> + Send + 'static, + check: WriteCheck, cancel: &CancellationToken, ) -> Result> { let task = { @@ -453,11 +585,25 @@ impl SettingsService { .await; } let mut lease = owner.lease(&path, &cancel).await?; - let current = snapshot(&*format, lease.read(&cancel).await)?; - if current.revision != expected { - return Err(SettingsError::Conflict); + let stored = stored_bytes(lease.read(&cancel).await)?; + match check { + WriteCheck::Registered(registration) => { + let source = current_registration(&owner, format.source(), ®istration)?; + if matches!(source.value.kind, Kind::Rust(_)) { + format.decode(stored.as_deref(), &cancel).await?; + } + if revision(stored.as_deref()) != expected { + return Err(SettingsError::Conflict); + } + } + WriteCheck::Compare(compare) => { + let current = format.decode(stored.as_deref(), &cancel).await?; + if revision(stored.as_deref()) != expected { + return Err(SettingsError::Conflict); + } + compare(¤t, &document)?; + } } - check(¤t.document, &document)?; let mut bytes = serde_json::to_vec_pretty(&document) .map_err(|_| SettingsError::Invalid("cannot encode settings"))?; bytes.push(b'\n'); @@ -538,17 +684,23 @@ fn revision(bytes: Option<&[u8]>) -> String { |bytes| format!("{:x}", Sha256::digest(bytes)), ) } -fn snapshot( +fn stored_bytes(read: std::result::Result, FileStorageError>) -> Result>> { + match read { + Ok(bytes) => Ok(Some(bytes)), + Err(FileStorageError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => { + Ok(None) + } + Err(error) => Err(error.into()), + } +} +async fn snapshot( format: &F, read: std::result::Result, FileStorageError>, + cancel: &CancellationToken, ) -> Result> { - let bytes = match read { - Ok(bytes) => Some(bytes), - Err(FileStorageError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => None, - Err(error) => return Err(error.into()), - }; + let bytes = stored_bytes(read)?; Ok(SettingsSnapshot { - document: format.decode(bytes.as_deref())?, + document: format.decode(bytes.as_deref(), cancel).await?, revision: revision(bytes.as_deref()), }) } diff --git a/crates/dim-app-server/src/settings/declared.rs b/crates/dim-app-server/src/settings/declared.rs index 96cdec4b7e..92c08e9f2a 100644 --- a/crates/dim-app-server/src/settings/declared.rs +++ b/crates/dim-app-server/src/settings/declared.rs @@ -100,14 +100,31 @@ impl Format for Declared { fn source(&self) -> &str { &self.declaration.source } - fn decode(&self, bytes: Option<&[u8]>) -> Result { - let document = match bytes { - Some(bytes) => serde_json::from_slice(bytes) - .map_err(|_| SettingsError::Invalid("invalid settings document"))?, - None => json!({}), - }; - self.prepare(document).map_err(|_| { - SettingsError::Invalid("persisted settings document does not match its schema") + fn validate<'a>( + &'a self, + document: &'a Value, + _: &'a CancellationToken, + ) -> BoxFuture<'a, Result<()>> { + Box::pin(async move { + self.prepare(document.clone()) + .map(drop) + .map_err(SettingsError::Document) + }) + } + fn decode<'a>( + &'a self, + bytes: Option<&'a [u8]>, + _: &'a CancellationToken, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let document = match bytes { + Some(bytes) => serde_json::from_slice(bytes) + .map_err(|_| SettingsError::Invalid("invalid settings document"))?, + None => json!({}), + }; + self.prepare(document).map_err(|_| { + SettingsError::Invalid("persisted settings document does not match its schema") + }) }) } } @@ -187,7 +204,7 @@ impl SettingsService { .get(source) .and_then(|registered| match ®istered.value.kind { Kind::Declared(declared) => Some(declared.clone()), - Kind::Rust(_) => None, + Kind::Rust(_) | Kind::Custom => None, }) .ok_or(SettingsError::UnknownSource)?; if let SettingsScope::Project(root) = scope { @@ -239,10 +256,10 @@ impl SettingsService { scope, expected, document, - move |current, next| match writer { + WriteCheck::Compare(Box::new(move |current, next| match writer { Writer::Client => Ok(()), Writer::Owner => rules.user_only(current, next), - }, + })), cancel, ) .await @@ -268,6 +285,11 @@ pub(crate) struct Update { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Projects {} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthorizeProject { + cwd: PathBuf, +} #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -296,7 +318,7 @@ impl SettingsError { } } /// `{ok: true, value}` or `{ok: false, error: {code, message}}`, as `sessions`. -fn envelope(result: Result) -> RpcValue { +pub(super) fn envelope(result: Result) -> RpcValue { match result { Ok(value) => json!({"ok": true, "value": value}), Err(error) => { @@ -314,11 +336,25 @@ fn request(args: RpcValue) -> std::result::Result serde_json::from_value(request).map_err(|_| invalid()) } -/// The owner path: `settings` by name for every language (§4.2). Only -/// `register` uses the caller's identity, to withdraw its sources when the -/// calling row unloads; each source has one owner (AGENTS.md rule 11). +/// The owner path: `settings` by name for every language (§4.2). Source registrations +/// belong to the calling row and expire when it unloads. pub struct Settings(Arc); impl Settings { + /// Registers a source with its existing decoder, defaults and write validation. + pub fn register_document( + &self, + owner: &Ctx, + ) -> rutis::Result>> { + RegisteredDocument::register( + self.0.clone(), + owner, + typed::(), + D::USER_FILE, + D::PROJECT_FILE, + Kind::Rust(TypeId::of::()), + ) + } + /// The declarations of the JSON Schema sources the row `instance_id` /// registered and still holds, by source name. pub fn declared_by(&self, instance_id: &str) -> Vec { @@ -329,7 +365,7 @@ impl Settings { .filter(|registered| registered.value.owner == instance_id) .filter_map(|registered| match ®istered.value.kind { Kind::Declared(declared) => Some(declared.declaration().clone()), - Kind::Rust(_) => None, + Kind::Rust(_) | Kind::Custom => None, }) .collect() } @@ -362,6 +398,15 @@ impl Settings { .await } + /// Admits a project root and publishes its existing authorization notice. + pub async fn authorize_project( + &self, + cwd: PathBuf, + cancel: &CancellationToken, + ) -> Result { + self.0.authorize_project(cwd, cancel).await + } + /// Lists authorized project scopes. pub fn projects(&self) -> Vec { self.0 @@ -378,14 +423,14 @@ impl Settings { impl HostDispatch for Settings { fn methods(&self) -> Option { Some( - json!({"register": "async", "read": "async", "update": "async", "projects": "sync", "declaredBy": "sync"}), + json!({"registerDocument": "async", "register": "async", "read": "async", "update": "async", "projects": "sync", "authorizeProject": "async", "declaredBy": "sync"}), ) } fn invoke(&self, method: &str, args: RpcValue) -> Reply { let service = Self(self.0.clone()); let cancel = CancellationToken::new(); match method { - "register" => { + "register" | "registerDocument" => { let caller = rutis_bridge::session::caller_row() .map(|row| row.ctx().clone()) .ok_or_else(|| { @@ -393,6 +438,10 @@ impl HostDispatch for Settings { "register needs the calling row's context: only a row of a language runtime can call it", ) })?; + if method == "registerDocument" { + let result = super::document::register(service.0, &caller, args); + return Ok(RpcValue::future(async move { result })); + } let registered = request(args).and_then(|declaration| { service .register(&caller, declaration) @@ -405,6 +454,13 @@ impl HostDispatch for Settings { let DeclaredBy { instance_id } = request(args)?; Ok(json!(service.declared_by(&instance_id)).into()) } + "authorizeProject" => { + let AuthorizeProject { cwd } = request(args)?; + Ok(RpcValue::future(async move { + let _guard = cancel.clone().drop_guard(); + Ok(envelope(service.authorize_project(cwd, &cancel).await)) + })) + } "projects" => { let Projects {} = request(args)?; let projects = service.projects(); diff --git a/crates/dim-app-server/src/settings/document.rs b/crates/dim-app-server/src/settings/document.rs new file mode 100644 index 0000000000..f0c10ed0f9 --- /dev/null +++ b/crates/dim-app-server/src/settings/document.rs @@ -0,0 +1,133 @@ +use super::*; +use rutis_bridge::session::{Error, Reference, Reply, Value, settle}; +use serde_json::Value as Json; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Declaration { + source: String, + user_file: String, + project_file: Option, +} + +struct Codec { + name: String, + methods: Reference, + owner: CancellationToken, + service: CancellationToken, +} + +impl Codec { + async fn call( + &self, + method: &str, + argument: Value, + cancel: &CancellationToken, + ) -> Result { + let invoke = async { + let args = Value::List(vec![argument]); + settle(self.methods.call_method_async(method, args).await?).await + }; + tokio::select! { + biased; + _ = self.owner.cancelled() => Err(SettingsError::UnknownSource), + _ = self.service.cancelled() => Err(SettingsError::Closed), + _ = cancel.cancelled() => Err(SettingsError::Cancelled), + result = invoke => + result.map_err(|error| SettingsError::Document(error.to_string())), + } + } +} + +impl Format for Codec { + type Document = Json; + fn source(&self) -> &str { + &self.name + } + fn decode<'a>( + &'a self, + bytes: Option<&'a [u8]>, + cancel: &'a CancellationToken, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let input = bytes.map_or(Value::Data(Json::Null), |bytes| { + Value::Bytes(bytes.to_vec()) + }); + self.call("decode", input, cancel) + .await? + .json() + .map_err(|error| SettingsError::Document(error.to_string())) + }) + } + fn validate<'a>( + &'a self, + document: &'a Json, + cancel: &'a CancellationToken, + ) -> BoxFuture<'a, Result<()>> { + Box::pin(async move { + self.call("validate", document.clone().into(), cancel) + .await + .map(drop) + }) + } +} + +pub(super) fn register(settings: Arc, caller: &Ctx, args: Value) -> Reply { + let invalid = || { + Error::value( + "expected a settings source declaration and a codec with decode and validate functions", + ) + }; + let [declaration, Value::Reference(methods)]: [Value; 2] = + args.list()?.try_into().map_err(|_| invalid())? + else { + return Err(invalid()); + }; + let declaration: Declaration = + serde_json::from_value(declaration.json()?).map_err(|_| invalid())?; + if !methods.is_object() { + return Err(invalid()); + } + let format = Codec { + name: declaration.source.clone(), + methods, + owner: caller.cancellation_token(), + service: settings.stopping.clone(), + }; + let source = RegisteredDocument::register( + settings, + caller, + Arc::new(format), + &declaration.user_file, + declaration.project_file.as_deref(), + Kind::Custom, + ) + .map_err(|error| Error::value(error.to_string()))?; + let read = source.clone(); + let read = Value::callback(move |args| { + let (scope,): (SettingsScope,) = serde_json::from_value(args.json()?) + .map_err(|_| Error::value("expected a settings scope"))?; + let read = read.clone(); + Ok(Value::future(async move { + let cancel = CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + Ok(declared::envelope(read.read(scope, &cancel).await)) + })) + }); + let update = Value::callback(move |args| { + let (scope, revision, document): (SettingsScope, String, Json) = + serde_json::from_value(args.json()?) + .map_err(|_| Error::value("expected scope, expectedRevision and document"))?; + let source = source.clone(); + Ok(Value::future(async move { + let cancel = CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + Ok(declared::envelope( + source.update(scope, &revision, document, &cancel).await, + )) + })) + }); + Ok(Value::Record( + [("read".into(), read), ("update".into(), update)].into(), + )) +} diff --git a/crates/dim-app-server/src/settings/native.rs b/crates/dim-app-server/src/settings/native.rs index 1c268fc165..2a0250dea2 100644 --- a/crates/dim-app-server/src/settings/native.rs +++ b/crates/dim-app-server/src/settings/native.rs @@ -14,9 +14,10 @@ fn write_error(error: dim_agent_runtime::AgentError) -> SettingsError { } } -fn decode( +async fn decode( format: &F, row: UserDocument, + cancel: &CancellationToken, ) -> Result<(i64, SettingsSnapshot)> { if row.version <= 0 { return Err(SettingsError::Invalid( @@ -26,13 +27,13 @@ fn decode( Ok(( row.version, SettingsSnapshot { - document: format.decode(Some(row.document.as_bytes()))?, + document: format.decode(Some(row.document.as_bytes()), cancel).await?, revision: token(format.source(), row.version), }, )) } impl SettingsService { - pub(super) async fn native_read( + pub(super) async fn native_read( &self, format: Arc, path: FilePath, @@ -55,9 +56,10 @@ impl SettingsService { .await .map_err(|_| SettingsError::Persistence)? { - return decode(&*format, row); + return decode(&*format, row, &cancel).await; } - let imported = snapshot(&*format, files.read(&path, &cancel).await)?; + let imported = + snapshot(&*format, files.read(&path, &cancel).await, &cancel).await?; let body = serde_json::to_string(&imported.document) .map_err(|_| SettingsError::Invalid("cannot encode settings"))?; let row = db @@ -67,23 +69,23 @@ impl SettingsService { document: body, imported_revision: imported.revision, }, - cancel, + cancel.clone(), stopping, ) .await .map_err(write_error)?; - decode(&*format, row) + decode(&*format, row, &cancel).await }) }; task.await? } - pub(super) async fn native_replace( + pub(super) async fn native_replace( self: &Arc, format: Arc, path: FilePath, expected: String, document: F::Document, - check: impl FnOnce(&F::Document, &F::Document) -> Result<()> + Send + 'static, + check: WriteCheck, cancel: &CancellationToken, ) -> Result> { let (version, current) = self.native_read(format.clone(), path, cancel).await?; @@ -92,7 +94,13 @@ impl SettingsService { if current.revision != expected { return Err(SettingsError::Conflict); } - let decision = match check(¤t.document, &document) { + let checked = match check { + WriteCheck::Registered(registration) => { + current_registration(self, format.source(), ®istration).map(|_| ()) + } + WriteCheck::Compare(compare) => compare(¤t.document, &document), + }; + let decision = match checked { Ok(()) => UserDecision::Write { document: serde_json::to_string(&document) .map_err(|_| SettingsError::Invalid("cannot encode settings"))?, diff --git a/crates/dim-app-server/src/settings_methods.rs b/crates/dim-app-server/src/settings_methods.rs index 8cd1fdd3b2..db589319c2 100644 --- a/crates/dim-app-server/src/settings_methods.rs +++ b/crates/dim-app-server/src/settings_methods.rs @@ -121,7 +121,7 @@ pub struct SettingsMethodsPlugin { impl SettingsMethodsPlugin { pub fn new(names: &Names<'_>) -> rutis::Result { Ok(Self { - service: names.key()?, + service: Key::of(), methods: names.key()?, }) } diff --git a/crates/dim-app-server/src/skills_management.rs b/crates/dim-app-server/src/skills_management.rs index 30cde4c5b5..533047430f 100644 --- a/crates/dim-app-server/src/skills_management.rs +++ b/crates/dim-app-server/src/skills_management.rs @@ -7,7 +7,7 @@ use crate::{ acquire::{self, Staging}, }, protocol::{canonical_cwd, optional_non_null}, - settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}, + settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope}, }; use dim_agent_capabilities::methods::{ Interruption, MethodCall, MethodDecl, RpcError, params, reply, @@ -107,7 +107,7 @@ impl BusinessDocument for SkillDocument { /// Adapts the owner's business document to the reusable Skill catalog port. /// Settings announces its writes; the catalog listens to them itself. struct SkillStorage { - settings: Arc, + settings: Arc>, } impl SkillSettings for SkillStorage { fn skills( @@ -115,10 +115,7 @@ impl SkillSettings for SkillStorage { cancel: CancellationToken, ) -> BoxFuture<'_, Result> { Box::pin(async move { - let snapshot = self - .settings - .read::(SettingsScope::User, &cancel) - .await?; + let snapshot = self.settings.read(SettingsScope::User, &cancel).await?; Ok(SkillSettingsSnapshot { version: snapshot.revision, disabled: snapshot.document.disabled_skill_ids.into_iter().collect(), @@ -138,10 +135,7 @@ impl SkillSettings for SkillStorage { if id.trim().is_empty() { return Err(SkillSettingsError::Invalid("empty Skill id".into())); } - let current = self - .settings - .read::(SettingsScope::User, &cancel) - .await?; + let current = self.settings.read(SettingsScope::User, &cancel).await?; if current.revision != expected { return Err(SkillSettingsError::Conflict); } @@ -188,10 +182,7 @@ impl SkillStorage { cancel: CancellationToken, ) -> Result { loop { - let current = self - .settings - .read::(SettingsScope::User, &cancel) - .await?; + let current = self.settings.read(SettingsScope::User, &cancel).await?; let mut document = current.document; let unchanged = match &root { Some(root) => document.plugin_skills.get(&plugin) == Some(root), @@ -223,10 +214,7 @@ impl SkillStorage { cancel: CancellationToken, ) -> Result { loop { - let current = self - .settings - .read::(SettingsScope::User, &cancel) - .await?; + let current = self.settings.read(SettingsScope::User, &cancel).await?; let mut document = current.document; let unchanged = match &installation { Some(installation) => document.installations.get(&id) == Some(installation), @@ -597,7 +585,7 @@ fn recorded(source: &SkillInstallSource) -> SourceParams { pub struct SkillsCatalogPlugin { platform: Key, - settings: Key, + settings: Key, methods: Key, parts: Key, } @@ -631,7 +619,7 @@ impl DynPlugin for SkillsCatalogPlugin { let parts = ctx.require_at(&self.parts)?; let home = platform.home.clone(); clean_staging(&home); - settings.register::(ctx)?; + let settings = settings.register_document::(ctx)?; let settings = Arc::new(SkillSettingsHost(Arc::new(SkillStorage { settings }))); let catalog = dim_agent_capabilities::skills::SkillsCatalogPlugin::mount( ctx, diff --git a/crates/dim-app-server/tests/hooks_settings_flow.rs b/crates/dim-app-server/tests/hooks_settings_flow.rs index c716e69d6b..0df3574193 100644 --- a/crates/dim-app-server/tests/hooks_settings_flow.rs +++ b/crates/dim-app-server/tests/hooks_settings_flow.rs @@ -159,6 +159,19 @@ async fn catalog_reports_sources_states_and_never_reads_foreign_hook_files() { ) .await .unwrap(); + let service = fixture.root.get::().unwrap(); + let native = service + .sources(&fixture.project, fixture.cancel.clone()) + .await + .unwrap(); + let wire = fixture + .face("sources", json!({"cwd":fixture.project})) + .await + .unwrap(); + assert_eq!(wire, serde_json::to_value(native).unwrap()); + assert_eq!(wire["sources"][1]["state"], "ok"); + assert_eq!(wire["sources"][1]["enabled"], false); + assert!(wire["sources"][1]["document"]["hooks"]["Stop"].is_array()); assert_eq!(catalog["sources"][1]["state"], "ok"); assert_eq!(catalog["sources"][1]["enabled"], false); let hooks = catalog["hooks"].as_array().unwrap(); diff --git a/crates/dim-app-server/tests/mcp_flow.rs b/crates/dim-app-server/tests/mcp_flow.rs index 55ba7f09c1..7dddf0a583 100644 --- a/crates/dim-app-server/tests/mcp_flow.rs +++ b/crates/dim-app-server/tests/mcp_flow.rs @@ -40,7 +40,7 @@ impl Capture { Ok(Self { services, mcp: dim_app_server::mcp::owner_key(), - settings: names.key()?, + settings: Key::of(), files: names.key()?, }) } diff --git a/crates/dim-app-server/tests/settings_flow.rs b/crates/dim-app-server/tests/settings_flow.rs index 897d1402e7..1d826582d8 100644 --- a/crates/dim-app-server/tests/settings_flow.rs +++ b/crates/dim-app-server/tests/settings_flow.rs @@ -48,11 +48,9 @@ fn owner( name: &'static str, register: impl Fn(&SettingsService, &Ctx) -> rutis::Result<()> + Send + Sync + 'static, ) -> Owner { - let catalog = dim_app_server::catalog(); - let build = Build::default(); Owner { name, - settings: Names::copy(&catalog, &build).key().unwrap(), + settings: Key::of(), register: Arc::new(register), } } @@ -82,14 +80,6 @@ struct ProcessSettings { capture: Captured, settings: Key, } -impl ProcessSettings { - fn new(names: &Names<'_>, capture: Captured) -> rutis::Result { - Ok(Self { - capture, - settings: names.key()?, - }) - } -} impl DynPlugin for ProcessSettings { fn name(&self) -> &str { "test.process-settings" @@ -181,11 +171,15 @@ async fn server_reload_preserves_project_root_identity_and_settings() { let mut builder = AgentBuilder::new(AgentConfig::default()); defaults::mock_hosts(&mut builder); defaults::install(&mut builder); - builder.require_feature( - Feature::new("test.process-settings").session("test.process-settings", move |names| { - Ok(Box::new(ProcessSettings::new(names, capture.clone())?)) - }), - ); + builder.require_feature(Feature::new("test.process-settings").session( + "test.process-settings", + move |_| { + Ok(Box::new(ProcessSettings { + capture: capture.clone(), + settings: Key::of(), + })) + }, + )); let server = serve( builder, ServerConfig { @@ -800,8 +794,12 @@ async fn sources_appear_while_registered_and_names_are_exclusive() { owner_call(&dispatch, "read", read.clone()).await["error"]["code"], "unknown_source" ); - let source = root.plugin(owner("test.owner", |settings, ctx| { - settings.register::(ctx)?; + let first = Arc::new(std::sync::OnceLock::new()); + let registered = first.clone(); + let public = root.get::().unwrap(); + let source = root.plugin(owner("test.owner", move |settings, ctx| { + let doc = public.register_document::(ctx)?; + assert!(registered.set(doc).is_ok()); settings.register_declared(ctx, declaration("declared")) })); wait_active( @@ -873,6 +871,26 @@ async fn sources_appear_while_registered_and_names_are_exclusive() { .await .is_err() ); + let files = root.get::().unwrap(); + let mut notices = listen::(&root, &settings_changes("example")); + let held = files + .lock(&files.path(0, "example.json").unwrap(), &cancel) + .await + .unwrap(); + let pending = first.get().unwrap().update( + SettingsScope::User, + &saved.revision, + Document { + value: "obsolete".into(), + }, + &cancel, + ); + tokio::pin!(pending); + assert!( + tokio::time::timeout(Duration::from_millis(75), &mut pending) + .await + .is_err() + ); source.dispose().await.unwrap(); assert!(matches!( settings @@ -885,7 +903,25 @@ async fn sources_appear_while_registered_and_names_are_exclusive() { "unknown_source" ); assert!(home.join("example.json").exists()); - settings.register::(&root).unwrap(); + let next = root + .get::() + .unwrap() + .register_document::(&root) + .unwrap(); + drop(held); + assert!(matches!(pending.await, Err(SettingsError::UnknownSource))); + assert!(matches!( + first + .get() + .unwrap() + .read(SettingsScope::User, &cancel) + .await, + Err(SettingsError::UnknownSource) + )); + assert_eq!( + next.read(SettingsScope::User, &cancel).await.unwrap(), + saved + ); assert_eq!( settings .read::(SettingsScope::User, &cancel) @@ -893,6 +929,28 @@ async fn sources_appear_while_registered_and_names_are_exclusive() { .unwrap(), saved ); + let committed = next + .update( + SettingsScope::User, + &saved.revision, + Document { + value: "current".into(), + }, + &cancel, + ) + .await + .unwrap(); + saw( + &mut notices, + change(SettingsScope::User, &committed.revision), + ) + .await; + assert!( + notices + .borrow() + .iter() + .all(|event| event.revision == saved.revision || event.revision == committed.revision) + ); root.shutdown().await.unwrap(); fs::remove_dir_all(home).unwrap(); } diff --git a/crates/dim-app-server/tests/transport_flow/collaboration.rs b/crates/dim-app-server/tests/transport_flow/collaboration.rs index 4d7ba3c392..d9baad853d 100644 --- a/crates/dim-app-server/tests/transport_flow/collaboration.rs +++ b/crates/dim-app-server/tests/transport_flow/collaboration.rs @@ -542,6 +542,7 @@ async fn launch_held_team( } struct CaptureMemberConfig { + context: Arc>, configs: Arc>>>, config: rutis::host::Key, @@ -550,9 +551,11 @@ impl CaptureMemberConfig { fn new( names: &dim_agent_runtime::Names<'_>, configs: Arc>>>, + context: Arc>, ) -> rutis::Result { Ok(Self { configs, + context, config: names.key()?, }) } @@ -570,6 +573,7 @@ impl rutis::host::DynPlugin for CaptureMemberConfig { ) -> rutis::host::BoxFuture<'a, rutis::Result> { Box::pin(async move { let config = ctx.require_at(&self.config)?; + self.context.get_or_init(|| ctx.clone()); self.configs.lock().unwrap().push(config); Ok(rutis::host::Effect::Done) }) @@ -583,6 +587,8 @@ async fn product_collaboration_adopts_profile_and_default_capabilities() { std::fs::create_dir_all(&home).unwrap(); let configs = Arc::new(std::sync::Mutex::new(Vec::new())); let observed = configs.clone(); + let context = Arc::new(std::sync::OnceLock::new()); + let captured = context.clone(); let (server, agent) = launch_with(Arc::new(MockTools), ServerConfig { product_home: Some(home.clone()), target_home: Some(home.join("rust")), @@ -590,7 +596,10 @@ async fn product_collaboration_adopts_profile_and_default_capabilities() { }, move |builder| { builder.require_feature(Feature::new("capture-member-config").session( "capture-member-config", - move |names| Ok(Box::new(CaptureMemberConfig::new(names, observed.clone())?)), + move |names| { + let part = CaptureMemberConfig::new(names, observed.clone(), captured.clone())?; + Ok(Box::new(part)) + }, )); }).await; let mut client = Client::new_version(&server, false, 4).await; @@ -627,6 +636,12 @@ async fn product_collaboration_adopts_profile_and_default_capabilities() { let mut remote = Client::new_version(&server, true, 4).await; assert_eq!(remote.rpc("collaboration.model_policy", json!({})).await["error"]["data"]["appError"], "local_transport_required"); let read = client.rpc("collaboration.model_policy", json!({})).await; + let policy = context.get().unwrap().get_at::( + &rutis_bridge::session::host_key("collaborationModelPolicy"), + ).unwrap(); + let wire = policy.invoke("read", json!([{}]).into()).unwrap(); + let wire = rutis_bridge::session::settle(wire).await.unwrap().json().unwrap(); + assert_eq!(wire, read["result"]); assert_eq!(read["result"]["policy"], json!({"mode":"agent"})); let initial = read["result"]["revision"].as_str().unwrap().to_owned(); for invalid in [ diff --git a/crates/dim-app-server/tests/transport_flow/plugin_manager.rs b/crates/dim-app-server/tests/transport_flow/plugin_manager.rs index 57004d95ef..95bb0ce6e7 100644 --- a/crates/dim-app-server/tests/transport_flow/plugin_manager.rs +++ b/crates/dim-app-server/tests/transport_flow/plugin_manager.rs @@ -3089,9 +3089,9 @@ async fn plugin_content_follows_the_record_over_restarts() { /// The product's local execution profile with mock model hosts, with Hooks /// installed: a Session mounts the Hooks parts and reads its hook sources. -fn hooks_builder(home: &Path) -> AgentBuilder { +fn hooks_builder() -> AgentBuilder { let mut builder = product_builder(); - dim_app_server::hooks_settings::install(&mut builder, Some(home.to_owned())); + dim_app_server::hooks_settings::install(&mut builder); dim_agent_capabilities::hooks::install(&mut builder); builder } @@ -3185,7 +3185,7 @@ async fn plugin_hooks_run_with_their_plugin_root_and_follow_the_record() { .to_string(), ) .unwrap(); - let server = serve(hooks_builder(&home), config.clone()).await.unwrap(); + let server = serve(hooks_builder(), config.clone()).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; select_fixture_model(&mut client).await; @@ -3261,7 +3261,7 @@ async fn plugin_hooks_run_with_their_plugin_root_and_follow_the_record() { // The registration is kept in `hooks-plugins`, so a new process restores // it without being told again. - let server = serve(hooks_builder(&home), config).await.unwrap(); + let server = serve(hooks_builder(), config).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; when_served(&mut client, "plugin.list", json!({})).await; let session = session_in(&mut client, &work).await; @@ -3334,7 +3334,7 @@ async fn a_refused_plugin_hook_document_stops_only_its_own_kind() { let source = home.join("src/kit"); write_hook_plugin(&source, "kit", &runs, "kit"); std::fs::write(source.join("hooks.json"), json!({"hooks": []}).to_string()).unwrap(); - let server = serve(hooks_builder(&home), config.clone()).await.unwrap(); + let server = serve(hooks_builder(), config.clone()).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; select_fixture_model(&mut client).await; @@ -3370,7 +3370,7 @@ async fn a_refused_plugin_hook_document_stops_only_its_own_kind() { // Startup registers every plugin in use again, so a refused document is // reported again after a restart. - let server = serve(hooks_builder(&home), config).await.unwrap(); + let server = serve(hooks_builder(), config).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; let list = call(&mut client, "plugin.list", json!({})).await; assert_eq!(item(&list, "kit")["refused"][0]["kind"], "hooks", "{list}"); @@ -3407,7 +3407,7 @@ async fn a_plugin_hooks_document_that_cannot_be_read_stays_refused() { let work = home.join("work"); std::fs::create_dir_all(&work).unwrap(); let runs = home.join("hook-runs"); - let server = serve(hooks_builder(&home), config.clone()).await.unwrap(); + let server = serve(hooks_builder(), config.clone()).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; select_fixture_model(&mut client).await; @@ -3465,7 +3465,7 @@ async fn a_plugin_hooks_document_that_cannot_be_read_stays_refused() { // Startup registers every plugin in use again, so the refusal and the // plugin's other content survive a restart. - let server = serve(hooks_builder(&home), config).await.unwrap(); + let server = serve(hooks_builder(), config).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; let list = call(&mut client, "plugin.list", json!({})).await; assert_eq!(item(&list, "kit")["refused"][0]["kind"], "hooks", "{list}"); @@ -3510,7 +3510,7 @@ async fn plugin_hooks_follow_the_hooks_owner() { let runs = home.join("hook-runs"); let source = home.join("src/kit"); write_hook_plugin(&source, "kit", &runs, "kit"); - let server = serve(hooks_builder(&home), config).await.unwrap(); + let server = serve(hooks_builder(), config).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; select_fixture_model(&mut client).await; @@ -4761,7 +4761,7 @@ async fn a_failed_prompt_hook_proceeds_and_the_reply_names_it() { .to_string(), ) .unwrap(); - let server = serve(hooks_builder(&home), config).await.unwrap(); + let server = serve(hooks_builder(), config).await.unwrap(); let mut client = Client::new_version(&server, false, 3).await; select_fixture_model(&mut client).await; let cwd = home.join("work"); diff --git a/crates/dim-app-server/tests/transport_flow/settings_methods.rs b/crates/dim-app-server/tests/transport_flow/settings_methods.rs index 5e02c33647..4f11d8a297 100644 --- a/crates/dim-app-server/tests/transport_flow/settings_methods.rs +++ b/crates/dim-app-server/tests/transport_flow/settings_methods.rs @@ -6,7 +6,7 @@ use super::*; use dim_agent_runtime::Names; use dim_app_server::{ session_typescript::SessionTypeScriptConfig, - settings::{SettingsChanged, SettingsService, SourceDeclaration, settings_changes}, + settings::{Settings, SettingsChanged, SourceDeclaration, settings_changes}, }; use rutis::Ctx; use rutis::host::{BoxFuture, DynPlugin, Effect, Key, TypeKey}; @@ -100,7 +100,7 @@ fn configured_models() -> Arc { /// Registers a declared source with project scope, the way a C4 owner row does /// (§3.1): `settings.read`/`settings.update` need one to take `{project: root}`. -struct ProjectSource(Key); +struct ProjectSource(Key); impl ProjectSource { fn new(names: &Names<'_>) -> rutis::Result { Ok(Self(names.key()?)) @@ -115,7 +115,7 @@ impl DynPlugin for ProjectSource { } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { Box::pin(async move { - ctx.require_at(&self.0)?.register_declared( + ctx.require_at(&self.0)?.register( ctx, SourceDeclaration { source: "example".into(), @@ -225,6 +225,24 @@ async fn node_settings_typescript_owner_reads_and_writes() { let created = client.rpc("session.create", create(json!([]))).await; assert_ok(&created); let session = created["result"]["sessionId"].as_str().unwrap().to_owned(); + let custom = owner(&mut client, &session, "custom_read", json!({})).await; + assert_eq!(custom["value"]["document"], json!({"count":3}), "{custom}"); + let revision = &custom["value"]["revision"]; + let update = |count| json!({"expectedRevision":revision, "count":count}); + let rejected = owner(&mut client, &session, "custom_update", update(-1)).await; + assert_eq!(rejected["error"]["code"], "invalid_document", "{rejected}"); + let written = owner(&mut client, &session, "custom_update", update(6)).await; + assert_eq!( + written["value"]["document"], + json!({"count":6}), + "{written}" + ); + assert_eq!( + owner(&mut client, &session, "custom_read", json!({})).await, + written + ); + let stale = owner(&mut client, &session, "custom_update", update(5)).await; + assert_eq!(stale["error"]["code"], "conflict", "{stale}"); let user = json!({"source":"example","scope":"user"}); let mut changes = log.0.subscribe(); @@ -346,6 +364,30 @@ async fn node_settings_typescript_owner_reads_and_writes() { let mut other = create(json!([])); other["cwd"] = json!(project); assert_ok(&client.rpc("session.create", other).await); + let roots = client.rpc("settings.projects", json!({})).await; + let root = roots["result"]["projects"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["cwd"] == json!(project.canonicalize().unwrap())) + .unwrap()["root"] + .clone(); + let parallel = tokio::time::timeout( + Duration::from_secs(10), + owner( + &mut client, + &session, + "custom_concurrent", + json!({"root": root}), + ), + ) + .await + .expect("a suspended decoder must not block writers"); + assert_eq!(parallel["stale"]["error"]["code"], "conflict", "{parallel}"); + assert_eq!( + parallel["written"]["value"]["document"]["count"], 8, + "{parallel}" + ); let events = tokio::time::timeout(Duration::from_secs(5), async { loop { let events = owner(&mut client, &session, "events", json!({})).await; diff --git a/crates/dim-modality/src/engine.rs b/crates/dim-modality/src/engine.rs index 4aa75f4af7..9b97e0deeb 100644 --- a/crates/dim-modality/src/engine.rs +++ b/crates/dim-modality/src/engine.rs @@ -28,7 +28,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::FileScope; -use dim_app_server::settings::SettingsService; +use dim_app_server::settings::RegisteredDocument; use jiff::{SignedDuration, Timestamp}; use rutis::Ctx; use rutis::host::{CtxHost, Key}; @@ -467,7 +467,7 @@ pub struct TaskResultReply { pub(crate) struct Shared { pub(crate) files: Arc, fs: Arc, - pub(crate) settings: Arc, + pub(crate) settings: Arc>, pub(crate) selection: Arc, pub(crate) selectable: Arc, pub(crate) ctx: Ctx, @@ -493,7 +493,7 @@ impl Shared { pub(crate) fn new( files: Arc, fs: Arc, - settings: Arc, + settings: Arc>, selection: Arc, selectable: Arc, ctx: Ctx, diff --git a/crates/dim-modality/src/lib.rs b/crates/dim-modality/src/lib.rs index 6a4d0365fe..710e229933 100644 --- a/crates/dim-modality/src/lib.rs +++ b/crates/dim-modality/src/lib.rs @@ -51,7 +51,7 @@ use dim_agent_types::{ModalityModelSnapshot, ModelCapabilitySnapshot, ModelId}; use dim_app_server::{ methods::ManagementMethods, protocol::Empty, - settings::{BusinessDocument, SettingsError, SettingsScope, SettingsService}, + settings::{BusinessDocument, RegisteredDocument, Settings, SettingsError, SettingsScope}, }; pub use engine::{ ArtifactHook, Clock, DEFAULT_LIST_LIMIT, MAX_INLINE_BYTES, MAX_LIST_LIMIT, MAX_RESULT_BYTES, @@ -1045,7 +1045,7 @@ pub(crate) enum OcrLookup { } pub(crate) async fn evaluate( - settings: &SettingsService, + settings: &RegisteredDocument, selectable: &SelectableModelsHost, selection: &ModelSelectionHost, ctx: &Ctx, @@ -1054,7 +1054,7 @@ pub(crate) async fn evaluate( ocr: OcrLookup, ) -> Result<(String, Evaluation), RpcError> { let snapshot = settings - .read::(SettingsScope::User, cancel) + .read(SettingsScope::User, cancel) .await .map_err(settings_error)?; let selectable_models = selectable @@ -1195,7 +1195,7 @@ fn selection_refusal( /// Process owner of the `modality` Settings source and the `modality.*` /// management namespace (Modality §1, A.3). pub struct ModalityPlugin { - settings: Key, + settings: Key, methods: Key, selection: Key, selectable: Key, @@ -1237,7 +1237,7 @@ impl DynPlugin for ModalityPlugin { let selection = ctx.require_at(&self.selection)?; let selectable = ctx.require_at(&self.selectable)?; let files = ctx.require_at(&self.files)?.open(ctx)?; - settings.register::(ctx)?; + let settings = settings.register_document::(ctx)?; // The task layer: one state for the methods, the scheduler and // `modalityTasks` (A.3, A.6). let shared = Arc::new(engine::Shared::new( @@ -1397,7 +1397,7 @@ impl DynPlugin for ModalityPlugin { } } let updated = settings - .update::( + .update( SettingsScope::User, ¶ms.expected_revision, document, diff --git a/crates/dim-session-title/tests/appended_context_flow.rs b/crates/dim-session-title/tests/appended_context_flow.rs index cd3e92cbd2..4e6e2cdfa9 100644 --- a/crates/dim-session-title/tests/appended_context_flow.rs +++ b/crates/dim-session-title/tests/appended_context_flow.rs @@ -20,14 +20,14 @@ const SKILL: &str = "\nSkill: check\nDescription: D\nF /// answers as its additional context. const HOOK_CONTEXT: &str = "Read src/parser.rs before answering."; -fn builder(home: &std::path::Path) -> AgentBuilder { +fn builder() -> AgentBuilder { let mut builder = AgentBuilder::new(AgentConfig::default()); dim_session_title::install(&mut builder); defaults::install(&mut builder); defaults::mock_model_hosts(&mut builder); defaults::tool_host(&mut builder, Arc::new(MockTools)); dim_app_server::collaboration::install(&mut builder); - dim_app_server::hooks_settings::install(&mut builder, Some(home.to_owned())); + dim_app_server::hooks_settings::install(&mut builder); dim_agent_capabilities::hooks::install(&mut builder); builder } @@ -97,7 +97,7 @@ async fn start_with( .unwrap(); }); let server = serve( - builder(&store.0), + builder(), ServerConfig { unix_path: Some(PathBuf::from("/tmp").join(format!( "dim-title-appended-{}/server.sock", diff --git a/crates/dimcode/tests/cli_flow/hooks.rs b/crates/dimcode/tests/cli_flow/hooks.rs index 1e2dd37a27..d05120dfae 100644 --- a/crates/dimcode/tests/cli_flow/hooks.rs +++ b/crates/dimcode/tests/cli_flow/hooks.rs @@ -604,7 +604,7 @@ fn a_stop_hook_exports_its_session_from_dimcode_home() { let mut builder = AgentBuilder::new(AgentConfig::default()); defaults::mock_hosts(&mut builder); defaults::install(&mut builder); - dim_app_server::hooks_settings::install(&mut builder, Some(home.0.clone())); + dim_app_server::hooks_settings::install(&mut builder); dim_agent_capabilities::hooks::install(&mut builder); let server = serve( builder, diff --git a/docs/architecture/rust-agent/generated/app-server/services.json b/docs/architecture/rust-agent/generated/app-server/services.json index e5709a60db..5acad87200 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.json +++ b/docs/architecture/rust-agent/generated/app-server/services.json @@ -295,7 +295,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" }, @@ -331,7 +331,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -369,7 +369,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -505,7 +505,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -542,7 +542,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -580,7 +580,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -1525,7 +1525,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -1550,7 +1550,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -1574,12 +1574,6 @@ "provider": 39, "declared": true, "external": true - }, - { - "service": "dim_app_server::settings::SettingsService", - "provider": 18, - "declared": true, - "external": true } ] }, @@ -1606,7 +1600,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" }, @@ -1656,7 +1650,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -1712,7 +1706,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -1910,7 +1904,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -1923,7 +1917,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -1937,7 +1931,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -1962,7 +1956,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -1981,7 +1975,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -2001,7 +1995,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -2021,7 +2015,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -2034,7 +2028,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -2048,7 +2042,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -2078,7 +2072,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -2103,7 +2097,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -2129,7 +2123,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -2444,7 +2438,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -2481,7 +2475,7 @@ "generation": 1 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -2519,7 +2513,7 @@ "external": true }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "provider": 18, "declared": true, "external": true @@ -2539,7 +2533,7 @@ "status": "Ready" }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "status": "Ready" } @@ -2552,7 +2546,7 @@ "generation": 0 }, { - "service": "dim_app_server::settings::SettingsService", + "service": "dim_app_server::settings::declared::Settings", "scope": null, "provider": 18, "generation": 1 @@ -2564,12 +2558,6 @@ "provider": 1, "declared": true, "external": false - }, - { - "service": "dim_app_server::settings::SettingsService", - "provider": 18, - "declared": true, - "external": true } ] }, @@ -3534,6 +3522,12 @@ "generation": 1, "removing": false }, + { + "service": "dim_app_server::collaboration_model_policy::CollaborationModelPolicy", + "provider": 35, + "generation": 1, + "removing": false + }, { "service": "dim_app_server::connection::ConnectionHub", "provider": 43, @@ -3618,6 +3612,12 @@ "generation": 1, "removing": false }, + { + "service": "dim_app_server::settings::RegisteredDocument", + "provider": 33, + "generation": 1, + "removing": false + }, { "service": "dim_app_server::settings::SettingsService", "provider": 18, @@ -3744,6 +3744,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#collaborationModelPolicy", + "provider": 35, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#credentialVariablesHost", "provider": 1, diff --git a/docs/architecture/rust-agent/generated/app-server/services.md b/docs/architecture/rust-agent/generated/app-server/services.md index b51f2577af..8905821c91 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.md +++ b/docs/architecture/rust-agent/generated/app-server/services.md @@ -99,7 +99,7 @@ flowchart LR p3 -->|"dim_app_server::control::ProcessActivity"| p72 p10 -->|"dim_app_server::methods::ManagementMethods"| p72 p14 -->|"dim_app_server::plugin_files::PluginFiles"| p72 - p18 -->|"dim_app_server::settings::SettingsService"| p72 + p18 -->|"dim_app_server::settings::declared::Settings"| p72 p38 -->|"dyn rutis_bridge::session::services::HostDispatch#sessions"| p72 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p71 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p70 @@ -109,7 +109,7 @@ flowchart LR p17 -->|"dim_agent_capabilities::host::SelectableModelsHost"| p68 p10 -->|"dim_app_server::methods::ManagementMethods"| p68 p14 -->|"dim_app_server::plugin_files::PluginFiles"| p68 - p18 -->|"dim_app_server::settings::SettingsService"| p68 + p18 -->|"dim_app_server::settings::declared::Settings"| p68 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p67 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p66 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p65 @@ -148,11 +148,11 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p41 p40 -->|"dim_app_server::agents::AgentIndex"| p41 p39 -->|"dim_app_server::collaboration::CollaborationDirectory"| p41 - p18 -->|"dim_app_server::settings::SettingsService"| p41 + p18 -->|"dim_app_server::settings::declared::Settings"| p41 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p40 p38 -->|"dim_app_server::agents::AgentDirectory"| p40 p3 -->|"dim_app_server::control::ProcessActivity"| p40 - p18 -->|"dim_app_server::settings::SettingsService"| p40 + p18 -->|"dim_app_server::settings::declared::Settings"| p40 p8 -->|"dim_app_server::storage::face::Store"| p40 p8 -->|"dim_app_server::storage::metadata::binding::SessionMetadata"| p40 p6 -->|"dim_app_server::storage::sqlite::SqliteStorage"| p40 @@ -165,16 +165,16 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p36 p10 -->|"dim_app_server::methods::ManagementMethods"| p36 p10 -->|"dim_app_server::methods::ManagementMethods"| p35 - p18 -->|"dim_app_server::settings::SettingsService"| p35 + p18 -->|"dim_app_server::settings::declared::Settings"| p35 p4 -->|"dim_agent_capabilities::file_storage::face::FsHost"| p34 p10 -->|"dim_app_server::methods::ManagementMethods"| p34 - p18 -->|"dim_app_server::settings::SettingsService"| p34 + p18 -->|"dim_app_server::settings::declared::Settings"| p34 p10 -->|"dim_app_server::methods::ManagementMethods"| p33 - p18 -->|"dim_app_server::settings::SettingsService"| p33 + p18 -->|"dim_app_server::settings::declared::Settings"| p33 p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p32 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p32 p10 -->|"dim_app_server::methods::ManagementMethods"| p32 - p18 -->|"dim_app_server::settings::SettingsService"| p32 + p18 -->|"dim_app_server::settings::declared::Settings"| p32 p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p31 p10 -->|"dim_app_server::methods::ManagementMethods"| p31 p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p30 @@ -191,9 +191,9 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p24 p23 -->|"dim_app_server::mcp::publication::Publication"| p24 p10 -->|"dim_app_server::methods::ManagementMethods"| p24 - p18 -->|"dim_app_server::settings::SettingsService"| p24 + p18 -->|"dim_app_server::settings::declared::Settings"| p24 p1 -->|"dim_agent_capabilities::host::CredentialVariablesHost"| p23 - p18 -->|"dim_app_server::settings::SettingsService"| p23 + p18 -->|"dim_app_server::settings::declared::Settings"| p23 p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p22 p18 -->|"dim_app_server::settings::declared::Settings"| p22 p18 -->|"dim_app_server::settings::declared::Settings"| p21 diff --git a/docs/architecture/rust-agent/generated/app-server/services.mmd b/docs/architecture/rust-agent/generated/app-server/services.mmd index 85105c8a0f..04e4414ca2 100644 --- a/docs/architecture/rust-agent/generated/app-server/services.mmd +++ b/docs/architecture/rust-agent/generated/app-server/services.mmd @@ -94,7 +94,7 @@ flowchart LR p3 -->|"dim_app_server::control::ProcessActivity"| p72 p10 -->|"dim_app_server::methods::ManagementMethods"| p72 p14 -->|"dim_app_server::plugin_files::PluginFiles"| p72 - p18 -->|"dim_app_server::settings::SettingsService"| p72 + p18 -->|"dim_app_server::settings::declared::Settings"| p72 p38 -->|"dyn rutis_bridge::session::services::HostDispatch#sessions"| p72 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p71 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p70 @@ -104,7 +104,7 @@ flowchart LR p17 -->|"dim_agent_capabilities::host::SelectableModelsHost"| p68 p10 -->|"dim_app_server::methods::ManagementMethods"| p68 p14 -->|"dim_app_server::plugin_files::PluginFiles"| p68 - p18 -->|"dim_app_server::settings::SettingsService"| p68 + p18 -->|"dim_app_server::settings::declared::Settings"| p68 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p67 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p66 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p65 @@ -143,11 +143,11 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p41 p40 -->|"dim_app_server::agents::AgentIndex"| p41 p39 -->|"dim_app_server::collaboration::CollaborationDirectory"| p41 - p18 -->|"dim_app_server::settings::SettingsService"| p41 + p18 -->|"dim_app_server::settings::declared::Settings"| p41 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p40 p38 -->|"dim_app_server::agents::AgentDirectory"| p40 p3 -->|"dim_app_server::control::ProcessActivity"| p40 - p18 -->|"dim_app_server::settings::SettingsService"| p40 + p18 -->|"dim_app_server::settings::declared::Settings"| p40 p8 -->|"dim_app_server::storage::face::Store"| p40 p8 -->|"dim_app_server::storage::metadata::binding::SessionMetadata"| p40 p6 -->|"dim_app_server::storage::sqlite::SqliteStorage"| p40 @@ -160,16 +160,16 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p36 p10 -->|"dim_app_server::methods::ManagementMethods"| p36 p10 -->|"dim_app_server::methods::ManagementMethods"| p35 - p18 -->|"dim_app_server::settings::SettingsService"| p35 + p18 -->|"dim_app_server::settings::declared::Settings"| p35 p4 -->|"dim_agent_capabilities::file_storage::face::FsHost"| p34 p10 -->|"dim_app_server::methods::ManagementMethods"| p34 - p18 -->|"dim_app_server::settings::SettingsService"| p34 + p18 -->|"dim_app_server::settings::declared::Settings"| p34 p10 -->|"dim_app_server::methods::ManagementMethods"| p33 - p18 -->|"dim_app_server::settings::SettingsService"| p33 + p18 -->|"dim_app_server::settings::declared::Settings"| p33 p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p32 p46 -->|"dim_agent_runtime::parts::PartRegistry"| p32 p10 -->|"dim_app_server::methods::ManagementMethods"| p32 - p18 -->|"dim_app_server::settings::SettingsService"| p32 + p18 -->|"dim_app_server::settings::declared::Settings"| p32 p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p31 p10 -->|"dim_app_server::methods::ManagementMethods"| p31 p29 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p30 @@ -186,9 +186,9 @@ flowchart LR p46 -->|"dim_agent_runtime::parts::PartRegistry"| p24 p23 -->|"dim_app_server::mcp::publication::Publication"| p24 p10 -->|"dim_app_server::methods::ManagementMethods"| p24 - p18 -->|"dim_app_server::settings::SettingsService"| p24 + p18 -->|"dim_app_server::settings::declared::Settings"| p24 p1 -->|"dim_agent_capabilities::host::CredentialVariablesHost"| p23 - p18 -->|"dim_app_server::settings::SettingsService"| p23 + p18 -->|"dim_app_server::settings::declared::Settings"| p23 p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p22 p18 -->|"dim_app_server::settings::declared::Settings"| p22 p18 -->|"dim_app_server::settings::declared::Settings"| p21 diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index d2481d5fb9..39f915d650 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -15,6 +15,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `basePromptSettingsHost` | process | PromptSettings | data | `base` async | | `callChannel` | process | CallChannel | data | `closed` async, `notify` async | | `collaborationDirectory` | process | CollaborationDirectory | data | `relations` async | +| `collaborationModelPolicy` | process | CollaborationModelPolicy | data | `read` async | | `connectionHub` | process | Connection | internal(control) | — | | `credentialVariablesHost` | process | root | data | `variables` async | | `eventHub` | process | eventhub | data | `declare` async, `publish` async | @@ -23,7 +24,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `fileStorage` | process | FileStorage | internal(object) | — | | `fsHost` | process | FileStorage | data | `backup` async, `closeRead` async, `createDirectory` async, `list` async, `lock` async, `openRead` async, `readAt` async, `readBytes` async, `remove` async, `replace` async, `stat` async, `unlock` async | | `grokOAuthService` | process | GrokOAuth | internal(secret) | — | -| `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `withdraw` async | +| `hooksService` | process | HooksSettings | data | `plugins` async, `refusal` sync, `register` async, `sources` async, `withdraw` async | | `hostPlatform` | process | HostPlatform | internal(object) | — | | `listenAddresses` | process | Transport | data | `read` async | | `loader` | process | rutis-loader | internal(owner-api) | — | @@ -55,8 +56,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `sessionPermissions` | process | AgentDirectory | data | `permission` async, `permissionDefaults` async | | `sessionStore` | process | SessionStore | internal(owner-api) | — | | `sessions` | process | AgentDirectory | data | `delete` async, `exists` async, `history` async, `idle` async, `input` async, `launch` async, `lookup` async, `pending` async, `stop` async, `withdraw` async | -| `settings` | process | Settings | data | `declaredBy` sync, `projects` sync, `read` async, `register` async, `update` async | -| `settingsService` | process | Settings | internal(owner-api) | — | +| `settings` | process | Settings | data | `authorizeProject` async, `declaredBy` sync, `projects` sync, `read` async, `register` async, `registerDocument` async, `update` async | | `skillsCatalog` | process | SkillsCatalog | data | `issues` async, `plugins` async, `register` async, `withdraw` async | | `skillsInstructionsSettingsHost` | process | PromptSettings | data | `instructions` async | | `sqliteStorage` | process | SqliteStorage | data | `abandonFile` async, `agentOwner` async, `agents` async, `batchEnd` async, `batchEndAt` async, `branches` async, `commitFile` async, `commitTimelineRound` async, `createSession` async, `delete` async, `head` async, `importUserIfAbsent` async, `ledMembers` async, `memberSessions` async, `members` async, `ownedAgents` async, `ownedPaths` async, `owners` async, `ownsFile` async, `ownsOutput` async, `readPreferences` async, `readSelection` async, `readUser` async, `registerOutput` async, `replaceUser` async, `reserveFile` async, `save` async, `sessionConfig` async, `storageReport` async, `unfinishedOwned` async, `writeSelection` async | diff --git a/docs/design/appserver/mcp-management.md b/docs/design/appserver/mcp-management.md index 65cbd57e42..079289ebf4 100644 --- a/docs/design/appserver/mcp-management.md +++ b/docs/design/appserver/mcp-management.md @@ -1358,7 +1358,7 @@ business configuration, not an event. | `McpAuth` ([MCP OAuth](mcp-oauth.md)) | The `mcp.auth.*` methods of the same namespace; the credential record is untouched by a move | | `credentialVariablesHost` (capabilities host, D19) | The names of the environment variables the daemon reads credentials from; `McpPublication` and `McpPlugin` declare it, and the assembly root in `serve` provides it | -The MCP publication coordinator is private typed wiring within the MCP owner. Its command queue, connection generations and application watch have no public catalog name; the existing management methods and `mcpSession` expose the owner operations. The explicit private dependency still orders assembly and shutdown. +The MCP publication coordinator is private typed wiring within the MCP owner. Its command queue, connection generations and application watch have no public catalog name; the existing management methods and `mcpSession` expose the owner operations. The explicit private dependency still orders assembly and shutdown. MCP registers its documents with Settings and uses the same source-bound reads for management and publication. The secrets document stays inside MCP. ### 8.1 Plugin content data face diff --git a/docs/design/appserver/permission-command-rules.md b/docs/design/appserver/permission-command-rules.md index b7fabf37eb..db41e0158b 100644 --- a/docs/design/appserver/permission-command-rules.md +++ b/docs/design/appserver/permission-command-rules.md @@ -181,7 +181,7 @@ Bindings per profile (exactly one each): | --- | --- | | `defaults::install`, `install_with_prompt`, `install_with_process_model` (mock App Server profile and test hosts) | `install_profile` binds the fixed empty host `NoCommandRules` with `session_data_value`, next to the `EmptyPromptHost` it already binds. Existing tests are unchanged | | `install_with_prompt_capability`, `install_local_execution`, `install_minimal_execution` | Bind nothing, like `PromptHost`: the host that installs them binds the port. Capability-only hosts (integration tests, the `xtask` local graph) bind `CommandRules(Arc::new(NoCommandRules))` | -| App Server product profile (`install_local_execution` in `main.rs`, its tests and the `xtask` App Server graph) | The profile calls `permission_rules::install(&mut builder)`, which adds the feature `CommandRules` and requires its Session part `CommandRules` (`require_feature`, Deps `Keyed`); it provides `CommandRules` reading `SettingsService::read::(User)` on each call. `serve` registers the process part `PermissionRulesPlugin` (`register_part`, Deps `Keyed` and `Keyed`, owner row `permission`) with local execution, next to `mcp` and `skills`; it provides the management methods. Both live in `dim-app-server/src/permission_rules.rs` with the `PermissionSettings` document type (`NAMESPACE = "permission"`, `USER_FILE = "permission.json"`, no `PROJECT_FILE`) | +| App Server product profile (`install_local_execution` in `main.rs`, its tests and the `xtask` App Server graph) | The profile calls `permission_rules::install(&mut builder)`, which adds the feature `CommandRules` and requires its Session part `CommandRules` (`require_feature`, Deps `Keyed`); it provides `CommandRules` reading `RegisteredDocument::read(User)` on each call. `serve` registers the process part `PermissionRulesPlugin` (`register_part`, Deps `Keyed` and `Keyed`, owner row `permission`) with local execution, next to `mcp` and `skills`; it provides the management methods. Both live in `dim-app-server/src/permission_rules.rs` with the `PermissionSettings` document type (`NAMESPACE = "permission"`, `USER_FILE = "permission.json"`, no `PROJECT_FILE`) | ## 5. Flows diff --git a/docs/design/appserver/settings-service.md b/docs/design/appserver/settings-service.md index 10ad7b029e..28a98a85c2 100644 --- a/docs/design/appserver/settings-service.md +++ b/docs/design/appserver/settings-service.md @@ -17,8 +17,7 @@ each source with Settings when it starts ([ADR 007](../../adr/007-plugin-configu the source name, its files, a JSON Schema (with `default` values) and its user-only fields (§3.1). Settings then offers three things over JSON documents: -- the process service `settings`, which the owner uses: `register`, `read`, `update` (CAS on - the revision) and `projects`; +- the process service `settings` for source registration, reads, writes and project admission (§4.2); - the client management methods `settings.read`, `settings.update`, `settings.sources` and `settings.projects`; - the same rutis events as S8a, `settings.changed` and `settings.project_authorized`. Their @@ -119,7 +118,7 @@ owner depends on `settings`. Every owner, built-in Rust and TypeScript alike, registers its sources from its own process row's `apply`. Declared sources use `settings.register(declaration)` through their language binding -(§4.2, §4.5); native `BusinessDocument` sources use `SettingsService::register::` (§4.5). Neither the App Server's assembly nor PluginManager +(§4.2, §4.5); native `BusinessDocument` sources use `Settings::register_document::` (§4.5). Neither the App Server's assembly nor PluginManager declares sources. A registration belongs to the plugin that made it and is withdrawn when that plugin unloads (turned off, removed or reloaded); a reload registers again from the new generation. The stored documents stay in the home whether or not their source is registered: an @@ -212,6 +211,8 @@ Process scope, no instance key, provided by Settings. | Method | Mode | Request | Reply | | --- | --- | --- | --- | | `register` | async | a declaration (§3.1) | nothing; rejects when refused | +| `registerDocument` | async | `({source, userFile, projectFile?}, codec)` | Source-bound `read(scope)` and `update(scope, expectedRevision, document)`, each returning the Settings result with a snapshot. The owner supplies `decode(bytes or null)` and `validate(document)`. The registration ends on owner unload. | +| `authorizeProject` | async | `{cwd}` | Settings result with the authorized root number. A newly admitted root emits the project authorization notice (§4.4). | | `read` | async | `{source, scope: Scope}` | `Snapshot` | | `update` | async | `{source, scope: Scope, expectedRevision, document}` | `Snapshot` (the stored document) | | `declaredBy` | sync | `{instanceId: string}` (the live loader instance ID in decimal) | The JSON Schema declarations registered by that instance, ordered by source name. An instance with no live declarations returns an empty array. | @@ -230,7 +231,7 @@ Process scope, no instance key, provided by Settings. - Errors of `read`, `update` and `projects` (§6): `unknown_source`, `invalid_scope`, `invalid_document`, `user_only_field`, `conflict`, `unsynced`, `failed`, `closed`, `cancelled`. -Only `register` uses the caller's identity, to withdraw the registration with the calling row. +Both registration methods use the caller's identity, to withdraw the registration with the calling row. Ownership comes from the registering row: each source has one owner, and only that package is written against it. This is the trust model of in-process plugins (AGENTS.md rule 11): dependency declarations are not a sandbox. @@ -262,7 +263,7 @@ with `managementMethods` (§4.5). They are never served to paired devices (overv the `plugin` tool's `config` command, which additionally returns the user document with `writeOnly` members redacted and listed in `writeOnlySet` (PluginManager §6). - `schedule` is not a declared source. `ScheduleDocument` is a Rust `BusinessDocument`, - registered with `settings.register::`, validated by its own `validate()`, + registered with `settings.register_document::`, validated by its own `validate()`, served by `schedule.*`, and `settings_unknown_source` on every `settings.*` path. A Rust source keeps its own typed methods and is out of a schema-driven surface; `settings.sources` lists declared sources only and therefore never lists it. @@ -313,15 +314,16 @@ Permission does). ### 4.5 Rust binding The `Settings` binding exposes the owner operations of the public `settings` data face. -It provides `register(ctx, declaration)`, `read(source, scope, cancel)`, -`update(source, scope, expected, document, cancel)` and `projects()`. +Declared sources use `register`, `declared_by`, `read` and `update`. Native `BusinessDocument` sources use +`register_document` and its bound read/update operations. Project admission and listing use +`authorize_project` and `projects`. The dispatcher calls these same operations, and native consumers call them directly without JSON conversion. Registration retains the caller's lifetime; updates are owner writes and preserve user-only fields. The existing Settings owner still supplies the source registry, validation and persistence. `SettingsService` retains the native `BusinessDocument` and client management paths below. -PluginManager's declared-source tools also use it for reads and owner writes. +PluginManager reads and updates its declared sources through the public `Settings` binding. This binding does not make native sources visible through declared-source operations or change the local-client boundary in §4.3 and §7. diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5b2be8c345..04d25dc0de 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -11,7 +11,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | | `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | -| `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction. SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | +| `settings` | 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. | ## Additional public bindings @@ -134,7 +134,7 @@ serves declared sources and excludes the native `mcp-secrets` document. | Caller → Settings | Current operation and contract | | --- | --- | | PluginManager; declared-source consumers | Filter declarations by live loader instance using declaredBy above. Reuse settings.read/update/projects for owner edits and reads. SettingsMethods uses its client path and lists only declared sources. | -| Agents create/restore, Hooks and MCP management | authorize_project(cwd,cancelled) → root registers the authorized root and publishes the existing notice. It is a write performed at trusted admission. project_root/path/sources are reads covered by settings.projects. | +| Agents create/restore, Hooks and MCP management | `settings.authorizeProject({cwd}) → SettingsResult` registers the authorized root and publishes the existing notice. It is a write performed at trusted admission. project_root/path/sources are reads covered by settings.projects. | | PermissionRules and CommandRules; CollaborationModelPolicy and optional Collaboration runtime | User permission and collaboration policy reads/writes. Expose the existing commandRules.read projection to rule consumers; use the policy owner's read returning {revision,policy} for Collaboration. Preserve absent-profile fallback. | | HooksSettings and HookSources | hooks, hooks-projects and hooks-plugins. The runtime consumes sources(cwd,cancelled) → HookSourcesSnapshot. Source resolution, revisions and enablement belong to Hooks. | | Mcp and McpPublication | mcp, mcp-projects, mcp-plugins and mcp-secrets. Publication reads effective server configuration and constructs live connections. Keep partial decoding of individual server entries and credential use at the MCP owner. | @@ -148,4 +148,4 @@ existing decoder for stored bytes, its default for absence, and validates the re `validate(document) → void` applies BusinessDocument write validation before admitting a replacement. Settings performs serialization, version checks and persistence. Both calls propagate the original Settings error and end with the registration generation. Foreign codec -calls occur outside SQLite transactions. Declared-schema sources reuse their existing codec. +calls occur outside SQLite transactions and exclusive file leases. Declared-schema sources reuse their existing codec. diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 7f10a66063..effeafc0de 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -418,6 +418,8 @@ Plugin documents are kept in the Settings source `hooks-plugins`, one `{dir, hoo It is separate from the local client management entry in A.7. Each operation accepts exactly one JSON object; positional arrays and scalar requests are invalid. +The Session hook runner obtains the effective source documents through `hooksService.sources({cwd})`. The reply contains `{sources: [{id, path, enabled, state, document}]}`. A lookup reads the project source only for an already authorized working directory. + | Operation | Request | Reply | | --- | --- | --- | | `register` (async) | `{plugin, dir, document}`; plugin id and directory are strings | `null` | @@ -692,7 +694,7 @@ Codex `apply_patch` has no alias: its input is a patch, while Dim's `write` and | `Approval.respond` | `Approval::respond(approval_id, ApprovalDecision)` from `Keyed` | | `HookSources` | Session port `HookSourcesHost(Arc)`, bound by App Server as `CommandRules` and `SkillSettingsHost` are | | `hooks`, `hooks-projects`, `hooks-plugins` | `BusinessDocument` types in App Server (`hooks`: `USER_FILE` `hooks.json`, no `PROJECT_FILE`; `hooks-projects`: `USER_FILE` `hooks-projects.json`; `hooks-plugins`: `USER_FILE` `hooks-plugins.json`, one `{dir, hooks}` entry per plugin id, as `McpPluginServers` in `mcp/config.rs`) | -| `.dimcode/hooks.json` | Read by `HooksSettings` through `FileStorage::path(root, ".dimcode/hooks.json")` and `read_limited`, `root` from `SettingsService::project_root(cwd)`, parsed into the `hooks` document type | +| `.dimcode/hooks.json` | Read by `HooksSettings` through `FileStorage::path(root, ".dimcode/hooks.json")` and `read_limited`, `root` from `settings.projects({})`, parsed into the `hooks` document type | | `register`, `withdraw`, `plugins()` | `HooksService::register_plugin(plugin: String, dir: PathBuf, document: serde_json::Value, cancel: &CancellationToken) -> Result<()>`, `withdraw_plugin(plugin: String, cancel: &CancellationToken) -> Result<()>`, `plugins(cancel: &CancellationToken) -> Result>` and `plugin_refusal(&self, plugin: &str) -> Option<(String, Option<&'static str>)>`, as `McpService`'s (`crates/dim-app-server/src/mcp.rs`): a refused document leaves no entry, and `plugin_refusal` reports its error text with the static reason its cause carries, both read under one lock; PluginManager reads the service through `names.key()` in its `Owners`, its `Kind::Hooks` added to `OWNERS` and `CONTENT` ([PluginManager §3.7](PluginManager.md#37-content-registration)) | | `hooks.*` | `Keyed`; `methods.register(ctx, "hooks", …)` | | Runner | Session service `HooksRuntime`, private to Hooks; processes from `HostPlatform::build_process_spec` and `spawn`, with the event's stdin object (A.3) as the initial stdin (A.6.3), owned by `ctx.effect` | diff --git a/docs/design/plugins/Scheduler.md b/docs/design/plugins/Scheduler.md index a356ccfa29..be7802721e 100644 --- a/docs/design/plugins/Scheduler.md +++ b/docs/design/plugins/Scheduler.md @@ -924,7 +924,7 @@ 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`, `PluginFiles`) keyed with `names.key()`; the crate depends on `dim-app-server`, which `xtask check` allows | +| `settings`, `pluginFiles` | Typed App Server services (`Settings` → `RegisteredDocument`, `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 `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`. | diff --git a/docs/design/subagent-model-policy.md b/docs/design/subagent-model-policy.md index b933a994f5..a4fa6b6da1 100644 --- a/docs/design/subagent-model-policy.md +++ b/docs/design/subagent-model-policy.md @@ -53,7 +53,7 @@ decision by an LLM. `agent` means the existing request/profile selection behavio | Identify the requesting branch | `CollaborationSession::request` already receives `branch_id`; pass it within Collaboration, without changing an event or tool request | | Read the adopted leader model | `Session::get(branch_id)` while consuming `collaboration/request`, before starting its delivery task | | Resolve an explicit model | The existing `AgentIndex` model-selection host and configured/non-catalog profile paths | -| Persist and edit policy | Native `BusinessDocument`, `SettingsService::read/update`, source CAS and owner management methods, as used by `permission_rules.rs` | +| Persist and edit policy | Native `BusinessDocument`, source-bound `read/update`, source CAS and owner management methods, as used by `permission_rules.rs` | | Start/restore and retain members | Existing Agents/Collaboration Session creation, usage holds and cleanup, including idle unloading | Do not use `leader.config().model` or `session.summaries` as the adopted leader model: @@ -126,7 +126,7 @@ serve Rust `BusinessDocument` sources. A dedicated `CollaborationModelPolicyPlugin` process owner row provides these methods by registering namespace `collaboration` with the process `ManagementMethods` table. It owns the native document's read/validation/CAS -operations and depends on `Keyed` and `Keyed`. +operations and depends on `Keyed` and `Keyed`. It is not the Collaboration plugin that Rpc already reaches through a Gate: the management owner must reload independently without unloading Rpc, per the methods contract §3.2. @@ -136,6 +136,8 @@ contract §3.2. | `collaboration.model_policy` | `{}` | `{revision: string, policy: Policy}` | false | `Report` | | `collaboration.set_model_policy` | `{expectedRevision: string, policy: Policy}` | `{revision: string}` | true | `Report` | +The process data face `collaborationModelPolicy.read({})` and the local management read return the same `{revision, policy}`. Collaboration reads the owner when selecting a new member’s model. + `Policy` is exactly the tagged source type above. Use the existing local v3 management authorization; a paired device has no access. Invalid request shape or policy is invalid params (`-32602`, `invalid_params`); source CAS conflict is @@ -147,11 +149,8 @@ before another CAS, without automatically replacing the user's selection. App Server configurations without `local_execution()` continue using existing `agent` behavior and expose no policy management methods. -Collaboration must not gain an unconditional Settings dependency: declare the -dependency as `When>`, with keys from -`names.when::>(local_execution())`, the same predicate Agents -uses. Obtain it from `Deps`. In those hosts Collaboration already -reaches Settings through AgentIndex; account-only roots do not add a wait. The +The local execution profile gates Collaboration on Settings. At member creation, +Collaboration reads the current policy through `collaborationModelPolicy.read({})`. The composition root reserves the native source and registers its dedicated management owner only under that predicate. The owner's `apply` registers its methods with `methods.register(ctx, "collaboration", ...)`. diff --git a/docs/zh/design/appserver/permission-command-rules.md b/docs/zh/design/appserver/permission-command-rules.md index 903baa45c7..77f1c40a41 100644 --- a/docs/zh/design/appserver/permission-command-rules.md +++ b/docs/zh/design/appserver/permission-command-rules.md @@ -165,7 +165,7 @@ impl Permission { | --- | --- | | `defaults::install`、`install_with_prompt`、`install_with_process_model`(App Server mock 配置与测试宿主) | `install_profile` 用 `session_data_value` 绑定固定的空宿主 `NoCommandRules`,与它已绑定的 `EmptyPromptHost` 并列。现有测试不变 | | `install_with_prompt_capability`、`install_local_execution`、`install_minimal_execution` | 与 `PromptHost` 一样不绑定:由安装它们的宿主绑定端口。只用 capabilities 的宿主(集成测试、`xtask` 本地图)绑定 `CommandRules(Arc::new(NoCommandRules))` | -| App Server 产品配置(`main.rs` 中的 `install_local_execution`、其测试与 `xtask` App Server 图) | 配置调用 `permission_rules::install(&mut builder)`,加入功能 `CommandRules` 并要求它的 Session 部分 `CommandRules`(`require_feature`,Deps `Keyed`),它提供的 `CommandRules` 每次调用都读取 `SettingsService::read::(User)`。`serve` 在本地执行时注册进程部分 `PermissionRulesPlugin`(`register_part`,Deps `Keyed` 与 `Keyed`,所有者行 `permission`),与 `mcp`、`skills` 并列,由它提供管理方法。两者与文档类型 `PermissionSettings`(`NAMESPACE = "permission"`、`USER_FILE = "permission.json"`、无 `PROJECT_FILE`)同在 `dim-app-server/src/permission_rules.rs` | +| App Server 产品配置(`main.rs` 中的 `install_local_execution`、其测试与 `xtask` App Server 图) | 配置调用 `permission_rules::install(&mut builder)`,加入功能 `CommandRules` 并要求它的 Session 部分 `CommandRules`(`require_feature`,Deps `Keyed`),它提供的 `CommandRules` 每次调用都读取 `RegisteredDocument::read(User)`。`serve` 在本地执行时注册进程部分 `PermissionRulesPlugin`(`register_part`,Deps `Keyed` 与 `Keyed`,所有者行 `permission`),与 `mcp`、`skills` 并列,由它提供管理方法。两者与文档类型 `PermissionSettings`(`NAMESPACE = "permission"`、`USER_FILE = "permission.json"`、无 `PROJECT_FILE`)同在 `dim-app-server/src/permission_rules.rs` | ## 5. 流程 diff --git a/docs/zh/design/appserver/settings-service.md b/docs/zh/design/appserver/settings-service.md index 670232c59a..018d0002f2 100644 --- a/docs/zh/design/appserver/settings-service.md +++ b/docs/zh/design/appserver/settings-service.md @@ -16,7 +16,7 @@ Settings 为不是用 Rust 写的插件提供业务来源。这类插件在启 ([ADR 007](../../adr/007-plugin-configuration.md) D5):来源名、文件、JSON Schema(含 `default` 值)和 仅限用户的字段(§3.1)。随后 Settings 在 JSON 文档上提供三样东西: -- 进程服务 `settings`,供所有者使用:`register`、`read`、`update`(按 revision 做 CAS)和 `projects`; +- 进程服务 `settings` 用于来源登记、读写及项目授权(§4.2); - 客户端管理方法 `settings.read`、`settings.update`、`settings.sources` 和 `settings.projects`; - 与 S8a 相同的 rutis 事件 `settings.changed` 和 `settings.project_authorized`。它们的载荷改为 可序列化。没有 `subscribe(source)`。 @@ -103,7 +103,7 @@ Settings 不赋予任何字段特殊含义,只有一个例外:schema 带 JSO 每个所有者,不论是内置 Rust 还是 TypeScript,都在自己进程行的 `apply` 中登记来源。声明式来源 通过对应语言绑定调用 `settings.register(declaration)`(§4.2、§4.5);原生 `BusinessDocument` 来源 -使用 `SettingsService::register::`(§4.5)。 +使用 `Settings::register_document::`(§4.5)。 App Server 的装配和 PluginManager 都不声明来源。登记属于发起它的插件,在该插件卸载(关闭、移除或 重载)时撤回;重载时由新一代重新登记。不论来源是否已登记,存储的文档都留在 home 中:未登记的来源 在所有路径上都是 `unknown_source`,有所有者登记它后,其文档重新可用。 @@ -191,6 +191,8 @@ Settings 在内存中保存已登记的来源(声明已编译),各自保 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | | `register` | async | 一份声明(§3.1) | 无;被拒绝时 reject | +| `registerDocument` | 异步 | `({source, userFile, projectFile?}, codec)` | 返回本次登记的 `read(scope)` 和 `update(scope, expectedRevision, document)`,两者都返回含快照的 Settings 结果。所有者提供 `decode(bytes 或 null)` 和 `validate(document)`。所有者卸载时登记结束。 | +| `authorizeProject` | 异步 | `{cwd}` | 返回含已授权根目录编号的 Settings 结果。首次授权会发布 §4.4 的项目授权通知。 | | `read` | async | `{source, scope: Scope}` | `Snapshot` | | `update` | async | `{source, scope: Scope, expectedRevision, document}` | `Snapshot`(保存后的文档) | | `declaredBy` | sync | `{instanceId: string}`,加载器实例 ID 的十进制字符串 | 该实例已注册且仍有效的 JSON Schema 声明,按来源名称排序。无有效声明时返回空数组。 | @@ -206,7 +208,7 @@ Settings 在内存中保存已登记的来源(声明已编译),各自保 - `read`、`update` 和 `projects` 的错误(§6):`unknown_source`、`invalid_scope`、`invalid_document`、 `user_only_field`、`conflict`、`unsynced`、`failed`、`closed`、`cancelled`。 -只有 `register` 使用调用方身份,以便随调用行撤回登记。所有权来自登记它的行:每个来源只有一个所有者, +两种登记方法都使用调用方身份,以便随调用行撤回登记。所有权来自登记它的行:每个来源只有一个所有者, 只有那个包针对它编写。这是进程内 插件的信任模型(AGENTS.md 规则 11):依赖声明不是沙箱。 @@ -233,7 +235,7 @@ Settings 在内存中保存已登记的来源(声明已编译),各自保 agent 侧的对应物仍是 `plugin` 工具的 `config` 命令,它额外返回用户文档,并把 `writeOnly` 成员去掉后列在 `writeOnlySet` 里(PluginManager §6)。 - `schedule` 不是声明的来源。`ScheduleDocument` 是 Rust 的 `BusinessDocument`,经 - `settings.register::` 登记,由它自己的 `validate()` 校验,由 `schedule.*` + `settings.register_document::` 登记,由它自己的 `validate()` 校验,由 `schedule.*` 提供,在所有 `settings.*` 路径上都是 `settings_unknown_source`。Rust 来源保留自己类型化的 方法,不属于 schema 驱动的表面;`settings.sources` 只列声明的来源,因此从不列出它。 - `settings.sources` 从不提供给已配对设备(§4.3 开头),也不在 Web 入口的允许清单里,因此 @@ -273,13 +275,12 @@ Settings 在内存中保存已登记的来源(声明已编译),各自保 ### 4.5 Rust 绑定 `Settings` 绑定公开公共 `settings` 数据面的 owner 操作,提供 -`register(ctx, declaration)`、`read(source, scope, cancel)`、 -`update(source, scope, expected, document, cancel)` 和 `projects()`。 +声明式来源的 `register`、`declared_by`、`read` 和 `update`,原生 `BusinessDocument` 来源的 `register_document` 及其绑定的读写操作,以及项目授权与枚举的 `authorize_project` 和 `projects`。 Dispatcher 调用这些相同操作;原生消费者直接调用,无需 JSON 转换。登记仍绑定调用者生命周期, 更新仍是不能修改 user-only 字段的 owner 写入。来源注册、校验和持久化仍由同一个 Settings owner 承担。 `SettingsService` 保留下述原生 `BusinessDocument` 和客户端管理路径。 -PluginManager 的声明式来源工具也通过它读取并进行 owner 写入。此绑定不使声明式操作可见 +PluginManager 的声明式来源工具通过公共 `Settings` 绑定读取并写入。此绑定不使声明式操作可见 原生来源,也不改变 §4.3 和 §7 的本地客户端边界。 在 `dim-app-server::settings` 中(S8a 的类型,只在注明处改动): diff --git a/docs/zh/design/plugins/Hooks.md b/docs/zh/design/plugins/Hooks.md index a5bd428a1a..897f6e3489 100644 --- a/docs/zh/design/plugins/Hooks.md +++ b/docs/zh/design/plugins/Hooks.md @@ -417,6 +417,8 @@ AcpGateway 自己的设计把 Hooks 对 `session.submit` 的 `input_blocked` 拒 `hooksService` 是现有插件内容操作的进程数据面,与 A.7 的本地客户端管理入口分开。 每个操作只接受一个 JSON 对象;位置参数数组和标量请求无效。 +Session 的 Hook 执行器通过 `hooksService.sources({cwd})` 获取生效的来源文档,返回 `{sources: [{id, path, enabled, state, document}]}`。只有工作目录已获授权时,读取才包含项目来源。 + | 操作 | 请求 | 回复 | | --- | --- | --- | | `register`(异步) | `{plugin, dir, document}`;插件 ID 和目录为字符串 | `null` | @@ -690,7 +692,7 @@ Codex 的 `apply_patch` 没有别名:它的输入是补丁,而 Dim 的 `writ | `Approval.respond` | 经 `Keyed` 调用 `Approval::respond(approval_id, ApprovalDecision)` | | `HookSources` | Session 端口 `HookSourcesHost(Arc)`,由 App Server 绑定,如同 `CommandRules` 与 `SkillSettingsHost` | | `hooks`、`hooks-projects`、`hooks-plugins` | App Server 中的 `BusinessDocument` 类型(`hooks`:`USER_FILE` 为 `hooks.json`,没有 `PROJECT_FILE`;`hooks-projects`:`USER_FILE` 为 `hooks-projects.json`;`hooks-plugins`:`USER_FILE` 为 `hooks-plugins.json`,每个插件 id 一条 `{dir, hooks}`,如同 `mcp/config.rs` 中的 `McpPluginServers`) | -| `.dimcode/hooks.json` | 由 `HooksSettings` 经 `FileStorage::path(root, ".dimcode/hooks.json")` 与 `read_limited` 读取,`root` 来自 `SettingsService::project_root(cwd)`,解析为 `hooks` 文档类型 | +| `.dimcode/hooks.json` | 由 `HooksSettings` 经 `FileStorage::path(root, ".dimcode/hooks.json")` 与 `read_limited` 读取,`root` 来自 `settings.projects({})`,解析为 `hooks` 文档类型 | | `register`、`withdraw`、`plugins()` | `HooksService::register_plugin(plugin: String, dir: PathBuf, document: serde_json::Value, cancel: &CancellationToken) -> Result<()>`、`withdraw_plugin(plugin: String, cancel: &CancellationToken) -> Result<()>`、`plugins(cancel: &CancellationToken) -> Result>` 与 `plugin_refusal(&self, plugin: &str) -> Option<(String, Option<&'static str>)>`,如同 `McpService` 的(`crates/dim-app-server/src/mcp.rs`):被拒绝的文档不留条目,`plugin_refusal` 报告其错误文本以及原因携带的静态 reason,两者在同一把锁下读取;PluginManager 在其 `Owners` 中经 `names.key()` 读取该服务,`Kind::Hooks` 加入 `OWNERS` 与 `CONTENT`([PluginManager §3.7](PluginManager.md#37-内容登记)) | | `hooks.*` | `Keyed`;`methods.register(ctx, "hooks", …)` | | 执行器 | Session 服务 `HooksRuntime`,Hooks 私有;进程来自 `HostPlatform::build_process_spec` 与 `spawn`,事件的 stdin 对象(A.3)作为初始 stdin(A.6.3),由 `ctx.effect` 持有 | diff --git a/docs/zh/design/plugins/Scheduler.md b/docs/zh/design/plugins/Scheduler.md index ea116645ce..51ec4bf11f 100644 --- a/docs/zh/design/plugins/Scheduler.md +++ b/docs/zh/design/plugins/Scheduler.md @@ -871,7 +871,7 @@ 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`、`PluginFiles`);该 crate 依赖 `dim-app-server`,`xtask check` 允许 | +| `settings`、`pluginFiles` | 用 `names.key()` 键入的 App Server 类型化服务(`Settings` → `RegisteredDocument`、`PluginFiles`);该 crate 依赖 `dim-app-server`,`xtask check` 允许 | | `sessions` | 共享的宿主分发名称,以其 JSON 信封调用;其原生请求类型对 App Server 私有 | | 进程存储 | 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`。 | diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index c7ea5d1837..ea11f6a682 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -66,11 +66,26 @@ export interface Settings { * home when the row unloads. Rejects (failing the caller's apply) when the declaration is * invalid or its name or a file is registered already. Call it from a row's own `apply`. */ register(declaration: SourceDeclaration): Promise; + registerDocument( + declaration: { source: string; userFile: string; projectFile?: string }, + codec: { decode(bytes: Uint8Array | null): D | Promise; validate(document: D): void | Promise } + ): Promise<{ + read(scope: SettingsScope): Promise>; + update(scope: SettingsScope, expectedRevision: string, document: D): Promise>; + }>; read(request: { source: string; scope: SettingsScope }): Promise>; update(request: { source: string; scope: SettingsScope; expectedRevision: string; document: JsonObject }): Promise>; + authorizeProject(request: { cwd: string }): Promise>; projects(request: Record): SettingsResult<{ projects: { root: number; cwd: string }[] }>; } +export interface CollaborationModelPolicy { + read(request: Record): Promise<{ + revision: string; + policy: { mode: "agent" } | { mode: "inherit" } | { mode: "fixed"; model: ModelId }; + }>; +} + export type TitleSource = 'auto' | 'manual'; export interface Title { text: string; source: TitleSource } /** `revision` counts committed title writes; 0 means never written. */ @@ -811,6 +826,13 @@ export interface SummaryPromptSettingsHost { /** Hooks-owned plugin content registration; see Hooks A.2. */ export interface HooksService { + sources(request: { cwd: string }): Promise<{ sources: { + id: "user" | "project" | `plugin:${string}`; + path: string | null; + enabled: boolean; + state: "ok" | "missing" | { invalid: string }; + document: { hooks: Record; disableAllHooks: boolean } | null; + }[] }>; register(request: { plugin: string; dir: string; document: JsonValue }): Promise; withdraw(request: { plugin: string }): Promise; plugins(request: Record): Promise; diff --git a/runtime/fixtures/settings-owner.ts b/runtime/fixtures/settings-owner.ts index a90949079c..5c265ecc07 100644 --- a/runtime/fixtures/settings-owner.ts +++ b/runtime/fixtures/settings-owner.ts @@ -1,9 +1,9 @@ import { definePlugin } from '@arcships/rutis' import provides from './settings-owner.json' with { type: 'json' } import sources from './settings-owner.settings.json' with { type: 'json' } -import type { PartRegistry, SessionMethods, Settings as SettingsService, SourceDeclaration } from '../../npm/plugin.js' +import type { JsonValue, PartRegistry, SessionMethods, Settings as SettingsService, SourceDeclaration } from '../../npm/plugin.js' -type Envelope = { ok: boolean; value?: unknown; error?: { code: string; message: string } } +type Envelope = { ok: boolean; value?: JsonValue; error?: { code: string; message: string } } type Settings = { read(request: unknown): Promise; update(request: unknown): Promise } type MethodCall = { method: string; params: { sessionId: string; [key: string]: unknown } } @@ -16,17 +16,61 @@ export const part = definePlugin({ inject: ['settings', 'sessionMethods'], async apply(ctx) { const settings = ctx.use('settings') - const events: { name: string; payload: unknown }[] = [] + let pauseDecode: (() => Promise) | undefined + const registerCustom = () => ctx.use('settings').registerDocument( + { source: 'example-custom', userFile: 'example-custom.json', projectFile: '.example-custom.json' }, + { + async decode(bytes): Promise<{ count: number }> { + await pauseDecode?.() + return bytes === null ? { count: 3 } : JSON.parse(new TextDecoder().decode(bytes)) + }, + validate(document: { count: number }) { + if (!Number.isInteger(document.count) || document.count < 0) throw new Error('invalid count') + }, + }, + ) + let custom: Awaited> + const events: { name: string; payload: JsonValue }[] = [] for (const name of ['settings/example', 'settings/projects']) { - ctx.on(name, (payload: unknown) => { events.push({ name, payload }) }) + ctx.on(name, (payload: JsonValue) => { events.push({ name, payload }) }) } await ctx.use('sessionMethods').register( 'session.example', - ['read', 'update', 'events', 'declared'].map(name => ({ + ['read', 'update', 'events', 'declared', 'custom_read', 'custom_update', 'custom_concurrent'].map(name => ({ name: `session.example.${name}`, mutating: false, interruption: 'report', progress: false, })), async (call: MethodCall) => { const { sessionId: _, ...request } = call.params + if (call.method.endsWith('.custom_read')) { + custom ??= await registerCustom() + return { kind: 'value', value: await custom.read('user') } + } + if (call.method.endsWith('.custom_concurrent')) { + if (typeof request.root !== 'number') throw new Error('expected project root') + const scope = { project: request.root } + const original = await custom.read(scope) + if (!original.ok) throw new Error(original.error.message) + let entered!: () => void + let release!: () => void + const decoding = new Promise(resolve => { entered = resolve }) + const released = new Promise(resolve => { release = resolve }) + pauseDecode = () => { entered(); return released } + const reader = Promise.resolve(custom.read(scope)) + try { + await decoding + const stale = await custom.update(scope, 'stale', { count: 7 }) + const written = await custom.update(scope, original.value.revision, { count: 8 }) + return { kind: 'value', value: { stale, written } } + } finally { + pauseDecode = undefined + release() + await reader + } + } + if (call.method.endsWith('.custom_update')) { + if (typeof request.expectedRevision !== 'string' || typeof request.count !== 'number') throw new Error('expected revision and count') + return { kind: 'value', value: await custom.update('user', request.expectedRevision, { count: request.count }) } + } if (call.method.endsWith('.declared')) { if (typeof request.instanceId !== 'string') throw new Error('expected instanceId') return { kind: 'value', value: ctx.use('settings').declaredBy({ instanceId: request.instanceId }) }