From 15c07178f726ff70afee21599ab0b47db55dfd8b Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 00:51:24 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(agents):=20=E6=8C=89=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E8=A1=8C=E5=8F=8C=E5=90=91=E5=88=86=E9=A1=B5=E8=AF=BB=E5=8F=96?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=8E=86=E5=8F=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 31 +++ rust/crates/agent-runtime/src/lib.rs | 2 + rust/crates/agent-runtime/src/records.rs | 222 +++++++++++++++++- rust/crates/agent-runtime/src/tests.rs | 205 ++++++++++++++++ rust/crates/core/src/protocol/command.rs | 4 + rust/fixtures/agents/record-page-v1.json | 10 + shared/plugins/contract/v1/README.md | 16 +- .../v1/fixtures/agents/record-read.json | 11 + shared/plugins/reference/domains/agents.md | 1 + .../plugins/reference/protocol-changelog.md | 1 + 10 files changed, 497 insertions(+), 6 deletions(-) create mode 100644 rust/fixtures/agents/record-page-v1.json create mode 100644 shared/plugins/contract/v1/fixtures/agents/record-read.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 59fc5f66..66332710 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -496,6 +496,7 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.list` | List a page of recorded agent sessions by directory and order, with their activity and the whole list's counts, or find one by its ID | | `agentSessions.search` | Search recorded agent session text | | `agentSessions.read` | Read one recorded range as messages and where the next page starts | +| `agentSessions.page` | Read a bounded whole-line window before or after a recorded byte cursor, growing only for a long source line | | `agentSessions.stats` | Sum recorded agent usage with the latest rate limits | | `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | | `agentLibrary.configure` | Open the agent library in the platform's application data | @@ -9180,3 +9181,33 @@ retained history. Unknown operations/fields and malformed projection input fail with `invalid_request`. This hot path is excluded from request tracing; its text may contain secrets. Public backend methods and lifecycle are specified in the [plugin contract](../../shared/plugins/contract/v1/README.md#workflow-host-methods). + +### Recorded conversation windows + +`agentSessions.page` takes `{agent, path, size, cursor, direction}` for a readable +agent. `size` is a listed session's nonzero `readBytes` snapshot; empty sessions +need no page request. `direction` is `before` +or `after`, and `cursor` is zero, `size`, or a whole-line boundary previously +returned by Core. The answer is `{changed, tooLong, start, end, messages}`. +A nonempty source window advances in the requested direction even when no +message was found; use `start` to read older content and `end` for newer content. +An exhausted edge returns `start == end == cursor`. A zero size, invalid direction or an +interior cursor refuses with `agentSessions.invalidPage`; existing read grants, +source ownership and cached-file revision checks apply. + +Core starts with 256 KiB of source, grows up to 16 MiB only when one line needs +it, and passes whole lines to the existing backend `read` function in batches +of at most 128 lines or about 64 KiB (a single long line is kept whole). The +encoded messages of a page are bounded to 768 KiB and 2048 messages, except +that the first complete batch is retained when it exceeds the page budget +while still fitting the backend result bound. A rejected next batch is read +again on the next page. `tooLong` stops a window that cannot advance within +the source bound. File replacement or truncation answers `changed` with no +messages; append-only growth beyond `size` stays outside the snapshot. Hosts +keep a bounded set of pages and reread evicted windows rather than truncating +long conversations. The backend `read` request includes `messageIDs: true`; +only then may a backend return the optional message `id`, an opaque source +identity for mirrors. Deduplicate it within the same agent, session and source +snapshot. The original read and title requests omit this flag, preserving the +strict message shape understood by older Core versions. See the executable +examples in [`record-page-v1.json`](../fixtures/agents/record-page-v1.json). diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 1ceaa170..0a25a43b 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -81,6 +81,7 @@ pub const AGENT_SESSION_COMMANDS: &[&str] = &[ "agentSessions.list", "agentSessions.search", "agentSessions.read", + "agentSessions.page", "agentSessions.stats", "agentSessions.calls", ]; @@ -147,6 +148,7 @@ impl Runtime { "agentSessions.list" => self.records.list(self, payload), "agentSessions.search" => self.records.search(self, payload), "agentSessions.read" => self.records.read(self, payload), + "agentSessions.page" => self.records.page(self, payload), "agentSessions.stats" => self.records.stats(self, payload), "agentSessions.calls" => self.records.calls(self, payload), "agentLibrary.configure" => self.library.configure(payload), diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index ed539be9..8dbb5935 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -23,7 +23,7 @@ use lithe_agent_sessions::stats::{call_speed, model_name, GroupBy, SpeedRanker, use lithe_agent_sessions::{ discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES, - MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, + MAX_READ_BYTES, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, }; use lithe_lsp_engine::agent_host::AgentHostFailure; use lithe_plugin_agents::SessionSourceDeclaration; @@ -49,6 +49,14 @@ const MAX_TITLE_BYTES: usize = 512; /// Most messages one read item returns. const MAX_MESSAGES_PER_ITEM: usize = 2048; +/// Initial source window of a recorded page, grown only for a long line. +const RECORD_PAGE_BYTES: u64 = 256 * 1024; +/// Source bytes and lines of a single plugin read batch. +const RECORD_BATCH_BYTES: usize = 64 * 1024; +const RECORD_BATCH_LINES: usize = 128; +/// Encoded message budget of a recorded page. +const RECORD_RESULT_BYTES: usize = 768 * 1024; + /// Longest text of one read message, in bytes. const MAX_MESSAGE_TEXT_BYTES: usize = 1024 * 1024; @@ -488,6 +496,7 @@ impl Records { &sources[source].source, "titles", items, + false, ) else { continue; }; @@ -628,6 +637,7 @@ impl Records { &sources[source].source, "messages", items, + false, )?; let messages = answers .into_iter() @@ -638,6 +648,200 @@ impl Records { Ok(json!({ "changed": false, "messages": messages, "end": end })) } + /// `agentSessions.page`: a bounded window before or after a whole-line cursor. + /// 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(rename_all = "camelCase", deny_unknown_fields)] + struct PageRequest { + agent: String, + path: String, + size: u64, + cursor: u64, + direction: String, + } + let request: PageRequest = crate::decode(payload)?; + let invalid = || { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidPage", + "The session page or direction is invalid.", + ) + }; + if request.size == 0 + || request.cursor > request.size + || !matches!(request.direction.as_str(), "before" | "after") + { + return Err(invalid()); + } + let before = request.direction == "before"; + let config = self.config().ok_or_else(not_configured)?; + let (plugin_id, agent_id) = split_record_key(&request.agent).ok_or_else(invalid)?; + let agent = readable_agent(runtime, plugin_id, agent_id)?; + let sources = rooted_sources(&agent, &config); + let source = source_index(&sources, Path::new(&request.path)).ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.outsideSources", + "The file is not in a session directory of the agent.", + ) + })?; + let empty = |changed: bool, too_long: bool| json!({ "changed": changed, "tooLong": too_long, "start": request.cursor, "end": request.cursor, "messages": [] }); + // Validate the snapshot even for an exhausted edge. A cursor inside a line cannot + // silently discard that line; callers must use the boundaries returned by Core. + if request.size > 0 { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + if store + .read_range( + &request.agent, + &request.path, + ByteRange { + start: request.size - 1, + end: request.size, + }, + )? + .is_none() + { + return Ok(empty(true, false)); + } + if request.cursor > 0 && request.cursor < request.size { + let preceding = store.read_range( + &request.agent, + &request.path, + ByteRange { + start: request.cursor - 1, + end: request.cursor, + }, + )?; + match preceding { + None => return Ok(empty(true, false)), + Some(byte) if byte != b"\n" => return Err(invalid()), + _ => {} + } + } + } + if (before && request.cursor == 0) || (!before && request.cursor == request.size) { + return Ok(empty(false, false)); + } + let mut span = RECORD_PAGE_BYTES; + let (start, bytes) = loop { + let start = if before { + request.cursor.saturating_sub(span) + } else { + request.cursor + }; + let end = if before { + request.cursor + } else { + request.cursor.saturating_add(span).min(request.size) + }; + let (bytes, preceding) = { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + let bytes = + store.read_range(&request.agent, &request.path, ByteRange { start, end })?; + let preceding = if before && start > 0 { + store.read_range( + &request.agent, + &request.path, + ByteRange { + start: start - 1, + end: start, + }, + )? + } else { + Some(Vec::new()) + }; + (bytes, preceding) + }; + let (Some(mut bytes), Some(preceding)) = (bytes, preceding) else { + return Ok(empty(true, false)); + }; + let mut aligned = start; + if before && start > 0 && preceding != b"\n" { + let skip = bytes + .iter() + .position(|byte| *byte == b'\n') + .map_or(bytes.len(), |index| index + 1); + bytes.drain(..skip); + aligned += skip as u64; + } else if !before && end < request.size && bytes.last() != Some(&b'\n') { + bytes.truncate(whole_lines(&bytes)); + } + if !bytes.is_empty() { + break (aligned, bytes); + } + if span >= MAX_READ_BYTES || (!before && end == request.size) || (before && start == 0) + { + return Ok(empty(false, true)); + } + span = (span * 4).min(MAX_READ_BYTES); + }; + // Small batches keep a backend's encoded answer below its function limit. + // Accept batches atomically, so no message can be skipped at a page boundary. + let mut groups = Vec::new(); + let mut group_start = 0; + let mut lines = 0; + for (index, byte) in bytes.iter().enumerate() { + if *byte == b'\n' { + lines += 1; + if index + 1 - group_start >= RECORD_BATCH_BYTES || lines >= RECORD_BATCH_LINES { + groups.push((group_start, index + 1)); + group_start = index + 1; + lines = 0; + } + } + } + if group_start < bytes.len() { + groups.push((group_start, bytes.len())); + } + if before { + groups.reverse(); + } + let mut collected = VecDeque::new(); + let mut total = 0; + let mut count = 0; + let (mut from, mut to) = if before { + (bytes.len(), bytes.len()) + } else { + (0, 0) + }; + for (low, high) in groups { + 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!({})))?; + let size = + serde_json::to_vec(&messages).map_or(RECORD_RESULT_BYTES + 1, |data| data.len()); + if count > 0 + && (total + size > RECORD_RESULT_BYTES + || count + messages.len() > MAX_MESSAGES_PER_ITEM) + { + break; + } + 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(); + Ok( + json!({ "changed": false, "tooLong": false, "start": start + from as u64, "end": start + to as u64, "messages": messages }), + ) + } + /// `agentSessions.stats`: usage of the readable agents for the host. pub fn stats(&self, runtime: &Runtime, payload: Value) -> Result { #[derive(Deserialize)] @@ -838,7 +1042,7 @@ impl Records { return Err(AgentHostFailure::new( codes::HOST_BUSY, "The session records are busy; try again shortly.", - )) + )); } }; let Some(store) = reader.as_ref() else { @@ -1161,15 +1365,21 @@ fn call_read( source: &SessionSourceDeclaration, mode: &str, items: Vec, + message_ids: bool, ) -> Result, CoreError> { let backend = backend_for(link, &agent.plugin_id, &source.read)?; let count = items.len(); - let params = json!({ + let mut params = json!({ "agentID": agent.agent.id, "sourceID": source.id, "mode": mode, "items": items, }); + // Older hosts reject unknown message fields. Backends emit IDs only when the + // caller explicitly asks for them; ordinary reads keep the original wire shape. + if message_ids { + params["messageIDs"] = true.into(); + } let answer = link .call( &backend, @@ -1219,6 +1429,9 @@ struct ReadMessage { /// `user`, `assistant`, `thought` or `tool`. role: String, text: String, + /// An optional opaque identity shared by mirrored records in the source file. + #[serde(default, skip_serializing_if = "Option::is_none")] + id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] at_ms: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1247,6 +1460,9 @@ fn decode_messages(item: Value) -> Result, CoreError> { message.role.as_str(), "user" | "assistant" | "thought" | "tool" ) && message.text.len() <= MAX_MESSAGE_TEXT_BYTES + && message.id.as_deref().is_none_or(|id| { + !id.is_empty() && id.len() <= 256 && id.bytes().all(|b| b.is_ascii_graphic()) + }) && message .tool_name .as_deref() diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 038589bd..72fd0283 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1837,3 +1837,208 @@ fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { } mod library; + +#[test] +fn records_pages_walk_both_directions_without_cutting_or_dropping_lines() { + let harness = Harness::new("record-pages", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + let mut text = fs::read_to_string(&file).unwrap(); + for n in 0..12 { + text.push_str(&json!({ "type": "user", "session": "s1", "at": 1_795_824_000_000_i64, "text": format!("{n}:{}", "x".repeat(40_000)) }).to_string()); + text.push('\n'); + } + fs::write(&file, &text).unwrap(); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let size = text.len() as u64; + let page = |direction: &str, cursor: u64| { + harness.run( + "agentSessions.page", + json!({ + "agent": AGENT_KEY, "path": path_text(&file), "size": size, + "direction": direction, "cursor": cursor + }), + ) + }; + let last = page("before", size); + assert_eq!(last["end"], size, "{last}"); + assert!(last["start"].as_u64().unwrap() > 0); + assert!(last["messages"].as_array().unwrap().last().unwrap()["text"] + .as_str() + .unwrap() + .starts_with("11:")); + let mut cursor = 0; + let mut texts = Vec::new(); + while cursor < size { + let next = page("after", cursor); + assert_eq!(next["start"], cursor); + let end = next["end"].as_u64().unwrap(); + assert!(end > cursor, "a page must advance"); + texts.extend( + next["messages"] + .as_array() + .unwrap() + .iter() + .map(|m| m["text"].as_str().unwrap().to_string()), + ); + cursor = end; + } + assert_eq!(texts.len(), 13); + for (n, value) in texts.iter().skip(1).enumerate() { + assert!(value.starts_with(&format!("{n}:"))); + } + let previous = page("before", last["start"].as_u64().unwrap()); + assert_eq!(previous["end"], last["start"]); + assert_eq!(harness.refused("agentSessions.page", json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "direction": "sideways", "cursor": 0 })), "agentSessions.invalidPage"); +} + +#[test] +fn records_pages_grow_for_a_long_line_and_reject_stale_or_unreadable_sources() { + let harness = Harness::new("record-long-page", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + let mut text = fs::read_to_string(&file).unwrap(); + let start = text.len() as u64; + text.push_str( + &json!({ "type": "user", "session": "s1", "text": "x".repeat(600_000) }).to_string(), + ); + text.push('\n'); + fs::write(&file, &text).unwrap(); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let size = text.len() as u64; + let request = |direction: &str, cursor: u64| { + json!({ + "agent": AGENT_KEY, "path": path_text(&file), "size": size, + "direction": direction, "cursor": cursor + }) + }; + for (direction, cursor) in [("after", start), ("before", size)] { + let page = harness.run("agentSessions.page", request(direction, cursor)); + assert_eq!(page["end"], size, "{page}"); + assert_eq!( + page["messages"].as_array().unwrap().last().unwrap()["text"] + .as_str() + .unwrap() + .len(), + 600_000 + ); + } + let exhausted = harness.run("agentSessions.page", request("after", size)); + assert_eq!(exhausted["start"], exhausted["end"]); + assert_eq!(exhausted["tooLong"], false); + assert_eq!( + harness.refused("agentSessions.page", request("after", start + 1)), + "agentSessions.invalidPage" + ); + let mut empty = request("after", 0); + empty["size"] = 0.into(); + assert_eq!( + harness.refused("agentSessions.page", empty), + "agentSessions.invalidPage" + ); + fs::write(&file, b"replaced\n").unwrap(); + let changed = harness.run("agentSessions.page", request("before", size)); + assert_eq!(changed["changed"], true); + assert_eq!(changed["messages"], json!([])); + harness.grant(&["backend.launch", "agents.native", "agents.run"]); + assert_eq!( + harness.refused("agentSessions.page", request("before", size)), + "agentSessions.readNotGranted" + ); +} + +#[test] +fn records_page_message_ids_are_opt_in_and_validated() { + let harness = Harness::new("record-message-ids", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + harness.link.set_answer(|function, params| { + if function == "sessions.read" && params["mode"] == "messages" { + assert_eq!(params["messageIDs"], true); + let mut answer = read(params); + for message in answer["items"][0]["messages"].as_array_mut().unwrap() { + message["id"] = "source-message-1".into(); + } + Ok(answer) + } else { + sample_backend(function, params) + } + }); + let request = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": fs::metadata(&file).unwrap().len(), "cursor": 0, "direction": "after" }); + let page = harness.run("agentSessions.page", request.clone()); + assert_eq!(page["messages"][0]["id"], "source-message-1"); + for id in ["", "bad id", "\n", &"x".repeat(257)] { + let id = id.to_string(); + harness.link.set_answer(move |_, _| { + Ok(json!({ "items": [{ "messages": [{ "role": "user", "text": "text", "id": id }] }] })) + }); + assert_eq!( + harness.refused("agentSessions.page", request.clone()), + "agentSessions.invalidRead" + ); + } +} + +#[test] +fn records_page_contract_examples_match_the_runtime() { + let fixture: Value = + serde_json::from_str(include_str!("../../../fixtures/agents/record-page-v1.json")).unwrap(); + let read_fixture: Value = serde_json::from_str(include_str!( + "../../../../shared/plugins/contract/v1/fixtures/agents/record-read.json" + )) + .unwrap(); + let harness = Harness::new("record-contract", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + harness.run( + "agentSessions.sync", + json!({"pluginID": PLUGIN, "agentID": AGENT}), + ); + let size = fs::metadata(&file).unwrap().len(); + for case in fixture["cases"].as_array().unwrap() { + let cursor = if case["cursor"] == 0 { 0 } else { size }; + let page = harness.run( + "agentSessions.page", + json!({ + "agent": AGENT_KEY, "path": path_text(&file), "size": size, + "cursor": cursor, "direction": case["direction"] + }), + ); + for field in ["start", "end"] { + let expected = if case[field] == 0 { 0 } else { size }; + assert_eq!(page[field], expected); + } + for field in fixture["responseFields"].as_array().unwrap() { + assert!(page.get(field.as_str().unwrap()).is_some()); + } + } + for mode in ["legacy", "withIDs"] { + let answer = read_fixture[mode]["result"].clone(); + let expects_ids = read_fixture[mode]["request"]["messageIDs"] == true; + harness.link.set_answer(move |_, params| { + assert_eq!(params["messageIDs"] == true, expects_ids); + Ok(answer.clone()) + }); + let command = if expects_ids { + "agentSessions.page" + } else { + "agentSessions.read" + }; + let request = if expects_ids { + json!({"agent": AGENT_KEY, "path": path_text(&file), "size": size, "cursor": 0, "direction": "after"}) + } else { + json!({"agent": AGENT_KEY, "path": path_text(&file), "range": {"start": 0, "end": size}}) + }; + let result = harness.run(command, request); + assert_eq!( + result["messages"], + read_fixture[mode]["result"]["items"][0]["messages"] + ); + } +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 2df08078..ac78c38b 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -254,6 +254,8 @@ pub enum AgentsCommand { RecordsSearch, /// Reads one recorded range as messages (`agentSessions.read`). RecordsRead, + /// Reads a bounded window before or after a session cursor (`agentSessions.page`). + RecordsPage, /// Sums recorded usage with the latest rate limits (`agentSessions.stats`). RecordsStats, /// Lists a page of recorded calls, most recent first (`agentSessions.calls`). @@ -292,6 +294,7 @@ impl AgentsCommand { Self::RecordsList => "agentSessions.list", Self::RecordsSearch => "agentSessions.search", Self::RecordsRead => "agentSessions.read", + Self::RecordsPage => "agentSessions.page", Self::RecordsStats => "agentSessions.stats", Self::RecordsCalls => "agentSessions.calls", Self::LibraryConfigure => "agentLibrary.configure", @@ -1296,6 +1299,7 @@ impl CoreCommand { "agentSessions.list" => Some(Self::Agents(AgentsCommand::RecordsList)), "agentSessions.search" => Some(Self::Agents(AgentsCommand::RecordsSearch)), "agentSessions.read" => Some(Self::Agents(AgentsCommand::RecordsRead)), + "agentSessions.page" => Some(Self::Agents(AgentsCommand::RecordsPage)), "agentSessions.stats" => Some(Self::Agents(AgentsCommand::RecordsStats)), "agentSessions.calls" => Some(Self::Agents(AgentsCommand::RecordsCalls)), "agentLibrary.configure" => Some(Self::Agents(AgentsCommand::LibraryConfigure)), diff --git a/rust/fixtures/agents/record-page-v1.json b/rust/fixtures/agents/record-page-v1.json new file mode 100644 index 00000000..c2a28200 --- /dev/null +++ b/rust/fixtures/agents/record-page-v1.json @@ -0,0 +1,10 @@ +{ + "description": "A whole-line recorded conversation window. Before reads end at the cursor; after reads start there; exhausted edges make no progress.", + "cases": [ + {"direction": "after", "cursor": 0, "start": 0, "end": 100}, + {"direction": "before", "cursor": 100, "start": 0, "end": 100}, + {"direction": "after", "cursor": 100, "start": 100, "end": 100}, + {"direction": "before", "cursor": 0, "start": 0, "end": 0} + ], + "responseFields": ["changed", "tooLong", "start", "end", "messages"] +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 882bac2e..8e7747b8 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4110,12 +4110,22 @@ state?}` and has 30 seconds. It answers: conversation text; - `rateLimits`: `{atMs, windows, plan?}`, the latest quota the file shows. -`read` receives `{agentID, sourceID, mode, items: [{path, lines}]}` and has +`read` receives `{agentID, sourceID, mode, messageIDs?, items: [{path, lines}]}` and has 15 seconds. It answers exactly `{items}`, one per request item: in `titles` mode `{title}` (cut to 512 bytes), in `messages` mode `{messages}`, at most -2048 `{role, text, atMs?, toolName?}` with `role` one of `user`, +2048 `{role, text, id?, atMs?, toolName?}` with `role` one of `user`, `assistant`, `thought` and `tool`, `text` at most 1 MiB and `toolName` 1–256 -bytes. +bytes. Optional `id` is 1–256 visible ASCII bytes, opaque to the host, stable +within the source session, and equal for mirrored representations of the same +message. Return it only when `messageIDs` is `true`; when absent or `false`, +omit every `id` so older Core revisions keep accepting the original shape. +Omit it when the format has no reliable identity. Hosts may use it to +remove mirrors across adjacent record pages; it does not identify a live turn. +This optional field remains within `agents` 0. Core's `agentSessions.page` +requests IDs; title reads and the original `agentSessions.read` do not. +Existing backends may ignore `messageIDs` and keep returning no IDs. This is +a normal plugin function in all four official SDKs; no new handler or SDK +version is required. Fixture: `fixtures/agents/record-read.json`. A summary is `{key, calls, failedCalls, compactionCalls, tokens: {input, output, cacheRead, cacheWrite5m, cacheWrite1h, reasoning}, cacheHitRate?, diff --git a/shared/plugins/contract/v1/fixtures/agents/record-read.json b/shared/plugins/contract/v1/fixtures/agents/record-read.json new file mode 100644 index 00000000..20283d16 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/record-read.json @@ -0,0 +1,11 @@ +{ + "description": "Record-read IDs are opt-in; ordinary function handlers in every SDK pass the JSON request and result unchanged.", + "legacy": { + "request": {"agentID": "sample", "sourceID": "sessions", "mode": "messages", "items": [{"path": "/work/session.jsonl", "lines": ["question"]}]}, + "result": {"items": [{"messages": [{"role": "user", "text": "question"}]}]} + }, + "withIDs": { + "request": {"agentID": "sample", "sourceID": "sessions", "mode": "messages", "messageIDs": true, "items": [{"path": "/work/session.jsonl", "lines": ["question"]}]}, + "result": {"items": [{"messages": [{"role": "user", "text": "question", "id": "source-1"}]}]} + } +} diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 102ebf8d..970c84c2 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -35,6 +35,7 @@ - Core 缓存记录,负责列表、全文搜索和统计;缓存不存正文,可以删除重建。 - `lithe/host/agents/usage` 按天、Agent 或模型汇总用户已开启记录的 Agent 的用量,并带上最近的额度窗口。它只给数字和模型名,不含对话正文、标题、会话 ID 或工作目录,适合做跨 Agent 的统计和额度面板。 - `agentSessions.calls` 按时间倒序分页列出 `scan` 报告的每一次调用,带所属 Agent 和调用本身(模型、令牌数等),以及 Core 算出的费用、缓存命中率和速度,供用量页的请求列表和详情使用;不含正文。 +- 连续浏览正文用 `agentSessions.page`,按返回的字节边界向前或向后读取。恢复会话前先同步并固定 `readBytes`,历史与新的会话事件分别保存,避免把旧提示误当成新轮次。Core 向普通 `read` 函数传 `messageIDs: true` 时,插件可返回稳定的消息 `id` 来识别同一消息的镜像;省略或为 `false` 时不得返回 `id`,保证旧 Core 仍接受原来的结果。没有稳定标识的格式省略 `id`,不按文本去重。四语 SDK 的普通 JSON 函数处理器直接支持这个可选参数。参见 [读取样例](../../contract/v1/fixtures/agents/record-read.json)。 ### 资源库:指令、技能、MCP 服务器与 Hooks diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 09204084..1fbd2449 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| 未创建(本地改动) | 未提交 | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,旧 `agentSessions.read` 和标题读取不协商。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;Core 修订、宿主发布和 PR 编号尚未产生。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | From 1727663330e7d64a7a5fa73ca7b5a66d9385d28d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 00:57:41 +0800 Subject: [PATCH 2/4] =?UTF-8?q?docs(agents):=20=E7=99=BB=E8=AE=B0=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E5=88=86=E9=A1=B5=E5=8D=8F=E8=AE=AE=20PR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1fbd2449..c5cc6fe1 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| 未创建(本地改动) | 未提交 | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,旧 `agentSessions.read` 和标题读取不协商。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;Core 修订、宿主发布和 PR 编号尚未产生。 | +| [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,旧 `agentSessions.read` 和标题读取不协商。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | From ed8615b5ab085f0054676f8f6a0726bc7f603293 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 11:03:12 +0800 Subject: [PATCH 3/4] =?UTF-8?q?feat(agents):=20=E8=AE=B0=E5=BD=95=E5=88=86?= =?UTF-8?q?=E9=A1=B5=E5=8F=AF=E5=B8=A6=E5=AE=9E=E6=97=B6=20toolCall=20?= =?UTF-8?q?=E8=AF=A6=E6=83=85=EF=BC=8C=E8=AE=A9=E5=8E=86=E5=8F=B2=E8=BD=AE?= =?UTF-8?q?=E6=AC=A1=E4=B8=8E=E5=AE=9E=E6=97=B6=E4=B8=80=E8=87=B4=EF=BC=88?= =?UTF-8?q?API-45=200=20=E5=86=85=E8=A1=A5=E5=85=85=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 5 +- rust/crates/agent-runtime/src/records.rs | 67 +++++++++++++++++++ rust/crates/agent-runtime/src/tests.rs | 38 +++++++++++ shared/plugins/contract/v1/README.md | 14 ++++ .../v1/fixtures/agents/record-read.json | 6 +- .../plugins/reference/protocol-changelog.md | 2 +- 6 files changed, 127 insertions(+), 5 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 66332710..0ebbe472 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -9209,5 +9209,8 @@ long conversations. The backend `read` request includes `messageIDs: true`; only then may a backend return the optional message `id`, an opaque source identity for mirrors. Deduplicate it within the same agent, session and source snapshot. The original read and title requests omit this flag, preserving the -strict message shape understood by older Core versions. See the executable +strict message shape understood by older Core versions. The page request also sends +`toolCalls: true`, which lets a `tool` message carry the live `toolCall` +details (`toolCallID`, `status`, `toolKind`, `title`, `locations`); Core checks +them against the live event's bounds. See the executable examples in [`record-page-v1.json`](../fixtures/agents/record-page-v1.json). diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 8dbb5935..f2906e62 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -1377,8 +1377,10 @@ fn call_read( }); // Older hosts reject unknown message fields. Backends emit IDs only when the // caller explicitly asks for them; ordinary reads keep the original wire shape. + // A page also asks for tool-call details, so recorded turns can show as live ones. if message_ids { params["messageIDs"] = true.into(); + params["toolCalls"] = true.into(); } let answer = link .call( @@ -1436,6 +1438,70 @@ struct ReadMessage { at_ms: Option, #[serde(default, skip_serializing_if = "Option::is_none")] tool_name: Option, + /// Tool-call details in the live `toolCall` shape, only when `toolCalls` was asked for. + /// Messages of one call share its ID: the call, then its result. + #[serde( + default, + rename = "toolCallID", + skip_serializing_if = "Option::is_none" + )] + tool_call_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + status: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + tool_kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + locations: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct ReadLocation { + path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + line: Option, +} + +const MAX_TOOL_LABEL_BYTES: usize = 1024; +const MAX_TOOL_LOCATIONS: usize = 64; + +/// Checks a message's tool-call details against the live `toolCall` event's bounds. +fn valid_tool_details(message: &ReadMessage) -> bool { + let label = |text: &str| !text.is_empty() && text.len() <= MAX_TOOL_LABEL_BYTES; + let details = message.tool_call_id.is_some() + || message.status.is_some() + || message.tool_kind.is_some() + || message.title.is_some() + || message.locations.is_some(); + if !details { + return true; + } + message.role == "tool" + && message.tool_call_id.as_deref().is_some_and(label) + && message.status.as_deref().is_none_or(|status| { + matches!(status, "pending" | "inProgress" | "completed" | "failed") + }) + && message.tool_kind.as_deref().is_none_or(|kind| { + matches!( + kind, + "read" + | "edit" + | "delete" + | "move" + | "search" + | "execute" + | "think" + | "fetch" + | "other" + ) + }) + && message.title.as_deref().is_none_or(label) + && message.locations.as_ref().is_none_or(|locations| { + locations.len() <= MAX_TOOL_LOCATIONS + && locations.iter().all(|location| label(&location.path)) + }) } #[derive(Deserialize)] @@ -1467,6 +1533,7 @@ fn decode_messages(item: Value) -> Result, CoreError> { .tool_name .as_deref() .is_none_or(|name| !name.is_empty() && name.len() <= 256) + && valid_tool_details(message) }); if valid { Ok(item.messages) diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 72fd0283..6e69b87d 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1962,6 +1962,7 @@ fn records_page_message_ids_are_opt_in_and_validated() { harness.link.set_answer(|function, params| { if function == "sessions.read" && params["mode"] == "messages" { assert_eq!(params["messageIDs"], true); + assert_eq!(params["toolCalls"], true); let mut answer = read(params); for message in answer["items"][0]["messages"].as_array_mut().unwrap() { message["id"] = "source-message-1".into(); @@ -1986,6 +1987,43 @@ fn records_page_message_ids_are_opt_in_and_validated() { } } +#[test] +fn records_page_tool_call_details_follow_the_live_bounds() { + let harness = Harness::new("record-tool-calls", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let request = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": fs::metadata(&file).unwrap().len(), "cursor": 0, "direction": "after" }); + let call = json!({ "role": "tool", "text": "", "toolName": "Read", "toolCallID": "call-1", + "status": "inProgress", "toolKind": "read", "title": "Read main.go", + "locations": [{ "path": "/work/main.go", "line": 3 }] }); + let result = json!({ "role": "tool", "text": "package main", "toolCallID": "call-1", "status": "completed" }); + let answer = json!({ "items": [{ "messages": [call, result] }] }); + harness.link.set_answer(move |_, _| Ok(answer.clone())); + let page = harness.run("agentSessions.page", request.clone()); + assert_eq!(page["messages"][0]["locations"][0]["line"], 3); + assert_eq!(page["messages"][1]["status"], "completed"); + let refused = [ + json!({ "role": "assistant", "text": "x", "toolCallID": "call-1" }), + json!({ "role": "tool", "text": "x", "status": "completed" }), + json!({ "role": "tool", "text": "x", "toolCallID": "call-1", "status": "done" }), + json!({ "role": "tool", "text": "x", "toolCallID": "call-1", "toolKind": "shell" }), + json!({ "role": "tool", "text": "x", "toolCallID": "", "title": "t" }), + json!({ "role": "tool", "text": "x", "toolCallID": "c", "locations": [{ "path": "" }] }), + ]; + for message in refused { + harness + .link + .set_answer(move |_, _| Ok(json!({ "items": [{ "messages": [message.clone()] }] }))); + assert_eq!( + harness.refused("agentSessions.page", request.clone()), + "agentSessions.invalidRead" + ); + } +} + #[test] fn records_page_contract_examples_match_the_runtime() { let fixture: Value = diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 8e7747b8..a28a9381 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4123,6 +4123,20 @@ Omit it when the format has no reliable identity. Hosts may use it to remove mirrors across adjacent record pages; it does not identify a live turn. This optional field remains within `agents` 0. Core's `agentSessions.page` requests IDs; title reads and the original `agentSessions.read` do not. + +`agentSessions.page` also sends `toolCalls: true`. Only then may a `tool` +message carry the live [`toolCall`](#native-sessions) details: `toolCallID` +(required with any other detail), `status` (`pending`, `inProgress`, +`completed`, `failed`), `toolKind` (`read`, `edit`, `delete`, `move`, +`search`, `execute`, `think`, `fetch`, `other`), `title` and `locations` +(at most 64 `{path, line?}`), labels and paths 1 byte to 1 KiB. A call and +its result are separate messages with the same `toolCallID`, in file order; +`text` holds the result's output. A host folds them into one tool call the +way it folds live `toolCall` updates, and starts a turn at each `user` +message, so a recorded turn shows like a live one. Details on another role, +or without `toolCallID`, are `agentSessions.invalidRead`. A backend +translates its records with the same mapping its live session uses. This +remains within `agents` 0; a backend that ignores `toolCalls` keeps working. Existing backends may ignore `messageIDs` and keep returning no IDs. This is a normal plugin function in all four official SDKs; no new handler or SDK version is required. Fixture: `fixtures/agents/record-read.json`. diff --git a/shared/plugins/contract/v1/fixtures/agents/record-read.json b/shared/plugins/contract/v1/fixtures/agents/record-read.json index 20283d16..1bd13969 100644 --- a/shared/plugins/contract/v1/fixtures/agents/record-read.json +++ b/shared/plugins/contract/v1/fixtures/agents/record-read.json @@ -1,11 +1,11 @@ { - "description": "Record-read IDs are opt-in; ordinary function handlers in every SDK pass the JSON request and result unchanged.", + "description": "Record-read IDs and tool-call details are opt-in; ordinary function handlers in every SDK pass the JSON request and result unchanged.", "legacy": { "request": {"agentID": "sample", "sourceID": "sessions", "mode": "messages", "items": [{"path": "/work/session.jsonl", "lines": ["question"]}]}, "result": {"items": [{"messages": [{"role": "user", "text": "question"}]}]} }, "withIDs": { - "request": {"agentID": "sample", "sourceID": "sessions", "mode": "messages", "messageIDs": true, "items": [{"path": "/work/session.jsonl", "lines": ["question"]}]}, - "result": {"items": [{"messages": [{"role": "user", "text": "question", "id": "source-1"}]}]} + "request": {"agentID": "sample", "sourceID": "sessions", "mode": "messages", "messageIDs": true, "toolCalls": true, "items": [{"path": "/work/session.jsonl", "lines": ["question"]}]}, + "result": {"items": [{"messages": [{"role": "user", "text": "question", "id": "source-1"}, {"role": "tool", "text": "", "id": "source-2", "toolName": "Read", "toolCallID": "call-1", "status": "inProgress", "toolKind": "read", "title": "Read main.go", "locations": [{"path": "/work/main.go", "line": 3}]}, {"role": "tool", "text": "package main", "id": "source-3", "toolCallID": "call-1", "status": "completed"}]}]} } } diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c5cc6fe1..5eb41ec8 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,旧 `agentSessions.read` 和标题读取不协商。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | +| [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。同时增加可选请求参数 `toolCalls`:只有 `true` 时 `tool` 消息才可带实时 `toolCall` 的详情 `toolCallID`、`status`、`toolKind`、`title`、`locations`(同一调用和它的结果共用 `toolCallID`,宿主按实时方式合并,让历史轮次和实时显示一致)。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,两个参数都由它发送,旧 `agentSessions.read` 和标题读取不协商。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | From 52a0e901cb3ad4c77be83c80fcc6ff692fe5b265 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 11:19:01 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(agents):=20=E6=8C=89=E8=AF=84=E5=AE=A1?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8E=86=E5=8F=B2=E5=88=86=E9=A1=B5=E7=9A=84?= =?UTF-8?q?=E4=B8=89=E5=A4=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 长行不再和前面的短行合成一批:加入后会超过约 64 KiB 的行另起一批, 避免合并后的回答超过 1 MiB 函数结果上限而让翻页失败 - 旧 agentSessions.read 不请求工具详情,回答里带详情字段(含显式 null) 时按 agentSessions.invalidRead 拒绝;只有 page 接受 - 会话缓存的文件新增 generation(缓存结构升到 2):文件被替换或截断后 重新读取时换新值;agentSessions.list 回答它,agentSessions.page 必须 带上,不一致时回答 changed,同长度替换也能识别 --- rust/contracts/rust-core-api.md | 17 +- rust/crates/agent-runtime/src/records.rs | 70 ++++++-- rust/crates/agent-runtime/src/tests.rs | 159 +++++++++++++++++- rust/crates/agent-sessions/src/store.rs | 41 ++++- rust/crates/agent-sessions/src/tests/store.rs | 11 +- shared/plugins/contract/v1/README.md | 5 + .../plugins/reference/protocol-changelog.md | 2 +- 7 files changed, 270 insertions(+), 35 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 0ebbe472..248ac68c 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -9184,9 +9184,9 @@ may contain secrets. Public backend methods and lifecycle are specified in the ### Recorded conversation windows -`agentSessions.page` takes `{agent, path, size, cursor, direction}` for a readable -agent. `size` is a listed session's nonzero `readBytes` snapshot; empty sessions -need no page request. `direction` is `before` +`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` or `after`, and `cursor` is zero, `size`, or a whole-line boundary previously returned by Core. The answer is `{changed, tooLong, start, end, messages}`. A nonempty source window advances in the requested direction even when no @@ -9197,13 +9197,16 @@ source ownership and cached-file revision checks apply. Core starts with 256 KiB of source, grows up to 16 MiB only when one line needs it, and passes whole lines to the existing backend `read` function in batches -of at most 128 lines or about 64 KiB (a single long line is kept whole). The +of at most 128 lines or about 64 KiB. A line that would take a nonempty batch past +64 KiB starts the next batch, so a long line is read alone and kept whole. The encoded messages of a page are bounded to 768 KiB and 2048 messages, except that the first complete batch is retained when it exceeds the page budget while still fitting the backend result bound. A rejected next batch is read again on the next page. `tooLong` stops a window that cannot advance within the source bound. File replacement or truncation answers `changed` with no -messages; append-only growth beyond `size` stays outside the snapshot. Hosts +messages: the cache reads such a file again under a new `generation`, and a page +whose `generation` is not the file's current one answers `changed` before reading, +even when the replacement has the same length; append-only growth beyond `size` stays outside the snapshot. Hosts keep a bounded set of pages and reread evicted windows rather than truncating long conversations. The backend `read` request includes `messageIDs: true`; only then may a backend return the optional message `id`, an opaque source @@ -9212,5 +9215,7 @@ snapshot. The original read and title requests omit this flag, preserving the strict message shape understood by older Core versions. The page request also sends `toolCalls: true`, which lets a `tool` message carry the live `toolCall` details (`toolCallID`, `status`, `toolKind`, `title`, `locations`); Core checks -them against the live event's bounds. See the executable +them against the live event's bounds. `agentSessions.read` does not ask for them +and refuses a reading that carries any of these fields, even as `null`, with +`agentSessions.invalidRead`. See the executable examples in [`record-page-v1.json`](../fixtures/agents/record-page-v1.json). diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index f2906e62..83bf3457 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -52,7 +52,7 @@ const MAX_MESSAGES_PER_ITEM: usize = 2048; /// Initial source window of a recorded page, grown only for a long line. const RECORD_PAGE_BYTES: u64 = 256 * 1024; /// Source bytes and lines of a single plugin read batch. -const RECORD_BATCH_BYTES: usize = 64 * 1024; +pub(crate) const RECORD_BATCH_BYTES: usize = 64 * 1024; const RECORD_BATCH_LINES: usize = 128; /// Encoded message budget of a recorded page. const RECORD_RESULT_BYTES: usize = 768 * 1024; @@ -642,7 +642,7 @@ impl Records { let messages = answers .into_iter() .next() - .map(decode_messages) + .map(|item| decode_messages(item, false)) .transpose()? .unwrap_or_default(); Ok(json!({ "changed": false, "messages": messages, "end": end })) @@ -658,6 +658,8 @@ impl Records { agent: String, path: String, size: u64, + /// The `generation` the listed record carried with `size`. + generation: i64, cursor: u64, direction: String, } @@ -690,6 +692,17 @@ impl Records { let empty = |changed: bool, too_long: bool| json!({ "changed": changed, "tooLong": too_long, "start": request.cursor, "end": request.cursor, "messages": [] }); // Validate the snapshot even for an exhausted edge. A cursor inside a line cannot // silently discard that line; callers must use the boundaries returned by Core. + // Offsets of an earlier reading of a replaced or truncated file are void. + let current = |store: &SessionStore| -> Result { + Ok(store.generation(&request.agent, &request.path)? == Some(request.generation)) + }; + { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + if !current(store)? { + return Ok(empty(true, false)); + } + } if request.size > 0 { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; @@ -740,6 +753,9 @@ impl Records { let (bytes, preceding) = { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; + if !current(store)? { + return Ok(empty(true, false)); + } let bytes = store.read_range(&request.agent, &request.path, ByteRange { start, end })?; let preceding = if before && start > 0 { @@ -781,18 +797,31 @@ impl Records { }; // Small batches keep a backend's encoded answer below its function limit. // Accept batches atomically, so no message can be skipped at a page boundary. + // A line that would push a nonempty batch past the threshold starts its own batch, + // so a long line is never combined with the short lines around it. let mut groups = Vec::new(); let mut group_start = 0; + let mut line_start = 0; let mut lines = 0; - for (index, byte) in bytes.iter().enumerate() { - if *byte == b'\n' { - lines += 1; - if index + 1 - group_start >= RECORD_BATCH_BYTES || lines >= RECORD_BATCH_LINES { - groups.push((group_start, index + 1)); - group_start = index + 1; - lines = 0; - } + let ends = bytes + .iter() + .enumerate() + .filter(|(_, byte)| **byte == b'\n') + .map(|(index, _)| index + 1) + .chain((whole_lines(&bytes) < bytes.len()).then_some(bytes.len())); + for end in ends { + if group_start < line_start && end - group_start > RECORD_BATCH_BYTES { + groups.push((group_start, line_start)); + group_start = line_start; + lines = 0; + } + lines += 1; + if end - group_start >= RECORD_BATCH_BYTES || lines >= RECORD_BATCH_LINES { + groups.push((group_start, end)); + group_start = end; + lines = 0; } + line_start = end; } if group_start < bytes.len() { groups.push((group_start, bytes.len())); @@ -817,7 +846,8 @@ impl Records { vec![json!({ "path": request.path, "lines": text_lines(&bytes[low..high]) })], true, )?; - let messages = decode_messages(answer.into_iter().next().unwrap_or_else(|| json!({})))?; + 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()); if count > 0 @@ -1511,7 +1541,12 @@ struct ReadItem { messages: Vec, } -fn decode_messages(item: Value) -> Result, CoreError> { +/// The fields a reader may return only when the request asked for `toolCalls`. +const TOOL_DETAIL_FIELDS: [&str; 5] = ["toolCallID", "status", "toolKind", "title", "locations"]; + +/// Decodes one answer item. Without `tool_details` the original strict shape applies: +/// a detail field, even an explicit null, makes the reading invalid. +fn decode_messages(item: Value, tool_details: bool) -> Result, CoreError> { let invalid = || { refusal( ErrorCode::ParseFailed, @@ -1519,6 +1554,17 @@ fn decode_messages(item: Value) -> Result, CoreError> { "The agent plugin returned an invalid reading of the session.", ) }; + let unrequested = !tool_details + && item["messages"].as_array().is_some_and(|messages| { + messages.iter().any(|message| { + TOOL_DETAIL_FIELDS + .iter() + .any(|field| message.get(field).is_some()) + }) + }); + if unrequested { + return Err(invalid()); + } let item: ReadItem = serde_json::from_value(item).map_err(|_| invalid())?; let valid = item.messages.len() <= MAX_MESSAGES_PER_ITEM && item.messages.iter().all(|message| { diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 6e69b87d..496a078a 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1852,12 +1852,13 @@ fn records_pages_walk_both_directions_without_cutting_or_dropping_lines() { "agentSessions.sync", json!({ "pluginID": PLUGIN, "agentID": AGENT }), ); + let generation = generation_of(&harness); let size = text.len() as u64; let page = |direction: &str, cursor: u64| { harness.run( "agentSessions.page", json!({ - "agent": AGENT_KEY, "path": path_text(&file), "size": size, + "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "direction": direction, "cursor": cursor }), ) @@ -1891,7 +1892,7 @@ fn records_pages_walk_both_directions_without_cutting_or_dropping_lines() { } let previous = page("before", last["start"].as_u64().unwrap()); assert_eq!(previous["end"], last["start"]); - assert_eq!(harness.refused("agentSessions.page", json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "direction": "sideways", "cursor": 0 })), "agentSessions.invalidPage"); + assert_eq!(harness.refused("agentSessions.page", json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "direction": "sideways", "cursor": 0 })), "agentSessions.invalidPage"); } #[test] @@ -1909,10 +1910,11 @@ fn records_pages_grow_for_a_long_line_and_reject_stale_or_unreadable_sources() { "agentSessions.sync", json!({ "pluginID": PLUGIN, "agentID": AGENT }), ); + let generation = generation_of(&harness); let size = text.len() as u64; let request = |direction: &str, cursor: u64| { json!({ - "agent": AGENT_KEY, "path": path_text(&file), "size": size, + "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "direction": direction, "cursor": cursor }) }; @@ -1959,6 +1961,7 @@ fn records_page_message_ids_are_opt_in_and_validated() { "agentSessions.sync", json!({ "pluginID": PLUGIN, "agentID": AGENT }), ); + let generation = generation_of(&harness); harness.link.set_answer(|function, params| { if function == "sessions.read" && params["mode"] == "messages" { assert_eq!(params["messageIDs"], true); @@ -1972,7 +1975,7 @@ fn records_page_message_ids_are_opt_in_and_validated() { sample_backend(function, params) } }); - let request = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": fs::metadata(&file).unwrap().len(), "cursor": 0, "direction": "after" }); + let request = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": fs::metadata(&file).unwrap().len(), "generation": generation, "cursor": 0, "direction": "after" }); let page = harness.run("agentSessions.page", request.clone()); assert_eq!(page["messages"][0]["id"], "source-message-1"); for id in ["", "bad id", "\n", &"x".repeat(257)] { @@ -1995,7 +1998,8 @@ fn records_page_tool_call_details_follow_the_live_bounds() { "agentSessions.sync", json!({ "pluginID": PLUGIN, "agentID": AGENT }), ); - let request = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": fs::metadata(&file).unwrap().len(), "cursor": 0, "direction": "after" }); + let generation = generation_of(&harness); + let request = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": fs::metadata(&file).unwrap().len(), "generation": generation, "cursor": 0, "direction": "after" }); let call = json!({ "role": "tool", "text": "", "toolName": "Read", "toolCallID": "call-1", "status": "inProgress", "toolKind": "read", "title": "Read main.go", "locations": [{ "path": "/work/main.go", "line": 3 }] }); @@ -2024,6 +2028,146 @@ fn records_page_tool_call_details_follow_the_live_bounds() { } } +#[test] +fn legacy_reads_refuse_tool_details_they_did_not_ask_for() { + let harness = Harness::new("record-legacy-details", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let generation = generation_of(&harness); + let size = fs::metadata(&file).unwrap().len(); + let legacy = json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": 0, "end": size } }); + let page = json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "cursor": 0, "direction": "after" }); + let detailed = + json!({ "role": "tool", "text": "x", "toolCallID": "call-1", "status": "completed" }); + let answer = json!({ "items": [{ "messages": [detailed] }] }); + harness.link.set_answer(move |_, params| { + assert_eq!( + params.get("toolCalls").is_some(), + params["messageIDs"] == true + ); + Ok(answer.clone()) + }); + assert_eq!( + harness.run("agentSessions.page", page)["messages"][0]["toolCallID"], + "call-1" + ); + assert_eq!( + harness.refused("agentSessions.read", legacy.clone()), + "agentSessions.invalidRead" + ); + // An explicit null is still a field the legacy shape does not have. + let null = + json!({ "items": [{ "messages": [{ "role": "tool", "text": "x", "status": null }] }] }); + harness.link.set_answer(move |_, _| Ok(null.clone())); + assert_eq!( + harness.refused("agentSessions.read", legacy), + "agentSessions.invalidRead" + ); +} + +#[test] +fn records_page_keeps_a_long_line_out_of_a_batch_of_short_ones() { + let harness = Harness::new("record-long-line", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + let short = json!({ "type": "note", "text": "a".repeat(40 * 1024) }); + let long = + json!({ "type": "note", "text": "b".repeat(1000 * 1024), "pad": "c".repeat(100 * 1024) }); + let mut text = fs::read_to_string(&file).unwrap(); + text.push_str(&format!("{short}\n{long}\n")); + fs::write(&file, text).unwrap(); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let generation = generation_of(&harness); + harness.link.set_answer(|_, params| { + let lines = params["items"][0]["lines"].as_array().unwrap(); + let oversized = lines + .iter() + .any(|line| line.as_str().unwrap().len() > super::records::RECORD_BATCH_BYTES); + assert!( + !oversized || lines.len() == 1, + "a long line was batched with others" + ); + let messages: Vec = lines + .iter() + .filter_map(|line| serde_json::from_str::(line.as_str().unwrap()).ok()) + .filter_map(|line| { + line["text"] + .as_str() + .map(|text| json!({ "role": "user", "text": text })) + }) + .collect(); + Ok(json!({ "items": [{ "messages": messages }] })) + }); + let size = fs::metadata(&file).unwrap().len(); + let page = harness.run( + "agentSessions.page", + json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "cursor": size, "direction": "before" }), + ); + assert_eq!(page["messages"].as_array().unwrap().len(), 1); + assert!(page["messages"][0]["text"] + .as_str() + .unwrap() + .starts_with('b')); + let earlier = harness.run( + "agentSessions.page", + json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "cursor": page["start"], "direction": "before" }), + ); + assert!(earlier["messages"] + .as_array() + .unwrap() + .iter() + .any(|m| m["text"].as_str().unwrap().starts_with('a'))); +} + +/// The generation the list gives the sample session's file. +fn generation_of(harness: &Harness) -> i64 { + let sessions = + harness.run("agentSessions.list", json!({ "sessionID": "s1" }))["sessions"].clone(); + sessions[0]["generation"] + .as_i64() + .expect("a listed generation") +} + +#[test] +fn records_page_refuses_offsets_of_an_earlier_reading() { + let harness = Harness::new("record-generation", ALL_GRANTS); + let file = write_session_file(&harness, 1_795_824_000_000); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let old = generation_of(&harness); + let size = fs::metadata(&file).unwrap().len(); + let request = |generation: i64| json!({ "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "cursor": size, "direction": "before" }); + assert_eq!( + harness.run("agentSessions.page", request(old))["changed"], + false + ); + // Same length, other content: only the generation tells the readings apart. + let text = fs::read_to_string(&file) + .unwrap() + .replace("hello from the user", "HELLO FROM THE USER"); + fs::write(&file, text).unwrap(); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + let new = generation_of(&harness); + assert_ne!(new, old); + let stale = harness.run("agentSessions.page", request(old)); + assert_eq!(stale["changed"], true); + assert_eq!(stale["messages"], json!([])); + assert_eq!( + harness.run("agentSessions.page", request(new))["changed"], + false + ); +} + #[test] fn records_page_contract_examples_match_the_runtime() { let fixture: Value = @@ -2038,13 +2182,14 @@ fn records_page_contract_examples_match_the_runtime() { "agentSessions.sync", json!({"pluginID": PLUGIN, "agentID": AGENT}), ); + let generation = generation_of(&harness); let size = fs::metadata(&file).unwrap().len(); for case in fixture["cases"].as_array().unwrap() { let cursor = if case["cursor"] == 0 { 0 } else { size }; let page = harness.run( "agentSessions.page", json!({ - "agent": AGENT_KEY, "path": path_text(&file), "size": size, + "agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "cursor": cursor, "direction": case["direction"] }), ); @@ -2069,7 +2214,7 @@ fn records_page_contract_examples_match_the_runtime() { "agentSessions.read" }; let request = if expects_ids { - json!({"agent": AGENT_KEY, "path": path_text(&file), "size": size, "cursor": 0, "direction": "after"}) + json!({"agent": AGENT_KEY, "path": path_text(&file), "size": size, "generation": generation, "cursor": 0, "direction": "after"}) } else { json!({"agent": AGENT_KEY, "path": path_text(&file), "range": {"start": 0, "end": size}}) }; diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index 832e149b..dfb12a3d 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -29,7 +29,7 @@ use crate::text; /// Version of the database layout. A cache of another version is deleted and /// rebuilt from the session files, so it is never migrated. -pub const SCHEMA_VERSION: u32 = 1; +pub const SCHEMA_VERSION: u32 = 2; /// Longest identifier, in bytes: agent, session, call, thread and request IDs. pub const MAX_ID_BYTES: usize = 256; @@ -83,6 +83,10 @@ pub fn database_file_name() -> String { format!("{DATABASE_PREFIX}{SCHEMA_VERSION}.sqlite3") } +/// A fresh file generation: random, so a file that is forgotten and read again +/// cannot repeat an earlier value. Kept within 53 bits for JSON consumers. +const NEW_GENERATION: &str = "(random() & 9007199254740991)"; + const SCHEMA: &str = " CREATE TABLE files ( id INTEGER PRIMARY KEY, @@ -93,6 +97,7 @@ CREATE TABLE files ( stamp_modified_ms INTEGER, fingerprint BLOB NOT NULL, state TEXT, + generation INTEGER NOT NULL, UNIQUE (agent, path) ) STRICT; @@ -335,6 +340,10 @@ pub struct SessionEntry { /// How many bytes of `path` the cache has read: every whole line up to /// here, so [`SessionStore::read_range`] takes any range that ends by it. pub read_bytes: u64, + /// Which reading of `path` the records come from. It stays the same while the + /// file only grows and changes when the cache reads it again from the start, + /// because it was replaced or truncated; offsets of another generation are void. + pub generation: i64, /// The session's messages in `path`: the prompts and replies its plugin /// reported as searchable text. Tool output and other files' copies are /// not counted. @@ -359,7 +368,7 @@ pub struct SessionEntry { macro_rules! selected_sessions { () => { "WITH ranked AS ( - SELECT f.agent, f.path, f.cursor_offset, s.*, + SELECT f.agent, f.path, f.cursor_offset, f.generation, s.*, ROW_NUMBER() OVER ( PARTITION BY f.agent, s.session_id ORDER BY s.described DESC, f.path @@ -613,7 +622,7 @@ impl SessionStore { " SELECT agent, session_id, path, file_count, parent_session_id, cwd, first_started_ms, last_updated_ms, agent_version, title_start, title_end, - cursor_offset, file_id + cursor_offset, file_id, generation FROM selected ORDER BY CASE WHEN ?6 = 1 THEN first_started_ms ELSE COALESCE(last_updated_ms, first_started_ms) END DESC NULLS LAST, @@ -649,6 +658,7 @@ impl SessionStore { agent_version: row.get(8)?, title_range: optional_range(row.get(9)?, row.get(10)?), read_bytes: row.get(11)?, + generation: row.get(13)?, message_count: 0, subagent_count: 0, model: None, @@ -1001,12 +1011,20 @@ impl SessionStore { Some(id) => { clear_file(&transaction, id)?; update_cursor(&transaction, id, 0, empty_fingerprint, None, None)?; + transaction + .execute( + &format!("UPDATE files SET generation = {NEW_GENERATION} WHERE id = ?1"), + [id], + ) + .map_err(|error| sql_error("Could not write the agent session cache", error))?; id } None => transaction .query_row( - "INSERT INTO files (agent, path, cursor_offset, fingerprint) - VALUES (?1, ?2, 0, ?3) RETURNING id", + &format!( + "INSERT INTO files (agent, path, cursor_offset, fingerprint, generation) + VALUES (?1, ?2, 0, ?3, {NEW_GENERATION}) RETURNING id" + ), params![agent, path, empty_fingerprint], |row| row.get(0), ) @@ -1028,6 +1046,19 @@ impl SessionStore { .map_err(|error| sql_error("Could not read the agent session cache", error)) } + /// The generation of a file the cache has read, `None` when it has not. + pub fn generation(&self, agent: &str, path: &str) -> Result, CoreError> { + check_caller_id("agent", agent)?; + self.connection + .query_row( + "SELECT generation FROM files WHERE agent = ?1 AND path = ?2", + params![agent, path], + |row| row.get(0), + ) + .optional() + .map_err(|error| sql_error("Could not read the agent session cache", error)) + } + fn known_file(&self, agent: &str, path: &str) -> Result, CoreError> { let row = self .connection diff --git a/rust/crates/agent-sessions/src/tests/store.rs b/rust/crates/agent-sessions/src/tests/store.rs index 8fbdfc02..e659c5a2 100644 --- a/rust/crates/agent-sessions/src/tests/store.rs +++ b/rust/crates/agent-sessions/src/tests/store.rs @@ -682,10 +682,13 @@ fn a_rebuild_with_other_chunks_gives_the_same_records() { keys(&calls(&whole, &CallFilter::default())), ["c1", "c2", "c3", "c4"] ); - assert_eq!( - sessions(&incremental, every_session()), - sessions(&whole, every_session()) - ); + // Each cache reads a file under its own generation; the records are the same. + let records = |store: &SessionStore| { + let mut entries = sessions(store, every_session()); + entries.iter_mut().for_each(|entry| entry.generation = 0); + entries + }; + assert_eq!(records(&incremental), records(&whole)); for text in ["migration", "数据库", "数据库迁移", "an"] { assert_eq!( search(&incremental, text, &[]), diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index a28a9381..7d7e232a 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4065,6 +4065,11 @@ Lithe list, search and sum them without the CLI running: changed since the cache read it; sync and list again. A backend's whole `messages` answer must fit the 1 MiB function result bound, so a host pages a long record with ranges well below it. +- A listed session also gives `generation`, an opaque integer naming the + cache's reading of `path`. It stays the same while the file only grows and + changes when the file was replaced or truncated and read again from the + start; byte offsets taken under another generation do not apply. It was + added within `agents` 0; an older Core does not answer it. - `sessionID`, `readBytes` and `end` were added within `agents` 0. A Core that predates them refuses `sessionID` as an unknown field, answers neither `readBytes` nor `end`, and may hand `read` a range that ends inside a line; diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 5eb41ec8..239ead8c 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。同时增加可选请求参数 `toolCalls`:只有 `true` 时 `tool` 消息才可带实时 `toolCall` 的详情 `toolCallID`、`status`、`toolKind`、`title`、`locations`(同一调用和它的结果共用 `toolCallID`,宿主按实时方式合并,让历史轮次和实时显示一致)。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,两个参数都由它发送,旧 `agentSessions.read` 和标题读取不协商。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | +| [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。同时增加可选请求参数 `toolCalls`:只有 `true` 时 `tool` 消息才可带实时 `toolCall` 的详情 `toolCallID`、`status`、`toolKind`、`title`、`locations`(同一调用和它的结果共用 `toolCallID`,宿主按实时方式合并,让历史轮次和实时显示一致)。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,两个参数都由它发送,旧 `agentSessions.read` 和标题读取不协商,回答里出现这些详情字段(包括显式 `null`)时以 `agentSessions.invalidRead` 拒绝。`agentSessions.list` 的会话新增 `generation`:文件只增长时不变,被替换或截断后重新读取时换新值;`agentSessions.page` 必须带上同一次列表的 `generation`,不一致时回答 `changed`。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 |