Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions rust/contracts/ide-api/v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ configuration values, never portable workspace identifiers.
| `lithe_operations_list` | none | read | retained Build/Run operations and status, without log bodies |
| `lithe_operation_output` | `operationID`, optional opaque `cursor` | read | state, nullable exitCode, bounded output and cursor |
| `lithe_operation_stop` | `operationID` | execute | stop request for that exact execution |
| `lithe_sessions_search` | `query`, optional `agent` | read | at most 20 hits with agent, session ID, time and a bounded excerpt; served only when declared |
| `lithe_sessions_read` | `sessionID`, optional `agent`, optional `cursor` | read | one bounded page of the session's recorded messages and its cursor; served only when declared |

The catalog has no language- or tool-specific capability. Toolchains and build
tools belong to plugins, so an agent reads and sets their options through
Expand Down Expand Up @@ -174,6 +176,54 @@ silently answers them. Output is retained only as long as its existing IDE outpu
slot: replacing a run, removing its tab, or closing the workspace may expire an
operation. Callers receive `OPERATION_EXPIRED`, never another run's output.

## Agent sessions

`lithe_sessions_search` and `lithe_sessions_read` let an MCP client search and read
the local session records of the user's coding agents (API-45). They are the only
tools a host serves only when it declares them: a host that declares no selection
serves every other tool and never these two. A host declares them only while all
three hold: the user enabled the IDE connection for this project, turned on the
separate "Allow MCP clients to search local sessions" switch, and allowed Lithe to
read at least one agent's sessions. The host checks the switch and the per-agent
consent again on every call, so a client that listed the tools earlier is refused
once the user withdraws either one. Turning the switch on or off reopens the
connection with the new declaration; the descriptor path and client configuration
do not change.

Both tools read only agents whose sessions the user allowed; an `agent` argument
names one of them as `<pluginID>/<agentID>`, and an agent the user did not allow
returns `PERMISSION_DENIED`. They cover every allowed agent's sessions, not only
sessions started in this project. They search what Lithe has already indexed and
do not start a sync; a session updated after Lithe's last sync appears once the
user next opens the agent history. Remote workspaces return `NOT_AVAILABLE`.

Search requires every word of `query` and returns at most 20 hits. Each hit has
`agent`, `agentName`, `sessionID`, `atMs` and an `excerpt` of at most 1,024 UTF-8
bytes re-read from the session file, with `excerptTruncated` when cut and
`changed` when the file no longer holds the indexed text. The excerpts of one
answer total at most 32,768 bytes; `truncated: true` reports that hits were left
out. Read returns `agent`, `agentName`, `sessionID`, `title`, `messages`
(`role`, `text`, `atMs`, optional `toolName` of at most 128 bytes, `truncated`
when a message was cut to 4,096 bytes or by the page bound), `hasMore`,
`changed` and, while `hasMore` is true, `nextCursor`. A page holds at most
65,536 bytes of message text and at most 2,000 messages. `tooLong: true` reports
a record line longer than the 16 MiB Lithe reads at once: the page ends before
it and `hasMore` is false. `omitted: n` reports that the page met its bound
inside one read made larger for a long line and left out the `n` messages after
it; the next page starts after them.

The cursor is the opaque `nextCursor` of the previous page of the same session,
answered on the same connection. The host signs it with a key of the
connection, so a cursor from another connection, including the one before a
reopen, returns `INVALID_ARGUMENTS`, as does any other value; read the session
again from its start without a cursor. A session ID that two allowed agents
share returns `INVALID_ARGUMENTS` until `agent` names one; an unknown session
returns `NOT_FOUND`.

Neither tool returns a file path, working directory, account or credential. The
host logs `agent.records.inspected` with the tool name, the number of hits or
messages and the duration; never the query, session ID or content.

## Output and errors

Operation IDs identify executions, not reusable UI slots. Copying/updating a run
Expand Down Expand Up @@ -221,3 +271,6 @@ surface; it does not introduce a new plugin marketplace, sandbox or UI extension
- Both platforms: configure a plugin Build option, reload, execute a Build task, start a configuration,
read incremental output, restart, reject the old ID, stop, revoke, and close the
project. Confirm installed resource manifests/hashes remain unchanged.
- Agent sessions: with the switch off or no agent allowed, `tools/list` omits both
session tools and a direct call returns `NOT_SUPPORTED`; with both on, search and
read stay within their bounds, return no path and log no query.
4 changes: 2 additions & 2 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,9 +492,9 @@ 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 recorded agent sessions |
| `agentSessions.list` | List recorded agent sessions, or find one by its ID |
| `agentSessions.search` | Search recorded agent session text |
| `agentSessions.read` | Read one recorded range as messages |
| `agentSessions.read` | Read one recorded range as messages and where the next page starts |
| `agentSessions.stats` | Sum recorded agent usage with the latest rate limits |
| `plugins.declarative.validate` | Validate and normalize a declarative plugin manifest |
| `plugins.ui.applyResult` | Check a backend result for a plugin view and return the whole view to draw |
Expand Down
76 changes: 63 additions & 13 deletions rust/crates/agent-runtime/src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ 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::pricing::PriceTable;
use lithe_agent_sessions::stats::{GroupBy, Summarizer};
use lithe_agent_sessions::stats::{GroupBy, SpeedRanker, Summarizer};
use lithe_agent_sessions::{
discover, ByteRange, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter,
SessionParser, SessionSource, SessionStore, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE,
Expand Down Expand Up @@ -352,6 +352,8 @@ impl Records {
cwd: Option<String>,
#[serde(default)]
active_since_ms: Option<i64>,
#[serde(rename = "sessionID", default)]
session_id: Option<String>,
#[serde(default)]
offset: u64,
#[serde(default)]
Expand All @@ -367,6 +369,7 @@ impl Records {
agents,
cwd: request.cwd,
active_since_ms: request.active_since_ms,
session_id: request.session_id,
offset: request.offset,
limit: request.limit.unwrap_or(100).clamp(1, MAX_SESSIONS_PAGE),
};
Expand Down Expand Up @@ -495,7 +498,9 @@ impl Records {
}

/// `agentSessions.read`: the messages of a byte range of a session file,
/// as the agent's plugin reads them.
/// as the agent's plugin reads them. A range that ends inside a line is
/// read up to its last whole line, and `end` says where that is, so a host
/// reads a long session a page at a time and no line is cut in two.
pub fn read(&self, runtime: &Runtime, payload: Value) -> Result<Value, CoreError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
Expand All @@ -522,14 +527,40 @@ impl Records {
"The file is not in a session directory of the agent.",
)
})?;
let bytes = {
let (bytes, ends_line) = {
let reader = self.lock_reader();
let store = reader.as_ref().ok_or_else(not_configured)?;
store.read_range(&request.agent, &request.path, request.range)?
let bytes = store.read_range(&request.agent, &request.path, request.range)?;
// A range ends a line when its last byte is a newline or the byte
// after it begins one; a span a plugin recorded without its
// newline is read whole.
let ends_line = match &bytes {
Some(bytes) if bytes.last() != Some(&b'\n') => {
let next = ByteRange {
start: request.range.end,
end: request.range.end.saturating_add(1),
};
!matches!(
store.read_range(&request.agent, &request.path, next),
Ok(Some(byte)) if byte != b"\n" && byte != b"\r"
)
}
_ => true,
};
(bytes, ends_line)
};
let Some(bytes) = bytes else {
let Some(mut bytes) = bytes else {
return Ok(json!({ "changed": true, "messages": [] }));
};
if !ends_line {
bytes.truncate(whole_lines(&bytes));
}
// A range inside one line reads nothing and answers its own start, so
// the caller asks again with a larger range.
let end = request.range.start + bytes.len() as u64;
if bytes.is_empty() {
return Ok(json!({ "changed": false, "messages": [], "end": end }));
}
let items = vec![json!({ "path": request.path, "lines": text_lines(&bytes) })];
let answers = call_read(
&*runtime.link,
Expand All @@ -544,7 +575,7 @@ impl Records {
.map(decode_messages)
.transpose()?
.unwrap_or_default();
Ok(json!({ "changed": false, "messages": messages }))
Ok(json!({ "changed": false, "messages": messages, "end": end }))
}

/// `agentSessions.stats`: usage of the readable agents for the host.
Expand Down Expand Up @@ -573,8 +604,8 @@ impl Records {
"Group by day, agent, model, session or cwd.",
)
})?;
let summaries = match allowed_agents(runtime, request.agents) {
None => json!([]),
let (summaries, speeds) = match allowed_agents(runtime, request.agents) {
None => (json!([]), json!([])),
Some(agents) => {
let filter = CallFilter {
agents,
Expand All @@ -589,28 +620,37 @@ impl Records {
};
Ok(json!({
"summaries": summaries,
"speeds": speeds,
"rateLimits": self.rate_limit_entries(runtime),
}))
}

/// The summaries of the calls `filter` selects, grouped by `group_by`,
/// and the models ranked by median output speed over the same calls.
fn summarize(
&self,
store: &SessionStore,
filter: &CallFilter,
group_by: GroupBy,
) -> Result<Value, CoreError> {
) -> Result<(Value, Value), CoreError> {
let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner);
let mut summarizer = Summarizer::new(group_by, prices.as_ref());
let mut speeds = SpeedRanker::default();
store.for_each_call(filter, |entry| {
summarizer.add(&entry);
speeds.add(&entry.call);
Ok(())
})?;
Ok(serde_json::to_value(summarizer.finish()).unwrap_or_else(|_| json!([])))
Ok((
serde_json::to_value(summarizer.finish()).unwrap_or_else(|_| json!([])),
serde_json::to_value(speeds.finish()).unwrap_or_else(|_| json!([])),
))
}

/// Answers `lithe/host/agents/usage` for a plugin granted
/// `agents.usage.read`: totals of the readable agents, grouped by day,
/// agent or model, and their rate limits. It carries no conversation text,
/// agent or model, the models' median output speeds, and the agents'
/// rate limits. It carries no conversation text,
/// titles, session IDs or directories. Runs with the asking backend's
/// session lock held, so it never waits for the cache.
pub fn usage(&self, runtime: &Runtime, params: &Value) -> Result<Value, AgentHostFailure> {
Expand Down Expand Up @@ -645,8 +685,8 @@ impl Records {
.iter()
.map(CatalogAgent::record_key)
.collect();
let summaries = if agents.is_empty() {
json!([])
let (summaries, speeds) = if agents.is_empty() {
(json!([]), json!([]))
} else {
let reader = match self.reader.try_lock() {
Ok(reader) => reader,
Expand Down Expand Up @@ -678,6 +718,7 @@ impl Records {
"sinceMs": since_ms,
"untilMs": until_ms,
"summaries": summaries,
"speeds": speeds,
"rateLimits": self.rate_limit_entries(runtime),
}))
}
Expand Down Expand Up @@ -901,6 +942,15 @@ fn backend_for(
})
}

/// 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 {
bytes
.iter()
.rposition(|byte| *byte == b'\n')
.map_or(0, |index| index + 1)
}

/// The lines of `bytes` as text, without their line breaks.
fn text_lines(bytes: &[u8]) -> Vec<String> {
if bytes.is_empty() {
Expand Down
60 changes: 58 additions & 2 deletions rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,8 @@ fn scan(params: &Value) -> Value {
"startedAtMs": record["at"],
"model": record["model"],
"tokens": { "input": record["input"], "output": record["output"] },
"firstTokenMs": record["first"],
"durationMs": record["duration"],
"range": range,
})),
Some("limits") => {
Expand Down Expand Up @@ -1222,7 +1224,7 @@ fn write_session_file(harness: &Harness, now: i64) -> PathBuf {
let lines = [
json!({ "type": "session", "id": "s1", "cwd": "/work/project", "at": now }),
json!({ "type": "user", "session": "s1", "text": "hello from the user", "at": now }),
json!({ "type": "call", "session": "s1", "key": "c1", "model": "sample-model", "input": 100, "output": 20, "at": now }),
json!({ "type": "call", "session": "s1", "key": "c1", "model": "sample-model", "input": 100, "output": 300, "first": 500, "duration": 2500, "at": now }),
json!({ "type": "limits", "at": now, "used": 40.0 }),
];
let text: String = lines.iter().map(|line| format!("{line}\n")).collect();
Expand Down Expand Up @@ -1274,8 +1276,58 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() {
);
assert_eq!(
read,
json!({ "changed": false, "messages": [{ "role": "user", "text": "hello from the user" }] })
json!({
"changed": false,
"messages": [{ "role": "user", "text": "hello from the user" }],
"end": hits[0]["range"]["end"],
})
);

// The list gives how much of the file the cache has read and finds one
// session by its ID, so a viewer can page through a whole record.
let size = fs::metadata(&file).unwrap().len();
assert_eq!(sessions[0]["readBytes"], size, "{sessions}");
let found = harness.run("agentSessions.list", json!({ "sessionID": "s1" }))["sessions"].clone();
assert_eq!(found.as_array().map(Vec::len), Some(1), "{found}");
let none = harness.run("agentSessions.list", json!({ "sessionID": "s9" }))["sessions"].clone();
assert_eq!(none.as_array().map(Vec::len), Some(0), "{none}");
let whole = harness.run(
"agentSessions.read",
json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": 0, "end": size } }),
);
assert_eq!(whole["end"], size, "{whole}");
assert_eq!(
whole["messages"].as_array().map(Vec::len),
Some(1),
"{whole}"
);
// A page that ends inside a line stops at the line before it, and the
// plugin never sees the cut line.
let text = fs::read_to_string(&file).unwrap();
let second = text.find('\n').unwrap() as u64 + 1;
let third = second + text[second as usize..].find('\n').unwrap() as u64 + 1;
let page = harness.run(
"agentSessions.read",
json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": 0, "end": third + 5 } }),
);
assert_eq!(page["end"], third, "{page}");
assert_eq!(page["messages"].as_array().map(Vec::len), Some(1), "{page}");
let last = harness
.link
.calls_of("sessions.read")
.last()
.cloned()
.unwrap();
let sent = last["items"][0]["lines"].as_array().map(Vec::len);
assert_eq!(sent, Some(2), "{last}");
let calls = harness.link.calls_of("sessions.read").len();
let inside = harness.run(
"agentSessions.read",
json!({ "agent": AGENT_KEY, "path": path_text(&file), "range": { "start": second + 1, "end": second + 5 } }),
);
let expected = json!({ "changed": false, "messages": [], "end": second + 1 });
assert_eq!(inside, expected);
assert_eq!(harness.link.calls_of("sessions.read").len(), calls);
assert_eq!(
harness.refused(
"agentSessions.read",
Expand All @@ -1287,6 +1339,9 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() {
let stats = harness.run("agentSessions.stats", json!({ "groupBy": "model" }));
assert_eq!(stats["summaries"][0]["calls"], 1, "{stats}");
assert_eq!(stats["summaries"][0]["tokens"]["input"], 100, "{stats}");
// 300 output tokens in the 2 seconds after the first token.
let speed = json!([{ "model": "sample-model", "calls": 1, "medianTokensPerSecond": 150.0, "lowerBound": false }]);
assert_eq!(stats["speeds"], speed, "{stats}");
assert_eq!(
stats["rateLimits"][0]["windows"][0]["usedPercent"], 40.0,
"{stats}"
Expand All @@ -1299,6 +1354,7 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() {
.answer(AGENTS_USAGE, json!({ "groupBy": "agent" }))
.expect("usage");
assert_eq!(usage["summaries"][0]["calls"], 1, "{usage}");
assert_eq!(usage["speeds"], speed, "{usage}");
let text = usage.to_string();
for private in ["\"s1\"", "/work/project", "hello", "s1.jsonl"] {
assert!(!text.contains(private), "usage carries {private}: {text}");
Expand Down
Loading
Loading