Skip to content
Draft
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: 67 additions & 5 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -491,18 +491,25 @@ or removing a command fails until the table changes in the same commit.
| `agents.close` | End a live agent session |
| `agents.waitEvents` | Wait, bounded, for agent session events after a sequence |
| `agents.projection` | Read a bounded conversation view or apply a loaded history page |
| `agentSessions.configure` | Open the agent session record cache |
| `agentSessions.configure` | Open the agent session record cache, and with `dataDirectory` the user's usage settings and rate-limit history in the platform's application data |
| `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, 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.stats` | Sum recorded agent usage with the latest rate limits. Optional `overview` returns totals, breakdown and time series in one snapshot, and with `overview.speeds: true` also the speed ranking; `groupBy: "hour"` returns sparse `{kind: "hour", startMs}` keys aligned to the fixed UTC offset or optional `hourAnchorMs`; groups and splits by the plugin's `account` and `purpose` labels and filters by them, by `cancelled` and by whole working directories (`cwds`); `sessions: {top?}` adds figures per session (nearest-rank p50, p90, p99, mean and max of calls, tokens, cost and duration, and the costliest sessions), `messages: true` the messages per hour or day, and a chosen currency `currency {code, perUSD, atMs}` |
| `agentSessions.calls` | List a page of recorded agent calls, most recent first, filtered like `agentSessions.stats` (`cwds` included), with their cost, cache hit rate and speed, the `generation` and `size` that open the call with `agentSessions.page`, and `context {tokens, window?, share?}`, how full the call's context was against the model's listed window |
| `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 |
| `agentUsage.read` | Read the user's usage settings: the chosen currency, the kept exchange rates and each installed agent's prices and alerts |
| `agentUsage.setPrice` | Set or remove the price of one model of an agent whose plugin declares `usage.customPrices` (user requests only); its calls use it before the price table |
| `agentUsage.setAlert` | Set or remove alert thresholds on a rate-limit window of an agent whose plugin declares `usage.rateLimitAlerts` (user requests only) |
| `agentUsage.setCurrency` | Choose the currency costs are shown in, one with an exchange rate a plugin reported, or US dollars (user requests only) |
| `agentUsage.refreshRateLimits` | Ask the plugin's `usage.rateLimits` function for the agent's current rate limits and keep them as its latest snapshot (user requests only) |
| `agentUsage.refreshExchangeRates` | Ask the plugin's `usage.exchangeRates` function for rates of currencies per US dollar and keep them (user requests only) |
| `agentUsage.rateLimitHistory` | Read the kept readings of an agent's rate-limit windows in a range |
| `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 @@ -9477,5 +9484,60 @@ 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.
#### Usage features

A plugin declares the usage features it implements for an agent in
`agents[].usage {rateLimits?, exchangeRates?, customPrices?,
rateLimitAlerts?}`; the catalog gives `usage` with each as a boolean. An
`agentUsage.*` command for a feature the declaration leaves out refuses with
`agentUsage.notDeclared` (`not_supported`), which the host shows as
unsupported. Core makes no network request for any of them.

- `refreshRateLimits {pluginID, agentID}` calls the plugin function with
`{agentID}` (15 seconds), checks the answer as a `rateLimits` session event
(`agentUsage.invalidAnswer`), keeps it timed now and answers `{rateLimits}`,
the agent's entry as `agentSessions.stats` gives it.
- `refreshExchangeRates {pluginID, agentID, currencies}` takes 1–32 ISO 4217
codes other than `USD` (`agentUsage.invalidCurrency`), calls the function
with `{agentID, base: "USD", currencies}` and accepts exactly `{rates}`, units
per US dollar above 0 and at most 10000000 for asked currencies. It answers
every kept rate, `{currency, perUSD, atMs, pluginID, agentID}`.
`setCurrency {currency}` takes a code with a kept rate
(`agentUsage.noExchangeRate`), or `null` or `USD`. Costs stay in US dollars;
`agentSessions.stats` adds `currency {code, perUSD, atMs}`.
- `setPrice {pluginID, agentID, model, price}`: `price` is `{input, output,
cacheRead?, cacheWrite?, reasoning?}` in US dollars per million tokens, 0 to
100000 each, or `null`; at most 256 models per agent
(`agentUsage.invalidPrice`). The agent's calls of `model` use it whatever
provider served them, before the price table and without one.
- `setAlert {pluginID, agentID, window, thresholds}`: up to four percentages
1–100, duplicates dropped, `[]` removing them; at most eight windows per
agent (`agentUsage.invalidAlert`). Rate-limit windows then carry `alert
{thresholds, reached?}`, and Core logs `agent.usage.alert_hit` when a kept
snapshot reaches a higher threshold than the one before it.
- `rateLimitHistory {pluginID, agentID, window?, sinceMs?, untilMs?}` answers
`{windows: [{window, label?, windowMinutes?, points: [{atMs, usedPercent,
resetsAtMs?}]}]}`, points oldest first (`agentUsage.invalidRange` when the
range ends before it starts). Every kept snapshot adds a point per window,
at least five minutes apart within a cycle (a closer reading replaces the
last value), a new cycle always starting one; points older than 35 days
and beyond 4000 per window are dropped, and `agentSessions.forget` removes
the agent's history.
- `read {}` answers `{currency?, exchangeRates, agents: [{pluginID, agentID,
prices, alerts}]}`.

The settings (`usage-settings.json`) and history (`rate-limit-history.json`)
live owner-only in the `dataDirectory` of `agentSessions.configure`, which is
absolute and not the cache directory (`agentSessions.invalidDirectory`);
without it every command but `refreshRateLimits` refuses with
`agentUsage.notConfigured`. A settings file Core cannot read is moved to
`usage-settings.unreadable.json`. Changes and plugin calls run only for user
requests (`agentUsage.userActionRequired`). Other refusals:
`agentUsage.unknownAgent`, `agentUsage.notGranted` (the user enabled neither
running nor reading the agent), `agentUsage.backendUnavailable`,
`agentUsage.pluginFailed` and `agentUsage.saveFailed`.

The session cache's layout version is 5, which added the `account`,
`purpose`, `cancelled` and `toolUses` of calls and the daily rows that count
them: a cache of another version is deleted and rebuilt from the session
files on the first sync.
104 changes: 104 additions & 0 deletions rust/crates/agent-runtime/src/files.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
//! Files the runtime keeps for itself or edits for the user: reads bounded
//! in size, and writes that replace a file whole, so that a reader sees
//! either the old bytes or the new ones and never part of a write.

use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

/// Why a bounded read failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReadFailure {
/// The file is larger than the bound.
TooLarge,
/// Something other than a file is there, or reading it failed.
Io(io::ErrorKind),
}

impl ReadFailure {
/// The failure's category, as log events name it.
pub(crate) fn kind(self) -> io::ErrorKind {
match self {
ReadFailure::TooLarge => io::ErrorKind::FileTooLarge,
ReadFailure::Io(kind) => kind,
}
}
}

/// The bytes of the file at `path`, following links; `None` when nothing is
/// there. A file larger than `max` is refused without reading more than
/// `max + 1` bytes of it.
pub(crate) fn read_bounded(path: &Path, max: u64) -> Result<Option<Vec<u8>>, ReadFailure> {
let failed = |error: io::Error| ReadFailure::Io(error.kind());
let mut file = match fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(failed(error)),
};
let metadata = file.metadata().map_err(failed)?;
if !metadata.is_file() {
return Err(ReadFailure::Io(io::ErrorKind::InvalidInput));
}
if metadata.len() > max {
return Err(ReadFailure::TooLarge);
}
let mut bytes = Vec::new();
Read::by_ref(&mut file)
.take(max + 1)
.read_to_end(&mut bytes)
.map_err(failed)?;
if bytes.len() as u64 > max {
return Err(ReadFailure::TooLarge);
}
Ok(Some(bytes))
}

/// A new name next to `target`, unique within the process, for a file
/// written for `purpose` and then renamed over `target` or removed.
pub(crate) fn sibling_temporary(target: &Path, purpose: &str) -> Option<PathBuf> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let parent = target.parent()?;
let name = target.file_name()?.to_string_lossy();
Some(parent.join(format!(
".{name}.lithe-{purpose}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
)))
}

/// Replaces the file at `target` with `bytes`: a new owner-only file next
/// to it, given the old file's permissions when there is one, written to
/// disk, then renamed over it. `target` is never a link; callers resolve
/// links first. When the write fails and the new file cannot be removed
/// either, `kept` hears why, since that file may hold a copy of `bytes`.
pub(crate) fn replace_file(
target: &Path,
bytes: &[u8],
kept: impl FnOnce(&io::Error),
) -> io::Result<()> {
let temporary = sibling_temporary(target, "write")
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
let existing = fs::metadata(target).ok();
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
lithe_platform::fs::owner_only_file(&mut options);
let result = (|| {
let mut file = options.open(&temporary)?;
file.write_all(bytes)?;
if let Some(metadata) = &existing {
fs::set_permissions(&temporary, metadata.permissions())?;
}
file.sync_all()?;
drop(file);
fs::rename(&temporary, target)
})();
if result.is_err() {
if let Err(error) = fs::remove_file(&temporary) {
if error.kind() != io::ErrorKind::NotFound {
kept(&error);
}
}
}
result
}
20 changes: 10 additions & 10 deletions rust/crates/agent-runtime/src/interaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! because the engine may call back while holding its own backend lock.

use crate::live::{self, LiveSession};
use crate::Runtime;
use crate::{refusal, require_user, Runtime};
use lithe_plugin_rpc::{codes, AGENTS_DID_ANSWER_QUESTION, AGENTS_DID_CANCEL, AGENTS_DID_PROMPT};
use lithe_protocol::{CoreError, ErrorCode};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -234,7 +234,7 @@ pub(crate) enum Delivery {

pub(crate) fn send(session: &LiveSession, delivery: Delivery) -> Result<(), CoreError> {
session.interaction_sender.try_send(delivery).map_err(|_| {
live::refusal(
refusal(
ErrorCode::InvalidRequest,
"agents.interactionBusy",
"The agent input queue is busy; try again.",
Expand Down Expand Up @@ -443,7 +443,7 @@ pub(crate) fn worker(
pub(crate) fn delivered(receiver: mpsc::Receiver<bool>) -> Result<(), CoreError> {
match receiver.recv_timeout(std::time::Duration::from_secs(5)) {
Ok(true) | Err(mpsc::RecvTimeoutError::Timeout) => Ok(()),
_ => Err(live::refusal(
_ => Err(refusal(
ErrorCode::ProcessFailed,
"agents.backendUnavailable",
"The agent backend did not acknowledge the input.",
Expand Down Expand Up @@ -474,15 +474,15 @@ pub(crate) fn respond_question(runtime: &Arc<Runtime>, payload: Value) -> Result
cancelled: bool,
}
let request: Request = crate::decode(payload)?;
live::require_user("answer a question of")?;
require_user(|| live::user_action_required("answer a question of"))?;
let session = runtime.live.session(&request.session)?;
let mut state = session.lock_turns();
let pending = state
.interaction
.questions
.get(&request.request)
.ok_or_else(|| {
live::refusal(
refusal(
ErrorCode::InvalidRequest,
"agents.questionNotPending",
"This question is no longer waiting for an answer.",
Expand All @@ -493,7 +493,7 @@ pub(crate) fn respond_question(runtime: &Arc<Runtime>, payload: Value) -> Result
|| state.interaction.stopping
|| state.active_turn != Some(pending.turn)
{
return Err(live::refusal(
return Err(refusal(
ErrorCode::InvalidRequest,
"agents.questionNotPending",
"The question's turn is stopping or ended.",
Expand Down Expand Up @@ -524,7 +524,7 @@ pub(crate) fn respond_question(runtime: &Arc<Runtime>, payload: Value) -> Result
})
};
if !valid {
return Err(live::refusal(
return Err(refusal(
ErrorCode::InvalidRequest,
"agents.invalidQuestionAnswer",
"Answer each question using its options or allowed text.",
Expand Down Expand Up @@ -558,11 +558,11 @@ pub(crate) fn update_queue(runtime: &Arc<Runtime>, payload: Value) -> Result<Val
resume: bool,
}
let request: Request = crate::decode(payload)?;
live::require_user("change the queue of")?;
require_user(|| live::user_action_required("change the queue of"))?;
let session = runtime.live.session(&request.session)?;
let mut state = session.lock_turns();
if state.interaction.closed || (request.resume && state.interaction.stopping) {
return Err(live::refusal(
return Err(refusal(
ErrorCode::InvalidRequest,
"agents.turnStopping",
"Wait for the current turn to stop.",
Expand All @@ -575,7 +575,7 @@ pub(crate) fn update_queue(runtime: &Arc<Runtime>, payload: Value) -> Result<Val
.iter()
.position(|v| v.id == id)
.ok_or_else(|| {
live::refusal(
refusal(
ErrorCode::InvalidRequest,
"agents.inputNotQueued",
"This input is no longer queued.",
Expand Down
Loading