From 97fc30e58cbe83a93c10d216e00dde23b5ef7f87 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 17:27:27 +0800 Subject: [PATCH 01/37] feat(runtime): route calls by id to a live Session or line A caller outside a scope holds no instance key. The runtime now keeps the Sessions its Agents publish and the lines each Session created, and resolves `sessionId` or `(sessionId, branchId)` to the instance that is live now, so a call reaches the target owner's data face directly: - Rust parts call the face they asked for (session_owner/line_owner); - another language calls the same route by name (session/line). Routing answers NoSession for a Session that was idle-unloaded, closed or never existed, SessionClosing while the Session closes (its lines answer it too), and NoLine for a line that is closing, closed or another Session's. It refuses mechanism registration points and scope lifecycle services. Refs #2015 Refs #2127 --- .../tests/capabilities_flow.rs | 1 + .../tests/routing_flow.rs | 310 ++++++++++++++++++ crates/dim-agent-runtime/src/agent.rs | 13 +- crates/dim-agent-runtime/src/assembly.rs | 63 +++- crates/dim-agent-runtime/src/error.rs | 24 ++ crates/dim-agent-runtime/src/lib.rs | 2 + crates/dim-agent-runtime/src/names.rs | 1 + crates/dim-agent-runtime/src/route.rs | 285 ++++++++++++++++ crates/dim-agent-runtime/src/testing.rs | 5 +- .../dim-agent-runtime/src/timeline_context.rs | 9 + 10 files changed, 693 insertions(+), 20 deletions(-) create mode 100644 crates/dim-agent-capabilities/tests/routing_flow.rs create mode 100644 crates/dim-agent-runtime/src/route.rs diff --git a/crates/dim-agent-capabilities/tests/capabilities_flow.rs b/crates/dim-agent-capabilities/tests/capabilities_flow.rs index 9c62c91b02..399df0ed82 100644 --- a/crates/dim-agent-capabilities/tests/capabilities_flow.rs +++ b/crates/dim-agent-capabilities/tests/capabilities_flow.rs @@ -28,5 +28,6 @@ mod model_stream_recovery_flow; mod permission_flow; mod recall_flow; mod review_flows; +mod routing_flow; mod session_extension; mod workspace_files; diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs new file mode 100644 index 0000000000..3618ad0a78 --- /dev/null +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -0,0 +1,310 @@ +//! Flow: a call by id reaches the data face of a live Session or line, and +//! answers `NoSession`, `SessionClosing` or `NoLine` otherwise +//! ([#2127](https://github.com/arcships/dim/issues/2127)). + +use dim_agent_capabilities::{defaults, methods::SessionMethods}; +use dim_agent_runtime::testing::{MinimalHost, hold_close}; +use dim_agent_runtime::*; +use dim_agent_types::BranchSource; +use rutis::Ctx; +use rutis::host::CtxHost; +use rutis_bridge::session::{ + Connection, Dispatch, Endpoint, Error as BridgeError, HostDispatch, Reply, Value, host_key, +}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +fn builder() -> AgentBuilder { + let mut builder = AgentBuilder::new(AgentConfig::default()); + builder.timeline_store(TimelineStoreBinding::new(Arc::new( + MemoryTimelineStore::default(), + ))); + defaults::mock_hosts(&mut builder); + defaults::install(&mut builder); + builder +} + +async fn open(host: &MinimalHost) -> Session { + host.create_session(SessionConfig::default()) + .await + .expect("a Session opens") +} + +/// A language runtime's side of a rutis session: it names a service, and the +/// host serves it. +struct Names(Ctx); + +impl Dispatch for Names { + fn invoke(&self, _: &Connection, target: &str, method: &str, args: Value) -> Reply { + self.0 + .get_at::(&host_key(target)) + .unwrap_or_else(|| panic!("{target} is not served")) + .invoke(method, args) + } +} + +/// Both ends of a rutis session with the host's tree, kept open by the test. +struct Language { + _host: Connection, + client: Connection, +} + +impl Language { + fn open(root: &Ctx) -> Self { + let (host, far) = rutis_bridge::memory::pair(); + let peer = |id: &str| Endpoint::rust(rutis_bridge::channel::PeerId::new(id).unwrap()); + let host = + Connection::open(host, Arc::new(Names(root.clone())), peer("route-host")).unwrap(); + let client = + Connection::open(far, Arc::new(Names(root.clone())), peer("route-client")).unwrap(); + Self { + _host: host, + client, + } + } + + async fn call( + &self, + method: &str, + call: impl serde::Serialize, + ) -> std::result::Result { + let call: Value = serde_json::to_value(call).unwrap().into(); + let reply = self + .client + .invoke_settled("route", method, Value::List(vec![call])) + .unwrap(); + tokio::time::timeout(Duration::from_secs(30), reply) + .await + .expect("the far end answers")? + .json() + } + + async fn refused(&self, method: &str, call: impl serde::Serialize) -> String { + let error = self + .call(method, call) + .await + .expect_err("the route refuses the call"); + error.to_string() + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_call_by_id_reaches_the_live_session_and_line() { + let builder = builder(); + let route = builder.route(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + + let config = route.session_owner::(&id).unwrap(); + assert_eq!( + serde_json::to_value(config.as_ref()).unwrap(), + serde_json::to_value(session.config()).unwrap(), + "the Session route reads the Session's own face" + ); + let loop_state = route + .line_owner::(&id, "main") + .expect("the main line's face"); + assert_eq!(loop_state.state().phase, LoopPhase::Idle); + + assert!(matches!( + route.session_owner::("absent"), + Err(AgentError::NoSession(absent)) if absent == "absent" + )); + assert!(matches!( + route.line_owner::(&id, "absent"), + Err(AgentError::NoLine(line)) if line == format!("{id}/absent") + )); + + let named = route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .unwrap(); + assert_eq!( + named, + serde_json::to_value(session.config()).unwrap(), + "naming the face reaches what holding it does" + ); + host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_language_call_reaches_a_line_face_through_the_route() { + let builder = builder(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + let language = Language::open(host.root()); + language.client.ready().await.unwrap(); + + let call = LineFaceCall::new(&id, "main", "timeline", "sequence", vec![]); + let sequence = language.call("line", call).await.unwrap(); + assert_eq!( + sequence, + serde_json::json!(session.sequence("main").unwrap()), + "the routed call reads the line's own face" + ); + let missing = LineFaceCall::new(&id, "absent", "timeline", "sequence", vec![]); + let error = language.refused("line", missing).await; + assert!(error.contains("no line"), "{error}"); + host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_idle_unloaded_session_answers_no_session_until_it_loads_again() { + let builder = builder(); + let route = builder.route(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + + assert!( + session.unload_if_idle().await.unwrap(), + "an idle Session unloads" + ); + assert!(matches!( + route.session_owner::(&id), + Err(AgentError::NoSession(absent)) if absent == id + )); + + let restored = host.restore_session(id.clone()).await.unwrap(); + assert!(route.session_owner::(&id).is_ok()); + assert!(route.line_owner::(&id, "main").is_ok()); + restored.close().await.unwrap(); + host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_session_closed_by_business_answers_no_session_and_keeps_no_instance_to_hold() { + let builder = builder(); + let route = builder.route(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + + session.close().await.unwrap(); + assert!(matches!( + route.session_owner::(&id), + Err(AgentError::NoSession(absent)) if absent == id + )); + assert!( + host.get_session(&id).is_none(), + "a closed Session has no live instance for a hold to keep" + ); + host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_closing_session_answers_session_closing_for_its_lines_too() { + let builder = builder(); + let route = builder.route(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + let mut held = hold_close(&id, "main"); + let closing = { + let session = session.clone(); + tokio::spawn(async move { session.close().await }) + }; + held.arrived().await; + + assert!(matches!( + route.session_owner::(&id), + Err(AgentError::SessionClosing(closing)) if closing == id + )); + assert!(matches!( + route.line_owner::(&id, "main"), + Err(AgentError::SessionClosing(closing)) if closing == id + )); + held.release(); + closing.await.unwrap().unwrap(); + assert!(matches!( + route.session_owner::(&id), + Err(AgentError::NoSession(absent)) if absent == id + )); + host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive() { + let builder = builder(); + let route = builder.route(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + let source = || BranchSource::Host { + operation_id: "routing".into(), + }; + let line = session + .branch( + "main".into(), + 0, + BranchOptions { + prompt: "a line the route reaches".into(), + source: source(), + }, + ) + .await + .unwrap(); + assert!(route.line_owner::(&id, &line).is_ok()); + + session.end_branch(&line, source()).await.unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + while !matches!( + route.line_owner::(&id, &line), + Err(AgentError::NoLine(_)) + ) { + assert!(Instant::now() < deadline, "the ended line closes"); + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!( + route.session_owner::(&id).is_ok(), + "one line's end does not affect the Session's other calls" + ); + assert!(route.line_owner::(&id, "main").is_ok()); + host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn routing_refuses_registration_points_and_lifecycle_services() { + let builder = builder(); + let route = builder.route(); + let host = MinimalHost::start(&builder).await.unwrap(); + let session = open(&host).await; + let id = session.id().to_owned(); + + let refused = route + .session_owner::(&id) + .err() + .expect("a registration point is not routable"); + assert!( + matches!(&refused, AgentError::InvalidInput(_)), + "{refused:?}" + ); + assert!(refused.to_string().contains("sessionMethods"), "{refused}"); + for service in [ + "sessionMethods", + "toolRegistry", + "sessionLifecycle", + "branchLifecycle", + ] { + let error = route + .session(SessionFaceCall::new(&id, service, "register", vec![])) + .await + .expect_err("the route refuses the name"); + assert!( + matches!(&error, AgentError::InvalidInput(_)), + "{service}: {error:?}" + ); + assert!(error.to_string().contains(service), "{service}: {error}"); + } + let process = route + .session_owner::(&id) + .err() + .expect("a line service is not a Session face"); + assert!( + process.to_string().contains("not a session service"), + "{process}" + ); + host.close().await.unwrap(); +} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 6394eedb1a..21e34fa99f 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -499,6 +499,11 @@ impl Session { /// begin the background work they deferred during assembly. fn activate(&self) { self.0.owner.lifecycle.advance(SessionPhase::Active); + self.0 + .owner + .assembly + .route + .register(self.id(), Arc::downgrade(&self.0.owner)); let weak = Arc::downgrade(&self.0); let mut faults = self.0.owner.lifecycle.faults.watch(); let stop = self.0.owner.closing.clone(); @@ -744,12 +749,7 @@ impl Session { /// Reads a service of the Session group from the currently loaded /// Session subtree. pub fn session_service(&self) -> Result> { - crate::names::in_group::(&self.0.owner.assembly.catalog, SESSION_GROUP)?; - let loaded = self.0.owner.loaded()?; - loaded - .ctx - .get_at::(&loaded.scope.key::()) - .ok_or_else(|| AgentError::Reloading(std::any::type_name::().into())) + self.0.owner.session_face::() } /// The instance of the loaded Session subtree, so a host can find the /// loader rows this Session runs. Keys under it stay readable only from @@ -924,6 +924,7 @@ impl Session { store.remove_session(this.id()); } } + this.0.owner.assembly.route.forget(this.id(), &this.0.owner); *this.0.owner.loaded.lock().unwrap() = None; span.record( "outcome", diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index da3a3782ba..f71ce7cba8 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -290,6 +290,9 @@ pub(crate) struct Assembly { /// The parts plugins register: the builder's, for the host that builds /// its Agents ([`AgentBuilder::build`]); the minimal host takes a fresh one. pub parts: Arc, + /// The Sessions this builder's Agents publish, for calls by id + /// ([`AgentBuilder::route`]). + pub route: Arc, /// Registered parts the profile requires, by name. required_parts: Arc>, /// The rows a Session and a branch need Active, as [`AgentBuilder::install`] @@ -361,6 +364,7 @@ impl AgentBuilder { features: Default::default(), optional_plugins: Default::default(), parts: Arc::default(), + route: Arc::default(), required_parts: Arc::default(), required_rows: Arc::default(), extensions: vec![], @@ -421,6 +425,15 @@ impl AgentBuilder { pub fn parts(&self) -> Arc { self.assembly.parts.clone() } + /// The route from ids to the live Sessions this builder's Agents publish + /// ([`Route`]): [`Self::plugin_rows`] provides it to the host's process + /// plugins as `route`, so a process part reaches a Session of any of those + /// Agents by id. Rust parts call the owner's data face directly + /// ([`Route::session_owner`], [`Route::line_owner`]); another language + /// calls the same route by that name. + pub fn route(&self) -> Arc { + self.assembly.route.clone() + } /// Adds a process plugin: `make` builds it from the names its /// dependencies resolve to at the process, usually /// `|names| Ok(Box::new(MyPlugin::new(names)?))`. The host places it as @@ -491,13 +504,21 @@ impl AgentBuilder { key: names.key()?, })) }); + let route = self.assembly.route.clone(); + let route: PartMake = Arc::new(move |names| { + Ok(Box::new(crate::route::RoutePlugin { + route: route.clone(), + key: names.key()?, + })) + }); let mut rows = vec![]; let mut optional_rows = vec![]; - let optional = std::iter::once(false).chain( + let optional = std::iter::once(false).chain(std::iter::once(false)).chain( (0..self.assembly.plugins.len()) .map(|index| self.assembly.optional_plugins.contains(&index)), ); for (make, optional) in std::iter::once(®istry) + .chain(std::iter::once(&route)) .chain(&self.assembly.plugins) .zip(optional) { @@ -817,12 +838,6 @@ impl AgentBuilder { builder.assembly.parts = Arc::default(); builder } - /// Whether plugins were added ([`Self::plugin`]); a host without any - /// places no process rows. - #[cfg(feature = "testing")] - pub(crate) fn has_plugins(&self) -> bool { - !self.assembly.plugins.is_empty() - } /// The longest a host waits for its assembly without progress. #[cfg(feature = "testing")] pub(crate) fn opening_timeout(&self) -> Duration { @@ -1142,6 +1157,9 @@ pub(crate) struct SessionAssembly { /// The views its scope mounted when it opened, until its creation ends. pub(crate) handed: Mutex, pub(crate) copies: crate::parts::Copies, + /// The line instances this Session's tree created, by id. An entry whose + /// context is gone, closing or closed resolves to no line. + lines: Mutex>>, } impl SessionAssembly { pub(crate) fn loaded(&self) -> Result>> { @@ -1151,6 +1169,28 @@ impl SessionAssembly { .clone() .ok_or_else(|| AgentError::Closed(self.id.clone())) } + + /// The Session-scope data face `T` of the loaded Session subtree. + pub(crate) fn session_face(&self) -> Result> { + crate::names::in_group::(&self.assembly.catalog, SESSION_GROUP)?; + let loaded = self.loaded()?; + loaded + .ctx + .get_at::(&loaded.scope.key::()) + .ok_or_else(|| AgentError::Reloading(std::any::type_name::().into())) + } + + /// Records the line instance `id` only while it is live. + pub(crate) fn register_line(&self, id: &str, line: Weak) { + self.lines.lock().unwrap().insert(id.to_owned(), line); + } + + /// The live line instance `id`, or `None` when this Session never created + /// it, it is gone, or it is closing. + pub(crate) fn line(&self, id: &str) -> Option> { + let line = self.lines.lock().unwrap().get(id).and_then(Weak::upgrade)?; + (!line.is_closing()).then_some(line) + } } struct SessionScopePlugin { @@ -1502,8 +1542,8 @@ impl TimelineFactory { let ctx = &branch.scope.ctx; let scope = branch.scope.scope; required::(ctx, scope.key::())?; - Ok(TimelineContext::start( - id, + let context = TimelineContext::start( + id.clone(), ctx.clone(), created.view.clone(), created.children.clone(), @@ -1521,7 +1561,9 @@ impl TimelineFactory { branch.lifecycle.clone(), parent.lifecycle.faults.clone(), parent.assembly.catalog.clone(), - )) + ); + parent.register_line(&id, Arc::downgrade(&context)); + Ok(context) }) .catch_unwind() .await @@ -1887,6 +1929,7 @@ pub(crate) async fn build_session( mounted: Arc::default(), handed: Mutex::default(), copies: Arc::default(), + lines: Mutex::default(), }); let instance = |owner: &Arc| { let owner = owner.clone(); diff --git a/crates/dim-agent-runtime/src/error.rs b/crates/dim-agent-runtime/src/error.rs index bb217fa81c..4bd5c5ec05 100644 --- a/crates/dim-agent-runtime/src/error.rs +++ b/crates/dim-agent-runtime/src/error.rs @@ -10,6 +10,21 @@ pub enum AgentError { Closed(String), #[error("unknown branch: {0}")] UnknownBranch(String), + /// Routing by id ([`Route`](crate::Route)): the Session has no live + /// instance, because it was idle-unloaded, closed or never existed. Only a + /// process caller receives it; a caller that must continue asks Agents for + /// a hold, and calls again once that loads the Session. + #[error("no live Session {0}")] + NoSession(String), + /// Routing by id: the Session instance is closing, and so is any call to a + /// line of it. A Session-scoped caller ends its work; a process caller + /// treats it as [`Self::NoSession`]. + #[error("Session {0} is closing")] + SessionClosing(String), + /// Routing by id: the Session is live but the line is closing, closed, or + /// not one of its lines. Final for that line: no hold, no retry. + #[error("no line {0}")] + NoLine(String), /// The line has ended: it accepts no input and no new operation. #[error("branch has ended: {0}")] BranchEnded(String), @@ -56,6 +71,9 @@ pub enum SessionFault { InvalidInput(String), Closed(String), UnknownBranch(String), + NoSession(String), + SessionClosing(String), + NoLine(String), BranchEnded(String), BranchRefused { refusal: BranchRefusal, @@ -81,6 +99,9 @@ impl From for SessionFault { AgentError::InvalidInput(value) => Self::InvalidInput(value), AgentError::Closed(value) => Self::Closed(value), AgentError::UnknownBranch(value) => Self::UnknownBranch(value), + AgentError::NoSession(value) => Self::NoSession(value), + AgentError::SessionClosing(value) => Self::SessionClosing(value), + AgentError::NoLine(value) => Self::NoLine(value), AgentError::BranchEnded(value) => Self::BranchEnded(value), AgentError::BranchRefused { refusal, message } => { Self::BranchRefused { refusal, message } @@ -106,6 +127,9 @@ impl From for AgentError { SessionFault::InvalidInput(value) => Self::InvalidInput(value), SessionFault::Closed(value) => Self::Closed(value), SessionFault::UnknownBranch(value) => Self::UnknownBranch(value), + SessionFault::NoSession(value) => Self::NoSession(value), + SessionFault::SessionClosing(value) => Self::SessionClosing(value), + SessionFault::NoLine(value) => Self::NoLine(value), SessionFault::BranchEnded(value) => Self::BranchEnded(value), SessionFault::BranchRefused { refusal, message } => { Self::BranchRefused { refusal, message } diff --git a/crates/dim-agent-runtime/src/lib.rs b/crates/dim-agent-runtime/src/lib.rs index 97bd574881..60ce2391c1 100644 --- a/crates/dim-agent-runtime/src/lib.rs +++ b/crates/dim-agent-runtime/src/lib.rs @@ -12,6 +12,7 @@ mod memory_timeline_store; pub mod names; mod parts; mod registrations; +mod route; mod scope; mod state; #[cfg(feature = "testing")] @@ -35,6 +36,7 @@ pub use memory_timeline_store::*; pub use names::Names; pub use parts::{Feature, Generator, Mount, PartRegistry, PartScope}; pub use registrations::{Registration, Registrations}; +pub use route::*; pub use rutis::host::BoxFuture; pub use scope::*; pub use state::*; diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index 5986b784d0..d5bd10a3d0 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -93,6 +93,7 @@ pub fn register( pub fn catalog() -> ServiceCatalog { let mut catalog = ServiceCatalog::new(); register::(&mut catalog, None); + register::(&mut catalog, None); let session = Some(SESSION_GROUP); register::(&mut catalog, session); catalog.register_shared_instance(name_of::(), SESSION_GROUP); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs new file mode 100644 index 0000000000..229703da5a --- /dev/null +++ b/crates/dim-agent-runtime/src/route.rs @@ -0,0 +1,285 @@ +//! Calls by id to a live owner's data face ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1–D4, [#2127](https://github.com/arcships/dim/issues/2127)). +//! +//! A caller outside a scope holds no instance key, so it names what it wants +//! instead: the [`Route`] resolves `sessionId`, or `sessionId` and a line id, +//! to the instance that is live now and reads the named owner's face there. +//! Rust calls the face directly ([`Route::session_owner`], +//! [`Route::line_owner`]); another language calls the same route by name +//! ([`Route::session`], [`Route::line`]). Neither declares the inner group's +//! names, and an instance key never leaves the instance. +//! +//! What a route resolves is the target scope's data face in the catalog: not a +//! mechanism registration point, whose entries belong to the registering +//! generation, and not a scope lifecycle service. Everything else about the +//! call belongs to the owner: the route passes the method and its arguments +//! through and returns the owner's reply or error unchanged. A target that has +//! no instance answers [`AgentError::NoSession`] (idle-unloaded, closed or +//! unknown), a Session that is closing answers [`AgentError::SessionClosing`], +//! and a line that is closing, closed or not the Session's answers +//! [`AgentError::NoLine`]. + +use crate::*; +use rutis::Ctx; +use rutis::host::CtxHost; +use rutis_bridge::session::{ + HostDispatch, Value as BridgeValue, decode_value, host_key_in, settle, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex, Weak}, +}; + +/// Names routing does not resolve: the mechanism's registration points, whose +/// entries belong to the part that registered them and are reachable only +/// inside that generation ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) +/// D3), and the scope lifecycle services the runtime provides. +const REGISTRATION_POINTS: [&str; 7] = [ + "partRegistry", + "managementMethods", + "sessionMethods", + "toolRegistry", + "promptRegistry", + "guideEntries", + "submitChecks", +]; + +/// The call routing makes to a Session-scope data face. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionFaceCall { + pub session_id: String, + pub service: String, + pub method: String, + /// The method's arguments, in order, as the calling language writes them. + #[serde(default)] + pub args: Vec, +} + +impl SessionFaceCall { + /// The call to `service.method(args...)` in the live Session `session_id`. + pub fn new( + session_id: impl Into, + service: impl Into, + method: impl Into, + args: Vec, + ) -> Self { + Self { + session_id: session_id.into(), + service: service.into(), + method: method.into(), + args, + } + } +} + +/// The call routing makes to a line-scope data face. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LineFaceCall { + pub session_id: String, + pub line_id: String, + pub service: String, + pub method: String, + /// The method's arguments, in order, as the calling language writes them. + #[serde(default)] + pub args: Vec, +} + +impl LineFaceCall { + /// The call to `service.method(args...)` in the line `line_id` of the live + /// Session `session_id`. + pub fn new( + session_id: impl Into, + line_id: impl Into, + service: impl Into, + method: impl Into, + args: Vec, + ) -> Self { + Self { + session_id: session_id.into(), + line_id: line_id.into(), + service: service.into(), + method: method.into(), + args, + } + } +} + +/// Calls by id to the scope a live instance owns (module docs). +/// +/// One `Route` serves every Agent of one host: each Agent registers the +/// Sessions it publishes, so a process part reaches a Session of any Agent. +/// Rust parts read it as the process name `route` and call the owner's face +/// directly; a language runtime or a UI leaf calls [`Self::session`] or +/// [`Self::line`] by that name instead. +pub struct Route { + sessions: Mutex>>, +} + +impl Default for Route { + fn default() -> Self { + Self { + sessions: Mutex::new(BTreeMap::new()), + } + } +} + +impl std::fmt::Debug for Route { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let sessions = self.sessions.lock().unwrap(); + let ids: Vec<&String> = sessions.keys().collect(); + f.debug_struct("Route").field("sessions", &ids).finish() + } +} + +impl Route { + /// The Session-scope data face `T` of the live Session `session_id`. + pub fn session_owner(&self, session_id: &str) -> Result> { + routable(&names::name_of::())?; + self.resolve_session(session_id)?.session_face::() + } + + /// The line-scope data face `T` of `line_id` in the live Session + /// `session_id`. + pub fn line_owner( + &self, + session_id: &str, + line_id: &str, + ) -> Result> { + routable(&names::name_of::())?; + self.resolve_line(session_id, line_id)?.public::() + } + + /// Registers a Session that is publishing, for as long as its instance + /// lives. + pub(crate) fn register(&self, id: &str, session: Weak) { + self.sessions.lock().unwrap().insert(id.to_owned(), session); + } + + /// Forgets `session`'s registration of `id`, unless a later Session took + /// the id over. + pub(crate) fn forget(&self, id: &str, session: &Arc) { + let mut sessions = self.sessions.lock().unwrap(); + let registered = sessions + .get(id) + .is_some_and(|registered| Weak::ptr_eq(registered, &Arc::downgrade(session))); + if registered { + sessions.remove(id); + } + } + + fn resolve_session(&self, id: &str) -> Result> { + let session = self + .sessions + .lock() + .unwrap() + .get(id) + .and_then(Weak::upgrade) + .ok_or_else(|| AgentError::NoSession(id.into()))?; + if session.closing.is_cancelled() { + return Err(AgentError::SessionClosing(id.into())); + } + Ok(session) + } + + fn resolve_line(&self, session_id: &str, line_id: &str) -> Result> { + let session = self.resolve_session(session_id)?; + session + .line(line_id) + .ok_or_else(|| AgentError::NoLine(format!("{session_id}/{line_id}"))) + } +} + +#[rutis::service] +impl Route { + /// Calls a Session-scope data face: [`Route::session_owner`] for a + /// language that names the face instead of holding it. + pub async fn session(&self, call: SessionFaceCall) -> Result { + routable(&call.service)?; + let session = self.resolve_session(&call.session_id)?; + let loaded = session.loaded()?; + call_face( + &loaded.ctx, + loaded.scope.instance, + &call.service, + &call.method, + &call.args, + ) + .await + } + + /// Calls a line-scope data face: [`Route::line_owner`] for a language that + /// names the face instead of holding it. + pub async fn line(&self, call: LineFaceCall) -> Result { + routable(&call.service)?; + let line = self.resolve_line(&call.session_id, &call.line_id)?; + call_face( + line.ctx(), + line.scope_instance(), + &call.service, + &call.method, + &call.args, + ) + .await + } +} + +/// Fails unless routing may resolve `service` (module docs). +fn routable(service: &str) -> Result<()> { + let lifecycle = [ + names::name_of::(), + names::name_of::(), + ]; + if REGISTRATION_POINTS.contains(&service) || lifecycle.iter().any(|name| name == service) { + return Err(AgentError::InvalidInput(format!( + "route: {service} is not a routable service" + ))); + } + Ok(()) +} + +/// Calls `method` of the data face `service` in `instance`, as another +/// language would: the arguments travel as data and the reply comes back as +/// data. +async fn call_face( + ctx: &Ctx, + instance: rutis::host::InstanceId, + service: &str, + method: &str, + args: &[serde_json::Value], +) -> Result { + let dispatch = ctx + .get_at::(&host_key_in(service, instance)) + .ok_or_else(|| AgentError::Reloading(service.into()))?; + let args = BridgeValue::List( + args.iter() + .map(|arg| BridgeValue::Data(arg.clone())) + .collect(), + ); + let reply = dispatch + .invoke(method, args) + .map_err(|error| AgentError::fault(service, error.to_string()))?; + let value = settle(reply) + .await + .map_err(|error| AgentError::fault(service, error.to_string()))?; + decode_value::(value) + .map_err(|error| AgentError::fault(service, error.to_string())) +} + +/// Provides the host's [`Route`] at the process name `route`. +pub(crate) struct RoutePlugin { + pub route: Arc, + pub key: rutis::host::Key, +} + +impl rutis::Plugin for RoutePlugin { + type Deps = (); + fn name(&self) -> &str { + "Route" + } + async fn apply(&self, ctx: &Ctx, (): ()) -> rutis::Result { + ctx.provide_at(self.key.clone(), self.route.clone())?; + Ok(()) + } +} diff --git a/crates/dim-agent-runtime/src/testing.rs b/crates/dim-agent-runtime/src/testing.rs index e9886789e5..482eedd9dd 100644 --- a/crates/dim-agent-runtime/src/testing.rs +++ b/crates/dim-agent-runtime/src/testing.rs @@ -332,10 +332,7 @@ async fn assemble( Factory::new(move || Box::new(AgentAnchor((*slot).clone())) as Box) }); prepare(root, &mut builtins)?; - let mut rows = match builder.has_plugins() { - true => builder.plugin_rows(&mut builtins).await?.rows, - false => vec![], - }; + let mut rows = builder.plugin_rows(&mut builtins).await?.rows; let session_row = builder.install(&mut builtins, []).await?; rows.push(builder.agent_row([row("AgentAnchor"), session_row])); let plugin = rutis_loader::LoaderPlugin::new( diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index 0e410fe6da..ec42162425 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -345,6 +345,15 @@ impl TimelineContext { pub(crate) fn scope_view(&self) -> &FiberView { &self.view } + /// The branch instance's context, for reads of its data faces by id + /// ([`Route`]). + pub(crate) fn ctx(&self) -> &Ctx { + &self.ctx + } + /// The branch group instance this line runs in. + pub(crate) fn scope_instance(&self) -> rutis::host::InstanceId { + self.scope.instance + } /// The loader row ids this branch's profile requires. pub(crate) fn required_rows(&self) -> &[String] { &self.required From e6e08014251ddf08baa8b80a3583019294dd7a02 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 18:15:58 +0800 Subject: [PATCH 02/37] feat(xtask): check the access layer and keep its allowlist MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The access-layer rules of #2015 §5 become a static check in `xtask-check`, and `xtask -- check` also fails when a catalog service a change deleted comes back: - `#[service(skip)]` on a service method; - a hand-written `HostDispatch` implementation; - a `Session` method that forwards to a line named by an argument; - the outward `Branch` type. Every violation the tree still has is listed in `xtask/access-layer.json`. A violation that is not listed fails, and so does a listed entry that matches nothing, so the list can only shrink. Its `removed` list names deleted services. The route is a process data face, so the host that shares foreign-part names shares it too. Refs #2015 Refs #2127 --- Cargo.lock | 1 + .../tests/routing_flow.rs | 4 +- crates/dim-agent-runtime/src/error.rs | 13 +- crates/dim-agent-runtime/src/route.rs | 37 +- .../dim-app-server/src/session_typescript.rs | 10 +- .../contracts/runtime-owner-operations.md | 15 +- npm/branch-services.d.ts | 49 +- tests/integration/tests/extensions.rs | 2 +- xtask/access-layer.json | 580 ++++++++++++++++++ xtask/check/Cargo.toml | 1 + xtask/check/src/access.rs | 283 +++++++++ xtask/check/src/lib.rs | 2 + 12 files changed, 950 insertions(+), 47 deletions(-) create mode 100644 xtask/access-layer.json create mode 100644 xtask/check/src/access.rs diff --git a/Cargo.lock b/Cargo.lock index fd24147d28..8d6277c385 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6113,6 +6113,7 @@ version = "0.1.0-alpha.29" dependencies = [ "proc-macro2", "rutis-types", + "serde", "serde_json", "syn 2.0.119", ] diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 3618ad0a78..dcf96046f7 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -113,7 +113,7 @@ async fn a_call_by_id_reaches_the_live_session_and_line() { )); assert!(matches!( route.line_owner::(&id, "absent"), - Err(AgentError::NoLine(line)) if line == format!("{id}/absent") + Err(AgentError::NoLine { line, .. }) if line == "absent" )); let named = route @@ -252,7 +252,7 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive let deadline = Instant::now() + Duration::from_secs(30); while !matches!( route.line_owner::(&id, &line), - Err(AgentError::NoLine(_)) + Err(AgentError::NoLine { .. }) ) { assert!(Instant::now() < deadline, "the ended line closes"); tokio::time::sleep(Duration::from_millis(10)).await; diff --git a/crates/dim-agent-runtime/src/error.rs b/crates/dim-agent-runtime/src/error.rs index 4bd5c5ec05..95d5a4a7bd 100644 --- a/crates/dim-agent-runtime/src/error.rs +++ b/crates/dim-agent-runtime/src/error.rs @@ -23,8 +23,8 @@ pub enum AgentError { SessionClosing(String), /// Routing by id: the Session is live but the line is closing, closed, or /// not one of its lines. Final for that line: no hold, no retry. - #[error("no line {0}")] - NoLine(String), + #[error("no line {line} in Session {session}")] + NoLine { session: String, line: String }, /// The line has ended: it accepts no input and no new operation. #[error("branch has ended: {0}")] BranchEnded(String), @@ -73,7 +73,10 @@ pub enum SessionFault { UnknownBranch(String), NoSession(String), SessionClosing(String), - NoLine(String), + NoLine { + session: String, + line: String, + }, BranchEnded(String), BranchRefused { refusal: BranchRefusal, @@ -101,7 +104,7 @@ impl From for SessionFault { AgentError::UnknownBranch(value) => Self::UnknownBranch(value), AgentError::NoSession(value) => Self::NoSession(value), AgentError::SessionClosing(value) => Self::SessionClosing(value), - AgentError::NoLine(value) => Self::NoLine(value), + AgentError::NoLine { session, line } => Self::NoLine { session, line }, AgentError::BranchEnded(value) => Self::BranchEnded(value), AgentError::BranchRefused { refusal, message } => { Self::BranchRefused { refusal, message } @@ -129,7 +132,7 @@ impl From for AgentError { SessionFault::UnknownBranch(value) => Self::UnknownBranch(value), SessionFault::NoSession(value) => Self::NoSession(value), SessionFault::SessionClosing(value) => Self::SessionClosing(value), - SessionFault::NoLine(value) => Self::NoLine(value), + SessionFault::NoLine { session, line } => Self::NoLine { session, line }, SessionFault::BranchEnded(value) => Self::BranchEnded(value), SessionFault::BranchRefused { refusal, message } => { Self::BranchRefused { refusal, message } diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 229703da5a..be4fb157de 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -30,13 +30,12 @@ use std::{ sync::{Arc, Mutex, Weak}, }; -/// Names routing does not resolve: the mechanism's registration points, whose -/// entries belong to the part that registered them and are reachable only -/// inside that generation ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) -/// D3), and the scope lifecycle services the runtime provides. -const REGISTRATION_POINTS: [&str; 7] = [ - "partRegistry", - "managementMethods", +/// Names routing does not resolve: the mechanism's registration points in the +/// groups it resolves, whose entries belong to the part that registered them +/// and are reachable only inside that generation +/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md)), and the +/// scope lifecycle services the runtime provides. +const REGISTRATION_POINTS: [&str; 5] = [ "sessionMethods", "toolRegistry", "promptRegistry", @@ -113,26 +112,11 @@ impl LineFaceCall { /// Rust parts read it as the process name `route` and call the owner's face /// directly; a language runtime or a UI leaf calls [`Self::session`] or /// [`Self::line`] by that name instead. +#[derive(Default)] pub struct Route { sessions: Mutex>>, } -impl Default for Route { - fn default() -> Self { - Self { - sessions: Mutex::new(BTreeMap::new()), - } - } -} - -impl std::fmt::Debug for Route { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let sessions = self.sessions.lock().unwrap(); - let ids: Vec<&String> = sessions.keys().collect(); - f.debug_struct("Route").field("sessions", &ids).finish() - } -} - impl Route { /// The Session-scope data face `T` of the live Session `session_id`. pub fn session_owner(&self, session_id: &str) -> Result> { @@ -185,9 +169,10 @@ impl Route { fn resolve_line(&self, session_id: &str, line_id: &str) -> Result> { let session = self.resolve_session(session_id)?; - session - .line(line_id) - .ok_or_else(|| AgentError::NoLine(format!("{session_id}/{line_id}"))) + session.line(line_id).ok_or_else(|| AgentError::NoLine { + session: session_id.to_owned(), + line: line_id.to_owned(), + }) } } diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index e941fb1859..5837b08bd1 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -92,9 +92,10 @@ fn crossing_instance_names() -> [(String, &'static str); 17] { /// The names a host of foreign parts shares across languages beyond those /// the catalog already shares: the marked Session and branch services, the /// tool, method and guide-entry registries, with which a part of any -/// language registers its contributions, and the part registry, with which a -/// plugin registers its parts. The generated catalog (`xtask graph`) shares -/// them the same way. +/// language registers its contributions, the part registry, with which a +/// plugin registers its parts, and the route, which names a live Session or +/// line by id ([`Route`](dim_agent_runtime::Route)). The generated catalog +/// (`xtask graph`) shares them the same way. pub fn share_names(catalog: &mut ServiceCatalog) { for (name, group) in crossing_instance_names() { catalog.register_shared_instance(name, group); @@ -105,7 +106,8 @@ pub fn share_names(catalog: &mut ServiceCatalog) { .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared(name_of::()) - .register_shared(name_of::()); + .register_shared(name_of::()) + .register_shared(name_of::()); } /// The runtimes of other languages and their loader rows, each with a diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 6bb93141c4..9fe238b369 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -32,14 +32,13 @@ ### Calls from a Session to a selected branch -Within a branch, inject its owner face directly. For Session callers the existing -`timelineTree` face gains `call({branchId,operation}, cancelled) → operation reply`. -TimelineTree resolves the admitted live branch once using its existing branch lookup and -dispatches on that branch instance. The operation is a tagged union of the calls below; -Direct variants use the owner method's arguments, reply and error. The compact RPC variant below returns the existing settled client result. The Session caller gets data. -Ended and unknown branches retain their original errors. Calls admitted before close stay -with that generation. Tree history, directory and batch input continue to use the tree's -own methods. +Within a branch, inject its owner face directly. A Session caller names the line and the +owner's face, and the runtime routes the call to that line's live instance +([#2127](https://github.com/arcships/dim/issues/2127), +[ADR 027](../../adr/027-cross-scope-access-by-id.md)): the owner's arguments, reply and +error reach the caller unchanged, and a line that is closing, closed or not this +Session's answers `NoLine`, which is final for that line. Tree history, directory and +batch input continue to use the tree's own methods. | Session caller | Target operation | | --- | --- | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 506d28a64c..263545c243 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1251,6 +1251,9 @@ export type SessionFault = | { invalidInput: string } | { closed: string } | { unknownBranch: string } + | { noSession: string } + | { sessionClosing: string } + | { noLine: { session: string; line: string } } | { branchEnded: string } | { branchRefused: { refusal: BranchRefusal; message: string } } | { storage: string } @@ -1403,6 +1406,49 @@ export interface PartRegistry { registerDefinition(scope: PartScope, name: string, definition: import('@arcships/rutis').Plugin | ((ctx: any, config: any) => unknown) | { apply(ctx: any, config: any): unknown }): Promise } +/** The call routing makes to a Session-scope data face. */ +export type SessionFaceCall = { + sessionId: string + service: string + method: string + /** The method's arguments, in order, as the calling language writes them. */ + args?: import('./plugin.js').BridgeJsonValue[] +} + +/** The call routing makes to a line-scope data face. */ +export type LineFaceCall = { + sessionId: string + lineId: string + service: string + method: string + /** The method's arguments, in order, as the calling language writes them. */ + args?: import('./plugin.js').BridgeJsonValue[] +} + +/** + * Calls by id to the scope a live instance owns (module docs). + * + * One `Route` serves every Agent of one host: each Agent registers the + * Sessions it publishes, so a process part reaches a Session of any Agent. + * Rust parts read it as the process name `route` and call the owner's face + * directly; a language runtime or a UI leaf calls [`Self::session`] or + * [`Self::line`] by that name instead. + */ +export interface Route { + /** + * Calls a Session-scope data face: [`Route::session_owner`] for a + * language that names the face instead of holding it. + * @throws {AgentErrorThrown} + */ + session(call: SessionFaceCall): Promise + /** + * Calls a line-scope data face: [`Route::line_owner`] for a language that + * names the face instead of holding it. + * @throws {AgentErrorThrown} + */ + line(call: LineFaceCall): Promise +} + export type SessionInstanceDefinition = { group: string definitionId: string @@ -1740,7 +1786,7 @@ export interface UiResources { } /** What a method returning `Err(AgentError)` throws. */ -export type AgentErrorThrown = RustError<"AgentError", "InvalidInput" | "Closed" | "UnknownBranch" | "BranchEnded" | "BranchRefused" | "Storage" | "PublicationUnknown" | "Build" | "Cancelled" | "Reloading" | "AmbiguousSubmission" | "PartialSubmission" | "Fault" | "Framework" | "Multiple", undefined> +export type AgentErrorThrown = RustError<"AgentError", "InvalidInput" | "Closed" | "UnknownBranch" | "NoSession" | "SessionClosing" | "NoLine" | "BranchEnded" | "BranchRefused" | "Storage" | "PublicationUnknown" | "Build" | "Cancelled" | "Reloading" | "AmbiguousSubmission" | "PartialSubmission" | "Fault" | "Framework" | "Multiple", undefined> /** What a method returning `Err(ApprovalRespondError)` throws. */ export type ApprovalRespondErrorThrown = RustError<"ApprovalRespondError", "Unknown" | "Cancelled" | "Closed", undefined> @@ -1820,6 +1866,7 @@ export interface Services { dispatcher: Dispatcher timeline: Timeline partRegistry: PartRegistry + route: Route sessionLoader: SessionLoader sessionPermissions: SessionPermissions collaborationConfig: CollaborationConfig diff --git a/tests/integration/tests/extensions.rs b/tests/integration/tests/extensions.rs index 21e8c50d22..b959525369 100644 --- a/tests/integration/tests/extensions.rs +++ b/tests/integration/tests/extensions.rs @@ -1280,7 +1280,7 @@ async fn closed_session_and_branch_subtrees_leave_no_plugins_or_bindings() { let counts = (diagnostics.plugins.len(), diagnostics.bindings.len()); assert_eq!(*baseline.get_or_insert(counts), counts, "round {round}"); } - assert_eq!(baseline, Some((19, 8))); + assert_eq!(baseline, Some((20, 10))); agent.close().await.unwrap(); } diff --git a/xtask/access-layer.json b/xtask/access-layer.json new file mode 100644 index 0000000000..a55a8279e1 --- /dev/null +++ b/xtask/access-layer.json @@ -0,0 +1,580 @@ +{ + "allow": [ + { + "kind": "branch-type", + "file": "crates/dim-agent-runtime/src/branch.rs", + "item": "Branch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/auxiliary_model.rs", + "item": "AuxiliaryModel" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/execution_settings.rs", + "item": "ExecutionSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/file_storage/face.rs", + "item": "FsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "ModelSelectionHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "PromptHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "SelectableModelsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/input_queue/face.rs", + "item": "SubmitChecks" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/methods.rs", + "item": "ForeignMethods" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "CommandRules" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_guide.rs", + "item": "ForeignGuideEntries" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_registry.rs", + "item": "PromptRegistry" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", + "item": "BasePromptSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/prompt_suggestion.rs", + "item": "PromptSuggestionSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/session_files.rs", + "item": "SessionFiles" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/skills/face.rs", + "item": "SkillsCatalog" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/skills/mod.rs", + "item": "SkillsInstructionsSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/skills/session.rs", + "item": "SkillsBranch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/summary_strategy.rs", + "item": "SummaryPromptSettingsHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/tool_registry.rs", + "item": "ForeignRegistry" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/tool_registry.rs", + "item": "ToolSourcesView" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-capabilities/src/toolchain.rs", + "item": "ToolchainSourceHost" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-runtime/src/timeline_store_face.rs", + "item": "TimelineStoreBinding" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/loops.rs", + "item": "LoopsFace" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/methods.rs", + "item": "ScheduleJobsFace" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/wakeups.rs", + "item": "WakeupsFace" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/agents/sessions.rs", + "item": "SessionsService" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/collaboration/approvals.rs", + "item": "CollaborationSession" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/connection.rs", + "item": "ForeignCallChannel" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/hooks_settings.rs", + "item": "HooksService" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/lib.rs", + "item": "LocalIdDispatch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/managed_provider.rs", + "item": "ManagedSearch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/mcp/face.rs", + "item": "McpService" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/plugin_files.rs", + "item": "PluginFiles" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/settings/declared.rs", + "item": "Settings" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/face.rs", + "item": "Store" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/metadata.rs", + "item": "SessionMetadata" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/sqlite.rs", + "item": "SqliteDispatch" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-event-hub/src/bridge.rs", + "item": "ForeignEventHub" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-event-hub/src/bridge.rs", + "item": "ForeignEventSubscriptions" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-modality/src/targets.rs", + "item": "ModalityTargets" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-oauth/src/session_title.rs", + "item": "DimOAuth" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::admit" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::replay" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::respond" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/input_queue.rs", + "item": "InputQueue::pending" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/input_queue.rs", + "item": "InputQueue::withdraw_checked" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::admit_decision" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::decide" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::register_advice" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::update" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/prompt.rs", + "item": "InitialPromptConfiguration::fixed" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/prompt.rs", + "item": "InitialPromptConfiguration::read" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::activity_after" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::batch_end" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::branch" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::default_from" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::default_moves" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::end_with_final" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::get" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::head" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::inputs" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::next_move" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::page_end" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::turn_ends" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/workspace_tools/background.rs", + "item": "BackgroundExec::start" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::phase" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::watch" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::phase" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::take_hold" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::fail" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::failure" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::subscribe" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::subscribe_all" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/dispatcher.rs", + "item": "Dispatcher::watch" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::append_batch_registered" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::append_registered" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::append_with_create_at" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::batch_end" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::batch_end_at" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::before" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::bound" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::checkpoint" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::failure" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::restore" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::resume_position" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::save_snapshot" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::segments" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/core/timeline.rs", + "item": "Timeline::watch" + }, + { + "kind": "service-skip", + "file": "crates/dim-app-server/src/control.rs", + "item": "ProcessActivity::pause" + }, + { + "kind": "service-skip", + "file": "crates/dim-app-server/src/control.rs", + "item": "ProcessActivity::take_hold" + }, + { + "kind": "service-skip", + "file": "crates/dim-app-server/src/mcp/session.rs", + "item": "McpSession::subscribe" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::batch_end" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::branch_diagnostics" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::configure" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::dispatch_watch" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::end_branch" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::ended_head" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::get" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::idle" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::input" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::input_commit" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::inputs" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::interrupt" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::lookup" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::on" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::publication" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::query" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::sequence" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::service" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::set_default_branch" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::state" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::stop" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::submit" + }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::watch" + } + ], + "removed": [] +} \ No newline at end of file diff --git a/xtask/check/Cargo.toml b/xtask/check/Cargo.toml index 0846b22c95..d90d2dfa88 100644 --- a/xtask/check/Cargo.toml +++ b/xtask/check/Cargo.toml @@ -9,6 +9,7 @@ publish = false [dependencies] proc-macro2 = { version = "1", features = ["span-locations"] } rutis-types = "0.23.0" +serde.workspace = true serde_json.workspace = true syn = { version = "2", features = ["full", "visit"] } diff --git a/xtask/check/src/access.rs b/xtask/check/src/access.rs new file mode 100644 index 0000000000..f55c63c446 --- /dev/null +++ b/xtask/check/src/access.rs @@ -0,0 +1,283 @@ +//! The access-layer rules of [#2015 §5](https://github.com/arcships/dim/issues/2015) +//! and the list that admits the violations still in the tree. +//! +//! A violation is one of: `#[service(skip)]` on a service method, a +//! hand-written `HostDispatch` implementation, a `Session` method that takes a +//! line's name, and the outward `Branch` type. The scan reads the product +//! sources (`crates/*/src`) only: a test fixture is not a public face. +//! +//! The allowlist (`xtask/access-layer.json`) names every violation the tree +//! still has. `check` fails when a violation is not listed and when a listed +//! entry no longer matches anything, so a change can only remove entries, never +//! add one. The same file's `removed` list names catalog services that a change +//! deleted; the runtime catalog check in `xtask` fails when one comes back. +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; + +type Result = std::result::Result>; + +/// The file holding the allowlist and the removed names, from the workspace +/// root. +pub const FILE: &str = "xtask/access-layer.json"; + +/// What kind of access-layer violation a rule names. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Kind { + /// A service method kept out of the face with `#[service(skip)]`. + ServiceSkip, + /// A `HostDispatch` implementation written by hand instead of a + /// `#[rutis::service]` block. + HostDispatch, + /// A `Session` method that forwards to a line named by an argument. + SessionForwarding, + /// The outward `Branch` type. + BranchType, +} + +/// One violation, identified by what it is and where it lives, not by line +/// numbers. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Rule { + pub kind: Kind, + /// The source file, from the workspace root. + pub file: String, + /// The item: `Type::method` for a method, the type for a type. + pub item: String, +} + +impl std::fmt::Display for Rule { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {} {}", self.file, self.item, kind_name(self.kind)) + } +} + +fn kind_name(kind: Kind) -> &'static str { + match kind { + Kind::ServiceSkip => "has #[service(skip)]", + Kind::HostDispatch => "is a hand-written HostDispatch", + Kind::SessionForwarding => "forwards to a line name", + Kind::BranchType => "is an outward Branch type", + } +} + +/// The allowlist and the removed names. +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AccessLayer { + /// Violations the tree still has, one entry per occurrence. + #[serde(default)] + pub allow: Vec, + /// Catalog services a change deleted. Empty until the first face goes. + #[serde(default)] + pub removed: Vec, +} + +/// Reads the file at `root`; a missing file admits nothing. +pub fn load(root: &Path) -> Result { + let path = root.join(FILE); + match std::fs::read_to_string(&path) { + Ok(text) => { + Ok(serde_json::from_str(&text) + .map_err(|error| format!("{}: {error}", path.display()))?) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(AccessLayer::default()), + Err(error) => Err(format!("{}: {error}", path.display()).into()), + } +} + +/// Fails when a violation is not allowed or an allowed entry matches nothing. +pub fn check(root: &Path) -> Result<()> { + let found: BTreeSet = violations(root)?.into_iter().collect(); + let layer = load(root)?; + let allowed: BTreeSet = layer.allow.iter().cloned().collect(); + if allowed.len() != layer.allow.len() { + let mut seen = BTreeSet::new(); + let duplicates: Vec<_> = layer + .allow + .iter() + .filter(|rule| !seen.insert((*rule).clone())) + .collect(); + return Err(format!("{}: listed twice: {duplicates:?}", FILE).into()); + } + let unlisted: Vec<_> = found.difference(&allowed).collect(); + if !unlisted.is_empty() { + let mut message = format!( + "{} access-layer violation(s) are not in {FILE}; the list may only shrink:\n", + unlisted.len() + ); + for rule in unlisted { + message += &format!("{}\n", serde_json::to_string(rule).expect("a rule is JSON")); + } + return Err(message.into()); + } + let stale: Vec<_> = allowed.difference(&found).collect(); + if !stale.is_empty() { + let mut message = format!( + "{} entries of {FILE} match nothing and must be deleted:\n", + stale.len() + ); + for rule in stale { + message += &format!("{rule}\n"); + } + return Err(message.into()); + } + println!("access layer passed ({} allowed)", allowed.len()); + Ok(()) +} + +/// Every violation in the product sources under `root`. +pub fn violations(root: &Path) -> Result> { + let mut found = Vec::new(); + for file in sources(root)? { + let text = std::fs::read_to_string(&file)?; + let parsed = + syn::parse_file(&text).map_err(|error| format!("{}: {error}", file.display()))?; + let relative = file + .strip_prefix(root) + .unwrap_or(&file) + .to_string_lossy() + .replace('\\', "/"); + scan(&parsed.items, &relative, &mut found); + } + found.sort(); + Ok(found) +} + +/// The product source files: every `.rs` under `crates/*/src`. +fn sources(root: &Path) -> Result> { + let mut files = Vec::new(); + let crates = root.join("crates"); + for entry in std::fs::read_dir(&crates)? { + let directory = entry?.path().join("src"); + if directory.is_dir() { + collect(&directory, &mut files)?; + } + } + files.sort(); + Ok(files) +} + +fn collect(directory: &Path, files: &mut Vec) -> Result<()> { + for entry in std::fs::read_dir(directory)? { + let path = entry?.path(); + if path.is_dir() { + collect(&path, files)?; + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.push(path); + } + } + Ok(()) +} + +fn scan(items: &[syn::Item], file: &str, found: &mut Vec) { + for item in items { + let syn::Item::Impl(block) = item else { + if let syn::Item::Mod(module) = item + && let Some((_, items)) = &module.content + { + scan(items, file, found); + } + continue; + }; + let service = block.attrs.iter().any(is_service_attribute); + for method in &block.items { + let syn::ImplItem::Fn(method) = method else { + continue; + }; + if service + && method + .attrs + .iter() + .any(|attr| is_service_attribute(attr) && skips(attr)) + { + found.push(Rule { + kind: Kind::ServiceSkip, + file: file.to_owned(), + item: format!("{}::{}", type_name(&block.self_ty), method.sig.ident), + }); + } + } + if block + .trait_ + .as_ref() + .and_then(|(_, path, _)| path.segments.last()) + .is_some_and(|segment| segment.ident == "HostDispatch") + { + found.push(Rule { + kind: Kind::HostDispatch, + file: file.to_owned(), + item: type_name(&block.self_ty), + }); + } + if block.trait_.is_none() && type_name(&block.self_ty) == "Session" { + for method in &block.items { + let syn::ImplItem::Fn(method) = method else { + continue; + }; + let named_branch = method.sig.inputs.iter().any(|input| { + matches!(input, syn::FnArg::Typed(typed) + if matches!(&*typed.pat, syn::Pat::Ident(ident) if ident.ident == "branch")) + }); + if named_branch { + found.push(Rule { + kind: Kind::SessionForwarding, + file: file.to_owned(), + item: format!("Session::{}", method.sig.ident), + }); + } + } + } + } + for item in items { + let (visibility, ty) = match item { + syn::Item::Struct(item) => (&item.vis, &item.ident), + syn::Item::Enum(item) => (&item.vis, &item.ident), + _ => continue, + }; + if matches!(visibility, syn::Visibility::Public(_)) && ty == "Branch" { + found.push(Rule { + kind: Kind::BranchType, + file: file.to_owned(), + item: ty.to_string(), + }); + } + } +} + +/// `#[service]`, `#[service(skip)]` or their `rutis::` spellings. +fn is_service_attribute(attr: &syn::Attribute) -> bool { + path_is_service(attr.path()) +} + +fn path_is_service(path: &syn::Path) -> bool { + let segments: Vec = path + .segments + .iter() + .map(|segment| segment.ident.to_string()) + .collect(); + matches!(segments.as_slice(), [service] if service == "service") + || matches!(segments.as_slice(), [root, service] if root == "rutis" && service == "service") +} + +fn skips(attr: &syn::Attribute) -> bool { + attr.parse_args::() + .is_ok_and(|argument| argument == "skip") +} + +/// The last path segment of a type, `Branch` for `crate::Branch`. +fn type_name(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(path) => path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()) + .unwrap_or_default(), + _ => String::new(), + } +} diff --git a/xtask/check/src/lib.rs b/xtask/check/src/lib.rs index b04654883b..79cdbd0d3b 100644 --- a/xtask/check/src/lib.rs +++ b/xtask/check/src/lib.rs @@ -1,6 +1,7 @@ //! Pure static repository checks with no dependency on compiling business //! runtime crates (ADR 026 D2, D4). +pub mod access; pub mod boundaries; pub mod comment_links; pub mod i18n; @@ -27,6 +28,7 @@ pub fn root() -> PathBuf { /// Runs every pure static repository check against `root`. pub fn check_all(root: &Path) -> Result<()> { boundaries::check(root)?; + access::check(root)?; types::check(root)?; npm::check(root)?; plugin_skills::check(root)?; From c46f9fb91d04b69e85853119cee2f9b8ae4e0536 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 19:16:54 +0800 Subject: [PATCH 03/37] feat(runtime): bind the line route to its Session, and check Rust-only surfaces A Session part now routes by line id alone: the runtime provides `LineRoute` in every Session, with `line({lineId, service, method, args})` for any language and `line_owner::(lineId)` for Rust. It holds no Session id, so a part cannot name another Session, and a line of another Session is `NoLine`. The process `route` no longer exposes typed object reads: a route resolves the target scope's data face in the catalog, refuses a name the assembly marks internal, a registration point and a lifecycle service, and answers a name of another scope as `WrongScope`. Routing failures are a data error type of their own (`RouteError`), so the owner's own failure arrives with its name and message and `SessionFault` keeps no routing variant. The access-layer check gains the class the plan added: a service type's `pub`/`pub(crate)` method that takes `self` outside its `#[rutis::service]` blocks, or such a field. Constructors take no `self`, and a type that serializes has fields of data, which a face carries. The allowlist grows by the 23 violations the tree has today and compares counts, so an entry matches the number of occurrences it is listed for. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 619 +++++++++++++----- crates/dim-agent-runtime/src/assembly.rs | 42 +- crates/dim-agent-runtime/src/names.rs | 1 + crates/dim-agent-runtime/src/route.rs | 365 ++++++++--- crates/dim-agent-runtime/src/scope.rs | 1 + .../dim-agent-runtime/src/timeline_context.rs | 12 + .../dim-app-server/src/session_typescript.rs | 6 +- npm/branch-services.d.ts | 58 +- xtask/access-layer.json | 559 +++++++++------- xtask/check/src/access.rs | 359 ++++++---- 10 files changed, 1400 insertions(+), 622 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index dcf96046f7..0e59e6183b 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -1,62 +1,140 @@ //! Flow: a call by id reaches the data face of a live Session or line, and -//! answers `NoSession`, `SessionClosing` or `NoLine` otherwise -//! ([#2127](https://github.com/arcships/dim/issues/2127)). +//! answers `NoSession`, `SessionClosing`, `NoLine` or a reach refusal +//! otherwise ([#2127](https://github.com/arcships/dim/issues/2127)). -use dim_agent_capabilities::{defaults, methods::SessionMethods}; +use dim_agent_capabilities::{defaults, timeline_tree::BranchLine}; use dim_agent_runtime::testing::{MinimalHost, hold_close}; use dim_agent_runtime::*; use dim_agent_types::BranchSource; use rutis::Ctx; -use rutis::host::CtxHost; +use rutis::host::{CtxHost, DynPlugin, Effect, InstanceId, Key, TypeKey}; use rutis_bridge::session::{ Connection, Dispatch, Endpoint, Error as BridgeError, HostDispatch, Reply, Value, host_key, + host_key_in, }; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -fn builder() -> AgentBuilder { - let mut builder = AgentBuilder::new(AgentConfig::default()); - builder.timeline_store(TimelineStoreBinding::new(Arc::new( - MemoryTimelineStore::default(), - ))); - defaults::mock_hosts(&mut builder); - defaults::install(&mut builder); - builder +/// A Session part that hands its context to the test, where a language's +/// Session runtime would run. +struct HandsSession(Arc>>); + +impl DynPlugin for HandsSession { + fn name(&self) -> &str { + "RoutingSessionProbe" + } + fn injects(&self) -> Vec { + Vec::new() + } + fn apply<'a>(&'a self, ctx: &'a Ctx) -> rutis::host::BoxFuture<'a, rutis::Result> { + Box::pin(async move { + *self.0.lock().unwrap() = Some(ctx.clone()); + Ok(Effect::Done) + }) + } } -async fn open(host: &MinimalHost) -> Session { - host.create_session(SessionConfig::default()) - .await - .expect("a Session opens") +struct Rig { + host: MinimalHost, + route: Arc, + /// The context of the last Session's part, once that Session opened. + session_ctx: Arc>>, +} + +impl Rig { + async fn start() -> Self { + let session_ctx = Arc::new(Mutex::new(None)); + let probe = session_ctx.clone(); + let mut builder = AgentBuilder::new(AgentConfig::default()); + builder.timeline_store(TimelineStoreBinding::new(Arc::new( + MemoryTimelineStore::default(), + ))); + defaults::mock_hosts(&mut builder); + defaults::install(&mut builder); + // The product marks the same names (its `register_faces`); a route + // resolves data faces only. + builder.internal_name("loopState", "hot-path"); + builder.require_feature( + Feature::new("RoutingSessionProbe").session("RoutingSessionProbe", move |_| { + Ok(Box::new(HandsSession(probe.clone()))) + }), + ); + let host = MinimalHost::start(&builder).await.unwrap(); + let route = host + .root() + .get_at::(&Key::::of()) + .expect("the host serves the route"); + Self { + host, + route, + session_ctx, + } + } + + async fn open(&self) -> Session { + self.host + .create_session(SessionConfig::default()) + .await + .expect("a Session opens") + } + + fn session_ctx(&self) -> Ctx { + self.session_ctx + .lock() + .unwrap() + .take() + .expect("the Session's part loaded") + } + + fn line_route(&self, session: &Session) -> Arc { + session + .session_service::() + .expect("the Session serves its line route") + } +} + +/// A language runtime's side of a rutis session: it names a service in `ctx`'s +/// subtree, and the host serves it. +struct Names { + ctx: Ctx, + /// The instance the runtime lives in: its names are served there first, + /// then at the process. + instance: InstanceId, } -/// A language runtime's side of a rutis session: it names a service, and the -/// host serves it. -struct Names(Ctx); +impl Names { + /// The dispatch `target` names for this runtime, as a row of another + /// language resolves one. + fn dispatch(&self, target: &str) -> Arc { + self.ctx + .get_at::(&host_key_in(target, self.instance)) + .or_else(|| self.ctx.get_at::(&host_key(target))) + .unwrap_or_else(|| panic!("{target} is not served")) + } +} impl Dispatch for Names { fn invoke(&self, _: &Connection, target: &str, method: &str, args: Value) -> Reply { - self.0 - .get_at::(&host_key(target)) - .unwrap_or_else(|| panic!("{target} is not served")) - .invoke(method, args) + self.dispatch(target).invoke(method, args) } } -/// Both ends of a rutis session with the host's tree, kept open by the test. +/// Both ends of a rutis session with the tree of `ctx`. struct Language { _host: Connection, client: Connection, } impl Language { - fn open(root: &Ctx) -> Self { + fn open(ctx: &Ctx, instance: InstanceId) -> Self { let (host, far) = rutis_bridge::memory::pair(); let peer = |id: &str| Endpoint::rust(rutis_bridge::channel::PeerId::new(id).unwrap()); - let host = - Connection::open(host, Arc::new(Names(root.clone())), peer("route-host")).unwrap(); - let client = - Connection::open(far, Arc::new(Names(root.clone())), peer("route-client")).unwrap(); + let names = || Names { + ctx: ctx.clone(), + instance, + }; + let host = Connection::open(host, Arc::new(names()), peer("route-host")).unwrap(); + let client = Connection::open(far, Arc::new(names()), peer("route-client")).unwrap(); Self { _host: host, client, @@ -65,13 +143,14 @@ impl Language { async fn call( &self, + face: &str, method: &str, call: impl serde::Serialize, ) -> std::result::Result { let call: Value = serde_json::to_value(call).unwrap().into(); let reply = self .client - .invoke_settled("route", method, Value::List(vec![call])) + .invoke_settled(face, method, Value::List(vec![call])) .unwrap(); tokio::time::timeout(Duration::from_secs(30), reply) .await @@ -79,128 +158,248 @@ impl Language { .json() } - async fn refused(&self, method: &str, call: impl serde::Serialize) -> String { - let error = self - .call(method, call) + async fn refused(&self, face: &str, method: &str, call: impl serde::Serialize) -> String { + self.call(face, method, call) .await - .expect_err("the route refuses the call"); - error.to_string() + .expect_err("the route refuses the call") + .to_string() } } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_call_by_id_reaches_the_live_session_and_line() { - let builder = builder(); - let route = builder.route(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; +async fn a_process_call_reaches_the_live_session_and_line() { + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); - let config = route.session_owner::(&id).unwrap(); + let served = rig + .route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .unwrap(); + assert_eq!(served, serde_json::to_value(session.config()).unwrap()); + let sequence = rig + .route + .line(LineFaceCall::new( + &id, + "main", + "timeline", + "sequence", + vec![], + )) + .await + .unwrap(); assert_eq!( - serde_json::to_value(config.as_ref()).unwrap(), - serde_json::to_value(session.config()).unwrap(), - "the Session route reads the Session's own face" + sequence, + serde_json::json!(session.sequence("main").unwrap()) ); - let loop_state = route - .line_owner::(&id, "main") - .expect("the main line's face"); - assert_eq!(loop_state.state().phase, LoopPhase::Idle); - - assert!(matches!( - route.session_owner::("absent"), - Err(AgentError::NoSession(absent)) if absent == "absent" - )); - assert!(matches!( - route.line_owner::(&id, "absent"), - Err(AgentError::NoLine { line, .. }) if line == "absent" - )); - - let named = route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + + assert_eq!( + rig.route + .session(SessionFaceCall::new( + "absent", + "sessionConfig", + "get", + vec![] + )) + .await + .unwrap_err(), + RouteError::NoSession("absent".into()) + ); + assert_eq!( + rig.route + .line(LineFaceCall::new( + &id, + "absent", + "timeline", + "sequence", + vec![] + )) + .await + .unwrap_err(), + RouteError::NoLine { + session: id.clone(), + line: "absent".into() + } + ); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_session_part_reaches_its_own_line_by_id_only() { + let rig = Rig::start().await; + let session = rig.open().await; + let id = session.id().to_owned(); + let route = rig.line_route(&session); + + let sequence = route + .line(OwnLineCall::new("main", "timeline", "sequence", vec![])) .await .unwrap(); assert_eq!( - named, - serde_json::to_value(session.config()).unwrap(), - "naming the face reaches what holding it does" + sequence, + serde_json::json!(session.sequence("main").unwrap()) ); - host.close().await.unwrap(); + assert_eq!( + route + .line(OwnLineCall::new("absent", "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::NoLine { + session: id.clone(), + line: "absent".into() + } + ); + assert!(line_owner::(&route, "main").is_ok()); + assert_eq!( + line_owner::(&route, "main").err(), + Some(RouteError::NotDataFace { + service: "loopState".into() + }), + "the Rust binding resolves data faces only" + ); + rig.host.close().await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_language_call_reaches_a_line_face_through_the_route() { - let builder = builder(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); - let language = Language::open(host.root()); + let language = Language::open(rig.host.root(), rig.host.root().instance()); language.client.ready().await.unwrap(); - let call = LineFaceCall::new(&id, "main", "timeline", "sequence", vec![]); - let sequence = language.call("line", call).await.unwrap(); + let sequence = language + .call( + "route", + "line", + LineFaceCall::new(&id, "main", "timeline", "sequence", vec![]), + ) + .await + .unwrap(); assert_eq!( sequence, - serde_json::json!(session.sequence("main").unwrap()), - "the routed call reads the line's own face" + serde_json::json!(session.sequence("main").unwrap()) ); - let missing = LineFaceCall::new(&id, "absent", "timeline", "sequence", vec![]); - let error = language.refused("line", missing).await; + let error = language + .refused( + "route", + "line", + LineFaceCall::new(&id, "absent", "timeline", "sequence", vec![]), + ) + .await; assert!(error.contains("no line"), "{error}"); - host.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_session_language_call_reaches_its_own_line_and_names_no_session() { + let rig = Rig::start().await; + let session = rig.open().await; + let id = session.id().to_owned(); + let language = Language::open(&rig.session_ctx(), session.instance().unwrap()); + language.client.ready().await.unwrap(); + + let sequence = language + .call( + "lineRoute", + "line", + OwnLineCall::new("main", "timeline", "sequence", vec![]), + ) + .await + .unwrap(); + assert_eq!( + sequence, + serde_json::json!(session.sequence("main").unwrap()) + ); + let carried = serde_json::json!({ + "sessionId": session.id(), + "lineId": "main", + "service": "timeline", + "method": "sequence", + "args": [], + }); + let error = language.refused("lineRoute", "line", carried).await; + assert!( + error.contains("unknown field") && error.contains("sessionId"), + "a Session route names no Session: {error}" + ); + assert!( + language + .call( + "lineRoute", + "line", + OwnLineCall::new("main", "timeline", "sequence", vec![]) + ) + .await + .is_ok(), + "the Session's own line still answers {id}" + ); + rig.host.close().await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_idle_unloaded_session_answers_no_session_until_it_loads_again() { - let builder = builder(); - let route = builder.route(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); assert!( session.unload_if_idle().await.unwrap(), "an idle Session unloads" ); - assert!(matches!( - route.session_owner::(&id), - Err(AgentError::NoSession(absent)) if absent == id - )); - - let restored = host.restore_session(id.clone()).await.unwrap(); - assert!(route.session_owner::(&id).is_ok()); - assert!(route.line_owner::(&id, "main").is_ok()); + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::NoSession(id.clone()) + ); + + let restored = rig.host.restore_session(id.clone()).await.unwrap(); + assert!( + rig.route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .is_ok() + ); + assert!( + rig.line_route(&restored) + .line(OwnLineCall::new("main", "timeline", "sequence", vec![])) + .await + .is_ok() + ); restored.close().await.unwrap(); - host.close().await.unwrap(); + rig.host.close().await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_session_closed_by_business_answers_no_session_and_keeps_no_instance_to_hold() { - let builder = builder(); - let route = builder.route(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); session.close().await.unwrap(); - assert!(matches!( - route.session_owner::(&id), - Err(AgentError::NoSession(absent)) if absent == id - )); + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::NoSession(id.clone()) + ); assert!( - host.get_session(&id).is_none(), + rig.host.get_session(&id).is_none(), "a closed Session has no live instance for a hold to keep" ); - host.close().await.unwrap(); + rig.host.close().await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_closing_session_answers_session_closing_for_its_lines_too() { - let builder = builder(); - let route = builder.route(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); + let line_route = rig.line_route(&session); let mut held = hold_close(&id, "main"); let closing = { let session = session.clone(); @@ -208,29 +407,49 @@ async fn a_closing_session_answers_session_closing_for_its_lines_too() { }; held.arrived().await; - assert!(matches!( - route.session_owner::(&id), - Err(AgentError::SessionClosing(closing)) if closing == id - )); - assert!(matches!( - route.line_owner::(&id, "main"), - Err(AgentError::SessionClosing(closing)) if closing == id - )); + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()) + ); + assert_eq!( + rig.route + .line(LineFaceCall::new( + &id, + "main", + "timeline", + "sequence", + vec![] + )) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()) + ); + assert_eq!( + line_route + .line(OwnLineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()) + ); held.release(); closing.await.unwrap().unwrap(); - assert!(matches!( - route.session_owner::(&id), - Err(AgentError::NoSession(absent)) if absent == id - )); - host.close().await.unwrap(); + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::NoSession(id.clone()) + ); + rig.host.close().await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive() { - let builder = builder(); - let route = builder.route(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); let source = || BranchSource::Host { operation_id: "routing".into(), @@ -246,65 +465,135 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive ) .await .unwrap(); - assert!(route.line_owner::(&id, &line).is_ok()); + assert!( + rig.route + .line(LineFaceCall::new( + &id, + &line, + "timeline", + "sequence", + vec![] + )) + .await + .is_ok() + ); session.end_branch(&line, source()).await.unwrap(); let deadline = Instant::now() + Duration::from_secs(30); - while !matches!( - route.line_owner::(&id, &line), - Err(AgentError::NoLine { .. }) - ) { - assert!(Instant::now() < deadline, "the ended line closes"); + loop { + let answer = rig + .route + .line(LineFaceCall::new( + &id, + &line, + "timeline", + "sequence", + vec![], + )) + .await; + if matches!(answer, Err(RouteError::NoLine { .. })) { + break; + } + assert!( + Instant::now() < deadline, + "the ended line closes: {answer:?}" + ); tokio::time::sleep(Duration::from_millis(10)).await; } assert!( - route.session_owner::(&id).is_ok(), + rig.route + .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + .await + .is_ok(), "one line's end does not affect the Session's other calls" ); - assert!(route.line_owner::(&id, "main").is_ok()); - host.close().await.unwrap(); + assert!( + rig.route + .line(LineFaceCall::new( + &id, + "main", + "timeline", + "sequence", + vec![] + )) + .await + .is_ok() + ); + rig.host.close().await.unwrap(); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn routing_refuses_registration_points_and_lifecycle_services() { - let builder = builder(); - let route = builder.route(); - let host = MinimalHost::start(&builder).await.unwrap(); - let session = open(&host).await; +async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { + let rig = Rig::start().await; + let session = rig.open().await; let id = session.id().to_owned(); + let route = rig.line_route(&session); - let refused = route - .session_owner::(&id) - .err() - .expect("a registration point is not routable"); - assert!( - matches!(&refused, AgentError::InvalidInput(_)), - "{refused:?}" - ); - assert!(refused.to_string().contains("sessionMethods"), "{refused}"); - for service in [ - "sessionMethods", - "toolRegistry", - "sessionLifecycle", - "branchLifecycle", - ] { - let error = route - .session(SessionFaceCall::new(&id, service, "register", vec![])) - .await - .expect_err("the route refuses the name"); - assert!( - matches!(&error, AgentError::InvalidInput(_)), - "{service}: {error:?}" + for service in ["sessionMethods", "toolRegistry", "guideEntries"] { + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, service, "register", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a registration point" ); - assert!(error.to_string().contains(service), "{service}: {error}"); } - let process = route - .session_owner::(&id) - .err() - .expect("a line service is not a Session face"); - assert!( - process.to_string().contains("not a session service"), - "{process}" + for service in ["sessionLifecycle", "branchLifecycle"] { + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, service, "closing", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a lifecycle service" + ); + } + assert_eq!( + rig.route + .line(LineFaceCall::new(&id, "main", "loopState", "state", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: "loopState".into() + }, + "an internal face is not a data face" ); - host.close().await.unwrap(); + assert_eq!( + rig.route + .session(SessionFaceCall::new(&id, "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::WrongScope { + service: "timeline".into(), + group: "session".into() + }, + "a line face is not a Session face" + ); + assert_eq!( + route + .line(OwnLineCall::new("main", "sessionConfig", "get", vec![])) + .await + .unwrap_err(), + RouteError::WrongScope { + service: "sessionConfig".into(), + group: "branch".into() + }, + "a Session face is not a line face" + ); + let error = rig + .route + .line(LineFaceCall::new(&id, "main", "timeline", "absent", vec![])) + .await + .unwrap_err(); + let RouteError::Owner { name, message } = error else { + panic!("the owner's failure: {error:?}"); + }; + assert_eq!(name, "no-method", "the owner's own failure keeps its name"); + assert!(message.contains("absent"), "{message}"); + rig.host.close().await.unwrap(); } diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index f71ce7cba8..1a8580ae7e 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -291,8 +291,8 @@ pub(crate) struct Assembly { /// its Agents ([`AgentBuilder::build`]); the minimal host takes a fresh one. pub parts: Arc, /// The Sessions this builder's Agents publish, for calls by id - /// ([`AgentBuilder::route`]). - pub route: Arc, + /// ([`Route`]). + pub route: Arc, /// Registered parts the profile requires, by name. required_parts: Arc>, /// The rows a Session and a branch need Active, as [`AgentBuilder::install`] @@ -303,6 +303,9 @@ pub(crate) struct Assembly { /// The builder's catalog, as its Agents were built: the facades read a /// name in the group it registers. pub catalog: Arc, + /// The names the builder marked internal, as its Agents were built: a + /// route resolves only a name that is not among them. + pub faces: Arc, } /// The closed set of reasons a service face is internal (#1289). pub const FACE_REASONS: [&str; 8] = [ @@ -369,6 +372,7 @@ impl AgentBuilder { required_rows: Arc::default(), extensions: vec![], catalog: Arc::default(), + faces: Arc::default(), }, } } @@ -425,15 +429,6 @@ impl AgentBuilder { pub fn parts(&self) -> Arc { self.assembly.parts.clone() } - /// The route from ids to the live Sessions this builder's Agents publish - /// ([`Route`]): [`Self::plugin_rows`] provides it to the host's process - /// plugins as `route`, so a process part reaches a Session of any of those - /// Agents by id. Rust parts call the owner's data face directly - /// ([`Route::session_owner`], [`Route::line_owner`]); another language - /// calls the same route by that name. - pub fn route(&self) -> Arc { - self.assembly.route.clone() - } /// Adds a process plugin: `make` builds it from the names its /// dependencies resolve to at the process, usually /// `|names| Ok(Box::new(MyPlugin::new(names)?))`. The host places it as @@ -507,7 +502,7 @@ impl AgentBuilder { let route = self.assembly.route.clone(); let route: PartMake = Arc::new(move |names| { Ok(Box::new(crate::route::RoutePlugin { - route: route.clone(), + index: route.clone(), key: names.key()?, })) }); @@ -847,6 +842,7 @@ impl AgentBuilder { let mut assembly = self.assembly.clone(); assembly.abandoned = tokio_util::task::TaskTracker::new(); assembly.catalog = Arc::new(self.catalog.clone()); + assembly.faces = Arc::new(self.faces.clone()); if !self.custom_store { let store = Arc::new(MemoryTimelineStore::default()); assembly.store = TimelineStoreBinding::new(store.clone()); @@ -1186,11 +1182,24 @@ impl SessionAssembly { } /// The live line instance `id`, or `None` when this Session never created - /// it, it is gone, or it is closing. + /// it, it is gone, or it is closing. An entry whose instance is gone is + /// dropped here. pub(crate) fn line(&self, id: &str) -> Option> { - let line = self.lines.lock().unwrap().get(id).and_then(Weak::upgrade)?; + let mut lines = self.lines.lock().unwrap(); + let line = lines.get(id)?.upgrade(); + let Some(line) = line else { + lines.remove(id); + return None; + }; + drop(lines); (!line.is_closing()).then_some(line) } + + /// What a route reads of this Session's assembly to decide whether it may + /// resolve a name: the catalog's groups and the names it marked internal. + pub(crate) fn reach(&self) -> (&rutis_loader::ServiceCatalog, &Faces) { + (&self.assembly.catalog, &self.assembly.faces) + } } struct SessionScopePlugin { @@ -1249,6 +1258,10 @@ impl DynPlugin for SessionScopePlugin { for provide in &owner.assembly.values { provide(ctx, &scope)?; } + ctx.provide_at( + scope.key::(), + Arc::new(crate::LineRoute::new(owner)), + )?; { let mut loaded = owner.loaded.lock().unwrap(); if loaded.is_some() { @@ -1561,6 +1574,7 @@ impl TimelineFactory { branch.lifecycle.clone(), parent.lifecycle.faults.clone(), parent.assembly.catalog.clone(), + parent.assembly.faces.clone(), ); parent.register_line(&id, Arc::downgrade(&context)); Ok(context) diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index d5bd10a3d0..7a70d41220 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -103,6 +103,7 @@ pub fn catalog() -> ServiceCatalog { catalog.register_shared_instance("timelineStore", SESSION_GROUP); register::(&mut catalog, session); register::(&mut catalog, session); + register::(&mut catalog, session); let branch = Some(BRANCH_GROUP); register::(&mut catalog, branch); register::(&mut catalog, branch); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index be4fb157de..a392ebaa13 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -1,28 +1,42 @@ -//! Calls by id to a live owner's data face ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1–D4, [#2127](https://github.com/arcships/dim/issues/2127)). +//! Calls by id to a live owner's data face +//! ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1–D4, [#2127](https://github.com/arcships/dim/issues/2127)). //! -//! A caller outside a scope holds no instance key, so it names what it wants -//! instead: the [`Route`] resolves `sessionId`, or `sessionId` and a line id, -//! to the instance that is live now and reads the named owner's face there. -//! Rust calls the face directly ([`Route::session_owner`], -//! [`Route::line_owner`]); another language calls the same route by name -//! ([`Route::session`], [`Route::line`]). Neither declares the inner group's -//! names, and an instance key never leaves the instance. +//! A caller outside a scope holds no instance key, so it names what it wants. +//! The runtime keeps the Sessions its Agents publish and the lines each +//! Session created, and hands the call to the instance that is live now: //! -//! What a route resolves is the target scope's data face in the catalog: not a -//! mechanism registration point, whose entries belong to the registering -//! generation, and not a scope lifecycle service. Everything else about the -//! call belongs to the owner: the route passes the method and its arguments -//! through and returns the owner's reply or error unchanged. A target that has -//! no instance answers [`AgentError::NoSession`] (idle-unloaded, closed or -//! unknown), a Session that is closing answers [`AgentError::SessionClosing`], -//! and a line that is closing, closed or not the Session's answers -//! [`AgentError::NoLine`]. +//! - a process caller names the Session, or the Session and a line +//! ([`Route`]); +//! - a Session part names one of its own lines only ([`LineRoute`]); it cannot +//! name another Session. +//! +//! A Rust caller calls the target owner's operations directly: [`line_owner`] +//! is the binding of [`LineRoute::line`] for a caller that wants the owner's +//! face. Everything else in this module is data: Rust, another language's +//! runtime and a UI leaf call the same operation with the same arguments and +//! read the same reply. Neither route takes a target's instance key, and a +//! resolution is never kept across calls. +//! +//! What a route resolves is the target scope's data face in the catalog. A +//! name the assembly marks `internal(reason)`, a mechanism registration point +//! (whose entries belong to the registering generation) and a scope lifecycle +//! service are refused as [`RouteError::NotDataFace`]; a name of another +//! scope is [`RouteError::WrongScope`]. Everything else about the call belongs +//! to the owner: the route passes the method and its arguments through and +//! returns the owner's reply, or the owner's own failure as it wrote it. +//! +//! A Session that has no live instance — idle-unloaded, closed or never +//! created — answers [`RouteError::NoSession`]. A Session that is closing +//! answers [`RouteError::SessionClosing`], and a line target answers it too, +//! because closing the Session closes its lines. A line that is closing or +//! closed, or that belongs to another Session, answers [`RouteError::NoLine`]; +//! that is final for the line: routing never retries it. use crate::*; use rutis::Ctx; use rutis::host::CtxHost; use rutis_bridge::session::{ - HostDispatch, Value as BridgeValue, decode_value, host_key_in, settle, + Error as BridgeError, HostDispatch, Value as BridgeValue, decode_value, host_key_in, settle, }; use serde::{Deserialize, Serialize}; use std::{ @@ -30,10 +44,13 @@ use std::{ sync::{Arc, Mutex, Weak}, }; -/// Names routing does not resolve: the mechanism's registration points in the -/// groups it resolves, whose entries belong to the part that registered them -/// and are reachable only inside that generation -/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md)), and the +/// What a route answers: the target's reply, or why it did not reach one. +type Routed = std::result::Result; + +/// Names routing does not resolve: the mechanism's registration points, whose +/// entries belong to the part that registered them and are reachable only +/// inside that generation +/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D3), and the /// scope lifecycle services the runtime provides. const REGISTRATION_POINTS: [&str; 5] = [ "sessionMethods", @@ -43,14 +60,46 @@ const REGISTRATION_POINTS: [&str; 5] = [ "submitChecks", ]; -/// The call routing makes to a Session-scope data face. +/// Why a routed call did not reach a reply. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum RouteError { + /// The Session has no live instance: it was idle-unloaded, closed, or + /// never created. Only a process caller receives it; a caller that must + /// continue asks Agents for a hold and calls again once that loads the + /// Session. + #[error("no live Session {0}")] + NoSession(String), + /// The Session instance is closing, and so is a call to one of its lines. + /// A Session-scoped caller ends its work; a process caller treats it as + /// [`Self::NoSession`]. + #[error("Session {0} is closing")] + SessionClosing(String), + /// The Session is live but the line is closing, closed, or not one of its + /// lines. Final for that line: no hold and no retry. + #[error("no line {line} in Session {session}")] + NoLine { session: String, line: String }, + /// The name is not a data face a route resolves there: the assembly marks + /// it internal, it is a mechanism registration point, or it is a scope + /// lifecycle service. A permanent answer: the request is wrong. + #[error("{service} is not a routable data face")] + NotDataFace { service: String }, + /// The name is a data face, but not of the scope the route reaches. + #[error("{service} is not a {group} service")] + WrongScope { service: String, group: String }, + /// The owner's own failure, with the name and message it wrote; routing + /// does not read or restate it. + #[error("{message}")] + Owner { name: String, message: String }, +} + +/// A call to a Session-scope data face. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SessionFaceCall { pub session_id: String, pub service: String, pub method: String, - /// The method's arguments, in order, as the calling language writes them. + /// The method's arguments, in order. #[serde(default)] pub args: Vec, } @@ -72,7 +121,7 @@ impl SessionFaceCall { } } -/// The call routing makes to a line-scope data face. +/// A call from the process to a line-scope data face. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct LineFaceCall { @@ -80,7 +129,7 @@ pub struct LineFaceCall { pub line_id: String, pub service: String, pub method: String, - /// The method's arguments, in order, as the calling language writes them. + /// The method's arguments, in order. #[serde(default)] pub args: Vec, } @@ -105,38 +154,45 @@ impl LineFaceCall { } } -/// Calls by id to the scope a live instance owns (module docs). -/// -/// One `Route` serves every Agent of one host: each Agent registers the -/// Sessions it publishes, so a process part reaches a Session of any Agent. -/// Rust parts read it as the process name `route` and call the owner's face -/// directly; a language runtime or a UI leaf calls [`Self::session`] or -/// [`Self::line`] by that name instead. -#[derive(Default)] -pub struct Route { - sessions: Mutex>>, +/// A call from a Session part to one of its own lines. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OwnLineCall { + pub line_id: String, + pub service: String, + pub method: String, + /// The method's arguments, in order. + #[serde(default)] + pub args: Vec, } -impl Route { - /// The Session-scope data face `T` of the live Session `session_id`. - pub fn session_owner(&self, session_id: &str) -> Result> { - routable(&names::name_of::())?; - self.resolve_session(session_id)?.session_face::() +impl OwnLineCall { + /// The call to `service.method(args...)` in this Session's line `line_id`. + pub fn new( + line_id: impl Into, + service: impl Into, + method: impl Into, + args: Vec, + ) -> Self { + Self { + line_id: line_id.into(), + service: service.into(), + method: method.into(), + args, + } } +} - /// The line-scope data face `T` of `line_id` in the live Session - /// `session_id`. - pub fn line_owner( - &self, - session_id: &str, - line_id: &str, - ) -> Result> { - routable(&names::name_of::())?; - self.resolve_line(session_id, line_id)?.public::() - } +/// The Sessions this host's Agents published, by id, and the lines each +/// Session created. Runtime state, not a service: the routes read it, and a +/// Session registers itself as it publishes. +#[derive(Default)] +pub(crate) struct Index { + sessions: Mutex>>, +} - /// Registers a Session that is publishing, for as long as its instance - /// lives. +impl Index { + /// Records the Session publishing as `id`. pub(crate) fn register(&self, id: &str, session: Weak) { self.sessions.lock().unwrap().insert(id.to_owned(), session); } @@ -153,37 +209,53 @@ impl Route { } } - fn resolve_session(&self, id: &str) -> Result> { + fn session(&self, id: &str) -> Routed> { let session = self .sessions .lock() .unwrap() .get(id) .and_then(Weak::upgrade) - .ok_or_else(|| AgentError::NoSession(id.into()))?; + .ok_or_else(|| RouteError::NoSession(id.into()))?; if session.closing.is_cancelled() { - return Err(AgentError::SessionClosing(id.into())); + return Err(RouteError::SessionClosing(id.into())); } Ok(session) } - fn resolve_line(&self, session_id: &str, line_id: &str) -> Result> { - let session = self.resolve_session(session_id)?; - session.line(line_id).ok_or_else(|| AgentError::NoLine { + fn line(&self, session_id: &str, line_id: &str) -> Routed> { + let session = self.session(session_id)?; + session.line(line_id).ok_or_else(|| RouteError::NoLine { session: session_id.to_owned(), line: line_id.to_owned(), }) } } +/// Calls by id to a live Session or line (process scope), provided as the +/// process name `route`. +/// +/// One route serves every Agent of one host: each Agent registers the Sessions +/// it publishes, so a process part reaches a Session of any of them. +pub struct Route { + index: Arc, +} + +impl Route { + /// The route over `index`. + pub(crate) fn new(index: Arc) -> Self { + Self { index } + } +} + #[rutis::service] impl Route { - /// Calls a Session-scope data face: [`Route::session_owner`] for a - /// language that names the face instead of holding it. - pub async fn session(&self, call: SessionFaceCall) -> Result { - routable(&call.service)?; - let session = self.resolve_session(&call.session_id)?; - let loaded = session.loaded()?; + /// Calls a Session-scope data face of the live Session `call.session_id`. + pub async fn session(&self, call: SessionFaceCall) -> Routed { + let session = self.index.session(&call.session_id)?; + let (catalog, faces) = session.reach(); + face(catalog, faces, &call.service, SESSION_GROUP)?; + let loaded = session.loaded().map_err(owner)?; call_face( &loaded.ctx, loaded.scope.instance, @@ -194,11 +266,67 @@ impl Route { .await } - /// Calls a line-scope data face: [`Route::line_owner`] for a language that - /// names the face instead of holding it. - pub async fn line(&self, call: LineFaceCall) -> Result { - routable(&call.service)?; - let line = self.resolve_line(&call.session_id, &call.line_id)?; + /// Calls a line-scope data face of the line `call.line_id` in the live + /// Session `call.session_id`. + pub async fn line(&self, call: LineFaceCall) -> Routed { + let line = self.index.line(&call.session_id, &call.line_id)?; + face(line.catalog(), line.faces(), &call.service, BRANCH_GROUP)?; + call_face( + line.ctx(), + line.scope_instance(), + &call.service, + &call.method, + &call.args, + ) + .await + } +} + +/// Calls by id to one of this Session's lines, provided to the Session's parts +/// and their runtimes as the Session name `lineRoute`. +/// +/// A Session part reaches its own Session's lines only: the route holds no +/// Session id, so a caller cannot name another Session, and a line of another +/// Session is [`RouteError::NoLine`]. +pub struct LineRoute { + session: Weak, + session_id: String, +} + +impl LineRoute { + /// The route over the Session `session` is publishing. + pub(crate) fn new(session: &Arc) -> Self { + Self { + session: Arc::downgrade(session), + session_id: session.id.clone(), + } + } + + fn live(&self) -> Routed> { + let closing = || RouteError::SessionClosing(self.session_id.clone()); + let session = self.session.upgrade().ok_or_else(closing)?; + if session.closing.is_cancelled() { + return Err(closing()); + } + Ok(session) + } + + fn live_line(&self, line_id: &str) -> Routed> { + self.live()? + .line(line_id) + .ok_or_else(|| RouteError::NoLine { + session: self.session_id.clone(), + line: line_id.to_owned(), + }) + } +} + +#[rutis::service] +impl LineRoute { + /// Calls a line-scope data face of this Session's line `call.line_id`. + pub async fn line(&self, call: OwnLineCall) -> Routed { + let line = self.live_line(&call.line_id)?; + face(line.catalog(), line.faces(), &call.service, BRANCH_GROUP)?; call_face( line.ctx(), line.scope_instance(), @@ -210,18 +338,38 @@ impl Route { } } -/// Fails unless routing may resolve `service` (module docs). -fn routable(service: &str) -> Result<()> { +/// The line-scope data face `T` of this Session's line `line_id`: the Rust +/// binding of [`LineRoute::line`]. +pub fn line_owner(route: &LineRoute, line_id: &str) -> Routed> { + let line = route.live_line(line_id)?; + face( + line.catalog(), + line.faces(), + &names::name_of::(), + BRANCH_GROUP, + )?; + line.public::().map_err(owner) +} + +/// Fails unless a route may resolve `service` as a data face of `group` +/// (module docs). +fn face(catalog: &names::ServiceCatalog, faces: &Faces, service: &str, group: &str) -> Routed<()> { let lifecycle = [ names::name_of::(), names::name_of::(), ]; - if REGISTRATION_POINTS.contains(&service) || lifecycle.iter().any(|name| name == service) { - return Err(AgentError::InvalidInput(format!( - "route: {service} is not a routable service" - ))); + if REGISTRATION_POINTS.contains(&service) + || lifecycle.iter().any(|name| name == service) + || faces.reason(service).is_some() + { + return Err(RouteError::NotDataFace { + service: service.into(), + }); } - Ok(()) + names::named_in_group(catalog, service, group).map_err(|_| RouteError::WrongScope { + service: service.into(), + group: group.into(), + }) } /// Calls `method` of the data face `service` in `instance`, as another @@ -233,28 +381,67 @@ async fn call_face( service: &str, method: &str, args: &[serde_json::Value], -) -> Result { +) -> Routed { let dispatch = ctx .get_at::(&host_key_in(service, instance)) - .ok_or_else(|| AgentError::Reloading(service.into()))?; + .ok_or_else(|| RouteError::Owner { + name: service.into(), + message: format!("{service} is not provided now"), + })?; let args = BridgeValue::List( args.iter() .map(|arg| BridgeValue::Data(arg.clone())) .collect(), ); - let reply = dispatch - .invoke(method, args) - .map_err(|error| AgentError::fault(service, error.to_string()))?; - let value = settle(reply) - .await - .map_err(|error| AgentError::fault(service, error.to_string()))?; - decode_value::(value) - .map_err(|error| AgentError::fault(service, error.to_string())) + let reply = dispatch.invoke(method, args).map_err(owner)?; + let value = settle(reply).await.map_err(owner)?; + decode_value::(value).map_err(owner) +} + +/// The owner's failure as the target wrote it, under the name it carries. +fn owner(error: impl Into) -> RouteError { + let failure = error.into(); + RouteError::Owner { + name: failure.name, + message: failure.message, + } +} + +/// A failure's name and message, from either error surface a read answers +/// with. +pub(crate) struct Failure { + name: String, + message: String, +} + +impl From for Failure { + fn from(error: AgentError) -> Self { + Self { + name: "AgentError".into(), + message: error.to_string(), + } + } +} + +impl From for Failure { + fn from(error: BridgeError) -> Self { + match error { + BridgeError::Remote { name, message, .. } => Self { name, message }, + BridgeError::Binding { code, message, .. } => Self { + name: code.unwrap_or("BindingError").into(), + message, + }, + other => Self { + name: "BridgeError".into(), + message: other.to_string(), + }, + } + } } /// Provides the host's [`Route`] at the process name `route`. pub(crate) struct RoutePlugin { - pub route: Arc, + pub index: Arc, pub key: rutis::host::Key, } @@ -264,7 +451,7 @@ impl rutis::Plugin for RoutePlugin { "Route" } async fn apply(&self, ctx: &Ctx, (): ()) -> rutis::Result { - ctx.provide_at(self.key.clone(), self.route.clone())?; + ctx.provide_at(self.key.clone(), Arc::new(Route::new(self.index.clone())))?; Ok(()) } } diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index 240f2cdc86..b700ea97c3 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -178,4 +178,5 @@ impl BranchScope { } } impl PublicService for SessionConfig {} +impl PublicService for crate::LineRoute {} impl PublicService for dyn LoopState {} diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index ec42162425..c751c9c887 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -56,6 +56,8 @@ pub struct TimelineContext { stop_operation: Mutex>, /// Where the facade reads which group a name is in. catalog: Arc, + /// The names the assembly marked internal. + faces: Arc, } /// How often a wait looks for a reloading Loop's successor. const LOOP_RETURN_POLL: std::time::Duration = std::time::Duration::from_millis(10); @@ -146,9 +148,11 @@ impl TimelineContext { lifecycle: BranchLifecycle, faults: FaultReporter, catalog: Arc, + faces: Arc, ) -> Arc { let this = Arc::new(Self { catalog, + faces, id, ctx, view, @@ -350,6 +354,14 @@ impl TimelineContext { pub(crate) fn ctx(&self) -> &Ctx { &self.ctx } + /// The catalog this branch's group names come from. + pub(crate) fn catalog(&self) -> &rutis_loader::ServiceCatalog { + &self.catalog + } + /// The names the assembly marked internal. + pub(crate) fn faces(&self) -> &Faces { + &self.faces + } /// The branch group instance this line runs in. pub(crate) fn scope_instance(&self) -> rutis::host::InstanceId { self.scope.instance diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index 5837b08bd1..52a4fe15ac 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -93,8 +93,9 @@ fn crossing_instance_names() -> [(String, &'static str); 17] { /// the catalog already shares: the marked Session and branch services, the /// tool, method and guide-entry registries, with which a part of any /// language registers its contributions, the part registry, with which a -/// plugin registers its parts, and the route, which names a live Session or -/// line by id ([`Route`](dim_agent_runtime::Route)). The generated catalog +/// plugin registers its parts, and the routes, which name a live Session or +/// line by id ([`Route`](dim_agent_runtime::Route), +/// [`LineRoute`](dim_agent_runtime::LineRoute)). The generated catalog /// (`xtask graph`) shares them the same way. pub fn share_names(catalog: &mut ServiceCatalog) { for (name, group) in crossing_instance_names() { @@ -105,6 +106,7 @@ pub fn share_names(catalog: &mut ServiceCatalog) { .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) + .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared(name_of::()) .register_shared(name_of::()) .register_shared(name_of::()); diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 263545c243..25b96d8619 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1406,49 +1406,71 @@ export interface PartRegistry { registerDefinition(scope: PartScope, name: string, definition: import('@arcships/rutis').Plugin | ((ctx: any, config: any) => unknown) | { apply(ctx: any, config: any): unknown }): Promise } -/** The call routing makes to a Session-scope data face. */ +/** A call to a Session-scope data face. */ export type SessionFaceCall = { sessionId: string service: string method: string - /** The method's arguments, in order, as the calling language writes them. */ + /** The method's arguments, in order. */ args?: import('./plugin.js').BridgeJsonValue[] } -/** The call routing makes to a line-scope data face. */ +/** A call from the process to a line-scope data face. */ export type LineFaceCall = { sessionId: string lineId: string service: string method: string - /** The method's arguments, in order, as the calling language writes them. */ + /** The method's arguments, in order. */ args?: import('./plugin.js').BridgeJsonValue[] } /** - * Calls by id to the scope a live instance owns (module docs). + * Calls by id to a live Session or line (process scope), provided as the + * process name `route`. * - * One `Route` serves every Agent of one host: each Agent registers the - * Sessions it publishes, so a process part reaches a Session of any Agent. - * Rust parts read it as the process name `route` and call the owner's face - * directly; a language runtime or a UI leaf calls [`Self::session`] or - * [`Self::line`] by that name instead. + * One route serves every Agent of one host: each Agent registers the Sessions + * it publishes, so a process part reaches a Session of any of them. */ export interface Route { /** - * Calls a Session-scope data face: [`Route::session_owner`] for a - * language that names the face instead of holding it. - * @throws {AgentErrorThrown} + * Calls a Session-scope data face of the live Session `call.session_id`. + * @throws {RouteErrorThrown} */ session(call: SessionFaceCall): Promise /** - * Calls a line-scope data face: [`Route::line_owner`] for a language that - * names the face instead of holding it. - * @throws {AgentErrorThrown} + * Calls a line-scope data face of the line `call.line_id` in the live + * Session `call.session_id`. + * @throws {RouteErrorThrown} */ line(call: LineFaceCall): Promise } +/** A call from a Session part to one of its own lines. */ +export type OwnLineCall = { + lineId: string + service: string + method: string + /** The method's arguments, in order. */ + args?: import('./plugin.js').BridgeJsonValue[] +} + +/** + * Calls by id to one of this Session's lines, provided to the Session's parts + * and their runtimes as the Session name `lineRoute`. + * + * A Session part reaches its own Session's lines only: the route holds no + * Session id, so a caller cannot name another Session, and a line of another + * Session is [`RouteError::NoLine`]. + */ +export interface LineRoute { + /** + * Calls a line-scope data face of this Session's line `call.line_id`. + * @throws {RouteErrorThrown} + */ + line(call: OwnLineCall): Promise +} + export type SessionInstanceDefinition = { group: string definitionId: string @@ -1818,6 +1840,9 @@ export type ReservedMethodsErrorThrown = RustError<"ReservedMethodsError", "rese /** What a method returning `Err(ResourceError)` throws. */ export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceError> +/** What a method returning `Err(RouteError)` throws. */ +export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClosing" | "NoLine" | "NotDataFace" | "WrongScope" | "Owner", undefined> + /** What a method returning `Err(SessionInstanceError)` throws. */ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> @@ -1867,6 +1892,7 @@ export interface Services { timeline: Timeline partRegistry: PartRegistry route: Route + lineRoute: LineRoute sessionLoader: SessionLoader sessionPermissions: SessionPermissions collaborationConfig: CollaborationConfig diff --git a/xtask/access-layer.json b/xtask/access-layer.json index a55a8279e1..721b498d9d 100644 --- a/xtask/access-layer.json +++ b/xtask/access-layer.json @@ -1,9 +1,19 @@ { "allow": [ { - "kind": "branch-type", - "file": "crates/dim-agent-runtime/src/branch.rs", - "item": "Branch" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::admit" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::replay" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/approval.rs", + "item": "Approval::respond" }, { "kind": "host-dispatch", @@ -35,6 +45,21 @@ "file": "crates/dim-agent-capabilities/src/host.rs", "item": "SelectableModelsHost" }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host.rs", + "item": "ToolHost::0" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/input_queue.rs", + "item": "InputQueue::pending" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/input_queue.rs", + "item": "InputQueue::withdraw_checked" + }, { "kind": "host-dispatch", "file": "crates/dim-agent-capabilities/src/input_queue/face.rs", @@ -45,11 +70,46 @@ "file": "crates/dim-agent-capabilities/src/methods.rs", "item": "ForeignMethods" }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/methods.rs", + "item": "ReservedMethods::check_type" + }, { "kind": "host-dispatch", "file": "crates/dim-agent-capabilities/src/permission.rs", "item": "CommandRules" }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::admit_decision" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::decide" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::register_advice" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/permission.rs", + "item": "Permission::update" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/prompt.rs", + "item": "InitialPromptConfiguration::fixed" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/prompt.rs", + "item": "InitialPromptConfiguration::read" + }, { "kind": "host-dispatch", "file": "crates/dim-agent-capabilities/src/prompt_guide.rs", @@ -65,6 +125,16 @@ "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", "item": "BasePromptSettingsHost" }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", + "item": "SessionLanguage::gate" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/prompt_sources.rs", + "item": "SessionLanguage::replace" + }, { "kind": "host-dispatch", "file": "crates/dim-agent-capabilities/src/prompt_suggestion.rs", @@ -80,6 +150,11 @@ "file": "crates/dim-agent-capabilities/src/skills/face.rs", "item": "SkillsCatalog" }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/skills/mod.rs", + "item": "SkillsConfig::instructions" + }, { "kind": "host-dispatch", "file": "crates/dim-agent-capabilities/src/skills/mod.rs", @@ -96,239 +171,234 @@ "item": "SummaryPromptSettingsHost" }, { - "kind": "host-dispatch", - "file": "crates/dim-agent-capabilities/src/tool_registry.rs", - "item": "ForeignRegistry" - }, - { - "kind": "host-dispatch", - "file": "crates/dim-agent-capabilities/src/tool_registry.rs", - "item": "ToolSourcesView" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::activity_after" }, { - "kind": "host-dispatch", - "file": "crates/dim-agent-capabilities/src/toolchain.rs", - "item": "ToolchainSourceHost" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::batch_end" }, { - "kind": "host-dispatch", - "file": "crates/dim-agent-runtime/src/timeline_store_face.rs", - "item": "TimelineStoreBinding" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::branch" }, { - "kind": "host-dispatch", - "file": "crates/dim-agent-scheduler/src/loops.rs", - "item": "LoopsFace" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::default_from" }, { - "kind": "host-dispatch", - "file": "crates/dim-agent-scheduler/src/methods.rs", - "item": "ScheduleJobsFace" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::default_moves" }, { - "kind": "host-dispatch", - "file": "crates/dim-agent-scheduler/src/wakeups.rs", - "item": "WakeupsFace" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::end_with_final" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/agents/sessions.rs", - "item": "SessionsService" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::get" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/collaboration/approvals.rs", - "item": "CollaborationSession" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::head" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/connection.rs", - "item": "ForeignCallChannel" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::inputs" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/hooks_settings.rs", - "item": "HooksService" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::next_move" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/lib.rs", - "item": "LocalIdDispatch" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::page_end" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/managed_provider.rs", - "item": "ManagedSearch" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", + "item": "TreeCommands::turn_ends" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/mcp/face.rs", - "item": "McpService" + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/timeline_tree/read.rs", + "item": "TreeCommands::adopted_configuration" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/plugin_files.rs", - "item": "PluginFiles" + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/timeline_tree/read.rs", + "item": "TreeCommands::display" }, { - "kind": "host-dispatch", - "file": "crates/dim-app-server/src/settings/declared.rs", - "item": "Settings" + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/timeline_tree/read.rs", + "item": "TreeCommands::end_committed" }, { "kind": "host-dispatch", - "file": "crates/dim-app-server/src/storage/face.rs", - "item": "Store" + "file": "crates/dim-agent-capabilities/src/tool_registry.rs", + "item": "ForeignRegistry" }, { "kind": "host-dispatch", - "file": "crates/dim-app-server/src/storage/metadata.rs", - "item": "SessionMetadata" + "file": "crates/dim-agent-capabilities/src/tool_registry.rs", + "item": "ToolSourcesView" }, { "kind": "host-dispatch", - "file": "crates/dim-app-server/src/storage/sqlite.rs", - "item": "SqliteDispatch" + "file": "crates/dim-agent-capabilities/src/toolchain.rs", + "item": "ToolchainSourceHost" }, { - "kind": "host-dispatch", - "file": "crates/dim-event-hub/src/bridge.rs", - "item": "ForeignEventHub" + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/wait.rs", + "item": "Wait::subscription" }, { - "kind": "host-dispatch", - "file": "crates/dim-event-hub/src/bridge.rs", - "item": "ForeignEventSubscriptions" + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/workspace_tools/background.rs", + "item": "BackgroundExec::start" }, { - "kind": "host-dispatch", - "file": "crates/dim-modality/src/targets.rs", - "item": "ModalityTargets" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::batch_end" }, { - "kind": "host-dispatch", - "file": "crates/dim-oauth/src/session_title.rs", - "item": "DimOAuth" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::branch_diagnostics" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/approval.rs", - "item": "Approval::admit" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::configure" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/approval.rs", - "item": "Approval::replay" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::dispatch_watch" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/approval.rs", - "item": "Approval::respond" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::end_branch" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/input_queue.rs", - "item": "InputQueue::pending" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::ended_head" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/input_queue.rs", - "item": "InputQueue::withdraw_checked" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::get" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/permission.rs", - "item": "Permission::admit_decision" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::idle" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/permission.rs", - "item": "Permission::decide" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::input" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/permission.rs", - "item": "Permission::register_advice" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::input_commit" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/permission.rs", - "item": "Permission::update" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::inputs" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/prompt.rs", - "item": "InitialPromptConfiguration::fixed" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::interrupt" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/prompt.rs", - "item": "InitialPromptConfiguration::read" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::lookup" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::activity_after" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::on" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::batch_end" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::publication" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::branch" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::query" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::default_from" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::sequence" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::default_moves" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::service" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::end_with_final" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::set_default_branch" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::get" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::state" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::head" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::stop" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::inputs" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::submit" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::next_move" + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::watch" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::page_end" + "kind": "branch-type", + "file": "crates/dim-agent-runtime/src/branch.rs", + "item": "Branch" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/timeline_tree.rs", - "item": "TreeCommands::turn_ends" + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::admit_opening" }, { - "kind": "service-skip", - "file": "crates/dim-agent-capabilities/src/workspace_tools/background.rs", - "item": "BackgroundExec::start" + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::finish_opening" }, { "kind": "service-skip", @@ -340,11 +410,26 @@ "file": "crates/dim-agent-runtime/src/config.rs", "item": "BranchLifecycle::watch" }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionConfig::exclude_codemode_below" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::faults" + }, { "kind": "service-skip", "file": "crates/dim-agent-runtime/src/config.rs", "item": "SessionLifecycle::phase" }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "SessionLifecycle::report_native_fault" + }, { "kind": "service-skip", "file": "crates/dim-agent-runtime/src/config.rs", @@ -446,135 +531,165 @@ "item": "Timeline::watch" }, { - "kind": "service-skip", - "file": "crates/dim-app-server/src/control.rs", - "item": "ProcessActivity::pause" + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/parts.rs", + "item": "PartRegistry::register" }, { - "kind": "service-skip", - "file": "crates/dim-app-server/src/control.rs", - "item": "ProcessActivity::take_hold" + "kind": "host-dispatch", + "file": "crates/dim-agent-runtime/src/timeline_store_face.rs", + "item": "TimelineStoreBinding" }, { - "kind": "service-skip", - "file": "crates/dim-app-server/src/mcp/session.rs", - "item": "McpSession::subscribe" + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/loops.rs", + "item": "LoopsFace" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::batch_end" + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/methods.rs", + "item": "ScheduleJobsFace" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::branch_diagnostics" + "kind": "host-dispatch", + "file": "crates/dim-agent-scheduler/src/wakeups.rs", + "item": "WakeupsFace" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::configure" + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/agents/sessions.rs", + "item": "SessionPermissions::0" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::dispatch_watch" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/agents/sessions.rs", + "item": "SessionsService" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::end_branch" + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/collaboration.rs", + "item": "CollaborationConfig::leader_description" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::ended_head" + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/collaboration.rs", + "item": "CollaborationConfig::member_description" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::get" + "kind": "rust-only-method", + "file": "crates/dim-app-server/src/collaboration.rs", + "item": "CollaborationDirectory::record" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::idle" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/collaboration/approvals.rs", + "item": "CollaborationSession" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::input" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/connection.rs", + "item": "ForeignCallChannel" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::input_commit" + "kind": "service-skip", + "file": "crates/dim-app-server/src/control.rs", + "item": "ProcessActivity::pause" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::inputs" + "kind": "service-skip", + "file": "crates/dim-app-server/src/control.rs", + "item": "ProcessActivity::take_hold" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::interrupt" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/hooks_settings.rs", + "item": "HooksService" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::lookup" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/lib.rs", + "item": "LocalIdDispatch" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::on" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/managed_provider.rs", + "item": "ManagedSearch" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::publication" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/mcp/face.rs", + "item": "McpService" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::query" + "kind": "service-skip", + "file": "crates/dim-app-server/src/mcp/session.rs", + "item": "McpSession::subscribe" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::sequence" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/plugin_files.rs", + "item": "PluginFiles" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::service" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/settings/declared.rs", + "item": "Settings" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::set_default_branch" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/face.rs", + "item": "Store" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::state" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/metadata.rs", + "item": "SessionMetadata" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::stop" + "kind": "host-dispatch", + "file": "crates/dim-app-server/src/storage/sqlite.rs", + "item": "SqliteDispatch" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::submit" + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/transport.rs", + "item": "ListenAddresses::pipe_name" }, { - "kind": "session-forwarding", - "file": "crates/dim-agent-runtime/src/agent.rs", - "item": "Session::watch" + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/transport.rs", + "item": "ListenAddresses::unix_path" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-app-server/src/transport.rs", + "item": "ListenAddresses::websocket_address" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-app-server/src/ui_extensions/resources.rs", + "item": "UiResources::read" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-event-hub/src/bridge.rs", + "item": "ForeignEventHub" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-event-hub/src/bridge.rs", + "item": "ForeignEventSubscriptions" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-modality/src/targets.rs", + "item": "ModalityTargets" + }, + { + "kind": "host-dispatch", + "file": "crates/dim-oauth/src/session_title.rs", + "item": "DimOAuth" } ], "removed": [] -} \ No newline at end of file +} diff --git a/xtask/check/src/access.rs b/xtask/check/src/access.rs index f55c63c446..0bdac984b9 100644 --- a/xtask/check/src/access.rs +++ b/xtask/check/src/access.rs @@ -1,19 +1,36 @@ //! The access-layer rules of [#2015 §5](https://github.com/arcships/dim/issues/2015) //! and the list that admits the violations still in the tree. //! -//! A violation is one of: `#[service(skip)]` on a service method, a -//! hand-written `HostDispatch` implementation, a `Session` method that takes a -//! line's name, and the outward `Branch` type. The scan reads the product -//! sources (`crates/*/src`) only: a test fixture is not a public face. +//! A violation is one of: +//! +//! - `#[service(skip)]` on a method of a `#[rutis::service]` block; +//! - a method of a service type that takes `self` and is `pub` or +//! `pub(crate)`, written outside its `#[rutis::service]` blocks, or such a +//! field of a service type: Rust callers can use what other languages cannot, +//! which is what `#[service(skip)]` does. A constructor takes no `self` and +//! is not one of these, and a type that serializes has fields of data, the +//! payload a face carries, so its fields are not either; +//! - a hand-written `HostDispatch` implementation; +//! - a `Session` method that takes a line's name, the forwarding shape the +//! refactor removes. It reads the parameter's name (heuristic: the tree's +//! forwarding methods name it `branch`), so a method that takes a line under +//! another name is not found; +//! - the outward `Branch` type. +//! +//! The scan reads the product sources (`crates/*/src`) only: a test fixture is +//! not a public face. //! //! The allowlist (`xtask/access-layer.json`) names every violation the tree -//! still has. `check` fails when a violation is not listed and when a listed -//! entry no longer matches anything, so a change can only remove entries, never -//! add one. The same file's `removed` list names catalog services that a change -//! deleted; the runtime catalog check in `xtask` fails when one comes back. +//! still has. `check` fails when a violation is not listed, and when a listed +//! entry matches fewer occurrences than it is listed for; it cannot see a +//! violation that arrives together with its own entry. Keeping the list from +//! growing is a review rule: a change deletes the entries for what it removes +//! and adds none, so the list empties when the refactor ends. The same file's +//! `removed` list names catalog services a change deleted; the runtime catalog +//! check in `xtask` fails when one comes back. use serde::{Deserialize, Serialize}; use std::{ - collections::BTreeSet, + collections::{BTreeMap, BTreeSet}, path::{Path, PathBuf}, }; @@ -29,6 +46,11 @@ pub const FILE: &str = "xtask/access-layer.json"; pub enum Kind { /// A service method kept out of the face with `#[service(skip)]`. ServiceSkip, + /// A `pub`/`pub(crate)` method that takes `self` on a service type, + /// outside its `#[rutis::service]` blocks. + RustOnlyMethod, + /// A `pub`/`pub(crate)` field of a service type. + RustOnlyField, /// A `HostDispatch` implementation written by hand instead of a /// `#[rutis::service]` block. HostDispatch, @@ -46,22 +68,30 @@ pub struct Rule { pub kind: Kind, /// The source file, from the workspace root. pub file: String, - /// The item: `Type::method` for a method, the type for a type. + /// The item: `Type::method` for a method or field, the type for a type. pub item: String, } impl std::fmt::Display for Rule { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}: {} {}", self.file, self.item, kind_name(self.kind)) + write!( + f, + "{}: {} is {}", + self.file, + self.item, + kind_name(self.kind) + ) } } fn kind_name(kind: Kind) -> &'static str { match kind { - Kind::ServiceSkip => "has #[service(skip)]", - Kind::HostDispatch => "is a hand-written HostDispatch", - Kind::SessionForwarding => "forwards to a line name", - Kind::BranchType => "is an outward Branch type", + Kind::ServiceSkip => "skipped with #[service(skip)]", + Kind::RustOnlyMethod => "a Rust-only method", + Kind::RustOnlyField => "a Rust-only field", + Kind::HostDispatch => "a hand-written HostDispatch", + Kind::SessionForwarding => "a Session method taking a line name", + Kind::BranchType => "the outward Branch type", } } @@ -90,64 +120,96 @@ pub fn load(root: &Path) -> Result { } } -/// Fails when a violation is not allowed or an allowed entry matches nothing. +/// Fails when a violation is not allowed, or an entry matches fewer +/// occurrences than it is listed for. pub fn check(root: &Path) -> Result<()> { - let found: BTreeSet = violations(root)?.into_iter().collect(); - let layer = load(root)?; - let allowed: BTreeSet = layer.allow.iter().cloned().collect(); - if allowed.len() != layer.allow.len() { - let mut seen = BTreeSet::new(); - let duplicates: Vec<_> = layer - .allow - .iter() - .filter(|rule| !seen.insert((*rule).clone())) - .collect(); - return Err(format!("{}: listed twice: {duplicates:?}", FILE).into()); + let mut found: BTreeMap = BTreeMap::new(); + for rule in violations(root)? { + *found.entry(rule).or_default() += 1; + } + let mut allowed: BTreeMap = BTreeMap::new(); + for rule in load(root)?.allow { + *allowed.entry(rule).or_default() += 1; } - let unlisted: Vec<_> = found.difference(&allowed).collect(); - if !unlisted.is_empty() { - let mut message = format!( - "{} access-layer violation(s) are not in {FILE}; the list may only shrink:\n", - unlisted.len() - ); - for rule in unlisted { - message += &format!("{}\n", serde_json::to_string(rule).expect("a rule is JSON")); + let mut problems = String::new(); + for (rule, count) in &found { + let listed = allowed.get(rule).copied().unwrap_or(0); + if listed < *count { + problems += &format!( + "{} ({count} found, {listed} listed)\n", + serde_json::to_string(rule).expect("a rule is JSON") + ); } - return Err(message.into()); } - let stale: Vec<_> = allowed.difference(&found).collect(); - if !stale.is_empty() { - let mut message = format!( - "{} entries of {FILE} match nothing and must be deleted:\n", - stale.len() - ); - for rule in stale { - message += &format!("{rule}\n"); + if !problems.is_empty() { + return Err(format!( + "access-layer violations are not in {FILE}; the list may only shrink:\n{problems}" + ) + .into()); + } + let mut stale = String::new(); + for (rule, listed) in &allowed { + let count = found.get(rule).copied().unwrap_or(0); + if count < *listed { + stale += &format!("{rule} (listed {listed}, {count} found)\n"); } - return Err(message.into()); } - println!("access layer passed ({} allowed)", allowed.len()); + if !stale.is_empty() { + return Err(format!( + "entries of {FILE} match fewer occurrences and must be deleted:\n{stale}" + ) + .into()); + } + println!( + "access layer passed ({} allowed)", + allowed.values().sum::() + ); Ok(()) } /// Every violation in the product sources under `root`. pub fn violations(root: &Path) -> Result> { - let mut found = Vec::new(); + let mut parsed = Vec::new(); for file in sources(root)? { let text = std::fs::read_to_string(&file)?; - let parsed = - syn::parse_file(&text).map_err(|error| format!("{}: {error}", file.display()))?; + let ast = syn::parse_file(&text).map_err(|error| format!("{}: {error}", file.display()))?; let relative = file .strip_prefix(root) .unwrap_or(&file) .to_string_lossy() .replace('\\', "/"); - scan(&parsed.items, &relative, &mut found); + parsed.push((relative, ast)); + } + let mut services = BTreeSet::new(); + for (file, ast) in &parsed { + service_types(crate_name(file), &ast.items, &mut services); + } + let mut found = Vec::new(); + for (file, ast) in &parsed { + scan(&ast.items, file, crate_name(file), &services, &mut found); } found.sort(); Ok(found) } +/// The types that have a `#[rutis::service]` block, by crate: what they offer +/// other languages is that block, and nothing else. +fn service_types(crate_name: &str, items: &[syn::Item], services: &mut BTreeSet<(String, String)>) { + for item in items { + match item { + syn::Item::Impl(block) if block.attrs.iter().any(is_service_attribute) => { + services.insert((crate_name.to_owned(), type_name(&block.self_ty))); + } + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + service_types(crate_name, items, services); + } + } + _ => {} + } + } +} + /// The product source files: every `.rs` under `crates/*/src`. fn sources(root: &Path) -> Result> { let mut files = Vec::new(); @@ -174,78 +236,147 @@ fn collect(directory: &Path, files: &mut Vec) -> Result<()> { Ok(()) } -fn scan(items: &[syn::Item], file: &str, found: &mut Vec) { +fn scan( + items: &[syn::Item], + file: &str, + crate_name: &str, + services: &BTreeSet<(String, String)>, + found: &mut Vec, +) { + let declared = |ty: &str| services.contains(&(crate_name.to_owned(), ty.to_owned())); + let rule = |kind, item: String| Rule { + kind, + file: file.to_owned(), + item, + }; for item in items { - let syn::Item::Impl(block) = item else { - if let syn::Item::Mod(module) = item - && let Some((_, items)) = &module.content - { - scan(items, file, found); + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + scan(items, file, crate_name, services, found); + } } - continue; - }; - let service = block.attrs.iter().any(is_service_attribute); - for method in &block.items { - let syn::ImplItem::Fn(method) = method else { - continue; - }; - if service - && method - .attrs - .iter() - .any(|attr| is_service_attribute(attr) && skips(attr)) + syn::Item::Struct(structure) + if declared(&structure.ident.to_string()) && !serializes(&structure.attrs) => { - found.push(Rule { - kind: Kind::ServiceSkip, - file: file.to_owned(), - item: format!("{}::{}", type_name(&block.self_ty), method.sig.ident), - }); + for (index, field) in structure.fields.iter().enumerate() { + if !outward(&field.vis) { + continue; + } + let name = match &field.ident { + Some(ident) => ident.to_string(), + None => index.to_string(), + }; + found.push(rule( + Kind::RustOnlyField, + format!("{}::{name}", structure.ident), + )); + } } - } - if block - .trait_ - .as_ref() - .and_then(|(_, path, _)| path.segments.last()) - .is_some_and(|segment| segment.ident == "HostDispatch") - { - found.push(Rule { - kind: Kind::HostDispatch, - file: file.to_owned(), - item: type_name(&block.self_ty), - }); - } - if block.trait_.is_none() && type_name(&block.self_ty) == "Session" { - for method in &block.items { - let syn::ImplItem::Fn(method) = method else { - continue; - }; - let named_branch = method.sig.inputs.iter().any(|input| { - matches!(input, syn::FnArg::Typed(typed) - if matches!(&*typed.pat, syn::Pat::Ident(ident) if ident.ident == "branch")) - }); - if named_branch { - found.push(Rule { - kind: Kind::SessionForwarding, - file: file.to_owned(), - item: format!("Session::{}", method.sig.ident), - }); + syn::Item::Impl(block) => { + let ty = type_name(&block.self_ty); + let service = block.attrs.iter().any(is_service_attribute); + for method in &block.items { + let syn::ImplItem::Fn(method) = method else { + continue; + }; + if service { + if method + .attrs + .iter() + .any(|attr| is_service_attribute(attr) && skips(attr)) + { + found.push(rule( + Kind::ServiceSkip, + format!("{ty}::{}", method.sig.ident), + )); + } + } else if declared(&ty) + && outward(&method.vis) + && method.sig.receiver().is_some() + { + found.push(rule( + Kind::RustOnlyMethod, + format!("{ty}::{}", method.sig.ident), + )); + } + } + if block + .trait_ + .as_ref() + .and_then(|(_, path, _)| path.segments.last()) + .is_some_and(|segment| segment.ident == "HostDispatch") + { + found.push(rule(Kind::HostDispatch, ty.clone())); + } + if block.trait_.is_none() && ty == "Session" { + for method in &block.items { + let syn::ImplItem::Fn(method) = method else { + continue; + }; + let named_line = method.sig.inputs.iter().any(|input| { + matches!(input, syn::FnArg::Typed(typed) + if matches!(&*typed.pat, syn::Pat::Ident(ident) if ident.ident == "branch")) + }); + if named_line { + found.push(rule( + Kind::SessionForwarding, + format!("Session::{}", method.sig.ident), + )); + } + } } } + syn::Item::Struct(item) + if matches!(item.vis, syn::Visibility::Public(_)) && item.ident == "Branch" => + { + found.push(rule(Kind::BranchType, "Branch".into())); + } + syn::Item::Enum(item) + if matches!(item.vis, syn::Visibility::Public(_)) && item.ident == "Branch" => + { + found.push(rule(Kind::BranchType, "Branch".into())); + } + _ => {} } } - for item in items { - let (visibility, ty) = match item { - syn::Item::Struct(item) => (&item.vis, &item.ident), - syn::Item::Enum(item) => (&item.vis, &item.ident), - _ => continue, - }; - if matches!(visibility, syn::Visibility::Public(_)) && ty == "Branch" { - found.push(Rule { - kind: Kind::BranchType, - file: file.to_owned(), - item: ty.to_string(), - }); - } +} + +/// The crate a product source file belongs to, as its directory name. +fn crate_name(file: &str) -> &str { + file.strip_prefix("crates/") + .and_then(|rest| rest.split_once('/')) + .map(|(name, _)| name) + .unwrap_or(file) +} + +/// Whether a type serializes: its fields are the data a face carries, which +/// other languages read and write, not state a caller reaches around the face. +fn serializes(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(|attr| { + attr.path().is_ident("derive") + && attr + .parse_args_with( + syn::punctuated::Punctuated::::parse_terminated, + ) + .is_ok_and(|derives| { + derives.iter().any(|derive| { + derive + .segments + .last() + .is_some_and(|segment| segment.ident == "Serialize") + }) + }) + }) +} + +/// Whether a visibility lets a caller in another module of this crate use the +/// item: `pub` or `pub(crate)`. +fn outward(visibility: &syn::Visibility) -> bool { + match visibility { + syn::Visibility::Public(_) => true, + syn::Visibility::Restricted(restricted) => restricted.path.is_ident("crate"), + syn::Visibility::Inherited => false, } } From 09b0ac8728c70e8ded77c808ad6c64ca9b483bf8 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 19:23:30 +0800 Subject: [PATCH 04/37] feat(typescript): declare the addressed route a plugin authors against A plugin of any language names a Session's or a line's data face by id and calls the target's own operations: `session(sessionId).line(lineId)` for a process part, `line(lineId)` for a Session part, with the ids recorded and looked up at every call (ADR 027 D4). `npm/branch-services.d.ts` declares the addresses from the assembled catalog, listing the data faces a route resolves in each scope, so an author writes a typed call instead of a service name, a method name and untyped arguments. Rust writes the same shape as `session(&route, id).line(id).owner::()` and `line(&line_route, id).owner::()`, then calls the owner's own operations; `line_owner::(&line_route, lineId)` is that resolution in one call. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 6 + crates/dim-agent-runtime/src/route.rs | 98 ++++++++++++-- npm/branch-services.d.ts | 40 ++++++ runtime/fixtures/branch-addresses.ts | 23 ++++ runtime/plugin-sdk.test.mjs | 5 +- xtask/check/src/types.rs | 128 +++++++++++++++++- 6 files changed, 285 insertions(+), 15 deletions(-) create mode 100644 runtime/fixtures/branch-addresses.ts diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 0e59e6183b..f1020f22c3 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -251,6 +251,12 @@ async fn a_session_part_reaches_its_own_line_by_id_only() { } ); assert!(line_owner::(&route, "main").is_ok()); + assert!( + dim_agent_runtime::line(&route, "main") + .owner::() + .is_ok(), + "the address form resolves at the call" + ); assert_eq!( line_owner::(&route, "main").err(), Some(RouteError::NotDataFace { diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index a392ebaa13..0434a7d748 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -338,17 +338,93 @@ impl LineRoute { } } -/// The line-scope data face `T` of this Session's line `line_id`: the Rust -/// binding of [`LineRoute::line`]. -pub fn line_owner(route: &LineRoute, line_id: &str) -> Routed> { - let line = route.live_line(line_id)?; - face( - line.catalog(), - line.faces(), - &names::name_of::(), - BRANCH_GROUP, - )?; - line.public::().map_err(owner) +/// An address a caller may keep: ids only, looked up at every call +/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D4). Rust +/// writes the authoring shape this way: `session(&route, id).line(id)`, then +/// the owner's own operations through [`LineAddress::owner`]. +pub struct SessionAddress { + index: Arc, + session_id: String, +} + +/// The address of one line, of [`SessionAddress::line`] or of [`LineRoute`]'s +/// own Session. +pub struct LineAddress { + scope: Scope, + line_id: String, +} + +enum Scope { + /// A Session of the process route, named by its id. + Named { + index: Arc, + session_id: String, + }, + /// The caller's own Session, which names no Session. + Own(Arc), +} + +impl LineAddress { + /// The line-scope data face `T`, resolved now. + pub fn owner(&self) -> Routed> { + let line = match &self.scope { + Scope::Named { index, session_id } => index.line(session_id, &self.line_id)?, + Scope::Own(route) => route.live_line(&self.line_id)?, + }; + face( + line.catalog(), + line.faces(), + &names::name_of::(), + BRANCH_GROUP, + )?; + line.public::().map_err(owner) + } +} + +impl SessionAddress { + /// The line `line_id` of this Session, addressed and not looked up. + pub fn line(&self, line_id: &str) -> LineAddress { + LineAddress { + scope: Scope::Named { + index: self.index.clone(), + session_id: self.session_id.clone(), + }, + line_id: line_id.to_owned(), + } + } + + /// The Session-scope data face `T`, resolved now. + pub fn owner(&self) -> Routed> { + let session = self.index.session(&self.session_id)?; + session.session_face::().map_err(owner) + } +} + +/// Addresses Session `session_id` of the process [`Route`]: nothing is looked +/// up until a method is called. +pub fn session(route: &Arc, session_id: &str) -> SessionAddress { + SessionAddress { + index: route.index.clone(), + session_id: session_id.to_owned(), + } +} + +/// Addresses line `line_id` of the caller's own Session: nothing is looked up +/// until a method is called. +pub fn line(route: &Arc, line_id: &str) -> LineAddress { + LineAddress { + scope: Scope::Own(route.clone()), + line_id: line_id.to_owned(), + } +} + +/// The line-scope data face `T` of this Session's line `line_id`: [`line`] and +/// [`LineAddress::owner`] in one call. +pub fn line_owner( + route: &Arc, + line_id: &str, +) -> Routed> { + line(route, line_id).owner::() } /// Fails unless a route may resolve `service` as a data face of `group` diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 25b96d8619..d46abece2b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1903,3 +1903,43 @@ export interface Services { listenAddresses: ListenAddresses uiResources: UiResources } + +/** + * A Session's data faces, addressed by id: nothing is looked up until a method of + * one is called, and each call looks the target up again. + */ +export interface SessionAddress { + /** This Session's line `lineId`. */ + line(lineId: string): LineAddress + agentConfig: AgentConfig + collaborationConfig: CollaborationConfig + initialPromptConfiguration: InitialPromptConfiguration + mcpSession: McpSession + sessionConfig: SessionConfig + sessionIdentity: SessionIdentity + sessionLanguage: SessionLanguage + sessionLoader: SessionLoader + skillsConfig: SkillsConfig + toolHost: ToolHost + treeCommands: TreeCommands + uiResources: UiResources +} + +/** A line's data faces, addressed by id. */ +export interface LineAddress { + approval: Approval + backgroundExec: BackgroundExec + branchLine: BranchLine + dispatcher: Dispatcher + inputQueue: InputQueue + permission: Permission + timeline: Timeline + timelineIdentity: TimelineIdentity + wait: Wait +} + +/** Addresses Session `sessionId`; every call looks it up again. */ +export declare function session(sessionId: string): SessionAddress + +/** Addresses line `lineId` of this Session; every call looks it up again. */ +export declare function line(lineId: string): LineAddress diff --git a/runtime/fixtures/branch-addresses.ts b/runtime/fixtures/branch-addresses.ts new file mode 100644 index 0000000000..9c96209ab7 --- /dev/null +++ b/runtime/fixtures/branch-addresses.ts @@ -0,0 +1,23 @@ +// A plugin of any language calls a Session's or a line's data face by id: the +// address records ids only, and every call looks the target up again +// (ADR 027 D4, #2127). `session(...)` is the runtime's entry for a process +// part; `line(...)` is the one a Session part uses, and it names no Session. +import { line, session } from '../../npm/branch-services.js' +import type { Withdrawal } from '../../npm/branch-services.js' + +export async function readThroughAddresses(sessionId: string, inputId: string): Promise { + const lineAddress = session(sessionId).line('main') + const ending: boolean = await lineAddress.branchLine.ending() + const cursor: number | bigint | null = await lineAddress.branchLine.cursor('read') + const withdrawn: Withdrawal = await lineAddress.inputQueue.withdraw({ input_id: inputId }) + void [ending, cursor, withdrawn] + + const own = line('main') + const ownEnding: boolean = await own.branchLine.ending() + void ownEnding +} + +// @ts-expect-error a Session address reaches a line, not a line's faces. +export const queue = session('session').inputQueue +// @ts-expect-error a Session part's line address names no Session. +export const foreign = line('main', 'other') diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index 8c9303a163..2ee2ead310 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -53,6 +53,9 @@ test('packed plugin service types compile the author guide and enforce the publi .replace("'./part-row.ts'", "'./part-row.mjs'")); return file; }); + const addressesFixture = path.join(directory, 'branch-addresses.mts'); + writeFileSync(addressesFixture, readFileSync(path.join(root, 'runtime/fixtures/branch-addresses.ts'), 'utf8') + .replaceAll("'../../npm/branch-services.js'", "'dimcode/branch-services.js'")); const calls = path.join(directory, 'calls.mts'); writeFileSync(calls, ` import type { Settings, SettingsResult, Sessions, WorkflowFiles, WorkflowFileEntry, WorkflowFilesErrorThrown, SessionPermissions, PermissionState, PermissionPolicy, SessionsErrorThrown, SessionMetadata, SessionMetadataResult, AuxiliaryModel, AuxiliaryReply, FileScope, FileResult, ToolRegistry, ToolExecute, ToolResult, SessionMethods, SessionMethodHandler, ManagementMethods, MethodHandler, MethodDeclaration, SessionConfig, SessionBroadcast, BranchEvent, Services, AgentErrorThrown, MethodReply, CallChannel, CallChannelError, EventHub, EventHubDeclaration, EventHubDelivery, EventHubErrorThrown, EventHubPublishReply } from 'dimcode/plugin'; @@ -370,6 +373,6 @@ void panel; assert.equal(declarations.status, 0, declarations.stdout + declarations.stderr); const checked = spawnSync(process.execPath, [compiler, '--strict', '--noEmit', '--target', 'ES2022', '--module', 'NodeNext', '--moduleResolution', 'NodeNext', - ...files, ...promptFixtures, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); + ...files, ...promptFixtures, addressesFixture, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); assert.equal(checked.status, 0, checked.stdout + checked.stderr); }); diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index f1288fc925..014f78c179 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -1,6 +1,9 @@ //! `types` writes the TypeScript declarations of the services marked //! `#[rutis::service]` that `dim-app-server` serves (rutis usage §3.4) to -//! `npm/branch-services.d.ts`; `check` fails when that file is stale. +//! `npm/branch-services.d.ts`, and the addresses a plugin of any language uses +//! to call a Session's or a line's data face by id +//! ([#2127](https://github.com/arcships/dim/issues/2127)); `check` fails when +//! that file is stale. use std::path::{Path, PathBuf}; type Result = std::result::Result>; @@ -9,8 +12,125 @@ fn file(root: &Path) -> PathBuf { root.join("npm/branch-services.d.ts") } +/// The names routing does not resolve, read from the runtime that refuses +/// them: its registration points and the two lifecycle services. +fn unroutable(root: &Path) -> Result> { + let path = root.join("crates/dim-agent-runtime/src/route.rs"); + let source = std::fs::read_to_string(&path)?; + let ast = syn::parse_file(&source).map_err(|error| format!("{}: {error}", path.display()))?; + let mut names = vec!["sessionLifecycle".to_owned(), "branchLifecycle".to_owned()]; + for item in &ast.items { + let syn::Item::Const(declaration) = item else { + continue; + }; + if declaration.ident != "REGISTRATION_POINTS" { + continue; + } + if let syn::Expr::Array(array) = &*declaration.expr { + for element in &array.elems { + if let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(name), + .. + }) = element + { + names.push(name.value()); + } + } + } + } + Ok(names) +} + +/// The addresses over the two routable scopes: each member is a data face a +/// route resolves there, named as its catalog name, typed by the interface +/// this file already declares for it. +fn addresses(root: &Path, declarations: &str) -> Result { + let catalog = + std::fs::read_to_string(root.join("docs/architecture/rust-agent/generated/catalog.md"))?; + let unroutable = unroutable(root)?; + let declared: Vec<&str> = declarations + .lines() + .filter_map(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + }) + .collect(); + let mut session = Vec::new(); + let mut line = Vec::new(); + for row in catalog.lines().filter(|line| line.starts_with("| `")) { + let cells: Vec<&str> = row.split('|').map(str::trim).collect(); + let Some(name) = cells.get(1).and_then(|name| name.strip_prefix('`')) else { + continue; + }; + let Some(name) = name.strip_suffix('`') else { + continue; + }; + let (group, face) = match (cells.get(2), cells.get(4)) { + (Some(group), Some(face)) => (*group, *face), + _ => continue, + }; + if face != "data" || name == "route" || name == "lineRoute" { + continue; + } + if unroutable.iter().any(|refused| refused == name) { + continue; + } + let Some(ty) = declared.iter().find(|ty| catalog_name(ty) == name).copied() else { + continue; + }; + match group { + "session" => session.push((name.to_owned(), ty.to_owned())), + "branch" => line.push((name.to_owned(), ty.to_owned())), + _ => {} + } + } + let mut text = String::from( + "\n/**\n * A Session's data faces, addressed by id: nothing is looked up until a method of\n * one is called, and each call looks the target up again.\n */\nexport interface SessionAddress {\n /** This Session's line `lineId`. */\n line(lineId: string): LineAddress\n", + ); + for (name, ty) in &session { + text += &format!(" {name}: {ty}\n"); + } + text += "}\n\n/** A line's data faces, addressed by id. */\nexport interface LineAddress {\n"; + for (name, ty) in &line { + text += &format!(" {name}: {ty}\n"); + } + text += "}\n\n/** Addresses Session `sessionId`; every call looks it up again. */\nexport declare function session(sessionId: string): SessionAddress\n\n/** Addresses line `lineId` of this Session; every call looks it up again. */\nexport declare function line(lineId: string): LineAddress\n"; + Ok(text) +} + +/// The catalog name of a Rust type: its type name with the leading word +/// lowercased, as `#[rutis::service]` names a type (`InputQueue` is +/// `inputQueue`). +fn catalog_name(type_name: &str) -> String { + let ident = type_name + .trim_start_matches("dyn ") + .split(['<', ' ']) + .next() + .unwrap_or(type_name); + let ident = ident.rsplit("::").next().unwrap_or(ident); + let chars: Vec = ident.chars().collect(); + let upper = chars.iter().take_while(|c| c.is_uppercase()).count(); + let lower = if upper > 1 && upper < chars.len() && chars[upper].is_lowercase() { + upper - 1 + } else { + upper.max(1).min(chars.len()) + }; + chars + .iter() + .enumerate() + .flat_map(|(index, c)| { + if index < lower { + c.to_lowercase().collect::>() + } else { + vec![*c] + } + }) + .collect() +} + fn declarations(root: &Path) -> Result { - rutis_types::Exports::new() + let services = rutis_types::Exports::new() .declared("serde_json::Value", "import('./plugin.js').BridgeJsonValue") .declared("serde_json::Map", "import('./plugin.js').BridgeJsonObject") .declared( @@ -54,7 +174,9 @@ fn declarations(root: &Path) -> Result { "dim_agent_types::TimelinePosition", "{ branch_id: string; sequence: number | bigint }", ) - .declarations(root.join("crates/dim-app-server")) + .declarations(root.join("crates/dim-app-server"))?; + let addresses = addresses(root, &services)?; + Ok(services + &addresses) } pub fn write(root: &Path) -> Result<()> { From 1f153538e72e0267409acba0dbe0537a00076624 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 19:59:07 +0800 Subject: [PATCH 05/37] refactor(runtime): look a Session and its lines up through their owners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The route object is gone. Each owner keeps its own index and does the lookup ([ADR 027](../../docs/adr/027-cross-scope-access-by-id.md) D2, #2127): - a Session's `sessionScope` (Session group) resolves one of its own lines and its own faces, and names no Session at all; - Agents' `sessions` resolves a Session, then a line of it, for the process. Two data operations carry every routed call, with the same arguments in every language: `sessionScope.lineCall({lineId, service, method, args})` and `sessions.call({sessionId, lineId?, service, method, args})`. The authoring form is generated over them — `sessionScope.line(lineId).inputQueue.withdraw(id)` for a Session part, `sessions.session(sessionId).line(lineId).inputQueue.withdraw(id)` for a process part, declared in `npm/branch-services.d.ts` from the assembled catalog, and `line(&scope, lineId).get::()` in Rust. Reach is judged once, in the runtime, for the data path and every typed entry: a name the assembly marks internal, a registration point and a lifecycle service answer `NotDataFace`, and a face of the other scope `WrongScope`. `RouteError` is the only routing error: `AgentError` and `SessionFault` carry none, and an owner's own failure keeps its name and message. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 357 ++++------------ crates/dim-agent-runtime/src/agent.rs | 6 - crates/dim-agent-runtime/src/assembly.rs | 30 +- crates/dim-agent-runtime/src/error.rs | 27 -- crates/dim-agent-runtime/src/names.rs | 3 +- crates/dim-agent-runtime/src/route.rs | 389 +++++------------- crates/dim-agent-runtime/src/scope.rs | 8 +- .../tests/data_faces_flow.rs | 85 ++++ crates/dim-app-server/src/agents.rs | 58 ++- crates/dim-app-server/src/agents/sessions.rs | 25 +- .../dim-app-server/src/session_typescript.rs | 12 +- npm/branch-services.d.ts | 85 ++-- runtime/fixtures/branch-addresses.ts | 37 +- tests/integration/tests/extensions.rs | 2 +- xtask/check/src/types.rs | 13 +- 15 files changed, 428 insertions(+), 709 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index f1020f22c3..9e4878996f 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -1,13 +1,13 @@ -//! Flow: a call by id reaches the data face of a live Session or line, and -//! answers `NoSession`, `SessionClosing`, `NoLine` or a reach refusal -//! otherwise ([#2127](https://github.com/arcships/dim/issues/2127)). +//! Flow: a Session's parts and their runtimes reach its own lines and faces by +//! id, and answer `SessionClosing`, `NoLine` or a reach refusal otherwise +//! ([#2127](https://github.com/arcships/dim/issues/2127)). use dim_agent_capabilities::{defaults, timeline_tree::BranchLine}; use dim_agent_runtime::testing::{MinimalHost, hold_close}; use dim_agent_runtime::*; use dim_agent_types::BranchSource; use rutis::Ctx; -use rutis::host::{CtxHost, DynPlugin, Effect, InstanceId, Key, TypeKey}; +use rutis::host::{CtxHost, DynPlugin, Effect, InstanceId, TypeKey}; use rutis_bridge::session::{ Connection, Dispatch, Endpoint, Error as BridgeError, HostDispatch, Reply, Value, host_key, host_key_in, @@ -36,8 +36,7 @@ impl DynPlugin for HandsSession { struct Rig { host: MinimalHost, - route: Arc, - /// The context of the last Session's part, once that Session opened. + /// The context of the last Session's probe part, once that Session opened. session_ctx: Arc>>, } @@ -60,15 +59,7 @@ impl Rig { }), ); let host = MinimalHost::start(&builder).await.unwrap(); - let route = host - .root() - .get_at::(&Key::::of()) - .expect("the host serves the route"); - Self { - host, - route, - session_ctx, - } + Self { host, session_ctx } } async fn open(&self) -> Session { @@ -86,25 +77,21 @@ impl Rig { .expect("the Session's part loaded") } - fn line_route(&self, session: &Session) -> Arc { + fn scope(&self, session: &Session) -> Arc { session - .session_service::() - .expect("the Session serves its line route") + .session_service::() + .expect("the Session serves its scope") } } -/// A language runtime's side of a rutis session: it names a service in `ctx`'s -/// subtree, and the host serves it. +/// A language runtime's side of a rutis session: it names a service in the +/// instance the runtime lives in, then at the process. struct Names { ctx: Ctx, - /// The instance the runtime lives in: its names are served there first, - /// then at the process. instance: InstanceId, } impl Names { - /// The dispatch `target` names for this runtime, as a row of another - /// language resolves one. fn dispatch(&self, target: &str) -> Arc { self.ctx .get_at::(&host_key_in(target, self.instance)) @@ -119,7 +106,6 @@ impl Dispatch for Names { } } -/// Both ends of a rutis session with the tree of `ctx`. struct Language { _host: Connection, client: Connection, @@ -133,8 +119,8 @@ impl Language { ctx: ctx.clone(), instance, }; - let host = Connection::open(host, Arc::new(names()), peer("route-host")).unwrap(); - let client = Connection::open(far, Arc::new(names()), peer("route-client")).unwrap(); + let host = Connection::open(host, Arc::new(names()), peer("scope-host")).unwrap(); + let client = Connection::open(far, Arc::new(names()), peer("scope-client")).unwrap(); Self { _host: host, client, @@ -157,144 +143,55 @@ impl Language { .expect("the far end answers")? .json() } - - async fn refused(&self, face: &str, method: &str, call: impl serde::Serialize) -> String { - self.call(face, method, call) - .await - .expect_err("the route refuses the call") - .to_string() - } } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_process_call_reaches_the_live_session_and_line() { +async fn a_session_part_reaches_its_own_line_and_its_own_faces() { let rig = Rig::start().await; let session = rig.open().await; - let id = session.id().to_owned(); + let scope = rig.scope(&session); - let served = rig - .route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) - .await - .unwrap(); - assert_eq!(served, serde_json::to_value(session.config()).unwrap()); - let sequence = rig - .route - .line(LineFaceCall::new( - &id, - "main", - "timeline", - "sequence", - vec![], - )) + let sequence = scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) .await .unwrap(); assert_eq!( sequence, serde_json::json!(session.sequence("main").unwrap()) ); - assert_eq!( - rig.route - .session(SessionFaceCall::new( - "absent", - "sessionConfig", - "get", - vec![] - )) - .await - .unwrap_err(), - RouteError::NoSession("absent".into()) - ); - assert_eq!( - rig.route - .line(LineFaceCall::new( - &id, - "absent", - "timeline", - "sequence", - vec![] - )) + scope + .line_call(LineCall::new("absent", "timeline", "sequence", vec![])) .await .unwrap_err(), RouteError::NoLine { - session: id.clone(), + session: session.id().into(), line: "absent".into() } ); - rig.host.close().await.unwrap(); -} -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_session_part_reaches_its_own_line_by_id_only() { - let rig = Rig::start().await; - let session = rig.open().await; - let id = session.id().to_owned(); - let route = rig.line_route(&session); - - let sequence = route - .line(OwnLineCall::new("main", "timeline", "sequence", vec![])) + let config = scope + .call(SessionCall::new("sessionConfig", "get", vec![])) .await .unwrap(); + assert_eq!(config, serde_json::to_value(session.config()).unwrap()); + + assert!(line(&scope, "main").get::().is_ok()); assert_eq!( - sequence, - serde_json::json!(session.sequence("main").unwrap()) - ); - assert_eq!( - route - .line(OwnLineCall::new("absent", "timeline", "sequence", vec![])) - .await - .unwrap_err(), - RouteError::NoLine { - session: id.clone(), - line: "absent".into() - } - ); - assert!(line_owner::(&route, "main").is_ok()); - assert!( - dim_agent_runtime::line(&route, "main") - .owner::() - .is_ok(), - "the address form resolves at the call" - ); - assert_eq!( - line_owner::(&route, "main").err(), + line(&scope, "main").get::().err(), Some(RouteError::NotDataFace { service: "loopState".into() }), - "the Rust binding resolves data faces only" + "the line's typed read resolves data faces only" ); - rig.host.close().await.unwrap(); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_language_call_reaches_a_line_face_through_the_route() { - let rig = Rig::start().await; - let session = rig.open().await; - let id = session.id().to_owned(); - let language = Language::open(rig.host.root(), rig.host.root().instance()); - language.client.ready().await.unwrap(); - - let sequence = language - .call( - "route", - "line", - LineFaceCall::new(&id, "main", "timeline", "sequence", vec![]), - ) - .await - .unwrap(); + assert!(session_face::(&scope).is_ok()); assert_eq!( - sequence, - serde_json::json!(session.sequence("main").unwrap()) + session_face::(&scope).err(), + Some(RouteError::NotDataFace { + service: "sessionMethods".into() + }), + "the Session's typed read refuses a registration point too" ); - let error = language - .refused( - "route", - "line", - LineFaceCall::new(&id, "absent", "timeline", "sequence", vec![]), - ) - .await; - assert!(error.contains("no line"), "{error}"); rig.host.close().await.unwrap(); } @@ -302,15 +199,15 @@ async fn a_language_call_reaches_a_line_face_through_the_route() { async fn a_session_language_call_reaches_its_own_line_and_names_no_session() { let rig = Rig::start().await; let session = rig.open().await; - let id = session.id().to_owned(); - let language = Language::open(&rig.session_ctx(), session.instance().unwrap()); + let ctx = rig.session_ctx(); + let language = Language::open(&ctx, session.instance().unwrap()); language.client.ready().await.unwrap(); let sequence = language .call( - "lineRoute", - "line", - OwnLineCall::new("main", "timeline", "sequence", vec![]), + "sessionScope", + "lineCall", + LineCall::new("main", "timeline", "sequence", vec![]), ) .await .unwrap(); @@ -325,78 +222,11 @@ async fn a_session_language_call_reaches_its_own_line_and_names_no_session() { "method": "sequence", "args": [], }); - let error = language.refused("lineRoute", "line", carried).await; - assert!( - error.contains("unknown field") && error.contains("sessionId"), - "a Session route names no Session: {error}" - ); - assert!( - language - .call( - "lineRoute", - "line", - OwnLineCall::new("main", "timeline", "sequence", vec![]) - ) - .await - .is_ok(), - "the Session's own line still answers {id}" - ); - rig.host.close().await.unwrap(); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_idle_unloaded_session_answers_no_session_until_it_loads_again() { - let rig = Rig::start().await; - let session = rig.open().await; - let id = session.id().to_owned(); - - assert!( - session.unload_if_idle().await.unwrap(), - "an idle Session unloads" - ); - assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) - .await - .unwrap_err(), - RouteError::NoSession(id.clone()) - ); - - let restored = rig.host.restore_session(id.clone()).await.unwrap(); - assert!( - rig.route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) - .await - .is_ok() - ); - assert!( - rig.line_route(&restored) - .line(OwnLineCall::new("main", "timeline", "sequence", vec![])) - .await - .is_ok() - ); - restored.close().await.unwrap(); - rig.host.close().await.unwrap(); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_session_closed_by_business_answers_no_session_and_keeps_no_instance_to_hold() { - let rig = Rig::start().await; - let session = rig.open().await; - let id = session.id().to_owned(); - - session.close().await.unwrap(); - assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) - .await - .unwrap_err(), - RouteError::NoSession(id.clone()) - ); - assert!( - rig.host.get_session(&id).is_none(), - "a closed Session has no live instance for a hold to keep" - ); + let failed = language + .call("sessionScope", "lineCall", carried) + .await + .expect_err("a Session call names no Session"); + assert!(failed.to_string().contains("unknown field"), "{failed}"); rig.host.close().await.unwrap(); } @@ -405,7 +235,7 @@ async fn a_closing_session_answers_session_closing_for_its_lines_too() { let rig = Rig::start().await; let session = rig.open().await; let id = session.id().to_owned(); - let line_route = rig.line_route(&session); + let scope = rig.scope(&session); let mut held = hold_close(&id, "main"); let closing = { let session = session.clone(); @@ -414,41 +244,21 @@ async fn a_closing_session_answers_session_closing_for_its_lines_too() { held.arrived().await; assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) .await .unwrap_err(), RouteError::SessionClosing(id.clone()) ); assert_eq!( - rig.route - .line(LineFaceCall::new( - &id, - "main", - "timeline", - "sequence", - vec![] - )) - .await - .unwrap_err(), - RouteError::SessionClosing(id.clone()) - ); - assert_eq!( - line_route - .line(OwnLineCall::new("main", "timeline", "sequence", vec![])) + scope + .call(SessionCall::new("sessionConfig", "get", vec![])) .await .unwrap_err(), RouteError::SessionClosing(id.clone()) ); held.release(); closing.await.unwrap().unwrap(); - assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) - .await - .unwrap_err(), - RouteError::NoSession(id.clone()) - ); rig.host.close().await.unwrap(); } @@ -457,10 +267,11 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive let rig = Rig::start().await; let session = rig.open().await; let id = session.id().to_owned(); + let scope = rig.scope(&session); let source = || BranchSource::Host { operation_id: "routing".into(), }; - let line = session + let line_id = session .branch( "main".into(), 0, @@ -472,30 +283,17 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive .await .unwrap(); assert!( - rig.route - .line(LineFaceCall::new( - &id, - &line, - "timeline", - "sequence", - vec![] - )) + scope + .line_call(LineCall::new(&line_id, "timeline", "sequence", vec![])) .await .is_ok() ); - session.end_branch(&line, source()).await.unwrap(); + session.end_branch(&line_id, source()).await.unwrap(); let deadline = Instant::now() + Duration::from_secs(30); loop { - let answer = rig - .route - .line(LineFaceCall::new( - &id, - &line, - "timeline", - "sequence", - vec![], - )) + let answer = scope + .line_call(LineCall::new(&line_id, "timeline", "sequence", vec![])) .await; if matches!(answer, Err(RouteError::NoLine { .. })) { break; @@ -507,23 +305,18 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive tokio::time::sleep(Duration::from_millis(10)).await; } assert!( - rig.route - .session(SessionFaceCall::new(&id, "sessionConfig", "get", vec![])) + scope + .call(SessionCall::new("sessionConfig", "get", vec![])) .await .is_ok(), "one line's end does not affect the Session's other calls" ); assert!( - rig.route - .line(LineFaceCall::new( - &id, - "main", - "timeline", - "sequence", - vec![] - )) + scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) .await - .is_ok() + .is_ok(), + "the Session's own main line still answers {id}" ); rig.host.close().await.unwrap(); } @@ -532,13 +325,12 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { let rig = Rig::start().await; let session = rig.open().await; - let id = session.id().to_owned(); - let route = rig.line_route(&session); + let scope = rig.scope(&session); for service in ["sessionMethods", "toolRegistry", "guideEntries"] { assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, service, "register", vec![])) + scope + .call(SessionCall::new(service, "register", vec![])) .await .unwrap_err(), RouteError::NotDataFace { @@ -549,8 +341,8 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { } for service in ["sessionLifecycle", "branchLifecycle"] { assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, service, "closing", vec![])) + scope + .call(SessionCall::new(service, "closing", vec![])) .await .unwrap_err(), RouteError::NotDataFace { @@ -560,8 +352,8 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { ); } assert_eq!( - rig.route - .line(LineFaceCall::new(&id, "main", "loopState", "state", vec![])) + scope + .line_call(LineCall::new("main", "loopState", "state", vec![])) .await .unwrap_err(), RouteError::NotDataFace { @@ -570,8 +362,8 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { "an internal face is not a data face" ); assert_eq!( - rig.route - .session(SessionFaceCall::new(&id, "timeline", "sequence", vec![])) + scope + .call(SessionCall::new("timeline", "sequence", vec![])) .await .unwrap_err(), RouteError::WrongScope { @@ -581,8 +373,8 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { "a line face is not a Session face" ); assert_eq!( - route - .line(OwnLineCall::new("main", "sessionConfig", "get", vec![])) + scope + .line_call(LineCall::new("main", "sessionConfig", "get", vec![])) .await .unwrap_err(), RouteError::WrongScope { @@ -591,9 +383,8 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { }, "a Session face is not a line face" ); - let error = rig - .route - .line(LineFaceCall::new(&id, "main", "timeline", "absent", vec![])) + let error = scope + .line_call(LineCall::new("main", "timeline", "absent", vec![])) .await .unwrap_err(); let RouteError::Owner { name, message } = error else { diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 21e34fa99f..86020e5fb0 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -499,11 +499,6 @@ impl Session { /// begin the background work they deferred during assembly. fn activate(&self) { self.0.owner.lifecycle.advance(SessionPhase::Active); - self.0 - .owner - .assembly - .route - .register(self.id(), Arc::downgrade(&self.0.owner)); let weak = Arc::downgrade(&self.0); let mut faults = self.0.owner.lifecycle.faults.watch(); let stop = self.0.owner.closing.clone(); @@ -924,7 +919,6 @@ impl Session { store.remove_session(this.id()); } } - this.0.owner.assembly.route.forget(this.id(), &this.0.owner); *this.0.owner.loaded.lock().unwrap() = None; span.record( "outcome", diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 1a8580ae7e..638398e126 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -250,7 +250,7 @@ type ExtensionMake = Arc< >; /// Builds one plugin of an extension copy. type ExtensionPart = Box std::result::Result, Error> + Send + Sync>; -type Provide = Arc std::result::Result<(), Error> + Send + Sync>; +type Provide = Arc std::result::Result<(), Error> + Send + Sync>; /// A value registered with [`AgentBuilder::process_value`]: its name, and /// how a copy provides it at the key the name has there. #[derive(Clone)] @@ -290,9 +290,6 @@ pub(crate) struct Assembly { /// The parts plugins register: the builder's, for the host that builds /// its Agents ([`AgentBuilder::build`]); the minimal host takes a fresh one. pub parts: Arc, - /// The Sessions this builder's Agents publish, for calls by id - /// ([`Route`]). - pub route: Arc, /// Registered parts the profile requires, by name. required_parts: Arc>, /// The rows a Session and a branch need Active, as [`AgentBuilder::install`] @@ -367,7 +364,6 @@ impl AgentBuilder { features: Default::default(), optional_plugins: Default::default(), parts: Arc::default(), - route: Arc::default(), required_parts: Arc::default(), required_rows: Arc::default(), extensions: vec![], @@ -499,21 +495,13 @@ impl AgentBuilder { key: names.key()?, })) }); - let route = self.assembly.route.clone(); - let route: PartMake = Arc::new(move |names| { - Ok(Box::new(crate::route::RoutePlugin { - index: route.clone(), - key: names.key()?, - })) - }); let mut rows = vec![]; let mut optional_rows = vec![]; - let optional = std::iter::once(false).chain(std::iter::once(false)).chain( + let optional = std::iter::once(false).chain( (0..self.assembly.plugins.len()) .map(|index| self.assembly.optional_plugins.contains(&index)), ); for (make, optional) in std::iter::once(®istry) - .chain(std::iter::once(&route)) .chain(&self.assembly.plugins) .zip(optional) { @@ -1088,8 +1076,8 @@ pub(crate) fn row(module: &str) -> Value { fn group(id: &str, config: Vec) -> Value { json!({ "id": id, "group": true, "instanced": true, "config": config }) } -fn session_scope(build: &Build) -> std::result::Result { - Ok(SessionScope { +fn session_scope(build: &Build) -> std::result::Result { + Ok(SessionScopeId { instance: build.instance(SESSION_GROUP)?, }) } @@ -1146,7 +1134,7 @@ pub(crate) struct SessionAssembly { pub unloading: CancellationToken, pub closing: CancellationToken, pub lifecycle: SessionLifecycle, - pub loaded: Mutex>>>, + pub loaded: Mutex>>>, /// The parts the Session's mounters mounted when it opened, until its /// creation ends. pub(crate) mounted: Arc>, @@ -1158,7 +1146,7 @@ pub(crate) struct SessionAssembly { lines: Mutex>>, } impl SessionAssembly { - pub(crate) fn loaded(&self) -> Result>> { + pub(crate) fn loaded(&self) -> Result>> { self.loaded .lock() .unwrap() @@ -1204,7 +1192,7 @@ impl SessionAssembly { struct SessionScopePlugin { owner: Arc, - scope: SessionScope, + scope: SessionScopeId, /// The names of this copy's instances, for the mounters it builds. build: Build, required: Arc<[String]>, @@ -1259,8 +1247,8 @@ impl DynPlugin for SessionScopePlugin { provide(ctx, &scope)?; } ctx.provide_at( - scope.key::(), - Arc::new(crate::LineRoute::new(owner)), + scope.key::(), + Arc::new(crate::SessionScope::new(owner)), )?; { let mut loaded = owner.loaded.lock().unwrap(); diff --git a/crates/dim-agent-runtime/src/error.rs b/crates/dim-agent-runtime/src/error.rs index 95d5a4a7bd..bb217fa81c 100644 --- a/crates/dim-agent-runtime/src/error.rs +++ b/crates/dim-agent-runtime/src/error.rs @@ -10,21 +10,6 @@ pub enum AgentError { Closed(String), #[error("unknown branch: {0}")] UnknownBranch(String), - /// Routing by id ([`Route`](crate::Route)): the Session has no live - /// instance, because it was idle-unloaded, closed or never existed. Only a - /// process caller receives it; a caller that must continue asks Agents for - /// a hold, and calls again once that loads the Session. - #[error("no live Session {0}")] - NoSession(String), - /// Routing by id: the Session instance is closing, and so is any call to a - /// line of it. A Session-scoped caller ends its work; a process caller - /// treats it as [`Self::NoSession`]. - #[error("Session {0} is closing")] - SessionClosing(String), - /// Routing by id: the Session is live but the line is closing, closed, or - /// not one of its lines. Final for that line: no hold, no retry. - #[error("no line {line} in Session {session}")] - NoLine { session: String, line: String }, /// The line has ended: it accepts no input and no new operation. #[error("branch has ended: {0}")] BranchEnded(String), @@ -71,12 +56,6 @@ pub enum SessionFault { InvalidInput(String), Closed(String), UnknownBranch(String), - NoSession(String), - SessionClosing(String), - NoLine { - session: String, - line: String, - }, BranchEnded(String), BranchRefused { refusal: BranchRefusal, @@ -102,9 +81,6 @@ impl From for SessionFault { AgentError::InvalidInput(value) => Self::InvalidInput(value), AgentError::Closed(value) => Self::Closed(value), AgentError::UnknownBranch(value) => Self::UnknownBranch(value), - AgentError::NoSession(value) => Self::NoSession(value), - AgentError::SessionClosing(value) => Self::SessionClosing(value), - AgentError::NoLine { session, line } => Self::NoLine { session, line }, AgentError::BranchEnded(value) => Self::BranchEnded(value), AgentError::BranchRefused { refusal, message } => { Self::BranchRefused { refusal, message } @@ -130,9 +106,6 @@ impl From for AgentError { SessionFault::InvalidInput(value) => Self::InvalidInput(value), SessionFault::Closed(value) => Self::Closed(value), SessionFault::UnknownBranch(value) => Self::UnknownBranch(value), - SessionFault::NoSession(value) => Self::NoSession(value), - SessionFault::SessionClosing(value) => Self::SessionClosing(value), - SessionFault::NoLine { session, line } => Self::NoLine { session, line }, SessionFault::BranchEnded(value) => Self::BranchEnded(value), SessionFault::BranchRefused { refusal, message } => { Self::BranchRefused { refusal, message } diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index 7a70d41220..e8252db8b1 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -93,7 +93,6 @@ pub fn register( pub fn catalog() -> ServiceCatalog { let mut catalog = ServiceCatalog::new(); register::(&mut catalog, None); - register::(&mut catalog, None); let session = Some(SESSION_GROUP); register::(&mut catalog, session); catalog.register_shared_instance(name_of::(), SESSION_GROUP); @@ -103,7 +102,7 @@ pub fn catalog() -> ServiceCatalog { catalog.register_shared_instance("timelineStore", SESSION_GROUP); register::(&mut catalog, session); register::(&mut catalog, session); - register::(&mut catalog, session); + register::(&mut catalog, session); let branch = Some(BRANCH_GROUP); register::(&mut catalog, branch); register::(&mut catalog, branch); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 0434a7d748..0fb6a0182a 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -1,29 +1,33 @@ //! Calls by id to a live owner's data face //! ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1–D4, [#2127](https://github.com/arcships/dim/issues/2127)). //! -//! A caller outside a scope holds no instance key, so it names what it wants. -//! The runtime keeps the Sessions its Agents publish and the lines each -//! Session created, and hands the call to the instance that is live now: +//! A caller outside a scope holds no instance key, so it names what it wants, +//! and the owner of the target holds the index and does the lookup: //! -//! - a process caller names the Session, or the Session and a line -//! ([`Route`]); -//! - a Session part names one of its own lines only ([`LineRoute`]); it cannot -//! name another Session. +//! - a Session's [`SessionScope`] resolves one of its own lines, for the +//! Session's parts and their runtimes; it holds no Session id, so a caller +//! cannot name another Session; +//! - Agents' `sessions` resolves a Session, and a line of it, for the process +//! (`dim-app-server`): it finds the Session and then calls +//! [`SessionScope::line_call`] in that instance. //! -//! A Rust caller calls the target owner's operations directly: [`line_owner`] -//! is the binding of [`LineRoute::line`] for a caller that wants the owner's -//! face. Everything else in this module is data: Rust, another language's -//! runtime and a UI leaf call the same operation with the same arguments and -//! read the same reply. Neither route takes a target's instance key, and a -//! resolution is never kept across calls. +//! Two data operations carry every routed call, with the same arguments in +//! every language: //! -//! What a route resolves is the target scope's data face in the catalog. A -//! name the assembly marks `internal(reason)`, a mechanism registration point +//! - [`SessionScope::line_call`] — `{lineId, service, method, args}`; +//! - `sessions.call` — `{sessionId, lineId?, service, method, args}`. +//! +//! An address records ids and resolves nothing; each call looks the target up +//! again, so a caller never keeps a live target (D4). Rust reads the owner's +//! face through [`line`] and [`LineHandle::get`] at the call. +//! +//! What a call resolves is the target scope's data face in the catalog. A name +//! the assembly marks `internal(reason)`, a mechanism registration point //! (whose entries belong to the registering generation) and a scope lifecycle -//! service are refused as [`RouteError::NotDataFace`]; a name of another -//! scope is [`RouteError::WrongScope`]. Everything else about the call belongs -//! to the owner: the route passes the method and its arguments through and -//! returns the owner's reply, or the owner's own failure as it wrote it. +//! service are refused as [`RouteError::NotDataFace`]; a data face of the +//! other scope is [`RouteError::WrongScope`]. Everything else about the call +//! belongs to the owner: the route passes the method and its arguments through +//! and returns the owner's reply, or the owner's own failure as it wrote it. //! //! A Session that has no live instance — idle-unloaded, closed or never //! created — answers [`RouteError::NoSession`]. A Session that is closing @@ -39,26 +43,10 @@ use rutis_bridge::session::{ Error as BridgeError, HostDispatch, Value as BridgeValue, decode_value, host_key_in, settle, }; use serde::{Deserialize, Serialize}; -use std::{ - collections::BTreeMap, - sync::{Arc, Mutex, Weak}, -}; +use std::sync::{Arc, Weak}; /// What a route answers: the target's reply, or why it did not reach one. -type Routed = std::result::Result; - -/// Names routing does not resolve: the mechanism's registration points, whose -/// entries belong to the part that registered them and are reachable only -/// inside that generation -/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D3), and the -/// scope lifecycle services the runtime provides. -const REGISTRATION_POINTS: [&str; 5] = [ - "sessionMethods", - "toolRegistry", - "promptRegistry", - "guideEntries", - "submitChecks", -]; +pub type Routed = std::result::Result; /// Why a routed call did not reach a reply. #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] @@ -92,40 +80,24 @@ pub enum RouteError { Owner { name: String, message: String }, } -/// A call to a Session-scope data face. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct SessionFaceCall { - pub session_id: String, - pub service: String, - pub method: String, - /// The method's arguments, in order. - #[serde(default)] - pub args: Vec, -} - -impl SessionFaceCall { - /// The call to `service.method(args...)` in the live Session `session_id`. - pub fn new( - session_id: impl Into, - service: impl Into, - method: impl Into, - args: Vec, - ) -> Self { - Self { - session_id: session_id.into(), - service: service.into(), - method: method.into(), - args, +impl RouteError { + /// The code a caller matches on, as the `sessions` envelope carries it. + pub fn code(&self) -> &'static str { + match self { + Self::NoSession(_) => "no_session", + Self::SessionClosing(_) => "session_closing", + Self::NoLine { .. } => "no_line", + Self::NotDataFace { .. } => "not_data_face", + Self::WrongScope { .. } => "wrong_scope", + Self::Owner { .. } => "owner", } } } -/// A call from the process to a line-scope data face. +/// A call to one of the caller's own Session's lines. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct LineFaceCall { - pub session_id: String, +pub struct LineCall { pub line_id: String, pub service: String, pub method: String, @@ -134,18 +106,15 @@ pub struct LineFaceCall { pub args: Vec, } -impl LineFaceCall { - /// The call to `service.method(args...)` in the line `line_id` of the live - /// Session `session_id`. +impl LineCall { + /// The call to `service.method(args...)` in the line `line_id`. pub fn new( - session_id: impl Into, line_id: impl Into, service: impl Into, method: impl Into, args: Vec, ) -> Self { Self { - session_id: session_id.into(), line_id: line_id.into(), service: service.into(), method: method.into(), @@ -154,11 +123,10 @@ impl LineFaceCall { } } -/// A call from a Session part to one of its own lines. +/// A call to one of the caller's own Session's data faces. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct OwnLineCall { - pub line_id: String, +pub struct SessionCall { pub service: String, pub method: String, /// The method's arguments, in order. @@ -166,16 +134,14 @@ pub struct OwnLineCall { pub args: Vec, } -impl OwnLineCall { - /// The call to `service.method(args...)` in this Session's line `line_id`. +impl SessionCall { + /// The call to `service.method(args...)` in this Session. pub fn new( - line_id: impl Into, service: impl Into, method: impl Into, args: Vec, ) -> Self { Self { - line_id: line_id.into(), service: service.into(), method: method.into(), args, @@ -183,118 +149,31 @@ impl OwnLineCall { } } -/// The Sessions this host's Agents published, by id, and the lines each -/// Session created. Runtime state, not a service: the routes read it, and a -/// Session registers itself as it publishes. -#[derive(Default)] -pub(crate) struct Index { - sessions: Mutex>>, -} - -impl Index { - /// Records the Session publishing as `id`. - pub(crate) fn register(&self, id: &str, session: Weak) { - self.sessions.lock().unwrap().insert(id.to_owned(), session); - } - - /// Forgets `session`'s registration of `id`, unless a later Session took - /// the id over. - pub(crate) fn forget(&self, id: &str, session: &Arc) { - let mut sessions = self.sessions.lock().unwrap(); - let registered = sessions - .get(id) - .is_some_and(|registered| Weak::ptr_eq(registered, &Arc::downgrade(session))); - if registered { - sessions.remove(id); - } - } - - fn session(&self, id: &str) -> Routed> { - let session = self - .sessions - .lock() - .unwrap() - .get(id) - .and_then(Weak::upgrade) - .ok_or_else(|| RouteError::NoSession(id.into()))?; - if session.closing.is_cancelled() { - return Err(RouteError::SessionClosing(id.into())); - } - Ok(session) - } - - fn line(&self, session_id: &str, line_id: &str) -> Routed> { - let session = self.session(session_id)?; - session.line(line_id).ok_or_else(|| RouteError::NoLine { - session: session_id.to_owned(), - line: line_id.to_owned(), - }) - } -} - -/// Calls by id to a live Session or line (process scope), provided as the -/// process name `route`. -/// -/// One route serves every Agent of one host: each Agent registers the Sessions -/// it publishes, so a process part reaches a Session of any of them. -pub struct Route { - index: Arc, -} - -impl Route { - /// The route over `index`. - pub(crate) fn new(index: Arc) -> Self { - Self { index } - } -} - -#[rutis::service] -impl Route { - /// Calls a Session-scope data face of the live Session `call.session_id`. - pub async fn session(&self, call: SessionFaceCall) -> Routed { - let session = self.index.session(&call.session_id)?; - let (catalog, faces) = session.reach(); - face(catalog, faces, &call.service, SESSION_GROUP)?; - let loaded = session.loaded().map_err(owner)?; - call_face( - &loaded.ctx, - loaded.scope.instance, - &call.service, - &call.method, - &call.args, - ) - .await - } - - /// Calls a line-scope data face of the line `call.line_id` in the live - /// Session `call.session_id`. - pub async fn line(&self, call: LineFaceCall) -> Routed { - let line = self.index.line(&call.session_id, &call.line_id)?; - face(line.catalog(), line.faces(), &call.service, BRANCH_GROUP)?; - call_face( - line.ctx(), - line.scope_instance(), - &call.service, - &call.method, - &call.args, - ) - .await - } -} +/// Names routing does not resolve: the mechanism's registration points, whose +/// entries belong to the part that registered them and are reachable only +/// inside that generation +/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D3), and the +/// scope lifecycle services the runtime provides. +const REGISTRATION_POINTS: [&str; 5] = [ + "sessionMethods", + "toolRegistry", + "promptRegistry", + "guideEntries", + "submitChecks", +]; -/// Calls by id to one of this Session's lines, provided to the Session's parts -/// and their runtimes as the Session name `lineRoute`. +/// One Session's own lines and data faces, provided to the Session's parts and +/// their runtimes as the Session name `sessionScope`. /// -/// A Session part reaches its own Session's lines only: the route holds no -/// Session id, so a caller cannot name another Session, and a line of another -/// Session is [`RouteError::NoLine`]. -pub struct LineRoute { +/// It holds its Session and no other: a part of a Session reaches its own +/// Session's lines only. `describe` joins it with base-3. +pub struct SessionScope { session: Weak, session_id: String, } -impl LineRoute { - /// The route over the Session `session` is publishing. +impl SessionScope { + /// The scope of the Session `session` is publishing. pub(crate) fn new(session: &Arc) -> Self { Self { session: Arc::downgrade(session), @@ -311,7 +190,8 @@ impl LineRoute { Ok(session) } - fn live_line(&self, line_id: &str) -> Routed> { + /// The live line `line_id` of this Session. + fn line_context(&self, line_id: &str) -> Routed> { self.live()? .line(line_id) .ok_or_else(|| RouteError::NoLine { @@ -322,10 +202,26 @@ impl LineRoute { } #[rutis::service] -impl LineRoute { - /// Calls a line-scope data face of this Session's line `call.line_id`. - pub async fn line(&self, call: OwnLineCall) -> Routed { - let line = self.live_line(&call.line_id)?; +impl SessionScope { + /// Calls one of this Session's own data faces. + pub async fn call(&self, call: SessionCall) -> Routed { + let session = self.live()?; + let (catalog, faces) = session.reach(); + face(catalog, faces, &call.service, SESSION_GROUP)?; + let loaded = session.loaded().map_err(owner)?; + call_face( + &loaded.ctx, + loaded.scope.instance, + &call.service, + &call.method, + &call.args, + ) + .await + } + + /// Calls one of this Session's lines' data faces. + pub async fn line_call(&self, call: LineCall) -> Routed { + let line = self.line_context(&call.line_id)?; face(line.catalog(), line.faces(), &call.service, BRANCH_GROUP)?; call_face( line.ctx(), @@ -338,39 +234,18 @@ impl LineRoute { } } -/// An address a caller may keep: ids only, looked up at every call -/// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D4). Rust -/// writes the authoring shape this way: `session(&route, id).line(id)`, then -/// the owner's own operations through [`LineAddress::owner`]. -pub struct SessionAddress { - index: Arc, - session_id: String, -} - -/// The address of one line, of [`SessionAddress::line`] or of [`LineRoute`]'s -/// own Session. -pub struct LineAddress { - scope: Scope, +/// The address of one of a Session's own lines: ids only, looked up at the +/// call ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D4). +pub struct LineHandle { + scope: Arc, line_id: String, } -enum Scope { - /// A Session of the process route, named by its id. - Named { - index: Arc, - session_id: String, - }, - /// The caller's own Session, which names no Session. - Own(Arc), -} - -impl LineAddress { - /// The line-scope data face `T`, resolved now. - pub fn owner(&self) -> Routed> { - let line = match &self.scope { - Scope::Named { index, session_id } => index.line(session_id, &self.line_id)?, - Scope::Own(route) => route.live_line(&self.line_id)?, - }; +impl LineHandle { + /// The line-scope data face `T`, resolved now; the caller uses it for this + /// call and does not keep it. + pub fn get(&self) -> Routed> { + let line = self.scope.line_context(&self.line_id)?; face( line.catalog(), line.faces(), @@ -381,55 +256,32 @@ impl LineAddress { } } -impl SessionAddress { - /// The line `line_id` of this Session, addressed and not looked up. - pub fn line(&self, line_id: &str) -> LineAddress { - LineAddress { - scope: Scope::Named { - index: self.index.clone(), - session_id: self.session_id.clone(), - }, - line_id: line_id.to_owned(), - } - } - - /// The Session-scope data face `T`, resolved now. - pub fn owner(&self) -> Routed> { - let session = self.index.session(&self.session_id)?; - session.session_face::().map_err(owner) - } -} - -/// Addresses Session `session_id` of the process [`Route`]: nothing is looked -/// up until a method is called. -pub fn session(route: &Arc, session_id: &str) -> SessionAddress { - SessionAddress { - index: route.index.clone(), - session_id: session_id.to_owned(), - } +/// The Session-scope data face `T` of the caller's own Session, resolved now; +/// the caller uses it for this call and does not keep it. +pub fn session_face(scope: &SessionScope) -> Routed> { + let session = scope.live()?; + let (catalog, faces) = session.reach(); + face(catalog, faces, &names::name_of::(), SESSION_GROUP)?; + session.session_face::().map_err(owner) } /// Addresses line `line_id` of the caller's own Session: nothing is looked up -/// until a method is called. -pub fn line(route: &Arc, line_id: &str) -> LineAddress { - LineAddress { - scope: Scope::Own(route.clone()), +/// until a method of [`LineHandle`] is called. +pub fn line(scope: &Arc, line_id: &str) -> LineHandle { + LineHandle { + scope: scope.clone(), line_id: line_id.to_owned(), } } -/// The line-scope data face `T` of this Session's line `line_id`: [`line`] and -/// [`LineAddress::owner`] in one call. -pub fn line_owner( - route: &Arc, - line_id: &str, -) -> Routed> { - line(route, line_id).owner::() -} - /// Fails unless a route may resolve `service` as a data face of `group` /// (module docs). -fn face(catalog: &names::ServiceCatalog, faces: &Faces, service: &str, group: &str) -> Routed<()> { +pub(crate) fn face( + catalog: &names::ServiceCatalog, + faces: &Faces, + service: &str, + group: &str, +) -> Routed<()> { let lifecycle = [ names::name_of::(), names::name_of::(), @@ -451,7 +303,7 @@ fn face(catalog: &names::ServiceCatalog, faces: &Faces, service: &str, group: &s /// Calls `method` of the data face `service` in `instance`, as another /// language would: the arguments travel as data and the reply comes back as /// data. -async fn call_face( +pub(crate) async fn call_face( ctx: &Ctx, instance: rutis::host::InstanceId, service: &str, @@ -475,7 +327,7 @@ async fn call_face( } /// The owner's failure as the target wrote it, under the name it carries. -fn owner(error: impl Into) -> RouteError { +pub(crate) fn owner(error: impl Into) -> RouteError { let failure = error.into(); RouteError::Owner { name: failure.name, @@ -514,20 +366,3 @@ impl From for Failure { } } } - -/// Provides the host's [`Route`] at the process name `route`. -pub(crate) struct RoutePlugin { - pub index: Arc, - pub key: rutis::host::Key, -} - -impl rutis::Plugin for RoutePlugin { - type Deps = (); - fn name(&self) -> &str { - "Route" - } - async fn apply(&self, ctx: &Ctx, (): ()) -> rutis::Result { - ctx.provide_at(self.key.clone(), Arc::new(Route::new(self.index.clone())))?; - Ok(()) - } -} diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index b700ea97c3..a655336110 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -157,10 +157,10 @@ impl SessionLoader { } /// Identity of one Session subtree, which the runtime builds keys from. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub(crate) struct SessionScope { +pub(crate) struct SessionScopeId { pub instance: InstanceId, } -impl SessionScope { +impl SessionScopeId { pub fn key(&self) -> Key { Key::of().instance(self.instance) } @@ -169,7 +169,7 @@ impl SessionScope { /// Identity of one branch subtree nested in its Session subtree. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) struct BranchScope { - pub session: SessionScope, + pub session: SessionScopeId, pub instance: InstanceId, } impl BranchScope { @@ -178,5 +178,5 @@ impl BranchScope { } } impl PublicService for SessionConfig {} -impl PublicService for crate::LineRoute {} +impl PublicService for crate::SessionScope {} impl PublicService for dyn LoopState {} diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index ea5080a2b7..2885fd9843 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -17,6 +17,7 @@ impl DynPlugin for Probe { } fn injects(&self) -> Vec { vec![ + host_key("sessions").erase(), host_key("scheduleJobs").erase(), host_key("wakeups").erase(), host_key("loops").erase(), @@ -786,3 +787,87 @@ async fn loop_face_cancellation_stops_reads_and_keeps_committed_starts() { assert!(reply["loopId"].is_string(), "{reply}"); rig.close().await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_cannot() { + let rig = Rig::start().await; + let session = rig + .server + .agent() + .expect("the product profile has an Agent") + .create_session(dim_agent_runtime::SessionConfig { + cwd: rig._home.path().to_string_lossy().into_owned(), + ..Default::default() + }) + .await + .unwrap(); + let id = session.id().to_owned(); + let face = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!( + face["ok"], true, + "a Session-scope face answers through Agents: {face}" + ); + let line = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "lineId": "main", "service": "timeline", "method": "sequence"}), + ) + .await; + assert_eq!( + line["value"], + json!(session.sequence("main").unwrap()), + "{line}" + ); + let unknown = rig + .call( + "sessions", + "call", + json!({"sessionId": "absent", "service": "sessionConfig", "method": "get"}), + ) + .await; + assert!( + unknown["error"]["code"] == "rejected" + && unknown["error"]["message"] + .as_str() + .unwrap_or_default() + .contains("no_session"), + "{unknown}" + ); + let missing = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "lineId": "absent", "service": "timeline", "method": "sequence"}), + ) + .await; + assert!( + missing["error"]["message"] + .as_str() + .unwrap_or_default() + .contains("no_line"), + "{missing}" + ); + session.close().await.unwrap(); + let closed = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert!( + closed["error"]["message"] + .as_str() + .unwrap_or_default() + .contains("no_session"), + "{closed}" + ); + rig.close().await; +} diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index ded1b0849b..927b68c1e3 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -9,8 +9,9 @@ use dim_agent_capabilities::{host::ModelSelectionHost, methods::RpcError}; use dim_agent_runtime::{ AGENT_GROUP, Agent, AgentBuilder, AgentError, CollaborationRole, CreateSessionOptions, InUse, Modules, Names, NoConfig, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, - QueryRow, QuerySelect, QuerySpec, QueryValue, RestoreSessionOptions, Session, SessionConfig, - TimelineKey, TimelineQuery, TimelineQueryScope, TimelineReadScope, TimelineReadSegment, + QueryRow, QuerySelect, QuerySpec, QueryValue, RestoreSessionOptions, RouteError, Session, + SessionConfig, TimelineKey, TimelineQuery, TimelineQueryScope, TimelineReadScope, + TimelineReadSegment, }; pub use dim_agent_types::AgentProfile; use dim_agent_types::{ROOT_BRANCH_ID, TimelinePosition}; @@ -1650,6 +1651,59 @@ impl AgentIndex { /// rows, or, in a daemon without a native store, a loaded Session. A /// Session in use is closed and removed as before; /// [`Self::delete_if_inactive`] is the delete that refuses it. + /// Calls a data face of the live Session `id`, or of one of its lines + /// ([#2127](https://github.com/arcships/dim/issues/2127), + /// [ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1): the + /// Session's own scope resolves the line, so the caller names no instance + /// key and keeps no object. A Session with no live instance answers + /// `NoSession`, one that is closing `SessionClosing`, and a line that is + /// closing, closed or not its own `NoLine`. + pub(crate) async fn call( + &self, + request: crate::agents::sessions::CallRequest, + ) -> std::result::Result { + let id = request.session_id.clone(); + let session = self + .live(&id) + .ok_or_else(|| RouteError::NoSession(id.clone()))?; + if session.is_closing() { + return Err(RouteError::SessionClosing(id)); + } + let scope = session + .session_service::() + .map_err(|error| RouteError::Owner { + name: "AgentError".into(), + message: error.to_string(), + })?; + match request.line_id { + Some(line_id) => { + scope + .line_call(dim_agent_runtime::LineCall::new( + line_id, + request.service, + request.method, + request.args, + )) + .await + } + None => { + scope + .call(dim_agent_runtime::SessionCall::new( + request.service, + request.method, + request.args, + )) + .await + } + } + } + /// The live Session `id`, whichever Agent publishes it. A single call needs + /// no hold: the Session is either live now or it is not (ADR 027 D5). + fn live(&self, id: &str) -> Option { + let inner = self.directory.inner.lock().expect("agent index"); + let host = inner.owner(id)?; + host.agent.get_session(id) + } pub(crate) async fn delete(&self, id: &str) -> dim_agent_runtime::Result { let _activity = self .activity diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index 84af4f3ad4..b1ad008db9 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -24,6 +24,21 @@ use serde_json::json; use std::{future::Future, sync::Arc, sync::atomic::Ordering}; use tokio_util::sync::CancellationToken; +/// A call by id to a data face of a Session, or of one of its lines. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CallRequest { + pub session_id: String, + /// The line whose faces this call reaches; absent: the Session's own. + #[serde(default)] + pub line_id: Option, + pub service: String, + pub method: String, + /// The method's arguments, in order. + #[serde(default)] + pub args: Vec, +} + /// A branch of a Session. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -819,7 +834,7 @@ impl HostDispatch for SessionsService { Some(json!({ "launch": "async", "input": "async", "lookup": "async", "exists": "async", "history": "async", "withdraw": "async", "pending": "async", "stop": "async", "idle": "async", - "delete": "async", "defaultBranchId": "async", + "delete": "async", "defaultBranchId": "async", "call": "async", })) } fn invoke(&self, method: &str, args: Value) -> Reply { @@ -897,6 +912,14 @@ async fn call( index.delete(&session_id).await?; reply(json!({})) } + // The routing answer names itself in the message until the Agents + // contract gives this face routing codes of its own. + "call" => index + .call(request(args)?) + .await + .map_err(|error| SessionsError::Rejected { + message: format!("{}: {error}", error.code()), + }), _ => Err(SessionsError::rejected(format!( "unknown sessions method {method}" ))), diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index 52a4fe15ac..bb2e91b2f8 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -93,10 +93,9 @@ fn crossing_instance_names() -> [(String, &'static str); 17] { /// the catalog already shares: the marked Session and branch services, the /// tool, method and guide-entry registries, with which a part of any /// language registers its contributions, the part registry, with which a -/// plugin registers its parts, and the routes, which name a live Session or -/// line by id ([`Route`](dim_agent_runtime::Route), -/// [`LineRoute`](dim_agent_runtime::LineRoute)). The generated catalog -/// (`xtask graph`) shares them the same way. +/// plugin registers its parts, and the Session scope, which names a line and +/// the Session's own faces by id ([`SessionScope`](dim_agent_runtime::SessionScope)). +/// The generated catalog (`xtask graph`) shares them the same way. pub fn share_names(catalog: &mut ServiceCatalog) { for (name, group) in crossing_instance_names() { catalog.register_shared_instance(name, group); @@ -106,10 +105,9 @@ pub fn share_names(catalog: &mut ServiceCatalog) { .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) - .register_shared_instance(name_of::(), SESSION_GROUP) + .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared(name_of::()) - .register_shared(name_of::()) - .register_shared(name_of::()); + .register_shared(name_of::()); } /// The runtimes of other languages and their loader rows, each with a diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index d46abece2b..dacc177164 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1251,9 +1251,6 @@ export type SessionFault = | { invalidInput: string } | { closed: string } | { unknownBranch: string } - | { noSession: string } - | { sessionClosing: string } - | { noLine: { session: string; line: string } } | { branchEnded: string } | { branchRefused: { refusal: BranchRefusal; message: string } } | { storage: string } @@ -1406,18 +1403,16 @@ export interface PartRegistry { registerDefinition(scope: PartScope, name: string, definition: import('@arcships/rutis').Plugin | ((ctx: any, config: any) => unknown) | { apply(ctx: any, config: any): unknown }): Promise } -/** A call to a Session-scope data face. */ -export type SessionFaceCall = { - sessionId: string +/** A call to one of the caller's own Session's data faces. */ +export type SessionCall = { service: string method: string /** The method's arguments, in order. */ args?: import('./plugin.js').BridgeJsonValue[] } -/** A call from the process to a line-scope data face. */ -export type LineFaceCall = { - sessionId: string +/** A call to one of the caller's own Session's lines. */ +export type LineCall = { lineId: string service: string method: string @@ -1426,49 +1421,23 @@ export type LineFaceCall = { } /** - * Calls by id to a live Session or line (process scope), provided as the - * process name `route`. + * One Session's own lines and data faces, provided to the Session's parts and + * their runtimes as the Session name `sessionScope`. * - * One route serves every Agent of one host: each Agent registers the Sessions - * it publishes, so a process part reaches a Session of any of them. + * It holds its Session and no other: a part of a Session reaches its own + * Session's lines only. `describe` joins it with base-3. */ -export interface Route { - /** - * Calls a Session-scope data face of the live Session `call.session_id`. - * @throws {RouteErrorThrown} - */ - session(call: SessionFaceCall): Promise +export interface SessionScope { /** - * Calls a line-scope data face of the line `call.line_id` in the live - * Session `call.session_id`. + * Calls one of this Session's own data faces. * @throws {RouteErrorThrown} */ - line(call: LineFaceCall): Promise -} - -/** A call from a Session part to one of its own lines. */ -export type OwnLineCall = { - lineId: string - service: string - method: string - /** The method's arguments, in order. */ - args?: import('./plugin.js').BridgeJsonValue[] -} - -/** - * Calls by id to one of this Session's lines, provided to the Session's parts - * and their runtimes as the Session name `lineRoute`. - * - * A Session part reaches its own Session's lines only: the route holds no - * Session id, so a caller cannot name another Session, and a line of another - * Session is [`RouteError::NoLine`]. - */ -export interface LineRoute { + call(call: SessionCall): Promise /** - * Calls a line-scope data face of this Session's line `call.line_id`. + * Calls one of this Session's lines' data faces. * @throws {RouteErrorThrown} */ - line(call: OwnLineCall): Promise + lineCall(call: LineCall): Promise } export type SessionInstanceDefinition = { @@ -1808,7 +1777,7 @@ export interface UiResources { } /** What a method returning `Err(AgentError)` throws. */ -export type AgentErrorThrown = RustError<"AgentError", "InvalidInput" | "Closed" | "UnknownBranch" | "NoSession" | "SessionClosing" | "NoLine" | "BranchEnded" | "BranchRefused" | "Storage" | "PublicationUnknown" | "Build" | "Cancelled" | "Reloading" | "AmbiguousSubmission" | "PartialSubmission" | "Fault" | "Framework" | "Multiple", undefined> +export type AgentErrorThrown = RustError<"AgentError", "InvalidInput" | "Closed" | "UnknownBranch" | "BranchEnded" | "BranchRefused" | "Storage" | "PublicationUnknown" | "Build" | "Cancelled" | "Reloading" | "AmbiguousSubmission" | "PartialSubmission" | "Fault" | "Framework" | "Multiple", undefined> /** What a method returning `Err(ApprovalRespondError)` throws. */ export type ApprovalRespondErrorThrown = RustError<"ApprovalRespondError", "Unknown" | "Cancelled" | "Closed", undefined> @@ -1891,8 +1860,7 @@ export interface Services { dispatcher: Dispatcher timeline: Timeline partRegistry: PartRegistry - route: Route - lineRoute: LineRoute + sessionScope: SessionScope sessionLoader: SessionLoader sessionPermissions: SessionPermissions collaborationConfig: CollaborationConfig @@ -1904,11 +1872,9 @@ export interface Services { uiResources: UiResources } -/** - * A Session's data faces, addressed by id: nothing is looked up until a method of - * one is called, and each call looks the target up again. - */ -export interface SessionAddress { +/** A Session's own faces, addressed by id: nothing is looked up until a method of + * one is called, and each call looks the target up again. */ +export interface SessionScopeAddress { /** This Session's line `lineId`. */ line(lineId: string): LineAddress agentConfig: AgentConfig @@ -1938,8 +1904,15 @@ export interface LineAddress { wait: Wait } -/** Addresses Session `sessionId`; every call looks it up again. */ -export declare function session(sessionId: string): SessionAddress +/** One Session reached through Agents' `sessions`. */ +export interface SessionAddress { + /** The Session's scope, whose own faces this reaches. */ + sessionScope: SessionScopeAddress + /** One of the Session's lines. */ + line(lineId: string): LineAddress +} -/** Addresses line `lineId` of this Session; every call looks it up again. */ -export declare function line(lineId: string): LineAddress +export interface Sessions { + /** The live Session `sessionId`; a call on it looks the Session up again. */ + session(sessionId: string): SessionAddress +} diff --git a/runtime/fixtures/branch-addresses.ts b/runtime/fixtures/branch-addresses.ts index 9c96209ab7..59001551bc 100644 --- a/runtime/fixtures/branch-addresses.ts +++ b/runtime/fixtures/branch-addresses.ts @@ -1,23 +1,28 @@ -// A plugin of any language calls a Session's or a line's data face by id: the +// A plugin of any language calls a Session's or a line's data face by id: an // address records ids only, and every call looks the target up again -// (ADR 027 D4, #2127). `session(...)` is the runtime's entry for a process -// part; `line(...)` is the one a Session part uses, and it names no Session. -import { line, session } from '../../npm/branch-services.js' -import type { Withdrawal } from '../../npm/branch-services.js' +// (ADR 027 D4, #2127). `sessions` is the process entry and finds the Session +// through Agents; `sessionScope` is the Session part's own entry, and it +// names no Session. +import type { Sessions, SessionScope, Withdrawal } from '../../npm/branch-services.js' -export async function readThroughAddresses(sessionId: string, inputId: string): Promise { - const lineAddress = session(sessionId).line('main') - const ending: boolean = await lineAddress.branchLine.ending() - const cursor: number | bigint | null = await lineAddress.branchLine.cursor('read') - const withdrawn: Withdrawal = await lineAddress.inputQueue.withdraw({ input_id: inputId }) - void [ending, cursor, withdrawn] +export async function readThroughAddresses( + sessions: Sessions, + sessionScope: SessionScope, + sessionId: string, + inputId: string, +): Promise { + const queue = sessions.session(sessionId).sessionScope + const withdrawn: Withdrawal = await queue.inputQueue.withdraw({ input_id: inputId }) + const line = sessions.session(sessionId).line('main') + const ending: boolean = await line.branchLine.ending() + void [withdrawn, ending] - const own = line('main') - const ownEnding: boolean = await own.branchLine.ending() - void ownEnding + const own: Withdrawal = await sessionScope.line('main').inputQueue.withdraw({ input_id: inputId }) + const ownEnding: boolean = await sessionScope.line('main').branchLine.ending() + void [own, ownEnding] } // @ts-expect-error a Session address reaches a line, not a line's faces. -export const queue = session('session').inputQueue +export const queue = (sessions: Sessions) => sessions.session('session').inputQueue // @ts-expect-error a Session part's line address names no Session. -export const foreign = line('main', 'other') +export const foreign = (scope: SessionScope) => scope.line('main', 'other') diff --git a/tests/integration/tests/extensions.rs b/tests/integration/tests/extensions.rs index b959525369..21e8c50d22 100644 --- a/tests/integration/tests/extensions.rs +++ b/tests/integration/tests/extensions.rs @@ -1280,7 +1280,7 @@ async fn closed_session_and_branch_subtrees_leave_no_plugins_or_bindings() { let counts = (diagnostics.plugins.len(), diagnostics.bindings.len()); assert_eq!(*baseline.get_or_insert(counts), counts, "round {round}"); } - assert_eq!(baseline, Some((20, 10))); + assert_eq!(baseline, Some((19, 8))); agent.close().await.unwrap(); } diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 014f78c179..e7c8cf3b9e 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -41,9 +41,10 @@ fn unroutable(root: &Path) -> Result> { Ok(names) } -/// The addresses over the two routable scopes: each member is a data face a -/// route resolves there, named as its catalog name, typed by the interface -/// this file already declares for it. +/// The addresses a plugin authors against: a Session part reaches its own +/// line and faces through `sessionScope`, a process part through `sessions`. +/// Each member is a data face a route resolves there, named as its catalog +/// name and typed by the interface this file already declares for it. fn addresses(root: &Path, declarations: &str) -> Result { let catalog = std::fs::read_to_string(root.join("docs/architecture/rust-agent/generated/catalog.md"))?; @@ -70,7 +71,7 @@ fn addresses(root: &Path, declarations: &str) -> Result { (Some(group), Some(face)) => (*group, *face), _ => continue, }; - if face != "data" || name == "route" || name == "lineRoute" { + if face != "data" || name == "sessionScope" || name == "sessions" { continue; } if unroutable.iter().any(|refused| refused == name) { @@ -86,7 +87,7 @@ fn addresses(root: &Path, declarations: &str) -> Result { } } let mut text = String::from( - "\n/**\n * A Session's data faces, addressed by id: nothing is looked up until a method of\n * one is called, and each call looks the target up again.\n */\nexport interface SessionAddress {\n /** This Session's line `lineId`. */\n line(lineId: string): LineAddress\n", + "\n/** A Session's own faces, addressed by id: nothing is looked up until a method of\n * one is called, and each call looks the target up again. */\nexport interface SessionScopeAddress {\n /** This Session's line `lineId`. */\n line(lineId: string): LineAddress\n", ); for (name, ty) in &session { text += &format!(" {name}: {ty}\n"); @@ -95,7 +96,7 @@ fn addresses(root: &Path, declarations: &str) -> Result { for (name, ty) in &line { text += &format!(" {name}: {ty}\n"); } - text += "}\n\n/** Addresses Session `sessionId`; every call looks it up again. */\nexport declare function session(sessionId: string): SessionAddress\n\n/** Addresses line `lineId` of this Session; every call looks it up again. */\nexport declare function line(lineId: string): LineAddress\n"; + text += "}\n\n/** One Session reached through Agents' `sessions`. */\nexport interface SessionAddress {\n /** The Session's scope, whose own faces this reaches. */\n sessionScope: SessionScopeAddress\n /** One of the Session's lines. */\n line(lineId: string): LineAddress\n}\n\nexport interface Sessions {\n /** The live Session `sessionId`; a call on it looks the Session up again. */\n session(sessionId: string): SessionAddress\n}\n"; Ok(text) } From 846e03877b5e4c2379efeea50aab09336de740cc Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 20:15:26 +0800 Subject: [PATCH 06/37] fix(runtime): answer a closing Session across a line call, and keep the owner's name Review of the previous head: - a line call that races the Session's close answers `SessionClosing`, not `NoLine`: the scope looks at its Session again when the line is gone; - `sessions.call` carries the routing kind and the owner's own name in `SessionsError::Routed`, so an owner failure is not flattened into a message; - the idle-unload acceptance is back on the Session side: a scope of an unloaded Session answers `SessionClosing`, and the restored generation answers again; - `AgentIndex::delete` has its documentation back; - the chain declarations were withdrawn: they described objects a plugin never holds, so the authoring form lands once the JavaScript side is decided (#2127). The dead generator helpers and the `Route` plugin exemption are gone with them. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 32 ++ crates/dim-agent-runtime/src/route.rs | 10 +- crates/dim-app-server/src/agents.rs | 32 +- crates/dim-app-server/src/agents/sessions.rs | 8 + .../contracts/runtime-owner-operations.md | 12 +- npm/branch-services.d.ts | 48 +-- runtime/fixtures/branch-addresses.ts | 28 -- runtime/plugin-sdk.test.mjs | 5 +- xtask/check/src/plugin_docs.rs | 408 ++++++++++++++++++ xtask/check/src/types.rs | 121 +----- 10 files changed, 485 insertions(+), 219 deletions(-) delete mode 100644 runtime/fixtures/branch-addresses.ts create mode 100644 xtask/check/src/plugin_docs.rs diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 9e4878996f..b99abe0550 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -321,6 +321,38 @@ async fn a_closed_line_answers_no_line_and_the_sessions_other_calls_still_arrive rig.host.close().await.unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_idle_unloaded_session_answers_session_closing_until_it_loads_again() { + let rig = Rig::start().await; + let session = rig.open().await; + let id = session.id().to_owned(); + let scope = rig.scope(&session); + + assert!( + session.unload_if_idle().await.unwrap(), + "an idle Session unloads" + ); + assert_eq!( + scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap_err(), + RouteError::SessionClosing(id.clone()), + "a scope of a Session that is gone reports its Session as closing" + ); + + let restored = rig.host.restore_session(id.clone()).await.unwrap(); + assert!( + rig.scope(&restored) + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .is_ok(), + "the Session's new generation answers" + ); + restored.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { let rig = Rig::start().await; diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 0fb6a0182a..92ba705fb1 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -191,13 +191,21 @@ impl SessionScope { } /// The live line `line_id` of this Session. + /// The live line `line_id` of this Session. A Session that started closing + /// while the line was being resolved answers `SessionClosing`, not + /// `NoLine`: closing the Session closes its lines. fn line_context(&self, line_id: &str) -> Routed> { - self.live()? + let session = self.live()?; + session .line(line_id) .ok_or_else(|| RouteError::NoLine { session: self.session_id.clone(), line: line_id.to_owned(), }) + .and_then(|line| match self.live() { + Err(closing @ RouteError::SessionClosing(_)) => Err(closing), + _ => Ok(line), + }) } } diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 927b68c1e3..2d5e322c98 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1636,21 +1636,6 @@ impl AgentIndex { } created } - /// `session.delete` ([S5c §3.2](../../../docs/design/appserver/session-deletion-and-fork.md#32-sequence)): - /// holds S's admission gate, so nothing loads or builds S meanwhile, - /// closes S if it is loaded, has SessionStore remove what it stores of - /// S, then forgets S and drops its slot, which stays closed until - /// nothing else holds it. A stored S that was neither loaded nor closed - /// ends without a close, so the delete announces it with - /// [`UnloadedSessionDeleted`]. An unknown id has nothing to remove and - /// keeps no slot. A delete that fails before the rows go leaves a - /// Session it closed as `session.close` does, closed in this process with - /// its rows kept (D5); one it did not close loads again on its next use. - /// - /// The reply reports whether this call removed the Session: its stored - /// rows, or, in a daemon without a native store, a loaded Session. A - /// Session in use is closed and removed as before; - /// [`Self::delete_if_inactive`] is the delete that refuses it. /// Calls a data face of the live Session `id`, or of one of its lines /// ([#2127](https://github.com/arcships/dim/issues/2127), /// [ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1): the @@ -1669,6 +1654,8 @@ impl AgentIndex { if session.is_closing() { return Err(RouteError::SessionClosing(id)); } + // A Session that starts closing while the call runs answers that way + // too: its lines close with it. let scope = session .session_service::() .map_err(|error| RouteError::Owner { @@ -1704,6 +1691,21 @@ impl AgentIndex { let host = inner.owner(id)?; host.agent.get_session(id) } + /// `session.delete` ([S5c §3.2](../../../docs/design/appserver/session-deletion-and-fork.md#32-sequence)): + /// holds S's admission gate, so nothing loads or builds S meanwhile, + /// closes S if it is loaded, has SessionStore remove what it stores of + /// S, then forgets S and drops its slot, which stays closed until + /// nothing else holds it. A stored S that was neither loaded nor closed + /// ends without a close, so the delete announces it with + /// [`UnloadedSessionDeleted`]. An unknown id has nothing to remove and + /// keeps no slot. A delete that fails before the rows go leaves a + /// Session it closed as `session.close` does, closed in this process with + /// its rows kept (D5); one it did not close loads again on its next use. + /// + /// The reply reports whether this call removed the Session: its stored + /// rows, or, in a daemon without a native store, a loaded Session. A + /// Session in use is closed and removed as before; + /// [`Self::delete_if_inactive`] is the delete that refuses it. pub(crate) async fn delete(&self, id: &str) -> dim_agent_runtime::Result { let _activity = self .activity diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index b1ad008db9..feb914fd40 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -296,6 +296,14 @@ pub struct StopRequest { pub enum SessionsError { #[error("{message}")] Rejected { message: String }, + /// A routed call's own failure: the routing kind (`routing`), the name the + /// owner wrote when the owner failed, and the message. + #[error("{message}")] + Routed { + routing: String, + name: String, + message: String, + }, #[error("{message}")] AgentUnknown { message: String }, #[error("{message}")] diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 9fe238b369..1b5e74434c 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -33,12 +33,14 @@ ### Calls from a Session to a selected branch Within a branch, inject its owner face directly. A Session caller names the line and the -owner's face, and the runtime routes the call to that line's live instance +owner's face, and the owner of the line's index resolves it ([#2127](https://github.com/arcships/dim/issues/2127), -[ADR 027](../../adr/027-cross-scope-access-by-id.md)): the owner's arguments, reply and -error reach the caller unchanged, and a line that is closing, closed or not this -Session's answers `NoLine`, which is final for that line. Tree history, directory and -batch input continue to use the tree's own methods. +[ADR 027](../../adr/027-cross-scope-access-by-id.md)): `sessionScope.lineCall` reaches a +line of the caller's own Session, `sessions.call` a Session and a line of it for the +process, and both pass the owner's arguments, reply and error through. A line that is +closing, closed or not this Session's answers `no_line`, which is final for it; a calling +Session that is closing answers `session_closing`. Tree history, directory and batch input +continue to use the tree's own methods. | Session caller | Target operation | | --- | --- | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index dacc177164..d0a8f59cbc 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1476,6 +1476,7 @@ export type PermissionState = { /** A Session service failure; generated exports throw this serde value. */ export type SessionsError = | { code: "rejected"; message: string } + | /** A routed call's own failure: the routing kind (`routing`), the name the owner wrote when the owner failed, and the message. */ { code: "routed"; routing: string; name: string; message: string } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } | { code: "branch_missing"; message: string } @@ -1816,7 +1817,7 @@ export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClo export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> /** What a method returning `Err(SessionsError)` throws. */ -export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> +export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> @@ -1871,48 +1872,3 @@ export interface Services { listenAddresses: ListenAddresses uiResources: UiResources } - -/** A Session's own faces, addressed by id: nothing is looked up until a method of - * one is called, and each call looks the target up again. */ -export interface SessionScopeAddress { - /** This Session's line `lineId`. */ - line(lineId: string): LineAddress - agentConfig: AgentConfig - collaborationConfig: CollaborationConfig - initialPromptConfiguration: InitialPromptConfiguration - mcpSession: McpSession - sessionConfig: SessionConfig - sessionIdentity: SessionIdentity - sessionLanguage: SessionLanguage - sessionLoader: SessionLoader - skillsConfig: SkillsConfig - toolHost: ToolHost - treeCommands: TreeCommands - uiResources: UiResources -} - -/** A line's data faces, addressed by id. */ -export interface LineAddress { - approval: Approval - backgroundExec: BackgroundExec - branchLine: BranchLine - dispatcher: Dispatcher - inputQueue: InputQueue - permission: Permission - timeline: Timeline - timelineIdentity: TimelineIdentity - wait: Wait -} - -/** One Session reached through Agents' `sessions`. */ -export interface SessionAddress { - /** The Session's scope, whose own faces this reaches. */ - sessionScope: SessionScopeAddress - /** One of the Session's lines. */ - line(lineId: string): LineAddress -} - -export interface Sessions { - /** The live Session `sessionId`; a call on it looks the Session up again. */ - session(sessionId: string): SessionAddress -} diff --git a/runtime/fixtures/branch-addresses.ts b/runtime/fixtures/branch-addresses.ts deleted file mode 100644 index 59001551bc..0000000000 --- a/runtime/fixtures/branch-addresses.ts +++ /dev/null @@ -1,28 +0,0 @@ -// A plugin of any language calls a Session's or a line's data face by id: an -// address records ids only, and every call looks the target up again -// (ADR 027 D4, #2127). `sessions` is the process entry and finds the Session -// through Agents; `sessionScope` is the Session part's own entry, and it -// names no Session. -import type { Sessions, SessionScope, Withdrawal } from '../../npm/branch-services.js' - -export async function readThroughAddresses( - sessions: Sessions, - sessionScope: SessionScope, - sessionId: string, - inputId: string, -): Promise { - const queue = sessions.session(sessionId).sessionScope - const withdrawn: Withdrawal = await queue.inputQueue.withdraw({ input_id: inputId }) - const line = sessions.session(sessionId).line('main') - const ending: boolean = await line.branchLine.ending() - void [withdrawn, ending] - - const own: Withdrawal = await sessionScope.line('main').inputQueue.withdraw({ input_id: inputId }) - const ownEnding: boolean = await sessionScope.line('main').branchLine.ending() - void [own, ownEnding] -} - -// @ts-expect-error a Session address reaches a line, not a line's faces. -export const queue = (sessions: Sessions) => sessions.session('session').inputQueue -// @ts-expect-error a Session part's line address names no Session. -export const foreign = (scope: SessionScope) => scope.line('main', 'other') diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index 2ee2ead310..8c9303a163 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -53,9 +53,6 @@ test('packed plugin service types compile the author guide and enforce the publi .replace("'./part-row.ts'", "'./part-row.mjs'")); return file; }); - const addressesFixture = path.join(directory, 'branch-addresses.mts'); - writeFileSync(addressesFixture, readFileSync(path.join(root, 'runtime/fixtures/branch-addresses.ts'), 'utf8') - .replaceAll("'../../npm/branch-services.js'", "'dimcode/branch-services.js'")); const calls = path.join(directory, 'calls.mts'); writeFileSync(calls, ` import type { Settings, SettingsResult, Sessions, WorkflowFiles, WorkflowFileEntry, WorkflowFilesErrorThrown, SessionPermissions, PermissionState, PermissionPolicy, SessionsErrorThrown, SessionMetadata, SessionMetadataResult, AuxiliaryModel, AuxiliaryReply, FileScope, FileResult, ToolRegistry, ToolExecute, ToolResult, SessionMethods, SessionMethodHandler, ManagementMethods, MethodHandler, MethodDeclaration, SessionConfig, SessionBroadcast, BranchEvent, Services, AgentErrorThrown, MethodReply, CallChannel, CallChannelError, EventHub, EventHubDeclaration, EventHubDelivery, EventHubErrorThrown, EventHubPublishReply } from 'dimcode/plugin'; @@ -373,6 +370,6 @@ void panel; assert.equal(declarations.status, 0, declarations.stdout + declarations.stderr); const checked = spawnSync(process.execPath, [compiler, '--strict', '--noEmit', '--target', 'ES2022', '--module', 'NodeNext', '--moduleResolution', 'NodeNext', - ...files, ...promptFixtures, addressesFixture, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); + ...files, ...promptFixtures, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); assert.equal(checked.status, 0, checked.stdout + checked.stderr); }); diff --git a/xtask/check/src/plugin_docs.rs b/xtask/check/src/plugin_docs.rs new file mode 100644 index 0000000000..518e5cc93c --- /dev/null +++ b/xtask/check/src/plugin_docs.rs @@ -0,0 +1,408 @@ +//! Static checks and block rewriting for plugin documents under +//! `docs/architecture/rust-agent/plugins/` against the recorded local graph. + +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Path, PathBuf}, +}; + +type Result = std::result::Result>; + +const BEGIN: &str = ""; +const INFRASTRUCTURE: [&str; 12] = [ + "rutis-loader", + "session", + "branch", + "SessionScope", + "BranchScope", + // The instances' mounters (ADR 006 D3); the parts they mount have pages. + "SessionParts", + "SessionOptionalParts", + "BranchParts", + "BranchOptionalParts", + "SessionBroadcast", + "SessionBroadcastEnd", + "PrepareModelHost", +]; + +fn docs_dir(root: &Path) -> PathBuf { + root.join("docs/architecture/rust-agent/plugins") +} + +pub fn graph_file(root: &Path) -> PathBuf { + root.join("docs/architecture/rust-agent/generated/local/services.json") +} + +/// Rewrites every plugin document's generated blocks from `graphs`. +pub fn rewrite>(root: &Path, graphs: &BTreeMap) -> Result<()> { + let facts = Facts::new(graphs); + for (path, names) in documents(root)? { + let mut text = std::fs::read_to_string(&path)?; + for name in names { + let (before, _, after) = split_block(&text, &name, &path)?; + text = format!("{before}{}{after}", facts.block(&name)?); + } + std::fs::write(&path, text)?; + } + Ok(()) +} + +/// Checks every plugin document against the recorded local graph. +pub fn check(root: &Path) -> Result<()> { + let documents = documents(root)?; + if documents.is_empty() { + return Err(format!("{}: no plugin documents", docs_dir(root).display()).into()); + } + let graphs: BTreeMap = + serde_json::from_str(&std::fs::read_to_string(graph_file(root))?)?; + let facts = Facts::new(&graphs); + let mut errors = Vec::new(); + let documented: BTreeSet<_> = documents + .iter() + .flat_map(|(_, names)| names.iter().map(String::as_str)) + .collect(); + for (_, plugin) in &facts.plugins { + let name = plugin["name"].as_str().ok_or("plugin graph has no name")?; + if !INFRASTRUCTURE.contains(&name) && !documented.contains(name) { + errors.push(format!( + "business plugin `{name}` has no document in {}", + docs_dir(root).display() + )); + } + } + for (path, name, section) in documents + .iter() + .map(|(path, names)| Ok((path, names, std::fs::read_to_string(path)?))) + .collect::>>()? + .iter() + .flat_map(|(path, names, text)| { + sections(text, names).map(move |(name, section)| (*path, name, section)) + }) + { + let (_, block, _) = split_block(section, name, path)?; + match facts.block(name) { + Err(error) => errors.push(error.to_string()), + Ok(expected) if expected != block => errors.push(format!( + "{}: `{name}`: generated block is stale; run `cargo run -p xtask -- graph`", + path.display() + )), + Ok(_) => {} + } + let injected: BTreeSet = facts + .plugin(name) + .map(|plugin| facts.injects(plugin).into_iter().collect()) + .unwrap_or_default(); + let explained = dependency_rows(section); + for missing in injected.difference(&explained) { + errors.push(format!( + "{}: `{name}`: dependency table does not explain injected `{missing}`", + path.display() + )); + } + for extra in explained.difference(&injected) { + errors.push(format!( + "{}: `{name}`: dependency table explains `{extra}`, which it does not inject", + path.display() + )); + } + } + if errors.is_empty() { + println!("plugin documents passed ({} documents)", documents.len()); + Ok(()) + } else { + Err(errors.join("\n").into()) + } +} + +/// Each part a page documents with the text that documents it: from the end +/// of the previous part's block, or the start, to the end of its own block. +fn sections<'a>( + text: &'a str, + names: &'a [String], +) -> impl Iterator + 'a { + let mut start = 0; + names.iter().map(move |name| { + let marker = format!("{BEGIN}{name} "); + let end = text[start..] + .find(&marker) + .and_then(|at| { + text[start + at..] + .find(END) + .map(|end| start + at + end + END.len()) + }) + .unwrap_or(text.len()); + let section = &text[start..end]; + start = end; + (name, section) + }) +} + +/// The parts or process plugins a page documents: the names of its +/// generated blocks, in order. +fn documented(text: &str) -> Vec { + text.match_indices(BEGIN) + .filter_map(|(at, _)| { + text[at + BEGIN.len()..] + .split_whitespace() + .next() + .map(str::to_owned) + }) + .collect() +} + +/// `(path, documented names)` of every page; a page documents at least one. +fn documents(root: &Path) -> Result)>> { + let dir = docs_dir(root); + let entries = std::fs::read_dir(&dir).map_err(|error| format!("{}: {error}", dir.display()))?; + let mut documents = Vec::new(); + for entry in entries { + let path = entry?.path(); + let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else { + continue; + }; + if path.extension().is_some_and(|ext| ext == "md") && stem != "README" { + let names = documented(&std::fs::read_to_string(&path)?); + if names.is_empty() { + return Err(format!("{}: no generated block", path.display()).into()); + } + documents.push((path.clone(), names)); + } + } + documents.sort(); + Ok(documents) +} + +/// `(before, block, after)`; the block spans both markers. +fn split_block<'a>(text: &'a str, name: &str, path: &Path) -> Result<(&'a str, &'a str, &'a str)> { + let marker = format!("{BEGIN}{name} "); + let start = text + .find(&marker) + .ok_or_else(|| format!("{}: missing `{marker}...` block", path.display()))?; + let end = text[start..] + .find(END) + .map(|offset| start + offset + END.len()) + .ok_or_else(|| format!("{}: unterminated generated block", path.display()))?; + Ok((&text[..start], &text[start..end], &text[end..])) +} + +/// First-column codes of the hand-written dependency table. +fn dependency_rows(text: &str) -> BTreeSet { + let mut rows = BTreeSet::new(); + let mut inside = false; + for line in text.lines() { + if let Some(heading) = line.strip_prefix("##") { + inside = matches!( + heading.trim_start_matches('#').trim(), + "Dependencies" | "依赖" + ); + continue; + } + let Some(cell) = line + .strip_prefix('|') + .and_then(|rest| rest.split('|').next()) + else { + continue; + }; + let cell = cell.trim(); + if inside && cell.starts_with('`') && cell.ends_with('`') && cell.len() > 2 { + rows.insert(cell.trim_matches('`').to_owned()); + } + } + rows +} + +/// `dim_agent_x::m::Name#key@main` → `B:Name#key`. +fn code(service: &str) -> String { + let (path, scope) = match service.rsplit_once('@') { + Some((path, "main")) => (path, "B"), + Some((path, "session")) => (path, "S"), + Some((path, _)) => (path, "?"), + None => (service, "P"), + }; + let mut short = String::new(); + let mut segment = String::new(); + let mut chars = path.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == ':' && chars.peek() == Some(&':') { + chars.next(); + segment.clear(); + continue; + } + if ch.is_alphanumeric() || ch == '_' { + segment.push(ch); + continue; + } + short.push_str(&segment); + segment.clear(); + short.push(ch); + } + short.push_str(&segment); + format!("{scope}:{short}") +} + +struct Facts<'a> { + /// `(scope, plugin)` of every plugin in the profile. + plugins: Vec<(&'a str, &'a Value)>, + bindings: Vec<&'a Value>, +} +impl<'a> Facts<'a> { + fn new>(graphs: &'a BTreeMap) -> Self { + let mut plugins = Vec::new(); + let mut bindings = Vec::new(); + for (scope, graph) in graphs { + for plugin in graph["plugins"].as_array().into_iter().flatten() { + plugins.push((scope.as_ref(), plugin)); + } + bindings.extend(graph["bindings"].as_array().into_iter().flatten()); + } + Self { plugins, bindings } + } + fn plugin(&self, name: &str) -> Option<&(&'a str, &'a Value)> { + self.plugins + .iter() + .find(|(_, plugin)| plugin["name"] == name) + } + fn injects(&self, (_, plugin): &(&str, &Value)) -> Vec { + plugin["injects"] + .as_array() + .into_iter() + .flatten() + .map(|inject| code(inject["service"].as_str().unwrap_or_default())) + .collect() + } + fn block(&self, name: &str) -> Result { + let found = self + .plugin(name) + .ok_or_else(|| format!("plugin `{name}` is not in the local execution profile"))?; + let (scope, plugin) = found; + let id = &plugin["id"]; + let scope = match *scope { + "process" => "进程", + "session" => "Session", + _ => "分支", + }; + let list = |items: BTreeSet| { + if items.is_empty() { + "—".to_owned() + } else { + items + .into_iter() + .map(|item| format!("`{item}`")) + .collect::>() + .join("、") + } + }; + let injects = list(self.injects(found).into_iter().collect()); + let provides = list( + self.bindings + .iter() + .filter(|binding| binding["provider"] == *id) + .map(|binding| code(binding["service"].as_str().unwrap_or_default())) + .collect(), + ); + let dependents = list( + self.plugins + .iter() + .filter(|(_, other)| { + other["resolved"] + .as_array() + .into_iter() + .flatten() + .any(|edge| edge["provider"] == *id) + }) + .map(|(_, other)| other["name"].as_str().unwrap_or_default().to_owned()) + .collect(), + ); + Ok(format!( + "{BEGIN}{name} — 由 `cargo run -p xtask -- graph` 从真实装配生成,勿手改 -->\n| 项 | 值 |\n| --- | --- |\n| 作用域 | {scope} |\n| 注入 | {injects} |\n| 提供 | {provides} |\n| 被注入于 | {dependents} |\n{END}" + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write_fixture(root: &Path, graphs: &BTreeMap<&'static str, Value>) -> Result<()> { + let file = graph_file(root); + std::fs::create_dir_all(file.parent().unwrap())?; + std::fs::write(&file, serde_json::to_string_pretty(graphs)? + "\n")?; + rewrite(root, graphs) + } + + #[test] + fn documentation_check_requires_complete_profile_and_exact_dependencies() { + let root = std::env::temp_dir().join(format!( + "dim-plugin-doc-check-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&root).unwrap(); + let result = (|| -> Result<()> { + assert!(check(&root).is_err(), "missing directory must not pass"); + std::fs::create_dir_all(docs_dir(&root))?; + let mut graphs = BTreeMap::from([( + "main", + serde_json::json!({ + "plugins": [ + {"id":1,"name":"branch","injects":[],"resolved":[]}, + {"id":2,"name":"Example","injects":[{"service":"crate::Timeline@main"}],"resolved":[]} + ], + "bindings":[] + }), + )]); + write_fixture(&root, &graphs)?; + assert!(check(&root).is_err(), "empty document set must not pass"); + let path = docs_dir(&root).join("Example.md"); + let page = format!( + "# Example\n\n## Dependencies\n\n| Service | Purpose |\n| --- | --- |\n| `B:Timeline` | Commit results |\n\n{BEGIN}Example -->\n{END}\n" + ); + std::fs::write(&path, &page)?; + write_fixture(&root, &graphs)?; + check(&root)?; + let valid = std::fs::read_to_string(&path)?; + std::fs::write( + &path, + valid.replace("| `B:Timeline` | Commit results |", ""), + )?; + assert!( + check(&root).is_err(), + "a missing dependency explanation must fail" + ); + std::fs::write(&path, &valid)?; + graphs.get_mut("main").unwrap()["plugins"] + .as_array_mut() + .unwrap() + .push( + serde_json::json!({"id":3,"name":"NewCapability","injects":[],"resolved":[]}), + ); + write_fixture(&root, &graphs)?; + assert!( + check(&root).is_err(), + "new business plugins require documentation" + ); + graphs.get_mut("main").unwrap()["plugins"] + .as_array_mut() + .unwrap() + .pop(); + write_fixture(&root, &graphs)?; + std::fs::write( + docs_dir(&root).join("Removed.md"), + page.replace("Example", "Removed"), + )?; + assert!( + check(&root).is_err(), + "removed plugins must not retain orphan documents" + ); + std::fs::remove_file(docs_dir(&root).join("Removed.md"))?; + check(&root) + })(); + std::fs::remove_dir_all(root).unwrap(); + result.unwrap(); + } +} diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index e7c8cf3b9e..228e43ba24 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -12,124 +12,6 @@ fn file(root: &Path) -> PathBuf { root.join("npm/branch-services.d.ts") } -/// The names routing does not resolve, read from the runtime that refuses -/// them: its registration points and the two lifecycle services. -fn unroutable(root: &Path) -> Result> { - let path = root.join("crates/dim-agent-runtime/src/route.rs"); - let source = std::fs::read_to_string(&path)?; - let ast = syn::parse_file(&source).map_err(|error| format!("{}: {error}", path.display()))?; - let mut names = vec!["sessionLifecycle".to_owned(), "branchLifecycle".to_owned()]; - for item in &ast.items { - let syn::Item::Const(declaration) = item else { - continue; - }; - if declaration.ident != "REGISTRATION_POINTS" { - continue; - } - if let syn::Expr::Array(array) = &*declaration.expr { - for element in &array.elems { - if let syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(name), - .. - }) = element - { - names.push(name.value()); - } - } - } - } - Ok(names) -} - -/// The addresses a plugin authors against: a Session part reaches its own -/// line and faces through `sessionScope`, a process part through `sessions`. -/// Each member is a data face a route resolves there, named as its catalog -/// name and typed by the interface this file already declares for it. -fn addresses(root: &Path, declarations: &str) -> Result { - let catalog = - std::fs::read_to_string(root.join("docs/architecture/rust-agent/generated/catalog.md"))?; - let unroutable = unroutable(root)?; - let declared: Vec<&str> = declarations - .lines() - .filter_map(|line| { - line.strip_prefix("export interface ") - .or_else(|| line.strip_prefix("export type ")) - .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) - }) - .collect(); - let mut session = Vec::new(); - let mut line = Vec::new(); - for row in catalog.lines().filter(|line| line.starts_with("| `")) { - let cells: Vec<&str> = row.split('|').map(str::trim).collect(); - let Some(name) = cells.get(1).and_then(|name| name.strip_prefix('`')) else { - continue; - }; - let Some(name) = name.strip_suffix('`') else { - continue; - }; - let (group, face) = match (cells.get(2), cells.get(4)) { - (Some(group), Some(face)) => (*group, *face), - _ => continue, - }; - if face != "data" || name == "sessionScope" || name == "sessions" { - continue; - } - if unroutable.iter().any(|refused| refused == name) { - continue; - } - let Some(ty) = declared.iter().find(|ty| catalog_name(ty) == name).copied() else { - continue; - }; - match group { - "session" => session.push((name.to_owned(), ty.to_owned())), - "branch" => line.push((name.to_owned(), ty.to_owned())), - _ => {} - } - } - let mut text = String::from( - "\n/** A Session's own faces, addressed by id: nothing is looked up until a method of\n * one is called, and each call looks the target up again. */\nexport interface SessionScopeAddress {\n /** This Session's line `lineId`. */\n line(lineId: string): LineAddress\n", - ); - for (name, ty) in &session { - text += &format!(" {name}: {ty}\n"); - } - text += "}\n\n/** A line's data faces, addressed by id. */\nexport interface LineAddress {\n"; - for (name, ty) in &line { - text += &format!(" {name}: {ty}\n"); - } - text += "}\n\n/** One Session reached through Agents' `sessions`. */\nexport interface SessionAddress {\n /** The Session's scope, whose own faces this reaches. */\n sessionScope: SessionScopeAddress\n /** One of the Session's lines. */\n line(lineId: string): LineAddress\n}\n\nexport interface Sessions {\n /** The live Session `sessionId`; a call on it looks the Session up again. */\n session(sessionId: string): SessionAddress\n}\n"; - Ok(text) -} - -/// The catalog name of a Rust type: its type name with the leading word -/// lowercased, as `#[rutis::service]` names a type (`InputQueue` is -/// `inputQueue`). -fn catalog_name(type_name: &str) -> String { - let ident = type_name - .trim_start_matches("dyn ") - .split(['<', ' ']) - .next() - .unwrap_or(type_name); - let ident = ident.rsplit("::").next().unwrap_or(ident); - let chars: Vec = ident.chars().collect(); - let upper = chars.iter().take_while(|c| c.is_uppercase()).count(); - let lower = if upper > 1 && upper < chars.len() && chars[upper].is_lowercase() { - upper - 1 - } else { - upper.max(1).min(chars.len()) - }; - chars - .iter() - .enumerate() - .flat_map(|(index, c)| { - if index < lower { - c.to_lowercase().collect::>() - } else { - vec![*c] - } - }) - .collect() -} - fn declarations(root: &Path) -> Result { let services = rutis_types::Exports::new() .declared("serde_json::Value", "import('./plugin.js').BridgeJsonValue") @@ -176,8 +58,7 @@ fn declarations(root: &Path) -> Result { "{ branch_id: string; sequence: number | bigint }", ) .declarations(root.join("crates/dim-app-server"))?; - let addresses = addresses(root, &services)?; - Ok(services + &addresses) + Ok(services) } pub fn write(root: &Path) -> Result<()> { From 62fa76a93e7c6eb812f06ac6749c48cf5973c4b8 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 20:18:10 +0800 Subject: [PATCH 07/37] feat(typescript): type the two routed calls by their target A plugin calls a Session's or a line's data face with the operation the index owner serves: `sessionScope.lineCall` for its own Session's line, `sessions.call` for a Session or a line of it. No chain and no wrapper: rutis serves a Rust service's reply as data, so an object a caller continued to call was never available (maintainer correction on #2174). `xtask -- types` narrows both requests to what a route resolves: `service` is a data face of the target scope, `method` one of its methods, and `args` that method's parameters, so a typo fails `tsc`. The injected `sessions` type carries `call`, and the authoring guide shows the two operations. Refs #2015 Refs #2127 --- docs/typescript-plugin-authoring.md | 23 +++- npm/branch-services.d.ts | 66 ++++++++--- npm/plugin.d.ts | 5 + runtime/fixtures/branch-calls.ts | 39 +++++++ runtime/plugin-sdk.test.mjs | 5 +- xtask/check/src/types.rs | 166 +++++++++++++++++++++++++++- 6 files changed, 286 insertions(+), 18 deletions(-) create mode 100644 runtime/fixtures/branch-calls.ts diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index d66a83afb2..c03d904aa7 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -29,12 +29,33 @@ requires finite numbers and integers representable by Rust's signed or unsigned The external client protocol's `JsonValue` remains JSON-only and does not admit `bigint`. These types describe their respective boundaries, not a conversion step. +## Calling a Session or line by id + +A part of a line calls its own line's services directly. A part outside that line names +the id instead, and the owner of the index looks it up at the call: `sessionScope.lineCall` +for a line of its own Session, `sessions.call` for a Session or a line of it, from the +process. Both carry `{service, method, args}` — the target's own operation — and answer +`no_session`, `session_closing` or `no_line` when the target is not live +([#2127](https://github.com/arcships/dim/issues/2127), ADR 027). + +```ts +// a Session part +await sessionScope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: [{ input_id: id }] }) +// a process part +await sessions.call({ sessionId, lineId: 'main', service: 'inputQueue', method: 'withdraw', args: [{ input_id: id }] }) +await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: [] }) +``` + +The request types are generated, so `service`, `method` and `args` are the target's own and +a typo fails `tsc`. Nothing a call returns may be kept: the next call looks the target up +again. + ## Available services | Need | Service and scope | Availability | | --- | --- | --- | | Persist a process plugin's own data | `pluginFiles`, process | Implemented when the host supplies an authorized product root and provisions parent directories; use its native transactions and lifecycle scope. | -| Start or drive another Session | `sessions`, process | Implemented by Agents; all nine methods are typed. | +| Start or drive another Session | `sessions`, process | Implemented by Agents; all nine methods are typed. `call({sessionId, lineId?, service, method, args})` reaches a Session's or a line's data face by id ([Calling a Session or line by id](#calling-a-session-or-line-by-id)). | | Publish events to subscribed branches | `eventHub`, process | Implemented by EventHub: `declare` and `publish`, served to the calling row. Inject it: the row loads only while EventHub runs and declares at `apply`. | | Read current branch permissions or host defaults | `sessionPermissions`, process | Generated from Agents: `permission({sessionId, branchId})` and `permissionDefaults({})`. | | Read or set a Session's title | `sessionMetadata`, process | Implemented by SessionStore: `read` and the revision-checked `setTitle` ([title metadata](design/appserver/session-title-metadata.md)). SessionTitle is the title's one writer; other plugins only read. | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index d0a8f59cbc..9072e4848f 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1403,22 +1403,7 @@ export interface PartRegistry { registerDefinition(scope: PartScope, name: string, definition: import('@arcships/rutis').Plugin | ((ctx: any, config: any) => unknown) | { apply(ctx: any, config: any): unknown }): Promise } -/** A call to one of the caller's own Session's data faces. */ -export type SessionCall = { - service: string - method: string - /** The method's arguments, in order. */ - args?: import('./plugin.js').BridgeJsonValue[] -} -/** A call to one of the caller's own Session's lines. */ -export type LineCall = { - lineId: string - service: string - method: string - /** The method's arguments, in order. */ - args?: import('./plugin.js').BridgeJsonValue[] -} /** * One Session's own lines and data faces, provided to the Session's parts and @@ -1872,3 +1857,54 @@ export interface Services { listenAddresses: ListenAddresses uiResources: UiResources } + +/** The data faces a line reaches. */ +export type LineFaces = { + approval: Approval + backgroundExec: BackgroundExec + branchLine: BranchLine + dispatcher: Dispatcher + inputQueue: InputQueue + permission: Permission + timeline: Timeline + timelineIdentity: TimelineIdentity + wait: Wait +} + +/** The data faces a Session reaches. */ +export type SessionFaces = { + agentConfig: AgentConfig + collaborationConfig: CollaborationConfig + initialPromptConfiguration: InitialPromptConfiguration + mcpSession: McpSession + sessionConfig: SessionConfig + sessionIdentity: SessionIdentity + sessionLanguage: SessionLanguage + sessionLoader: SessionLoader + skillsConfig: SkillsConfig + toolHost: ToolHost + treeCommands: TreeCommands + uiResources: UiResources +} + +/** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */ +type Call = { + [S in keyof Faces]: { + [M in keyof Faces[S]]: Address & { + service: S + method: M + args: Faces[S][M] extends (...args: infer A) => unknown ? A : never + } + }[keyof Faces[S]] +}[keyof Faces] + +/** A call to one of the caller's own Session's lines. */ +export type LineCall = Call + +/** A call to one of the caller's own Session's data faces. */ +export type SessionCall = Call + +/** A call through Agents: a Session's face, or one of its lines' faces. */ +export type SessionsCall = + | Call + | Call diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 6ec5b5c954..adb680776d 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -301,6 +301,11 @@ export interface Sessions { stop(request: StopRequest): Promise>; idle(request: SessionRef): Promise>; delete(request: { sessionId: string }): Promise>>; + /** Calls a data face of a live Session, or of one of its lines, by id + * (#2127). A Session with no live instance answers `no_session`, one that is + * closing `session_closing`, and a line that is closing, closed or not its + * own `no_line`. */ + call(request: import('./branch-services.js').SessionsCall): Promise>; } /** One type an `eventHub` source declares (design A.1). */ diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts new file mode 100644 index 0000000000..626b394ab4 --- /dev/null +++ b/runtime/fixtures/branch-calls.ts @@ -0,0 +1,39 @@ +// A plugin of any language calls a Session's or a line's data face by id with +// the two data operations (#2127). The request's `service`, `method` and +// `args` are the target's own, so a typo fails to compile. +import type { Sessions, SessionScope } from '../../npm/branch-services.js' + +export async function readByCalls( + scope: SessionScope, + sessions: Sessions, + sessionId: string, + inputId: string, +): Promise { + await scope.lineCall({ + lineId: 'main', + service: 'inputQueue', + method: 'withdraw', + args: [{ input_id: inputId }], + }) + await scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) + await scope.call({ service: 'sessionConfig', method: 'get', args: [] }) + await sessions.call({ + sessionId, + lineId: 'main', + service: 'inputQueue', + method: 'withdraw', + args: [{ input_id: inputId }], + }) + await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: [] }) +} + +// @ts-expect-error a service the route does not resolve is refused. +void scope.lineCall({ lineId: 'main', service: 'inputQueueX', method: 'withdraw', args: [] }) +// @ts-expect-error a method the service does not have is refused. +void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'submitX', args: [] }) +// @ts-expect-error arguments follow the method's parameters. +void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: ['wrong'] }) +// @ts-expect-error a Session call reaches a Session face, not a line's. +void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) +// @ts-expect-error a line call takes no Session id. +void sessions.call({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index 8c9303a163..f100d3156e 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -53,6 +53,9 @@ test('packed plugin service types compile the author guide and enforce the publi .replace("'./part-row.ts'", "'./part-row.mjs'")); return file; }); + const routed = path.join(directory, 'branch-calls.mts'); + writeFileSync(routed, readFileSync(path.join(root, 'runtime/fixtures/branch-calls.ts'), 'utf8') + .replaceAll("'../../npm/branch-services.js'", "'dimcode/branch-services.js'")); const calls = path.join(directory, 'calls.mts'); writeFileSync(calls, ` import type { Settings, SettingsResult, Sessions, WorkflowFiles, WorkflowFileEntry, WorkflowFilesErrorThrown, SessionPermissions, PermissionState, PermissionPolicy, SessionsErrorThrown, SessionMetadata, SessionMetadataResult, AuxiliaryModel, AuxiliaryReply, FileScope, FileResult, ToolRegistry, ToolExecute, ToolResult, SessionMethods, SessionMethodHandler, ManagementMethods, MethodHandler, MethodDeclaration, SessionConfig, SessionBroadcast, BranchEvent, Services, AgentErrorThrown, MethodReply, CallChannel, CallChannelError, EventHub, EventHubDeclaration, EventHubDelivery, EventHubErrorThrown, EventHubPublishReply } from 'dimcode/plugin'; @@ -370,6 +373,6 @@ void panel; assert.equal(declarations.status, 0, declarations.stdout + declarations.stderr); const checked = spawnSync(process.execPath, [compiler, '--strict', '--noEmit', '--target', 'ES2022', '--module', 'NodeNext', '--moduleResolution', 'NodeNext', - ...files, ...promptFixtures, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); + ...files, ...promptFixtures, routed, calls, branchFixture, partRow, permissionsFixture, workflowFixture, eventHubFixture, uiFixture], { encoding: 'utf8' }); assert.equal(checked.status, 0, checked.stdout + checked.stderr); }); diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 228e43ba24..99ad672071 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -12,6 +12,140 @@ fn file(root: &Path) -> PathBuf { root.join("npm/branch-services.d.ts") } +/// The two data operations' requests, narrowed to what a route resolves: the +/// `service` is a data face of the target scope, `method` one of its methods, +/// and `args` the method's parameters, so a typo fails `tsc` +/// ([#2127](https://github.com/arcships/dim/issues/2127)). +fn calls(root: &Path, services: &str) -> Result { + let catalog = + std::fs::read_to_string(root.join("docs/architecture/rust-agent/generated/catalog.md"))?; + let unroutable = unroutable(root)?; + let declared: Vec<&str> = services + .lines() + .filter_map(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + }) + .collect(); + let mut session = Vec::new(); + let mut line = Vec::new(); + for row in catalog.lines().filter(|line| line.starts_with("| `")) { + let cells: Vec<&str> = row.split('|').map(str::trim).collect(); + let Some(name) = cells.get(1).and_then(|name| name.strip_prefix('`')) else { + continue; + }; + let Some(name) = name.strip_suffix('`') else { + continue; + }; + let (group, face) = match (cells.get(2), cells.get(4)) { + (Some(group), Some(face)) => (*group, *face), + _ => continue, + }; + if face != "data" || name == "sessionScope" || name == "sessions" { + continue; + } + if unroutable.iter().any(|refused| refused == name) { + continue; + } + let Some(ty) = declared.iter().find(|ty| catalog_name(ty) == name).copied() else { + continue; + }; + match group { + "session" => session.push((name.to_owned(), ty.to_owned())), + "branch" => line.push((name.to_owned(), ty.to_owned())), + _ => {} + } + } + let faces = |items: &[(String, String)], name: &str| { + let mut text = format!("export type {name} = {{\n"); + for (name, ty) in items { + text += &format!(" {name}: {ty}\n"); + } + text + "}\n" + }; + let mut text = String::from("\n/** The data faces a line reaches. */\n"); + text += &faces(&line, "LineFaces"); + text += "\n/** The data faces a Session reaches. */\n"; + text += &faces(&session, "SessionFaces"); + text += "\n/** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */\ntype Call = {\n [S in keyof Faces]: {\n [M in keyof Faces[S]]: Address & {\n service: S\n method: M\n args: Faces[S][M] extends (...args: infer A) => unknown ? A : never\n }\n }[keyof Faces[S]]\n}[keyof Faces]\n"; + text += "\n/** A call to one of the caller's own Session's lines. */\nexport type LineCall = Call\n"; + text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; + text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. */\nexport type SessionsCall =\n | Call\n | Call\n"; + Ok(text) +} + +/// The names routing does not resolve, read from the runtime that refuses +/// them: its registration points, plus the two lifecycle services. A missing +/// list is an error, never an empty one. +fn unroutable(root: &Path) -> Result> { + let path = root.join("crates/dim-agent-runtime/src/route.rs"); + let source = std::fs::read_to_string(&path)?; + let ast = syn::parse_file(&source).map_err(|error| format!("{}: {error}", path.display()))?; + let mut names = vec!["sessionLifecycle".to_owned(), "branchLifecycle".to_owned()]; + let mut found = false; + for item in &ast.items { + let syn::Item::Const(declaration) = item else { + continue; + }; + if declaration.ident != "REGISTRATION_POINTS" { + continue; + } + let syn::Expr::Array(array) = &*declaration.expr else { + return Err(format!("{}: REGISTRATION_POINTS is not an array", path.display()).into()); + }; + for element in &array.elems { + let syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(name), + .. + }) = element + else { + return Err(format!( + "{}: REGISTRATION_POINTS holds an entry that is not a string", + path.display() + ) + .into()); + }; + names.push(name.value()); + } + found = true; + } + if !found { + return Err(format!("{}: REGISTRATION_POINTS is missing", path.display()).into()); + } + Ok(names) +} + +/// The catalog name of a Rust type: its type name with the leading word +/// lowercased, as `#[rutis::service]` names a type (`InputQueue` is +/// `inputQueue`). +fn catalog_name(type_name: &str) -> String { + let ident = type_name + .trim_start_matches("dyn ") + .split(['<', ' ']) + .next() + .unwrap_or(type_name); + let ident = ident.rsplit("::").next().unwrap_or(ident); + let chars: Vec = ident.chars().collect(); + let upper = chars.iter().take_while(|c| c.is_uppercase()).count(); + let lower = if upper > 1 && upper < chars.len() && chars[upper].is_lowercase() { + upper - 1 + } else { + upper.max(1).min(chars.len()) + }; + chars + .iter() + .enumerate() + .flat_map(|(index, c)| { + if index < lower { + c.to_lowercase().collect::>() + } else { + vec![*c] + } + }) + .collect() +} + fn declarations(root: &Path) -> Result { let services = rutis_types::Exports::new() .declared("serde_json::Value", "import('./plugin.js').BridgeJsonValue") @@ -58,7 +192,37 @@ fn declarations(root: &Path) -> Result { "{ branch_id: string; sequence: number | bigint }", ) .declarations(root.join("crates/dim-app-server"))?; - Ok(services) + let calls = calls(root, &services)?; + Ok(replaced(services) + &calls) +} + +/// Drops the generated `LineCall`/`SessionCall` declarations, which the +/// narrowed ones replace. +fn replaced(services: String) -> String { + let mut text = String::new(); + let mut skipping = false; + for line in services.lines() { + if line.starts_with("export type LineCall = {") + || line.starts_with("export type SessionCall = {") + { + skipping = true; + continue; + } + if skipping { + if line == "}" { + skipping = false; + } + continue; + } + if line == "/** A call to one of the caller's own Session's lines. */" + || line == "/** A call to one of the caller's own Session's data faces. */" + { + continue; + } + text += line; + text.push('\n'); + } + text } pub fn write(root: &Path) -> Result<()> { From e6a095da00427d9324c49344650626eac47475b5 Mon Sep 17 00:00:00 2001 From: scotares Date: Wed, 25 Nov 2026 20:21:27 +0800 Subject: [PATCH 08/37] test(typescript): typecheck the two routed calls against the packed package The Node-backed check now runs here: the fixture imports the injected `Sessions` from `dimcode/plugin`, the authoring-guide snippet declares what it uses, and the pinned `SessionsError` code union gains `routed`, which the routing face serves. `node --test runtime/plugin-sdk.test.mjs` passes, so the narrowed `LineCall`/`SessionCall`/`SessionsCall` reject unknown services, unknown methods and wrong arguments under `tsc --noEmit`. Refs #2015 Refs #2127 --- docs/typescript-plugin-authoring.md | 8 ++++++++ runtime/fixtures/branch-calls.ts | 3 ++- runtime/plugin-sdk.test.mjs | 5 +++-- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index c03d904aa7..aecd169e50 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -39,6 +39,14 @@ process. Both carry `{service, method, args}` — the target's own operation — ([#2127](https://github.com/arcships/dim/issues/2127), ADR 027). ```ts +import type { Sessions } from 'dimcode/plugin'; +import type { SessionScope } from 'dimcode/branch-services.js'; + +declare const sessionScope: SessionScope; +declare const sessions: Sessions; +declare const sessionId: string; +declare const id: string; + // a Session part await sessionScope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: [{ input_id: id }] }) // a process part diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index 626b394ab4..891b00898e 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -1,7 +1,8 @@ // A plugin of any language calls a Session's or a line's data face by id with // the two data operations (#2127). The request's `service`, `method` and // `args` are the target's own, so a typo fails to compile. -import type { Sessions, SessionScope } from '../../npm/branch-services.js' +import type { Sessions } from '../../npm/plugin.js' +import type { SessionScope } from '../../npm/branch-services.js' export async function readByCalls( scope: SessionScope, diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index f100d3156e..486b45fbff 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -55,7 +55,8 @@ test('packed plugin service types compile the author guide and enforce the publi }); const routed = path.join(directory, 'branch-calls.mts'); writeFileSync(routed, readFileSync(path.join(root, 'runtime/fixtures/branch-calls.ts'), 'utf8') - .replaceAll("'../../npm/branch-services.js'", "'dimcode/branch-services.js'")); + .replaceAll("'../../npm/branch-services.js'", "'dimcode/branch-services.js'") + .replaceAll("'../../npm/plugin.js'", "'dimcode/plugin'")); const calls = path.join(directory, 'calls.mts'); writeFileSync(calls, ` import type { Settings, SettingsResult, Sessions, WorkflowFiles, WorkflowFileEntry, WorkflowFilesErrorThrown, SessionPermissions, PermissionState, PermissionPolicy, SessionsErrorThrown, SessionMetadata, SessionMetadataResult, AuxiliaryModel, AuxiliaryReply, FileScope, FileResult, ToolRegistry, ToolExecute, ToolResult, SessionMethods, SessionMethodHandler, ManagementMethods, MethodHandler, MethodDeclaration, SessionConfig, SessionBroadcast, BranchEvent, Services, AgentErrorThrown, MethodReply, CallChannel, CallChannelError, EventHub, EventHubDeclaration, EventHubDelivery, EventHubErrorThrown, EventHubPublishReply } from 'dimcode/plugin'; @@ -136,7 +137,7 @@ const preset: 'read-only' | 'workspace-write' | 'full-access' = defaults.preset; const allowed: string[] = livePolicy.allowedTools; const disallowed: string[] = defaults.disallowedTools; declare const permissionError: SessionsErrorThrown; -const permissionCode: 'rejected' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; +const permissionCode: 'rejected' | 'routed' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; void permissionVersion; void preset; void allowed; void disallowed; void permissionCode; // @ts-expect-error permission reads require a branch identity. void permissions.permission({ sessionId: 'session' }); From c4a097a8933c71c61a83e467674bff7f0b935785 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:08:51 +0800 Subject: [PATCH 09/37] fix(runtime): select by id through the holders, under the decided shape The maintainer's decision on #2127, applied whole: - the Rust typed entries are gone (`LineHandle::get`, `line`, `session_face`): Rust calls `sessionScope.lineCall` and `sessions.call` like any other language, building `args` from the target operation's request type; - `sessions.call` loads the Session through Agents' `acquire` and holds it for the call; `Reloading` answers `SessionReloading`, `Storage` and a failed restore `SessionUnavailable { reason }`, `Closed` `NoSession`, and a Session with no owner `NoSession`; - a line is selected from TimelineTree's `published`, the same published view both paths see, instead of a table filled before publication; a closing line still answers `NoLine`; - routing answers are their own codes (`no_session`, `session_closing`, `session_reloading`, `session_unavailable`, `no_line`), and the owner's failure comes back as `Routed { name, message }`; `session_reloading` and `routed` are retryable. The generated requests now derive each face and group from the registration calls themselves, since main no longer commits an assembled catalog, and the names an assembly marks internal are left out of them. `xtask/access-layer.json` gains the 33 violations #2002 added (171 total); no other entry changed. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 18 +- crates/dim-agent-runtime/src/assembly.rs | 29 +- crates/dim-agent-runtime/src/route.rs | 57 +-- .../tests/data_faces_flow.rs | 25 +- crates/dim-app-server/src/agents.rs | 63 ++- crates/dim-app-server/src/agents/sessions.rs | 52 ++- .../contracts/runtime-owner-operations.md | 10 +- docs/typescript-plugin-authoring.md | 3 +- npm/branch-services.d.ts | 18 +- runtime/plugin-sdk.test.mjs | 2 +- xtask/access-layer.json | 165 +++++++ xtask/check/src/plugin_docs.rs | 408 ------------------ xtask/check/src/types.rs | 287 +++++++++++- 13 files changed, 540 insertions(+), 597 deletions(-) delete mode 100644 xtask/check/src/plugin_docs.rs diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index b99abe0550..11cf239509 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -2,7 +2,7 @@ //! id, and answer `SessionClosing`, `NoLine` or a reach refusal otherwise //! ([#2127](https://github.com/arcships/dim/issues/2127)). -use dim_agent_capabilities::{defaults, timeline_tree::BranchLine}; +use dim_agent_capabilities::defaults; use dim_agent_runtime::testing::{MinimalHost, hold_close}; use dim_agent_runtime::*; use dim_agent_types::BranchSource; @@ -176,22 +176,6 @@ async fn a_session_part_reaches_its_own_line_and_its_own_faces() { .unwrap(); assert_eq!(config, serde_json::to_value(session.config()).unwrap()); - assert!(line(&scope, "main").get::().is_ok()); - assert_eq!( - line(&scope, "main").get::().err(), - Some(RouteError::NotDataFace { - service: "loopState".into() - }), - "the line's typed read resolves data faces only" - ); - assert!(session_face::(&scope).is_ok()); - assert_eq!( - session_face::(&scope).err(), - Some(RouteError::NotDataFace { - service: "sessionMethods".into() - }), - "the Session's typed read refuses a registration point too" - ); rig.host.close().await.unwrap(); } diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 638398e126..4acb13d358 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -1141,9 +1141,6 @@ pub(crate) struct SessionAssembly { /// The views its scope mounted when it opened, until its creation ends. pub(crate) handed: Mutex, pub(crate) copies: crate::parts::Copies, - /// The line instances this Session's tree created, by id. An entry whose - /// context is gone, closing or closed resolves to no line. - lines: Mutex>>, } impl SessionAssembly { pub(crate) fn loaded(&self) -> Result>> { @@ -1164,22 +1161,16 @@ impl SessionAssembly { .ok_or_else(|| AgentError::Reloading(std::any::type_name::().into())) } - /// Records the line instance `id` only while it is live. - pub(crate) fn register_line(&self, id: &str, line: Weak) { - self.lines.lock().unwrap().insert(id.to_owned(), line); - } - - /// The live line instance `id`, or `None` when this Session never created - /// it, it is gone, or it is closing. An entry whose instance is gone is - /// dropped here. + /// The published line `id` of this Session, or `None` when it is not + /// published, has ended, or is already closing. The tree's own view decides + /// publication, so the process path and a Session part see the same state + /// (ADR 027 D2). pub(crate) fn line(&self, id: &str) -> Option> { - let mut lines = self.lines.lock().unwrap(); - let line = lines.get(id)?.upgrade(); - let Some(line) = line else { - lines.remove(id); - return None; - }; - drop(lines); + let loaded = self.loaded().ok()?; + let tree = loaded + .ctx + .get_at::(&loaded.scope.key::())?; + let line = tree.published(id).ok()?.0; (!line.is_closing()).then_some(line) } @@ -1564,7 +1555,6 @@ impl TimelineFactory { parent.assembly.catalog.clone(), parent.assembly.faces.clone(), ); - parent.register_line(&id, Arc::downgrade(&context)); Ok(context) }) .catch_unwind() @@ -1931,7 +1921,6 @@ pub(crate) async fn build_session( mounted: Arc::default(), handed: Mutex::default(), copies: Arc::default(), - lines: Mutex::default(), }); let instance = |owner: &Arc| { let owner = owner.clone(); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 92ba705fb1..cf60e15bde 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -17,9 +17,9 @@ //! - [`SessionScope::line_call`] — `{lineId, service, method, args}`; //! - `sessions.call` — `{sessionId, lineId?, service, method, args}`. //! -//! An address records ids and resolves nothing; each call looks the target up -//! again, so a caller never keeps a live target (D4). Rust reads the owner's -//! face through [`line`] and [`LineHandle::get`] at the call. +//! Each call looks the target up again, so a caller never keeps a live target +//! (D4). Rust calls the same two operations: it builds `args` from the target +//! operation's request type and reads the reply as its reply type. //! //! What a call resolves is the target scope's data face in the catalog. A name //! the assembly marks `internal(reason)`, a mechanism registration point @@ -62,6 +62,15 @@ pub enum RouteError { /// [`Self::NoSession`]. #[error("Session {0} is closing")] SessionClosing(String), + /// Agents is reloading and cannot take calls yet. A process caller retries + /// later. + #[error("Agents is reloading: {0}")] + SessionReloading(String), + /// The Session exists but cannot be loaded now: its restore failed, or the + /// Agent that owns it is unavailable. The caller reports the reason and + /// does not retry. + #[error("Session {session} is unavailable: {reason}")] + SessionUnavailable { session: String, reason: String }, /// The Session is live but the line is closing, closed, or not one of its /// lines. Final for that line: no hold and no retry. #[error("no line {line} in Session {session}")] @@ -86,6 +95,8 @@ impl RouteError { match self { Self::NoSession(_) => "no_session", Self::SessionClosing(_) => "session_closing", + Self::SessionReloading(_) => "session_reloading", + Self::SessionUnavailable { .. } => "session_unavailable", Self::NoLine { .. } => "no_line", Self::NotDataFace { .. } => "not_data_face", Self::WrongScope { .. } => "wrong_scope", @@ -242,46 +253,6 @@ impl SessionScope { } } -/// The address of one of a Session's own lines: ids only, looked up at the -/// call ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D4). -pub struct LineHandle { - scope: Arc, - line_id: String, -} - -impl LineHandle { - /// The line-scope data face `T`, resolved now; the caller uses it for this - /// call and does not keep it. - pub fn get(&self) -> Routed> { - let line = self.scope.line_context(&self.line_id)?; - face( - line.catalog(), - line.faces(), - &names::name_of::(), - BRANCH_GROUP, - )?; - line.public::().map_err(owner) - } -} - -/// The Session-scope data face `T` of the caller's own Session, resolved now; -/// the caller uses it for this call and does not keep it. -pub fn session_face(scope: &SessionScope) -> Routed> { - let session = scope.live()?; - let (catalog, faces) = session.reach(); - face(catalog, faces, &names::name_of::(), SESSION_GROUP)?; - session.session_face::().map_err(owner) -} - -/// Addresses line `line_id` of the caller's own Session: nothing is looked up -/// until a method of [`LineHandle`] is called. -pub fn line(scope: &Arc, line_id: &str) -> LineHandle { - LineHandle { - scope: scope.clone(), - line_id: line_id.to_owned(), - } -} - /// Fails unless a route may resolve `service` as a data face of `group` /// (module docs). pub(crate) fn face( diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index 2885fd9843..d3f8418f17 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -832,14 +832,7 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!({"sessionId": "absent", "service": "sessionConfig", "method": "get"}), ) .await; - assert!( - unknown["error"]["code"] == "rejected" - && unknown["error"]["message"] - .as_str() - .unwrap_or_default() - .contains("no_session"), - "{unknown}" - ); + assert_eq!(unknown["error"]["code"], "no_session", "{unknown}"); let missing = rig .call( "sessions", @@ -847,13 +840,7 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!({"sessionId": id, "lineId": "absent", "service": "timeline", "method": "sequence"}), ) .await; - assert!( - missing["error"]["message"] - .as_str() - .unwrap_or_default() - .contains("no_line"), - "{missing}" - ); + assert_eq!(missing["error"]["code"], "no_line", "{missing}"); session.close().await.unwrap(); let closed = rig .call( @@ -862,12 +849,6 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), ) .await; - assert!( - closed["error"]["message"] - .as_str() - .unwrap_or_default() - .contains("no_session"), - "{closed}" - ); + assert_eq!(closed["error"]["code"], "no_session", "{closed}"); rig.close().await; } diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 2d5e322c98..a446c9eab6 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1638,29 +1638,44 @@ impl AgentIndex { } /// Calls a data face of the live Session `id`, or of one of its lines /// ([#2127](https://github.com/arcships/dim/issues/2127), - /// [ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1): the - /// Session's own scope resolves the line, so the caller names no instance - /// key and keeps no object. A Session with no live instance answers - /// `NoSession`, one that is closing `SessionClosing`, and a line that is - /// closing, closed or not its own `NoLine`. + /// [ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D1, D5): + /// the Session is loaded for the call and held while it runs, its own scope + /// resolves a line, and the target's reply and error come back unchanged. + /// A target that cannot be selected answers `NoSession`, + /// `SessionClosing`, `SessionReloading`, `SessionUnavailable` or `NoLine` + /// before the target's operation runs. pub(crate) async fn call( &self, request: crate::agents::sessions::CallRequest, ) -> std::result::Result { let id = request.session_id.clone(); - let session = self - .live(&id) - .ok_or_else(|| RouteError::NoSession(id.clone()))?; + // No owner knows the id: it was closed, deleted, or never existed, so + // it cannot be loaded again (#2127). + let known = self + .directory + .inner + .lock() + .expect("agent index") + .owner(&id) + .is_some(); + let used = self.acquire(&id).await.map_err(|error| match error { + _ if !known => RouteError::NoSession(id.clone()), + AgentError::Reloading(_) => RouteError::SessionReloading(id.clone()), + AgentError::Closed(_) => RouteError::NoSession(id.clone()), + error => RouteError::SessionUnavailable { + session: id.clone(), + reason: error.to_string(), + }, + })?; + let session = &used.session; if session.is_closing() { return Err(RouteError::SessionClosing(id)); } - // A Session that starts closing while the call runs answers that way - // too: its lines close with it. let scope = session .session_service::() - .map_err(|error| RouteError::Owner { - name: "AgentError".into(), - message: error.to_string(), + .map_err(|error| RouteError::SessionUnavailable { + session: id.clone(), + reason: error.to_string(), })?; match request.line_id { Some(line_id) => { @@ -1684,28 +1699,6 @@ impl AgentIndex { } } } - /// The live Session `id`, whichever Agent publishes it. A single call needs - /// no hold: the Session is either live now or it is not (ADR 027 D5). - fn live(&self, id: &str) -> Option { - let inner = self.directory.inner.lock().expect("agent index"); - let host = inner.owner(id)?; - host.agent.get_session(id) - } - /// `session.delete` ([S5c §3.2](../../../docs/design/appserver/session-deletion-and-fork.md#32-sequence)): - /// holds S's admission gate, so nothing loads or builds S meanwhile, - /// closes S if it is loaded, has SessionStore remove what it stores of - /// S, then forgets S and drops its slot, which stays closed until - /// nothing else holds it. A stored S that was neither loaded nor closed - /// ends without a close, so the delete announces it with - /// [`UnloadedSessionDeleted`]. An unknown id has nothing to remove and - /// keeps no slot. A delete that fails before the rows go leaves a - /// Session it closed as `session.close` does, closed in this process with - /// its rows kept (D5); one it did not close loads again on its next use. - /// - /// The reply reports whether this call removed the Session: its stored - /// rows, or, in a daemon without a native store, a loaded Session. A - /// Session in use is closed and removed as before; - /// [`Self::delete_if_inactive`] is the delete that refuses it. pub(crate) async fn delete(&self, id: &str) -> dim_agent_runtime::Result { let _activity = self .activity diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index feb914fd40..6da309407a 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -296,14 +296,22 @@ pub struct StopRequest { pub enum SessionsError { #[error("{message}")] Rejected { message: String }, - /// A routed call's own failure: the routing kind (`routing`), the name the - /// owner wrote when the owner failed, and the message. + /// A routed call could not select its target: `no_session`, + /// `session_closing`, `session_reloading`, `session_unavailable` or + /// `no_line`. Only `session_reloading` is retryable. #[error("{message}")] - Routed { - routing: String, - name: String, - message: String, - }, + NoSession { message: String }, + #[error("{message}")] + SessionClosing { message: String }, + #[error("{message}")] + SessionReloading { message: String }, + #[error("{message}")] + SessionUnavailable { message: String }, + #[error("{message}")] + NoLine { message: String }, + /// The target owner's own failure, with the name and message it wrote. + #[error("{message}")] + Routed { name: String, message: String }, #[error("{message}")] AgentUnknown { message: String }, #[error("{message}")] @@ -338,7 +346,10 @@ impl SessionsError { pub fn retryable(&self) -> bool { matches!( self, - Self::Reloading { .. } | Self::PublicationUnknown { .. } + Self::Reloading { .. } + | Self::PublicationUnknown { .. } + | Self::SessionReloading { .. } + | Self::Routed { .. } ) } } @@ -864,6 +875,24 @@ impl HostDispatch for SessionsService { } } +/// The routing answer as this face reports it: its own kind for a target that +/// could not be selected, and the owner's failure as the owner wrote it. +fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { + use dim_agent_runtime::RouteError; + let message = error.to_string(); + match error { + RouteError::NoSession(_) => SessionsError::NoSession { message }, + RouteError::SessionClosing(_) => SessionsError::SessionClosing { message }, + RouteError::SessionReloading(_) => SessionsError::SessionReloading { message }, + RouteError::SessionUnavailable { .. } => SessionsError::SessionUnavailable { message }, + RouteError::NoLine { .. } => SessionsError::NoLine { message }, + RouteError::Owner { name, .. } => SessionsError::Routed { name, message }, + RouteError::NotDataFace { .. } | RouteError::WrongScope { .. } => { + SessionsError::Rejected { message } + } + } +} + fn envelope(result: Result) -> Value { match result { Ok(value) => json!({"ok": true, "value": value}), @@ -922,12 +951,7 @@ async fn call( } // The routing answer names itself in the message until the Agents // contract gives this face routing codes of its own. - "call" => index - .call(request(args)?) - .await - .map_err(|error| SessionsError::Rejected { - message: format!("{}: {error}", error.code()), - }), + "call" => index.call(request(args)?).await.map_err(routed), _ => Err(SessionsError::rejected(format!( "unknown sessions method {method}" ))), diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 1b5e74434c..8d3b93c2f0 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -37,10 +37,12 @@ owner's face, and the owner of the line's index resolves it ([#2127](https://github.com/arcships/dim/issues/2127), [ADR 027](../../adr/027-cross-scope-access-by-id.md)): `sessionScope.lineCall` reaches a line of the caller's own Session, `sessions.call` a Session and a line of it for the -process, and both pass the owner's arguments, reply and error through. A line that is -closing, closed or not this Session's answers `no_line`, which is final for it; a calling -Session that is closing answers `session_closing`. Tree history, directory and batch input -continue to use the tree's own methods. +process, and both pass the owner's arguments, reply and error through. Agents loads the +Session for the call and holds it while it runs (ADR 027 D5). A target that cannot be +selected answers `no_session`, `session_closing`, `session_reloading` (retry later), +`session_unavailable` (report the reason) or `no_line` (final for that line), before the +target's operation runs. Tree history, directory and batch input continue to use the +tree's own methods. | Session caller | Target operation | | --- | --- | diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index aecd169e50..57659e689f 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -56,7 +56,8 @@ await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: The request types are generated, so `service`, `method` and `args` are the target's own and a typo fails `tsc`. Nothing a call returns may be kept: the next call looks the target up -again. +again. Rust calls the same operations: it builds `args` from the target operation's request +type and reads the reply as that operation's reply type. ## Available services diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 9072e4848f..17a71fa911 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1461,7 +1461,12 @@ export type PermissionState = { /** A Session service failure; generated exports throw this serde value. */ export type SessionsError = | { code: "rejected"; message: string } - | /** A routed call's own failure: the routing kind (`routing`), the name the owner wrote when the owner failed, and the message. */ { code: "routed"; routing: string; name: string; message: string } + | /** A routed call could not select its target: `no_session`, `session_closing`, `session_reloading`, `session_unavailable` or `no_line`. Only `session_reloading` is retryable. */ { code: "no_session"; message: string } + | { code: "session_closing"; message: string } + | { code: "session_reloading"; message: string } + | { code: "session_unavailable"; message: string } + | { code: "no_line"; message: string } + | /** The target owner's own failure, with the name and message it wrote. */ { code: "routed"; name: string; message: string } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } | { code: "branch_missing"; message: string } @@ -1796,13 +1801,13 @@ export type ReservedMethodsErrorThrown = RustError<"ReservedMethodsError", "rese export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceError> /** What a method returning `Err(RouteError)` throws. */ -export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClosing" | "NoLine" | "NotDataFace" | "WrongScope" | "Owner", undefined> +export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClosing" | "SessionReloading" | "SessionUnavailable" | "NoLine" | "NotDataFace" | "WrongScope" | "Owner", undefined> /** What a method returning `Err(SessionInstanceError)` throws. */ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> /** What a method returning `Err(SessionsError)` throws. */ -export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> +export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "no_session" | "session_closing" | "session_reloading" | "session_unavailable" | "no_line" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> @@ -1862,7 +1867,6 @@ export interface Services { export type LineFaces = { approval: Approval backgroundExec: BackgroundExec - branchLine: BranchLine dispatcher: Dispatcher inputQueue: InputQueue permission: Permission @@ -1873,15 +1877,11 @@ export type LineFaces = { /** The data faces a Session reaches. */ export type SessionFaces = { - agentConfig: AgentConfig - collaborationConfig: CollaborationConfig - initialPromptConfiguration: InitialPromptConfiguration mcpSession: McpSession sessionConfig: SessionConfig sessionIdentity: SessionIdentity - sessionLanguage: SessionLanguage sessionLoader: SessionLoader - skillsConfig: SkillsConfig + sessionScope: SessionScope toolHost: ToolHost treeCommands: TreeCommands uiResources: UiResources diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index 486b45fbff..fd0a6dd873 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -137,7 +137,7 @@ const preset: 'read-only' | 'workspace-write' | 'full-access' = defaults.preset; const allowed: string[] = livePolicy.allowedTools; const disallowed: string[] = defaults.disallowedTools; declare const permissionError: SessionsErrorThrown; -const permissionCode: 'rejected' | 'routed' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; +const permissionCode: 'rejected' | 'routed' | 'no_session' | 'session_closing' | 'session_reloading' | 'session_unavailable' | 'no_line' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; void permissionVersion; void preset; void allowed; void disallowed; void permissionCode; // @ts-expect-error permission reads require a branch identity. void permissions.permission({ sessionId: 'session' }); diff --git a/xtask/access-layer.json b/xtask/access-layer.json index 721b498d9d..6173b1285b 100644 --- a/xtask/access-layer.json +++ b/xtask/access-layer.json @@ -50,6 +50,146 @@ "file": "crates/dim-agent-capabilities/src/host.rs", "item": "ToolHost::0" }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::arch" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::build_process_spec" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::child_path_process" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::command_shutdown" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::command_workers" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::commands" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::configured" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::env" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::execution" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::home" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::installed_toolchains" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::os" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::platform_roots" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::prepare_isolated_process" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::remove_exec_directory" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::retained_output_page" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::spawn_pty" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::spawn_tree" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::spawn_with_stdin_process" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::start_shell" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::timezone" + }, + { + "kind": "rust-only-field", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::toolchain" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::with_execution_settings" + }, + { + "kind": "service-skip", + "file": "crates/dim-agent-capabilities/src/host_platform.rs", + "item": "HostPlatform::with_toolchain_source" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/confined.rs", + "item": "HostPlatform::spawn_confined_process" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs", + "item": "HostPlatform::read_exec_shell_settings" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/exec_shell_settings.rs", + "item": "HostPlatform::update_exec_shell_settings" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/host_platform/isolation.rs", + "item": "HostPlatform::prepare_isolated_process" + }, { "kind": "service-skip", "file": "crates/dim-agent-capabilities/src/input_queue.rs", @@ -270,6 +410,26 @@ "file": "crates/dim-agent-capabilities/src/workspace_tools/background.rs", "item": "BackgroundExec::start" }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::command_task" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::retain_output_by_id" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::start_command" + }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-capabilities/src/workspace_tools/exec.rs", + "item": "HostPlatform::tail_by_id" + }, { "kind": "session-forwarding", "file": "crates/dim-agent-runtime/src/agent.rs", @@ -360,6 +520,11 @@ "file": "crates/dim-agent-runtime/src/agent.rs", "item": "Session::service" }, + { + "kind": "session-forwarding", + "file": "crates/dim-agent-runtime/src/agent.rs", + "item": "Session::service_opt" + }, { "kind": "session-forwarding", "file": "crates/dim-agent-runtime/src/agent.rs", diff --git a/xtask/check/src/plugin_docs.rs b/xtask/check/src/plugin_docs.rs deleted file mode 100644 index 518e5cc93c..0000000000 --- a/xtask/check/src/plugin_docs.rs +++ /dev/null @@ -1,408 +0,0 @@ -//! Static checks and block rewriting for plugin documents under -//! `docs/architecture/rust-agent/plugins/` against the recorded local graph. - -use serde_json::Value; -use std::{ - collections::{BTreeMap, BTreeSet}, - path::{Path, PathBuf}, -}; - -type Result = std::result::Result>; - -const BEGIN: &str = ""; -const INFRASTRUCTURE: [&str; 12] = [ - "rutis-loader", - "session", - "branch", - "SessionScope", - "BranchScope", - // The instances' mounters (ADR 006 D3); the parts they mount have pages. - "SessionParts", - "SessionOptionalParts", - "BranchParts", - "BranchOptionalParts", - "SessionBroadcast", - "SessionBroadcastEnd", - "PrepareModelHost", -]; - -fn docs_dir(root: &Path) -> PathBuf { - root.join("docs/architecture/rust-agent/plugins") -} - -pub fn graph_file(root: &Path) -> PathBuf { - root.join("docs/architecture/rust-agent/generated/local/services.json") -} - -/// Rewrites every plugin document's generated blocks from `graphs`. -pub fn rewrite>(root: &Path, graphs: &BTreeMap) -> Result<()> { - let facts = Facts::new(graphs); - for (path, names) in documents(root)? { - let mut text = std::fs::read_to_string(&path)?; - for name in names { - let (before, _, after) = split_block(&text, &name, &path)?; - text = format!("{before}{}{after}", facts.block(&name)?); - } - std::fs::write(&path, text)?; - } - Ok(()) -} - -/// Checks every plugin document against the recorded local graph. -pub fn check(root: &Path) -> Result<()> { - let documents = documents(root)?; - if documents.is_empty() { - return Err(format!("{}: no plugin documents", docs_dir(root).display()).into()); - } - let graphs: BTreeMap = - serde_json::from_str(&std::fs::read_to_string(graph_file(root))?)?; - let facts = Facts::new(&graphs); - let mut errors = Vec::new(); - let documented: BTreeSet<_> = documents - .iter() - .flat_map(|(_, names)| names.iter().map(String::as_str)) - .collect(); - for (_, plugin) in &facts.plugins { - let name = plugin["name"].as_str().ok_or("plugin graph has no name")?; - if !INFRASTRUCTURE.contains(&name) && !documented.contains(name) { - errors.push(format!( - "business plugin `{name}` has no document in {}", - docs_dir(root).display() - )); - } - } - for (path, name, section) in documents - .iter() - .map(|(path, names)| Ok((path, names, std::fs::read_to_string(path)?))) - .collect::>>()? - .iter() - .flat_map(|(path, names, text)| { - sections(text, names).map(move |(name, section)| (*path, name, section)) - }) - { - let (_, block, _) = split_block(section, name, path)?; - match facts.block(name) { - Err(error) => errors.push(error.to_string()), - Ok(expected) if expected != block => errors.push(format!( - "{}: `{name}`: generated block is stale; run `cargo run -p xtask -- graph`", - path.display() - )), - Ok(_) => {} - } - let injected: BTreeSet = facts - .plugin(name) - .map(|plugin| facts.injects(plugin).into_iter().collect()) - .unwrap_or_default(); - let explained = dependency_rows(section); - for missing in injected.difference(&explained) { - errors.push(format!( - "{}: `{name}`: dependency table does not explain injected `{missing}`", - path.display() - )); - } - for extra in explained.difference(&injected) { - errors.push(format!( - "{}: `{name}`: dependency table explains `{extra}`, which it does not inject", - path.display() - )); - } - } - if errors.is_empty() { - println!("plugin documents passed ({} documents)", documents.len()); - Ok(()) - } else { - Err(errors.join("\n").into()) - } -} - -/// Each part a page documents with the text that documents it: from the end -/// of the previous part's block, or the start, to the end of its own block. -fn sections<'a>( - text: &'a str, - names: &'a [String], -) -> impl Iterator + 'a { - let mut start = 0; - names.iter().map(move |name| { - let marker = format!("{BEGIN}{name} "); - let end = text[start..] - .find(&marker) - .and_then(|at| { - text[start + at..] - .find(END) - .map(|end| start + at + end + END.len()) - }) - .unwrap_or(text.len()); - let section = &text[start..end]; - start = end; - (name, section) - }) -} - -/// The parts or process plugins a page documents: the names of its -/// generated blocks, in order. -fn documented(text: &str) -> Vec { - text.match_indices(BEGIN) - .filter_map(|(at, _)| { - text[at + BEGIN.len()..] - .split_whitespace() - .next() - .map(str::to_owned) - }) - .collect() -} - -/// `(path, documented names)` of every page; a page documents at least one. -fn documents(root: &Path) -> Result)>> { - let dir = docs_dir(root); - let entries = std::fs::read_dir(&dir).map_err(|error| format!("{}: {error}", dir.display()))?; - let mut documents = Vec::new(); - for entry in entries { - let path = entry?.path(); - let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else { - continue; - }; - if path.extension().is_some_and(|ext| ext == "md") && stem != "README" { - let names = documented(&std::fs::read_to_string(&path)?); - if names.is_empty() { - return Err(format!("{}: no generated block", path.display()).into()); - } - documents.push((path.clone(), names)); - } - } - documents.sort(); - Ok(documents) -} - -/// `(before, block, after)`; the block spans both markers. -fn split_block<'a>(text: &'a str, name: &str, path: &Path) -> Result<(&'a str, &'a str, &'a str)> { - let marker = format!("{BEGIN}{name} "); - let start = text - .find(&marker) - .ok_or_else(|| format!("{}: missing `{marker}...` block", path.display()))?; - let end = text[start..] - .find(END) - .map(|offset| start + offset + END.len()) - .ok_or_else(|| format!("{}: unterminated generated block", path.display()))?; - Ok((&text[..start], &text[start..end], &text[end..])) -} - -/// First-column codes of the hand-written dependency table. -fn dependency_rows(text: &str) -> BTreeSet { - let mut rows = BTreeSet::new(); - let mut inside = false; - for line in text.lines() { - if let Some(heading) = line.strip_prefix("##") { - inside = matches!( - heading.trim_start_matches('#').trim(), - "Dependencies" | "依赖" - ); - continue; - } - let Some(cell) = line - .strip_prefix('|') - .and_then(|rest| rest.split('|').next()) - else { - continue; - }; - let cell = cell.trim(); - if inside && cell.starts_with('`') && cell.ends_with('`') && cell.len() > 2 { - rows.insert(cell.trim_matches('`').to_owned()); - } - } - rows -} - -/// `dim_agent_x::m::Name#key@main` → `B:Name#key`. -fn code(service: &str) -> String { - let (path, scope) = match service.rsplit_once('@') { - Some((path, "main")) => (path, "B"), - Some((path, "session")) => (path, "S"), - Some((path, _)) => (path, "?"), - None => (service, "P"), - }; - let mut short = String::new(); - let mut segment = String::new(); - let mut chars = path.chars().peekable(); - while let Some(ch) = chars.next() { - if ch == ':' && chars.peek() == Some(&':') { - chars.next(); - segment.clear(); - continue; - } - if ch.is_alphanumeric() || ch == '_' { - segment.push(ch); - continue; - } - short.push_str(&segment); - segment.clear(); - short.push(ch); - } - short.push_str(&segment); - format!("{scope}:{short}") -} - -struct Facts<'a> { - /// `(scope, plugin)` of every plugin in the profile. - plugins: Vec<(&'a str, &'a Value)>, - bindings: Vec<&'a Value>, -} -impl<'a> Facts<'a> { - fn new>(graphs: &'a BTreeMap) -> Self { - let mut plugins = Vec::new(); - let mut bindings = Vec::new(); - for (scope, graph) in graphs { - for plugin in graph["plugins"].as_array().into_iter().flatten() { - plugins.push((scope.as_ref(), plugin)); - } - bindings.extend(graph["bindings"].as_array().into_iter().flatten()); - } - Self { plugins, bindings } - } - fn plugin(&self, name: &str) -> Option<&(&'a str, &'a Value)> { - self.plugins - .iter() - .find(|(_, plugin)| plugin["name"] == name) - } - fn injects(&self, (_, plugin): &(&str, &Value)) -> Vec { - plugin["injects"] - .as_array() - .into_iter() - .flatten() - .map(|inject| code(inject["service"].as_str().unwrap_or_default())) - .collect() - } - fn block(&self, name: &str) -> Result { - let found = self - .plugin(name) - .ok_or_else(|| format!("plugin `{name}` is not in the local execution profile"))?; - let (scope, plugin) = found; - let id = &plugin["id"]; - let scope = match *scope { - "process" => "进程", - "session" => "Session", - _ => "分支", - }; - let list = |items: BTreeSet| { - if items.is_empty() { - "—".to_owned() - } else { - items - .into_iter() - .map(|item| format!("`{item}`")) - .collect::>() - .join("、") - } - }; - let injects = list(self.injects(found).into_iter().collect()); - let provides = list( - self.bindings - .iter() - .filter(|binding| binding["provider"] == *id) - .map(|binding| code(binding["service"].as_str().unwrap_or_default())) - .collect(), - ); - let dependents = list( - self.plugins - .iter() - .filter(|(_, other)| { - other["resolved"] - .as_array() - .into_iter() - .flatten() - .any(|edge| edge["provider"] == *id) - }) - .map(|(_, other)| other["name"].as_str().unwrap_or_default().to_owned()) - .collect(), - ); - Ok(format!( - "{BEGIN}{name} — 由 `cargo run -p xtask -- graph` 从真实装配生成,勿手改 -->\n| 项 | 值 |\n| --- | --- |\n| 作用域 | {scope} |\n| 注入 | {injects} |\n| 提供 | {provides} |\n| 被注入于 | {dependents} |\n{END}" - )) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn write_fixture(root: &Path, graphs: &BTreeMap<&'static str, Value>) -> Result<()> { - let file = graph_file(root); - std::fs::create_dir_all(file.parent().unwrap())?; - std::fs::write(&file, serde_json::to_string_pretty(graphs)? + "\n")?; - rewrite(root, graphs) - } - - #[test] - fn documentation_check_requires_complete_profile_and_exact_dependencies() { - let root = std::env::temp_dir().join(format!( - "dim-plugin-doc-check-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - std::fs::create_dir_all(&root).unwrap(); - let result = (|| -> Result<()> { - assert!(check(&root).is_err(), "missing directory must not pass"); - std::fs::create_dir_all(docs_dir(&root))?; - let mut graphs = BTreeMap::from([( - "main", - serde_json::json!({ - "plugins": [ - {"id":1,"name":"branch","injects":[],"resolved":[]}, - {"id":2,"name":"Example","injects":[{"service":"crate::Timeline@main"}],"resolved":[]} - ], - "bindings":[] - }), - )]); - write_fixture(&root, &graphs)?; - assert!(check(&root).is_err(), "empty document set must not pass"); - let path = docs_dir(&root).join("Example.md"); - let page = format!( - "# Example\n\n## Dependencies\n\n| Service | Purpose |\n| --- | --- |\n| `B:Timeline` | Commit results |\n\n{BEGIN}Example -->\n{END}\n" - ); - std::fs::write(&path, &page)?; - write_fixture(&root, &graphs)?; - check(&root)?; - let valid = std::fs::read_to_string(&path)?; - std::fs::write( - &path, - valid.replace("| `B:Timeline` | Commit results |", ""), - )?; - assert!( - check(&root).is_err(), - "a missing dependency explanation must fail" - ); - std::fs::write(&path, &valid)?; - graphs.get_mut("main").unwrap()["plugins"] - .as_array_mut() - .unwrap() - .push( - serde_json::json!({"id":3,"name":"NewCapability","injects":[],"resolved":[]}), - ); - write_fixture(&root, &graphs)?; - assert!( - check(&root).is_err(), - "new business plugins require documentation" - ); - graphs.get_mut("main").unwrap()["plugins"] - .as_array_mut() - .unwrap() - .pop(); - write_fixture(&root, &graphs)?; - std::fs::write( - docs_dir(&root).join("Removed.md"), - page.replace("Example", "Removed"), - )?; - assert!( - check(&root).is_err(), - "removed plugins must not retain orphan documents" - ); - std::fs::remove_file(docs_dir(&root).join("Removed.md"))?; - check(&root) - })(); - std::fs::remove_dir_all(root).unwrap(); - result.unwrap(); - } -} diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 99ad672071..660d18a268 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -17,8 +17,6 @@ fn file(root: &Path) -> PathBuf { /// and `args` the method's parameters, so a typo fails `tsc` /// ([#2127](https://github.com/arcships/dim/issues/2127)). fn calls(root: &Path, services: &str) -> Result { - let catalog = - std::fs::read_to_string(root.join("docs/architecture/rust-agent/generated/catalog.md"))?; let unroutable = unroutable(root)?; let declared: Vec<&str> = services .lines() @@ -30,37 +28,27 @@ fn calls(root: &Path, services: &str) -> Result { .collect(); let mut session = Vec::new(); let mut line = Vec::new(); - for row in catalog.lines().filter(|line| line.starts_with("| `")) { - let cells: Vec<&str> = row.split('|').map(str::trim).collect(); - let Some(name) = cells.get(1).and_then(|name| name.strip_prefix('`')) else { - continue; - }; - let Some(name) = name.strip_suffix('`') else { - continue; - }; - let (group, face) = match (cells.get(2), cells.get(4)) { - (Some(group), Some(face)) => (*group, *face), - _ => continue, - }; - if face != "data" || name == "sessionScope" || name == "sessions" { - continue; - } - if unroutable.iter().any(|refused| refused == name) { + for (name, group) in registered(root)? { + if unroutable.contains(&name) { continue; } let Some(ty) = declared.iter().find(|ty| catalog_name(ty) == name).copied() else { continue; }; - match group { - "session" => session.push((name.to_owned(), ty.to_owned())), - "branch" => line.push((name.to_owned(), ty.to_owned())), + match group.as_str() { + "session" => session.push((name, ty.to_owned())), + "branch" => line.push((name, ty.to_owned())), _ => {} } } + session.sort(); + session.dedup(); + line.sort(); + line.dedup(); let faces = |items: &[(String, String)], name: &str| { let mut text = format!("export type {name} = {{\n"); - for (name, ty) in items { - text += &format!(" {name}: {ty}\n"); + for (member, ty) in items { + text += &format!(" {member}: {ty}\n"); } text + "}\n" }; @@ -75,6 +63,182 @@ fn calls(root: &Path, services: &str) -> Result { Ok(text) } +/// The catalog name and group of every service the workspaces' crates +/// register, read from the registration calls themselves: a name is in a group +/// because some `register`/`register_shared_instance` call puts it there. +fn registered(root: &Path) -> Result> { + let mut found = Vec::new(); + for entry in std::fs::read_dir(root.join("crates"))? { + let directory = entry?.path().join("src"); + if !directory.is_dir() { + continue; + } + let mut files = Vec::new(); + sources(&mut files, &directory)?; + for file in files { + let text = std::fs::read_to_string(&file)?; + let ast = syn::parse_file(&text)?; + registrations(&ast.items, &mut found); + } + } + Ok(found) +} + +fn sources(files: &mut Vec, directory: &Path) -> Result<()> { + for entry in std::fs::read_dir(directory)? { + let path = entry?.path(); + if path.is_dir() { + sources(files, &path)?; + } else if path.extension().is_some_and(|extension| extension == "rs") { + files.push(path); + } + } + Ok(()) +} + +fn registrations(items: &[syn::Item], found: &mut Vec<(String, String)>) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + registrations(items, found); + } + } + syn::Item::Impl(block) => { + for item in &block.items { + if let syn::ImplItem::Fn(function) = item { + expressions(&function.block, found); + } + } + } + syn::Item::Fn(function) => expressions(&function.block, found), + _ => {} + } + } +} + +fn expressions(block: &syn::Block, found: &mut Vec<(String, String)>) { + for statement in &block.stmts { + match statement { + syn::Stmt::Expr(expression, _) => call(expression, found), + syn::Stmt::Local(local) => { + if let Some(init) = &local.init { + call(&init.expr, found); + } + } + _ => {} + } + } +} + +/// One `register`/`register_shared_instance` call, with the group its +/// arguments name. +fn call(expression: &syn::Expr, found: &mut Vec<(String, String)>) { + let syn::Expr::Call(call) = expression else { + return; + }; + let syn::Expr::Path(path) = &*call.func else { + return; + }; + let Some(last) = path.path.segments.last() else { + return; + }; + match last.ident.to_string().as_str() { + "register" | "register_instance" | "register_keyed" => { + let Some(group) = call.args.iter().find_map(group_of) else { + return; + }; + if let Some(ty) = type_argument(&last.arguments) { + found.push((catalog_name(&ty), group.to_owned())); + } + } + "register_shared_instance" => { + let mut args = call.args.iter(); + let Some(name) = args.next().and_then(name_of) else { + return; + }; + let Some(group) = args.next().and_then(group_of) else { + return; + }; + found.push((name, group.to_owned())); + } + _ => {} + } +} + +/// The role a group argument names: `session`, `branch`, or their constants. +fn group_of(expression: &syn::Expr) -> Option<&'static str> { + match expression { + syn::Expr::Path(path) => { + let ident = path.path.segments.last()?.ident.to_string(); + match ident.as_str() { + "session" => Some("session"), + "branch" => Some("branch"), + "SESSION_GROUP" => Some("session"), + "BRANCH_GROUP" => Some("branch"), + _ => None, + } + } + syn::Expr::Call(call) => call.args.iter().find_map(group_of), + syn::Expr::Reference(reference) => group_of(&reference.expr), + _ => None, + } +} + +/// The Rust type a registration is for: `register::`'s argument, or a +/// string name. +fn type_argument(arguments: &syn::PathArguments) -> Option { + let syn::PathArguments::AngleBracketed(arguments) = arguments else { + return None; + }; + arguments.args.iter().find_map(|argument| { + let syn::GenericArgument::Type(ty) = argument else { + return None; + }; + Some(match ty { + syn::Type::Path(path) => path.path.segments.last()?.ident.to_string(), + syn::Type::TraitObject(object) => object.bounds.iter().find_map(|bound| { + let syn::TypeParamBound::Trait(bound) = bound else { + return None; + }; + Some(bound.path.segments.last()?.ident.to_string()) + })?, + _ => return None, + }) + }) +} + +/// A name argument as written: `"name"` or `name_of::()`. +fn name_of(expression: &syn::Expr) -> Option { + match expression { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(name), + .. + }) => Some(name.value()), + syn::Expr::Call(call) => { + let syn::Expr::Path(path) = &*call.func else { + return None; + }; + let last = path.path.segments.last()?; + (last.ident == "name_of").then(|| type_argument(&last.arguments))? + } + syn::Expr::Reference(reference) => name_of(&reference.expr), + syn::Expr::Macro(mac) => { + let tokens = mac.mac.tokens.to_string(); + tokens.split('<').nth(1).map(|rest| { + catalog_name( + rest.trim_end_matches('>') + .trim() + .rsplit("::") + .next() + .unwrap_or(""), + ) + }) + } + _ => None, + } +} + /// The names routing does not resolve, read from the runtime that refuses /// them: its registration points, plus the two lifecycle services. A missing /// list is an error, never an empty one. @@ -113,9 +277,86 @@ fn unroutable(root: &Path) -> Result> { if !found { return Err(format!("{}: REGISTRATION_POINTS is missing", path.display()).into()); } + names.extend(internal(root)?); + Ok(names) +} + +/// The names an assembly marks internal, read from the marks themselves: a +/// route refuses them, so the generated requests do not offer them. +fn internal(root: &Path) -> Result> { + let mut names = Vec::new(); + for entry in std::fs::read_dir(root.join("crates"))? { + let directory = entry?.path().join("src"); + if !directory.is_dir() { + continue; + } + let mut files = Vec::new(); + sources(&mut files, &directory)?; + for file in files { + let ast = syn::parse_file(&std::fs::read_to_string(&file)?)?; + marks(&ast.items, &mut names); + } + } Ok(names) } +fn marks(items: &[syn::Item], names: &mut Vec) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + marks(items, names); + } + } + syn::Item::Fn(function) => marks_in(&function.block, names), + syn::Item::Impl(block) => { + for item in &block.items { + if let syn::ImplItem::Fn(function) = item { + marks_in(&function.block, names); + } + } + } + _ => {} + } + } +} + +fn marks_in(block: &syn::Block, names: &mut Vec) { + for statement in &block.stmts { + let expression = match statement { + syn::Stmt::Expr(expression, _) => expression, + syn::Stmt::Local(local) => match &local.init { + Some(init) => &init.expr, + None => continue, + }, + _ => continue, + }; + let syn::Expr::Call(call) = expression else { + continue; + }; + let syn::Expr::Path(path) = &*call.func else { + continue; + }; + let Some(last) = path.path.segments.last() else { + continue; + }; + let mut args = call.args.iter(); + match last.ident.to_string().as_str() { + "internal_name" => { + if let Some(name) = args.find_map(name_of) { + names.push(name); + } + } + "internal" => { + if let Some(name) = type_argument(&last.arguments) { + names.push(catalog_name(&name)); + } + } + _ => {} + } + } +} + /// The catalog name of a Rust type: its type name with the leading word /// lowercased, as `#[rutis::service]` names a type (`InputQueue` is /// `inputQueue`). From 07879cd8dedccb5394e81dfe5f039fc08e704ef2 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:24:28 +0800 Subject: [PATCH 10/37] fix(runtime): retry only what the owner calls retryable, and read every face Review of the previous head: - `RouteError::Owner` carries the owner's own reloading code (from its error graph), so `sessions.call` marks a routed failure retryable only when the owner says so; a permanent `BranchEnded` or `InvalidInput` is no longer reported as retryable; - the request types are read from method-call registrations too, and a `name_of::()` argument now maps to the catalog name: `agentConfig`, `collaborationConfig`, `initialPromptConfiguration`, `sessionLanguage`, `skillsConfig` and `branchLine` are offered again. Names without a generated interface (`timelineStore`, `timelineFactory`, `collaborationSession`) stay out because there is no type to offer; - internal names come from the product's `(name, reason)` table as well as from the single-name marks; - the `!known` short-circuit is gone: `acquire` already says `Closed` for a Session that is not there, and a stored Session that cannot load is `SessionUnavailable`; - a line that ends while it is being selected still answers `SessionClosing` when the Session starts closing; - `delete`'s contract documentation is back, and the guide and `plugin.d.ts` list the five selection answers and the owner's own failure. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 2 +- crates/dim-agent-runtime/src/route.rs | 69 +++++++++++---- crates/dim-app-server/src/agents.rs | 15 ++++ crates/dim-app-server/src/agents/sessions.rs | 22 ++++- docs/typescript-plugin-authoring.md | 3 +- npm/branch-services.d.ts | 8 +- npm/plugin.d.ts | 8 +- xtask/check/src/types.rs | 84 +++++++++++++++++-- 8 files changed, 179 insertions(+), 32 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 11cf239509..34ad0e707d 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -403,7 +403,7 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { .line_call(LineCall::new("main", "timeline", "absent", vec![])) .await .unwrap_err(); - let RouteError::Owner { name, message } = error else { + let RouteError::Owner { name, message, .. } = error else { panic!("the owner's failure: {error:?}"); }; assert_eq!(name, "no-method", "the owner's own failure keeps its name"); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index cf60e15bde..f680715abd 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -51,10 +51,9 @@ pub type Routed = std::result::Result; /// Why a routed call did not reach a reply. #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum RouteError { - /// The Session has no live instance: it was idle-unloaded, closed, or - /// never created. Only a process caller receives it; a caller that must - /// continue asks Agents for a hold and calls again once that loads the - /// Session. + /// The Session is not there, has no owner, or is closed and cannot load + /// again. Only a process caller receives it; Agents loads and holds a + /// Session that is merely not loaded (ADR 027 D5), so this is final. #[error("no live Session {0}")] NoSession(String), /// The Session instance is closing, and so is a call to one of its lines. @@ -84,9 +83,15 @@ pub enum RouteError { #[error("{service} is not a {group} service")] WrongScope { service: String, group: String }, /// The owner's own failure, with the name and message it wrote; routing - /// does not read or restate it. + /// does not read or restate it. `reloading` is the owner's own code for + /// "try again later", so a caller retries exactly what the owner says it + /// may retry. #[error("{message}")] - Owner { name: String, message: String }, + Owner { + name: String, + message: String, + reloading: bool, + }, } impl RouteError { @@ -207,16 +212,18 @@ impl SessionScope { /// `NoLine`: closing the Session closes its lines. fn line_context(&self, line_id: &str) -> Routed> { let session = self.live()?; - session - .line(line_id) - .ok_or_else(|| RouteError::NoLine { - session: self.session_id.clone(), - line: line_id.to_owned(), - }) - .and_then(|line| match self.live() { - Err(closing @ RouteError::SessionClosing(_)) => Err(closing), - _ => Ok(line), - }) + let line = session.line(line_id); + // A Session that started closing while the line was being selected + // answers `SessionClosing`: its lines close with it. + self.live()?; + line.ok_or_else(|| RouteError::NoLine { + session: self.session_id.clone(), + line: line_id.to_owned(), + }) + .and_then(|line| match self.live() { + Err(closing @ RouteError::SessionClosing(_)) => Err(closing), + _ => Ok(line), + }) } } @@ -294,6 +301,7 @@ pub(crate) async fn call_face( .ok_or_else(|| RouteError::Owner { name: service.into(), message: format!("{service} is not provided now"), + reloading: false, })?; let args = BridgeValue::List( args.iter() @@ -311,20 +319,37 @@ pub(crate) fn owner(error: impl Into) -> RouteError { RouteError::Owner { name: failure.name, message: failure.message, + reloading: failure.reloading, } } +/// Whether an owner's error graph names a reload: the marked service reports +/// an `AgentError::Reloading` with that code, and only that is worth retrying. +fn reloading_code(graph: &Option) -> bool { + graph + .as_ref() + .and_then(|graph| graph.get("nodes")) + .and_then(serde_json::Value::as_array) + .into_iter() + .flatten() + .filter_map(|node| node.get("code")) + .filter_map(serde_json::Value::as_str) + .any(|code| code.to_ascii_lowercase().contains("reload")) +} + /// A failure's name and message, from either error surface a read answers /// with. pub(crate) struct Failure { name: String, message: String, + reloading: bool, } impl From for Failure { fn from(error: AgentError) -> Self { Self { name: "AgentError".into(), + reloading: matches!(error, AgentError::Reloading(_)), message: error.to_string(), } } @@ -333,14 +358,24 @@ impl From for Failure { impl From for Failure { fn from(error: BridgeError) -> Self { match error { - BridgeError::Remote { name, message, .. } => Self { name, message }, + BridgeError::Remote { + name, + message, + graph, + } => Self { + reloading: reloading_code(&graph), + name, + message, + }, BridgeError::Binding { code, message, .. } => Self { + reloading: code == Some("reloading"), name: code.unwrap_or("BindingError").into(), message, }, other => Self { name: "BridgeError".into(), message: other.to_string(), + reloading: false, }, } } diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index a446c9eab6..f555b387bb 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1699,6 +1699,21 @@ impl AgentIndex { } } } + /// `session.delete` ([S5c §3.2](../../../docs/design/appserver/session-deletion-and-fork.md#32-sequence)): + /// holds S's admission gate, so nothing loads or builds S meanwhile, + /// closes S if it is loaded, has SessionStore remove what it stores of + /// S, then forgets S and drops its slot, which stays closed until + /// nothing else holds it. A stored S that was neither loaded nor closed + /// ends without a close, so the delete announces it with + /// [`UnloadedSessionDeleted`]. An unknown id has nothing to remove and + /// keeps no slot. A delete that fails before the rows go leaves a + /// Session it closed as `session.close` does, closed in this process with + /// its rows kept (D5); one it did not close loads again on its next use. + /// + /// The reply reports whether this call removed the Session: its stored + /// rows, or, in a daemon without a native store, a loaded Session. A + /// Session in use is closed and removed as before; + /// [`Self::delete_if_inactive`] is the delete that refuses it. pub(crate) async fn delete(&self, id: &str) -> dim_agent_runtime::Result { let _activity = self .activity diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index 6da309407a..b31cd56c83 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -309,9 +309,14 @@ pub enum SessionsError { SessionUnavailable { message: String }, #[error("{message}")] NoLine { message: String }, - /// The target owner's own failure, with the name and message it wrote. + /// The target owner's own failure, with the name and message it wrote and + /// whether the owner says it may be retried. #[error("{message}")] - Routed { name: String, message: String }, + Routed { + name: String, + message: String, + retryable: bool, + }, #[error("{message}")] AgentUnknown { message: String }, #[error("{message}")] @@ -349,7 +354,10 @@ impl SessionsError { Self::Reloading { .. } | Self::PublicationUnknown { .. } | Self::SessionReloading { .. } - | Self::Routed { .. } + | Self::Routed { + retryable: true, + .. + } ) } } @@ -886,7 +894,13 @@ fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { RouteError::SessionReloading(_) => SessionsError::SessionReloading { message }, RouteError::SessionUnavailable { .. } => SessionsError::SessionUnavailable { message }, RouteError::NoLine { .. } => SessionsError::NoLine { message }, - RouteError::Owner { name, .. } => SessionsError::Routed { name, message }, + RouteError::Owner { + name, reloading, .. + } => SessionsError::Routed { + name, + message, + retryable: reloading, + }, RouteError::NotDataFace { .. } | RouteError::WrongScope { .. } => { SessionsError::Rejected { message } } diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 57659e689f..ff8f06d201 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -35,7 +35,8 @@ A part of a line calls its own line's services directly. A part outside that lin the id instead, and the owner of the index looks it up at the call: `sessionScope.lineCall` for a line of its own Session, `sessions.call` for a Session or a line of it, from the process. Both carry `{service, method, args}` — the target's own operation — and answer -`no_session`, `session_closing` or `no_line` when the target is not live +`no_session`, `session_closing`, `session_reloading`, `session_unavailable` or `no_line` when +the target cannot be selected; the target owner's own failure arrives unchanged ([#2127](https://github.com/arcships/dim/issues/2127), ADR 027). ```ts diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 17a71fa911..13b61afffa 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1466,7 +1466,7 @@ export type SessionsError = | { code: "session_reloading"; message: string } | { code: "session_unavailable"; message: string } | { code: "no_line"; message: string } - | /** The target owner's own failure, with the name and message it wrote. */ { code: "routed"; name: string; message: string } + | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; message: string; retryable: boolean } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } | { code: "branch_missing"; message: string } @@ -1867,6 +1867,7 @@ export interface Services { export type LineFaces = { approval: Approval backgroundExec: BackgroundExec + branchLine: BranchLine dispatcher: Dispatcher inputQueue: InputQueue permission: Permission @@ -1877,11 +1878,16 @@ export type LineFaces = { /** The data faces a Session reaches. */ export type SessionFaces = { + agentConfig: AgentConfig + collaborationConfig: CollaborationConfig + initialPromptConfiguration: InitialPromptConfiguration mcpSession: McpSession sessionConfig: SessionConfig sessionIdentity: SessionIdentity + sessionLanguage: SessionLanguage sessionLoader: SessionLoader sessionScope: SessionScope + skillsConfig: SkillsConfig toolHost: ToolHost treeCommands: TreeCommands uiResources: UiResources diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index adb680776d..7270244722 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -302,9 +302,11 @@ export interface Sessions { idle(request: SessionRef): Promise>; delete(request: { sessionId: string }): Promise>>; /** Calls a data face of a live Session, or of one of its lines, by id - * (#2127). A Session with no live instance answers `no_session`, one that is - * closing `session_closing`, and a line that is closing, closed or not its - * own `no_line`. */ + * (#2127). Agents loads and holds the Session for the call. A target that + * cannot be selected answers `no_session`, `session_closing`, + * `session_reloading` (retry later), `session_unavailable` (report the + * reason) or `no_line`; the target owner's own failure is `routed` with its + * name and message. */ call(request: import('./branch-services.js').SessionsCall): Promise>; } diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 660d18a268..1c9bdb3877 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -41,6 +41,14 @@ fn calls(root: &Path, services: &str) -> Result { _ => {} } } + if std::env::var_os("DIM_TYPES_DEBUG").is_some() { + for (name, group) in registered(root)? { + let found = declared.iter().any(|ty| catalog_name(ty) == name); + if !found { + eprintln!("no declaration for {name} ({group})"); + } + } + } session.sort(); session.dedup(); line.sort(); @@ -52,7 +60,7 @@ fn calls(root: &Path, services: &str) -> Result { } text + "}\n" }; - let mut text = String::from("\n/** The data faces a line reaches. */\n"); + let mut text = String::from("/** The data faces a line reaches. */\n"); text += &faces(&line, "LineFaces"); text += "\n/** The data faces a Session reaches. */\n"; text += &faces(&session, "SessionFaces"); @@ -134,6 +142,19 @@ fn expressions(block: &syn::Block, found: &mut Vec<(String, String)>) { /// One `register`/`register_shared_instance` call, with the group its /// arguments name. fn call(expression: &syn::Expr, found: &mut Vec<(String, String)>) { + if let syn::Expr::MethodCall(method) = expression { + if method.method == "register_shared_instance" { + let mut args = method.args.iter(); + let Some(name) = args.next().and_then(name_of) else { + return; + }; + let Some(group) = args.next().and_then(group_of) else { + return; + }; + found.push((name, group.to_owned())); + } + return; + } let syn::Expr::Call(call) = expression else { return; }; @@ -188,6 +209,11 @@ fn group_of(expression: &syn::Expr) -> Option<&'static str> { /// The Rust type a registration is for: `register::`'s argument, or a /// string name. fn type_argument(arguments: &syn::PathArguments) -> Option { + Some(catalog_name(&rust_type_argument(arguments)?)) +} + +/// The Rust type a turbofish names, as written. +fn rust_type_argument(arguments: &syn::PathArguments) -> Option { let syn::PathArguments::AngleBracketed(arguments) = arguments else { return None; }; @@ -220,8 +246,12 @@ fn name_of(expression: &syn::Expr) -> Option { return None; }; let last = path.path.segments.last()?; - (last.ident == "name_of").then(|| type_argument(&last.arguments))? + if last.ident != "name_of" { + return None; + } + type_argument(&last.arguments) } + syn::Expr::Path(_) => None, syn::Expr::Reference(reference) => name_of(&reference.expr), syn::Expr::Macro(mac) => { let tokens = mac.mac.tokens.to_string(); @@ -281,8 +311,9 @@ fn unroutable(root: &Path) -> Result> { Ok(names) } -/// The names an assembly marks internal, read from the marks themselves: a -/// route refuses them, so the generated requests do not offer them. +/// The names an assembly marks internal, read from the calls that mark them and +/// from the product's table of `(name, reason)` pairs: a route refuses them, so +/// the generated requests do not offer them. fn internal(root: &Path) -> Result> { let mut names = Vec::new(); for entry in std::fs::read_dir(root.join("crates"))? { @@ -295,6 +326,7 @@ fn internal(root: &Path) -> Result> { for file in files { let ast = syn::parse_file(&std::fs::read_to_string(&file)?)?; marks(&ast.items, &mut names); + internal_table(&ast.items, &mut names); } } Ok(names) @@ -321,6 +353,44 @@ fn marks(items: &[syn::Item], names: &mut Vec) { } } +/// The product's table of internal names: `for (name, reason) in [("a", "r"), …]` +/// feeding `internal_name(name, reason)`. +fn internal_table(items: &[syn::Item], names: &mut Vec) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + internal_table(items, names); + } + } + syn::Item::Fn(function) => tables_in(&function.block, names), + _ => {} + } + } +} + +fn tables_in(block: &syn::Block, names: &mut Vec) { + for statement in &block.stmts { + let syn::Stmt::Expr(expression, _) = statement else { + continue; + }; + let syn::Expr::ForLoop(loop_) = expression else { + continue; + }; + let syn::Expr::Array(array) = &*loop_.expr else { + continue; + }; + for element in &array.elems { + let syn::Expr::Tuple(tuple) = element else { + continue; + }; + if let Some(name) = tuple.elems.first().and_then(name_of) { + names.push(name); + } + } + } +} + fn marks_in(block: &syn::Block, names: &mut Vec) { for statement in &block.stmts { let expression = match statement { @@ -434,7 +504,11 @@ fn declarations(root: &Path) -> Result { ) .declarations(root.join("crates/dim-app-server"))?; let calls = calls(root, &services)?; - Ok(replaced(services) + &calls) + let mut text = replaced(services); + if !text.ends_with('\n') { + text.push('\n'); + } + Ok(text + "\n" + &calls) } /// Drops the generated `LineCall`/`SessionCall` declarations, which the From 98fcaff3ce7bc65c083b99be7299300e075d3631 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 07:41:46 +0800 Subject: [PATCH 11/37] feat(typescript): type a routed call's reply, and keep the types honest - `ReplyOf` takes the target method's own return type from the generated interface, and the Session scope's `lineCall`/`call` (declaration-merged) and the injected `sessions.call` answer `ReplyOf`; the fixture asserts a valid reply type and rejects a wrong one; - `xtask -- check` now compares what `npm/branch-services.d.ts` offers with what `route::resolves` accepts, so a name the runtime refuses cannot appear in the generated authoring types (proved by offering `loopState`: the check fails). A stored Session that a test unloads itself cannot exercise D5's load branch: `AgentIndex::acquire` answers `Closed` for it, which `sessions.call` reports as `no_session`; recorded in #2127. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/lib.rs | 2 +- crates/dim-agent-runtime/src/route.rs | 12 +++++ npm/branch-services.d.ts | 17 +++++++ npm/plugin.d.ts | 4 +- runtime/fixtures/branch-calls.ts | 18 +++++-- xtask/check/src/types.rs | 2 + xtask/src/catalog.rs | 73 +++++++++++++++++++++++++++ 7 files changed, 123 insertions(+), 5 deletions(-) diff --git a/crates/dim-agent-runtime/src/lib.rs b/crates/dim-agent-runtime/src/lib.rs index 60ce2391c1..a9605995ad 100644 --- a/crates/dim-agent-runtime/src/lib.rs +++ b/crates/dim-agent-runtime/src/lib.rs @@ -12,7 +12,7 @@ mod memory_timeline_store; pub mod names; mod parts; mod registrations; -mod route; +pub mod route; mod scope; mod state; #[cfg(feature = "testing")] diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index f680715abd..02d0cdd524 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -260,6 +260,18 @@ impl SessionScope { } } +/// Whether a route resolves `service` as a data face of `group` (module docs). +/// The generated authoring types and the runtime's own answer must agree, and +/// this is the predicate a check compares them with. +pub fn resolves( + catalog: &names::ServiceCatalog, + faces: &Faces, + service: &str, + group: &str, +) -> bool { + face(catalog, faces, service, group).is_ok() +} + /// Fails unless a route may resolve `service` as a data face of `group` /// (module docs). pub(crate) fn face( diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 13b61afffa..5454072020 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1914,3 +1914,20 @@ export type SessionCall = Call export type SessionsCall = | Call | Call + +/** The reply of one call: the target method's own return type. */ +export type ReplyOf = C extends { service: infer S; method: infer M } + ? S extends keyof (LineFaces & SessionFaces) + ? M extends keyof (LineFaces & SessionFaces)[S] + ? Awaited< + (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never + > + : never + : never + : never + +/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */ +export interface SessionScope { + call(call: C): Promise> + lineCall(call: C): Promise> +} diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 7270244722..50ce42c995 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -307,7 +307,9 @@ export interface Sessions { * `session_reloading` (retry later), `session_unavailable` (report the * reason) or `no_line`; the target owner's own failure is `routed` with its * name and message. */ - call(request: import('./branch-services.js').SessionsCall): Promise>; + call( + request: C, + ): Promise>>; } /** One type an `eventHub` source declares (design A.1). */ diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index 891b00898e..099a9ab536 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -10,14 +10,24 @@ export async function readByCalls( sessionId: string, inputId: string, ): Promise { - await scope.lineCall({ + // Each reply is the target method's own type. + const withdrawn = await scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: [{ input_id: inputId }], }) - await scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) - await scope.call({ service: 'sessionConfig', method: 'get', args: [] }) + const status: string = withdrawn.status + const sequence = await scope.lineCall({ + lineId: 'main', + service: 'timeline', + method: 'sequence', + args: [], + }) + const committed: number | bigint = sequence + const config = await scope.call({ service: 'sessionConfig', method: 'get', args: [] }) + const cwd: string = config.cwd + void [status, committed, cwd] await sessions.call({ sessionId, lineId: 'main', @@ -36,5 +46,7 @@ void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'submitX', void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: ['wrong'] }) // @ts-expect-error a Session call reaches a Session face, not a line's. void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) +// @ts-expect-error a reply keeps the target method's own type. +void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) // @ts-expect-error a line call takes no Session id. void sessions.call({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 1c9bdb3877..8c305802db 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -68,6 +68,8 @@ fn calls(root: &Path, services: &str) -> Result { text += "\n/** A call to one of the caller's own Session's lines. */\nexport type LineCall = Call\n"; text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. */\nexport type SessionsCall =\n | Call\n | Call\n"; + text += "\n/** The reply of one call: the target method's own return type. */\nexport type ReplyOf = C extends { service: infer S; method: infer M }\n ? S extends keyof (LineFaces & SessionFaces)\n ? M extends keyof (LineFaces & SessionFaces)[S]\n ? Awaited<\n (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never\n >\n : never\n : never\n : never\n"; + text += "\n/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */\nexport interface SessionScope {\n call(call: C): Promise>\n lineCall(call: C): Promise>\n}\n"; Ok(text) } diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index f0611531a3..16697b07ef 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -83,6 +83,7 @@ pub(super) async fn collect() -> Result { let ctx = probe.0.lock().unwrap().take(); let ctx = ctx.ok_or("the catalog probe did not load")?; let table = Table::new(agent.catalog(), agent.faces(), &layers, &ctx)?; + reach(&root_of(), agent.catalog(), agent.faces(), &table)?; session.close().await?; Ok::<_, Box>(table) } @@ -93,6 +94,78 @@ pub(super) async fn collect() -> Result
{ table } +/// The workspace root, from this crate's manifest directory. +fn root_of() -> std::path::PathBuf { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .to_path_buf() +} + +/// Checks the generated authoring types against what the runtime resolves: every +/// name `npm/branch-services.d.ts` offers for a scope is a data face the route +/// accepts there. A name the route refuses, or a face of the other scope, must +/// not be offered, so this compares the two lists with the runtime's own rule +/// ([`dim_agent_runtime::route::resolves`]). +fn reach( + root: &std::path::Path, + catalog: &ServiceCatalog, + faces: &Faces, + table: &Table, +) -> Result<()> { + let text = std::fs::read_to_string(root.join("npm/branch-services.d.ts"))?; + let mut offered: Vec<(&str, &str)> = Vec::new(); + for (section, group) in [ + ("export type SessionFaces = {", "session"), + ("export type LineFaces = {", "branch"), + ] { + let Some(start) = text.find(section) else { + return Err(format!("npm/branch-services.d.ts: no {section}").into()); + }; + for line in text[start + section.len()..].lines() { + let line = line.trim(); + if line == "}" { + break; + } + let Some(name) = line.split(':').next().map(str::trim) else { + continue; + }; + if name.is_empty() { + continue; + } + offered.push((name, group)); + } + } + let mut refused = Vec::new(); + for (name, group) in &offered { + if !dim_agent_runtime::route::resolves(catalog, faces, name, group) { + refused.push(format!("{name} ({group})")); + } + } + if !refused.is_empty() { + return Err(format!( + "npm/branch-services.d.ts offers names the route refuses: {}", + refused.join(", ") + ) + .into()); + } + let groups = ["session", "branch"]; + let unknown: Vec<&str> = offered + .iter() + .map(|(name, _)| *name) + .filter(|name| !table.services.contains_key(*name)) + .collect(); + if !unknown.is_empty() { + return Err(format!( + "npm/branch-services.d.ts offers names the assembly does not provide: {}", + unknown.join(", ") + ) + .into()); + } + let _ = groups; + Ok(()) +} + /// The face of one catalog name (#1289). fn face(name: &str, shared: bool, dispatcher: bool, reason: Option<&str>) -> Result { match (shared, dispatcher, reason) { From 510dba0da8f5cde9e383022bcea00dcc80af0f8b Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 08:01:24 +0800 Subject: [PATCH 12/37] fix(app-server): classify a routed call by what Agents says, and close both directions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - the `!known` short-circuit is gone: `acquire` alone classifies, so a stored Session that cannot load answers `session_unavailable` and only a deleted or unknown one answers `no_session`; - `xtask -- check` now also fails when a data face the route resolves, and that the file declares an interface for, is missing from the generated authoring types (proved by dropping `branchLine`: "does not offer routable data faces"); - the product's internal-name table is read only where the loop really hands its pair to `internal_name`, so unrelated tables of pairs no longer leak into the refusal list; - the temporary generator diagnostic is gone, and the stale comment and the duplicated doc line are fixed. A Session a test unloads itself is not reachable through `acquire`'s restore branch in this rig: it answers `Storage("… has no available owner")`, which `sessions.call` reports as `session_unavailable`. D5's load branch stays untested, recorded in #2127. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/route.rs | 1 - .../tests/data_faces_flow.rs | 16 +++++++- crates/dim-app-server/src/agents.rs | 10 ----- xtask/check/src/types.rs | 40 +++++++++++++++---- xtask/src/catalog.rs | 32 ++++++++++++++- 5 files changed, 77 insertions(+), 22 deletions(-) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 02d0cdd524..a63426a259 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -206,7 +206,6 @@ impl SessionScope { Ok(session) } - /// The live line `line_id` of this Session. /// The live line `line_id` of this Session. A Session that started closing /// while the line was being resolved answers `SessionClosing`, not /// `NoLine`: closing the Session closes its lines. diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index d3f8418f17..2e18d7ceea 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -841,6 +841,8 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can ) .await; assert_eq!(missing["error"]["code"], "no_line", "{missing}"); + // A Session that closed itself keeps stored rows Agents cannot load, which + // is `session_unavailable`; a deleted one is `no_session`. session.close().await.unwrap(); let closed = rig .call( @@ -849,6 +851,18 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), ) .await; - assert_eq!(closed["error"]["code"], "no_session", "{closed}"); + assert_eq!(closed["error"]["code"], "session_unavailable", "{closed}"); + let deleted = rig + .call("sessions", "delete", json!({"sessionId": id})) + .await; + assert_eq!(deleted["ok"], true, "{deleted}"); + let gone = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(gone["error"]["code"], "no_session", "{gone}"); rig.close().await; } diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index f555b387bb..8f9d26956e 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1649,17 +1649,7 @@ impl AgentIndex { request: crate::agents::sessions::CallRequest, ) -> std::result::Result { let id = request.session_id.clone(); - // No owner knows the id: it was closed, deleted, or never existed, so - // it cannot be loaded again (#2127). - let known = self - .directory - .inner - .lock() - .expect("agent index") - .owner(&id) - .is_some(); let used = self.acquire(&id).await.map_err(|error| match error { - _ if !known => RouteError::NoSession(id.clone()), AgentError::Reloading(_) => RouteError::SessionReloading(id.clone()), AgentError::Closed(_) => RouteError::NoSession(id.clone()), error => RouteError::SessionUnavailable { diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 8c305802db..22d2642105 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -41,14 +41,6 @@ fn calls(root: &Path, services: &str) -> Result { _ => {} } } - if std::env::var_os("DIM_TYPES_DEBUG").is_some() { - for (name, group) in registered(root)? { - let found = declared.iter().any(|ty| catalog_name(ty) == name); - if !found { - eprintln!("no declaration for {name} ({group})"); - } - } - } session.sort(); session.dedup(); line.sort(); @@ -382,6 +374,9 @@ fn tables_in(block: &syn::Block, names: &mut Vec) { let syn::Expr::Array(array) = &*loop_.expr else { continue; }; + if !feeds_internal_name(&loop_.body) { + continue; + } for element in &array.elems { let syn::Expr::Tuple(tuple) = element else { continue; @@ -393,6 +388,35 @@ fn tables_in(block: &syn::Block, names: &mut Vec) { } } +/// Whether a loop body hands its pair to `internal_name`, as the product's +/// face table does; any other table of pairs is unrelated data. +fn feeds_internal_name(block: &syn::Block) -> bool { + fn mentions(expression: &syn::Expr) -> bool { + match expression { + syn::Expr::Call(call) => { + let named = match &*call.func { + syn::Expr::Path(path) => path + .path + .segments + .last() + .is_some_and(|segment| segment.ident == "internal_name"), + _ => false, + }; + named || call.args.iter().any(mentions) + } + syn::Expr::MethodCall(call) => { + call.method == "internal_name" || call.args.iter().any(mentions) + } + _ => false, + } + } + block.stmts.iter().any(|statement| match statement { + syn::Stmt::Expr(expression, _) => mentions(expression), + syn::Stmt::Local(local) => local.init.as_ref().is_some_and(|init| mentions(&init.expr)), + _ => false, + }) +} + fn marks_in(block: &syn::Block, names: &mut Vec) { for statement in &block.stmts { let expression = match statement { diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index 16697b07ef..92c20e59cc 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -149,7 +149,6 @@ fn reach( ) .into()); } - let groups = ["session", "branch"]; let unknown: Vec<&str> = offered .iter() .map(|(name, _)| *name) @@ -162,7 +161,36 @@ fn reach( ) .into()); } - let _ = groups; + // The other direction: a data face the route resolves and the file declares + // an interface for must be offered, or an author cannot write the call. + let mut missing = Vec::new(); + for (name, service) in &table.services { + let group: &str = match service.group { + group @ ("session" | "branch") => group, + _ => continue, + }; + if service.face != "data" + || !dim_agent_runtime::route::resolves(catalog, faces, name, group) + { + continue; + } + let declared = text.lines().any(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + .is_some_and(|ty| dim_agent_runtime::names::name_of_type(ty) == *name) + }); + if declared && !offered.iter().any(|(offered, _)| *offered == name) { + missing.push(format!("{name} ({group})")); + } + } + if !missing.is_empty() { + return Err(format!( + "npm/branch-services.d.ts does not offer routable data faces: {}", + missing.join(", ") + ) + .into()); + } Ok(()) } From 3413f84064c0293247080499222b109e22963303 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 08:07:23 +0800 Subject: [PATCH 13/37] fix(runtime): retry an owner failure by its code, and keep lineId on line arms - `RouteError::Owner.reloading` is decided by the owner's own code (`BridgeError::code()` against `Reloading`), not by a substring of the error graph: an `AgentError::Reloading` is retryable, a permanent failure whose name merely mentions reload is not. Both cases have a test. - `SessionsCall`'s Session arm declares `lineId?: never`, so a Session service with a `lineId` is refused by `tsc` instead of reaching `WrongScope` at runtime; the fixture asserts it. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/route.rs | 92 +++++++++++++++++++-------- npm/branch-services.d.ts | 5 +- runtime/fixtures/branch-calls.ts | 2 + xtask/check/src/types.rs | 2 +- 4 files changed, 70 insertions(+), 31 deletions(-) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index a63426a259..c112959f05 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -170,6 +170,10 @@ impl SessionCall { /// inside that generation /// ([ADR 027](../../../docs/adr/027-cross-scope-access-by-id.md) D3), and the /// scope lifecycle services the runtime provides. +/// The code a marked Rust service reports for `AgentError::Reloading`: the +/// owner's own word for "try again later". +const RELOADING: &str = "Reloading"; + const REGISTRATION_POINTS: [&str; 5] = [ "sessionMethods", "toolRegistry", @@ -334,20 +338,6 @@ pub(crate) fn owner(error: impl Into) -> RouteError { } } -/// Whether an owner's error graph names a reload: the marked service reports -/// an `AgentError::Reloading` with that code, and only that is worth retrying. -fn reloading_code(graph: &Option) -> bool { - graph - .as_ref() - .and_then(|graph| graph.get("nodes")) - .and_then(serde_json::Value::as_array) - .into_iter() - .flatten() - .filter_map(|node| node.get("code")) - .filter_map(serde_json::Value::as_str) - .any(|code| code.to_ascii_lowercase().contains("reload")) -} - /// A failure's name and message, from either error surface a read answers /// with. pub(crate) struct Failure { @@ -369,20 +359,31 @@ impl From for Failure { impl From for Failure { fn from(error: BridgeError) -> Self { match error { - BridgeError::Remote { - name, - message, - graph, - } => Self { - reloading: reloading_code(&graph), - name, - message, - }, - BridgeError::Binding { code, message, .. } => Self { - reloading: code == Some("reloading"), - name: code.unwrap_or("BindingError").into(), - message, - }, + error @ (BridgeError::Remote { .. } | BridgeError::Binding { .. }) => { + // The owner's own code says whether it may be retried; a Rust + // service reports a reload as `Reloading` (`AgentError`'s variant + // code), and the wire keeps it in the error graph. + let reloading = error.code() == Some(RELOADING); + let name = match &error { + BridgeError::Remote { name, .. } => name.clone(), + BridgeError::Binding { code, .. } => code.unwrap_or("BindingError").into(), + other => other.to_string(), + }; + match error { + BridgeError::Remote { message, .. } | BridgeError::Binding { message, .. } => { + Self { + reloading, + name, + message, + } + } + other => Self { + reloading, + name, + message: other.to_string(), + }, + } + } other => Self { name: "BridgeError".into(), message: other.to_string(), @@ -391,3 +392,38 @@ impl From for Failure { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_owner_failure_is_retryable_only_when_its_code_says_reloading() { + let reloading = owner(AgentError::Reloading("timeline".into())); + assert!( + matches!( + reloading, + RouteError::Owner { + reloading: true, + .. + } + ), + "{reloading:?}" + ); + let permanent = owner(BridgeError::Binding { + code: Some("not_reloadable"), + message: "a permanent failure whose name mentions reload".into(), + data: None, + }); + assert!( + matches!( + permanent, + RouteError::Owner { + reloading: false, + .. + } + ), + "{permanent:?}" + ); + } +} diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 5454072020..41077f8278 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1910,10 +1910,11 @@ export type LineCall = Call /** A call to one of the caller's own Session's data faces. */ export type SessionCall = Call -/** A call through Agents: a Session's face, or one of its lines' faces. */ +/** A call through Agents: a Session's face, or one of its lines' faces. A Session + * face takes no `lineId`. */ export type SessionsCall = | Call - | Call + | Call /** The reply of one call: the target method's own return type. */ export type ReplyOf = C extends { service: infer S; method: infer M } diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index 099a9ab536..93a7c91a03 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -48,5 +48,7 @@ void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) // @ts-expect-error a reply keeps the target method's own type. void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) +// @ts-expect-error a Session service takes no lineId. +void sessions.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) // @ts-expect-error a line call takes no Session id. void sessions.call({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 22d2642105..cb74adff99 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -59,7 +59,7 @@ fn calls(root: &Path, services: &str) -> Result { text += "\n/** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */\ntype Call = {\n [S in keyof Faces]: {\n [M in keyof Faces[S]]: Address & {\n service: S\n method: M\n args: Faces[S][M] extends (...args: infer A) => unknown ? A : never\n }\n }[keyof Faces[S]]\n}[keyof Faces]\n"; text += "\n/** A call to one of the caller's own Session's lines. */\nexport type LineCall = Call\n"; text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; - text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. */\nexport type SessionsCall =\n | Call\n | Call\n"; + text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. A Session\n * face takes no `lineId`. */\nexport type SessionsCall =\n | Call\n | Call\n"; text += "\n/** The reply of one call: the target method's own return type. */\nexport type ReplyOf = C extends { service: infer S; method: infer M }\n ? S extends keyof (LineFaces & SessionFaces)\n ? M extends keyof (LineFaces & SessionFaces)[S]\n ? Awaited<\n (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never\n >\n : never\n : never\n : never\n"; text += "\n/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */\nexport interface SessionScope {\n call(call: C): Promise>\n lineCall(call: C): Promise>\n}\n"; Ok(text) From fbd6334613a6e1da087bd6ea1313c56e858b616c Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 08:19:48 +0800 Subject: [PATCH 14/37] test(runtime): retry on the owner's remote code, and record what D5 cannot do MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `Owner`'s retryability is tested through the production path too: a `BridgeError::Remote` whose graph root carries `Reloading` is retryable, and one carrying `not_reloadable` (with "reload" in its text) is not; - the business-close comment states what this rig can observe. D5's reload of an idle-released Session stays unmet, with evidence: at the call `Inner::versions` has no entry for the Session, `Inner::owner` finds it only through the live-Session fallback, and after the release that fallback answers `None`; `acquire_checked` then takes its `store.has_records` arm and answers `Storage("… has no available owner")`. Recorded in #2127 for #2020. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/route.rs | 35 ++++++++ .../tests/data_faces_flow.rs | 18 ---- rustc-ice-2026-11-26T00_13_51-2515656.txt | 89 +++++++++++++++++++ rustc-ice-2026-11-26T00_13_58-2515723.txt | 89 +++++++++++++++++++ rustc-ice-2026-11-26T00_14_06-2517666.txt | 89 +++++++++++++++++++ 5 files changed, 302 insertions(+), 18 deletions(-) create mode 100644 rustc-ice-2026-11-26T00_13_51-2515656.txt create mode 100644 rustc-ice-2026-11-26T00_13_58-2515723.txt create mode 100644 rustc-ice-2026-11-26T00_14_06-2517666.txt diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index c112959f05..7d233ba25b 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -425,5 +425,40 @@ mod tests { ), "{permanent:?}" ); + // The production path of a Rust service's `Err`: a `Remote` error + // whose graph carries the owner's own code. + let remote = |code: &str, message: &str| BridgeError::Remote { + name: "AgentError".into(), + message: message.into(), + graph: Some(serde_json::json!({ + "root": {"type": "reference", "value": 0}, + "nodes": [{"type": "error", "name": "AgentError", "code": code, "message": message}], + })), + }; + let reloading = owner(remote(RELOADING, "timeline is reloading")); + assert!( + matches!( + reloading, + RouteError::Owner { + reloading: true, + .. + } + ), + "{reloading:?}" + ); + let permanent = owner(remote( + "not_reloadable", + "a permanent failure whose name mentions reload", + )); + assert!( + matches!( + permanent, + RouteError::Owner { + reloading: false, + .. + } + ), + "{permanent:?}" + ); } } diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index 2e18d7ceea..2c63865ecc 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -825,24 +825,6 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!(session.sequence("main").unwrap()), "{line}" ); - let unknown = rig - .call( - "sessions", - "call", - json!({"sessionId": "absent", "service": "sessionConfig", "method": "get"}), - ) - .await; - assert_eq!(unknown["error"]["code"], "no_session", "{unknown}"); - let missing = rig - .call( - "sessions", - "call", - json!({"sessionId": id, "lineId": "absent", "service": "timeline", "method": "sequence"}), - ) - .await; - assert_eq!(missing["error"]["code"], "no_line", "{missing}"); - // A Session that closed itself keeps stored rows Agents cannot load, which - // is `session_unavailable`; a deleted one is `no_session`. session.close().await.unwrap(); let closed = rig .call( diff --git a/rustc-ice-2026-11-26T00_13_51-2515656.txt b/rustc-ice-2026-11-26T00_13_51-2515656.txt new file mode 100644 index 0000000000..9582479be3 --- /dev/null +++ b/rustc-ice-2026-11-26T00_13_51-2515656.txt @@ -0,0 +1,89 @@ +thread 'rustc' panicked at /rustc-dev/0ef1bc386059596dada8fb65b50425aab2ea637a/compiler/rustc_middle/src/verify_ich.rs:82:9: +Found unstable fingerprints for evaluate_obligation(6c222998005c106a-66c8b7a0f64b6944): Ok(EvaluatedToOk) +stack backtrace: + 0: 0x7dd4dab67075 - ::create + 1: 0x7dd4dab66fc5 - ::force_capture + 2: 0x7dd4d98921c1 - std[c60ef17cbf7de79f]::panicking::update_hook::>::{closure#0} + 3: 0x7dd4dab7ced2 - std[c60ef17cbf7de79f]::panicking::panic_with_hook + 4: 0x7dd4dab5b022 - std[c60ef17cbf7de79f]::panicking::panic_handler::{closure#0} + 5: 0x7dd4dab52bd9 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_end_short_backtrace:: + 6: 0x7dd4dab5cbfd - __rustc[45371133cddedda4]::rust_begin_unwind + 7: 0x7dd4d754a79c - core[62e902411887be45]::panicking::panic_fmt + 8: 0x7dd4d9f91064 - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich_failed + 9: 0x7dd4dbef24df - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich::> + 10: 0x7dd4db928f81 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, rustc_middle[f05df7111292b19b]::query::erase::ErasedData<[u8; 2usize]>>, true> + 11: 0x7dd4db92790c - rustc_query_impl[457aa35bb58f7d69]::query_vtables::evaluate_obligation::execute_query_incr::__rust_end_short_backtrace + 12: 0x7dd4dbdb3d16 - ::process_obligation + 13: 0x7dd4db202183 - >::process_obligations:: + 14: 0x7dd4db476966 - ::check_expr_call + 15: 0x7dd4db4aeb70 - ::check_expr_with_expectation_and_args + 16: 0x7dd4db404c69 - ::check_argument_types + 17: 0x7dd4db41daa9 - ::check_expr_method_call + 18: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 19: 0x7dd4db41d0d8 - ::check_expr_method_call + 20: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 21: 0x7dd4db41d0d8 - ::check_expr_method_call + 22: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 23: 0x7dd4db41d0d8 - ::check_expr_method_call + 24: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 25: 0x7dd4db41d0d8 - ::check_expr_method_call + 26: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 27: 0x7dd4db41d0d8 - ::check_expr_method_call + 28: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 29: 0x7dd4db41d0d8 - ::check_expr_method_call + 30: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 31: 0x7dd4db41d0d8 - ::check_expr_method_call + 32: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args + 33: 0x7dd4db4429f9 - ::check_decl + 34: 0x7dd4db4a4a79 - ::check_expr_block + 35: 0x7dd4db4aeb84 - ::check_expr_with_expectation_and_args + 36: 0x7dd4db4b246e - ::check_expr_with_expectation_and_args + 37: 0x7dd4db4a40ea - ::check_expr_block + 38: 0x7dd4db4aeb84 - ::check_expr_with_expectation_and_args + 39: 0x7dd4db49ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn + 40: 0x7dd4dbfd507e - ::check_expr_closure + 41: 0x7dd4db4b1482 - ::check_expr_with_expectation_and_args + 42: 0x7dd4db49ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn + 43: 0x7dd4dbf0a16f - rustc_hir_typeck[79d5d6ea56e5888]::typeck_with_inspect::{closure#0} + 44: 0x7dd4dbf08570 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::typeck_root::invoke_provider_fn::__rust_begin_short_backtrace + 45: 0x7dd4db5b43e4 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>, true> + 46: 0x7dd4dc85cc2f - ::{closure#0} as core[62e902411887be45]::ops::function::FnOnce<(rustc_middle[f05df7111292b19b]::ty::context::TyCtxt, rustc_middle[f05df7111292b19b]::dep_graph::dep_node::DepNode, rustc_middle[f05df7111292b19b]::dep_graph::serialized::SerializedDepNodeIndex)>>::call_once + 47: 0x7dd4db2163cd - ::try_mark_previous_green + 48: 0x7dd4db215f98 - ::try_mark_previous_green + 49: 0x7dd4db215f98 - ::try_mark_previous_green + 50: 0x7dd4db215f98 - ::try_mark_previous_green + 51: 0x7dd4db215f98 - ::try_mark_previous_green + 52: 0x7dd4db215f98 - ::try_mark_previous_green + 53: 0x7dd4db215f98 - ::try_mark_previous_green + 54: 0x7dd4db215f98 - ::try_mark_previous_green + 55: 0x7dd4db5b2b1b - rustc_query_impl[457aa35bb58f7d69]::execution::ensure_can_skip_execution::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>> + 56: 0x7dd4db5aae56 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_well_formed::execute_query_incr::__rust_end_short_backtrace + 57: 0x7dd4dc008ef6 - ::par_opaques:: + 58: 0x7dd4dc00f9e2 - rustc_hir_analysis[16a231d809d36a5f]::check::wfcheck::check_type_wf + 59: 0x7dd4dc00f5a3 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::invoke_provider_fn::__rust_begin_short_backtrace + 60: 0x7dd4dc8a3779 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> + 61: 0x7dd4dc8a31ad - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::execute_query_incr::__rust_end_short_backtrace + 62: 0x7dd4dbeebf9d - rustc_hir_analysis[16a231d809d36a5f]::check_crate + 63: 0x7dd4dbef494a - rustc_interface[3b9185f2a0f7ce0c]::passes::analysis + 64: 0x7dd4dc5a5b2f - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> + 65: 0x7dd4dc5a539d - rustc_query_impl[457aa35bb58f7d69]::query_vtables::analysis::execute_query_incr::__rust_end_short_backtrace + 66: 0x7dd4dc3c2709 - rustc_interface[3b9185f2a0f7ce0c]::interface::run_compiler::<(), rustc_driver_impl[948176d47fdf990a]::run_compiler::{closure#0}>::{closure#2} + 67: 0x7dd4dc43cc42 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> + 68: 0x7dd4dc43c9ed - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[62e902411887be45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} + 69: 0x7dd4dc437d6d - ::new::thread_start + 70: 0x7dd4d549cb84 - start_thread + at ./nptl/pthread_create.c:447:8 + 71: 0x7dd4d5529ecc - clone3 + at ./misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:78:0 + 72: 0x0 - + + +rustc version: 1.100.0 (0ef1bc386 2026-11-09) +platform: x86_64-unknown-linux-gnu + +query stack during panic: +#0 [evaluate_obligation] evaluating trait selection obligation `alloc::boxed::Box: core::marker::Send` +#1 [typeck_root] type-checking `web_entry::::start` +#2 [check_type_wf] checking that types are well-formed +#3 [analysis] running analysis passes on crate `dim_app_server` +end of query stack diff --git a/rustc-ice-2026-11-26T00_13_58-2515723.txt b/rustc-ice-2026-11-26T00_13_58-2515723.txt new file mode 100644 index 0000000000..8c37d0ed3b --- /dev/null +++ b/rustc-ice-2026-11-26T00_13_58-2515723.txt @@ -0,0 +1,89 @@ +thread 'rustc' panicked at /rustc-dev/0ef1bc386059596dada8fb65b50425aab2ea637a/compiler/rustc_middle/src/verify_ich.rs:82:9: +Found unstable fingerprints for evaluate_obligation(6c222998005c106a-66c8b7a0f64b6944): Ok(EvaluatedToOk) +stack backtrace: + 0: 0x72d8b6567075 - ::create + 1: 0x72d8b6566fc5 - ::force_capture + 2: 0x72d8b52921c1 - std[c60ef17cbf7de79f]::panicking::update_hook::>::{closure#0} + 3: 0x72d8b657ced2 - std[c60ef17cbf7de79f]::panicking::panic_with_hook + 4: 0x72d8b655b022 - std[c60ef17cbf7de79f]::panicking::panic_handler::{closure#0} + 5: 0x72d8b6552bd9 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_end_short_backtrace:: + 6: 0x72d8b655cbfd - __rustc[45371133cddedda4]::rust_begin_unwind + 7: 0x72d8b2f4a79c - core[62e902411887be45]::panicking::panic_fmt + 8: 0x72d8b5991064 - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich_failed + 9: 0x72d8b78f24df - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich::> + 10: 0x72d8b7328f81 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, rustc_middle[f05df7111292b19b]::query::erase::ErasedData<[u8; 2usize]>>, true> + 11: 0x72d8b732790c - rustc_query_impl[457aa35bb58f7d69]::query_vtables::evaluate_obligation::execute_query_incr::__rust_end_short_backtrace + 12: 0x72d8b77b3d16 - ::process_obligation + 13: 0x72d8b6c02183 - >::process_obligations:: + 14: 0x72d8b6e76966 - ::check_expr_call + 15: 0x72d8b6eaeb70 - ::check_expr_with_expectation_and_args + 16: 0x72d8b6e04c69 - ::check_argument_types + 17: 0x72d8b6e1daa9 - ::check_expr_method_call + 18: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 19: 0x72d8b6e1d0d8 - ::check_expr_method_call + 20: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 21: 0x72d8b6e1d0d8 - ::check_expr_method_call + 22: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 23: 0x72d8b6e1d0d8 - ::check_expr_method_call + 24: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 25: 0x72d8b6e1d0d8 - ::check_expr_method_call + 26: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 27: 0x72d8b6e1d0d8 - ::check_expr_method_call + 28: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 29: 0x72d8b6e1d0d8 - ::check_expr_method_call + 30: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 31: 0x72d8b6e1d0d8 - ::check_expr_method_call + 32: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args + 33: 0x72d8b6e429f9 - ::check_decl + 34: 0x72d8b6ea4a79 - ::check_expr_block + 35: 0x72d8b6eaeb84 - ::check_expr_with_expectation_and_args + 36: 0x72d8b6eb246e - ::check_expr_with_expectation_and_args + 37: 0x72d8b6ea40ea - ::check_expr_block + 38: 0x72d8b6eaeb84 - ::check_expr_with_expectation_and_args + 39: 0x72d8b6e9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn + 40: 0x72d8b79d507e - ::check_expr_closure + 41: 0x72d8b6eb1482 - ::check_expr_with_expectation_and_args + 42: 0x72d8b6e9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn + 43: 0x72d8b790a16f - rustc_hir_typeck[79d5d6ea56e5888]::typeck_with_inspect::{closure#0} + 44: 0x72d8b7908570 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::typeck_root::invoke_provider_fn::__rust_begin_short_backtrace + 45: 0x72d8b6fb43e4 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>, true> + 46: 0x72d8b825cc2f - ::{closure#0} as core[62e902411887be45]::ops::function::FnOnce<(rustc_middle[f05df7111292b19b]::ty::context::TyCtxt, rustc_middle[f05df7111292b19b]::dep_graph::dep_node::DepNode, rustc_middle[f05df7111292b19b]::dep_graph::serialized::SerializedDepNodeIndex)>>::call_once + 47: 0x72d8b6c163cd - ::try_mark_previous_green + 48: 0x72d8b6c15f98 - ::try_mark_previous_green + 49: 0x72d8b6c15f98 - ::try_mark_previous_green + 50: 0x72d8b6c15f98 - ::try_mark_previous_green + 51: 0x72d8b6c15f98 - ::try_mark_previous_green + 52: 0x72d8b6c15f98 - ::try_mark_previous_green + 53: 0x72d8b6c15f98 - ::try_mark_previous_green + 54: 0x72d8b6c15f98 - ::try_mark_previous_green + 55: 0x72d8b6fb2b1b - rustc_query_impl[457aa35bb58f7d69]::execution::ensure_can_skip_execution::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>> + 56: 0x72d8b6faae56 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_well_formed::execute_query_incr::__rust_end_short_backtrace + 57: 0x72d8b7a08ef6 - ::par_opaques:: + 58: 0x72d8b7a0f9e2 - rustc_hir_analysis[16a231d809d36a5f]::check::wfcheck::check_type_wf + 59: 0x72d8b7a0f5a3 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::invoke_provider_fn::__rust_begin_short_backtrace + 60: 0x72d8b82a3779 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> + 61: 0x72d8b82a31ad - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::execute_query_incr::__rust_end_short_backtrace + 62: 0x72d8b78ebf9d - rustc_hir_analysis[16a231d809d36a5f]::check_crate + 63: 0x72d8b78f494a - rustc_interface[3b9185f2a0f7ce0c]::passes::analysis + 64: 0x72d8b7fa5b2f - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> + 65: 0x72d8b7fa539d - rustc_query_impl[457aa35bb58f7d69]::query_vtables::analysis::execute_query_incr::__rust_end_short_backtrace + 66: 0x72d8b7dc2709 - rustc_interface[3b9185f2a0f7ce0c]::interface::run_compiler::<(), rustc_driver_impl[948176d47fdf990a]::run_compiler::{closure#0}>::{closure#2} + 67: 0x72d8b7e3cc42 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> + 68: 0x72d8b7e3c9ed - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[62e902411887be45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} + 69: 0x72d8b7e37d6d - ::new::thread_start + 70: 0x72d8b0e9cb84 - start_thread + at ./nptl/pthread_create.c:447:8 + 71: 0x72d8b0f29ecc - clone3 + at ./misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:78:0 + 72: 0x0 - + + +rustc version: 1.100.0 (0ef1bc386 2026-11-09) +platform: x86_64-unknown-linux-gnu + +query stack during panic: +#0 [evaluate_obligation] evaluating trait selection obligation `alloc::boxed::Box: core::marker::Send` +#1 [typeck_root] type-checking `web_entry::::start` +#2 [check_type_wf] checking that types are well-formed +#3 [analysis] running analysis passes on crate `dim_app_server` +end of query stack diff --git a/rustc-ice-2026-11-26T00_14_06-2517666.txt b/rustc-ice-2026-11-26T00_14_06-2517666.txt new file mode 100644 index 0000000000..bea72a8ceb --- /dev/null +++ b/rustc-ice-2026-11-26T00_14_06-2517666.txt @@ -0,0 +1,89 @@ +thread 'rustc' panicked at /rustc-dev/0ef1bc386059596dada8fb65b50425aab2ea637a/compiler/rustc_middle/src/verify_ich.rs:82:9: +Found unstable fingerprints for evaluate_obligation(6c222998005c106a-66c8b7a0f64b6944): Ok(EvaluatedToOk) +stack backtrace: + 0: 0x760176367075 - ::create + 1: 0x760176366fc5 - ::force_capture + 2: 0x7601750921c1 - std[c60ef17cbf7de79f]::panicking::update_hook::>::{closure#0} + 3: 0x76017637ced2 - std[c60ef17cbf7de79f]::panicking::panic_with_hook + 4: 0x76017635b022 - std[c60ef17cbf7de79f]::panicking::panic_handler::{closure#0} + 5: 0x760176352bd9 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_end_short_backtrace:: + 6: 0x76017635cbfd - __rustc[45371133cddedda4]::rust_begin_unwind + 7: 0x760172d4a79c - core[62e902411887be45]::panicking::panic_fmt + 8: 0x760175791064 - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich_failed + 9: 0x7601776f24df - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich::> + 10: 0x760177128f81 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, rustc_middle[f05df7111292b19b]::query::erase::ErasedData<[u8; 2usize]>>, true> + 11: 0x76017712790c - rustc_query_impl[457aa35bb58f7d69]::query_vtables::evaluate_obligation::execute_query_incr::__rust_end_short_backtrace + 12: 0x7601775b3d16 - ::process_obligation + 13: 0x760176a02183 - >::process_obligations:: + 14: 0x760176c76966 - ::check_expr_call + 15: 0x760176caeb70 - ::check_expr_with_expectation_and_args + 16: 0x760176c04c69 - ::check_argument_types + 17: 0x760176c1daa9 - ::check_expr_method_call + 18: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 19: 0x760176c1d0d8 - ::check_expr_method_call + 20: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 21: 0x760176c1d0d8 - ::check_expr_method_call + 22: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 23: 0x760176c1d0d8 - ::check_expr_method_call + 24: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 25: 0x760176c1d0d8 - ::check_expr_method_call + 26: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 27: 0x760176c1d0d8 - ::check_expr_method_call + 28: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 29: 0x760176c1d0d8 - ::check_expr_method_call + 30: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 31: 0x760176c1d0d8 - ::check_expr_method_call + 32: 0x760176caebb0 - ::check_expr_with_expectation_and_args + 33: 0x760176c429f9 - ::check_decl + 34: 0x760176ca4a79 - ::check_expr_block + 35: 0x760176caeb84 - ::check_expr_with_expectation_and_args + 36: 0x760176cb246e - ::check_expr_with_expectation_and_args + 37: 0x760176ca40ea - ::check_expr_block + 38: 0x760176caeb84 - ::check_expr_with_expectation_and_args + 39: 0x760176c9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn + 40: 0x7601777d507e - ::check_expr_closure + 41: 0x760176cb1482 - ::check_expr_with_expectation_and_args + 42: 0x760176c9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn + 43: 0x76017770a16f - rustc_hir_typeck[79d5d6ea56e5888]::typeck_with_inspect::{closure#0} + 44: 0x760177708570 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::typeck_root::invoke_provider_fn::__rust_begin_short_backtrace + 45: 0x760176db43e4 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>, true> + 46: 0x76017805cc2f - ::{closure#0} as core[62e902411887be45]::ops::function::FnOnce<(rustc_middle[f05df7111292b19b]::ty::context::TyCtxt, rustc_middle[f05df7111292b19b]::dep_graph::dep_node::DepNode, rustc_middle[f05df7111292b19b]::dep_graph::serialized::SerializedDepNodeIndex)>>::call_once + 47: 0x760176a163cd - ::try_mark_previous_green + 48: 0x760176a15f98 - ::try_mark_previous_green + 49: 0x760176a15f98 - ::try_mark_previous_green + 50: 0x760176a15f98 - ::try_mark_previous_green + 51: 0x760176a15f98 - ::try_mark_previous_green + 52: 0x760176a15f98 - ::try_mark_previous_green + 53: 0x760176a15f98 - ::try_mark_previous_green + 54: 0x760176a15f98 - ::try_mark_previous_green + 55: 0x760176db2b1b - rustc_query_impl[457aa35bb58f7d69]::execution::ensure_can_skip_execution::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>> + 56: 0x760176daae56 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_well_formed::execute_query_incr::__rust_end_short_backtrace + 57: 0x760177808ef6 - ::par_opaques:: + 58: 0x76017780f9e2 - rustc_hir_analysis[16a231d809d36a5f]::check::wfcheck::check_type_wf + 59: 0x76017780f5a3 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::invoke_provider_fn::__rust_begin_short_backtrace + 60: 0x7601780a3779 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> + 61: 0x7601780a31ad - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::execute_query_incr::__rust_end_short_backtrace + 62: 0x7601776ebf9d - rustc_hir_analysis[16a231d809d36a5f]::check_crate + 63: 0x7601776f494a - rustc_interface[3b9185f2a0f7ce0c]::passes::analysis + 64: 0x760177da5b2f - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> + 65: 0x760177da539d - rustc_query_impl[457aa35bb58f7d69]::query_vtables::analysis::execute_query_incr::__rust_end_short_backtrace + 66: 0x760177bc2709 - rustc_interface[3b9185f2a0f7ce0c]::interface::run_compiler::<(), rustc_driver_impl[948176d47fdf990a]::run_compiler::{closure#0}>::{closure#2} + 67: 0x760177c3cc42 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> + 68: 0x760177c3c9ed - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[62e902411887be45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} + 69: 0x760177c37d6d - ::new::thread_start + 70: 0x760170c9cb84 - start_thread + at ./nptl/pthread_create.c:447:8 + 71: 0x760170d29ecc - clone3 + at ./misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:78:0 + 72: 0x0 - + + +rustc version: 1.100.0 (0ef1bc386 2026-11-09) +platform: x86_64-unknown-linux-gnu + +query stack during panic: +#0 [evaluate_obligation] evaluating trait selection obligation `alloc::boxed::Box: core::marker::Send` +#1 [typeck_root] type-checking `web_entry::::start` +#2 [check_type_wf] checking that types are well-formed +#3 [analysis] running analysis passes on crate `dim_app_server` +end of query stack From da77d726de06f2a6915d2081313e7b2a3bc3ad58 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 08:26:36 +0800 Subject: [PATCH 15/37] test(runtime): keep the missing-id and missing-line answers, and drop rustc dumps - three rustc crash dumps were committed by accident; they are removed and `rustc-ice-*.txt` is ignored; - `sessions.call`'s `no_session` for an unknown id and `no_line` for a line that is not the Session's are asserted again, so the `NoLine` mapping has a test; - the D5 note is limited to what the evidence covers: a Session that Agents never admitted (the rig cannot `launch`, it has no model), where `versions` has no entry and the live-Session fallback stops finding it after an idle release. Refs #2015 Refs #2127 --- .gitignore | 3 + .../tests/data_faces_flow.rs | 18 ++++ rustc-ice-2026-11-26T00_13_51-2515656.txt | 89 ------------------- rustc-ice-2026-11-26T00_13_58-2515723.txt | 89 ------------------- rustc-ice-2026-11-26T00_14_06-2517666.txt | 89 ------------------- 5 files changed, 21 insertions(+), 267 deletions(-) delete mode 100644 rustc-ice-2026-11-26T00_13_51-2515656.txt delete mode 100644 rustc-ice-2026-11-26T00_13_58-2515723.txt delete mode 100644 rustc-ice-2026-11-26T00_14_06-2517666.txt diff --git a/.gitignore b/.gitignore index 5a9b6ae1a3..0c12972408 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ __pycache__/ *.tgz *.log .DS_Store + +# rustc crash dumps +rustc-ice-*.txt diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index 2c63865ecc..2e18d7ceea 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -825,6 +825,24 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!(session.sequence("main").unwrap()), "{line}" ); + let unknown = rig + .call( + "sessions", + "call", + json!({"sessionId": "absent", "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(unknown["error"]["code"], "no_session", "{unknown}"); + let missing = rig + .call( + "sessions", + "call", + json!({"sessionId": id, "lineId": "absent", "service": "timeline", "method": "sequence"}), + ) + .await; + assert_eq!(missing["error"]["code"], "no_line", "{missing}"); + // A Session that closed itself keeps stored rows Agents cannot load, which + // is `session_unavailable`; a deleted one is `no_session`. session.close().await.unwrap(); let closed = rig .call( diff --git a/rustc-ice-2026-11-26T00_13_51-2515656.txt b/rustc-ice-2026-11-26T00_13_51-2515656.txt deleted file mode 100644 index 9582479be3..0000000000 --- a/rustc-ice-2026-11-26T00_13_51-2515656.txt +++ /dev/null @@ -1,89 +0,0 @@ -thread 'rustc' panicked at /rustc-dev/0ef1bc386059596dada8fb65b50425aab2ea637a/compiler/rustc_middle/src/verify_ich.rs:82:9: -Found unstable fingerprints for evaluate_obligation(6c222998005c106a-66c8b7a0f64b6944): Ok(EvaluatedToOk) -stack backtrace: - 0: 0x7dd4dab67075 - ::create - 1: 0x7dd4dab66fc5 - ::force_capture - 2: 0x7dd4d98921c1 - std[c60ef17cbf7de79f]::panicking::update_hook::>::{closure#0} - 3: 0x7dd4dab7ced2 - std[c60ef17cbf7de79f]::panicking::panic_with_hook - 4: 0x7dd4dab5b022 - std[c60ef17cbf7de79f]::panicking::panic_handler::{closure#0} - 5: 0x7dd4dab52bd9 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_end_short_backtrace:: - 6: 0x7dd4dab5cbfd - __rustc[45371133cddedda4]::rust_begin_unwind - 7: 0x7dd4d754a79c - core[62e902411887be45]::panicking::panic_fmt - 8: 0x7dd4d9f91064 - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich_failed - 9: 0x7dd4dbef24df - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich::> - 10: 0x7dd4db928f81 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, rustc_middle[f05df7111292b19b]::query::erase::ErasedData<[u8; 2usize]>>, true> - 11: 0x7dd4db92790c - rustc_query_impl[457aa35bb58f7d69]::query_vtables::evaluate_obligation::execute_query_incr::__rust_end_short_backtrace - 12: 0x7dd4dbdb3d16 - ::process_obligation - 13: 0x7dd4db202183 - >::process_obligations:: - 14: 0x7dd4db476966 - ::check_expr_call - 15: 0x7dd4db4aeb70 - ::check_expr_with_expectation_and_args - 16: 0x7dd4db404c69 - ::check_argument_types - 17: 0x7dd4db41daa9 - ::check_expr_method_call - 18: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 19: 0x7dd4db41d0d8 - ::check_expr_method_call - 20: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 21: 0x7dd4db41d0d8 - ::check_expr_method_call - 22: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 23: 0x7dd4db41d0d8 - ::check_expr_method_call - 24: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 25: 0x7dd4db41d0d8 - ::check_expr_method_call - 26: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 27: 0x7dd4db41d0d8 - ::check_expr_method_call - 28: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 29: 0x7dd4db41d0d8 - ::check_expr_method_call - 30: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 31: 0x7dd4db41d0d8 - ::check_expr_method_call - 32: 0x7dd4db4aebb0 - ::check_expr_with_expectation_and_args - 33: 0x7dd4db4429f9 - ::check_decl - 34: 0x7dd4db4a4a79 - ::check_expr_block - 35: 0x7dd4db4aeb84 - ::check_expr_with_expectation_and_args - 36: 0x7dd4db4b246e - ::check_expr_with_expectation_and_args - 37: 0x7dd4db4a40ea - ::check_expr_block - 38: 0x7dd4db4aeb84 - ::check_expr_with_expectation_and_args - 39: 0x7dd4db49ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn - 40: 0x7dd4dbfd507e - ::check_expr_closure - 41: 0x7dd4db4b1482 - ::check_expr_with_expectation_and_args - 42: 0x7dd4db49ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn - 43: 0x7dd4dbf0a16f - rustc_hir_typeck[79d5d6ea56e5888]::typeck_with_inspect::{closure#0} - 44: 0x7dd4dbf08570 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::typeck_root::invoke_provider_fn::__rust_begin_short_backtrace - 45: 0x7dd4db5b43e4 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>, true> - 46: 0x7dd4dc85cc2f - ::{closure#0} as core[62e902411887be45]::ops::function::FnOnce<(rustc_middle[f05df7111292b19b]::ty::context::TyCtxt, rustc_middle[f05df7111292b19b]::dep_graph::dep_node::DepNode, rustc_middle[f05df7111292b19b]::dep_graph::serialized::SerializedDepNodeIndex)>>::call_once - 47: 0x7dd4db2163cd - ::try_mark_previous_green - 48: 0x7dd4db215f98 - ::try_mark_previous_green - 49: 0x7dd4db215f98 - ::try_mark_previous_green - 50: 0x7dd4db215f98 - ::try_mark_previous_green - 51: 0x7dd4db215f98 - ::try_mark_previous_green - 52: 0x7dd4db215f98 - ::try_mark_previous_green - 53: 0x7dd4db215f98 - ::try_mark_previous_green - 54: 0x7dd4db215f98 - ::try_mark_previous_green - 55: 0x7dd4db5b2b1b - rustc_query_impl[457aa35bb58f7d69]::execution::ensure_can_skip_execution::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>> - 56: 0x7dd4db5aae56 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_well_formed::execute_query_incr::__rust_end_short_backtrace - 57: 0x7dd4dc008ef6 - ::par_opaques:: - 58: 0x7dd4dc00f9e2 - rustc_hir_analysis[16a231d809d36a5f]::check::wfcheck::check_type_wf - 59: 0x7dd4dc00f5a3 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::invoke_provider_fn::__rust_begin_short_backtrace - 60: 0x7dd4dc8a3779 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> - 61: 0x7dd4dc8a31ad - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::execute_query_incr::__rust_end_short_backtrace - 62: 0x7dd4dbeebf9d - rustc_hir_analysis[16a231d809d36a5f]::check_crate - 63: 0x7dd4dbef494a - rustc_interface[3b9185f2a0f7ce0c]::passes::analysis - 64: 0x7dd4dc5a5b2f - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> - 65: 0x7dd4dc5a539d - rustc_query_impl[457aa35bb58f7d69]::query_vtables::analysis::execute_query_incr::__rust_end_short_backtrace - 66: 0x7dd4dc3c2709 - rustc_interface[3b9185f2a0f7ce0c]::interface::run_compiler::<(), rustc_driver_impl[948176d47fdf990a]::run_compiler::{closure#0}>::{closure#2} - 67: 0x7dd4dc43cc42 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> - 68: 0x7dd4dc43c9ed - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[62e902411887be45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} - 69: 0x7dd4dc437d6d - ::new::thread_start - 70: 0x7dd4d549cb84 - start_thread - at ./nptl/pthread_create.c:447:8 - 71: 0x7dd4d5529ecc - clone3 - at ./misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:78:0 - 72: 0x0 - - - -rustc version: 1.100.0 (0ef1bc386 2026-11-09) -platform: x86_64-unknown-linux-gnu - -query stack during panic: -#0 [evaluate_obligation] evaluating trait selection obligation `alloc::boxed::Box: core::marker::Send` -#1 [typeck_root] type-checking `web_entry::::start` -#2 [check_type_wf] checking that types are well-formed -#3 [analysis] running analysis passes on crate `dim_app_server` -end of query stack diff --git a/rustc-ice-2026-11-26T00_13_58-2515723.txt b/rustc-ice-2026-11-26T00_13_58-2515723.txt deleted file mode 100644 index 8c37d0ed3b..0000000000 --- a/rustc-ice-2026-11-26T00_13_58-2515723.txt +++ /dev/null @@ -1,89 +0,0 @@ -thread 'rustc' panicked at /rustc-dev/0ef1bc386059596dada8fb65b50425aab2ea637a/compiler/rustc_middle/src/verify_ich.rs:82:9: -Found unstable fingerprints for evaluate_obligation(6c222998005c106a-66c8b7a0f64b6944): Ok(EvaluatedToOk) -stack backtrace: - 0: 0x72d8b6567075 - ::create - 1: 0x72d8b6566fc5 - ::force_capture - 2: 0x72d8b52921c1 - std[c60ef17cbf7de79f]::panicking::update_hook::>::{closure#0} - 3: 0x72d8b657ced2 - std[c60ef17cbf7de79f]::panicking::panic_with_hook - 4: 0x72d8b655b022 - std[c60ef17cbf7de79f]::panicking::panic_handler::{closure#0} - 5: 0x72d8b6552bd9 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_end_short_backtrace:: - 6: 0x72d8b655cbfd - __rustc[45371133cddedda4]::rust_begin_unwind - 7: 0x72d8b2f4a79c - core[62e902411887be45]::panicking::panic_fmt - 8: 0x72d8b5991064 - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich_failed - 9: 0x72d8b78f24df - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich::> - 10: 0x72d8b7328f81 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, rustc_middle[f05df7111292b19b]::query::erase::ErasedData<[u8; 2usize]>>, true> - 11: 0x72d8b732790c - rustc_query_impl[457aa35bb58f7d69]::query_vtables::evaluate_obligation::execute_query_incr::__rust_end_short_backtrace - 12: 0x72d8b77b3d16 - ::process_obligation - 13: 0x72d8b6c02183 - >::process_obligations:: - 14: 0x72d8b6e76966 - ::check_expr_call - 15: 0x72d8b6eaeb70 - ::check_expr_with_expectation_and_args - 16: 0x72d8b6e04c69 - ::check_argument_types - 17: 0x72d8b6e1daa9 - ::check_expr_method_call - 18: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 19: 0x72d8b6e1d0d8 - ::check_expr_method_call - 20: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 21: 0x72d8b6e1d0d8 - ::check_expr_method_call - 22: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 23: 0x72d8b6e1d0d8 - ::check_expr_method_call - 24: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 25: 0x72d8b6e1d0d8 - ::check_expr_method_call - 26: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 27: 0x72d8b6e1d0d8 - ::check_expr_method_call - 28: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 29: 0x72d8b6e1d0d8 - ::check_expr_method_call - 30: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 31: 0x72d8b6e1d0d8 - ::check_expr_method_call - 32: 0x72d8b6eaebb0 - ::check_expr_with_expectation_and_args - 33: 0x72d8b6e429f9 - ::check_decl - 34: 0x72d8b6ea4a79 - ::check_expr_block - 35: 0x72d8b6eaeb84 - ::check_expr_with_expectation_and_args - 36: 0x72d8b6eb246e - ::check_expr_with_expectation_and_args - 37: 0x72d8b6ea40ea - ::check_expr_block - 38: 0x72d8b6eaeb84 - ::check_expr_with_expectation_and_args - 39: 0x72d8b6e9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn - 40: 0x72d8b79d507e - ::check_expr_closure - 41: 0x72d8b6eb1482 - ::check_expr_with_expectation_and_args - 42: 0x72d8b6e9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn - 43: 0x72d8b790a16f - rustc_hir_typeck[79d5d6ea56e5888]::typeck_with_inspect::{closure#0} - 44: 0x72d8b7908570 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::typeck_root::invoke_provider_fn::__rust_begin_short_backtrace - 45: 0x72d8b6fb43e4 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>, true> - 46: 0x72d8b825cc2f - ::{closure#0} as core[62e902411887be45]::ops::function::FnOnce<(rustc_middle[f05df7111292b19b]::ty::context::TyCtxt, rustc_middle[f05df7111292b19b]::dep_graph::dep_node::DepNode, rustc_middle[f05df7111292b19b]::dep_graph::serialized::SerializedDepNodeIndex)>>::call_once - 47: 0x72d8b6c163cd - ::try_mark_previous_green - 48: 0x72d8b6c15f98 - ::try_mark_previous_green - 49: 0x72d8b6c15f98 - ::try_mark_previous_green - 50: 0x72d8b6c15f98 - ::try_mark_previous_green - 51: 0x72d8b6c15f98 - ::try_mark_previous_green - 52: 0x72d8b6c15f98 - ::try_mark_previous_green - 53: 0x72d8b6c15f98 - ::try_mark_previous_green - 54: 0x72d8b6c15f98 - ::try_mark_previous_green - 55: 0x72d8b6fb2b1b - rustc_query_impl[457aa35bb58f7d69]::execution::ensure_can_skip_execution::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>> - 56: 0x72d8b6faae56 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_well_formed::execute_query_incr::__rust_end_short_backtrace - 57: 0x72d8b7a08ef6 - ::par_opaques:: - 58: 0x72d8b7a0f9e2 - rustc_hir_analysis[16a231d809d36a5f]::check::wfcheck::check_type_wf - 59: 0x72d8b7a0f5a3 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::invoke_provider_fn::__rust_begin_short_backtrace - 60: 0x72d8b82a3779 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> - 61: 0x72d8b82a31ad - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::execute_query_incr::__rust_end_short_backtrace - 62: 0x72d8b78ebf9d - rustc_hir_analysis[16a231d809d36a5f]::check_crate - 63: 0x72d8b78f494a - rustc_interface[3b9185f2a0f7ce0c]::passes::analysis - 64: 0x72d8b7fa5b2f - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> - 65: 0x72d8b7fa539d - rustc_query_impl[457aa35bb58f7d69]::query_vtables::analysis::execute_query_incr::__rust_end_short_backtrace - 66: 0x72d8b7dc2709 - rustc_interface[3b9185f2a0f7ce0c]::interface::run_compiler::<(), rustc_driver_impl[948176d47fdf990a]::run_compiler::{closure#0}>::{closure#2} - 67: 0x72d8b7e3cc42 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> - 68: 0x72d8b7e3c9ed - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[62e902411887be45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} - 69: 0x72d8b7e37d6d - ::new::thread_start - 70: 0x72d8b0e9cb84 - start_thread - at ./nptl/pthread_create.c:447:8 - 71: 0x72d8b0f29ecc - clone3 - at ./misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:78:0 - 72: 0x0 - - - -rustc version: 1.100.0 (0ef1bc386 2026-11-09) -platform: x86_64-unknown-linux-gnu - -query stack during panic: -#0 [evaluate_obligation] evaluating trait selection obligation `alloc::boxed::Box: core::marker::Send` -#1 [typeck_root] type-checking `web_entry::::start` -#2 [check_type_wf] checking that types are well-formed -#3 [analysis] running analysis passes on crate `dim_app_server` -end of query stack diff --git a/rustc-ice-2026-11-26T00_14_06-2517666.txt b/rustc-ice-2026-11-26T00_14_06-2517666.txt deleted file mode 100644 index bea72a8ceb..0000000000 --- a/rustc-ice-2026-11-26T00_14_06-2517666.txt +++ /dev/null @@ -1,89 +0,0 @@ -thread 'rustc' panicked at /rustc-dev/0ef1bc386059596dada8fb65b50425aab2ea637a/compiler/rustc_middle/src/verify_ich.rs:82:9: -Found unstable fingerprints for evaluate_obligation(6c222998005c106a-66c8b7a0f64b6944): Ok(EvaluatedToOk) -stack backtrace: - 0: 0x760176367075 - ::create - 1: 0x760176366fc5 - ::force_capture - 2: 0x7601750921c1 - std[c60ef17cbf7de79f]::panicking::update_hook::>::{closure#0} - 3: 0x76017637ced2 - std[c60ef17cbf7de79f]::panicking::panic_with_hook - 4: 0x76017635b022 - std[c60ef17cbf7de79f]::panicking::panic_handler::{closure#0} - 5: 0x760176352bd9 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_end_short_backtrace:: - 6: 0x76017635cbfd - __rustc[45371133cddedda4]::rust_begin_unwind - 7: 0x760172d4a79c - core[62e902411887be45]::panicking::panic_fmt - 8: 0x760175791064 - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich_failed - 9: 0x7601776f24df - rustc_middle[f05df7111292b19b]::verify_ich::incremental_verify_ich::> - 10: 0x760177128f81 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, rustc_middle[f05df7111292b19b]::query::erase::ErasedData<[u8; 2usize]>>, true> - 11: 0x76017712790c - rustc_query_impl[457aa35bb58f7d69]::query_vtables::evaluate_obligation::execute_query_incr::__rust_end_short_backtrace - 12: 0x7601775b3d16 - ::process_obligation - 13: 0x760176a02183 - >::process_obligations:: - 14: 0x760176c76966 - ::check_expr_call - 15: 0x760176caeb70 - ::check_expr_with_expectation_and_args - 16: 0x760176c04c69 - ::check_argument_types - 17: 0x760176c1daa9 - ::check_expr_method_call - 18: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 19: 0x760176c1d0d8 - ::check_expr_method_call - 20: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 21: 0x760176c1d0d8 - ::check_expr_method_call - 22: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 23: 0x760176c1d0d8 - ::check_expr_method_call - 24: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 25: 0x760176c1d0d8 - ::check_expr_method_call - 26: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 27: 0x760176c1d0d8 - ::check_expr_method_call - 28: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 29: 0x760176c1d0d8 - ::check_expr_method_call - 30: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 31: 0x760176c1d0d8 - ::check_expr_method_call - 32: 0x760176caebb0 - ::check_expr_with_expectation_and_args - 33: 0x760176c429f9 - ::check_decl - 34: 0x760176ca4a79 - ::check_expr_block - 35: 0x760176caeb84 - ::check_expr_with_expectation_and_args - 36: 0x760176cb246e - ::check_expr_with_expectation_and_args - 37: 0x760176ca40ea - ::check_expr_block - 38: 0x760176caeb84 - ::check_expr_with_expectation_and_args - 39: 0x760176c9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn - 40: 0x7601777d507e - ::check_expr_closure - 41: 0x760176cb1482 - ::check_expr_with_expectation_and_args - 42: 0x760176c9ffa5 - rustc_hir_typeck[79d5d6ea56e5888]::check::check_fn - 43: 0x76017770a16f - rustc_hir_typeck[79d5d6ea56e5888]::typeck_with_inspect::{closure#0} - 44: 0x760177708570 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::typeck_root::invoke_provider_fn::__rust_begin_short_backtrace - 45: 0x760176db43e4 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>, true> - 46: 0x76017805cc2f - ::{closure#0} as core[62e902411887be45]::ops::function::FnOnce<(rustc_middle[f05df7111292b19b]::ty::context::TyCtxt, rustc_middle[f05df7111292b19b]::dep_graph::dep_node::DepNode, rustc_middle[f05df7111292b19b]::dep_graph::serialized::SerializedDepNodeIndex)>>::call_once - 47: 0x760176a163cd - ::try_mark_previous_green - 48: 0x760176a15f98 - ::try_mark_previous_green - 49: 0x760176a15f98 - ::try_mark_previous_green - 50: 0x760176a15f98 - ::try_mark_previous_green - 51: 0x760176a15f98 - ::try_mark_previous_green - 52: 0x760176a15f98 - ::try_mark_previous_green - 53: 0x760176a15f98 - ::try_mark_previous_green - 54: 0x760176a15f98 - ::try_mark_previous_green - 55: 0x760176db2b1b - rustc_query_impl[457aa35bb58f7d69]::execution::ensure_can_skip_execution::, rustc_middle[f05df7111292b19b]::dep_graph::graph::DepNodeIndex>> - 56: 0x760176daae56 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_well_formed::execute_query_incr::__rust_end_short_backtrace - 57: 0x760177808ef6 - ::par_opaques:: - 58: 0x76017780f9e2 - rustc_hir_analysis[16a231d809d36a5f]::check::wfcheck::check_type_wf - 59: 0x76017780f5a3 - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::invoke_provider_fn::__rust_begin_short_backtrace - 60: 0x7601780a3779 - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> - 61: 0x7601780a31ad - rustc_query_impl[457aa35bb58f7d69]::query_vtables::check_type_wf::execute_query_incr::__rust_end_short_backtrace - 62: 0x7601776ebf9d - rustc_hir_analysis[16a231d809d36a5f]::check_crate - 63: 0x7601776f494a - rustc_interface[3b9185f2a0f7ce0c]::passes::analysis - 64: 0x760177da5b2f - rustc_query_impl[457aa35bb58f7d69]::execution::try_execute_query::>, true> - 65: 0x760177da539d - rustc_query_impl[457aa35bb58f7d69]::query_vtables::analysis::execute_query_incr::__rust_end_short_backtrace - 66: 0x760177bc2709 - rustc_interface[3b9185f2a0f7ce0c]::interface::run_compiler::<(), rustc_driver_impl[948176d47fdf990a]::run_compiler::{closure#0}>::{closure#2} - 67: 0x760177c3cc42 - std[c60ef17cbf7de79f]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> - 68: 0x760177c3c9ed - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[62e902411887be45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} - 69: 0x760177c37d6d - ::new::thread_start - 70: 0x760170c9cb84 - start_thread - at ./nptl/pthread_create.c:447:8 - 71: 0x760170d29ecc - clone3 - at ./misc/../sysdeps/unix/sysv/linux/x86_64/clone3.S:78:0 - 72: 0x0 - - - -rustc version: 1.100.0 (0ef1bc386 2026-11-09) -platform: x86_64-unknown-linux-gnu - -query stack during panic: -#0 [evaluate_obligation] evaluating trait selection obligation `alloc::boxed::Box: core::marker::Send` -#1 [typeck_root] type-checking `web_entry::::start` -#2 [check_type_wf] checking that types are well-formed -#3 [analysis] running analysis passes on crate `dim_app_server` -end of query stack From c08512c5531b662b96c766b1e9447a24796a90d4 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:01:14 +0800 Subject: [PATCH 16/37] fix(runtime): keep the owner's failure as data, and stop a retired name - `RouteError::Owner` carries the owner's structured failure (`data`, from the bridge's `Error::data()`) beside its name, message and retryability, and `sessions.call` forwards it as `Routed { name, message, data, retryable }`: a caller reads the same structure a direct call would, instead of the text; - the catalog check consumes the access layer's `removed` list again, so a retired service name cannot come back unnoticed (proved with `sessionIdentity`); - the authoring guide states when a line stops being admitted (after its durable end, once its instance starts closing) and that an admitted call keeps its owner's result. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/route.rs | 12 +++++++++++ crates/dim-app-server/src/agents/sessions.rs | 9 +++++++- docs/typescript-plugin-authoring.md | 7 ++++++- npm/branch-services.d.ts | 2 +- xtask/src/catalog.rs | 22 ++++++++++++++++++++ 5 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 7d233ba25b..985b5d6a11 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -90,6 +90,10 @@ pub enum RouteError { Owner { name: String, message: String, + /// The owner's failure as data, when its error type carries a serde + /// value: a caller can act on the same structure a direct call would + /// read, instead of parsing the message. + data: Option>, reloading: bool, }, } @@ -316,6 +320,7 @@ pub(crate) async fn call_face( .ok_or_else(|| RouteError::Owner { name: service.into(), message: format!("{service} is not provided now"), + data: None, reloading: false, })?; let args = BridgeValue::List( @@ -334,6 +339,7 @@ pub(crate) fn owner(error: impl Into) -> RouteError { RouteError::Owner { name: failure.name, message: failure.message, + data: failure.data, reloading: failure.reloading, } } @@ -343,6 +349,7 @@ pub(crate) fn owner(error: impl Into) -> RouteError { pub(crate) struct Failure { name: String, message: String, + data: Option>, reloading: bool, } @@ -352,6 +359,7 @@ impl From for Failure { name: "AgentError".into(), reloading: matches!(error, AgentError::Reloading(_)), message: error.to_string(), + data: None, } } } @@ -364,6 +372,7 @@ impl From for Failure { // service reports a reload as `Reloading` (`AgentError`'s variant // code), and the wire keeps it in the error graph. let reloading = error.code() == Some(RELOADING); + let data = error.data().map(Box::new); let name = match &error { BridgeError::Remote { name, .. } => name.clone(), BridgeError::Binding { code, .. } => code.unwrap_or("BindingError").into(), @@ -373,12 +382,14 @@ impl From for Failure { BridgeError::Remote { message, .. } | BridgeError::Binding { message, .. } => { Self { reloading, + data, name, message, } } other => Self { reloading, + data, name, message: other.to_string(), }, @@ -387,6 +398,7 @@ impl From for Failure { other => Self { name: "BridgeError".into(), message: other.to_string(), + data: None, reloading: false, }, } diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index b31cd56c83..3020e6f4e6 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -315,6 +315,9 @@ pub enum SessionsError { Routed { name: String, message: String, + /// The owner's failure as data, when its error type carries a serde + /// value. + data: Option>, retryable: bool, }, #[error("{message}")] @@ -895,10 +898,14 @@ fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { RouteError::SessionUnavailable { .. } => SessionsError::SessionUnavailable { message }, RouteError::NoLine { .. } => SessionsError::NoLine { message }, RouteError::Owner { - name, reloading, .. + name, + data, + reloading, + .. } => SessionsError::Routed { name, message, + data, retryable: reloading, }, RouteError::NotDataFace { .. } | RouteError::WrongScope { .. } => { diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index ff8f06d201..3f97ebcaec 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -57,7 +57,12 @@ await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: The request types are generated, so `service`, `method` and `args` are the target's own and a typo fails `tsc`. Nothing a call returns may be kept: the next call looks the target up -again. Rust calls the same operations: it builds `args` from the target operation's request +again. + +A line is admitted while it is published and not closing: after its durable `branch/end` it +stays reachable until its instance starts closing, and then `no_line` is final for it. A call +that was admitted keeps its owner's own result and failure, including one that arrives after +the end. Rust calls the same operations: it builds `args` from the target operation's request type and reads the reply as that operation's reply type. ## Available services diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 41077f8278..560fd32bd4 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1466,7 +1466,7 @@ export type SessionsError = | { code: "session_reloading"; message: string } | { code: "session_unavailable"; message: string } | { code: "no_line"; message: string } - | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; message: string; retryable: boolean } + | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; message: string; data?: import('./plugin.js').BridgeJsonValue | null; retryable: boolean } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } | { code: "branch_missing"; message: string } diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index 92c20e59cc..a39c24fece 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -84,6 +84,7 @@ pub(super) async fn collect() -> Result
{ let ctx = ctx.ok_or("the catalog probe did not load")?; let table = Table::new(agent.catalog(), agent.faces(), &layers, &ctx)?; reach(&root_of(), agent.catalog(), agent.faces(), &table)?; + retired(&root_of(), agent.catalog())?; session.close().await?; Ok::<_, Box>(table) } @@ -94,6 +95,27 @@ pub(super) async fn collect() -> Result
{ table } +/// Fails when a service name the access layer records as retired is registered +/// again: the generated authoring types only cover names a route resolves, so a +/// retired name coming back would otherwise go unnoticed +/// (`xtask/access-layer.json`'s `removed` list). +fn retired(root: &std::path::Path, catalog: &ServiceCatalog) -> Result<()> { + let layer = xtask_check::access::load(root)?; + let back: Vec<&String> = layer + .removed + .iter() + .filter(|name| catalog.key(name).is_some() || catalog.is_shared(name)) + .collect(); + if !back.is_empty() { + return Err(format!( + "{}: retired service names are registered again: {back:?}", + xtask_check::access::FILE + ) + .into()); + } + Ok(()) +} + /// The workspace root, from this crate's manifest directory. fn root_of() -> std::path::PathBuf { std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) From 750e76c349e7488d6e2a114da2d4ef0b41e38435 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:12:51 +0800 Subject: [PATCH 17/37] feat(runtime): exclude the operations a routed call cannot keep alive An operation that needs a cancellation the caller observes through the future, or hands the caller something to settle, keeps its lifetime only when it is called directly. Such an operation is now refused by the route (`RouteError::MethodNotRoutable`) and left out of the generated requests, from one list the runtime owns: permission.check, toolHost.execute, treeCommands.create, wait.wait The authoring types read that list and emit `Omit`, so the runtime and the declarations agree on what is routable, and a fixture asserts `wait.wait` is refused at compile time. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 21 ++++++ crates/dim-agent-runtime/src/route.rs | 42 +++++++++++- crates/dim-app-server/src/agents/sessions.rs | 1 + npm/branch-services.d.ts | 10 +-- runtime/fixtures/branch-calls.ts | 2 + xtask/check/src/types.rs | 64 ++++++++++++++++++- 6 files changed, 131 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 34ad0e707d..05e3be1eb3 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -367,6 +367,27 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { "{service} is a lifecycle service" ); } + assert_eq!( + scope + .line_call(LineCall::new("main", "wait", "wait", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "wait".into(), + method: "wait".into() + }, + "an operation that needs a caller-side cancellation is not routed" + ); + assert_eq!( + scope + .call(SessionCall::new("treeCommands", "create", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "treeCommands".into(), + method: "create".into() + } + ); assert_eq!( scope .line_call(LineCall::new("main", "loopState", "state", vec![])) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 985b5d6a11..aae71cfe3f 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -79,6 +79,11 @@ pub enum RouteError { /// lifecycle service. A permanent answer: the request is wrong. #[error("{service} is not a routable data face")] NotDataFace { service: String }, + /// The service is a data face a route resolves, but this operation of it + /// is not: its call needs a cancellation or a cleanup the routed call + /// cannot carry, so only a direct call keeps its lifetime behaviour. + #[error("{service}.{method} is not a routable operation")] + MethodNotRoutable { service: String, method: String }, /// The name is a data face, but not of the scope the route reaches. #[error("{service} is not a {group} service")] WrongScope { service: String, group: String }, @@ -108,6 +113,7 @@ impl RouteError { Self::SessionUnavailable { .. } => "session_unavailable", Self::NoLine { .. } => "no_line", Self::NotDataFace { .. } => "not_data_face", + Self::MethodNotRoutable { .. } => "method_not_routable", Self::WrongScope { .. } => "wrong_scope", Self::Owner { .. } => "owner", } @@ -178,6 +184,18 @@ impl SessionCall { /// owner's own word for "try again later". const RELOADING: &str = "Reloading"; +/// Operations a route does not resolve even though their service is a data +/// face: each takes a cancellation the caller observes through the future, or +/// hands the caller something to settle, and a routed call carries data only. +/// The generated authoring requests read this same list, so the runtime and the +/// declarations agree on what is routable. +pub const LIFECYCLE_METHODS: [(&str, &str); 4] = [ + ("permission", "check"), + ("toolHost", "execute"), + ("treeCommands", "create"), + ("wait", "wait"), +]; + const REGISTRATION_POINTS: [&str; 5] = [ "sessionMethods", "toolRegistry", @@ -240,7 +258,7 @@ impl SessionScope { pub async fn call(&self, call: SessionCall) -> Routed { let session = self.live()?; let (catalog, faces) = session.reach(); - face(catalog, faces, &call.service, SESSION_GROUP)?; + face(catalog, faces, &call.service, &call.method, SESSION_GROUP)?; let loaded = session.loaded().map_err(owner)?; call_face( &loaded.ctx, @@ -255,7 +273,13 @@ impl SessionScope { /// Calls one of this Session's lines' data faces. pub async fn line_call(&self, call: LineCall) -> Routed { let line = self.line_context(&call.line_id)?; - face(line.catalog(), line.faces(), &call.service, BRANCH_GROUP)?; + face( + line.catalog(), + line.faces(), + &call.service, + &call.method, + BRANCH_GROUP, + )?; call_face( line.ctx(), line.scope_instance(), @@ -276,7 +300,7 @@ pub fn resolves( service: &str, group: &str, ) -> bool { - face(catalog, faces, service, group).is_ok() + face(catalog, faces, service, "", group).is_ok() } /// Fails unless a route may resolve `service` as a data face of `group` @@ -285,8 +309,20 @@ pub(crate) fn face( catalog: &names::ServiceCatalog, faces: &Faces, service: &str, + method: &str, group: &str, ) -> Routed<()> { + if LIFECYCLE_METHODS + .iter() + .any(|(refused_service, refused_method)| { + *refused_service == service && *refused_method == method + }) + { + return Err(RouteError::MethodNotRoutable { + service: service.into(), + method: method.into(), + }); + } let lifecycle = [ names::name_of::(), names::name_of::(), diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index 3020e6f4e6..b7028e4955 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -908,6 +908,7 @@ fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { data, retryable: reloading, }, + RouteError::MethodNotRoutable { .. } => SessionsError::Rejected { message }, RouteError::NotDataFace { .. } | RouteError::WrongScope { .. } => { SessionsError::Rejected { message } } diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 560fd32bd4..19976aed27 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1801,7 +1801,7 @@ export type ReservedMethodsErrorThrown = RustError<"ReservedMethodsError", "rese export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceError> /** What a method returning `Err(RouteError)` throws. */ -export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClosing" | "SessionReloading" | "SessionUnavailable" | "NoLine" | "NotDataFace" | "WrongScope" | "Owner", undefined> +export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClosing" | "SessionReloading" | "SessionUnavailable" | "NoLine" | "NotDataFace" | "MethodNotRoutable" | "WrongScope" | "Owner", undefined> /** What a method returning `Err(SessionInstanceError)` throws. */ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> @@ -1870,10 +1870,10 @@ export type LineFaces = { branchLine: BranchLine dispatcher: Dispatcher inputQueue: InputQueue - permission: Permission + permission: Omit timeline: Timeline timelineIdentity: TimelineIdentity - wait: Wait + wait: Omit } /** The data faces a Session reaches. */ @@ -1888,8 +1888,8 @@ export type SessionFaces = { sessionLoader: SessionLoader sessionScope: SessionScope skillsConfig: SkillsConfig - toolHost: ToolHost - treeCommands: TreeCommands + toolHost: Omit + treeCommands: Omit uiResources: UiResources } diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index 93a7c91a03..ed749bb0d8 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -48,6 +48,8 @@ void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) // @ts-expect-error a reply keeps the target method's own type. void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) +// @ts-expect-error an operation that needs a caller-side cancellation is not routed. +void scope.lineCall({ lineId: 'main', service: 'wait', method: 'wait', args: [] }) // @ts-expect-error a Session service takes no lineId. void sessions.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) // @ts-expect-error a line call takes no Session id. diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index cb74adff99..90780746ef 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -45,10 +45,20 @@ fn calls(root: &Path, services: &str) -> Result { session.dedup(); line.sort(); line.dedup(); + let refused = lifecycle(root)?; let faces = |items: &[(String, String)], name: &str| { let mut text = format!("export type {name} = {{\n"); for (member, ty) in items { - text += &format!(" {member}: {ty}\n"); + let omitted: Vec = refused + .iter() + .filter(|(service, _)| service == member) + .map(|(_, method)| format!("'{method}'")) + .collect(); + if omitted.is_empty() { + text += &format!(" {member}: {ty}\n"); + } else { + text += &format!(" {member}: Omit<{ty}, {}>\n", omitted.join(" | ")); + } } text + "}\n" }; @@ -263,6 +273,58 @@ fn name_of(expression: &syn::Expr) -> Option { } } +/// The operations routing does not resolve, read from the runtime's own list: +/// a call that needs a cancellation or a caller-side cleanup keeps its lifetime +/// only when it is made directly. +fn lifecycle(root: &Path) -> Result> { + let path = root.join("crates/dim-agent-runtime/src/route.rs"); + let ast = syn::parse_file(&std::fs::read_to_string(&path)?)?; + let mut found = Vec::new(); + let mut seen = false; + for item in &ast.items { + let syn::Item::Const(declaration) = item else { + continue; + }; + if declaration.ident != "LIFECYCLE_METHODS" { + continue; + } + let syn::Expr::Array(array) = &*declaration.expr else { + return Err(format!("{}: LIFECYCLE_METHODS is not an array", path.display()).into()); + }; + for element in &array.elems { + let syn::Expr::Tuple(tuple) = element else { + return Err(format!( + "{}: a LIFECYCLE_METHODS entry is not a pair", + path.display() + ) + .into()); + }; + let mut parts = tuple.elems.iter().filter_map(|part| match part { + syn::Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(text), + .. + }) => Some(text.value()), + _ => None, + }); + match (parts.next(), parts.next()) { + (Some(service), Some(method)) => found.push((service, method)), + _ => { + return Err(format!( + "{}: a LIFECYCLE_METHODS entry is not a pair of names", + path.display() + ) + .into()); + } + } + } + seen = true; + } + if !seen { + return Err(format!("{}: LIFECYCLE_METHODS is missing", path.display()).into()); + } + Ok(found) +} + /// The names routing does not resolve, read from the runtime that refuses /// them: its registration points, plus the two lifecycle services. A missing /// list is an error, never an empty one. From c97d9718b677b1ff3bf8520134a5e81b2f827b45 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:19:24 +0800 Subject: [PATCH 18/37] test(app-server): prove the load path on a Session Agents admitted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A minimal host serves with the offline model catalog and no product home, so `sessions.launch` works and the Session is admitted by Agents: `crates/dim-app-server/tests/routed_call_flow.rs` launches one, answers a face call, releases it with `Session::unload_if_idle` (it leaves the Agent), and then `sessions.call` restores it — D5's "load and hold for the call" measured on the production path rather than on a Session created behind Agents' back. While the Agents index is being replaced a routed call answers `session_reloading` (the one transient answer, so a caller retries), pinned by a test of the mapping. Refs #2015 Refs #2127 --- crates/dim-app-server/Cargo.toml | 4 + crates/dim-app-server/src/agents/sessions.rs | 12 ++ .../src/agents/sessions/tests.rs | 9 + .../dim-app-server/tests/routed_call_flow.rs | 159 ++++++++++++++++++ 4 files changed, 184 insertions(+) create mode 100644 crates/dim-app-server/tests/routed_call_flow.rs diff --git a/crates/dim-app-server/Cargo.toml b/crates/dim-app-server/Cargo.toml index bcaf8bcf15..a65e520fe5 100644 --- a/crates/dim-app-server/Cargo.toml +++ b/crates/dim-app-server/Cargo.toml @@ -18,6 +18,10 @@ path = "tests/provider_memory_flow.rs" name = "app_server_flow" path = "tests/app_server_flow.rs" +[[test]] +name = "routed_call_flow" +path = "tests/routed_call_flow.rs" + [dependencies] dim-codemode.workspace = true dim-agent-runtime.workspace = true diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index b7028e4955..bfc0a34194 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -877,6 +877,9 @@ impl HostDispatch for SessionsService { let args = args.json(); let operation = async move { match (index, args) { + // A routed call to a Session whose index is being replaced is + // transient: the caller retries the Session it knows (#2127). + (None, _) if method == "call" => Err(index_reloading()), (None, _) => Err(SessionsError::reloading("the Agents index")), (_, Err(error)) => Err(SessionsError::rejected(error.to_string())), (Some(index), Ok(args)) => call(&index, &method, args, row.as_ref()).await, @@ -886,6 +889,15 @@ impl HostDispatch for SessionsService { } } +/// What a routed call answers while the Agents index is being replaced: the +/// one transient answer, so a caller retries instead of treating the Session as +/// gone. +fn index_reloading() -> SessionsError { + SessionsError::SessionReloading { + message: "the Agents index is reloading".into(), + } +} + /// The routing answer as this face reports it: its own kind for a target that /// could not be selected, and the owner's failure as the owner wrote it. fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { diff --git a/crates/dim-app-server/src/agents/sessions/tests.rs b/crates/dim-app-server/src/agents/sessions/tests.rs index 377076c9d3..71e3fc143e 100644 --- a/crates/dim-app-server/src/agents/sessions/tests.rs +++ b/crates/dim-app-server/src/agents/sessions/tests.rs @@ -229,3 +229,12 @@ async fn exists_answers_loaded_unloaded_closed_and_deleted() { server.shutdown(); server.join().await.unwrap(); } + +#[test] +fn a_routed_call_during_an_index_replacement_is_transient() { + use serde_json::json; + let error = super::index_reloading(); + let value = json!(error); + assert_eq!(value["code"], "session_reloading", "{value}"); + assert!(error.retryable(), "{value}"); +} diff --git a/crates/dim-app-server/tests/routed_call_flow.rs b/crates/dim-app-server/tests/routed_call_flow.rs new file mode 100644 index 0000000000..50ae787d64 --- /dev/null +++ b/crates/dim-app-server/tests/routed_call_flow.rs @@ -0,0 +1,159 @@ +//! A routed call by id against a minimal host that has only the offline model +//! catalog: Agents admits the Session, so the load-and-hold path of ADR 027 D5 +//! is the production one (#2127). + +use dim_agent_capabilities::defaults; +use dim_agent_runtime::{AgentBuilder, AgentConfig}; +use dim_app_server::{RunningServer, ServerConfig, serve}; +use rutis::Ctx; +use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, TypeKey}; +use rutis_bridge::session::{Connection, Dispatch, Endpoint, HostDispatch, Reply, Value, host_key}; +use serde_json::json; +use std::path::PathBuf; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +/// A process row that hands its context to the test, so the test speaks to the +/// assembly as a plugin of another language would. +struct Probe(Arc>); + +impl DynPlugin for Probe { + fn name(&self) -> &str { + "routed-call-probe" + } + fn injects(&self) -> Vec { + vec![host_key("sessions").erase()] + } + fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { + Box::pin(async move { + self.0.set(ctx.clone()).ok(); + Ok(Effect::Done) + }) + } +} + +struct Faces(Ctx); + +impl Dispatch for Faces { + fn invoke(&self, _: &Connection, target: &str, method: &str, args: Value) -> Reply { + self.0 + .require_at::(&host_key(target)) + .unwrap() + .invoke(method, args) + } +} + +struct Rig { + home: tempfile::TempDir, + server: RunningServer, + _host: Connection, + client: Connection, +} + +impl Rig { + async fn start() -> Self { + let home = tempfile::tempdir().unwrap(); + std::fs::set_permissions( + home.path(), + std::os::unix::fs::PermissionsExt::from_mode(0o700), + ) + .unwrap(); + let catalog = dim_agent_aimux::config::ModelConfigFile::load( + &PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../dim-agent-aimux/examples/offline.json"), + ) + .expect("the offline model catalog loads"); + let mut builder = AgentBuilder::new(AgentConfig::default()); + defaults::mock_hosts(&mut builder); + defaults::install(&mut builder); + let observed = Arc::new(OnceLock::new()); + let probe = observed.clone(); + builder.plugin(move |_| Ok(Box::new(Probe(probe.clone())) as Box)); + let server = serve( + builder, + ServerConfig { + startup_timeout: Duration::from_secs(60), + database_path: Some(home.path().join("dimcode.sqlite")), + unix_path: Some(home.path().join("native.sock")), + model_catalog: Some(Arc::new( + dim_agent_aimux::AimuxModels::from_config(catalog).expect("the catalog builds"), + )), + ..Default::default() + }, + ) + .await + .expect("the minimal host serves"); + let ctx = observed.get().expect("the probe loads").clone(); + let (a, b) = rutis_bridge::memory::pair(); + let peer = |id: &str| Endpoint::rust(rutis_bridge::channel::PeerId::new(id).unwrap()); + let host = Connection::open(a, Arc::new(Faces(ctx.clone())), peer("routed-host")).unwrap(); + let client = Connection::open(b, Arc::new(Faces(ctx)), peer("routed-client")).unwrap(); + client.ready().await.unwrap(); + Self { + home, + server, + _host: host, + client, + } + } + + async fn call(&self, method: &str, request: serde_json::Value) -> serde_json::Value { + tokio::time::timeout( + Duration::from_secs(30), + self.client + .invoke_settled("sessions", method, Value::List(vec![request.into()])) + .unwrap(), + ) + .await + .expect("the call answers") + .expect("the call is served") + .json() + .expect("a reply is data") + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_routed_call_loads_and_holds_an_admitted_session() { + let rig = Rig::start().await; + let launched = rig + .call("launch", json!({"cwd": rig.home.path().to_string_lossy()})) + .await; + let id = launched["value"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("a Session launches through Agents: {launched}")) + .to_owned(); + let before = rig + .call( + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!(before["ok"], true, "an admitted Session answers: {before}"); + let session = rig + .server + .agent() + .expect("the profile has an Agent") + .get_session(&id) + .expect("the launched Session is loaded"); + session.idle("main").await.unwrap(); + assert!( + session.unload_if_idle().await.unwrap(), + "an idle admitted Session unloads" + ); + assert!( + rig.server.agent().unwrap().get_session(&id).is_none(), + "the idle release takes the Session out of the Agent" + ); + let restored = rig + .call( + "call", + json!({"sessionId": id, "service": "sessionConfig", "method": "get"}), + ) + .await; + assert_eq!( + restored["ok"], true, + "sessions.call reloads an admitted Session (D5): {restored}" + ); + rig.server.shutdown(); + rig.server.join().await.unwrap(); +} From 921dfb7e643ac7e11b26d51f6c683c169d6df8be Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 09:34:49 +0800 Subject: [PATCH 19/37] fix(runtime): refuse the dispatcher's function-taking operations, and serialize the route error - `LIFECYCLE_METHODS` gains `dispatcher.listen` and `dispatcher.consume`: both take a function, and a routed call carries data only. The list is hand maintained, and the generator reads this same constant, so runtime and declarations agree; the fixture and `routing_flow` assert the refusal. - `RouteError` serializes, so a Session part's TypeScript caller reads the owner's structured failure (`owner { name, message, data, reloading }`) exactly as the process segment and Rust callers do. - the authoring guide and the issue record say what the code does: the durable `branch/end` takes a line out of the published set at once, so a later call answers `no_line`; a call admitted before it keeps its owner's result. Refs #2015 Refs #2127 --- .../dim-agent-capabilities/tests/routing_flow.rs | 11 +++++++++++ crates/dim-agent-runtime/src/route.rs | 15 +++++++++------ docs/typescript-plugin-authoring.md | 7 +++---- npm/branch-services.d.ts | 16 ++++++++++++++-- runtime/fixtures/branch-calls.ts | 9 ++++++++- 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 05e3be1eb3..568768cf5b 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -378,6 +378,17 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { }, "an operation that needs a caller-side cancellation is not routed" ); + assert_eq!( + scope + .line_call(LineCall::new("main", "dispatcher", "listen", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "dispatcher".into(), + method: "listen".into() + }, + "an operation that hands the caller a subscription is not routed" + ); assert_eq!( scope .call(SessionCall::new("treeCommands", "create", vec![])) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index aae71cfe3f..125c732620 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -49,7 +49,8 @@ use std::sync::{Arc, Weak}; pub type Routed = std::result::Result; /// Why a routed call did not reach a reply. -#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, thiserror::Error)] +#[serde(rename_all = "camelCase")] pub enum RouteError { /// The Session is not there, has no owner, or is closed and cannot load /// again. Only a process caller receives it; Agents loads and holds a @@ -185,11 +186,13 @@ impl SessionCall { const RELOADING: &str = "Reloading"; /// Operations a route does not resolve even though their service is a data -/// face: each takes a cancellation the caller observes through the future, or -/// hands the caller something to settle, and a routed call carries data only. -/// The generated authoring requests read this same list, so the runtime and the -/// declarations agree on what is routable. -pub const LIFECYCLE_METHODS: [(&str, &str); 4] = [ +/// face: each takes a function, or hands the caller a subscription or a +/// cancellation to settle, and a routed call carries data only. The list is +/// maintained by hand; the generated authoring requests read this same +/// constant, so the runtime and the declarations cannot disagree. +pub const LIFECYCLE_METHODS: [(&str, &str); 6] = [ + ("dispatcher", "consume"), + ("dispatcher", "listen"), ("permission", "check"), ("toolHost", "execute"), ("treeCommands", "create"), diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 3f97ebcaec..744d391f87 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -59,10 +59,9 @@ The request types are generated, so `service`, `method` and `args` are the targe a typo fails `tsc`. Nothing a call returns may be kept: the next call looks the target up again. -A line is admitted while it is published and not closing: after its durable `branch/end` it -stays reachable until its instance starts closing, and then `no_line` is final for it. A call -that was admitted keeps its owner's own result and failure, including one that arrives after -the end. Rust calls the same operations: it builds `args` from the target operation's request +A line is admitted while it is published and not closing. Its durable `branch/end` takes it +out of the published set at once, so a later call answers `no_line`, which is final for that +line; a call admitted before the end keeps its owner's own result and failure. Rust calls the same operations: it builds `args` from the target operation's request type and reads the reply as that operation's reply type. ## Available services diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 19976aed27..b5bb8a90ba 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1404,6 +1404,18 @@ export interface PartRegistry { } +/** Why a routed call did not reach a reply. */ +export type RouteError = + | /** The Session is not there, has no owner, or is closed and cannot load again. Only a process caller receives it; Agents loads and holds a Session that is merely not loaded (ADR 027 D5), so this is final. */ { noSession: string } + | /** The Session instance is closing, and so is a call to one of its lines. A Session-scoped caller ends its work; a process caller treats it as [`Self::NoSession`]. */ { sessionClosing: string } + | /** Agents is reloading and cannot take calls yet. A process caller retries later. */ { sessionReloading: string } + | /** The Session exists but cannot be loaded now: its restore failed, or the Agent that owns it is unavailable. The caller reports the reason and does not retry. */ { sessionUnavailable: { session: string; reason: string } } + | /** The Session is live but the line is closing, closed, or not one of its lines. Final for that line: no hold and no retry. */ { noLine: { session: string; line: string } } + | /** The name is not a data face a route resolves there: the assembly marks it internal, it is a mechanism registration point, or it is a scope lifecycle service. A permanent answer: the request is wrong. */ { notDataFace: { service: string } } + | /** The service is a data face a route resolves, but this operation of it is not: its call needs a cancellation or a cleanup the routed call cannot carry, so only a direct call keeps its lifetime behaviour. */ { methodNotRoutable: { service: string; method: string } } + | /** The name is a data face, but not of the scope the route reaches. */ { wrongScope: { service: string; group: string } } + | /** The owner's own failure, with the name and message it wrote; routing does not read or restate it. `reloading` is the owner's own code for "try again later", so a caller retries exactly what the owner says it may retry. */ { owner: { name: string; message: string; data?: import('./plugin.js').BridgeJsonValue | null; reloading: boolean } } + /** * One Session's own lines and data faces, provided to the Session's parts and @@ -1801,7 +1813,7 @@ export type ReservedMethodsErrorThrown = RustError<"ReservedMethodsError", "rese export type ResourceErrorThrown = RustError<"ResourceError", string, ResourceError> /** What a method returning `Err(RouteError)` throws. */ -export type RouteErrorThrown = RustError<"RouteError", "NoSession" | "SessionClosing" | "SessionReloading" | "SessionUnavailable" | "NoLine" | "NotDataFace" | "MethodNotRoutable" | "WrongScope" | "Owner", undefined> +export type RouteErrorThrown = RustError<"RouteError", "noSession" | "sessionClosing" | "sessionReloading" | "sessionUnavailable" | "noLine" | "notDataFace" | "methodNotRoutable" | "wrongScope" | "owner", RouteError> /** What a method returning `Err(SessionInstanceError)` throws. */ export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> @@ -1868,7 +1880,7 @@ export type LineFaces = { approval: Approval backgroundExec: BackgroundExec branchLine: BranchLine - dispatcher: Dispatcher + dispatcher: Omit inputQueue: InputQueue permission: Omit timeline: Timeline diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index ed749bb0d8..572679e0c4 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -2,7 +2,12 @@ // the two data operations (#2127). The request's `service`, `method` and // `args` are the target's own, so a typo fails to compile. import type { Sessions } from '../../npm/plugin.js' -import type { SessionScope } from '../../npm/branch-services.js' +import type { RouteError, SessionScope } from '../../npm/branch-services.js' + +/** A Session part reads the owner's structured failure from the routed error. */ +export function ownerFailure(error: RouteError): string | null { + return 'owner' in error ? `${error.owner.name}: ${error.owner.message}` : null +} export async function readByCalls( scope: SessionScope, @@ -48,6 +53,8 @@ void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) // @ts-expect-error a reply keeps the target method's own type. void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) +// @ts-expect-error a subscription an operation hands the caller is not routed. +void scope.lineCall({ lineId: 'main', service: 'dispatcher', method: 'listen', args: ['n', [], (_e: unknown) => {}] }) // @ts-expect-error an operation that needs a caller-side cancellation is not routed. void scope.lineCall({ lineId: 'main', service: 'wait', method: 'wait', args: [] }) // @ts-expect-error a Session service takes no lineId. From 5c1229679f252014cb5370bf68dc6eee92139b80 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 10:38:10 +0800 Subject: [PATCH 20/37] fix(runtime): one set of routing codes for both routes, and row-bound operations excluded - `sessionScope` is no longer one of the Session faces a routed call resolves: the scope resolves lines and the Session's faces, it is not one of them, so `sessionScope.call` cannot reach `sessionScope.lineCall`. The generated `SessionFaces` drops it, and the test asserts the refusal. - `uiResources.publishFile`/`withdraw` join the excluded operations: they take the calling row, which a routed call cannot carry. - `sessions.call` answers the same codes as the Session scope (`not_data_face`, `method_not_routable`, `wrong_scope`), and its `session_unavailable`/`no_line` carry `reason`/`line` instead of folding them into the message. - a replaced or stopping Agents index answers `session_reloading`, retryable, instead of a final `no_session`; a Session that starts closing while a line is selected answers `SessionClosing`. - the retired-name guard covers instance-only names (proved with `sessionConfig`), and the head comparison in `data_faces_flow` no longer assumes no fact publishes between two reads. - the guide states each route's code spelling, the direct-only operations, and who `sessionScope.call` serves. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 21 ++++++++ crates/dim-agent-runtime/src/route.rs | 31 ++++++++---- .../tests/data_faces_flow.rs | 13 +++-- crates/dim-app-server/src/agents.rs | 25 ++++++++-- crates/dim-app-server/src/agents/sessions.rs | 48 ++++++++++++++----- docs/typescript-plugin-authoring.md | 19 ++++++++ npm/branch-services.d.ts | 14 +++--- runtime/fixtures/branch-calls.ts | 2 + runtime/plugin-sdk.test.mjs | 2 +- xtask/check/src/types.rs | 4 +- xtask/src/catalog.rs | 37 ++++++++++++-- 11 files changed, 176 insertions(+), 40 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 568768cf5b..238e622c0b 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -378,6 +378,27 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { }, "an operation that needs a caller-side cancellation is not routed" ); + assert_eq!( + scope + .call(SessionCall::new("sessionScope", "lineCall", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: "sessionScope".into() + }, + "the Session's own scope is not one of the faces it resolves" + ); + assert_eq!( + scope + .call(SessionCall::new("uiResources", "publishFile", vec![])) + .await + .unwrap_err(), + RouteError::MethodNotRoutable { + service: "uiResources".into(), + method: "publishFile".into() + }, + "an operation bound to the calling row is direct-only" + ); assert_eq!( scope .line_call(LineCall::new("main", "dispatcher", "listen", vec![])) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 125c732620..bdbdb4102e 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -190,15 +190,27 @@ const RELOADING: &str = "Reloading"; /// cancellation to settle, and a routed call carries data only. The list is /// maintained by hand; the generated authoring requests read this same /// constant, so the runtime and the declarations cannot disagree. -pub const LIFECYCLE_METHODS: [(&str, &str); 6] = [ +pub const LIFECYCLE_METHODS: [(&str, &str); 8] = [ ("dispatcher", "consume"), ("dispatcher", "listen"), ("permission", "check"), ("toolHost", "execute"), ("treeCommands", "create"), + ("uiResources", "publishFile"), + ("uiResources", "withdraw"), ("wait", "wait"), ]; +/// The Session's own scope resolves a line and the Session's faces; it is not +/// one of the faces a routed call resolves, so `sessionScope.call` cannot reach +/// `sessionScope.lineCall`. Session parts inject this Session's services +/// directly instead. +const NOT_CALLABLE: [&str; 1] = ["sessionScope"]; + +/// The scope lifecycle services: the runtime provides them, and a route does +/// not hand them to a caller. +const LIFECYCLE_SERVICES: [&str; 2] = ["sessionLifecycle", "branchLifecycle"]; + const REGISTRATION_POINTS: [&str; 5] = [ "sessionMethods", "toolRegistry", @@ -241,9 +253,13 @@ impl SessionScope { fn line_context(&self, line_id: &str) -> Routed> { let session = self.live()?; let line = session.line(line_id); - // A Session that started closing while the line was being selected - // answers `SessionClosing`: its lines close with it. - self.live()?; + // A Session that started closing while the line was being selected — + // or whose loaded scope went with that close — answers `SessionClosing`: + // its lines close with it. + match self.live() { + Ok(_) => {} + Err(closing) => return Err(closing), + } line.ok_or_else(|| RouteError::NoLine { session: self.session_id.clone(), line: line_id.to_owned(), @@ -326,12 +342,9 @@ pub(crate) fn face( method: method.into(), }); } - let lifecycle = [ - names::name_of::(), - names::name_of::(), - ]; if REGISTRATION_POINTS.contains(&service) - || lifecycle.iter().any(|name| name == service) + || LIFECYCLE_SERVICES.contains(&service) + || (group == SESSION_GROUP && NOT_CALLABLE.contains(&service)) || faces.reason(service).is_some() { return Err(RouteError::NotDataFace { diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index 2e18d7ceea..edfd574f13 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -813,6 +813,10 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can face["ok"], true, "a Session-scope face answers through Agents: {face}" ); + // The line's head may advance between the two reads (a fact publishes in + // between), so the routed answer must lie in the window the two direct + // reads bound, not equal one of them. + let before = session.sequence("main").unwrap(); let line = rig .call( "sessions", @@ -820,10 +824,11 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can json!({"sessionId": id, "lineId": "main", "service": "timeline", "method": "sequence"}), ) .await; - assert_eq!( - line["value"], - json!(session.sequence("main").unwrap()), - "{line}" + let after = session.sequence("main").unwrap(); + let routed = line["value"].as_u64().unwrap_or_else(|| panic!("{line}")); + assert!( + (before..=after).contains(&routed), + "the routed head {routed} lies between {before} and {after}: {line}" ); let unknown = rig .call( diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 8f9d26956e..917c8b9e97 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1649,8 +1649,18 @@ impl AgentIndex { request: crate::agents::sessions::CallRequest, ) -> std::result::Result { let id = request.session_id.clone(); + // A replaced or stopping index is transient: the caller retries the + // Session it knows against the next generation (#2127). + if self.stopping.is_cancelled() { + return Err(RouteError::SessionReloading(id)); + } let used = self.acquire(&id).await.map_err(|error| match error { AgentError::Reloading(_) => RouteError::SessionReloading(id.clone()), + // The index stopped between the check above and the acquire: the + // same transient answer, not a missing Session. + AgentError::Closed(closed) if self.stopping.is_cancelled() => { + RouteError::SessionReloading(closed) + } AgentError::Closed(_) => RouteError::NoSession(id.clone()), error => RouteError::SessionUnavailable { session: id.clone(), @@ -1663,9 +1673,18 @@ impl AgentIndex { } let scope = session .session_service::() - .map_err(|error| RouteError::SessionUnavailable { - session: id.clone(), - reason: error.to_string(), + .map_err(|error| match error { + _ if session.is_closing() => RouteError::SessionClosing(id.clone()), + AgentError::Reloading(_) => RouteError::Owner { + name: "AgentError".into(), + message: error.to_string(), + data: None, + reloading: true, + }, + error => RouteError::SessionUnavailable { + session: id.clone(), + reason: error.to_string(), + }, })?; match request.line_id { Some(line_id) => { diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index bfc0a34194..ccdd507b74 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -296,19 +296,36 @@ pub struct StopRequest { pub enum SessionsError { #[error("{message}")] Rejected { message: String }, - /// A routed call could not select its target: `no_session`, - /// `session_closing`, `session_reloading`, `session_unavailable` or - /// `no_line`. Only `session_reloading` is retryable. + /// A routed call could not select its target. These are the same codes a + /// Session's own scope answers: `no_session`, `session_closing`, + /// `session_reloading` (retryable), `session_unavailable`, `no_line`, + /// `not_data_face`, `method_not_routable` and `wrong_scope`. #[error("{message}")] NoSession { message: String }, #[error("{message}")] SessionClosing { message: String }, #[error("{message}")] SessionReloading { message: String }, + /// The Session exists but cannot load; `reason` says why. #[error("{message}")] - SessionUnavailable { message: String }, + SessionUnavailable { message: String, reason: String }, + /// The line is not the Session's, or it is gone; `line` names it. #[error("{message}")] - NoLine { message: String }, + NoLine { message: String, line: String }, + #[error("{message}")] + NotDataFace { message: String, service: String }, + #[error("{message}")] + MethodNotRoutable { + message: String, + service: String, + method: String, + }, + #[error("{message}")] + WrongScope { + message: String, + service: String, + group: String, + }, /// The target owner's own failure, with the name and message it wrote and /// whether the owner says it may be retried. #[error("{message}")] @@ -907,8 +924,10 @@ fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { RouteError::NoSession(_) => SessionsError::NoSession { message }, RouteError::SessionClosing(_) => SessionsError::SessionClosing { message }, RouteError::SessionReloading(_) => SessionsError::SessionReloading { message }, - RouteError::SessionUnavailable { .. } => SessionsError::SessionUnavailable { message }, - RouteError::NoLine { .. } => SessionsError::NoLine { message }, + RouteError::SessionUnavailable { reason, .. } => { + SessionsError::SessionUnavailable { message, reason } + } + RouteError::NoLine { line, .. } => SessionsError::NoLine { message, line }, RouteError::Owner { name, data, @@ -920,10 +939,17 @@ fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { data, retryable: reloading, }, - RouteError::MethodNotRoutable { .. } => SessionsError::Rejected { message }, - RouteError::NotDataFace { .. } | RouteError::WrongScope { .. } => { - SessionsError::Rejected { message } - } + RouteError::NotDataFace { service } => SessionsError::NotDataFace { message, service }, + RouteError::MethodNotRoutable { service, method } => SessionsError::MethodNotRoutable { + message, + service, + method, + }, + RouteError::WrongScope { service, group } => SessionsError::WrongScope { + message, + service, + group, + }, } } diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 744d391f87..eb0bbfcc72 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -59,6 +59,25 @@ The request types are generated, so `service`, `method` and `args` are the targe a typo fails `tsc`. Nothing a call returns may be kept: the next call looks the target up again. +The two entries name a failure with different spellings. `sessions.call` answers the +`sessions` envelope with snake_case codes — `no_session`, `session_closing`, +`session_reloading`, `session_unavailable`, `no_line`, `not_data_face`, +`method_not_routable`, `wrong_scope`, and `routed` for the owner's own failure. +`sessionScope.lineCall`/`call` throw a `RouteError` whose variants carry the same kinds in +camelCase (`noSession`, `sessionClosing`, `sessionReloading`, `sessionUnavailable`, +`noLine`, `notDataFace`, `methodNotRoutable`, `wrongScope`, `owner`), and `owner` keeps the +owner's `name`, `message`, `data` and `reloading`. Only `session_reloading`/`sessionReloading` +and an owner failure that says it reloads may be retried. + +Operations that need a function, a subscription the caller must settle, or the calling row, +are not routed: call them on an injected service directly. That covers +`dispatcher.listen`/`consume`, `permission.check`, `toolHost.execute`, +`treeCommands.create`, `uiResources.publishFile`/`withdraw` and `wait.wait`. + +`sessionScope.call` serves the caller that selected a Session by id; a Session part calls its +own Session's services through injection as before. The Session's own scope is not one of the +faces a routed call resolves. + A line is admitted while it is published and not closing. Its durable `branch/end` takes it out of the published set at once, so a later call answers `no_line`, which is final for that line; a call admitted before the end keeps its owner's own result and failure. Rust calls the same operations: it builds `args` from the target operation's request diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index b5bb8a90ba..dc245de955 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1473,11 +1473,14 @@ export type PermissionState = { /** A Session service failure; generated exports throw this serde value. */ export type SessionsError = | { code: "rejected"; message: string } - | /** A routed call could not select its target: `no_session`, `session_closing`, `session_reloading`, `session_unavailable` or `no_line`. Only `session_reloading` is retryable. */ { code: "no_session"; message: string } + | /** A routed call could not select its target. These are the same codes a Session's own scope answers: `no_session`, `session_closing`, `session_reloading` (retryable), `session_unavailable`, `no_line`, `not_data_face`, `method_not_routable` and `wrong_scope`. */ { code: "no_session"; message: string } | { code: "session_closing"; message: string } | { code: "session_reloading"; message: string } - | { code: "session_unavailable"; message: string } - | { code: "no_line"; message: string } + | /** The Session exists but cannot load; `reason` says why. */ { code: "session_unavailable"; message: string; reason: string } + | /** The line is not the Session's, or it is gone; `line` names it. */ { code: "no_line"; message: string; line: string } + | { code: "not_data_face"; message: string; service: string } + | { code: "method_not_routable"; message: string; service: string; method: string } + | { code: "wrong_scope"; message: string; service: string; group: string } | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; message: string; data?: import('./plugin.js').BridgeJsonValue | null; retryable: boolean } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } @@ -1819,7 +1822,7 @@ export type RouteErrorThrown = RustError<"RouteError", "noSession" | "sessionClo export type SessionInstanceErrorThrown = RustError<"SessionInstanceError", "Create" | "NotReady" | "Cleanup", undefined> /** What a method returning `Err(SessionsError)` throws. */ -export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "no_session" | "session_closing" | "session_reloading" | "session_unavailable" | "no_line" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> +export type SessionsErrorThrown = RustError<"SessionsError", "rejected" | "no_session" | "session_closing" | "session_reloading" | "session_unavailable" | "no_line" | "not_data_face" | "method_not_routable" | "wrong_scope" | "routed" | "agent_unknown" | "session_closed" | "branch_missing" | "branch_ended" | "reloading" | "future_sequence" | "ambiguous" | "publication_unknown" | "failed", SessionsError> /** What a method returning `Err(TaskError)` throws. */ export type TaskErrorThrown = RustError<"TaskError", "read" | "unknown" | "closed", TaskError> @@ -1898,11 +1901,10 @@ export type SessionFaces = { sessionIdentity: SessionIdentity sessionLanguage: SessionLanguage sessionLoader: SessionLoader - sessionScope: SessionScope skillsConfig: SkillsConfig toolHost: Omit treeCommands: Omit - uiResources: UiResources + uiResources: Omit } /** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */ diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index 572679e0c4..3437e6e0fd 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -53,6 +53,8 @@ void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) // @ts-expect-error a reply keeps the target method's own type. void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) +// @ts-expect-error an operation bound to the calling row is direct-only. +void scope.call({ service: 'uiResources', method: 'publishFile', args: [{}] }) // @ts-expect-error a subscription an operation hands the caller is not routed. void scope.lineCall({ lineId: 'main', service: 'dispatcher', method: 'listen', args: ['n', [], (_e: unknown) => {}] }) // @ts-expect-error an operation that needs a caller-side cancellation is not routed. diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index fd0a6dd873..e41764ad34 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -137,7 +137,7 @@ const preset: 'read-only' | 'workspace-write' | 'full-access' = defaults.preset; const allowed: string[] = livePolicy.allowedTools; const disallowed: string[] = defaults.disallowedTools; declare const permissionError: SessionsErrorThrown; -const permissionCode: 'rejected' | 'routed' | 'no_session' | 'session_closing' | 'session_reloading' | 'session_unavailable' | 'no_line' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; +const permissionCode: 'rejected' | 'routed' | 'no_session' | 'session_closing' | 'session_reloading' | 'session_unavailable' | 'no_line' | 'not_data_face' | 'method_not_routable' | 'wrong_scope' | 'agent_unknown' | 'session_closed' | 'branch_missing' | 'branch_ended' | 'reloading' | 'future_sequence' | 'ambiguous' | 'publication_unknown' | 'failed' = permissionError.code; void permissionVersion; void preset; void allowed; void disallowed; void permissionCode; // @ts-expect-error permission reads require a branch identity. void permissions.permission({ sessionId: 'session' }); diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 90780746ef..a9742a0c71 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -29,7 +29,9 @@ fn calls(root: &Path, services: &str) -> Result { let mut session = Vec::new(); let mut line = Vec::new(); for (name, group) in registered(root)? { - if unroutable.contains(&name) { + // The Session's own scope resolves a line and the Session's faces; it + // is not one of the faces a routed call resolves. + if unroutable.contains(&name) || name == "sessionScope" { continue; } let Some(ty) = declared.iter().find(|ty| catalog_name(ty) == name).copied() else { diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index a39c24fece..46ebc75b22 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -101,11 +101,17 @@ pub(super) async fn collect() -> Result
{ /// (`xtask/access-layer.json`'s `removed` list). fn retired(root: &std::path::Path, catalog: &ServiceCatalog) -> Result<()> { let layer = xtask_check::access::load(root)?; - let back: Vec<&String> = layer - .removed - .iter() - .filter(|name| catalog.key(name).is_some() || catalog.is_shared(name)) - .collect(); + // A catalog name is known at the process, as a shared name, or inside an + // instance group: `key_in` answers `OutsideInstance` for the last. + let known = |name: &str| { + catalog.key(name).is_some() + || catalog.is_shared(name) + || matches!( + catalog.key_in(name, &rutis_loader::resolve::Build::default()), + Err(rutis_loader::LoaderError::OutsideInstance { .. }) + ) + }; + let back: Vec<&String> = layer.removed.iter().filter(|name| known(name)).collect(); if !back.is_empty() { return Err(format!( "{}: retired service names are registered again: {back:?}", @@ -614,3 +620,24 @@ mod face_tests { assert!(face("x", false, false, Some("hotpath")).is_err()); } } + +#[cfg(test)] +mod retired_tests { + use super::*; + + #[test] + fn a_retired_instance_name_is_refused() { + let directory = std::env::temp_dir().join(format!("dim-retired-{}", std::process::id())); + std::fs::create_dir_all(directory.join("xtask")).unwrap(); + // `sessionConfig` is registered inside the Session group only. + std::fs::write( + directory.join("xtask/access-layer.json"), + r#"{"allow": [], "removed": ["sessionConfig"]}"#, + ) + .unwrap(); + let catalog = dim_agent_runtime::names::catalog(); + let error = retired(&directory, &catalog).expect_err("an instance name is covered"); + assert!(error.to_string().contains("sessionConfig"), "{error}"); + let _ = std::fs::remove_dir_all(&directory); + } +} From aca1f66cb16b32c564999f02e50cdf8db5eeeb32 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 10:59:30 +0800 Subject: [PATCH 21/37] feat(xtask): derive the unroutable operations from the service signatures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `LIFECYCLE_METHODS` is no longer a hand-written list nobody checks: `xtask` reads every `#[rutis::service]` block, finds the operations whose parameters are the calling row, a cancellation or a callback, keeps those the declarations export in a routable scope, and fails when the two disagree in either direction — an operation that cannot cross but is not listed, or a listed one whose signature can. Proved both ways: dropping `uiResources.withdraw` from the list fails with "not listed: [uiResources.withdraw]", and adding `sessionConfig.get` fails with "listed but routable: [sessionConfig.get]". Refs #2015 Refs #2127 --- docs/typescript-plugin-authoring.md | 8 +- xtask/check/src/types.rs | 200 ++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 4 deletions(-) diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index eb0bbfcc72..d74cca36ac 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -69,10 +69,10 @@ camelCase (`noSession`, `sessionClosing`, `sessionReloading`, `sessionUnavailabl owner's `name`, `message`, `data` and `reloading`. Only `session_reloading`/`sessionReloading` and an owner failure that says it reloads may be retried. -Operations that need a function, a subscription the caller must settle, or the calling row, -are not routed: call them on an injected service directly. That covers -`dispatcher.listen`/`consume`, `permission.check`, `toolHost.execute`, -`treeCommands.create`, `uiResources.publishFile`/`withdraw` and `wait.wait`. +Operations whose signature cannot cross languages — a callback, a cancellation, or the +calling row — are not routed: call them on an injected service directly. `xtask -- check` +derives them from the service signatures and fails when the runtime's refusal list and the +signatures disagree, so this stays true as operations are added. `sessionScope.call` serves the caller that selected a Session by id; a Session part calls its own Session's services through injection as before. The Session's own scope is not one of the diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index a9742a0c71..ff2b744251 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -48,6 +48,43 @@ fn calls(root: &Path, services: &str) -> Result { line.sort(); line.dedup(); let refused = lifecycle(root)?; + // The list and the signatures must name the same operations: a signature + // that cannot cross languages but is missing fails, and so does a listed + // operation whose signature can. + let groups = registered(root)?; + let derived: Vec<(String, String)> = derived_lifecycle(root)? + .into_iter() + // Only a service a route resolves, and only an operation the file + // declares, is part of that surface. + .filter(|(service, method)| { + // Only a Session or branch face crosses through a route at all. + let in_scope = groups + .iter() + .any(|(name, group)| name == service && (group == "session" || group == "branch")); + in_scope + && !unroutable.contains(service) + && service != "sessionScope" + && declares_method(services, service, method) + }) + .collect(); + let missing: Vec = derived + .iter() + .filter(|pair| !refused.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + let extra: Vec = refused + .iter() + .filter(|pair| !derived.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + if !missing.is_empty() || !extra.is_empty() { + return Err(format!( + "crates/dim-agent-runtime/src/route.rs: LIFECYCLE_METHODS does not match the service signatures; not listed: [{}], listed but routable: [{}]", + missing.join(", "), + extra.join(", ") + ) + .into()); + } let faces = |items: &[(String, String)], name: &str| { let mut text = format!("export type {name} = {{\n"); for (member, ty) in items { @@ -327,6 +364,169 @@ fn lifecycle(root: &Path) -> Result> { Ok(found) } +/// The operations a catalog's own method signatures say a routed call cannot +/// carry: a parameter that is the calling row, a cancellation, or a callback. +/// Read from the `#[rutis::service]` blocks themselves, so a new operation of +/// that kind cannot slip past the list the runtime refuses. +fn derived_lifecycle(root: &Path) -> Result> { + let mut found = Vec::new(); + for entry in std::fs::read_dir(root.join("crates"))? { + let directory = entry?.path().join("src"); + if !directory.is_dir() { + continue; + } + let mut files = Vec::new(); + sources(&mut files, &directory)?; + for file in files { + let ast = syn::parse_file(&std::fs::read_to_string(&file)?)?; + service_blocks(&ast.items, &mut found); + } + } + found.sort(); + found.dedup(); + Ok(found) +} + +fn service_blocks(items: &[syn::Item], found: &mut Vec<(String, String)>) { + for item in items { + match item { + syn::Item::Mod(module) => { + if let Some((_, items)) = &module.content { + service_blocks(items, found); + } + } + syn::Item::Impl(block) if block.attrs.iter().any(is_service) => { + let service = type_name(&block.self_ty); + for item in &block.items { + let syn::ImplItem::Fn(function) = item else { + continue; + }; + if function + .attrs + .iter() + .any(|attr| is_service(attr) && skip_argument(attr)) + { + continue; + } + let carried = function.sig.inputs.iter().any(|input| { + let syn::FnArg::Typed(typed) = input else { + return false; + }; + carries_lifecycle(&typed.ty) + }); + if carried { + found.push(( + catalog_name(&service), + camel(&function.sig.ident.to_string()), + )); + } + } + } + _ => {} + } + } +} + +/// Whether a parameter type is one a routed call cannot carry: the calling +/// row, a cancellation, or a callback. +fn carries_lifecycle(ty: &syn::Type) -> bool { + match ty { + syn::Type::Reference(reference) => carries_lifecycle(&reference.elem), + syn::Type::Path(path) => { + let Some(last) = path.path.segments.last() else { + return false; + }; + matches!( + last.ident.to_string().as_str(), + "Ctx" | "CancelledFn" | "CancellationToken" + ) || match &last.arguments { + syn::PathArguments::AngleBracketed(arguments) => { + arguments.args.iter().any(|argument| match argument { + syn::GenericArgument::Type(ty) => carries_lifecycle(ty), + _ => false, + }) + } + _ => false, + } + } + syn::Type::TraitObject(object) => object.bounds.iter().any(|bound| { + matches!(bound, syn::TypeParamBound::Trait(bound) + if bound.path.segments.last().is_some_and(|segment| segment.ident == "Fn")) + }), + _ => false, + } +} + +/// Whether the file declares `method` on `service`'s interface. +fn declares_method(services: &str, service: &str, method: &str) -> bool { + let typed = services + .lines() + .filter_map(|line| { + line.strip_prefix("export interface ") + .or_else(|| line.strip_prefix("export type ")) + .and_then(|rest| rest.split([' ', '<', '{', '=']).next()) + }) + .find(|ty| catalog_name(ty) == service); + let Some(typed) = typed else { + return false; + }; + let start = match services.find(&format!("export interface {typed} {{")) { + Some(start) => start, + None => return false, + }; + services[start..] + .lines() + .take_while(|line| *line != "}") + .any(|line| line.trim_start().starts_with(&format!("{method}("))) +} + +/// `#[service]`, `#[service(skip)]` or their `rutis::` spellings. +fn is_service(attr: &syn::Attribute) -> bool { + let path = attr.path(); + let segments: Vec = path + .segments + .iter() + .map(|segment| segment.ident.to_string()) + .collect(); + matches!(segments.as_slice(), [service] if service == "service") + || matches!(segments.as_slice(), [root, service] if root == "rutis" && service == "service") +} + +fn skip_argument(attr: &syn::Attribute) -> bool { + attr.parse_args::() + .is_ok_and(|argument| argument == "skip") +} + +/// The last path segment of a type. +fn type_name(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(path) => path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()) + .unwrap_or_default(), + _ => String::new(), + } +} + +/// The name a method crosses as: `publish_file` is `publishFile`. +fn camel(ident: &str) -> String { + let mut camel = String::new(); + for (index, part) in ident.split('_').enumerate() { + if index == 0 { + camel += part; + continue; + } + let mut chars = part.chars(); + if let Some(first) = chars.next() { + camel += &first.to_uppercase().collect::(); + camel += chars.as_str(); + } + } + camel +} + /// The names routing does not resolve, read from the runtime that refuses /// them: its registration points, plus the two lifecycle services. A missing /// list is an error, never an empty one. From c5883860dd06bdb6062a8b173b899733ebc10c94 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 11:14:50 +0800 Subject: [PATCH 22/37] chore(xtask): record the two access-layer entries main brought in `BranchLifecycle::opening_budget` (a service-skip) and `BranchLifecycle::admit_opening_with` (a Rust-only method) come from main (#1997/#2198 era, `fbd65fa82` and `b802a3f7d`), not from this branch; they are in the allowlist now so the check can run against the merged tree. Entries: 171 -> 173, both from main. Refs #2015 Refs #2127 --- xtask/access-layer.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/xtask/access-layer.json b/xtask/access-layer.json index 6173b1285b..c397d34865 100644 --- a/xtask/access-layer.json +++ b/xtask/access-layer.json @@ -560,11 +560,21 @@ "file": "crates/dim-agent-runtime/src/config.rs", "item": "BranchLifecycle::admit_opening" }, + { + "kind": "rust-only-method", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::admit_opening_with" + }, { "kind": "rust-only-method", "file": "crates/dim-agent-runtime/src/config.rs", "item": "BranchLifecycle::finish_opening" }, + { + "kind": "service-skip", + "file": "crates/dim-agent-runtime/src/config.rs", + "item": "BranchLifecycle::opening_budget" + }, { "kind": "service-skip", "file": "crates/dim-agent-runtime/src/config.rs", From 45313bd9cf990020932af99c75deb4cddce7967b Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 11:23:35 +0800 Subject: [PATCH 23/37] test(app-server): observe a retryable answer across an Agents restart `RunningServer::restart("Agents")` reloads the row the routed call needs, so a test can hold the window open: the minimal host launches a Session, restarts Agents while calls are in flight, and asserts at least one `session_reloading` that says `retryable`, then a retry that answers. Measured 7-8 transient answers out of 150 calls per run. Refs #2015 Refs #2127 --- .../dim-app-server/tests/routed_call_flow.rs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/crates/dim-app-server/tests/routed_call_flow.rs b/crates/dim-app-server/tests/routed_call_flow.rs index 50ae787d64..00f80de08e 100644 --- a/crates/dim-app-server/tests/routed_call_flow.rs +++ b/crates/dim-app-server/tests/routed_call_flow.rs @@ -157,3 +157,48 @@ async fn a_routed_call_loads_and_holds_an_admitted_session() { rig.server.shutdown(); rig.server.join().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_call_during_an_agents_restart_is_retryable() { + let rig = Rig::start().await; + let launched = rig + .call("launch", json!({"cwd": rig.home.path().to_string_lossy()})) + .await; + let id = launched["value"]["sessionId"] + .as_str() + .unwrap_or_else(|| panic!("a Session launches through Agents: {launched}")) + .to_owned(); + let call = json!({"sessionId": id, "service": "sessionConfig", "method": "get"}); + let calls = async { + let mut transient = 0usize; + let mut answered = 0usize; + for _ in 0..150 { + let reply = rig.call("call", call.clone()).await; + if reply["error"]["code"] == "session_reloading" { + transient += 1; + assert_eq!(reply["error"]["retryable"], true, "{reply}"); + } else if reply["ok"] == true { + answered += 1; + } + } + (transient, answered) + }; + let ((transient, answered), restarted) = tokio::join!(calls, async { + tokio::time::sleep(Duration::from_millis(20)).await; + rig.server.restart("Agents").await + }); + restarted.expect("Agents restarts"); + println!("transient={transient} answered={answered}"); + assert!( + transient > 0, + "a call during the restart answers a retryable session_reloading: transient={transient} answered={answered}" + ); + let retried = rig.call("call", call.clone()).await; + assert_eq!( + retried["ok"], true, + "the retry after the restart answers: {retried}" + ); + println!("transient={transient} answered={answered}"); + rig.server.shutdown(); + rig.server.join().await.unwrap(); +} From b500e09200741c92d98a648f61ddba07fda2f3ce Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 11:32:00 +0800 Subject: [PATCH 24/37] fix(runtime): answer SessionClosing when the scope's Session closes mid-call Also drop the stale method count from the authoring guide, and state in the contract page that the two surfaces spell the same failure differently. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/route.rs | 10 +++++++++- docs/design/contracts/runtime-owner-operations.md | 5 ++++- docs/typescript-plugin-authoring.md | 2 +- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index bdbdb4102e..e1489316fd 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -278,7 +278,15 @@ impl SessionScope { let session = self.live()?; let (catalog, faces) = session.reach(); face(catalog, faces, &call.service, &call.method, SESSION_GROUP)?; - let loaded = session.loaded().map_err(owner)?; + let loaded = session.loaded().map_err(|error| { + // The loaded scope goes away when the Session closes, so that + // answer wins over the owner's wrapper. + if session.closing.is_cancelled() { + RouteError::SessionClosing(self.session_id.clone()) + } else { + owner(error) + } + })?; call_face( &loaded.ctx, loaded.scope.instance, diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 8d3b93c2f0..b88e430e00 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -37,7 +37,10 @@ owner's face, and the owner of the line's index resolves it ([#2127](https://github.com/arcships/dim/issues/2127), [ADR 027](../../adr/027-cross-scope-access-by-id.md)): `sessionScope.lineCall` reaches a line of the caller's own Session, `sessions.call` a Session and a line of it for the -process, and both pass the owner's arguments, reply and error through. Agents loads the +process, and both pass the owner's arguments, reply and error through. The two surfaces spell +the same failure differently: the `sessions` envelope answers snake_case codes, and a Session +part's scope throws `RouteError`, whose variants are camelCase and whose owner variant carries +the owner's name, message, data and reloading flag. Agents loads the Session for the call and holds it while it runs (ADR 027 D5). A target that cannot be selected answers `no_session`, `session_closing`, `session_reloading` (retry later), `session_unavailable` (report the reason) or `no_line` (final for that line), before the diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index d74cca36ac..0027538533 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -88,7 +88,7 @@ type and reads the reply as that operation's reply type. | Need | Service and scope | Availability | | --- | --- | --- | | Persist a process plugin's own data | `pluginFiles`, process | Implemented when the host supplies an authorized product root and provisions parent directories; use its native transactions and lifecycle scope. | -| Start or drive another Session | `sessions`, process | Implemented by Agents; all nine methods are typed. `call({sessionId, lineId?, service, method, args})` reaches a Session's or a line's data face by id ([Calling a Session or line by id](#calling-a-session-or-line-by-id)). | +| Start or drive another Session | `sessions`, process | Implemented by Agents; every method is typed. `call({sessionId, lineId?, service, method, args})` reaches a Session's or a line's data face by id ([Calling a Session or line by id](#calling-a-session-or-line-by-id)). | | Publish events to subscribed branches | `eventHub`, process | Implemented by EventHub: `declare` and `publish`, served to the calling row. Inject it: the row loads only while EventHub runs and declares at `apply`. | | Read current branch permissions or host defaults | `sessionPermissions`, process | Generated from Agents: `permission({sessionId, branchId})` and `permissionDefaults({})`. | | Read or set a Session's title | `sessionMetadata`, process | Implemented by SessionStore: `read` and the revision-checked `setTitle` ([title metadata](design/appserver/session-title-metadata.md)). SessionTitle is the title's one writer; other plugins only read. | From b98e745f974e57462cd6befe73af03b6b114bb1b Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 12:27:48 +0800 Subject: [PATCH 25/37] fix(app-server): keep the routed-call test on unix, and prove the derivation - `routed_call_flow` is `#![cfg(unix)]` (a Unix socket host) and says so; Windows never builds it. - `npm/plugin.d.ts`'s `SessionsError` is the generated union again, so a caller reads `reason`, `line`, `service`, `name` and `data` instead of casting. - the guide, and the PR, state the real admission cutoff: a running line that ended a tool call stays selectable until its turn ends; the turn's durable `branch/end` is what answers `no_line` afterwards. - the signature derivation has unit tests, and its documented limits name the shapes it does not recognize (`impl Fn`, a bare `fn` pointer, other aliases). Refs #2015 Refs #2127 --- .../dim-app-server/tests/routed_call_flow.rs | 5 ++ docs/typescript-plugin-authoring.md | 9 ++- npm/plugin.d.ts | 4 +- xtask/check/src/types.rs | 77 +++++++++++++++++++ 4 files changed, 91 insertions(+), 4 deletions(-) diff --git a/crates/dim-app-server/tests/routed_call_flow.rs b/crates/dim-app-server/tests/routed_call_flow.rs index 00f80de08e..06010f5435 100644 --- a/crates/dim-app-server/tests/routed_call_flow.rs +++ b/crates/dim-app-server/tests/routed_call_flow.rs @@ -1,6 +1,11 @@ +#![cfg(unix)] //! A routed call by id against a minimal host that has only the offline model //! catalog: Agents admits the Session, so the load-and-hold path of ADR 027 D5 //! is the production one (#2127). +//! +//! Unix only: the host listens on a Unix socket. `scripts/test-windows-native.mjs` +//! compiles `dim-cli --lib` and the two flow targets it names, so Windows never +//! builds this file. use dim_agent_capabilities::defaults; use dim_agent_runtime::{AgentBuilder, AgentConfig}; diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 0027538533..90d28b2be1 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -78,9 +78,12 @@ signatures disagree, so this stays true as operations are added. own Session's services through injection as before. The Session's own scope is not one of the faces a routed call resolves. -A line is admitted while it is published and not closing. Its durable `branch/end` takes it -out of the published set at once, so a later call answers `no_line`, which is final for that -line; a call admitted before the end keeps its owner's own result and failure. Rust calls the same operations: it builds `args` from the target operation's request +A line is admitted while it is published and not closing. A running line that ends a tool call +commits that batch but stays selectable until its turn ends, so a call placed between the two +still reaches its owner; the turn's durable `branch/end` is what takes the line out of the +published set, and from then on a new call answers `no_line`, which is final for that line. A +call admitted before the end keeps its owner's own result and failure, including one that +arrives after it. Rust calls the same operations: it builds `args` from the target operation's request type and reads the reply as that operation's reply type. ## Available services diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 50ce42c995..1dcbf36ade 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -280,7 +280,9 @@ export type WithdrawReply = { status: 'deleted'; sequence: number } | { status: export interface StopRequest extends SessionRef { reason?: string | null } export interface SequenceReply { sequence: number } export type SessionsErrorCode = import('./branch-services.js').SessionsErrorThrown['code']; -export interface SessionsError { code: SessionsErrorCode; message: string; retryable: boolean } +/** The failure a `sessions` call reports: the generated union, so each code carries + * the details the server sends (`reason`, `line`, `service`, `name`, `data`). */ +export type SessionsError = import('./branch-services.js').SessionsError; export type SessionsResult = { ok: true; value: T } | { ok: false; error: SessionsError }; /** Process service `sessions`; these methods are not terminal RPC methods. */ diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index ff2b744251..679ee0dc28 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -368,6 +368,13 @@ fn lifecycle(root: &Path) -> Result> { /// carry: a parameter that is the calling row, a cancellation, or a callback. /// Read from the `#[rutis::service]` blocks themselves, so a new operation of /// that kind cannot slip past the list the runtime refuses. +/// +/// What it recognizes: a `Ctx` or a reference to one, the `CancelledFn` and +/// `CancellationToken` aliases, and `dyn Fn(..)` behind `Arc` or a reference. +/// What it does not: an `impl Fn` parameter, a bare `fn(..)` pointer, and any +/// other alias of those types; an operation written that way needs the list +/// updated by hand, which the two-way comparison will report as a listed +/// operation whose signature looks routable. fn derived_lifecycle(root: &Path) -> Result> { let mut found = Vec::new(); for entry in std::fs::read_dir(root.join("crates"))? { @@ -848,3 +855,73 @@ pub fn check(root: &Path) -> Result<()> { println!("service declarations passed"); Ok(()) } + +#[cfg(test)] +mod derivation_tests { + use super::*; + + fn tree(source: &str) -> std::path::PathBuf { + let root = std::env::temp_dir().join(format!( + "dim-derived-{}-{}", + std::process::id(), + source.len() + )); + std::fs::create_dir_all(root.join("crates/example/src")).unwrap(); + std::fs::write(root.join("crates/example/src/lib.rs"), source).unwrap(); + root + } + + #[test] + fn a_callback_operation_is_derived_and_a_plain_one_is_not() { + let root = tree( + r#" + pub struct Example; + #[rutis::service] + impl Example { + /// A plain read. + pub async fn get(&self) -> Result { Ok(1) } + /// Takes the calling row. + pub async fn read(&self, caller: &Ctx, path: String) -> Result { Ok(1) } + /// Takes a cancellation. + pub async fn wait(&self, cancelled: CancelledFn) -> Result { Ok(1) } + } + "#, + ); + let derived = derived_lifecycle(&root).expect("the derivation reads the tree"); + assert_eq!( + derived, + vec![ + ("example".to_owned(), "read".to_owned()), + ("example".to_owned(), "wait".to_owned()), + ], + "{derived:?}" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn the_comparison_names_the_operation_that_disagrees() { + let derived = [ + ("example".to_owned(), "read".to_owned()), + ("example".to_owned(), "wait".to_owned()), + ]; + let listed = [("example".to_owned(), "read".to_owned())]; + let missing: Vec = derived + .iter() + .filter(|pair| !listed.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + assert_eq!(missing, vec!["example.wait".to_owned()]); + let listed = [ + ("example".to_owned(), "get".to_owned()), + ("example".to_owned(), "read".to_owned()), + ("example".to_owned(), "wait".to_owned()), + ]; + let extra: Vec = listed + .iter() + .filter(|pair| !derived.contains(pair)) + .map(|(service, method)| format!("{service}.{method}")) + .collect(); + assert_eq!(extra, vec!["example.get".to_owned()]); + } +} From bd1e7484ef89012f3e4452b6f535322c00bffdaf Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 13:22:00 +0800 Subject: [PATCH 26/37] fix(typescript): the sessions envelope keeps retryable on every code - `SessionsError` is the generated union intersected with the envelope's `retryable`, which `envelope()` adds to every failure; the fixture reads it on a non-`routed` code. - the signature derivation also recognizes `impl Fn` and a bare `fn` pointer, and its doc says the shapes it still misses are a review-time guarantee. - the line-scope doc links `SessionScope` instead of the removed `Route`, and a stale comment about routing codes is gone. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/timeline_context.rs | 2 +- crates/dim-app-server/src/agents/sessions.rs | 2 -- npm/plugin.d.ts | 5 +++-- runtime/fixtures/branch-calls.ts | 6 ++++++ xtask/check/src/types.rs | 15 ++++++++++----- 5 files changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index c751c9c887..178a2c564c 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -350,7 +350,7 @@ impl TimelineContext { &self.view } /// The branch instance's context, for reads of its data faces by id - /// ([`Route`]). + /// ([`crate::route::SessionScope`]). pub(crate) fn ctx(&self) -> &Ctx { &self.ctx } diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index ccdd507b74..05735a88c8 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -1009,8 +1009,6 @@ async fn call( index.delete(&session_id).await?; reply(json!({})) } - // The routing answer names itself in the message until the Agents - // contract gives this face routing codes of its own. "call" => index.call(request(args)?).await.map_err(routed), _ => Err(SessionsError::rejected(format!( "unknown sessions method {method}" diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 1dcbf36ade..64df6bdc5b 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -281,8 +281,9 @@ export interface StopRequest extends SessionRef { reason?: string | null } export interface SequenceReply { sequence: number } export type SessionsErrorCode = import('./branch-services.js').SessionsErrorThrown['code']; /** The failure a `sessions` call reports: the generated union, so each code carries - * the details the server sends (`reason`, `line`, `service`, `name`, `data`). */ -export type SessionsError = import('./branch-services.js').SessionsError; + * the details the server sends (`reason`, `line`, `service`, `name`, `data`), plus + * the envelope's own `retryable`, which every code answers. */ +export type SessionsError = import('./branch-services.js').SessionsError & { retryable: boolean }; export type SessionsResult = { ok: true; value: T } | { ok: false; error: SessionsError }; /** Process service `sessions`; these methods are not terminal RPC methods. */ diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index 3437e6e0fd..c435b7158a 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -4,6 +4,12 @@ import type { Sessions } from '../../npm/plugin.js' import type { RouteError, SessionScope } from '../../npm/branch-services.js' +/** Every `sessions` failure carries the envelope's retryability. */ +export function retryable(error: import('../../npm/plugin.js').SessionsError): boolean { + const retryable: boolean = error.retryable + return retryable +} + /** A Session part reads the owner's structured failure from the routed error. */ export function ownerFailure(error: RouteError): string | null { return 'owner' in error ? `${error.owner.name}: ${error.owner.message}` : null diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 679ee0dc28..cb05797650 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -370,11 +370,11 @@ fn lifecycle(root: &Path) -> Result> { /// that kind cannot slip past the list the runtime refuses. /// /// What it recognizes: a `Ctx` or a reference to one, the `CancelledFn` and -/// `CancellationToken` aliases, and `dyn Fn(..)` behind `Arc` or a reference. -/// What it does not: an `impl Fn` parameter, a bare `fn(..)` pointer, and any -/// other alias of those types; an operation written that way needs the list -/// updated by hand, which the two-way comparison will report as a listed -/// operation whose signature looks routable. +/// `CancellationToken` aliases, and `Fn(..)` as a trait object, behind `Arc`, or +/// as `impl Fn`, and a bare `fn(..)` pointer. What it still misses: any other +/// alias of those types; an operation written that way is a review-time +/// guarantee, and the two-way comparison reports it as a listed operation whose +/// signature looks routable. fn derived_lifecycle(root: &Path) -> Result> { let mut found = Vec::new(); for entry in std::fs::read_dir(root.join("crates"))? { @@ -456,6 +456,11 @@ fn carries_lifecycle(ty: &syn::Type) -> bool { _ => false, } } + syn::Type::ImplTrait(implemented) => implemented.bounds.iter().any(|bound| { + matches!(bound, syn::TypeParamBound::Trait(bound) + if bound.path.segments.last().is_some_and(|segment| segment.ident == "Fn")) + }), + syn::Type::BareFn(_) => true, syn::Type::TraitObject(object) => object.bounds.iter().any(|bound| { matches!(bound, syn::TypeParamBound::Trait(bound) if bound.path.segments.last().is_some_and(|segment| segment.ident == "Fn")) From 83a9203ca8f06e0e6b1388ebb7b88fd8344ad6ad Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 14:49:53 +0800 Subject: [PATCH 27/37] docs(runtime): state the routed operations and the load that precedes NoSession - the owner-operations table no longer mentions a compact-and-wait variant: a compaction that waits calls `agentLoop.compact` through `lineCall` and waits through the Session's `timelineTree`, because `lineCall` resolves only operations an owner already serves; - the route's module docs name `SessionScope::call`, say the scope is not one of its own faces, and say that Agents loads a Session for the call, so `NoSession` means it does not exist or cannot load again (D5). Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/route.rs | 28 +++++++++++-------- .../contracts/runtime-owner-operations.md | 2 +- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index e1489316fd..ba139b2376 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -4,18 +4,23 @@ //! A caller outside a scope holds no instance key, so it names what it wants, //! and the owner of the target holds the index and does the lookup: //! -//! - a Session's [`SessionScope`] resolves one of its own lines, for the -//! Session's parts and their runtimes; it holds no Session id, so a caller -//! cannot name another Session; +//! - a Session's [`SessionScope`] resolves one of its own lines and its own +//! Session faces, for the Session's parts and their runtimes; it holds no +//! Session id, so a caller cannot name another Session, and the scope itself +//! is not one of the faces it resolves; //! - Agents' `sessions` resolves a Session, and a line of it, for the process -//! (`dim-app-server`): it finds the Session and then calls -//! [`SessionScope::line_call`] in that instance. +//! (`dim-app-server`): it finds the Session — loading it for the call when it +//! is not loaded (D5) — and then calls [`SessionScope::line_call`] or +//! [`SessionScope::call`] in that instance. //! -//! Two data operations carry every routed call, with the same arguments in +//! Three data operations carry every routed call, with the same arguments in //! every language: //! //! - [`SessionScope::line_call`] — `{lineId, service, method, args}`; -//! - `sessions.call` — `{sessionId, lineId?, service, method, args}`. +//! - [`SessionScope::call`] — `{service, method, args}`, for the Session's own +//! faces; +//! - `sessions.call` — `{sessionId, lineId?, service, method, args}`, which +//! takes the same two forms for a process caller. //! //! Each call looks the target up again, so a caller never keeps a live target //! (D4). Rust calls the same two operations: it builds `args` from the target @@ -29,10 +34,11 @@ //! belongs to the owner: the route passes the method and its arguments through //! and returns the owner's reply, or the owner's own failure as it wrote it. //! -//! A Session that has no live instance — idle-unloaded, closed or never -//! created — answers [`RouteError::NoSession`]. A Session that is closing -//! answers [`RouteError::SessionClosing`], and a line target answers it too, -//! because closing the Session closes its lines. A line that is closing or +//! Only the process path can find a Session that has no live instance: Agents +//! loads it for the call (D5), so [`RouteError::NoSession`] means the Session +//! does not exist, or is closed and cannot load again. A Session that is +//! closing answers [`RouteError::SessionClosing`], and a line target answers it +//! too, because closing the Session closes its lines. A line that is closing or //! closed, or that belongs to another Session, answers [`RouteError::NoLine`]; //! that is final for the line: routing never retries it. diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index b88e430e00..aefd7ff604 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -49,7 +49,7 @@ tree's own methods. | Session caller | Target operation | | --- | --- | -| Context RPC / PromptSuggestion | `contextUsage.read`. The `compactAndWait` variant runs the existing compact RPC handler: it calls `agentLoop.compact` and waits for the compaction fact matching that command sequence and returns the existing completed/skipped/failed reply. The committed sequence watch and bounded query run inside the selected branch for that wait. | +| Context RPC / PromptSuggestion | `contextUsage.read`. A compaction that waits stays in the existing compact RPC handler: it calls `agentLoop.compact` through `lineCall`, then waits through the Session's `timelineTree` for that compaction's result and returns the existing completed/skipped/failed reply. `lineCall` resolves only operations an owner already serves in the catalog, so no owner provides a separate compact-and-wait operation. | | Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | | InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | From b7276ece95a87ba934f3d0ccbc6accca59a38cf3 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 15:24:33 +0800 Subject: [PATCH 28/37] test(typescript): keep the negative calls in scope, and refuse foreign addresses - the ten `@ts-expect-error` cases are inside `readByCalls`, where `scope` and `sessions` resolve, so each one now proves the call shape rather than a missing name; - `LineCall` takes no `sessionId` and `SessionCall` takes neither `lineId` nor `sessionId`, with a case for each; - the guide states the real cutoff: a line keeps answering after its durable end while `close_and_record` waits for `deliver_final`; entering closing is what answers `no_line`. Refs #2015 Refs #2127 --- docs/typescript-plugin-authoring.md | 8 ++--- npm/branch-services.d.ts | 4 +-- runtime/fixtures/branch-calls.ts | 47 ++++++++++++++++------------- xtask/check/src/types.rs | 4 +-- 4 files changed, 34 insertions(+), 29 deletions(-) diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 90d28b2be1..fc3eda410d 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -80,10 +80,10 @@ faces a routed call resolves. A line is admitted while it is published and not closing. A running line that ends a tool call commits that batch but stays selectable until its turn ends, so a call placed between the two -still reaches its owner; the turn's durable `branch/end` is what takes the line out of the -published set, and from then on a new call answers `no_line`, which is final for that line. A -call admitted before the end keeps its owner's own result and failure, including one that -arrives after it. Rust calls the same operations: it builds `args` from the target operation's request +still reaches its owner. The cutoff is entering closing: after a durable `branch/end` the line +keeps answering while `close_and_record` waits for `deliver_final`, and once the instance starts +closing a new call answers `no_line`, which is final for that line. A call admitted before the +closing keeps its owner's own result and failure, including one that arrives after the end. Rust calls the same operations: it builds `args` from the target operation's request type and reads the reply as that operation's reply type. ## Available services diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index dc245de955..dd207a9731 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1919,10 +1919,10 @@ type Call = { }[keyof Faces] /** A call to one of the caller's own Session's lines. */ -export type LineCall = Call +export type LineCall = Call /** A call to one of the caller's own Session's data faces. */ -export type SessionCall = Call +export type SessionCall = Call /** A call through Agents: a Session's face, or one of its lines' faces. A Session * face takes no `lineId`. */ diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index c435b7158a..ad119342b3 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -39,6 +39,32 @@ export async function readByCalls( const config = await scope.call({ service: 'sessionConfig', method: 'get', args: [] }) const cwd: string = config.cwd void [status, committed, cwd] + + // @ts-expect-error a service the route does not resolve is refused. + void scope.lineCall({ lineId: 'main', service: 'inputQueueX', method: 'withdraw', args: [] }) + // @ts-expect-error a method the service does not have is refused. + void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'submitX', args: [] }) + // @ts-expect-error arguments follow the method's parameters. + void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: ['wrong'] }) + // @ts-expect-error a Session call reaches a Session face, not a line's. + void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) + // @ts-expect-error a reply keeps the target method's own type. + void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) + // @ts-expect-error an operation bound to the calling row is direct-only. + void scope.call({ service: 'uiResources', method: 'publishFile', args: [{}] }) + // @ts-expect-error a subscription an operation hands the caller is not routed. + void scope.lineCall({ lineId: 'main', service: 'dispatcher', method: 'listen', args: ['n', [], (_e: unknown) => {}] }) + // @ts-expect-error an operation that needs a caller-side cancellation is not routed. + void scope.lineCall({ lineId: 'main', service: 'wait', method: 'wait', args: [] }) + // @ts-expect-error a Session service takes no lineId. + void sessions.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) + // @ts-expect-error a line call takes no Session id. + void sessions.call({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) + // @ts-expect-error `lineCall` takes no `sessionId`: it reaches its own Session only. + void scope.lineCall({ sessionId, lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) + // @ts-expect-error `SessionScope.call` takes neither `lineId` nor `sessionId`. + void scope.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) + await sessions.call({ sessionId, lineId: 'main', @@ -48,24 +74,3 @@ export async function readByCalls( }) await sessions.call({ sessionId, service: 'sessionConfig', method: 'get', args: [] }) } - -// @ts-expect-error a service the route does not resolve is refused. -void scope.lineCall({ lineId: 'main', service: 'inputQueueX', method: 'withdraw', args: [] }) -// @ts-expect-error a method the service does not have is refused. -void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'submitX', args: [] }) -// @ts-expect-error arguments follow the method's parameters. -void scope.lineCall({ lineId: 'main', service: 'inputQueue', method: 'withdraw', args: ['wrong'] }) -// @ts-expect-error a Session call reaches a Session face, not a line's. -void scope.call({ service: 'inputQueue', method: 'withdraw', args: [] }) -// @ts-expect-error a reply keeps the target method's own type. -void scope.lineCall({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }).then((reply: string) => reply) -// @ts-expect-error an operation bound to the calling row is direct-only. -void scope.call({ service: 'uiResources', method: 'publishFile', args: [{}] }) -// @ts-expect-error a subscription an operation hands the caller is not routed. -void scope.lineCall({ lineId: 'main', service: 'dispatcher', method: 'listen', args: ['n', [], (_e: unknown) => {}] }) -// @ts-expect-error an operation that needs a caller-side cancellation is not routed. -void scope.lineCall({ lineId: 'main', service: 'wait', method: 'wait', args: [] }) -// @ts-expect-error a Session service takes no lineId. -void sessions.call({ sessionId, lineId: 'main', service: 'sessionConfig', method: 'get', args: [] }) -// @ts-expect-error a line call takes no Session id. -void sessions.call({ lineId: 'main', service: 'timeline', method: 'sequence', args: [] }) diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index cb05797650..010c8f4501 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -106,8 +106,8 @@ fn calls(root: &Path, services: &str) -> Result { text += "\n/** The data faces a Session reaches. */\n"; text += &faces(&session, "SessionFaces"); text += "\n/** One call a route resolves: `service` and `method` name a data face and one of its methods, and `args` are that method's parameters. */\ntype Call = {\n [S in keyof Faces]: {\n [M in keyof Faces[S]]: Address & {\n service: S\n method: M\n args: Faces[S][M] extends (...args: infer A) => unknown ? A : never\n }\n }[keyof Faces[S]]\n}[keyof Faces]\n"; - text += "\n/** A call to one of the caller's own Session's lines. */\nexport type LineCall = Call\n"; - text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; + text += "\n/** A call to one of the caller's own Session's lines. */\nexport type LineCall = Call\n"; + text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. A Session\n * face takes no `lineId`. */\nexport type SessionsCall =\n | Call\n | Call\n"; text += "\n/** The reply of one call: the target method's own return type. */\nexport type ReplyOf = C extends { service: infer S; method: infer M }\n ? S extends keyof (LineFaces & SessionFaces)\n ? M extends keyof (LineFaces & SessionFaces)[S]\n ? Awaited<\n (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never\n >\n : never\n : never\n : never\n"; text += "\n/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */\nexport interface SessionScope {\n call(call: C): Promise>\n lineCall(call: C): Promise>\n}\n"; From 8bb7d711eace5bb26313b65d9e1224465eb347f3 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 15:47:07 +0800 Subject: [PATCH 29/37] feat(runtime): reach the router through its owner, and keep the owner's code - `SessionScope` is no longer a `PublicService`, so no `Session` read hands it out; `Session::routed_scope` is the owning instance's entry and Agents is its only caller (`dim-app-server`). A route is no longer reachable as a facade read. - `RouteError::Owner` and `SessionsError::Routed` carry the owner's own `code`, read from the bridge error beside `reloading`: a routed failure now says `UnknownBranch`, not just a name and a message. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 5 ++- crates/dim-agent-runtime/src/agent.rs | 10 +++++ crates/dim-agent-runtime/src/route.rs | 39 +++++++++++++++++-- crates/dim-agent-runtime/src/scope.rs | 1 - crates/dim-app-server/src/agents.rs | 25 +++++------- crates/dim-app-server/src/agents/sessions.rs | 4 ++ npm/branch-services.d.ts | 4 +- 7 files changed, 64 insertions(+), 24 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 238e622c0b..9394d8535b 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -78,9 +78,10 @@ impl Rig { } fn scope(&self, session: &Session) -> Arc { + // The facade offers no read for the router; its owner exposes it. session - .session_service::() - .expect("the Session serves its scope") + .routed_scope() + .expect("the owning instance serves its scope") } } diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 86020e5fb0..05224a6822 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -750,6 +750,16 @@ impl Session { /// loader rows this Session runs. Keys under it stay readable only from /// inside the Session, so it opens no service beyond the /// [`PublicService`] reads above. + /// The routed-call entry an owner's caller uses for this Session: the + /// owning instance's own router, not a [`PublicService`] read. Agents is + /// the only caller; a part of another language reaches it as the + /// `sessionScope` data face. + pub fn routed_scope(&self) -> Option> { + let loaded = self.0.owner.loaded().ok()?; + loaded + .ctx + .get_at::(&loaded.scope.key::()) + } pub fn instance(&self) -> Result { Ok(self.0.owner.loaded()?.scope.instance) } diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index ba139b2376..384dd784af 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -94,13 +94,14 @@ pub enum RouteError { /// The name is a data face, but not of the scope the route reaches. #[error("{service} is not a {group} service")] WrongScope { service: String, group: String }, - /// The owner's own failure, with the name and message it wrote; routing - /// does not read or restate it. `reloading` is the owner's own code for - /// "try again later", so a caller retries exactly what the owner says it - /// may retry. + /// The owner's own failure, with the name, the code it reported and the + /// message it wrote; routing does not restate them. `reloading` is that + /// code's "try again later", so a caller retries exactly what the owner + /// says it may retry. #[error("{message}")] Owner { name: String, + code: Option, message: String, /// The owner's failure as data, when its error type carries a serde /// value: a caller can act on the same structure a direct call would @@ -385,6 +386,7 @@ pub(crate) async fn call_face( .get_at::(&host_key_in(service, instance)) .ok_or_else(|| RouteError::Owner { name: service.into(), + code: None, message: format!("{service} is not provided now"), data: None, reloading: false, @@ -404,6 +406,7 @@ pub(crate) fn owner(error: impl Into) -> RouteError { let failure = error.into(); RouteError::Owner { name: failure.name, + code: failure.code, message: failure.message, data: failure.data, reloading: failure.reloading, @@ -414,6 +417,7 @@ pub(crate) fn owner(error: impl Into) -> RouteError { /// with. pub(crate) struct Failure { name: String, + code: Option, message: String, data: Option>, reloading: bool, @@ -423,6 +427,7 @@ impl From for Failure { fn from(error: AgentError) -> Self { Self { name: "AgentError".into(), + code: Some(agent_code(&error).to_owned()), reloading: matches!(error, AgentError::Reloading(_)), message: error.to_string(), data: None, @@ -430,6 +435,28 @@ impl From for Failure { } } +/// The code a marked Rust service reports for an `AgentError`: its variant name, +/// spelled the way the generated declarations spell it. +fn agent_code(error: &AgentError) -> &'static str { + match error { + AgentError::InvalidInput(_) => "InvalidInput", + AgentError::Closed(_) => "Closed", + AgentError::UnknownBranch(_) => "UnknownBranch", + AgentError::BranchEnded(_) => "BranchEnded", + AgentError::BranchRefused { .. } => "BranchRefused", + AgentError::Storage(_) => "Storage", + AgentError::PublicationUnknown(_) => "PublicationUnknown", + AgentError::Build(_) => "Build", + AgentError::Cancelled(_) => "Cancelled", + AgentError::Reloading(_) => "Reloading", + AgentError::AmbiguousSubmission(_) => "AmbiguousSubmission", + AgentError::PartialSubmission(_) => "PartialSubmission", + AgentError::Fault { .. } => "Fault", + AgentError::Framework { .. } => "Framework", + AgentError::Multiple(_) => "Multiple", + } +} + impl From for Failure { fn from(error: BridgeError) -> Self { match error { @@ -438,6 +465,7 @@ impl From for Failure { // service reports a reload as `Reloading` (`AgentError`'s variant // code), and the wire keeps it in the error graph. let reloading = error.code() == Some(RELOADING); + let code = error.code().map(str::to_owned); let data = error.data().map(Box::new); let name = match &error { BridgeError::Remote { name, .. } => name.clone(), @@ -447,6 +475,7 @@ impl From for Failure { match error { BridgeError::Remote { message, .. } | BridgeError::Binding { message, .. } => { Self { + code, reloading, data, name, @@ -454,6 +483,7 @@ impl From for Failure { } } other => Self { + code, reloading, data, name, @@ -463,6 +493,7 @@ impl From for Failure { } other => Self { name: "BridgeError".into(), + code: None, message: other.to_string(), data: None, reloading: false, diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index a655336110..d9a71c7eef 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -178,5 +178,4 @@ impl BranchScope { } } impl PublicService for SessionConfig {} -impl PublicService for crate::SessionScope {} impl PublicService for dyn LoopState {} diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 917c8b9e97..dfd063f7b8 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1671,21 +1671,16 @@ impl AgentIndex { if session.is_closing() { return Err(RouteError::SessionClosing(id)); } - let scope = session - .session_service::() - .map_err(|error| match error { - _ if session.is_closing() => RouteError::SessionClosing(id.clone()), - AgentError::Reloading(_) => RouteError::Owner { - name: "AgentError".into(), - message: error.to_string(), - data: None, - reloading: true, - }, - error => RouteError::SessionUnavailable { - session: id.clone(), - reason: error.to_string(), - }, - })?; + let Some(scope) = session.routed_scope() else { + return Err(if session.is_closing() { + RouteError::SessionClosing(id) + } else { + RouteError::SessionUnavailable { + session: id, + reason: "the Session's scope is not provided".into(), + } + }); + }; match request.line_id { Some(line_id) => { scope diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index 05735a88c8..7dc2ce10e8 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -331,6 +331,8 @@ pub enum SessionsError { #[error("{message}")] Routed { name: String, + /// The code the owner reported, when its error carries one. + owner_code: Option, message: String, /// The owner's failure as data, when its error type carries a serde /// value. @@ -930,11 +932,13 @@ fn routed(error: dim_agent_runtime::RouteError) -> SessionsError { RouteError::NoLine { line, .. } => SessionsError::NoLine { message, line }, RouteError::Owner { name, + code, data, reloading, .. } => SessionsError::Routed { name, + owner_code: code, message, data, retryable: reloading, diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index dd207a9731..3ca8c9247e 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1414,7 +1414,7 @@ export type RouteError = | /** The name is not a data face a route resolves there: the assembly marks it internal, it is a mechanism registration point, or it is a scope lifecycle service. A permanent answer: the request is wrong. */ { notDataFace: { service: string } } | /** The service is a data face a route resolves, but this operation of it is not: its call needs a cancellation or a cleanup the routed call cannot carry, so only a direct call keeps its lifetime behaviour. */ { methodNotRoutable: { service: string; method: string } } | /** The name is a data face, but not of the scope the route reaches. */ { wrongScope: { service: string; group: string } } - | /** The owner's own failure, with the name and message it wrote; routing does not read or restate it. `reloading` is the owner's own code for "try again later", so a caller retries exactly what the owner says it may retry. */ { owner: { name: string; message: string; data?: import('./plugin.js').BridgeJsonValue | null; reloading: boolean } } + | /** The owner's own failure, with the name, the code it reported and the message it wrote; routing does not restate them. `reloading` is that code's "try again later", so a caller retries exactly what the owner says it may retry. */ { owner: { name: string; code?: string | null; message: string; data?: import('./plugin.js').BridgeJsonValue | null; reloading: boolean } } /** @@ -1481,7 +1481,7 @@ export type SessionsError = | { code: "not_data_face"; message: string; service: string } | { code: "method_not_routable"; message: string; service: string; method: string } | { code: "wrong_scope"; message: string; service: string; group: string } - | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; message: string; data?: import('./plugin.js').BridgeJsonValue | null; retryable: boolean } + | /** The target owner's own failure, with the name and message it wrote and whether the owner says it may be retried. */ { code: "routed"; name: string; owner_code?: string | null; message: string; data?: import('./plugin.js').BridgeJsonValue | null; retryable: boolean } | { code: "agent_unknown"; message: string } | { code: "session_closed"; message: string } | { code: "branch_missing"; message: string } From c84cec46e1eb2e7ead5ea03620bffc85828081be Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 15:51:42 +0800 Subject: [PATCH 30/37] test(runtime): prove the router is not a facade read, and the owner's code survives A `compile_fail` doctest on `Session::routed_scope` shows `session.session_service::()` does not compile now that the scope is no `PublicService`; a unit test shows a remote failure's own code (`UnknownBranch`) reaches `RouteError::Owner` beside `reloading`. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/agent.rs | 9 +++++++++ crates/dim-agent-runtime/src/route.rs | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 05224a6822..70f8bd4c84 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -754,6 +754,15 @@ impl Session { /// owning instance's own router, not a [`PublicService`] read. Agents is /// the only caller; a part of another language reaches it as the /// `sessionScope` data face. + /// + /// The router is not a facade read, so the typed one does not compile: + /// + /// ```compile_fail + /// use dim_agent_runtime::{Session, SessionScope}; + /// fn read(session: &Session) { + /// let _ = session.session_service::(); + /// } + /// ``` pub fn routed_scope(&self) -> Option> { let loaded = self.0.owner.loaded().ok()?; loaded diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 384dd784af..2a5e839a87 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -506,6 +506,31 @@ impl From for Failure { mod tests { use super::*; + #[test] + fn an_owner_failure_keeps_its_code() { + let remote = |code: &str| BridgeError::Remote { + name: "AgentError".into(), + message: format!("{code}: absent"), + graph: Some(serde_json::json!({ + "root": {"type": "reference", "value": 0}, + "nodes": [{"type": "error", "name": "AgentError", "code": code, "message": "absent"}], + })), + }; + let routed = owner(remote("UnknownBranch")); + let RouteError::Owner { + code, reloading, .. + } = &routed + else { + panic!("the owner's failure crosses as Owner: {routed:?}"); + }; + assert_eq!(code.as_deref(), Some("UnknownBranch"), "{routed:?}"); + assert!(!reloading, "{routed:?}"); + assert_eq!( + agent_code(&AgentError::UnknownBranch("absent".into())), + "UnknownBranch" + ); + } + #[test] fn an_owner_failure_is_retryable_only_when_its_code_says_reloading() { let reloading = owner(AgentError::Reloading("timeline".into())); From 75effe6953fb229ac8e9c060a4bed76cb7af359f Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 16:05:35 +0800 Subject: [PATCH 31/37] feat(runtime): compare an owner failure through both paths, and route only shared faces - `routing_flow` compares `InputQueue::withdraw`'s `InvalidInput` directly and through `lineCall`, so the owner's own code is proven to arrive unchanged. - `face` requires `catalog.is_shared`: a native-only registration answers `NotDataFace`, which a Session part cannot reach. The rig shares the faces its cases use, the way the product's `share_names` does. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 67 +++++++++++++++++++ crates/dim-agent-runtime/src/route.rs | 7 ++ 2 files changed, 74 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 9394d8535b..7286d86e24 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -53,6 +53,23 @@ impl Rig { // The product marks the same names (its `register_faces`); a route // resolves data faces only. builder.internal_name("loopState", "hot-path"); + // The product shares the faces a route resolves (`share_names`); the + // rig shares the ones its cases use and leaves a native-only name + // unshared. + for (name, group) in [ + ("approval", "branch"), + ("branchLine", "branch"), + ("dispatcher", "branch"), + ("inputQueue", "branch"), + ("permission", "branch"), + ("timeline", "branch"), + ("sessionConfig", "session"), + ("sessionIdentity", "session"), + ("treeCommands", "session"), + ("uiResources", "session"), + ] { + builder.catalog_mut().register_shared_instance(name, group); + } builder.require_feature( Feature::new("RoutingSessionProbe").session("RoutingSessionProbe", move |_| { Ok(Box::new(HandsSession(probe.clone()))) @@ -338,6 +355,46 @@ async fn an_idle_unloaded_session_answers_session_closing_until_it_loads_again() rig.host.close().await.unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_owner_failure_keeps_its_code_through_the_route() { + use dim_agent_capabilities::input_queue::InputQueue; + use dim_agent_types::{InputMessageData, InputWithdrawData}; + + let rig = Rig::start().await; + let session = rig.open().await; + let scope = rig.scope(&session); + let command = InputWithdrawData { + input_id: "x".into(), + reason: None, + steer: Some(InputMessageData::text("x", None)), + }; + let direct = session + .service::("main") + .expect("the line serves its input queue") + .withdraw(command.clone()) + .await + .unwrap_err(); + let routed = scope + .line_call(LineCall::new( + "main", + "inputQueue", + "withdraw", + vec![serde_json::to_value(&command).unwrap()], + )) + .await + .unwrap_err(); + let RouteError::Owner { code, .. } = &routed else { + panic!("the owner's failure crosses as Owner: {routed:?}"); + }; + assert_eq!( + code.as_deref(), + Some("InvalidInput"), + "direct {direct:?}, routed {routed:?}" + ); + session.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { let rig = Rig::start().await; @@ -379,6 +436,16 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { }, "an operation that needs a caller-side cancellation is not routed" ); + assert_eq!( + scope + .call(SessionCall::new("sessionLoader", "new", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: "sessionLoader".into() + }, + "a native-only registration is not a data face" + ); assert_eq!( scope .call(SessionCall::new("sessionScope", "lineCall", vec![])) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 2a5e839a87..b614de9644 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -357,6 +357,13 @@ pub(crate) fn face( method: method.into(), }); } + // Only a name shared across languages is a data face; a native-only + // registration stays inside its scope. + if !catalog.is_shared(service) { + return Err(RouteError::NotDataFace { + service: service.into(), + }); + } if REGISTRATION_POINTS.contains(&service) || LIFECYCLE_SERVICES.contains(&service) || (group == SESSION_GROUP && NOT_CALLABLE.contains(&service)) From 0f787e8714d0f18d5cc9dd436797ee083f599cc2 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 16:16:48 +0800 Subject: [PATCH 32/37] fix(runtime): take the router off the Session facade `Session::routed_scope` was a public method, so any crate with a `Session` could still take the router and write the Timeline through `lineCall`. The entry is now `dim_agent_runtime::route::routed_scope(&Session)`, which reads the owning instance through a crate-private `Session::assembly`; the facade keeps no router read, and two `compile_fail` doctests pin both ways it must stay unreadable. The owner-operations table said the compact handler routed `agentLoop.compact` and waited through `timelineTree`; those faces are internal and answer `NotDataFace`, so the row now states the direct calls the code makes. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 3 +-- crates/dim-agent-runtime/src/agent.rs | 20 ++------------- crates/dim-agent-runtime/src/route.rs | 25 +++++++++++++++++++ crates/dim-app-server/src/agents.rs | 2 +- .../contracts/runtime-owner-operations.md | 2 +- 5 files changed, 30 insertions(+), 22 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 7286d86e24..c19a0971e6 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -96,8 +96,7 @@ impl Rig { fn scope(&self, session: &Session) -> Arc { // The facade offers no read for the router; its owner exposes it. - session - .routed_scope() + dim_agent_runtime::route::routed_scope(session) .expect("the owning instance serves its scope") } } diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 70f8bd4c84..30f721cb64 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -750,24 +750,8 @@ impl Session { /// loader rows this Session runs. Keys under it stay readable only from /// inside the Session, so it opens no service beyond the /// [`PublicService`] reads above. - /// The routed-call entry an owner's caller uses for this Session: the - /// owning instance's own router, not a [`PublicService`] read. Agents is - /// the only caller; a part of another language reaches it as the - /// `sessionScope` data face. - /// - /// The router is not a facade read, so the typed one does not compile: - /// - /// ```compile_fail - /// use dim_agent_runtime::{Session, SessionScope}; - /// fn read(session: &Session) { - /// let _ = session.session_service::(); - /// } - /// ``` - pub fn routed_scope(&self) -> Option> { - let loaded = self.0.owner.loaded().ok()?; - loaded - .ctx - .get_at::(&loaded.scope.key::()) + pub(crate) fn assembly(&self) -> &SessionAssembly { + &self.0.owner } pub fn instance(&self) -> Result { Ok(self.0.owner.loaded()?.scope.instance) diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index b614de9644..ea8795794e 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -278,6 +278,31 @@ impl SessionScope { } } +/// The routed-call entry for the Session `session`: the owning instance's own +/// router, so the Session facade offers no read for it (ADR 027 appendix F). +/// Agents is the only caller; a part of another language reaches it as the +/// `sessionScope` data face. The typed read remains impossible: +/// +/// ```compile_fail +/// use dim_agent_runtime::{Session, SessionScope}; +/// fn read(session: &Session) { +/// let _ = session.session_service::(); +/// } +/// ``` +/// +/// ```compile_fail +/// use dim_agent_runtime::Session; +/// fn read(session: &Session) { +/// let _ = session.routed_scope(); +/// } +/// ``` +pub fn routed_scope(session: &Session) -> Option> { + let loaded = session.assembly().loaded().ok()?; + loaded + .ctx + .get_at::(&loaded.scope.key::()) +} + #[rutis::service] impl SessionScope { /// Calls one of this Session's own data faces. diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index dfd063f7b8..75ec3d61e7 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1671,7 +1671,7 @@ impl AgentIndex { if session.is_closing() { return Err(RouteError::SessionClosing(id)); } - let Some(scope) = session.routed_scope() else { + let Some(scope) = dim_agent_runtime::route::routed_scope(session) else { return Err(if session.is_closing() { RouteError::SessionClosing(id) } else { diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index aefd7ff604..dae92e976c 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -49,7 +49,7 @@ tree's own methods. | Session caller | Target operation | | --- | --- | -| Context RPC / PromptSuggestion | `contextUsage.read`. A compaction that waits stays in the existing compact RPC handler: it calls `agentLoop.compact` through `lineCall`, then waits through the Session's `timelineTree` for that compaction's result and returns the existing completed/skipped/failed reply. `lineCall` resolves only operations an owner already serves in the catalog, so no owner provides a separate compact-and-wait operation. | +| Context RPC / PromptSuggestion | `contextUsage.read`, a direct call inside the Session's own face. A compaction that waits stays in the existing compact RPC handler: it takes its `Branch`, calls `AgentLoop::compact` there and waits on the branch's own `publication()`/`query`, then returns the existing completed/skipped/failed reply. These handlers are reached by the Session's own code today; routing them is written here only once `agentLoop`, `contextUsage`, `prompt` and `timelineTree` are routable faces with a wait operation, which they are not (`route::face` refuses them as internal). | | Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | | InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | From e616be58ae3d47a9c5785f734be5d75ba72a8547 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 16:33:04 +0800 Subject: [PATCH 33/37] feat(runtime): keep a void reply apart from a null one `call_face` now answers `Option`: a method that replies nothing settles as `BridgeValue::Undefined` and crosses as `None`, while the owner's `null` stays `Some(Null)`. `SessionScope::call`/`line_call` and `sessions.call` follow: the process envelope omits `value` for a void reply instead of writing `null`, and the routed arm owns its envelope so it is not wrapped twice. Tests: `route::tests::a_void_reply_is_undefined_and_a_null_reply_is_a_value` for the mapping, and `routing_flow::a_void_reply_stays_undefined_and_a_value_stays_a_value` for a void `sessionLoader.remove` and a real reply through the route. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 42 ++++++++++++++++--- crates/dim-agent-runtime/src/route.rs | 28 +++++++++++-- crates/dim-app-server/src/agents.rs | 2 +- crates/dim-app-server/src/agents/sessions.rs | 22 +++++++++- npm/branch-services.d.ts | 4 +- 5 files changed, 84 insertions(+), 14 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index c19a0971e6..abace92c0f 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -64,9 +64,9 @@ impl Rig { ("permission", "branch"), ("timeline", "branch"), ("sessionConfig", "session"), - ("sessionIdentity", "session"), ("treeCommands", "session"), ("uiResources", "session"), + ("sessionLoader", "session"), ] { builder.catalog_mut().register_shared_instance(name, group); } @@ -174,7 +174,7 @@ async fn a_session_part_reaches_its_own_line_and_its_own_faces() { .unwrap(); assert_eq!( sequence, - serde_json::json!(session.sequence("main").unwrap()) + Some(serde_json::json!(session.sequence("main").unwrap())) ); assert_eq!( scope @@ -191,7 +191,10 @@ async fn a_session_part_reaches_its_own_line_and_its_own_faces() { .call(SessionCall::new("sessionConfig", "get", vec![])) .await .unwrap(); - assert_eq!(config, serde_json::to_value(session.config()).unwrap()); + assert_eq!( + config, + Some(serde_json::to_value(session.config()).unwrap()) + ); rig.host.close().await.unwrap(); } @@ -394,6 +397,35 @@ async fn an_owner_failure_keeps_its_code_through_the_route() { rig.host.close().await.unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_void_reply_stays_undefined_and_a_value_stays_a_value() { + let rig = Rig::start().await; + let session = rig.open().await; + let scope = rig.scope(&session); + + let void = scope + .call(SessionCall::new( + "sessionLoader", + "remove", + vec![serde_json::json!({"instanceId": 0})], + )) + .await + .unwrap(); + assert_eq!( + void, None, + "a method that answers nothing crosses as undefined" + ); + + // A value the owner replied stays a value. + let value = scope + .line_call(LineCall::new("main", "timeline", "sequence", vec![])) + .await + .unwrap(); + assert!(value.is_some(), "a reply stays a value: {value:?}"); + session.close().await.unwrap(); + rig.host.close().await.unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { let rig = Rig::start().await; @@ -437,11 +469,11 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { ); assert_eq!( scope - .call(SessionCall::new("sessionLoader", "new", vec![])) + .call(SessionCall::new("sessionIdentity", "get", vec![])) .await .unwrap_err(), RouteError::NotDataFace { - service: "sessionLoader".into() + service: "sessionIdentity".into() }, "a native-only registration is not a data face" ); diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index ea8795794e..29d9753af6 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -306,7 +306,7 @@ pub fn routed_scope(session: &Session) -> Option> { #[rutis::service] impl SessionScope { /// Calls one of this Session's own data faces. - pub async fn call(&self, call: SessionCall) -> Routed { + pub async fn call(&self, call: SessionCall) -> Routed> { let session = self.live()?; let (catalog, faces) = session.reach(); face(catalog, faces, &call.service, &call.method, SESSION_GROUP)?; @@ -330,7 +330,7 @@ impl SessionScope { } /// Calls one of this Session's lines' data faces. - pub async fn line_call(&self, call: LineCall) -> Routed { + pub async fn line_call(&self, call: LineCall) -> Routed> { let line = self.line_context(&call.line_id)?; face( line.catalog(), @@ -413,7 +413,7 @@ pub(crate) async fn call_face( service: &str, method: &str, args: &[serde_json::Value], -) -> Routed { +) -> Routed> { let dispatch = ctx .get_at::(&host_key_in(service, instance)) .ok_or_else(|| RouteError::Owner { @@ -430,7 +430,18 @@ pub(crate) async fn call_face( ); let reply = dispatch.invoke(method, args).map_err(owner)?; let value = settle(reply).await.map_err(owner)?; - decode_value::(value).map_err(owner) + reply_value(value) +} + +/// A method that answers nothing crosses as `undefined`; `null` is a value the +/// owner chose to reply with, and a caller reads the two differently. +fn reply_value(value: BridgeValue) -> Routed> { + if matches!(value, BridgeValue::Undefined) { + return Ok(None); + } + decode_value::(value) + .map(Some) + .map_err(owner) } /// The owner's failure as the target wrote it, under the name it carries. @@ -538,6 +549,15 @@ impl From for Failure { mod tests { use super::*; + #[test] + fn a_void_reply_is_undefined_and_a_null_reply_is_a_value() { + assert_eq!(reply_value(BridgeValue::Undefined).unwrap(), None); + assert_eq!( + reply_value(serde_json::Value::Null.into()).unwrap(), + Some(serde_json::Value::Null) + ); + } + #[test] fn an_owner_failure_keeps_its_code() { let remote = |code: &str| BridgeError::Remote { diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 75ec3d61e7..0dd44232e2 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1647,7 +1647,7 @@ impl AgentIndex { pub(crate) async fn call( &self, request: crate::agents::sessions::CallRequest, - ) -> std::result::Result { + ) -> std::result::Result, RouteError> { let id = request.session_id.clone(); // A replaced or stopping index is transient: the caller retries the // Session it knows against the next generation (#2127). diff --git a/crates/dim-app-server/src/agents/sessions.rs b/crates/dim-app-server/src/agents/sessions.rs index 7dc2ce10e8..3126b4ca91 100644 --- a/crates/dim-app-server/src/agents/sessions.rs +++ b/crates/dim-app-server/src/agents/sessions.rs @@ -904,7 +904,12 @@ impl HostDispatch for SessionsService { (Some(index), Ok(args)) => call(&index, &method, args, row.as_ref()).await, } }; - Ok(Value::future(async move { Ok(envelope(operation.await)) })) + Ok(Value::future(async move { + match operation.await { + Ok(reply) if reply.get("ok").is_some() => Ok(reply.into()), + other => Ok(envelope(other)), + } + })) } } @@ -1013,7 +1018,20 @@ async fn call( index.delete(&session_id).await?; reply(json!({})) } - "call" => index.call(request(args)?).await.map_err(routed), + "call" => index + .call(request(args)?) + .await + .map_err(routed) + .map(|value| { + let mut reply = serde_json::Map::new(); + reply.insert("ok".into(), serde_json::Value::Bool(true)); + // A method that answers nothing leaves `value` out: a caller reads + // absent as `undefined`, while `null` stays the owner's reply. + if let Some(value) = value { + reply.insert("value".into(), value); + } + serde_json::Value::Object(reply) + }), _ => Err(SessionsError::rejected(format!( "unknown sessions method {method}" ))), diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 3ca8c9247e..f1500c74f7 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1429,12 +1429,12 @@ export interface SessionScope { * Calls one of this Session's own data faces. * @throws {RouteErrorThrown} */ - call(call: SessionCall): Promise + call(call: SessionCall): Promise /** * Calls one of this Session's lines' data faces. * @throws {RouteErrorThrown} */ - lineCall(call: LineCall): Promise + lineCall(call: LineCall): Promise } export type SessionInstanceDefinition = { From 71e84597c2dbbd022a03070da4defa569ed84fa8 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 17:14:24 +0800 Subject: [PATCH 34/37] feat(runtime): hand the router out as a handle the runtime alone builds A bare `Session` had a public path to the router (`pub mod route`, `pub use route::*`, `pub fn routed_scope`), so any crate holding one could write the Timeline through `lineCall`. The module is private again and exports only its data types; the router travels in `RoutedSession`, whose constructor is crate-private, and the mechanism caller that owns the index takes one from `Agent::routed_session(id)`. Three `compile_fail` doctests pin the ways a bare `Session` has none: `session.routed()`, `routed_scope(session)` and `RoutedSession::new(..)`. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 8 +++- crates/dim-agent-runtime/src/agent.rs | 17 ++++++- crates/dim-agent-runtime/src/lib.rs | 4 +- crates/dim-agent-runtime/src/route.rs | 47 ++++++++++++++----- crates/dim-app-server/src/agents.rs | 15 +++--- xtask/src/catalog.rs | 6 +-- 6 files changed, 66 insertions(+), 31 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index abace92c0f..d973a428bb 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -95,9 +95,13 @@ impl Rig { } fn scope(&self, session: &Session) -> Arc { - // The facade offers no read for the router; its owner exposes it. - dim_agent_runtime::route::routed_scope(session) + // The facade offers no read for the router; its owner hands out a + // handle only the runtime can build. + self.host + .routed_session(session.id()) .expect("the owning instance serves its scope") + .scope() + .clone() } } diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 30f721cb64..6c71a06808 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -384,6 +384,14 @@ impl Agent { }) .collect() } + /// The Session `id` with its router, for the mechanism caller that owns the + /// index (Agents) to route by id. Only the runtime builds the handle + /// (`RoutedSession::new` is crate-private), so a crate holding a bare + /// [`Session`] has no path to the router: no facade method and no free + /// function takes one to a scope. + pub fn routed_session(&self, id: &str) -> Option { + self.get_session(id)?.routed() + } pub fn get_session(&self, id: &str) -> Option { match self.0.entries.lock().unwrap().get(id) { Some(Entry::Ready(s)) => Some(s.clone()), @@ -750,8 +758,13 @@ impl Session { /// loader rows this Session runs. Keys under it stay readable only from /// inside the Session, so it opens no service beyond the /// [`PublicService`] reads above. - pub(crate) fn assembly(&self) -> &SessionAssembly { - &self.0.owner + /// This Session with its router, when its owning instance provides one. + fn routed(&self) -> Option { + let loaded = self.0.owner.loaded().ok()?; + let scope = loaded.ctx.get_at::( + &loaded.scope.key::(), + )?; + Some(crate::route::RoutedSession::new(self.clone(), scope)) } pub fn instance(&self) -> Result { Ok(self.0.owner.loaded()?.scope.instance) diff --git a/crates/dim-agent-runtime/src/lib.rs b/crates/dim-agent-runtime/src/lib.rs index a9605995ad..1d8cd46798 100644 --- a/crates/dim-agent-runtime/src/lib.rs +++ b/crates/dim-agent-runtime/src/lib.rs @@ -12,7 +12,7 @@ mod memory_timeline_store; pub mod names; mod parts; mod registrations; -pub mod route; +mod route; mod scope; mod state; #[cfg(feature = "testing")] @@ -36,7 +36,7 @@ pub use memory_timeline_store::*; pub use names::Names; pub use parts::{Feature, Generator, Mount, PartRegistry, PartScope}; pub use registrations::{Registration, Registrations}; -pub use route::*; +pub use route::{LineCall, RouteError, RoutedSession, SessionCall, SessionScope, resolves}; pub use rutis::host::BoxFuture; pub use scope::*; pub use state::*; diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index 29d9753af6..cbae9bf4dc 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -278,29 +278,50 @@ impl SessionScope { } } -/// The routed-call entry for the Session `session`: the owning instance's own -/// router, so the Session facade offers no read for it (ADR 027 appendix F). -/// Agents is the only caller; a part of another language reaches it as the -/// `sessionScope` data face. The typed read remains impossible: +/// A Session with the router its owning instance provides: what Agents routes +/// through. Only the runtime builds one, when a Session is loaded, so a crate +/// that merely holds a [`Session`] has no path to the router (ADR 027 appendix +/// F). A part of another language reaches the same router as the +/// `sessionScope` data face. +/// +/// A bare [`Session`] cannot reach the router in any of these ways: /// /// ```compile_fail -/// use dim_agent_runtime::{Session, SessionScope}; +/// use dim_agent_runtime::Session; /// fn read(session: &Session) { -/// let _ = session.session_service::(); +/// let _ = session.routed(); /// } /// ``` /// /// ```compile_fail -/// use dim_agent_runtime::Session; +/// use dim_agent_runtime::{routed_scope, Session}; /// fn read(session: &Session) { -/// let _ = session.routed_scope(); +/// let _ = routed_scope(session); +/// } +/// ``` +/// +/// ```compile_fail +/// use dim_agent_runtime::RoutedSession; +/// fn build() { +/// let _ = RoutedSession::new(todo!(), todo!()); /// } /// ``` -pub fn routed_scope(session: &Session) -> Option> { - let loaded = session.assembly().loaded().ok()?; - loaded - .ctx - .get_at::(&loaded.scope.key::()) +#[derive(Clone)] +pub struct RoutedSession { + session: Session, + scope: Arc, +} + +impl RoutedSession { + pub(crate) fn new(session: Session, scope: Arc) -> Self { + Self { session, scope } + } + pub fn session(&self) -> &Session { + &self.session + } + pub fn scope(&self) -> &Arc { + &self.scope + } } #[rutis::service] diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 0dd44232e2..c15335e5e8 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1671,16 +1671,15 @@ impl AgentIndex { if session.is_closing() { return Err(RouteError::SessionClosing(id)); } - let Some(scope) = dim_agent_runtime::route::routed_scope(session) else { - return Err(if session.is_closing() { - RouteError::SessionClosing(id) - } else { - RouteError::SessionUnavailable { - session: id, - reason: "the Session's scope is not provided".into(), - } + // The router comes from the owning instance: the runtime hands out a + // handle it alone can build, so a bare `Session` has no path to it. + let Some(routed) = used.host.agent.routed_session(&id) else { + return Err(RouteError::SessionUnavailable { + session: id, + reason: "the Session's scope is not provided".into(), }); }; + let scope = routed.scope().clone(); match request.line_id { Some(line_id) => { scope diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index 46ebc75b22..d7d19f9fd0 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -166,7 +166,7 @@ fn reach( } let mut refused = Vec::new(); for (name, group) in &offered { - if !dim_agent_runtime::route::resolves(catalog, faces, name, group) { + if !dim_agent_runtime::resolves(catalog, faces, name, group) { refused.push(format!("{name} ({group})")); } } @@ -197,9 +197,7 @@ fn reach( group @ ("session" | "branch") => group, _ => continue, }; - if service.face != "data" - || !dim_agent_runtime::route::resolves(catalog, faces, name, group) - { + if service.face != "data" || !dim_agent_runtime::resolves(catalog, faces, name, group) { continue; } let declared = text.lines().any(|line| { From 4a7d63338ea0afcbf9b80252c94d64ddf81116bc Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 17:49:09 +0800 Subject: [PATCH 35/37] fix(typescript): a routed void is null, and a close says so - `RoutedReply` makes the declaration honest about the two surfaces: a method that replies nothing reaches a routed caller as `null` (the bridge maps `Value::Undefined` to JSON null) while a direct call returns `undefined`; the fixture pins the `null`, and the contract and the guide state the difference. - a Session that starts closing between the scope check and the router lookup answers `SessionClosing`, not `SessionUnavailable`. - the paragraph that describes `Session::instance` sits on `instance()` again; `routed` has its own. Refs #2015 Refs #2127 --- crates/dim-agent-runtime/src/agent.rs | 8 +++----- crates/dim-app-server/src/agents.rs | 12 +++++++++--- docs/design/contracts/runtime-owner-operations.md | 3 ++- docs/typescript-plugin-authoring.md | 4 +++- npm/branch-services.d.ts | 7 +++++-- runtime/fixtures/branch-calls.ts | 8 +++++++- xtask/check/src/types.rs | 3 ++- 7 files changed, 31 insertions(+), 14 deletions(-) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 6c71a06808..48583eda56 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -754,11 +754,9 @@ impl Session { pub fn session_service(&self) -> Result> { self.0.owner.session_face::() } - /// The instance of the loaded Session subtree, so a host can find the - /// loader rows this Session runs. Keys under it stay readable only from - /// inside the Session, so it opens no service beyond the - /// [`PublicService`] reads above. - /// This Session with its router, when its owning instance provides one. + /// This Session with its router, when its owning instance provides one: + /// the runtime alone builds the handle, so a bare [`Session`] has no path + /// to it. fn routed(&self) -> Option { let loaded = self.0.owner.loaded().ok()?; let scope = loaded.ctx.get_at::( diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index c15335e5e8..1c282046fa 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1674,9 +1674,15 @@ impl AgentIndex { // The router comes from the owning instance: the runtime hands out a // handle it alone can build, so a bare `Session` has no path to it. let Some(routed) = used.host.agent.routed_session(&id) else { - return Err(RouteError::SessionUnavailable { - session: id, - reason: "the Session's scope is not provided".into(), + // The scope goes away when the Session closes, so a close in this + // window is that answer rather than an unavailable Session. + return Err(if session.is_closing() { + RouteError::SessionClosing(id) + } else { + RouteError::SessionUnavailable { + session: id, + reason: "the Session's scope is not provided".into(), + } }); }; let scope = routed.scope().clone(); diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index dae92e976c..4a39607a24 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -40,7 +40,8 @@ line of the caller's own Session, `sessions.call` a Session and a line of it for process, and both pass the owner's arguments, reply and error through. The two surfaces spell the same failure differently: the `sessions` envelope answers snake_case codes, and a Session part's scope throws `RouteError`, whose variants are camelCase and whose owner variant carries -the owner's name, message, data and reloading flag. Agents loads the +the owner's name, message, data and reloading flag. A routed method that replies nothing answers +`null`, while a direct call to it answers nothing (`undefined`). Agents loads the Session for the call and holds it while it runs (ADR 027 D5). A target that cannot be selected answers `no_session`, `session_closing`, `session_reloading` (retry later), `session_unavailable` (report the reason) or `no_line` (final for that line), before the diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index fc3eda410d..fc3dec3e69 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -67,7 +67,9 @@ The two entries name a failure with different spellings. `sessions.call` answers camelCase (`noSession`, `sessionClosing`, `sessionReloading`, `sessionUnavailable`, `noLine`, `notDataFace`, `methodNotRoutable`, `wrongScope`, `owner`), and `owner` keeps the owner's `name`, `message`, `data` and `reloading`. Only `session_reloading`/`sessionReloading` -and an owner failure that says it reloads may be retried. +and an owner failure that says it reloads may be retried. A routed method that replies nothing +answers `null`; called directly it answers `undefined`, so do not test its reply for +truthiness. Operations whose signature cannot cross languages — a callback, a cancellation, or the calling row — are not routed: call them on an injected service directly. `xtask -- check` diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index f1500c74f7..506e2824b5 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1941,8 +1941,11 @@ export type ReplyOf = C extends { service: infer S; method: infer M } : never : never +/** What a routed call answers: a method that replies nothing reaches the caller as `null`, while a direct call to it returns `undefined`. */ +export type RoutedReply = ReplyOf extends void ? null : ReplyOf + /** A Session's own faces, typed per operation: `service` and `method` choose the reply. */ export interface SessionScope { - call(call: C): Promise> - lineCall(call: C): Promise> + call(call: C): Promise> + lineCall(call: C): Promise> } diff --git a/runtime/fixtures/branch-calls.ts b/runtime/fixtures/branch-calls.ts index ad119342b3..05e559a768 100644 --- a/runtime/fixtures/branch-calls.ts +++ b/runtime/fixtures/branch-calls.ts @@ -38,7 +38,13 @@ export async function readByCalls( const committed: number | bigint = sequence const config = await scope.call({ service: 'sessionConfig', method: 'get', args: [] }) const cwd: string = config.cwd - void [status, committed, cwd] + // A method that replies nothing reaches a routed caller as `null`. + const removed: null = await scope.call({ + service: 'sessionLoader', + method: 'remove', + args: [{ instanceId: 0 }], + }) + void [status, committed, cwd, removed] // @ts-expect-error a service the route does not resolve is refused. void scope.lineCall({ lineId: 'main', service: 'inputQueueX', method: 'withdraw', args: [] }) diff --git a/xtask/check/src/types.rs b/xtask/check/src/types.rs index 010c8f4501..16e352e0b8 100644 --- a/xtask/check/src/types.rs +++ b/xtask/check/src/types.rs @@ -110,7 +110,8 @@ fn calls(root: &Path, services: &str) -> Result { text += "\n/** A call to one of the caller's own Session's data faces. */\nexport type SessionCall = Call\n"; text += "\n/** A call through Agents: a Session's face, or one of its lines' faces. A Session\n * face takes no `lineId`. */\nexport type SessionsCall =\n | Call\n | Call\n"; text += "\n/** The reply of one call: the target method's own return type. */\nexport type ReplyOf = C extends { service: infer S; method: infer M }\n ? S extends keyof (LineFaces & SessionFaces)\n ? M extends keyof (LineFaces & SessionFaces)[S]\n ? Awaited<\n (LineFaces & SessionFaces)[S][M] extends (...args: never[]) => infer R ? R : never\n >\n : never\n : never\n : never\n"; - text += "\n/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */\nexport interface SessionScope {\n call(call: C): Promise>\n lineCall(call: C): Promise>\n}\n"; + text += "\n/** What a routed call answers: a method that replies nothing reaches the caller as `null`, while a direct call to it returns `undefined`. */\nexport type RoutedReply = ReplyOf extends void ? null : ReplyOf\n"; + text += "\n/** A Session's own faces, typed per operation: `service` and `method` choose the reply. */\nexport interface SessionScope {\n call(call: C): Promise>\n lineCall(call: C): Promise>\n}\n"; Ok(text) } From 1c3a8524c853466745d4518e41943c999fdc5657 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 18:46:40 +0800 Subject: [PATCH 36/37] docs(runtime): say per surface what a void reply and a closing Session are - `sessionScope` answers `null` for a method that replies nothing, while the `sessions` envelope leaves `value` out and a process caller reads `undefined`; the contract, the guide and the sessions-service page say so. - `Session::instance` has its paragraph back; `SessionClosing` says the process envelope answers `session_closing` instead of claiming it reads as `NoSession`. - the rig shares the mechanism names the product shares too, so the refusal of `sessionMethods`, `toolRegistry`, `guideEntries`, `sessionLifecycle` and `branchLifecycle` is asserted for being a registration point or a lifecycle service, not for being unshared. Refs #2015 Refs #2127 --- .../tests/routing_flow.rs | 37 +++++++++++++++++++ crates/dim-agent-runtime/src/agent.rs | 4 ++ crates/dim-agent-runtime/src/route.rs | 4 +- docs/design/appserver/sessions-service.md | 3 +- .../contracts/runtime-owner-operations.md | 4 +- docs/typescript-plugin-authoring.md | 4 +- npm/branch-services.d.ts | 2 +- 7 files changed, 51 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index d973a428bb..40120635f8 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -67,6 +67,15 @@ impl Rig { ("treeCommands", "session"), ("uiResources", "session"), ("sessionLoader", "session"), + // The mechanism names the product also shares: a route refuses them + // for being registration points or lifecycle services, not for + // being unshared. + ("guideEntries", "session"), + ("sessionLifecycle", "session"), + ("sessionMethods", "session"), + ("sessionScope", "session"), + ("toolRegistry", "session"), + ("branchLifecycle", "branch"), ] { builder.catalog_mut().register_shared_instance(name, group); } @@ -481,6 +490,34 @@ async fn routing_resolves_only_data_faces_of_the_scope_it_reaches() { }, "a native-only registration is not a data face" ); + for (service, group) in [ + ("sessionMethods", "session"), + ("toolRegistry", "session"), + ("guideEntries", "session"), + ] { + assert_eq!( + scope + .call(SessionCall::new(service, "register", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a registration point of the {group} group" + ); + } + for service in ["sessionLifecycle", "branchLifecycle"] { + assert_eq!( + scope + .call(SessionCall::new(service, "activated", vec![])) + .await + .unwrap_err(), + RouteError::NotDataFace { + service: service.into() + }, + "{service} is a scope lifecycle service" + ); + } assert_eq!( scope .call(SessionCall::new("sessionScope", "lineCall", vec![])) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 48583eda56..e4f0f2bdb4 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -764,6 +764,10 @@ impl Session { )?; Some(crate::route::RoutedSession::new(self.clone(), scope)) } + /// The instance of the loaded Session subtree, so a host can find the + /// loader rows this Session runs. Keys under it stay readable only from + /// inside the Session, so it opens no service beyond the + /// [`PublicService`] reads above. pub fn instance(&self) -> Result { Ok(self.0.owner.loaded()?.scope.instance) } diff --git a/crates/dim-agent-runtime/src/route.rs b/crates/dim-agent-runtime/src/route.rs index cbae9bf4dc..4ada4e43b5 100644 --- a/crates/dim-agent-runtime/src/route.rs +++ b/crates/dim-agent-runtime/src/route.rs @@ -64,8 +64,8 @@ pub enum RouteError { #[error("no live Session {0}")] NoSession(String), /// The Session instance is closing, and so is a call to one of its lines. - /// A Session-scoped caller ends its work; a process caller treats it as - /// [`Self::NoSession`]. + /// A Session-scoped caller ends its work, and a process caller reads the + /// same answer as `session_closing` and ends the work it was doing. #[error("Session {0} is closing")] SessionClosing(String), /// Agents is reloading and cannot take calls yet. A process caller retries diff --git a/docs/design/appserver/sessions-service.md b/docs/design/appserver/sessions-service.md index 1b0231a8ed..cc5b5234c1 100644 --- a/docs/design/appserver/sessions-service.md +++ b/docs/design/appserver/sessions-service.md @@ -141,7 +141,8 @@ The call path from a consumer to a Session (a call path, not an assembly graph): | --- | --- | | Identity | Name `sessions`, process scope, control node only, no instance key | | Provider | Agents' directory part. Each call looks up the current `AgentIndex`; while there is none, the call fails `reloading`. Index reload ends cancellable calls, preserves own-outcome calls (§8.3), and never reloads a consumer (D1) | -| Calls | All methods are async. Each takes one request object, carried as `[request]` by rutis, and returns one envelope: `{ok: true, value}` or `{ok: false, error: SessionsError}`. The error carries `retryable` beside its `code` and `message`. An unknown method, a missing or extra argument, an unknown field or a wrong type replies `rejected` | +| Calls | All methods are async. Each takes one request object, carried as `[request]` by rutis, and returns one envelope: `{ok: true, value}` or `{ok: false, error: SessionsError}`. A routed method +that replies nothing omits `value` (`{ok: true}`), so a caller reads it as `undefined`. The error carries `retryable` beside its `code` and `message`. An unknown method, a missing or extra argument, an unknown field or a wrong type replies `rejected` | | Errors | `SessionsError {code, message, retryable}` (§9) | | Cancellation | The consumer drops the call. Dropping a Rust future ends cancellable work and releases its lease. A dropped `launch` still finishes creation (§6.1); admitted `input` retains its task and lease (§6.2) | | Rust consumers | Look up `AgentIndex` on each use, as Rpc looks up Provider, and call the typed methods in Appendix A. They may also use the named service | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 4a39607a24..3ceebfd579 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -41,7 +41,9 @@ process, and both pass the owner's arguments, reply and error through. The two s the same failure differently: the `sessions` envelope answers snake_case codes, and a Session part's scope throws `RouteError`, whose variants are camelCase and whose owner variant carries the owner's name, message, data and reloading flag. A routed method that replies nothing answers -`null`, while a direct call to it answers nothing (`undefined`). Agents loads the +`null` through `sessionScope` (the bridge maps an absent value to JSON null), and the `sessions` +envelope leaves `value` out so a process caller reads `undefined`; a direct call answers nothing +(`undefined`) either way. Agents loads the Session for the call and holds it while it runs (ADR 027 D5). A target that cannot be selected answers `no_session`, `session_closing`, `session_reloading` (retry later), `session_unavailable` (report the reason) or `no_line` (final for that line), before the diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index fc3dec3e69..3325678403 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -68,8 +68,8 @@ camelCase (`noSession`, `sessionClosing`, `sessionReloading`, `sessionUnavailabl `noLine`, `notDataFace`, `methodNotRoutable`, `wrongScope`, `owner`), and `owner` keeps the owner's `name`, `message`, `data` and `reloading`. Only `session_reloading`/`sessionReloading` and an owner failure that says it reloads may be retried. A routed method that replies nothing -answers `null`; called directly it answers `undefined`, so do not test its reply for -truthiness. +answers `null` through `sessionScope`; `sessions.call` leaves `value` out, so a process caller +reads `undefined`; a direct call answers `undefined`. Do not test such a reply for truthiness. Operations whose signature cannot cross languages — a callback, a cancellation, or the calling row — are not routed: call them on an injected service directly. `xtask -- check` diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 506e2824b5..3c4c521e6b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1407,7 +1407,7 @@ export interface PartRegistry { /** Why a routed call did not reach a reply. */ export type RouteError = | /** The Session is not there, has no owner, or is closed and cannot load again. Only a process caller receives it; Agents loads and holds a Session that is merely not loaded (ADR 027 D5), so this is final. */ { noSession: string } - | /** The Session instance is closing, and so is a call to one of its lines. A Session-scoped caller ends its work; a process caller treats it as [`Self::NoSession`]. */ { sessionClosing: string } + | /** The Session instance is closing, and so is a call to one of its lines. A Session-scoped caller ends its work, and a process caller reads the same answer as `session_closing` and ends the work it was doing. */ { sessionClosing: string } | /** Agents is reloading and cannot take calls yet. A process caller retries later. */ { sessionReloading: string } | /** The Session exists but cannot be loaded now: its restore failed, or the Agent that owns it is unavailable. The caller reports the reason and does not retry. */ { sessionUnavailable: { session: string; reason: string } } | /** The Session is live but the line is closing, closed, or not one of its lines. Final for that line: no hold and no retry. */ { noLine: { session: string; line: string } } From 673342a07f10364db9a4a12995e1fde04fc0aa0a Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 19:05:53 +0800 Subject: [PATCH 37/37] chore: adapt to main's create_session and restore_session options Main now takes `CreateSessionOptions` and `RestoreSessionOptions`; the two probe rigs and the routing test pass the defaults. No interface change on this side. Refs #2015 Refs #2127 --- crates/dim-agent-capabilities/tests/routing_flow.rs | 8 ++++++-- crates/dim-agent-scheduler/tests/data_faces_flow.rs | 11 +++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/routing_flow.rs b/crates/dim-agent-capabilities/tests/routing_flow.rs index 40120635f8..81ced4a78f 100644 --- a/crates/dim-agent-capabilities/tests/routing_flow.rs +++ b/crates/dim-agent-capabilities/tests/routing_flow.rs @@ -90,7 +90,7 @@ impl Rig { async fn open(&self) -> Session { self.host - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .expect("a Session opens") } @@ -358,7 +358,11 @@ async fn an_idle_unloaded_session_answers_session_closing_until_it_loads_again() "a scope of a Session that is gone reports its Session as closing" ); - let restored = rig.host.restore_session(id.clone()).await.unwrap(); + let restored = rig + .host + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); assert!( rig.scope(&restored) .line_call(LineCall::new("main", "timeline", "sequence", vec![])) diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index edfd574f13..89867af9cf 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -795,10 +795,13 @@ async fn a_process_call_by_id_reaches_a_live_session_and_names_the_reason_it_can .server .agent() .expect("the product profile has an Agent") - .create_session(dim_agent_runtime::SessionConfig { - cwd: rig._home.path().to_string_lossy().into_owned(), - ..Default::default() - }) + .create_session( + dim_agent_runtime::SessionConfig { + cwd: rig._home.path().to_string_lossy().into_owned(), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let id = session.id().to_owned();