From c300f288a9d70efebb6b1b9f421ad8d5d13bcc52 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 12:16:00 +0800 Subject: [PATCH 01/12] Plan move Session admission, faults and branch opening to owners From 018188285e891e73e255ee3e61486a19d3cd16cb Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 19:04:42 +0800 Subject: [PATCH 02/12] Expose branch opening and submit checks through their existing owners --- .../dim-agent-capabilities/src/input_queue.rs | 21 ++- .../src/input_queue/face.rs | 124 ++++++++++++++++++ crates/dim-agent-capabilities/src/prompt.rs | 8 +- .../src/tool_binding.rs | 11 +- crates/dim-agent-runtime/src/assembly.rs | 5 - crates/dim-agent-runtime/src/config.rs | 65 ++++++++- crates/dim-agent-runtime/src/names.rs | 1 - .../dim-agent-runtime/src/timeline_context.rs | 32 +---- crates/dim-app-server/src/lib.rs | 2 - .../dim-app-server/src/session_typescript.rs | 1 + .../tests/transport_flow/branch_typescript.rs | 33 +++++ .../tests/transport_flow/submit_checks.rs | 48 +++++++ docs/architecture/README.md | 2 +- .../rust-agent/generated/catalog.md | 5 +- .../rust-agent/generated/local/services.json | 46 +------ .../rust-agent/generated/local/services.md | 2 - .../rust-agent/generated/local/services.mmd | 2 - .../rust-agent/generated/services.json | 46 +------ .../rust-agent/generated/services.md | 2 - .../rust-agent/generated/services.mmd | 2 - .../rust-agent/plugins/InputQueue.md | 6 +- .../architecture/rust-agent/plugins/Prompt.md | 3 +- .../rust-agent/plugins/ToolExecution.md | 5 +- .../rust-agent/plugins/ToolRegistry.md | 4 +- docs/architecture/rust-agent/single-tree.md | 2 +- .../rust-agent/tool-contributions.md | 6 +- docs/design/contracts/session-boundary.md | 2 +- docs/design/roadmap.md | 2 +- docs/design/service-faces.md | 2 - docs/design/session-typescript.md | 2 +- docs/zh/design/contracts/session-boundary.md | 2 +- npm/branch-services.d.ts | 6 + npm/plugin.d.ts | 11 ++ runtime/fixtures/branch-opening.ts | 14 ++ runtime/fixtures/submit-check.ts | 22 ++++ tests/integration/tests/prompt_lifecycle.rs | 12 +- 36 files changed, 377 insertions(+), 182 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/input_queue/face.rs create mode 100644 runtime/fixtures/branch-opening.ts create mode 100644 runtime/fixtures/submit-check.ts diff --git a/crates/dim-agent-capabilities/src/input_queue.rs b/crates/dim-agent-capabilities/src/input_queue.rs index 9d6aa61e0a..4a411301f9 100644 --- a/crates/dim-agent-capabilities/src/input_queue.rs +++ b/crates/dim-agent-capabilities/src/input_queue.rs @@ -1,3 +1,4 @@ +mod face; mod pending; mod recovery; @@ -450,7 +451,8 @@ impl DynPlugin for InputQueuePlugin { pub const INPUT_METHODS: &str = "session.input"; /// The operator-input entry that asks the submit checks (Hooks A.6.2). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub enum SubmitEntry { /// Rpc `session.submit`. Submit, @@ -471,7 +473,8 @@ impl SubmitEntry { } /// The input an entry is about to write, as its checks see it (Hooks A.6.2). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SubmitCheckRequest { pub entry: SubmitEntry, pub branch_id: String, @@ -481,7 +484,8 @@ pub struct SubmitCheckRequest { } /// What one check decided for the input (Hooks A.6.2). -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] pub enum SubmitCheckReply { /// The input may be written; these contexts go after the operator's own /// content, in name order. `warnings` are for the caller to show, never @@ -497,7 +501,8 @@ pub enum SubmitCheckReply { /// What the table decided for the input (Hooks A.6.2): every check that ran, /// combined in name order. A block ends the table's work and carries neither /// blocks nor warnings. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] pub enum SubmitDecision { /// The input may be written. Proceed { @@ -527,7 +532,7 @@ pub struct CheckInterrupted; /// the operator-input entries call them before writing anything. No check is /// registered unless a part registers one, and then the entries write /// unchecked. -#[derive(Default)] +#[derive(Clone, Default)] pub struct SubmitChecks { checks: Arc>>, } @@ -645,6 +650,7 @@ struct WithdrawParams { /// Serves `session.input.withdraw` for every branch of its Session through /// the branch's InputQueue, so Rpc names no owning service. pub struct InputMethodsPlugin { + session: rutis::host::InstanceId, tree: Key, methods: Key, checks: Key, @@ -652,6 +658,7 @@ pub struct InputMethodsPlugin { impl InputMethodsPlugin { pub fn new(names: &Names<'_>) -> std::result::Result { Ok(Self { + session: names.instance(dim_agent_runtime::SESSION_GROUP)?, tree: names.key()?, methods: names.key()?, checks: names.key()?, @@ -671,6 +678,10 @@ impl DynPlugin for InputMethodsPlugin { let methods = ctx.require_at(&self.methods)?; let checks = Arc::new(SubmitChecks::default()); ctx.provide_at(self.checks.clone(), checks.clone())?; + ctx.provide_at::( + rutis_bridge::session::host_key_in("submitChecks", self.session), + checks.clone(), + )?; methods.register( ctx, INPUT_METHODS, diff --git a/crates/dim-agent-capabilities/src/input_queue/face.rs b/crates/dim-agent-capabilities/src/input_queue/face.rs new file mode 100644 index 0000000000..cc98350650 --- /dev/null +++ b/crates/dim-agent-capabilities/src/input_queue/face.rs @@ -0,0 +1,124 @@ +use super::{CheckSubmission, SubmitCheckReply, SubmitCheckRequest, SubmitChecks}; +use crate::{ + host::{HostError, HostFuture}, + port_faces::{invalid, unknown_method}, +}; +use rutis::host::CtxHost; +use rutis_bridge::session::{HostDispatch, Reference, Reply, Value, arg, decode_value, settle}; +use std::sync::Arc; +use tokio_util::sync::CancellationToken; + +struct ForeignCheck { + callback: Reference, + closing: CancellationToken, +} + +impl CheckSubmission for ForeignCheck { + fn check( + &self, + request: SubmitCheckRequest, + cancel: CancellationToken, + ) -> HostFuture<'_, SubmitCheckReply> { + Box::pin(async move { + let stop = cancel.child_token(); + let _finish = stop.clone().drop_guard(); + let cancelled = Value::callback(move |_| { + let stop = stop.clone(); + Ok(Value::future(async move { + stop.cancelled().await; + Ok(Value::Undefined) + })) + }); + let reply = async { + let result = self + .callback + .call_async(Value::List(vec![arg(&request)?, cancelled])) + .await?; + decode_value(settle(result).await?) + }; + tokio::select! { + biased; + _ = cancel.cancelled() => Err(HostError::Cancelled("submit check interrupted".into())), + _ = self.closing.cancelled() => Err(HostError::failed("submit check unloaded")), + result = reply => result.map_err(|error| HostError::failed(error.to_string())), + } + }) + } +} + +impl HostDispatch for SubmitChecks { + fn methods(&self) -> Option { + Some(serde_json::json!({"register":"async","check":"async"})) + } + + fn invoke(&self, method: &str, args: Value) -> Reply { + match method { + "register" => { + let [name, Value::Reference(callback)] = <[_; 2]>::try_from(args.list()?) + .map_err(|_| invalid("submitChecks", "register expects a name and a check"))? + else { + return Err(invalid("submitChecks", "expected a check function")); + }; + if !callback.is_function() { + return Err(invalid("submitChecks", "expected a check function")); + } + let name: String = decode_value(name)?; + let row = rutis_bridge::session::caller_row() + .ok_or_else(|| invalid("submitChecks", "register requires a calling row"))?; + let registered = self + .register( + row.ctx(), + &name, + Arc::new(ForeignCheck { + callback, + closing: row.ctx().cancellation_token(), + }), + ) + .map(|()| Value::Undefined) + .map_err(|error| { + rutis_bridge::exports::failure( + "SubmitCheckError", + "failed", + error.to_string(), + None, + ) + }); + Ok(Value::future(async move { registered })) + } + "check" => { + let [request, Value::Reference(cancelled)] = <[_; 2]>::try_from(args.list()?) + .map_err(|_| { + invalid( + "submitChecks", + "check expects a request and cancellation function", + ) + })? + else { + return Err(invalid("submitChecks", "expected a cancellation function")); + }; + if !cancelled.is_function() { + return Err(invalid("submitChecks", "expected a cancellation function")); + } + let request: SubmitCheckRequest = decode_value(request)?; + let owner = self.clone(); + let stop = rutis_bridge::session::caller_row() + .map(|row| row.ctx().cancellation_token().child_token()) + .unwrap_or_default(); + Ok(Value::cancellable_future(async move { + let _finish = stop.clone().drop_guard(); + let run = owner.check(&request, &stop); + tokio::pin!(run); + let result = tokio::select! { + result = &mut run => result, + _ = async { settle(cancelled.call_async(Value::List(vec![])).await?).await } => { + stop.cancel(); + run.await + } + }.map_err(|_| rutis_bridge::exports::failure("SubmitCheckError","cancelled","submit check interrupted".into(),None))?; + arg(&result) + })) + } + _ => Err(unknown_method("submitChecks", method)), + } + } +} diff --git a/crates/dim-agent-capabilities/src/prompt.rs b/crates/dim-agent-capabilities/src/prompt.rs index f02f1cd77d..5be6c9e300 100644 --- a/crates/dim-agent-capabilities/src/prompt.rs +++ b/crates/dim-agent-capabilities/src/prompt.rs @@ -132,7 +132,6 @@ pub struct Prompt { identity: Arc, lifecycle: CancellationToken, branch_phase: Arc, - opening: Arc, opened: tokio::sync::watch::Sender>>, /// The Session's guide entries: the composition the listener adopts. guide: Arc, @@ -723,7 +722,6 @@ pub struct PromptPlugin { identity: rutis::host::Key, faults: rutis::host::Key, branch_phase: rutis::host::Key, - opening: rutis::host::Key, guide: rutis::host::Key, state: rutis::host::Key>, prompt: rutis::host::Key, @@ -740,7 +738,6 @@ impl PromptPlugin { identity: names.key()?, faults: names.key()?, branch_phase: names.key()?, - opening: names.key()?, guide: names.key()?, state: names.state_cell()?, prompt: names.key()?, @@ -762,7 +759,6 @@ impl DynPlugin for PromptPlugin { self.identity.erase(), self.faults.erase(), self.branch_phase.erase(), - self.opening.erase(), self.guide.erase(), ] } @@ -776,7 +772,6 @@ impl DynPlugin for PromptPlugin { let identity = ctx.require_at(&self.identity)?; let faults = ctx.require_at(&self.faults)?; let branch_phase = ctx.require_at(&self.branch_phase)?; - let opening = ctx.require_at(&self.opening)?; let guide = ctx.require_at(&self.guide)?; if ctx.cancellation_token().is_cancelled() { return Ok(Effect::Done); @@ -793,7 +788,6 @@ impl DynPlugin for PromptPlugin { identity, lifecycle: ctx.cancellation_token(), branch_phase, - opening, opened: tokio::sync::watch::channel(None).0, guide, tasks: TaskTracker::new(), @@ -947,7 +941,7 @@ impl DynPlugin for PromptPlugin { }; if let Some(snapshot) = opening { let (reply, opened) = oneshot::channel(); - prompt.opening.register(Box::pin(async move { + prompt.branch_phase.admit_opening(Box::pin(async move { opened .await .map_err(|_| AgentError::Closed("Prompt".into()))? diff --git a/crates/dim-agent-capabilities/src/tool_binding.rs b/crates/dim-agent-capabilities/src/tool_binding.rs index d058f440f7..99f7e2777e 100644 --- a/crates/dim-agent-capabilities/src/tool_binding.rs +++ b/crates/dim-agent-capabilities/src/tool_binding.rs @@ -13,8 +13,8 @@ use crate::{ tool_registry::{ToolClaim, ToolContribution, ToolRegistry, ToolSourceSet}, }; use dim_agent_runtime::{ - AgentError, BranchLifecycle, BranchOpening, Dispatcher, Names, QueryFilter, QueryOperand, - QueryOutput, QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, Timeline, TimelineQuery, + AgentError, BranchLifecycle, Dispatcher, Names, QueryFilter, QueryOperand, QueryOutput, + QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, Timeline, TimelineQuery, TimelineQueryScope, }; use dim_agent_types::*; @@ -405,7 +405,6 @@ pub struct ToolBindingPlugin { timeline: Key, phase: Key, dispatcher: Key, - opening: Key, } impl ToolBindingPlugin { pub fn new(names: &Names<'_>) -> std::result::Result { @@ -416,7 +415,6 @@ impl ToolBindingPlugin { timeline: names.key()?, phase: names.key()?, dispatcher: names.key()?, - opening: names.key()?, }) } } @@ -431,7 +429,6 @@ impl DynPlugin for ToolBindingPlugin { self.timeline.erase(), self.phase.erase(), self.dispatcher.erase(), - self.opening.erase(), ] } fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { @@ -441,7 +438,7 @@ impl DynPlugin for ToolBindingPlugin { let timeline = ctx.require_at(&self.timeline)?; let phase = ctx.require_at(&self.phase)?; let dispatcher = ctx.require_at(&self.dispatcher)?; - let opening = ctx.require_at(&self.opening)?; + let opening = phase.clone(); let binding = Arc::new(ToolBinding { registry: registry.clone(), state: Mutex::default(), @@ -481,7 +478,7 @@ impl DynPlugin for ToolBindingPlugin { opening_cancel.clone(), ); let (reply, receipt) = tokio::sync::oneshot::channel(); - let registered = opening.register(Box::pin(async move { + let registered = opening.admit_opening(Box::pin(async move { receipt .await .map_err(|_| AgentError::Closed("ToolBinding".into()))? diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index d39d7f9921..3217c90525 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -1268,7 +1268,6 @@ struct LoadedBranch { timeline: Timeline, dispatcher: Dispatcher, lifecycle: BranchLifecycle, - opening: Arc, } struct BranchScopePlugin { owner: Arc, @@ -1305,8 +1304,6 @@ impl DynPlugin for BranchScopePlugin { ctx.provide_at(scope.key::(), Arc::new(dispatcher.clone()))?; let lifecycle = BranchLifecycle::new(); ctx.provide_at(scope.key::(), Arc::new(lifecycle.clone()))?; - let opening = Arc::new(BranchOpening::new()); - ctx.provide_at(scope.key::(), opening.clone())?; ctx.provide_at( scope.key::(), Arc::new(TimelineIdentity { @@ -1325,7 +1322,6 @@ impl DynPlugin for BranchScopePlugin { timeline, dispatcher, lifecycle, - opening, })); let site = Arc::new(crate::parts::MountSite { scope: crate::PartScope::Branch, @@ -1458,7 +1454,6 @@ impl TimelineFactory { branch.timeline.clone(), branch.dispatcher.clone(), branch.lifecycle.clone(), - branch.opening.clone(), parent.faults.clone(), parent.assembly.catalog.clone(), )) diff --git a/crates/dim-agent-runtime/src/config.rs b/crates/dim-agent-runtime/src/config.rs index bf5935d826..8efce79ab8 100644 --- a/crates/dim-agent-runtime/src/config.rs +++ b/crates/dim-agent-runtime/src/config.rs @@ -307,32 +307,83 @@ impl Phases

{ /// branch's [`crate::TimelineContext`]. Capabilities that spawn background /// work in `apply` wait for [`Self::activated`] before doing it. #[derive(Clone)] -pub struct BranchLifecycle(Phases); +pub struct BranchLifecycle { + phases: Phases, + opening: Arc>>>, +} +type OpeningReceipt = rutis::host::BoxFuture<'static, crate::Result<()>>; + #[service] impl BranchLifecycle { pub(crate) fn new() -> Self { - Self(Phases::new()) + Self { + phases: Phases::new(), + opening: Arc::new(Mutex::new(Some(Vec::new()))), + } + } + /// Registers a completion for the current branch opening. Once opening seals, + /// registration fails. A failed completion fails the opening. + pub fn register_opening( + &self, + completion: Arc< + dyn Fn() -> rutis::host::BoxFuture<'static, std::result::Result<(), rutis::Error>> + + Send + + Sync, + >, + ) -> std::result::Result<(), crate::AgentError> { + self.admit_opening(Box::pin(async move { Ok(completion().await?) })) } + #[service(skip)] pub fn phase(&self) -> BranchPhase { - self.0.get() + self.phases.get() } #[service(skip)] pub fn watch(&self) -> tokio::sync::watch::Receiver { - self.0.watch() + self.phases.watch() } /// Waits until the branch leaves `Loading`: true when it became Active, /// false when it closes without ever starting. pub async fn activated(&self) -> bool { - self.0.reach(|phase| *phase != BranchPhase::Loading).await == Some(BranchPhase::Active) + self.phases + .reach(|phase| *phase != BranchPhase::Loading) + .await + == Some(BranchPhase::Active) } /// Waits until the branch starts closing; background work ends then, /// without waiting for its capability to unload. pub async fn closing(&self) { - self.0.reach(|phase| *phase >= BranchPhase::Closing).await; + self.phases + .reach(|phase| *phase >= BranchPhase::Closing) + .await; } pub(crate) fn advance(&self, next: BranchPhase) { - self.0.advance(next); + self.phases.advance(next); + } +} + +impl BranchLifecycle { + pub fn admit_opening(&self, receipt: OpeningReceipt) -> crate::Result<()> { + let mut receipts = self.opening.lock().unwrap(); + receipts + .as_mut() + .ok_or_else(|| crate::AgentError::Closed("branch opening".into()))? + .push(receipt); + Ok(()) + } + pub(crate) async fn finish_opening( + &self, + ctx: &rutis::Ctx, + scope: rutis::host::PluginId, + ) -> crate::Result<()> { + use futures_util::{StreamExt, stream::FuturesUnordered}; + let receipts = self.opening.lock().unwrap().take().unwrap_or_default(); + let mut pending: FuturesUnordered<_> = receipts.into_iter().collect(); + while let Some(result) = pending.next().await { + result?; + ctx.emit(crate::assembly::OpeningAdvanced(scope))?; + } + Ok(()) } } diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index c44bf9274f..f9208baf6e 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -108,7 +108,6 @@ pub fn catalog() -> ServiceCatalog { register::(&mut catalog, branch); register::(&mut catalog, branch); register::(&mut catalog, branch); - register::(&mut catalog, branch); register::(&mut catalog, branch); register::(&mut catalog, branch); catalog diff --git a/crates/dim-agent-runtime/src/timeline_context.rs b/crates/dim-agent-runtime/src/timeline_context.rs index 204fb8683d..bcf2b01a12 100644 --- a/crates/dim-agent-runtime/src/timeline_context.rs +++ b/crates/dim-agent-runtime/src/timeline_context.rs @@ -41,7 +41,6 @@ pub struct TimelineContext { timeline: Timeline, dispatcher: Dispatcher, lifecycle: BranchLifecycle, - opening: Arc, /// Signals a possible change of [`BranchStatus`]; the status itself is /// read from its owners on query. changed: watch::Sender<()>, @@ -64,33 +63,6 @@ const LOOP_RETURN_POLL: std::time::Duration = std::time::Duration::from_millis(1 /// The latest stop and the sequence of its interrupt (0 until written). type StopOperation = (Arc>, Arc); -/// Receipts registered synchronously by the unique branch opening dispatch. -/// Work remains owned and joined by the capability, not by this collector. -pub struct BranchOpening(Mutex>>>>); -impl BranchOpening { - pub fn register(&self, receipt: BoxFuture<'static, Result<()>>) -> Result<()> { - let mut receipts = self.0.lock().unwrap(); - receipts - .as_mut() - .ok_or_else(|| AgentError::Closed("branch opening".into()))? - .push(receipt); - Ok(()) - } - pub(crate) fn new() -> Self { - Self(Mutex::new(Some(Vec::new()))) - } - async fn finish(&self, ctx: &Ctx, scope: rutis::host::PluginId) -> Result<()> { - use futures_util::{StreamExt, stream::FuturesUnordered}; - let receipts = self.0.lock().unwrap().take().unwrap_or_default(); - let mut pending: FuturesUnordered<_> = receipts.into_iter().collect(); - while let Some(result) = pending.next().await { - result?; - ctx.emit(OpeningAdvanced(scope))?; - } - Ok(()) - } -} - impl TimelineContext { /// Dispatches the opening through `through`, seals registration and waits /// for capability receipts and their committed fence. First activations, @@ -114,7 +86,7 @@ impl TimelineContext { .await .map_err(|_| AgentError::Closed("branch dispatch".into()))?; } - let receipts = self.opening.finish(&self.ctx, self.view.id); + let receipts = self.lifecycle.finish_opening(&self.ctx, self.view.id); tokio::pin!(receipts); loop { if let Some(error) = dispatch.borrow_and_update().failure.clone() { @@ -165,7 +137,6 @@ impl TimelineContext { timeline: Timeline, dispatcher: Dispatcher, lifecycle: BranchLifecycle, - opening: Arc, faults: FaultReporter, catalog: Arc, ) -> Arc { @@ -182,7 +153,6 @@ impl TimelineContext { timeline, dispatcher, lifecycle, - opening, changed: watch::channel(()).0, failure: Mutex::new(None), ended: AtomicU64::new(0), diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index e892c17b0b..8bec8a343b 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1486,7 +1486,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("promptSourcesBranch", "hot-path"), ("agentIndex", "owner-api"), ("agentLoop", "hot-path"), - ("branchOpening", "hot-path"), ("compactionStrategyHost", "hot-path"), ("configurationPublisher", "hot-path"), ("configureControl", "hot-path"), @@ -1516,7 +1515,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("sessionLoader", "control"), ("sessionStore", "owner-api"), ("settingsService", "owner-api"), - ("submitChecks", "hot-path"), ("timelineFactory", "control"), ("timelineTree", "owner-api"), ("timelineTreeControl", "owner-api"), diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index bdc540f30e..4cc3bcd244 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -99,6 +99,7 @@ pub fn share_names(catalog: &mut ServiceCatalog) { catalog.register_shared_instance(name, group); } catalog + .register_shared_instance("submitChecks", SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) .register_shared_instance(name_of::(), SESSION_GROUP) diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 2b1a27572d..617fe1dd0f 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -554,3 +554,36 @@ async fn node_branch_typescript_writes_and_follows_extension_events() { server.join().await.unwrap(); let _ = std::fs::remove_dir_all(&home); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_branch_opening_completion_can_refuse_session_creation() { + let mut parts = branch_part(); + parts.rows = vec![json!({ + "id": "opening-receipt", + "name": parts.anchor.parent().unwrap().join("fixtures/branch-opening.ts"), + "provides": {}, + })]; + let (server, agent) = launch_with( + Arc::new(MockTools), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.require_part("OpeningReceiptFixture"); + }, + ) + .await; + let error = agent + .create_session(Default::default()) + .await + .err() + .expect("opening must fail"); + assert!( + error.to_string().contains("opening completion refused"), + "{error}" + ); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/crates/dim-app-server/tests/transport_flow/submit_checks.rs b/crates/dim-app-server/tests/transport_flow/submit_checks.rs index ce0c9ff880..341f906806 100644 --- a/crates/dim-app-server/tests/transport_flow/submit_checks.rs +++ b/crates/dim-app-server/tests/transport_flow/submit_checks.rs @@ -806,3 +806,51 @@ async fn concurrent_duplicates_report_warnings_once_for_the_committed_write() { server.shutdown(); server.join().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_submit_check_registers_on_the_native_admission_table() { + let mut parts = super::session_typescript::fixture(); + parts.rows = vec![json!({ + "id": "submit-check", + "name": parts.anchor.parent().unwrap().join("fixtures/submit-check.ts"), + "provides": {}, + })]; + let (server, agent) = super::launch_with( + Arc::new(MockTools), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.require_part("SubmitCheckFixture"); + }, + ) + .await; + let mut client = Client::new_version(&server, false, 3).await; + let created = client.rpc("session.create", create(json!([]))).await; + assert_ok(&created); + let id = created["result"]["sessionId"].as_str().unwrap(); + let probe = client + .rpc("session.checkfixture.probe", json!({"sessionId":id})) + .await; + assert_ok(&probe); + assert_eq!( + probe["result"], + json!({"kind":"proceed","blocks":[],"warnings":[{"check":"fixture","message":"foreign check ran"}]}) + ); + let refused = client + .rpc( + "session.submit", + json!({"sessionId":id,"branchId":"main","text":"refuse this input"}), + ) + .await; + assert_eq!( + refused["error"]["data"]["appError"], "input_blocked", + "{refused}" + ); + assert_eq!(refused["error"]["message"], "foreign check refused"); + assert!(inputs(&agent.get_session(id).unwrap()).await.is_empty()); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 313ca487d7..437c903e5a 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -27,7 +27,7 @@ Hosts register process modules before awaiting `AgentBuilder::install`. Scoped m Loader readiness, reconcile and process activation share the opening’s inactivity policy: each row's first activation in that process subtree renews the interval. Dependencies are `Keyed`, `KeyedGate`, `Option>` and `When`; contributions register with their owner ([How Dim uses rutis](../design/rutis-usage.md#appendix-a-rust-binding)). -Session and child-branch assembly observe progress within their own opening; another scope cannot renew their interval. Opening dispatch advancement and receipt completion renew the same inactivity interval after assembly. A storage read has its own cancellation budget. Opening handlers register `BranchOpening` receipts and return without awaiting host I/O on the Dispatcher. Each capability owns and joins its work; the tree waits for the receipts and their committed dispatch fence before publishing readiness or the first child input. Closing signals initial prompt loading before dispatch drains. Deadlines request cancellation, not abandonment: a non-cooperative host still has to settle before cleanup completes. +Session and child-branch assembly observe progress within their own opening; another scope cannot renew their interval. Opening dispatch advancement and receipt completion renew the same inactivity interval after assembly. A storage read has its own cancellation budget. Opening handlers register `BranchLifecycle` receipts and return without awaiting host I/O on the Dispatcher. Each capability owns and joins its work; the tree waits for the receipts and their committed dispatch fence before publishing readiness or the first child input. Closing signals initial prompt loading before dispatch drains. Deadlines request cancellation, not abandonment: a non-cooperative host still has to settle before cleanup completes. The public host exposes provider/account operations and leases request-local credentials. It does not implement a particular account realm, PKCE flow, token exchange, refresh policy, private catalog projection or provider-specific error classification. Those behaviors belong to the separately supplied plugin. The trusted native host owns generic `pluginFiles` transactions: credential-file bytes, including refresh tokens, cross the local Rutis bridge for storage, without being interpreted by the host. This is source separation, not a sandbox against the host or same-user processes. Refresh tokens are excluded from provider connection DTOs, model requests, terminal RPC, history and logs. Terminal/history projection also excludes access credentials, authorization codes and PKCE state. A credential or recovery result acquires its release guard inside the accepted, generation-tracked operation, before validation or handoff to a caller; a dropped waiter cannot orphan it. A delivered or buffered lease retains a tracker token until release is enqueued, so generation cleanup cannot outrun its owner. Release uses that generation's dispatch, not whichever plugin is currently installed. diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index d2481d5fb9..c57c983baf 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -90,7 +90,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `sessionLoader` | session | SessionScope | internal(control) | — | | `sessionMethods` | session | SessionMethods | data | `register` async | | `skillsConfig` | session | SessionScope | data | `get` async | -| `submitChecks` | session | InputMethods | internal(hot-path) | — | +| `submitChecks` | session | InputMethods | data | `check` async, `register` async | | `timelineFactory` | session | SessionScope | internal(control) | — | | `timelineStore` | session | SessionScope | data | `append` sync, `batchEnd` async, `batchEndAt` async, `branches` async, `closeCommits` async, `commits` async, `createSession` async, `head` async, `latestSnapshot` async, `query` async, `readPage` async, `readSegments` async, `releaseSession` async, `rollbackSession` async, `saveSnapshot` async, `sessionConfig` async, `trace` async | | `timelineTree` | session | TimelineTree | internal(owner-api) | — | @@ -103,9 +103,8 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `agentLoop` | branch | Loop | internal(hot-path) | — | | `approval` | branch | Approval | data | `decide` async, `pending` async | | `backgroundExec` | branch | BackgroundExec | data | `output` async, `outputPage` async, `stop` async, `wait` async | -| `branchLifecycle` | branch | BranchScope | data | `activated` async, `closing` async | +| `branchLifecycle` | branch | BranchScope | data | `activated` async, `closing` async, `registerOpening` async | | `branchLine` | branch | BranchLine | data | `cursor` async, `ending` async, `resolved` async | -| `branchOpening` | branch | BranchScope | internal(hot-path) | — | | `configurationPublisher` | branch | ContextPreparation | internal(hot-path) | — | | `configureControl` | branch | Prompt | internal(hot-path) | — | | `contextPreparation` | branch | ContextPreparation | internal(hot-path) | — | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 998b011461..38999dd1d6 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -299,11 +299,6 @@ "service": "dim_agent_runtime::core::timeline::Timeline@main", "scope": null, "status": "Ready" - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "status": "Ready" } ], "resolved": [ @@ -336,12 +331,6 @@ "scope": null, "provider": 60, "generation": 1 - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "provider": 60, - "generation": 1 } ], "reads": [ @@ -374,12 +363,6 @@ "provider": 60, "declared": true, "external": false - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "provider": 60, - "declared": true, - "external": false } ] }, @@ -643,11 +626,6 @@ "service": "dim_agent_runtime::lifecycle::FaultReporter@session", "scope": null, "status": "Ready" - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "status": "Ready" } ], "resolved": [ @@ -704,12 +682,6 @@ "scope": null, "provider": 33, "generation": 1 - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "provider": 60, - "generation": 1 } ], "reads": [ @@ -766,12 +738,6 @@ "provider": 33, "declared": true, "external": true - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "provider": 60, - "declared": true, - "external": false } ] }, @@ -2164,12 +2130,6 @@ "generation": 1, "removing": false }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "provider": 60, - "generation": 1, - "removing": false - }, { "service": "dyn dim_agent_runtime::contracts::ConfigureControl@main", "provider": 74, @@ -4214,6 +4174,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#submitChecks@session", + "provider": 39, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#timelineStore@session", "provider": 33, diff --git a/docs/architecture/rust-agent/generated/local/services.md b/docs/architecture/rust-agent/generated/local/services.md index 22720434f6..3435e82d4e 100644 --- a/docs/architecture/rust-agent/generated/local/services.md +++ b/docs/architecture/rust-agent/generated/local/services.md @@ -82,7 +82,6 @@ flowchart LR p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p78 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p78 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p78 - p60 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p78 p51 -->|"dim_agent_capabilities::skills::session::SessionSkills@session"| p77 p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p77 p74 -->|"dyn dim_agent_runtime::contracts::ConfigureControl@main"| p77 @@ -102,7 +101,6 @@ flowchart LR p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p74 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p74 p33 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p74 - p60 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p74 p33 -->|"dim_agent_capabilities::permission::CommandRules@session"| p73 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p73 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p73 diff --git a/docs/architecture/rust-agent/generated/local/services.mmd b/docs/architecture/rust-agent/generated/local/services.mmd index 110a80e370..39dc37d24e 100644 --- a/docs/architecture/rust-agent/generated/local/services.mmd +++ b/docs/architecture/rust-agent/generated/local/services.mmd @@ -77,7 +77,6 @@ flowchart LR p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p78 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p78 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p78 - p60 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p78 p51 -->|"dim_agent_capabilities::skills::session::SessionSkills@session"| p77 p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p77 p74 -->|"dyn dim_agent_runtime::contracts::ConfigureControl@main"| p77 @@ -97,7 +96,6 @@ flowchart LR p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p74 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p74 p33 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p74 - p60 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p74 p33 -->|"dim_agent_capabilities::permission::CommandRules@session"| p73 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p73 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p73 diff --git a/docs/architecture/rust-agent/generated/services.json b/docs/architecture/rust-agent/generated/services.json index 664c670a07..c6cbc0301b 100644 --- a/docs/architecture/rust-agent/generated/services.json +++ b/docs/architecture/rust-agent/generated/services.json @@ -252,11 +252,6 @@ "service": "dim_agent_runtime::core::timeline::Timeline@main", "scope": null, "status": "Ready" - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "status": "Ready" } ], "resolved": [ @@ -289,12 +284,6 @@ "scope": null, "provider": 35, "generation": 1 - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "provider": 35, - "generation": 1 } ], "reads": [ @@ -327,12 +316,6 @@ "provider": 35, "declared": true, "external": false - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "provider": 35, - "declared": true, - "external": false } ] }, @@ -434,11 +417,6 @@ "service": "dim_agent_runtime::lifecycle::FaultReporter@session", "scope": null, "status": "Ready" - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "status": "Ready" } ], "resolved": [ @@ -495,12 +473,6 @@ "scope": null, "provider": 21, "generation": 1 - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "scope": null, - "provider": 35, - "generation": 1 } ], "reads": [ @@ -557,12 +529,6 @@ "provider": 21, "declared": true, "external": true - }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "provider": 35, - "declared": true, - "external": false } ] }, @@ -1648,12 +1614,6 @@ "generation": 1, "removing": false }, - { - "service": "dim_agent_runtime::timeline_context::BranchOpening@main", - "provider": 35, - "generation": 1, - "removing": false - }, { "service": "dyn dim_agent_runtime::contracts::ConfigureControl@main", "provider": 46, @@ -2395,6 +2355,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#submitChecks@session", + "provider": 25, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#timelineStore@session", "provider": 21, diff --git a/docs/architecture/rust-agent/generated/services.md b/docs/architecture/rust-agent/generated/services.md index 3ef05722ac..b5f30f37b9 100644 --- a/docs/architecture/rust-agent/generated/services.md +++ b/docs/architecture/rust-agent/generated/services.md @@ -54,7 +54,6 @@ flowchart LR p35 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p48 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p48 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p48 - p35 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p48 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p47 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p47 p40 -->|"dim_agent_capabilities::context_preparation::ConfigurationPublisher@main"| p46 @@ -66,7 +65,6 @@ flowchart LR p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p46 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p46 p21 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p46 - p35 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p46 p21 -->|"dim_agent_capabilities::permission::CommandRules@session"| p45 p21 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 diff --git a/docs/architecture/rust-agent/generated/services.mmd b/docs/architecture/rust-agent/generated/services.mmd index 1845fe1eb5..4ad520d3b4 100644 --- a/docs/architecture/rust-agent/generated/services.mmd +++ b/docs/architecture/rust-agent/generated/services.mmd @@ -49,7 +49,6 @@ flowchart LR p35 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p48 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p48 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p48 - p35 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p48 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p47 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p47 p40 -->|"dim_agent_capabilities::context_preparation::ConfigurationPublisher@main"| p46 @@ -61,7 +60,6 @@ flowchart LR p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p46 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p46 p21 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p46 - p35 -->|"dim_agent_runtime::timeline_context::BranchOpening@main"| p46 p21 -->|"dim_agent_capabilities::permission::CommandRules@session"| p45 p21 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 diff --git a/docs/architecture/rust-agent/plugins/InputQueue.md b/docs/architecture/rust-agent/plugins/InputQueue.md index 92c833317e..c320c24559 100644 --- a/docs/architecture/rust-agent/plugins/InputQueue.md +++ b/docs/architecture/rust-agent/plugins/InputQueue.md @@ -11,7 +11,9 @@ the opt-in [block-presence read](../../../design/input-state-read.md#block-prese `session.input.withdraw` for every branch of its Session, served through that branch's InputQueue. It also provides the Session table `submitChecks` ([`SubmitChecks`](../../../../crates/dim-agent-capabilities/src/input_queue.rs)): -Session parts register submit checks with it from their own `apply` and the +Session parts call `submitChecks.register(name, check)` from their own `apply`. +Native and cross-language callers use `submitChecks.check({entry, branchId, user?, mode}, cancelled)` +to run the same registered checks. The registration is withdrawn when that part unloads. A `session.input.withdraw` with `steer` validates the operator's content and calls each check registered now, in name order, before admitting its command; @@ -64,7 +66,7 @@ covers the table and the Rpc entries. | --- | --- | | 作用域 | Session | | 注入 | `S:SessionMethods`、`S:TreeCommands` | -| 提供 | `S:SubmitChecks` | +| 提供 | `S:SubmitChecks`、`S:dyn HostDispatch#submitChecks` | | 被注入于 | `HooksSession`、`Skills` | diff --git a/docs/architecture/rust-agent/plugins/Prompt.md b/docs/architecture/rust-agent/plugins/Prompt.md index 666af9c158..f3daf28621 100644 --- a/docs/architecture/rust-agent/plugins/Prompt.md +++ b/docs/architecture/rust-agent/plugins/Prompt.md @@ -25,7 +25,6 @@ The publisher receives explicit adopted state instead of rebuilding history. | `B:Dispatcher` | Order configuration adoption and state projection. | | `B:Timeline` | Write controls and query adopted prompt/configuration properties. | | `S:FaultReporter` | Report owned work failures. | -| `B:BranchOpening` | Register initial prompt completion receipt. | | `S:GuideEntries` | The entries whose load or unload moves this branch's composition. | ## Events and lifetime @@ -68,7 +67,7 @@ owners, rule check and complete-candidate concurrency limit. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:BranchLifecycle`、`B:BranchOpening`、`B:ConfigurationPublisher`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:FaultReporter`、`S:GuideEntries`、`S:InitialPromptConfiguration`、`S:PromptHost` | +| 注入 | `B:BranchLifecycle`、`B:ConfigurationPublisher`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:FaultReporter`、`S:GuideEntries`、`S:InitialPromptConfiguration`、`S:PromptHost` | | 提供 | `B:Prompt`、`B:StateCell`、`B:dyn ConfigureControl` | | 被注入于 | `PromptSourcesBranch`、`SkillsBranch`、`ToolBinding` | diff --git a/docs/architecture/rust-agent/plugins/ToolExecution.md b/docs/architecture/rust-agent/plugins/ToolExecution.md index 7e61be9749..2afef15b5c 100644 --- a/docs/architecture/rust-agent/plugins/ToolExecution.md +++ b/docs/architecture/rust-agent/plugins/ToolExecution.md @@ -21,7 +21,6 @@ declaration splits into protocol and policy is ToolRegistry's | `B:Timeline` | Reconcile committed configuration/request pins. | | `B:BranchLifecycle` | Gate background refresh on activation/closing. | | `B:Dispatcher` | Handle branch opening. | -| `B:BranchOpening` | Register initial tool-adoption completion receipt. | ### Events and lifetime @@ -37,7 +36,7 @@ initial model configuration, fixing the tools registered then before the first input. Every registry read, request preparation, `bind_current` and the adoption task's included, takes in what is registered at that moment, so a tool registered later is adopted for the next request. With a model configuration, opening reconciles its tools through Prompt before -the existing BranchOpening receipt completes. Failed adoption retains pins and the prefix; +the existing BranchLifecycle receipt completes. Failed adoption retains pins and the prefix; a later change retries. Pins are runtime handles, not persistent executable identities; missing tools cannot be recovered by replaying their old definitions. @@ -93,7 +92,7 @@ task, mutex, lifecycle phase or protocol field is needed. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:BranchLifecycle`、`B:BranchOpening`、`B:Dispatcher`、`B:Prompt`、`B:Timeline`、`S:ToolRegistry` | +| 注入 | `B:BranchLifecycle`、`B:Dispatcher`、`B:Prompt`、`B:Timeline`、`S:ToolRegistry` | | 提供 | `B:ToolBinding` | | 被注入于 | `Loop`、`ToolExecutor` | diff --git a/docs/architecture/rust-agent/plugins/ToolRegistry.md b/docs/architecture/rust-agent/plugins/ToolRegistry.md index e01ed3ad28..35819c577d 100644 --- a/docs/architecture/rust-agent/plugins/ToolRegistry.md +++ b/docs/architecture/rust-agent/plugins/ToolRegistry.md @@ -140,7 +140,7 @@ how Sessions unload and restore; App Server recovery is described in Initial attachment and adoption satisfy [Session boundary A.5](../../../design/contracts/session-boundary.md#a5-tool-contribution) -through ToolBinding initialization and the existing Prompt / BranchOpening path, +through ToolBinding initialization and the existing Prompt / BranchLifecycle path, before Session publication and input admission. A branch whose configuration has no tool part declares the registry's current host and registered tools through PrepareModelHost / `bind_current` on each request; a registration change @@ -175,7 +175,7 @@ malformed results, retained handlers of an unloaded row, and cancellation withou | §4 rule 5 | Memory notifications add no Timeline batches; existing producers retain atomic commit ownership. | | §4 rule 6 | Declarations reach model context through Prompt adoption; results use ToolExecutor. | | §4 rule 7 | Parts register through ToolRegistry's public `register`; private provider state is not read. | -| §4 rule 8 | No infrastructure change: registration is an effect of the caller (`ctx.effect`, the bridge's `caller_row`); adoption uses `SessionLifecycle`, ToolBinding initialization and BranchOpening. | +| §4 rule 8 | No infrastructure change: registration is an effect of the caller (`ctx.effect`, the bridge's `caller_row`); adoption uses `SessionLifecycle`, ToolBinding initialization and BranchLifecycle. | | §4 rule 9 | Registry availability stays in memory and process logs, not new Timeline facts. | | §1 | ToolRegistry owns its table and attachment; App Server remains assembly only. | | ADR 002 D1 | The registry and contributions belong to one Session. | diff --git a/docs/architecture/rust-agent/single-tree.md b/docs/architecture/rust-agent/single-tree.md index a5376618ea..45064af258 100644 --- a/docs/architecture/rust-agent/single-tree.md +++ b/docs/architecture/rust-agent/single-tree.md @@ -105,7 +105,7 @@ profile 未要求的已登记部件由可选挂载器挂载,宿主通过现有 必需部件在 `apply` 中登记的子插件仍由该部件等待,等待指子插件 `Active` 而不是 settle:`(&view).await` 在子插件的依赖尚未就绪时也会返回,此时子插件仍是 `Pending`。部件用 `mount_active` 挂载子插件,等待本身没有期限:创建期间整次打开的无进展期限覆盖它,到期时报告子插件的名字和它缺的依赖,创建随之失败;创建之后,该部件与任何缺依赖的行一样保持 `Loading` 直到子插件 `Active`(rutis D22),其代被取消时结束等待;返回因此意味着其服务和订阅已就绪。创建只等待自己的必需行和已挂载的必需部件,不再做全进程检查;`Agent::check_assembly()` 在测试创建 Session 与分支之后跑一次,检查必需行和作用域交出的必需视图及其子树的 Active 状态,发现未等待的子插件就报告;仅可选行及其子树不参加此 Active 校验。两者仍参加必需读取和实例键审计。release 与 debug 创建因此相同,每次创建都不做全进程诊断扫描。 -这修正装配自身的等待范围([#132](https://github.com/arcships/dim/issues/132),[ADR 002 D3](../../adr/002-plugin-scope.md#d3-dependencies-follow-scope-and-point-from-extensions-to-the-core)、[Session access §9.4](../../design/contracts/session-access.md#94-optional-parts-per-enabled-plugin)、[规则 §4.8](principles.md#4-通过时间线扩展行为))。输入仍经原有分支初始化、ToolBinding 取样和 BranchOpening;不增加发布阶段或工具专用接线。顺序、批次、Timeline 及重载语义均不变。 +这修正装配自身的等待范围([#132](https://github.com/arcships/dim/issues/132),[ADR 002 D3](../../adr/002-plugin-scope.md#d3-dependencies-follow-scope-and-point-from-extensions-to-the-core)、[Session access §9.4](../../design/contracts/session-access.md#94-optional-parts-per-enabled-plugin)、[规则 §4.8](principles.md#4-通过时间线扩展行为))。输入仍经原有分支初始化、ToolBinding 取样和 BranchLifecycle;不增加发布阶段或工具专用接线。顺序、批次、Timeline 及重载语义均不变。 loader 的 `create_instance` 仍先等待行 settled;异步 apply 一直不返回的行可能占用该等待。此限制保留在 #132 中,不因此增加后台创建管理器;部件仍应遵守 apply 只登记服务/订阅、发布后再开始业务工作的规则。 diff --git a/docs/architecture/rust-agent/tool-contributions.md b/docs/architecture/rust-agent/tool-contributions.md index 42305901d0..10abddd1a7 100644 --- a/docs/architecture/rust-agent/tool-contributions.md +++ b/docs/architecture/rust-agent/tool-contributions.md @@ -11,7 +11,7 @@ part apply: tools.register(ctx, ToolContribution) (other languages: toolRegistry.register(declaration, execute)) Session services Active -> ToolBinding reads ToolRegistry (first snapshot takes in what is registered) - -> existing Prompt adoption and BranchOpening finish + -> existing Prompt adoption and BranchLifecycle finish -> Session publication and first input a part registers, or unloads and its registration is withdrawn -> registry task rereads -> sources_state() changes @@ -174,7 +174,7 @@ New bindings automatically adopt the replacement through the existing flow below | 组件 | 作用域 | 注入 | 提供 | 被谁注入 | | --- | --- | --- | --- | --- | | `ToolRegistryPlugin` | Session | `S:ToolHost`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle` | `S:ToolRegistry`、`S:ToolSourcesView` | ToolBinding;注册工具或来源的部件(BranchTool、Questions、Skills、Wait、CollaborationSession、McpSession) | -| `ToolBindingPlugin` | 分支 | `S:ToolRegistry`、`B:Prompt`(采用入口)、`B:Timeline`、`B:BranchLifecycle`、`B:Dispatcher`、`B:BranchOpening` | `B:ToolBinding` | Loop、ToolExecutor | +| `ToolBindingPlugin` | 分支 | `S:ToolRegistry`、`B:Prompt`(采用入口)、`B:Timeline`、`B:BranchLifecycle`、`B:Dispatcher` | `B:ToolBinding` | Loop、ToolExecutor | - 来源方注入 ToolRegistry 以注册来源(沿用第 3 节),不注入 ToolBinding。 - 审批由 ToolExecutor 注入 `B:Approval` 调用,Tools 不涉及。 @@ -302,7 +302,7 @@ apply: 完成后才提供 B:ToolBinding(已有模型时,Loop 因此在采用落入 Timeline 后才开始请求) branch/start、branch/resume 分发时(Prompt 已在同一事件写入模型配置,ToolBinding 依赖 Prompt,分发在其后): - 登记为 BranchOpening 工作:等 Prompt 初始采用完成,按 apply 的同一规则比较 ──> 一致则 pin,否则 adopt_tools ──> pin + 登记为 BranchLifecycle 工作:等 Prompt 初始采用完成,按 apply 的同一规则比较 ──> 一致则 pin,否则 adopt_tools ──> pin 开启工作完成后分支才接受输入,首个请求已有对齐的工具部分 ToolRegistry.changed()(分支 activated() 之后才处理;之前的变化保留在 watch 中): diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index a1de0032d9..0bbd6f4f3c 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -388,7 +388,7 @@ No protocol version is added and persistence formats are unchanged. A Session part contributes a tool by registering it with the Session's `toolRegistry`, from any language. The registration belongs to the part that made it and is withdrawn when that part unloads (ADR 002 D3, D5). ToolRegistry does not depend on the parts that register; they depend on it, so when ToolRegistry reloads, the parts registered with it reload and register again. `SessionConfig.tools` is the Session's optional mount list, fixed at creation ([session-access A.3](session-access.md#a3-sessionconfig-fields)). Without one, the Session declares every host tool in the host's order and every registered tool by name, so a plugin's tools are usable once its part registers them, with no configuration edit (#364); with one, it declares the host and registered tools the list names, in its order, and `[]` declares none of them. Other sources' tools follow in both cases and are governed by their sources' own configuration, not by the mount list. Each mounted registered tool is a registry-owned versioned set keyed `#contributed:` (#241): it is declared while a part has it registered, withdrawn with the registration, and declared under a new version when a part registers it again. A version is a new UUID, never reused even across registry instances and processes, so a version persisted in `tool_sources` names one generation. Every read takes in what is registered then; once the Session is published, the registry's own task also rereads after every registration and withdrawal, until the Session starts closing. A tool the mount list names that no part has registered is not declared and is reported in diagnostics, and the Session still starts; the tool is declared from the next request after a part registers it, without a Session reload. Required dependency waiting rules are unchanged; an optional part registered when the Session opens settles before publication, and one that is Pending or Failed never fails Session readiness (#132, #207, ADR 006 D3). -ToolBinding reconciles the table through the existing Prompt / BranchOpening flow before the Session accepts input. A branch with adopted model configuration uses `Prompt::adopt_tools` when its tool part differs. For a request without adopted configuration, ToolBinding captures a registry snapshot before PrepareModelHost selects from the supplied definitions, then binds the selection against the same retained handlers. With adopted configuration but no tool part, `bind_current` declares and binds the registry's current tools on each request. Registration changes need no adoption in either request path. No new core readiness phase is needed. Source changes, including registered tools in a configuration with a tool part, go through the existing registry notification and Prompt adoption path (`context/configured` with `tool_sources`), and requests retain the handlers selected for their own prefix. A tool name follows `[A-Za-z0-9_-]{1,64}`; a name that is registered already or is a host tool's is refused. The mount list decides what is declared, and only duplicate names in it fail the Session ([tool contributions](../../architecture/rust-agent/tool-contributions.md)). Permission decides whether a declared tool's call runs: its preset and `allowedTools`/`disallowedTools` change live through `session.permission.update` and never change the declarations, which are part of the prompt prefix. To block a tool and keep the context stable, keep it mounted and deny it in Permission; to change what the model sees, create the Session with a different mount list. +ToolBinding reconciles the table through the existing Prompt / BranchLifecycle flow before the Session accepts input. A branch with adopted model configuration uses `Prompt::adopt_tools` when its tool part differs. For a request without adopted configuration, ToolBinding captures a registry snapshot before PrepareModelHost selects from the supplied definitions, then binds the selection against the same retained handlers. With adopted configuration but no tool part, `bind_current` declares and binds the registry's current tools on each request. Registration changes need no adoption in either request path. No new core readiness phase is needed. Source changes, including registered tools in a configuration with a tool part, go through the existing registry notification and Prompt adoption path (`context/configured` with `tool_sources`), and requests retain the handlers selected for their own prefix. A tool name follows `[A-Za-z0-9_-]{1,64}`; a name that is registered already or is a host tool's is refused. The mount list decides what is declared, and only duplicate names in it fail the Session ([tool contributions](../../architecture/rust-agent/tool-contributions.md)). Permission decides whether a declared tool's call runs: its preset and `allowedTools`/`disallowedTools` change live through `session.permission.update` and never change the declarations, which are part of the prompt prefix. To block a tool and keep the context stable, keep it mounted and deny it in Permission; to change what the model sees, create the Session with a different mount list. | Method | Mode | Request | Reply | | --- | --- | --- | --- | diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index bb2125290c..0c4f95f643 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -50,7 +50,7 @@ Status: Draft. 依据:[总体设计](overview.md) §8 阶段与附录 B/F、[ | C2 | `SessionConfig.interactive` 与 `session.create` 参数(只做这一个字段;存储保持 v13,旧记录缺省为交互) | S | Rpc | — | SessionTitle、S2、Questions(已由 #262 实现) | | C6 | Session 广播通知记录,Rpc 原样转发 | S | Rpc | — | S5b | | ~~C7~~ | ~~固定前缀读~~:不需要新接口,现有门面组合即可(#50,session-access §9.2) | — | — | — | — | -| C3 | 部件把工具注册到 ToolRegistry(#382),注册在部件卸载时撤回;ToolRegistry 不硬依赖可选插件:分支初始化首次读取 ToolRegistry 时纳入当时已注册的工具,并沿既有 BranchOpening 在 Session 接受输入前完成采用;之后注册或撤回的工具由 ToolRegistry 跟随,从下一个请求起提供或撤下,不需要重载(#241);Session 的挂载列表 `SessionConfig.tools` 可选,没有时声明全部宿主工具与部件注册的全部工具(#364),有时只声明其中列出的,列出但没有部件注册的工具直接省略(#34) | S | 装配 | — | Web、Goal、Scheduler、Workflow | +| C3 | 部件把工具注册到 ToolRegistry(#382),注册在部件卸载时撤回;ToolRegistry 不硬依赖可选插件:分支初始化首次读取 ToolRegistry 时纳入当时已注册的工具,并沿既有 BranchLifecycle 在 Session 接受输入前完成采用;之后注册或撤回的工具由 ToolRegistry 跟随,从下一个请求起提供或撤下,不需要重载(#241);Session 的挂载列表 `SessionConfig.tools` 可选,没有时声明全部宿主工具与部件注册的全部工具(#364),有时只声明其中列出的,列出但没有部件注册的工具直接省略(#34) | S | 装配 | — | Web、Goal、Scheduler、Workflow | | C4 | #4 Session 级:TypeScript 部件向 `toolRegistry` 注册工具、提供 `sessionMethods`,订阅 Session 广播,随 Session 装配和卸载;Session 装配不等可选插件的部件(#34,装配实现由 #132 跟踪,完整 C4 验收以其落地为前提) | L,先 spike | 装配 | C3、#132(验收) | 所有 TypeScript 插件 | | C5 | #4 分支级:TypeScript 部件按名使用 `Dispatcher`、`Branch::input`、`TreeCommands` | M | 装配 | C4 | Goal | | S1 | InputQueue 撤回:`input/withdraw`、`input/deleted`、`session.input.withdraw`(新事件需做格式决定) | M | 事件类型 | C1 | `Ctrl+S`/`/queue`、Goal、S2 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index de466837b4..539b1ee5b2 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -177,11 +177,9 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `contextUsage` | branch | ContextUsage | hot-path | 本地请求计数器、请求引用与按序统计;`session.context.usage` 是 App Server RPC。按 #1292 确认是否需要独立插件操作。 | | `toolBinding` | branch | ToolBinding | hot-path | 待迁移;按 #1292 定义操作面 | | `toolExecutor` | branch | ToolExecutor | hot-path | 待迁移;按 #1292 定义操作面 | -| `branchOpening` | branch | BranchScope | hot-path | 待迁移;按 #1292 定义操作面 | | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | | `fileReads` | branch | FileReads | hot-path | 待迁移;按 #1292 定义操作面 | -| `submitChecks` | session | InputMethods | hot-path | 待迁移;按 #1292 定义操作面 | | `historyRenderer` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | | `contextModelHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | | `prepareModelHost` | session | PrepareModelHost | hot-path | 待迁移;按 #1292 定义操作面 | diff --git a/docs/design/session-typescript.md b/docs/design/session-typescript.md index f1aa7638a7..9e40312542 100644 --- a/docs/design/session-typescript.md +++ b/docs/design/session-typescript.md @@ -178,7 +178,7 @@ names. A named tool that no row has registered (its row is absent, Pending or di applied yet) is not declared and produces the `tool.attach` diagnostic; once a row registers it, the next request declares it without a Session reload. A withdrawn registration's set is withdrawn, and the row's next generation registers again under a new version. ToolBinding adopts changes through -Prompt/BranchOpening as for other sources, and each request keeps its selected handlers. A new +Prompt/BranchLifecycle as for other sources, and each request keeps its selected handlers. A new generation is not substituted into an old request. ## Session methods diff --git a/docs/zh/design/contracts/session-boundary.md b/docs/zh/design/contracts/session-boundary.md index 5716286ef2..4b4af3095b 100644 --- a/docs/zh/design/contracts/session-boundary.md +++ b/docs/zh/design/contracts/session-boundary.md @@ -387,7 +387,7 @@ Client A Rpc call admission provider han Session 部件把工具注册到本 Session 的 `toolRegistry` 来贡献它,任何语言都一样。注册属于发起它的部件,在该部件卸载时撤回(ADR 002 D3、D5)。ToolRegistry 不依赖注册的部件,而是它们依赖 ToolRegistry,因此 ToolRegistry 重载时,注册到它的部件随之重载并重新注册。`SessionConfig.tools` 是 Session 可选的挂载列表,创建时确定([session-access A.3](session-access.md#a3-sessionconfig-字段))。没有挂载列表时,Session 按宿主的顺序声明全部宿主工具,再按名称声明全部注册的工具,因此插件的部件注册工具后即可使用,不需要修改配置(#364);有挂载列表时,按列表顺序声明其中列出的宿主工具与注册工具,`[]` 不声明任何宿主工具或注册工具。两种情况下其他来源的工具都排在其后,由来源自己的配置决定,不受挂载列表影响。每个挂载的注册工具是注册表自有的带版本集合,键为 `#contributed:`(#241):有部件注册时声明,随注册撤回而撤下,再次注册时以新版本声明。版本是新的 UUID,跨注册表实例与进程也不复用,因此 `tool_sources` 中持久化的版本只指一个代次。每次读取都纳入当时已注册的内容;Session 发布后,注册表自己的任务还在每次注册与撤回后重读,直到 Session 开始关闭。挂载列表列出但没有部件注册的工具不声明,并记录诊断,Session 照常启动;有部件注册之后的下一个请求起即声明,不需要重载 Session。必需依赖的等待规则不变;Session 打开时已登记的可选部件在发布前加载结束,处于 Pending 或 Failed 的可选部件不会让 Session 就绪失败(#132、#207、ADR 006 D3)。 -ToolBinding 沿既有 Prompt / BranchOpening 流程完成匹配与必要的采用,随后 Session 才接受输入。已有模型配置的分支在工具部分不匹配时使用 `Prompt::adopt_tools`。请求尚无已采用配置时,ToolBinding 先取得注册表快照,PrepareModelHost 从传入的声明中选择工具,再由 ToolBinding 按同一快照保留的处理器绑定。已有已采用配置但不含工具部分时,每个请求经 `bind_current` 声明并绑定注册表当前的工具。这两条请求路径中,注册的变化都无需采用。不新增 core 就绪阶段。来源变化,包括带工具部分的配置中的注册工具,沿既有注册表通知和 Prompt 采用路径传播(带 `tool_sources` 的 `context/configured`),请求保留其前缀选定的处理器。工具名须满足 `[A-Za-z0-9_-]{1,64}`;已被注册的名称或宿主工具名会被拒绝。声明什么由挂载列表决定,只有列表中的重复名称使 Session 失败([工具贡献](../../../architecture/rust-agent/tool-contributions.md))。已声明工具的调用是否执行由 Permission 决定:其预设与 `allowedTools`/`disallowedTools` 可经 `session.permission.update` 实时修改,从不改变工具声明,而声明属于提示词前缀。要在保持上下文稳定的同时阻止某个工具,就保留挂载并在 Permission 中拒绝它;要改变模型看到的工具,就用另一个挂载列表创建 Session。 +ToolBinding 沿既有 Prompt / BranchLifecycle 流程完成匹配与必要的采用,随后 Session 才接受输入。已有模型配置的分支在工具部分不匹配时使用 `Prompt::adopt_tools`。请求尚无已采用配置时,ToolBinding 先取得注册表快照,PrepareModelHost 从传入的声明中选择工具,再由 ToolBinding 按同一快照保留的处理器绑定。已有已采用配置但不含工具部分时,每个请求经 `bind_current` 声明并绑定注册表当前的工具。这两条请求路径中,注册的变化都无需采用。不新增 core 就绪阶段。来源变化,包括带工具部分的配置中的注册工具,沿既有注册表通知和 Prompt 采用路径传播(带 `tool_sources` 的 `context/configured`),请求保留其前缀选定的处理器。工具名须满足 `[A-Za-z0-9_-]{1,64}`;已被注册的名称或宿主工具名会被拒绝。声明什么由挂载列表决定,只有列表中的重复名称使 Session 失败([工具贡献](../../../architecture/rust-agent/tool-contributions.md))。已声明工具的调用是否执行由 Permission 决定:其预设与 `allowedTools`/`disallowedTools` 可经 `session.permission.update` 实时修改,从不改变工具声明,而声明属于提示词前缀。要在保持上下文稳定的同时阻止某个工具,就保留挂载并在 Permission 中拒绝它;要改变模型看到的工具,就用另一个挂载列表创建 Session。 | 方法 | 模式 | 请求 | 回复 | | --- | --- | --- | --- | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index b89bf93026..bb64089d7b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -834,6 +834,12 @@ export interface SessionIdentity { * work in `apply` wait for [`Self::activated`] before doing it. */ export interface BranchLifecycle { + /** + * Registers a completion for the current branch opening. Once opening seals, + * registration fails. A failed completion fails the opening. + * @throws {AgentErrorThrown} + */ + registerOpening(completion: () => void | Promise): Promise /** * Waits until the branch leaves `Loading`: true when it became Active, * false when it closes without ever starting. diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index c7ea5d1837..a9a0b25000 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -566,6 +566,17 @@ export type SessionMethodReply = MethodReply; export type MethodHandler = (call: MethodCall, cancelled: Promise, progress: MethodProgress) => Promise>; /** How a registered Session namespace serves one call. */ export type SessionMethodHandler = (call: SessionMethodCall, cancelled: Promise, progress: MethodProgress) => Promise>; +export type SubmitCheckRequest = { + entry: 'submit' | 'branch' | 'steer'; branchId: string; + user?: import('./branch-services.js').UserInput | null; mode: import('./branch-services.js').InputMode; +}; +export type SubmitCheckResult = { kind: 'proceed'; blocks: string[]; warnings: W[] } + | { kind: 'block'; message: string }; +export interface SubmitChecks { + register(name: string, check: (request: SubmitCheckRequest, cancelled: () => Promise) => Promise>): Promise; + check(request: SubmitCheckRequest, cancelled: () => Promise): Promise>; +} + /** Process service `managementMethods` (protected-local v3 only): a process row * registers each of its namespaces, which stays registered until the row unloads. */ export interface ManagementMethods { diff --git a/runtime/fixtures/branch-opening.ts b/runtime/fixtures/branch-opening.ts new file mode 100644 index 0000000000..df29da09dc --- /dev/null +++ b/runtime/fixtures/branch-opening.ts @@ -0,0 +1,14 @@ +import { definePlugin } from '@arcships/rutis' +import type { BranchLifecycle } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const opening = definePlugin({ + name: 'OpeningReceiptFixture', + inject: ['branchLifecycle'], + async apply(ctx) { + await ctx.use('branchLifecycle').registerOpening(async () => { + throw new Error('opening completion refused') + }) + }, +}) +export default partRow('branch', opening) diff --git a/runtime/fixtures/submit-check.ts b/runtime/fixtures/submit-check.ts new file mode 100644 index 0000000000..794653081f --- /dev/null +++ b/runtime/fixtures/submit-check.ts @@ -0,0 +1,22 @@ +import { definePlugin } from '@arcships/rutis' +import type { SessionMethods, SubmitChecks } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const part = definePlugin({ + name: 'SubmitCheckFixture', + inject: ['submitChecks', 'sessionMethods'], + async apply(ctx) { + const checks = ctx.use('submitChecks') + await checks.register('fixture', async request => { + if (request.entry === 'submit') return {kind: 'block', message: 'foreign check refused'} + return {kind: 'proceed', blocks: [], warnings: ['foreign check ran']} + }) + await ctx.use('sessionMethods').register('session.checkfixture', [ + { name: 'session.checkfixture.probe', mutating: false, interruption: 'report', progress: false }, + ], async (_call, cancelled) => { + const value = await checks.check({entry: 'branch', branchId: 'main', mode: 'queue'}, () => cancelled) + return {kind: 'value', value} + }) + }, +}) +export default partRow('session', part) diff --git a/tests/integration/tests/prompt_lifecycle.rs b/tests/integration/tests/prompt_lifecycle.rs index 948faf094d..a5ecfc1bc0 100644 --- a/tests/integration/tests/prompt_lifecycle.rs +++ b/tests/integration/tests/prompt_lifecycle.rs @@ -1329,11 +1329,11 @@ impl DynPlugin for OpeningObserved { } } -struct OpeningFailure(Key, Key); +struct OpeningFailure(Key, Key); struct SlowOpening { dispatcher: Key, - opening: Key, + opening: Key, timeline: Key, receipts: bool, completed: Arc, @@ -1377,7 +1377,7 @@ impl DynPlugin for SlowOpening { if receipts { for step in 1..=7 { let (timeline, completed) = (timeline.clone(), completed.clone()); - opening.register(Box::pin(async move { + opening.admit_opening(Box::pin(async move { tokio::time::sleep(Duration::from_millis(200 * step)).await; assert!( timeline_events( @@ -1394,7 +1394,7 @@ impl DynPlugin for SlowOpening { }))?; } } else { - opening.register(Box::pin(async move { + opening.admit_opening(Box::pin(async move { assert!( timeline_events(&timeline, TimelineQueryScope::Branch, ..=1001) .await? @@ -1529,8 +1529,8 @@ impl DynPlugin for OpeningFailure { dispatcher.subscribe(ctx, "OpeningFailure", &["branch/start"], move |_| { let opening = opening.clone(); Box::pin(async move { - opening.register(Box::pin(std::future::pending()))?; - opening.register(Box::pin(async { + opening.admit_opening(Box::pin(std::future::pending()))?; + opening.admit_opening(Box::pin(async { Err(AgentError::InvalidInput("opening rejected".into())) }))?; Ok(()) From aa877e2192a8ea84a22dc030bdd61fe0f775d11b Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 19:10:31 +0800 Subject: [PATCH 03/12] Keep Session fault state on its lifecycle owner --- crates/dim-agent-capabilities/src/prompt.rs | 16 ++++---- crates/dim-agent-runtime/src/agent.rs | 14 +++---- crates/dim-agent-runtime/src/assembly.rs | 7 +--- crates/dim-agent-runtime/src/config.rs | 6 +++ crates/dim-agent-runtime/src/names.rs | 1 - crates/dim-app-server/src/lib.rs | 1 - .../tests/transport_flow/tool_cleanup.rs | 18 +++------ .../rust-agent/generated/catalog.md | 1 - .../rust-agent/generated/local/services.json | 38 ++++++++----------- .../rust-agent/generated/local/services.md | 2 +- .../rust-agent/generated/local/services.mmd | 2 +- .../rust-agent/generated/services.json | 38 ++++++++----------- .../rust-agent/generated/services.md | 2 +- .../rust-agent/generated/services.mmd | 2 +- .../architecture/rust-agent/plugins/Prompt.md | 4 +- docs/design/service-faces.md | 1 - 16 files changed, 67 insertions(+), 86 deletions(-) diff --git a/crates/dim-agent-capabilities/src/prompt.rs b/crates/dim-agent-capabilities/src/prompt.rs index 5be6c9e300..eb34a3eb62 100644 --- a/crates/dim-agent-capabilities/src/prompt.rs +++ b/crates/dim-agent-capabilities/src/prompt.rs @@ -128,7 +128,7 @@ pub struct Prompt { publisher: Arc, timeline: Arc, dispatcher: Arc, - faults: Arc, + session_lifecycle: Arc, identity: Arc, lifecycle: CancellationToken, branch_phase: Arc, @@ -283,7 +283,7 @@ impl Prompt { fn report_panic(&self, panic: Box) -> AgentError { let error = AgentError::fault("Prompt", panic_message(panic)); - self.faults.report(error.clone()); + self.session_lifecycle.report_fault(error.clone()); error } @@ -720,7 +720,7 @@ pub struct PromptPlugin { initial: rutis::host::Key, publisher: rutis::host::Key, identity: rutis::host::Key, - faults: rutis::host::Key, + session_lifecycle: rutis::host::Key, branch_phase: rutis::host::Key, guide: rutis::host::Key, state: rutis::host::Key>, @@ -736,7 +736,7 @@ impl PromptPlugin { initial: names.key()?, publisher: names.key()?, identity: names.key()?, - faults: names.key()?, + session_lifecycle: names.key()?, branch_phase: names.key()?, guide: names.key()?, state: names.state_cell()?, @@ -757,7 +757,7 @@ impl DynPlugin for PromptPlugin { self.initial.erase(), self.publisher.erase(), self.identity.erase(), - self.faults.erase(), + self.session_lifecycle.erase(), self.branch_phase.erase(), self.guide.erase(), ] @@ -770,7 +770,7 @@ impl DynPlugin for PromptPlugin { let initial = ctx.require_at(&self.initial)?; let publisher = ctx.require_at(&self.publisher)?; let identity = ctx.require_at(&self.identity)?; - let faults = ctx.require_at(&self.faults)?; + let session_lifecycle = ctx.require_at(&self.session_lifecycle)?; let branch_phase = ctx.require_at(&self.branch_phase)?; let guide = ctx.require_at(&self.guide)?; if ctx.cancellation_token().is_cancelled() { @@ -784,7 +784,7 @@ impl DynPlugin for PromptPlugin { publisher, timeline: timeline.clone(), dispatcher: dispatcher.clone(), - faults, + session_lifecycle, identity, lifecycle: ctx.cancellation_token(), branch_phase, @@ -1043,7 +1043,7 @@ impl DynPlugin for PromptPlugin { | AgentError::InvalidInput(_) ) { - owner.faults.report(error); + owner.session_lifecycle.report_fault(error); break; } } diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 8dc2a60409..e27382f428 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -464,7 +464,7 @@ impl Session { fn activate(&self) { self.0.owner.lifecycle.advance(SessionPhase::Active); let weak = Arc::downgrade(&self.0); - let mut faults = self.0.owner.faults.watch(); + let mut faults = self.0.owner.lifecycle.faults.watch(); let stop = self.0.owner.closing.clone(); let supervisor = tokio::spawn(async move { loop { @@ -509,7 +509,7 @@ impl Session { .await } pub async fn input(&self, data: InputMessageData, branch: &str) -> Result> { - if let Some(error) = self.0.owner.faults.failure() { + if let Some(error) = self.0.owner.lifecycle.faults.failure() { return Err(error); } if self.0.owner.closing.is_cancelled() { @@ -524,7 +524,7 @@ impl Session { data: InputMessageData, branch: &str, ) -> Result<(Arc, InputCommit)> { - if let Some(error) = self.0.owner.faults.failure() { + if let Some(error) = self.0.owner.lifecycle.faults.failure() { return Err(error); } if self.0.owner.closing.is_cancelled() { @@ -539,7 +539,7 @@ impl Session { inputs: Vec, branch: &str, ) -> Result>> { - if let Some(error) = self.0.owner.faults.failure() { + if let Some(error) = self.0.owner.lifecycle.faults.failure() { return Err(error); } if self.0.owner.closing.is_cancelled() { @@ -556,7 +556,7 @@ impl Session { update: ConfigureUpdate, branch: &str, ) -> Result { - if let Some(error) = self.0.owner.faults.failure() { + if let Some(error) = self.0.owner.lifecycle.faults.failure() { return Err(error); } if self.0.owner.closing.is_cancelled() { @@ -733,7 +733,7 @@ impl Session { } /// The runtime fault that stopped this Session, if any; separate from cleanup. pub fn failure(&self) -> Option { - self.0.owner.faults.failure() + self.0.owner.lifecycle.faults.failure() } /// Observes complete Session cleanup without initiating it. pub fn closed(&self) -> BoxFuture<'static, Result<()>> { @@ -831,7 +831,7 @@ impl Session { ); let mut errors = vec![]; this.0.tree.begin_close(); - if let Some(error) = this.0.owner.faults.failure() { + if let Some(error) = this.0.owner.lifecycle.faults.failure() { for info in this.0.tree.list() { if let Some(branch) = this.0.tree.get(&info.id) { branch.0.mark_failure(&error); diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 3217c90525..96513f1af2 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -1072,7 +1072,6 @@ pub(crate) struct SessionAssembly { pub id: String, pub restored: bool, pub unloading: CancellationToken, - pub faults: FaultReporter, pub closing: CancellationToken, pub lifecycle: SessionLifecycle, pub loaded: Mutex>>>, @@ -1140,7 +1139,6 @@ impl DynPlugin for SessionScopePlugin { rutis_bridge::session::host_key("timelineStore").instance(scope.instance), owner.assembly.store.clone(), )?; - ctx.provide_at(scope.key::(), Arc::new(owner.faults.clone()))?; for provide in &owner.assembly.values { provide(ctx, &scope)?; } @@ -1297,7 +1295,7 @@ impl DynPlugin for BranchScopePlugin { ancestors, session.assembly.store.clone(), owner.sequence, - session.faults.clone(), + session.lifecycle.faults.clone(), ); let dispatcher = Dispatcher::new(scope.instance, owner.sequence, timeline.clone()); ctx.provide_at(scope.key::(), Arc::new(timeline.clone()))?; @@ -1454,7 +1452,7 @@ impl TimelineFactory { branch.timeline.clone(), branch.dispatcher.clone(), branch.lifecycle.clone(), - parent.faults.clone(), + parent.lifecycle.faults.clone(), parent.assembly.catalog.clone(), )) }) @@ -1815,7 +1813,6 @@ pub(crate) async fn build_session( config, id, restored: matches!(initialization, SessionInitialization::Restore(_)), - faults: FaultReporter::default(), unloading: CancellationToken::new(), lifecycle: SessionLifecycle::new(closing.clone()), closing, diff --git a/crates/dim-agent-runtime/src/config.rs b/crates/dim-agent-runtime/src/config.rs index 8efce79ab8..b63cfd3ff3 100644 --- a/crates/dim-agent-runtime/src/config.rs +++ b/crates/dim-agent-runtime/src/config.rs @@ -404,6 +404,7 @@ impl BranchLifecycle { /// parts in other languages use [`Self::hold`]. #[derive(Clone)] pub struct SessionLifecycle { + pub(crate) faults: crate::FaultReporter, phases: Phases, closing: tokio_util::sync::CancellationToken, /// Live holds, with [`RELEASING`] set once an idle release is decided. @@ -425,12 +426,17 @@ impl SessionLifecycle { pub(crate) fn new(closing: tokio_util::sync::CancellationToken) -> Self { Self { phases: Phases::new(), + faults: crate::FaultReporter::default(), closing, holds: Arc::default(), foreign: Arc::default(), } } #[service(skip)] + pub fn report_fault(&self, error: crate::AgentError) { + self.faults.report(error); + } + #[service(skip)] pub fn phase(&self) -> SessionPhase { let phase = self.phases.get(); if phase < SessionPhase::Closing && self.closing.is_cancelled() { diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index f9208baf6e..5986b784d0 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -98,7 +98,6 @@ pub fn catalog() -> ServiceCatalog { catalog.register_shared_instance(name_of::(), SESSION_GROUP); register::(&mut catalog, session); register::(&mut catalog, session); - register::(&mut catalog, session); register::(&mut catalog, session); catalog.register_shared_instance("timelineStore", SESSION_GROUP); register::(&mut catalog, session); diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 8bec8a343b..f68da8c1a7 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1493,7 +1493,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("contextModelHost", "hot-path"), ("contextPreparation", "hot-path"), ("contextUsage", "hot-path"), - ("faultReporter", "hot-path"), ("fileReads", "hot-path"), ("fileStorage", "object"), ("grokOAuthService", "secret"), diff --git a/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs b/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs index a17017dd06..9ea31a22dd 100644 --- a/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs +++ b/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs @@ -9,8 +9,8 @@ struct SessionCleanup { entered: Arc, release: Arc, fail: bool, - faults: Arc>>>, - reporter: rutis::host::Key, + faults: Arc>>>, + reporter: rutis::host::Key, } impl SessionCleanup { fn new( @@ -18,7 +18,7 @@ impl SessionCleanup { entered: Arc, release: Arc, fail: bool, - faults: Arc>>>, + faults: Arc>>>, ) -> rutis::Result { Ok(Self { entered, @@ -109,15 +109,9 @@ async fn closed_notification_waits_for_session_resources_and_registry_removal() assert_ok(&client.rpc("session.attach", json!({"sessionId":sid})).await); let session = agent.get_session(&sid).unwrap(); if fault { - faults - .lock() - .unwrap() - .as_ref() - .unwrap() - .report(dim_agent_runtime::AgentError::fault( - "test host", - "private runtime detail", - )); + faults.lock().unwrap().as_ref().unwrap().report_fault( + dim_agent_runtime::AgentError::fault("test host", "private runtime detail"), + ); } else { drop(session.close()); } diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index c57c983baf..ff4a79b8e9 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -74,7 +74,6 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `commandRules` | session | CommandRules | data | `read` async | | `compactionStrategyHost` | session | ProductSummaryStrategy | internal(hot-path) | — | | `contextModelHost` | session | SessionScope | internal(hot-path) | — | -| `faultReporter` | session | SessionScope | internal(hot-path) | — | | `guideEntries` | session | PromptGuide | data | `register` async | | `historyRenderer` | session | SessionScope | internal(hot-path) | — | | `initialPromptConfiguration` | session | PromptRegistry | data | `get` async | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index 38999dd1d6..e96df3e8f5 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -608,22 +608,22 @@ "status": "Ready" }, { - "service": "dim_agent_runtime::config::TimelineIdentity@main", + "service": "dim_agent_runtime::config::SessionLifecycle@session", "scope": null, "status": "Ready" }, { - "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", + "service": "dim_agent_runtime::config::TimelineIdentity@main", "scope": null, "status": "Ready" }, { - "service": "dim_agent_runtime::core::timeline::Timeline@main", + "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", "scope": null, "status": "Ready" }, { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", + "service": "dim_agent_runtime::core::timeline::Timeline@main", "scope": null, "status": "Ready" } @@ -660,27 +660,27 @@ "generation": 1 }, { - "service": "dim_agent_runtime::config::TimelineIdentity@main", + "service": "dim_agent_runtime::config::SessionLifecycle@session", "scope": null, - "provider": 60, + "provider": 33, "generation": 1 }, { - "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", + "service": "dim_agent_runtime::config::TimelineIdentity@main", "scope": null, "provider": 60, "generation": 1 }, { - "service": "dim_agent_runtime::core::timeline::Timeline@main", + "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", "scope": null, "provider": 60, "generation": 1 }, { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", + "service": "dim_agent_runtime::core::timeline::Timeline@main", "scope": null, - "provider": 33, + "provider": 60, "generation": 1 } ], @@ -715,6 +715,12 @@ "declared": true, "external": false }, + { + "service": "dim_agent_runtime::config::SessionLifecycle@session", + "provider": 33, + "declared": true, + "external": true + }, { "service": "dim_agent_runtime::config::TimelineIdentity@main", "provider": 60, @@ -732,12 +738,6 @@ "provider": 60, "declared": true, "external": false - }, - { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", - "provider": 33, - "declared": true, - "external": true } ] }, @@ -4078,12 +4078,6 @@ "generation": 1, "removing": false }, - { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", - "provider": 33, - "generation": 1, - "removing": false - }, { "service": "dim_agent_runtime::scope::SessionLoader@session", "provider": 33, diff --git a/docs/architecture/rust-agent/generated/local/services.md b/docs/architecture/rust-agent/generated/local/services.md index 3435e82d4e..4040fac953 100644 --- a/docs/architecture/rust-agent/generated/local/services.md +++ b/docs/architecture/rust-agent/generated/local/services.md @@ -97,10 +97,10 @@ flowchart LR p43 -->|"dim_agent_capabilities::prompt::InitialPromptConfiguration@session"| p74 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p74 p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p74 + p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p74 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p74 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p74 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p74 - p33 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p74 p33 -->|"dim_agent_capabilities::permission::CommandRules@session"| p73 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p73 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p73 diff --git a/docs/architecture/rust-agent/generated/local/services.mmd b/docs/architecture/rust-agent/generated/local/services.mmd index 39dc37d24e..707defe688 100644 --- a/docs/architecture/rust-agent/generated/local/services.mmd +++ b/docs/architecture/rust-agent/generated/local/services.mmd @@ -92,10 +92,10 @@ flowchart LR p43 -->|"dim_agent_capabilities::prompt::InitialPromptConfiguration@session"| p74 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p74 p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p74 + p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p74 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p74 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p74 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p74 - p33 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p74 p33 -->|"dim_agent_capabilities::permission::CommandRules@session"| p73 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p73 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p73 diff --git a/docs/architecture/rust-agent/generated/services.json b/docs/architecture/rust-agent/generated/services.json index c6cbc0301b..4b91bc12e7 100644 --- a/docs/architecture/rust-agent/generated/services.json +++ b/docs/architecture/rust-agent/generated/services.json @@ -399,22 +399,22 @@ "status": "Ready" }, { - "service": "dim_agent_runtime::config::TimelineIdentity@main", + "service": "dim_agent_runtime::config::SessionLifecycle@session", "scope": null, "status": "Ready" }, { - "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", + "service": "dim_agent_runtime::config::TimelineIdentity@main", "scope": null, "status": "Ready" }, { - "service": "dim_agent_runtime::core::timeline::Timeline@main", + "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", "scope": null, "status": "Ready" }, { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", + "service": "dim_agent_runtime::core::timeline::Timeline@main", "scope": null, "status": "Ready" } @@ -451,27 +451,27 @@ "generation": 1 }, { - "service": "dim_agent_runtime::config::TimelineIdentity@main", + "service": "dim_agent_runtime::config::SessionLifecycle@session", "scope": null, - "provider": 35, + "provider": 21, "generation": 1 }, { - "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", + "service": "dim_agent_runtime::config::TimelineIdentity@main", "scope": null, "provider": 35, "generation": 1 }, { - "service": "dim_agent_runtime::core::timeline::Timeline@main", + "service": "dim_agent_runtime::core::dispatcher::Dispatcher@main", "scope": null, "provider": 35, "generation": 1 }, { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", + "service": "dim_agent_runtime::core::timeline::Timeline@main", "scope": null, - "provider": 21, + "provider": 35, "generation": 1 } ], @@ -506,6 +506,12 @@ "declared": true, "external": false }, + { + "service": "dim_agent_runtime::config::SessionLifecycle@session", + "provider": 21, + "declared": true, + "external": true + }, { "service": "dim_agent_runtime::config::TimelineIdentity@main", "provider": 35, @@ -523,12 +529,6 @@ "provider": 35, "declared": true, "external": false - }, - { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", - "provider": 21, - "declared": true, - "external": true } ] }, @@ -2277,12 +2277,6 @@ "generation": 1, "removing": false }, - { - "service": "dim_agent_runtime::lifecycle::FaultReporter@session", - "provider": 21, - "generation": 1, - "removing": false - }, { "service": "dim_agent_runtime::scope::SessionLoader@session", "provider": 21, diff --git a/docs/architecture/rust-agent/generated/services.md b/docs/architecture/rust-agent/generated/services.md index b5f30f37b9..967073405f 100644 --- a/docs/architecture/rust-agent/generated/services.md +++ b/docs/architecture/rust-agent/generated/services.md @@ -61,10 +61,10 @@ flowchart LR p21 -->|"dim_agent_capabilities::prompt::InitialPromptConfiguration@session"| p46 p28 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p46 p35 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p46 + p21 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p46 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p46 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p46 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p46 - p21 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p46 p21 -->|"dim_agent_capabilities::permission::CommandRules@session"| p45 p21 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 diff --git a/docs/architecture/rust-agent/generated/services.mmd b/docs/architecture/rust-agent/generated/services.mmd index 4ad520d3b4..9bf6c8defb 100644 --- a/docs/architecture/rust-agent/generated/services.mmd +++ b/docs/architecture/rust-agent/generated/services.mmd @@ -56,10 +56,10 @@ flowchart LR p21 -->|"dim_agent_capabilities::prompt::InitialPromptConfiguration@session"| p46 p28 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p46 p35 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p46 + p21 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p46 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p46 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p46 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p46 - p21 -->|"dim_agent_runtime::lifecycle::FaultReporter@session"| p46 p21 -->|"dim_agent_capabilities::permission::CommandRules@session"| p45 p21 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 diff --git a/docs/architecture/rust-agent/plugins/Prompt.md b/docs/architecture/rust-agent/plugins/Prompt.md index f3daf28621..6fef82a7d3 100644 --- a/docs/architecture/rust-agent/plugins/Prompt.md +++ b/docs/architecture/rust-agent/plugins/Prompt.md @@ -24,7 +24,7 @@ The publisher receives explicit adopted state instead of rebuilding history. | `B:TimelineIdentity` | Session and branch ids of the `prompt.load` span. | | `B:Dispatcher` | Order configuration adoption and state projection. | | `B:Timeline` | Write controls and query adopted prompt/configuration properties. | -| `S:FaultReporter` | Report owned work failures. | +| `S:SessionLifecycle` | Report owned work failures. | | `S:GuideEntries` | The entries whose load or unload moves this branch's composition. | ## Events and lifetime @@ -67,7 +67,7 @@ owners, rule check and complete-candidate concurrency limit. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:BranchLifecycle`、`B:ConfigurationPublisher`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:FaultReporter`、`S:GuideEntries`、`S:InitialPromptConfiguration`、`S:PromptHost` | +| 注入 | `B:BranchLifecycle`、`B:ConfigurationPublisher`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:InitialPromptConfiguration`、`S:PromptHost`、`S:SessionLifecycle` | | 提供 | `B:Prompt`、`B:StateCell`、`B:dyn ConfigureControl` | | 被注入于 | `PromptSourcesBranch`、`SkillsBranch`、`ToolBinding` | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 539b1ee5b2..f3cca2728f 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -185,7 +185,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `prepareModelHost` | session | PrepareModelHost | hot-path | 待迁移;按 #1292 定义操作面 | | `prepareContextHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | | `compactionStrategyHost` | session | ProductSummaryStrategy | hot-path | 待迁移;按 #1292 定义操作面 | -| `faultReporter` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | ### 3.6 入口、凭据与宿主资源 From 3df887a5bacad0969b8663bde07969dae0e64018 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 19:19:34 +0800 Subject: [PATCH 04/12] Expose Session fault reporting and observation on the lifecycle face --- crates/dim-agent-capabilities/src/prompt.rs | 4 +- crates/dim-agent-runtime/src/config.rs | 94 +++++++++++++------ crates/dim-agent-runtime/src/error.rs | 82 +++++++++++++++- .../tests/transport_flow/branch_typescript.rs | 33 +++++++ .../tests/transport_flow/tool_cleanup.rs | 12 ++- .../rust-agent/generated/catalog.md | 2 +- .../contracts/runtime-owner-operations.md | 2 +- npm/branch-services.d.ts | 45 ++++++++- npm/plugin.d.ts | 2 +- runtime/fixtures/session-fault.ts | 30 ++++++ 10 files changed, 265 insertions(+), 41 deletions(-) create mode 100644 runtime/fixtures/session-fault.ts diff --git a/crates/dim-agent-capabilities/src/prompt.rs b/crates/dim-agent-capabilities/src/prompt.rs index eb34a3eb62..71cb8cbc96 100644 --- a/crates/dim-agent-capabilities/src/prompt.rs +++ b/crates/dim-agent-capabilities/src/prompt.rs @@ -283,7 +283,7 @@ impl Prompt { fn report_panic(&self, panic: Box) -> AgentError { let error = AgentError::fault("Prompt", panic_message(panic)); - self.session_lifecycle.report_fault(error.clone()); + self.session_lifecycle.report_native_fault(error.clone()); error } @@ -1043,7 +1043,7 @@ impl DynPlugin for PromptPlugin { | AgentError::InvalidInput(_) ) { - owner.session_lifecycle.report_fault(error); + owner.session_lifecycle.report_native_fault(error); break; } } diff --git a/crates/dim-agent-runtime/src/config.rs b/crates/dim-agent-runtime/src/config.rs index b63cfd3ff3..6c9f7effd4 100644 --- a/crates/dim-agent-runtime/src/config.rs +++ b/crates/dim-agent-runtime/src/config.rs @@ -409,16 +409,21 @@ pub struct SessionLifecycle { closing: tokio_util::sync::CancellationToken, /// Live holds, with [`RELEASING`] set once an idle release is decided. holds: Arc, - /// The holds parts in other languages took, by id ([`Self::hold`]). - foreign: Arc>, + foreign: Arc>, } -/// Each hold is also a cleanup of the row that took it: the row's unload -/// runs it, or [`SessionLifecycle::release`] runs it early. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FaultQuery {} #[derive(Default)] -struct ForeignHolds { +struct ForeignResources { next: u64, - held: std::collections::HashMap, + entries: std::collections::HashMap, } +type FaultListener = Arc< + dyn Fn(Option) -> rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + + Send + + Sync, +>; /// Set in the hold count by the idle release decision; no hold follows it. const RELEASING: usize = 1 << (usize::BITS - 1); #[service] @@ -432,9 +437,11 @@ impl SessionLifecycle { foreign: Arc::default(), } } - #[service(skip)] - pub fn report_fault(&self, error: crate::AgentError) { - self.faults.report(error); + pub fn report_fault(&self, error: crate::SessionFault) { + self.faults.report(error.into()); + } + pub fn failure(&self, _request: FaultQuery) -> Option { + self.faults.failure().map(crate::SessionFault::from) } #[service(skip)] pub fn phase(&self) -> SessionPhase { @@ -492,30 +499,39 @@ impl SessionLifecycle { /// TypeScript) once the Session is closing or its idle release is /// decided. pub fn hold(&self, ctx: &rutis::Ctx) -> Option { - let hold = self.take_hold()?; - let mut foreign = self.foreign.lock().unwrap(); - foreign.next += 1; - let id = foreign.next; - let holds = Arc::downgrade(&self.foreign); - let disposer = ctx - .effect(move || async move { - if let Some(holds) = holds.upgrade() { - holds.lock().unwrap().held.remove(&id); - } - Ok(()) - }) - .ok()?; - foreign.held.insert(id, (hold, disposer)); - Some(id) + self.own(ctx, self.take_hold()?).ok() + } + + /// Observes the current failure and subsequent reports until release or caller unload. + pub fn observe_fault( + &self, + ctx: &rutis::Ctx, + listener: FaultListener, + ) -> Result { + let stop = tokio_util::sync::CancellationToken::new(); + let id = self.own(ctx, stop.clone().drop_guard())?; + let mut faults = self.faults.watch(); + tokio::spawn(async move { + tokio::select! { + _ = stop.cancelled() => {} + _ = async { + loop { + let current = faults.borrow_and_update().clone().map(crate::SessionFault::from); + if listener(current).await.is_err() || faults.changed().await.is_err() { + return; + } + } + } => {} + } + }); + Ok(id) } - /// Releases the hold `id` took and ends its cleanup in the row that - /// took it: true when it was held, false when it was released already - /// or by its row's unload. + + /// Releases a hold or fault observation. The caller's unload also releases it. pub async fn release(&self, id: u64) -> std::result::Result { - let Some((hold, disposer)) = self.foreign.lock().unwrap().held.remove(&id) else { + let Some(disposer) = self.foreign.lock().unwrap().entries.remove(&id) else { return Ok(false); }; - drop(hold); disposer .dispose() .await @@ -539,6 +555,26 @@ impl SessionLifecycle { } } +impl SessionLifecycle { + pub fn report_native_fault(&self, error: crate::AgentError) { + self.faults.report(error); + } + fn own(&self, ctx: &rutis::Ctx, resource: T) -> Result { + let mut foreign = self.foreign.lock().unwrap(); + foreign.next += 1; + let id = foreign.next; + let resources = Arc::downgrade(&self.foreign); + let disposer = ctx.effect(move || async move { + drop(resource); + if let Some(resources) = resources.upgrade() { + resources.lock().unwrap().entries.remove(&id); + } + Ok(()) + })?; + foreign.entries.insert(id, disposer); + Ok(id) + } +} /// An activity hold from [`SessionLifecycle::take_hold`]; dropping it releases it. /// It carries no identity, result or cancellation. pub struct SessionHold(Arc); diff --git a/crates/dim-agent-runtime/src/error.rs b/crates/dim-agent-runtime/src/error.rs index 9791e471f6..1d7fbeb2ee 100644 --- a/crates/dim-agent-runtime/src/error.rs +++ b/crates/dim-agent-runtime/src/error.rs @@ -49,9 +49,89 @@ pub enum AgentError { Multiple(Vec), } +/// A failure reported to a Session. Framework failures carry their diagnostic text. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SessionFault { + InvalidInput(String), + Closed(String), + UnknownBranch(String), + BranchEnded(String), + BranchRefused { + refusal: BranchRefusal, + message: String, + }, + Storage(String), + PublicationUnknown(String), + Build(String), + Cancelled(String), + Reloading(String), + AmbiguousSubmission(String), + PartialSubmission(String), + Fault { + component: String, + message: String, + }, + Framework(String), + Multiple(Vec), +} +impl From for SessionFault { + fn from(error: AgentError) -> Self { + match error { + AgentError::InvalidInput(value) => Self::InvalidInput(value), + AgentError::Closed(value) => Self::Closed(value), + AgentError::UnknownBranch(value) => Self::UnknownBranch(value), + AgentError::BranchEnded(value) => Self::BranchEnded(value), + AgentError::BranchRefused { refusal, message } => { + Self::BranchRefused { refusal, message } + } + AgentError::Storage(value) => Self::Storage(value), + AgentError::PublicationUnknown(value) => Self::PublicationUnknown(value), + AgentError::Build(value) => Self::Build(value), + AgentError::Cancelled(value) => Self::Cancelled(value), + AgentError::Reloading(value) => Self::Reloading(value), + AgentError::AmbiguousSubmission(value) => Self::AmbiguousSubmission(value), + AgentError::PartialSubmission(value) => Self::PartialSubmission(value), + AgentError::Fault { component, message } => Self::Fault { component, message }, + AgentError::Framework(value) => Self::Framework(value.to_string()), + AgentError::Multiple(value) => { + Self::Multiple(value.into_iter().map(Into::into).collect()) + } + } + } +} +impl From for AgentError { + fn from(error: SessionFault) -> Self { + match error { + SessionFault::InvalidInput(value) => Self::InvalidInput(value), + SessionFault::Closed(value) => Self::Closed(value), + SessionFault::UnknownBranch(value) => Self::UnknownBranch(value), + SessionFault::BranchEnded(value) => Self::BranchEnded(value), + SessionFault::BranchRefused { refusal, message } => { + Self::BranchRefused { refusal, message } + } + SessionFault::Storage(value) => Self::Storage(value), + SessionFault::PublicationUnknown(value) => Self::PublicationUnknown(value), + SessionFault::Build(value) => Self::Build(value), + SessionFault::Cancelled(value) => Self::Cancelled(value), + SessionFault::Reloading(value) => Self::Reloading(value), + SessionFault::AmbiguousSubmission(value) => Self::AmbiguousSubmission(value), + SessionFault::PartialSubmission(value) => Self::PartialSubmission(value), + SessionFault::Fault { component, message } => Self::Fault { component, message }, + SessionFault::Framework(value) => { + Self::Framework(Arc::new(rutis::host::ErrorKind::PluginFailed(value.into()))) + } + SessionFault::Multiple(value) => { + Self::Multiple(value.into_iter().map(Into::into).collect()) + } + } + } +} + /// Why the tree refused an operation on a line, named the way the protocol's /// `appError` names it ([timeline branches §14](../../../docs/design/timeline-branches.md#14-clients)). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum BranchRefusal { /// The target is already the Session's default branch. AlreadyDefault, diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 617fe1dd0f..1ea87fc2a4 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -587,3 +587,36 @@ async fn node_branch_opening_completion_can_refuse_session_creation() { server.shutdown(); server.join().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_session_fault_is_observed_and_closes_the_native_session() { + let receipt = std::env::temp_dir().join(format!("dim-fault-{}", uuid::Uuid::new_v4())); + let mut parts = branch_part(); + parts.rows = vec![json!({ + "id": "session-fault", + "name": parts.anchor.parent().unwrap().join("fixtures/session-fault.ts"), + "provides": {}, "config": {"receipt": receipt}, + })]; + let (server, agent) = launch_with( + Arc::new(MockTools), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.require_part("SessionFaultFixture"); + }, + ) + .await; + let error = match agent.create_session(Default::default()).await { + Ok(session) => session.close().await.unwrap_err(), + Err(error) => error, + }; + assert!(error.to_string().contains("fixture storage"), "{error}"); + let stored: Value = serde_json::from_slice(&std::fs::read(&receipt).unwrap()).unwrap(); + assert_eq!(stored, json!({"storage": "fixture storage"})); + std::fs::remove_file(receipt).unwrap(); + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs b/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs index 9ea31a22dd..44501e2e7b 100644 --- a/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs +++ b/crates/dim-app-server/tests/transport_flow/tool_cleanup.rs @@ -109,9 +109,15 @@ async fn closed_notification_waits_for_session_resources_and_registry_removal() assert_ok(&client.rpc("session.attach", json!({"sessionId":sid})).await); let session = agent.get_session(&sid).unwrap(); if fault { - faults.lock().unwrap().as_ref().unwrap().report_fault( - dim_agent_runtime::AgentError::fault("test host", "private runtime detail"), - ); + faults + .lock() + .unwrap() + .as_ref() + .unwrap() + .report_native_fault(dim_agent_runtime::AgentError::fault( + "test host", + "private runtime detail", + )); } else { drop(session.close()); } diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index ff4a79b8e9..ad43cfe422 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -85,7 +85,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `sessionConfig` | session | SessionScope | data | `get` async | | `sessionIdentity` | session | SessionScope | data | `get` async | | `sessionLanguage` | session | PromptSources | data | `get` async | -| `sessionLifecycle` | session | SessionScope | data | `activated` async, `closing` async, `hold` async, `release` async | +| `sessionLifecycle` | session | SessionScope | data | `activated` async, `closing` async, `failure` async, `hold` async, `observeFault` async, `release` async, `reportFault` async | | `sessionLoader` | session | SessionScope | internal(control) | — | | `sessionMethods` | session | SessionMethods | data | `register` async | | `skillsConfig` | session | SessionScope | data | `get` async | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 2e4e54fbd8..b1c8f37e48 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -26,7 +26,7 @@ | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | -| Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → AgentError or null`, `observeFault(listener) → subscription`. First fault wins with existing storage-fault precedence. | +| Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → AgentError or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | | Compaction, stop and activity callers → `agentLoop` | `agentLoop.compact({}) → sequence`, `stopTurn({turnId, reason}) → sequence or null`; `agentLoop.state({}) → {phase, turnId?}`, `observe(listener)` delivers that snapshot. | diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index bb64089d7b..fa7b41092e 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -852,6 +852,37 @@ export interface BranchLifecycle { closing(): Promise } +/** + * Why the tree refused an operation on a line, named the way the protocol's + * `appError` names it ([timeline branches §14](../../../docs/design/timeline-branches.md#14-clients)). + */ +export type BranchRefusal = + | /** The target is already the Session's default branch. */ "already_default" + | /** The target cannot be the default branch: a plugin line, or a line a client opened before `FORMAT` 53. */ "not_selectable" + | /** The target or an ancestor of it is ending or ended, so an end already on its way to it wins. */ "protected" + | /** The target cannot end: the current default branch, or an ancestor of the default branch. The root's own refusal is the operation's input error, which its callers already answer. */ "cannot_end" + +/** A failure reported to a Session. Framework failures carry their diagnostic text. */ +export type SessionFault = + | { invalidInput: string } + | { closed: string } + | { unknownBranch: string } + | { branchEnded: string } + | { branchRefused: { refusal: BranchRefusal; message: string } } + | { storage: string } + | { publicationUnknown: string } + | { build: string } + | { cancelled: string } + | { reloading: string } + | { ambiguousSubmission: string } + | { partialSubmission: string } + | { fault: { component: string; message: string } } + | { framework: string } + | { multiple: SessionFault[] } + +export interface FaultQuery { +} + /** * Lifecycle of one Session, provided by its scope. Session capabilities that * spawn background work in `apply`, such as replacing Session-owned instances @@ -870,6 +901,8 @@ export interface BranchLifecycle { * parts in other languages use [`Self::hold`]. */ export interface SessionLifecycle { + reportFault(error: SessionFault): Promise + failure(request: FaultQuery): Promise /** * Waits until the Session is published or starts closing: true only when * it was published and is not closing. @@ -890,9 +923,12 @@ export interface SessionLifecycle { */ hold(): Promise /** - * Releases the hold `id` took and ends its cleanup in the row that - * took it: true when it was held, false when it was released already - * or by its row's unload. + * Observes the current failure and subsequent reports until release or caller unload. + * @throws {ErrorThrown} + */ + observeFault(listener: (arg0: SessionFault | null) => void | Promise): Promise + /** + * Releases a hold or fault observation. The caller's unload also releases it. * @throws {AgentErrorThrown} */ release(id: number | bigint): Promise @@ -1307,6 +1343,9 @@ export type AgentErrorThrown = RustError<"AgentError", "InvalidInput" | "Closed" /** What a method returning `Err(ApprovalRespondError)` throws. */ export type ApprovalRespondErrorThrown = RustError<"ApprovalRespondError", "Unknown" | "Cancelled" | "Closed", undefined> +/** What a method returning `Err(Error)` throws. */ +export type ErrorThrown = RustError<"Error", string, undefined> + /** What a method returning `Err(HostError)` throws. */ export type HostErrorThrown = RustError<"HostError", "Failed" | "Cancelled", undefined> diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index a9a0b25000..a0a9ce7515 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -259,7 +259,7 @@ export type BranchEvent = Omit & { /** The services Dim's Rust types serve to other languages, by name: * `ctx.use('name')`. */ export type { - AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionIdentity, SessionLifecycle, + AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionFault, SessionIdentity, SessionLifecycle, TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, diff --git a/runtime/fixtures/session-fault.ts b/runtime/fixtures/session-fault.ts new file mode 100644 index 0000000000..9cacf19ae1 --- /dev/null +++ b/runtime/fixtures/session-fault.ts @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import { writeFile } from 'node:fs/promises' +import { definePlugin } from '@arcships/rutis' +import type { SessionLifecycle } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const part = definePlugin<{ receipt: string }>({ + name: 'SessionFaultFixture', + inject: ['sessionLifecycle'], + async apply(ctx, config) { + const lifecycle = ctx.use('sessionLifecycle') + assert.equal(await lifecycle.failure({}), null) + let observed!: () => void + const delivered = new Promise(resolve => { observed = resolve }) + const subscription = await lifecycle.observeFault(async error => { + if (error && 'storage' in error && error.storage === 'fixture storage') observed() + }) + await lifecycle.reportFault({ fault: { component: 'fixture', message: 'first' } }) + await lifecycle.reportFault({ cancelled: 'later' }) + assert.deepEqual(await lifecycle.failure({}), { fault: { component: 'fixture', message: 'first' } }) + await lifecycle.reportFault({ storage: 'fixture storage' }) + await delivered + await lifecycle.reportFault({ storage: 'later storage' }) + assert.equal(await lifecycle.release(subscription), true) + assert.equal(await lifecycle.release(subscription), false) + await writeFile(config.receipt, JSON.stringify(await lifecycle.failure({}))) + }, +}) + +export default partRow('session', part) From 2e832eb929736d434727d2cdcab20da4bfe752a5 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 19:31:26 +0800 Subject: [PATCH 05/12] Migrate Skills and MCP instances to the Session loader data face --- .../src/file_storage.rs | 2 +- .../src/file_storage/face.rs | 37 +----- crates/dim-agent-capabilities/src/lib.rs | 1 + .../dim-agent-capabilities/src/os_string.rs | 37 ++++++ .../src/skills/content.rs | 112 +++++++----------- .../dim-agent-capabilities/src/skills/mod.rs | 8 +- .../src/skills/session.rs | 9 +- crates/dim-agent-runtime/src/scope.rs | 94 +++++++++++++-- crates/dim-app-server/src/lib.rs | 1 - crates/dim-app-server/src/mcp/publication.rs | 111 ++++++++++------- crates/dim-app-server/src/mcp/session.rs | 9 +- .../dim-app-server/src/session_typescript.rs | 3 +- .../tests/transport_flow/branch_typescript.rs | 79 ++++++++++++ .../rust-agent/generated/catalog.md | 2 +- .../rust-agent/generated/local/services.json | 12 ++ .../rust-agent/generated/services.json | 6 + .../architecture/rust-agent/plugins/Skills.md | 27 ++--- docs/design/service-faces.md | 1 - npm/branch-services.d.ts | 22 ++++ runtime/fixtures/session-loader.ts | 30 +++++ 20 files changed, 414 insertions(+), 189 deletions(-) create mode 100644 crates/dim-agent-capabilities/src/os_string.rs create mode 100644 runtime/fixtures/session-loader.ts diff --git a/crates/dim-agent-capabilities/src/file_storage.rs b/crates/dim-agent-capabilities/src/file_storage.rs index 1bd2a8fcfb..2c44155b30 100644 --- a/crates/dim-agent-capabilities/src/file_storage.rs +++ b/crates/dim-agent-capabilities/src/file_storage.rs @@ -98,7 +98,7 @@ pub struct FilePath { /// stores it. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] pub struct DirectoryEntry { - #[serde(serialize_with = "face::serialize_name")] + #[serde(serialize_with = "crate::os_string::serialize")] pub name: OsString, pub kind: EntryKind, } diff --git a/crates/dim-agent-capabilities/src/file_storage/face.rs b/crates/dim-agent-capabilities/src/file_storage/face.rs index eb0a582dee..0e831cfbf5 100644 --- a/crates/dim-agent-capabilities/src/file_storage/face.rs +++ b/crates/dim-agent-capabilities/src/file_storage/face.rs @@ -4,7 +4,7 @@ use rutis::Ctx; use rutis_bridge::session::{Error, HostDispatch, Reply, Value}; use serde::{Deserialize, Serialize}; use std::{ - ffi::{OsStr, OsString}, + ffi::OsString, path::{Component, Path}, sync::Arc, }; @@ -18,39 +18,6 @@ pub struct OpenRead { pub size: u64, } -pub(super) fn serialize_name( - name: &OsStr, - serializer: S, -) -> std::result::Result { - match name.to_str() { - Some(text) => serializer.serialize_str(text), - #[cfg(any(unix, windows))] - None => name.serialize(serializer), - #[cfg(not(any(unix, windows)))] - None => Err(serde::ser::Error::custom( - "unsupported filesystem name encoding", - )), - } -} - -#[derive(Deserialize)] -#[serde(untagged)] -enum EntryName { - Text(String), - #[cfg(any(unix, windows))] - Native(OsString), -} - -fn deserialize_name<'de, D: serde::Deserializer<'de>>( - deserializer: D, -) -> std::result::Result { - Ok(match EntryName::deserialize(deserializer)? { - EntryName::Text(text) => text.into(), - #[cfg(any(unix, windows))] - EntryName::Native(name) => name, - }) -} - #[derive(Debug, Deserialize)] #[serde(untagged, deny_unknown_fields)] pub enum FsRemove { @@ -59,7 +26,7 @@ pub enum FsRemove { }, Entry { parent: String, - #[serde(deserialize_with = "deserialize_name")] + #[serde(deserialize_with = "crate::os_string::deserialize")] name: OsString, }, } diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index fc1a2b8175..588447991e 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -24,6 +24,7 @@ pub mod images; pub mod input_queue; pub mod methods; pub mod model_provider; +mod os_string; mod output; pub mod permission; mod port_faces; diff --git a/crates/dim-agent-capabilities/src/os_string.rs b/crates/dim-agent-capabilities/src/os_string.rs new file mode 100644 index 0000000000..fb13b68446 --- /dev/null +++ b/crates/dim-agent-capabilities/src/os_string.rs @@ -0,0 +1,37 @@ +use serde::{Deserialize, Serialize}; +use std::ffi::{OsStr, OsString}; + +pub(crate) fn serialize( + name: &impl AsRef, + serializer: S, +) -> std::result::Result { + let name = name.as_ref(); + match name.to_str() { + Some(text) => serializer.serialize_str(text), + #[cfg(any(unix, windows))] + None => name.serialize(serializer), + #[cfg(not(any(unix, windows)))] + None => Err(serde::ser::Error::custom( + "unsupported filesystem name encoding", + )), + } +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum OsValue { + Text(String), + #[cfg(any(unix, windows))] + Native(OsString), +} + +pub(crate) fn deserialize<'de, T: From, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + Ok(match OsValue::deserialize(deserializer)? { + OsValue::Text(text) => text.into(), + #[cfg(any(unix, windows))] + OsValue::Native(name) => name, + } + .into()) +} diff --git a/crates/dim-agent-capabilities/src/skills/content.rs b/crates/dim-agent-capabilities/src/skills/content.rs index e86bd21273..7fad6cc719 100644 --- a/crates/dim-agent-capabilities/src/skills/content.rs +++ b/crates/dim-agent-capabilities/src/skills/content.rs @@ -1,11 +1,13 @@ //! Immutable content services owned by real Session loader instances. use super::{CatalogView, SkillDefinition, SkillStatus, SkillView, SkillsError}; -use dim_agent_runtime::SessionLoader; -use rutis::host::{CtxHost, FiberView, InstanceId, Key, TypeKey}; +use dim_agent_runtime::{ + Names, SESSION_GROUP, SessionInstance, SessionInstanceDefinition, SessionLoader, +}; +use rutis::host::{CtxHost, InstanceId, Key}; use rutis::{Ctx, Plugin}; use std::{ - collections::{BTreeMap, BTreeSet, HashMap}, - sync::{Arc, Mutex}, + collections::{BTreeMap, BTreeSet}, + sync::Arc, }; use tokio_util::sync::CancellationToken; @@ -19,66 +21,53 @@ pub(super) enum ContentError { Lifecycle(String), } -/// One content instance's configuration: its definition, the key it provides -/// it at, and the collection of the Skills generation that created it. -#[derive(Clone)] -pub(super) struct ContentConfig { +struct Contribution(Arc); + +pub(super) struct ContentPlugin { definition: Arc, key: Key, - contributions: Arc, } -struct Contribution(Arc); -/// The ready content of one Skills generation. Skills holds it and hands it -/// to each content instance it creates, which adds itself while it runs; it -/// is no service, so an instance does not wait for Skills, which waits for -/// its instances. -#[derive(Default)] -pub(super) struct SkillContributions(Mutex>>); -pub(super) struct ContentPlugin(pub(super) ContentConfig); +impl ContentPlugin { + pub(super) fn new(names: &Names<'_>, value: &SessionInstanceDefinition) -> rutis::Result { + Ok(Self { + definition: Arc::new(serde_json::from_value(value.instance_data.clone())?), + key: Key::dynamic(value.definition_id.clone()).instance(names.instance(SESSION_GROUP)?), + }) + } +} impl Plugin for ContentPlugin { type Deps = (); fn name(&self) -> &str { "SkillContent" } async fn apply(&self, ctx: &Ctx, (): ()) -> rutis::Result { - let contributions = self.0.contributions.clone(); - let service = Arc::new(Contribution(self.0.definition.clone())); - ctx.provide_at(self.0.key.clone(), service.clone())?; - let key = self.0.key.erase(); - let cleanup = contributions.clone(); - ctx.effect(move || async move { - cleanup.0.lock().unwrap().remove(&key); - Ok(()) - })?; - contributions - .0 - .lock() - .unwrap() - .insert(self.0.key.erase(), service); + ctx.provide_at( + self.key.clone(), + Arc::new(Contribution(self.definition.clone())), + )?; Ok(()) } } pub(super) struct Contents { - /// The Session instance the content services are keyed in. + ctx: Ctx, session: InstanceId, - contributions: Arc, - instances: BTreeMap, + loader: Arc, + instances: BTreeMap)>, } impl Contents { - pub(super) fn new(session: InstanceId) -> Self { + pub(super) fn new(ctx: Ctx, session: InstanceId, loader: Arc) -> Self { Self { + ctx, session, - contributions: Arc::default(), + loader, instances: BTreeMap::new(), } } pub(super) async fn close(&mut self) -> Result<(), ContentError> { let mut error = None; for (_, (instance, _)) in std::mem::take(&mut self.instances) { - if let Err(failure) = instance.shutdown().await { - error = Some(ContentError::Lifecycle(failure.to_string())); - } else if let Some(failure) = instance.state().error { + if let Err(failure) = self.loader.remove(instance).await { error = Some(ContentError::Lifecycle(failure.to_string())); } } @@ -87,10 +76,9 @@ impl Contents { pub(super) async fn update( &mut self, view: Result, - loader: &SessionLoader, cancel: &CancellationToken, ) -> Result, SkillsError> { - let mut result = self.reconcile(view, loader, cancel).await; + let mut result = self.reconcile(view, cancel).await; if result.is_err() && let Err(error) = self.close().await { @@ -107,7 +95,6 @@ impl Contents { async fn reconcile( &mut self, view: Result, - loader: &SessionLoader, cancel: &CancellationToken, ) -> Result, ContentError> { let view = view?; @@ -124,13 +111,12 @@ impl Contents { .map(|entry| entry.definition.name.clone()) .collect(); let obsolete: Vec<_> = { - let ready = self.contributions.0.lock().unwrap(); self.instances .iter() .filter(|(id, (_, key))| { selected.get(*id).is_none_or(|definition| { - ready - .get(key) + self.ctx + .get_at(key) .is_none_or(|service| **definition != *service.0) }) }) @@ -139,13 +125,10 @@ impl Contents { }; for id in obsolete { let (instance, _) = self.instances.remove(&id).unwrap(); - instance - .shutdown() + self.loader + .remove(instance) .await .map_err(|error| ContentError::Lifecycle(error.to_string()))?; - if let Some(error) = instance.state().error { - return Err(ContentError::Lifecycle(error.to_string())); - } } for (id, definition) in selected { if cancel.is_cancelled() { @@ -155,39 +138,32 @@ impl Contents { continue; } let provided = Key::::dynamic(id.clone()).instance(self.session); - let key = provided.erase(); - let instance = loader - .create_instance(GROUP) - .with(ContentConfig { - definition, - key: provided, - contributions: self.contributions.clone(), + let instance = self + .loader + .create(SessionInstanceDefinition { + group: GROUP.to_owned(), + definition_id: id.clone(), + instance_data: serde_json::json!(definition), }) .await .map_err(|error| ContentError::Lifecycle(error.to_string()))?; - let ready = self.contributions.0.lock().unwrap().contains_key(&key); - if cancel.is_cancelled() || !ready { - instance - .view - .shutdown() + if cancel.is_cancelled() || self.ctx.get_at(&provided).is_none() { + self.loader + .remove(instance) .await .map_err(|error| ContentError::Lifecycle(error.to_string()))?; - if let Some(error) = instance.view.state().error { - return Err(ContentError::Lifecycle(error.to_string())); - } return Err(if cancel.is_cancelled() { SkillsError::Closed.into() } else { ContentError::Lifecycle("content instance did not become ready".into()) }); } - self.instances.insert(id, (instance.view, key)); + self.instances.insert(id, (instance, provided)); } - let ready = self.contributions.0.lock().unwrap(); Ok(Arc::new(SkillView::from_contributions( self.instances .values() - .filter_map(|(_, key)| ready.get(key)) + .filter_map(|(_, key)| self.ctx.get_at(key)) .map(|service| (service.0.name.clone(), service.0.clone())) .collect(), disabled, diff --git a/crates/dim-agent-capabilities/src/skills/mod.rs b/crates/dim-agent-capabilities/src/skills/mod.rs index e1a9f7d785..18dd29e557 100644 --- a/crates/dim-agent-capabilities/src/skills/mod.rs +++ b/crates/dim-agent-capabilities/src/skills/mod.rs @@ -108,10 +108,10 @@ pub fn install_with_config(builder: &mut AgentBuilder, config: SkillsConfig) { dim_agent_runtime::SESSION_GROUP, ); builder.session_value(Arc::new(config)); - builder.session_extension_part::( + builder.session_extension_part::( content::GROUP, "SkillContent", - |_, config| Ok(Box::new(content::ContentPlugin(config.clone()))), + |names, value| Ok(Box::new(content::ContentPlugin::new(names, value)?)), ); for part in PARTS { builder.require_part(part); @@ -131,7 +131,8 @@ pub fn register_parts(ctx: &Ctx, parts: &std::sync::Arc) -> Result /// A parsed `SKILL.md`; the body is read at scan time with path variables /// already replaced. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub struct SkillDefinition { /// TS `getSkillId`: `user:` or `workspace::`; a /// plugin's Skill is `plugin::`. @@ -148,6 +149,7 @@ pub struct SkillDefinition { /// palettes leave it out and a token naming it loads nothing. The `skill` /// tool still loads it. pub user_invocable: bool, + #[serde(with = "crate::os_string")] pub file_path: PathBuf, pub body: String, } diff --git a/crates/dim-agent-capabilities/src/skills/session.rs b/crates/dim-agent-capabilities/src/skills/session.rs index 91fbdc9ce6..94020e27c2 100644 --- a/crates/dim-agent-capabilities/src/skills/session.rs +++ b/crates/dim-agent-capabilities/src/skills/session.rs @@ -205,7 +205,9 @@ impl DynPlugin for SkillsPlugin { async { Ok(None) } })?; let contents = Arc::new(tokio::sync::Mutex::new(super::content::Contents::new( + ctx.clone(), self.session, + loader.clone(), ))); let tasks = TaskTracker::new(); let cleanup = contents.clone(); @@ -217,18 +219,17 @@ impl DynPlugin for SkillsPlugin { })?; let initial = tasks .spawn({ - let (contents, catalog, cwd, loader, stopped) = ( + let (contents, catalog, cwd, stopped) = ( contents.clone(), catalog.clone(), cwd.clone(), - loader.clone(), lifecycle.clone(), ); async move { contents .lock() .await - .update(catalog.query(Some(&cwd)).await, &loader, &stopped) + .update(catalog.query(Some(&cwd)).await, &stopped) .await } }) @@ -283,7 +284,7 @@ impl DynPlugin for SkillsPlugin { let cancel = stopped.child_token(); let update = async { let view = catalog.query(Some(&cwd)).await; - contents.lock().await.update(view, &loader, &cancel).await + contents.lock().await.update(view, &cancel).await }; tokio::pin!(update); let view = tokio::select! { diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index 2b5afb0d0c..0ae9afbe1a 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -1,6 +1,6 @@ use crate::*; use rutis::Ctx; -use rutis::host::{InstanceId, Key}; +use rutis::host::{CtxHost, InstanceId, Key}; /// Explicit opt-in for services that are safe to obtain from a public Session handle. /// @@ -45,23 +45,95 @@ use rutis::host::{InstanceId, Key}; /// ``` pub trait PublicService: Send + Sync + 'static {} -/// The loader that owns this Session's subtree. Not publicly accessible. -/// Only lock-free instance creation is exposed to Session capabilities. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionInstanceDefinition { + pub group: String, + pub definition_id: String, + pub instance_data: serde_json::Value, +} + +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionInstance { + pub instance_id: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum SessionInstanceError { + #[error("{0}")] + Create(String), + #[error("{0}")] + NotReady(String), + #[error("{0}")] + Cleanup(String), +} + +/// The loader anchored in this Session's subtree. pub struct SessionLoader { loader: rutis_loader::Loader, - /// A running loader row of the instance new instances go in: the loader - /// places an instance from a row's context, and a mounted part is not a - /// row ([`crate::PartRegistry`]). anchor: Ctx, + instances: std::sync::Mutex>, } +#[rutis::service] impl SessionLoader { pub fn new(loader: rutis_loader::Loader, anchor: Ctx) -> Self { - Self { loader, anchor } + Self { + loader, + anchor, + instances: Default::default(), + } + } + + pub async fn create( + &self, + definition: SessionInstanceDefinition, + ) -> std::result::Result { + let group = definition.group.clone(); + let created = self + .loader + .create_instance(&self.anchor, &group) + .with(self.anchor.instance()) + .with(definition) + .await + .map_err(|error| SessionInstanceError::Create(error.to_string()))?; + let instance = SessionInstance { + instance_id: created.plugin.0, + }; + self.instances + .lock() + .unwrap() + .insert(instance.instance_id, created.view); + if let Some((row, state)) = created + .report + .iter() + .find(|(_, state)| !matches!(state, rutis_loader::edit::InstanceResult::Active)) + { + self.remove(instance).await?; + return Err(SessionInstanceError::NotReady(format!("{row}: {state:?}"))); + } + Ok(instance) } - /// Creates an instance of `group` where the configuration tree puts it - /// inside this loader's instance. - pub fn create_instance(&self, group: &str) -> rutis_loader::edit::CreateInstance<'_> { - self.loader.create_instance(&self.anchor, group) + + pub async fn remove( + &self, + instance: SessionInstance, + ) -> std::result::Result<(), SessionInstanceError> { + let view = self + .instances + .lock() + .unwrap() + .get(&instance.instance_id) + .cloned(); + if let Some(view) = view { + let result = view.shutdown().await; + self.instances.lock().unwrap().remove(&instance.instance_id); + result.map_err(|error| SessionInstanceError::Cleanup(error.to_string()))?; + if let Some(error) = view.state().error { + return Err(SessionInstanceError::Cleanup(error.to_string())); + } + } + Ok(()) } } /// Identity of one Session subtree, which the runtime builds keys from. diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index f68da8c1a7..b9b3b38afd 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1511,7 +1511,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("providerConnectionResolver", "host-resource"), ("providerService", "secret"), ("serverControl", "control"), - ("sessionLoader", "control"), ("sessionStore", "owner-api"), ("settingsService", "owner-api"), ("timelineFactory", "control"), diff --git a/crates/dim-app-server/src/mcp/publication.rs b/crates/dim-app-server/src/mcp/publication.rs index 77ae5463ee..c14623fe58 100644 --- a/crates/dim-app-server/src/mcp/publication.rs +++ b/crates/dim-app-server/src/mcp/publication.rs @@ -11,13 +11,12 @@ use super::{ use crate::settings::{SettingsScope, SettingsService}; use dim_agent_capabilities::host::CredentialVariablesHost; use dim_agent_runtime::{ - Modules, Names, SessionLifecycle, SessionLoader, SessionPhase, StateCell, - names::ServiceCatalog, register_part, + Modules, Names, SessionInstance, SessionInstanceDefinition, SessionInstanceError, + SessionLifecycle, SessionLoader, SessionPhase, StateCell, names::ServiceCatalog, register_part, }; -use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, ErrorKind, Key, TypeKey}; +use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis::{Ctx, Plugin}; use rutis_loader::Loader; -use rutis_loader::edit::InstanceResult; use serde::Serialize; use serde_json::json; use std::{ @@ -83,17 +82,35 @@ impl McpOwner { } } -/// Private immutable instance value. Never encoded in loader options. -#[derive(Clone)] -pub(super) struct ConnectionConfig { +#[derive(serde::Serialize, serde::Deserialize)] +struct ConnectionData { id: String, configuration: McpServerSettings, +} + +pub(super) struct ConnectionPlugin { + data: ConnectionData, key: Key, } -pub(super) struct ConnectionPlugin(ConnectionConfig); impl ConnectionPlugin { - pub(super) fn new(value: &ConnectionConfig) -> Self { - Self(value.clone()) + pub(super) fn new( + value: &SessionInstanceDefinition, + scope: rutis::host::InstanceId, + ) -> rutis::Result { + Ok(Self { + data: serde_json::from_value(value.instance_data.clone())?, + key: Key::dynamic(value.definition_id.clone()).instance(scope), + }) + } + + fn standalone(build: &rutis_loader::resolve::Build) -> rutis::Result { + let definition = build + .value::() + .ok_or_else(|| rutis::Error::msg("missing MCP instance definition"))?; + let scope = build + .value::() + .ok_or_else(|| rutis::Error::msg("missing MCP instance scope"))?; + Self::new(&definition, *scope) } } impl Plugin for ConnectionPlugin { @@ -102,8 +119,11 @@ impl Plugin for ConnectionPlugin { "McpServer" } async fn apply(&self, ctx: &Ctx, auth: Arc) -> rutis::Result { - let plugin = - McpServerPlugin::new(&self.0.id, self.0.configuration.clone(), self.0.key.clone())?; + let plugin = McpServerPlugin::new( + &self.data.id, + self.data.configuration.clone(), + self.key.clone(), + )?; Plugin::apply(&plugin, ctx, auth).await } } @@ -245,15 +265,11 @@ impl McpPublication { /// Explicit standalone hosts register and install this top-level template. /// Agents instead register the template nested in their Session assembly. pub fn standalone_template(builtins: &mut Modules) -> serde_json::Value { - builtins.builtins.register_with::( - "StandaloneMcpServer", - |build, _| { - let value = build.value::().ok_or_else(|| { - rutis::Error::from(ErrorKind::PluginFailed("missing MCP instance value".into())) - })?; - Ok(ConnectionPlugin::new(&value)) - }, - ); + builtins + .builtins + .register_with::("StandaloneMcpServer", |build, _| { + ConnectionPlugin::standalone(build) + }); json!({"id":GROUP,"group":true,"instanced":true,"config":[{"id":"StandaloneMcpServer","name":"StandaloneMcpServer"}]}) } } @@ -393,7 +409,7 @@ struct Generation { id: String, configuration: McpServerSettings, owner: McpOwner, - instance: rutis_loader::edit::Instance, + instance: SessionInstance, service: Arc, lease: Weak, /// Set before a withdrawal retires it, so its holders report the entry @@ -654,8 +670,12 @@ impl Projection { let mut failed = false; for reference in references { if let Some(generation) = self.generations.remove(&reference) - && (generation.instance.view.shutdown().await.is_err() - || generation.instance.view.state().error.is_some()) + && generation + .owner + .loader + .remove(generation.instance) + .await + .is_err() { self.cleanup_failed.insert(generation.source); failed = true; @@ -721,16 +741,31 @@ impl Projection { McpServerPlugin::new(&id, configuration.clone(), key.clone())?; let created = owner .loader - .create_instance(GROUP) - .with(ConnectionConfig { - id: id.clone(), - configuration: configuration.clone(), - key: key.clone(), + .create(SessionInstanceDefinition { + group: GROUP.to_owned(), + definition_id: reference.clone(), + instance_data: serde_json::json!(ConnectionData { + id: id.clone(), + configuration: configuration.clone() + }), }) .await; let instance = match created { Ok(instance) => instance, - Err(_) => { + Err(error) => { + if matches!(error, SessionInstanceError::Cleanup(_)) { + self.cleanup_failed.insert(source); + } + if !matches!(error, SessionInstanceError::Create(_)) + && (!owner.admits() || cancel.is_cancelled()) + { + self.publish(); + return Err(if owner.admits() { + McpError::Unavailable + } else { + McpError::Closed + }); + } self.application_failed.insert( (owner.id.clone(), source, id.clone()), (self.sources[&source].revision.clone(), owner.closed.clone()), @@ -740,15 +775,8 @@ impl Projection { } }; let service = owner.ctx.get_at(&key); - if !owner.admits() - || cancel.is_cancelled() - || service.is_none() - || instance - .report - .iter() - .any(|(_, result)| !matches!(result, InstanceResult::Active)) - { - if instance.view.shutdown().await.is_err() || instance.view.state().error.is_some() { + if !owner.admits() || cancel.is_cancelled() || service.is_none() { + if owner.loader.remove(instance).await.is_err() { self.cleanup_failed.insert(source); } if owner.admits() && !cancel.is_cancelled() { @@ -941,10 +969,7 @@ mod tests { let fault = faults.clone(); builtins.builtins.register_with::( "StandaloneMcpServer", - move |build, _| { - let config = build.value::().unwrap(); - Ok(Probe(ConnectionPlugin::new(&config), fault.clone())) - }, + move |build, _| Ok(Probe(ConnectionPlugin::standalone(build)?, fault.clone())), ); let plugin = rutis_loader::LoaderPlugin::new(builtins, Default::default()); let loader = plugin.handle(); diff --git a/crates/dim-app-server/src/mcp/session.rs b/crates/dim-app-server/src/mcp/session.rs index a7683bec27..7ba97bc027 100644 --- a/crates/dim-app-server/src/mcp/session.rs +++ b/crates/dim-app-server/src/mcp/session.rs @@ -35,10 +35,15 @@ use tokio_util::{sync::CancellationToken, task::TaskTracker}; pub fn install(builder: &mut AgentBuilder) { crate::register_names(builder.catalog_mut()); builder - .session_extension_part::( + .session_extension_part::( super::publication::GROUP, "McpServer", - |_, value| Ok(Box::new(super::publication::ConnectionPlugin::new(value))), + |names, value| { + Ok(Box::new(super::publication::ConnectionPlugin::new( + value, + names.instance(dim_agent_runtime::SESSION_GROUP)?, + )?)) + }, ) .require_part("McpSession") .require_part("TemporaryMcp"); diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index 4cc3bcd244..e941fb1859 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -31,7 +31,7 @@ use tokio::sync::watch; /// The Session and branch services marked `#[rutis::service]`: provided in /// their instance, each is served by name there. -fn crossing_instance_names() -> [(String, &'static str); 16] { +fn crossing_instance_names() -> [(String, &'static str); 17] { [ ( name_of::(), @@ -50,6 +50,7 @@ fn crossing_instance_names() -> [(String, &'static str); 16] { name_of::(), SESSION_GROUP, ), + (name_of::(), SESSION_GROUP), (name_of::(), SESSION_GROUP), (name_of::(), BRANCH_GROUP), ( diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 1ea87fc2a4..611a632e21 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -620,3 +620,82 @@ async fn node_session_fault_is_observed_and_closes_the_native_session() { server.shutdown(); server.join().await.unwrap(); } + +struct FixtureInstance; +impl rutis::Plugin for FixtureInstance { + type Deps = (); + fn name(&self) -> &str { + "FixtureInstance" + } + async fn apply(&self, _: &rutis::Ctx, (): ()) -> rutis::Result { + Ok(()) + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] +async fn node_session_loader_creates_and_removes_only_its_own_instance() { + let mut parts = branch_part(); + parts.rows = vec![json!({ + "id": "session-loader", + "name": parts.anchor.parent().unwrap().join("fixtures/session-loader.ts"), + "provides": {}, + })]; + let (server, agent) = launch_with( + Arc::new(MockTools), + ServerConfig { + session_typescript: Some(parts), + ..Default::default() + }, + |builder| { + builder.session_extension_part::( + "FixtureInstances", + "FixtureInstance", + |_, definition| { + if definition.definition_id != "fixture-content" + || definition.instance_data != json!({"body":"content"}) + { + return Err(rutis::Error::msg("unexpected instance definition")); + } + Ok(Box::new(FixtureInstance)) + }, + ); + builder.require_part("SessionLoaderFixture"); + }, + ) + .await; + let mut client = Client::new_version(&server, false, 3).await; + let first = super::session_typescript::new_session(&mut client, json!([])).await; + let second = super::session_typescript::new_session(&mut client, json!([])).await; + let leaves = || { + agent + .diagnostics() + .unwrap() + .plugins + .into_iter() + .filter(|plugin| { + plugin.name == "FixtureInstance" && plugin.state == rutis::host::FiberState::Active + }) + .count() + }; + let before = leaves(); + let reply = client + .rpc("session.loaderfixture.create", json!({"sessionId": first})) + .await; + assert_ok(&reply); + let id = reply["result"]["instanceId"].as_u64().unwrap(); + assert_eq!(leaves(), before + 1); + for (session, expected) in [(second, before + 1), (first, before)] { + assert_ok( + &client + .rpc( + "session.loaderfixture.remove", + json!({"sessionId":session,"instanceId":id}), + ) + .await, + ); + assert_eq!(leaves(), expected); + } + server.shutdown(); + server.join().await.unwrap(); +} diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index ad43cfe422..e9fbe900dc 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -86,7 +86,7 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `sessionIdentity` | session | SessionScope | data | `get` async | | `sessionLanguage` | session | PromptSources | data | `get` async | | `sessionLifecycle` | session | SessionScope | data | `activated` async, `closing` async, `failure` async, `hold` async, `observeFault` async, `release` async, `reportFault` async | -| `sessionLoader` | session | SessionScope | internal(control) | — | +| `sessionLoader` | session | SessionScope | data | `create` async, `remove` async | | `sessionMethods` | session | SessionMethods | data | `register` async | | `skillsConfig` | session | SessionScope | data | `get` async | | `submitChecks` | session | InputMethods | data | `check` async, `register` async | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index e96df3e8f5..412c1802e1 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -3030,6 +3030,12 @@ "declared": true, "external": true }, + { + "service": "dim_agent_capabilities::skills::content::Contribution#user:graph@session", + "provider": 58, + "declared": false, + "external": true + }, { "service": "dim_agent_capabilities::tool_registry::ToolRegistry@session", "provider": 54, @@ -4156,6 +4162,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#sessionLoader@session", + "provider": 33, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#sessionMethods@session", "provider": 49, diff --git a/docs/architecture/rust-agent/generated/services.json b/docs/architecture/rust-agent/generated/services.json index 4b91bc12e7..82c28896d1 100644 --- a/docs/architecture/rust-agent/generated/services.json +++ b/docs/architecture/rust-agent/generated/services.json @@ -2343,6 +2343,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#sessionLoader@session", + "provider": 21, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#sessionMethods@session", "provider": 30, diff --git a/docs/architecture/rust-agent/plugins/Skills.md b/docs/architecture/rust-agent/plugins/Skills.md index df9bc5dcb8..314565420a 100644 --- a/docs/architecture/rust-agent/plugins/Skills.md +++ b/docs/architecture/rust-agent/plugins/Skills.md @@ -198,16 +198,11 @@ text when it is absent or fails; the factory `SkillsConfig` outranks it ### Content instances -`SkillContentInstances` is an instanced Session extension template. Each enabled, -active catalog definition creates a `SkillContent` leaf with an immutable private -definition and a unique scoped contribution key passed through -`create_instance().with(...)`. Definitions and bodies are not loader row options. -The leaf provides its content service and adds the same service to the -collection of ready content that Skills holds for its generation and hands to -each leaf in its instance value; disposal withdraws it. The collection is no -service, so a leaf does not wait for Skills, which waits for its leaves: no -apply-time dependency cycle and no undeclared dynamic read. Each Skills -generation closes its leaves with itself and starts a new collection. +`SkillContentInstances` is an instanced Session extension template. Skills calls +`sessionLoader.create` with the Skill id as `definitionId` and the immutable +definition as `instanceData`. SkillContent publishes the definition at its +private Session-scoped key. Skills reads the contributions of the instances +it owns and releases them through `sessionLoader.remove`. The catalog still owns source precedence, shadowing and enablement. Skills owns selection and reconciliation, not a second lifecycle tree. Unchanged definitions @@ -239,8 +234,7 @@ replacement task and shuts down every content fiber; tool handlers reject work a generation cancellation. Initial creation also runs in a tracked task, so dropping apply cannot abandon it. Creation is awaited to settlement even if cancelled, then an unusable instance is shut down. Failed updates drain partial/current -instances and publish an unavailable view. `FiberView::shutdown` and its retained -error preserve cleanup failures; no lock-taking loader mutation runs in apply or +instances and publish an unavailable view. `sessionLoader.remove` propagates cleanup failures; no lock-taking loader mutation runs in apply or dispose. Content lifecycle failures use the existing public `SkillsError::Closed` state, with details logged; disposer failures propagate to Session shutdown. Catalog errors retain their existing public variants. Closing one Session cannot @@ -340,7 +334,7 @@ The instanced loader group containing one [SkillContent](Skills.md#skillcontent) ### Dependencies -None on the group itself. The leaf declares its Session contribution dependency. +None on the group itself. ### Events and lifetime @@ -374,11 +368,8 @@ None: its instance value carries what it needs. ### Events and lifetime -No Timeline events or external execution. Private instance values contain the -definition, the scoped service key and the Skills generation's collection of -ready content; loader options never contain the Skill body. The leaf provides -its definition and adds that same service to the collection. Its effect withdraws the contribution. Skills coordinates selection; -rutis owns the instance lifecycle. See [Skills](Skills.md) for update and failure rules. +The leaf publishes its immutable definition under the private key derived from +`definitionId` in its Session. Unloading the leaf withdraws that binding. See [Skills](Skills.md) for update and failure rules. ### Tests diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index f3cca2728f..fff7e88f39 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -203,7 +203,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `hooksService` | process | HooksSettings | host-resource | | `providerService` | process | Provider | 当前为 secret,迁移后通过数据操作使用凭据 | | `providerConnectionResolver` | process | Provider | host-resource | -| `sessionLoader` | session | SessionScope | control | | `timelineFactory` | session | SessionScope | control | ## 4. 批次契约(#1292) diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index fa7b41092e..81664ffa7b 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -1019,6 +1019,24 @@ 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 } +export interface SessionInstanceDefinition { + group: string + definitionId: string + instanceData: import('./plugin.js').BridgeJsonValue +} + +export interface SessionInstance { + instanceId: number | bigint +} + +/** The loader anchored in this Session's subtree. */ +export interface SessionLoader { + /** @throws {SessionInstanceErrorThrown} */ + create(definition: SessionInstanceDefinition): Promise + /** @throws {SessionInstanceErrorThrown} */ + remove(instance: SessionInstance): Promise +} + /** A branch of a Session. */ export interface SessionRef { sessionId: string @@ -1367,6 +1385,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(SessionInstanceError)` throws. */ +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> @@ -1411,6 +1432,7 @@ export interface Services { dispatcher: Dispatcher timeline: Timeline partRegistry: PartRegistry + sessionLoader: SessionLoader sessionPermissions: SessionPermissions collaborationConfig: CollaborationConfig collaborationDirectory: CollaborationDirectory diff --git a/runtime/fixtures/session-loader.ts b/runtime/fixtures/session-loader.ts new file mode 100644 index 0000000000..e29fb6015d --- /dev/null +++ b/runtime/fixtures/session-loader.ts @@ -0,0 +1,30 @@ +import { definePlugin } from '@arcships/rutis' +import type { SessionMethods, Services } from '../../npm/plugin.js' +import { partRow } from './part-row.ts' + +const part = definePlugin({ + name: 'SessionLoaderFixture', + inject: ['sessionLoader', 'sessionMethods'], + async apply(ctx) { + const loader = ctx.use('sessionLoader') + const namespace = 'session.loaderfixture' + await ctx.use('sessionMethods').register(namespace, + ['create', 'remove'].map(name => ({ + name: namespace + '.' + name, mutating: true, interruption: 'report', progress: false, + })), + async call => { + if (call.method === namespace + '.create') { + const { instanceId } = await loader.create({ + group: 'FixtureInstances', definitionId: 'fixture-content', instanceData: { body: 'content' }, + }) + return { kind: 'value', value: { instanceId: Number(instanceId) } } + } + const id = call.params.instanceId + if (typeof id !== 'number') throw new Error('missing instanceId') + await loader.remove({ instanceId: id }) + return { kind: 'value', value: {} } + }) + }, +}) + +export default partRow('session', part) From 8171d21f4fc2e741fd6817f3556af3509fc5b6da Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 19:59:22 +0800 Subject: [PATCH 06/12] Check the loader group parent before creating a Session child --- .../src/input_queue/face.rs | 14 ++++++++++++-- crates/dim-agent-runtime/src/assembly.rs | 6 +++++- crates/dim-agent-runtime/src/config.rs | 2 +- crates/dim-agent-runtime/src/scope.rs | 17 ++++++++++++++++- crates/dim-app-server/src/mcp/publication.rs | 2 +- .../tests/transport_flow/branch_typescript.rs | 13 +++++++++++++ .../contracts/runtime-owner-operations.md | 2 +- runtime/fixtures/session-loader.ts | 3 ++- 8 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/dim-agent-capabilities/src/input_queue/face.rs b/crates/dim-agent-capabilities/src/input_queue/face.rs index cc98350650..d81f1f645c 100644 --- a/crates/dim-agent-capabilities/src/input_queue/face.rs +++ b/crates/dim-agent-capabilities/src/input_queue/face.rs @@ -108,13 +108,23 @@ impl HostDispatch for SubmitChecks { let _finish = stop.clone().drop_guard(); let run = owner.check(&request, &stop); tokio::pin!(run); + let cancellation = + async { settle(cancelled.call_async(Value::List(vec![])).await?).await }; let result = tokio::select! { result = &mut run => result, - _ = async { settle(cancelled.call_async(Value::List(vec![])).await?).await } => { + _ = cancellation => { stop.cancel(); run.await } - }.map_err(|_| rutis_bridge::exports::failure("SubmitCheckError","cancelled","submit check interrupted".into(),None))?; + } + .map_err(|_| { + rutis_bridge::exports::failure( + "SubmitCheckError", + "cancelled", + "submit check interrupted".into(), + None, + ) + })?; arg(&result) })) } diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 96513f1af2..50554cd8d0 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -1108,7 +1108,11 @@ impl DynPlugin for SessionScopePlugin { let (owner, scope) = (&self.owner, self.scope); ctx.provide_at( scope.key::(), - Arc::new(crate::SessionLoader::new(owner.loader.clone(), ctx.clone())), + Arc::new(crate::SessionLoader::new( + owner.loader.clone(), + ctx.clone(), + Some(SESSION_GROUP), + )), )?; ctx.provide_at(scope.key::(), Arc::new(owner.config.clone()))?; ctx.provide_at( diff --git a/crates/dim-agent-runtime/src/config.rs b/crates/dim-agent-runtime/src/config.rs index 6c9f7effd4..38e20edcba 100644 --- a/crates/dim-agent-runtime/src/config.rs +++ b/crates/dim-agent-runtime/src/config.rs @@ -516,7 +516,7 @@ impl SessionLifecycle { _ = stop.cancelled() => {} _ = async { loop { - let current = faults.borrow_and_update().clone().map(crate::SessionFault::from); + let current = faults.borrow_and_update().clone().map(Into::into); if listener(current).await.is_err() || faults.changed().await.is_err() { return; } diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index 0ae9afbe1a..f1a2dd4b53 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -73,14 +73,20 @@ pub enum SessionInstanceError { pub struct SessionLoader { loader: rutis_loader::Loader, anchor: Ctx, + parent_group: Option<&'static str>, instances: std::sync::Mutex>, } #[rutis::service] impl SessionLoader { - pub fn new(loader: rutis_loader::Loader, anchor: Ctx) -> Self { + pub fn new( + loader: rutis_loader::Loader, + anchor: Ctx, + parent_group: Option<&'static str>, + ) -> Self { Self { loader, anchor, + parent_group, instances: Default::default(), } } @@ -90,6 +96,15 @@ impl SessionLoader { definition: SessionInstanceDefinition, ) -> std::result::Result { let group = definition.group.clone(); + if self + .loader + .get(&group) + .is_some_and(|row| row.parent.as_deref() != self.parent_group) + { + return Err(SessionInstanceError::Create(format!( + "instance group {group} is outside the loader scope" + ))); + } let created = self .loader .create_instance(&self.anchor, &group) diff --git a/crates/dim-app-server/src/mcp/publication.rs b/crates/dim-app-server/src/mcp/publication.rs index c14623fe58..20985eecaa 100644 --- a/crates/dim-app-server/src/mcp/publication.rs +++ b/crates/dim-app-server/src/mcp/publication.rs @@ -44,7 +44,7 @@ pub struct McpOwner { } impl McpOwner { pub fn new(ctx: Ctx, loader: Loader) -> Self { - let loader = Arc::new(SessionLoader::new(loader, ctx.clone())); + let loader = Arc::new(SessionLoader::new(loader, ctx.clone(), None)); Self { id: uuid::Uuid::new_v4().to_string(), closed: ctx.cancellation_token(), diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 611a632e21..149e924c0c 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -679,6 +679,19 @@ async fn node_session_loader_creates_and_removes_only_its_own_instance() { .count() }; let before = leaves(); + let refused = client + .rpc( + "session.loaderfixture.create", + json!({"sessionId": first, "group":"session"}), + ) + .await; + assert!( + refused["error"] + .to_string() + .contains("outside the loader scope"), + "{refused}" + ); + assert_eq!(leaves(), before); let reply = client .rpc("session.loaderfixture.create", json!({"sessionId": first})) .await; diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index b1c8f37e48..69027af1ec 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -17,7 +17,7 @@ | Caller → owner | New API | | --- | --- | | Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | -| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session anchors each instance. Skills supplies its content definition; MCP supplies its connection definition and resolves driver and credentials locally. | +| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Skills supplies its content definition; MCP supplies its connection definition and resolves driver and credentials locally. | | Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | | Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | | History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | diff --git a/runtime/fixtures/session-loader.ts b/runtime/fixtures/session-loader.ts index e29fb6015d..e8edf10eec 100644 --- a/runtime/fixtures/session-loader.ts +++ b/runtime/fixtures/session-loader.ts @@ -15,7 +15,8 @@ const part = definePlugin({ async call => { if (call.method === namespace + '.create') { const { instanceId } = await loader.create({ - group: 'FixtureInstances', definitionId: 'fixture-content', instanceData: { body: 'content' }, + group: typeof call.params.group === 'string' ? call.params.group : 'FixtureInstances', + definitionId: 'fixture-content', instanceData: { body: 'content' }, }) return { kind: 'value', value: { instanceId: Number(instanceId) } } } From 167d8d83f18881e6892ae4e9f64f19822d2f55a9 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:02:05 +0800 Subject: [PATCH 07/12] Keep resolved MCP connections with their publication owner --- crates/dim-app-server/src/mcp/publication.rs | 94 ++++++++++++------- crates/dim-app-server/src/mcp/session.rs | 2 +- docs/design/branch-typescript.md | 2 +- .../contracts/runtime-owner-operations.md | 4 +- docs/design/plugin-contract.md | 4 +- docs/design/session-typescript.md | 2 +- docs/typescript-plugin-authoring.md | 4 +- docs/zh/design/plugin-contract.md | 4 +- 8 files changed, 69 insertions(+), 47 deletions(-) diff --git a/crates/dim-app-server/src/mcp/publication.rs b/crates/dim-app-server/src/mcp/publication.rs index 20985eecaa..49a952c0ae 100644 --- a/crates/dim-app-server/src/mcp/publication.rs +++ b/crates/dim-app-server/src/mcp/publication.rs @@ -20,7 +20,7 @@ use rutis_loader::Loader; use serde::Serialize; use serde_json::json; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap}, sync::{ Arc, Weak, atomic::{AtomicBool, Ordering}, @@ -82,25 +82,14 @@ impl McpOwner { } } -#[derive(serde::Serialize, serde::Deserialize)] -struct ConnectionData { - id: String, - configuration: McpServerSettings, -} - pub(super) struct ConnectionPlugin { - data: ConnectionData, - key: Key, + definition: (rutis::host::InstanceId, String), } impl ConnectionPlugin { - pub(super) fn new( - value: &SessionInstanceDefinition, - scope: rutis::host::InstanceId, - ) -> rutis::Result { - Ok(Self { - data: serde_json::from_value(value.instance_data.clone())?, - key: Key::dynamic(value.definition_id.clone()).instance(scope), - }) + pub(super) fn new(value: &SessionInstanceDefinition, scope: rutis::host::InstanceId) -> Self { + Self { + definition: (scope, value.definition_id.clone()), + } } fn standalone(build: &rutis_loader::resolve::Build) -> rutis::Result { @@ -110,21 +99,23 @@ impl ConnectionPlugin { let scope = build .value::() .ok_or_else(|| rutis::Error::msg("missing MCP instance scope"))?; - Self::new(&definition, *scope) + Ok(Self::new(&definition, *scope)) } } impl Plugin for ConnectionPlugin { - type Deps = ::Deps; + type Deps = (Arc, Arc); fn name(&self) -> &str { "McpServer" } - async fn apply(&self, ctx: &Ctx, auth: Arc) -> rutis::Result { - let plugin = McpServerPlugin::new( - &self.data.id, - self.data.configuration.clone(), - self.key.clone(), - )?; - Plugin::apply(&plugin, ctx, auth).await + async fn apply(&self, ctx: &Ctx, (owner, auth): Self::Deps) -> rutis::Result { + let plugin = owner + .definitions + .lock() + .unwrap() + .get(&self.definition) + .cloned() + .ok_or_else(|| rutis::Error::msg("unknown MCP connection definition"))?; + Plugin::apply(plugin.as_ref(), ctx, auth).await } } @@ -156,6 +147,7 @@ enum Command { Settle { reply: oneshot::Sender> }, } pub struct Publication { + definitions: std::sync::Mutex>>, commands: mpsc::Sender, released: watch::Sender<()>, applications: StateCell>, @@ -368,6 +360,7 @@ impl DynPlugin for McpPublication { let (commands, receiver) = mpsc::channel(64); let (released, releases) = watch::channel(()); let port = Arc::new(Publication { + definitions: Default::default(), commands, released, applications: StateCell::new(BTreeMap::new()), @@ -669,16 +662,22 @@ impl Projection { async fn retire(&mut self, references: Vec) -> bool { let mut failed = false; for reference in references { - if let Some(generation) = self.generations.remove(&reference) - && generation + if let Some(generation) = self.generations.remove(&reference) { + if generation .owner .loader .remove(generation.instance) .await .is_err() - { - self.cleanup_failed.insert(generation.source); - failed = true; + { + self.cleanup_failed.insert(generation.source); + failed = true; + } + self.port + .definitions + .lock() + .unwrap() + .remove(&(generation.owner.scope, reference)); } } failed @@ -738,21 +737,25 @@ impl Projection { } let reference = format!("mcp:{}", uuid::Uuid::new_v4()); let key = Key::::dynamic(reference.clone()).instance(owner.scope); - McpServerPlugin::new(&id, configuration.clone(), key.clone())?; + let plugin = McpServerPlugin::new(&id, configuration.clone(), key.clone())?; + let definition = (owner.scope, reference.clone()); + self.port + .definitions + .lock() + .unwrap() + .insert(definition.clone(), Arc::new(plugin)); let created = owner .loader .create(SessionInstanceDefinition { group: GROUP.to_owned(), definition_id: reference.clone(), - instance_data: serde_json::json!(ConnectionData { - id: id.clone(), - configuration: configuration.clone() - }), + instance_data: serde_json::Value::Null, }) .await; let instance = match created { Ok(instance) => instance, Err(error) => { + self.port.definitions.lock().unwrap().remove(&definition); if matches!(error, SessionInstanceError::Cleanup(_)) { self.cleanup_failed.insert(source); } @@ -779,6 +782,7 @@ impl Projection { if owner.loader.remove(instance).await.is_err() { self.cleanup_failed.insert(source); } + self.port.definitions.lock().unwrap().remove(&definition); if owner.admits() && !cancel.is_cancelled() { self.application_failed.insert( (owner.id.clone(), source, id.clone()), @@ -1042,6 +1046,24 @@ mod tests { std::fs::remove_dir_all(self.home).unwrap(); } } + #[tokio::test] + async fn publication_admits_a_bearer_that_expands_to_empty() { + let fixture = Fixture::with_entry( + None, + json!({ + "type":"http","url":"https://example.test/mcp", + "auth":{"type":"bearer","token":"${DIM_EMPTY_MCP_PUBLICATION_TEST:-}"} + }), + ) + .await; + let connection = fixture.acquire().await; + assert!(matches!( + connection.service.state(), + McpServerState::Disconnected + )); + fixture.close().await; + } + #[tokio::test] async fn publication_reload_and_stop_retire_retained_connections() { let mut fixture = Fixture::new().await; diff --git a/crates/dim-app-server/src/mcp/session.rs b/crates/dim-app-server/src/mcp/session.rs index 7ba97bc027..429fb92bc2 100644 --- a/crates/dim-app-server/src/mcp/session.rs +++ b/crates/dim-app-server/src/mcp/session.rs @@ -42,7 +42,7 @@ pub fn install(builder: &mut AgentBuilder) { Ok(Box::new(super::publication::ConnectionPlugin::new( value, names.instance(dim_agent_runtime::SESSION_GROUP)?, - )?)) + ))) }, ) .require_part("McpSession") diff --git a/docs/design/branch-typescript.md b/docs/design/branch-typescript.md index 521db102ab..c995006137 100644 --- a/docs/design/branch-typescript.md +++ b/docs/design/branch-typescript.md @@ -50,7 +50,7 @@ every instance of that group; a row gets the nearest enclosing instance. Its met | --- | --- | --- | --- | | `treeCommands` | `session` | `TreeCommands` | `list()`, `info(id)`, `input(id, input)`, `create(parent, at, options, cancelled)`, `end(id, source)`, `page(id, after, limit)` | | `dispatcher` | `branch` | `Dispatcher` | `consume(name, keys, rebuild, handler)`, `listen(name, keys, handler)`, `committed()`, `notify()`, `sequence()`, `changed()` | -| `branchLifecycle` | `branch` | `BranchLifecycle` | `activated()`, `closing()` | +| `branchLifecycle` | `branch` | `BranchLifecycle` | `activated()`, `closing()`. `registerOpening` registers work that branch opening waits for. | | `timeline` | `branch` | `Timeline` | `append({type, name, data, tags?})` → the committed event; `query(query)` (the one bounded read, `include_publishing` for the branch's not-yet-published facts), `ancestors()`, `sequence()`, `committed()`, `hasPending()` | | `timelineIdentity` | `branch` | `TimelineIdentity` | `get()` → `{sessionId, branchId}` | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 69027af1ec..68117a01d4 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -17,7 +17,7 @@ | Caller → owner | New API | | --- | --- | | Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | -| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Skills supplies its content definition; MCP supplies its connection definition and resolves driver and credentials locally. | +| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | | Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | | Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | | History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | @@ -26,7 +26,7 @@ | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | -| Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → AgentError or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | +| Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → SessionFault or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | | Compaction, stop and activity callers → `agentLoop` | `agentLoop.compact({}) → sequence`, `stopTurn({turnId, reason}) → sequence or null`; `agentLoop.state({}) → {phase, turnId?}`, `observe(listener)` delivers that snapshot. | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 5330ed2b61..035a2a33ad 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -116,12 +116,12 @@ R4). This table says what each name Dim defines is for. | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | | `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | | `sessionIdentity` | `session` | SessionScope | yes | `get()`: `{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload | +| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | | `sessionConfig` | `session` | SessionScope | yes | `get()`: the creation-time configuration, the snapshot a tool call carries | | `agentConfig` | `session` | SessionScope | yes | `get()`: the Agent's identity and default model | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | | `dispatcher` | `branch` | BranchScope | yes, `consume`, `listen` and reads; their Rust forms are the same `consume` and `subscribe`, which is Rust-only | Ordered consumption (§5.2) | -| `branchLifecycle` | `branch` | BranchScope | yes | `activated`, `closing` | +| `branchLifecycle` | `branch` | BranchScope | yes | `activated`, `closing`. `registerOpening` registers work that branch opening waits for. | | `timelineIdentity` | `branch` | BranchScope | yes | `{sessionId, branchId}` | The Rust host ports and registries (ToolRegistry, PromptRegistry, ToolHost, ModelHost, diff --git a/docs/design/session-typescript.md b/docs/design/session-typescript.md index 9e40312542..139504d727 100644 --- a/docs/design/session-typescript.md +++ b/docs/design/session-typescript.md @@ -319,7 +319,7 @@ A Session row reads its Session from the Session services every language has | --- | --- | | `sessionIdentity` | `get()` returns `{sessionId, restored}`. | | `sessionConfig` | `get()` returns the creation-time SessionConfig in the serde form ToolCall uses. | -| `sessionLifecycle` | `activated()`, `closing()`, `hold()` and `release(id)`, the phases and activity holds of the Rust `SessionLifecycle`; `hold()` returns the id of a hold the calling row owns, which lasts until `release(id)` or that row's unload. | +| `sessionLifecycle` | `activated()`, `closing()`, `hold()` and `release(id)`, the phases and activity holds of the Rust `SessionLifecycle`; `hold()` returns the id of a hold the calling row owns, which lasts until `release(id)` or that row's unload. `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | There is no setup call and no `sessionEvents:` entry: the row registers ``ctx.on(`session/${sessionId}`, listener)`` in its `apply` with the id it read. The channel name is diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 67eafc82a9..e3fa1e0207 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -768,7 +768,7 @@ A Session part learns about its Session from three Session services, read by nam | --- | --- | | `sessionIdentity` | `get()` returns `{sessionId, restored}`; `restored` is true when the Session was loaded from storage rather than created. | | `sessionConfig` | `get()` returns the creation-time configuration, the same snapshot a `ToolCall` carries as `config`. | -| `sessionLifecycle` | `activated()` resolves when the Session is published (`false` if it never is); `closing()` resolves when its close starts. `hold()` keeps an idle unload from ending accepted work: it returns the id of a hold the calling part owns, or `null` once the Session is closing or its release is decided. `release(id)` ends that hold and returns whether it was still held; the part's unload ends the holds it still has. | +| `sessionLifecycle` | `activated()` resolves when the Session is published (`false` if it never is); `closing()` resolves when its close starts. `hold()` keeps an idle unload from ending accepted work: it returns the id of a hold the calling part owns, or `null` once the Session is closing or its release is decided. `release(id)` ends that hold and returns whether it was still held; the part's unload ends the holds it still has. `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | A part needs no tool or client method to observe. This one listens to its Session's channel from `apply` and stops when the Session starts closing: @@ -846,7 +846,7 @@ parts. | --- | --- | | `dispatcher` | `consume(name, keys, rebuild, handler)` registers an ordered consumer on the calling part's context. It subscribes first and holds the matching facts, calls `rebuild` once — the part reads the facts it folds through `timeline.query` including its publishing facts and returns the cutoff that read took — then delivers the held facts above the cutoff and each later matching fact, in sequence order, and none twice. `listen(name, keys, handler)` registers a live consumer only, for a part that does not rebuild. A handler's throw/rejection follows the native branch failure path. `committed()` returns the committed cutoff; read facts and properties through `timeline.query`. `notify/sequence/changed` expose native dispatch progress and wakeups, not an ordered event subscription. | | `treeCommands` | Session directory `list/info`, validated `input` by branch id and `create`. These are the Rust data methods, not the process `sessions` request envelopes. | -| `branchLifecycle` | Background work waits for `activated()` and releases its resources when `closing()` resolves. Never wait for activation inside a Dispatcher callback. | +| `branchLifecycle` | Background work waits for `activated()` and releases its resources when `closing()` resolves. Never wait for activation inside a Dispatcher callback. `registerOpening` registers work that branch opening waits for. | | `timelineIdentity` | `get()` returns the original Session and branch ids. | This part reconstructs its own input count, then follows live input. The native subscription diff --git a/docs/zh/design/plugin-contract.md b/docs/zh/design/plugin-contract.md index 73f2f50f92..591456f797 100644 --- a/docs/zh/design/plugin-contract.md +++ b/docs/zh/design/plugin-contract.md @@ -105,12 +105,12 @@ process (root) process parts: storage, catalogs, connections, Ag | `collaborationMembers:` | 进程 | 成员提供者 | 已设计,未实现 | [ExternalAgent](plugins/ExternalAgent.md);实现时向 Collaboration 登记(rutis 使用 R6) | | `treeCommands` | `session` | TimelineTree | 是 | 按分支 id 的 `input`、`create`、`list`、`info` | | `sessionIdentity` | `session` | SessionScope | 是 | `get()`:`{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | 是 | `activated`、`closing`、`hold`、`release`:hold 是调用方的行拥有的 id,由 `release(id)` 或该行卸载结束 | +| `sessionLifecycle` | `session` | SessionScope | 是 | `activated`、`closing`、`hold`、`release`:hold 是调用方的行拥有的 id,由 `release(id)` 或该行卸载结束 `reportFault` 上报故障,`failure` 读取当前故障,`observeFault` 订阅。调用 `release(id)` 或卸载该行会结束订阅。 | | `sessionConfig` | `session` | SessionScope | 是 | `get()`:创建时的配置,即工具调用携带的快照 | | `agentConfig` | `session` | SessionScope | 是 | `get()`:Agent 的身份与默认模型 | | `timeline` | `branch` | BranchScope | 是,`before` 除外 | `append`、已发布序号与事件查询(§5.4);查询随其声明到达其他语言 | | `dispatcher` | `branch` | BranchScope | 是,`consume`、`listen` 和读取;它们的 Rust 形式就是同一个 `consume`,以及仅限 Rust 的 `subscribe` | 有序消费(§5.2) | -| `branchLifecycle` | `branch` | BranchScope | 是 | `activated`、`closing` | +| `branchLifecycle` | `branch` | BranchScope | 是 | `activated`、`closing`;`registerOpening` 登记分支打开时等待的工作 | | `timelineIdentity` | `branch` | BranchScope | 是 | `{sessionId, branchId}` | Rust 宿主端口和注册表(ToolRegistry、PromptRegistry、ToolHost、ModelHost、PrepareModelHost, From 44a787b27f5f83bfcadbbffe4950ef61992c606d Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:03:35 +0800 Subject: [PATCH 08/12] Preserve optional host rows when creating nested Session instances --- crates/dim-agent-runtime/src/assembly.rs | 9 +++++++++ crates/dim-agent-runtime/src/scope.rs | 12 ++++++++---- crates/dim-app-server/src/mcp/publication.rs | 7 ++++++- docs/design/contracts/runtime-owner-operations.md | 2 +- tests/integration/tests/extensions.rs | 6 +++++- 5 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 50554cd8d0..fd1b06275f 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -683,6 +683,11 @@ impl AgentBuilder { session: required_session.clone(), branch: required_branch.clone(), }; + let extension_groups: Arc<[String]> = assembly + .extensions + .iter() + .map(|(group, _)| group.clone()) + .collect(); builtins.register(session_scope_module, move |build| { let owner = build.value::>().ok_or_else(|| { rutis::Error::from(ErrorKind::PluginFailed( @@ -692,12 +697,14 @@ impl AgentBuilder { let scope = session_scope(build)?; *owner.instance.lock().unwrap() = Some(scope.instance); let required = required_session.clone(); + let extension_groups = extension_groups.clone(); let build = build.clone(); Factory::new(move || { Box::new(SessionScopePlugin { owner: (*owner).clone(), scope, build: build.clone(), + extension_groups: extension_groups.clone(), required: required.clone(), }) as Box }) @@ -1098,6 +1105,7 @@ struct SessionScopePlugin { /// The names of this copy's instances, for the mounters it builds. build: Build, required: Arc<[String]>, + extension_groups: Arc<[String]>, } impl DynPlugin for SessionScopePlugin { fn name(&self) -> &str { @@ -1112,6 +1120,7 @@ impl DynPlugin for SessionScopePlugin { owner.loader.clone(), ctx.clone(), Some(SESSION_GROUP), + self.extension_groups.clone(), )), )?; ctx.provide_at(scope.key::(), Arc::new(owner.config.clone()))?; diff --git a/crates/dim-agent-runtime/src/scope.rs b/crates/dim-agent-runtime/src/scope.rs index f1a2dd4b53..240f2cdc86 100644 --- a/crates/dim-agent-runtime/src/scope.rs +++ b/crates/dim-agent-runtime/src/scope.rs @@ -74,6 +74,7 @@ pub struct SessionLoader { loader: rutis_loader::Loader, anchor: Ctx, parent_group: Option<&'static str>, + extension_groups: std::sync::Arc<[String]>, instances: std::sync::Mutex>, } #[rutis::service] @@ -82,11 +83,13 @@ impl SessionLoader { loader: rutis_loader::Loader, anchor: Ctx, parent_group: Option<&'static str>, + extension_groups: std::sync::Arc<[String]>, ) -> Self { Self { loader, anchor, parent_group, + extension_groups, instances: Default::default(), } } @@ -119,10 +122,11 @@ impl SessionLoader { .lock() .unwrap() .insert(instance.instance_id, created.view); - if let Some((row, state)) = created - .report - .iter() - .find(|(_, state)| !matches!(state, rutis_loader::edit::InstanceResult::Active)) + if self.extension_groups.contains(&group) + && let Some((row, state)) = created + .report + .iter() + .find(|(_, state)| !matches!(state, rutis_loader::edit::InstanceResult::Active)) { self.remove(instance).await?; return Err(SessionInstanceError::NotReady(format!("{row}: {state:?}"))); diff --git a/crates/dim-app-server/src/mcp/publication.rs b/crates/dim-app-server/src/mcp/publication.rs index 49a952c0ae..f344bbedb9 100644 --- a/crates/dim-app-server/src/mcp/publication.rs +++ b/crates/dim-app-server/src/mcp/publication.rs @@ -44,7 +44,12 @@ pub struct McpOwner { } impl McpOwner { pub fn new(ctx: Ctx, loader: Loader) -> Self { - let loader = Arc::new(SessionLoader::new(loader, ctx.clone(), None)); + let loader = Arc::new(SessionLoader::new( + loader, + ctx.clone(), + None, + [GROUP.to_owned()].into(), + )); Self { id: uuid::Uuid::new_v4().to_string(), closed: ctx.cancellation_token(), diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 68117a01d4..3d36fd9d6d 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -17,7 +17,7 @@ | Caller → owner | New API | | --- | --- | | Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | -| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | +| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Registered Session extension definitions must activate their instance rows. Host-added optional groups retain their optional rows. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | | Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | | Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | | History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | diff --git a/tests/integration/tests/extensions.rs b/tests/integration/tests/extensions.rs index 26e7f483fd..c2543e290f 100644 --- a/tests/integration/tests/extensions.rs +++ b/tests/integration/tests/extensions.rs @@ -1516,7 +1516,11 @@ impl DynPlugin for LateNestedInstances { self.entered.notify_one(); self.release.notified().await; loader - .create_instance("late-nested") + .create(dim_agent_runtime::SessionInstanceDefinition { + group: "late-nested".into(), + definition_id: "late-nested".into(), + instance_data: serde_json::Value::Null, + }) .await .map_err(|error| { rutis::Error::from(rutis::host::ErrorKind::PluginFailed( From 21f137ad447074a634d00d3a950e7e41664b26d2 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:04:29 +0800 Subject: [PATCH 09/12] Verify foreign opening work settles when a sibling receipt refuses --- .../tests/transport_flow/branch_typescript.rs | 5 +++- runtime/fixtures/branch-opening.ts | 23 ++++++++++++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 149e924c0c..87e03c56cb 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -558,11 +558,12 @@ async fn node_branch_typescript_writes_and_follows_extension_events() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "requires DIM_TEST_NODE and DIM_TEST_JS_RUNTIME"] async fn node_branch_opening_completion_can_refuse_session_creation() { + let receipt = std::env::temp_dir().join(format!("dim-opening-{}", uuid::Uuid::new_v4())); let mut parts = branch_part(); parts.rows = vec![json!({ "id": "opening-receipt", "name": parts.anchor.parent().unwrap().join("fixtures/branch-opening.ts"), - "provides": {}, + "provides": {}, "config":{"receipt":receipt}, })]; let (server, agent) = launch_with( Arc::new(MockTools), @@ -584,6 +585,8 @@ async fn node_branch_opening_completion_can_refuse_session_creation() { error.to_string().contains("opening completion refused"), "{error}" ); + assert_eq!(std::fs::read_to_string(&receipt).unwrap(), "settled"); + std::fs::remove_file(receipt).unwrap(); server.shutdown(); server.join().await.unwrap(); } diff --git a/runtime/fixtures/branch-opening.ts b/runtime/fixtures/branch-opening.ts index df29da09dc..0723eaf094 100644 --- a/runtime/fixtures/branch-opening.ts +++ b/runtime/fixtures/branch-opening.ts @@ -1,12 +1,29 @@ +import { writeFile } from 'node:fs/promises' import { definePlugin } from '@arcships/rutis' import type { BranchLifecycle } from '../../npm/plugin.js' import { partRow } from './part-row.ts' -const opening = definePlugin({ +const opening = definePlugin<{ receipt: string }>({ name: 'OpeningReceiptFixture', inject: ['branchLifecycle'], - async apply(ctx) { - await ctx.use('branchLifecycle').registerOpening(async () => { + async apply(ctx, config) { + const lifecycle = ctx.use('branchLifecycle') + let start!: () => void + const started = new Promise(resolve => { start = resolve }) + let stop!: () => void + const stopped = new Promise(resolve => { stop = resolve }) + let pending: Promise | undefined + ctx.effect(async () => { + stop() + await pending + }) + await lifecycle.registerOpening(() => { + pending = stopped.then(() => writeFile(config.receipt, 'settled')) + start() + return pending + }) + await lifecycle.registerOpening(async () => { + await started throw new Error('opening completion refused') }) }, From ba79ec4ad3fd268ae9748c01d48d7af5a9dc9d89 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:08:49 +0800 Subject: [PATCH 10/12] Regenerate lifecycle declarations against main --- npm/branch-services.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 6fbc040c8b..9bfdd4101f 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -880,7 +880,7 @@ export type SessionFault = | { framework: string } | { multiple: SessionFault[] } -export interface FaultQuery { +export type FaultQuery = { } /** @@ -1019,13 +1019,13 @@ 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 } -export interface SessionInstanceDefinition { +export type SessionInstanceDefinition = { group: string definitionId: string instanceData: import('./plugin.js').BridgeJsonValue } -export interface SessionInstance { +export type SessionInstance = { instanceId: number | bigint } From 332cb346ff12cdd55da9900a8ee4461d26182ab9 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 20 Nov 2026 20:56:23 +0800 Subject: [PATCH 11/12] Clarify the Session lifecycle hold and fault operations --- docs/design/plugin-contract.md | 2 +- docs/zh/design/plugin-contract.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 035a2a33ad..1d34d18338 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -116,7 +116,7 @@ R4). This table says what each name Dim defines is for. | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | | `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | | `sessionIdentity` | `session` | SessionScope | yes | `get()`: `{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | +| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload. `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | | `sessionConfig` | `session` | SessionScope | yes | `get()`: the creation-time configuration, the snapshot a tool call carries | | `agentConfig` | `session` | SessionScope | yes | `get()`: the Agent's identity and default model | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | diff --git a/docs/zh/design/plugin-contract.md b/docs/zh/design/plugin-contract.md index 591456f797..8798193f08 100644 --- a/docs/zh/design/plugin-contract.md +++ b/docs/zh/design/plugin-contract.md @@ -105,7 +105,7 @@ process (root) process parts: storage, catalogs, connections, Ag | `collaborationMembers:` | 进程 | 成员提供者 | 已设计,未实现 | [ExternalAgent](plugins/ExternalAgent.md);实现时向 Collaboration 登记(rutis 使用 R6) | | `treeCommands` | `session` | TimelineTree | 是 | 按分支 id 的 `input`、`create`、`list`、`info` | | `sessionIdentity` | `session` | SessionScope | 是 | `get()`:`{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | 是 | `activated`、`closing`、`hold`、`release`:hold 是调用方的行拥有的 id,由 `release(id)` 或该行卸载结束 `reportFault` 上报故障,`failure` 读取当前故障,`observeFault` 订阅。调用 `release(id)` 或卸载该行会结束订阅。 | +| `sessionLifecycle` | `session` | SessionScope | 是 | `activated`、`closing`、`hold`、`release`:hold 是调用方的行拥有的 id,由 `release(id)` 或该行卸载结束。`reportFault` 上报故障,`failure` 读取当前故障,`observeFault` 订阅。调用 `release(id)` 或卸载该行会结束订阅。 | | `sessionConfig` | `session` | SessionScope | 是 | `get()`:创建时的配置,即工具调用携带的快照 | | `agentConfig` | `session` | SessionScope | 是 | `get()`:Agent 的身份与默认模型 | | `timeline` | `branch` | BranchScope | 是,`before` 除外 | `append`、已发布序号与事件查询(§5.4);查询随其声明到达其他语言 | From a1fad30101d442e0ce10d8f2fe855728ecf2ca0b Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 21 Nov 2026 23:19:21 +0800 Subject: [PATCH 12/12] Regenerate session lifecycle service declarations --- npm/branch-services.d.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index 9bfdd4101f..ecc3766d96 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -853,14 +853,19 @@ export interface BranchLifecycle { } /** - * Why the tree refused an operation on a line, named the way the protocol's - * `appError` names it ([timeline branches §14](../../../docs/design/timeline-branches.md#14-clients)). + * Why the tree refused an operation on a line, named the way the protocol + * names it: the codes `session.branch_set_default` answers as its `appError` + * and the codes the branch tool answers as its own result + * ([timeline branches §11](../../../docs/design/timeline-branches.md#11-the-branch-tool), + * [§14](../../../docs/design/timeline-branches.md#14-clients)). */ export type BranchRefusal = | /** The target is already the Session's default branch. */ "already_default" | /** The target cannot be the default branch: a plugin line, or a line a client opened before `FORMAT` 53. */ "not_selectable" | /** The target or an ancestor of it is ending or ended, so an end already on its way to it wins. */ "protected" | /** The target cannot end: the current default branch, or an ancestor of the default branch. The root's own refusal is the operation's input error, which its callers already answer. */ "cannot_end" + | /** The caller may not open a line: only the root, and the current default branch, open one. */ "not_opener" + | /** The Session holds its limit of open tool lines, counting the admitted reservations. */ "limit_reached" /** A failure reported to a Session. Framework failures carry their diagnostic text. */ export type SessionFault =