From eb1c594016560b29d357a981dc04114513a76b44 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 09:56:21 +0800 Subject: [PATCH 1/6] feat(agents): project live and recorded session entries in Core Share the bounded entry index, revisioned reads, file summaries and retry validation across live sessions and loaded history pages. Refs 1lck/Lithe-IDEA#2552. --- rust/contracts/application-boundary.md | 12 + rust/contracts/rust-core-api.md | 57 ++ rust/crates/agent-runtime/src/events.rs | 68 +- rust/crates/agent-runtime/src/interaction.rs | 6 + rust/crates/agent-runtime/src/lib.rs | 8 + rust/crates/agent-runtime/src/live.rs | 70 +- rust/crates/agent-runtime/src/projection.rs | 604 ++++++++++++++++++ .../agent-runtime/src/projection/command.rs | 196 ++++++ .../agent-runtime/src/projection/history.rs | 208 ++++++ .../agent-runtime/src/projection/tests.rs | 151 +++++ .../agent-runtime/src/projection/wire.rs | 98 +++ rust/crates/agent-runtime/src/records.rs | 46 +- rust/crates/agent-runtime/src/tests.rs | 119 ++++ rust/crates/core/src/protocol/command.rs | 4 + .../agents/session-projection-v1.json | 22 + 15 files changed, 1663 insertions(+), 6 deletions(-) create mode 100644 rust/crates/agent-runtime/src/projection.rs create mode 100644 rust/crates/agent-runtime/src/projection/command.rs create mode 100644 rust/crates/agent-runtime/src/projection/history.rs create mode 100644 rust/crates/agent-runtime/src/projection/tests.rs create mode 100644 rust/crates/agent-runtime/src/projection/wire.rs create mode 100644 rust/fixtures/agents/session-projection-v1.json diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 128574e2..6258810e 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -107,6 +107,18 @@ turn is suppressed, allowing a same-batch terminal result to finish Stop. See [the native session contract](../../shared/plugins/contract/v1/README.md#native-sessions) and [the shared fixture](../fixtures/agents/turn-interaction-v1.json). +### Agent conversation views + +Core assigns stable row IDs, merges live message deltas and tool updates, and +applies previously loaded history pages to the same row index and retention +budget. A restored conversation places historical turns before live turns. +Retry names the original row and Core checks its identity and contents again +when it accepts the prompt. The desktop owns the unconfirmed input preview, +draft, scroll anchor and selection. Closing a process leaves its conversation +readable until the host releases the view. The projection lives in memory. +See the [command contract](rust-core-api.md#agent-conversation-projection) +and [mixed-session example](../fixtures/agents/session-projection-v1.json). + ### Dev Container configuration and execution environment The same explicit runtime target follows discovery, configuration lookup, build, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 60f77ab1..9b51a28c 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -492,6 +492,7 @@ or removing a command fails until the table changes in the same commit. | `agents.setConfigOption` | Pick a value of a session setting the agent backend reported | | `agents.close` | End a live agent session | | `agents.waitEvents` | Wait, bounded, for agent session events after a sequence | +| `agents.projection` | Read a bounded conversation view or apply a loaded history page | | `agentSessions.configure` | Open the agent session record cache | | `agentSessions.sync` | Read one agent's changed session files through its plugin | | `agentSessions.forget` | Drop one agent's cached session records | @@ -9194,6 +9195,62 @@ may contain secrets. Public backend methods and lifecycle are specified in the ### Recorded conversation windows +#### Agent conversation projection + +A desktop that requests `projection: true` in `agents.start` owns a view +identified by the returned session ID. Core applies accepted events before +publishing their sequence. Ordinary sends enter the projection before backend +delivery completes. Failed delivery retracts the corresponding row. Existing +hosts can continue to use the original event stream. Pass `compact: true` to +`agents.waitEvents` to receive change notifications and required UI events +without streaming message and tool bodies a second time. Recovery delivery +and acknowledgements keep their existing semantics. Hosts drain through the header's `exitSequence` before they stop waiting for final recoveries. A compact wait can include +`views`, a map of session IDs to installed revisions. Only events and recoveries for those sessions cross the boundary. Consecutive short text +suffixes for one row then arrive in `inline[session]` with the new revision, +row position, appended text and budget status in the same response. + +`agents.projection` takes one application operation. + +| Operation | Request | Result | +| --- | --- | --- | +| `open` | No arguments | An independent history viewer ID in `session`. Supply its catalog `agent` key to bind cached pages to its read grant. | +| `page` | `session, ticket, start, end, messages, before, replace?` | Applies one page from the existing record reader. An increasing ticket orders page changes. Replaying the same ticket is idempotent. `restarted` marks a full history viewer that reopened at this page. | +| `chunk` | `session, frame, offset` | Reads the next UTF-8 fragment of an oversized response. | +| `clearHistory` | `session, ticket` | Removes recorded rows, preserving live rows. | +| `read` | `session, after?, offset?, snapshot?` | A bounded update with `revision`, history `ticket`, `trimmed` rows, `outputDropped` upstream lines, their display total `dropped`, and `room` for another record page. | +| `release` | `session` | Releases rows, buffered updates and snapshot resources. Releasing twice is safe. | + +On a first read or an expired cursor, `reset` is true. Replace rows starting +at `start`. Request `nextOffset` with the returned revision in `snapshot` +until the snapshot ends. In ordinary reads, apply `edits` in order. Each edit +specifies a zero-based position `at` and a row to insert at the end or replace, +a text suffix to append, or a row to remove. Apply any `cut` to the front +after that edit. `more` asks the reader to continue after the delivered +revision. A header or file list in the response replaces its previous value. +Absent optional row fields have their empty or false value. Row kinds 0 through 4 mean user input, assistant text, thought, tool and notice. +`serial` identifies a retained row across index changes. The original input +identified by `opening` is eligible for retry when the row's `retryable` and the +header's `canPrompt` are true. Pass its `retrySerial` to `agents.prompt`. +Draft text, pending paste operations and native request progress remain local. + +Read responses fit a 512 KiB payload budget. If a header, file list or row +would exceed it, the response carries `frame`, `chunk` and `nextByte`. Join +the chunks and decode the resulting page when `nextByte` is zero. A discarded +frame returns `agentSessions.invalidPage`. Retry from the last installed +revision. Ordinary file reads can pass `projection: {session,ticket}` to +`agentSessions.page` to merge the authorized page directly and return its byte +range. Use the separate `page` operation for a page captured before resuming +a CLI that may immediately append to the source. + +Files preserve their first-occurrence order within the retained session, a +turn, or a visible reply segment keyed by its first row serial. Empty paths +and non-mutating tools contribute no files. The retained view keeps up to +2,000 rows and a 4 MiB estimated row budget. Reply text keeps a 256 KiB +prefix and tool output a 16 KiB tail on UTF-8 boundaries. A transport replay +gap, row eviction and dropped upstream output keep their respective meanings. + +#### Recorded session pages + `agentSessions.page` takes `{agent, path, size, generation, cursor, direction}` for a readable agent. `size` is a listed session's nonzero `readBytes` snapshot and `generation` the same listing's `generation`; empty sessions need no page request. `direction` is `before` diff --git a/rust/crates/agent-runtime/src/events.rs b/rust/crates/agent-runtime/src/events.rs index 3413c294..09a33d5b 100644 --- a/rust/crates/agent-runtime/src/events.rs +++ b/rust/crates/agent-runtime/src/events.rs @@ -803,6 +803,8 @@ pub(crate) struct HostEvent { pub sequence: u64, pub session: String, pub event: Box, + #[serde(skip)] + kind: String, } impl HostEvent { @@ -834,10 +836,19 @@ struct QueueState { #[derive(Default)] pub(crate) struct EventQueue { state: Mutex, + pub(crate) views: crate::projection::command::Views, ready: Condvar, } impl EventQueue { + pub(crate) fn project_input(&self, id: &str, event: impl FnOnce() -> Value) { + if let Some(p) = self.views.get(id) { + p.lock() + .unwrap_or_else(PoisonError::into_inner) + .event(&event()) + } + } + /// Reserves a recovery before sending an input. The fixed headroom covers /// Core's bounded failure code and envelope; recovery omits backend prose. pub fn reserve_input(&self, session: &str, input: &crate::interaction::Input) -> bool { @@ -886,13 +897,28 @@ impl EventQueue { /// Stores compact encoded payloads. Superseded interaction snapshots are /// replaced; only replay eviction marks a gap, not snapshot compaction. pub fn push(&self, session: &str, event: Value) { + let kind = event["kind"].as_str().unwrap_or_default().to_owned(); let snapshot = event["kind"] == "interactionState"; let exited = event["kind"] == "exited"; let resolved = event["kind"] == "inputResolved"; let encoded = serde_json::value::to_raw_value(&event).expect("session event serializes"); + // Serialize a session's projection and replay order without holding the + // shared queue lock while merging rows or evicting old content. + let view = self.views.get(session); + let mut projection = view + .as_ref() + .map(|v| v.lock().unwrap_or_else(PoisonError::into_inner)); + if let Some(p) = projection.as_mut() { + p.event(&event) + } let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); state.next_sequence += 1; let sequence = state.next_sequence; + if exited { + if let Some(p) = projection.as_mut() { + p.set_exit_sequence(sequence); + } + } if resolved { let key = ( session.to_string(), @@ -911,6 +937,7 @@ impl EventQueue { .expect("input resolution is an object") .remove("message"); let recovery = HostEvent { + kind: kind.clone(), sequence, session: session.into(), event: serde_json::value::to_raw_value(&recovery).expect("recovery serializes"), @@ -920,6 +947,7 @@ impl EventQueue { } } let entry = HostEvent { + kind, sequence, session: session.into(), event: encoded, @@ -946,7 +974,19 @@ impl EventQueue { /// Reads ordered replay and current snapshots after `after`. Recoveries /// also travel outside the cursor until acknowledged, including after an /// output gap or a lost response. A future cursor only probes the latest ID. + #[cfg(test)] pub fn wait(&self, after: u64, timeout: Duration, limit: usize) -> Value { + self.wait_mode(after, timeout, limit, false, None) + } + + pub fn wait_mode( + &self, + after: u64, + timeout: Duration, + limit: usize, + compact: bool, + views: Option<&BTreeMap>, + ) -> Value { let deadline = Instant::now() + timeout.min(MAX_WAIT); let limit = limit.clamp(1, MAX_EVENTS_PER_WAIT); let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); @@ -978,14 +1018,40 @@ impl EventQueue { events.dedup_by_key(|event| event.sequence); events.truncate(limit); let next = events.last().map_or(state.next_sequence, |e| e.sequence); + // Advance the shared cursor over every event, then deliver only this + // window's sessions and rejected drafts across the application boundary. + let visible = |session: &str| !compact || views.is_none_or(|ids| ids.contains_key(session)); + events.retain(|e| visible(&e.session)); let recoveries: Vec<_> = state .recoveries .values() .filter_map(|slot| slot.event.as_ref()) - .filter(|event| after <= state.next_sequence && event.sequence <= next) + .filter(|event| { + after <= state.next_sequence && event.sequence <= next && visible(&event.session) + }) .collect(); let mut recoveries = recoveries; recoveries.sort_by_key(|event| event.sequence); + if compact { + let events: Vec<_> = events + .iter() + .map(|e| { + if matches!( + e.kind.as_str(), + "inputResolved" + | "interactionFailed" + | "questionAnswered" + | "turnStarted" + | "turnEnded" + ) { + json!(e) + } else { + json!({"session":e.session,"sequence":e.sequence,"event":{"kind":e.kind}}) + } + }) + .collect(); + return json!({"events":events,"next":next,"missed":missed,"recoveries":recoveries}); + } json!({"events":events,"next":next,"missed":missed,"recoveries":recoveries}) } } diff --git a/rust/crates/agent-runtime/src/interaction.rs b/rust/crates/agent-runtime/src/interaction.rs index 0af00618..9657c96c 100644 --- a/rust/crates/agent-runtime/src/interaction.rs +++ b/rust/crates/agent-runtime/src/interaction.rs @@ -393,6 +393,12 @@ pub(crate) fn worker( runtime.live.queue.push(&session.id, json!({"kind":"inputResolved", "turn":params["turn"], "input":params["input"], "accepted":false, "content":input})); } } else if state.active_turn == params["turn"].as_u64() { + if input.as_ref().is_some_and(|i| i.id.is_empty()) { + runtime.live.queue.project_input( + &session.id, + || json!({"kind":"promptRetracted","input":"","turn":params["turn"]}), + ); + } let event = json!({"kind":"turnEnded", "turn":params["turn"], "reason":"failed"}); state.active_turn = None; state.interaction.stopping = false; diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 1f089040..a217a829 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -41,6 +41,7 @@ mod events; mod interaction; mod library; mod live; +mod projection; mod records; #[cfg(test)] @@ -74,6 +75,7 @@ pub const AGENT_COMMANDS: &[&str] = &[ "agents.setConfigOption", "agents.close", "agents.waitEvents", + "agents.projection", ]; /// The commands of the `agentSessions.*` family. @@ -128,6 +130,7 @@ impl Runtime { match command { "agents.configure" => { let answer = self.catalog.configure(payload)?; + self.live.queue.views.purge_unreadable(&self.catalog); // A session whose agent is gone or no longer granted ends. self.live.end_where(|plugin_id, agent_id| { self.catalog @@ -147,6 +150,11 @@ impl Runtime { "agents.setConfigOption" => live::set_config_option(self, payload), "agents.close" => live::close(self, payload), "agents.waitEvents" => live::wait_events(self, payload), + "agents.projection" => self + .live + .queue + .views + .execute(&self.catalog, crate::decode(payload)?), "agentSessions.configure" => self.records.configure(payload), "agentSessions.sync" => self.records.sync(self, payload), "agentSessions.forget" => self.records.forget(payload), diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index 3bd19211..f0658a4e 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -454,6 +454,8 @@ struct StartRequest { /// The agent CLI's own ID of a session to resume. #[serde(default)] resume: Option, + #[serde(default)] + projection: bool, /// Whether the user trusts the workspace. #[serde(default)] workspace_trusted: bool, @@ -647,6 +649,12 @@ fn start_checked(runtime: &Arc, request: StartRequest) -> Result, request: StartRequest) -> Result, payload: Value) -> Result, + #[serde(rename = "retrySerial", default)] + retry_serial: Option, } fn default_input_mode() -> String { "send".into() @@ -1098,6 +1109,27 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result>(); + let eligible = runtime.live.queue.views.get(&session.id).is_some_and(|v| { + v.lock().unwrap_or_else(PoisonError::into_inner).can_retry( + serial, + &request.text, + &paths, + ) + }); + if mode != "send" || !eligible { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.invalidPrompt", + "The original prompt is no longer available.", + )); + } + } if !matches!(mode, "send" | "queue" | "steer") { return Err(refusal( ErrorCode::InvalidRequest, @@ -1188,6 +1220,10 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, payload: Value) -> Result, #[serde(default)] acknowledge: Vec, + #[serde(default)] + compact: bool, + #[serde(default)] + views: Option>, } let request: WaitRequest = crate::decode(payload)?; if request.acknowledge.len() > 512 { @@ -1392,9 +1432,35 @@ pub(crate) fn wait_events(runtime: &Arc, payload: Value) -> Result(v: &'a Value, key: &str) -> &'a str { + v[key].as_str().unwrap_or_default() +} + +fn prefix(s: &str, bytes: usize) -> &str { + &s[..s.floor_char_boundary(bytes.min(s.len()))] +} + +fn tail(s: &str) -> &str { + &s[s.ceil_char_boundary(s.len().saturating_sub(MAX_OUTPUT))..] +} + +/// One retained row. Serial is stable across replacements, trims and historical prepends. +#[derive(Clone, Default, Serialize)] +#[serde(rename_all = "camelCase")] +struct Row { + kind: u8, + serial: u64, + turn: u64, + #[serde(skip_serializing_if = "String::is_empty")] + id: String, + #[serde(skip_serializing_if = "String::is_empty")] + text: String, + #[serde(skip_serializing_if = "Vec::is_empty")] + attachments: Vec, + #[serde(skip_serializing_if = "std::ops::Not::not")] + supplement: bool, + #[serde(skip_serializing_if = "String::is_empty")] + status: String, + #[serde(skip_serializing_if = "String::is_empty")] + tool_kind: String, + #[serde(skip_serializing_if = "String::is_empty")] + title: String, + #[serde(skip_serializing_if = "String::is_empty")] + command: String, + #[serde(skip_serializing_if = "Vec::is_empty")] + locations: Vec, + #[serde(skip_serializing_if = "String::is_empty")] + output: String, + #[serde(skip_serializing_if = "String::is_empty")] + level: String, + #[serde(skip_serializing_if = "String::is_empty")] + code: String, + at_ms: i64, + #[serde(skip_serializing_if = "std::ops::Not::not")] + retryable: bool, +} + +impl Row { + fn size(&self) -> usize { + 64 + self.text.len() + + self.title.len() + + self.command.len() + + self.output.len() + + self.attachments.iter().map(|s| s.len() + 16).sum::() + } + + fn key(&self) -> Option<(bool, u8, String)> { + (!self.id.is_empty() && self.kind <= TOOL).then(|| { + ( + self.turn >= RECORD_FLOOR, + if self.kind == THOUGHT { + ASSISTANT + } else { + self.kind + }, + self.id.clone(), + ) + }) + } + + fn retryable(&mut self) { + self.retryable = self.kind == USER + && !self.supplement + && self.turn != 0 + && self.text.len() < MAX_TEXT + && (!self.text.is_empty() || !self.attachments.is_empty()); + } + + fn tool_update(&mut self, later: &Value, recorded: bool) { + for (target, value) in [ + (&mut self.status, text(later, "status")), + (&mut self.tool_kind, text(later, "toolKind")), + (&mut self.title, prefix(text(later, "title"), 1024)), + ( + &mut self.command, + prefix(text(later, "command"), MAX_OUTPUT), + ), + ( + &mut self.output, + tail(text(later, if recorded { "text" } else { "output" })), + ), + ] { + if !value.is_empty() { + target.clear(); + target.push_str(value); + } + } + if let Some(locations) = later["locations"].as_array().filter(|a| !a.is_empty()) { + self.locations = locations + .iter() + .map(|v| crate::events::ToolLocation { + path: text(v, "path").to_owned(), + line: v["line"].as_u64(), + }) + .collect(); + } + if self.at_ms == 0 { + self.at_ms = later["atMs"].as_i64().unwrap_or_default(); + } + } +} + +/// The replay log contains row edits, bounded independently of retained history. +/// A reader which falls behind replaces its local rows from bounded snapshot pages. +#[derive(Default)] +pub(crate) struct Projection { + rows: Vec, + index: HashMap<(bool, u8, String), usize>, + serial: u64, + opening: Option, + bytes: usize, + trimmed: usize, + lost_output: usize, + low: u64, + high: u64, + revision: u64, + ticket: u64, + pub(crate) owner: Option, + restarted: bool, + last_page: Option<(u64, u64, bool)>, + journal: VecDeque<(u64, Value, usize)>, + journal_bytes: usize, + wire: wire::Frames, + // Pin one multi-page read so continuous output cannot force a reader back + // to the first page. A history mutation or view release discards the pin. + snapshot: Option<(u64, Vec)>, + header: Value, + header_revision: u64, + files: Value, + files_revision: u64, +} + +impl Projection { + pub(crate) fn new() -> Self { + Self { + header: json!({"activeTurn":0,"canPrompt":true}), + files: json!({"session":[],"turns":{}}), + ..Self::default() + } + } + + /// The state reader can see exit ahead of the wait cursor. The host drains + /// through this sequence to deliver every final recovery and notification. + pub(crate) fn set_exit_sequence(&mut self, seq: u64) { + self.header["exitSequence"] = seq.into(); + } + + pub(crate) fn can_retry(&self, serial: u64, text: &str, paths: &[&str]) -> bool { + self.header["canPrompt"] == true + && self + .opening + .and_then(|i| self.rows.get(i)) + .is_some_and(|r| { + r.serial == serial && r.retryable && r.text == text && r.attachments == paths + }) + } + + fn reindex(&mut self) { + self.index.clear(); + self.opening = None; + self.bytes = 0; + for (at, row) in self.rows.iter().enumerate() { + if row.kind == USER && !row.supplement { + self.opening = Some(at); + } + if let Some(key) = row.key() { + self.index.insert(key, at); + } + self.bytes += row.size(); + } + } + + fn trim(&mut self) -> usize { + let mut cut = 0; + while self.rows.len() > 1 && (self.rows.len() > MAX_ROWS || self.bytes > MAX_BYTES) { + let n = (self.rows.len() / 4).max(1); + self.rows.drain(..n); + self.reindex(); + cut += n; + } + self.trimmed += cut; + cut + } + + fn changed_files(&mut self) { + let mut all = Vec::new(); + let mut turns = std::collections::BTreeMap::>::new(); + let mut seen = HashSet::new(); + let mut turn_seen = HashSet::new(); + let mut spans = std::collections::BTreeMap::>::new(); + let mut span_seen = HashSet::new(); + let mut previous = None; + let mut span = 0; + for row in &self.rows { + if row.kind == USER { + previous = None; + continue; + } + if previous != Some(row.turn) || row.turn == 0 { + span = row.serial; + previous = Some(row.turn) + } + if row.kind != TOOL || !matches!(row.tool_kind.as_str(), "edit" | "delete" | "move") { + continue; + } + for path in row + .locations + .iter() + .map(|l| l.path.as_str()) + .filter(|p| !p.is_empty()) + { + if seen.insert(path) { + all.push(path) + } + if span_seen.insert((span, path)) { + spans.entry(span).or_default().push(path) + } + if turn_seen.insert((row.turn, path)) { + turns.entry(row.turn).or_default().push(path) + } + } + } + let next = json!({"session":all,"turns":turns,"spans":spans}); + if self.files != next { + self.files = next; + self.files_revision = self.revision; + } + } + + fn log_edit(&mut self, edit: Value) { + let size = edit.to_string().len(); + self.journal_bytes += size; + self.journal.push_back((self.revision, edit, size)); + while self.journal.len() > 512 || self.journal_bytes > MAX_BYTES { + if let Some((_, _, n)) = self.journal.pop_front() { + self.journal_bytes -= n + } + } + } + + fn append(&mut self, mut row: Row) -> usize { + self.serial += 1; + row.serial = self.serial; + row.retryable(); + let at = self.rows.len(); + if row.kind == USER && !row.supplement { + self.opening = Some(at); + } + if let Some(key) = row.key() { + self.index.insert(key, at); + } + self.bytes += row.size(); + self.rows.push(row); + at + } + + /// Applies an event under the same lock that assigns its delivery sequence. + pub(crate) fn event(&mut self, e: &Value) { + let turn = e["turn"].as_u64().unwrap_or_default(); + let kind = text(e, "kind"); + self.revision += 1; + let mut files = false; + let mut edit = Value::Null; + match kind { + "message" => { + let id = text(e, "messageID"); + let data = text(e, "text"); + if let Some(&at) = self.index.get(&(false, ASSISTANT, id.into())) { + let row = &mut self.rows[at]; + let before = row.text.len(); + if e["delta"] == true { + let add = prefix(data, MAX_TEXT - before); + row.text.push_str(add); + edit = json!({"at":at,"append":add}); + } else { + row.text = prefix(data, MAX_TEXT).into(); + edit = json!({"at":at,"row":row}); + } + self.bytes = self.bytes - before + row.text.len(); + } else { + let at = self.append(Row { + kind: if e["role"] == "thought" { + THOUGHT + } else { + ASSISTANT + }, + turn, + id: id.into(), + text: prefix(data, MAX_TEXT).into(), + ..Row::default() + }); + edit = json!({"at":at,"row":self.rows[at]}); + } + } + "toolCall" => { + let id = text(e, "toolCallID"); + let at = if let Some(&at) = self.index.get(&(false, TOOL, id.into())) { + at + } else { + self.append(Row { + kind: TOOL, + turn, + id: id.into(), + ..Row::default() + }) + }; + let row = &mut self.rows[at]; + let before = row.size(); + files = e.get("locations").is_some() || e.get("toolKind").is_some(); + row.tool_update(e, false); + self.bytes = self.bytes - before + row.size(); + edit = json!({"at":at,"row":row}); + } + "promptDispatched" | "inputResolved" + if kind == "promptDispatched" || e["accepted"] == true => + { + if let Some(content) = e.get("content").filter(|v| v.is_object()) { + let at = self.append(Row { + turn, + id: text(content, "id").into(), + text: prefix(text(content, "text"), MAX_TEXT).into(), + attachments: content["attachments"] + .as_array() + .into_iter() + .flatten() + .map(|v| text(v, "path").into()) + .collect(), + supplement: kind == "inputResolved", + ..Row::default() + }); + edit = json!({"at":at,"row":self.rows[at]}); + } + } + "promptRetracted" => { + if let Some(at) = self.rows.iter().position(|r| { + r.kind == 0 + && r.turn < RECORD_FLOOR + && r.id == text(e, "input") + && (!r.id.is_empty() || r.turn == turn) + }) { + self.rows.remove(at); + self.reindex(); + edit = json!({"at":at,"remove":true}); + } + } + "notice" | "turnEnded" => { + if kind == "notice" || !matches!(text(e, "reason"), "" | "completed") { + let notice = kind == "notice"; + let at = self.append(Row { + kind: NOTICE, + turn: if notice { + self.header["activeTurn"].as_u64().unwrap_or(0) + } else { + turn + }, + level: if notice { text(e, "level") } else { "warning" }.into(), + code: prefix( + text(e, if notice { "code" } else { "reason" }), + if notice { 128 } else { 64 }, + ) + .into(), + text: prefix(text(e, if notice { "text" } else { "message" }), MAX_TEXT) + .into(), + ..Row::default() + }); + edit = json!({"at":at,"row":self.rows[at]}); + } + } + "outputLineDropped" => self.lost_output += 1, + _ => {} + } + let cut = self.trim(); + if cut > 0 { + edit["cut"] = cut.into(); + } + if files || cut > 0 { + self.changed_files() + } + let h = &mut self.header; + match kind { + "started" => { + h["pluginID"] = e["pluginID"].clone(); + h["agentID"] = e["agentID"].clone(); + if let Some(v) = e.get("resume") { + h["agentSessionID"] = v.clone() + } + } + "session" => { + for k in ["agentSessionID", "model", "effort", "agentVersion"] { + if let Some(v) = e + .get(k) + .filter(|v| v.as_str().is_some_and(|s| !s.is_empty())) + { + h[k] = v.clone() + } + } + } + "interactionState" => { + h["interaction"] = e.clone(); + h["activeTurn"] = e["activeTurn"].clone(); + h["canPrompt"] = e["canPrompt"].clone(); + } + "turnStarted" => { + h["activeTurn"] = turn.into(); + h["canPrompt"] = false.into(); + } + "turnEnded" => { + if h["activeTurn"] == turn { + h["activeTurn"] = 0.into(); + h["canPrompt"] = h["interaction"].is_null().into(); + } + if let Some(p) = h["pending"].as_array_mut() { + p.retain(|v| v["turn"] != turn) + } + } + "permissionRequested" | "permissionDecided" => { + if !h["pending"].is_array() { + h["pending"] = json!([]) + } + let p = h["pending"].as_array_mut().expect("pending list"); + p.retain(|v| v["permission"] != e["permission"]); + if kind == "permissionRequested" { + p.push(e.clone()) + } + } + "plan" => h["plan"] = e["entries"].clone(), + "configOptions" => h["configOptions"] = e["configOptions"].clone(), + "usage" => { + let mut usage = e.clone(); + if text(e, "model").is_empty() { + usage["model"] = h["model"].clone() + } + h["usage"] = usage; + } + "rateLimits" => { + h["rateLimits"] = e["windows"].clone(); + h["ratePlan"] = e["plan"].clone(); + } + "exited" => { + h["exit"] = json!({"reason":e["reason"],"exitCode":e["exitCode"]}); + h["activeTurn"] = 0.into(); + h["pending"] = Value::Null; + h["configOptions"] = Value::Null; + h["interaction"] = Value::Null; + h["canPrompt"] = false.into(); + } + _ => { + self.log_edit(edit); + return; + } + } + self.header_revision = self.revision; + self.log_edit(edit); + } + + /// The common streaming case fits in the wait reply. Combine adjacent + /// suffixes for the same retained row, preserving the reader's base version. + pub(crate) fn inline_text(&self, after: u64) -> Option { + let count = usize::try_from(self.revision.checked_sub(after)?).ok()?; + if count == 0 || count > self.journal.len() { + return None; + } + let mut edits = self.journal.range(self.journal.len() - count..); + let first = &edits.next()?.1; + let at = first.get("at")?.as_u64()?; + let suffix = first.get("append")?.as_str()?; + if first.get("cut").is_some() || suffix.len() > 4096 { + return None; + } + let mut combined = suffix.to_owned(); + for (_, edit, _) in edits { + let next = edit.get("append")?.as_str()?; + if edit["at"] != at || edit.get("cut").is_some() || combined.len() + next.len() > 4096 { + return None; + } + combined.push_str(next); + } + Some( + json!({"revision":self.revision,"at":at,"text":combined,"room":self.rows.len()) -> Value { + let reset = after == 0 + || snapshot.is_some() + || after > self.revision + || self + .journal + .front() + .map_or(after < self.revision, |(first, _, _)| { + after.saturating_add(1) < *first + }); + let opening = self.opening.map_or(0, |at| self.rows[at].serial); + let mut out = json!({"opening":opening,"reset":reset,"ticket":self.ticket,"revision":self.revision,"dropped":self.trimmed+self.lost_output,"trimmed":self.trimmed,"outputDropped":self.lost_output,"room":self.rows.len() (*v, rows.as_slice(), offset.min(rows.len())), + None => (self.revision, self.rows.as_slice(), 0), + }; + let mut bytes = 0; + let rows_in_page: Vec<_> = rows[start..] + .iter() + .take(128) + .take_while(|r| { + if bytes > 0 && bytes + r.size() > PAGE_BYTES { + return false; + } + bytes += r.size(); + true + }) + .collect(); + let next = start + rows_in_page.len(); + out["revision"] = revision.into(); + out["start"] = start.into(); + out["rows"] = json!(rows_in_page); + if next < rows.len() { + out["nextOffset"] = next.into(); + if pinned.is_none() { + self.snapshot = Some((self.revision, self.rows.clone())); + } + } else { + self.snapshot = None; + out["more"] = (revision < self.revision).into(); + } + if start == 0 { + out["header"] = self.header.clone(); + out["files"] = self.files.clone(); + } + return out; + } else { + let mut bytes = 0; + let mut next = after; + let edits: Vec<_> = self + .journal + .iter() + .filter(|(r, _, _)| *r > after) + .take(256) + .take_while(|(_, _, n)| { + if bytes != 0 && bytes + n > PAGE_BYTES { + return false; + } + bytes += n; + true + }) + .filter_map(|(r, edit, _)| { + next = *r; + (!edit.is_null()).then_some(edit) + }) + .collect(); + out["edits"] = json!(edits); + out["more"] = (next < self.revision).into(); + out["revision"] = next.into(); + } + let delivered = out["revision"].as_u64().unwrap_or_default(); + if after < self.header_revision && delivered >= self.header_revision { + out["header"] = self.header.clone() + } + if after < self.files_revision && delivered >= self.files_revision { + out["files"] = self.files.clone() + } + out + } +} diff --git a/rust/crates/agent-runtime/src/projection/command.rs b/rust/crates/agent-runtime/src/projection/command.rs new file mode 100644 index 00000000..c32c02cb --- /dev/null +++ b/rust/crates/agent-runtime/src/projection/command.rs @@ -0,0 +1,196 @@ +//! Application-only operations for an in-memory view. No operation reads files or starts a CLI. + +use super::{Projection, Value}; +use crate::live::refusal; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::json; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +#[derive(Deserialize)] +#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)] +pub(crate) enum Request { + Open { + agent: Option, + }, + Release { + session: String, + }, + Read { + session: String, + #[serde(default)] + after: u64, + #[serde(default)] + offset: usize, + snapshot: Option, + }, + Chunk { + session: String, + frame: u64, + offset: usize, + }, + Page { + session: String, + ticket: u64, + messages: Vec, + start: u64, + end: u64, + before: bool, + #[serde(default)] + replace: bool, + }, + ClearHistory { + session: String, + ticket: u64, + }, +} + +/// Live IDs are allocated by the process owner. Detached history views have a separate namespace. +#[derive(Default)] +pub(crate) struct Views { + sessions: Mutex>>>, + next: AtomicU64, +} + +impl Views { + pub(crate) fn open_live(&self, session: &str, owner: String) { + self.sessions + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert( + session.into(), + Arc::new(Mutex::new(Projection { + owner: Some(owner), + ..Projection::new() + })), + ); + } + + pub(crate) fn get(&self, session: &str) -> Option>> { + self.sessions + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(session) + .cloned() + } + + pub(crate) fn release(&self, session: &str) { + self.sessions + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(session); + } + + /// Drop cached historical rows after the catalog has revoked their source. + pub(crate) fn purge_unreadable(&self, catalog: &crate::catalog::Catalog) { + let sessions: Vec<_> = self + .sessions + .lock() + .unwrap_or_else(PoisonError::into_inner) + .values() + .cloned() + .collect(); + for view in sessions { + let mut p = view.lock().unwrap_or_else(PoisonError::into_inner); + if p.high != 0 + && p.owner + .as_ref() + .is_some_and(|key| !catalog.find_key(key).is_some_and(|a| a.may_read_sessions)) + { + p.clear_history(); + } + } + } + + pub(crate) fn execute( + &self, + catalog: &crate::catalog::Catalog, + request: Request, + ) -> Result { + let session = match &request { + Request::Open { agent } => { + let id = format!("history-{}", self.next.fetch_add(1, Ordering::Relaxed) + 1); + let mut p = Projection { + owner: agent.clone(), + ..Projection::new() + }; + p.header = json!({"canPrompt":false,"exit":{"reason":"recorded"}}); + self.sessions + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(id.clone(), Arc::new(Mutex::new(p))); + return Ok(json!({"session":id})); + } + Request::Release { session } => { + self.release(session); + return Ok(json!({})); + } + Request::Read { session, .. } + | Request::Chunk { session, .. } + | Request::Page { session, .. } + | Request::ClearHistory { session, .. } => session, + }; + let viewer = session.starts_with("history-"); + let view = self.get(session).ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agents.unknownSession", + "The transcript was released.", + ) + })?; + let mut p = view.lock().unwrap_or_else(PoisonError::into_inner); + match request { + Request::Read { + after, + offset, + snapshot, + .. + } => { + let page = p.read(after, offset, snapshot); + Ok(p.wire.encode(page)) + } + Request::Chunk { frame, offset, .. } => p.wire.chunk(frame, offset), + Request::Page { + ticket, + messages, + start, + end, + before, + replace, + .. + } => { + if p.owner + .as_ref() + .is_some_and(|key| !catalog.find_key(key).is_some_and(|a| a.may_read_sessions)) + { + return Err(refusal( + ErrorCode::PermissionDenied, + "agentSessions.readNotGranted", + "Session history access was withdrawn.", + )); + } + if end <= start { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidPage", + "The loaded byte range is empty.", + )); + } + crate::records::validate_projection_page(&messages)?; + p.page(ticket, (start, end, before), &messages, viewer, replace); + Ok(json!({"restarted":p.restarted,"ticket":p.ticket})) + } + Request::ClearHistory { ticket, .. } => { + if ticket > p.ticket { + p.clear_history(); + p.ticket = ticket; + p.restarted = false; + } + Ok(json!({})) + } + _ => unreachable!("open and release return above"), + } + } +} diff --git a/rust/crates/agent-runtime/src/projection/history.rs b/rust/crates/agent-runtime/src/projection/history.rs new file mode 100644 index 00000000..7a96be87 --- /dev/null +++ b/rust/crates/agent-runtime/src/projection/history.rs @@ -0,0 +1,208 @@ +//! Historical pages share the live transcript's row IDs and retention budget. +//! Pages are supplied only after the existing record reader checks the source generation. + +use super::{ + prefix, text, Projection, Row, Value, ASSISTANT, MAX_BYTES, MAX_ROWS, MAX_TEXT, RECORD_BASE, + RECORD_FLOOR, THOUGHT, TOOL, USER, +}; + +impl Projection { + /// A retried read of the same byte range can return after its first result was lost. + pub(crate) fn page( + &mut self, + ticket: u64, + range: (u64, u64, bool), + messages: &[Value], + viewer: bool, + replace: bool, + ) -> bool { + if ticket > self.ticket { + if replace || self.last_page != Some(range) { + self.restarted = self.history(messages, range.2, viewer, replace); + self.last_page = Some(range); + } + self.ticket = ticket; + } + self.restarted + } + + /// Folds a previously authorized page in file order. A prepend may join a tool + /// call with a later result already visible at the start of the next page. + pub(crate) fn history( + &mut self, + messages: &[Value], + before: bool, + viewer: bool, + replace: bool, + ) -> bool { + let restart = + viewer && (self.rows.len() >= MAX_ROWS * 3 / 4 || self.bytes >= MAX_BYTES * 3 / 4); + if restart { + self.trimmed = 0; + self.lost_output = 0; + } + if restart || replace { + self.clear_history() + } + if self.high == 0 { + self.high = RECORD_BASE; + self.low = RECORD_BASE + } + // A mirrored prompt spans both pages. Keep its original turn so that + // replies already visible after it stay in the same group. + let mut fresh_ids = std::collections::HashSet::new(); + let users = messages + .iter() + .filter(|m| { + if m["role"] != "user" { + return false; + } + let id = text(m, "id"); + id.is_empty() + || (!self.index.contains_key(&(true, USER, id.into())) && fresh_ids.insert(id)) + }) + .count() as u64; + let mut next_turn = if before { self.low - users } else { self.high }; + let mut turn = next_turn; + if before { + self.low = next_turn + } else { + self.high += users + } + let mut page = Projection { + serial: self.serial, + ..Projection::default() + }; + for m in messages { + let role = text(m, "role"); + + let kind = match role { + "user" => USER, + "assistant" => ASSISTANT, + "thought" => THOUGHT, + "tool" => TOOL, + _ => continue, + }; + let id = if kind == TOOL { + text(m, "toolCallID") + } else { + text(m, "id") + }; + if kind == USER { + let key = (true, USER, id.to_owned()); + turn = page + .index + .get(&key) + .map(|&i| page.rows[i].turn) + .or_else(|| self.index.get(&key).map(|&i| self.rows[i].turn)) + .unwrap_or_else(|| { + next_turn += 1; + next_turn + }); + } + let at_ms = m["atMs"].as_i64().unwrap_or_default(); + let mut row = Row { + turn, + kind, + at_ms, + id: id.into(), + ..Row::default() + }; + if kind == TOOL { + row.tool_update(m, true); + if row.title.is_empty() { + row.title = prefix(text(m, "toolName"), 1024).into() + } + } else { + row.text = prefix(text(m, "text"), MAX_TEXT).into() + } + let key = row.key(); + if let Some(&at) = key.as_ref().and_then(|k| page.index.get(k)) { + if kind == TOOL { + page.rows[at].tool_update(m, true) + } + continue; + } + if let Some(&at) = key.as_ref().and_then(|k| self.index.get(k)) { + let later = &mut self.rows[at]; + if later.turn < RECORD_FLOOR { + continue; + } + if !before { + if kind == TOOL { + later.tool_update(m, true) + } + continue; + } + if kind == TOOL { + if !later.status.is_empty() { + row.status.clone_from(&later.status) + } + if !later.title.is_empty() { + row.title.clone_from(&later.title) + } + if !later.tool_kind.is_empty() { + row.tool_kind.clone_from(&later.tool_kind) + } + if !later.command.is_empty() { + row.command.clone_from(&later.command) + } + if !later.output.is_empty() { + row.output.clone_from(&later.output) + } + if !later.locations.is_empty() { + row.locations.clone_from(&later.locations) + } + if row.at_ms == 0 { + row.at_ms = later.at_ms + } + } + let serial = later.serial; + later.serial = 0; + let pos = page.append(row); + page.rows[pos].serial = serial; + } else { + page.append(row); + } + } + self.serial = page.serial; + for row in &mut page.rows { + if row.kind == TOOL && row.status.is_empty() { + row.status = "completed".into() + } + } + self.rows.retain(|r| r.serial != 0); + if before { + page.rows.append(&mut self.rows); + self.rows = page.rows + } else { + let live = self + .rows + .iter() + .position(|r| r.turn < RECORD_FLOOR) + .unwrap_or(self.rows.len()); + self.rows.splice(live..live, page.rows); + } + self.reset_readers(); + restart + } + + pub(crate) fn clear_history(&mut self) { + self.rows.retain(|r| r.turn < RECORD_FLOOR); + self.last_page = None; + self.low = 0; + self.high = 0; + self.reset_readers(); + } + + fn reset_readers(&mut self) { + self.wire.clear(); + self.snapshot = None; + self.reindex(); + self.trim(); + self.revision += 1; + self.journal.clear(); + self.journal_bytes = 0; + self.changed_files(); + } +} diff --git a/rust/crates/agent-runtime/src/projection/tests.rs b/rust/crates/agent-runtime/src/projection/tests.rs new file mode 100644 index 00000000..c4ee6cb1 --- /dev/null +++ b/rust/crates/agent-runtime/src/projection/tests.rs @@ -0,0 +1,151 @@ +//! Mixed live and recorded sessions exercise the same input as the desktop boundary test. +use super::*; + +#[test] +fn mixed_history_and_live_rows_share_one_budget() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/agents/session-projection-v1.json" + )) + .unwrap(); + let mut p = Projection::new(); + for event in fixture["events"].as_array().unwrap() { + p.event(event) + } + let live = p.rows[0].serial; + for page in ["later", "earlier"] { + p.history(fixture[page].as_array().unwrap(), true, false, false); + } + assert_eq!( + json!(p.rows.iter().map(|r| &r.text).collect::>()), + fixture["texts"] + ); + assert_eq!(p.files["session"], fixture["files"]); + assert_eq!(p.rows[1].output, fixture["output"]); + assert_eq!(p.rows[3].serial, live); + // When the file is loaded first, the desktop consumes the same live suffix + // as sparse row edits, without retransmitting any historical rows. + let mut resumed = Projection::new(); + for page in ["later", "earlier"] { + resumed.history(fixture[page].as_array().unwrap(), true, false, false); + } + let before = resumed.revision; + for event in fixture["events"].as_array().unwrap() { + resumed.event(event) + } + let update = resumed.read(before, 0, None); + let edits = update["edits"].as_array().unwrap(); + assert_eq!(edits.len(), 2); + for (expected, actual) in fixture["liveEdits"].as_array().unwrap().iter().zip(edits) { + assert_eq!(expected["at"], actual["at"]); + if let Some(fields) = expected["row"].as_object() { + for (key, value) in fields { + assert_eq!(&actual["row"][key], value, "{key}"); + } + } else { + assert_eq!(actual, expected); + } + } + p.clear_history(); + assert_eq!(p.rows.len(), 1); + assert_eq!(p.rows[0].serial, live); +} + +#[test] +fn append_returns_only_the_suffix_and_evicted_cursor_reads_a_window() { + let mut p = Projection::new(); + p.event(&json!({"kind":"message","messageID":"m","text":"x".repeat(MAX_TEXT-4)})); + let old = p.revision; + p.event(&json!({"kind":"message","messageID":"m","text":"é中","delta":true})); + assert_eq!(p.inline_text(old).unwrap()["text"], "é"); + let change = p.read(old, 0, None); + assert_eq!(change["edits"][0]["append"], "é"); + assert!(change.to_string().len() < 256); + for _ in 0..=MAX_ROWS { + p.event(&json!({"kind":"notice","text":"test"})) + } + let snapshot = p.read(old, 0, None); + assert_eq!(snapshot["reset"], true); + assert!(snapshot["dropped"].as_u64().unwrap() > 0); + assert_eq!(snapshot["nextOffset"], 128); +} + +#[test] +fn mixed_rows_trim_at_the_shared_byte_limit_and_keep_file_order() { + let mut p = Projection::new(); + let body = "x".repeat(MAX_TEXT); + for turn in 1..=10 { + p.event(&json!({"kind":"message","turn":turn,"text":body,"messageID":turn.to_string()})); + } + let live = p.rows.last().unwrap().serial; + let mut history = vec![json!({"role":"assistant","id":"old","text":"before"})]; + for id in 1..=8 { + history.push(json!({"role":"assistant","id":id.to_string(),"text":body})); + } + p.history(&history, true, false, false); + assert!(p.trimmed > 0 && p.bytes <= MAX_BYTES); + assert_eq!(p.rows.last().unwrap().serial, live); + let tool = |id: &str, kind: &str, path: &str| json!({"kind":"toolCall","turn":10,"toolCallID":id,"toolKind":kind,"locations":[{"path":path}]}); + p.event(&tool("read", "read", "ignored")); + p.event(&tool("one", "edit", "a")); + p.event(&tool("two", "move", "b")); + p.event(&tool("three", "delete", "a")); + assert_eq!(p.files["session"], json!(["a", "b"])); + p.event(&tool("one", "edit", "c")); + assert_eq!(p.files["session"], json!(["c", "b", "a"])); +} + +#[test] +fn snapshot_continues_at_a_stable_version_while_output_arrives() { + let mut p = Projection::new(); + for _ in 0..180 { + p.event(&json!({"kind":"notice","text":"row"})) + } + let first = p.read(0, 0, None); + let version = first["revision"].as_u64().unwrap(); + p.event(&json!({"kind":"notice","text":"next"})); + let last = p.read(0, 128, Some(version)); + assert_eq!(last["start"], 128); + assert_eq!(last["revision"], version); + assert_eq!(last["rows"].as_array().unwrap().len(), 52); + assert_eq!(last["more"], true); + assert_eq!(p.read(version, 0, None)["edits"][0]["row"]["text"], "next"); +} + +#[test] +fn oversized_unicode_rows_cross_the_boundary_in_bounded_frames() { + let mut frames = wire::Frames::default(); + let original = json!({"rows":[{"text":"中".repeat(PAGE_BYTES/2)}]}); + let mut part = frames.encode(original.clone()); + let mut joined = String::new(); + loop { + assert!(part.to_string().len() < PAGE_BYTES); + joined.push_str(part["chunk"].as_str().unwrap()); + let next = part["nextByte"].as_u64().unwrap(); + if next == 0 { + break; + } + part = frames + .chunk(part["frame"].as_u64().unwrap(), next as usize) + .unwrap(); + } + assert_eq!(serde_json::from_str::(&joined).unwrap(), original); + assert!(frames.chunk(part["frame"].as_u64().unwrap(), 0).is_err()); +} + +#[test] +fn overlapping_user_rows_keep_the_turn_of_replies_already_visible() { + let mut p = Projection::new(); + let user = |id: &str| json!({"role":"user","id":id,"text":id}); + p.history( + &[user("same"), json!({"role":"assistant","text":"reply"})], + true, + false, + false, + ); + let serial = p.rows[0].serial; + p.history(&[user("earlier"), user("same")], true, false, false); + assert_eq!(p.rows.len(), 3); + assert_eq!(p.rows[1].serial, serial); + assert_eq!(p.rows[1].turn, p.rows[2].turn); + assert_ne!(p.rows[0].turn, p.rows[1].turn); +} diff --git a/rust/crates/agent-runtime/src/projection/wire.rs b/rust/crates/agent-runtime/src/projection/wire.rs new file mode 100644 index 00000000..9ef4f7b0 --- /dev/null +++ b/rust/crates/agent-runtime/src/projection/wire.rs @@ -0,0 +1,98 @@ +//! Split unusually large rows, file lists or interaction headers at the application boundary. +//! Normal deltas take the fast path without allocating another serialized copy. +use super::{Value, PAGE_BYTES}; +use crate::live::refusal; +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::json; +use std::collections::VecDeque; + +// Each source byte may expand to six bytes inside a JSON string. Leave room for the envelope. +const CHUNK_BYTES: usize = (PAGE_BYTES - 1024) / 6; + +#[derive(Default)] +pub(super) struct Frames { + next: u64, + // One event read can overlap a historical page read in the same window. + pending: VecDeque<(u64, String)>, +} + +fn fits(v: &Value, budget: &mut usize) -> bool { + let cost = match v { + Value::String(s) => s.len().saturating_mul(6) + 3, + Value::Array(items) => { + if !items.iter().all(|v| fits(v, budget)) { + return false; + } + 3 + } + Value::Object(fields) => { + for (key, val) in fields { + let key_bytes = key.len() * 6 + 4; + if *budget < key_bytes { + return false; + } + *budget -= key_bytes; + if !fits(val, budget) { + return false; + } + } + 3 + } + _ => 32, + }; + if *budget < cost { + return false; + } + *budget -= cost; + true +} + +impl Frames { + pub(super) fn clear(&mut self) { + self.pending.clear() + } + + pub(super) fn encode(&mut self, page: Value) -> Value { + let mut budget = PAGE_BYTES - 512; + if fits(&page, &mut budget) { + return page; + } + let raw = page.to_string(); + if raw.len() <= PAGE_BYTES - 512 { + return page; + } + self.next += 1; + if self.pending.len() == 2 { + self.pending.pop_front(); + } + self.pending.push_back((self.next, raw)); + self.chunk(self.next, 0) + .expect("new frame starts at byte zero") + } + + pub(super) fn chunk(&mut self, id: u64, offset: usize) -> Result { + let invalid = || { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidPage", + "The projection frame or byte offset is no longer available.", + ) + }; + let at = self + .pending + .iter() + .position(|(key, _)| *key == id) + .ok_or_else(invalid)?; + let raw = &self.pending[at].1; + if offset >= raw.len() || !raw.is_char_boundary(offset) { + return Err(invalid()); + } + let end = raw.floor_char_boundary((offset + CHUNK_BYTES).min(raw.len())); + let more = end < raw.len(); + let part = json!({"frame":id,"chunk":&raw[offset..end],"nextByte":if more{end}else{0}}); + if !more { + self.pending.remove(at); + } + Ok(part) + } +} diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index a773780b..896c5cca 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -654,6 +654,12 @@ impl Records { /// Core owns range growth and the output budget; hosts retain only a few pages. /// The plugin still receives the existing, format-neutral `read` request. pub fn page(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct PageTarget { + session: String, + ticket: u64, + } #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct PageRequest { @@ -664,6 +670,7 @@ impl Records { generation: i64, cursor: u64, direction: String, + projection: Option, } let request: PageRequest = crate::decode(payload)?; let invalid = || { @@ -869,9 +876,36 @@ impl Records { } } let messages: Vec = collected.into_iter().flatten().collect(); - Ok( - json!({ "changed": false, "tooLong": false, "start": start + from as u64, "end": start + to as u64, "messages": messages }), - ) + let low = start + from as u64; + let high = start + to as u64; + if let Some(target) = request.projection { + let view = runtime + .live + .queue + .views + .get(&target.session) + .ok_or_else(invalid)?; + let mut view = view + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if view.owner.as_deref() != Some(request.agent.as_str()) { + return Err(invalid()); + } + // The catalog may have changed while the backend read the file. + readable_agent(runtime, plugin_id, agent_id)?; + let messages = messages.into_iter().map(|m| json!(m)).collect::>(); + let restart = view.page( + target.ticket, + (low, high, before), + &messages, + target.session.starts_with("history-"), + false, + ); + return Ok( + json!({"changed":false,"tooLong":false,"start":low,"end":high,"restarted":restart}), + ); + } + Ok(json!({"changed":false,"tooLong":false,"start":low,"end":high,"messages":messages})) } /// `agentSessions.stats`: usage of the readable agents for the host. @@ -1757,6 +1791,12 @@ fn decode_messages(item: Value, tool_details: bool) -> Result, } } +/// Pages submitted by a host use the same normalized record shape and per-item +/// limits as pages returned by the authorized record reader. +pub(crate) fn validate_projection_page(messages: &[Value]) -> Result<(), CoreError> { + decode_messages(json!({"messages":messages}), true).map(|_| ()) +} + /// Where the files of one source go to be scanned. struct Route { root: PathBuf, diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index d75e1558..a025ee04 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -785,6 +785,95 @@ fn start_refuses_before_anything_runs() { assert!(harness.link.notices_of(AGENTS_DID_START).is_empty()); } +#[test] +fn compact_wait_scopes_events_to_the_requesting_window() { + let h = Harness::new("scoped-wait", ALL_GRANTS); + for id in ["shown", "other"] { + h.runtime + .live + .queue + .push(id, json!({"kind":"notice","text":id})); + } + let reply = h.run( + "agents.waitEvents", + json!({"compact":true,"views":{"shown":0}}), + ); + assert_eq!(reply["next"], 2); + assert_eq!(reply["events"].as_array().unwrap().len(), 1); + assert_eq!(reply["events"][0]["session"], "shown"); + assert!( + h.run("agents.waitEvents", json!({"compact":true,"views":{}}))["events"] + .as_array() + .unwrap() + .is_empty() + ); +} + +#[test] +fn projected_session_reads_accepted_rows_before_replay_and_validates_retries() { + let mut h = Harness::new("projection", ALL_GRANTS); + let mut start = h.start_payload(); + start["projection"] = true.into(); + let session = h.run("agents.start", start)["session"] + .as_str() + .unwrap() + .to_owned(); + let read = |after| json!({"op":"read","session":session,"after":after}); + h.run("agents.prompt", json!({"session":session,"text":"Inspect"})); + h.report(&session,json!([ + {"kind":"message","role":"assistant","messageID":"r","turn":1,"text":"A"}, + {"kind":"permissionRequested","turn":1,"permission":"p","title":"Read?","options":[{"id":"yes","label":"Yes","optionKind":"allowOnce"}]} + ])).unwrap(); + let initial = h.run("agents.projection", read(0)); + let serial = &initial["rows"][0]["serial"]; + assert_eq!(initial["rows"][0]["text"], "Inspect"); + assert_eq!(initial["rows"][1]["text"], "A"); + assert_eq!(initial["header"]["pending"][0]["permission"], "p"); + h.report( + &session, + json!([ + {"kind":"message","role":"assistant","messageID":"r","turn":1,"text":"B","delta":true}, + {"kind":"turnEnded","turn":1,"reason":"completed"} + ]), + ) + .unwrap(); + let next = h.run( + "agents.projection", + read(initial["revision"].as_u64().unwrap()), + ); + assert_eq!(next["edits"][0]["append"], "B"); + assert_eq!(next["header"]["pending"], json!([])); + assert_eq!(next["header"]["canPrompt"], true); + assert_eq!( + h.refused( + "agents.prompt", + json!({"session":session,"retrySerial":serial,"text":"Changed"}) + ), + "agents.invalidPrompt" + ); + assert_eq!( + h.run( + "agents.prompt", + json!({"session":session,"retrySerial":serial,"text":"Inspect"}) + )["turn"], + 2 + ); + h.run("agents.close", json!({"session":session})); + h.next_event(&session, "exited"); + let ended = h.run("agents.projection", read(0)); + assert!(ended["header"]["exitSequence"].as_u64().unwrap() > 0); + assert_eq!(ended["header"]["canPrompt"], false); + assert_eq!(ended["header"]["pending"], Value::Null); + h.run( + "agents.projection", + json!({"op":"release","session":session}), + ); + assert_eq!( + h.refused("agents.projection", read(0)), + "agents.unknownSession" + ); +} + #[test] fn native_session_relays_the_cli_and_checks_reports_against_turns() { let mut harness = Harness::new("native", ALL_GRANTS); @@ -2632,6 +2721,36 @@ fn exiting_before_steering_acknowledgement_returns_the_original_input() { assert_eq!(harness.next_event(&session, "exited")["exitCode"], 1); } +#[test] +fn projected_disk_pages_survive_retry_and_are_purged_when_access_is_revoked() { + let h = Harness::new("project-record", ALL_GRANTS); + let file = write_session_file(&h, 1_795_824_000_000); + h.run( + "agentSessions.sync", + json!({"pluginID":PLUGIN,"agentID":AGENT}), + ); + let view = + h.run("agents.projection", json!({"op":"open","agent":AGENT_KEY}))["session"].clone(); + let query = |ticket| json!({"agent":AGENT_KEY,"path":path_text(&file),"size":fs::metadata(&file).unwrap().len(),"generation":generation_of(&h),"direction":"after","cursor":0,"projection":{"session":view,"ticket":ticket}}); + let read = || h.run("agents.projection", json!({"op":"read","session":view})); + let req = query(1); + assert!(h + .run("agentSessions.page", req.clone()) + .get("messages") + .is_none()); + let rows = read()["rows"].clone(); + assert!(!rows.as_array().unwrap().is_empty()); + h.run("agentSessions.page", query(2)); + assert_eq!(read()["rows"], rows); + h.grant(&[]); + assert_eq!(read()["rows"], json!([])); + assert_eq!( + h.refused("agentSessions.page", req), + "agentSessions.readNotGranted" + ); + h.run("agents.projection", json!({"op":"release","session":view})); +} + #[test] fn records_pages_walk_both_directions_without_cutting_or_dropping_lines() { let harness = Harness::new("record-pages", ALL_GRANTS); diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index f2a3d780..91c72685 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -246,6 +246,8 @@ pub enum AgentsCommand { Close, /// Waits, bounded, for session events after a sequence (`agents.waitEvents`). WaitEvents, + /// Reads or releases a bounded Agent conversation view. + Projection, /// Opens the session record cache (`agentSessions.configure`). RecordsConfigure, /// Reads one agent's changed session files through its plugin (`agentSessions.sync`). @@ -294,6 +296,7 @@ impl AgentsCommand { Self::SetConfigOption => "agents.setConfigOption", Self::Close => "agents.close", Self::WaitEvents => "agents.waitEvents", + Self::Projection => "agents.projection", Self::RecordsConfigure => "agentSessions.configure", Self::RecordsSync => "agentSessions.sync", Self::RecordsForget => "agentSessions.forget", @@ -1303,6 +1306,7 @@ impl CoreCommand { "agents.setConfigOption" => Some(Self::Agents(AgentsCommand::SetConfigOption)), "agents.close" => Some(Self::Agents(AgentsCommand::Close)), "agents.waitEvents" => Some(Self::Agents(AgentsCommand::WaitEvents)), + "agents.projection" => Some(Self::Agents(AgentsCommand::Projection)), "agentSessions.configure" => Some(Self::Agents(AgentsCommand::RecordsConfigure)), "agentSessions.sync" => Some(Self::Agents(AgentsCommand::RecordsSync)), "agentSessions.forget" => Some(Self::Agents(AgentsCommand::RecordsForget)), diff --git a/rust/fixtures/agents/session-projection-v1.json b/rust/fixtures/agents/session-projection-v1.json new file mode 100644 index 00000000..97dce895 --- /dev/null +++ b/rust/fixtures/agents/session-projection-v1.json @@ -0,0 +1,22 @@ +{ + "earlier": [ + {"role":"user","text":"Fix it"}, + {"role":"tool","toolCallID":"c1","toolKind":"edit","title":"Edit","locations":[{"path":"src/main.rs"}]} + ], + "later": [ + {"role":"tool","toolCallID":"c1","status":"completed","text":"ok"}, + {"role":"assistant","id":"old","text":"Fixed"} + ], + "events": [ + {"kind":"turnStarted","turn":1}, + {"kind":"message","messageID":"live","role":"assistant","turn":1,"text":"An"}, + {"kind":"message","messageID":"live","role":"assistant","turn":1,"delta":true,"text":"swer"} + ], + "texts":["Fix it","","Fixed","Answer"], + "output":"ok", + "files":["src/main.rs"], + "liveEdits": [ + {"at":3,"row":{"kind":1,"serial":5,"turn":1,"id":"live","text":"An"}}, + {"at":3,"append":"swer"} + ] +} From 67e9ef3ef216acf3bbc727a790961d7071f547cb Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 10:41:30 +0800 Subject: [PATCH 2/6] fix(agents): retain tool diffs and resume loaded session views Resolve changed paths against the session directory, account for diff text in the row budget and keep retained row identities across CLI restarts. --- rust/contracts/rust-core-api.md | 11 +- rust/crates/agent-runtime/src/live.rs | 8 ++ rust/crates/agent-runtime/src/projection.rs | 124 ++++++++++++++++-- .../agent-runtime/src/projection/command.rs | 42 ++++-- .../agent-runtime/src/projection/history.rs | 3 + .../agent-runtime/src/projection/tests.rs | 47 +++++++ 6 files changed, 208 insertions(+), 27 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 9b51a28c..85f8c882 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -9213,13 +9213,22 @@ row position, appended text and budget status in the same response. | Operation | Request | Result | | --- | --- | --- | -| `open` | No arguments | An independent history viewer ID in `session`. Supply its catalog `agent` key to bind cached pages to its read grant. | +| `open` | `agent?, cwd?` | An independent history viewer ID in `session`. Supply its catalog `agent` key to bind cached pages to its read grant. | | `page` | `session, ticket, start, end, messages, before, replace?` | Applies one page from the existing record reader. An increasing ticket orders page changes. Replaying the same ticket is idempotent. `restarted` marks a full history viewer that reopened at this page. | | `chunk` | `session, frame, offset` | Reads the next UTF-8 fragment of an oversized response. | | `clearHistory` | `session, ticket` | Removes recorded rows, preserving live rows. | | `read` | `session, after?, offset?, snapshot?` | A bounded update with `revision`, history `ticket`, `trimmed` rows, `outputDropped` upstream lines, their display total `dropped`, and `room` for another record page. | | `release` | `session` | Releases rows, buffered updates and snapshot resources. Releasing twice is safe. | +A detached view can supply its session directory as `cwd` on `open`. Changed +files resolve against that directory, or against the live CLI working directory. +A tool row retains its latest supplied `diff`, including a missing versus empty +`oldText`. The per-text and aggregate retention limits also cover these diffs. +When `agents.start` resumes a session with `projection: true`, it can pass +`previousView` to keep the same agent's retained rows and their serials. +Earlier live turns then occupy historical turn numbers. The old view remains +owned by the caller until the new process starts successfully. + On a first read or an expired cursor, `reset` is true. Replace rows starting at `start`. Request `nextOffset` with the returned revision in `snapshot` until the snapshot ends. In ordinary reads, apply `edits` in order. Each edit diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index f0658a4e..d29b0a03 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -456,6 +456,8 @@ struct StartRequest { resume: Option, #[serde(default)] projection: bool, + /// View whose retained rows precede this resumed process. + previous_view: Option, /// Whether the user trusts the workspace. #[serde(default)] workspace_trusted: bool, @@ -653,6 +655,12 @@ fn start_checked(runtime: &Arc, request: StartRequest) -> Result &str { &s[s.ceil_char_boundary(s.len().saturating_sub(MAX_OUTPUT))..] } +/// Resolve a reported change lexically; a deleted or moved file need not exist on disk. +fn changed_path(cwd: &std::path::Path, raw: &str) -> String { + use std::path::{Component, PathBuf}; + if cwd.as_os_str().is_empty() { + return raw.into(); + } + let joined = cwd.join(raw); + let mut clean = PathBuf::new(); + for component in joined.components() { + match component { + Component::CurDir => {} + Component::ParentDir if clean.file_name().is_some() => { + clean.pop(); + } + Component::ParentDir if clean.has_root() => {} + part => clean.push(part.as_os_str()), + } + } + if clean.as_os_str().is_empty() { + ".".into() + } else { + clean.to_string_lossy().into_owned() + } +} + /// One retained row. Serial is stable across replacements, trims and historical prepends. #[derive(Clone, Default, Serialize)] #[serde(rename_all = "camelCase")] @@ -65,6 +90,8 @@ struct Row { locations: Vec, #[serde(skip_serializing_if = "String::is_empty")] output: String, + #[serde(skip_serializing_if = "Option::is_none")] + diff: Option, #[serde(skip_serializing_if = "String::is_empty")] level: String, #[serde(skip_serializing_if = "String::is_empty")] @@ -80,6 +107,11 @@ impl Row { + self.title.len() + self.command.len() + self.output.len() + + self.diff.as_ref().map_or(0, |d| { + 64 + d.path.len() + + d.new_text.len() + + d.old_text.as_deref().unwrap_or_default().len() + }) + self.attachments.iter().map(|s| s.len() + 16).sum::() } @@ -124,6 +156,26 @@ impl Row { target.push_str(value); } } + if let Some(diff) = later["diff"].as_object() { + self.diff = Some(crate::events::ToolDiff { + path: prefix( + diff.get("path").and_then(Value::as_str).unwrap_or_default(), + 1024, + ) + .into(), + old_text: diff + .get("oldText") + .and_then(Value::as_str) + .map(|s| prefix(s, MAX_TEXT).into()), + new_text: prefix( + diff.get("newText") + .and_then(Value::as_str) + .unwrap_or_default(), + MAX_TEXT, + ) + .into(), + }); + } if let Some(locations) = later["locations"].as_array().filter(|a| !a.is_empty()) { self.locations = locations .iter() @@ -143,6 +195,7 @@ impl Row { /// A reader which falls behind replaces its local rows from bounded snapshot pages. #[derive(Default)] pub(crate) struct Projection { + cwd: std::path::PathBuf, rows: Vec, index: HashMap<(bool, u8, String), usize>, serial: u64, @@ -178,6 +231,45 @@ impl Projection { } } + /// A restarted CLI starts numbering turns at one again. Keep the source window's + /// row identities and page boundaries, and give its finished turns historical IDs. + pub(crate) fn resume_rows(&mut self, source: &Self, include_history: bool) { + self.rows.extend( + source + .rows + .iter() + .filter(|row| include_history || row.turn < RECORD_FLOOR) + .cloned(), + ); + self.serial = source.serial; + self.low = if source.low == 0 { + RECORD_BASE + } else { + source.low + }; + self.high = source.high.max(RECORD_BASE); + let mut turns = HashMap::new(); + for row in &mut self.rows { + if row.turn < RECORD_FLOOR && row.turn != 0 { + row.turn = *turns.entry(row.turn).or_insert_with(|| { + self.high += 1; + self.high + }); + } + row.retryable = false; + } + self.trimmed = source.trimmed; + self.ticket = source.ticket; + self.last_page = if include_history { + source.last_page + } else { + None + }; + self.reindex(); + self.opening = None; + self.changed_files(); + } + /// The state reader can see exit ahead of the wait cursor. The host drains /// through this sequence to deliver every final recovery and notification. pub(crate) fn set_exit_sequence(&mut self, seq: u64) { @@ -223,10 +315,10 @@ impl Projection { fn changed_files(&mut self) { let mut all = Vec::new(); - let mut turns = std::collections::BTreeMap::>::new(); + let mut turns = std::collections::BTreeMap::>::new(); let mut seen = HashSet::new(); let mut turn_seen = HashSet::new(); - let mut spans = std::collections::BTreeMap::>::new(); + let mut spans = std::collections::BTreeMap::>::new(); let mut span_seen = HashSet::new(); let mut previous = None; let mut span = 0; @@ -239,23 +331,25 @@ impl Projection { span = row.serial; previous = Some(row.turn) } - if row.kind != TOOL || !matches!(row.tool_kind.as_str(), "edit" | "delete" | "move") { + if row.kind != TOOL { continue; } - for path in row + let locations = row .locations .iter() - .map(|l| l.path.as_str()) - .filter(|p| !p.is_empty()) - { - if seen.insert(path) { - all.push(path) + .filter(|_| matches!(row.tool_kind.as_str(), "edit" | "delete" | "move")) + .map(|l| l.path.as_str()); + let paths = row.diff.iter().map(|d| d.path.as_str()).chain(locations); + for raw in paths.filter(|p| !p.is_empty()) { + let path = changed_path(&self.cwd, raw); + if seen.insert(path.clone()) { + all.push(path.clone()); } - if span_seen.insert((span, path)) { - spans.entry(span).or_default().push(path) + if span_seen.insert((span, path.clone())) { + spans.entry(span).or_default().push(path.clone()); } - if turn_seen.insert((row.turn, path)) { - turns.entry(row.turn).or_default().push(path) + if turn_seen.insert((row.turn, path.clone())) { + turns.entry(row.turn).or_default().push(path); } } } @@ -345,7 +439,9 @@ impl Projection { }; let row = &mut self.rows[at]; let before = row.size(); - files = e.get("locations").is_some() || e.get("toolKind").is_some(); + files = e.get("locations").is_some() + || e.get("toolKind").is_some() + || e.get("diff").is_some(); row.tool_update(e, false); self.bytes = self.bytes - before + row.size(); edit = json!({"at":at,"row":row}); diff --git a/rust/crates/agent-runtime/src/projection/command.rs b/rust/crates/agent-runtime/src/projection/command.rs index c32c02cb..84b9ac93 100644 --- a/rust/crates/agent-runtime/src/projection/command.rs +++ b/rust/crates/agent-runtime/src/projection/command.rs @@ -14,6 +14,7 @@ use std::sync::{Arc, Mutex, PoisonError}; pub(crate) enum Request { Open { agent: Option, + cwd: Option, }, Release { session: String, @@ -55,17 +56,33 @@ pub(crate) struct Views { } impl Views { - pub(crate) fn open_live(&self, session: &str, owner: String) { - self.sessions - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert( - session.into(), - Arc::new(Mutex::new(Projection { - owner: Some(owner), - ..Projection::new() - })), - ); + pub(crate) fn open_live( + &self, + session: &str, + owner: String, + cwd: &str, + previous: Option<&str>, + catalog: &crate::catalog::Catalog, + ) { + let mut view = Projection { + cwd: cwd.into(), + owner: Some(owner), + ..Projection::new() + }; + let mut sessions = self.sessions.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(source) = previous.and_then(|id| sessions.get(id)) { + let source = source.lock().unwrap_or_else(PoisonError::into_inner); + if source.owner == view.owner { + // A grant update can be purging the source while this view is published. + let readable = source + .owner + .as_deref() + .and_then(|key| catalog.find_key(key)) + .is_some_and(|agent| agent.may_read_sessions); + view.resume_rows(&source, readable); + } + } + sessions.insert(session.into(), Arc::new(Mutex::new(view))); } pub(crate) fn get(&self, session: &str) -> Option>> { @@ -110,10 +127,11 @@ impl Views { request: Request, ) -> Result { let session = match &request { - Request::Open { agent } => { + Request::Open { agent, cwd } => { let id = format!("history-{}", self.next.fetch_add(1, Ordering::Relaxed) + 1); let mut p = Projection { owner: agent.clone(), + cwd: cwd.as_deref().unwrap_or_default().into(), ..Projection::new() }; p.header = json!({"canPrompt":false,"exit":{"reason":"recorded"}}); diff --git a/rust/crates/agent-runtime/src/projection/history.rs b/rust/crates/agent-runtime/src/projection/history.rs index 7a96be87..8d23e1e7 100644 --- a/rust/crates/agent-runtime/src/projection/history.rs +++ b/rust/crates/agent-runtime/src/projection/history.rs @@ -150,6 +150,9 @@ impl Projection { if !later.output.is_empty() { row.output.clone_from(&later.output) } + if later.diff.is_some() { + row.diff.clone_from(&later.diff); + } if !later.locations.is_empty() { row.locations.clone_from(&later.locations) } diff --git a/rust/crates/agent-runtime/src/projection/tests.rs b/rust/crates/agent-runtime/src/projection/tests.rs index c4ee6cb1..b4908111 100644 --- a/rust/crates/agent-runtime/src/projection/tests.rs +++ b/rust/crates/agent-runtime/src/projection/tests.rs @@ -149,3 +149,50 @@ fn overlapping_user_rows_keep_the_turn_of_replies_already_visible() { assert_eq!(p.rows[1].turn, p.rows[2].turn); assert_ne!(p.rows[0].turn, p.rows[1].turn); } + +#[test] +fn tool_diffs_survive_partial_updates_and_share_the_file_and_byte_budgets() { + let mut p = Projection::new(); + p.cwd = std::env::temp_dir().join("projected-files"); + let file = p.cwd.join("a.txt"); + let huge = "é".repeat(MAX_TEXT); + p.event(&json!({"kind":"toolCall","toolCallID":"a","turn":1,"diff":{"path":"sub/../a.txt","newText":huge}})); + p.event(&json!({"kind":"toolCall","toolCallID":"a","turn":1,"status":"completed"})); + p.event(&json!({"kind":"toolCall","toolCallID":"b","turn":1,"toolKind":"edit","locations":[{"path":file}]})); + let first = &p.rows[0]; + let diff = first.diff.as_ref().unwrap(); + assert!(diff.old_text.is_none()); + assert_eq!(diff.new_text.len(), MAX_TEXT); + assert!(first.size() >= MAX_TEXT); + assert_eq!(p.files["session"], json!([file])); + for n in 0..20 { + p.event(&json!({"kind":"toolCall","toolCallID":n.to_string(),"turn":1,"diff":{"path":"a.txt","oldText":huge,"newText":huge}})); + } + assert!(p.bytes <= MAX_BYTES && p.trimmed > 0); +} + +#[test] +fn resumed_view_keeps_loaded_rows_with_fresh_live_turn_numbers() { + let mut source = Projection::new(); + source.history( + &[json!({"role":"user","text":"recorded","id":"r"})], + true, + true, + false, + ); + source.event(&json!({"kind":"promptDispatched","turn":1,"content":{"text":"previous"}})); + let mut next = Projection::new(); + let mut revoked = Projection::new(); + revoked.resume_rows(&source, false); + assert_eq!(revoked.rows.len(), 1); + assert_eq!(revoked.rows[0].text, "previous"); + next.resume_rows(&source, true); + next.event(&json!({"kind":"promptDispatched","turn":1,"content":{"text":"continued"}})); + assert_eq!(next.rows.len(), 3); + assert_eq!(next.rows[0].serial, source.rows[0].serial); + assert_eq!(next.rows[1].serial, source.rows[1].serial); + assert_ne!(next.rows[1].turn, next.rows[0].turn); + assert!(next.rows[1].turn >= RECORD_FLOOR && !next.rows[1].retryable); + assert_eq!(next.rows[2].turn, 1); + assert!(next.rows[2].serial > source.serial); +} From b4173ba94cbf92e863c9cf45db878315e8b5d691 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 11:34:24 +0800 Subject: [PATCH 3/6] fix(agents): preserve live history and page cursors within projection bounds --- rust/contracts/rust-core-api.md | 14 ++- rust/crates/agent-runtime/src/projection.rs | 97 +++++++++++++----- .../agent-runtime/src/projection/command.rs | 12 ++- .../agent-runtime/src/projection/history.rs | 99 +++++++++++++------ .../agent-runtime/src/projection/tests.rs | 88 ++++++++++++++++- rust/crates/agent-runtime/src/records.rs | 62 +++++++++++- rust/crates/agent-runtime/src/tests.rs | 69 +++++++++++++ 7 files changed, 376 insertions(+), 65 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 85f8c882..798d57a6 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -9226,7 +9226,8 @@ A tool row retains its latest supplied `diff`, including a missing versus empty `oldText`. The per-text and aggregate retention limits also cover these diffs. When `agents.start` resumes a session with `projection: true`, it can pass `previousView` to keep the same agent's retained rows and their serials. -Earlier live turns then occupy historical turn numbers. The old view remains +Earlier live turns then occupy historical turn numbers. Only rows read from disk carry +`recorded: true`. Clearing history or losing the read grant preserves earlier live turns. The old view remains owned by the caller until the new process starts successfully. On a first read or an expired cursor, `reset` is true. Replace rows starting @@ -9240,6 +9241,8 @@ Absent optional row fields have their empty or false value. Row kinds 0 through `serial` identifies a retained row across index changes. The original input identified by `opening` is eligible for retry when the row's `retryable` and the header's `canPrompt` are true. Pass its `retrySerial` to `agents.prompt`. +A prompt whose original UTF-8 text exceeds the retention limit is ineligible for retry. +On process exit, `header.exit.stderrTail` carries the bounded CLI diagnostic tail. Draft text, pending paste operations and native request progress remain local. Read responses fit a 512 KiB payload budget. If a header, file list or row @@ -9248,13 +9251,18 @@ the chunks and decode the resulting page when `nextByte` is zero. A discarded frame returns `agentSessions.invalidPage`. Retry from the last installed revision. Ordinary file reads can pass `projection: {session,ticket}` to `agentSessions.page` to merge the authorized page directly and return its byte -range. Use the separate `page` operation for a page captured before resuming +range. A detached viewer restarts at the requested page if the combined rows +would exceed its capacity. Its cursor advances over complete source lines that +fit. If one line alone normalizes beyond that capacity, it returns `tooLong` +with both offsets at the original cursor. Use the separate `page` operation for a page captured before resuming a CLI that may immediately append to the source. Files preserve their first-occurrence order within the retained session, a turn, or a visible reply segment keyed by its first row serial. Empty paths and non-mutating tools contribute no files. The retained view keeps up to -2,000 rows and a 4 MiB estimated row budget. Reply text keeps a 256 KiB +2,000 rows and a 4 MiB estimated row budget, including tool paths and their +changed-file index entries. Each tool row retains whole locations within a +1 MiB location budget. Reply text keeps a 256 KiB prefix and tool output a 16 KiB tail on UTF-8 boundaries. A transport replay gap, row eviction and dropped upstream output keep their respective meanings. diff --git a/rust/crates/agent-runtime/src/projection.rs b/rust/crates/agent-runtime/src/projection.rs index ab07cd62..6d93161e 100644 --- a/rust/crates/agent-runtime/src/projection.rs +++ b/rust/crates/agent-runtime/src/projection.rs @@ -11,8 +11,8 @@ use serde::Serialize; use serde_json::{json, Value}; use std::collections::{HashMap, HashSet, VecDeque}; -const MAX_ROWS: usize = 2000; -const MAX_BYTES: usize = 4 << 20; +pub(super) const MAX_ROWS: usize = 2000; +pub(super) const MAX_BYTES: usize = 4 << 20; const MAX_TEXT: usize = 256 << 10; const MAX_OUTPUT: usize = 16 << 10; const RECORD_BASE: u64 = 1 << 62; @@ -25,6 +25,8 @@ const ASSISTANT: u8 = 1; const THOUGHT: u8 = 2; const TOOL: u8 = 3; const NOTICE: u8 = 4; +// Index namespace only, never sent as a row kind. +const TOOL_MIRROR_KEY: u8 = 5; fn text<'a>(v: &'a Value, key: &str) -> &'a str { v[key].as_str().unwrap_or_default() @@ -63,6 +65,20 @@ fn changed_path(cwd: &std::path::Path, raw: &str) -> String { } } +// A changed path can also appear in the session, turn and reply file lists. +fn location_bytes(cwd: &std::path::Path, path: &str, indexed: bool) -> usize { + let payload = std::mem::size_of::() + path.len(); + if !indexed { + return payload; + } + let base = if std::path::Path::new(path).is_relative() { + cwd.as_os_str().len() + 1 + } else { + 0 + }; + payload + 3 * (std::mem::size_of::() + path.len() + base) +} + /// One retained row. Serial is stable across replacements, trims and historical prepends. #[derive(Clone, Default, Serialize)] #[serde(rename_all = "camelCase")] @@ -70,6 +86,12 @@ struct Row { kind: u8, serial: u64, turn: u64, + // Disk provenance is independent of the turn number assigned on CLI restart. + #[serde(skip_serializing_if = "std::ops::Not::not")] + recorded: bool, + // A source message ID without a tool call is only for deduplicating disk mirrors. + #[serde(skip)] + mirror_id: String, #[serde(skip_serializing_if = "String::is_empty")] id: String, #[serde(skip_serializing_if = "String::is_empty")] @@ -102,13 +124,21 @@ struct Row { } impl Row { - fn size(&self) -> usize { - 64 + self.text.len() + fn size(&self, cwd: &std::path::Path) -> usize { + let indexed = matches!(self.tool_kind.as_str(), "edit" | "delete" | "move"); + 64 + self.id.len() + + self.mirror_id.len() + + self.text.len() + + self + .locations + .iter() + .map(|l| location_bytes(cwd, &l.path, indexed)) + .sum::() + self.title.len() + self.command.len() + self.output.len() + self.diff.as_ref().map_or(0, |d| { - 64 + d.path.len() + 64 + location_bytes(cwd, &d.path, true) + d.new_text.len() + d.old_text.as_deref().unwrap_or_default().len() }) @@ -116,9 +146,15 @@ impl Row { } fn key(&self) -> Option<(bool, u8, String)> { + if !self.recorded && self.turn >= RECORD_FLOOR { + return None; + } + if !self.mirror_id.is_empty() { + return Some((true, TOOL_MIRROR_KEY, self.mirror_id.clone())); + } (!self.id.is_empty() && self.kind <= TOOL).then(|| { ( - self.turn >= RECORD_FLOOR, + self.recorded, if self.kind == THOUGHT { ASSISTANT } else { @@ -129,15 +165,16 @@ impl Row { }) } - fn retryable(&mut self) { + fn set_text(&mut self, original: &str) { + self.text = prefix(original, MAX_TEXT).into(); self.retryable = self.kind == USER && !self.supplement && self.turn != 0 - && self.text.len() < MAX_TEXT + && original.len() <= MAX_TEXT && (!self.text.is_empty() || !self.attachments.is_empty()); } - fn tool_update(&mut self, later: &Value, recorded: bool) { + fn tool_update(&mut self, later: &Value, recorded: bool, cwd: &std::path::Path) { for (target, value) in [ (&mut self.status, text(later, "status")), (&mut self.tool_kind, text(later, "toolKind")), @@ -177,11 +214,18 @@ impl Row { }); } if let Some(locations) = later["locations"].as_array().filter(|a| !a.is_empty()) { + let mut budget = 4 * MAX_TEXT; self.locations = locations .iter() - .map(|v| crate::events::ToolLocation { - path: text(v, "path").to_owned(), - line: v["line"].as_u64(), + .filter_map(|v| { + let path = text(v, "path"); + // Keep whole, usable paths. A status update may later turn a read into an edit. + let cost = location_bytes(cwd, path, true); + budget = budget.checked_sub(cost)?; + Some(crate::events::ToolLocation { + path: path.into(), + line: v["line"].as_u64(), + }) }) .collect(); } @@ -195,7 +239,7 @@ impl Row { /// A reader which falls behind replaces its local rows from bounded snapshot pages. #[derive(Default)] pub(crate) struct Projection { - cwd: std::path::PathBuf, + pub(super) cwd: std::path::PathBuf, rows: Vec, index: HashMap<(bool, u8, String), usize>, serial: u64, @@ -238,7 +282,7 @@ impl Projection { source .rows .iter() - .filter(|row| include_history || row.turn < RECORD_FLOOR) + .filter(|row| include_history || !row.recorded) .cloned(), ); self.serial = source.serial; @@ -266,6 +310,7 @@ impl Projection { None }; self.reindex(); + self.trim(); self.opening = None; self.changed_files(); } @@ -297,7 +342,7 @@ impl Projection { if let Some(key) = row.key() { self.index.insert(key, at); } - self.bytes += row.size(); + self.bytes += row.size(&self.cwd); } } @@ -374,7 +419,6 @@ impl Projection { fn append(&mut self, mut row: Row) -> usize { self.serial += 1; row.serial = self.serial; - row.retryable(); let at = self.rows.len(); if row.kind == USER && !row.supplement { self.opening = Some(at); @@ -382,7 +426,7 @@ impl Projection { if let Some(key) = row.key() { self.index.insert(key, at); } - self.bytes += row.size(); + self.bytes += row.size(&self.cwd); self.rows.push(row); at } @@ -438,22 +482,21 @@ impl Projection { }) }; let row = &mut self.rows[at]; - let before = row.size(); + let before = row.size(&self.cwd); files = e.get("locations").is_some() || e.get("toolKind").is_some() || e.get("diff").is_some(); - row.tool_update(e, false); - self.bytes = self.bytes - before + row.size(); + row.tool_update(e, false, &self.cwd); + self.bytes = self.bytes - before + row.size(&self.cwd); edit = json!({"at":at,"row":row}); } "promptDispatched" | "inputResolved" if kind == "promptDispatched" || e["accepted"] == true => { if let Some(content) = e.get("content").filter(|v| v.is_object()) { - let at = self.append(Row { + let mut row = Row { turn, id: text(content, "id").into(), - text: prefix(text(content, "text"), MAX_TEXT).into(), attachments: content["attachments"] .as_array() .into_iter() @@ -462,7 +505,9 @@ impl Projection { .collect(), supplement: kind == "inputResolved", ..Row::default() - }); + }; + row.set_text(text(content, "text")); + let at = self.append(row); edit = json!({"at":at,"row":self.rows[at]}); } } @@ -572,7 +617,7 @@ impl Projection { h["ratePlan"] = e["plan"].clone(); } "exited" => { - h["exit"] = json!({"reason":e["reason"],"exitCode":e["exitCode"]}); + h["exit"] = json!({"reason":e["reason"],"exitCode":e["exitCode"],"stderrTail":e["stderrTail"]}); h["activeTurn"] = 0.into(); h["pending"] = Value::Null; h["configOptions"] = Value::Null; @@ -639,10 +684,10 @@ impl Projection { .iter() .take(128) .take_while(|r| { - if bytes > 0 && bytes + r.size() > PAGE_BYTES { + if bytes > 0 && bytes + r.size(&self.cwd) > PAGE_BYTES { return false; } - bytes += r.size(); + bytes += r.size(&self.cwd); true }) .collect(); diff --git a/rust/crates/agent-runtime/src/projection/command.rs b/rust/crates/agent-runtime/src/projection/command.rs index 84b9ac93..86b25a57 100644 --- a/rust/crates/agent-runtime/src/projection/command.rs +++ b/rust/crates/agent-runtime/src/projection/command.rs @@ -111,7 +111,7 @@ impl Views { .collect(); for view in sessions { let mut p = view.lock().unwrap_or_else(PoisonError::into_inner); - if p.high != 0 + if p.rows.iter().any(|row| row.recorded) && p.owner .as_ref() .is_some_and(|key| !catalog.find_key(key).is_some_and(|a| a.may_read_sessions)) @@ -197,6 +197,16 @@ impl Views { )); } crate::records::validate_projection_page(&messages)?; + if viewer + && (messages.len() > super::MAX_ROWS + || Projection::record_page_bytes(&p.cwd, &messages) > super::MAX_BYTES) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidPage", + "The page exceeds the viewer window.", + )); + } p.page(ticket, (start, end, before), &messages, viewer, replace); Ok(json!({"restarted":p.restarted,"ticket":p.ticket})) } diff --git a/rust/crates/agent-runtime/src/projection/history.rs b/rust/crates/agent-runtime/src/projection/history.rs index 8d23e1e7..d83912c3 100644 --- a/rust/crates/agent-runtime/src/projection/history.rs +++ b/rust/crates/agent-runtime/src/projection/history.rs @@ -2,11 +2,54 @@ //! Pages are supplied only after the existing record reader checks the source generation. use super::{ - prefix, text, Projection, Row, Value, ASSISTANT, MAX_BYTES, MAX_ROWS, MAX_TEXT, RECORD_BASE, + prefix, text, Projection, Row, Value, ASSISTANT, MAX_BYTES, MAX_ROWS, RECORD_BASE, RECORD_FLOOR, THOUGHT, TOOL, USER, }; +impl Row { + fn from_record(m: &Value, kind: u8, turn: u64, cwd: &std::path::Path) -> Self { + let mut row = Self { + recorded: true, + turn, + kind, + at_ms: m["atMs"].as_i64().unwrap_or_default(), + ..Self::default() + }; + if kind == TOOL { + row.id = text(m, "toolCallID").into(); + if row.id.is_empty() { + row.mirror_id = text(m, "id").into(); + } + row.tool_update(m, true, cwd); + if row.title.is_empty() { + row.title = prefix(text(m, "toolName"), 1024).into(); + } + } else { + row.id = text(m, "id").into(); + row.set_text(text(m, "text")); + } + row + } +} + impl Projection { + /// Count the bounded rows a decoded source group can contribute before combining groups. + /// Overlapping IDs may reduce this estimate once the page joins its neighbours. + pub(crate) fn record_page_bytes(cwd: &std::path::Path, messages: &[Value]) -> usize { + messages + .iter() + .map(|m| { + let kind = match text(m, "role") { + "tool" => TOOL, + "user" => USER, + "thought" => THOUGHT, + _ => ASSISTANT, + }; + Row::from_record(m, kind, 0, cwd).size(cwd) + }) + .sum() + } + /// A retried read of the same byte range can return after its first result was lost. pub(crate) fn page( &mut self, @@ -83,12 +126,8 @@ impl Projection { "tool" => TOOL, _ => continue, }; - let id = if kind == TOOL { - text(m, "toolCallID") - } else { - text(m, "id") - }; if kind == USER { + let id = text(m, "id"); let key = (true, USER, id.to_owned()); turn = page .index @@ -100,37 +139,22 @@ impl Projection { next_turn }); } - let at_ms = m["atMs"].as_i64().unwrap_or_default(); - let mut row = Row { - turn, - kind, - at_ms, - id: id.into(), - ..Row::default() - }; - if kind == TOOL { - row.tool_update(m, true); - if row.title.is_empty() { - row.title = prefix(text(m, "toolName"), 1024).into() - } - } else { - row.text = prefix(text(m, "text"), MAX_TEXT).into() - } + let mut row = Row::from_record(m, kind, turn, &self.cwd); let key = row.key(); if let Some(&at) = key.as_ref().and_then(|k| page.index.get(k)) { if kind == TOOL { - page.rows[at].tool_update(m, true) + page.rows[at].tool_update(m, true, &self.cwd) } continue; } if let Some(&at) = key.as_ref().and_then(|k| self.index.get(k)) { let later = &mut self.rows[at]; - if later.turn < RECORD_FLOOR { + if !later.recorded { continue; } if !before { if kind == TOOL { - later.tool_update(m, true) + later.tool_update(m, true, &self.cwd) } continue; } @@ -182,26 +206,43 @@ impl Projection { let live = self .rows .iter() - .position(|r| r.turn < RECORD_FLOOR) + .position(|r| !r.recorded) .unwrap_or(self.rows.len()); self.rows.splice(live..live, page.rows); } + self.reindex(); + if viewer && !restart && (self.rows.len() > MAX_ROWS || self.bytes > MAX_BYTES) { + // Rebuild from the actual requested page, including its overlapping rows. + self.trimmed = 0; + self.lost_output = 0; + self.history(messages, before, false, true); + return true; + } self.reset_readers(); restart } pub(crate) fn clear_history(&mut self) { - self.rows.retain(|r| r.turn < RECORD_FLOOR); + self.rows.retain(|r| !r.recorded); self.last_page = None; self.low = 0; - self.high = 0; + self.high = self + .rows + .iter() + .map(|row| row.turn) + .filter(|turn| *turn >= RECORD_FLOOR) + .max() + .unwrap_or(0); + if self.high != 0 { + self.low = RECORD_BASE; + } + self.reindex(); self.reset_readers(); } fn reset_readers(&mut self) { self.wire.clear(); self.snapshot = None; - self.reindex(); self.trim(); self.revision += 1; self.journal.clear(); diff --git a/rust/crates/agent-runtime/src/projection/tests.rs b/rust/crates/agent-runtime/src/projection/tests.rs index b4908111..022dd697 100644 --- a/rust/crates/agent-runtime/src/projection/tests.rs +++ b/rust/crates/agent-runtime/src/projection/tests.rs @@ -163,7 +163,7 @@ fn tool_diffs_survive_partial_updates_and_share_the_file_and_byte_budgets() { let diff = first.diff.as_ref().unwrap(); assert!(diff.old_text.is_none()); assert_eq!(diff.new_text.len(), MAX_TEXT); - assert!(first.size() >= MAX_TEXT); + assert!(first.size(&p.cwd) >= MAX_TEXT); assert_eq!(p.files["session"], json!([file])); for n in 0..20 { p.event(&json!({"kind":"toolCall","toolCallID":n.to_string(),"turn":1,"diff":{"path":"a.txt","oldText":huge,"newText":huge}})); @@ -196,3 +196,89 @@ fn resumed_view_keeps_loaded_rows_with_fresh_live_turn_numbers() { assert_eq!(next.rows[2].turn, 1); assert!(next.rows[2].serial > source.serial); } + +#[test] +fn revoked_disk_history_does_not_remove_retained_live_turns() { + let mut original = Projection::new(); + original.history(&[json!({"role":"user","text":"disk"})], true, false, false); + original.event(&json!({"kind":"promptDispatched","turn":1,"content":{"text":"first live"}})); + let mut resumed = Projection::new(); + resumed.resume_rows(&original, false); + let serial = resumed.rows[0].serial; + resumed.clear_history(); + let mut again = Projection::new(); + again.resume_rows(&resumed, false); + assert_eq!(again.rows.len(), 1); + assert_eq!( + (again.rows[0].text.as_str(), again.rows[0].serial), + ("first live", serial) + ); +} + +#[test] +fn a_viewer_reopens_on_the_requested_page_before_trimming_it() { + let mut view = Projection::new(); + let page = |start: usize| { + (start..start + 1100) + .map(|n| json!({"role":"user","text":n.to_string()})) + .collect::>() + }; + view.history(&page(1100), true, true, false); + assert!(view.history(&page(0), true, true, false)); + assert_eq!(view.rows.len(), 1100); + assert_eq!(view.rows[0].text, "0"); + assert_eq!(view.rows.last().unwrap().text, "1099"); +} + +#[test] +fn mirrored_tool_messages_and_call_ids_have_separate_keys() { + let mirror = json!({"role":"tool","id":"s","toolName":"Read","text":"mirror"}); + let call = json!({"role":"tool","toolCallID":"s","text":"call"}); + let mut view = Projection::new(); + view.history(&[mirror.clone(), call], true, true, false); + let serial = view.rows[0].serial; + view.history(&[mirror.clone(), mirror], true, true, false); + assert_eq!(view.rows.len(), 2); + assert_eq!(view.rows[0].serial, serial); + assert_eq!(view.rows[1].output, "call"); +} + +#[test] +fn only_fully_retained_utf8_prompts_can_be_retried() { + let mut p = Projection::new(); + let kept = "a".repeat(MAX_TEXT - 1); + p.event(&json!({"kind":"promptDispatched","turn":1,"content":{"text":format!("{kept}界")}})); + assert_eq!(p.rows[0].text, kept); + assert!(!p.can_retry(p.rows[0].serial, &kept, &[])); + let exact = "a".repeat(MAX_TEXT); + p.event(&json!({"kind":"promptDispatched","turn":2,"content":{"text":exact}})); + assert!(p.can_retry(p.rows[1].serial, &exact, &[])); +} + +#[test] +fn failed_exit_keeps_the_cli_diagnostic_in_the_projection_header() { + let mut p = Projection::new(); + p.event(&json!({"kind":"exited","reason":"failed","exitCode":1,"stderrTail":"agent error"})); + assert_eq!( + p.read(0, 0, None)["header"]["exit"]["stderrTail"], + "agent error" + ); +} + +#[test] +fn tool_location_bytes_are_bounded_and_paths_remain_whole() { + let mut p = Projection::new(); + let path = "a".repeat(32768); + let locations = (0..64) + .map(|i| json!({"path":format!("{path}{i}")})) + .collect::>(); + for n in 0..22 { + p.event(&json!({"kind":"toolCall","toolKind":"edit","turn":1,"toolCallID":n.to_string(),"locations":locations})); + } + assert!(p.trimmed > 0 && p.bytes <= MAX_BYTES); + let row = p.rows.last().unwrap(); + assert!(!row.locations.is_empty() && row.locations.len() < locations.len()); + for loc in &row.locations { + assert!(locations.iter().any(|v| v["path"] == loc.path)); + } +} diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 896c5cca..8bc26758 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -835,18 +835,42 @@ impl Records { if group_start < bytes.len() { groups.push((group_start, bytes.len())); } - if before { + // Work from the cursor outwards. Splitting a group below keeps the cursor at + // a real source-line boundary so the adjacent page can be read in either direction. + if !before { groups.reverse(); } + let viewer = request + .projection + .as_ref() + .filter(|t| t.session.starts_with("history-")); + let cwd = if let Some(target) = viewer { + let view = runtime + .live + .queue + .views + .get(&target.session) + .ok_or_else(invalid)?; + let view = view + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if view.owner.as_deref() != Some(&request.agent) { + return Err(invalid()); + } + Some(view.cwd.clone()) + } else { + None + }; let mut collected = VecDeque::new(); let mut total = 0; let mut count = 0; + let mut row_bytes = 0; let (mut from, mut to) = if before { (bytes.len(), bytes.len()) } else { (0, 0) }; - for (low, high) in groups { + while let Some((low, high)) = groups.pop() { let answer = call_read( &*runtime.link, &agent, @@ -859,12 +883,41 @@ impl Records { decode_messages(answer.into_iter().next().unwrap_or_else(|| json!({})), true)?; let size = serde_json::to_vec(&messages).map_or(RECORD_RESULT_BYTES + 1, |data| data.len()); + let messages: Vec = messages.into_iter().map(|m| json!(m)).collect(); + let cost = cwd.as_deref().map_or(0, |dir| { + crate::projection::Projection::record_page_bytes(dir, &messages) + }); + let over_window = cwd.is_some() + && (count + messages.len() > crate::projection::MAX_ROWS + || row_bytes + cost > crate::projection::MAX_BYTES); if count > 0 && (total + size > RECORD_RESULT_BYTES - || count + messages.len() > MAX_MESSAGES_PER_ITEM) + || count + messages.len() > MAX_MESSAGES_PER_ITEM + || over_window) { break; } + if over_window { + // One source line cannot be split by a byte cursor. Report the existing + // too-long condition without acknowledging any of its messages. + let middle = low + (high - low) / 2; + let split = bytes[low..high - 1] + .iter() + .enumerate() + .filter(|(_, b)| **b == b'\n') + .map(|(i, _)| low + i + 1) + .min_by_key(|at| at.abs_diff(middle)); + let Some(split) = split else { + return Ok(empty(false, true)); + }; + if before { + groups.extend([(low, split), (split, high)]); + } else { + groups.extend([(split, high), (low, split)]); + } + continue; + } + row_bytes += cost; total += size; count += messages.len(); if before { @@ -875,7 +928,7 @@ impl Records { collected.push_back(messages); } } - let messages: Vec = collected.into_iter().flatten().collect(); + let messages: Vec = collected.into_iter().flatten().collect(); let low = start + from as u64; let high = start + to as u64; if let Some(target) = request.projection { @@ -893,7 +946,6 @@ impl Records { } // The catalog may have changed while the backend read the file. readable_agent(runtime, plugin_id, agent_id)?; - let messages = messages.into_iter().map(|m| json!(m)).collect::>(); let restart = view.page( target.ticket, (low, high, before), diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index a025ee04..26d28c03 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -2721,6 +2721,75 @@ fn exiting_before_steering_acknowledgement_returns_the_original_input() { assert_eq!(harness.next_event(&session, "exited")["exitCode"], 1); } +#[test] +fn projected_pages_acknowledge_only_complete_source_lines_that_fit_the_view() { + let h = Harness::new("project-page-capacity", ALL_GRANTS); + let file = write_session_file(&h, 1_795_824_000_000); + h.run( + "agentSessions.sync", + json!({"pluginID":PLUGIN,"agentID":AGENT}), + ); + let size = fs::metadata(&file).unwrap().len(); + let generation = generation_of(&h); + let source = fs::read_to_string(&file).unwrap(); + let page = |view: &Value, direction: &str, cursor: u64, ticket: u64| { + h.run("agentSessions.page", json!({"agent":AGENT_KEY,"path":path_text(&file),"size":size, + "generation":generation,"direction":direction,"cursor":cursor,"projection":{"session":view,"ticket":ticket}})) + }; + for (direction, start, finish, edge) in + [("after", 0, size, "end"), ("before", size, 0, "start")] + { + let view = + h.run("agents.projection", json!({"op":"open","agent":AGENT_KEY}))["session"].clone(); + h.link.set_answer(|_, params| { + let messages: Vec<_> = params["items"][0]["lines"] + .as_array() + .unwrap() + .iter() + .flat_map(|line| { + let kind = serde_json::from_str::(line.as_str().unwrap()).unwrap() + ["type"] + .clone(); + (0..510).map(move |n| json!({"role":"assistant","text":format!("{kind} {n}")})) + }) + .collect(); + Ok(json!({"items":[{"messages":messages}]})) + }); + let first = page(&view, direction, start, 1); + let middle = first[edge].as_u64().unwrap(); + assert!(middle > 0 && middle < size); + assert_eq!(source.as_bytes()[middle as usize - 1], b'\n'); + let second = page(&view, direction, middle, 2); + assert_eq!(second[edge], finish); + assert_eq!( + second[if direction == "after" { "start" } else { "end" }], + middle + ); + assert_eq!(second["restarted"], true); + let rows = h.run("agents.projection", json!({"op":"read","session":view})); + let expected = if direction == "after" { + &source[middle as usize..] + } else { + &source[..middle as usize] + }; + let first_line: Value = serde_json::from_str(expected.lines().next().unwrap()).unwrap(); + assert_eq!(rows["rows"][0]["text"], format!("{} 0", first_line["type"])); + + h.link.set_answer(|_, _| { + Ok(json!({"items":[{"messages":vec![json!({"role":"assistant","text":"x"});2048]}]})) + }); + let huge = page(&view, direction, start, 3); + assert_eq!( + ( + huge["tooLong"].as_bool(), + huge["start"].as_u64(), + huge["end"].as_u64() + ), + (Some(true), Some(start), Some(start)) + ); + } +} + #[test] fn projected_disk_pages_survive_retry_and_are_purged_when_access_is_revoked() { let h = Harness::new("project-record", ALL_GRANTS); From 53ba69a85dd59407c9e5f615964c570d06b19702 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 11:58:58 +0800 Subject: [PATCH 4/6] fix(agents): verify folded pages and invalidate revoked snapshots --- rust/contracts/rust-core-api.md | 5 +- rust/crates/agent-runtime/src/projection.rs | 7 +- .../agent-runtime/src/projection/command.rs | 7 +- .../agent-runtime/src/projection/history.rs | 51 ++++---- rust/crates/agent-runtime/src/records.rs | 123 +++++++++--------- rust/crates/agent-runtime/src/tests.rs | 82 ++++++++++++ 6 files changed, 178 insertions(+), 97 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 798d57a6..3c6001c4 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -9227,7 +9227,8 @@ A tool row retains its latest supplied `diff`, including a missing versus empty When `agents.start` resumes a session with `projection: true`, it can pass `previousView` to keep the same agent's retained rows and their serials. Earlier live turns then occupy historical turn numbers. Only rows read from disk carry -`recorded: true`. Clearing history or losing the read grant preserves earlier live turns. The old view remains +`recorded: true`. Clearing history or losing the read grant preserves earlier live turns and invalidates +recorded data held by snapshots and response frames, even after row eviction. The old view remains owned by the caller until the new process starts successfully. On a first read or an expired cursor, `reset` is true. Replace rows starting @@ -9253,7 +9254,7 @@ revision. Ordinary file reads can pass `projection: {session,ticket}` to `agentSessions.page` to merge the authorized page directly and return its byte range. A detached viewer restarts at the requested page if the combined rows would exceed its capacity. Its cursor advances over complete source lines that -fit. If one line alone normalizes beyond that capacity, it returns `tooLong` +fit after folding mirrors and partial tool updates. If one line alone normalizes beyond that capacity, it returns `tooLong` with both offsets at the original cursor. Use the separate `page` operation for a page captured before resuming a CLI that may immediately append to the source. diff --git a/rust/crates/agent-runtime/src/projection.rs b/rust/crates/agent-runtime/src/projection.rs index 6d93161e..977e62c6 100644 --- a/rust/crates/agent-runtime/src/projection.rs +++ b/rust/crates/agent-runtime/src/projection.rs @@ -11,8 +11,8 @@ use serde::Serialize; use serde_json::{json, Value}; use std::collections::{HashMap, HashSet, VecDeque}; -pub(super) const MAX_ROWS: usize = 2000; -pub(super) const MAX_BYTES: usize = 4 << 20; +const MAX_ROWS: usize = 2000; +const MAX_BYTES: usize = 4 << 20; const MAX_TEXT: usize = 256 << 10; const MAX_OUTPUT: usize = 16 << 10; const RECORD_BASE: u64 = 1 << 62; @@ -252,6 +252,8 @@ pub(crate) struct Projection { revision: u64, ticket: u64, pub(crate) owner: Option, + // Frames and snapshots can outlive the last recorded row in the current window. + has_record_cache: bool, restarted: bool, last_page: Option<(u64, u64, bool)>, journal: VecDeque<(u64, Value, usize)>, @@ -285,6 +287,7 @@ impl Projection { .filter(|row| include_history || !row.recorded) .cloned(), ); + self.has_record_cache = self.rows.iter().any(|row| row.recorded); self.serial = source.serial; self.low = if source.low == 0 { RECORD_BASE diff --git a/rust/crates/agent-runtime/src/projection/command.rs b/rust/crates/agent-runtime/src/projection/command.rs index 86b25a57..0456a2db 100644 --- a/rust/crates/agent-runtime/src/projection/command.rs +++ b/rust/crates/agent-runtime/src/projection/command.rs @@ -111,7 +111,7 @@ impl Views { .collect(); for view in sessions { let mut p = view.lock().unwrap_or_else(PoisonError::into_inner); - if p.rows.iter().any(|row| row.recorded) + if p.has_record_cache && p.owner .as_ref() .is_some_and(|key| !catalog.find_key(key).is_some_and(|a| a.may_read_sessions)) @@ -197,10 +197,7 @@ impl Views { )); } crate::records::validate_projection_page(&messages)?; - if viewer - && (messages.len() > super::MAX_ROWS - || Projection::record_page_bytes(&p.cwd, &messages) > super::MAX_BYTES) - { + if viewer && !Projection::record_page_fits(&p.cwd, &messages) { return Err(refusal( ErrorCode::InvalidRequest, "agentSessions.invalidPage", diff --git a/rust/crates/agent-runtime/src/projection/history.rs b/rust/crates/agent-runtime/src/projection/history.rs index d83912c3..47977de6 100644 --- a/rust/crates/agent-runtime/src/projection/history.rs +++ b/rust/crates/agent-runtime/src/projection/history.rs @@ -33,21 +33,14 @@ impl Row { } impl Projection { - /// Count the bounded rows a decoded source group can contribute before combining groups. - /// Overlapping IDs may reduce this estimate once the page joins its neighbours. - pub(crate) fn record_page_bytes(cwd: &std::path::Path, messages: &[Value]) -> usize { - messages - .iter() - .map(|m| { - let kind = match text(m, "role") { - "tool" => TOOL, - "user" => USER, - "thought" => THOUGHT, - _ => ASSISTANT, - }; - Row::from_record(m, kind, 0, cwd).size(cwd) - }) - .sum() + /// Measure a complete standalone page after all partial calls and mirrors have been folded. + pub(crate) fn record_page_fits(cwd: &std::path::Path, messages: &[Value]) -> bool { + let mut page = Self { + cwd: cwd.into(), + ..Self::default() + }; + page.fold_history(messages, false); + page.rows.len() <= MAX_ROWS && page.bytes <= MAX_BYTES } /// A retried read of the same byte range can return after its first result was lost. @@ -78,7 +71,7 @@ impl Projection { viewer: bool, replace: bool, ) -> bool { - let restart = + let mut restart = viewer && (self.rows.len() >= MAX_ROWS * 3 / 4 || self.bytes >= MAX_BYTES * 3 / 4); if restart { self.trimmed = 0; @@ -87,6 +80,22 @@ impl Projection { if restart || replace { self.clear_history() } + self.fold_history(messages, before); + if viewer && !restart && (self.rows.len() > MAX_ROWS || self.bytes > MAX_BYTES) { + // The source page fits on its own. Preserve its full range, including overlaps. + self.clear_history(); + self.trimmed = 0; + self.lost_output = 0; + self.fold_history(messages, before); + restart = true; + } + self.reset_readers(); + restart + } + + /// Merge in file order without trimming or publishing a partial window. + fn fold_history(&mut self, messages: &[Value], before: bool) { + self.has_record_cache |= !messages.is_empty(); if self.high == 0 { self.high = RECORD_BASE; self.low = RECORD_BASE @@ -211,18 +220,10 @@ impl Projection { self.rows.splice(live..live, page.rows); } self.reindex(); - if viewer && !restart && (self.rows.len() > MAX_ROWS || self.bytes > MAX_BYTES) { - // Rebuild from the actual requested page, including its overlapping rows. - self.trimmed = 0; - self.lost_output = 0; - self.history(messages, before, false, true); - return true; - } - self.reset_readers(); - restart } pub(crate) fn clear_history(&mut self) { + self.has_record_cache = false; self.rows.retain(|r| !r.recorded); self.last_page = None; self.low = 0; diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 8bc26758..b468aafd 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -861,74 +861,71 @@ impl Records { } else { None }; - let mut collected = VecDeque::new(); - let mut total = 0; - let mut count = 0; - let mut row_bytes = 0; - let (mut from, mut to) = if before { - (bytes.len(), bytes.len()) - } else { - (0, 0) - }; - while let Some((low, high)) = groups.pop() { - let answer = call_read( - &*runtime.link, - &agent, - &sources[source].source, - "messages", - vec![json!({ "path": request.path, "lines": text_lines(&bytes[low..high]) })], - true, - )?; - let messages = - decode_messages(answer.into_iter().next().unwrap_or_else(|| json!({})), true)?; - let size = - serde_json::to_vec(&messages).map_or(RECORD_RESULT_BYTES + 1, |data| data.len()); - let messages: Vec = messages.into_iter().map(|m| json!(m)).collect(); - let cost = cwd.as_deref().map_or(0, |dir| { - crate::projection::Projection::record_page_bytes(dir, &messages) - }); - let over_window = cwd.is_some() - && (count + messages.len() > crate::projection::MAX_ROWS - || row_bytes + cost > crate::projection::MAX_BYTES); - if count > 0 - && (total + size > RECORD_RESULT_BYTES - || count + messages.len() > MAX_MESSAGES_PER_ITEM - || over_window) - { - break; - } - if over_window { - // One source line cannot be split by a byte cursor. Report the existing - // too-long condition without acknowledging any of its messages. - let middle = low + (high - low) / 2; - let split = bytes[low..high - 1] - .iter() - .enumerate() - .filter(|(_, b)| **b == b'\n') - .map(|(i, _)| low + i + 1) - .min_by_key(|at| at.abs_diff(middle)); - let Some(split) = split else { - return Ok(empty(false, true)); - }; + let mut range = 0..bytes.len(); + let (messages, from, to) = loop { + let mut collected = VecDeque::new(); + let mut total = 0; + let mut count = 0; + let (mut from, mut to) = if before { + (range.end, range.end) + } else { + (range.start, range.start) + }; + for &(low, high) in groups.iter().rev() { + let (low, high) = (low.max(range.start), high.min(range.end)); + if low >= high { + continue; + } + let answer = call_read( + &*runtime.link, + &agent, + &sources[source].source, + "messages", + vec![json!({ "path": request.path, "lines": text_lines(&bytes[low..high]) })], + true, + )?; + let messages = + decode_messages(answer.into_iter().next().unwrap_or_else(|| json!({})), true)?; + let size = serde_json::to_vec(&messages) + .map_or(RECORD_RESULT_BYTES + 1, |data| data.len()); + let messages: Vec = messages.into_iter().map(|m| json!(m)).collect(); + if count > 0 + && (total + size > RECORD_RESULT_BYTES + || count + messages.len() > MAX_MESSAGES_PER_ITEM) + { + break; + } + total += size; + count += messages.len(); if before { - groups.extend([(low, split), (split, high)]); + from = low; + collected.push_front(messages); } else { - groups.extend([(split, high), (low, split)]); + to = high; + collected.push_back(messages); } - continue; } - row_bytes += cost; - total += size; - count += messages.len(); - if before { - from = low; - collected.push_front(messages); - } else { - to = high; - collected.push_back(messages); + let messages: Vec = collected.into_iter().flatten().collect(); + if cwd + .as_deref() + .is_none_or(|dir| crate::projection::Projection::record_page_fits(dir, &messages)) + { + break (messages, from, to); } - } - let messages: Vec = collected.into_iter().flatten().collect(); + // Narrow the source range towards the cursor. Each retry drops at least one + // complete line; an indivisible over-budget line leaves the cursor unchanged. + let middle = from + (to - from) / 2; + let split = bytes[from..to - 1] + .iter() + .enumerate() + .filter(|(_, byte)| **byte == b'\n') + .map(|(i, _)| from + i + 1) + .min_by_key(|at| at.abs_diff(middle)); + let Some(split) = split else { + return Ok(empty(false, true)); + }; + range = if before { split..to } else { from..split }; + }; let low = start + from as u64; let high = start + to as u64; if let Some(target) = request.projection { diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 26d28c03..4c11543e 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -2790,6 +2790,88 @@ fn projected_pages_acknowledge_only_complete_source_lines_that_fit_the_view() { } } +#[test] +fn detached_pages_measure_partial_tool_calls_after_their_edits_are_folded() { + let h = Harness::new("folded-page-budget", ALL_GRANTS); + let file = write_session_file(&h, 1_795_824_000_000); + h.run( + "agentSessions.sync", + json!({"pluginID":PLUGIN,"agentID":AGENT}), + ); + let generation = generation_of(&h); + let size = fs::metadata(&file).unwrap().len(); + let cwd = h.work.join("d".repeat(230)); + let view = h.run( + "agents.projection", + json!({"op":"open","agent":AGENT_KEY,"cwd":path_text(&cwd)}), + )["session"] + .clone(); + let locations: Vec<_> = (0..64) + .map(|n| json!({"path":format!("{}{n}", "p".repeat(250))})) + .collect(); + let mut messages = Vec::new(); + for n in 0..40 { + messages + .push(json!({"role":"tool","text":"","toolCallID":n.to_string(),"toolKind":"edit"})); + messages.push( + json!({"role":"tool","text":"done","toolCallID":n.to_string(),"locations":locations}), + ); + } + let submit = |messages: &[Value]| json!({"op":"page","session":view,"ticket":1,"start":0,"end":size,"messages":messages,"before":false}); + assert_eq!( + h.refused("agents.projection", submit(&messages)), + "agentSessions.invalidPage" + ); + h.link + .set_answer(move |_, _| Ok(json!({"items":[{"messages":messages}]}))); + let page=h.run("agentSessions.page",json!({"agent":AGENT_KEY,"path":path_text(&file),"size":size,"generation":generation,"direction":"after","cursor":0,"projection":{"session":view,"ticket":1}})); + assert_eq!( + (page["tooLong"].as_bool(), page["end"].as_u64()), + (Some(true), Some(0)) + ); + let mirrors = vec![json!({"role":"tool","text":"done","toolCallID":"same"}); 2048]; + h.run("agents.projection", submit(&mirrors)); + let installed = h.run("agents.projection", json!({"op":"read","session":view})); + assert_eq!(installed["rows"].as_array().unwrap().len(), 1); +} + +#[test] +fn revoking_records_discards_snapshots_and_frames_after_live_rows_evict_history() { + let h = Harness::new("purge-evicted-records", ALL_GRANTS); + let session = h.run("agents.projection", json!({"op":"open","agent":AGENT_KEY}))["session"] + .as_str() + .unwrap() + .to_owned(); + let view = h.runtime.live.queue.views.get(&session).unwrap(); + let history = vec![json!({"role":"assistant","text":"\u{1}".repeat(1024)}); 130]; + let revision = { + let mut p = view.lock().unwrap(); + p.page(1, (0, 1, false), &history, true, false); + let first = p.read(0, 0, None); + assert_eq!(first["nextOffset"], 128); + first["revision"].clone() + }; + let frame = h.run("agents.projection", json!({"op":"read","session":session})); + assert!(frame["nextByte"].as_u64().unwrap() > 0); + { + let mut p = view.lock().unwrap(); + for _ in 0..2100 { + p.event(&json!({"kind":"notice","text":"live"})); + } + } + h.grant(&[]); + assert_eq!(h.refused("agents.projection",json!({"op":"chunk","session":session,"frame":frame["frame"],"offset":frame["nextByte"]})),"agentSessions.invalidPage"); + let page = view + .lock() + .unwrap() + .read(0, 128, Some(revision.as_u64().unwrap())); + assert!(page["rows"] + .as_array() + .unwrap() + .iter() + .all(|r| r["recorded"] != true)); +} + #[test] fn projected_disk_pages_survive_retry_and_are_purged_when_access_is_revoked() { let h = Harness::new("project-record", ALL_GRANTS); From 7978cbdc7a779209237ee4ddc44c5c9e773b7584 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 19:14:47 +0800 Subject: [PATCH 5/6] test(agents): use a platform-native provider profile path --- rust/crates/agent-runtime/src/tests/providers.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/rust/crates/agent-runtime/src/tests/providers.rs b/rust/crates/agent-runtime/src/tests/providers.rs index 8b192b6e..fa77425f 100644 --- a/rust/crates/agent-runtime/src/tests/providers.rs +++ b/rust/crates/agent-runtime/src/tests/providers.rs @@ -52,7 +52,8 @@ fn providers_read(params: &Value) -> Result { .as_array() .and_then(|files| files.iter().find(|file| file["id"] == "main")) .ok_or_else(|| failure("plugin.params.invalid"))?; - let config = read_json(Path::new(file["path"].as_str().unwrap())); + let config_path = Path::new(file["path"].as_str().unwrap()); + let config = read_json(config_path); let user = json!({ "layer": "user", "file": "main" }); let mut providers = vec![json!({ "id": "local", "name": "Local", "protocol": "chat", "builtIn": true @@ -92,7 +93,8 @@ fn providers_read(params: &Value) -> Result { .map(|(name, profile)| { let mut row = profile.clone(); row["name"] = json!(name); - row["source"] = json!({ "layer": "user", "path": "/etc/sample/profiles.json" }); + row["source"] = + json!({ "layer": "user", "path": config_path.with_file_name("profiles.json") }); row }) .collect() @@ -314,7 +316,8 @@ fn providers_are_read_with_their_sources_and_names_only() { ); assert_eq!(providers[2]["source"]["variable"], "BETA_BASE_URL"); assert_eq!( - agent["profiles"][0]["source"]["path"], "/etc/sample/profiles.json", + agent["profiles"][0]["source"]["path"], + path_text(&test.config_file().with_file_name("profiles.json")), "a path the plugin found is shown as written" ); assert_eq!(agent["environmentNames"], json!(["BETA_TOKEN"])); From b67ed19e7c6e45db0173000b9cedde07ba073dd5 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Wed, 2 Dec 2026 22:21:15 +0800 Subject: [PATCH 6/6] fix(agents): preserve message roles and full events for unprojected sessions --- rust/contracts/rust-core-api.md | 10 ++++-- rust/crates/agent-runtime/src/events.rs | 30 +++++++++++----- rust/crates/agent-runtime/src/live.rs | 25 ++++++++----- rust/crates/agent-runtime/src/projection.rs | 27 ++++++-------- .../agent-runtime/src/projection/command.rs | 10 ++++++ .../agent-runtime/src/projection/tests.rs | 36 +++++++++++++++++++ rust/crates/agent-runtime/src/tests.rs | 23 ++++++++++-- shared/plugins/contract/v1/README.md | 4 ++- .../plugins/reference/protocol-changelog.md | 1 + 9 files changed, 125 insertions(+), 41 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index beb5cd62..ef017935 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -9217,7 +9217,8 @@ publishing their sequence. Ordinary sends enter the projection before backend delivery completes. Failed delivery retracts the corresponding row. Existing hosts can continue to use the original event stream. Pass `compact: true` to `agents.waitEvents` to receive change notifications and required UI events -without streaming message and tool bodies a second time. Recovery delivery +without streaming message and tool bodies a second time. Sessions without an active projection, +including released views, deliver full event bodies even in compact mode. Recovery delivery and acknowledgements keep their existing semantics. Hosts drain through the header's `exitSequence` before they stop waiting for final recoveries. A compact wait can include `views`, a map of session IDs to installed revisions. Only events and recoveries for those sessions cross the boundary. Consecutive short text suffixes for one row then arrive in `inline[session]` with the new revision, @@ -9240,7 +9241,8 @@ A tool row retains its latest supplied `diff`, including a missing versus empty `oldText`. The per-text and aggregate retention limits also cover these diffs. When `agents.start` resumes a session with `projection: true`, it can pass `previousView` to keep the same agent's retained rows and their serials. -Earlier live turns then occupy historical turn numbers. Only rows read from disk carry +The resumed view keeps the upstream dropped-line count. Assistant replies and thoughts +with the same message ID remain distinct. Earlier live turns then occupy historical turn numbers. Only rows read from disk carry `recorded: true`. Clearing history or losing the read grant preserves earlier live turns and invalidates recorded data held by snapshots and response frames, even after row eviction. The old view remains owned by the caller until the new process starts successfully. @@ -9255,7 +9257,9 @@ revision. A header or file list in the response replaces its previous value. Absent optional row fields have their empty or false value. Row kinds 0 through 4 mean user input, assistant text, thought, tool and notice. `serial` identifies a retained row across index changes. The original input identified by `opening` is eligible for retry when the row's `retryable` and the -header's `canPrompt` are true. Pass its `retrySerial` to `agents.prompt`. +header's `canPrompt` are true. Pass its `retrySerial` to `agents.prompt` in +`send` mode. Other modes return `agents.invalidInputMode`. An unavailable opening +prompt or a mismatch in its serial, text or attachments returns `agents.retryUnavailable`. A prompt whose original UTF-8 text exceeds the retention limit is ineligible for retry. On process exit, `header.exit.stderrTail` carries the bounded CLI diagnostic tail. Draft text, pending paste operations and native request progress remain local. diff --git a/rust/crates/agent-runtime/src/events.rs b/rust/crates/agent-runtime/src/events.rs index 09a33d5b..e66e669e 100644 --- a/rust/crates/agent-runtime/src/events.rs +++ b/rust/crates/agent-runtime/src/events.rs @@ -1001,6 +1001,16 @@ impl EventQueue { .unwrap_or_else(PoisonError::into_inner) .0; } + // A session may have released its view while the wait was asleep. Full event + // bodies remain its only way to receive an actionable permission or question. + let projected = if compact { + drop(state); + let ids = self.views.session_ids(); + state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + Some(ids) + } else { + None + }; let missed = after < state.dropped_through; let mut events: Vec<&HostEvent> = state .events @@ -1032,18 +1042,20 @@ impl EventQueue { .collect(); let mut recoveries = recoveries; recoveries.sort_by_key(|event| event.sequence); - if compact { + if let Some(projected) = projected { let events: Vec<_> = events .iter() .map(|e| { - if matches!( - e.kind.as_str(), - "inputResolved" - | "interactionFailed" - | "questionAnswered" - | "turnStarted" - | "turnEnded" - ) { + if !projected.contains(&e.session) + || matches!( + e.kind.as_str(), + "inputResolved" + | "interactionFailed" + | "questionAnswered" + | "turnStarted" + | "turnEnded" + ) + { json!(e) } else { json!({"session":e.session,"sequence":e.sequence,"event":{"kind":e.kind}}) diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index 002bf2cb..36c747f6 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -1117,7 +1117,21 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, payload: Value) -> Result { let id = text(e, "messageID"); + let role = if e["role"] == "thought" { + THOUGHT + } else { + ASSISTANT + }; let data = text(e, "text"); - if let Some(&at) = self.index.get(&(false, ASSISTANT, id.into())) { + if let Some(&at) = self.index.get(&(false, role, id.into())) { let row = &mut self.rows[at]; let before = row.text.len(); if e["delta"] == true { @@ -459,11 +456,7 @@ impl Projection { self.bytes = self.bytes - before + row.text.len(); } else { let at = self.append(Row { - kind: if e["role"] == "thought" { - THOUGHT - } else { - ASSISTANT - }, + kind: role, turn, id: id.into(), text: prefix(data, MAX_TEXT).into(), diff --git a/rust/crates/agent-runtime/src/projection/command.rs b/rust/crates/agent-runtime/src/projection/command.rs index 0456a2db..22acaf80 100644 --- a/rust/crates/agent-runtime/src/projection/command.rs +++ b/rust/crates/agent-runtime/src/projection/command.rs @@ -93,6 +93,16 @@ impl Views { .cloned() } + /// Capture view membership after a long poll without nesting the registry and event locks. + pub(crate) fn session_ids(&self) -> std::collections::HashSet { + self.sessions + .lock() + .unwrap_or_else(PoisonError::into_inner) + .keys() + .cloned() + .collect() + } + pub(crate) fn release(&self, session: &str) { self.sessions .lock() diff --git a/rust/crates/agent-runtime/src/projection/tests.rs b/rust/crates/agent-runtime/src/projection/tests.rs index 022dd697..a493eb7c 100644 --- a/rust/crates/agent-runtime/src/projection/tests.rs +++ b/rust/crates/agent-runtime/src/projection/tests.rs @@ -183,7 +183,12 @@ fn resumed_view_keeps_loaded_rows_with_fresh_live_turn_numbers() { source.event(&json!({"kind":"promptDispatched","turn":1,"content":{"text":"previous"}})); let mut next = Projection::new(); let mut revoked = Projection::new(); + source.event(&json!({"kind":"outputLineDropped"})); revoked.resume_rows(&source, false); + assert_eq!( + revoked.read(0, 0, None)["dropped"], + source.read(0, 0, None)["dropped"] + ); assert_eq!(revoked.rows.len(), 1); assert_eq!(revoked.rows[0].text, "previous"); next.resume_rows(&source, true); @@ -282,3 +287,34 @@ fn tool_location_bytes_are_bounded_and_paths_remain_whole() { assert!(locations.iter().any(|v| v["path"] == loc.path)); } } + +#[test] +fn messages_with_the_same_id_remain_distinct_by_role() { + let mut p = Projection::new(); + for (role, data, delta) in [ + ("thought", "think", false), + ("assistant", "answer", false), + ("thought", "!", true), + ("assistant", ".", true), + ] { + p.event(&json!({"kind":"message","turn":1,"role":role,"messageID":"same","text":data,"delta":delta})); + } + let page = [ + json!({"role":"thought","id":"same","text":"old thought"}), + json!({"role":"assistant","id":"same","text":"old reply"}), + ]; + p.history(&page, true, false, false); + p.history(&page, true, false, false); + assert_eq!( + p.rows + .iter() + .map(|r| (r.kind, r.text.as_str())) + .collect::>(), + [ + (THOUGHT, "old thought"), + (ASSISTANT, "old reply"), + (THOUGHT, "think!"), + (ASSISTANT, "answer.") + ] + ); +} diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 78940d8c..74760dfb 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -800,7 +800,17 @@ fn compact_wait_scopes_events_to_the_requesting_window() { ); assert_eq!(reply["next"], 2); assert_eq!(reply["events"].as_array().unwrap().len(), 1); - assert_eq!(reply["events"][0]["session"], "shown"); + assert_eq!(reply["events"][0]["event"]["text"], "shown"); + let q = &h.runtime.live.queue; + q.views + .open_live("shown", AGENT_KEY.into(), "", None, &h.runtime.catalog); + q.push("shown", json!({"kind":"notice","text":"projected"})); + let all = h.run("agents.waitEvents", json!({"compact":true})); + assert_eq!(all["events"][1]["event"]["text"], "other"); + assert_eq!(all["events"][2]["event"], json!({"kind":"notice"})); + q.views.release("shown"); + let released = h.run("agents.waitEvents", json!({"compact":true,"after":2})); + assert_eq!(released["events"][0]["event"]["text"], "projected"); assert!( h.run("agents.waitEvents", json!({"compact":true,"views":{}}))["events"] .as_array() @@ -824,6 +834,15 @@ fn projected_session_reads_accepted_rows_before_replay_and_validates_retries() { {"kind":"message","role":"assistant","messageID":"r","turn":1,"text":"A"}, {"kind":"permissionRequested","turn":1,"permission":"p","title":"Read?","options":[{"id":"yes","label":"Yes","optionKind":"allowOnce"}]} ])).unwrap(); + for mode in ["queue", "steer", "invalid"] { + assert_eq!( + h.refused( + "agents.prompt", + json!({"session":session,"retrySerial":1,"text":"Inspect","mode":mode}) + ), + "agents.invalidInputMode" + ); + } let initial = h.run("agents.projection", read(0)); let serial = &initial["rows"][0]["serial"]; assert_eq!(initial["rows"][0]["text"], "Inspect"); @@ -849,7 +868,7 @@ fn projected_session_reads_accepted_rows_before_replay_and_validates_retries() { "agents.prompt", json!({"session":session,"retrySerial":serial,"text":"Changed"}) ), - "agents.invalidPrompt" + "agents.retryUnavailable" ); assert_eq!( h.run( diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 0f1fa21e..3f75e5d2 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3843,7 +3843,9 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. - `agents.prompt` takes at most 1 MiB of text, which may be empty only when the prompt carries attachments (`agents.invalidPrompt`), and refuses a second `send` while one runs (`agents.turnInProgress`). `mode` defaults - to `send`; other modes are defined below. `attachments` is + to `send`; other modes are defined below. A host retry may include `retrySerial` only + in `send` mode (`agents.invalidInputMode`). It must match the retained, retryable + opening prompt, including its text and attachment paths (`agents.retryUnavailable`). `attachments` is the files, folders and images the user picked, pasted or dropped, in the user's order: at most 64 `{path}` (`agents.tooManyAttachments`), each an absolute path to an existing file or directory diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 8554ae83..0738e86c 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -20,6 +20,7 @@ | --- | --- | --- | --- | --- | | [#249](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/249)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 在 #248 的 `configuration.providers` 上补充密钥写入、Lithe 保存的供应商列表和备份恢复。`providers` 新增可选 `listKeptBy`(`cli` / `lithe`,默认 `cli`)。密钥只写不读:`agentProviders.apply` 的 `addProvider`/`updateProvider` 可带 `key`(1–1024 字节,无控制字符和换行,否则 `agentProviders.invalidKey`),`updateProvider` 可带 `clearKey`(不能与 `key` 同时给);Core 只在内存里把它交给插件的 `edit`,不写日志、不进错误信息,快照的供应商只回答 `keySet`。`listKeptBy` 为 `lithe` 时(CLI 配置只能放一个自定义端点),Core 在资源库目录的 `saved-providers.json` 保存用户的供应商列表(不含密钥),插件用已有的 `lithe/host/credentials/*` 存密钥;修改带 `active` 与 `setProvider` 的 `provider`,供应商可带 `model`;快照的供应商增加 `saved`、`origin`、`model`,每个 Agent 增加 `listKeptBy`;Core 先存列表再调插件,失败时恢复列表。`apply` 替换文件前先备份到资源库目录的 `backups/`(自上次恢复以来第一次修改前的原样,加最近 20 份历史;可能含密钥,只在本机、仅所有者可读,不发给插件、不经接口回答),快照增加 `backup {savedAtMs, modifiedSince}`。新增宿主命令 `agentProviders.restore {agent, discardLaterChanges?}`(只接受用户发起)。新增错误码 `agentProviders.invalidKey`、`endpointExists`、`activeProvider`、`backupFailed`、`noBackup`、`changedSinceApply`、`restoreFailed`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.restore_applied`、`restore_failed`。旧 Core 把 `listKeptBy`、`key`、`clearKey` 当未知字段拒绝,不认识 `agentProviders.restore`。没有新增插件可调用的宿主方法、通知或能力版本。 | | [#248](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/248)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | Agent 配置新增可选 `configuration.providers {read, edit?, operations?}`:插件函数 `read` 回答模型与模型供应商快照(格式 `litheAgentProviders`),`edit` 在暂存副本上应用一项修改(格式 `litheAgentProvidersEdit`),Core 应用后重新读取确认。`operations` 从 `addProvider`、`updateProvider`、`removeProvider`、`setProviderEnabled`、`setModel`、`setProvider`、`setProfile` 中声明,未声明的操作以 `agentProviders.unsupportedOperation` 拒绝。Core 执行隐私规则:环境变量和密钥只回答名称,地址去掉 userinfo、查询和片段,名称、数量和长度设上限;插件不得读取凭据文件和钥匙串;设置里的端点环境变量(BASE_URL 一类)作为供应商的 `baseUrl` 回答,其他环境变量只给名称。新增宿主命令 `agentProviders.read`、`agentProviders.apply`,错误码 `agentProviders.*`(见契约 [Models and providers](../contract/v1/README.md#models-and-providers)),日志事件 `agent.providers.read_finished`、`read_failed`、`change_applied`、`change_failed`。宿主命令 `agentLibrary.read` 新增可选 `query`、`agent`、`presence`、`sort`,回答在有筛选时增加 `matches`,新错误码 `agentLibrary.invalidFilter`;不带参数时行为不变。声明 `providers` 时配置 `read` 可省略,权限沿用 `agents.configuration`。旧 Core 把 `providers` 当未知字段拒绝清单,把新筛选参数当未知字段拒绝。同时修正 Agent 日志里耗时字段名,使 `duration_ms` 不再被丢弃。样例见 `fixtures/agents/agents.plugin.json` 和 `fixtures/manifest/invalid-manifests.json`。没有新增插件可调用的宿主方法、通知或能力版本。 | +| [#247](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/247)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 宿主命令说明 | 补充 `agents.prompt` 重试的发送模式、原始提示词校验和拒绝原因。 | | [#246](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/246)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | `toolCall` 事件新增可选 `command`:`execute` 调用实际运行的命令行(1 字节到 1 MiB),此时 `title` 写这条命令要做什么(例如 CLI 给的描述),宿主把标题作为步骤标题、命令放进命令卡片,没有 `command` 时只用标题。`didStart` 新增 `toolCommands: true`,后端只在看到它时才发送 `command`;旧 Core 的 `toolCall` 严格解码,收到 `command` 会拒绝整批报告。会话来源 `read` 函数新增可选请求参数 `toolCommands`,`agentSessions.page` 随 `toolCalls` 一起发送,只有这时 `tool` 消息才可带 `command`,否则以 `agentSessions.invalidRead` 拒绝。四语 SDK 的 `AgentSessionStart` 新增 `toolCommands`(Rust `tool_commands`、Go `ToolCommands`、Java `toolCommands()`、Node `toolCommands`);记录读取仍是普通 JSON 函数,无类型变化。没有新增宿主方法、错误码或能力版本。样例见 `fixtures/agents/native-session.json` 与 `fixtures/agents/record-read.json`。 | | [#245](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/245)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.stats` 新增可选 `splitBy`(`agent`/`model`/`provider`/`modelProvider`,在 `groupBy` 之后再拆一层,第二个键在 summary 的 `split`)、筛选 `models`、`providers`、`failed`、`search`(同时作用于 `summaries` 和 `speeds`)和 `detail`(每组增加 `speed` 速度中位数与 `firstToken` 平均首字耗时);`groupBy` 新增只给宿主的 `provider`、`modelProvider`、`all`。`agentSessions.calls` 新增 `models`、`providers`、`search`,与 stats 的筛选规则相同。新增错误码 `agentSessions.invalidSplit`、`agentSessions.invalidFilter`。`agents/usage`(插件)的分组和回答不变。旧 Core 把新字段当未知字段拒绝,把新分组名当 `agentSessions.invalidGroup` 拒绝。没有新增宿主方法、通知或能力版本。 | | [#241](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/241)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.search` 的命中新增 `generation` 和 `readBytes`,都是命中所在文件(可能是子代理文件)的值,宿主据此从命中处用 `agentSessions.page` 分页读取该文件。旧 Core 不回答这两个字段。没有新增宿主方法、通知、错误码或能力版本。 |