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
72 changes: 70 additions & 2 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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.
12 changes: 9 additions & 3 deletions rust/crates/agent-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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<const N: usize>(event: &str, fields: [(&str, Value); N]) {
log_fields(event, fields.into_iter());
}
Expand All @@ -215,5 +219,7 @@ pub(crate) fn log_fields<'a>(event: &str, fields: impl Iterator<Item = (&'a str,
let fields: BTreeMap<String, Value> = 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();
}
}
48 changes: 44 additions & 4 deletions rust/crates/agent-runtime/src/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,11 @@ fn start_checked(runtime: &Arc<Runtime>, request: StartRequest) -> Result<Value,
runtime.live.queue.views.release(&id);
runtime.live.lock().remove(&id);
streams.handle.terminate();
let _ = streams.handle.dispose(DISPOSE_TIMEOUT);
if let Err(error) = streams.handle.dispose(DISPOSE_TIMEOUT) {
// The refusal below says why the start failed; this says what it
// left: a CLI that may still be running.
log_cleanup_failed(&request.plugin_id, &request.agent_id, &id, &error);
}
return Err(refusal(
ErrorCode::ProcessFailed,
"agents.backendUnavailable",
Expand Down Expand Up @@ -927,6 +931,29 @@ fn read_output(runtime: &Arc<Runtime>, session: &Arc<LiveSession>, output: Box<d
}
}

/// Logs that Core could not reap the CLI of a session, which may still be
/// running. The error is redacted and carries Core's code, never the CLI's
/// arguments or output.
fn log_cleanup_failed(plugin: &str, agent: &str, session: &str, error: &CoreError) {
log(
"agent.session.cleanup_failed",
[
("plugin", json!(plugin)),
("agent", json!(agent)),
("session", json!(session)),
(
"error",
json!(lithe_request_context::events::redact(&error.message)),
),
(
"error_code",
serde_json::to_value(&error.code).expect("Core error codes encode"),
),
("error_domain", json!("core")),
],
);
}

fn finish(runtime: &Arc<Runtime>, session: &Arc<LiveSession>) {
let handle = &session.handle;
let deadline = Instant::now() + EXIT_WAIT;
Expand All @@ -938,7 +965,15 @@ fn finish(runtime: &Arc<Runtime>, session: &Arc<LiveSession>) {
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 {
Expand All @@ -957,9 +992,14 @@ fn finish(runtime: &Arc<Runtime>, session: &Arc<LiveSession>) {
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 {
Expand Down
Loading
Loading