diff --git a/crates/dim-agent-capabilities/src/agent_loop/read.rs b/crates/dim-agent-capabilities/src/agent_loop/read.rs index 4c1d68c284..639951d2b4 100644 --- a/crates/dim-agent-capabilities/src/agent_loop/read.rs +++ b/crates/dim-agent-capabilities/src/agent_loop/read.rs @@ -1,6 +1,6 @@ use crate::{ methods::{Interruption, MethodDecl, RpcError, SessionMethods, params}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::*; use rutis::host::{BoxFuture, CtxHost, DynPlugin, Effect, Key, TypeKey}; @@ -20,7 +20,7 @@ struct Params { } pub struct LoopMethodsPlugin { - tree: Key, + tree: Key, methods: Key, } impl LoopMethodsPlugin { diff --git a/crates/dim-agent-capabilities/src/context_methods.rs b/crates/dim-agent-capabilities/src/context_methods.rs index cd08041e60..a67ce8f41a 100644 --- a/crates/dim-agent-capabilities/src/context_methods.rs +++ b/crates/dim-agent-capabilities/src/context_methods.rs @@ -3,7 +3,7 @@ use crate::{ context_preparation::{ContextOpError, ContextPreparation}, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, - timeline_tree::TreeCommands, + timeline_tree::{BranchCall, BranchOperation, TimelineTree}, }; use dim_agent_runtime::{ Branch, Names, QueryFilter, QueryOperand, QueryOutput, QueryPage, QuerySelect, QuerySpec, @@ -19,7 +19,7 @@ use tokio_util::sync::CancellationToken; pub const NAMESPACE: &str = "session.context"; pub struct ContextMethodsPlugin { - tree: Key, + tree: Key, methods: Key, } impl ContextMethodsPlugin { @@ -62,11 +62,19 @@ impl DynPlugin for ContextMethodsPlugin { branch_id: String, } let Params { branch_id } = params(value)?; - let branch = tree.get(&branch_id)?; - match method.as_str() { - "session.context.compact" => compact(&branch, &cancel).await, - _ => usage(&branch, cancel).await, - } + let operation = if method == "session.context.compact" { + BranchOperation::CompactAndWait + } else { + BranchOperation::ContextUsage + }; + tree.call_branch( + BranchCall { + branch_id, + operation, + }, + cancel, + ) + .await }) }), )?; @@ -76,7 +84,10 @@ impl DynPlugin for ContextMethodsPlugin { } /// Writes `context/compact`, or joins the outstanding command, and waits for /// the result that carries that command. -async fn compact(branch: &Branch, cancel: &CancellationToken) -> Result { +pub(crate) async fn compact( + branch: &Branch, + cancel: &CancellationToken, +) -> Result { let command = branch .service::()? .compact()?; @@ -191,24 +202,31 @@ async fn compact(branch: &Branch, cancel: &CancellationToken) -> Result Result { - match branch.service::()?.usage(cancel).await { - Ok(usage) => reply(usage), - Err(ContextOpError::NotReady) => Err(RpcError::app( - -32000, - "context_usage_unavailable", - ContextOpError::NotReady.to_string(), - )), - Err(ContextOpError::NotConfigured) => Err(RpcError::app( - -32000, - "context_not_configured", - ContextOpError::NotConfigured.to_string(), - )), - Err(ContextOpError::Model(error)) => Err(RpcError::app( - -32000, - "context_model_failed", - error.to_string(), - )), - Err(ContextOpError::Read(error)) => Err(error.into()), +impl TimelineTree { + pub(crate) async fn context_usage( + &self, + branch_id: &str, + cancel: CancellationToken, + ) -> Result { + let branch = self.get(branch_id)?; + match branch.service::()?.usage(cancel).await { + Ok(usage) => Ok(usage), + Err(ContextOpError::NotReady) => Err(RpcError::app( + -32000, + "context_usage_unavailable", + ContextOpError::NotReady.to_string(), + )), + Err(ContextOpError::NotConfigured) => Err(RpcError::app( + -32000, + "context_not_configured", + ContextOpError::NotConfigured.to_string(), + )), + Err(ContextOpError::Model(error)) => Err(RpcError::app( + -32000, + "context_model_failed", + error.to_string(), + )), + Err(ContextOpError::Read(error)) => Err(error.into()), + } } } diff --git a/crates/dim-agent-capabilities/src/input_queue.rs b/crates/dim-agent-capabilities/src/input_queue.rs index 9d6aa61e0a..808d113679 100644 --- a/crates/dim-agent-capabilities/src/input_queue.rs +++ b/crates/dim-agent-capabilities/src/input_queue.rs @@ -4,7 +4,7 @@ mod recovery; use crate::{ host::HostFuture, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::{ AgentError, Dispatcher, InputSnapshot, Names, Registrations, Result, StateCell, Timeline, @@ -207,7 +207,7 @@ pub struct InputQueue { observable: Arc>, pending_snapshot: Mutex>, timeline: Arc, - tree: Arc, + tree: Arc, branch_id: String, /// Answers to `input/withdraw` commands by their sequence, until the /// withdrawal that wrote each one collects it. @@ -232,7 +232,7 @@ impl Drop for WithdrawalWaiter<'_> { impl InputQueue { /// Commits an input through the branch entry, accepting each submission id once. pub async fn submit(&self, input: InputMessageData) -> Result { - let event = self.tree.get(&self.branch_id)?.input(input).await?; + let event = self.tree.input(self.branch_id.clone(), input).await?; Ok(InputRef { input_id: event.id.clone(), sequence: event.sequence, @@ -365,7 +365,7 @@ pub struct InputQueuePlugin { queue: Key, timeline: Key, dispatcher: Key, - tree: Key, + tree: Key, identity: Key, } impl InputQueuePlugin { @@ -642,10 +642,42 @@ struct WithdrawParams { steer: Option, } +impl TimelineTree { + async fn withdraw_checked( + &self, + branch_id: &str, + command: impl Future> + Send, + cancel: &CancellationToken, + ) -> std::result::Result { + let branch = self.get(branch_id)?; + let queue = branch.service::()?; + let answer = queue.withdraw_checked(command.await?).await?; + if let (Withdrawal::Deleted { sequence }, Some(_)) = &answer { + let publication = branch.publication(); + let mut progress = publication.watch(); + tokio::select! { + _ = progress.wait_for( + |&(published, closed)| published >= *sequence || closed, + ) => {} + _ = cancel.cancelled() => + return Err(RpcError::interrupted()), + } + if publication.sequence() < *sequence { + return Err(RpcError::app( + -32000, + "publication_unknown", + "committed, but publication was not confirmed; query history after recovery", + )); + } + } + Ok(answer) + } +} + /// Serves `session.input.withdraw` for every branch of its Session through /// the branch's InputQueue, so Rpc names no owning service. pub struct InputMethodsPlugin { - tree: Key, + tree: Key, methods: Key, checks: Key, } @@ -687,14 +719,13 @@ impl DynPlugin for InputMethodsPlugin { return pending::read(&tree, value, &cancel).await; } let p: WithdrawParams = params(value)?; - let branch = tree.get(&p.branch_id)?; - let queue = branch.service::()?; + let mut checks_warnings = Vec::new(); + let command = async { let mut steer = p.steer.map(|user| InputMessageData { user: Some(user), mode: Some(InputMode::Steer), ..Default::default() }); - let mut checks_warnings = Vec::new(); if let Some(input) = &steer { // The operator's own content is validated before // the checks run: a check's context must never be @@ -734,35 +765,12 @@ impl DynPlugin for InputMethodsPlugin { } } } - let (answer, replacement) = queue - .withdraw_checked( - InputWithdrawData { - input_id: p.input_id, - reason: p.reason, - steer, - }, - ) - .await?; + Ok(InputWithdrawData {input_id:p.input_id,reason:p.reason,steer}) + }; + let (answer, replacement) = + tree.withdraw_checked(&p.branch_id, command, &cancel).await?; let mut result = match answer { Withdrawal::Deleted { sequence } => { - if replacement.is_some() { - let publication = branch.publication(); - let mut progress = publication.watch(); - tokio::select! { - _ = progress.wait_for( - |&(published, closed)| published >= sequence || closed, - ) => {} - _ = cancel.cancelled() => - return Err(RpcError::interrupted()), - } - if publication.sequence() < sequence { - return Err(RpcError::app( - -32000, - "publication_unknown", - "committed, but publication was not confirmed; query history after recovery", - )); - } - } serde_json::json!({"status": "deleted", "sequence": sequence}) } Withdrawal::NotHeld => serde_json::json!({"status": "notHeld"}), diff --git a/crates/dim-agent-capabilities/src/input_queue/pending.rs b/crates/dim-agent-capabilities/src/input_queue/pending.rs index b06cd1f4ee..6800a63d65 100644 --- a/crates/dim-agent-capabilities/src/input_queue/pending.rs +++ b/crates/dim-agent-capabilities/src/input_queue/pending.rs @@ -19,7 +19,7 @@ struct Params { } pub(super) async fn read( - tree: &TreeCommands, + tree: &TimelineTree, value: Value, cancel: &CancellationToken, ) -> std::result::Result { diff --git a/crates/dim-agent-capabilities/src/lib.rs b/crates/dim-agent-capabilities/src/lib.rs index df3e0e681d..5cb3c843ee 100644 --- a/crates/dim-agent-capabilities/src/lib.rs +++ b/crates/dim-agent-capabilities/src/lib.rs @@ -76,7 +76,6 @@ fn register_names_in(catalog: &mut dim_agent_runtime::names::ServiceCatalog) { }; let session = Some(SESSION_GROUP); register::(catalog, session); - register::(catalog, session); register::(catalog, session); catalog.register_shared_instance("toolSourcesView", SESSION_GROUP); register::(catalog, session); @@ -144,7 +143,7 @@ impl PublicService for shell_session::ShellSession {} impl PublicService for dyn exec_stop::ExecStop {} impl PublicService for workspace_tools::file_reads::FileReads {} impl PublicService for timeline_tree::BranchLine {} -impl PublicService for timeline_tree::TreeCommands {} +impl PublicService for timeline_tree::TimelineTree {} impl PublicService for wait::Wait {} impl PublicService for skills::SkillsBranch {} impl PublicService for prompt::Prompt {} diff --git a/crates/dim-agent-capabilities/src/prompt_suggestion.rs b/crates/dim-agent-capabilities/src/prompt_suggestion.rs index 5c4579326b..613734df19 100644 --- a/crates/dim-agent-capabilities/src/prompt_suggestion.rs +++ b/crates/dim-agent-capabilities/src/prompt_suggestion.rs @@ -10,7 +10,6 @@ //! The `prompt-suggestion` Settings source belongs to the App Server //! ([`PromptSuggestionSettingsHost`]); the part reads it at each decision and //! stays idle while it is off. -use crate::context_preparation::ContextPreparation; use crate::history::fold_output_parts; use crate::host::{ HostError, ModelChunk, ModelConnection, ModelHost, ModelStream, ProviderConnectionResolver, @@ -23,7 +22,7 @@ use crate::session_broadcast::{ SessionBroadcast, SessionBroadcastEvent, SessionNotice, notify, session_channel, }; use crate::settings::{SettingsChanged, settings_changes}; -use crate::timeline_tree::TreeCommands; +use crate::timeline_tree::TimelineTree; use dim_agent_runtime::{ AgentBuilder, CollaborationRole, Feature, Names, SessionConfig, SessionIdentity, SessionLifecycle, @@ -484,7 +483,7 @@ struct Hosts { model: Arc, resolver: Option>, settings: Option>, - tree: Arc, + tree: Arc, } struct PromptSuggestionPlugin { @@ -492,7 +491,7 @@ struct PromptSuggestionPlugin { config: Key, lifecycle: Key, methods: Key, - tree: Key, + tree: Key, model: Key, resolver: Option>, settings: Option>, @@ -1100,13 +1099,12 @@ impl Part { } async fn compaction_due(&self, max_chars: u32, cancel: CancellationToken) -> bool { - let Ok(branch) = self.hosts.tree.get(DEFAULT_BRANCH_ID) else { - return false; - }; - let Ok(preparation) = branch.service::() else { - return false; - }; - let Ok(usage) = preparation.usage(cancel).await else { + let Ok(usage) = self + .hosts + .tree + .context_usage(DEFAULT_BRANCH_ID, cancel) + .await + else { return false; }; compaction_due( diff --git a/crates/dim-agent-capabilities/src/recall.rs b/crates/dim-agent-capabilities/src/recall.rs index c8799430a7..6c0c13ba1a 100644 --- a/crates/dim-agent-capabilities/src/recall.rs +++ b/crates/dim-agent-capabilities/src/recall.rs @@ -12,7 +12,7 @@ use crate::{ context_policy::check_cancel, host::{HostError, HostFuture, ToolExecutionContext}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, tool_registry::{ToolConcurrency, ToolContribution, ToolHandler, ToolRegistry, definition}, }; use dim_agent_runtime::{ @@ -91,7 +91,7 @@ fn recall_definition() -> ToolDefinition { } pub struct RecallPlugin { - tree: Key, + tree: Key, tools: Key, } @@ -127,7 +127,7 @@ impl DynPlugin for RecallPlugin { } } -struct RecallTool(Arc); +struct RecallTool(Arc); impl RecallTool { async fn run( diff --git a/crates/dim-agent-capabilities/src/recall/search.rs b/crates/dim-agent-capabilities/src/recall/search.rs index 31a7803dec..069da404c8 100644 --- a/crates/dim-agent-capabilities/src/recall/search.rs +++ b/crates/dim-agent-capabilities/src/recall/search.rs @@ -677,7 +677,7 @@ fn text_candidates(words: &[String]) -> Option { } pub(super) async fn run( - tree: &TreeCommands, + tree: &TimelineTree, branch: &Branch, branch_id: &str, arguments: &Arguments, @@ -875,7 +875,7 @@ fn mark_current( } pub(super) async fn open( - tree: &TreeCommands, + tree: &TimelineTree, branch: &Branch, branch_id: &str, head: u64, @@ -1097,7 +1097,7 @@ impl Search<'_> { } pub(super) async fn index( - tree: &TreeCommands, + tree: &TimelineTree, branch: &Branch, branch_id: &str, calling_turn: &str, diff --git a/crates/dim-agent-capabilities/src/shell_input.rs b/crates/dim-agent-capabilities/src/shell_input.rs index 7a0547d011..a6bc4504f0 100644 --- a/crates/dim-agent-capabilities/src/shell_input.rs +++ b/crates/dim-agent-capabilities/src/shell_input.rs @@ -16,7 +16,7 @@ use crate::{ Interruption, MethodCall, MethodDecl, Progress, RpcError, SessionMethods, params, reply, }, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, workspace_tools::exec::{ OutputSink, bounded_preview, capture_preview, pump, sanitize, signal_name, tail_bytes, }, @@ -136,7 +136,7 @@ struct Registry { struct ShellInput { platform: Arc, cwd: PathBuf, - tree: Arc, + tree: Arc, lifecycle: Arc, identity: Arc, /// This generation's cancellation: with the Session's closing, it ends @@ -224,7 +224,11 @@ impl ShellInput { } check_run_id(&p.run_id)?; self.admit(&self.registry.lock().unwrap(), &p.run_id, &cancel)?; - self.tree.get(&p.branch_id)?; + if self.tree.directory_entry(&p.branch_id)?.state + == dim_agent_runtime::BranchDirectoryState::Ended + { + return Err(dim_agent_runtime::AgentError::BranchEnded(p.branch_id).into()); + } let built = async { #[cfg(feature = "testing")] testing::pause(&self.cwd).await; @@ -545,7 +549,7 @@ const SHELL_INPUT_ENTRY: &str = r#", + }, + #[serde(rename = "prompt.adoptedConfiguration")] + AdoptedConfiguration, + #[serde(rename = "approval.pending")] + ApprovalPending, + #[serde(rename = "approval.decide", rename_all = "camelCase")] + ApprovalDecide { + request_id: String, + decision: ApprovalDecision, + }, + #[serde(rename = "inputQueue.withdraw")] + Withdraw { command: InputWithdrawData }, +} + /// A line whose `branch/end` is committed and whose close has not completed. struct PendingEnd { /// The sequence of `branch/end` on the line: the result's `endEvent`. @@ -242,30 +318,68 @@ pub struct TimelineTree { /// its settling task. admitted: tokio::sync::Notify, } -/// Shared with Timeline roots; never owns the tree or its child roots. -pub struct TreeCommands { - tree: Weak, -} #[service] -impl TreeCommands { +impl TimelineTree { + pub async fn call( + &self, + request: BranchCall, + cancelled: Arc< + dyn Fn() -> BoxFuture<'static, std::result::Result<(), Error>> + Send + Sync, + >, + ) -> std::result::Result { + let cancel = CancellationToken::new(); + let _guard = cancel.clone().drop_guard(); + let called = self.call_branch(request, cancel.clone()); + tokio::pin!(called); + tokio::select! { + result = &mut called => result, + _ = cancelled() => { + cancel.cancel(); + called.await + } + } + .map_err(|error| { + let code = error + .data + .as_ref() + .map_or("rpc_error", |data| data.app_error.as_str()); + rutis_bridge::exports::failure( + "RpcError", + code, + error.message.clone(), + Some(serde_json::json!(error)), + ) + }) + } + + pub fn directory( + &self, + request: DirectoryRequest, + ) -> std::result::Result { + match request.id { + Some(id) => self.directory_entry(&id).map(DirectoryReply::One), + None => Ok(DirectoryReply::All(TimelineTreeControl::directory(self))), + } + } + + pub async fn display( + &self, + id: String, + ) -> std::result::Result { + self.display_line(id).await + } + #[service(skip)] pub fn get(&self, id: &str) -> Result { - let tree = self - .tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))?; - if tree.ended_head(id).is_some() { + if self.ended_head(id).is_some() { return Err(AgentError::BranchEnded(id.into())); } - tree.owned_context(id) + self.owned_context(id) .map(|context| context.branch()) .ok_or_else(|| AgentError::UnknownBranch(id.into())) } pub fn list(&self) -> Vec { - self.tree - .upgrade() - .map(|tree| tree.list()) - .unwrap_or_default() + TimelineTreeControl::list(self) } #[service(skip)] pub async fn branch( @@ -275,10 +389,7 @@ impl TreeCommands { options: BranchOptions, admission: CancellationToken, ) -> Result { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .create_child(parent, at, options, admission, None) + self.create_child(parent, at, options, admission, None) .await } /// Opens a line for the `branch` tool: the caller's eligibility and the @@ -292,10 +403,7 @@ impl TreeCommands { admission: CancellationToken, open: ToolOpen, ) -> Result { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .create_child(parent, at, options, admission, Some(open)) + self.create_child(parent, at, options, admission, Some(open)) .await } // The data methods below spell out `std::result::Result` for rutis' @@ -304,11 +412,7 @@ impl TreeCommands { /// The directory record of branch `id`, from its reservation on, so a /// part that loads with its own line reads it during its replay. pub fn info(&self, id: String) -> std::result::Result { - let tree = self - .tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))?; - tree.info(&id).ok_or(AgentError::UnknownBranch(id)) + self.line_info(&id).ok_or(AgentError::UnknownBranch(id)) } /// Commits `input` to branch `id` through its validating `Branch::input` /// and returns the committed event, or the input already committed with @@ -322,8 +426,7 @@ impl TreeCommands { } /// Commits `inputs` to branch `id` as one atomic batch through its /// validating `Branch::inputs`: the given order, contiguous sequences and - /// one publication. Rust only: no other language has a consumer. - #[service(skip)] + /// one publication. pub async fn inputs( &self, id: String, @@ -337,36 +440,24 @@ impl TreeCommands { id: String, source: BranchSource, ) -> std::result::Result<(), AgentError> { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .end(&id, source) - .await + self.end_line(&id, source).await } /// Ends the line `id` with a tool end's `final_message` riding on its /// `branch/end`, which the parent receives once the end is admitted - /// (design §10). Rust only: the `branch` tool is its one caller. - #[service(skip)] + /// (design §10). pub async fn end_with_final( &self, id: String, source: BranchSource, final_message: Option, ) -> std::result::Result<(), AgentError> { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .end_with_final(&id, source, final_message) - .await + self.settle_end(&id, source, final_message).await } /// The line the Session's conversation is on: the root until a /// `branch/default` moves it, then that fact's line while it is open and /// selectable (design §4, §5, §20.20). pub fn default_branch(&self) -> Result { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into())) - .map(|tree| tree.state.lock().unwrap().default.clone()) + TimelineTreeControl::default_branch(self) } /// Moves the default branch to `id` and answers it. The target must be an /// open conversation line that is not already the default branch, and @@ -374,11 +465,7 @@ impl TreeCommands { /// writes `branch/default` on the root and one status note to each /// participant that is not the root (design §4, §10, §14). pub async fn set_default_branch(&self, id: String, source: BranchSource) -> Result { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .set_default_branch(&id, source) - .await + self.move_default(&id, source).await } /// One page of `id`'s committed batches up to `through`; an ended line /// reads at its fixed head and `through` must end an atomic batch. @@ -389,45 +476,37 @@ impl TreeCommands { limit: usize, through: u64, ) -> std::result::Result>, AgentError> { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .page(&id, after, limit, through) - .await + self.read_page(&id, after, limit, through).await } /// Ends a raw-event page on an atomic batch boundary without reading its payloads. - #[service(skip)] pub async fn page_end( &self, - id: &str, + id: String, after: u64, limit: std::num::NonZeroU64, through: u64, ) -> Result { - let tree = self - .tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))?; - let head = tree + let id = id.as_str(); + let head = self .head(id) .ok_or_else(|| AgentError::UnknownBranch(id.into()))?; if after > through || through > head { return Err(AgentError::InvalidInput("future Timeline cursor".into())); } let target = after.saturating_add(limit.get()).min(through); - if let Some(context) = tree.owned_context(id) { + if let Some(context) = self.owned_context(id) { let timeline = context.timeline(); timeline.batch_end(after).await?; timeline.batch_end(through).await?; timeline.batch_end_at(target).await } else { let key = TimelineKey { - session_id: tree.session_id.clone(), + session_id: self.session_id.clone(), branch_id: id.into(), }; - tree.store.batch_end(&key, after).await?; - tree.store.batch_end(&key, through).await?; - tree.store.batch_end_at(&key, target).await + self.store.batch_end(&key, after).await?; + self.store.batch_end(&key, through).await?; + self.store.batch_end_at(&key, target).await } } /// Computes properties at a fixed cutoff. Chain scope reads only published @@ -438,79 +517,30 @@ impl TreeCommands { id: String, query: dim_agent_runtime::TimelineQuery, ) -> std::result::Result { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .query(&id, query) - .await - } - /// The head a read of `id` ends at: fixed once ended, published while - /// open. - #[service(skip)] - fn head(&self, id: &str) -> Option { - self.tree.upgrade()?.head(id) + self.query_line(&id, query).await } /// Checks that `sequence` ends an atomic batch of line `id`, forwarding to - /// its Timeline while open and reading the store once it ends. The check - /// stays out of the service surface because no other language reads batch - /// structure. - #[service(skip)] + /// its Timeline while open and reading the store once it ends. pub async fn batch_end( &self, id: String, sequence: u64, ) -> std::result::Result<(), AgentError> { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .batch_end(&id, sequence) - .await + self.check_batch_end(&id, sequence).await } /// The line the latest `branch/default` moved from, `None` when the root /// held the role or no move was recorded. Rust only: the status note's /// reconciling load is its one reader (design §5). #[service(skip)] pub fn default_from(&self) -> Option { - self.tree - .upgrade() - .and_then(|tree| tree.state.lock().unwrap().default_from.clone()) + self.state.lock().unwrap().default_from.clone() } /// A signal that changes after each move; it wakes a line's writer, which /// reads the transitions the tree owes it from its own queue, not from this /// value (design §5). #[service(skip)] fn default_moves(&self) -> watch::Receiver { - self.tree - .upgrade() - .map(|tree| tree.default_moved.subscribe()) - .unwrap_or_else(|| watch::channel(0).1) - } - /// The oldest move `id` owes a status note for, in commit order; this call - /// takes it off the line's queue (design §5, §20.21). - #[service(skip)] - fn next_move(&self, id: &str) -> Option { - self.tree.upgrade()?.next_move(id) - } - /// A signal that changes when line `id` ends a turn; it carries that - /// `turn/end`'s sequence. - #[service(skip)] - fn turn_ends(&self, id: &str) -> Option> { - self.tree.upgrade()?.turn_ends(id) - } - /// Whether line `id` did anything after `from` that a line it opened must - /// see: an operator input, or a tool call. - #[service(skip)] - async fn activity_after( - &self, - id: &str, - from: u64, - through: u64, - ) -> std::result::Result { - self.tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))? - .activity_after(id, from, through) - .await + self.default_moved.subscribe() } /// Creates a child of `parent` cut at `at` and returns its id. /// `cancelled` is the caller's cancellation as an explicit argument, the @@ -547,6 +577,145 @@ impl TreeCommands { Ok(created?.id().to_owned()) } } +impl TimelineTree { + /// Selects the branch now. Polling the returned operation configures that + /// instance even when the caller first has to persist Session state. + pub fn configure_prompt( + &self, + branch_id: &str, + request: crate::prompt::PromptConfigurationRequest, + ) -> Result> + Send + 'static> + { + let branch = self.get(branch_id)?; + Ok(async move { + branch + .admitted_service::()? + .configure(request) + .await + }) + } + + /// Binds a configuration write to its branch before the caller prepares + /// the model. The Prompt owner is read when the prepared write runs. + pub fn prepare_prompt_write( + &self, + branch_id: &str, + ) -> Result< + impl FnOnce( + crate::prompt::PromptConfigurationRequest, + ) -> BoxFuture<'static, Result> + + use<>, + > { + let branch = self.get(branch_id)?; + Ok( + move |request| -> BoxFuture<'static, Result> { + Box::pin(async move { + branch + .service::()? + .configure(request) + .await + }) + }, + ) + } + + /// The native result of the selected branch's `prompt.adoptedConfiguration` operation. + pub fn adopted_configuration(&self, branch_id: &str) -> Result> { + Ok(self + .get(branch_id)? + .service::()? + .adopted_configuration(Default::default())) + } + + pub fn pending_approvals(&self, branch_id: &str) -> Result> { + let branch = self.get(branch_id)?; + if branch.is_closing() { + return Err(AgentError::Closed(branch_id.into())); + } + Ok(branch.service::()?.pending()) + } + + pub fn decide_approval( + &self, + branch_id: &str, + request_id: String, + decision: ApprovalDecision, + ) -> Result< + impl Future> + + Send + + 'static + + use<>, + > { + let approval = self + .get(branch_id)? + .service::()?; + Ok(async move { approval.decide(request_id, decision).await }) + } + + pub fn withdraw( + &self, + branch_id: &str, + command: InputWithdrawData, + ) -> Result> + Send + 'static + use<>> { + let queue = self + .get(branch_id)? + .service::()?; + Ok(async move { queue.withdraw(command).await }) + } + + pub(crate) async fn call_branch( + &self, + request: BranchCall, + cancel: CancellationToken, + ) -> std::result::Result { + let branch_id = &request.branch_id; + match request.operation { + BranchOperation::ContextUsage => { + crate::methods::reply(self.context_usage(branch_id, cancel).await?) + } + BranchOperation::CompactAndWait => { + crate::context_methods::compact(&self.get(branch_id)?, &cancel).await + } + BranchOperation::ConfigurePrompt { request } => { + let configure = self.configure_prompt(branch_id, *request)?; + let outcome = tokio::select! { + result = configure => result?, + _ = cancel.cancelled() => return Err(crate::methods::RpcError::interrupted()), + }; + crate::methods::reply(outcome) + } + BranchOperation::AdoptedConfiguration => { + crate::methods::reply(self.adopted_configuration(branch_id)?) + } + BranchOperation::ApprovalDecide { + request_id, + decision, + } => { + self.decide_approval(branch_id, request_id, decision)? + .await + .map_err(|error| { + use crate::approval::ApprovalRespondError; + let code = match error { + ApprovalRespondError::Unknown => "Unknown", + ApprovalRespondError::Cancelled => "Cancelled", + ApprovalRespondError::Closed => "Closed", + }; + crate::methods::RpcError::service(code, error.to_string()) + })?; + Ok(serde_json::Value::Null) + } + BranchOperation::Withdraw { command } => { + crate::methods::reply(self.withdraw(branch_id, command)?.await.map_err( + |error| crate::methods::RpcError::service(error.variant(), error.to_string()), + )?) + } + BranchOperation::ApprovalPending => { + crate::methods::reply(self.pending_approvals(branch_id)?) + } + } + } +} + /// One page of an open line's own facts after `after`, at most `limit`, never /// past `through`, ending on an atomic batch: a page that reaches its limit /// inside one runs to that batch's end, so an open and an ended line's pages @@ -1176,7 +1345,7 @@ impl TimelineTree { /// One page of `id`'s committed batches, never past `through`: an ended /// line reads at its fixed head. `through` must end an atomic batch, as it /// does for a live line's read, so a page cannot be cut inside one. - async fn page( + async fn read_page( &self, id: &str, after: u64, @@ -1210,7 +1379,7 @@ impl TimelineTree { .map(|record| record.event) .collect()) } - async fn query( + async fn query_line( &self, id: &str, query: TimelineQuery, @@ -1289,7 +1458,7 @@ impl TimelineTree { } /// The batch-end check of one line, forwarding to its Timeline while open /// and reading the store at the tree's key after it ends. - async fn batch_end(&self, id: &str, sequence: u64) -> Result<()> { + async fn check_batch_end(&self, id: &str, sequence: u64) -> Result<()> { if let Some(context) = self.owned_context(id) { return context.timeline().batch_end(sequence).await; } @@ -1370,7 +1539,7 @@ impl TimelineTree { // (design §7.1.1), so only the roster's key can be live there. let skip_root = key == parent_key(); for (line, through) in chain.into_iter().rev() { - if self.info(&line).is_none() || (skip_root && line == ROOT_BRANCH_ID) { + if self.line_info(&line).is_none() || (skip_root && line == ROOT_BRANCH_ID) { continue; } let scope = self.stored_scope(&line, 1, through); @@ -1609,7 +1778,17 @@ impl TimelineTree { } /// A line's directory record, published or still opening; absent once a /// failed creation removed it. - fn info(&self, id: &str) -> Option { + pub fn directory_entry(&self, id: &str) -> Result { + let state = self.state.lock().unwrap(); + state + .nodes + .get(id) + .and_then(Node::directory_entry) + .or_else(|| state.ended.get(id).map(EndedLine::directory_entry)) + .ok_or_else(|| AgentError::UnknownBranch(id.into())) + } + + fn line_info(&self, id: &str) -> Option { let state = self.state.lock().unwrap(); state .nodes @@ -1617,15 +1796,15 @@ impl TimelineTree { .map(|node| node.info.clone()) .or_else(|| state.ended.get(id).map(|ended| ended.info.clone())) } - async fn end(&self, id: &str, source: BranchSource) -> Result<()> { - self.end_with_final(id, source, None).await + async fn end_line(&self, id: &str, source: BranchSource) -> Result<()> { + self.settle_end(id, source, None).await } /// Ends `id` with `final_message` riding on `branch/end` when it is a tool /// end, and waits for the close. The guard, the command and the message are /// one operation: a refused end writes neither, so a line the user has just /// made the default branch never tells its parent it ended (design §10, /// §20.26a). - async fn end_with_final( + async fn settle_end( &self, id: &str, source: BranchSource, @@ -1823,7 +2002,7 @@ impl TimelineTree { /// that fails answers its error and changes nothing. Once the write is /// admitted the tree settles it, so a caller that goes away after that /// point does not leave the fact unapplied. - async fn set_default_branch(&self, id: &str, source: BranchSource) -> Result { + async fn move_default(&self, id: &str, source: BranchSource) -> Result { let operations = self.operations.clone().lock_owned().await; let owner = self .weak @@ -2888,7 +3067,7 @@ impl TimelineTreeControl for TimelineTree { }) } fn end(&self, id: String, source: BranchSource) -> BoxFuture<'_, Result<()>> { - Box::pin(async move { TimelineTree::end(self, &id, source).await }) + Box::pin(async move { TimelineTree::end_line(self, &id, source).await }) } fn default_branch(&self) -> Result { Ok(self.state.lock().unwrap().default.clone()) @@ -2898,7 +3077,7 @@ impl TimelineTreeControl for TimelineTree { id: String, source: BranchSource, ) -> BoxFuture<'_, Result> { - Box::pin(async move { TimelineTree::set_default_branch(self, &id, source).await }) + Box::pin(async move { TimelineTree::move_default(self, &id, source).await }) } fn ended_head(&self, id: &str) -> Option { TimelineTree::ended_head(self, id) @@ -2914,45 +3093,15 @@ impl TimelineTreeControl for TimelineTree { .collect() } fn directory(&self) -> Vec { - // Collect the records under the lock, then resolve heads through - // `head()`, which takes the lock itself. - let mut entries: Vec = { + let mut entries = { let state = self.state.lock().unwrap(); - let mut entries: Vec = state + state .nodes .values() - .filter(|node| matches!(&*node.ready.borrow(), Some(Ok(_)))) - .map(|node| { - let end_event = node - .context - .as_ref() - .and_then(|context| context.end_event()); - BranchDirectoryEntry { - info: node.info.clone(), - head: 0, - state: match end_event { - Some(_) => BranchDirectoryState::Ending, - None => BranchDirectoryState::Open, - }, - end_event, - } - }) - .collect(); - for ended in state.ended.values() { - entries.push(BranchDirectoryEntry { - info: ended.info.clone(), - head: ended.head, - state: BranchDirectoryState::Ended, - end_event: ended.end_event, - }); - } - entries + .filter_map(Node::directory_entry) + .chain(state.ended.values().map(EndedLine::directory_entry)) + .collect::>() }; - for entry in &mut entries { - if entry.state != BranchDirectoryState::Ended { - entry.head = self.head(&entry.info.id).unwrap_or(0); - } - } entries.sort_by(|a, b| { let order = |id: &str| id != ROOT_BRANCH_ID; (order(&a.info.id), &a.info.id).cmp(&(order(&b.info.id), &b.info.id)) @@ -2985,7 +3134,7 @@ impl TimelineTreeControl for TimelineTree { pub struct TreeTimelinePlugin { timeline: Key, dispatcher: Key, - commands: Key, + commands: Key, identity: Key, } impl TreeTimelinePlugin { @@ -3016,10 +3165,11 @@ impl DynPlugin for TreeTimelinePlugin { let dispatcher = ctx.require_at(&self.dispatcher)?; let commands = ctx.require_at(&self.commands)?; let identity = ctx.require_at(&self.identity)?; + let commands = Arc::downgrade(&commands); let cleanup = commands.clone(); let parent = identity.branch_id.clone(); ctx.effect(move || async move { - if let Some(tree) = cleanup.tree.upgrade() { + if let Some(tree) = cleanup.upgrade() { let cancelled = TimelineTree::cancel_pending( &mut tree.state.lock().unwrap(), Some(&parent), @@ -3036,17 +3186,14 @@ impl DynPlugin for TreeTimelinePlugin { let branch = &identity.branch_id; let result = match &event.kind { EventKind::BranchCreate(_) => commands - .tree .upgrade() .ok_or_else(|| AgentError::Closed("TimelineTree".into())) .and_then(|tree| tree.on_create(branch, &timeline, &event)), EventKind::BranchEnd(data) => commands - .tree .upgrade() .ok_or_else(|| AgentError::Closed("TimelineTree".into())) .map(|tree| tree.on_end(branch, event.sequence, data.clone())), EventKind::TurnEnd(_) => commands - .tree .upgrade() .ok_or_else(|| AgentError::Closed("TimelineTree".into())) .map(|tree| tree.on_turn_end(branch, event.sequence)), @@ -3060,7 +3207,6 @@ impl DynPlugin for TreeTimelinePlugin { } } pub struct TimelineTreePlugin { - commands: Key, tree: Key, control: Key, factory: Key, @@ -3070,11 +3216,11 @@ pub struct TimelineTreePlugin { } impl TimelineTreePlugin { pub fn new(names: &Names<'_>) -> rutis::Result { + let session = names.instance(dim_agent_runtime::SESSION_GROUP)?; Ok(Self { - commands: names.key()?, tree: names.key()?, - control: names.key()?, - factory: names.key()?, + control: Key::of().instance(session), + factory: Key::of().instance(session), store: names.key()?, identity: names.key()?, guide: names.key()?, @@ -3120,10 +3266,6 @@ impl DynPlugin for TimelineTreePlugin { let tree = TimelineTree::new(factory, store, identity.session_id.clone()); let owner = tree.clone(); ctx.effect(move || async move { owner.close().await.map_err(Into::into) })?; - let commands = Arc::new(TreeCommands { - tree: Arc::downgrade(&tree), - }); - ctx.provide_at(self.commands.clone(), commands)?; ctx.provide_at(self.tree.clone(), tree.clone())?; ctx.provide_at(self.control.clone(), tree as Arc)?; Ok(Effect::Done) @@ -3133,7 +3275,7 @@ impl DynPlugin for TimelineTreePlugin { /// Session part: registers the `branch` tool, which forks the calling /// branch through the tree. pub struct BranchToolPlugin { - tree: Key, + tree: Key, tools: Key, config: BranchToolConfig, } @@ -3367,7 +3509,7 @@ pub struct BranchLinePlugin { identity: Key, lifecycle: Key, session: Key, - tree: Key, + tree: Key, guide: Key, config: BranchToolConfig, } @@ -3512,7 +3654,7 @@ impl DynPlugin for BranchLinePlugin { } pub struct BranchLine { own: String, - tree: Arc, + tree: Arc, /// The line's own Timeline, which a load writes through before the tree /// has registered the line. timeline: Arc, @@ -4862,7 +5004,7 @@ fn first_line(purpose: &str) -> String { } struct BranchTool { - tree: Arc, + tree: Arc, /// The Session's cap on open tool lines (§6.1). max_open_lines: usize, } @@ -5201,7 +5343,7 @@ impl BranchTool { let next = self .tree .page_end( - &target.id, + target.id.clone(), after, NonZeroU64::new(limit as u64).unwrap(), head, @@ -5357,7 +5499,7 @@ enum LineRead { } async fn line_read_items( - tree: &TreeCommands, + tree: &TimelineTree, branch: &str, after: u64, through: u64, diff --git a/crates/dim-agent-capabilities/src/timeline_tree/read.rs b/crates/dim-agent-capabilities/src/timeline_tree/read.rs index 1f62f9f8d3..bf9762e5b9 100644 --- a/crates/dim-agent-capabilities/src/timeline_tree/read.rs +++ b/crates/dim-agent-capabilities/src/timeline_tree/read.rs @@ -1,25 +1,22 @@ use super::*; +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] pub struct DirectoryDisplay { pub entry: BranchDirectoryEntry, + #[serde(skip_serializing_if = "Option::is_none")] pub purpose: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub cut_messages: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub end: Option, } -impl TreeCommands { +impl TimelineTree { /// Reads one branch's creation purpose/source and end detail. /// Unknown branches and failed history reads return errors. - pub async fn display(&self, id: String) -> Result { - let tree = self - .tree - .upgrade() - .ok_or_else(|| AgentError::Closed("TimelineTree".into()))?; - let mut entry = tree - .directory() - .into_iter() - .find(|entry| entry.info.id == id) - .ok_or(AgentError::UnknownBranch(id))?; + pub(super) async fn display_line(&self, id: String) -> Result { + let mut entry = self.directory_entry(&id)?; let mut purpose = None; if let (Some(parent), Some(anchor)) = (&entry.info.parent, entry.info.create_anchor) { let point = self diff --git a/crates/dim-agent-capabilities/src/tool_executor/read.rs b/crates/dim-agent-capabilities/src/tool_executor/read.rs index dfc8884658..ba02d17a62 100644 --- a/crates/dim-agent-capabilities/src/tool_executor/read.rs +++ b/crates/dim-agent-capabilities/src/tool_executor/read.rs @@ -1,6 +1,6 @@ use crate::{ methods::{Interruption, MethodDecl, RpcError, SessionMethods, params}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::*; use dim_agent_types::{ToolRead, ToolUseData}; @@ -20,7 +20,7 @@ struct Params { } pub struct ToolMethodsPlugin { - tree: Key, + tree: Key, methods: Key, } impl ToolMethodsPlugin { diff --git a/crates/dim-agent-capabilities/src/wait.rs b/crates/dim-agent-capabilities/src/wait.rs index 95ad74cf54..65385826a5 100644 --- a/crates/dim-agent-capabilities/src/wait.rs +++ b/crates/dim-agent-capabilities/src/wait.rs @@ -11,7 +11,7 @@ //! as TS only commits inputs of a running turn. use crate::{ host::{CancelledFn, HostError, HostFuture, ToolExecutionContext, call_until_cancelled}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, tool_registry::{ToolConcurrency, ToolContribution, ToolHandler, ToolRegistry, definition}, workspace_tools::background::{WAKE_TASK_TAG, tagged}, }; @@ -366,7 +366,7 @@ fn wait_definition() -> ToolDefinition { definition } -struct WaitTool(Arc); +struct WaitTool(Arc); impl WaitTool { async fn run( &self, @@ -458,7 +458,7 @@ impl ToolHandler for WaitTool { } pub struct WaitPlugin { - tree: Key, + tree: Key, tools: Key, } impl WaitPlugin { diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index 8ae7975162..4ed181d39e 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -21,7 +21,7 @@ use crate::{ host::{HostError, HostFuture, SessionFiles, ToolDriver, ToolExecutionContext, ToolHost}, host_platform::HostPlatform, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, tool_registry::ToolConcurrency, }; use background::BackgroundExecPlugin; @@ -156,7 +156,7 @@ pub(crate) struct WorkspaceTools { /// would finish after its result. Member asynchronous execution is a /// separate design. member: bool, - tree: Arc, + tree: Arc, files: FileTools, /// Cancelled on unload: new calls settle as reloading, running ones stop. lifecycle: CancellationToken, @@ -323,7 +323,7 @@ struct WorkspaceToolsPlugin { platform: Key, session_config: Key, identity: Key, - tree: Key, + tree: Key, methods: Key, /// The owner's one walked index, shared with `workspace.files.search`. mentions: Key, diff --git a/crates/dim-agent-capabilities/src/workspace_tools/pending.rs b/crates/dim-agent-capabilities/src/workspace_tools/pending.rs index 9756629398..63a63d1931 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/pending.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/pending.rs @@ -1,6 +1,6 @@ use crate::{ methods::{RpcError, params}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::*; use dim_agent_types::{ExecEndedData, ExecStartedData, FinishedExec, PendingExec}; @@ -19,7 +19,7 @@ struct Params { } pub(super) async fn read( - tree: &TreeCommands, + tree: &TimelineTree, value: Value, cancel: &CancellationToken, ) -> std::result::Result { @@ -148,7 +148,7 @@ pub(super) async fn read( /// The newest [`FINISHED_LIMIT`] `exec/ended` facts at the cutoff, each with /// the `exec/started` it ends, newest end first. pub(super) async fn finished( - tree: &TreeCommands, + tree: &TimelineTree, value: Value, cancel: &CancellationToken, ) -> std::result::Result { @@ -301,7 +301,7 @@ pub(super) async fn finished( /// requests `requests` names whose response made several calls: the order of /// the tasks one parallel batch dispatched. pub async fn call_positions( - tree: &TreeCommands, + tree: &TimelineTree, branch_id: &str, through: u64, requests: impl IntoIterator, diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index 7e8bd70bc6..4faeff1c93 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -10,7 +10,7 @@ use dim_agent_capabilities::{ ResolveContextModel, StrategyDiagnostics, StrategyOutcome, ToolDriver, ToolExecutionContext, ToolHost, }, - timeline_tree::{BranchToolConfig, TreeCommands}, + timeline_tree::{BranchToolConfig, TimelineTree}, tool_registry::ToolRegistry, workspace_tools::{file_reads::FileReads, files::FileTools}, }; @@ -156,7 +156,7 @@ struct Probe { delay_child: AtomicBool, child_builds: AtomicUsize, child_cleanups: Arc, - commands: Mutex>>, + commands: Mutex>>, /// The Session's tool registry, so a test can call the `branch` tool itself. tool_registry: Mutex>>, /// main's Timeline as its capabilities receive it, for direct writes. @@ -196,7 +196,7 @@ struct ProbePlugin { timeline: Key, dispatcher: Key, identity: Key, - commands: Key, + commands: Key, registry: Key, } impl ProbePlugin { @@ -1733,7 +1733,7 @@ struct SettleOnActivation { child: String, source: BranchSource, ends: Arc>>, - tree: Key, + tree: Key, session: Key, identity: Key, } @@ -2708,7 +2708,7 @@ async fn a_host_line_opens_with_its_identity_block_and_the_creator_prompt() { ) .await .unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); assert!(matches!( tree.batch_end(child.clone(), batch[0].sequence).await, Err(AgentError::InvalidInput(_)) @@ -3506,7 +3506,7 @@ async fn call(session: &Session, branch: &str, arguments: &str) -> (String, Stri /// serves both an open line and one that ended. async fn line_events(session: &Session, branch: &str) -> Result>> { session - .session_service::()? + .session_service::()? .page(branch.to_owned(), 0, LINE_PAGE, session.sequence(branch)?) .await } @@ -7280,7 +7280,7 @@ async fn a_host_lines_end_says_nothing_to_main() { .await; assert!(blocks_with(&events, "().unwrap(); + let tree = session.session_service::().unwrap(); let facts = local_events(&session, &host).await; let head = facts.last().unwrap().sequence; let mut query = TimelineQuery { @@ -7401,7 +7401,7 @@ async fn a_tree_page_refuses_a_through_inside_a_batch() { .append_batch_registered(vec![input("first"), input("second")], |_| Ok(())) .unwrap(); let (inside, end) = (batch[0].sequence, batch[1].sequence); - let commands = session.session_service::().unwrap(); + let commands = session.session_service::().unwrap(); let refused = |page: Result>>, ended: bool| { assert!( matches!(page, Err(AgentError::InvalidInput(ref message)) if message.contains("inside an atomic batch")), @@ -8139,7 +8139,7 @@ async fn a_turn_spanning_a_restart_after_a_steer_writes_no_idle_notice() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn tree_chain_queries_preserve_inherited_cuts_after_ending_and_restore() { - async fn texts(tree: &TreeCommands, branch: &str) -> Vec { + async fn texts(tree: &TimelineTree, branch: &str) -> Vec { let mut query = TimelineQuery { scope: TimelineQueryScope::Chain, from: None, @@ -8243,7 +8243,7 @@ async fn tree_chain_queries_preserve_inherited_cuts_after_ending_and_restore() { .await .unwrap(); soon(session.idle(&leaf)).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let expected = ["visible-root", "visible-child", "visible-leaf"]; assert_eq!(texts(&tree, &leaf).await, expected); assert_eq!(texts(&tree, &zero).await, ["visible-root"]); @@ -8261,7 +8261,7 @@ async fn tree_chain_queries_preserve_inherited_cuts_after_ending_and_restore() { soon(agent.close()).await.unwrap(); let agent = MinimalHost::start(&config).await.unwrap(); let restored = agent.restore_session(session_id).await.unwrap(); - let tree = restored.session_service::().unwrap(); + let tree = restored.session_service::().unwrap(); assert_eq!(texts(&tree, &leaf).await, expected); assert_eq!(texts(&tree, &zero).await, ["visible-root"]); soon(agent.close()).await.unwrap(); @@ -8916,7 +8916,7 @@ async fn timeline_store_binding_preserves_memory_batch_publication_and_wire_read host.close().await.unwrap(); } -/// The tree's refusal code and message for a `TreeCommands` call. +/// The tree's refusal code and message for a `TimelineTree` call. fn refusal(error: &Result<()>) -> (&'static str, String) { match error { Err(AgentError::BranchRefused { refusal, message }) => (refusal.code(), message.clone()), @@ -8933,7 +8933,7 @@ async fn the_default_branch_starts_at_the_root_and_survives_a_restart() { .unwrap(); assert_eq!(session.default_branch().unwrap(), "main"); let line = open_line(&session, "a line to continue on").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); assert_eq!( tree.default_branch().unwrap(), "main", @@ -9123,7 +9123,7 @@ async fn an_end_whose_final_message_fails_is_delivered_by_the_next_restore() { .unwrap(); let session_id = session.id().to_owned(); let line = open_line(&session, "deliver me").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); store.fail_next_delivery("main"); let failed = tree .end_with_final( @@ -9226,7 +9226,7 @@ async fn a_second_end_retries_an_undelivered_final_message() { .unwrap(); let line = open_line(&session, "deliver me").await; soon(session.idle("main")).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let source = || BranchSource::Tool { turn_id: "turn".into(), request_id: "request".into(), @@ -9314,7 +9314,7 @@ async fn ending_the_parent_of_a_line_with_an_undelivered_message_answers() { .await .unwrap(); soon(session.idle(&child)).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); store.fail_next_lookup(&parent); let failed = soon(tree.end_with_final( child.clone(), @@ -9375,7 +9375,7 @@ async fn ending_the_root_the_default_branch_or_an_ancestor_is_refused() { .await .unwrap(); soon(session.idle(&inner)).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let user = BranchSource::User { operation_id: "end".into(), }; @@ -10077,7 +10077,7 @@ async fn a_move_answers_only_after_its_fact_is_durable() { .await .unwrap(); let line = open_line(&session, "continue on").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); // The line's turn and its parent's roster writes settle before the store // is armed, so the held batch is the move's own. tokio::time::sleep(Duration::from_millis(50)).await; @@ -10133,7 +10133,7 @@ async fn a_move_whose_write_fails_changes_nothing() { .unwrap(); let session_id = session.id().to_owned(); let line = open_line(&session, "stay on main").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); // The line's turn and its parent's roster writes settle before the store // is armed, so the held batch is the move's own. tokio::time::sleep(Duration::from_millis(50)).await; @@ -10237,7 +10237,7 @@ async fn a_restore_falls_back_to_the_root_for_a_target_it_cannot_select() { "main", "a {source:?} line cannot hold the role" ); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let refused = tree .set_default_branch( line.clone(), @@ -10369,7 +10369,7 @@ async fn every_refusal_of_a_move_writes_nothing() { let session = soon(agent.create_session(SessionConfig::default())) .await .unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let switch = |line: &str| { let tree = tree.clone(); let line = line.to_owned(); @@ -10504,7 +10504,7 @@ async fn a_former_default_branch_keeps_no_stale_instruction_and_ends_after_a_mov [("main".to_owned(), 0), (a.clone(), 2), (nested.clone(), 1)], "the root has no note and A holds the one that says it lost the role" ); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let refused = tree .end( a.clone(), @@ -10725,7 +10725,7 @@ async fn a_pre_upgrade_host_line_is_refused_and_a_user_line_is_accepted() { .await .unwrap(); soon(session.idle(&line)).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let refused = tree .set_default_branch( legacy.clone(), @@ -10780,7 +10780,7 @@ async fn a_switch_and_a_tool_lines_end_admit_in_one_order_without_a_refused_ones .unwrap(); let line = open_line(&session, "the line that ends").await; soon(session.idle("main")).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let source = BranchSource::Tool { turn_id: "turn".into(), request_id: "request".into(), @@ -11715,7 +11715,7 @@ async fn owed_notes(session: &Session, line: &str, count: usize) -> Vec /// Waits, bounded, for the tree to answer `line` as the default branch: an /// admitted `branch/default` settles even when its caller went away. -async fn answers_default(tree: &TreeCommands, line: &str) { +async fn answers_default(tree: &TimelineTree, line: &str) { for _ in 0..600 { if tree.default_branch().is_ok_and(|default| default == line) { return; @@ -11784,7 +11784,7 @@ async fn a_move_committed_before_its_writer_starts_still_owes_its_note() { stopped.is_ok(), "the writers of lines {b} and {c} never stopped at the test seam" ); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let switch = |target: &str| { let tree = tree.clone(); let target = target.to_owned(); @@ -11850,7 +11850,7 @@ async fn a_move_cancelled_after_admission_settles_under_the_tree() { .await .unwrap(); let line = open_line(&session, "switched while cancelled").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); // The line's turn and its parent's roster writes settle before the store is // armed, so the held batch is the move's own. tokio::time::sleep(Duration::from_millis(50)).await; @@ -11898,7 +11898,7 @@ async fn a_cancelled_move_whose_publication_fails_keeps_the_tree_until_it_settle .unwrap(); let first = open_line(&session, "first switch").await; let second = open_line(&session, "second switch").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); tokio::time::sleep(Duration::from_millis(50)).await; store.hold_next_default("main"); let mut moved = Box::pin(tree.set_default_branch( @@ -11958,7 +11958,7 @@ async fn an_end_retry_cancelled_after_admission_settles_under_the_tree() { .unwrap(); let line = open_line(&session, "deliver me").await; soon(session.idle("main")).await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let source = || BranchSource::Tool { turn_id: "turn".into(), request_id: "request".into(), @@ -12079,7 +12079,7 @@ async fn a_close_waits_for_an_admitted_move_and_a_restore_reads_its_fact() { /// with its caller gone: the tree owns what happens to it. async fn move_admitted_while_held(session: &Session, store: &Arc) -> String { let line = open_line(session, "moved while closing").await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); tokio::time::sleep(Duration::from_millis(50)).await; store.hold_next_default("main"); let mut moved = Box::pin(tree.set_default_branch( @@ -12706,7 +12706,7 @@ async fn an_open_after_a_move_waits_and_counts_the_moves_result() { let cut = idle_cut(&session, "main").await; let a = open_line(&session, "a").await; switch(&session, &a).await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); store.hold_next_default("main"); let mut moved = Box::pin(tree.set_default_branch( @@ -12766,7 +12766,7 @@ async fn an_open_from_the_moving_line_is_refused_once_the_move_settles() { .unwrap(); let b = open_line(&session, "b").await; switch(&session, &b).await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); store.hold_next_default("main"); let mut moved = Box::pin(tree.set_default_branch( diff --git a/crates/dim-agent-capabilities/tests/input_flow.rs b/crates/dim-agent-capabilities/tests/input_flow.rs index 76f3dc355e..c5328f0b22 100644 --- a/crates/dim-agent-capabilities/tests/input_flow.rs +++ b/crates/dim-agent-capabilities/tests/input_flow.rs @@ -11,7 +11,7 @@ use std::{ time::Duration, }; -use dim_agent_capabilities::{defaults, timeline_tree::TreeCommands}; +use dim_agent_capabilities::{defaults, timeline_tree::TimelineTree}; use dim_agent_runtime::testing::{MinimalHost, branch_events}; use dim_agent_runtime::{ AgentBuilder, AgentConfig, AgentError, BoxFuture, MemoryTimelineStore, PublishCallback, @@ -198,7 +198,7 @@ async fn a_subscriber_receives_the_batch_in_order_and_nothing_before_it_commits( #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_invalid_second_input_writes_nothing() { let Fixture { host, session } = start(memory()).await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let before = session.sequence("main").unwrap(); let invalid = InputMessageData { submission_id: Some("test:invalid".into()), @@ -226,7 +226,7 @@ async fn an_invalid_second_input_writes_nothing() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn an_empty_batch_is_refused() { let Fixture { host, session } = start(memory()).await; - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let before = session.sequence("main").unwrap(); let error = tree.inputs("main".into(), Vec::new()).await; assert!( @@ -262,7 +262,7 @@ async fn a_full_replay_returns_the_committed_events() { let batch = || vec![input("test:one", "one"), input("test:two", "two")]; let first = session.inputs(batch(), "main").await.unwrap(); session.idle("main").await.unwrap(); - let tree = session.session_service::().unwrap(); + let tree = session.session_service::().unwrap(); let replay = tree.inputs("main".into(), batch()).await.unwrap(); assert_eq!( replay diff --git a/crates/dim-agent-questions/src/lib.rs b/crates/dim-agent-questions/src/lib.rs index 57238d7f23..62a9e9f74e 100644 --- a/crates/dim-agent-questions/src/lib.rs +++ b/crates/dim-agent-questions/src/lib.rs @@ -17,7 +17,7 @@ use dim_agent_capabilities::{ host::{HostError, HostFuture, ToolExecutionContext}, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, tool_registry::{ ToolClaim, ToolConcurrency, ToolContribution, ToolHandler, ToolRegistry, definition, }, @@ -512,7 +512,7 @@ pub struct QuestionsPlugin { config: Key, tools: Key, methods: Key, - tree: Key, + tree: Key, } impl QuestionsPlugin { pub fn new(names: &Names<'_>) -> rutis::Result { diff --git a/crates/dim-agent-questions/src/pending.rs b/crates/dim-agent-questions/src/pending.rs index 18f46d10b8..4073189839 100644 --- a/crates/dim-agent-questions/src/pending.rs +++ b/crates/dim-agent-questions/src/pending.rs @@ -17,7 +17,7 @@ struct Params { } pub(super) async fn read( - tree: &TreeCommands, + tree: &TimelineTree, value: Value, cancel: &CancellationToken, ) -> Result { diff --git a/crates/dim-agent-runtime/src/contracts.rs b/crates/dim-agent-runtime/src/contracts.rs index 8f4a1dcd14..8f9f997abb 100644 --- a/crates/dim-agent-runtime/src/contracts.rs +++ b/crates/dim-agent-runtime/src/contracts.rs @@ -136,7 +136,8 @@ pub struct TimelineInfo { } /// Whether a line takes input, is finishing a committed end, or has ended. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub enum BranchDirectoryState { /// The line takes input, and its head is live. Open, @@ -148,7 +149,8 @@ pub enum BranchDirectoryState { } /// One line's directory record: its identity, its state, its head and its end. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct BranchDirectoryEntry { pub info: TimelineInfo, /// The published head while open or ending, the fixed head once ended. @@ -156,6 +158,7 @@ pub struct BranchDirectoryEntry { pub state: BranchDirectoryState, /// The sequence of the line's own `branch/end`: committed while ending, /// recorded once ended. + #[serde(skip_serializing_if = "Option::is_none")] pub end_event: Option, } diff --git a/crates/dim-agent-runtime/src/names.rs b/crates/dim-agent-runtime/src/names.rs index 32acd86572..10718e2eca 100644 --- a/crates/dim-agent-runtime/src/names.rs +++ b/crates/dim-agent-runtime/src/names.rs @@ -5,7 +5,7 @@ //! part is a rutis `host::DynPlugin` that keeps the keys of the services it //! depends on, declares them in `injects` and reads them with `require_at` //! in `apply`. [`Names`] gives those keys: the Rust binding takes a service's name from its type, as -//! `#[rutis::service]` does (`TreeCommands` is `treeCommands`), its group from +//! `#[rutis::service]` does (`TimelineTree` is `timelineTree`), its group from //! the catalog, and its key for each copy from the instances the copy runs in. //! A part therefore names no group: where its row is placed decides, and a //! row placed outside a group one of its names belongs to fails at @@ -99,9 +99,7 @@ pub fn catalog() -> ServiceCatalog { 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); register::(&mut catalog, session); let branch = Some(BRANCH_GROUP); register::(&mut catalog, branch); diff --git a/crates/dim-app-server/examples/timeline_acceptance.rs b/crates/dim-app-server/examples/timeline_acceptance.rs index 7aec0fe4bc..5d62eebee7 100644 --- a/crates/dim-app-server/examples/timeline_acceptance.rs +++ b/crates/dim-app-server/examples/timeline_acceptance.rs @@ -15,7 +15,6 @@ use dim_agent_capabilities::{ defaults, history::{HistoryRenderer, summary_message}, host::*, - timeline_tree::TreeCommands, }; use dim_agent_runtime::{testing::MinimalHost, *}; use dim_agent_types::*; @@ -85,40 +84,6 @@ fn quantile(values: &mut [f64], p: f64) -> f64 { values[((values.len() as f64 * p).ceil() as usize).saturating_sub(1)] } -struct CaptureTree { - captured: Arc>>>, - - tree: rutis::host::Key, -} -impl CaptureTree { - fn new( - names: &dim_agent_runtime::Names<'_>, - captured: Arc>>>, - ) -> rutis::Result { - Ok(Self { - captured, - tree: names.key()?, - }) - } -} -impl rutis::host::DynPlugin for CaptureTree { - fn name(&self) -> &str { - "measurement.tree" - } - fn injects(&self) -> Vec { - vec![self.tree.erase()] - } - fn apply<'a>( - &'a self, - ctx: &'a rutis::Ctx, - ) -> rutis::host::BoxFuture<'a, rutis::Result> { - Box::pin(async move { - let tree = ctx.require_at(&self.tree)?; - *self.captured.lock().unwrap() = Some(tree); - Ok(rutis::host::Effect::Done) - }) - } -} struct Compactor { samples: Arc>, } @@ -244,8 +209,6 @@ async fn memory(steps: usize) -> std::result::Result<(), Error> { let directory = directory("memory"); let db = SqliteStorage::open(directory.join("dimcode.sqlite"))?; let store = SqliteTimelineStore::new(db.clone()); - let captured = Arc::new(Mutex::new(None)); - let capture = captured.clone(); let samples = Arc::new(Mutex::new(PreparationSamples { count: 0, warm: [0; 100], @@ -268,11 +231,6 @@ async fn memory(steps: usize) -> std::result::Result<(), Error> { Feature::new("PrepareModelHost").session("PrepareModelHost", |names| { Ok(Box::new(DefaultPrepareModelPlugin::new(names)?)) }), - ) - .require_feature( - Feature::new("measurement.tree").session("measurement.tree", move |names| { - Ok(Box::new(CaptureTree::new(names, capture.clone())?)) - }), ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await?; @@ -284,8 +242,7 @@ async fn memory(steps: usize) -> std::result::Result<(), Error> { }) .await?; session.idle("main").await?; - let tree = captured.lock().unwrap().clone().unwrap(); - let timeline = tree.get("main")?; + let timeline = session.publication("main")?; let mut idle = Vec::with_capacity(steps / 100 + 2); let mut turn_warm = [0usize; 100]; let mut turn_recent = [0usize; 100]; @@ -815,8 +772,6 @@ async fn reads() -> std::result::Result<(), Error> { ); timing.push(start.elapsed().as_secs_f64() * 1000.); } - let captured = Arc::new(Mutex::new(None)); - let target = captured.clone(); let observed = Arc::new(Mutex::new(Vec::with_capacity(21))); let stop_target = observed.clone(); let mut builder = AgentBuilder::new(AgentConfig::default()); @@ -824,11 +779,6 @@ async fn reads() -> std::result::Result<(), Error> { defaults::install(&mut builder); builder .timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())) - .require_feature( - Feature::new("measurement.tree").session("measurement.tree", move |names| { - Ok(Box::new(CaptureTree::new(names, target.clone())?)) - }), - ) .require_feature( Feature::new("measurement.stop").branch("measurement.stop", move |names| { Ok(Box::new(CaptureStop::new(names, stop_target.clone())?)) @@ -837,7 +787,7 @@ async fn reads() -> std::result::Result<(), Error> { let agent = MinimalHost::start(&builder).await?; let session = agent.restore_session(name.into()).await?; session.idle("main").await?; - let active = captured.lock().unwrap().clone().unwrap().get("main")?; + let active = session.publication("main")?; let mut dispatch = Vec::new(); for _ in 0..20 { let reader = active.clone(); diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 4edfb12ea9..619465b0da 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -456,7 +456,7 @@ async fn ended_page( through: u64, ) -> dim_agent_runtime::Result>> { session - .session_service::()? + .session_service::()? .page(branch.to_owned(), after, limit, through) .await } diff --git a/crates/dim-app-server/src/agents/configuration.rs b/crates/dim-app-server/src/agents/configuration.rs index 38cb981dd8..6df00c1ef7 100644 --- a/crates/dim-app-server/src/agents/configuration.rs +++ b/crates/dim-app-server/src/agents/configuration.rs @@ -3,9 +3,9 @@ use crate::connection::{configuration_outcome, port_error}; use dim_agent_capabilities::{ host::ModelSelectionRequest, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, - prompt::{Prompt, PromptConfigurationRequest}, + prompt::PromptConfigurationRequest, prompt_sources, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::{Names, PromptSourceTarget}; use dim_agent_types::{DEFAULT_BRANCH_ID, ModelSelection, PromptScope}; @@ -19,7 +19,7 @@ use tokio_util::sync::CancellationToken; /// and reads back the profile the branch's configuration was adopted from. pub(crate) struct AgentsSessionPlugin { index: Key, - tree: Key, + tree: Key, methods: Key, } impl AgentsSessionPlugin { @@ -74,7 +74,7 @@ impl DynPlugin for AgentsSessionPlugin { /// `session.agent.get`: the profile recorded on the branch's adopted /// configuration. It reads the branch's published Prompt snapshot, which /// projects the configuration inherited from the branch's ancestry. -fn configured_agent(tree: &TreeCommands, value: Value) -> Result { +fn configured_agent(tree: &TimelineTree, value: Value) -> Result { #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Params { @@ -90,10 +90,7 @@ fn configured_agent(tree: &TreeCommands, value: Value) -> Result() - .map_err(|_| RpcError::reloading())? - .adopted_configuration(Default::default()) + .adopted_configuration(&branch_id)? .and_then(|configuration| configuration.metadata) .and_then(|metadata| metadata.agent_id); reply(Answer { agent_id }) @@ -104,7 +101,7 @@ fn configured_agent(tree: &TreeCommands, value: Value) -> Result, - tree: Arc, + tree: Arc, value: Value, cancel: CancellationToken, ) -> Result { @@ -126,7 +123,7 @@ async fn adopt_profile( "Agent configuration updates only support main", )); } - let branch = tree.get(&branch_id)?; + let configure = tree.prepare_prompt_write(&branch_id)?; let profile = index .host(Some(&agent_id)) .ok_or_else(crate::protocol::agent_unknown)? @@ -153,10 +150,9 @@ async fn adopt_profile( }), // A profile without a model keeps the adopted configuration; it is // materialized so the configuration can carry the profile's record. - None => branch - .service::() + None => tree + .adopted_configuration(&branch_id) .map_err(|_| RpcError::reloading())? - .adopted_configuration(Default::default()) .map(|configuration| ModelSelection { provider_id: configuration.provider_id, model_id: configuration.model_id, @@ -181,13 +177,10 @@ async fn adopt_profile( scope: scope.clone(), }; let entry = prompt_sources::session_entry(profile.system_prompt, scope); - let prompt = branch.service::()?; - let adoption = prompt - .as_ref() - .configure(PromptConfigurationRequest::Loaded { - model, - sources: vec![(target, entry)], - }); + let adoption = configure(PromptConfigurationRequest::Loaded { + model, + sources: vec![(target, entry)], + }); tokio::select! { result = adoption => reply(json!({"outcome": configuration_outcome(result?)?})), _ = cancel.cancelled() => Err(RpcError::interrupted()), diff --git a/crates/dim-app-server/src/collaboration.rs b/crates/dim-app-server/src/collaboration.rs index 10eb058b3d..ea5f50d4e6 100644 --- a/crates/dim-app-server/src/collaboration.rs +++ b/crates/dim-app-server/src/collaboration.rs @@ -26,7 +26,7 @@ use dim_agent_capabilities::{ methods::RpcError, prompt::Prompt, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, tool_registry::{ToolContribution, ToolHandler, ToolRegistry, definition}, }; use dim_agent_runtime::{ @@ -826,6 +826,7 @@ struct Op { waiter: Option, } struct BranchRecord { + phase: Arc, ctx: Ctx, dispatcher: Arc, approvals: BTreeMap, @@ -949,7 +950,7 @@ pub struct CollaborationSession { collaboration: Arc, session_id: String, role: CollaborationRole, - tree: Arc, + tree: Arc, /// Gives each request its hold on this Session. lifecycle: Arc, /// The deployment's selectable models, when it reads them: the `models` @@ -1305,7 +1306,11 @@ impl CollaborationSession { return Err(RpcError::invalid("branchId must not be empty")); } // An ended or unknown branch answers its own error, never `idle`. - let _branch = self.tree.get(branch_id)?; + if self.tree.directory_entry(branch_id)?.state + == dim_agent_runtime::BranchDirectoryState::Ended + { + return Err(AgentError::BranchEnded(branch_id.to_owned()).into()); + } // The calling branch's own request is the only work this call may // stop. `branch.open` also holds a request that is still waiting for // its delivery or for a `Busy` refusal, which runs no turn of its @@ -2451,12 +2456,15 @@ impl CollaborationSession { InputFate::Pending => {} } match session - .service::(ROOT_BRANCH_ID)? - .withdraw(InputWithdrawData { - input_id: input.to_owned(), - reason: Some(reason.into()), - steer: None, - }) + .session_service::()? + .withdraw( + ROOT_BRANCH_ID, + InputWithdrawData { + input_id: input.to_owned(), + reason: Some(reason.into()), + steer: None, + }, + )? .await? { // (W): no turn will run for the input; the settle names it. @@ -2523,21 +2531,21 @@ impl CollaborationSession { result_id: &str, data: &CollaborationResultData, ) -> dim_agent_runtime::Result<()> { - let suppressed = { + let phase = { let mut state = self.state.lock().unwrap(); let Some(branch) = state.branches.get_mut(branch_id) else { return Ok(()); }; - branch + if branch .ops .remove(&data.request_event_id) .is_none_or(|op| op.suppressed || branch.closing) + { + return Ok(()); + } + branch.phase.clone() }; - if suppressed { - return Ok(()); - } - let branch = self.tree.get(branch_id)?; - if branch.is_closing() { + if phase.phase() >= dim_agent_runtime::BranchPhase::Closing { return Ok(()); } let status = match &data.outcome { @@ -2565,9 +2573,11 @@ impl CollaborationSession { mode: Some(InputMode::Steer), ..Default::default() }; - match branch.input(input).await { + match self.tree.input(branch_id.to_owned(), input).await { Ok(_) => Ok(()), - Err(AgentError::Closed(_)) if branch.is_closing() => Ok(()), + Err( + AgentError::Closed(_) | AgentError::BranchEnded(_) | AgentError::UnknownBranch(_), + ) if phase.phase() >= dim_agent_runtime::BranchPhase::Closing => Ok(()), Err(error) => Err(error), } } @@ -2607,22 +2617,19 @@ impl CollaborationSession { /// Unload: pending work stops; operations without `delivered` and /// requests without `result` are settled on this Timeline. async fn unload(self: &Arc, branch_id: &str) { - let tasks = { + let (tasks, phase) = { let mut state = self.state.lock().unwrap(); let Some(branch) = state.branches.get_mut(branch_id) else { return; }; branch.closing = true; branch.abort.cancel(); - branch.tasks.clone() + (branch.tasks.clone(), branch.phase.clone()) }; self.retire_branch_approvals(branch_id).await; tasks.close(); tasks.wait().await; - let closing = self - .tree - .get(branch_id) - .map_or(true, |branch| branch.is_closing()); + let closing = phase.phase() >= dim_agent_runtime::BranchPhase::Closing; let (ops, members): (Vec, Vec) = { let state = self.state.lock().unwrap(); let ops = state @@ -3375,7 +3382,7 @@ struct CollaborationSessionPlugin { collaboration: Key, identity: Key, config: Key, - tree: Key, + tree: Key, lifecycle: Key, tools: Key, guide: Key, @@ -4000,6 +4007,7 @@ async fn restore( service.state.lock().unwrap().branches.insert( branch_id.clone(), BranchRecord { + phase: phase.clone(), ctx, dispatcher: dispatcher.clone(), approvals: BTreeMap::new(), @@ -4022,15 +4030,17 @@ async fn restore( return; } let result = async { - let branch = service.tree.get(&branch_id)?; - let queue = branch.service::()?; for input_id in stale_inputs { - queue - .withdraw(InputWithdrawData { - input_id, - reason: Some(RELOADING.into()), - steer: None, - }) + service + .tree + .withdraw( + &branch_id, + InputWithdrawData { + input_id, + reason: Some(RELOADING.into()), + steer: None, + }, + )? .await?; } Ok::<_, AgentError>(()) diff --git a/crates/dim-app-server/src/collaboration/approvals.rs b/crates/dim-app-server/src/collaboration/approvals.rs index 2bf2ba43ce..5b6b003a1e 100644 --- a/crates/dim-app-server/src/collaboration/approvals.rs +++ b/crates/dim-app-server/src/collaboration/approvals.rs @@ -1,7 +1,6 @@ use super::*; use dim_agent_capabilities::{ - approval::{Approval, ApprovalRespondError}, - input_queue::InputQueue, + approval::ApprovalRespondError, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params, reply}, session_broadcast::{SessionNotice, notify}, }; @@ -149,19 +148,30 @@ struct DetailParams { } impl CollaborationSession { - fn member_approval(&self, session_id: &str, branch_id: &str) -> Option> { - let (_, member) = self.collaboration.index.session(session_id)?; - member.service::(branch_id).ok() + async fn decide_member( + &self, + descriptor: &MemberApprovalDescriptor, + decision: ApprovalDecision, + ) -> Result<(), ApprovalRespondError> { + let (_, member) = self + .collaboration + .index + .session(&descriptor.member.session_id) + .ok_or(ApprovalRespondError::Unknown)?; + let tree = member + .session_service::() + .map_err(|_| ApprovalRespondError::Unknown)?; + tree.decide_approval( + &descriptor.member.branch_id, + descriptor.request_id.clone(), + decision, + ) + .map_err(|_| ApprovalRespondError::Unknown)? + .await } async fn deny_member(&self, descriptor: &MemberApprovalDescriptor) { - if let Some(approval) = - self.member_approval(&descriptor.member.session_id, &descriptor.member.branch_id) - { - let _ = approval - .respond(&descriptor.request_id, ApprovalDecision::Deny) - .await; - } + let _ = self.decide_member(descriptor, ApprovalDecision::Deny).await; } /// Returns the current live delegation destination, or `None` when it is absent or closing. @@ -334,12 +344,12 @@ impl CollaborationSession { let branch_id = branch_id.to_owned(); let approval_id = approval_id.to_owned(); tasks.spawn(async move { - if let Ok(approval) = owner - .tree - .get(&branch_id) - .and_then(|branch| branch.service::()) + if let Ok(decision) = + owner + .tree + .decide_approval(&branch_id, approval_id, ApprovalDecision::Deny) { - let _ = approval.respond(&approval_id, ApprovalDecision::Deny).await; + let _ = decision.await; } }); } @@ -382,12 +392,16 @@ impl CollaborationSession { } async fn retire_route(&self, branch_id: &str, route: &Route) { - let (ctx, dispatcher) = { + let (ctx, dispatcher, phase) = { let state = self.state.lock().unwrap(); let Some(branch) = state.branches.get(branch_id) else { return; }; - (branch.ctx.clone(), branch.dispatcher.clone()) + ( + branch.ctx.clone(), + branch.dispatcher.clone(), + branch.phase.clone(), + ) }; notify( &ctx, @@ -403,16 +417,15 @@ impl CollaborationSession { }, ); self.deny_member(&route.descriptor).await; - if let Ok(branch) = self.tree.get(branch_id) - && let Ok(queue) = branch.service::() - && let Err(error) = queue - .withdraw(InputWithdrawData { - input_id: route.input_id.clone(), - reason: Some("Member approval ended".into()), - steer: None, - }) - .await - && !branch.is_closing() + if let Ok(withdraw) = self.tree.withdraw( + branch_id, + InputWithdrawData { + input_id: route.input_id.clone(), + reason: Some("Member approval ended".into()), + steer: None, + }, + ) && let Err(error) = withdraw.await + && phase.phase() < dim_agent_runtime::BranchPhase::Closing { dispatcher.fail(error); } @@ -474,16 +487,15 @@ impl CollaborationSession { let branch_id = branch_id.to_owned(); let input_id = event.id.clone(); tasks.spawn(async move { - if let Ok(branch) = owner.tree.get(&branch_id) - && let Ok(queue) = branch.service::() - { - let _ = queue - .withdraw(InputWithdrawData { - input_id, - reason: Some("Member approval is not active".into()), - steer: None, - }) - .await; + if let Ok(withdraw) = owner.tree.withdraw( + &branch_id, + InputWithdrawData { + input_id, + reason: Some("Member approval is not active".into()), + steer: None, + }, + ) { + let _ = withdraw.await; } owner.deny_member(&source.descriptor).await; }); @@ -627,24 +639,20 @@ impl CollaborationSession { if p.branch_id.is_empty() || p.request_id.is_empty() { return Err(RpcError::invalid("Approval identity must not be empty")); } - let branch = match self.tree.get(&p.branch_id) { - Ok(branch) => branch, + let pending = match self.tree.pending_approvals(&p.branch_id) { + Ok(requests) => requests, Err( AgentError::UnknownBranch(_) | AgentError::BranchEnded(_) | AgentError::Closed(_), ) => return Ok(MemberApprovalDetail::Ended), Err(error) => return Err(error.into()), }; - if branch.is_closing() { - return Ok(MemberApprovalDetail::Ended); - } - let approval = branch.service::()?; - let mut id = None; - approval.replay(|request| { - if request.approval_id == p.request_id && request.call.name == MEMBER_APPROVAL_ALLOW { - id = serde_json::from_value::(Value::Object(request.call.input.clone())) - .ok() - .map(|answer| answer.approval_id); + let id = pending.into_iter().find_map(|request| { + if request.approval_id != p.request_id || request.call.name != MEMBER_APPROVAL_ALLOW { + return None; } + serde_json::from_value::(Value::Object(request.call.input)) + .ok() + .map(|answer| answer.approval_id) }); let route = id.and_then(|id| self.approval_route(&p.branch_id, &id)); let Some(route) = route else { @@ -698,17 +706,10 @@ impl ToolHandler for DecisionTool { } else { ApprovalDecision::Deny }; - let result = match self.session.member_approval( - &route.descriptor.member.session_id, - &route.descriptor.member.branch_id, - ) { - Some(approval) => { - approval - .respond(&route.descriptor.request_id, decision) - .await - } - None => Err(ApprovalRespondError::Unknown), - }; + let result = self + .session + .decide_member(&route.descriptor, decision) + .await; let code = match result { Ok(()) => "answered", Err(ApprovalRespondError::Unknown | ApprovalRespondError::Cancelled) => { diff --git a/crates/dim-app-server/src/collaboration/pending.rs b/crates/dim-app-server/src/collaboration/pending.rs index 0b6822c332..6d2eea37d1 100644 --- a/crates/dim-app-server/src/collaboration/pending.rs +++ b/crates/dim-app-server/src/collaboration/pending.rs @@ -49,7 +49,7 @@ pub(super) fn install( } async fn read( - tree: &TreeCommands, + tree: &TimelineTree, value: Value, cancel: &CancellationToken, ) -> std::result::Result { @@ -231,7 +231,7 @@ const FINISHED_LIMIT: u64 = 50; /// `collaboration/result` or a failed `collaboration/delivered` — each with /// its request and that request's latest delivery, newest end first. async fn finished( - tree: &TreeCommands, + tree: &TimelineTree, value: Value, cancel: &CancellationToken, ) -> std::result::Result { diff --git a/crates/dim-app-server/src/connection/tree.rs b/crates/dim-app-server/src/connection/tree.rs index 1b4dd6a071..2beaee6007 100644 --- a/crates/dim-app-server/src/connection/tree.rs +++ b/crates/dim-app-server/src/connection/tree.rs @@ -3,7 +3,7 @@ use crate::tree_protocol as wire; use dim_agent_capabilities::input_queue::{ CheckInterrupted, SubmitCheckRequest, SubmitChecks, SubmitDecision, SubmitEntry, append_blocks, }; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::timeline_tree::TimelineTree; use dim_agent_runtime::{ BranchOptions, InputCommit, QueryComparison, QueryFilter, QueryOperand, QueryOrder, QueryOrderKey, QueryOutput, QueryPage, QueryPick, QuerySelect, QuerySpec, QueryValue, @@ -286,7 +286,7 @@ impl Connection { } if window { let tree = session - .session_service::() + .session_service::() .map_err(history_error)?; let turn = if params.latest_turn { turn_window(&tree, branch, through).await? @@ -339,7 +339,7 @@ impl Connection { }); } let tree = session - .session_service::() + .session_service::() .map_err(history_error)?; let read = if session.ended_head(branch).is_some() { HistoryRead::Ended(&tree, self.protocol_version()) @@ -423,7 +423,7 @@ impl Connection { let reply = match session.query(branch, query.clone()).await { Err(AgentError::BranchEnded(_)) => { session - .session_service::() + .session_service::() .map_err(history_error)? .query(branch.to_owned(), query) .await @@ -484,7 +484,7 @@ impl Connection { }; let entries = if session.ended_head(branch).is_some() { let tree = session - .session_service::() + .session_service::() .map_err(history_error)?; scan_keys( &HistoryRead::Ended(&tree, self.protocol_version()), @@ -509,7 +509,7 @@ impl Connection { .is_some_and(|data| data.app_error == "branch_ended") => { let tree = session - .session_service::() + .session_service::() .map_err(history_error)?; scan_keys( &HistoryRead::Ended(&tree, self.protocol_version()), @@ -549,7 +549,7 @@ impl Connection { ) -> Result { let session = self.session(rpc, ¶ms.session_id)?; let tree = session - .session_service::() + .session_service::() .map_err(RpcError::from)?; let read = tree .display(params.branch_id) @@ -723,7 +723,7 @@ fn keys_too_large(bytes: usize) -> RpcError { /// its first request consumed or, when it has yet to take one, the newest /// message at or below the start. async fn turn_window( - tree: &TreeCommands, + tree: &TimelineTree, branch: &str, through: u64, ) -> Result { @@ -928,7 +928,7 @@ async fn turn_window( /// the tree that owns its fixed head (ADR 021 D2). enum HistoryRead<'a> { Open(&'a Session, u32), - Ended(&'a TreeCommands, u32), + Ended(&'a TimelineTree, u32), } impl HistoryRead<'_> { diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index d6f62ac68b..a9b2e78fcb 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -1510,9 +1510,6 @@ pub fn register_faces(builder: &mut dim_agent_runtime::AgentBuilder) { ("sessionStore", "owner-api"), ("settingsService", "owner-api"), ("submitChecks", "hot-path"), - ("timelineFactory", "control"), - ("timelineTree", "owner-api"), - ("timelineTreeControl", "owner-api"), ("toolBinding", "hot-path"), ("toolExecutor", "hot-path"), ("uiExtensions", "control"), diff --git a/crates/dim-app-server/src/session_language.rs b/crates/dim-app-server/src/session_language.rs index 15f3c1e228..ff69d2b505 100644 --- a/crates/dim-app-server/src/session_language.rs +++ b/crates/dim-app-server/src/session_language.rs @@ -3,11 +3,11 @@ //! in PromptSources' live cell; this part reads both and changes both, then //! has Prompt adopt the `dim/language` source. use crate::storage::Store; -use dim_agent_capabilities::prompt::BranchPrompt as _; +use dim_agent_capabilities::prompt::PromptConfigurationRequest; use dim_agent_capabilities::{ methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, params}, prompt_sources::{self, SessionLanguage}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::{Names, ReplyLanguage}; use dim_agent_types::ROOT_BRANCH_ID; @@ -24,7 +24,7 @@ const FAILED: &str = "language_failed"; /// The Session's two reply-language methods; one per Session instance. pub(crate) struct SessionLanguagePlugin { - tree: Key, + tree: Key, language: Key, methods: Key, /// Native storage, when the assembly has it: the record carries the value. @@ -82,7 +82,14 @@ impl DynPlugin for SessionLanguagePlugin { Box::pin(async move { match method.as_str() { "session.language.get" => { - tree.get(ROOT_BRANCH_ID).map_err(RpcError::from)?; + if tree.directory_entry(ROOT_BRANCH_ID)?.state + == dim_agent_runtime::BranchDirectoryState::Ended + { + return Err(dim_agent_runtime::AgentError::BranchEnded( + ROOT_BRANCH_ID.into(), + ) + .into()); + } read(cell?).await } _ => change(&tree, cell, store.as_deref(), params, cancel).await, @@ -105,7 +112,7 @@ async fn read(language: Arc) -> Result { /// `session.language.update`: writes the record, replaces the live cell and /// has Prompt adopt the source, all under the Session's language gate. async fn change( - tree: &TreeCommands, + tree: &TimelineTree, language_cell: Result, RpcError>, store: Option<&Store>, value: Value, @@ -143,7 +150,10 @@ async fn change( }) => None, Change::Code(code) => Some(code), }; - let branch = tree.get(ROOT_BRANCH_ID).map_err(RpcError::from)?; + let adoption = tree.configure_prompt( + ROOT_BRANCH_ID, + PromptConfigurationRequest::Targets(prompt_sources::language_update()), + )?; let language_cell = language_cell?; let _guard = language_cell.gate().await; // A failure before this write leaves the value unchanged; once the record @@ -157,7 +167,6 @@ async fn change( .map_err(|error| RpcError::app(-32000, FAILED, error.to_string()))?; } let applied = language_cell.replace(language); - let adoption = branch.configure(prompt_sources::language_update()); let outcome = tokio::select! { result = adoption => { crate::connection::configuration_outcome(result.map_err(RpcError::from)?)? @@ -173,10 +182,12 @@ async fn change( if info.id == ROOT_BRANCH_ID { continue; } - let Ok(side) = tree.get(&info.id) else { + let Ok(adoption) = tree.configure_prompt( + &info.id, + PromptConfigurationRequest::Targets(prompt_sources::language_update()), + ) else { continue; }; - let adoption = side.configure(prompt_sources::language_update()); let result = tokio::select! { result = adoption => result, _ = cancel.cancelled() => return Err(RpcError::interrupted()), diff --git a/crates/dim-app-server/src/session_typescript.rs b/crates/dim-app-server/src/session_typescript.rs index 2b45fe3afb..191fab5a03 100644 --- a/crates/dim-app-server/src/session_typescript.rs +++ b/crates/dim-app-server/src/session_typescript.rs @@ -39,7 +39,7 @@ fn crossing_instance_names() -> [(String, &'static str); 19] { ), (name_of::(), SESSION_GROUP), ( - name_of::(), + name_of::(), SESSION_GROUP, ), ( diff --git a/crates/dim-app-server/tests/storage_session_flow.rs b/crates/dim-app-server/tests/storage_session_flow.rs index e18d0a956d..765cb117d5 100644 --- a/crates/dim-app-server/tests/storage_session_flow.rs +++ b/crates/dim-app-server/tests/storage_session_flow.rs @@ -1,4 +1,4 @@ -use dim_agent_capabilities::{defaults, timeline_tree::TreeCommands}; +use dim_agent_capabilities::{defaults, timeline_tree::TimelineTree}; use dim_agent_runtime::Names; use dim_agent_runtime::testing::branch_events; use dim_agent_runtime::{ @@ -55,14 +55,14 @@ impl DynPlugin for CaptureTimeline { } struct GenericCleanupFault { - tree: Arc>>>, + tree: Arc>>>, timeline: Key, identity: Key, dispatcher: Key, - commands: Key, + commands: Key, } impl GenericCleanupFault { - fn new(names: &Names<'_>, tree: Arc>>>) -> rutis::Result { + fn new(names: &Names<'_>, tree: Arc>>>) -> rutis::Result { Ok(Self { tree, timeline: names.key()?, diff --git a/crates/dim-app-server/tests/transport_flow/branch_end.rs b/crates/dim-app-server/tests/transport_flow/branch_end.rs index 04e01b57d3..c0f7006cd5 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_end.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_end.rs @@ -148,7 +148,7 @@ async fn read_both_sides(config: ServerConfig) { assert_eq!(pinned["result"]["nextAfter"], cutoff); assert_eq!(pinned["result"], racing["result"]); let tree = session - .session_service::() + .session_service::() .unwrap(); let facts = tree.page(child.clone(), 0, 256, through).await.unwrap(); if native { 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 da90ddef16..a292f9f573 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -1,7 +1,7 @@ //! Branch TypeScript parts on the exported branch services //! (branch-typescript.md): a row that injects `dispatcher` runs in every //! branch, follows its committed events in order and writes input through -//! `treeCommands`. +//! `timelineTree`. use super::*; use dim_agent_runtime::Timeline; use dim_agent_runtime::testing::branch_events; @@ -318,7 +318,7 @@ impl rutis::host::DynPlugin for HoldBuild { } } -/// `treeCommands.create` takes the caller's cancellation as an explicit +/// `timelineTree.create` takes the caller's cancellation as an explicit /// argument, as C4's `cancelled` does: one that never completes lets the /// child be created; one that has completed ends the call `Cancelled`. A /// creation already committed is a fact TimelineTree finishes. diff --git a/crates/dim-app-server/tests/transport_flow/idle_unload.rs b/crates/dim-app-server/tests/transport_flow/idle_unload.rs index 3cee881df5..429e4266c0 100644 --- a/crates/dim-app-server/tests/transport_flow/idle_unload.rs +++ b/crates/dim-app-server/tests/transport_flow/idle_unload.rs @@ -4,8 +4,9 @@ //! the loaded count in `agent.list`, or a call's reply. use super::super::deletion::eventually; use super::*; +use dim_agent_capabilities::timeline_tree::TimelineTree; +use dim_agent_runtime::SessionIdentity; use dim_agent_runtime::testing::branch_events; -use dim_agent_runtime::{SessionIdentity, TimelineTreeControl}; use rutis::host::CtxHost; use std::sync::Weak; use tokio::sync::Notify; @@ -86,7 +87,7 @@ async fn checked_attach_rejects_a_different_cwd_before_restoring_the_session() { /// keeping that release under way until the test lets it finish. #[derive(Clone, Default)] pub(crate) struct Loads(Arc); -type Load = (String, bool, Weak); +type Load = (String, bool, Weak); #[derive(Default)] struct LoadsState { loads: std::sync::Mutex>, @@ -145,7 +146,7 @@ impl Loads { struct LoadsPart( Loads, rutis::host::Key, - rutis::host::Key, + rutis::host::Key, ); impl LoadsPart { fn new(names: &dim_agent_runtime::Names<'_>, a0: Loads) -> rutis::Result { diff --git a/crates/dim-app-server/tests/transport_flow/shell_input.rs b/crates/dim-app-server/tests/transport_flow/shell_input.rs index 3c4f9d6f02..7d63aae3fc 100644 --- a/crates/dim-app-server/tests/transport_flow/shell_input.rs +++ b/crates/dim-app-server/tests/transport_flow/shell_input.rs @@ -2,7 +2,7 @@ use super::*; use dim_agent_capabilities::{ model_provider::ModelProviderPlugin, shell_input::testing::hold_start, - timeline_tree::TreeCommands, workspace_tools::WorkspaceToolsConfig, + timeline_tree::TimelineTree, workspace_tools::WorkspaceToolsConfig, }; use dim_agent_runtime::BranchLifecycle; use dim_agent_runtime::testing::chain_events; @@ -1026,12 +1026,12 @@ async fn reloading_workspace_tools_answers_the_page_method_with_service_reloadin struct Probe(Arc>>); struct Probed { ctx: rutis::Ctx, - tree: Arc, + tree: Arc, } struct ProbePlugin { probe: Probe, - tree: rutis::host::Key, + tree: rutis::host::Key, } impl ProbePlugin { fn new(names: &dim_agent_runtime::Names<'_>, probe: Probe) -> rutis::Result { @@ -1253,7 +1253,7 @@ impl Shell { ) -> rutis::host::BoxFuture<'static, Result<(), Arc>> { self.restart_plugin("ShellInput") } - fn tree(&self) -> Arc { + fn tree(&self) -> Arc { self.probe.0.lock().unwrap().as_ref().unwrap().tree.clone() } /// A host's idle unload of the Session once its main branch is idle: diff --git a/crates/dim-goal/src/branch.rs b/crates/dim-goal/src/branch.rs index a51beed2e0..186659cbba 100644 --- a/crates/dim-goal/src/branch.rs +++ b/crates/dim-goal/src/branch.rs @@ -5,7 +5,7 @@ use crate::fold::{self, Conclusion, ConclusionAction, Decision, Fold, TurnEnd}; use crate::text::{self, GoalTexts, Live}; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::timeline_tree::TimelineTree; use dim_agent_runtime::{ AgentError, BoxFuture, BranchLifecycle, BranchOptions, Dispatcher, Names, QueryComparison, QueryFilter, QueryOperand, QueryOrder, QueryOrderKey, QueryOutput, QueryPage, QueryPick, @@ -167,7 +167,7 @@ where pub struct GoalBranch { dispatcher: Key, timeline: Key, - tree: Key, + tree: Key, settings: Key, identity: Key, phase: Key, @@ -378,7 +378,7 @@ struct Owner { branch_id: String, timeline: Arc, dispatcher: Arc, - tree: Arc, + tree: Arc, settings: Arc, texts: Arc, phase: Arc, diff --git a/crates/dim-goal/src/read.rs b/crates/dim-goal/src/read.rs index 85e61d07f7..dc9bd9f68e 100644 --- a/crates/dim-goal/src/read.rs +++ b/crates/dim-goal/src/read.rs @@ -3,7 +3,7 @@ use crate::{ fold::Fold, text, }; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::timeline_tree::TimelineTree; use dim_agent_runtime::{ AgentError, BoxFuture, QueryOutput, QueryPick, QueryValue, TimelineQuery, TimelineQueryReply, }; @@ -33,7 +33,7 @@ pub(crate) fn pause_reloaded(fold: &mut Fold) { } pub(crate) async fn current( - tree: &TreeCommands, + tree: &TimelineTree, branch_id: &str, cancel: &CancellationToken, ) -> Result { diff --git a/crates/dim-goal/src/session.rs b/crates/dim-goal/src/session.rs index bff4489001..18e0058638 100644 --- a/crates/dim-goal/src/session.rs +++ b/crates/dim-goal/src/session.rs @@ -10,9 +10,10 @@ use dim_agent_capabilities::{ host::{HostFuture, ToolExecutionContext}, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, reply}, prompt_guide::{GuideEntries, GuideEntry, GuideScope}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, tool_registry::{ToolContribution, ToolHandler, ToolRegistry}, }; +use dim_agent_runtime::BranchDirectoryState::{Ended, Ending, Open}; use dim_agent_runtime::{Names, SessionIdentity, TimelineKey}; use dim_agent_types::{DEFAULT_BRANCH_ID, ToolCall, ToolDefinition, ToolResult, ToolSource}; use rutis::Ctx; @@ -22,7 +23,7 @@ use std::sync::Arc; use tokio_util::sync::CancellationToken; pub struct GoalSession { - tree: Key, + tree: Key, tools: Key, methods: Key, guide: Key, @@ -117,18 +118,17 @@ impl DynPlugin for GoalSession { let id = branch_of(¶ms)?; return tokio::select! { result = async { - match owner.tree.get(&id) { - Ok(_) => { + match owner.tree.directory_entry(&id)?.state { + Open | Ending => { let key = TimelineKey { session_id: owner.identity.session_id.clone(), branch_id: id, }; owner.changes.current(&key).await } - Err(dim_agent_runtime::AgentError::BranchEnded(_)) => { + Ended => { crate::read::current(&owner.tree, &id, &cancel).await } - Err(error) => Err(error), } } => reply(result?), _ = cancel.cancelled() => Err(RpcError::interrupted()), @@ -144,7 +144,7 @@ impl DynPlugin for GoalSession { } struct Owner { - tree: Arc, + tree: Arc, identity: Arc, changes: Changes, } @@ -196,7 +196,11 @@ impl Owner { }; // The branch is checked through the tree first, so a missing or ended // branch answers as it does to every other write. - self.tree.get(&branch).map_err(RpcError::from)?; + if self.tree.directory_entry(&branch)?.state + == dim_agent_runtime::BranchDirectoryState::Ended + { + return Err(dim_agent_runtime::AgentError::BranchEnded(branch).into()); + } let sequence = self .changes .change( diff --git a/crates/dim-goal/tests/goal_product_flow.rs b/crates/dim-goal/tests/goal_product_flow.rs index 645159019d..c72ecb305e 100644 --- a/crates/dim-goal/tests/goal_product_flow.rs +++ b/crates/dim-goal/tests/goal_product_flow.rs @@ -15,7 +15,7 @@ use dim_agent_capabilities::history::summary_message; use dim_agent_capabilities::host::{ HostError, HostFuture, ModelChunk, ModelConnection, ModelDriver, ModelStopReason, ModelStream, }; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::timeline_tree::TimelineTree; use dim_agent_runtime::{BranchOptions, Session}; use dim_agent_types::{ BranchSource, ContextBaselineEntry, ContextCompactData, ContextCompactionData, @@ -1213,7 +1213,7 @@ async fn goal_evaluator_judge_creates_an_evaluator_and_completes_on_done() { let head = session.sequence(child).unwrap(); assert_eq!(session.ended_head(child), Some(head)); let line_events = session - .session_service::() + .session_service::() .unwrap() .page(child.to_owned(), 0, 256, head) .await diff --git a/crates/dim-goal/tests/support/mod.rs b/crates/dim-goal/tests/support/mod.rs index cef9a7996b..d6756bd3f9 100644 --- a/crates/dim-goal/tests/support/mod.rs +++ b/crates/dim-goal/tests/support/mod.rs @@ -627,7 +627,7 @@ pub async fn branch_creates(session: &Session, branch: &str) -> Vec<(u64, Branch /// built has no published events yet. pub async fn first_user_text(session: &Session, branch: &str) -> String { let tree = session - .session_service::() + .session_service::() .unwrap(); let mut last = String::new(); for _ in 0..750 { diff --git a/crates/dim-goal/tests/support/parts.rs b/crates/dim-goal/tests/support/parts.rs index 79c09c5771..12ffa74c95 100644 --- a/crates/dim-goal/tests/support/parts.rs +++ b/crates/dim-goal/tests/support/parts.rs @@ -8,7 +8,7 @@ )] use dim_agent_capabilities::host::ToolExecutionContext; use dim_agent_capabilities::methods::RpcError; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::timeline_tree::TimelineTree; use dim_agent_capabilities::{ defaults, file_storage::FileStoragePlugin, @@ -49,7 +49,7 @@ use tokio_util::sync::CancellationToken; #[derive(Default)] pub struct Probe { timelines: Mutex>>, - commands: Mutex>>, + commands: Mutex>>, dispatchers: Mutex>>, tools: Mutex>>, guide: Mutex>>, @@ -68,13 +68,13 @@ impl Probe { pub fn has(&self, branch: &str) -> bool { self.timelines.lock().unwrap().contains_key(branch) } - pub fn commands(&self, branch: &str) -> Arc { + pub fn commands(&self, branch: &str) -> Arc { self.commands .lock() .unwrap() .get(branch) .cloned() - .unwrap_or_else(|| panic!("branch {branch} has no TreeCommands")) + .unwrap_or_else(|| panic!("branch {branch} has no TimelineTree")) } pub fn dispatcher(&self, branch: &str) -> Arc { self.dispatchers @@ -134,7 +134,7 @@ impl DynPlugin for ProbeSession { struct ProbeBranch { probe: Arc, timeline: Key, - commands: Key, + commands: Key, dispatcher: Key, identity: Key, } diff --git a/crates/dim-image-understanding/src/lib.rs b/crates/dim-image-understanding/src/lib.rs index 0861a28dec..4da5aea580 100644 --- a/crates/dim-image-understanding/src/lib.rs +++ b/crates/dim-image-understanding/src/lib.rs @@ -2,7 +2,7 @@ //! References resolve only within the calling branch's published history. mod history; -use dim_agent_capabilities::timeline_tree::TreeCommands; +use dim_agent_capabilities::timeline_tree::TimelineTree; use dim_agent_capabilities::{ host::{ AuxiliaryErrorCode, AuxiliaryModel, AuxiliaryRequest, HostError, HostFuture, @@ -78,7 +78,7 @@ impl Drop for Flight { } struct ImageUnderstanding { - tree: Arc, + tree: Arc, files: Arc, identity: Arc, targets: Arc, @@ -277,7 +277,7 @@ impl ToolHandler for ImageUnderstanding { /// The Session part contributes `image_understand` and its reference guide. pub struct ImageUnderstandingPlugin { tools: Key, - tree: Key, + tree: Key, files: Key, identity: Key, targets: Key, diff --git a/crates/dim-report/src/draft.rs b/crates/dim-report/src/draft.rs index de83e42219..b7d0f9f96b 100644 --- a/crates/dim-report/src/draft.rs +++ b/crates/dim-report/src/draft.rs @@ -4,7 +4,7 @@ use crate::{ }; use dim_agent_capabilities::{ methods::{Caller, Interruption, MethodCall, MethodDecl, MethodTable, RpcError, params, reply}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::{SessionHold, SessionLifecycle}; use dim_agent_types::ModelId; @@ -30,7 +30,7 @@ const INPUT_LIMIT: usize = 1024; pub(super) struct Session { pub(super) lifecycle: Arc, - pub(super) tree: Arc, + pub(super) tree: Arc, } pub(super) fn register( diff --git a/crates/dim-report/src/evidence.rs b/crates/dim-report/src/evidence.rs index 164951d49b..6160c7f28c 100644 --- a/crates/dim-report/src/evidence.rs +++ b/crates/dim-report/src/evidence.rs @@ -1,7 +1,10 @@ -use dim_agent_capabilities::{methods::RpcError, prompt::Prompt, timeline_tree::TreeCommands}; +use dim_agent_capabilities::{ + methods::RpcError, + timeline_tree::{DirectoryReply, DirectoryRequest, TimelineTree}, +}; use dim_agent_runtime::{ - AgentError, Branch, QueryEvent, QueryFilter, QueryOperand, QueryOutput, QueryPage, QuerySelect, - QuerySpec, TimelineQuery, TimelineQueryScope, + AgentError, BranchDirectoryState, QueryEvent, QueryFilter, QueryOperand, QueryOutput, + QueryPage, QuerySelect, QuerySpec, TimelineQuery, TimelineQueryScope, }; use dim_agent_types::{ AgentEvent, BranchCreateFailedData, ContentBlock, DEFAULT_BRANCH_ID, EventKind, FinishReason, @@ -48,7 +51,7 @@ pub(super) enum ErrorReference { impl ErrorReference { pub(super) async fn capture( self, - tree: Option<&TreeCommands>, + tree: Option<&TimelineTree>, ) -> Result<(Snapshot, Option), RpcError> { let (observed, branch, timeline) = match self { Self::Observed { observed } => ( @@ -73,10 +76,7 @@ impl ErrorReference { return Err(RpcError::invalid("Client version is required")); } let client_version = Some(observed.client_version.clone()); - let default_model = tree - .and_then(|tree| tree.get(&branch).ok()) - .as_ref() - .and_then(adopted_model); + let default_model = tree.and_then(|tree| adopted_model(tree, &branch)); Ok(( Snapshot { error: Some(observed.into()), @@ -188,9 +188,15 @@ pub(super) struct Snapshot { } impl Snapshot { - pub(super) async fn capture_session(tree: &TreeCommands) -> (Self, Option) { - let branch = tree.get(DEFAULT_BRANCH_ID).ok(); - let conversation_through = branch.as_ref().map(Branch::sequence); + pub(super) async fn capture_session(tree: &TimelineTree) -> (Self, Option) { + let conversation_through = match tree.directory(DirectoryRequest { + id: Some(DEFAULT_BRANCH_ID.to_owned()), + }) { + Ok(DirectoryReply::One(entry)) if entry.state != BranchDirectoryState::Ended => { + Some(entry.head) + } + _ => None, + }; let timeline = match conversation_through { Some(through) => read_window(tree, DEFAULT_BRANCH_ID, through, ACTIVITY_KINDS) .await @@ -201,7 +207,7 @@ impl Snapshot { .map_err(|_| Missing::ReadFailed), None => Err(Missing::ReadFailed), }; - let model = branch.as_ref().and_then(adopted_model); + let model = adopted_model(tree, DEFAULT_BRANCH_ID); ( Self { error: None, @@ -223,7 +229,7 @@ pub(super) struct ConversationExcerpt { } pub(super) async fn capture_conversation( - tree: &TreeCommands, + tree: &TimelineTree, through: u64, ) -> Vec { let Ok((events, _)) = read_window( @@ -383,11 +389,8 @@ fn eligible_line(line: &str) -> bool { .any(|pattern| lower.contains(pattern)) } -fn adopted_model(branch: &Branch) -> Option { - let configuration = branch - .service::() - .ok()? - .adopted_configuration(Default::default())?; +fn adopted_model(tree: &TimelineTree, branch_id: &str) -> Option { + let configuration = tree.adopted_configuration(branch_id).ok()??; Some(ModelId { provider_id: configuration.provider_id, model_id: configuration.model_id, @@ -478,7 +481,7 @@ fn project(event: &AgentEvent, include_completed_model: bool) -> Option } async fn read( - tree: &TreeCommands, + tree: &TimelineTree, branch: &str, sequence: u64, operation: Operation, @@ -521,7 +524,7 @@ async fn read( } async fn read_window( - tree: &TreeCommands, + tree: &TimelineTree, branch: &str, through: u64, extra_kinds: &[&str], diff --git a/crates/dim-report/src/lib.rs b/crates/dim-report/src/lib.rs index d956188b05..ca089bd037 100644 --- a/crates/dim-report/src/lib.rs +++ b/crates/dim-report/src/lib.rs @@ -4,7 +4,7 @@ mod draft; mod evidence; mod render; -use dim_agent_capabilities::{methods::SessionMethods, timeline_tree::TreeCommands}; +use dim_agent_capabilities::{methods::SessionMethods, timeline_tree::TimelineTree}; use dim_agent_runtime::{AgentBuilder, Names, PartRegistry, PartScope, SessionLifecycle}; use dim_app_server::methods::ManagementMethods; use rutis::Ctx; @@ -50,7 +50,7 @@ impl DynPlugin for Report { struct ReportSession { methods: Key, lifecycle: Key, - tree: Key, + tree: Key, } impl ReportSession { diff --git a/crates/dim-session-title/src/lib.rs b/crates/dim-session-title/src/lib.rs index dc6bb30a15..dc1aa616a8 100644 --- a/crates/dim-session-title/src/lib.rs +++ b/crates/dim-session-title/src/lib.rs @@ -2,7 +2,7 @@ use dim_agent_capabilities::{ host::{AuxiliaryModel, AuxiliaryRequest}, methods::{Interruption, MethodCall, MethodDecl, RpcError, SessionMethods, reply}, session_broadcast::{SessionBroadcast, SessionBroadcastEvent, session_channel}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::{ AgentBuilder, CollaborationRole, Names, PartRegistry, PartScope, QueryFilter, QueryOperand, @@ -138,7 +138,7 @@ impl DynPlugin for SessionTitlePlugin { struct SessionTitle { settings: Key, - tree: Key, + tree: Key, store: Key, auxiliary: Key, identity: Key, @@ -286,7 +286,7 @@ struct Owner { ctx: Ctx, id: String, settings: Arc, - tree: Arc, + tree: Arc, store: Arc, auxiliary: Arc, state: Mutex, diff --git a/crates/dim-session-title/tests/goal_titles_flow.rs b/crates/dim-session-title/tests/goal_titles_flow.rs index 64af755c99..afbf7bc70b 100644 --- a/crates/dim-session-title/tests/goal_titles_flow.rs +++ b/crates/dim-session-title/tests/goal_titles_flow.rs @@ -4,7 +4,7 @@ use crate::support; use axum::{Router, http::StatusCode, routing::post}; -use dim_agent_capabilities::{adapters::MockTools, defaults, timeline_tree::TreeCommands}; +use dim_agent_capabilities::{adapters::MockTools, defaults, timeline_tree::TimelineTree}; use dim_agent_runtime::{AgentBuilder, AgentConfig, Feature}; use dim_agent_types::{InputBlock, InputMessageData, InputMode}; use dim_app_server::{RunningServer, ServerConfig, serve}; @@ -23,10 +23,10 @@ const PROVIDER: &str = "018ec73f-0000-7000-8000-00000000000a"; /// records with, so a test can write the record shape Goal owns without Goal /// having to produce it. #[derive(Clone, Default)] -struct Probe(Arc>>>); +struct Probe(Arc>>>); struct RecordPlugin { probe: Probe, - tree: rutis::host::Key, + tree: rutis::host::Key, } impl RecordPlugin { fn new(names: &dim_agent_runtime::Names<'_>, probe: Probe) -> rutis::Result { diff --git a/docs/architecture/image-understanding.md b/docs/architecture/image-understanding.md index 4e73cd715c..63a3303553 100644 --- a/docs/architecture/image-understanding.md +++ b/docs/architecture/image-understanding.md @@ -11,7 +11,7 @@ The tool is risk `session`; unknown input fields are rejected. | Service | Purpose | | --- | --- | | `S:ToolRegistry` | Register the tool for this generation. | -| `S:TreeCommands` | Query published inherited images and own-line tool facts. | +| `S:TimelineTree` | Query published inherited images and own-line tool facts. | | `P:SessionFiles` | Materialize immutable image bytes within the Session. | | `S:SessionIdentity` | Scope file reads to the calling Session. | | `P:ModalityTargets` | Resolve `image.understand` on every call, including reuse. | @@ -19,7 +19,7 @@ The tool is risk `session`; unknown input fields are rejected. | `S:GuideEntries` | Explain image references through the input guide. | These are the existing owners' faces, not new services. The tool consumes only -`treeCommands.query` with published chain scope, `sessionFiles.read`, +`timelineTree.query` with published chain scope, `sessionFiles.read`, `modalityTargets.resolve`, `auxiliaryModel.complete`, and the registration routes of ToolRegistry and GuideEntries. See their owner contracts rather than a separate image-specific model or storage interface. diff --git a/docs/architecture/rust-agent/event-driven-flows.md b/docs/architecture/rust-agent/event-driven-flows.md index d1826ba6b1..a4bb941fd8 100644 --- a/docs/architecture/rust-agent/event-driven-flows.md +++ b/docs/architecture/rust-agent/event-driven-flows.md @@ -97,7 +97,7 @@ sequenceDiagram | 项目 | 约定 | | --- | --- | -| TreeTimeline | 新增独立 Timeline 级 rutis 插件,订阅本分支 `branch/create`;依赖 Dispatcher、TimelineTree/TreeCommands | +| TreeTimeline | 新增独立 Timeline 级 rutis 插件,订阅本分支 `branch/create`;依赖 Dispatcher、TimelineTree/TimelineTree | | TimelineTree | 拥有所有分支实例、分支身份预留、构建任务、就绪结果和关闭;不限制分支数量 | | 首条输入 | 两种来源的子分支,首条输入都是一条 Queue 输入,第一个块是 raw 块 ``(宿主来源时为 `source="host"`),写明它是同一 Session 的一条线、由哪条线在其历史的何处开启。工具创建的块内还写目的和该线对父线的协议,没有操作者原文;宿主(RPC `session.branch_create`)创建的块只写身份,创建者的 prompt 作为同一输入的 `user` 原文紧随其后。两者都经输入注入,不另设注入通道 | | 创建准入 | 模型的 `branch` 工具与其他工具一样由 ToolExecutor 经 [Approval](plugins/Permission.md#approval) 准入(risk `session`);宿主 RPC `session.branch_create` 属于外部控制,不经准入,但要求 Session 挂载 `branch`(没有挂载列表即挂载全部工具),否则返回 `Branch tool is not enabled` | diff --git a/docs/architecture/rust-agent/generated/catalog.md b/docs/architecture/rust-agent/generated/catalog.md index a452bb4c93..d321807cfa 100644 --- a/docs/architecture/rust-agent/generated/catalog.md +++ b/docs/architecture/rust-agent/generated/catalog.md @@ -91,14 +91,11 @@ Each catalog name a part of the assembly provides or injects. `data` means share | `sessionMethods` | session | SessionMethods | data | `register` async | | `skillsConfig` | session | SessionScope | data | `get` async | | `submitChecks` | session | InputMethods | internal(hot-path) | — | -| `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) | — | -| `timelineTreeControl` | session | TimelineTree | internal(owner-api) | — | +| `timelineTree` | session | TimelineTree | data | `batchEnd` async, `call` async, `create` async, `defaultBranch` async, `directory` async, `display` async, `end` async, `endWithFinal` async, `info` async, `input` async, `inputs` async, `list` async, `page` async, `pageEnd` async, `query` async, `setDefaultBranch` async | | `toolHost` | session | WorkspaceTools | data | `execute` async | | `toolRegistry` | session | ToolRegistry | data | `register` async | | `toolSourcesView` | session | ToolRegistry | data | `get` sync, `observe` async | -| `treeCommands` | session | TimelineTree | data | `create` async, `defaultBranch` async, `end` async, `info` async, `input` async, `list` async, `page` async, `query` async, `setDefaultBranch` async | | `uiResources` | session | UiResources | data | `publishFile` async, `withdraw` async | | `agentLoop` | branch | Loop | data | `compact` sync, `observe` async, `state` sync, `stopTurn` sync | | `approval` | branch | Approval | data | `decide` async, `pending` async | diff --git a/docs/architecture/rust-agent/generated/local/services.json b/docs/architecture/rust-agent/generated/local/services.json index ed9a20457a..2e264420fa 100644 --- a/docs/architecture/rust-agent/generated/local/services.json +++ b/docs/architecture/rust-agent/generated/local/services.json @@ -97,7 +97,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -119,7 +119,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -145,7 +145,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -1168,7 +1168,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -1190,7 +1190,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -1216,7 +1216,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -1714,7 +1714,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -1752,7 +1752,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -1796,7 +1796,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -2582,7 +2582,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -2616,7 +2616,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -2660,7 +2660,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -2693,7 +2693,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -2705,7 +2705,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -2719,7 +2719,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -2826,7 +2826,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" } @@ -2839,7 +2839,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -2853,7 +2853,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3113,7 +3113,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -3153,7 +3153,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3197,7 +3197,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3270,7 +3270,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -3282,7 +3282,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3296,7 +3296,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3322,7 +3322,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -3345,7 +3345,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3371,7 +3371,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3408,7 +3408,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -3442,7 +3442,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3480,7 +3480,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3652,7 +3652,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" } @@ -3665,7 +3665,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3679,7 +3679,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3699,7 +3699,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" } @@ -3712,7 +3712,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3726,7 +3726,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -3839,7 +3839,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -3851,7 +3851,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 52, "generation": 1 @@ -3865,7 +3865,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 52, "declared": true, "external": true @@ -4064,12 +4064,6 @@ "generation": 1, "removing": false }, - { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", - "provider": 52, - "generation": 1, - "removing": false - }, { "service": "dim_agent_capabilities::tool_registry::ToolRegistry@session", "provider": 54, @@ -4214,6 +4208,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#timelineTree@session", + "provider": 52, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#toolHost@session", "provider": 56, @@ -4231,12 +4231,6 @@ "provider": 54, "generation": 1, "removing": false - }, - { - "service": "dyn rutis_bridge::session::services::HostDispatch#treeCommands@session", - "provider": 52, - "generation": 1, - "removing": false } ] } diff --git a/docs/architecture/rust-agent/generated/local/services.md b/docs/architecture/rust-agent/generated/local/services.md index 7890e94e73..68bbeee62e 100644 --- a/docs/architecture/rust-agent/generated/local/services.md +++ b/docs/architecture/rust-agent/generated/local/services.md @@ -68,7 +68,7 @@ flowchart LR end p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p81 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p81 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p80 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p80 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p80 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p80 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p80 @@ -122,7 +122,7 @@ flowchart LR p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p71 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p71 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p71 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p70 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p70 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p70 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p70 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p70 @@ -151,7 +151,7 @@ flowchart LR p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p66 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p66 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p65 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p65 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p65 p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p65 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p65 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p65 @@ -170,18 +170,18 @@ flowchart LR p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p5 p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p56 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p56 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p56 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p56 p19 -->|"dim_agent_capabilities::workspace_tools::mentions::MentionIndex"| p56 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p56 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p56 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p55 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p55 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p55 p56 -->|"dim_agent_capabilities::host::ToolHost@session"| p54 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p54 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p54 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p54 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p53 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p53 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p53 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p52 p33 -->|"dim_agent_runtime::assembly::TimelineFactory@session"| p52 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p52 @@ -197,19 +197,19 @@ flowchart LR p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p50 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p50 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p50 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p50 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p50 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p50 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p50 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p50 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p48 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p47 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p47 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p47 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p46 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p46 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p46 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p46 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p46 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p45 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p45 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p45 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p45 @@ -219,15 +219,15 @@ flowchart LR p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p43 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p41 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p40 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p40 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p40 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p39 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p39 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p39 p33 -->|"dim_agent_capabilities::hooks::sources::HookSourcesHost@session"| p38 p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p38 p39 -->|"dim_agent_capabilities::input_queue::SubmitChecks@session"| p38 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p38 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p38 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p37 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p37 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p37 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p36 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p36 diff --git a/docs/architecture/rust-agent/generated/local/services.mmd b/docs/architecture/rust-agent/generated/local/services.mmd index 13ea3c9a30..970e9d408f 100644 --- a/docs/architecture/rust-agent/generated/local/services.mmd +++ b/docs/architecture/rust-agent/generated/local/services.mmd @@ -63,7 +63,7 @@ flowchart LR end p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p81 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p81 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p80 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p80 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p80 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p80 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p80 @@ -117,7 +117,7 @@ flowchart LR p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p71 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p71 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p71 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p70 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p70 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p70 p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p70 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p70 @@ -146,7 +146,7 @@ flowchart LR p60 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p66 p60 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p66 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p65 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p65 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p65 p60 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p65 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p65 p60 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p65 @@ -165,18 +165,18 @@ flowchart LR p4 -->|"dim_agent_capabilities::file_storage::FileStorage"| p5 p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p56 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p56 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p56 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p56 p19 -->|"dim_agent_capabilities::workspace_tools::mentions::MentionIndex"| p56 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p56 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p56 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p55 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p55 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p55 p56 -->|"dim_agent_capabilities::host::ToolHost@session"| p54 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p54 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p54 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p54 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p53 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p53 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p53 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p52 p33 -->|"dim_agent_runtime::assembly::TimelineFactory@session"| p52 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p52 @@ -192,19 +192,19 @@ flowchart LR p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p50 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p50 p42 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p50 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p50 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p50 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p50 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p50 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p50 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p48 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p47 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p47 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p47 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p46 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p46 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p46 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p46 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p46 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p45 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p45 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p45 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p45 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p45 p33 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p45 @@ -214,15 +214,15 @@ flowchart LR p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p43 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p41 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p40 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p40 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p40 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p39 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p39 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p39 p33 -->|"dim_agent_capabilities::hooks::sources::HookSourcesHost@session"| p38 p5 -->|"dim_agent_capabilities::host_platform::HostPlatform"| p38 p39 -->|"dim_agent_capabilities::input_queue::SubmitChecks@session"| p38 p33 -->|"dim_agent_runtime::config::SessionConfig@session"| p38 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p38 - p52 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p37 + p52 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p37 p54 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p37 p49 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p36 p33 -->|"dim_agent_runtime::config::SessionIdentity@session"| p36 diff --git a/docs/architecture/rust-agent/generated/services.json b/docs/architecture/rust-agent/generated/services.json index 90f2419d75..cea4a5cce5 100644 --- a/docs/architecture/rust-agent/generated/services.json +++ b/docs/architecture/rust-agent/generated/services.json @@ -50,7 +50,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -72,7 +72,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -98,7 +98,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -959,7 +959,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -981,7 +981,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -1007,7 +1007,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -1326,7 +1326,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -1364,7 +1364,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -1408,7 +1408,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -1853,7 +1853,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" } @@ -1866,7 +1866,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -1880,7 +1880,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -2061,7 +2061,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" } @@ -2074,7 +2074,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -2088,7 +2088,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -2108,7 +2108,7 @@ "status": "Ready" }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" } @@ -2121,7 +2121,7 @@ "generation": 1 }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -2135,7 +2135,7 @@ "external": true }, { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -2150,7 +2150,7 @@ "generation": 1, "injects": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "status": "Ready" }, @@ -2162,7 +2162,7 @@ ], "resolved": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "scope": null, "provider": 31, "generation": 1 @@ -2176,7 +2176,7 @@ ], "reads": [ { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", + "service": "dim_agent_capabilities::timeline_tree::TimelineTree@session", "provider": 31, "declared": true, "external": true @@ -2269,12 +2269,6 @@ "generation": 1, "removing": false }, - { - "service": "dim_agent_capabilities::timeline_tree::TreeCommands@session", - "provider": 31, - "generation": 1, - "removing": false - }, { "service": "dim_agent_capabilities::tool_registry::ToolRegistry@session", "provider": 33, @@ -2401,6 +2395,12 @@ "generation": 1, "removing": false }, + { + "service": "dyn rutis_bridge::session::services::HostDispatch#timelineTree@session", + "provider": 31, + "generation": 1, + "removing": false + }, { "service": "dyn rutis_bridge::session::services::HostDispatch#toolHost@session", "provider": 21, @@ -2418,12 +2418,6 @@ "provider": 33, "generation": 1, "removing": false - }, - { - "service": "dyn rutis_bridge::session::services::HostDispatch#treeCommands@session", - "provider": 31, - "generation": 1, - "removing": false } ] } diff --git a/docs/architecture/rust-agent/generated/services.md b/docs/architecture/rust-agent/generated/services.md index caaf76dbb8..7d696f4a3a 100644 --- a/docs/architecture/rust-agent/generated/services.md +++ b/docs/architecture/rust-agent/generated/services.md @@ -40,7 +40,7 @@ flowchart LR p25["InputMethods"] p24["BranchTool"] end - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p50 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p50 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p50 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p50 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p50 @@ -86,7 +86,7 @@ flowchart LR p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p43 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p43 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p43 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p42 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p42 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p42 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p42 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p42 @@ -106,7 +106,7 @@ flowchart LR p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p40 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p40 p28 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p39 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p39 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p39 p35 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p39 p21 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p39 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p39 @@ -121,7 +121,7 @@ flowchart LR p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p33 p21 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p33 p30 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p32 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p32 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p32 p28 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p31 p21 -->|"dim_agent_runtime::assembly::TimelineFactory@session"| p31 p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p31 @@ -129,9 +129,9 @@ flowchart LR p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p29 p21 -->|"dim_agent_runtime::config::SessionConfig@session"| p27 p30 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p26 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p26 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p26 p30 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p25 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p25 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p24 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p25 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p24 p33 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p24 ``` diff --git a/docs/architecture/rust-agent/generated/services.mmd b/docs/architecture/rust-agent/generated/services.mmd index 3b3e8652ac..a36078d835 100644 --- a/docs/architecture/rust-agent/generated/services.mmd +++ b/docs/architecture/rust-agent/generated/services.mmd @@ -35,7 +35,7 @@ flowchart LR p25["InputMethods"] p24["BranchTool"] end - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p50 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p50 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p50 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p50 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p50 @@ -81,7 +81,7 @@ flowchart LR p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p43 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p43 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p43 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p42 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p42 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p42 p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p42 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p42 @@ -101,7 +101,7 @@ flowchart LR p35 -->|"dim_agent_runtime::core::dispatcher::Dispatcher@main"| p40 p35 -->|"dim_agent_runtime::core::timeline::Timeline@main"| p40 p28 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p39 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p39 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p39 p35 -->|"dim_agent_runtime::config::BranchLifecycle@main"| p39 p21 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p39 p35 -->|"dim_agent_runtime::config::TimelineIdentity@main"| p39 @@ -116,7 +116,7 @@ flowchart LR p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p33 p21 -->|"dim_agent_runtime::config::SessionLifecycle@session"| p33 p30 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p32 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p32 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p32 p28 -->|"dim_agent_capabilities::prompt_guide::GuideEntries@session"| p31 p21 -->|"dim_agent_runtime::assembly::TimelineFactory@session"| p31 p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p31 @@ -124,8 +124,8 @@ flowchart LR p21 -->|"dim_agent_runtime::config::SessionIdentity@session"| p29 p21 -->|"dim_agent_runtime::config::SessionConfig@session"| p27 p30 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p26 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p26 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p26 p30 -->|"dim_agent_capabilities::methods::SessionMethods@session"| p25 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p25 - p31 -->|"dim_agent_capabilities::timeline_tree::TreeCommands@session"| p24 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p25 + p31 -->|"dim_agent_capabilities::timeline_tree::TimelineTree@session"| p24 p33 -->|"dim_agent_capabilities::tool_registry::ToolRegistry@session"| p24 diff --git a/docs/architecture/rust-agent/interrupt.md b/docs/architecture/rust-agent/interrupt.md index 22006b2185..782fe2aa94 100644 --- a/docs/architecture/rust-agent/interrupt.md +++ b/docs/architecture/rust-agent/interrupt.md @@ -60,7 +60,7 @@ sequenceDiagram 控制事件与业务事件共用 Timeline、序号、时间字段和 Dispatcher;没有第二条控制总线。模型历史转换忽略控制事件。 -外部输入经门面 `Branch::input` 写入:门面在边界校验(`InputMessageData::validate`,只拒绝没有内容的输入,失败不落事实),然后追加 input/message,不读 Loop 状态。需要一起生效的多条输入经门面 `Branch::inputs` 一次提交:门面逐条按同一规则校验,批次为空或任一条不合法时不落任何事实;整批是一个原子批次,序号连续、一起发布,按给定顺序返回事件。批次内每条输入都必须带 submission id 且互不相同:都已提交时返回既有事件、不写;只有部分已提交时返回 `PartialSubmission`、不写。分支已关闭或故障时,两者以相同方式失败。`TreeCommands::inputs` 是同一入口的服务包装,仅 Rust 使用。能力产生的自动输入直接追加到本分支 Timeline,由产生方保证合法。InputQueue 只消费,不拦截写入。 +外部输入经门面 `Branch::input` 写入:门面在边界校验(`InputMessageData::validate`,只拒绝没有内容的输入,失败不落事实),然后追加 input/message,不读 Loop 状态。需要一起生效的多条输入经门面 `Branch::inputs` 一次提交:门面逐条按同一规则校验,批次为空或任一条不合法时不落任何事实;整批是一个原子批次,序号连续、一起发布,按给定顺序返回事件。批次内每条输入都必须带 submission id 且互不相同:都已提交时返回既有事件、不写;只有部分已提交时返回 `PartialSubmission`、不写。分支已关闭或故障时,两者以相同方式失败。`TimelineTree::inputs` 是同一入口的服务包装,仅 Rust 使用。能力产生的自动输入直接追加到本分支 Timeline,由产生方保证合法。InputQueue 只消费,不拦截写入。 中断前后的输入按 Timeline 顺序处理,提交与 stop 之间不需要锁: diff --git a/docs/architecture/rust-agent/plugins/BranchTool.md b/docs/architecture/rust-agent/plugins/BranchTool.md index 2dcb10a676..eda70a8f1d 100644 --- a/docs/architecture/rust-agent/plugins/BranchTool.md +++ b/docs/architecture/rust-agent/plugins/BranchTool.md @@ -27,14 +27,14 @@ descendant which is, is refused, because ending a line ends every line below it. | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Create a child, write and read a line, and end a line, per call. | +| `S:TimelineTree` | Create a child, write and read a line, and end a line, per call. | | `S:ToolRegistry` | Register `branch`, until this part unloads. | ## Events and lifetime No events of its own: the tree writes `branch/create`, `branch/start` and `branch/end`; a call writes its result, and `message` and `end` write their -inputs through `TreeCommands.input` (`end` the final message before the +inputs through `TimelineTree.input` (`end` the final message before the command it writes). The input is one action-based object, `{action, prompt?, at?, to?, content?, mode?, branch?, after?, limit?}`, with `action` required and no other properties; risk stays @@ -49,7 +49,7 @@ the calling line's BranchLine are found per call; the registration is withdrawn when this part unloads, and a reloaded TimelineTree reloads it with the services it injects. -`read` first resolves the raw page’s complete-batch endpoint through `TreeCommands.page_end`, then queries only display fields within that range through `TreeCommands.query`. It does not decode model requests, tool-call inputs or tool-result content. Both the raw-event limit and continuation remain batch based. It renders one item each: input, +`read` first resolves the raw page’s complete-batch endpoint through `TimelineTree.page_end`, then queries only display fields within that range through `TimelineTree.query`. It does not decode model requests, tool-call inputs or tool-result content. Both the raw-event limit and continuation remain batch based. It renders one item each: input, text, tool call, tool result and turn end. A tool result whose call lies on an earlier page carries no name: each page is rendered on its own. A tool result with declared effects carries them on its item, absent when the @@ -89,7 +89,7 @@ specific target from its own `step/tool-use` and `step/tool-result` (design [§6 | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:ToolRegistry`、`S:TreeCommands` | +| 注入 | `S:TimelineTree`、`S:ToolRegistry` | | 提供 | — | | 被注入于 | — | @@ -100,10 +100,10 @@ Owner: [timeline_tree.rs](../../../../crates/dim-agent-capabilities/src/timeline Folds the line's own committed facts into its role, the tool lines it opened, the state of its current turn and the line's read cursors, and writes its roster, the parent block, the idle notice, the ended notice and the one status note a -move of the default branch writes on a participant, through `S:TreeCommands`. +move of the default branch writes on a participant, through `S:TimelineTree`. Its role and its parent come from -`TreeCommands.info`, which is filled from the parent's `branch/create` at +`TimelineTree.info`, which is filled from the parent's `branch/create` at creation and at restore. ### Data face @@ -128,7 +128,7 @@ are unchanged. See [service faces](../../../design/service-faces.md). | `B:TimelineIdentity` | The line's own id. | | `B:BranchLifecycle` | Wait for the branch to be Active before writing. | | `S:SessionLifecycle` | Wait for the restored child directory to be published before roster repair. | -| `S:TreeCommands` | `info` for the role and its lines; `head`, the crate-internal `turn_ends` and the parent's new-activity check for the parent block; `default_branch`, the crate-internal move signal and the line's own queue of owed moves for the status note; `input` for every write. | +| `S:TimelineTree` | `info` for the role and its lines; `head`, the crate-internal `turn_ends` and the parent's new-activity check for the parent block; `default_branch`, the crate-internal move signal and the line's own queue of owed moves for the status note; `input` for every write. | | `S:GuideEntries` | Register the roster and message entries on every line, until this part unloads. | ### Events and lifetime @@ -214,7 +214,7 @@ BranchLine mounts at the committed Dispatcher cutoff without reading historical | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:BranchLifecycle`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:SessionLifecycle`、`S:TreeCommands` | +| 注入 | `B:BranchLifecycle`、`B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:GuideEntries`、`S:SessionLifecycle`、`S:TimelineTree` | | 提供 | `B:BranchLine`、`B:dyn HostDispatch#branchLine` | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/InputQueue.md b/docs/architecture/rust-agent/plugins/InputQueue.md index 92c833317e..7f1a2b23fc 100644 --- a/docs/architecture/rust-agent/plugins/InputQueue.md +++ b/docs/architecture/rust-agent/plugins/InputQueue.md @@ -31,7 +31,7 @@ InputQueue decides conditional acceptance in sequence order | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Find the branch named by a call and read its InputQueue. | +| `S:TimelineTree` | Find the branch named by a call and read its InputQueue. | | `S:SessionMethods` | Register `session.input` from `apply`, until this part unloads. | ### Events and lifetime @@ -63,7 +63,7 @@ covers the table and the Rpc entries. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:SessionMethods`、`S:TreeCommands` | +| 注入 | `S:SessionMethods`、`S:TimelineTree` | | 提供 | `S:SubmitChecks` | | 被注入于 | `HooksSession`、`Skills` | @@ -80,7 +80,7 @@ observable input queue. | --- | --- | | `B:Dispatcher` | Hand off restored queue state to live input/turn/interrupt transitions. | | `B:Timeline` | Commit withdrawal commands and atomic application or withdrawal results. | -| `S:TreeCommands` | Reach the validating branch input entry for `submit`. | +| `S:TimelineTree` | Reach the validating branch input entry for `submit`. | | `B:TimelineIdentity` | Identify the branch for `submit`. | ### Data face @@ -174,7 +174,7 @@ are ignored; original facts and native member indexes remain authoritative. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:TreeCommands` | +| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:TimelineTree` | | 提供 | `B:InputQueue`、`B:StateCell`、`B:dyn HostDispatch#inputQueue` | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/LoopMethods.md b/docs/architecture/rust-agent/plugins/LoopMethods.md index 7103a017f6..6f41163870 100644 --- a/docs/architecture/rust-agent/plugins/LoopMethods.md +++ b/docs/architecture/rust-agent/plugins/LoopMethods.md @@ -2,21 +2,21 @@ Loop's Session part registers nonmutating `session.turn.get`. The [read contract](../../../design/input-state-read.md#turn-identity-read) defines its fields. -It declares TreeCommands to query the selected branch and SessionMethods to register the entry. +It declares TimelineTree to query the selected branch and SessionMethods to register the entry. It owns no persistent state, background worker, events or services. Reads end with their request. ## Dependencies | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Query the requested branch at its published cutoff. | +| `S:TimelineTree` | Query the requested branch at its published cutoff. | | `S:SessionMethods` | Register the read entry. | | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:SessionMethods`、`S:TreeCommands` | +| 注入 | `S:SessionMethods`、`S:TimelineTree` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/PromptSuggestion.md b/docs/architecture/rust-agent/plugins/PromptSuggestion.md index 94aa0b3378..01179a070c 100644 --- a/docs/architecture/rust-agent/plugins/PromptSuggestion.md +++ b/docs/architecture/rust-agent/plugins/PromptSuggestion.md @@ -26,7 +26,7 @@ storage, no replay, no `model/usage` event. | `S:SessionConfig` | `interactive` and `collaboration_role`: only a root interactive Session offers. | | `S:SessionLifecycle` | `closing()` clears the offer before the channel ends. | | `S:SessionMethods` | Registers `session.suggestion` from `apply`, until this generation unloads. | -| `S:TreeCommands` | Resolves `main` for the context gate, which reads that branch's `ContextPreparation::usage`. | +| `S:TimelineTree` | Resolves `main` for the context gate, which reads that branch's `ContextPreparation::usage`. | | `P:ModelHost` | Invokes the suggestion request. | `PromptSuggestionSettingsHost`, the `prompt-suggestion` source read at each @@ -54,7 +54,7 @@ conversation. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:ModelHost`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TreeCommands` | +| 注入 | `P:ModelHost`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TimelineTree` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/Questions.md b/docs/architecture/rust-agent/plugins/Questions.md index d563a2c9ae..91b35842af 100644 --- a/docs/architecture/rust-agent/plugins/Questions.md +++ b/docs/architecture/rust-agent/plugins/Questions.md @@ -15,7 +15,7 @@ its `ToolResult`, so Questions writes no events. Design: | `S:SessionConfig` | `interactive`, read on each call: a non-interactive Session gets an error result at once. | | `S:ToolRegistry` | Register `ask_user`, until this part unloads. | | `S:SessionMethods` | Register the `session.question` namespace, until this part unloads. | -| `S:TreeCommands` | Resolve the branch facade for pending-question queries. | +| `S:TimelineTree` | Resolve the branch facade for pending-question queries. | ## Tool @@ -116,7 +116,7 @@ reuses its id. ## Pending reads -`session.question.pending` resolves the branch through `TreeCommands` and queries +`session.question.pending` resolves the branch through `TimelineTree` and queries unsettled `step/tool-call` identities at a fixed published cutoff. It reads the arguments of only the selected `ask_user` array elements and returns up to 128 batches plus a continuation. The result is independent of the transcript window @@ -161,7 +161,7 @@ Rules: [principles](../principles.md) §1 and §4, | Rule | Answer | | --- | --- | -| §1 Bounded Capability | One Session Capability in its own crate, registered by its feature and required by `install` (`require_feature`). Dependencies are `SessionConfig`, `ToolRegistry`, `SessionMethods` and `TreeCommands`, keyed by name for each Session (`names.part`); `apply` registers the unload disposer with `ctx.effect` before it registers the tool and the method, and starts no background work. Rpc and ToolExecutor hold no Questions logic. | +| §1 Bounded Capability | One Session Capability in its own crate, registered by its feature and required by `install` (`require_feature`). Dependencies are `SessionConfig`, `ToolRegistry`, `SessionMethods` and `TimelineTree`, keyed by name for each Session (`names.part`); `apply` registers the unload disposer with `ctx.effect` before it registers the tool and the method, and starts no background work. Rpc and ToolExecutor hold no Questions logic. | | §4.1 Command events for others' state | Not applicable: Questions changes no other module's state. The answer is the output of its own tool; ToolExecutor writes the call's terminal fact. A `respond` that finds nothing writes nothing; its reply says why. | | §4.2 No recall after handoff | The answer is handed to the waiting handler once, under the lock, and is never withdrawn; a later cancel does not replace it. | | §4.3 Before callbacks | Not applicable: no before callback. Rpc checks shape and `sessionId`; Questions checks the answer as the feature owner. | @@ -182,7 +182,7 @@ Rules: [principles](../principles.md) §1 and §4, | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:SessionConfig`、`S:SessionMethods`、`S:ToolRegistry`、`S:TreeCommands` | +| 注入 | `S:SessionConfig`、`S:SessionMethods`、`S:TimelineTree`、`S:ToolRegistry` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/Recall.md b/docs/architecture/rust-agent/plugins/Recall.md index d2a9847c02..5f95cf6df5 100644 --- a/docs/architecture/rust-agent/plugins/Recall.md +++ b/docs/architecture/rust-agent/plugins/Recall.md @@ -29,7 +29,7 @@ this is not a constant-time search guarantee. | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Resolve the calling branch and read its pinned history per call. | +| `S:TimelineTree` | Resolve the calling branch and read its pinned history per call. | | `S:ToolRegistry` | Register `recall`, until this part unloads. | ### Events and lifetime @@ -73,7 +73,7 @@ profile. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:ToolRegistry`、`S:TreeCommands` | +| 注入 | `S:TimelineTree`、`S:ToolRegistry` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/ShellInput.md b/docs/architecture/rust-agent/plugins/ShellInput.md index dfb61caf51..a92332b173 100644 --- a/docs/architecture/rust-agent/plugins/ShellInput.md +++ b/docs/architecture/rust-agent/plugins/ShellInput.md @@ -14,7 +14,7 @@ working directory, through the Session methods `shell.run`, `shell.stop` and | `P:HostPlatform` | Build each command as `exec` does (`build_process_spec`) and spawn its process tree. | | `S:SessionConfig` | The Session working directory. | | `S:GuideEntries` | Register the shell-input marker's guide entry at Session scope, until this plugin unloads. | -| `S:TreeCommands` | Check `branchId` at start; write a recorded run's input on that branch. | +| `S:TimelineTree` | Check `branchId` at start; write a recorded run's input on that branch. | | `S:SessionLifecycle` | `closing()` ends a run without writing; `hold()` keeps the Session from an idle unload while a run is registered. | | `S:SessionIdentity` | Session id of the `shell.run` span, one per started run. | | `S:SessionMethods` | Register the `shell` namespace from `apply`, until this generation unloads. | @@ -111,7 +111,7 @@ branch ids, the `runId` and the outcome (`completed:`, `stopped`, recorded result enters the Timeline, while progress is reply data of one call. - §4 rules 6 and 7: the output reaches the model only through the consumed input; ShellInput uses only public services (`Branch::input` through - `TreeCommands`, `SessionConfig`, `SessionLifecycle`, `SessionIdentity`, + `TimelineTree`, `SessionConfig`, `SessionLifecycle`, `SessionIdentity`, HostPlatform and `sessionMethods`). - ADR 002 D4–D5: no configuration of its own; the exec shell is HostPlatform's. The commands are the user's, not an agent's tool calls, so no Approval or @@ -147,7 +147,7 @@ for the race flows; production builds have no hook. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:HostPlatform`、`S:GuideEntries`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TreeCommands` | +| 注入 | `P:HostPlatform`、`S:GuideEntries`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TimelineTree` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/TimelineTree.md b/docs/architecture/rust-agent/plugins/TimelineTree.md index 29cff9be40..ab33d94da4 100644 --- a/docs/architecture/rust-agent/plugins/TimelineTree.md +++ b/docs/architecture/rust-agent/plugins/TimelineTree.md @@ -12,7 +12,7 @@ only active lines read their opening source. Parent-child adjacency orders the d A Session with one line is on its root without a query; a Session with more reads the root's newest `branch/default` or `session/forked` through the kind index to find the default branch. The App Server only maps these owner-produced properties into its wire fields. -`TreeCommands.page_end` resolves a raw-event page endpoint using atomic-batch metadata through the live Timeline or the ended line’s store. It decodes no event body and has no wire binding. The default branch's answer and its write are `TreeCommands` methods too: `default_branch()` answers the line the Session's conversation is on, restored from the root's newest `branch/default` or `session/forked`, and `set_default_branch(id, source)` admits an open conversation line whose chain is not ending, then writes `branch/default` on the root. Its refusals are `branch_already_default`, `branch_not_selectable` and `branch_target_protected`, and it writes nothing for any of them. A move queues its transition on every participant that is not the root, so a line owes its note from the moment it can take part, and signals every line; each line's own BranchLine drains its queue and writes the one status note its role earns; a load whose latest `branch:line` block disagrees with the tree writes the missing note once, and on the tree's current default branch a block whose text differs from the note this code writes is replaced once. +`TimelineTree.page_end` resolves a raw-event page endpoint using atomic-batch metadata through the live Timeline or the ended line’s store. The cross-language operation is `pageEnd`. The default branch's answer and its write are `TimelineTree` methods too: `default_branch()` answers the line the Session's conversation is on, restored from the root's newest `branch/default` or `session/forked`, and `set_default_branch(id, source)` admits an open conversation line whose chain is not ending, then writes `branch/default` on the root. Its refusals are `branch_already_default`, `branch_not_selectable` and `branch_target_protected`, and it writes nothing for any of them. A move queues its transition on every participant that is not the root, so a line owes its note from the moment it can take part, and signals every line; each line's own BranchLine drains its queue and writes the one status note its role earns; a load whose latest `branch:line` block disagrees with the tree writes the missing note once, and on the tree's current default branch a block whose text differs from the note this code writes is replaced once. ## TimelineTree @@ -23,7 +23,7 @@ block a nested line is told at open, the `info.source` a line was opened with, the one `branch/default` fact on the root, `branch/end` to `branch/ended` on the parent, and the restore rule that leaves an ended line closed ([timeline branches §5–§10](../../../design/timeline-branches.md#10-ending-a-line)). -Provides the TreeCommands/TimelineTreeControl ports. The `branch` tool is +The public Session service is `timelineTree`. Session assembly holds the native tree for startup and teardown. The branch factory is private to that assembly and its tree. The `branch` tool is [BranchTool](BranchTool.md)'s. Its model-facing texts — every child's identity block and the branch markers — with their classes are listed on [timeline branches §12.4](../../../design/timeline-branches.md#124-texts-and-their-classes). @@ -42,7 +42,7 @@ block and the branch markers — with their classes are listed on Produces `branch/create`, `branch/create-failed`, `branch/start`, `branch/resume`, `branch/end`, `branch/ended` and `branch/default`, and initial child input, through tree-owned operations. TreeTimeline consumes creation on the parent and an end on the -ending line. `TreeCommands::end` +ending line. `TimelineTree::end` checks only the target: it exists, it is open, and it is neither the root, the default branch nor an ancestor of it; a line that ended writes nothing and answers `branch_ended`. `info` answers for an @@ -61,7 +61,7 @@ line's facts are, and a failed read fails the create like any other opening failure (branch/create-failed). Each line's node publishes the sequence of its latest `turn/end`, which the line's BranchLine waits on for the parent block (design -[§7.1.1](../../../design/timeline-branches.md#711-the-parent-block-branchparent)). `TreeCommands` also +[§7.1.1](../../../design/timeline-branches.md#711-the-parent-block-branchparent)). `TimelineTree` also answers whether a line's parent has new activity past a sequence with an existence query over operator inputs and tool uses. Opening and end checks select lifecycle fields; inherited parent state selects the last matching @@ -97,7 +97,7 @@ Session close, and closing is not deletion of persisted history. | --- | --- | | 作用域 | Session | | 注入 | `S:GuideEntries`、`S:SessionIdentity`、`S:TimelineFactory`、`S:dyn TimelineStore` | -| 提供 | `S:TimelineTree`、`S:TreeCommands`、`S:dyn HostDispatch#treeCommands`、`S:dyn TimelineTreeControl` | +| 提供 | `S:TimelineTree`、`S:dyn HostDispatch#timelineTree`、`S:dyn TimelineTreeControl` | | 被注入于 | `BranchLine`、`BranchTool`、`InputMethods`、`InputQueue`、`LoopMethods`、`PromptSuggestion`、`Questions`、`Recall`、`ShellInput`、`ToolMethods`、`TreeTimeline`、`Wait`、`WorkspaceTools` | @@ -111,7 +111,7 @@ identity, and releases pending child reservations when the parent unloads. | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Reach the owning Session tree through its command port. | +| `S:TimelineTree` | Reach the owning Session tree through its command port. | | `B:TimelineIdentity` | Identify the parent branch. | | `B:Dispatcher` | Consume creation events. | | `B:Timeline` | Parent history, creation and end settlement location. | @@ -137,7 +137,7 @@ An accepted creation need not survive parent or Session close. | 项 | 值 | | --- | --- | | 作用域 | 分支 | -| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:TreeCommands` | +| 注入 | `B:Dispatcher`、`B:Timeline`、`B:TimelineIdentity`、`S:TimelineTree` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/ToolMethods.md b/docs/architecture/rust-agent/plugins/ToolMethods.md index 6c7856af57..e7bf69376d 100644 --- a/docs/architecture/rust-agent/plugins/ToolMethods.md +++ b/docs/architecture/rust-agent/plugins/ToolMethods.md @@ -8,7 +8,7 @@ ToolExecution's Session part registers `session.tool.get`. The caller-visible co | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Read the addressed branch’s own facts, including ended branches. | +| `S:TimelineTree` | Read the addressed branch’s own facts, including ended branches. | | `S:SessionMethods` | Register and withdraw the admitted read method. | It writes no event, holds no StateCell and starts no task. Each admitted request owns its @@ -18,7 +18,7 @@ query and cancellation; its returned call data is released after serialization. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:SessionMethods`、`S:TreeCommands` | +| 注入 | `S:SessionMethods`、`S:TimelineTree` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/Wait.md b/docs/architecture/rust-agent/plugins/Wait.md index b3f5424f81..4c5ed36619 100644 --- a/docs/architecture/rust-agent/plugins/Wait.md +++ b/docs/architecture/rust-agent/plugins/Wait.md @@ -13,7 +13,7 @@ timeout or an interruption. | Service | Purpose | | --- | --- | -| `S:TreeCommands` | Resolve the calling branch and its Wait service per call. | +| `S:TimelineTree` | Resolve the calling branch and its Wait service per call. | | `S:ToolRegistry` | Register `wait`, until this part unloads. | ### Events and lifetime @@ -65,7 +65,7 @@ input it refused and how the input is wrong. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `S:ToolRegistry`、`S:TreeCommands` | +| 注入 | `S:TimelineTree`、`S:ToolRegistry` | | 提供 | — | | 被注入于 | — | diff --git a/docs/architecture/rust-agent/plugins/WorkspaceTools.md b/docs/architecture/rust-agent/plugins/WorkspaceTools.md index f744aacb50..ada079ac2b 100644 --- a/docs/architecture/rust-agent/plugins/WorkspaceTools.md +++ b/docs/architecture/rust-agent/plugins/WorkspaceTools.md @@ -96,7 +96,7 @@ enter. | Service | Purpose | | --- | --- | | `P:HostPlatform` | Home, shell, environment and process supervision. | -| `S:TreeCommands` | Resolve the calling branch per call. | +| `S:TimelineTree` | Resolve the calling branch per call. | | `S:SessionConfig` | cwd and collaboration role. | | `S:SessionIdentity` | Session-specific output directory. | | `S:SessionMethods` | Register the `session.exec.output` namespace, until this part unloads. | @@ -332,7 +332,7 @@ or missing diffs do not provide a comparison. ### Rule check The read-only [`session.exec.output`](../../../design/background-task-output.md) -method resolves the requested branch through TreeCommands and reads that branch's +method resolves the requested branch through TimelineTree and reads that branch's BackgroundExec capture. It accepts only `{sessionId, branchId, taskId}` and returns `{text}`. It does not open a client-supplied or historical path, append events, acquire Session holds or start background work. Its sibling @@ -470,7 +470,7 @@ empty live preview and unavailable historical captures. | 项 | 值 | | --- | --- | | 作用域 | Session | -| 注入 | `P:HostPlatform`、`P:MentionIndex`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionMethods`、`S:TreeCommands` | +| 注入 | `P:HostPlatform`、`P:MentionIndex`、`S:SessionConfig`、`S:SessionIdentity`、`S:SessionMethods`、`S:TimelineTree` | | 提供 | `S:ToolHost`、`S:dyn HostDispatch#toolHost` | | 被注入于 | `ToolRegistry` | @@ -536,7 +536,7 @@ facts and posts completion notices for ShellSession; that producer retains its l PTY and stop port. See [Shell exec recovery](../../../design/shell-exec-recovery.md) for the profile and generation handoff. -`start` carries an optional task `title` into `exec/started` alongside the unchanged command-derived `description`. `session.exec.pending` returns that same title in each `PendingExec` item. The fact and inventory field are optional strings: missing values deserialize as absent and absent values are omitted on serialization. Existing persisted facts and inventories without a title remain readable. Persistence uses [native format v48](../../../design/appserver/native-storage-format.md#v48-task-titles), a marker-only, one-way upgrade that makes older strict readers reject the store at startup; ShellInput's command facts have no supplied title. This adds no state owner or service face and changes neither execution nor cancellation. The existing `toolHost`, `treeCommands` and `backgroundExec` faces retain their operations. +`start` carries an optional task `title` into `exec/started` alongside the unchanged command-derived `description`. `session.exec.pending` returns that same title in each `PendingExec` item. The fact and inventory field are optional strings: missing values deserialize as absent and absent values are omitted on serialization. Existing persisted facts and inventories without a title remain readable. Persistence uses [native format v48](../../../design/appserver/native-storage-format.md#v48-task-titles), a marker-only, one-way upgrade that makes older strict readers reject the store at startup; ShellInput's command facts have no supplied title. This adds no state owner or service face and changes neither execution nor cancellation. The existing `toolHost`, `timelineTree` and `backgroundExec` faces retain their operations. ### Data face diff --git a/docs/architecture/rust-agent/single-tree.md b/docs/architecture/rust-agent/single-tree.md index f3e4f62169..7c6fc661b5 100644 --- a/docs/architecture/rust-agent/single-tree.md +++ b/docs/architecture/rust-agent/single-tree.md @@ -241,7 +241,7 @@ Feature::new(name).session(..).branch(..) 不持有进程状态的插 | 方向 | 方式 | | --- | --- | | 向上(祖先作用域、进程) | `Deps` 注入 | -| 向下(Session → 分支) | `TreeCommands` / `Branch` | +| 向下(Session → 分支) | `TimelineTree` / `Branch` | | 横向(兄弟分支、其他 Session) | 不可见;经共同祖先的业务接口 | 门面(`Session::session_service::()`、`Session::service::(branch)`、`Branch::service::()`)只读取 `PublicService` 类型,并拒绝未在对应组(`session` 或 `branch`)注册的名字。 diff --git a/docs/architecture/rust-agent/timeline-storage.md b/docs/architecture/rust-agent/timeline-storage.md index 75f1c7a4be..945c72c937 100644 --- a/docs/architecture/rust-agent/timeline-storage.md +++ b/docs/architecture/rust-agent/timeline-storage.md @@ -165,7 +165,7 @@ fork 与 Session 删除在复制连接上分块提交(事件与快照每 256 | 能力重载重建 | 各所有者固定已提交截点后读取必要字段,`Dispatcher::consume` 在该截点之后接续实时事实;Goal 的旧事件收集尚未删除 | | TimelineTree 建分支 | 查询边界控制字段校验截点,祖先段由 Timeline 提供 | | 协作读取 | 取得并持有对端 Session,通过其 query 选择必要字段或正文 | -| App Server 历史、导出 | acquire Session;活动分支走 `Branch::query`,结束分支经 `TreeCommands` 在固定 head 上读存储 | +| App Server 历史、导出 | acquire Session;活动分支走 `Branch::query`,结束分支经 `TimelineTree` 在固定 head 上读存储 | 请求中的事件页面只在操作内持有。没有有效检查点时,完整上下文投影仍需要读取其有效前缀,属性查询不会自动消除这项业务工作。 diff --git a/docs/design/appserver/keyed-blocks.md b/docs/design/appserver/keyed-blocks.md index 162428627e..a32a604ede 100644 --- a/docs/design/appserver/keyed-blocks.md +++ b/docs/design/appserver/keyed-blocks.md @@ -94,7 +94,7 @@ The query does not introduce a persistent index on block keys. Storage still has to inspect candidate input properties and deletion relations; output pagination does not promise constant total query work. -The read follows the two-owner pattern of `session.history`: an open line is read through its Session (`Session::query`, which reads at the published head), an ended line through TimelineTree at its fixed head (`TreeCommands::query`). A line that ends while the call runs answers `branch_ended`; the read is then repeated through the tree at the fixed head. Unlike the `latestTurn` window, the read needs no native store: both owners serve it. +The read follows the two-owner pattern of `session.history`: an open line is read through its Session (`Session::query`, which reads at the published head), an ended line through TimelineTree at its fixed head (`TimelineTree::query`). A line that ends while the call runs answers `branch_ended`; the read is then repeated through the tree at the fixed head. Unlike the `latestTurn` window, the read needs no native store: both owners serve it. ## 4. `through` and the client's live overlay @@ -147,7 +147,7 @@ The two orders differ by construction and are not compared: the baseline lists a | ADR 019 D2 (fixed semantics) | Descending pages ordered by sequence, a short page means exhausted, and the advance is a range, not an offset | | ADR 019 D3 (the query addresses the event contract) | Only kinds and a sequence start are named; no table, column or index | | ADR 019 D4 (indexes are derived or part of the format) | No index is added; the block-key predicate is not expressible in the query and stays out | -| [ADR 020](../../adr/020-timeline-read-convergence.md) D1 (one read, the facades forward it) | Reads go through `Session::query` and `TreeCommands::query`, the same facades `session.history` uses | +| [ADR 020](../../adr/020-timeline-read-convergence.md) D1 (one read, the facades forward it) | Reads go through `Session::query` and `TimelineTree::query`, the same facades `session.history` uses | | [ADR 021](../../adr/021-reads-follow-the-state-owner.md) D3 (a client read requires a live Session) | The call acquires the Session; there is no branch that reads store facts for a Session the process does not hold | | ADR 021 D2 (an ended line is read through the object that owns its end) | An ended line is read through TimelineTree at its fixed head, including after the line ends mid-call | diff --git a/docs/design/appserver/session-history-window.md b/docs/design/appserver/session-history-window.md index 0beda5e4d7..0c5ba16705 100644 --- a/docs/design/appserver/session-history-window.md +++ b/docs/design/appserver/session-history-window.md @@ -22,7 +22,7 @@ and is served by `Connection::history` ([agents.rs](../../../crates/dim-app-server/src/agents.rs)): the call acquires the Session first, so a Session that unloaded is loaded again before the read; a live line pages through the branch's query and the store's - `batch_end`, and a line that has ended goes through `TreeCommands.page` at + `batch_end`, and a line that has ended goes through `TimelineTree.page` at its fixed head. The client protocol has no page read of stored facts for a Session the process does not hold (ADR 021 D3). `after` and `through` must end a batch. `limit` is required and must be positive; the v3 @@ -343,8 +343,8 @@ line is open, the branch's Timeline, which `Connection::history` already has the loaded Session for — each anchor is a kind selection and the page is a range selection, both through `Session::query`, with `Session::batch_end` for the page's ends. An ended line's Timeline is gone, so its anchors and its page are -the tree's read at the fixed head it owns: `TreeCommands::query` for both -directions and `TreeCommands::batch_end` for the page's ends +the tree's read at the fixed head it owns: `TimelineTree::query` for both +directions and `TimelineTree::batch_end` for the page's ends ([ADR 021](../../adr/021-reads-follow-the-state-owner.md) D2, [timeline read ownership §2](../timeline-read-ownership.md#2-owners-and-their-reads)). A line that ends while its window is read is served by the tree: the owner is diff --git a/docs/design/appserver/sessions-service.md b/docs/design/appserver/sessions-service.md index 15f99ce98b..7a65313e64 100644 --- a/docs/design/appserver/sessions-service.md +++ b/docs/design/appserver/sessions-service.md @@ -313,7 +313,7 @@ recovery from it: | Rpc `session.submit`, protocol v3 ([connection/tree.rs](../../../crates/dim-app-server/src/connection/tree.rs)) | An optional UUID | — | | Agents `sessions.input` (§6.2) | A required, non-empty id, `:` by convention | — | | The branch Timeline ([core/timeline.rs](../../../crates/dim-agent-runtime/src/core/timeline.rs)), through `Session::input` and `Session::lookup` (`sessions.input`, `sessions.lookup`, Rpc's `session.submit` and `session.input_lookup`) | — | Accepts each id once per branch; `accepted`, `unknown` or `ambiguous` for lookup | -| Goal parts ([crates/dim-goal](../../../crates/dim-goal)) | `goal:`, through `TreeCommands::input` | Nothing | +| Goal parts ([crates/dim-goal](../../../crates/dim-goal)) | `goal:`, through `TimelineTree::input` | Nothing | | Workflow ([engine.ts](../../../runtime/plugins/workflow/engine.ts)) | `workflow:` for each stage input and report, stored in its run file before the write | A retry, by the same or a replacement generation, resubmits the same id and settles from the reply | | Scheduler ([A.5](../plugins/Scheduler.md#a5-timeline-and-capability-mechanics), [A.6](../plugins/Scheduler.md#a6-run-outcome-delivery); runtime in draft [#317](https://github.com/arcships/dim/pull/317)) | `scheduler:`, one per delivery | An uncertain reply is settled by lookup (A.6); a window is never written twice | | `dimcode` and the Rust TUI ([#312](https://github.com/arcships/dim/pull/312)) | A new UUID for each submit | Nothing yet: an uncertain submit is reported to the user, not looked up | @@ -449,7 +449,7 @@ input the caller wrote. | Item | Rule | | --- | --- | | `through` | With `atLeast`: the published head (`Session::sequence`); below `atLeast`, `future_sequence`. Otherwise the requested `through`, which must not exceed the head (else `future_sequence`), or the head | -| `events` | The branch's own events in `(after, through]`, read by `AgentIndex::history_page`: a loaded line pages through the branch's query and asks the store whether the page's last event ends a batch, a line that has ended reads through `TreeCommands.page` at its fixed head, and the call acquires the Session before any of this, so a Session this process does not hold is loaded rather than read from storage. A line that ends while the page is read is re-read through the tree. `after` (default 0) must end a batch. A page takes `limit` events (1 to 256, default 256) when that many remain, then runs to the end of that batch, so it can exceed `limit`; it never passes `through`. With a published head or an `idle` cutoff as `through`, every batch is whole. The caller pages with `after` set to the last returned sequence until it reaches `through` | +| `events` | The branch's own events in `(after, through]`, read by `AgentIndex::history_page`: a loaded line pages through the branch's query and asks the store whether the page's last event ends a batch, a line that has ended reads through `TimelineTree.page` at its fixed head, and the call acquires the Session before any of this, so a Session this process does not hold is loaded rather than read from storage. A line that ends while the page is read is re-read through the tree. `after` (default 0) must end a batch. A page takes `limit` events (1 to 256, default 256) when that many remain, then runs to the end of that batch, so it can exceed `limit`; it never passes `through`. With a published head or an `idle` cutoff as `through`, every batch is whole. The caller pages with `after` set to the last returned sequence until it reaches `through` | | Form | Every event of the branch as an `AgentEvent` record, in the serde form `session.history` uses for the events it shows. Nothing is filtered, so the last sequence of a page always ends a batch | | Ancestors | Not included. Launched Sessions are read on `main`, which has none. A way to read a child branch's prefix is added when a consumer needs one | | Errors | `rejected` (`after` > `through`, `after` inside a batch, `limit` outside 1 to 256, `atLeast` together with `through`), `future_sequence`, `session_closed`, `branch_missing`, `reloading` | diff --git a/docs/design/appserver/timeline-identity-reads.md b/docs/design/appserver/timeline-identity-reads.md index 9235078c0c..4addcd3858 100644 --- a/docs/design/appserver/timeline-identity-reads.md +++ b/docs/design/appserver/timeline-identity-reads.md @@ -11,7 +11,7 @@ Scope: 原生 Store 的查询执行。关联问题:[#1320](https://github.com/ -> Timeline.query:固定 branch/chain、through 和可见尾部 -> Store.query:执行索引定位与属性投影 -结束分支 -> TreeCommands.query -> Store.query +结束分支 -> TimelineTree.query -> Store.query ``` 插件不读写数据库。Store 不计算业务状态。既有 session 方法仍由各业务 owner 提供。 diff --git a/docs/design/background-task-output.md b/docs/design/background-task-output.md index a4af157573..61443a336b 100644 --- a/docs/design/background-task-output.md +++ b/docs/design/background-task-output.md @@ -71,7 +71,7 @@ WorkspaceTools registers the leaf; Rpc's built-in list and namespace checks are unchanged. Each call resolves the named branch through WorkspaceTools' existing -`TreeCommands`, then asks that branch's BackgroundExec for the active task's +`TimelineTree`, then asks that branch's BackgroundExec for the active task's capture. No Session part retains branch business state. **Task identity.** Every request resolves `taskId` inside the branch it names: diff --git a/docs/design/branch-typescript.md b/docs/design/branch-typescript.md index 2328ee3996..0ef815a7ec 100644 --- a/docs/design/branch-typescript.md +++ b/docs/design/branch-typescript.md @@ -1,7 +1,5 @@ # Branch TypeScript binding -The [target Session tree binding](contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. - Status: implemented for [C5 / #64](https://github.com/arcships/dim/issues/64), the branch portion of [#4](https://github.com/arcships/dim/issues/4), on rutis 0.16.0 `build::Exports` ([arcships/rutis#440](https://github.com/arcships/rutis/issues/440)). Goal (#69) is its consumer; @@ -32,9 +30,9 @@ ordered consumption. | --- | --- | | Branch instance and typed keys | The `branch` group instance, nested in its Session's; the catalog keys each name for it (`Names`) | | Ordered consumption, handler failures, committed reads | Branch `Dispatcher` (over its `Timeline`) | -| Input validation and commitment | `Branch::input`, reached by branch id through Session `TreeCommands` | +| Input validation and commitment | `Branch::input`, reached by branch id through Session `TimelineTree` | | Event writes, including extension events | Branch `Timeline` | -| Branch directory and creation | Session `TreeCommands` / `TimelineTree` | +| Branch directory and creation | Session `TimelineTree` | | Activation and closing | `BranchLifecycle` | | Branch identity | `TimelineIdentity` | @@ -48,7 +46,7 @@ every instance of that group; a row gets the nearest enclosing instance. Its met | Name | Group | Rust type | Methods used by parts | | --- | --- | --- | --- | -| `treeCommands` | `session` | `TreeCommands` | `list()`, `info(id)`, `input(id, input)`, `create(parent, at, options, cancelled)`, `end(id, source)`, `page(id, after, limit)` | +| `timelineTree` | `session` | `TimelineTree` | `list()`, `info(id)`, `input(id, input)`, `create(parent, at, options, cancelled)`, `end(id, source)`, `page(id, after, limit, through)` | | `dispatcher` | `branch` | `Dispatcher` | `consume(name, keys, rebuild, handler)`, `listen(name, keys, handler)`, `committed()`, `notify()`, `sequence()`, `changed()` | | `branchLifecycle` | `branch` | `BranchLifecycle` | `activated()`, `closing()` | | `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()` | @@ -57,7 +55,7 @@ every instance of that group; a row gets the nearest enclosing instance. Its met The data methods were added for this purpose; the existing ones that return handles or take Rust closures stay as they are for Rust callers: -- `TreeCommands::info`, `input`, `create`, `end` and `page` address branches by id and return +- `TimelineTree::info`, `input`, `create`, `end` and `page` address branches by id and return data: `TimelineInfo` (with `source`, and answered for an ended line as well), the committed `AgentEvent`, the new branch's id, and one page of an open or ended line's committed batches. `create` takes the caller's cancellation explicitly (§Cancellation); `end` is @@ -81,7 +79,7 @@ closures stay as they are for Rust callers: and a core domain decodes only through its typed contract, so a malformed core event is rejected before anything is appended. Which owner writes which event is the event's contract, followed by review as for native capabilities, not a check of the export (time bus §2, AGENTS.md rule 11): - a part asks another owner through its command, such as input through `treeCommands.input`. + a part asks another owner through its command, such as input through `timelineTree.input`. C5 first left `Timeline` unexported because the generator cannot filter a type's methods and no part needed to write then (#196); the reads moved to `Dispatcher`. Extension events are the first @@ -148,7 +146,7 @@ same-module snapshots, online metadata, disablement and Pending apply unchanged. 5. Input written from a handler is committed to the Timeline tail and consumed later; its reply proves commitment, not dispatch or adoption. 6. One branch never receives another branch's Dispatcher. Cross-branch communication is input by - id through `treeCommands`, asynchronous. + id through `timelineTree`, asynchronous. ## Open @@ -168,7 +166,7 @@ same-module snapshots, online metadata, disablement and Pending apply unchanged. - In two Sessions sharing the runtime, each `main` part reads its own identity, follows `input/message`, `turn/start` and `turn/end` in commit order, and writes one marked input to its - branch through `treeCommands.input`. Later turn ends do not write again. + branch through `timelineTree.input`. Later turn ends do not write again. - A child in the first Session uses its own Dispatcher, identity and local fold. It writes its own marker despite inheriting its parent's prefix, without writing another marker to the parent. - After a restart, each restored Session's part rebuilds from committed history through a nonzero @@ -201,7 +199,7 @@ Existing C4 tools, methods, observation and Settings flows keep their own `node_ ## Source references - [Dispatcher](../../crates/dim-agent-runtime/src/core/dispatcher.rs), [Timeline](../../crates/dim-agent-runtime/src/core/timeline.rs), [TimelineIdentity and BranchLifecycle](../../crates/dim-agent-runtime/src/config.rs) -- [TimelineTree / TreeCommands](../../crates/dim-agent-capabilities/src/timeline_tree.rs) +- [TimelineTree](../../crates/dim-agent-capabilities/src/timeline_tree.rs) - [InputQueue rebuild](../../crates/dim-agent-capabilities/src/input_queue.rs) - [Declaration generator](../../xtask/check/src/types.rs) and [row placement](../../crates/dim-app-server/src/session_typescript.rs) - [Goal consumer contracts](plugins/Goal.md) diff --git a/docs/design/collaboration-timeline.md b/docs/design/collaboration-timeline.md index 8bce5ee18f..feff2c9e3c 100644 --- a/docs/design/collaboration-timeline.md +++ b/docs/design/collaboration-timeline.md @@ -281,7 +281,7 @@ prompts or implemented as a parallel tree. ## Unfinished delegation read CollaborationSession registers nonmutating `session.collaboration.pending`, using its existing -TreeCommands and SessionMethods dependencies. Parameters: `sessionId`, `branchId`, optional +TimelineTree and SessionMethods dependencies. Parameters: `sessionId`, `branchId`, optional published `through`, optional property-query `after`. Reply: `branchId`, fixed `through`, `requests`, `next`; at most 128 requests per page, ascending start sequence. diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index bfb01a389f..b4df3c1f75 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -18,6 +18,7 @@ | --- | --- | | 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. | +| Branch tool → timelineTree | `endWithFinal(id, source, finalMessage)` commits the final message on the existing branch end fact. | | 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. | @@ -35,7 +36,12 @@ Within a branch, inject its owner face directly. For Session callers the existing `timelineTree` face gains `call({branchId,operation}, cancelled) → operation reply`. TimelineTree resolves the admitted live branch once using its existing branch lookup and -dispatches on that branch instance. The operation is a tagged union of the calls below; +dispatches on that branch instance. The operation is tagged by `kind`. The Context calls and `approval.pending` take only +this tag. `approval.decide` takes `requestId` and `decision`; `inputQueue.withdraw` +takes `command` in the InputQueue owner's existing event shape. The +`prompt.configure` variant takes the owner's `request`. The +`prompt.adoptedConfiguration` variant takes only its tag. + Direct variants use the owner method's arguments, reply and error. The compact RPC variant below returns the existing settled client result. The Session caller gets data. Ended and unknown branches retain their original errors. Calls admitted before close stay with that generation. Tree history, directory and batch input continue to use the tree's diff --git a/docs/design/input-state-read.md b/docs/design/input-state-read.md index 3988d2f65b..3aa3557091 100644 --- a/docs/design/input-state-read.md +++ b/docs/design/input-state-read.md @@ -46,7 +46,7 @@ operator submit-check context remains inside user content, as specified by ### Rule check This extends the existing stateless InputMethods read, not the InputQueue -Capability's decisions. Its dependencies remain the `treeCommands` and +Capability's decisions. Its dependencies remain the `timelineTree` and `sessionMethods` data faces documented by [InputQueue](../architecture/rust-agent/plugins/InputQueue.md#inputmethods). It writes no facts, owns no background work, and retains no state between calls. Principles §4 rules 1–3, 5–6 and 9 require no new mechanism here: there is no @@ -66,7 +66,7 @@ assembly or lifecycle change is required. ## Turn identity read Loop owns `session.turn.get`, registered by its Session part `LoopMethods` with declared -TreeCommands and SessionMethods dependencies. It takes `sessionId`, `branchId`, optional +TimelineTree and SessionMethods dependencies. It takes `sessionId`, `branchId`, optional `through`, optional `turnId` or `inputId`; returns `branchId`, published `through`, and nullable `turn`. `turnId` and `inputId` are mutually exclusive and a supplied identity must be nonempty. A turn has `turnId`, boundary `sequence`, and `ended`; an ended boundary also carries its diff --git a/docs/design/model-configuration.md b/docs/design/model-configuration.md index 95ce604906..c065ca228e 100644 --- a/docs/design/model-configuration.md +++ b/docs/design/model-configuration.md @@ -28,7 +28,7 @@ The Session entry extends Agents' public entry surface. Its factory captures onl configuration and instance identity; services come from `Deps`. Provider remains a per-call lookup. Rpc's generic Session-method dispatch does not implement modes. -`AgentsSession` injects process `AgentIndex` and Session `TreeCommands` and +`AgentsSession` injects process `AgentIndex` and Session `TimelineTree` and `sessionMethods`, registers the namespace `session.agent` with `sessionMethods` from its `apply`, and reads the addressed branch's public Prompt service and published `PromptSnapshot` per call. The Session's method table owns admission, diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 5f2e796e07..4b8d28d0be 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -59,7 +59,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | Process (root) | Host start | Host shutdown | — (process parts provide their own) | | Agent (`agent`) | Agents creates an Agent | Agent close, host shutdown | Host-internal | -| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionIdentity`, `sessionLifecycle`, `treeCommands` | +| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionIdentity`, `sessionLifecycle`, `timelineTree` | | Branch (`branch`) | TimelineTree creates a branch | The branch ends, or its Session closes | `timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity` | Visibility follows the tree, as in [principles §2](../architecture/rust-agent/principles.md): @@ -67,7 +67,7 @@ Visibility follows the tree, as in [principles §2](../architecture/rust-agent/p | Direction | How | | --- | --- | | Up (an enclosing instance, the process) | Inject the service by name | -| Down (Session to branch) | `treeCommands`: input by branch id, branch creation. Never by injecting a branch service | +| Down (Session to branch) | `timelineTree`: input by branch id, branch creation. Never by injecting a branch service | | Sideways (sibling branches, other Sessions) | Not visible. Go through a common ancestor's business service, such as `sessions` | The scope roots, the facades and their publication rules are mechanisms. Each Session and branch is @@ -114,7 +114,7 @@ R4). This table says what each name Dim defines is for. | `workflowFiles` | process | App Server | yes | Marked `#[rutis::service]` | | `eventHub` | process | EventHub | designed, not implemented | A producer declares a source and publishes an event; EventHub delivers it to the Sessions subscribed, through Agents' `sessions` ([EventHub](plugins/EventHub.md)) | | `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` | +| `timelineTree` | `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 | | `sessionConfig` | `session` | SessionScope | yes | `get()`: the creation-time configuration, the snapshot a tool call carries | diff --git a/docs/design/plugins/Collaboration.md b/docs/design/plugins/Collaboration.md index b3349d2991..5ea7e5c866 100644 --- a/docs/design/plugins/Collaboration.md +++ b/docs/design/plugins/Collaboration.md @@ -1,7 +1,5 @@ # Collaboration -The [target Session tree binding](../contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. - Status: Draft ([#551](https://github.com/arcships/dim/issues/551)). Rules: [design rules](../../architecture/rust-agent/principles.md) §1, §4 and §5, [ADR 002](../../adr/002-plugin-scope.md). Scope: Session and branch. Language: Rust. The capability is [collaboration.rs](../../../crates/dim-app-server/src/collaboration.rs). This page owns what Collaboration writes for the model — the two markers it writes, the `agent` tool's coordination text and results, and the guide entries its Session part registers — and the delegation's ownership and lifetime (§6). The delegation mechanism — the facts, the member kinds, the settlement and the member-approval route — is the [overview](../overview.md#56-collaboration-delegation-to-an-external-agent) and [ExternalAgent](ExternalAgent.md)'s, and is not restated here. @@ -60,7 +58,7 @@ Rules: [design rules](../../architecture/rust-agent/principles.md) §1, §3, §4 | §4 rule 4 No business meaning in core | The texts are Collaboration's, and they travel on the declaration, the tool result and the markers; Timeline, Dispatcher and Loop gain no Collaboration branch | | §4 rule 5 Read the whole batch before deciding | Not applicable to this page: the texts are written by the Session part's tool handling and by the branch part's decisions, which follow dispatch order; this page adds no read and changes no decision | | §4 rule 6 Context from handed-over events | A marker reaches the model only as a consumed input, and a tool result only as `step/tool-result`; the page adds no context path | -| §4 rule 7 Public events and services only | The Session part declares the private process `Collaboration` binding and uses the Session's `sessionIdentity`, `sessionConfig`, `treeCommands`, `sessionLifecycle`, `toolRegistry` and `guideEntries`, and reads the deployment's public `selectableModels` port when it provides one (§7); the branch part injects the Session's `CollaborationSession`, `timeline`, `dispatcher`, `timelineIdentity` and `branchLifecycle`. The public `collaborationSession` projection follows the owner contract in §3; nothing reads another plugin's internal state | +| §4 rule 7 Public events and services only | The Session part declares the private process `Collaboration` binding and uses the Session's `sessionIdentity`, `sessionConfig`, `timelineTree`, `sessionLifecycle`, `toolRegistry` and `guideEntries`, and reads the deployment's public `selectableModels` port when it provides one (§7); the branch part injects the Session's `CollaborationSession`, `timeline`, `dispatcher`, `timelineIdentity` and `branchLifecycle`. The public `collaborationSession` projection follows the owner contract in §3; nothing reads another plugin's internal state | | §4 rule 8 Requirements to mechanism owners | None to the runtime, rutis, the loader, the lifecycle or the tool contracts: the entry route is Prompt's existing contract, the declaration is ToolRegistry's, and the inputs are the branch's existing operation. The delegation's requirements go to Agents, SessionStore and the deletion design (§6.5) | | §4 rule 9 Only facts later decisions use | No Timeline fact is added. The two markers are the model-visible results the delegation exists for, and the guide entries are registrations inside Prompt's scope. A delegation's ownership and leader are business records without a Timeline: they go through Agents' and SessionStore's typed writes (§6), not events | | §1 Plugin, part and Capability boundaries | Collaboration stays the App Server capability it is. The Session part registers a declaration, a tool and the entries; the branch part consumes the delegation's facts. No Capability is added and no core module gains business code | diff --git a/docs/design/plugins/ContextCompaction.md b/docs/design/plugins/ContextCompaction.md index fe2dd23d6a..bd90a19aee 100644 --- a/docs/design/plugins/ContextCompaction.md +++ b/docs/design/plugins/ContextCompaction.md @@ -86,8 +86,8 @@ unreleased. | provides S:CompactionStrategyHost(Some(summary strategy)) | | ContextMethods (new part) | | registers session.context with sessionMethods: compact, usage | - | compact -> TreeCommands.get(b).service::().compact() - | usage -> TreeCommands.get(b).service::().usage() + | compact -> TimelineTree.get(b).service::().compact() + | usage -> TimelineTree.get(b).service::().usage() +---------------------------------^---------------------------------+ Rpc (C1) dispatches ---' Branch scope (one Timeline, one Dispatcher) @@ -106,7 +106,7 @@ unreleased. `ProductContextModel` needs no service, so it is a plain Session value. ContextMethods is a separate part from the strategy because branches inject `CompactionStrategyHost`, and its -provider must not depend on `TreeCommands`, which the branch tree provides. +provider must not depend on `TimelineTree`, which the branch tree provides. ### 2.1 Where the manual step lives @@ -506,7 +506,7 @@ pub struct ProductContextModel; // ResolveContextModel, no de pub struct ProductSummaryStrategyPlugin { host: DepKey } // new(names) // Deps = (Keyed, Keyed); provides CompactionStrategyHost pub struct ContextMethodsPlugin; -// Deps = (Keyed, Keyed); methods.register(ctx, "session.context", ..) +// Deps = (Keyed, Keyed); methods.register(ctx, "session.context", ..) // dim-app-server/src/cli.rs, defaults::install_compaction, the one install of every profile // that compacts; the product profile passes ProductContextModel and its product home, @@ -1271,7 +1271,7 @@ A `failed` fact carries the same cost diagnostics as a completed one whenever th | §4 rule 4 (no business meaning in core) | Timeline, Dispatcher and facades unchanged. The digest is composed by ContextPolicy from the declarations on `step/tool-result` facts; no core part names an effect kind. | | §4 rule 5 (atomic batch) | Each new write is one event. | | §4 rule 6 (context only from handed-off events) | The replacement reaches the model only through the projection of a completed fact. Pending inputs are not consumed by a step (AGENTS rule 10). | -| §4 rule 7 (public events and services) | `TreeCommands`, `Branch::service` on `PublicService`s, `ProviderConnectionResolver`, `ModelHost`, `sessionMethods`. | +| §4 rule 7 (public events and services) | `TimelineTree`, `Branch::service` on `PublicService`s, `ProviderConnectionResolver`, `ModelHost`, `sessionMethods`. | | §4 rule 8 (infrastructure unchanged) | Dispatcher, envelope, rutis, loader, Agent assembly and facades unchanged. There is one infrastructure change (#130): snapshot anchoring in Timeline and both stores drops its knowledge of `context/compaction` and keeps only structural checks, and the owner's decode callback receives the anchor event. The requirement comes from Timeline itself: it must not know event content (principles §4 rule 4; Timeline checks only the envelope and reserved core domains, ADR 001). It closes within Timeline's own contract: a snapshot is a cache with a structural anchor. Valid snapshots behave the same, and an invalid one is a cache miss. | | §4 rule 9 (only needed facts) | `context/compact` is read by the Loop's later decisions and on reload. `context/compaction` is used by projection. `context/compaction-start` and the visible result are facts by the maintainer's decision, for two reasons. First, they do not only drive a state machine: they are content that users and other state machines need in order to read the history (a UI connecting at any time must see that a compaction is running or how it ended). Second, reload settlement uses them: an unmatched start means a compaction was in flight. The Loop and ContextPreparation rebuild from start/result pairs, which is more precise than commands alone because it tells a running compaction from a pending one and covers automatic compaction. Usage writes nothing. The completed result's `modelUsage` and `insufficientSpace` are descriptive fields of that required fact: the trigger reads the latest start's `through`, recovery reads the budget, and only a client reads the cost and the mark. The digest adds no fact: it is composed into the existing replacement from declarations the `step/tool-result` facts already carry. The next compaction's roll-forward is why the completed result stores the entries as data (`digest_entries`): that decision reads the field, never the rendered message, and the field is an optional part of a fact the projection already reads. | | ADR 002 D1 (scope) | Window facts, strategy and methods: Session. Command, step and slot: branch, in the Loop. The pinning, the digest, the retention rule and the mark are branch-scope ContextPolicy work: they read the branch's events and compose its record. | diff --git a/docs/design/plugins/Goal-property-queries.md b/docs/design/plugins/Goal-property-queries.md index 6bea3f89ef..74cb44f7ad 100644 --- a/docs/design/plugins/Goal-property-queries.md +++ b/docs/design/plugins/Goal-property-queries.md @@ -8,7 +8,7 @@ Issue: [#1320](https://github.com/arcships/dim/issues/1320)。 ## 1. 加载读取 -固定本分支已发布读头 S。通过声明的 timeline.query,结束分支通过 treeCommands.query,执行两次逻辑查询: +固定本分支已发布读头 S。通过声明的 timeline.query,结束分支通过 timelineTree.query,执行两次逻辑查询: 1. branch/start、session/forked 合并范围中的最后一条位置;不按 kind 分组、不统计历史条数。 2. 本地 opening 至 S 的 goal/state,Last、limit=1,只取 position.sequence 和 data。 diff --git a/docs/design/plugins/Goal-state-read.md b/docs/design/plugins/Goal-state-read.md index 6a70955514..8a9d459408 100644 --- a/docs/design/plugins/Goal-state-read.md +++ b/docs/design/plugins/Goal-state-read.md @@ -76,7 +76,7 @@ Goal branch 通过自己的 timeline 写私有业务事件 type=goal、name=stat 同一次业务变更的模型状态输入、命令 trigger、goal/state 由 Goal branch 用已有 append_batch 原子提交。原状态输入仍紧邻并位于 trigger 前;结构化 goal/state 放在它们之后。没有 trigger 的暂停/完成将模型状态输入与 goal/state 同批提交。 -输入由 Goal 的参数边界校验,submission ID、输入事件 ID 由生产者一次确定;不新增 TreeCommands 写接口,不修改 Branch::inputs。continuation 沿用原输入入口。公开方法仍返回 trigger 的 sequence。提交失败不报告变更成功;无法落盘 paused 时,下一次加载仍按 §4 暂停。 +输入由 Goal 的参数边界校验,submission ID、输入事件 ID 由生产者一次确定;不新增 TimelineTree 写接口,不修改 Branch::inputs。continuation 沿用原输入入口。公开方法仍返回 trigger 的 sequence。提交失败不报告变更成功;无法落盘 paused 时,下一次加载仍按 §4 暂停。 普通事件仅推进内存消费位置。getter 就绪与持久状态事件无关;不得为发布 getter 进度、关闭时刷 source_through 或确认归零而追加事件。 @@ -112,7 +112,7 @@ Store 使用现有类型/位置索引;新格式不从 input/message 文本筛 活 get 等入口固定位置已交付后返回内存目标和状态;零 SQL、零写入,不等待新的持久状态事件。不能再读旧 active 事件覆盖内存 paused。 -无活 owner 的结束分支通过原 TreeCommands.query 读取业务状态并应用结束/重载映射。保持原 GoalRead;through 是本次读/交付覆盖的位置,不是 source_through。历史页表示当时的持久状态,不能代替当前状态 API。 +无活 owner 的结束分支通过原 TimelineTree.query 读取业务状态并应用结束/重载映射。保持原 GoalRead;through 是本次读/交付覆盖的位置,不是 source_through。历史页表示当时的持久状态,不能代替当前状态 API。 新格式普通加载只返回一个 Goal 状态对象,不装载集合节点、不查控制源后缀。本地 opening 定位另需一次位置查询;其他所有者的资源结算不属于 Goal 状态读取。 diff --git a/docs/design/plugins/Goal.md b/docs/design/plugins/Goal.md index f44b2a1eb8..a9fbfcaf2f 100644 --- a/docs/design/plugins/Goal.md +++ b/docs/design/plugins/Goal.md @@ -12,10 +12,10 @@ Goal 属于一条分支。Session 部件注册命令和工具,branch 部件拥 | 部件 | 依赖和职责 | | --- | --- | -| GoalSession | TreeCommands、ToolRegistry、SessionMethods、GuideEntries、SessionIdentity;注册 goal_update、session.goal 和模型 guide。入口按 Session 与 branch 身份路由本插件拥有的 branch 处理句柄,不持有分支业务状态。 | -| GoalBranch | Dispatcher、Timeline、TimelineIdentity、BranchLifecycle、SessionLifecycle、TreeCommands、Settings;拥有状态、决定、业务事件和自己的任务。 | +| GoalSession | TimelineTree、ToolRegistry、SessionMethods、GuideEntries、SessionIdentity;注册 goal_update、session.goal 和模型 guide。入口按 Session 与 branch 身份路由本插件拥有的 branch 处理句柄,不持有分支业务状态。 | +| GoalBranch | Dispatcher、Timeline、TimelineIdentity、BranchLifecycle、SessionLifecycle、TimelineTree、Settings;拥有状态、决定、业务事件和自己的任务。 | -分支内写业务状态用声明的 timeline;普通 continuation 和评估分支操作沿用原输入/TreeCommands 服务。没有新公共分支服务、Store 依赖或恢复协调模块。部件在 apply 注册清理及服务,实际消费和任务遵守 activated/closing;关闭完成必要终态后才移除服务。 +分支内写业务状态用声明的 timeline;普通 continuation 和评估分支操作沿用原输入/TimelineTree 服务。没有新公共分支服务、Store 依赖或恢复协调模块。部件在 apply 注册清理及服务,实际消费和任务遵守 activated/closing;关闭完成必要终态后才移除服务。 maxContinuations 仍是 Settings 的 goal 源中的可选业务字段,范围 1..=1000,缺失表示无限额。每次决定通过 Settings 读取;不增加默认限额、缓存或重载配置机制。 diff --git a/docs/design/plugins/ImageUnderstanding.md b/docs/design/plugins/ImageUnderstanding.md index 295cf84d4f..cb8d81fce7 100644 --- a/docs/design/plugins/ImageUnderstanding.md +++ b/docs/design/plugins/ImageUnderstanding.md @@ -170,8 +170,8 @@ owner changes its own document. **M4 TimelineTree: published branch-chain queries for Session parts.** - **Problem.** A Session tool needs the calling branch's inherited, published history, not just its own line (§3). -- **Existing mechanisms, and why they fail.** `treeCommands.query` reads only one line; `Branch::query` supports inheritance but obtaining a branch through the Rust-only `get` method bypasses the data face. Reassembling ancestry in the consumer would duplicate the owner's range and continuation rules. -- **Needed capability.** Extend the existing `treeCommands.query` operation with published chain scope, using the shared property-query shape. TimelineTree owns the range, ancestor cuts, ended-line reads and continuation, as specified on its [owner page](../../architecture/rust-agent/plugins/TimelineTree.md). The tool consumes this operation, not a branch handle or storage internals. +- **Existing mechanisms, and why they fail.** `timelineTree.query` reads only one line; `Branch::query` supports inheritance but obtaining a branch through the Rust-only `get` method bypasses the data face. Reassembling ancestry in the consumer would duplicate the owner's range and continuation rules. +- **Needed capability.** Extend the existing `timelineTree.query` operation with published chain scope, using the shared property-query shape. TimelineTree owns the range, ancestor cuts, ended-line reads and continuation, as specified on its [owner page](../../architecture/rust-agent/plugins/TimelineTree.md). The tool consumes this operation, not a branch handle or storage internals. - **Ordering impact.** Read-only, fixed published cutoff; no change to sequences, batches, interruption, reload or event formats. Own-line queries retain their existing behavior. - **Owner and issue.** TimelineTree, [#1624](https://github.com/arcships/dim/issues/1624). @@ -209,7 +209,7 @@ Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [A | §4.4 No business meaning in core | No core change: the tool is registered through `toolRegistry`, and the reference rule stays in ModelProvider as Attachments already owns it. | | §4.5 Atomic batches | The design writes no event itself; Loop's ordinary tool-call batch covers the call and its result. | | §4.6 Context only from handed-off events | The answer reaches the model only as a tool result; no injection during request preparation. | -| §4.7 Public events and services only | The part uses `toolRegistry`, `treeCommands.query` with published chain scope (§5 M4) to resolve a reference, the declared `auxiliaryModel` host, `sessionFiles` to read stored image bytes, `guideEntries` for its input-guide entry, and Modality's M1 read. | +| §4.7 Public events and services only | The part uses `toolRegistry`, `timelineTree.query` with published chain scope (§5 M4) to resolve a reference, the declared `auxiliaryModel` host, `sessionFiles` to read stored image bytes, `guideEntries` for its input-guide entry, and Modality's M1 read. | | §4.8 Requirements to mechanism owners | §5, M1–M4. The existing TimelineTree query gains published chain scope; no new runtime or rutis mechanism. | | §4.9 Only facts later decisions use enter the Timeline | Only the ordinary tool facts enter; the digest index is derived and discarded. | | §1 Capability and App Server boundary | A Session Capability in its own crate; the App Server only installs it. | diff --git a/docs/design/plugins/ModelRecovery.md b/docs/design/plugins/ModelRecovery.md index a3a8204f2c..44c1ccff92 100644 --- a/docs/design/plugins/ModelRecovery.md +++ b/docs/design/plugins/ModelRecovery.md @@ -35,7 +35,7 @@ flowchart LR LP["Loop"] MR["ModelRecovery: disposer"]:::new TL["Timeline + Dispatcher"] - TC["TreeCommands: Branch::input"] + TC["TimelineTree: Branch::input"] IQ["InputQueue"] end MP -- "step/model-output-end (failed)" --> LP @@ -51,7 +51,7 @@ flowchart LR | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | -| `ModelRecovery` branch part | Branch | `B:AgentLoop` (the disposer port), `B:Timeline` (committed-fact query), `S:TreeCommands` (the handover input) | A disposer registration; no service | +| `ModelRecovery` branch part | Branch | `B:AgentLoop` (the disposer port), `B:Timeline` (committed-fact query), `S:TimelineTree` (the handover input) | A disposer registration; no service | The Loop's port admits one disposer on a branch, and a second registration fails. Registration is an effect of the part, so an unload withdraws it; the diff --git a/docs/design/plugins/PromptSuggestion.md b/docs/design/plugins/PromptSuggestion.md index c6a040a3ec..20510b0d35 100644 --- a/docs/design/plugins/PromptSuggestion.md +++ b/docs/design/plugins/PromptSuggestion.md @@ -13,7 +13,7 @@ The feature is one plugin with two parts, split by the owner of their state: | Part | Scope | State it owns | Depends on | Provides | | --- | --- | --- | --- | --- | | `PromptSuggestionSettings` | Process (App Server) | The `prompt-suggestion` Settings source | `P:Settings` | `P:PromptSuggestionSettingsHost` | -| `PromptSuggestion` | Session | The latest completed turn's request and content, the offer in flight, the shown offer, the unused count | `S:SessionIdentity`, `S:SessionConfig`, `S:SessionLifecycle`, `S:SessionMethods`, `S:TreeCommands`, `P:ModelHost`, `P:ProviderConnectionResolver` in the product's process-model mode, and, when the assembly binds it, `P:PromptSuggestionSettingsHost` | `session.suggestion` with `sessionMethods` | +| `PromptSuggestion` | Session | The latest completed turn's request and content, the offer in flight, the shown offer, the unused count | `S:SessionIdentity`, `S:SessionConfig`, `S:SessionLifecycle`, `S:SessionMethods`, `S:TimelineTree`, `P:ModelHost`, `P:ProviderConnectionResolver` in the product's process-model mode, and, when the assembly binds it, `P:PromptSuggestionSettingsHost` | `session.suggestion` with `sessionMethods` | The process part declares the source where every other business source of this daemon lives, next to `ExecutionSettings` and `ModelLog`; the source is process state shared by Sessions, so it is not a Session part ([ADR 002 D1](../../adr/002-plugin-scope.md)). The source itself is read by the Session part through the host port at each decision ([ADR 002 D4](../../adr/002-plugin-scope.md)): changing `enabled` or `maxChars` never reloads a part. @@ -302,7 +302,7 @@ None ([principles §4 rule 8](../../architecture/rust-agent/principles.md)). The | `ModelHost` | `invoke` | async | `{request, connection, cancel}` | A stream of `ModelChunk` | | `ProviderConnectionResolver` | `resolve` | async | `{request, cancel}` | `{connection, failurePolicy, recovery}` (process models only; a local model sends `ModelConnection::Local`, and its assembly installs the part with `install_local` instead of `install`) | | `SessionMethods` | `register` | sync | namespace `session.suggestion`, two declarations | The registrations end with this part's generation | -| `TreeCommands` | `get` | sync | `main` | The branch, whose `ContextPreparation::usage` the context gate reads | +| `TimelineTree` | `get` | sync | `main` | The branch, whose `ContextPreparation::usage` the context gate reads | | Session broadcast | record on `session/{sessionId}` | bus event | - | `Event {branchId, event}`, `Notice`, `Fence`, `Closed` | | Settings source `prompt-suggestion` | `read` | async | user scope | `{enabled, maxChars}` | diff --git a/docs/design/plugins/Pursuit.md b/docs/design/plugins/Pursuit.md index 85138351e5..ed9f284112 100644 --- a/docs/design/plugins/Pursuit.md +++ b/docs/design/plugins/Pursuit.md @@ -14,7 +14,7 @@ Requirement ([feature list](../../feature-list.md), Agent behavior): keep workin | P2 | The judge is chosen per goal by `set`, recorded on the `set` block | It is the user's intent for that goal, a Timeline fact | | P3 | Evaluate when the worker's completion report stops Goal | That is the only point where the worker decides the goal is done. A worker's `blocked` stands (it needs the user); a limit, or the user's own interrupt or pause, is not a completion and starts nothing | | P4 | Under the evaluator judge the worker's `completed` is a request; the status stays `active` | Only the evaluator completes the goal. The current execution records a completion request without changing the business status; see [Goal A16](Goal.md#appendix-e-assumptions) | -| P5 | The evaluator is a child branch cut at that `turn/end` | It sees what was done and why, runs under the same policy, and is an ordinary branch created with `treeCommands.create` | +| P5 | The evaluator is a child branch cut at that `turn/end` | It sees what was done and why, runs under the same policy, and is an ordinary branch created with `timelineTree.create` | | P6 | The evaluator writes its conclusion to the working branch as input; Goal there decides | A branch folds only its own events; cross-branch communication is input by id ([plugin contract §5.2](../plugin-contract.md#52-consuming-facts)), and a line reads the line it was cut from through a tool result ([Timeline branches](../timeline-branches.md) §6). Callers write, owners decide | ## 2. User flow @@ -53,7 +53,7 @@ Every decision is taken as Goal takes its own: by the Dispatcher handler from co | Consumed event | Condition | Action | | --- | --- | --- | -| `turn/end` N | Goal's C1–C4 hold (active goal, not interrupted, turn `completed`, latest and undecided), the judge is `evaluator`, and the turn contains a worker `completed` block | Instead of Goal's continuation decision: `treeCommands.create(B, N, {prompt, source: {kind: "host", operation_id: "goal:evaluate:N"}}, cancelled)`. Goal's `decided` counts that `branch/create` as `N`'s decision (§3), within this execution; reload pauses the goal and never creates the old evaluator again | +| `turn/end` N | Goal's C1–C4 hold (active goal, not interrupted, turn `completed`, latest and undecided), the judge is `evaluator`, and the turn contains a worker `completed` block | Instead of Goal's continuation decision: `timelineTree.create(B, N, {prompt, source: {kind: "host", operation_id: "goal:evaluate:N"}}, cancelled)`. Goal's `decided` counts that `branch/create` as `N`'s decision (§3), within this execution; reload pauses the goal and never creates the old evaluator again | | `branch/create-failed` for `goal:evaluate:N`, or `create` throws before any `branch/create` for `N` committed | `N` is still current | Pause (`evaluation_failed`), marked `after="N"` as Goal's pauses are; the first of the two to write it supersedes `N` for the other. A creation that committed records its own outcome (a child or `branch/create-failed`), so that fact decides it, and a throw because the task was cancelled writes nothing | | Conclusion input for evaluation `N` | The first conclusion for `N`, from the branch named by the `branch/create` for `goal:evaluate:N`, and `N` is still current: no newer change follows `N` — a `set`, `edit`, `clear`, `pause` or `resume` trigger, a new worker `completed`, or an old keyed block. A model-facing `goal:state` input is not another completion request. The current business state and in-memory evaluation identity determine whether the conclusion is still eligible; paused stops it | `done`: `completed` by the evaluator. `blocked`: `blocked` by the evaluator. `continue`: Goal's continuation decision ([Goal A.4](Goal.md#a4-continuation-decision) C1, C5 and C6, C6 only when `maxContinuations` is set, and the background wait), then a continuation with the Pursuit text, or pause (`limit`); as at any turn end, a pending driving input means no continuation (C5), and a background task still open means no decision yet: the current execution keeps the conclusion in memory, and the cancelled end that closes the last open task may take it while that execution remains running. `failed`: pause (`evaluation_failed`) | @@ -65,7 +65,7 @@ The evaluator identity comes from the line source and parent ([§13](#13-ending- | Consumed event | Condition | Action | | --- | --- | --- | -| `turn/end` M, status `completed` | The reply has a conclusion | Write it to `B` with `treeCommands.input` (Append), marked `evaluation="N" evaluator="E"` | +| `turn/end` M, status `completed` | The reply has a conclusion | Write it to `B` with `timelineTree.input` (Append), marked `evaluation="N" evaluator="E"` | | `turn/end` M, status `completed` | No conclusion, and `M` is the evaluator's first turn end | Write a follow-up (Queue, `after="M"`) on the evaluator branch asking it to end with one of the three conclusions | | `turn/end` M, status `completed` | No conclusion, and `M` is not its first turn end (it was already asked once) | Write `continue` to `B` with the whole reply, truncated to 4000 characters, as the feedback | | `turn/end` M, status `failed` or `cancelled` | — | Write `failed` to `B` | @@ -173,15 +173,15 @@ Evaluator identity and branch ending use the existing [Timeline branches](../tim | # | Change | | --- | --- | -| E1 | **Recognition from the line's source.** Goal on a line takes the evaluator role when `treeCommands.info(own id)` has `source = {kind: "host", operation_id: "goal:evaluate:N"}` and `parent = B`. It no longer reads the prompt's first line. The prompt keeps its `` first line, for the model only (§5) | -| E2 | **Goal ends its evaluator.** Evaluation `N` is settled on `B` once its conclusion or failure is decided (§4.1), or once a later goal change supersedes `N`. When it is settled, Goal on `B` ends `E` with `treeCommands.end(E, {kind: "host", operation_id: "goal:evaluate:N"})`, through an owned task that rechecks first. If the current execution has consumed the terminal fact for E, Goal does nothing. This is cleanup of work owned by the current execution, not a requirement to load historical evaluator relations or replay old decisions | +| E1 | **Recognition from the line's source.** Goal on a line takes the evaluator role when `timelineTree.info(own id)` has `source = {kind: "host", operation_id: "goal:evaluate:N"}` and `parent = B`. It no longer reads the prompt's first line. The prompt keeps its `` first line, for the model only (§5) | +| E2 | **Goal ends its evaluator.** Evaluation `N` is settled on `B` once its conclusion or failure is decided (§4.1), or once a later goal change supersedes `N`. When it is settled, Goal on `B` ends `E` with `timelineTree.end(E, {kind: "host", operation_id: "goal:evaluate:N"})`, through an owned task that rechecks first. If the current execution has consumed the terminal fact for E, Goal does nothing. This is cleanup of work owned by the current execution, not a requirement to load historical evaluator relations or replay old decisions | | E3 | **An outside end before the conclusion is `failed`.** A `branch/ended` for `E` on `B` that comes before `E`'s conclusion, while `N` is current, is decided as `failed`: pause (`evaluation_failed`), as in §4.1 | Interfaces: - Goal's branch part adds the Dispatcher key `branch/ended`. - Goal's branch part uses sessionLifecycle and branchLifecycle: new work waits for publication, and current owned work is cancelled/settled before closing. Loading does not start historical evaluator work. -- Goal's branch part uses `TreeCommands`'s `create`, `input`, `end` and `info` through their Rust exports, and reads `TimelineInfo.source` to recognize an evaluator line. +- Goal's branch part uses `TimelineTree`'s `create`, `input`, `end` and `info` through their Rust exports, and reads `TimelineInfo.source` to recognize an evaluator line. Acceptance, with a fake model, in the crate's flow tests under `crates/dim-goal/tests`: diff --git a/docs/design/plugins/Questions.md b/docs/design/plugins/Questions.md index 398bc9c353..9af9f47f1d 100644 --- a/docs/design/plugins/Questions.md +++ b/docs/design/plugins/Questions.md @@ -47,7 +47,7 @@ Contracts are given in language-neutral form; the Rust form is [Appendix G](#app | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | -| `QuestionsPlugin` | Session | `S:SessionConfig`, `S:ToolRegistry`, `S:SessionMethods`, `S:TreeCommands` | Registers `ask_user` with `toolRegistry` and `session.question` (`session.question.respond`, `session.question.pending`) with `sessionMethods` | +| `QuestionsPlugin` | Session | `S:SessionConfig`, `S:ToolRegistry`, `S:SessionMethods`, `S:TimelineTree` | Registers `ask_user` with `toolRegistry` and `session.question` (`session.question.respond`, `session.question.pending`) with `sessionMethods` | Installation: the part is installed whenever the plugin is enabled; installation never reads `SessionConfig.interactive` ([session access §9.4](../contracts/session-access.md#94-optional-parts-per-enabled-plugin)), so every Session that mounts `ask_user` declares it whatever its `interactive` (a Session without a mount list mounts it, one with a list when the list names it), and a fork keeps the same tool set and prompt prefix. @@ -348,7 +348,7 @@ None. Every mechanism Questions uses is implemented (§1). Considered and not ra | Element | Result | | --- | --- | | `question/*` events, Questions replay, dynamic events | Removed in #178 (§2) | -| Branch part `questions`, its Dispatcher subscription on `step/tool-result`, retained answered/cancelled entries, `question_already_answered` and `question_cancelled` | Removed in this revision. The handler that waits already belongs to the Session part, and branch close (through its interrupt) and reload reach it through ToolExecutor's cancel token, so a branch part only added a lookup through `TreeCommands` and a second lifetime. Retained entries only let a second client tell "answered elsewhere" from "not ready" before `step/tool-result`; without them both get `question_not_pending`, and the prompt still closes correctly at `step/tool-result`. Rechecked: answer, decline, interrupt, reload, close, restart and two clients (Appendix B) keep their outcomes | +| Branch part `questions`, its Dispatcher subscription on `step/tool-result`, retained answered/cancelled entries, `question_already_answered` and `question_cancelled` | Removed in this revision. The handler that waits already belongs to the Session part, and branch close (through its interrupt) and reload reach it through ToolExecutor's cancel token, so a branch part only added a lookup through `TimelineTree` and a second lifetime. Retained entries only let a second client tell "answered elsewhere" from "not ready" before `step/tool-result`; without them both get `question_not_pending`, and the prompt still closes correctly at `step/tool-result`. Rechecked: answer, decline, interrupt, reload, close, restart and two clients (Appendix B) keep their outcomes | | `branchId` default `"main"` in `respond` | Removed: a client always has the branch from `session.event`; a default only invites answering the wrong branch | | Former F2 (approvals in non-interactive Sessions) | Removed: Approval's, decided in [CLI commands](../cli-commands.md#execution-and-jsonl-output) and [sessions-service D10](../appserver/sessions-service.md) | | Mutex table instead of `StateCell` | Kept: entries are live I/O waits, not state rebuildable from the Timeline | diff --git a/docs/design/plugins/Recall.md b/docs/design/plugins/Recall.md index 3bc0c90dfe..9fb7506d87 100644 --- a/docs/design/plugins/Recall.md +++ b/docs/design/plugins/Recall.md @@ -87,7 +87,7 @@ Everything is computed from that one head, so a call never mixes two heads. An ancestor is still read to its cut. The pattern is the one `wait` already uses ([wait.rs](../../../crates/dim-agent-capabilities/src/wait.rs)): a Session tool that resolves the calling branch from `ToolExecutionContext.branch_id` through -`TreeCommands`. Recall does not apply compaction: it walks the whole pinned history the +`TimelineTree`. Recall does not apply compaction: it walks the whole pinned history the pages reach. Search has a separate candidate and verification path. It first selects origin @@ -124,7 +124,6 @@ accordingly. On a line while it is ending, `branch/end` is not told and the `end` call is told like any other call. - Candidate queries return `position`, `kind`, `id` and the identities required by §3.2, not the body. For input things the candidate is `input/consumed`: its position is the ordering anchor and `input_id` names the origin. For the other things the @@ -582,7 +581,7 @@ configured. Rejected: | Principles §4 rule 4 (no business meaning in core) | No core change. Recall itself also knows no producer: it tells runtime blocks by the tag and attributes of their text and by `key`/`retire`, so the Prompt, Goal and background-notification blocks need no case of their own. | | Principles §4 rule 5 (atomic batch) | Not applicable: it writes nothing; its read is pinned to one published head. | | Principles §4 rule 6 (context from handed-over events) | It selects with the context-assembly rules and adds only the public experience events it names; every other kind is not told. Its result reaches the model only as a tool result. | -| Principles §4 rule 7 (public events and services) | It uses `TreeCommands`, the Branch facade and public events and their join ids. It reads no plugin's internal state. | +| Principles §4 rule 7 (public events and services) | It uses `TimelineTree`, the Branch facade and public events and their join ids. It reads no plugin's internal state. | | Principles §4 rule 8 (infrastructure unchanged) | Timeline, Dispatcher, the envelope, assembly, the facades and the projection types are unchanged. | | Principles §4 rule 9 (only facts later decisions use) | No new event. | | Principles §1 (Capability and App Server boundary) | A Session Capability in `dim-agent-capabilities`, installed by `defaults::install_local_execution` beside `wait`, so the App Server's product and `--models` profiles both have it. | @@ -702,7 +701,7 @@ in `crates/dim-app-server/tests` that finds `recall` in the tool table of both t ## 15. Ready Every rule and cited contract above was rechecked against main at -`bf95eaf6` (events, Branch facade, `TreeCommands`, `wait`, ToolExecutor cancellation, the block +`bf95eaf6` (events, Branch facade, `TimelineTree`, `wait`, ToolExecutor cancellation, the block producers, `session/forked`, ADR 001 of 2026-10-20). Approved as Ready by the maintainer (2026-10-21), with these decisions: @@ -730,7 +729,7 @@ pub fn feature() -> Feature { Feature::new("Recall").session("Recall", |names| Ok(Box::new(RecallPlugin::new(names)?))) } pub struct RecallPlugin { - tree: Key, + tree: Key, tools: Key, } impl RecallPlugin { @@ -740,7 +739,7 @@ impl DynPlugin for RecallPlugin { // injects: [tree.erase(), tools.erase()] // apply: tools.register(ctx, ToolContribution { definition, handler: RecallTool(tree) }) } -struct RecallTool(Arc); +struct RecallTool(Arc); impl ToolHandler for RecallTool { /* §3–§6 */ } // dim-agent-capabilities/src/defaults.rs, install_local_execution, beside wait::install diff --git a/docs/design/plugins/Report.md b/docs/design/plugins/Report.md index 456b8e3be9..2da7cbb335 100644 --- a/docs/design/plugins/Report.md +++ b/docs/design/plugins/Report.md @@ -1,7 +1,5 @@ # Report plugin -The [target Session tree binding](../contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. - Status: Draft. Scope: Session reports and a process entry for errors without a readable Session. Issue: [#1319](https://github.com/arcships/dim/issues/1319). @@ -130,7 +128,7 @@ The client keeps the completed preview and bytes when a share action fails. The ## 8. Dependencies and rule check -The Session part declares the `sessionMethods`, `sessionLifecycle` and `treeCommands` data faces. It uses the [public branch read surface](../timeline-read-ownership.md#8-binding-appendix) for the published cutoff and adopted model selection. The process part declares the `managementMethods` and `partRegistry` data faces. Both use caller origin and the process build metadata already available to App Server. With no approved typed diagnostics source, build and platform information are sufficient process evidence. Model-assisted generation depends on the model owners in §7. App Server composes the parts as one feature. [Service catalog](../../architecture/rust-agent/generated/catalog.md). +The Session part declares the `sessionMethods`, `sessionLifecycle` and `timelineTree` data faces. It uses the [public branch read surface](../timeline-read-ownership.md#8-binding-appendix) for the published cutoff and adopted model selection. The process part declares the `managementMethods` and `partRegistry` data faces. Both use caller origin and the process build metadata already available to App Server. With no approved typed diagnostics source, build and platform information are sufficient process evidence. Model-assisted generation depends on the model owners in §7. App Server composes the parts as one feature. [Service catalog](../../architecture/rust-agent/generated/catalog.md). | Rule | Check | | --- | --- | diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 1db4af1c80..28751518d5 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -502,7 +502,7 @@ auxiliary binding use the owner contracts in §0. The optional service contract | Neutral | Rust | | --- | --- | | Namespace `session.rename` registered with `sessionMethods` | The Session part calls `methods.register(ctx, "session.rename", Vec, handler)` on a `Key` dependency | -| Published branch properties | Required `Key`; `TreeCommands::query("main", TimelineQuery)` with branch scope, `include_publishing: false` and one-row `QuerySelect::Fields` results. Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | +| Published branch properties | Required `Key`; `TimelineTree::query("main", TimelineQuery)` with branch scope, `include_publishing: false` and one-row `QuerySelect::Fields` results. Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | | Title metadata | `SessionMetadataService::read` and `SessionMetadataService::set_title` | | Auxiliary call | `AuxiliaryModel.0.complete` with its cancellation token | | Optional generation | `ctx.get_at(&host_key("sessionTitleGenerator"))` at use; `HostDispatch.generate` with a cancellable callback promise, using the request/reply types exported by `dim-session-title` | diff --git a/docs/design/plugins/ShellInput.md b/docs/design/plugins/ShellInput.md index 7e82efb1c3..ea5e745061 100644 --- a/docs/design/plugins/ShellInput.md +++ b/docs/design/plugins/ShellInput.md @@ -15,7 +15,7 @@ flowchart LR end subgraph S["Session scope"] SI["ShellInputPlugin (run registry, sessionMethods shell)"]:::new - TC["TreeCommands"] + TC["TimelineTree"] SS["SessionConfig, SessionLifecycle, SessionIdentity"] end subgraph B["Branch"] @@ -32,7 +32,7 @@ flowchart LR | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | -| `ShellInputPlugin` | Session | `P:HostPlatform` (as WorkspaceTools uses it), `S:SessionConfig` (`cwd`), `S:TreeCommands`, `S:SessionLifecycle`, `S:SessionIdentity`, `S:sessionMethods` | Registers `shell` with `sessionMethods` | +| `ShellInputPlugin` | Session | `P:HostPlatform` (as WorkspaceTools uses it), `S:SessionConfig` (`cwd`), `S:TimelineTree`, `S:SessionLifecycle`, `S:SessionIdentity`, `S:sessionMethods` | Registers `shell` with `sessionMethods` | Contracts depended on: @@ -229,7 +229,7 @@ Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [A | §4.4 No business meaning in core | Rpc, InputQueue and Loop gain no ShellInput handling: Rpc reaches it by namespace, and the marker is an ordinary raw block. | | §4.5 Read the whole batch | Not applicable: ShellInput reads no Timeline event, and its one event (`input/message`) needs no other fact in its batch. | | §4.6 Context only from handed-off events | The output reaches the model only after InputQueue applies and Loop consumes the input; `!!` output and progress never do. | -| §4.7 Public events and services only | ShellInput uses `Branch::input` through `S:TreeCommands`, `SessionConfig`, `SessionLifecycle`, `SessionIdentity`, HostPlatform and the `sessionMethods` contract. | +| §4.7 Public events and services only | ShellInput uses `Branch::input` through `S:TimelineTree`, `SessionConfig`, `SessionLifecycle`, `SessionIdentity`, HostPlatform and the `sessionMethods` contract. | | §4.8 Requirements to mechanism owners | Infrastructure is unchanged and nothing is raised to the runtime or rutis (§9). The changes needed from Rpc (per-call progress, in C1) and HostPlatform (command builder, S7) are listed in A.5; the Agents activity handle is replaced by the runtime activity hold that idle unload raised (A.5). | | §4.9 Only facts later decisions use enter the Timeline | Only the recorded `!` result enters, as an input the model reads. Progress is reply data of one call, not Session state, so it uses neither the Timeline nor a Session broadcast notice; run records go to the process log. | | §1 Capability and App Server boundary | ShellInput is a Session Capability in its own module of dim-agent-capabilities; Rpc only dispatches `sessionMethods`. | @@ -329,7 +329,7 @@ One input written with `Branch::input` on `branchId`: | Step | Mechanics | | --- | --- | -| Start | Parse the params (`invalid_params`); admit (below); resolve the branch through `S:TreeCommands`; build the `ProcessSpec` (S7; `shell_unavailable`) until the call's token fires; then, under the registry lock in one step, admit again, take the Session hold, `spawn` (`spawn_failed`), register the run with its hold and start its task in the generation's task tracker, not in the call. A `runId` counts as used once its process has spawned or a stop that came first ended it, so a refused start leaves it free | +| Start | Parse the params (`invalid_params`); admit (below); resolve the branch through `S:TimelineTree`; build the `ProcessSpec` (S7; `shell_unavailable`) until the call's token fires; then, under the registry lock in one step, admit again, take the Session hold, `spawn` (`spawn_failed`), register the run with its hold and start its task in the generation's task tracker, not in the call. A `runId` counts as used once its process has spawned or a stop that came first ended it, so a refused start leaves it free | | Admission | Refuses, in this order: an interrupted call (`operation_interrupted`), an unloading generation (`service_reloading`), a closing Session (`session_closed`), a registered run (`shell_busy`), a used `runId` (`duplicate_run`). The second admission then consumes a stop remembered for the `runId`: nothing starts and the reply is `{runId, status: "stopped", output: "", truncated: false, durationMs: 0}`, with nothing recorded and no span. Otherwise it takes the Session hold: `None` once the Session is closing or an idle release has been decided, which refuses the run `session_closed` and leaves its `runId` unused | | Hold | One `SessionLifecycle::take_hold()` per run, kept in its registry entry. The task drops it as it removes the run from the registry, after the run's last fact (Write below, the exit for `private`, or termination) and before `shell.stop` or the reply sees the end. While it is held, `Session::unload_if_idle()` refuses; a Session close ignores it (idle unload §5.1) | | Run | The task owns the process tree. It reads both pipes, sends capped progress (A.1), keeps the bounded tail, and waits for the exit, `shell.stop`, `SessionLifecycle::closing()` or the generation's cancellation | @@ -511,14 +511,14 @@ ShellInput is implemented in Rust as the `shell_input` module of dim-agent-capab | Neutral contract | Rust binding | | --- | --- | -| Plugin | `TypedPlugin`; `Deps = (Keyed, Keyed, Keyed, Keyed, Keyed, Keyed)` | +| Plugin | `TypedPlugin`; `Deps = (Keyed, Keyed, Keyed, Keyed, Keyed, Keyed)` | | Namespace `shell` | `methods.register(ctx, "shell", declarations, handler)` on the `Keyed` dependency (`dim_agent_capabilities::methods`), called in `apply` after ShellInput's own effects, so its unload effect runs first. `declarations` holds `MethodDecl { progress: true, ..MethodDecl::new("shell.run", true, Interruption::Report) }`, `MethodDecl::new("shell.stop", true, Interruption::Report)` and `MethodDecl::new("shell.list", false, Interruption::Report)` | | Handler | A `Handler`, called with the method name, the params, the call's `CancellationToken` (A.4 Two cancellations) and its `Progress`, returning a future of `Result`. Own errors are `RpcError::app(-32000, "shell_busy", ..)` and the like, and `RpcError::invalid` for `invalid_params`; runtime facade errors convert with `?` (`From for RpcError`) | | Progress | The handler's `Progress` argument: `progress.send(json!({"text": text}))`, with `"skipped"` added when bytes were left out. The run task holds a clone; a send after the reply is dropped | | Command construction | `HostPlatform::build_process_spec(command, cwd).await` returns `(ProcessSpec, ExecShellRuntime)` or `ProcessSpecError { code, reason }`; it reads the current shell itself. The handler `select!`s it against the call's token | | Process | `HostPlatform::spawn(ProcessSpec)` returns a `ProcessTree` with `stdout`, `stderr`, `wait` and `terminate` | | Run tasks | ShellInput's own `TaskTracker`, separate from the calls `SessionMethods` tracks; each task owns its `ProcessTree` and watches `ctx.cancelled()` and `SessionLifecycle::closing()`; `ctx.effect` registers the disposer that waits for the tracker. The call's token, the generation token and the Session phase are read under the registry lock right before `spawn`, and the disposer closes the tracker under that lock. The `SessionHold` from `SessionLifecycle::take_hold()` is taken there too and kept in the run's registry entry, which the task clears after the run's last fact | -| Recorded input (A.3) | `TreeCommands::get(branch_id)?.input(..)` | +| Recorded input (A.3) | `TimelineTree::get(branch_id)?.input(..)` | | Process log | A `tracing` span `shell.run` with `session_id`, `branch_id` and `run_id`, with `outcome` recorded when the run ends | ```rust diff --git a/docs/design/resume-read-design.md b/docs/design/resume-read-design.md index 1a5c2ad4e2..0785be01a5 100644 --- a/docs/design/resume-read-design.md +++ b/docs/design/resume-read-design.md @@ -37,7 +37,7 @@ CLI / ACP / Web 需要事实的业务 owner / App Server -> 活分支:Session/Branch 门面或本部件的 timeline - 结束分支:TreeCommands.query + 结束分支:TimelineTree.query -> Timeline 建立固定范围与祖先截止 -> Store.query 按索引执行,返回选定字段 @@ -50,7 +50,7 @@ CLI / ACP / Web | 层 | 负责 | | --- | --- | | 业务 owner | 定义当前状态、源事实、字段、转移、保存及恢复;拥有自己的任务。 | -| Timeline / TreeCommands | 固定分支、祖先、through、发布尾部、权限及取消范围。TreeCommands 仍只支持 branch。 | +| Timeline / TimelineTree | 固定分支、祖先、through、发布尾部、权限及取消范围。TimelineTree 仍只支持 branch。 | | Store | 用既有 query 执行索引定位、字段投影和通用关联;维护存储格式。 | | 客户端 | 窗口、展开视图、请求调度;采用 owner inventories,不从显示历史重建控制状态。 | @@ -183,7 +183,6 @@ v42 为审批、协作交付、未通知后台结果补成员索引,保留 exe 另用独立 cgroup 限制 CLI、守护进程及其子进程的合计内存并禁用该组交换,记录实际限制值、峰值、匿名内存、文件缓存、磁盘读取字节和限制触发次数。统计组内的测试工具开销单列;不能只报 RSS,也不能以预热整个数据库取得达标时间。首次格式升级仍单列。 - ### 9.1 恢复的是责任,不是旧执行现场 | 对象 | 重载必须保留的业务责任 | 不恢复的数据 | 必要读法 | diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index bb2125290c..b3d7de519a 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -52,7 +52,7 @@ Status: Draft. 依据:[总体设计](overview.md) §8 阶段与附录 B/F、[ | ~~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 | | 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 | +| C5 | #4 分支级:TypeScript 部件按名使用 `Dispatcher`、`Branch::input`、`TimelineTree` | M | 装配 | C4 | Goal | | S1 | InputQueue 撤回:`input/withdraw`、`input/deleted`、`session.input.withdraw`(新事件需做格式决定) | M | 事件类型 | C1 | `Ctrl+S`/`/queue`、Goal、S2 | | S2 | Agents `sessions` 服务:`launch`、`input`、`idle`、`withdraw` | L | `agents.rs` | C2、S1 | Scheduler、Workflow | | S3 | ~~Session 活动句柄~~:不需要,App Server 不自动卸载空闲 Session(#57) | S | `agents.rs` | — | — | diff --git a/docs/design/rutis-usage.md b/docs/design/rutis-usage.md index d0939817b2..8bfcf5889b 100644 --- a/docs/design/rutis-usage.md +++ b/docs/design/rutis-usage.md @@ -595,7 +595,7 @@ async def apply_branch(ctx, config): identity = await ctx.use("timelineIdentity").get() ... -branch = define_plugin(apply_branch, inject=["dispatcher", "timelineIdentity", "treeCommands"]) +branch = define_plugin(apply_branch, inject=["dispatcher", "timelineIdentity", "timelineTree"]) inject = ["partRegistry"] provides = {} diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0b4e2686b5..d43b65d844 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -114,7 +114,6 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | | `loader` | `rutis/loader` | 插件管理走数据面 | | `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 标题与 worktree 关联直接调 store | -| `treeCommands`、`timelineTreeControl` | `timelineTree` | 分支操作直接调用 Session 的树;不保留别名 | ### 3.4 对象/句柄:拆成操作加 id @@ -200,7 +199,6 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `providerService` | process | Provider | 当前为 secret,迁移后通过数据操作使用凭据 | | `providerConnectionResolver` | process | Provider | host-resource | | `sessionLoader` | session | SessionScope | control | -| `timelineFactory` | session | SessionScope | control | ## 4. 批次契约(#1292) diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index d17b4fe064..f0d5543e3b 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -1,7 +1,5 @@ # Timeline branches -The [target Session tree binding](contracts/runtime-owner-operations.md) moves calls from `treeCommands` to `timelineTree` with the same arguments and replies. The catalog entry and consumer injections change together. References to `treeCommands` below describe the pre-migration binding. - Status: Accepted ([#427](https://github.com/arcships/dim/issues/427)). This document holds both the requirements and the design: §1–§3 answer #427's questions, and §4 onward is the design. Scope: the TimelineTree plugin (TimelineTree, TreeTimeline, BranchTool, plus a new branch part for BranchLine), one App Server built-in method, one core event, one `BranchSource` kind, the CLI TUI, the Web workspace, and a rewrite of [design rules §2](../architecture/rust-agent/principles.md#2-作用域的含义). Language: Rust. Chinese: [中文](../zh/design/timeline-branches.md). This design delivers two capabilities: the Session's **default branch**, the line its conversation is on and choosing another open line as that line; and **who may open a line**, which is now the root always, plus whichever line is the current default branch. Every other line is refused, so at most two lines can open at any moment, and the root keeps the ability it has today. @@ -83,9 +81,9 @@ These needs are not branches: - **Sources.** Every line has a source, recorded in its parent's `branch/create`. The source records where the line was created from; it is not a role marker, and this design reads nothing from it beyond what is stated here: - A **tool line** was opened by the `branch` tool. It is a conversation line: it can be the default branch, and it ends itself with `end` while it is not the default branch. - A **user line** was opened by a client through `session.branch_create`. Its opener is the user, and it is a conversation line too: it can be the default branch. The user ends it; it cannot end itself. - - A **plugin line** was opened by a plugin (`TreeCommands.create`). Its creator owns its protocol, and it can never be the default branch. It opens no lines either. + - A **plugin line** was opened by a plugin (`TimelineTree.create`). Its creator owns its protocol, and it can never be the default branch. It opens no lines either. - The source can be read as `TimelineInfo.source`, returned for active lines by `TreeCommands.list` and `info` and absent on `main` (§5). Ended directory entries may omit it; opening their display detail reads the creation source at its known position. A plugin line's source is `{kind: "host", operation_id}`: the opener's opaque tag, which the core never interprets. A user line's source is `{kind: "user", operation_id}`, its own kind, so a reader that must tell a conversation line from a plugin line does not parse an `operation_id`. An opener finds its own lines by its own operation-id convention, for example Goal's `goal:evaluate:` prefix. The kind says where the line was created from, and nothing about a role. + The source can be read as `TimelineInfo.source`, returned for active lines by `TimelineTree.list` and `info` and absent on `main` (§5). Ended directory entries may omit it; opening their display detail reads the creation source at its known position. A plugin line's source is `{kind: "host", operation_id}`: the opener's opaque tag, which the core never interprets. A user line's source is `{kind: "user", operation_id}`, its own kind, so a reader that must tell a conversation line from a plugin line does not parse an `operation_id`. An opener finds its own lines by its own operation-id convention, for example Goal's `goal:evaluate:` prefix. The kind says where the line was created from, and nothing about a role. - **Lines created before the upgrade.** `session.branch_create` persists `{kind: "host", operation_id}` today ([connection/tree.rs](../../crates/dim-app-server/src/connection/tree.rs)), and this design rewrites no stored row. A line the user opened through a client before the upgrade, Web `/branch` under `FORMAT` 52 included, therefore stays `host` and is not a valid switch target afterwards, while the same action on a line opened after the upgrade works. This change accepts that limit instead of migrating the fact: `FORMAT` 53 is a marker-only bump that adds no data (§15, §16), and an upgrade case states it (§20). - **Reach of the tool.** A line messages and reads the line it was cut from and each open tool line it opened. A line the user opened stands on both sides of that rule: it messages the line it was cut from and reads it from its cut, and it coordinates the tool lines it opens; the line it was cut from neither messages nor reads it, because the user opened it (§6). `end {content}` takes no target, so it ends the calling line and no other (§6, §10, §11). A plugin line is not on any roster, and the tool neither messages it nor ends it. - **The parent block.** A line's BranchLine writes one keyed `` block on the line itself when the line it was cut from ends a turn and has new activity past the line's last read, the last head the line was told and the line's opening (§7.1.1, §12.1). The block reports positions and is state, not a request; the content stays in the pages a read returns. @@ -109,13 +107,13 @@ Every part belongs to the TimelineTree plugin ([timeline_tree.rs](../../crates/d | TimelineTree | Session | No | The line lifecycle: the identity block in every child's opening input, `TimelineInfo.source`, the end of a line (`branch/end` → `branch/ended`), refusing input once a line is ending, the restore rule, reads of an ended line's history, the default branch and its `branch/default` fact, and the branch directory (§14) | | TreeTimeline | Branch | Yes | Routes `branch/end` to TimelineTree, as it routes `branch/create` today. For an end issued by a tool call, it also routes the turn end that the close waits for | | BranchTool | Session | No | The action-based `branch` tool (§11). It finds the calling line's BranchLine per call, the way WorkspaceTools finds FileReads | -| **BranchLine** (new) | Branch | Yes | One line's view of its lines. Its role (root, tool line, user line or plugin line) and its parent come from `TreeCommands.info(own id)`. From its own facts it folds its open tool lines and the state of its current turn. It writes the roster, the idle notice and the ended notice, and the one status note a line receives when it becomes the default branch or stops being it. With two openers the roster is its own key, `branch:roster`, which holds the open tool lines it opened (§7.1) | +| **BranchLine** (new) | Branch | Yes | One line's view of its lines. Its role (root, tool line, user line or plugin line) and its parent come from `TimelineTree.info(own id)`. From its own facts it folds its open tool lines and the state of its current turn. It writes the roster, the idle notice and the ended notice, and the one status note a line receives when it becomes the default branch or stops being it. With two openers the roster is its own key, `branch:roster`, which holds the open tool lines it opened (§7.1) | -BranchLine injects `B:Dispatcher`, `B:TimelineIdentity`, `B:BranchLifecycle` and `S:TreeCommands`, and provides `B:BranchLine`. +BranchLine injects `B:Dispatcher`, `B:TimelineIdentity`, `B:BranchLifecycle` and `S:TimelineTree`, and provides `B:BranchLine`. It decides the way Goal does: from consumed state, through an owned write task that rechecks before writing, and only on live events after its load cutoff. A reload therefore writes nothing twice, with one exception: a load whose own history ends with a live roster key the fold does not match writes the roster once, because a restart that completed an ended line (§20.7) recorded `branch/ended` before `main`'s replay, so no live event follows it (§6.2). -The same exception reconciles a move that stopped between its fact and its notes. `branch/default` and each status note are separate batches (§4.5), so a daemon that stops after the fact commits leaves the fact in force and a note unwritten. On load, BranchLine compares two things for its own line: the `default` attribute of the latest live `branch:line` block on it, where a missing attribute means not default, and whether `TreeCommands` reports this line as the default branch now. When they differ it writes the note that matches the tree once, before the line's next model request, and a root never writes one. The new-default note names the line the move started from, so a reconciling load has to know that line: `branch/default` carries it, under the `from` field the note already needs (§16), which is what §4.9 admits a fact for, since the reconciled note decides with it. A load that finds its line's block and the tree in agreement writes nothing, so a second restart writes nothing. On the line the tree reports as the default branch alone, the comparison also reads the text of that block, so a note an older rule set wrote is replaced once at load. +The same exception reconciles a move that stopped between its fact and its notes. `branch/default` and each status note are separate batches (§4.5), so a daemon that stops after the fact commits leaves the fact in force and a note unwritten. On load, BranchLine compares two things for its own line: the `default` attribute of the latest live `branch:line` block on it, where a missing attribute means not default, and whether `TimelineTree` reports this line as the default branch now. When they differ it writes the note that matches the tree once, before the line's next model request, and a root never writes one. The new-default note names the line the move started from, so a reconciling load has to know that line: `branch/default` carries it, under the `from` field the note already needs (§16), which is what §4.9 admits a fact for, since the reconciled note decides with it. A load that finds its line's block and the tree in agreement writes nothing, so a second restart writes nothing. On the line the tree reports as the default branch alone, the comparison also reads the text of that block, so a note an older rule set wrote is replaced once at load. **Restoring the default branch.** A Session whose directory holds one line is on its root and reads nothing for it. A Session with more lines reads one fact: the newest `branch/default` or `session/forked` among the root's own events, through the existing `timeline_events_by_kind` index. A `branch/default` whose target is still open and can be selected names the default branch; a `session/forked` means the default branch is the root, because every `branch/default` the fork copied was written before its `session/forked` and is void; nothing recorded means the root. A target that is no longer open, one naming a plugin line and one naming a line created through a client before the upgrade all fall back to the root (§4). @@ -131,7 +129,7 @@ Ended display details read purpose/source and end data at their recorded positio ## 6. Messages between lines -A message is an `input/message` on the receiver's Timeline, written through `TreeCommands.input`. No new input path is added. A message carries one raw block, marked by its producer and without a key, and the mode of [InputQueue](../architecture/rust-agent/plugins/InputQueue.md): +A message is an `input/message` on the receiver's Timeline, written through `TimelineTree.input`. No new input path is added. A message carries one raw block, marked by its producer and without a key, and the mode of [InputQueue](../architecture/rust-agent/plugins/InputQueue.md): | Mode | Effect on the receiver | When to use it | | --- | --- | --- | @@ -154,7 +152,7 @@ These are Collaboration's message modes and words (`append`, `steer`), with the | Any other pair: siblings, a line and its grandparent | No | No | `branch_not_kin` | A line the user opened is a conversation line like a tool line, and the row it falls under is decided by the edge it stands on: as a line that was opened it has the second row, whose opener is the user and not the line it was cut from, and as an opener of tool lines it has the first row like any other opener. An ended tool line keeps its row, with its message refused: its opener still reads it, which is how the opener gets a result the line never sent. An ended plugin line stays under the plugin row, where no line reads it through the tool. `end` is not part of any pair: `end {content}` has no target, so it always ends the calling line (§10, §11). Coordination follows the parent-child relation, so it stays with the line that opened a line and never moves when the default branch moves, and a former default branch keeps the tool lines it opened and still messages and reads them. -- **Read.** `read {branch, after?, limit?}` returns one page of the target's committed history, open or ended, read from the store through `TreeCommands.page` and rendered the way Collaboration's `read` renders a member's page: inputs, text, tool calls and results, and turn ends, with `nextCursor`; a tool result item carries the effects its tool declared on that result (session boundary A.6), present only when the result declared at least one, a path verbatim and a command cut at its 200th character with the cut marked. The target is the line the caller was cut from, or a line the caller opened. One cursor rule covers both directions: +- **Read.** `read {branch, after?, limit?}` returns one page of the target's committed history, open or ended, read from the store through `TimelineTree.page` and rendered the way Collaboration's `read` renders a member's page: inputs, text, tool calls and results, and turn ends, with `nextCursor`; a tool result item carries the effects its tool declared on that result (session boundary A.6), present only when the result declared at least one, a path verbatim and a command cut at its 200th character with the cut marked. The target is the line the caller was cut from, or a line the caller opened. One cursor rule covers both directions: - With no `after`, a read continues after the caller's last successful read of that line: the `nextCursor` of the latest read that returned a page. With no earlier read, a read of the line the caller was cut from starts at the caller's cut, and a read of a line the caller opened starts at that line's first event. - An explicit `after` reads from that point. A read of the line the caller was cut from raises a value below the cut to the cut, because the events up to the cut are already the caller's own history. A read of a line the caller opened uses the value as given, so `after: 0` re-reads that line from its start. - Every successful read moves the cursor to its `nextCursor`, an explicit-after read included; the latest read wins. The cursor is a fact of the caller's own line: BranchLine retains live read results in memory; after a reload it locates the latest successful read for the requested target only when a cursor is used, then reads that request's result fields. Resume does not replay tool history. @@ -264,7 +262,7 @@ A read is on demand, so a line must also know that the line it was cut from move 3. the parent has new activity past `from = max(A, told, opened)`, where `A` is the line's read cursor for the parent (its cut when it has not read yet), `told` is the head the latest `branch:parent` block on the line reports (0 when there is none), and `opened` is the sequence of the line's `branch/create` event on the parent, at or above every cut. Activity from before the line existed is not news, and the line reads it when it needs it. - **What counts as new activity.** Two kinds of event count: an operator input, an `input/message` that carries `user` content, and a tool call. The creating call's `step/tool-use` is written before `opened`, so it is never counted. Nothing else counts on its own: the parent's text, its turn ends, block-only inputs such as the roster and messages from lines, and the creating call's result. The rule is that a line is told when the parent acts or when the operator tells the parent something, and never for the turn that only opened it (its creating call's result, its text and its turn end), which would make every line read its parent for nothing and train it to ignore the block. - **The check.** The parent's facts are read through the one event query ([ADR 019](../adr/019-event-query.md)): the branch's `input/message` and `step/tool-use` events, newest first, paged until one qualifies or the read reaches `from`. No other line's events are folded. -- **The write.** One keyed Append, `branch:parent`, written on the line itself through `TreeCommands.input`, with the parent's id, `head` and `after` as attributes. A later block of the same key replaces the earlier one in the keyed baseline. After the write the fold records the new head and the new input, so a second decision in the queue does not write again. +- **The write.** One keyed Append, `branch:parent`, written on the line itself through `TimelineTree.input`, with the parent's id, `head` and `after` as attributes. A later block of the same key replaces the earlier one in the keyed baseline. After the write the fold records the new head and the new input, so a second decision in the queue does not write again. - **At open.** When a child's inherited prefix holds a live `branch:parent` block, the child's opening input carries one more raw block, after the identity block: keyed `branch:parent`, live and not retired, naming the line that opened it P with `head` and `after` both the cut H. It supersedes the inherited block the way the identity supersedes the inherited roster (§7.1), so the line's latest `branch:parent` always names its own parent and its `told` starts at H, which equals `opened`; a compaction replays this block and never the one above it, and the usual block supersedes it when P moves. Only a nested line gets it: a line cut from `main` inherits no `branch:parent` block, so its opening input is byte for byte what it was. TimelineTree composes it where it writes the identity block, and reads whether the key is live from the keyed state of the prefix the child inherits, never from the rendered history. It reads that state while it opens the child, as it reads a resumed line's facts; a failed read fails the create like any other opening failure (branch/create-failed). - **What follows.** A running line gets the block with its next model request. An idle line is not woken: the block is consumed with the first request of its next turn, ahead of the input that starts that turn, which is the documented Append rule ([session access](contracts/session-access.md), [Loop](../architecture/rust-agent/plugins/Loop.md)). A reload writes nothing; a restart writes at most the one block that was due. `main` gets no block: nothing is above it. - **The record.** The line sends the System its configuration holds. The guide is the same on every line (§7.3), so a line whose System did not move from the one it inherited references the configuration that recorded it, on whichever line of its chain recorded it, and a line publishes its own `context/configured` when its System moves, as any branch does. @@ -378,7 +376,7 @@ This pair mirrors `branch/create` and `branch/create-failed`: a command on one T `ancestor` names the line whose own end started the cascade: the end that carries no `ancestor` of its own. Every descendant the cascade ends carries that line, `source` is copied from that same end, and the pair therefore names one end operation: who asked, and on which line. A line ended at its own request has a `source` and no `ancestor`, and a descendant whose own end was already committed keeps that pair when the cascade reaches it. `branch/ended` copies `source` and `ancestor` from the line's `branch/end`, and is always written on the ending line's own parent, taken from the directory. -**A general operation.** `TreeCommands.end(id, source)` and `Session::end_branch(id, source)` check only the target: it exists, it is open, it is not the root, it is not the default branch, and it is not an ancestor of the default branch. Ending the root would close the Session, and ending a line ends every line below it, so the default branch's whole chain is protected. These checks are about the target, not the caller. They never check who calls: the user, an opener and a plugin meet the same guards, and ending the default branch always takes a move of the default branch first. +**A general operation.** `TimelineTree.end(id, source)` and `Session::end_branch(id, source)` check only the target: it exists, it is open, it is not the root, it is not the default branch, and it is not an ancestor of the default branch. Ending the root would close the Session, and ending a line ends every line below it, so the default branch's whole chain is protected. These checks are about the target, not the caller. They never check who calls: the user, an opener and a plugin meet the same guards, and ending the default branch always takes a move of the default branch first. The check reads the chain from the directory at the moment of the call and under the tree lock that a move also takes, so a move and an end cannot interleave into a state the rule forbids. Two orderings are therefore admitted, and nothing else: either the end is admitted and the move is refused, because the target or one of its ancestors is ending or ended, or the move is admitted and a later end of a line on the new default branch's chain is refused. A move is refused with `branch_target_protected` when the target or any ancestor of it is still `ending`, so a target cannot become the default branch while an ancestor's cascade is already writing its descendants' ends. A refusal writes nothing. @@ -441,7 +439,7 @@ The tool takes one action-based input, which replaces `{prompt, at?}`. Its risk | `create` | `prompt`, `at?`, `idleNotice?` (`steer` \| `none`) | The root, and the current default branch | Opens a tool line cut at `at` (default: before this request's model start), which reports to the caller. Refused with `branch_limit_reached` when the open would cross the Session's cap, charged at the reservation (§6.1). The idle notice defaults to `steer`. | `Line created: C` | | `message` | `to`, `content`, `mode?` (`append` \| `steer`) | A line to a tool line it opened, or to the line it was cut from | One `input/message` on `to` | `Sent to C.` | | `read` | `branch`, `after?`, `limit?` (1–200) | A line on the line it was cut from or on a tool line it opened, open or ended. A line the user opened reads the line it was cut from on those terms; that line neither messages nor reads it, because the user opened it | One page from the store, from the caller's cursor when `after` is absent (§6) | The page as JSON: items, `nextCursor`, `done` | -| `end` | `content` | A tool line that is not the default branch, on itself | One `TreeCommands.end(C, source, final_message)` under the tree lock: it checks the guards, writes `branch/end` on C carrying the final message, then delivers that message (steer) to the parent under the submission id derived from `source` (§10). A refused end writes no final message | `Line C is ending; your final message was sent to P.` | +| `end` | `content` | A tool line that is not the default branch, on itself | One `TimelineTree.end(C, source, final_message)` under the tree lock: it checks the guards, writes `branch/end` on C carrying the final message, then delivers that message (steer) to the parent under the submission id derived from `source` (§10). A refused end writes no final message | `Line C is ending; your final message was sent to P.` | The input schema is `{action, prompt?, at?, idleNotice?, to?, content?, mode?, branch?, after?, limit?}`, with `action` required and `additionalProperties: false`. `idleNotice` is valid only for `create`. @@ -457,7 +455,7 @@ Refusals come back as error results (code in `structuredContent`) and write noth | `end` on the root, on the default branch, on a plugin line or on an ancestor of the default branch | `Only a line opened with create can end itself, and not while it or a line below it is the default branch.` | `branch_cannot_end` | | `read` with an `after` past the target's head | `after A is past line T's head H; a read starts at or below H` | none: an error result with no code | -These refusals are the tool's own rules. `TreeCommands.end` itself checks only the target (§10). An `end` whose line already committed its own `branch/end` takes the `branch_ended` row and writes no second final message: the first call's message is the line's last word. Because the guards, `branch/end` and the delivery are one operation under the tree lock a move also takes, a move that makes the target the default branch first is refused before any message is written, and the refusal above is the whole effect. An end that commits `branch/end` and stops before the delivery is not a second end to answer: the message is recorded in `branch/end` itself, and restore delivers it once (§10). +These refusals are the tool's own rules. `TimelineTree.end` itself checks only the target (§10). An `end` whose line already committed its own `branch/end` takes the `branch_ended` row and writes no second final message: the first call's message is the line's last word. Because the guards, `branch/end` and the delivery are one operation under the tree lock a move also takes, a move that makes the target the default branch first is refused before any message is written, and the refusal above is the whole effect. An end that commits `branch/end` and stops before the delivery is not a second end to answer: the message is recorded in `branch/end` itself, and restore delivers it once (§10). ### Activity page execution @@ -677,15 +675,15 @@ refusal is shown where the action was raised. The commands the composer offers a | Module | Change | Why | | --- | --- | --- | | [Design rules §2](../architecture/rust-agent/principles.md#2-作用域的含义) | Rewritten: lines of one subject, shared facts, parent and child as the only communication and reading relation, and the shared interaction surface. Relations row: "only between parent and child", reading the parent's committed events through a tool result. Session row: adds "end" | The current text, "equal lines, the relation only records the source", has no communication relation | -| TimelineTree | The identity block in `first_input` for every source. `TreeCommands.end(id, source)` and `TreeCommands.page(id, after, limit)`. `TimelineInfo.source`, filled from the parent's `branch/create` (§5). The end flow and its guards, refusing input once a line is ending, `branch/ended`, the restore rule, reads of ended lines, and the default branch: `branch/default` on the root, its restore read, and the fact the write makes. Its `directory()` reports an open line, an ending line (its own `branch/end` committed, from a tool, a user or a cascade, until its ended row is written) and an ended line, with the ending line's live head, and the current `defaultBranchId`. Its node publishes the sequence of the line's latest turn end to the line's children (§7.1.1). It also delivers the final message a tool end recorded: a tool end's `branch/end` carries it (§10, §16), so restore writes it on the parent under the id derived from that command when the parent holds no input with it, and writes nothing when it does | It owns the line lifecycle, the opening input and the default branch's one authoritative fact | +| TimelineTree | The identity block in `first_input` for every source. `TimelineTree.end(id, source)` and `TimelineTree.page(id, after, limit)`. `TimelineInfo.source`, filled from the parent's `branch/create` (§5). The end flow and its guards, refusing input once a line is ending, `branch/ended`, the restore rule, reads of ended lines, and the default branch: `branch/default` on the root, its restore read, and the fact the write makes. Its `directory()` reports an open line, an ending line (its own `branch/end` committed, from a tool, a user or a cascade, until its ended row is written) and an ended line, with the ending line's live head, and the current `defaultBranchId`. Its node publishes the sequence of the line's latest turn end to the line's children (§7.1.1). It also delivers the final message a tool end recorded: a tool end's `branch/end` carries it (§10, §16), so restore writes it on the parent under the id derived from that command when the parent holds no input with it, and writes nothing when it does | It owns the line lifecycle, the opening input and the default branch's one authoritative fact | | TreeTimeline | Consumes `branch/end`, plus the line's next turn end for an end issued by a tool call, and routes them to TimelineTree. It reports every `turn/end` to TimelineTree, which publishes it for the line's children | It routes `branch/create` the same way | | BranchTool | The action-based tool, plus the new BranchLine branch part. `read` and `message` reach the line the caller was cut from and the tool lines it opened, with one cursor rule. `create` admits the root and the current default branch and refuses every other line with `branch_not_opener`, then checks the Session's cap and refuses with `branch_limit_reached` | The tool's actions and one line's view of its lines | -| Session facade | `Session::end_branch(id, source)`, `Session::default_branch(id)` and `Session::set_default_branch(id, source)`. An ended line's head is `Session::sequence`; its history is read at that fixed head through `TreeCommands.page` | §17 | +| Session facade | `Session::end_branch(id, source)`, `Session::default_branch(id)` and `Session::set_default_branch(id, source)`. An ended line's head is `Session::sequence`; its history is read at that fixed head through `TimelineTree.page` | §17 | | App Server | `session.branch_end` (v3, a user source with a minted `operation_id`, listed in `hello.features` with the other Session methods when `session_execution` is on and the connection's entry is not bare or the daemon profile is not protected). `session.branch_set_default` (v3, the same admission). `session.history` on an ended line returns immediately, at its stored head. `session.branches` reads the tree's directory and carries `defaultBranchId` (§14). Every Session-level default target that today names `main` reads the default branch instead: `session.submit`, `session.stop`, `session.idle`, `session.goal.*` and `shell.run`, and a newly created scheduled job. `session.model.update`, `session.agent.update` and `session.prompt.refresh` act on the default branch rather than refusing every line but the root. `approval.respond` keeps the `branchId` its notice carried, so a pending request stays on the line that asked for it. `ProductEvent::new` carries the new kind in v3 and leaves it out of v1 and v2 | An entry and three reads, no business logic | | dim-agent-types | `branch/end` and `branch/ended` in `EventKind` and the v1 exclusion list, then `branch/default`, registered in the contract tests. `BranchSource` gains a kind for a line the user opened, distinct from a plugin's. The frozen fixtures are unchanged | Core facts (§16) | | Storage | `FORMAT` 52 → 53 as a marker-only upgrade `(52, &[])`: no table scan and no data migration, so an older daemon refuses the store instead of failing on its first decode. `SqliteTimelineStore`'s writer thread caches each Session's default branch for the catalog's recent activity, initialised by the same indexed point query that restore uses | A new event kind and a new `BranchSource` variant are rows a 52 daemon cannot decode | | Goal (Pursuit amendment) | Recognizes its evaluator from the line's source and ends it ([Pursuit §13](plugins/Pursuit.md#13-ending-the-evaluator-with-427)) | Goal owns its evaluator's protocol | -| Branch TypeScript binding | Regenerated `npm/branch-services.d.ts`: TreeCommands gains `end` and `page`, and `TimelineInfo` gains `source`. The `treeCommands` row of the [binding table](branch-typescript.md) lists `end` | TreeCommands is an exported service | +| Branch TypeScript binding | Regenerated `npm/branch-services.d.ts`: TimelineTree gains `end` and `page`, and `TimelineInfo` gains `source`. The `timelineTree` row of the [binding table](branch-typescript.md) lists `end` | TimelineTree is an exported service | | CLI TUI | §14 | Users follow, talk to, move to and end lines | | Plugin pages | TimelineTree.md and BranchTool.md, updated with the implementation (`xtask check`) | Pages follow the code | @@ -693,13 +691,13 @@ New public content: - three events: `branch/end`, `branch/ended` and `branch/default`; - one RPC method, `session.branch_set_default`; -- one TreeCommands read and one write, `default_branch()` and `set_default_branch(id, source)`; +- one TimelineTree read and one write, `default_branch()` and `set_default_branch(id, source)`; - `defaultBranchId` on the directory reply; - a `BranchSource` kind for a line the user opened; - the roster's key, `branch:roster`, announced to the model through the `` guide entry; - two refusal codes, `branch_not_opener` and `branch_limit_reached`. -BranchLine's service is read only by the tool, inside the same plugin. The turn-end signal is crate-internal, beside `TreeCommands.page` and `head`: it is not exported, and the TypeScript binding does not change. +BranchLine's service is read only by the tool, inside the same plugin. The turn-end signal is crate-internal, beside `TimelineTree.page` and `head`: it is not exported, and the TypeScript binding does not change. ## 16. Format @@ -729,12 +727,12 @@ The format decision for them is recorded in the storage contract: [#427 v20 deci - Reading the store directly from App Server would bypass the facade. - **Generic capability.** It carries no business meaning: - a command `branch/end {source, ancestor?, final?}` on the line and a result `branch/ended {branch, endEvent, source, ancestor?}` on its parent; - - `TreeCommands.end(id, source)`, `TreeCommands.end(id, source, final)` for a tool end, and `Session::end_branch(id, source)`, which check only the target; the final message is delivered after the command commits (§10); + - `TimelineTree.end(id, source)`, `TimelineTree.end(id, source, final)` for a tool end, and `Session::end_branch(id, source)`, which check only the target; the final message is delivered after the command commits (§10); - `TimelineInfo.source`, filled from the parent's `branch/create`; - no new input once `branch/end` is committed; - descendants end first; - restore treats an ended line as inactive and completes a `branch/end` that has no `branch/ended`; - - an ended line's committed history stays readable at its fixed head, through `TreeCommands.page`. + - an ended line's committed history stays readable at its fixed head, through `TimelineTree.page`. - **Effect on sequences, batches, interrupt and reload.** - Each event is its own batch: `branch/end` on the line, and `branch/ended` on the parent after the close. A tool end's final message is a second event on the parent, after `branch/end` and before the close, under an id derived from the command. - An end with a `host` or `user` source, or because of an ancestor, interrupts the line through `Branch::close()`. @@ -744,7 +742,7 @@ The format decision for them is recorded in the storage contract: [#427 v20 deci ## 18. Security - Lines share the Session's permission policy and Approval. A line is not isolation ([ADR 003](../adr/003-approval-scope.md)). -- Only TimelineTree and BranchLine write the markers. Other producers that write blocks (plugins, through `TreeCommands.input`) are trusted in-process parts. RPC writes no blocks. +- Only TimelineTree and BranchLine write the markers. Other producers that write blocks (plugins, through `TimelineTree.input`) are trusted in-process parts. RPC writes no blocks. - `session.branch_end` and `session.branch_set_default` are trusted user entries, as `session.branch_create` is. They need no approval, because they are not agent actions. - Any trusted in-process part can end any open line the end guards allow, just as it can write input to any line. Approval governs the tool's `end` like any other call. - The default branch confers no authority. Choosing it changes which line default targets resolve to; it does not widen a line's Permission, Approval or file roots ([ADR 003](../adr/003-approval-scope.md)). @@ -764,14 +762,14 @@ Rules: [design rules §1, §2 and §4](../architecture/rust-agent/principles.md) | §4.4 No business meaning in core | Dispatcher, `before` and batches are unchanged; the Timeline's admission check is generic (§17 R1). The identity text is TimelineTree's own domain, the lines of a Session. A tool line's protocol is written where `first_input` already writes tool-specific text, in the module that owns the tool | | §4.5 Batches | `branch/end` stands alone, carrying a tool end's final message. The message itself is one later `input/message` on the parent, under an id derived from that end, so the two are ordered and are not one batch, and restore completes the pair (§10). `branch/ended` comes last, after the close. The roster and the ended notice are one input. `branch/default` on the root stands alone, and each status note is one Append after it | | §4.6 Context | Identity, roster, messages, notices and the status note are adopted inputs. `read` returns a tool result. Nothing else enters the context | -| §4.7 Public events and services | BranchLine folds its own line's public events. The tool reads BranchLine (same plugin) and TreeCommands. `read` returns committed events as a tool result, the way Collaboration's `read` does, and no part folds another line's facts. Goal classifies the opening input by its own published A5 convention (§7.4). BranchLine and Goal read `TimelineInfo.source` through TreeCommands, a public service | -| §4.8 Infrastructure | The facade and format changes are R1 (§17). They come from the line lifecycle itself and close within the runtime. The default branch's fact, its read and its write are the same kind of infrastructure: one event, one `TreeCommands` read and one write, no business rule in a binding | +| §4.7 Public events and services | BranchLine folds its own line's public events. The tool reads BranchLine (same plugin) and TimelineTree. `read` returns committed events as a tool result, the way Collaboration's `read` does, and no part folds another line's facts. Goal classifies the opening input by its own published A5 convention (§7.4). BranchLine and Goal read `TimelineInfo.source` through TimelineTree, a public service | +| §4.8 Infrastructure | The facade and format changes are R1 (§17). They come from the line lifecycle itself and close within the runtime. The default branch's fact, its read and its write are the same kind of infrastructure: one event, one `TimelineTree` read and one write, no business rule in a binding | | §4.9 Only facts later decisions use | `branch/end` decides the close and the restore, and a tool end's final message rides on it because restore decides from it whether a delivery is still owed, and what to deliver; no other source carries one, and diagnostics record no message text (§18). `branch/ended` decides restore inactivity and the roster. `branch/default` decides which line the Session's defaults resolve to and which lines may open one, both of which later calls read, and a load that completes a stopped move reconciles its note from it instead of taking a second restore read; it carries the line moved to, the line moved from when that was not the root, and the operation, nothing else. No UI-only event and no presentation-only field | | ADR 002 D1 Scope | As in §5 | | D2 No wiring modules | BranchTool's feature registers BranchLine itself | -| D3 Scope dependencies | BranchLine depends outward on the Session's TreeCommands. No core part depends on it | +| D3 Scope dependencies | BranchLine depends outward on the Session's TimelineTree. No core part depends on it | | D4 Configuration | None | -| D5 Language-neutral contracts | Events, the RPC method, markers and the tool schema are data. TreeCommands' new read and write are exported and typed for TypeScript | +| D5 Language-neutral contracts | Events, the RPC method, markers and the tool schema are data. TimelineTree' new read and write are exported and typed for TypeScript | | ADR 003 Approval | The tool keeps risk `session`, and Approval admits every call. A user end is not an agent action. The right to open a line is not an authority the default branch confers: it is the rule of the tool, and it widens neither Permission nor Approval | ## 20. Acceptance @@ -804,9 +802,9 @@ Goal flows, in the crate's flow tests under `crates/dim-goal/tests` (§7.4): Line end and sources: -14. `TreeCommands.end` ends any open line the end guards allow, whoever calls it, for example a plugin part with a `host` source on a tool line, which gives the opener the ended notice. It refuses the root, the current default branch, an ancestor of the default branch, an unknown line, a line that is still opening and an ended line, and writes nothing. +14. `TimelineTree.end` ends any open line the end guards allow, whoever calls it, for example a plugin part with a `host` source on a tool line, which gives the opener the ended notice. It refuses the root, the current default branch, an ancestor of the default branch, an unknown line, a line that is still opening and an ended line, and writes nothing. 15. Ending a plugin line that has a child ends the child first, with `ancestor` set and `source` copied, then the line. Ending any line whose descendant is the default branch is refused before anything is written. -16. `TreeCommands.list` and `info` return `source` for a new child and for a restored active one, and none for the root. Ended directory entries load their source only in display detail. The stored directory rows are byte-for-byte unchanged. +16. `TimelineTree.list` and `info` return `source` for a new child and for a restored active one, and none for the root. Ended directory entries load their source only in display detail. The stored directory rows are byte-for-byte unchanged. The branch directory: diff --git a/docs/design/timeline-property-query.md b/docs/design/timeline-property-query.md index e7878865bc..35eb301065 100644 --- a/docs/design/timeline-property-query.md +++ b/docs/design/timeline-property-query.md @@ -285,7 +285,7 @@ FTS 表属于 v36;v35 仍只增加提交标识索引。v35→v36 是明确的 ### 7.2 改造顺序与兼容性 1. **查询契约与两个存储实现。** 先落实字段语义、完整范围、正文解码和分页;用同一组公开查询在内存与 SQLite 验证。旧接口迁移期间只委托新引擎,不维护两套筛选规则。 -2. **入口及直接查询调用方。** 修改 Timeline、门面、TreeCommands 和语言绑定。按 id、最新记录、配置等查询先改为字段结果;普通门面不能因此获得未发布事实。 +2. **入口及直接查询调用方。** 修改 Timeline、门面、TimelineTree 和语言绑定。按 id、最新记录、配置等查询先改为字段结果;普通门面不能因此获得未发布事实。 3. **恢复消费者。** 逐个完成第 5 节的恢复与实时交接验证,最后删除 `rebuild_facts` 及只服务于它的收集代码。 4. **请求构造。** 完成第 6 节的内容选择、正文消费和请求生命周期,删除两个 `prepared` 缓存;保留上下文结果一致性的流程验证。 @@ -301,7 +301,7 @@ Rust 类型只在 runtime 定义一次,服务和存储端口共用查询表达 Timeline::query(TimelineQuery) -> Result Branch::query(TimelineQuery) -> Result Session::query(branch_id, TimelineQuery) -> Result -TreeCommands::query(branch_id, TimelineQuery) -> Result +TimelineTree::query(branch_id, TimelineQuery) -> Result TimelineStore::query(TimelineReadScope, QuerySpec, QueryPage) -> Result ``` diff --git a/docs/design/timeline-read-entries.md b/docs/design/timeline-read-entries.md index 554b2da84e..1fe8bd0551 100644 --- a/docs/design/timeline-read-entries.md +++ b/docs/design/timeline-read-entries.md @@ -57,7 +57,6 @@ These contradict §5.4's "a part reads facts through its branch's `timeline` ser ### 1.6 Store port (`timeline_store.rs`) - ### 1.7 Dependency graph Every edge was read from a call site in this audit. An edge label lists the reads that cross it; the arrow into the store port is summarised because the calls inside `timeline.rs` were only partly enumerated. The dashed edge is the shared storage code, not a call. @@ -287,7 +286,7 @@ The request carries no read point. The service passes each segment its bound: an ### 6.5 Wiring - Capability parts declare a dependency on the branch's Timeline service and call `query` on it. The facades are not in their path. -- The goal plugin injects the Timeline service instead of `dispatcher` for reads and calls `Timeline.query`. `npm/branch-services.d.ts` already declares `query` on `Timeline`. The `Services` interface in `npm/branch-services.d.ts` lists `timeline: Timeline`, so the name exists. Goal injects dispatcher, timelineIdentity, treeCommands, settings, branchLifecycle and sessionLifecycle today; whether the binding resolves `timeline` for a branch part was not verified. Goal also reads to the committed position (`dispatcher.committed()` :104, `local(turnStart, through)` :176), so it belongs to the same open question as file reads and the collaboration rebuild. +- The goal plugin injects the Timeline service instead of `dispatcher` for reads and calls `Timeline.query`. `npm/branch-services.d.ts` already declares `query` on `Timeline`. The `Services` interface in `npm/branch-services.d.ts` lists `timeline: Timeline`, so the name exists. Goal injects dispatcher, timelineIdentity, timelineTree, settings, branchLifecycle and sessionLifecycle today; whether the binding resolves `timeline` for a branch part was not verified. Goal also reads to the committed position (`dispatcher.committed()` :104, `local(turnStart, through)` :176), so it belongs to the same open question as file reads and the collaboration rebuild. - The App Server reads a loaded session through `Session::query(branch, query)`, which forwards to `Branch::query` and then to the Timeline service. - The App Server reads an unloaded session through `SessionStore`, because no Timeline service exists for it. The page shape matches `query`, so loading a session does not change the protocol. - After the reads are deleted, `xtask types` regenerates `npm/branch-services.d.ts` and `xtask graph` regenerates `catalog.md`; nothing else in the generated files may change. diff --git a/docs/design/timeline-read-ownership.md b/docs/design/timeline-read-ownership.md index a9b07be6ec..e8b451c767 100644 --- a/docs/design/timeline-read-ownership.md +++ b/docs/design/timeline-read-ownership.md @@ -118,9 +118,9 @@ Timeline::query(TimelineQuery) -> Result Session::query(...) / Branch::query(...) // forward, published bound // ended line -TreeCommands::page(id: String, after: u64, limit: usize, through: u64) -> Result>> -TreeCommands::query(id: String, TimelineQuery) -> Result // window anchors and pages -TreeCommands::batch_end(id: String, sequence: u64) -> Result<()> // a window page's ends +TimelineTree::page(id: String, after: u64, limit: usize, through: u64) -> Result>> +TimelineTree::query(id: String, TimelineQuery) -> Result // window anchors and pages +TimelineTree::batch_end(id: String, sequence: u64) -> Result<()> // a window page's ends // branches and metadata TimelineStore::branches(session_id) -> Result> diff --git a/docs/design/tool-origin-read.md b/docs/design/tool-origin-read.md index b7c18ff335..6ba0746489 100644 --- a/docs/design/tool-origin-read.md +++ b/docs/design/tool-origin-read.md @@ -8,7 +8,7 @@ Null means no committed complete call has that identity at the cutoff; it does not mean an empty argument object. A partial call that never supplied arguments can have a terminal result and no complete call. -The Session part ToolMethods declares TreeCommands and SessionMethods. It queries +The Session part ToolMethods declares TimelineTree and SessionMethods. It queries the addressed branch's own facts, including ended branches, by request and call id, selects only the matching data and retains no event list. It never invokes the historical tool. Request cancellation ends the query. diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 44695393ff..b9f7d41e8d 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -51,7 +51,7 @@ provider and the methods it serves to other languages. This table says which to | Register Session and branch parts | `partRegistry`, process | `registerDefinition(scope, name, definition)` ([One row per plugin](#one-row-per-plugin)). | | Know this Session and its phases | `sessionIdentity`, `sessionConfig`, `sessionLifecycle`, Session | `get()` returns `{sessionId, restored}` or the creation-time configuration; `activated()`, `closing()`, `hold()` and `release(id)` ([Session observation](#session-observation)). | | Observe this Session | the `session/{sessionId}` channel | Listen with `ctx.on` ([Session observation](#session-observation)). | -| Consume branch events in order or act on branches | `dispatcher`, `branchLifecycle`, `timelineIdentity`, branch; `treeCommands`, Session | Use `Services` from the SDK. | +| Consume branch events in order or act on branches | `dispatcher`, `branchLifecycle`, `timelineIdentity`, branch; `timelineTree`, Session | Use `Services` from the SDK. | | Write events of your own domain | `timeline`, branch | Implemented ([extension events](#extension-events)); subscribe and read them through `dispatcher` like any event. | See [Session TypeScript bindings](design/session-typescript.md) and @@ -651,7 +651,7 @@ Return `{kind: 'value', value}`, return a failure as data, `{code, message}`, or rethrow the service error you received. An omitted value becomes JSON null. Rpc maps a failure to the wire error: `code` becomes `appError`, with JSON-RPC code -32602 for `invalid_params` and -32000 for the others, and a rethrown native error (such as an `AgentErrorThrown` from -`treeCommands.input`) maps as it does for built-in methods. Do not choose JSON-RPC codes yourself; a +`timelineTree.input`) maps as it does for built-in methods. Do not choose JSON-RPC codes yourself; a throw without a `code` is a binding failure. Handoff is not provided by this binding; connection-bound notifications are ([Connection-bound notifications](#connection-bound-notifications)). On unload, C1 stops @@ -846,7 +846,7 @@ parts. | Service | Contract | | --- | --- | | `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. | +| `timelineTree` | 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. | | `timelineIdentity` | `get()` returns the original Session and branch ids. | @@ -909,8 +909,8 @@ nothing may use `listen` instead, which delivers live facts only. The [real Node Callbacks can run on opening facts before publication. Register long work in the part's owned tasks and return; do not wait for dispatch, activation or a child creation whose progress depends -on this callback returning. `treeCommands.input` commits validated input to the Timeline tail; -its reply does not prove dispatch or adoption. `treeCommands.create(parent, at, options, cancelled)` takes a by-reference callback whose +on this callback returning. `timelineTree.input` commits validated input to the Timeline tail; +its reply does not prove dispatch or adoption. `timelineTree.create(parent, at, options, cancelled)` takes a by-reference callback whose Promise completes when the caller cancels. Complete it during the part's cleanup; the native call owns and ends the wait when creation completes. Cancellation before acceptance stops admission; after the creation anchor commits, TimelineTree finishes the branch or records `branch/create-failed`, @@ -946,7 +946,7 @@ it. The core's domains (`input`, `turn`, `step`, `context` and the others its events use) decode only through their typed contracts, so a malformed event there is rejected. Which events a part writes is otherwise the events' contract, as for native capabilities: core facts belong to their owners, -so ask them through their commands, such as input through `treeCommands.input`, rather than +so ask them through their commands, such as input through `timelineTree.input`, rather than appending their events. The branch's Timeline is closed by the branch itself, so `timeline` has no `close`. @@ -1026,7 +1026,6 @@ An unmodified plugin for rutis's Cordis 4 (`@deepseek-ai/cordis`) can be registe pass the plugin module, or its object or function, to `registerDefinition`, and its `inject` and `ctx.get(name)` resolve to its own instance's copies. - ## Packaging and trust The [plugin distribution proposal](design/plugin-distribution.md) defines the requirements for diff --git a/docs/zh/design/appserver/keyed-blocks.md b/docs/zh/design/appserver/keyed-blocks.md index 616bc1891f..d88e441d43 100644 --- a/docs/zh/design/appserver/keyed-blocks.md +++ b/docs/zh/design/appserver/keyed-blocks.md @@ -82,7 +82,7 @@ 该读使用属性查询的数组条件、删除关联及位置游标,不新增块级持久化投影。成本取决于 opening 以上的相关输入与关联查询;按[SQL 验收](../timeline-property-query.md#81-sql-成本验收)检查实际扫描量与索引,不能仅按返回块数估计。 -本读沿用 `session.history` 的双 owner 模式:活线经其 Session 读取(`Session::query`,读发布头),结束线经 TimelineTree 在其固定头读取(`TreeCommands::query`)。调用期间线结束会回答 `branch_ended`;随后改经 tree 在固定头重读。与 `latestTurn` 窗口不同,本读不需要原生存储:两种 owner 都能提供。 +本读沿用 `session.history` 的双 owner 模式:活线经其 Session 读取(`Session::query`,读发布头),结束线经 TimelineTree 在其固定头读取(`TimelineTree::query`)。调用期间线结束会回答 `branch_ended`;随后改经 tree 在固定头重读。与 `latestTurn` 窗口不同,本读不需要原生存储:两种 owner 都能提供。 ## 4. `through` 与客户端的实时 overlay @@ -135,7 +135,7 @@ projection(through) = delivered_state(through) | ADR 019 D2(固定语义) | 按 sequence 排序的下行页,短页即穷尽,推进用范围而非 offset | | ADR 019 D3(查询面向事件合同) | 只指名 kinds 与 sequence 起点;不指名表、列或索引 | | ADR 019 D4(索引是派生的或格式的一部分) | 不新增索引;块级 key 谓词在当前查询中无法表达,也不加入 | -| [ADR 020](../../adr/020-timeline-read-convergence.md) D1(一次读取,门面只转发) | 读取经 `Session::query` 与 `TreeCommands::query`,与 `session.history` 相同的门面 | +| [ADR 020](../../adr/020-timeline-read-convergence.md) D1(一次读取,门面只转发) | 读取经 `Session::query` 与 `TimelineTree::query`,与 `session.history` 相同的门面 | | [ADR 021](../../adr/021-reads-follow-the-state-owner.md) D3(客户端读取需要活着的 Session) | 调用先 acquire Session;没有为进程未持有的 Session 读取存储事实的分支 | | ADR 021 D2(结束线经拥有其结束的对象读取) | 结束线经 TimelineTree 在固定头读取,包括线在调用中途结束的情形 | diff --git a/docs/zh/design/appserver/sessions-service.md b/docs/zh/design/appserver/sessions-service.md index 89b88a6f09..2dbf0ef00f 100644 --- a/docs/zh/design/appserver/sessions-service.md +++ b/docs/zh/design/appserver/sessions-service.md @@ -224,7 +224,7 @@ Agents 取得该分支的发布观察器,调用 `Session::input`;它像对 | Rpc `session.submit`,协议 v3([connection/tree.rs](../../../../crates/dim-app-server/src/connection/tree.rs)) | 可选的 UUID | — | | Agents `sessions.input`(§6.2) | 必填、非空,按约定为 `:` | — | | 分支 Timeline([core/timeline.rs](../../../../crates/dim-agent-runtime/src/core/timeline.rs)),经 `Session::input` 与 `Session::lookup`(`sessions.input`、`sessions.lookup`、Rpc 的 `session.submit` 与 `session.input_lookup`) | — | 每个分支对每个标识只接受一次;查找回答 `accepted`、`unknown` 或 `ambiguous` | -| Goal 的部件([crates/dim-goal](../../../../crates/dim-goal)) | 经 `TreeCommands::input` 写 `goal:` | 不读取 | +| Goal 的部件([crates/dim-goal](../../../../crates/dim-goal)) | 经 `TimelineTree::input` 写 `goal:` | 不读取 | | Workflow([engine.ts](../../../../runtime/plugins/workflow/engine.ts)) | 每个阶段输入和报告写 `workflow:`,写入前先存入运行文件 | 同一代或替换代重试时以同一标识重新提交,按回复结算 | | Scheduler([A.5](../plugins/Scheduler.md#a5-timeline-与-capability-机制)、[A.6](../plugins/Scheduler.md#a6-运行结果投递);运行时在 draft [#317](https://github.com/arcships/dim/pull/317)) | `scheduler:`,每个投递一个 | 不确定的回复由查询结算(A.6);同一窗口绝不写两次 | | `dimcode` 与 Rust TUI([#312](https://github.com/arcships/dim/pull/312)) | 每次提交新生成一个 UUID | 目前不读取:不确定的提交只报告给用户,不查找 | @@ -303,7 +303,7 @@ Agents 在该分支上用 `Session::service::` 取得 S1 的 InputQu | 项 | 规则 | | --- | --- | | `through` | 带 `atLeast` 时:已发布 head(`Session::sequence`);低于 `atLeast` 时为 `future_sequence`。否则为请求的 `through`(不能超过 head,否则 `future_sequence`),或 head | -| `events` | 该分支自己在 `(after, through]` 内的事件,由 `AgentIndex::history_page` 读取:已装载的线经该分支的 query 分页,并问存储该页最后一条是否结束一个批次;已结束的线在固定的头部经 `TreeCommands.page` 读取;调用前会 acquire 该 Session,本进程不持有的线会被装载而不是直接读存储。读取过程中线结束时会改由 tree 重读同一页。`after`(缺省为 0)必须是某批次的结尾。剩余事件足够时,一页先取 `limit` 条(1 到 256,缺省 256),再读到该批次结尾,因此可能超过 `limit`;它从不越过 `through`。以已发布 head 或 `idle` 截止点作为 `through` 时,每个批次都完整。调用方把 `after` 设为上一页最后的序号继续读,直到 `through` | +| `events` | 该分支自己在 `(after, through]` 内的事件,由 `AgentIndex::history_page` 读取:已装载的线经该分支的 query 分页,并问存储该页最后一条是否结束一个批次;已结束的线在固定的头部经 `TimelineTree.page` 读取;调用前会 acquire 该 Session,本进程不持有的线会被装载而不是直接读存储。读取过程中线结束时会改由 tree 重读同一页。`after`(缺省为 0)必须是某批次的结尾。剩余事件足够时,一页先取 `limit` 条(1 到 256,缺省 256),再读到该批次结尾,因此可能超过 `limit`;它从不越过 `through`。以已发布 head 或 `idle` 截止点作为 `through` 时,每个批次都完整。调用方把 `after` 设为上一页最后的序号继续读,直到 `through` | | 形式 | 分支的每个事件都作为 `AgentEvent` 记录返回,序列化形式与 `session.history` 展示事件时相同。不做过滤,因此一页最后的序号总是某个批次的结尾 | | 祖先 | 不包含。启动的 Session 在 `main` 上读取,`main` 没有祖先。等有使用方需要时,再增加读取子分支前缀的方式 | | 错误 | `rejected`(`after` > `through`、`after` 位于批次中间、`limit` 不在 1 到 256 之间、同时给出 `atLeast` 与 `through`)、`future_sequence`、`session_closed`、`branch_missing`、`reloading` | diff --git a/docs/zh/design/plugin-contract.md b/docs/zh/design/plugin-contract.md index 91601b4992..fc014eb901 100644 --- a/docs/zh/design/plugin-contract.md +++ b/docs/zh/design/plugin-contract.md @@ -57,7 +57,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | 进程(根) | 宿主启动 | 宿主关闭 | —(进程部件自行提供) | | Agent(`agent`) | Agents 创建一个 Agent | Agent 关闭、宿主关闭 | 宿主内部 | -| Session(`session`) | 某个 Agent 创建或恢复一个 Session | Session 关闭、空闲卸载 | `sessionIdentity`、`sessionLifecycle`、`treeCommands` | +| Session(`session`) | 某个 Agent 创建或恢复一个 Session | Session 关闭、空闲卸载 | `sessionIdentity`、`sessionLifecycle`、`timelineTree` | | 分支(`branch`) | TimelineTree 创建一条分支 | 分支结束,或其 Session 关闭 | `timeline`、`dispatcher`、`branchLifecycle`、`timelineIdentity` | 可见性沿树,与[原则 §2](../../architecture/rust-agent/principles.md) 一致: @@ -65,7 +65,7 @@ process (root) process parts: storage, catalogs, connections, Ag | 方向 | 方式 | | --- | --- | | 向上(外层实例、进程) | 按名称注入服务 | -| 向下(Session 到分支) | `treeCommands`:按分支 id 输入、创建分支。从不通过注入分支服务 | +| 向下(Session 到分支) | `timelineTree`:按分支 id 输入、创建分支。从不通过注入分支服务 | | 横向(兄弟分支、其他 Session) | 不可见。经共同祖先的业务服务,例如 `sessions` | 作用域根、门面及其发布规则属于机制。每个 Session 和分支只在其装配 profile 要求的部件都处于 Active @@ -103,7 +103,7 @@ process (root) process parts: storage, catalogs, connections, Ag | `workflowFiles` | 进程 | App Server | 是 | 标记了 `#[rutis::service]` | | `eventHub` | 进程 | EventHub | 已设计,未实现 | 生产方声明来源并发布事件;EventHub 经 Agents 的 `sessions` 把它投递给订阅了的 Session ([EventHub](plugins/EventHub.md)) | | `collaborationMembers:` | 进程 | 成员提供者 | 已设计,未实现 | [ExternalAgent](plugins/ExternalAgent.md);实现时向 Collaboration 登记(rutis 使用 R6) | -| `treeCommands` | `session` | TimelineTree | 是 | 按分支 id 的 `input`、`create`、`list`、`info` | +| `timelineTree` | `session` | TimelineTree | 是 | 按分支 id 的 `input`、`create`、`list`、`info` | | `sessionIdentity` | `session` | SessionScope | 是 | `get()`:`{sessionId, restored}` | | `sessionLifecycle` | `session` | SessionScope | 是 | `activated`、`closing`、`hold`、`release`:hold 是调用方的行拥有的 id,由 `release(id)` 或该行卸载结束 | | `sessionConfig` | `session` | SessionScope | 是 | `get()`:创建时的配置,即工具调用携带的快照 | diff --git a/docs/zh/design/plugins/Collaboration.md b/docs/zh/design/plugins/Collaboration.md index 50f5070905..a316b52061 100644 --- a/docs/zh/design/plugins/Collaboration.md +++ b/docs/zh/design/plugins/Collaboration.md @@ -58,7 +58,7 @@ Session 部件在自己的 `apply` 中为每个标记各注册一个条目,按 | §4 规则 4 核心不带业务含义 | 文本属于 Collaboration,沿声明、工具结果与标记传递;Timeline、Dispatcher 与 Loop 不增加任何 Collaboration 分支 | | §4 规则 5 决定前读完整批次 | 本页不适用:文本由 Session 部件的工具处理与分支部件按派发序的决定写出;本页不增加读取,也不改变决定 | | §4 规则 6 上下文只来自交接后的事件 | 标记只作为被消费的输入到达模型,工具结果只作为 `step/tool-result`;本页不增加上下文路径 | -| §4 规则 7 只用公开事件与服务 | Session 部件声明私有进程级 `Collaboration` 类型依赖,并使用 Session 的 `sessionIdentity`、`sessionConfig`、`treeCommands`、`sessionLifecycle`、`toolRegistry` 与 `guideEntries`,并在部署提供时读取它的公开 `selectableModels` 端口(§7);分支部件注入 Session 的 `CollaborationSession`、`timeline`、`dispatcher`、`timelineIdentity` 与 `branchLifecycle`。公开的 `collaborationSession` 投影遵循 §3 链接的所有者契约;不读其他插件的内部状态 | +| §4 规则 7 只用公开事件与服务 | Session 部件声明私有进程级 `Collaboration` 类型依赖,并使用 Session 的 `sessionIdentity`、`sessionConfig`、`timelineTree`、`sessionLifecycle`、`toolRegistry` 与 `guideEntries`,并在部署提供时读取它的公开 `selectableModels` 端口(§7);分支部件注入 Session 的 `CollaborationSession`、`timeline`、`dispatcher`、`timelineIdentity` 与 `branchLifecycle`。公开的 `collaborationSession` 投影遵循 §3 链接的所有者契约;不读其他插件的内部状态 | | §4 规则 8 向机制所有者提需求 | 对运行时、rutis、loader、生命周期与工具契约无:条目走 Prompt 既有契约,声明走 ToolRegistry,输入走分支既有操作。委派的需求提给 Agents、SessionStore 与删除设计(§6.5) | | §4 规则 9 只有后续决定要用的事实进 Timeline | 不增加 Timeline 事实。两个标记是委派本就需要的模型可见结果,guide 条目是 Prompt 作用域内的注册。委派的所有权与 leader 是不进 Timeline 的业务记录,经 Agents 与 SessionStore 的具名写操作写入(§6),不是事件 | | §1 插件、部件与 Capability 有界 | Collaboration 仍是它现有的 App Server 能力。Session 部件注册声明、工具与条目;分支部件消费委派的事实。不新增 Capability,核心模块不增加业务代码 | diff --git a/docs/zh/design/plugins/ContextCompaction.md b/docs/zh/design/plugins/ContextCompaction.md index 8bbaa766ac..48117a05ce 100644 --- a/docs/zh/design/plugins/ContextCompaction.md +++ b/docs/zh/design/plugins/ContextCompaction.md @@ -47,8 +47,8 @@ F1 把压缩分成三层(§2.2),并新增: | 提供 S:CompactionStrategyHost(Some(摘要策略)) | | ContextMethods(新部件) | | 把 session.context 注册到 sessionMethods:compact, usage | - | compact -> TreeCommands.get(b).service::().compact() - | usage -> TreeCommands.get(b).service::().usage() + | compact -> TimelineTree.get(b).service::().compact() + | usage -> TimelineTree.get(b).service::().usage() +---------------------------------^---------------------------------+ Rpc(C1)分发 ---------' 分支作用域(一个 Timeline,一个 Dispatcher) @@ -64,7 +64,7 @@ F1 把压缩分成三层(§2.2),并新增: +-------------------------------------------------------------------+ ``` -`ProductContextModel` 不需要任何服务,所以是一个普通的 Session 值。ContextMethods 与策略部件分开:分支注入 `CompactionStrategyHost`,它的提供者不能依赖由分支树提供的 `TreeCommands`。 +`ProductContextModel` 不需要任何服务,所以是一个普通的 Session 值。ContextMethods 与策略部件分开:分支注入 `CompactionStrategyHost`,它的提供者不能依赖由分支树提供的 `TimelineTree`。 ### 2.1 手动步骤放在哪里 @@ -318,7 +318,7 @@ pub struct ProductContextModel; // ResolveContextModel,无 pub struct ProductSummaryStrategyPlugin { host: DepKey } // new(names) // Deps = (Keyed, Keyed);提供 CompactionStrategyHost pub struct ContextMethodsPlugin; -// Deps = (Keyed, Keyed);methods.register(ctx, "session.context", ..) +// Deps = (Keyed, Keyed);methods.register(ctx, "session.context", ..) // dim-app-server/src/cli.rs 的 defaults::install_compaction,每种会压缩的配置共用这一处安装; // 产品配置传入 ProductContextModel 和产品 home,--models 配置传入 AimuxModels 和它的 --home: @@ -650,7 +650,7 @@ consume pending inputs --> prepare next request | §4 规则 4(核心无业务含义) | Timeline、Dispatcher 和门面不变。清单由 ContextPolicy 从 `step/tool-result` 事实上的声明组合;核心没有任何部分认识效果类型。 | | §4 规则 5(原子批次) | 每次新写入都是一个事件。 | | §4 规则 6(上下文只来自交接后的事件) | 替换内容只经已完成事实的投影到达模型。待处理输入不被步骤消费(AGENTS 规则 10)。 | -| §4 规则 7(公开事件与服务) | `TreeCommands`、`PublicService` 上的 `Branch::service`、`ProviderConnectionResolver`、`ModelHost`、`sessionMethods`。 | +| §4 规则 7(公开事件与服务) | `TimelineTree`、`PublicService` 上的 `Branch::service`、`ProviderConnectionResolver`、`ModelHost`、`sessionMethods`。 | | §4 规则 8(基础设施不变) | Dispatcher、信封、rutis、loader、Agent 装配和门面都不改。有一处基础设施改动(#130):Timeline 与两个存储的快照锚定不再了解 `context/compaction`,只保留结构检查,所有者的解码回调接收锚点事件。需求来自 Timeline 自身:它不能了解事件内容(原则 §4 规则 4;Timeline 只检查信封与核心保留领域,ADR 001)。它在 Timeline 自己的合同内闭环:快照是带结构锚点的缓存。有效快照的行为不变,无效快照算作缓存未命中。| | §4 规则 9(只写需要的事实) | `context/compact` 由 Loop 后续的决定和重载读取。`context/compaction` 用于投影。按维护者的决定,`context/compaction-start` 和可见的结果都是事实,理由有两条。第一,它们不只是驱动某个状态机:用户和其他状态机读取历史时需要这些内容(任何时候接入的 UI 都必须看到压缩正在进行,或者它是怎样结束的)。第二,重载结算要用它们:没有结果的开始意味着当时有压缩在途。Loop 和 ContextPreparation 由开始与结果的配对重建,这比只靠指令更精确:它能区分运行中和待处理,也覆盖自动压缩。用量查询不写任何东西。已完成结果的 `modelUsage` 与 `insufficientSpace` 是这条必需事实上的描述性字段:触发点读最近一条开始事实的 `through`,预算恢复读预算,只有客户端读成本和标记。清单不新增事实:它由 `step/tool-result` 事实本来就携带的声明组合进现有的替换内容。后续压缩的滚动正是已完成结果以数据形式保存条目的原因(`digest_entries`):那个决定读这个字段,绝不读渲染出的消息,而这个字段是投影本来就会读取的事实上的可选部分。 | | ADR 002 D1(作用域) | 窗口事实、策略和方法:Session。指令、步骤和压缩槽:分支,在 Loop 中。钉住、清单、保留规则和标记是分支作用域的 ContextPolicy 工作:它们读分支的事件并组合它的记录。 | diff --git a/docs/zh/design/plugins/Goal.md b/docs/zh/design/plugins/Goal.md index 99ad52201e..6ea101bd47 100644 --- a/docs/zh/design/plugins/Goal.md +++ b/docs/zh/design/plugins/Goal.md @@ -4,7 +4,7 @@ 需求([功能列表](../../../feature-list.md),分支 Agent 行为):`/goal` 设置、编辑、暂停、恢复和清除目标("切换 Goal 模式");Goal 续跑朝明确的目标继续工作,并记录完成或受阻。 -Goal 在分支上保持一个常驻目标,并自动续跑该分支,直到模型报告目标已完成或受阻、用户暂停、清除或中断,或达到显式设置的续跑上限。Goal 是分支上的事件驱动状态机。**Goal 的状态是一条 `goal:state` 块**:一条普通的 `input/message`,带一个带 key 的 raw 块,Append,只由 Goal 的分支部分写入,因此模型、客户端与折叠读到同一个事实(§2、A.5)。**变更是一个触发器,不是状态陈述**:`session.goal.*` 的 `set`、`edit`、`pause`、`resume`、`clear` 与模型 `goal_update` 工具的 `completed` / `blocked` 各经 `treeCommands.inputs`(即 `Branch::inputs`)提交一个原子批次、两条输入:回答它的状态记录,然后是触发器;触发器是一个无 key 的块,说明被要求了什么;Goal 把每个触发器的记录写进同一批次、紧排在其前。记录出现之前写成的历史带旧 key `goal:objective` 与 `goal:status`,按旧规则折叠;其上第一个被回答的触发器写入一条记录。**一个目标只属于一个分支**:Goal 对分支 `B` 的折叠只使用写在 `B` 自身上的事件(从 `B` 的 `branch/start` 起的本地后缀),从不使用继承的前缀,因此子分支和分叉 Session 的 `main` 都从没有目标开始;若新分支继承的前缀中仍有存活的目标 key,它用自己的一次起始 clear 退役它([§3.4](#34-新分支清除继承的目标))。续跑不带 key,也不是变更。工具和方法只写触发器;它们不读 Goal 的状态,也不判断变更是否允许。**Goal 的折叠就是最新记录陈述的状态**,按序号顺序,用固定规则计算([§2](#2-数据与状态))。**分支部分**拥有这个折叠结果;它的 Dispatcher 处理器消费 `turn/end`、`stop/interrupt`、`input/deleted` 或 cancelled 的 `exec/ended` 时,只依据已消费的状态自己决定是否续跑;决定需要写入(续跑、状态记录或自动暂停)时,处理器把写入登记为自己拥有的工作,然后返回。**Session 部分**把 `goal_update` 工具注册到本 Session 的 `toolRegistry`,并把命名空间 `session.goal` 注册到本 Session 的 `sessionMethods`,以此提供 `session.goal.*` 方法([session-boundary](../contracts/session-boundary.md));每次调用按分支 id 经 `treeCommands.inputs`(即分支的公开多输入入口 `Branch::inputs`)把它的记录与触发器作为一个原子批次提交到调用方分支或指定分支。没有调用读取折叠结果:Session 部分从不向分支部分询问任何东西,Session 部分也不能依赖每个分支各一份的服务(ADR 002 D3)。Goal 不写自己类型的事件,也没有单独的"Goal 模式":目标的存在与状态可通过分支上存活的 goal 块看到(§6),覆盖了功能列表中"切换 Goal 模式"的说法。本文的每个契约都是语言中立的(服务名、作用域、key、带数据形状的方法、工具注册);Rust 绑定见[附录 G](#附录-g-rust-绑定)。Goal 通过公开的 Rust 导出使用运行时服务:Session 部分用 `TreeCommands` 和 `ToolRegistry`,分支部分用 `Dispatcher`、`Timeline`、`TimelineIdentity` 和 `TreeCommands`。 +Goal 在分支上保持一个常驻目标,并自动续跑该分支,直到模型报告目标已完成或受阻、用户暂停、清除或中断,或达到显式设置的续跑上限。Goal 是分支上的事件驱动状态机。**Goal 的状态是一条 `goal:state` 块**:一条普通的 `input/message`,带一个带 key 的 raw 块,Append,只由 Goal 的分支部分写入,因此模型、客户端与折叠读到同一个事实(§2、A.5)。**变更是一个触发器,不是状态陈述**:`session.goal.*` 的 `set`、`edit`、`pause`、`resume`、`clear` 与模型 `goal_update` 工具的 `completed` / `blocked` 各经 `timelineTree.inputs`(即 `Branch::inputs`)提交一个原子批次、两条输入:回答它的状态记录,然后是触发器;触发器是一个无 key 的块,说明被要求了什么;Goal 把每个触发器的记录写进同一批次、紧排在其前。记录出现之前写成的历史带旧 key `goal:objective` 与 `goal:status`,按旧规则折叠;其上第一个被回答的触发器写入一条记录。**一个目标只属于一个分支**:Goal 对分支 `B` 的折叠只使用写在 `B` 自身上的事件(从 `B` 的 `branch/start` 起的本地后缀),从不使用继承的前缀,因此子分支和分叉 Session 的 `main` 都从没有目标开始;若新分支继承的前缀中仍有存活的目标 key,它用自己的一次起始 clear 退役它([§3.4](#34-新分支清除继承的目标))。续跑不带 key,也不是变更。工具和方法只写触发器;它们不读 Goal 的状态,也不判断变更是否允许。**Goal 的折叠就是最新记录陈述的状态**,按序号顺序,用固定规则计算([§2](#2-数据与状态))。**分支部分**拥有这个折叠结果;它的 Dispatcher 处理器消费 `turn/end`、`stop/interrupt`、`input/deleted` 或 cancelled 的 `exec/ended` 时,只依据已消费的状态自己决定是否续跑;决定需要写入(续跑、状态记录或自动暂停)时,处理器把写入登记为自己拥有的工作,然后返回。**Session 部分**把 `goal_update` 工具注册到本 Session 的 `toolRegistry`,并把命名空间 `session.goal` 注册到本 Session 的 `sessionMethods`,以此提供 `session.goal.*` 方法([session-boundary](../contracts/session-boundary.md));每次调用按分支 id 经 `timelineTree.inputs`(即分支的公开多输入入口 `Branch::inputs`)把它的记录与触发器作为一个原子批次提交到调用方分支或指定分支。没有调用读取折叠结果:Session 部分从不向分支部分询问任何东西,Session 部分也不能依赖每个分支各一份的服务(ADR 002 D3)。Goal 不写自己类型的事件,也没有单独的"Goal 模式":目标的存在与状态可通过分支上存活的 goal 块看到(§6),覆盖了功能列表中"切换 Goal 模式"的说法。本文的每个契约都是语言中立的(服务名、作用域、key、带数据形状的方法、工具注册);Rust 绑定见[附录 G](#附录-g-rust-绑定)。Goal 通过公开的 Rust 导出使用运行时服务:Session 部分用 `TimelineTree` 和 `ToolRegistry`,分支部分用 `Dispatcher`、`Timeline`、`TimelineIdentity` 和 `TimelineTree`。 ## 1. 结构 @@ -17,7 +17,7 @@ flowchart LR subgraph SESS["Session 作用域"] GS["GoalSession:工具 goal_update,sessionMethods session.goal"]:::new TR["ToolRegistry"] - TC["TreeCommands"] + TC["TimelineTree"] end subgraph BR["分支作用域"] GB["GoalBranch(goal:折叠、决策)"]:::new @@ -26,7 +26,7 @@ flowchart LR end GS -- "注册 goal_update" --> TR Rpc -- "解析 Session,调用 sessionMethods session.goal" --> GS - GS -- "每次调用:treeCommands.inputs(branchId, [记录, 触发器])" --> TC + GS -- "每次调用:timelineTree.inputs(branchId, [记录, 触发器])" --> TC TC -- "Branch::inputs:kind=state 记录(goal:state,Append)然后 kind=goal 触发器(无 key),一个原子批次" --> TL TL -- "按顺序 branch/start、input/*、turn/*、stop/interrupt" --> GB GB -- "自有写入任务:turn end 或删除之后的记录、续跑或起始 clear" --> TL @@ -39,8 +39,8 @@ flowchart LR | 部分 | 作用域 | 依赖 | 提供 | | --- | --- | --- | --- | -| `GoalSession` | Session | `TreeCommands`、`ToolRegistry`、`SessionMethods`、`GuideEntries`(Session 导出) | 把 `goal_update` 注册到 `ToolRegistry`,把 `session.goal` 注册到 `SessionMethods`;经 `TreeCommands::inputs` 按分支 id 把每次变更作为一个原子批次提交(记录在前,触发器在后) | -| `GoalBranch` | 分支 | `Dispatcher`、`Timeline`、`TimelineIdentity`、`BranchLifecycle`(分支导出)、`SessionLifecycle`(Session 导出,用于加载时核对)、`TreeCommands`、用于其来源 `goal` 的进程服务 `Settings`(S8b) | 不提供服务;拥有折叠结果、续跑决策、状态记录和 Goal 自己的写入 | +| `GoalSession` | Session | `TimelineTree`、`ToolRegistry`、`SessionMethods`、`GuideEntries`(Session 导出) | 把 `goal_update` 注册到 `ToolRegistry`,把 `session.goal` 注册到 `SessionMethods`;经 `TimelineTree::inputs` 按分支 id 把每次变更作为一个原子批次提交(记录在前,触发器在后) | +| `GoalBranch` | 分支 | `Dispatcher`、`Timeline`、`TimelineIdentity`、`BranchLifecycle`(分支导出)、`SessionLifecycle`(Session 导出,用于加载时核对)、`TimelineTree`、用于其来源 `goal` 的进程服务 `Settings`(S8b) | 不提供服务;拥有折叠结果、续跑决策、状态记录和 Goal 自己的写入 | Session 部分在 apply 中把工具注册到 `ToolRegistry`,把方法命名空间 `session.goal` 注册到 `SessionMethods`。分支部分不提供服务;它作为分支定义注册,因此每个分支都有一份副本(C5)。安装了 Goal 的装配的每个 Session 都运行 Goal 的 Session 部分,因此该部分激活后,每个这样的 Session 都有 `session.goal`([session-boundary A.1](../contracts/session-boundary.md#a1-方法贡献))。`maxContinuations` 是 Goal 的 Settings 来源 `goal` 中文档的可选字段,属于业务配置([ADR 002](../../adr/002-plugin-scope.md) D4)。Goal 只通过 S8b 的进程服务 `settings` 读取它([Settings 服务](../appserver/settings-service.md)):每次使用时调用 `Settings::read`,经其公开的 Rust 绑定。Goal 的行在其 `apply` 中按 S8b §3.1 登记该来源:`source: "goal"`,一个用户文件,没有项目文件(只有用户作用域),没有 user-only 字段,JSON Schema 中 `maxContinuations` 为整数,`minimum: 1`、`maximum: 1000`,没有默认值(A4)。字段缺失表示没有上限;`null` 不是合法值。Settings 在写入和读取持久化文件时校验,因此 Goal 按交付的样子使用文档;变更是数据更新,从不重载。Dispatcher 回调登记自有任务后即返回,不等待 Settings。分支发布后,每个 turn/end 任务使用时调用 `settings.read {source: "goal", scope: "user"}`,再在写入前复核其决定轮次及当前已消费的折叠结果(A.6)。不缓存上限,也不监听 `settings.changed`。在该读取前已提交的变更无须重载即生效,包括文件后端 Settings 用户文档的直接编辑。来源不可读时停止该次决策,不产生自动输入,也不使用回退上限(附录 C)。中断暂停与继承目标的起始 clear 不需要读取上限。Goal 的工具都不写它;客户端经 `settings.read`/`settings.update` 写入它。Goal 只读取 `branch/start`、`input/message`、`input/consumed`、`input/deleted`、`turn/start`、`turn/end`、`stop/interrupt`、`exec/started` 和 `exec/ended` 的公开数据契约,并在 turn/end 决策时读取结束回合的一页有界 `step/tool-call`(A.4 C7);从不读取其他插件的状态。 @@ -70,7 +70,7 @@ flowchart TB Goal 不拥有自己类型的持久状态。分支 `B` 的目标是 `B` 本地事件中最新的存活 `goal:state` 块所陈述的状态;在记录出现之前写成的历史上,则是按下面规则折叠的两个旧 key。只有 Goal 的分支部分写这条记录。它是一条普通的 `input/message`,带一个 key 为 `goal:state` 的 raw 块,模式 Append,因此模型、客户端与 Goal 的折叠读到同一个事实:模型经 `render_input`,客户端经分支历史或通用带 key 投影,折叠经其 Dispatcher 订阅。没有为它特判任何规则或 ADR:这个块像其他被采用的输入一样进入模型上下文,压缩也像其他 key 一样经带 key 的基线重放它。 -**变更**是触发器,不是状态陈述。`session.goal.set/edit/pause/resume/clear` 与 `goal_update` 经 `TreeCommands::inputs`(`Branch::inputs`)提交一个原子批次、两条输入:回答该变更的状态记录,然后是触发器,其唯一的 raw 块 `kind="goal"`,说明被要求了什么(A.5),模式不变。记录排在前面,因此无论调度如何,InputQueue 都先应用记录、再应用触发器:触发器的轮次开始时,记录已经应用。分支部分在自己的写锁下撰写记录,且要等折叠已推进 Goal 自己的上一次写入,因此记录基于它之前的状态陈述该变更。记录按 submission id 在 `trigger="goal:"` 中写名触发器,而不是 `after`(A.5);折叠把这样的记录暂留一个事件,当下一个事件正是写名的触发器时,在触发器的序号处先应用变更、再应用记录(A14)。给定 `after` 的快照只写一次。没有记录的触发器——更早版本写成的历史,或批次之外写入的触发器——在加载时被回答一次(§4.2)。被 InputQueue 删除的变更触发器从未生效:折叠去掉它重新计算;只要已有写名该触发器的记录或任何更晚的记录曾被写入或正在被写入,Goal 就写一条补偿记录,其 `after` 是 `input/deleted` 的序号,陈述分支去掉该触发器后的状态。是否存在这样的记录在写锁下决定,因此在删除被折叠期间提交的记录会被补偿记录取代,绝不会成为最新的存活记录。 +**变更**是触发器,不是状态陈述。`session.goal.set/edit/pause/resume/clear` 与 `goal_update` 经 `TimelineTree::inputs`(`Branch::inputs`)提交一个原子批次、两条输入:回答该变更的状态记录,然后是触发器,其唯一的 raw 块 `kind="goal"`,说明被要求了什么(A.5),模式不变。记录排在前面,因此无论调度如何,InputQueue 都先应用记录、再应用触发器:触发器的轮次开始时,记录已经应用。分支部分在自己的写锁下撰写记录,且要等折叠已推进 Goal 自己的上一次写入,因此记录基于它之前的状态陈述该变更。记录按 submission id 在 `trigger="goal:"` 中写名触发器,而不是 `after`(A.5);折叠把这样的记录暂留一个事件,当下一个事件正是写名的触发器时,在触发器的序号处先应用变更、再应用记录(A14)。给定 `after` 的快照只写一次。没有记录的触发器——更早版本写成的历史,或批次之外写入的触发器——在加载时被回答一次(§4.2)。被 InputQueue 删除的变更触发器从未生效:折叠去掉它重新计算;只要已有写名该触发器的记录或任何更晚的记录曾被写入或正在被写入,Goal 就写一条补偿记录,其 `after` 是 `input/deleted` 的序号,陈述分支去掉该触发器后的状态。是否存在这样的记录在写锁下决定,因此在删除被折叠期间提交的记录会被补偿记录取代,绝不会成为最新的存活记录。 折叠在变更 `input/message` 的序号处应用它,并在同一条序号处应用批次中的记录(A14),因此没有任何决策会看到没有记录的触发器。它忽略三类记录:`after` 写名已被删除的变更的、比已折叠的最新变更更旧的、以及比已应用的最新记录更旧的;Goal 也从不撰写 `after` 低于自己已写记录的记录,因此无论写入任务的提交顺序如何,最新的存活记录总是陈述最新的状态。**模型**在受该变更影响的第一个请求处得知它:记录在同一原子批次中排在触发器之前提交,且 InputQueue 按序号顺序应用输入,因此携带触发器的第一个请求已经带着排在它之前的记录。Queue 命令仍驱动自己的轮次(A14)。之后被 InputQueue 删除(`input/deleted`)的变更被移除,折叠去掉它重新计算([session access](../contracts/session-access.md))。 @@ -287,13 +287,13 @@ Goal 只在它服务的分支上以来源 `goal` 写入 `input/message`;由此 | §1 Capability 与 App Server 边界 | 两个部分都是各自包中的 Capability;Rpc 只分派 `sessionMethods`。 | | ADR 002 D1 作用域跟随状态所有者 | 工具与方法是 Session 服务;目标、其折叠结果与决策是分支状态。 | | ADR 002 D2 不设接线模块 | Goal 自己把命名空间注册到 `sessionMethods`、把工具注册到 ToolRegistry;Rpc 经该 Session 的方法表分发,没有模块指名 Goal。 | -| ADR 002 D3 依赖跟随作用域 | 分支部分依赖分支服务与外层的 Session、进程服务(`treeCommands`、`settings`);Session 部分不依赖任何分支服务;重载重新折叠,可接受。 | +| ADR 002 D3 依赖跟随作用域 | 分支部分依赖分支服务与外层的 Session、进程服务(`timelineTree`、`settings`);Session 部分不依赖任何分支服务;重载重新折叠,可接受。 | | ADR 002 D4 结构性配置与业务配置分离 | `goal` 来源中的 `maxContinuations` 是业务配置,在自有 turn/end 任务内、已消费状态复核之前读取;不缓存或订阅配置事件。变更从不重载 Goal。 | | ADR 002 D5 合同语言中立 | 工具、方法与块格式以中立形式给出;§10 是 Rust 实现,附录 G 是它的绑定。 | ## 9. 向机制所有者提出的需求 -输入入口每次调用只提交一条输入,变更触发器与其记录因此无法共享一次提交。需求——一个原子多输入提交:批次整体校验、只准入一次,按给定顺序返回已提交事件,对已提交的 id 幂等重放——由输入入口的多输入提交满足:`TreeCommands::inputs`、`Session::inputs` 与 `Branch::inputs`,契约见 [interrupt §2](../../../architecture/rust-agent/interrupt.md#2-事件契约)。Goal 的变更批次是它的第一个消费者(#1195,[#1215](https://github.com/arcships/dim/pull/1215))。之前的需求"运行时服务按名字暴露给非 Rust 部分"(#4)已由 C5 交付([分支 TypeScript 绑定](../../../design/branch-typescript.md))。 +输入入口每次调用只提交一条输入,变更触发器与其记录因此无法共享一次提交。需求——一个原子多输入提交:批次整体校验、只准入一次,按给定顺序返回已提交事件,对已提交的 id 幂等重放——由输入入口的多输入提交满足:`TimelineTree::inputs`、`Session::inputs` 与 `Branch::inputs`,契约见 [interrupt §2](../../../architecture/rust-agent/interrupt.md#2-事件契约)。Goal 的变更批次是它的第一个消费者(#1195,[#1215](https://github.com/arcships/dim/pull/1215))。之前的需求"运行时服务按名字暴露给非 Rust 部分"(#4)已由 C5 交付([分支 TypeScript 绑定](../../../design/branch-typescript.md))。 ## 10. 实现 @@ -304,10 +304,10 @@ Rust,位于 `crates/dim-goal`,为一行:其 `install` 注册 Settings 来 | `text.rs` | 共享:变更触发器、状态记录与续跑输入(A.5)、标记编码、两句策略文本 | — | | `fold.rs` | 共享:已消费事实上的折叠(§2)与决策(A.4) | — | | `lib.rs` | 该行:注册 `goal` Settings 来源与两个部分;`install_with` 接收两句策略文本 | 进程行 | -| `session.rs` | `GoalSession`:把 `` 引导条目(A.5.1)注册到 `GuideEntries`,把 `goal_update` 注册到 `ToolRegistry`,把 `session.goal` 注册到 `SessionMethods`;经 `TreeCommands::inputs` 提交每个变更批次 | Session 部分 | +| `session.rs` | `GoalSession`:把 `` 引导条目(A.5.1)注册到 `GuideEntries`,把 `goal_update` 注册到 `ToolRegistry`,把 `session.goal` 注册到 `SessionMethods`;经 `TimelineTree::inputs` 提交每个变更批次 | Session 部分 | | `branch.rs` | `GoalBranch`:用 `Dispatcher::consume` 注册,折叠重建读到的内容(先走便宜路径),对实时事件决策,并以自有任务写入状态记录、续跑与 clear;从 `goal` 来源读取 `maxContinuations`。在 [Pursuit](Pursuit.md) 的评审裁判下它还创建评审分支并担任评审者角色 | 分支部分 | -新分支检查(§3.4)按祖先逐个读取继承前缀,从最近的开始,用 `TreeCommands::query` 查该祖先自己的线:`input/message`,从新到旧,每一页都在上一页之下有界,遇到第一个带 key 的块即停止。分支自己的事件从不参与这次读取,因此只看到继承前缀。嵌入方用 +新分支检查(§3.4)按祖先逐个读取继承前缀,从最近的开始,用 `TimelineTree::query` 查该祖先自己的线:`input/message`,从新到旧,每一页都在上一页之下有界,遇到第一个带 key 的块即停止。分支自己的事件从不参与这次读取,因此只看到继承前缀。嵌入方用 `dim_goal::install(&mut AgentBuilder)` 安装 Goal,或用 `install_with` 带上候选策略文本;`dimcode` 产品 profile 在其 install 回调中这样做,App Server 库不依赖本 crate。 验证覆盖精确事件顺序,以及实际插件的公开端口流程。 @@ -334,7 +334,7 @@ ToolRegistry 即提供它([Session 边界 A.5](../contracts/session-boundary.m | 结果 | `ToolResult.content`:`goal_update recorded: completed.` 或 `goal_update recorded: blocked.` 结果只确认写入;按折叠规则,该块成为当前状态(A15),[Pursuit](Pursuit.md) 的评审裁判下干活模型的 `completed` 除外,它是请求(A16)。错误只有参数错误 | | 风险类别 | `session`(只写分支输入)(A9) | | 提供范围 | 安装了 Goal 的装配中的每个 Session,所有角色(A9) | -| 处理器 | 校验参数,经 `treeCommands.inputs` 在调用方分支(`ToolCall.branchId`)上把该变更的记录与触发器作为一个原子批次提交,等待提交后返回。它不读折叠结果。在追加之前取消则不写任何内容;一旦追加,写入保持有效 | +| 处理器 | 校验参数,经 `timelineTree.inputs` 在调用方分支(`ToolCall.branchId`)上把该变更的记录与触发器作为一个原子批次提交,等待提交后返回。它不读折叠结果。在追加之前取消则不写任何内容;一旦追加,写入保持有效 | ### A.2 Session 方法 @@ -348,7 +348,7 @@ ToolRegistry 即提供它([Session 边界 A.5](../contracts/session-boundary.m | `session.goal.resume` | `{sessionId, branchId?}` | `{sequence}` | `resume`,Queue(A12) | | `session.goal.clear` | `{sessionId, branchId?}` | `{sequence}` | `clear`(退役 key),Append | -`branchId` 默认为 `main`(A13)。回复中的 `sequence` 是变更触发器的序号,它在同一原子批次中紧跟在记录之后提交;客户端在分支事件的该序号处看到它的效果。写入类方法只校验自己的参数;变更起什么作用由 §2 的折叠规则决定(每个块成为其 key 的当前值),从不由方法决定。Rpc 从参数中读取 `sessionId` 并授权,经 `index.acquire` 解析 Session(若已卸载则恢复),再携带原始参数发送调用;处理器经 `treeCommands.inputs` 按 id 把该批次写入指定分支。 +`branchId` 默认为 `main`(A13)。回复中的 `sequence` 是变更触发器的序号,它在同一原子批次中紧跟在记录之后提交;客户端在分支事件的该序号处看到它的效果。写入类方法只校验自己的参数;变更起什么作用由 §2 的折叠规则决定(每个块成为其 key 的当前值),从不由方法决定。Rpc 从参数中读取 `sessionId` 并授权,经 `index.acquire` 解析 Session(若已卸载则恢复),再携带原始参数发送调用;处理器经 `timelineTree.inputs` 按 id 把该批次写入指定分支。 ### A.3 读取目标 @@ -617,5 +617,5 @@ Goal 以 Rust 实现(§10);中立契约的绑定如下。 | 卸载清理函数 | `ctx.effect` | | `goal` Settings 来源 | 进程行中调用 `Settings::register`;每次决策用 `Settings::read(SOURCE, SettingsScope::User, &cancel)` 读取 | | 写入任务 | `TaskTracker` 上的自有工作,由 `Dispatcher` 处理器的 `consume` 生成,以做出决定的序号为键;`ctx.effect` 的清理关闭并等待它 | -| 写入 | 每个变更批次经 `TreeCommands::inputs`,来自 Session 部分的调用与 `goal_update` 工具;写入任务经 `TreeCommands::input` | -| Context 与重建 | 服务经 `ctx.require_at` 取得;分支事实经 `Timeline::query(TimelineQueryScope::Branch, ..)`,来源经 `TreeCommands::info`;角色解析前等待 `SessionLifecycle::activated`;重建先走便宜路径(一次降序输入扫描直到最新的 Goal 块),否则折叠其事实,然后执行 `decide_end`、`settle`、`decide_start`,并在任何实时事件之前回答一个未回答的变更触发器 | +| 写入 | 每个变更批次经 `TimelineTree::inputs`,来自 Session 部分的调用与 `goal_update` 工具;写入任务经 `TimelineTree::input` | +| Context 与重建 | 服务经 `ctx.require_at` 取得;分支事实经 `Timeline::query(TimelineQueryScope::Branch, ..)`,来源经 `TimelineTree::info`;角色解析前等待 `SessionLifecycle::activated`;重建先走便宜路径(一次降序输入扫描直到最新的 Goal 块),否则折叠其事实,然后执行 `decide_end`、`settle`、`decide_start`,并在任何实时事件之前回答一个未回答的变更触发器 | diff --git a/docs/zh/design/plugins/ModelRecovery.md b/docs/zh/design/plugins/ModelRecovery.md index 9e06249246..af3f5e86d0 100644 --- a/docs/zh/design/plugins/ModelRecovery.md +++ b/docs/zh/design/plugins/ModelRecovery.md @@ -17,7 +17,7 @@ flowchart LR LP["Loop"] MR["ModelRecovery:处置方"]:::new TL["Timeline + Dispatcher"] - TC["TreeCommands:Branch::input"] + TC["TimelineTree:Branch::input"] IQ["InputQueue"] end MP -- "step/model-output-end(failed)" --> LP @@ -33,7 +33,7 @@ flowchart LR | 部分 | 作用域 | 依赖 | 提供 | | --- | --- | --- | --- | -| `ModelRecovery` 分支部分 | 分支 | `B:AgentLoop`(处置方端口)、`B:Timeline`(已提交事实查询)、`S:TreeCommands`(handover 输入) | 一个处置方注册;不提供服务 | +| `ModelRecovery` 分支部分 | 分支 | `B:AgentLoop`(处置方端口)、`B:Timeline`(已提交事实查询)、`S:TimelineTree`(handover 输入) | 一个处置方注册;不提供服务 | Loop 的端口在每个分支上只接受一个处置方,第二次注册失败。注册是该部分的效果,因此卸载会撤回它;Loop 的任务随后回答 `finish`,打开的交接结束。该部分是分支部分,因此每个分支各有一份。 diff --git a/docs/zh/design/plugins/PromptSuggestion.md b/docs/zh/design/plugins/PromptSuggestion.md index be31257a02..763fca47f4 100644 --- a/docs/zh/design/plugins/PromptSuggestion.md +++ b/docs/zh/design/plugins/PromptSuggestion.md @@ -13,7 +13,7 @@ PromptSuggestion 提示用户接下来可能发送的消息。当一个看到某 | 部件 | 作用域 | 它拥有的状态 | 依赖 | 提供 | | --- | --- | --- | --- | --- | | `PromptSuggestionSettings` | 进程(App Server) | `prompt-suggestion` Settings 来源 | `P:Settings` | `P:PromptSuggestionSettingsHost` | -| `PromptSuggestion` | Session | 最近完成轮次的请求与内容、在途请求、正在显示的提示、未采用计数 | `S:SessionIdentity`、`S:SessionConfig`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TreeCommands`、`P:ModelHost`、产品 process 模型模式下的 `P:ProviderConnectionResolver`,以及装配绑定时的 `P:PromptSuggestionSettingsHost` | 通过 `sessionMethods` 提供 `session.suggestion` | +| `PromptSuggestion` | Session | 最近完成轮次的请求与内容、在途请求、正在显示的提示、未采用计数 | `S:SessionIdentity`、`S:SessionConfig`、`S:SessionLifecycle`、`S:SessionMethods`、`S:TimelineTree`、`P:ModelHost`、产品 process 模型模式下的 `P:ProviderConnectionResolver`,以及装配绑定时的 `P:PromptSuggestionSettingsHost` | 通过 `sessionMethods` 提供 `session.suggestion` | 进程部件在本 daemon 其他业务来源所在的位置声明该来源,与 `ExecutionSettings`、`ModelLog` 并列;该来源是各 Session 共用的进程状态,所以不是 Session 部件([ADR 002 D1](../../adr/002-plugin-scope.md))。Session 部件在每次决策时通过宿主端口读取该来源([ADR 002 D4](../../adr/002-plugin-scope.md)):修改 `enabled` 或 `maxChars` 从不重载任何部件。 @@ -301,7 +301,7 @@ CLI 只在看到该轮 `turn/end` 为 `Completed` 之后、且输入框为空、 | `ModelHost` | `invoke` | async | `{request, connection, cancel}` | `ModelChunk` 流 | | `ProviderConnectionResolver` | `resolve` | async | `{request, cancel}` | `{connection, failurePolicy, recovery}`(仅 process 模型;本地模型发送 `ModelConnection::Local`,其装配用 `install_local` 而不是 `install` 装载该部件) | | `SessionMethods` | `register` | sync | 命名空间 `session.suggestion`,两个声明 | 登记随该部件的代结束 | -| `TreeCommands` | `get` | sync | `main` | 分支,上下文门读取其 `ContextPreparation::usage` | +| `TimelineTree` | `get` | sync | `main` | 分支,上下文门读取其 `ContextPreparation::usage` | | Session 广播 | `session/{sessionId}` 上的记录 | 总线事件 | - | `Event {branchId, event}`、`Notice`、`Fence`、`Closed` | | Settings 来源 `prompt-suggestion` | `read` | async | 用户作用域 | `{enabled, maxChars}` | diff --git a/docs/zh/design/plugins/Pursuit.md b/docs/zh/design/plugins/Pursuit.md index b1f2875351..acd596051d 100644 --- a/docs/zh/design/plugins/Pursuit.md +++ b/docs/zh/design/plugins/Pursuit.md @@ -14,7 +14,7 @@ | P2 | 裁判由 `set` 按目标选择,记在 `set` 块上 | 它是用户对这个目标的意图,属于 Timeline 事实 | | P3 | 在干活模型的完成报告让 Goal 停下时评审 | 只有这个点是干活的模型认为目标已完成。干活模型的 `blocked` 直接生效(需要用户处理);上限,以及用户自己的中断或暂停,都不是完成,不启动任何东西 | | P4 | 评审裁判下干活模型的 `completed` 是请求,状态保持 `active` | 只有评审者能使目标完成。这是 Goal 折叠规则唯一的例外,随本设计记录在 [Goal A16](Goal.md#附录-e-假设) 中(维护者决定,2026-10-22) | -| P5 | 评审者是在该 `turn/end` 处切出的子分支 | 它能看到做了什么、为什么做,在同一策略下运行,是用 `treeCommands.create` 创建的普通分支 | +| P5 | 评审者是在该 `turn/end` 处切出的子分支 | 它能看到做了什么、为什么做,在同一策略下运行,是用 `timelineTree.create` 创建的普通分支 | | P6 | 评审者把结论作为输入写到工作分支;由那里的 Goal 决定 | 分支只折叠自己的事件;跨分支通信就是按 id 写输入([插件契约 §5.2](plugin-contract.md#52-消费事实)),一条线经工具结果读取它被切出来的那条线([Timeline 分支](../../../design/timeline-branches.md#6-线之间的消息) §6)。调用方写,所有者决定 | ## 2. 用户流程 @@ -53,7 +53,7 @@ | 消费的事件 | 条件 | 动作 | | --- | --- | --- | -| `turn/end` N | Goal 的 C1–C4 满足(目标 active、未中断、回合 `completed`、是最新的且未决定),裁判为 `evaluator`,且该回合包含干活模型的 `completed` 块 | 取代 Goal 的续跑决定:`treeCommands.create(B, N, {prompt, source: {kind: "host", operation_id: "goal:evaluate:N"}}, cancelled)`。Goal 的 `decided` 把该 `branch/create` 算作 `N` 的决定(§3),所以重载不会再次创建 | +| `turn/end` N | Goal 的 C1–C4 满足(目标 active、未中断、回合 `completed`、是最新的且未决定),裁判为 `evaluator`,且该回合包含干活模型的 `completed` 块 | 取代 Goal 的续跑决定:`timelineTree.create(B, N, {prompt, source: {kind: "host", operation_id: "goal:evaluate:N"}}, cancelled)`。Goal 的 `decided` 把该 `branch/create` 算作 `N` 的决定(§3),所以重载不会再次创建 | | `goal:evaluate:N` 的 `branch/create-failed`,或在 `N` 的任何 `branch/create` 提交之前 `create` 抛出 | `N` 仍是当前评审 | 暂停(`evaluation_failed`),与 Goal 的暂停一样标记 `after="N"`;两者中先写出暂停的一个使 `N` 对另一个而言已被取代。已提交的创建会记录自己的结果(子分支或 `branch/create-failed`),由那个事实决定;因任务被取消而抛出时不写任何东西 | | 评审 `N` 的结论输入 | 是 `N` 的第一份结论,来自 `goal:evaluate:N` 的 `branch/create` 所记录的分支,且 `N` 仍是当前评审:`N` 之后没有更新的变更:`set`、`edit`、`clear`、`pause` 或 `resume` 触发器、干活模型新的 `completed`,或旧历史中带 key 的块。Goal 为回答 `N` 自己回合内的变更而写的 `goal:state` 记录是那个变更的陈述,不是新的变更,因此不会让 `N` 过期;暂停目标的记录通过状态本身停止结论 | `done`:评审者判定的 `completed`。`blocked`:评审者判定的 `blocked`。`continue`:Goal 的续跑决定([Goal A.4](Goal.md#a4-续跑决策) 的 C1、C5 和 C6;只有设置了 `maxContinuations` 时 C6 才生效;以及后台等待),然后写使用 Pursuit 文本的续跑,或暂停(`limit`);与任何回合结束时一样,有待处理的驱动输入就不续跑(C5),有后台任务仍开放时也不决策:折叠保留该结论,关闭最后一个开放任务的 cancelled 结束会执行它。`failed`:暂停(`evaluation_failed`) | @@ -65,7 +65,7 @@ Goal 从分支的第一条本地 Queue 输入识别这个角色(Prompt 在 `br | 消费的事件 | 条件 | 动作 | | --- | --- | --- | -| `turn/end` M,状态 `completed` | 回复带有结论 | 用 `treeCommands.input` 写到 `B`(Append),标记 `evaluation="N" evaluator="E"` | +| `turn/end` M,状态 `completed` | 回复带有结论 | 用 `timelineTree.input` 写到 `B`(Append),标记 `evaluation="N" evaluator="E"` | | `turn/end` M,状态 `completed` | 没有结论,且 `M` 是评审分支的第一个回合结束 | 在评审分支上写一条追问(Queue,`after="M"`),要求它以三种结论之一结束 | | `turn/end` M,状态 `completed` | 没有结论,且 `M` 不是第一个回合结束(已经追问过一次) | 向 `B` 写 `continue`,以截断到 4000 字符的整个回复为反馈 | | `turn/end` M,状态 `failed` 或 `cancelled` | — | 向 `B` 写 `failed` | @@ -171,15 +171,15 @@ Goal 从分支的第一条本地 Queue 输入识别这个角色(Prompt 在 `br | # | 改动 | | --- | --- | -| E1 | **从线的来源识别。** 当 `treeCommands.info(自己的 id)` 的 `source = {kind: "host", operation_id: "goal:evaluate:N"}` 且 `parent = B` 时,这条线上的 Goal 担任评审者角色,不再读 prompt 的第一行。prompt 保留 `` 这一首行,只给模型看(§5) | -| E2 | **Goal 结束它的评审者。** 评审 `N` 的结论或失败已经决定(§4.1),或者之后的目标变更已经取代了 `N`,`N` 就在 `B` 上了结。了结之后,`B` 上的 Goal 通过一个写入前复核的自有任务,以 `treeCommands.end(E, {kind: "host", operation_id: "goal:evaluate:N"})` 结束 `E`。如果 `B` 的历史里已经有 `E` 的 `branch/ended`,Goal 什么也不做。加载时用同样的检查补齐:已记录的评审者,若它的 `N` 已了结、而 `B` 上没有它的 `branch/ended`,就结束它 | +| E1 | **从线的来源识别。** 当 `timelineTree.info(自己的 id)` 的 `source = {kind: "host", operation_id: "goal:evaluate:N"}` 且 `parent = B` 时,这条线上的 Goal 担任评审者角色,不再读 prompt 的第一行。prompt 保留 `` 这一首行,只给模型看(§5) | +| E2 | **Goal 结束它的评审者。** 评审 `N` 的结论或失败已经决定(§4.1),或者之后的目标变更已经取代了 `N`,`N` 就在 `B` 上了结。了结之后,`B` 上的 Goal 通过一个写入前复核的自有任务,以 `timelineTree.end(E, {kind: "host", operation_id: "goal:evaluate:N"})` 结束 `E`。如果 `B` 的历史里已经有 `E` 的 `branch/ended`,Goal 什么也不做。加载时用同样的检查补齐:已记录的评审者,若它的 `N` 已了结、而 `B` 上没有它的 `branch/ended`,就结束它 | | E3 | **结论之前的外部结束算 `failed`。** `N` 仍是当前评审时,如果 `B` 上 `E` 的 `branch/ended` 出现在 `E` 的结论之前,就判为 `failed`:暂停(`evaluation_failed`),与 §4.1 相同 | 接口: - Goal 的分支部件新增 Dispatcher key `branch/ended`。 - Goal 的分支部件注入 `sessionLifecycle`(`activated()`):加载时的结束要等 Session 发布其恢复打开的各条线(E2)。 -- Goal 的分支部件经 Rust 导出使用 `TreeCommands` 的 `create`、`input`、`end` 与 `info`,并读 `TimelineInfo.source` 识别评审线。 +- Goal 的分支部件经 Rust 导出使用 `TimelineTree` 的 `create`、`input`、`end` 与 `info`,并读 `TimelineInfo.source` 识别评审线。 验收,使用假模型,放在 `crates/dim-goal/tests` 的流程测试中: diff --git a/docs/zh/design/plugins/Questions.md b/docs/zh/design/plugins/Questions.md index 9e1e9b5bd4..067559f6d2 100644 --- a/docs/zh/design/plugins/Questions.md +++ b/docs/zh/design/plugins/Questions.md @@ -306,7 +306,7 @@ Session fork 只在没有缺少结果的工具提议的静止点切 `main`([se | 元素 | 结果 | | --- | --- | | `question/*` 事件、Questions 重放、动态事件 | 已在 #178 删除(§2) | -| 分支部分 `questions`、它对 `step/tool-result` 的 Dispatcher 订阅、保留的已回答/已取消条目、`question_already_answered` 和 `question_cancelled` | 本次删除。等待的处理函数本来就属于 Session 部分,分支关闭(经由它的中断)和重载通过 ToolExecutor 的取消令牌到达它,所以分支部分只多出一次经 `TreeCommands` 的查找和第二个生命周期。保留条目只是让第二个客户端在 `step/tool-result` 之前分辨“别处已回答”和“尚未就绪”;去掉后两者都得到 `question_not_pending`,提示仍在 `step/tool-result` 时正确关闭。已复核:回答、拒绝、中断、重载、关闭、重启和两个客户端(附录 B)的结果不变 | +| 分支部分 `questions`、它对 `step/tool-result` 的 Dispatcher 订阅、保留的已回答/已取消条目、`question_already_answered` 和 `question_cancelled` | 本次删除。等待的处理函数本来就属于 Session 部分,分支关闭(经由它的中断)和重载通过 ToolExecutor 的取消令牌到达它,所以分支部分只多出一次经 `TimelineTree` 的查找和第二个生命周期。保留条目只是让第二个客户端在 `step/tool-result` 之前分辨“别处已回答”和“尚未就绪”;去掉后两者都得到 `question_not_pending`,提示仍在 `step/tool-result` 时正确关闭。已复核:回答、拒绝、中断、重载、关闭、重启和两个客户端(附录 B)的结果不变 | | `respond` 中 `branchId` 默认 `"main"` | 删除:客户端总能从 `session.event` 得到分支;默认值只会诱发回答错分支 | | 原 F2(非交互 Session 中的审批) | 删除:归 Approval,已在 [CLI 命令](../../../design/cli-commands.md#execution-and-jsonl-output)和 [sessions-service D10](../appserver/sessions-service.md) 中决定 | | 用互斥表而不是 `StateCell` | 保留:条目是实时 I/O 等待,不是可从 Timeline 重建的状态 | diff --git a/docs/zh/design/plugins/Recall.md b/docs/zh/design/plugins/Recall.md index adc227f805..103dd145b6 100644 --- a/docs/zh/design/plugins/Recall.md +++ b/docs/zh/design/plugins/Recall.md @@ -40,7 +40,7 @@ Recall 就像客户端里的会话视图,只是讲给模型而不是展示给 ### 3.1 固定的读取 -每次调用开始时,工具读取 `head = branch.sequence()`(已发布序号)和 `events = branch.history(Some(head))`:对子分支,是父分支到 fork 点为止的事件(继承前缀)加上它自己的事件;对 fork 出的 Session 的 `main`,是复制来的事实、它的 `session/forked`,再加上它自己的事件。两者都是 fork 之前的历史,Recall 像读其他历史一样读取。其余一切都基于这一份固定的列表计算,所以一次调用不会混用两个 head。这与 `wait` 已有的做法一致([wait.rs](../../../../crates/dim-agent-capabilities/src/wait.rs)):一个 Session 工具从 `ToolExecutionContext.branch_id` 经 `TreeCommands` 找到调用方分支。Recall 不应用压缩,遍历的是整个列表。 +每次调用开始时,工具读取 `head = branch.sequence()`(已发布序号)和 `events = branch.history(Some(head))`:对子分支,是父分支到 fork 点为止的事件(继承前缀)加上它自己的事件;对 fork 出的 Session 的 `main`,是复制来的事实、它的 `session/forked`,再加上它自己的事件。两者都是 fork 之前的历史,Recall 像读其他历史一样读取。其余一切都基于这一份固定的列表计算,所以一次调用不会混用两个 head。这与 `wait` 已有的做法一致([wait.rs](../../../../crates/dim-agent-capabilities/src/wait.rs)):一个 Session 工具从 `ToolExecutionContext.branch_id` 经 `TimelineTree` 找到调用方分支。Recall 不应用压缩,遍历的是整个列表。 在行结束的过程中,`branch/end` 不讲,`end` 调用像其他调用一样讲述。 @@ -335,7 +335,7 @@ End of turn. Open one: open=. | 设计规则 §4 第 4 条(核心不带业务含义) | 不改核心。Recall 自己也不认识生产者:它按块文本的标签与属性以及 `key`/`retire` 讲述运行时块,Prompt、Goal 和后台通知的块都不需要专门处理。 | | 设计规则 §4 第 5 条(原子批次) | 不适用:它不写入;读取固定在一个已发布的 head 上。 | | 设计规则 §4 第 6 条(上下文只来自交接后的事件) | 它按上下文拼装的规则选取,只额外加入它点名的公开经历事件;其他类型都不讲。结果只以工具结果进入模型。 | -| 设计规则 §4 第 7 条(公开事件与服务) | 使用 `TreeCommands`、Branch 门面,以及公开事件和它们的关联 id。不读任何插件的内部状态。 | +| 设计规则 §4 第 7 条(公开事件与服务) | 使用 `TimelineTree`、Branch 门面,以及公开事件和它们的关联 id。不读任何插件的内部状态。 | | 设计规则 §4 第 8 条(基础设施不变) | Timeline、Dispatcher、信封、装配、门面和投影类型都不变。 | | 设计规则 §4 第 9 条(只有后续决定要用的事实进 Timeline) | 不新增事件。 | | 设计规则 §1(Capability 与 App Server 边界) | 是 `dim-agent-capabilities` 中的 Session Capability,装在 `defaults::install_local_execution` 中、与 `wait` 并列,所以 App Server 的产品 profile 和 `--models` profile 都有它。 | @@ -394,7 +394,7 @@ End of turn. Open one: open=. ## 15. Ready -以上每条规则和引用的合同都已在 main 的 `bf95eaf6` 上重新核对(事件、Branch 门面、`TreeCommands`、`wait`、ToolExecutor 的取消、块的生产者、`session/forked`、2026-10-20 的 ADR 001)。 +以上每条规则和引用的合同都已在 main 的 `bf95eaf6` 上重新核对(事件、Branch 门面、`TimelineTree`、`wait`、ToolExecutor 的取消、块的生产者、`session/forked`、2026-10-20 的 ADR 001)。 维护者已于 2026-10-21 批准本文为 Ready,并作出以下决定: @@ -416,7 +416,7 @@ pub fn feature() -> Feature { Feature::new("Recall").session("Recall", |names| Ok(Box::new(RecallPlugin::new(names)?))) } pub struct RecallPlugin { - tree: Key, + tree: Key, tools: Key, } impl RecallPlugin { @@ -426,7 +426,7 @@ impl DynPlugin for RecallPlugin { // injects: [tree.erase(), tools.erase()] // apply: tools.register(ctx, ToolContribution { definition, handler: RecallTool(tree) }) } -struct RecallTool(Arc); +struct RecallTool(Arc); impl ToolHandler for RecallTool { /* §3–§6 */ } // dim-agent-capabilities/src/defaults.rs,install_local_execution,与 wait::install 并列 diff --git a/docs/zh/design/plugins/ShellInput.md b/docs/zh/design/plugins/ShellInput.md index 9960fd631e..8b643d0e9f 100644 --- a/docs/zh/design/plugins/ShellInput.md +++ b/docs/zh/design/plugins/ShellInput.md @@ -15,7 +15,7 @@ flowchart LR end subgraph S["Session 作用域"] SI["ShellInputPlugin(运行注册表,sessionMethods shell)"]:::new - TC["TreeCommands"] + TC["TimelineTree"] SS["SessionConfig、SessionLifecycle、SessionIdentity"] end subgraph B["分支"] @@ -32,7 +32,7 @@ flowchart LR | 部分 | 作用域 | 依赖 | 提供 | | --- | --- | --- | --- | -| `ShellInputPlugin` | Session | `P:HostPlatform`(与 WorkspaceTools 的用法相同)、`S:SessionConfig`(`cwd`)、`S:TreeCommands`、`S:SessionLifecycle`、`S:SessionIdentity`、`S:sessionMethods` | 把 `shell` 注册到 `sessionMethods` | +| `ShellInputPlugin` | Session | `P:HostPlatform`(与 WorkspaceTools 的用法相同)、`S:SessionConfig`(`cwd`)、`S:TimelineTree`、`S:SessionLifecycle`、`S:SessionIdentity`、`S:sessionMethods` | 把 `shell` 注册到 `sessionMethods` | 依赖的契约: @@ -229,7 +229,7 @@ Session 部件加载期间该条目生效,其文本是代码([Prompt §5](Pr | §4.4 核心机制不带业务含义 | Rpc、InputQueue 与 Loop 不为 ShellInput 增加处理:Rpc 按命名空间找到它,标记是普通 raw 块。 | | §4.5 决定前读完整个批次 | 不适用:ShellInput 不读任何 Timeline 事件,它唯一的事件(`input/message`)不需要同批次的其他事实。 | | §4.6 模型上下文只含交接后被读取的事件 | 输出只在 InputQueue 应用、Loop 消费该输入后进入模型;`!!` 的输出和进度从不进入。 | -| §4.7 插件之间只通过公开事件和服务交互 | ShellInput 经 `S:TreeCommands` 使用 `Branch::input`,并使用 `SessionConfig`、`SessionLifecycle`、`SessionIdentity`、HostPlatform 与 `sessionMethods` 契约。 | +| §4.7 插件之间只通过公开事件和服务交互 | ShellInput 经 `S:TimelineTree` 使用 `Branch::input`,并使用 `SessionConfig`、`SessionLifecycle`、`SessionIdentity`、HostPlatform 与 `sessionMethods` 契约。 | | §4.8 基础设施默认不变 | 基础设施不变,不向运行时或 rutis 提需求(§9)。需要 Rpc(逐次调用的进度,在 C1 中)和 HostPlatform(命令构造器,S7)做的改动列在 A.5;Agents 活动句柄由空闲卸载提出的运行时活动持有取代(A.5)。 | | §4.9 只有后续决定要用的事实进入 Timeline | 只有 `!` 的记录结果进入,作为模型会读取的输入。进度是一次调用的回复数据,不是 Session 状态,因此既不进 Timeline,也不走 Session 广播通知;运行记录进入进程日志。 | | §1 Capability 与 App Server 边界 | ShellInput 是 dim-agent-capabilities 中自成模块的 Session Capability;Rpc 只分派 `sessionMethods`。 | @@ -329,7 +329,7 @@ setsid o--------------------------------------> own session (POSIX): not reache | 步骤 | 机制 | | --- | --- | -| 启动 | 解析参数(`invalid_params`);准入(见下);通过 `S:TreeCommands` 解析分支;构造 `ProcessSpec`(S7;`shell_unavailable`),直到调用的取消令牌触发为止;然后在登记表的锁内一步完成:再次准入、取得 Session 持有、`spawn`(`spawn_failed`)、连同持有登记运行,并在本代的任务跟踪器中启动它的任务,而不是在调用中运行。`runId` 在其进程启动后、或被先到的 stop 结束后才算用过,被拒绝的启动不占用它 | +| 启动 | 解析参数(`invalid_params`);准入(见下);通过 `S:TimelineTree` 解析分支;构造 `ProcessSpec`(S7;`shell_unavailable`),直到调用的取消令牌触发为止;然后在登记表的锁内一步完成:再次准入、取得 Session 持有、`spawn`(`spawn_failed`)、连同持有登记运行,并在本代的任务跟踪器中启动它的任务,而不是在调用中运行。`runId` 在其进程启动后、或被先到的 stop 结束后才算用过,被拒绝的启动不占用它 | | 准入 | 依次拒绝:调用已被中断(`operation_interrupted`)、本代正在卸载(`service_reloading`)、Session 正在关闭(`session_closed`)、已有登记的运行(`shell_busy`)、`runId` 已用过(`duplicate_run`)。第二次准入随后取走为该 `runId` 记住的 stop:什么都不启动,回复 `{runId, status: "stopped", output: "", truncated: false, durationMs: 0}`,不记录,也没有 span。否则它取得 Session 持有:Session 正在关闭或已决定空闲释放时为 `None`,此时以 `session_closed` 拒绝运行,`runId` 保持未使用 | | 持有 | 每次运行一个 `SessionLifecycle::take_hold()`,保存在它的登记项中。任务把运行移出登记表时释放它:在运行的最后一个事实之后(下文的写入、`private` 的退出或终止),并在 `shell.stop` 或回复看到运行结束之前。持有期间 `Session::unload_if_idle()` 拒绝;Session 关闭不理会它(空闲卸载 §5.1) | | 运行 | 任务持有进程树。它读取两个管道,发送有上限的进度(A.1),保留有界尾部,并等待退出、`shell.stop`、`SessionLifecycle::closing()` 或本代的取消 | @@ -511,14 +511,14 @@ ShellInput 用 Rust 实现,为 dim-agent-capabilities 的 `shell_input` 模块 | 中立契约 | Rust 绑定 | | --- | --- | -| 插件 | `TypedPlugin`;`Deps = (Keyed, Keyed, Keyed, Keyed, Keyed, Keyed)` | +| 插件 | `TypedPlugin`;`Deps = (Keyed, Keyed, Keyed, Keyed, Keyed, Keyed)` | | 命名空间 `shell` | 在 `Keyed` 依赖(`dim_agent_capabilities::methods`)上调用 `methods.register(ctx, "shell", declarations, handler)`,在 `apply` 中于 ShellInput 自己的 effect 之后调用,因此它的卸载 effect 先运行。`declarations` 为 `MethodDecl { progress: true, ..MethodDecl::new("shell.run", true, Interruption::Report) }`、`MethodDecl::new("shell.stop", true, Interruption::Report)` 和 `MethodDecl::new("shell.list", false, Interruption::Report)` | | 处理函数 | 一个 `Handler`,以方法名、参数、调用的 `CancellationToken`(A.4 两种取消)和它的 `Progress` 调用,返回 `Result` 的 future。自己的错误用 `RpcError::app(-32000, "shell_busy", ..)` 等,`invalid_params` 用 `RpcError::invalid`;运行时门面的错误用 `?` 转换(`From for RpcError`) | | 进度 | 处理函数的 `Progress` 参数:`progress.send(json!({"text": text}))`,有略去的字节时加上 `"skipped"`。运行任务持有它的克隆;回复之后的发送被丢弃 | | 命令构造 | `HostPlatform::build_process_spec(command, cwd).await` 返回 `(ProcessSpec, ExecShellRuntime)` 或 `ProcessSpecError { code, reason }`;内部读取当前 shell。处理函数用 `select!` 让它与调用的取消令牌竞争 | | 进程 | `HostPlatform::spawn(ProcessSpec)` 返回带 `stdout`、`stderr`、`wait` 和 `terminate` 的 `ProcessTree` | | 运行任务 | ShellInput 自己的 `TaskTracker`,与 `SessionMethods` 跟踪的调用分开;每个任务持有自己的 `ProcessTree`,观察 `ctx.cancelled()` 和 `SessionLifecycle::closing()`;`ctx.effect` 登记等待该跟踪器的卸载清理函数。`spawn` 之前在登记表的锁内读取调用的取消令牌、本代的取消令牌和 Session 阶段,卸载清理函数在同一把锁内关闭跟踪器。`SessionLifecycle::take_hold()` 返回的 `SessionHold` 也在那里取得,保存在运行的登记项中,任务在运行的最后一个事实之后清除该登记项 | -| 记录的输入(A.3) | `TreeCommands::get(branch_id)?.input(..)` | +| 记录的输入(A.3) | `TimelineTree::get(branch_id)?.input(..)` | | 进程日志 | `tracing` span `shell.run`,带 `session_id`、`branch_id` 与 `run_id`,运行结束时记录 `outcome` | ```rust diff --git a/docs/zh/design/rutis-usage.md b/docs/zh/design/rutis-usage.md index 7e8fb8c8d7..5c33abd93e 100644 --- a/docs/zh/design/rutis-usage.md +++ b/docs/zh/design/rutis-usage.md @@ -466,7 +466,7 @@ async def apply_branch(ctx, config): identity = await ctx.use("timelineIdentity").get() ... -branch = define_plugin(apply_branch, inject=["dispatcher", "timelineIdentity", "treeCommands"]) +branch = define_plugin(apply_branch, inject=["dispatcher", "timelineIdentity", "timelineTree"]) inject = ["partRegistry"] provides = {} diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 4492fb426c..9fc394f3f6 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -79,9 +79,9 @@ - **来源。** 每条线都有来源,记在父分支的 `branch/create` 里。来源记录这条线从哪里开出来,它不是角色标记: - **工具线**由 `branch` 工具开出。它是对话线:可以成为默认分支,不在默认分支时用 `end` 结束自己。 - **用户线**由客户端经 `session.branch_create` 开出。它的开线方是用户,它同样是对话线:可以成为默认分支。它由用户结束,不能结束自己。 - - **插件线**由插件(`TreeCommands.create`)开出。它的协议归创建者,永远不能成为默认分支。它也不开线。 + - **插件线**由插件(`TimelineTree.create`)开出。它的协议归创建者,永远不能成为默认分支。它也不开线。 - 来源可以从 `TimelineInfo.source` 读到,由 `TreeCommands.list` 和 `info` 返回,根上没有(§5)。已结束的目录条目可以不带它;打开显示详情时按已知位置读取创建来源。插件线的来源是 `{kind: "host", operation_id}`:开线一方的不透明标签,核心从不解释它。用户线有它自己的种类 `{kind: "user", operation_id}`,所以需要分辨对话线与插件线的读者不用去解析 `operation_id`。开线一方按自己的 operation id 约定找到自己的线,例如 Goal 的 `goal:evaluate:` 前缀。种类只说明这条线从哪里开出来,不携带角色。 + 来源可以从 `TimelineInfo.source` 读到,由 `TimelineTree.list` 和 `info` 返回,根上没有(§5)。已结束的目录条目可以不带它;打开显示详情时按已知位置读取创建来源。插件线的来源是 `{kind: "host", operation_id}`:开线一方的不透明标签,核心从不解释它。用户线有它自己的种类 `{kind: "user", operation_id}`,所以需要分辨对话线与插件线的读者不用去解析 `operation_id`。开线一方按自己的 operation id 约定找到自己的线,例如 Goal 的 `goal:evaluate:` 前缀。种类只说明这条线从哪里开出来,不携带角色。 - **升级前已经存在的线。** 今天 `session.branch_create` 写的是 `{kind: "host", operation_id}`([connection/tree.rs](../../crates/dim-app-server/src/connection/tree.rs)),本设计不改写任何已存的行。用户在升级前经客户端开出的线,包括 `FORMAT` 52 下用 Web `/branch` 开的线,升级后仍是 `host`,因此不再是合法的切换目标;升级后新开的同样一条线则可以。本次接受这个限制,而不迁移这条事实:`FORMAT` 53 只是升标记、不写数据(§15、§16),并且有一条验收用例写明它(§20)。 - **工具的作用范围。** 一条线读、也发消息给它被切出来的那条线和它开过的每条未结束的工具线。用户开出的线同时站在这条规则的两侧:它给被切出来的那条线发消息、也从自己的切点读它,并协调开在它下面的工具线;而被它切出来的那条线既不给它发消息、也不读它,因为它是用户开出的(§6)。`end {content}` 不接受目标,所以它只结束调用方自己,不结束别的线(§6、§10、§11)。插件线不在任何名册上,工具不给它发消息,也不结束它。 - **父线块。** 一条线的 BranchLine 在父线结束一轮、且父线在 `max(读取游标, 上次告知的头部, 开启点)` 之后有新活动时,在这条线自己身上写一个带 key 的 `` 块(§7.1.1、§12.1)。块只报位置,是状态而不是请求;内容仍留在读取返回的页里。 @@ -105,17 +105,17 @@ | TimelineTree | Session | 否 | 线的生命周期:每个子分支开启输入里的身份块、`TimelineInfo.source`、一条线的结束(`branch/end` → `branch/ended`)、线进入结束后拒绝输入、恢复规则、读已结束线的历史、默认分支及其 `branch/default` 事实,以及分支目录(§14) | | TreeTimeline | 分支 | 是 | 把 `branch/end` 转给 TimelineTree,就像现在转 `branch/create`。对由工具调用发出的结束,它还转交关闭要等的那一轮结束 | | BranchTool | Session | 否 | 按动作区分的 `branch` 工具(§11)。它每次调用时取调用方那条线的 BranchLine,与 WorkspaceTools 取 FileReads 的方式相同 | -| **BranchLine**(新) | 分支 | 是 | 一条线对自己相关各线的视图。它的角色(根、工具线、用户线或插件线)和父分支来自 `TreeCommands.info(自己的 id)`。它从自己的事实折叠出未结束的工具线和当前这一轮的状态。它写名册、空闲通知和结束通知,以及线成为默认分支或不再是默认分支时它收到的那条状态说明。名册是它自己的 key `branch:roster`,只列它开出的工具线(§7.1) | +| **BranchLine**(新) | 分支 | 是 | 一条线对自己相关各线的视图。它的角色(根、工具线、用户线或插件线)和父分支来自 `TimelineTree.info(自己的 id)`。它从自己的事实折叠出未结束的工具线和当前这一轮的状态。它写名册、空闲通知和结束通知,以及线成为默认分支或不再是默认分支时它收到的那条状态说明。名册是它自己的 key `branch:roster`,只列它开出的工具线(§7.1) | -BranchLine 注入 `B:Dispatcher`、`B:TimelineIdentity`、`B:BranchLifecycle` 和 `S:TreeCommands`,提供 `B:BranchLine`。 +BranchLine 注入 `B:Dispatcher`、`B:TimelineIdentity`、`B:BranchLifecycle` 和 `S:TimelineTree`,提供 `B:BranchLine`。 -它的决定方式与 Goal 相同:依据已消费的状态,通过一个写入前会复核的自有写任务,并且只对加载截点之后的实时事件作决定。所以重载时什么都不会写两次,只有一个例外:如果加载时自己的历史里最后有一个仍在生效的名册键,而与折叠出的名册不一致,它就把名册写一次——因为补完一条已结束线的重启(§20.7)在根重放之前就记下了 `branch/ended`,之后没有实时事件跟随(§6.2)。同一条例外补上一次停在事实与说明之间的移动。`branch/default` 和每条状态说明分别是独立的批次(§4.5),所以进程在事实提交之后、某条说明写出之前停下时,事实照样生效、说明却缺了。加载时 BranchLine 对自己这条线比较两件事:它上面最新的有效 `branch:line` 块的 `default` 属性(没有这个属性就算不是默认分支),以及 `TreeCommands` 现在是否报告这条线是默认分支。两者不一致时,它在这条线的下一次模型请求之前补写与树一致的那条说明,一次;根永远不写。给新默认分支的说明会写出移动从哪条线开始,所以补写的加载必须知道那条线:`branch/default` 带着它,放在说明本来就需要的 `from` 字段里(§16),这正是 §4.9 允许一条事实存在的理由——补写的说明要用它来决定。把这条线的块与树对上的加载什么也不写,所以再次重启也不写。只有对树报告为默认分支的那条线,比较还会读这个块的文本,所以旧规则写下的说明在加载时被替换一次。 +它的决定方式与 Goal 相同:依据已消费的状态,通过一个写入前会复核的自有写任务,并且只对加载截点之后的实时事件作决定。所以重载时什么都不会写两次,只有一个例外:如果加载时自己的历史里最后有一个仍在生效的名册键,而与折叠出的名册不一致,它就把名册写一次——因为补完一条已结束线的重启(§20.7)在根重放之前就记下了 `branch/ended`,之后没有实时事件跟随(§6.2)。同一条例外补上一次停在事实与说明之间的移动。`branch/default` 和每条状态说明分别是独立的批次(§4.5),所以进程在事实提交之后、某条说明写出之前停下时,事实照样生效、说明却缺了。加载时 BranchLine 对自己这条线比较两件事:它上面最新的有效 `branch:line` 块的 `default` 属性(没有这个属性就算不是默认分支),以及 `TimelineTree` 现在是否报告这条线是默认分支。两者不一致时,它在这条线的下一次模型请求之前补写与树一致的那条说明,一次;根永远不写。给新默认分支的说明会写出移动从哪条线开始,所以补写的加载必须知道那条线:`branch/default` 带着它,放在说明本来就需要的 `from` 字段里(§16),这正是 §4.9 允许一条事实存在的理由——补写的说明要用它来决定。把这条线的块与树对上的加载什么也不写,所以再次重启也不写。只有对树报告为默认分支的那条线,比较还会读这个块的文本,所以旧规则写下的说明在加载时被替换一次。 **默认分支的恢复。** 目录里只有一条线的 Session 就在根上,不为它读任何事实。有多条线的 Session 只读一条事实:在根自己的事件里,最新的一条 `branch/default` 或 `session/forked`,走现有的 `timeline_events_by_kind` 索引。目标仍未结束且可以被选中的 `branch/default` 指明默认分支;最新的一条是 `session/forked` 时,默认分支就是根,因为 fork 拷过来的所有 `branch/default` 都写在它的 `session/forked` 之前、一律失效;什么也没记就是根。目标已经不再是开着的线、指向插件线、以及指向升级前经客户端开出的线时,都回退到根(§4)。 ## 6. 线之间的消息 -消息是接收方 Timeline 上的一条 `input/message`,经 `TreeCommands.input` 写入,不新增输入通道。它带一个原始块,由生产者标记、不带 key,以及 [InputQueue](../../architecture/rust-agent/plugins/InputQueue.md) 的模式: +消息是接收方 Timeline 上的一条 `input/message`,经 `TimelineTree.input` 写入,不新增输入通道。它带一个原始块,由生产者标记、不带 key,以及 [InputQueue](../../architecture/rust-agent/plugins/InputQueue.md) 的模式: | 模式 | 对接收方的作用 | 何时用 | | --- | --- | --- | @@ -138,7 +138,7 @@ BranchLine 注入 `B:Dispatcher`、`B:TimelineIdentity`、`B:BranchLifecycle` | 其他任何组合:兄弟分支、相隔两代的线 | 不行 | 不行 | `branch_not_kin` | 用户开的线是像工具线一样的对话线,它落在哪一行由它所处的那条边决定:作为被开出的线,它属于第二行,那一行的开线方是用户,不是它被切出来的那条线;作为工具线的开线方,它与其他开线方一样属于第一行。已结束的工具线保留它原来的那一行,只是发消息被拒:开线方仍然读它,开线方就是这样拿到它没来得及发出的结果。已结束的插件线仍归插件那一行,没有哪条线经工具读它。`end` 不属于任何组合:`end {content}` 不接受目标,所以它永远结束调用方自己(§10、§11)。协调沿父子关系走,所以它留在开线的那条线上,默认分支移动时它不跟着动;曾经的默认分支保留它开出的工具线,并继续与它们互发消息、互读。 -- **读取。** `read {branch, after?, limit?}` 返回目标已提交历史的一页,未结束或已结束都可以,经 `TreeCommands.page` 从存储读取,按 Collaboration 的 `read` 渲染成员页面的方式呈现:输入、文本、工具调用与结果、每轮结束,带 `nextCursor`;工具结果条目携带其工具在该结果上声明的效果([工具契约 A.6](contracts/session-boundary.md#a6-工具效果)),仅当结果至少声明了一个时才存在,路径原样,命令在第 200 个字符处截断并标出截断。目标是被调用方切出来的那条线,或调用方开过的线。两个方向共用一条游标规则: +- **读取。** `read {branch, after?, limit?}` 返回目标已提交历史的一页,未结束或已结束都可以,经 `TimelineTree.page` 从存储读取,按 Collaboration 的 `read` 渲染成员页面的方式呈现:输入、文本、工具调用与结果、每轮结束,带 `nextCursor`;工具结果条目携带其工具在该结果上声明的效果([工具契约 A.6](contracts/session-boundary.md#a6-工具效果)),仅当结果至少声明了一个时才存在,路径原样,命令在第 200 个字符处截断并标出截断。目标是被调用方切出来的那条线,或调用方开过的线。两个方向共用一条游标规则: - 不带 `after` 时,读取从调用方上一次成功读取该线的位置继续:最后一次返回了页的读取的 `nextCursor`。此前没有读过时,读被切出来的那条线从调用方的切点开始,读调用方开过的线从那条线的第一个事件开始。 - 显式 `after` 从该点读取。读被切出来的那条线时,低于切点的值会抬到切点,因为切点之前的事件已经是这条线自己的历史。读自己开过的线时,值原样使用,所以 `after: 0` 会从一条线的开头重读。 - 每次成功读取都把游标移到它的 `nextCursor`,显式 `after` 的读取也一样;以最后一次为准。游标是调用方自己那条线的事实:BranchLine 从调用方自己的 `step/tool-use` 和 `step/tool-result` 折叠得到,所以重载和压缩都能重建它。 @@ -248,7 +248,7 @@ key 与模式互不相关([history.rs](../../../crates/dim-agent-capabilities/ 3. 父线在 `from = max(A, told, opened)` 之后有新活动:`A` 是这条线对父线的读取游标(还没读过时是它的切点),`told` 是这条线上最新一个 `branch:parent` 块报告的头部(没有时为 0),`opened` 是这条线的 `branch/create` 事件在父线上的序号,每个切点都不高于它。线存在之前发生的活动不算新闻,需要时线自己去读。 - **什么算新活动。** 只有两类事件算:操作者输入,即带 `user` 内容的 `input/message`;以及工具调用。创建调用的 `step/tool-use` 写在 `opened` 之前,所以从不会被算进去。其他都不单独算:父线的文本、它的轮次结束、只有块的输入(名册、来自各线的消息)、以及创建调用的结果。规则是:父线行动时、或操作者告诉父线事情时,线被告知;只为开启它的那一轮(它的创建调用结果、文本和轮次结束)则从不告知,否则每条线都会白白读一次父线,并学会忽略这个块。 - **检查方式。** 父线的事实通过唯一的事件查询读取([ADR 019](../../adr/019-event-query.md)):该分支的 `input/message` 和 `step/tool-use` 事件,从新到旧分页,直到有一个符合条件,或读取到达 `from`。不折叠任何其他线的事件。 -- **写入。** 一条带 key 的 Append,key 为 `branch:parent`,经 `TreeCommands.input` 写在这条线自己身上,属性是父线的 id、`head` 和 `after`。同一 key 的后一个块会在带 key 的基线里取代前一个。写完之后折叠记下新头部和新输入,所以队列里的第二次决定不会再写。 +- **写入。** 一条带 key 的 Append,key 为 `branch:parent`,经 `TimelineTree.input` 写在这条线自己身上,属性是父线的 id、`head` 和 `after`。同一 key 的后一个块会在带 key 的基线里取代前一个。写完之后折叠记下新头部和新输入,所以队列里的第二次决定不会再写。 - **开启时。** 子分支继承的前缀里持有活的 `branch:parent` 块时,子分支的开启输入在身份块之后再带一个原始块:key 为 `branch:parent`,活的、不 retire,名字是开出它的那条线 P,`head` 和 `after` 都等于切点 H。它像身份块取代继承的名册那样取代继承的块(§7.1),所以这条线最新的 `branch:parent` 总是名字它自己的父线,它的 `told` 从 H 开始,而 H 等于 `opened`;压缩重放的是这个块,从不重放上面那个,P 移动时照常的新块取代它。只有嵌套的线才会拿到它:从 `main` 切出来的线不继承任何 `branch:parent` 块,它的开启输入逐字节不变。TimelineTree 在写身份块的地方组合它,从子分支继承的前缀的带 key 状态判断这个 key 是否活着,绝不看渲染后的历史。它在开启子分支时读那份状态,如同读一条恢复的分支的 facts;读取失败时这次创建和任何其他开启失败一样失败(branch/create-failed)。 - **随后发生什么。** 运行中的线在下一次模型请求时拿到这个块。空闲的线不会被唤醒:这个块在它下一轮的第一个请求里、先于开启那一轮的输入被消费,这是有文档记录的 Append 规则([session access](contracts/session-access.md)、[Loop](../../architecture/rust-agent/plugins/Loop.md))。重载不写任何东西;重启最多写当时已经该写的那个块。`main` 拿不到块:它上面没有东西。 - **记录。** 这条线发送的是它自己配置里持有的 System。指南在每条线上都一样(§7.3),所以 System 没有相对继承来的那份发生移动的线,引用的是记录它的那份配置,无论记录在哪条线的链上;线的 System 移动时,它像任何分支一样写出自己的 `context/configured`。 @@ -353,7 +353,7 @@ WorkspaceTools 不变。 `ancestor` 指向用自己那次结束发起连锁的线:也就是本身不带 `ancestor` 的那次结束。连锁结束的每条后代都带这条线,`source` 也从同一次结束复制,于是(source, ancestor)这对值指明一次结束操作:谁要求的,在哪条线上。自己要求结束的线有 `source`、没有 `ancestor`;已被连锁结束之前就提交了自己结束的后代,保留它自己的那对值。`branch/ended` 从这条线的 `branch/end` 复制 `source` 和 `ancestor`,并且总是写在结束的那条线自己的父分支上,取自目录。 -**一个通用操作。** `TreeCommands.end(id, source)` 和 `Session::end_branch(id, source)` 只检查目标:它存在、未结束、不是根、不是默认分支,也不在默认分支的祖先链上。结束根就等于关闭 Session,而结束一条线会连带结束它下面的每一条,所以默认分支整条链都受保护。这些检查都是关于目标的,不是关于调用方的。它们从不检查是谁在调用:用户、开线方和插件遇到同样的守卫,要结束默认分支,永远得先把默认分支移走。 +**一个通用操作。** `TimelineTree.end(id, source)` 和 `Session::end_branch(id, source)` 只检查目标:它存在、未结束、不是根、不是默认分支,也不在默认分支的祖先链上。结束根就等于关闭 Session,而结束一条线会连带结束它下面的每一条,所以默认分支整条链都受保护。这些检查都是关于目标的,不是关于调用方的。它们从不检查是谁在调用:用户、开线方和插件遇到同样的守卫,要结束默认分支,永远得先把默认分支移走。 这项检查在调用那一刻、在移动默认分支同样要拿的树锁下,从目录里读出这条链,所以移动和结束不会交错出一个规则不允许的状态。因此只有两种次序被接纳:要么结束被接纳、移动被拒绝,因为目标或它的某个祖先正在结束或已经结束;要么移动被接纳、之后对新的默认分支链上某条线的结束被拒绝。目标或它的任一祖先仍处于 `ending` 时,移动以 `branch_target_protected` 被拒绝,所以一条线不会在某个祖先的连锁已经在写它的后代时被选为默认分支。被拒绝时什么也不写。 @@ -416,7 +416,7 @@ WorkspaceTools 不变。 | `create` | `prompt`、`at?`、`idleNotice?`(`steer` \| `none`) | 根,以及当前的默认分支 | 开一条切在 `at` 的工具线(默认与现在相同:在本次请求的模型开始之前),它向调用方汇报。这次开线会越过 Session 上限时以 `branch_limit_reached` 被拒绝,名额在预留时扣除(§6.1)。空闲通知默认是 `steer` | `Line created: C` | | `message` | `to`、`content`、`mode?`(`append` \| `steer`) | 一条线,给它开出的工具线,或给它被切出来的那条线 | 在 `to` 上写一条 `input/message` | `Sent to C.` | | `read` | `branch`、`after?`、`limit?`(1–200) | 一条线,读被切出来的那条线或它开出的工具线,未结束或已结束都可。用户开出的线按这一条读它被切出来的那条线;那条线不给它发消息、也不读它,因为它是用户开出的 | 从存储读一页;不给 `after` 时从调用方的游标开始(§6) | 这一页的 JSON:items、`nextCursor`、`done` | -| `end` | `content` | 不是默认分支的工具线,对它自己 | 树锁下的一次 `TreeCommands.end(C, source, final_message)`:先检查守卫,在 C 上写带最终消息的 `branch/end`,再用由 `source` 推出的 submission id 把这条消息(steer)送到父线(§10)。被拒绝的结束不写最终消息 | `Line C is ending; your final message was sent to P.` | +| `end` | `content` | 不是默认分支的工具线,对它自己 | 树锁下的一次 `TimelineTree.end(C, source, final_message)`:先检查守卫,在 C 上写带最终消息的 `branch/end`,再用由 `source` 推出的 submission id 把这条消息(steer)送到父线(§10)。被拒绝的结束不写最终消息 | `Line C is ending; your final message was sent to P.` | 输入 schema 为 `{action, prompt?, at?, idleNotice?, to?, content?, mode?, branch?, after?, limit?}`,`action` 必填,`additionalProperties: false`。`idleNotice` 只对 `create` 有效。 @@ -432,7 +432,7 @@ WorkspaceTools 不变。 | 在根、默认分支、插件线或默认分支的祖先上 `end` | `Only a line opened with create can end itself, and not while it or a line below it is the default branch.` | `branch_cannot_end` | | `read` 的 `after` 超过目标的头部 | `after A is past line T's head H; a read starts at or below H` | 无:带错误结果,不带代码 | -这些拒绝是工具自己的规则。`TreeCommands.end` 本身只检查目标(§10)。因为守卫、`branch/end` 和送达是移动同样要拿的树锁下的同一次操作,先让目标成为默认分支的移动会在任何消息写出之前把整次调用挡下,前面那条拒绝就是这次调用的全部效果。如果线已经提交了自己的 `branch/end`,再来的 `end` 取 `branch_ended` 一行,不会再写一条最终消息:第一次调用的消息就是这条线最后的话。已经提交 `branch/end`、却停在送达之前的结束不是一个要回答的新结束:消息记在 `branch/end` 本身里,恢复会送达一次(§10)。 +这些拒绝是工具自己的规则。`TimelineTree.end` 本身只检查目标(§10)。因为守卫、`branch/end` 和送达是移动同样要拿的树锁下的同一次操作,先让目标成为默认分支的移动会在任何消息写出之前把整次调用挡下,前面那条拒绝就是这次调用的全部效果。如果线已经提交了自己的 `branch/end`,再来的 `end` 取 `branch_ended` 一行,不会再写一条最终消息:第一次调用的消息就是这条线最后的话。已经提交 `branch/end`、却停在送达之前的结束不是一个要回答的新结束:消息记在 `branch/end` 本身里,恢复会送达一次(§10)。 ## 12. 提示词 @@ -559,7 +559,6 @@ WorkspaceTools 不变。 目录读取不访问历史,显示字段为空或省略。`session.branch.get {sessionId, branchId}`(v3,在 `hello.features` 单独声明)读取一条线的目录记录和显示详情:`purpose` 为创建提示的首行;`cutMessages` 为该分叉点继承的用户输入数,排除截止位置前已删除的输入;`end` 为可用的 `BranchEndData`。main 的前两项为空,没有可读结束事实时 `end` 为空。该读取由 TimelineTree 完成点查与固定前缀计数;未知分支和读取失败在本次详情调用中报错,不阻断目录列举,不写事实,也不重新打开结束的线。CLI 在选中一条线时才读取详情。 - `head` 有三条规则,决定客户端能用它做什么: - 已结束(`ended`)线的 `head` 和 `endEvent` 固定。客户端把 `head` 作为 `through` 传给 `session.history` 读这条线;`endEvent` 是这条线自己的 `branch/end` 序号,祖先结束级联到它时也一样。 @@ -595,15 +594,15 @@ WorkspaceTools 不变。 | 模块 | 改动 | 原因 | | --- | --- | --- | | [设计规则 §2](../../architecture/rust-agent/principles.md#2-作用域的含义) | 改写:同一主体的多条线、共享事实、父子是唯一的通信和读取关系、共用交互面。关系表一行改为"只在父子之间",读取父线已提交的事件经工具结果;Session 一行加上"结束" | 现在的文本是"平等的线,父子只记录来源",没有通信关系 | -| TimelineTree | 对每种来源都在 `first_input` 里写身份块。新增 `TreeCommands.end(id, source)` 和 `TreeCommands.page(id, after, limit)`。`TimelineInfo.source`,依据父分支的 `branch/create` 填写(§5)。结束流程及其守卫、线进入结束后拒绝输入、`branch/ended`、恢复规则、读已结束的线,以及默认分支:根上的 `branch/default`、它的恢复读取,和一次移动写下的那条事实。它的 `directory()` 报告未结束、结束中和已结束的线:结束中的线从工具、用户或级联写入它自己的 `branch/end` 起,到它的已结束记录被写入为止,带该事件与活头部,并带当前的 `defaultBranchId`。它的节点把这条线最新轮次结束的序号发布给它开出的线(§7.1.1)。它还送达工具结束记下的最终消息:工具结束的 `branch/end` 带着它(§10、§16),所以恢复在父线上没有带该指令推出的 id 的输入时写一条,已有则什么也不写 | 它拥有线的生命周期、开启输入,以及默认分支唯一的那条权威事实 | +| TimelineTree | 对每种来源都在 `first_input` 里写身份块。新增 `TimelineTree.end(id, source)` 和 `TimelineTree.page(id, after, limit)`。`TimelineInfo.source`,依据父分支的 `branch/create` 填写(§5)。结束流程及其守卫、线进入结束后拒绝输入、`branch/ended`、恢复规则、读已结束的线,以及默认分支:根上的 `branch/default`、它的恢复读取,和一次移动写下的那条事实。它的 `directory()` 报告未结束、结束中和已结束的线:结束中的线从工具、用户或级联写入它自己的 `branch/end` 起,到它的已结束记录被写入为止,带该事件与活头部,并带当前的 `defaultBranchId`。它的节点把这条线最新轮次结束的序号发布给它开出的线(§7.1.1)。它还送达工具结束记下的最终消息:工具结束的 `branch/end` 带着它(§10、§16),所以恢复在父线上没有带该指令推出的 id 的输入时写一条,已有则什么也不写 | 它拥有线的生命周期、开启输入,以及默认分支唯一的那条权威事实 | | TreeTimeline | 消费 `branch/end`,以及由工具调用发出的结束时这条线的下一次轮次结束,并转给 TimelineTree。它把每一次 `turn/end` 报告给 TimelineTree,后者为这条线的子线发布 | 它现在就这样转 `branch/create` | | BranchTool | 按动作区分的工具,加上新的 BranchLine 分支部件。`read` 和 `message` 读、写调用方被切出来的那条线和它开出的工具线,共用一条游标规则。`create` 接受根和当前默认分支,其余线以 `branch_not_opener` 拒绝,然后检查 Session 上限,超过时以 `branch_limit_reached` 拒绝 | 工具的各个动作,以及一条线对自己相关各线的视图 | -| Session 门面 | `Session::end_branch(id, source)`、`Session::default_branch(id)` 和 `Session::set_default_branch(id, source)`。已结束线的头部由 `Session::sequence` 给出;其历史在固定的头部经 `TreeCommands.page` 读取 | §17 | +| Session 门面 | `Session::end_branch(id, source)`、`Session::default_branch(id)` 和 `Session::set_default_branch(id, source)`。已结束线的头部由 `Session::sequence` 给出;其历史在固定的头部经 `TimelineTree.page` 读取 | §17 | | App Server | `session.branch_end`(v3,用户来源,带生成的 `operation_id`;`session_execution` 打开、且连接的入口不是裸入口或守护进程 profile 未受保护时,`hello.features` 把它和其他会话方法一起列出)。`session.branch_set_default`(v3,同样的准入)。对已结束的线,`session.history` 立即返回,截到它存储的头部。`session.branches` 读树的目录并带 `defaultBranchId`(§14)。今天写死 `main` 的每个 Session 级缺省目标改读默认分支:`session.submit`、`session.stop`、`session.idle`、`session.goal.*` 和 `shell.run`,以及新建的排期任务。`session.model.update`、`session.agent.update` 和 `session.prompt.refresh` 作用于默认分支,而不是拒绝除根以外的每条线。`approval.respond` 仍用它通知里带的 `branchId`,所以已挂起的请求留在提问的那条线上。`ProductEvent::new` 在 v3 里带上新的事件种类,v1、v2 里不带 | 一个入口和三条读取路径,没有业务逻辑 | | dim-agent-types | 在 `EventKind` 和 v1 排除列表里加入 `branch/end`、`branch/ended`,再加入 `branch/default`,并在契约测试中登记。`BranchSource` 增加一个变体,表示用户开的线,与插件的区分开。冻结样本不变 | 核心事实(§16) | | 存储 | `FORMAT` 52 → 53,只升标记的升级 `(52, &[])`:不扫表、不迁移数据,所以旧 daemon 会直接拒绝这个库,而不是在第一次解码时失败。`SqliteTimelineStore` 的写线程为会话目录的最近活动缓存每个 Session 的默认分支,初值来自恢复用的同一条索引点查 | 新的事件种类和新的 `BranchSource` 变体,是 52 版 daemon 解不出的行 | | Goal(Pursuit 修订) | 从线的来源识别它的评审者,并结束它([Pursuit §13](plugins/Pursuit.md#13-结束评审者随-427)) | 评审者的协议归 Goal | -| 分支 TypeScript 绑定 | 重新生成 `npm/branch-services.d.ts`:TreeCommands 新增 `end` 和 `page`,`TimelineInfo` 新增 `source`。[绑定表](../../design/branch-typescript.md)中 `treeCommands` 一行列出 `end` | TreeCommands 是导出的服务 | +| 分支 TypeScript 绑定 | 重新生成 `npm/branch-services.d.ts`:TimelineTree 新增 `end` 和 `page`,`TimelineInfo` 新增 `source`。[绑定表](../../design/branch-typescript.md)中 `timelineTree` 一行列出 `end` | TimelineTree 是导出的服务 | | CLI TUI | §14 | 用户跟随线、与线对话、把线选为默认分支、结束线 | | 插件页面 | TimelineTree.md 和 BranchTool.md 随实现更新(`xtask check`) | 页面跟随代码 | @@ -611,13 +610,13 @@ WorkspaceTools 不变。 - 三种事件:`branch/end`、`branch/ended` 和 `branch/default`; - 一个 RPC 方法,`session.branch_set_default`; -- 一次 TreeCommands 读和一次写,`default_branch()` 与 `set_default_branch(id, source)`; +- 一次 TimelineTree 读和一次写,`default_branch()` 与 `set_default_branch(id, source)`; - 目录回复上的 `defaultBranchId`; - 一个 `BranchSource` 变体,表示用户开的线; - 名册的 key `branch:roster`,经 `` 指南条目告知模型; - 两个拒绝码,`branch_not_opener` 与 `branch_limit_reached`。 -BranchLine 的服务只由同一插件里的工具读取。轮次结束信号是 crate 内部的,与 `TreeCommands.page`、`head` 并列:它不导出,TypeScript 绑定不变。 +BranchLine 的服务只由同一插件里的工具读取。轮次结束信号是 crate 内部的,与 `TimelineTree.page`、`head` 并列:它不导出,TypeScript 绑定不变。 ## 16. 格式 @@ -647,12 +646,12 @@ BranchLine 的服务只由同一插件里的工具读取。轮次结束信号是 - 由 App Server 直接读存储会绕过门面。 - **通用能力。** 不带业务含义: - 线上的指令 `branch/end {source, ancestor?}`,以及父分支上的结果 `branch/ended {branch, endEvent, source, ancestor?}`; - - `TreeCommands.end(id, source)`、工具结束用的 `TreeCommands.end(id, source, final)`,以及 `Session::end_branch(id, source)`,它们只检查目标;最终消息在指令提交之后送达(§10); + - `TimelineTree.end(id, source)`、工具结束用的 `TimelineTree.end(id, source, final)`,以及 `Session::end_branch(id, source)`,它们只检查目标;最终消息在指令提交之后送达(§10); - `TimelineInfo.source`,依据父分支的 `branch/create` 填写; - `branch/end` 提交后不再接受新输入; - 先结束后代; - 恢复时把已结束的线视为不活跃,并为没有 `branch/ended` 的 `branch/end` 补完结束; - - 已结束线已提交的历史在固定的头部仍可读取,经 `TreeCommands.page`。 + - 已结束线已提交的历史在固定的头部仍可读取,经 `TimelineTree.page`。 - **对序号、批次、中断、重载的影响。** - 每个事件单独一个批次:线上的 `branch/end`,以及关闭之后父分支上的 `branch/ended`。工具结束的最终消息是父线上的第二个事件,写在 `branch/end` 之后、关闭之前,带由该指令推出的 id。 - `host` 或 `user` 来源的结束,或因祖先而结束,经 `Branch::close()` 中断这条线。 @@ -662,7 +661,7 @@ BranchLine 的服务只由同一插件里的工具读取。轮次结束信号是 ## 18. 安全 - 各线共用 Session 的权限策略和 Approval。一条线不是隔离手段([ADR 003](../adr/003-approval-scope.md))。 -- 只有 TimelineTree 和 BranchLine 写这些标记。其他写块的生产者(经 `TreeCommands.input` 的插件)是受信任的进程内部件。RPC 不写块。 +- 只有 TimelineTree 和 BranchLine 写这些标记。其他写块的生产者(经 `TimelineTree.input` 的插件)是受信任的进程内部件。RPC 不写块。 - `session.branch_end`、`session.branch_set_default` 和 `session.branch_create` 一样,是受信任的用户入口。它们不需要审批,因为它们不是 agent 的动作。 - 任何受信任的进程内部件都能结束守卫允许的任一条未结束的线,就像它能向任一条线写输入。工具的 `end` 与其他调用一样受 Approval 约束。 - 默认分支不带任何权威。选择它只改变缺省目标指向哪条线,不扩大任何线的 Permission、Approval 或文件根([ADR 003](../adr/003-approval-scope.md))。 @@ -682,14 +681,14 @@ BranchLine 的服务只由同一插件里的工具读取。轮次结束信号是 | §4.4 核心不带业务含义 | Dispatcher、`before` 和批次不变;Timeline 的准入检查是通用的(§17 R1)。身份文本属于 TimelineTree 自己的领域,即一个 Session 的各条线。工具线的协议写在 `first_input` 现在写工具专用文本的地方,也就是拥有该工具的模块里 | | §4.5 批次 | `branch/end` 单独一个批次,工具结束时带着它的最终消息。消息本身是父线上更晚的一条 `input/message`,id 由那次结束推出,所以两者有次序但不是同一个批次,补全这对的是恢复(§10)。`branch/ended` 在关闭之后最后写入。名册和结束通知是同一条输入。根上的 `branch/default` 单独一个批次,每条状态说明都是它之后的一条 Append | | §4.6 上下文 | 身份、名册、消息、通知和状态说明都是被采用的输入。`read` 返回工具结果。没有别的东西进入上下文 | -| §4.7 公开事件与服务 | BranchLine 折叠的是它自己那条线的公开事件。工具读 BranchLine(同一插件)和 TreeCommands。`read` 像 Collaboration 的 `read` 一样,把已提交的事件作为工具结果返回,没有哪个部件折叠另一条线的事实。Goal 按它自己公开的 A5 约定判定开启输入(§7.4)。BranchLine 和 Goal 经公开服务 TreeCommands 读取 `TimelineInfo.source` | -| §4.8 基础设施 | 门面和格式的改动即 R1(§17)。需求来自线的生命周期本身,在运行时内闭环。默认分支的那条事实、它的读和它的写也是同类基础设施:一种事件、一次 `TreeCommands` 读和一次写,绑定里没有业务规则 | +| §4.7 公开事件与服务 | BranchLine 折叠的是它自己那条线的公开事件。工具读 BranchLine(同一插件)和 TimelineTree。`read` 像 Collaboration 的 `read` 一样,把已提交的事件作为工具结果返回,没有哪个部件折叠另一条线的事实。Goal 按它自己公开的 A5 约定判定开启输入(§7.4)。BranchLine 和 Goal 经公开服务 TimelineTree 读取 `TimelineInfo.source` | +| §4.8 基础设施 | 门面和格式的改动即 R1(§17)。需求来自线的生命周期本身,在运行时内闭环。默认分支的那条事实、它的读和它的写也是同类基础设施:一种事件、一次 `TimelineTree` 读和一次写,绑定里没有业务规则 | | §4.9 只有后续决定要用的事实才进 Timeline | `branch/end` 决定关闭和恢复,而工具结束的最终消息随它一起写,因为恢复要用它决定还欠不欠一次送达、该送什么;其他来源不携带消息,诊断也不记录消息文本(§18)。`branch/ended` 决定恢复时是否活跃,以及名册。`branch/default` 决定 Session 的缺省目标指向哪条线、哪几条线能开线,两者都是后续调用会读的;它只带一条线和移动它的操作,没有别的。没有只给 UI 用的事件,也没有只给展示用的字段 | | ADR 002 D1 作用域 | 见 §5 | | D2 不设接线模块 | BranchTool 的 feature 自己登记 BranchLine | -| D3 作用域依赖 | BranchLine 向外依赖 Session 的 TreeCommands。没有核心部件依赖它 | +| D3 作用域依赖 | BranchLine 向外依赖 Session 的 TimelineTree。没有核心部件依赖它 | | D4 配置 | 无 | -| D5 合同语言中立 | 事件、RPC 方法、标记和工具 schema 都是数据。TreeCommands 新的读和写已导出,并为 TypeScript 生成类型 | +| D5 合同语言中立 | 事件、RPC 方法、标记和工具 schema 都是数据。TimelineTree 新的读和写已导出,并为 TypeScript 生成类型 | | ADR 003 审批 | 工具风险仍是 `session`,Approval 放行每次调用。用户结束一条线不是 agent 的动作。开线权不是默认分支授予的权威:它是工具的规则,既不扩大 Permission 也不扩大 Approval | ## 20. 验收 @@ -722,9 +721,9 @@ Goal 流程,放在 `crates/dim-goal/tests` 的流程测试中(§7.4): 线的结束与来源: -14. `TreeCommands.end` 结束守卫允许的任一条未结束的线,不管是谁调用。例如插件部件以 `host` 来源结束一条工具线,开它的那条线就收到结束通知。它拒绝根、默认分支、默认分支的祖先、还在打开的线和已结束的线,什么也不写。 +14. `TimelineTree.end` 结束守卫允许的任一条未结束的线,不管是谁调用。例如插件部件以 `host` 来源结束一条工具线,开它的那条线就收到结束通知。它拒绝根、默认分支、默认分支的祖先、还在打开的线和已结束的线,什么也不写。 15. 结束一条有子分支的插件线时,先结束子分支(带 `ancestor`,复制 `source`),再结束这条线。结束任何后代就是默认分支的线时,在写任何东西之前就被拒绝。 -16. `TreeCommands.list` 和 `info` 对新建和恢复的子分支返回 `source`,对根不返回。已结束的目录条目只在显示详情时读取来源。存储的目录行逐字节不变。 +16. `TimelineTree.list` 和 `info` 对新建和恢复的子分支返回 `source`,对根不返回。已结束的目录条目只在显示详情时读取来源。存储的目录行逐字节不变。 分支目录: diff --git a/docs/zh/design/timeline-read-entries.md b/docs/zh/design/timeline-read-entries.md index bea91d4909..09eb6ffc28 100644 --- a/docs/zh/design/timeline-read-entries.md +++ b/docs/zh/design/timeline-read-entries.md @@ -57,7 +57,6 @@ ### 1.6 存储端口(`timeline_store.rs`) - ### 1.7 依赖图 每条边都是本次审计从调用点读出来的。边上的标签列出经过它的读;指向存储端口的那条是概括写的,因为 `timeline.rs` 内部的调用只枚举了一部分。虚线表示共用的存储代码,不是调用。 @@ -287,7 +286,7 @@ flowchart LR ### 6.5 接线 - 能力部件声明对其分支的 Timeline 服务的依赖,并直接调它的 `query`。门面不在它们的路径上。 -- goal 插件读事件时注入 Timeline 服务而不是 `dispatcher`,调用 `Timeline.query`。`npm/branch-services.d.ts` 已经在 `Timeline` 上声明了 `query`。该文件的 `Services` 接口列出了 `timeline: Timeline`,所以这个名字存在。goal 目前注入 dispatcher、timelineIdentity、treeCommands、settings、branchLifecycle 和 sessionLifecycle;绑定能否为分支部件解析 `timeline` 未核实。goal 还读到已分配位置(`dispatcher.committed()` :104、`local(turnStart, through)` :176),所以它和文件读取、协作重建属于同一个未决问题。 +- goal 插件读事件时注入 Timeline 服务而不是 `dispatcher`,调用 `Timeline.query`。`npm/branch-services.d.ts` 已经在 `Timeline` 上声明了 `query`。该文件的 `Services` 接口列出了 `timeline: Timeline`,所以这个名字存在。goal 目前注入 dispatcher、timelineIdentity、timelineTree、settings、branchLifecycle 和 sessionLifecycle;绑定能否为分支部件解析 `timeline` 未核实。goal 还读到已分配位置(`dispatcher.committed()` :104、`local(turnStart, through)` :176),所以它和文件读取、协作重建属于同一个未决问题。 - App Server 通过 `Session::query(branch, query)` 读已装载的会话,它转发到 `Branch::query`,再到 Timeline 服务。 - App Server 通过 `SessionStore` 读未装载的会话,因为它没有 Timeline 服务可用。页形状与 `query` 一致,所以装载与否不改变协议。 - 删除这些读之后,`xtask types` 重新生成 `npm/branch-services.d.ts`,`xtask graph` 重新生成 `catalog.md`;生成文件里其余内容不得变化。 diff --git a/npm/branch-services.d.ts b/npm/branch-services.d.ts index be376bab05..f07cc1caad 100644 --- a/npm/branch-services.d.ts +++ b/npm/branch-services.d.ts @@ -597,6 +597,24 @@ export interface SkillsConfig { get(): Promise } +export type BranchOperation = + | { kind: "contextUsage.read" } + | { kind: "compactAndWait" } + | { kind: "prompt.configure"; request: PromptConfigurationRequest } + | { kind: "prompt.adoptedConfiguration" } + | { kind: "approval.pending" } + | { kind: "approval.decide"; requestId: string; decision: ApprovalDecision } + | { kind: "inputQueue.withdraw"; command: InputWithdrawData } + +export type BranchCall = { + branchId: string + operation: BranchOperation +} + +export type DirectoryRequest = { + id?: string | null +} + export type TimelineInfo = { id: string parent?: string | null @@ -605,6 +623,45 @@ export type TimelineInfo = { source?: BranchSource | null } +/** Whether a line takes input, is finishing a committed end, or has ended. */ +export type BranchDirectoryState = + | /** The line takes input, and its head is live. */ "open" + | /** The line's own `branch/end` is committed and its ended row is not: input is refused, and its head is still live. */ "ending" + | /** The line has ended: its head and its end event are fixed. */ "ended" + +/** One line's directory record: its identity, its state, its head and its end. */ +export type BranchDirectoryEntry = { + info: TimelineInfo + /** The published head while open or ending, the fixed head once ended. */ + head: number | bigint + state: BranchDirectoryState + /** + * The sequence of the line's own `branch/end`: committed while ending, + * recorded once ended. + */ + endEvent?: number | bigint | null +} + +export type DirectoryReply = BranchDirectoryEntry | BranchDirectoryEntry[] + +export type BranchEndData = { + source: BranchSource + ancestor?: string | null + /** + * The message the parent receives, present only on a tool end, because + * only a tool end owes one and restore delivers a missing one from it + * ([timeline branches §10](../../../docs/design/timeline-branches.md#10-ending-a-line)). + */ + final?: string | null +} + +export type DirectoryDisplay = { + entry: BranchDirectoryEntry + purpose?: string | null + cutMessages?: number | bigint | null + end?: BranchEndData | null +} + /** Which branches a query covers. */ export type TimelineQueryScope = | /** The queried branch alone. */ "branch" @@ -717,8 +774,12 @@ export type BranchOptions = { source: BranchSource } -/** Shared with Timeline roots; never owns the tree or its child roots. */ -export interface TreeCommands { +export interface TimelineTree { + call(request: BranchCall, cancelled: () => void | Promise): Promise + /** @throws {AgentErrorThrown} */ + directory(request: DirectoryRequest): Promise + /** @throws {AgentErrorThrown} */ + display(id: string): Promise list(): Promise /** * The directory record of branch `id`, from its reservation on, so a @@ -733,11 +794,25 @@ export interface TreeCommands { * @throws {AgentErrorThrown} */ input(id: string, input: InputMessageData): Promise + /** + * Commits `inputs` to branch `id` as one atomic batch through its + * validating `Branch::inputs`: the given order, contiguous sequences and + * one publication. + * @throws {AgentErrorThrown} + */ + inputs(id: string, inputs: InputMessageData[]): Promise /** * Ends the line `id` with `source`; only the target is checked (§10). * @throws {AgentErrorThrown} */ end(id: string, source: BranchSource): Promise + /** + * Ends the line `id` with a tool end's `final_message` riding on its + * `branch/end`, which the parent receives once the end is admitted + * (design §10). + * @throws {AgentErrorThrown} + */ + endWithFinal(id: string, source: BranchSource, finalMessage?: string | null): Promise /** * The line the Session's conversation is on: the root until a * `branch/default` moves it, then that fact's line while it is open and @@ -760,6 +835,11 @@ export interface TreeCommands { * @throws {AgentErrorThrown} */ page(id: string, after: number | bigint, limit: number | bigint, through: number | bigint): Promise + /** + * Ends a raw-event page on an atomic batch boundary without reading its payloads. + * @throws {AgentErrorThrown} + */ + pageEnd(id: string, after: number | bigint, limit: number | bigint, through: number | bigint): Promise /** * Computes properties at a fixed cutoff. Chain scope reads only published * facts, with each ancestor bounded by its inherited cut. An ended line @@ -767,6 +847,12 @@ export interface TreeCommands { * @throws {AgentErrorThrown} */ query(id: string, query: TimelineQuery): Promise + /** + * Checks that `sequence` ends an atomic batch of line `id`, forwarding to + * its Timeline while open and reading the store once it ends. + * @throws {AgentErrorThrown} + */ + batchEnd(id: string, sequence: number | bigint): Promise /** * Creates a child of `parent` cut at `at` and returns its id. * `cancelled` is the caller's cancellation as an explicit argument, the @@ -1446,7 +1532,7 @@ export interface Services { prompt: Prompt sessionLanguage: SessionLanguage skillsConfig: SkillsConfig - treeCommands: TreeCommands + timelineTree: TimelineTree branchLine: BranchLine wait: Wait backgroundExec: BackgroundExec diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index fd5f3d0fa1..5c62717091 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -260,7 +260,7 @@ export type BranchEvent = Omit & { * `ctx.use('name')`. */ export type { AgentErrorThrown, BranchLifecycle, Dispatcher, PartRegistry, PartScope, ProcessActivity, Services, SessionIdentity, SessionLifecycle, - TimelineIdentity, TreeCommands, PermissionState, SessionPermissions, SessionsErrorThrown, + TimelineIdentity, TimelineTree, PermissionState, SessionPermissions, SessionsErrorThrown, WorkflowFiles, WorkflowFileEntry, WorkflowRoot, WorkflowFilesErrorThrown, UiResources, PublishFile, ResourceRef, ResourceErrorThrown, } from './branch-services.js'; diff --git a/runtime/fixtures/branch-part.ts b/runtime/fixtures/branch-part.ts index dadbf46420..dfd6a580ac 100644 --- a/runtime/fixtures/branch-part.ts +++ b/runtime/fixtures/branch-part.ts @@ -5,11 +5,11 @@ import type { BranchEvent, Services } from '../../npm/plugin.js' export const part = definePlugin({ name: 'BranchPartFixture', provides: {}, - inject: ['dispatcher', 'timeline', 'timelineIdentity', 'treeCommands', 'branchLine'], + inject: ['dispatcher', 'timeline', 'timelineIdentity', 'timelineTree', 'branchLine'], async apply(ctx) { const dispatcher = ctx.use('dispatcher') const timeline = ctx.use('timeline') - const tree = ctx.use('treeCommands') + const tree = ctx.use('timelineTree') const line = ctx.use('branchLine') const lineState = async () => JSON.stringify({ resolved: await line.resolved(), ending: await line.ending(), cursor: await line.cursor('main'), diff --git a/runtime/fixtures/cordis-branch.ts b/runtime/fixtures/cordis-branch.ts index eecfc63c63..fc9cd9d395 100644 --- a/runtime/fixtures/cordis-branch.ts +++ b/runtime/fixtures/cordis-branch.ts @@ -1,7 +1,7 @@ import type { Context } from '@deepseek-ai/cordis' export const name = 'cordis-branch-fixture' -export const inject = ['dispatcher', 'timelineIdentity', 'treeCommands'] +export const inject = ['dispatcher', 'timelineIdentity', 'timelineTree'] export async function apply(ctx: Context) { const { sessionId, branchId } = await ctx.get('timelineIdentity').get() @@ -9,7 +9,7 @@ export async function apply(ctx: Context) { await ctx.get('dispatcher').listen('cordis-branch-fixture', ['turn/end'], async () => { if (written) return written = true - await ctx.get('treeCommands').input(branchId, { + await ctx.get('timelineTree').input(branchId, { blocks: [{ type: 'raw', text: `` }], mode: 'queue', }) diff --git a/runtime/fixtures/extension-events.ts b/runtime/fixtures/extension-events.ts index fcabdd40a4..ff0be5af86 100644 --- a/runtime/fixtures/extension-events.ts +++ b/runtime/fixtures/extension-events.ts @@ -5,11 +5,11 @@ import type { BranchEvent, Services } from '../../npm/plugin.js' export const part = definePlugin({ name: 'ExtensionEventsFixture', provides: {}, - inject: ['dispatcher', 'timeline', 'timelineIdentity', 'treeCommands'], + inject: ['dispatcher', 'timeline', 'timelineIdentity', 'timelineTree'], async apply(ctx) { const dispatcher = ctx.use('dispatcher') const timeline = ctx.use('timeline') - const tree = ctx.use('treeCommands') + const tree = ctx.use('timelineTree') const { branchId } = await ctx.use('timelineIdentity').get() let appended = false let restored = false diff --git a/runtime/fixtures/python/python_branch_part.py b/runtime/fixtures/python/python_branch_part.py index 10829a6352..5b42f61a60 100644 --- a/runtime/fixtures/python/python_branch_part.py +++ b/runtime/fixtures/python/python_branch_part.py @@ -11,7 +11,7 @@ async def apply(ctx, config): dispatcher = ctx.use("dispatcher") timeline = ctx.use("timeline") - tree = ctx.use("treeCommands") + tree = ctx.use("timelineTree") identity = await ctx.use("timelineIdentity").get() session, branch = identity["sessionId"], identity["branchId"] seen = [] @@ -66,6 +66,6 @@ async def rebuild(): part = define_plugin( apply, - inject=["dispatcher", "timeline", "timelineIdentity", "treeCommands"], + inject=["dispatcher", "timeline", "timelineIdentity", "timelineTree"], name="PythonBranchPart", ) diff --git a/runtime/fixtures/tree-create.ts b/runtime/fixtures/tree-create.ts index b0446f8fc5..22649b422b 100644 --- a/runtime/fixtures/tree-create.ts +++ b/runtime/fixtures/tree-create.ts @@ -1,28 +1,59 @@ import { definePlugin } from '@arcships/rutis' import { partRow } from './part-row.ts' import provides from './tree-create.json' with { type: 'json' } -import type { SessionMethods } from '../../npm/plugin.js' - -type TreeCommands = { - create(parent: string, at: number | bigint, options: unknown, cancelled: () => Promise): Promise -} -type MethodCall = { method: string; params: { sessionId: string; at: number; cancel: boolean } } +import assert from 'node:assert/strict' +import type { SessionMethodReply, SessionMethods, TimelineTree } from '../../npm/plugin.js' export const part = definePlugin({ name: 'TreeCreateFixture', provides, - inject: ['treeCommands', 'sessionMethods'], + inject: ['timelineTree', 'sessionMethods'], async apply(ctx) { - const tree = ctx.use('treeCommands') + const tree = ctx.use('timelineTree') await ctx.use('sessionMethods').register( 'session.treeprobe', [{ name: 'session.treeprobe.create', mutating: true, interruption: 'report', progress: false }], - async (call: MethodCall) => { - const { at, cancel } = call.params - const options = { prompt: 'probe child', source: { kind: 'host', operation_id: crypto.randomUUID() } } + async ({ params }): Promise => { + const { at, cancel } = params + assert.ok(typeof at === 'number' || typeof at === 'bigint') + assert.equal(typeof cancel, 'boolean') + const options = { prompt: 'probe child', source: { kind: 'host' as const, operation_id: crypto.randomUUID() } } const cancelled = () => (cancel ? Promise.resolve() : new Promise(() => {})) try { - return { kind: 'value', value: { id: await tree.create('main', at, options, cancelled) } } + const id = await tree.create('main', at, options, cancelled) + assert.deepEqual(await tree.call({ branchId: id, operation: { kind: 'approval.pending' } }, cancelled), []) + assert.deepEqual(await tree.call({ + branchId: id, operation: { kind: 'inputQueue.withdraw', command: { input_id: 'absent' } }, + }, cancelled), { status: 'notHeld' }) + await assert.rejects(tree.call({ + branchId: id, operation: { kind: 'approval.decide', requestId: 'absent', decision: 'deny' }, + }, cancelled), { code: 'Unknown' }) + await assert.rejects( + tree.call({ branchId: 'missing', operation: { kind: 'approval.pending' } }, cancelled), + { code: 'session_invalid_input' }, + ) + const adopted = { kind: 'prompt.adoptedConfiguration' as const } + const rootModel = await tree.call({ branchId: 'main', operation: adopted }, cancelled) + const configured = await tree.call({ + branchId: id, operation: { kind: 'prompt.configure', request: { + sources: [], model: { providerId: 'fixture', modelId: 'tree-selected' }, + } }, + }, cancelled) + assert.equal(configured, 'adopted') + const childModel = await tree.call({ branchId: id, operation: adopted }, cancelled) + assert.ok(childModel && typeof childModel === 'object' && 'modelId' in childModel) + assert.equal(childModel.modelId, 'tree-selected') + assert.deepEqual(await tree.call({ branchId: 'main', operation: adopted }, cancelled), rootModel) + const entry = await tree.directory({id}) + assert.ok(!Array.isArray(entry) && entry.info.id === id && entry.state === 'open') + const directory = await tree.directory({}) + assert.ok(Array.isArray(directory) && directory.some(item => item.info.id === id)) + const detail = await tree.display(id) + assert.equal(detail.entry.info.id, id) + assert.equal(detail.purpose, 'probe child') + await tree.batchEnd('main', at) + assert.equal(Number(await tree.pageEnd('main', at, 1, at)), Number(at)) + return { kind: 'value', value: { id } } } catch (error) { return { kind: 'value', value: { error: (error as { code?: string }).code ?? String(error) } } } diff --git a/runtime/plugin-sdk.test.mjs b/runtime/plugin-sdk.test.mjs index 9b3b70d566..8e2c3b0cda 100644 --- a/runtime/plugin-sdk.test.mjs +++ b/runtime/plugin-sdk.test.mjs @@ -316,9 +316,9 @@ const referencedEntry = await branch.timeline.query({ page: { limit: 1 }, }); void referencedEntry; -void branch.treeCommands.input('main', { blocks: [{ type: 'raw', text: 'source marker' }], mode: 'queue' }); -void branch.treeCommands.create('main', cutoff, { prompt: 'child', source: { kind: 'host', operation_id: 'create-id' } }, cancelled); -const info = await branch.treeCommands.info('main'); +void branch.timelineTree.input('main', { blocks: [{ type: 'raw', text: 'source marker' }], mode: 'queue' }); +void branch.timelineTree.create('main', cutoff, { prompt: 'child', source: { kind: 'host', operation_id: 'create-id' } }, cancelled); +const info = await branch.timelineTree.info('main'); const parentCut: number | bigint | null | undefined = info.branch_point; const active: boolean = await branch.branchLifecycle.activated(); const closing: Promise = branch.branchLifecycle.closing(); @@ -331,9 +331,9 @@ void branch.dispatcher.listen({}, 'counter', ['input/message'], () => {}); // @ts-expect-error a handler returns void or a Promise of void. void branch.dispatcher.listen('counter', ['input/message'], () => 'ack'); // @ts-expect-error native input uses blocks, not the sessions service's rawBlocks. -void branch.treeCommands.input('main', { rawBlocks: [{ text: 'source marker' }] }); +void branch.timelineTree.input('main', { rawBlocks: [{ text: 'source marker' }] }); // @ts-expect-error native source field spelling comes from Rust serde. -void branch.treeCommands.create('main', 0, { prompt: 'child', source: { kind: 'host', operationId: 'id' } }, cancelled); +void branch.timelineTree.create('main', 0, { prompt: 'child', source: { kind: 'host', operationId: 'id' } }, cancelled); // @ts-expect-error sequence values must retain their number | bigint type. const lossyCut: number = cutoff; `); diff --git a/tests/integration/tests/local_execution.rs b/tests/integration/tests/local_execution.rs index 9cab6b9109..dc5bc28caa 100644 --- a/tests/integration/tests/local_execution.rs +++ b/tests/integration/tests/local_execution.rs @@ -15,7 +15,7 @@ use dim_agent_capabilities::{ HostPlatformConfig, HostPlatformPlugin, OutputEncoding, ShellEdition, ShellSource, ShellStatus, resolve_shell, }, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, wait, workspace_tools::{ self, WorkspaceToolsConfig, @@ -182,7 +182,7 @@ type Probed = Vec<(String, Arc, Ctx)>; #[derive(Clone, Default)] struct Seen { timelines: Arc>, - tree: Arc>>>, + tree: Arc>>>, } impl Seen { fn timeline(&self, branch: &str) -> Arc { @@ -214,7 +214,7 @@ impl Seen { let (.., ctx) = timelines.iter().rfind(|(id, ..)| id == branch).unwrap(); ctx.view(id).unwrap().restart() } - fn tree(&self) -> Arc { + fn tree(&self) -> Arc { self.tree.lock().unwrap().clone().expect("probed tree") } /// The probed branch's own context, which reads the services of its @@ -234,7 +234,7 @@ struct Probe { seen: Seen, timeline: Key, identity: Key, - tree: Key, + tree: Key, } impl Probe { fn new(names: &Names<'_>, hook: Hook, seen: Seen) -> rutis::Result { diff --git a/tests/integration/tests/local_support/mod.rs b/tests/integration/tests/local_support/mod.rs index 86af26bf38..fa1b233a18 100644 --- a/tests/integration/tests/local_support/mod.rs +++ b/tests/integration/tests/local_support/mod.rs @@ -19,7 +19,7 @@ use dim_agent_capabilities::{ prompt_sources, skill_settings::{SkillSettings, SkillSettingsHost}, skills::{self, MemorySkillSettings, SkillsCatalog, SkillsCatalogPlugin}, - timeline_tree::TreeCommands, + timeline_tree::TimelineTree, }; use dim_agent_runtime::testing::MinimalHost; use dim_agent_runtime::testing::chain_events; @@ -243,7 +243,7 @@ pub struct LifecycleProbe { pub events: Mutex>, pub recorded: Notify, lifecycles: Mutex>>, - trees: Mutex>>, + trees: Mutex>>, hold_close: std::sync::atomic::AtomicBool, pub close_held: Notify, pub release_close: Notify, @@ -259,7 +259,7 @@ impl LifecycleProbe { } /// The branch tree commands a part of `session` injects, which reach each /// published branch's own operations. - pub fn tree(&self, session: &str) -> Arc { + pub fn tree(&self, session: &str) -> Arc { self.trees.lock().unwrap()[session].clone() } pub fn count(&self, event: &str) -> usize { @@ -292,7 +292,7 @@ struct LifecycleProbePlugin { probe: Arc, lifecycle: Key, identity: Key, - tree: Key, + tree: Key, } impl LifecycleProbePlugin { fn new(names: &Names<'_>, probe: Arc) -> rutis::Result { diff --git a/tests/integration/tests/prompt_lifecycle.rs b/tests/integration/tests/prompt_lifecycle.rs index ecfc514d68..2973fde3ba 100644 --- a/tests/integration/tests/prompt_lifecycle.rs +++ b/tests/integration/tests/prompt_lifecycle.rs @@ -1199,7 +1199,7 @@ async fn overlapping_load_is_superseded_and_close_joins_cancellation() { }); started.notified().await; let branch = session - .session_service::() + .session_service::() .unwrap() .get("main") .unwrap();