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
2 changes: 1 addition & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ 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, or find one by its ID |
| `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.stats` | Sum recorded agent usage with the latest rate limits |
Expand Down
67 changes: 60 additions & 7 deletions rust/crates/agent-runtime/src/records.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use lithe_agent_sessions::pricing::PriceTable;
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,
SessionOrder, SessionParser, SessionSource, SessionStore, MAX_FILTER_DIRECTORIES,
MAX_SEARCH_HITS, MAX_SESSIONS_PAGE,
};
use lithe_lsp_engine::agent_host::AgentHostFailure;
use lithe_plugin_agents::SessionSourceDeclaration;
Expand Down Expand Up @@ -54,6 +55,9 @@ const MAX_MESSAGE_TEXT_BYTES: usize = 1024 * 1024;
/// Longest range `lithe/host/agents/usage` sums, in days.
const MAX_USAGE_DAYS: i64 = 366;

/// Longest directory `agentSessions.list`'s `cwdUnder` takes, in bytes.
const MAX_FILTER_DIRECTORY_BYTES: usize = 4096;

/// Largest `rate-limits.json` Core loads.
const MAX_RATE_FILE_BYTES: u64 = 1024 * 1024;

Expand Down Expand Up @@ -340,9 +344,17 @@ impl Records {
Ok(json!({ "files": files }))
}

/// `agentSessions.list`: the sessions of the readable agents, newest
/// first, with their titles when asked.
/// `agentSessions.list`: a page of the readable agents' sessions, most
/// recently active or started first, with their titles and the counts of
/// the whole list when asked.
pub fn list(&self, runtime: &Runtime, payload: Value) -> Result<Value, CoreError> {
#[derive(Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
enum ListOrder {
#[default]
Updated,
Started,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ListRequest {
Expand All @@ -351,32 +363,67 @@ impl Records {
#[serde(default)]
cwd: Option<String>,
#[serde(default)]
cwd_under: Vec<String>,
#[serde(default)]
active_since_ms: Option<i64>,
#[serde(rename = "sessionID", default)]
session_id: Option<String>,
#[serde(default)]
order: ListOrder,
#[serde(default)]
offset: u64,
#[serde(default)]
limit: Option<usize>,
#[serde(default)]
titles: bool,
#[serde(default)]
counts: bool,
}
let request: ListRequest = crate::decode(payload)?;
if request.cwd_under.len() > MAX_FILTER_DIRECTORIES
|| request.cwd_under.iter().any(|directory| {
directory.is_empty()
|| directory.len() > MAX_FILTER_DIRECTORY_BYTES
|| directory.chars().any(char::is_control)
})
{
return Err(CoreError::new(
ErrorCode::InvalidRequest,
"Invalid agent command payload: cwdUnder",
)
.with_details("agents.invalidPayload"));
}
let Some(agents) = allowed_agents(runtime, request.agents) else {
return Ok(json!({ "sessions": [] }));
let mut answer = json!({ "sessions": [] });
if request.counts {
answer["total"] = json!(0);
answer["groups"] = json!([]);
answer["groupsTruncated"] = json!(false);
}
return Ok(answer);
};
let filter = SessionFilter {
agents,
cwd: request.cwd,
cwd_under: request.cwd_under,
active_since_ms: request.active_since_ms,
session_id: request.session_id,
order: match request.order {
ListOrder::Updated => SessionOrder::Updated,
ListOrder::Started => SessionOrder::Started,
},
offset: request.offset,
limit: request.limit.unwrap_or(100).clamp(1, MAX_SESSIONS_PAGE),
};
let (entries, title_bytes) = {
let (entries, title_bytes, counts) = {
let reader = self.lock_reader();
let store = reader.as_ref().ok_or_else(not_configured)?;
let entries = store.sessions(&filter)?;
let counts = if request.counts {
Some(store.session_counts(&filter)?)
} else {
None
};
let mut title_bytes = Vec::with_capacity(entries.len());
for entry in &entries {
let bytes = match (request.titles, entry.title_range) {
Expand All @@ -388,7 +435,7 @@ impl Records {
};
title_bytes.push(bytes);
}
(entries, title_bytes)
(entries, title_bytes, counts)
};

let mut titles: Vec<Option<String>> = vec![None; entries.len()];
Expand Down Expand Up @@ -455,7 +502,13 @@ impl Records {
value
})
.collect();
Ok(json!({ "sessions": sessions }))
let mut answer = json!({ "sessions": sessions });
if let Some(counts) = counts {
answer["total"] = json!(counts.total);
answer["groups"] = serde_json::to_value(&counts.groups).unwrap_or_else(|_| json!([]));
answer["groupsTruncated"] = json!(counts.groups_truncated);
}
Ok(answer)
}

/// `agentSessions.search`: where the readable agents' sessions contain
Expand Down
58 changes: 58 additions & 0 deletions rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,64 @@ fn write_session_file(harness: &Harness, now: i64) -> PathBuf {
path
}

#[test]
fn records_list_filters_under_directories_counts_and_describes_activity() {
let harness = Harness::new("records-list", ALL_GRANTS);
let now = crate::now_ms();
write_session_file(&harness, now);
harness.run(
"agentSessions.sync",
json!({ "pluginID": PLUGIN, "agentID": AGENT }),
);

let answer = harness.run(
"agentSessions.list",
json!({ "cwdUnder": ["/work/"], "order": "started", "counts": true, "limit": 1 }),
);
assert_eq!(answer["total"], 1, "{answer}");
assert_eq!(answer["groupsTruncated"], false, "{answer}");
assert_eq!(
answer["groups"],
json!([{ "cwd": "/work/project", "count": 1, "updatedAtMs": now }])
);
let session = &answer["sessions"][0];
assert_eq!(session["messageCount"], 1, "{answer}");
assert_eq!(session["subagentCount"], 0, "{answer}");
assert_eq!(session["model"], "sample-model", "{answer}");
// The last message's range reads back the message itself.
let read = harness.run(
"agentSessions.read",
json!({ "agent": AGENT_KEY, "path": session["path"], "range": session["lastMessageRange"] }),
);
assert_eq!(read["messages"][0]["text"], "hello from the user", "{read}");

// Without `counts` the answer keeps its old shape; a directory that holds
// none of the sessions lists none and counts none.
let plain = harness.run("agentSessions.list", json!({}));
assert!(plain.get("total").is_none(), "{plain}");
let elsewhere = harness.run(
"agentSessions.list",
json!({ "cwdUnder": ["/work/project-two"], "counts": true }),
);
assert_eq!(
(elsewhere["sessions"].clone(), elsewhere["total"].clone()),
(json!([]), json!(0))
);

for payload in [
json!({ "cwdUnder": [""] }),
json!({ "cwdUnder": ["/work\nproject"] }),
json!({ "cwdUnder": ["/w".repeat(2_049)] }),
json!({ "cwdUnder": vec!["/work"; 65] }),
json!({ "order": "title" }),
] {
assert_eq!(
harness.refused("agentSessions.list", payload),
"agents.invalidPayload"
);
}
}

#[test]
fn records_sync_list_search_read_and_sum_through_the_plugin() {
let harness = Harness::new("records", ALL_GRANTS);
Expand Down
7 changes: 4 additions & 3 deletions rust/crates/agent-sessions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ pub use model::{
ByteRange, CallRecord, IndexSpan, ScanChunk, ScanOutput, SessionMeta, SessionParser, Tokens,
};
pub use store::{
database_file_name, CallEntry, CallFilter, FileFailure, SearchHit, SearchQuery, SessionEntry,
SessionFilter, SessionStore, SyncReport, MAX_ID_BYTES, MAX_INDEXED_SPAN_BYTES, MAX_LABEL_BYTES,
MAX_READ_BYTES, MAX_RECORDS_PER_CHUNK, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, MAX_STATE_BYTES,
database_file_name, CallEntry, CallFilter, FileFailure, SearchHit, SearchQuery, SessionCounts,
SessionEntry, SessionFilter, SessionGroup, SessionOrder, SessionStore, SyncReport,
MAX_FILTER_DIRECTORIES, MAX_ID_BYTES, MAX_INDEXED_SPAN_BYTES, MAX_LABEL_BYTES, MAX_READ_BYTES,
MAX_RECORDS_PER_CHUNK, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, MAX_SESSION_GROUPS, MAX_STATE_BYTES,
SCHEMA_VERSION,
};
Loading
Loading