From 31def84ff4c2c5326d1eaef7ffd92d48ff3ef7b9 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 3 Dec 2026 19:52:40 +0800 Subject: [PATCH] =?UTF-8?q?feat(agents):=20=E5=B7=B2=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E5=8F=AF=E6=81=A2=E5=A4=8D=E3=80=81=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E3=80=81=E7=9C=8B=E5=AD=90=E4=BB=A3=E7=90=86=EF=BC=8C?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9=E5=88=86=E7=B1=BB=E4=B8=8E=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E7=89=87=E6=AE=B5=E7=94=B1=20Core=20=E7=BB=99?= =?UTF-8?q?=E5=87=BA=20(#262)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 72 +- rust/crates/agent-runtime/src/lib.rs | 12 +- rust/crates/agent-runtime/src/live.rs | 48 +- rust/crates/agent-runtime/src/records.rs | 204 +++-- .../agent-runtime/src/records/export.rs | 620 ++++++++++++++ .../agent-runtime/src/records/resume.rs | 139 +++ .../agent-runtime/src/records/snippets.rs | 120 +++ .../agent-runtime/src/records/subagents.rs | 203 +++++ rust/crates/agent-runtime/src/tests.rs | 122 ++- .../agent-runtime/src/tests/sessions.rs | 795 ++++++++++++++++++ rust/crates/agent-sessions/src/folders.rs | 227 +++++ rust/crates/agent-sessions/src/lib.rs | 12 +- rust/crates/agent-sessions/src/model.rs | 39 + rust/crates/agent-sessions/src/stats.rs | 13 + rust/crates/agent-sessions/src/store.rs | 182 +++- rust/crates/agent-sessions/src/tests/mod.rs | 18 +- rust/crates/agent-sessions/src/tests/stats.rs | 19 +- rust/crates/agent-sessions/src/tests/store.rs | 104 ++- rust/crates/agent-sessions/src/tests/text.rs | 101 ++- rust/crates/agent-sessions/src/text.rs | 207 ++++- rust/crates/core/src/protocol/command.rs | 14 + .../core/src/tests/declarative_plugins.rs | 2 +- .../diagnostics/src/catalog_generated.rs | 28 + rust/crates/platform/Cargo.toml | 2 +- rust/crates/platform/src/lib.rs | 1 + rust/crates/platform/src/shell.rs | 205 +++++ rust/crates/plugin-agents/src/lib.rs | 94 ++- rust/crates/plugin-agents/src/tests.rs | 81 ++ .../fixtures/agents/folder-categories-v1.json | 52 ++ rust/logging/events/agent.json | 50 ++ shared/plugins/contract/v1/README.md | 246 +++++- .../v1/fixtures/agents/agents.plugin.json | 6 +- .../fixtures/manifest/invalid-manifests.json | 4 + .../contract/v1/plugin-manifest.schema.json | 35 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 18 +- .../plugins/reference/protocol-changelog.md | 3 +- 38 files changed, 3980 insertions(+), 126 deletions(-) create mode 100644 rust/crates/agent-runtime/src/records/export.rs create mode 100644 rust/crates/agent-runtime/src/records/resume.rs create mode 100644 rust/crates/agent-runtime/src/records/snippets.rs create mode 100644 rust/crates/agent-runtime/src/records/subagents.rs create mode 100644 rust/crates/agent-runtime/src/tests/sessions.rs create mode 100644 rust/crates/agent-sessions/src/folders.rs create mode 100644 rust/crates/platform/src/shell.rs create mode 100644 rust/fixtures/agents/folder-categories-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index d9464657..c4d468b3 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -494,12 +494,15 @@ or removing a command fails until the table changes in the same commit. | `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 | -| `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.list` | List a page of recorded agent sessions by directory and order, with their activity, whether each can be resumed, and the whole list's counts with each directory group's `category` (`root`, `temporary`, `hidden`), or find one by its ID | +| `agentSessions.search` | Search recorded agent session text; with `snippets: true` each hit carries a `snippet` and the UTF-8 byte ranges of its matched words | | `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. Optional `overview` returns totals, breakdown and time series in one snapshot; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs` | | `agentSessions.calls` | List a page of recorded agent calls, most recent first, with their cost, cache hit rate and speed | +| `agentSessions.resume` | Build the arguments, directory and copyable command line that continue a recorded session in the agent's terminal form, from the plugin's `terminal.resumeArguments`; needs `agents.run` | +| `agentSessions.export` | Export a recorded session as Markdown of at most `maxBytes`: messages, replies, one line per tool call and their times, keeping the start or the end, in words the host passes in `labels` | +| `agentSessions.subagents` | List a recorded session's subagents, as the plugin's scan reports them, with their calls and each one's usage; empty when the plugin reports none | | `agentLibrary.configure` | Open the agent library in the platform's application data | | `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | | `agentLibrary.save` | Replace the library the user edited if it is still at the revision read (instruction sets each with `on` and `agents`; `active` is refused), then write Lithe's block in the instruction file of every agent that follows the library, never over a block edited outside Lithe, and answer each agent's `written`, `unchanged`, `skipped` or `failed` with its reason in `instructions` | @@ -9408,3 +9411,68 @@ 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). + +#### Recorded session actions + +These commands only read the agents' session files; none deletes, moves or +rewrites them. + +`agentSessions.resume` takes `{agent, sessionID, toolPath, shell?}` and answers +`{pluginID, agentID, sessionID, executable, arguments, shell, cwd?, +commandLine?}`. `arguments` are the agent's `terminal.resumeArguments` with +`${sessionID}` replaced; Core accepts only IDs of 1–256 ASCII letters, digits, +`.`, `_`, `:` and `-` not starting with `-` (`agentSessions.unsafeResume`). +`commandLine` is quoted for `posix` or `powershell`, by default the host +platform's, and is absent when a part holds a control character or, for +PowerShell, a `"`. Core starts nothing; the host runs `executable` with +`arguments` in `cwd` through its terminal form. The command needs the agent's +`agents.sessions.read` and `agents.run` grants and refuses with +`agentSessions.runNotGranted`, `agentSessions.toolNotFound`, +`agentSessions.unknownSession` or `agentSessions.noResume` besides the +refusals of `read`. A listed session's `resumable` says whether the agent +declares the arguments and the ID passes the rule. + +`agentSessions.export` takes `{agent, sessionID, labels, maxBytes?, keep?, +utcOffsetSeconds?}` and answers `{changed, markdown, messages, truncated}`: +user and assistant messages under headings with their times and one line per +tool call, in file order, without thoughts or tool output, mirrors and the +records of one call folded. Every word of the export comes from the required +`labels` (`untitled`, `agent`, `session`, `directory`, `started`, +`lastActive`, `timeZone`, `user`, `assistant`, `tool`, `failed`, +`earlierOmitted`, `laterOmitted`; 1–256 bytes each, no control characters), +which the host takes from its translations; Core keeps no default text. `maxBytes` is 4 KiB to 4 MiB (default 1 MiB) and +`keep` is `start` or `end`; whole messages are kept from that side and a line +says the rest is left out. Core reads the session's own file from that side +through the backend's `read` with `messageIDs` and `toolCalls`, stops once it +has enough text, and reads at most 64 MiB. A file replaced during the export +answers `{changed: true}`. Missing, unknown or invalid labels and +out-of-range values refuse with `agentSessions.invalidExport`. Every +`agentSessions` command that takes an `agent` key refuses one that is +malformed or names no declared agent with `agentSessions.unknownAgent` and +`entry_not_found`. + +`agentSessions.subagents` takes `{agent, sessionID}` and answers `{subagents, +subagentsTruncated}`: the threads the backend's `scan` described in `threads` +(requested with `threads: true`) or that calls name in `threadID`, earliest +first, each with its description, `title?`, `usage` (a summary without `key`) +and `calls` (rows shaped like `agentSessions.calls`, at most 2000 per answer, +`callsTruncated` per subagent). At most 256 subagents. A backend that reports +no threads gives `[]`. + +`agentSessions.list` groups carry `category` when the directory is a disk or +share root, a temporary directory (macOS, Linux and Windows rules, chosen by +the form of the path) or a hidden folder below a home. Shared cases: +[`folder-categories-v1.json`](../fixtures/agents/folder-categories-v1.json). + +`agentSessions.search` with `snippets: true` reads each hit's range through +`read` and gives `snippet`, from 36 characters before the first matched word to +120 after it with `…` where cut, or the first 120 characters of the first +message with text when no word occurs; and `snippetMatches`, `[start, end]` +UTF-8 byte offsets into `snippet` of every matched word, merged where they +overlap or touch. Words match by the index's own rules: case-insensitive word +prefixes, adjacent pairs of CJK characters and single CJK characters. A hit +over 256 KiB, hits past 4 MiB in one search and hits the backend cannot read +carry neither field; the search does not fail. + +The session cache's layout version is 4: a cache of another version is deleted +and rebuilt from the session files on the first sync. diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 719857a1..3f5f0118 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -126,6 +126,9 @@ impl Runtime { "agentSessions.page" => self.records.page(self, payload), "agentSessions.stats" => self.records.stats(self, payload), "agentSessions.calls" => self.records.calls(self, payload), + "agentSessions.resume" => self.records.resume(self, payload), + "agentSessions.export" => self.records.export(self, payload), + "agentSessions.subagents" => self.records.subagents(self, payload), "agentLibrary.configure" => self.library.configure(payload), "agentLibrary.read" => self.library.read(self, payload), "agentLibrary.save" => self.library.save(self, payload), @@ -205,8 +208,9 @@ pub(crate) fn now_ms() -> i64 { }) } -/// Records a catalog event. Logging only queues, so it is safe under locks; -/// a refused fact is a defect of this crate's fields and is dropped. +/// Records a catalog event. Logging only queues, so it is safe under locks. +/// A refused fact is a defect of this crate's fields; it counts as dropped, +/// so the next drain reports that a fact was lost. pub(crate) fn log(event: &str, fields: [(&str, Value); N]) { log_fields(event, fields.into_iter()); } @@ -215,5 +219,7 @@ pub(crate) fn log_fields<'a>(event: &str, fields: impl Iterator = fields .map(|(name, value)| (name.to_string(), value)) .collect(); - let _ = lithe_diagnostics::core_events::record(event, fields, None); + if lithe_diagnostics::core_events::record(event, fields, None).is_err() { + lithe_diagnostics::core_events::note_dropped(); + } } diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index 36c747f6..19b80fb8 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -678,7 +678,11 @@ fn start_checked(runtime: &Arc, request: StartRequest) -> Result, session: &Arc, output: Box, session: &Arc) { let handle = &session.handle; let deadline = Instant::now() + EXIT_WAIT; @@ -938,7 +965,15 @@ fn finish(runtime: &Arc, session: &Arc) { if status.is_none() { handle.terminate(); } - let disposed = handle.dispose(DISPOSE_TIMEOUT).is_ok(); + // `agent.session.finished` says only that the session failed; this says + // what it left: a CLI that may still be running. + let disposed = match handle.dispose(DISPOSE_TIMEOUT) { + Ok(()) => true, + Err(error) => { + log_cleanup_failed(&session.plugin_id, &session.agent_id, &session.id, &error); + false + } + }; let exit_code = status.or_else(|| handle.exit_status()).flatten(); session.mark_end(EndReason::Exited, &runtime.live.queue); let reason = if disposed { @@ -957,9 +992,14 @@ fn finish(runtime: &Arc, session: &Arc) { if let Some(code) = exit_code { params["exitCode"] = json!(code); } - let _ = runtime + if runtime .link - .notify(&session.backend, AGENTS_DID_EXIT, params); + .notify(&session.backend, AGENTS_DID_EXIT, params) + .is_err() + { + // The backend keeps the session as running until it stops. + crate::interaction::failed(session, AGENTS_DID_EXIT, "agents.backendUnavailable"); + } } let mut event = json!({ "kind": "exited", "reason": reason.token() }); if let Some(code) = exit_code { diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs index 4ff0cf55..eab4d778 100644 --- a/rust/crates/agent-runtime/src/records.rs +++ b/rust/crates/agent-runtime/src/records.rs @@ -13,19 +13,24 @@ //! writer syncs and forgets, the reader lists, searches, reads and sums. The //! writer lock is held across calls to plugin backends; nothing a backend can //! ask for while it is called takes that lock. +//! +//! Nothing here writes an agent's session files: Core only reads them, and +//! the resume command, the Markdown export and the subagent usage are made +//! from those readings and the cache. use crate::backend::BackendLink; use crate::catalog::{record_key, split_record_key, CatalogAgent}; use crate::events::{check_rate_limits, RateLimits, RateWindow, MAX_RATE_WINDOWS}; use crate::{log, now_ms, Runtime}; +use lithe_agent_sessions::folder_category; use lithe_agent_sessions::pricing::{call_cost, PriceTable}; use lithe_agent_sessions::stats::{ call_speed, model_name, CallSelector, GroupBy, Overview, OverviewQuery, SpeedRanker, Summarizer, }; use lithe_agent_sessions::{ - discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, - SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES, - MAX_READ_BYTES, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, + discover, ByteRange, CallEntry, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionEntry, + SessionFilter, SessionOrder, SessionParser, SessionSource, SessionStore, + MAX_FILTER_DIRECTORIES, MAX_READ_BYTES, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, }; use lithe_lsp_engine::agent_host::AgentHostFailure; use lithe_plugin_agents::SessionSourceDeclaration; @@ -82,6 +87,11 @@ const RATE_FILE: &str = "rate-limits.json"; const MILLISECONDS_PER_DAY: i64 = 86_400_000; +mod export; +mod resume; +mod snippets; +mod subagents; + /// Where the cache is and what the session roots resolve against. #[derive(Debug, Clone)] struct Config { @@ -508,6 +518,7 @@ impl Records { } } + let mut declared: BTreeMap<&str, Option> = BTreeMap::new(); let sessions: Vec = entries .iter() .zip(titles) @@ -517,11 +528,24 @@ impl Records { if let Some(title) = title { value["title"] = json!(title); } + let agent = declared + .entry(entry.agent.as_str()) + .or_insert_with(|| runtime.catalog.find_key(&entry.agent)); + value["resumable"] = json!(agent + .as_ref() + .is_some_and(|agent| resume::resumable(agent, &entry.session_id))); value }) .collect(); let mut answer = json!({ "sessions": sessions }); - if let Some(counts) = counts { + if let Some(mut counts) = counts { + let home = self.config().map(|config| config.user_home); + for group in &mut counts.groups { + group.category = group + .cwd + .as_deref() + .and_then(|cwd| folder_category(cwd, home.as_deref())); + } answer["total"] = json!(counts.total); answer["groups"] = serde_json::to_value(&counts.groups).unwrap_or_else(|_| json!([])); answer["groupsTruncated"] = json!(counts.groups_truncated); @@ -530,7 +554,8 @@ impl Records { } /// `agentSessions.search`: where the readable agents' sessions contain - /// the words of a query. The host reads the hits it shows. + /// the words of a query, and with `snippets` a piece of each hit's text + /// with the words marked. pub fn search(&self, runtime: &Runtime, payload: Value) -> Result { #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -542,6 +567,8 @@ impl Records { session_id: Option, #[serde(default)] limit: Option, + #[serde(default)] + snippets: bool, } let request: SearchRequest = crate::decode(payload)?; let Some(agents) = allowed_agents(runtime, request.agents) else { @@ -551,17 +578,28 @@ impl Records { let reader = self.lock_reader(); let store = reader.as_ref().ok_or_else(not_configured)?; store.search(&SearchQuery { - text: request.text, + text: request.text.clone(), agents, session_id: request.session_id, limit: request.limit.unwrap_or(50).clamp(1, MAX_SEARCH_HITS), })? }; + let mut snippets = if request.snippets { + self.snippets(runtime, &hits, &request.text) + } else { + Vec::new() + }; + snippets.resize(hits.len(), None); let hits: Vec = hits .iter() - .map(|hit| { + .zip(snippets) + .map(|(hit, snippet)| { let mut value = serde_json::to_value(hit).unwrap_or_else(|_| json!({})); add_agent_ids(&mut value, &hit.agent); + if let Some(snippet) = snippet { + value["snippet"] = json!(snippet.text); + value["snippetMatches"] = json!(snippet.matches); + } value }) .collect(); @@ -582,14 +620,7 @@ impl Records { } let request: ReadRequest = crate::decode(payload)?; let config = self.config().ok_or_else(not_configured)?; - let (plugin_id, agent_id) = split_record_key(&request.agent).ok_or_else(|| { - refusal( - ErrorCode::InvalidRequest, - "agentSessions.unknownAgent", - "No installed plugin declares this agent.", - ) - })?; - let agent = readable_agent(runtime, plugin_id, agent_id)?; + let agent = readable_key(runtime, &request.agent)?; let sources = rooted_sources(&agent, &config); let source = source_index(&sources, Path::new(&request.path)).ok_or_else(|| { refusal( @@ -688,8 +719,7 @@ impl Records { } 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 agent = readable_key(runtime, &request.agent)?; let sources = rooted_sources(&agent, &config); let source = source_index(&sources, Path::new(&request.path)).ok_or_else(|| { refusal( @@ -804,37 +834,8 @@ impl Records { } 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. - // 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; - 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())); - } + let mut groups = line_batches(&bytes); // 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 { @@ -942,7 +943,7 @@ impl Records { return Err(invalid()); } // The catalog may have changed while the backend read the file. - readable_agent(runtime, plugin_id, agent_id)?; + readable_key(runtime, &request.agent)?; let restart = view.page( target.ticket, (low, high, before), @@ -1382,11 +1383,24 @@ impl Records { let Ok(bytes) = serde_json::to_vec(&file) else { return; }; - // Best effort: a lost snapshot comes back with the agent's next report. + // A lost snapshot comes back with the agent's next report, so a + // failure is logged and nothing else. A partial file left behind is + // overwritten by the next save. let path = config.cache_directory.join(RATE_FILE); let partial = config.cache_directory.join(format!("{RATE_FILE}.partial")); - if fs::write(&partial, bytes).is_ok() { - let _ = fs::rename(&partial, &path); + let saved = fs::write(&partial, bytes) + .map_err(|error| ("write", error)) + .and_then(|()| fs::rename(&partial, &path).map_err(|error| ("rename", error))); + if let Err((stage, error)) = saved { + log( + "agent.records.rate_limits_save_failed", + [ + ("stage", json!(stage)), + ("error", json!("The rate limits could not be saved")), + ("error_code", json!(format!("{:?}", error.kind()))), + ("error_domain", json!("io")), + ], + ); } } } @@ -1429,19 +1443,33 @@ struct AgentRequest { agent_id: String, } +/// `agentSessions.unknownAgent`, always with [`ErrorCode::EntryNotFound`], +/// whether the key is malformed or names an agent no plugin declares. +fn unknown_agent() -> CoreError { + refusal( + ErrorCode::EntryNotFound, + "agentSessions.unknownAgent", + "No installed plugin declares this agent.", + ) +} + +/// The agent a record key `/` names, when the user lets +/// Lithe read its sessions. +fn readable_key(runtime: &Runtime, key: &str) -> Result { + let (plugin_id, agent_id) = split_record_key(key).ok_or_else(unknown_agent)?; + readable_agent(runtime, plugin_id, agent_id) +} + /// The agent, when the user lets Lithe read its sessions. fn readable_agent( runtime: &Runtime, plugin_id: &str, agent_id: &str, ) -> Result { - let agent = runtime.catalog.find(plugin_id, agent_id).ok_or_else(|| { - refusal( - ErrorCode::EntryNotFound, - "agentSessions.unknownAgent", - "No installed plugin declares this agent.", - ) - })?; + let agent = runtime + .catalog + .find(plugin_id, agent_id) + .ok_or_else(unknown_agent)?; if !agent.may_read_sessions { return Err(refusal( ErrorCode::PermissionDenied, @@ -1664,6 +1692,62 @@ fn backend_for( }) } +/// The byte ranges of `bytes` to read with one `read` call each, in order. +/// Small batches keep a backend's encoded answer below its function limit. 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. +fn line_batches(bytes: &[u8]) -> Vec<(usize, usize)> { + let mut groups = Vec::new(); + let mut group_start = 0; + let mut line_start = 0; + let mut 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())); + } + groups +} + +/// The listed session `session_id` of the agent with record key `agent`. +fn find_session( + store: &SessionStore, + agent: &str, + session_id: &str, +) -> Result { + let filter = SessionFilter { + agents: vec![agent.to_owned()], + session_id: Some(session_id.to_owned()), + limit: 1, + ..SessionFilter::default() + }; + store.sessions(&filter)?.into_iter().next().ok_or_else(|| { + refusal( + ErrorCode::EntryNotFound, + "agentSessions.unknownSession", + "The session records hold no session with this ID.", + ) + }) +} + /// How many of `bytes`, which end inside a line, make whole lines: up to the /// last newline, none when they hold no newline. fn whole_lines(bytes: &[u8]) -> usize { @@ -2004,11 +2088,15 @@ impl SessionParser for PluginParser<'_> { "The file is not in a session directory of the agent.", )); }; + // `threads` asks for the subagent threads the lines describe; older + // Cores reject them in the answer, so a backend sends them only when + // asked. let mut params = json!({ "agentID": self.agent_id, "sourceID": route.source.id, "path": chunk.path.to_string_lossy(), "lines": chunk_lines(chunk.offset, chunk.bytes), + "threads": true, }); if let Some(state) = chunk.state { params["state"] = state.clone(); diff --git a/rust/crates/agent-runtime/src/records/export.rs b/rust/crates/agent-runtime/src/records/export.rs new file mode 100644 index 00000000..375900c5 --- /dev/null +++ b/rust/crates/agent-runtime/src/records/export.rs @@ -0,0 +1,620 @@ +//! `agentSessions.export`: a recorded session as Markdown, for the user to +//! save, share or hand to another agent. The session's own file is read +//! through the plugin's `read` function, as a page is; the user's messages, +//! the agent's replies and one line per tool call go in, in file order. +//! Thoughts and tool output stay out. +//! +//! The text is bounded by the request's `maxBytes`: whole messages from the +//! start or the end, the side the request keeps, and a line that says the +//! rest is left out. Reading stops once enough messages are in, so a long +//! session costs what the text holds, not the size of its file. +//! +//! Every word of the export comes from the request's `labels`, which the host +//! takes from its translations in the user's language. Core writes only +//! Markdown syntax, the session's own text, times and identifiers. + +use super::{ + call_read, decode_messages, decode_title, find_session, line_batches, not_configured, + readable_key, refusal, rooted_sources, source_index, text_lines, whole_lines, ReadMessage, + Records, RECORD_PAGE_BYTES, +}; +use crate::Runtime; +use lithe_agent_sessions::stats::civil_date_time; +use lithe_agent_sessions::{ByteRange, SessionEntry, SessionStore, MAX_READ_BYTES}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, VecDeque}; +use std::path::Path; + +/// The text a request gets when it names no `maxBytes`. +const DEFAULT_EXPORT_BYTES: usize = 1024 * 1024; +/// The bounds of `maxBytes`. +const MIN_EXPORT_BYTES: usize = 4 * 1024; +const MAX_EXPORT_BYTES: usize = 4 * 1024 * 1024; +/// Most bytes of the session file one export reads; a session whose messages +/// are mostly tool output would otherwise read its whole file. +const MAX_EXPORT_SOURCE_BYTES: u64 = 64 * 1024 * 1024; +/// Longest label, in bytes. +const MAX_LABEL_BYTES: usize = 256; +/// Longest command or tool title on a tool line, in bytes. +const MAX_TOOL_SUMMARY_BYTES: usize = 200; +/// Most file locations a tool line names. +const MAX_TOOL_SUMMARY_LOCATIONS: usize = 3; +/// The time zones `utcOffsetSeconds` may name: UTC-14:00 to UTC+14:00. +const MAX_UTC_OFFSET_SECONDS: i32 = 14 * 3600; + +/// Which messages a bounded export keeps. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +enum Keep { + /// The first messages, for reading a session from its beginning. + #[default] + Start, + /// The last messages, for continuing where a session stopped. + End, +} + +/// The words of an export in the user's language. All are required, each 1 +/// to [`MAX_LABEL_BYTES`] bytes on one line. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ExportLabels { + /// The title of a session whose title cannot be read. + untitled: String, + /// Header line: the agent's name and key. + agent: String, + /// Header line: the session's ID. + session: String, + /// Header line: the session's working directory. + directory: String, + /// Header line: when the session started. + started: String, + /// Header line: when the session was last active. + last_active: String, + /// Header line: the time zone of the times. + time_zone: String, + /// Heading of each of the user's messages. + user: String, + /// Heading of each of the agent's replies. + assistant: String, + /// Start of each tool call's line. + tool: String, + /// Marks a tool call that failed. + failed: String, + /// The line before the kept messages when earlier ones are left out. + earlier_omitted: String, + /// The line after the kept messages when later ones are left out. + later_omitted: String, +} + +impl ExportLabels { + /// The labels of a request, `None` when one is missing, unknown, empty, + /// too long or holds a control character. + fn decode(value: Option) -> Option { + let labels: Self = serde_json::from_value(value?).ok()?; + let all = [ + &labels.untitled, + &labels.agent, + &labels.session, + &labels.directory, + &labels.started, + &labels.last_active, + &labels.time_zone, + &labels.user, + &labels.assistant, + &labels.tool, + &labels.failed, + &labels.earlier_omitted, + &labels.later_omitted, + ]; + all.iter() + .all(|label| { + !label.trim().is_empty() + && label.len() <= MAX_LABEL_BYTES + && !label.chars().any(char::is_control) + }) + .then_some(labels) + } +} + +impl Records { + /// `agentSessions.export`: the session as Markdown, at most `maxBytes`. + pub fn export(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ExportRequest { + agent: String, + #[serde(rename = "sessionID")] + session_id: String, + #[serde(default)] + max_bytes: Option, + #[serde(default)] + keep: Keep, + #[serde(default)] + utc_offset_seconds: i32, + /// Checked by [`ExportLabels::decode`], so a missing or invalid + /// label refuses as an invalid export, not an invalid payload. + #[serde(default)] + labels: Option, + } + let request: ExportRequest = crate::decode(payload)?; + let max_bytes = request.max_bytes.unwrap_or(DEFAULT_EXPORT_BYTES); + let labels = ExportLabels::decode(request.labels); + let Some(labels) = labels.filter(|_| { + (MIN_EXPORT_BYTES..=MAX_EXPORT_BYTES).contains(&max_bytes) + && request.utc_offset_seconds.abs() <= MAX_UTC_OFFSET_SECONDS + }) else { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidExport", + "Give every label, and ask for 4 KiB to 4 MiB of text at a UTC offset of at most 14 hours.", + )); + }; + let config = self.config().ok_or_else(not_configured)?; + let agent = readable_key(runtime, &request.agent)?; + let sources = rooted_sources(&agent, &config); + let (session, title_bytes) = { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + let session = find_session(store, &request.agent, &request.session_id)?; + let title = match session.title_range { + Some(range) => store.read_range(&session.agent, &session.path, range)?, + None => None, + }; + (session, title) + }; + let source = source_index(&sources, Path::new(&session.path)).ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.outsideSources", + "The file is not in a session directory of the agent.", + ) + })?; + let source = &sources[source].source; + let title = title_bytes.and_then(|bytes| { + let item = json!({ "path": session.path, "lines": text_lines(&bytes) }); + call_read(&*runtime.link, &agent, source, "titles", vec![item], false) + .ok()? + .first() + .and_then(decode_title) + }); + + let read_batch = |bytes: &[u8]| -> Result, CoreError> { + let item = json!({ "path": session.path, "lines": text_lines(bytes) }); + let answer = call_read(&*runtime.link, &agent, source, "messages", vec![item], true)?; + decode_messages(answer.into_iter().next().unwrap_or_else(|| json!({})), true) + }; + let Some((messages, unread)) = + self.read_messages(&session, request.keep, max_bytes, read_batch)? + else { + return Ok(json!({ "changed": true })); + }; + + let header = header( + &labels, + title.as_deref(), + &agent.agent.display_name, + &request.agent, + &session, + request.utc_offset_seconds, + ); + let blocks: Vec = fold(messages) + .iter() + .filter_map(|message| block(&labels, message, request.utc_offset_seconds)) + .collect(); + let (markdown, count, truncated) = + assemble(&labels, header, &blocks, request.keep, max_bytes, unread); + Ok(json!({ + "changed": false, + "markdown": markdown, + "messages": count, + "truncated": truncated, + })) + } + + /// Reads the messages of `session`'s file from the side `keep` names + /// until their text passes `max_bytes`, the file ends, or + /// [`MAX_EXPORT_SOURCE_BYTES`] are read. Returns them in file order and + /// whether bytes were left unread, or `None` when the file changed. + fn read_messages( + &self, + session: &SessionEntry, + keep: Keep, + max_bytes: usize, + mut read_batch: impl FnMut(&[u8]) -> Result, CoreError>, + ) -> Result, bool)>, CoreError> { + let backward = keep == Keep::End; + let size = session.read_bytes; + let mut cursor = if backward { size } else { 0 }; + let mut windows: VecDeque> = VecDeque::new(); + let mut estimate = 0usize; + let mut read = 0u64; + loop { + let done = if backward { + cursor == 0 + } else { + cursor == size + }; + if done { + return Ok(Some((windows.into_iter().flatten().collect(), false))); + } + if estimate >= max_bytes || read >= MAX_EXPORT_SOURCE_BYTES { + return Ok(Some((windows.into_iter().flatten().collect(), true))); + } + let Some((start, bytes)) = self.window(session, cursor, backward)? else { + return Ok(None); + }; + if bytes.is_empty() { + // One line longer than a read allows: leave the rest out. + return Ok(Some((windows.into_iter().flatten().collect(), true))); + } + let end = start + bytes.len() as u64; + cursor = if backward { start } else { end }; + read += bytes.len() as u64; + let mut messages = Vec::new(); + for (low, high) in line_batches(&bytes) { + messages.extend(read_batch(&bytes[low..high])?); + } + estimate += messages.iter().map(estimated_size).sum::(); + if backward { + windows.push_front(messages); + } else { + windows.push_back(messages); + } + } + } + + /// The whole lines of the session's file next to `cursor`, before it when + /// `backward`, with their start; `None` when the file changed since it + /// was listed. Empty when one line is longer than [`MAX_READ_BYTES`]. + fn window( + &self, + session: &SessionEntry, + cursor: u64, + backward: bool, + ) -> Result)>, CoreError> { + let mut span = RECORD_PAGE_BYTES; + loop { + let (start, end) = if backward { + (cursor.saturating_sub(span), cursor) + } else { + (cursor, cursor.saturating_add(span).min(session.read_bytes)) + }; + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + if store.generation(&session.agent, &session.path)? != Some(session.generation) { + return Ok(None); + } + let Some(mut bytes) = read(store, session, start, end)? else { + return Ok(None); + }; + let mut aligned = start; + if backward && start > 0 { + let Some(preceding) = read(store, session, start - 1, start)? else { + return Ok(None); + }; + if 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 !backward && end < session.read_bytes { + bytes.truncate(whole_lines(&bytes)); + } + let whole = if backward { + start == 0 + } else { + end == session.read_bytes + }; + if !bytes.is_empty() || whole || span >= MAX_READ_BYTES { + return Ok(Some((aligned, bytes))); + } + span = (span * 4).min(MAX_READ_BYTES); + } + } +} + +fn read( + store: &SessionStore, + session: &SessionEntry, + start: u64, + end: u64, +) -> Result>, CoreError> { + store.read_range(&session.agent, &session.path, ByteRange { start, end }) +} + +/// About how many bytes a message adds to the text, to stop reading early. +fn estimated_size(message: &ReadMessage) -> usize { + match message.role.as_str() { + "user" | "assistant" => message.text.len() + 48, + "tool" => MAX_TOOL_SUMMARY_BYTES / 2, + _ => 0, + } +} + +/// The messages to export, in file order: no thoughts, each mirrored record +/// once, and each tool call once, with the details its later records add. +fn fold(messages: Vec) -> Vec { + let mut folded: Vec = Vec::new(); + let mut index: BTreeMap<(String, String), usize> = BTreeMap::new(); + for message in messages { + if message.role == "thought" { + continue; + } + let key = match (&message.tool_call_id, &message.id) { + (Some(call), _) if message.role == "tool" => Some(("call".to_owned(), call.clone())), + (_, Some(id)) => Some((message.role.clone(), id.clone())), + _ => None, + }; + if let Some(&at) = key.as_ref().and_then(|key| index.get(key)) { + if message.role == "tool" { + let earlier = &mut folded[at]; + if message.status.is_some() { + earlier.status = message.status; + } + earlier.title = earlier.title.take().or(message.title); + earlier.command = earlier.command.take().or(message.command); + earlier.tool_name = earlier.tool_name.take().or(message.tool_name); + earlier.locations = earlier.locations.take().or(message.locations); + earlier.at_ms = earlier.at_ms.or(message.at_ms); + } + continue; + } + if let Some(key) = key { + index.insert(key, folded.len()); + } + folded.push(message); + } + folded +} + +/// The title, then one `-