From 89eb54cface418ce3490a9a40dae609bae4f7df9 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 03:28:42 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat(agents):=20API-45=20Agent=20=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E6=97=B6=E3=80=81=E6=B8=85=E5=8D=95=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E4=B8=8E=E5=AE=BF=E4=B8=BB=E6=96=B9=E6=B3=95=EF=BC=88=E8=BF=9B?= =?UTF-8?q?=E8=A1=8C=E4=B8=AD=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/Cargo.lock | 30 + rust/crates/agent-runtime/Cargo.toml | 26 + rust/crates/agent-runtime/src/backend.rs | 73 + rust/crates/agent-runtime/src/catalog.rs | 192 +++ rust/crates/agent-runtime/src/events.rs | 630 ++++++++ rust/crates/agent-runtime/src/lib.rs | 208 +++ rust/crates/agent-runtime/src/live.rs | 1026 ++++++++++++ rust/crates/agent-runtime/src/records.rs | 1165 ++++++++++++++ rust/crates/agent-runtime/src/tests.rs | 1410 +++++++++++++++++ .../diagnostics/src/catalog_generated.rs | 101 ++ .../lsp-client/src/client/server_messages.rs | 15 + rust/crates/lsp-client/src/lib.rs | 4 + rust/crates/lsp-engine/src/agent_host.rs | 335 ++++ rust/crates/lsp-engine/src/events.rs | 5 + rust/crates/lsp-engine/src/lib.rs | 14 + rust/crates/lsp-engine/src/lifecycle.rs | 1 + rust/crates/lsp-engine/src/relay_hub.rs | 2 +- rust/crates/lsp-engine/src/server_messages.rs | 6 + rust/crates/lsp-transport/src/scripted.rs | 22 + rust/crates/plugin-agents/Cargo.toml | 12 + rust/crates/plugin-agents/src/lib.rs | 635 ++++++++ rust/crates/plugin-agents/src/tests.rs | 249 +++ rust/crates/plugin-manifest/Cargo.toml | 1 + rust/crates/plugin-manifest/src/manifest.rs | 11 + .../crates/plugin-manifest/src/permissions.rs | 36 + rust/crates/plugin-manifest/src/validation.rs | 22 +- rust/crates/plugin-model/src/capabilities.rs | 6 + rust/crates/plugin-rpc/src/host_api.rs | 9 +- .../plugin-rpc/src/host_notifications.rs | 72 + rust/crates/plugin-rpc/src/host_requests.rs | 37 + rust/crates/plugin-rpc/src/lib.rs | 15 + rust/logging/events/agent.json | 97 +- 32 files changed, 6462 insertions(+), 5 deletions(-) create mode 100644 rust/crates/agent-runtime/Cargo.toml create mode 100644 rust/crates/agent-runtime/src/backend.rs create mode 100644 rust/crates/agent-runtime/src/catalog.rs create mode 100644 rust/crates/agent-runtime/src/events.rs create mode 100644 rust/crates/agent-runtime/src/lib.rs create mode 100644 rust/crates/agent-runtime/src/live.rs create mode 100644 rust/crates/agent-runtime/src/records.rs create mode 100644 rust/crates/agent-runtime/src/tests.rs create mode 100644 rust/crates/lsp-engine/src/agent_host.rs create mode 100644 rust/crates/plugin-agents/Cargo.toml create mode 100644 rust/crates/plugin-agents/src/lib.rs create mode 100644 rust/crates/plugin-agents/src/tests.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index c3f3b966..2124d248 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -935,6 +935,25 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +[[package]] +name = "lithe-agent-runtime" +version = "0.1.0" +dependencies = [ + "lithe-agent-sessions", + "lithe-diagnostics", + "lithe-lsp-engine", + "lithe-lsp-transport", + "lithe-plugin-agents", + "lithe-plugin-manifest", + "lithe-plugin-model", + "lithe-plugin-rpc", + "lithe-protocol", + "lithe-request-context", + "lithe-workspace", + "serde", + "serde_json", +] + [[package]] name = "lithe-agent-sessions" version = "0.1.0" @@ -1295,6 +1314,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "lithe-plugin-agents" +version = "0.1.0" +dependencies = [ + "globset", + "lithe-plugin-model", + "serde", + "serde_json", +] + [[package]] name = "lithe-plugin-backend" version = "0.1.0" @@ -1389,6 +1418,7 @@ dependencies = [ "lithe-build", "lithe-debug", "lithe-platform", + "lithe-plugin-agents", "lithe-plugin-backend", "lithe-plugin-functions", "lithe-plugin-grammar", diff --git a/rust/crates/agent-runtime/Cargo.toml b/rust/crates/agent-runtime/Cargo.toml new file mode 100644 index 00000000..6d45e58f --- /dev/null +++ b/rust/crates/agent-runtime/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "lithe-agent-runtime" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Agent CLI sessions Core runs for agent plugins (plan API-45): the CLI processes, Lithe's session events, and the local session records" +publish = false + +[dependencies] +lithe-agent-sessions = { path = "../agent-sessions" } +lithe-diagnostics = { path = "../diagnostics" } +lithe-lsp-engine = { path = "../lsp-engine" } +lithe-lsp-transport = { path = "../lsp-transport" } +lithe-plugin-agents = { path = "../plugin-agents" } +lithe-plugin-manifest = { path = "../plugin-manifest" } +lithe-plugin-model = { path = "../plugin-model" } +lithe-plugin-rpc = { path = "../plugin-rpc" } +lithe-protocol = { path = "../protocol" } +lithe-request-context = { path = "../request-context" } +lithe-workspace = { path = "../workspace" } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +[dev-dependencies] +lithe-diagnostics = { path = "../diagnostics", features = ["test-support"] } +lithe-lsp-transport = { path = "../lsp-transport", features = ["test-support"] } diff --git a/rust/crates/agent-runtime/src/backend.rs b/rust/crates/agent-runtime/src/backend.rs new file mode 100644 index 00000000..e63c7d34 --- /dev/null +++ b/rust/crates/agent-runtime/src/backend.rs @@ -0,0 +1,73 @@ +//! How the runtime reaches agent plugin backends and starts agent CLIs. +//! +//! The runtime never holds one of its own locks while it uses a +//! [`BackendLink`]: the engine calls the runtime back with a backend's session +//! lock held, so a runtime lock held across an engine call could deadlock. + +use lithe_lsp_engine::agent_host::{self, AgentCallFailure}; +use lithe_lsp_transport::process::{LspProcessLauncher, SystemProcessLauncher}; +use lithe_protocol::CoreError; +use serde_json::Value; +use std::sync::Arc; +use std::time::Duration; + +/// The plugin backends and process launcher the runtime uses. The engine +/// implements it in production; tests replace it. +pub(crate) trait BackendLink: Send + Sync { + /// The ready backend session of `plugin_id` that serves `function_id`. + fn session_for( + &self, + plugin_id: &str, + function_id: &str, + root_uri: Option<&str>, + ) -> Option; + + /// Calls a function of a backend and waits for its answer. + fn call( + &self, + session_id: &str, + plugin_id: &str, + function_id: &str, + params: Value, + timeout: Duration, + ) -> Result; + + /// Sends an agent-session notification to a backend. + fn notify(&self, session_id: &str, method: &str, params: Value) -> Result<(), CoreError>; + + /// Starts agent CLI processes. + fn launcher(&self) -> Arc; +} + +/// The engine's plugin backends and real child processes. +pub(crate) struct EngineLink; + +impl BackendLink for EngineLink { + fn session_for( + &self, + plugin_id: &str, + function_id: &str, + root_uri: Option<&str>, + ) -> Option { + agent_host::agent_backend_session(plugin_id, function_id, root_uri) + } + + fn call( + &self, + session_id: &str, + plugin_id: &str, + function_id: &str, + params: Value, + timeout: Duration, + ) -> Result { + agent_host::call_agent_function(session_id, plugin_id, function_id, params, None, timeout) + } + + fn notify(&self, session_id: &str, method: &str, params: Value) -> Result<(), CoreError> { + agent_host::notify_agent_backend(session_id, method, params) + } + + fn launcher(&self) -> Arc { + Arc::new(SystemProcessLauncher) + } +} diff --git a/rust/crates/agent-runtime/src/catalog.rs b/rust/crates/agent-runtime/src/catalog.rs new file mode 100644 index 00000000..f5397e0b --- /dev/null +++ b/rust/crates/agent-runtime/src/catalog.rs @@ -0,0 +1,192 @@ +//! The agents the installed plugins declare, with what the user granted them. +//! +//! The host sends every installed plugin's manifest and granted permissions +//! with `agents.configure`, again whenever a plugin is installed, updated, +//! removed or its grants change. Core validates each manifest itself, so a +//! session only ever runs what a valid manifest declares. + +use lithe_plugin_agents::{ + catalog_entry, AgentDeclaration, PERMISSION_AGENTS_RUN, PERMISSION_AGENTS_SESSIONS, +}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{PoisonError, RwLock}; + +/// Most plugins one `agents.configure` carries. +const MAX_PLUGINS: usize = 1024; + +/// One plugin's agents and grants. +#[derive(Debug, Clone)] +pub(crate) struct PluginAgents { + pub agents: Vec, + pub granted: BTreeSet, +} + +impl PluginAgents { + pub fn may_run(&self) -> bool { + self.granted.contains(PERMISSION_AGENTS_RUN) + } + + pub fn may_read_sessions(&self) -> bool { + self.granted.contains(PERMISSION_AGENTS_SESSIONS) + } +} + +/// An agent found in the catalog. +#[derive(Debug, Clone)] +pub(crate) struct CatalogAgent { + pub plugin_id: String, + pub agent: AgentDeclaration, + pub may_run: bool, + pub may_read_sessions: bool, +} + +impl CatalogAgent { + /// The key of the agent in the session records: unique across plugins. + pub fn record_key(&self) -> String { + record_key(&self.plugin_id, &self.agent.id) + } +} + +/// The key of an agent in the session records. +pub(crate) fn record_key(plugin_id: &str, agent_id: &str) -> String { + format!("{plugin_id}/{agent_id}") +} + +/// Splits a record key into plugin and agent IDs. +pub(crate) fn split_record_key(key: &str) -> Option<(&str, &str)> { + key.split_once('/') +} + +#[derive(Default)] +pub(crate) struct Catalog { + plugins: RwLock>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConfigureRequest { + plugins: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ConfiguredPlugin { + manifest: Value, + #[serde(default)] + granted_permissions: Vec, +} + +impl Catalog { + /// Replaces the catalog with the agents of `payload`'s plugins. Plugins + /// whose manifest is invalid are listed as rejected and left out. + pub fn configure(&self, payload: Value) -> Result { + let request: ConfigureRequest = crate::decode(payload)?; + if request.plugins.len() > MAX_PLUGINS { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many plugins in one agents.configure.", + ) + .with_details("agents.tooManyPlugins")); + } + let mut plugins = BTreeMap::new(); + let mut rejected = Vec::new(); + for plugin in request.plugins { + let plugin_id = plugin + .manifest + .get("id") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let manifest = match lithe_plugin_manifest::validate_manifest_value(plugin.manifest) { + Ok(manifest) => manifest, + Err(rejection) => { + rejected.push(json!({ + "pluginID": plugin_id, + "code": rejection.code, + "message": rejection.message, + })); + continue; + } + }; + if manifest.agents().is_empty() { + continue; + } + let declared: BTreeSet<&str> = + manifest.permissions().iter().map(String::as_str).collect(); + let granted = plugin + .granted_permissions + .into_iter() + .filter(|permission| declared.contains(permission.as_str())) + .collect(); + plugins.insert( + manifest.id().to_string(), + PluginAgents { + agents: manifest.agents().to_vec(), + granted, + }, + ); + } + *self.plugins.write().unwrap_or_else(PoisonError::into_inner) = plugins; + Ok(json!({ "agents": self.entries(), "rejected": rejected })) + } + + /// Every declared agent as the host shows it. + pub fn list(&self) -> Value { + json!({ "agents": self.entries() }) + } + + fn entries(&self) -> Vec { + let plugins = self.plugins.read().unwrap_or_else(PoisonError::into_inner); + plugins + .iter() + .flat_map(|(plugin_id, plugin)| { + plugin.agents.iter().map(move |agent| { + let mut entry = catalog_entry(plugin_id, agent); + entry["mayRun"] = json!(plugin.may_run()); + entry["mayReadSessions"] = json!(plugin.may_read_sessions()); + entry + }) + }) + .collect() + } + + /// The agent `agent_id` of `plugin_id`. + pub fn find(&self, plugin_id: &str, agent_id: &str) -> Option { + let plugins = self.plugins.read().unwrap_or_else(PoisonError::into_inner); + let plugin = plugins.get(plugin_id)?; + let agent = plugin.agents.iter().find(|agent| agent.id == agent_id)?; + Some(CatalogAgent { + plugin_id: plugin_id.to_string(), + agent: agent.clone(), + may_run: plugin.may_run(), + may_read_sessions: plugin.may_read_sessions(), + }) + } + + /// The agent a record key names. + pub fn find_key(&self, key: &str) -> Option { + let (plugin_id, agent_id) = split_record_key(key)?; + self.find(plugin_id, agent_id) + } + + /// Every agent whose session records the user lets Lithe read. + pub fn readable(&self) -> Vec { + let plugins = self.plugins.read().unwrap_or_else(PoisonError::into_inner); + plugins + .iter() + .filter(|(_, plugin)| plugin.may_read_sessions()) + .flat_map(|(plugin_id, plugin)| { + plugin.agents.iter().map(move |agent| CatalogAgent { + plugin_id: plugin_id.clone(), + agent: agent.clone(), + may_run: plugin.may_run(), + may_read_sessions: true, + }) + }) + .filter(|agent| !agent.agent.session_sources.is_empty()) + .collect() + } +} diff --git a/rust/crates/agent-runtime/src/events.rs b/rust/crates/agent-runtime/src/events.rs new file mode 100644 index 00000000..8ddf6fd5 --- /dev/null +++ b/rust/crates/agent-runtime/src/events.rs @@ -0,0 +1,630 @@ +//! Lithe's agent session events: what a plugin backend reports with +//! `lithe/host/agents/report`, the checks Core runs on them, and the bounded +//! queue the host reads with `agents.waitEvents`. +//! +//! The model is the same for every agent. Names follow the Agent Client +//! Protocol where it has one, so an ACP session maps onto it item by item; a +//! field the agent does not report stays absent instead of being estimated. + +use lithe_agent_sessions::Tokens; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Condvar, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +/// Most events one report carries. +pub(crate) const MAX_EVENTS_PER_REPORT: usize = 256; + +/// Longest text of one event, in bytes: a reply, a tool's output or a diff +/// side. A longer text is refused; a backend splits it into deltas. +const MAX_TEXT_BYTES: usize = 1024 * 1024; + +/// Longest ID, title, label or model name, in bytes. +const MAX_LABEL_BYTES: usize = 1024; + +/// Most options of a permission request. +const MAX_PERMISSION_OPTIONS: usize = 8; + +/// Most permission requests a session waits on at once. +const MAX_PENDING_PERMISSIONS: usize = 16; + +/// Most file locations of one tool call. +const MAX_LOCATIONS: usize = 64; + +/// Most entries of a plan. +const MAX_PLAN_ENTRIES: usize = 256; + +/// Most windows of a rate-limit snapshot. +pub(crate) const MAX_RATE_WINDOWS: usize = 8; + +/// Most events the host queue keeps. The host reads continuously; when it +/// falls this far behind, the oldest events are dropped and the next read +/// says so. +const MAX_QUEUED_EVENTS: usize = 8192; + +/// Most events one `agents.waitEvents` returns. +const MAX_EVENTS_PER_WAIT: usize = 512; + +/// Longest wait of one `agents.waitEvents`. +const MAX_WAIT: Duration = Duration::from_secs(30); + +/// A session event a plugin backend reports. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub(crate) enum SessionEvent { + Session(SessionInfo), + Message(MessageEvent), + ToolCall(ToolCallEvent), + Plan(PlanEvent), + PermissionRequested(PermissionRequest), + Usage(UsageEvent), + RateLimits(RateLimits), + TurnEnded(TurnEnded), + Notice(Notice), +} + +/// What the agent says about its session. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct SessionInfo { + /// The agent CLI's own session ID, used to resume and to find the session + /// in the local records. + #[serde(rename = "agentSessionID")] + pub agent_session_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effort: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_version: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum MessageRole { + /// The agent's reply. + Assistant, + /// The agent's reasoning, as the CLI exposes it. + Thought, +} + +/// Text of the agent's reply or reasoning. `delta` text extends the message +/// with the same ID; otherwise it replaces it. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct MessageEvent { + pub turn: u64, + pub role: MessageRole, + #[serde(rename = "messageID")] + pub message_id: String, + pub text: String, + #[serde(default)] + pub delta: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum ToolKind { + Read, + Edit, + Delete, + Move, + Search, + Execute, + Think, + Fetch, + Other, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum ToolStatus { + Pending, + InProgress, + Completed, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ToolLocation { + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ToolDiff { + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub old_text: Option, + pub new_text: String, +} + +/// A tool call of the agent, reported again whenever its status changes. +/// Later reports of the same ID replace the fields they carry. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ToolCallEvent { + pub turn: u64, + #[serde(rename = "toolCallID")] + pub tool_call_id: String, + pub status: ToolStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tool_kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub locations: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub diff: Option, + /// What the tool printed, for example a command's output. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum PlanStatus { + Pending, + InProgress, + Completed, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct PlanEntry { + pub content: String, + pub status: PlanStatus, +} + +/// The agent's plan for the turn; each report replaces the last. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct PlanEvent { + pub turn: u64, + pub entries: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum PermissionOptionKind { + AllowOnce, + AllowAlways, + RejectOnce, + RejectAlways, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct PermissionOption { + pub id: String, + pub label: String, + pub option_kind: PermissionOptionKind, +} + +/// The agent asks the user before it acts. The user picks one of `options`. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct PermissionRequest { + pub turn: u64, + pub permission: String, + pub title: String, + #[serde( + rename = "toolCallID", + default, + skip_serializing_if = "Option::is_none" + )] + pub tool_call_id: Option, + pub options: Vec, +} + +/// Token counts of one model call or of a whole turn, as the agent reports +/// them. `contextUsed` and `contextWindow` describe the context afterwards. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct UsageEvent { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turn: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + #[serde(default)] + pub tokens: Tokens, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context_used: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context_window: Option, + /// What the CLI itself says the turn cost, in US dollars. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd: Option, +} + +/// One rate-limit window of the agent's account. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct RateWindow { + /// Stable ID of the window within the agent, for example `primary`. + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// Share of the window used, 0 to 100. + pub used_percent: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub window_minutes: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resets_at_ms: Option, +} + +/// The agent's rate-limit state. Core keeps the latest snapshot per agent and +/// window for the usage view. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct RateLimits { + pub windows: Vec, + /// The plan the account is on, as the agent names it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum StopReason { + Completed, + Cancelled, + MaxTokens, + MaxTurns, + Refused, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct TurnEnded { + pub turn: u64, + pub reason: StopReason, + /// What the agent said about a failure, shown as it is. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum NoticeLevel { + Info, + Warning, + Error, +} + +/// Something the agent tells the user outside a reply, for example a model +/// fallback or a context compaction. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Notice { + pub level: NoticeLevel, + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option, +} + +/// Why Core refused a report: a stable code for `error.data.code` and a +/// message that names the event by index, never its content. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ReportRefusal { + pub code: &'static str, + pub message: String, +} + +/// The turns and permission requests of one session, which the events of a +/// report must fit. +#[derive(Debug, Clone, Default)] +pub(crate) struct TurnState { + /// The last turn Core started. + pub last_turn: u64, + /// The turn in progress, if any. + pub active_turn: Option, + /// Permission requests waiting for the user: ID to the turn and options. + pub pending: BTreeMap)>, + /// The agent CLI's own session ID, once reported. + pub agent_session_id: Option, +} + +impl TurnState { + /// Starts the next turn. `None` while a turn is still in progress. + pub fn start_turn(&mut self) -> Option { + if self.active_turn.is_some() { + return None; + } + self.last_turn += 1; + self.active_turn = Some(self.last_turn); + Some(self.last_turn) + } + + /// Checks `events` against this state and applies them. Nothing is applied + /// when one event is refused. + pub fn apply(&mut self, events: &[SessionEvent]) -> Result<(), ReportRefusal> { + let mut next = self.clone(); + for (index, event) in events.iter().enumerate() { + next.apply_one(event) + .map_err(|(code, problem)| ReportRefusal { + code, + message: format!("Event {index} of the report {problem}."), + })?; + } + *self = next; + Ok(()) + } + + fn apply_one(&mut self, event: &SessionEvent) -> Result<(), (&'static str, String)> { + check_bounds(event).map_err(|problem| (INVALID_PARAMS, problem))?; + match event { + SessionEvent::Session(info) => { + self.agent_session_id = Some(info.agent_session_id.clone()); + } + SessionEvent::Message(message) => self.require_active(message.turn)?, + SessionEvent::ToolCall(call) => self.require_active(call.turn)?, + SessionEvent::Plan(plan) => self.require_active(plan.turn)?, + SessionEvent::PermissionRequested(request) => { + self.require_active(request.turn)?; + if self.pending.contains_key(&request.permission) { + return Err(( + INVALID_PARAMS, + "repeats a permission ID that is still waiting".to_string(), + )); + } + if self.pending.len() >= MAX_PENDING_PERMISSIONS { + return Err(( + LIMIT_EXCEEDED, + "exceeds the permission requests a session may wait on".to_string(), + )); + } + self.pending.insert( + request.permission.clone(), + (request.turn, request.options.clone()), + ); + } + SessionEvent::Usage(usage) => { + if let Some(turn) = usage.turn { + if turn == 0 || turn > self.last_turn { + return Err(( + PRECONDITION_FAILED, + "names a turn Core has not started".to_string(), + )); + } + } + } + SessionEvent::RateLimits(_) | SessionEvent::Notice(_) => {} + SessionEvent::TurnEnded(ended) => { + self.require_active(ended.turn)?; + self.active_turn = None; + self.pending.retain(|_, (turn, _)| *turn != ended.turn); + } + } + Ok(()) + } + + fn require_active(&self, turn: u64) -> Result<(), (&'static str, String)> { + if self.active_turn == Some(turn) { + Ok(()) + } else { + Err(( + PRECONDITION_FAILED, + "does not belong to the turn in progress".to_string(), + )) + } + } + + /// Takes the user's answer to a waiting permission request. The option + /// must be one the request listed. + pub fn decide(&mut self, permission: &str, option: &str) -> Result { + let Some((turn, options)) = self.pending.get(permission) else { + return Err("agents.permissionNotPending"); + }; + if !options.iter().any(|candidate| candidate.id == option) { + return Err("agents.unknownPermissionOption"); + } + let turn = *turn; + self.pending.remove(permission); + Ok(turn) + } +} + +const INVALID_PARAMS: &str = lithe_plugin_rpc::codes::HOST_INVALID_PARAMS; +const PRECONDITION_FAILED: &str = lithe_plugin_rpc::codes::HOST_PRECONDITION_FAILED; +const LIMIT_EXCEEDED: &str = lithe_plugin_rpc::codes::HOST_LIMIT_EXCEEDED; + +fn check_bounds(event: &SessionEvent) -> Result<(), String> { + let label = |value: &str, field: &str| { + if value.is_empty() || value.len() > MAX_LABEL_BYTES { + Err(format!("has an empty or overlong {field}")) + } else { + Ok(()) + } + }; + let optional_label = |value: &Option, field: &str| match value { + Some(value) => label(value, field), + None => Ok(()), + }; + let text = |value: &str, field: &str| { + if value.len() > MAX_TEXT_BYTES { + Err(format!("has a {field} longer than 1 MiB")) + } else { + Ok(()) + } + }; + match event { + SessionEvent::Session(info) => { + label(&info.agent_session_id, "agentSessionID")?; + optional_label(&info.model, "model")?; + optional_label(&info.effort, "effort")?; + optional_label(&info.agent_version, "agentVersion")?; + } + SessionEvent::Message(message) => { + label(&message.message_id, "messageID")?; + text(&message.text, "text")?; + } + SessionEvent::ToolCall(call) => { + label(&call.tool_call_id, "toolCallID")?; + optional_label(&call.title, "title")?; + if call.locations.len() > MAX_LOCATIONS { + return Err("has too many locations".to_string()); + } + for location in &call.locations { + text(&location.path, "location path")?; + } + if let Some(diff) = &call.diff { + text(&diff.path, "diff path")?; + text(diff.old_text.as_deref().unwrap_or_default(), "diff")?; + text(&diff.new_text, "diff")?; + } + text(call.output.as_deref().unwrap_or_default(), "output")?; + } + SessionEvent::Plan(plan) => { + if plan.entries.len() > MAX_PLAN_ENTRIES { + return Err("has too many plan entries".to_string()); + } + for entry in &plan.entries { + text(&entry.content, "plan entry")?; + } + } + SessionEvent::PermissionRequested(request) => { + label(&request.permission, "permission")?; + text(&request.title, "title")?; + optional_label(&request.tool_call_id, "toolCallID")?; + if request.options.is_empty() || request.options.len() > MAX_PERMISSION_OPTIONS { + return Err("needs one to eight options".to_string()); + } + for option in &request.options { + label(&option.id, "option ID")?; + label(&option.label, "option label")?; + } + let mut ids: Vec<&str> = request.options.iter().map(|o| o.id.as_str()).collect(); + ids.sort_unstable(); + ids.dedup(); + if ids.len() != request.options.len() { + return Err("repeats an option ID".to_string()); + } + } + SessionEvent::Usage(usage) => { + optional_label(&usage.model, "model")?; + if usage + .cost_usd + .is_some_and(|cost| !cost.is_finite() || cost < 0.0) + { + return Err("has an invalid cost".to_string()); + } + } + SessionEvent::RateLimits(limits) => check_rate_limits(limits)?, + SessionEvent::TurnEnded(ended) => { + text(ended.message.as_deref().unwrap_or_default(), "message")?; + } + SessionEvent::Notice(notice) => { + text(¬ice.text, "text")?; + optional_label(¬ice.code, "code")?; + } + } + Ok(()) +} + +/// Checks a rate-limit snapshot, from a session event or a session file scan. +pub(crate) fn check_rate_limits(limits: &RateLimits) -> Result<(), String> { + if limits.windows.is_empty() || limits.windows.len() > MAX_RATE_WINDOWS { + return Err("needs one to eight rate-limit windows".to_string()); + } + if limits + .plan + .as_deref() + .is_some_and(|plan| plan.is_empty() || plan.len() > MAX_LABEL_BYTES) + { + return Err("has an empty or overlong plan".to_string()); + } + for window in &limits.windows { + if window.id.is_empty() + || window.id.len() > MAX_LABEL_BYTES + || window + .label + .as_deref() + .is_some_and(|label| label.is_empty() || label.len() > MAX_LABEL_BYTES) + { + return Err("has an empty or overlong window ID or label".to_string()); + } + if !window.used_percent.is_finite() || !(0.0..=100.0).contains(&window.used_percent) { + return Err("has a used percentage outside 0 to 100".to_string()); + } + } + Ok(()) +} + +/// One event the host reads: Lithe's own lifecycle events and the events +/// backends report, in the order Core accepted them. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct HostEvent { + pub sequence: u64, + pub session: String, + pub event: Value, +} + +#[derive(Default)] +struct QueueState { + events: VecDeque, + next_sequence: u64, +} + +/// The events of every session, for `agents.waitEvents`. +#[derive(Default)] +pub(crate) struct EventQueue { + state: Mutex, + ready: Condvar, +} + +impl EventQueue { + /// Queues `event` of `session` and wakes a waiting reader. + pub fn push(&self, session: &str, event: Value) { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + state.next_sequence += 1; + let sequence = state.next_sequence; + state.events.push_back(HostEvent { + sequence, + session: session.to_string(), + event, + }); + while state.events.len() > MAX_QUEUED_EVENTS { + state.events.pop_front(); + } + drop(state); + self.ready.notify_all(); + } + + /// The events after `after`, waiting up to `timeout` for the first one. + /// `missed` is true when events after `after` were already dropped. + pub fn wait(&self, after: u64, timeout: Duration, limit: usize) -> Value { + let deadline = Instant::now() + timeout.min(MAX_WAIT); + let limit = limit.clamp(1, MAX_EVENTS_PER_WAIT); + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + while state.next_sequence <= after { + let now = Instant::now(); + if now >= deadline { + break; + } + state = self + .ready + .wait_timeout(state, deadline - now) + .unwrap_or_else(PoisonError::into_inner) + .0; + } + let oldest = state.events.front().map(|event| event.sequence); + let missed = oldest.is_some_and(|oldest| oldest > after + 1) && after < state.next_sequence; + let events: Vec<&HostEvent> = state + .events + .iter() + .filter(|event| event.sequence > after) + .take(limit) + .collect(); + let next = events + .last() + .map_or(after.min(state.next_sequence), |e| e.sequence); + json!({ "events": events, "next": next, "missed": missed }) + } +} diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs new file mode 100644 index 00000000..0d4a59bf --- /dev/null +++ b/rust/crates/agent-runtime/src/lib.rs @@ -0,0 +1,208 @@ +//! Agent sessions Core runs for agent plugins (plan API-45). +//! +//! An agent plugin declares agents: a CLI it requires as a tool, how a native +//! session talks to it, and where the CLI keeps its session files. Core owns +//! everything that touches the machine. It starts the CLI, writes its input +//! and reads its output, reads the session files, and keeps the cache; the +//! plugin backend only translates. It turns the CLI's lines into Lithe's +//! session events ([`events`]) and session-file lines into records. +//! +//! Core knows no agent: every agent-specific name, argument, protocol and file +//! layout comes from a plugin manifest and its backend. +//! +//! The host drives the runtime with two command families. `agents.*` covers +//! the catalog of declared agents and the live sessions; `agentSessions.*` +//! covers the local session records. Backends reach it with +//! `lithe/host/agents/*` requests, which the engine hands to the installed +//! [`AgentHost`] and which never reach the host application. +//! +//! Security rules this crate enforces: +//! +//! - Only a request the user started may start a session, send a prompt or +//! answer a permission request. Sessions run only in trusted local +//! workspaces, at most [`live::MAX_SESSIONS_PER_AGENT`] per agent. +//! - The executable is always the agent's declared tool, as the host resolved +//! it. The plugin chooses arguments only, never the environment. +//! - Session records are read only for agents the user granted +//! `agents.sessions.read`. Plugins granted `agents.usage.read` see totals +//! and rate limits, never text, titles, session IDs or directories. +//! - Logs carry opaque IDs and stable codes, never what flows through a +//! session. + +mod backend; +mod catalog; +mod events; +mod live; +mod records; + +#[cfg(test)] +mod tests; + +use backend::{BackendLink, EngineLink}; +use catalog::Catalog; +use lithe_lsp_engine::agent_host::{install_agent_host, AgentBackend, AgentHost, AgentHostFailure}; +use lithe_plugin_rpc::{codes, AGENTS_REPORT, AGENTS_USAGE, AGENTS_WRITE}; +use lithe_protocol::{CoreError, ErrorCode}; +use live::Live; +use records::Records; +use serde::de::DeserializeOwned; +use serde_json::Value; +use std::collections::BTreeMap; +use std::sync::{Arc, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// The commands of the `agents.*` family. +pub const AGENT_COMMANDS: &[&str] = &[ + "agents.configure", + "agents.catalog", + "agents.sessions", + "agents.start", + "agents.prompt", + "agents.cancel", + "agents.respondPermission", + "agents.close", + "agents.waitEvents", +]; + +/// The commands of the `agentSessions.*` family. +pub const AGENT_SESSION_COMMANDS: &[&str] = &[ + "agentSessions.configure", + "agentSessions.sync", + "agentSessions.forget", + "agentSessions.list", + "agentSessions.search", + "agentSessions.read", + "agentSessions.stats", +]; + +/// The agent catalog, the live sessions and the session records. +pub(crate) struct Runtime { + pub link: Arc, + pub catalog: Catalog, + pub live: Live, + pub records: Records, +} + +impl Runtime { + pub(crate) fn new(link: Arc) -> Arc { + Arc::new(Self { + link, + catalog: Catalog::default(), + live: Live::default(), + records: Records::default(), + }) + } + + pub(crate) fn execute( + self: &Arc, + command: &str, + payload: Value, + ) -> Result { + match command { + "agents.configure" => { + let answer = self.catalog.configure(payload)?; + // A session whose agent is gone or no longer granted ends. + self.live.end_where(|plugin_id, agent_id| { + self.catalog + .find(plugin_id, agent_id) + .is_none_or(|agent| !agent.may_run) + }); + Ok(answer) + } + "agents.catalog" => Ok(self.catalog.list()), + "agents.sessions" => Ok(self.live.list()), + "agents.start" => live::start(self, payload), + "agents.prompt" => live::prompt(self, payload), + "agents.cancel" => live::cancel(self, payload), + "agents.respondPermission" => live::respond_permission(self, payload), + "agents.close" => live::close(self, payload), + "agents.waitEvents" => live::wait_events(self, payload), + "agentSessions.configure" => self.records.configure(payload), + "agentSessions.sync" => self.records.sync(self, payload), + "agentSessions.forget" => self.records.forget(payload), + "agentSessions.list" => self.records.list(self, payload), + "agentSessions.search" => self.records.search(self, payload), + "agentSessions.read" => self.records.read(self, payload), + "agentSessions.stats" => self.records.stats(self, payload), + _ => Err(CoreError::new( + ErrorCode::NotSupported, + format!("Unknown agent command {command}."), + ) + .with_details("agents.unknownCommand")), + } + } +} + +/// The runtime as the engine reaches it. +struct Host(Arc); + +impl AgentHost for Host { + fn answer( + &self, + backend: AgentBackend<'_>, + method: &str, + params: &Value, + ) -> Result { + match method { + AGENTS_WRITE => self.0.live.write(backend, params), + AGENTS_REPORT => self.0.live.report(&self.0, backend, params), + AGENTS_USAGE => self.0.records.usage(&self.0, params), + _ => Err(AgentHostFailure::new( + codes::HOST_UNAVAILABLE, + "This host method is not available.", + )), + } + } + + fn backend_ended(&self, session_id: &str) { + self.0.live.backend_ended(session_id); + } +} + +static RUNTIME: OnceLock> = OnceLock::new(); + +fn runtime() -> &'static Arc { + RUNTIME.get_or_init(|| { + let runtime = Runtime::new(Arc::new(EngineLink)); + install_agent_host(Arc::new(Host(runtime.clone()))); + runtime + }) +} + +/// Runs one `agents.*` or `agentSessions.*` command. +pub fn execute(command: &str, payload: Value) -> Result { + runtime().execute(command, payload) +} + +/// Decodes a command payload. +pub(crate) fn decode(payload: Value) -> Result { + serde_json::from_value(payload).map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + format!("Invalid agent command payload: {error}"), + ) + .with_details("agents.invalidPayload") + }) +} + +/// Milliseconds since the Unix epoch. +pub(crate) fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| { + i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX) + }) +} + +/// 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. +pub(crate) fn log(event: &str, fields: [(&str, Value); N]) { + log_fields(event, fields.into_iter()); +} + +pub(crate) fn log_fields<'a>(event: &str, fields: impl Iterator) { + let fields: BTreeMap = fields + .map(|(name, value)| (name.to_string(), value)) + .collect(); + let _ = lithe_diagnostics::core_events::record(event, fields, None); +} diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs new file mode 100644 index 00000000..dabbd900 --- /dev/null +++ b/rust/crates/agent-runtime/src/live.rs @@ -0,0 +1,1026 @@ +//! Live agent sessions: the agent CLI processes Core runs for native +//! sessions, and the requests their plugin backends make about them. +//! +//! Each session has three threads. The output thread reads the CLI's stdout +//! line by line and hands the lines to the backend in `didOutput` batches; the +//! error thread keeps the last bytes of stderr for the user to see when the +//! CLI fails; the input thread writes what the backend sends with +//! `lithe/host/agents/write`, so a CLI that stops reading its input never +//! blocks the backend or the engine. When stdout ends, the output thread waits +//! for the process, ends its process tree and tells the backend and the host. +//! +//! Lithe never logs what flows through a session: logs carry the opaque +//! session ID, the plugin and agent IDs and stable codes only. + +use crate::events::{EventQueue, ReportRefusal, SessionEvent, TurnState, MAX_EVENTS_PER_REPORT}; +use crate::{log, log_fields, Runtime}; +use lithe_lsp_engine::agent_host::{AgentBackend, AgentHostFailure}; +use lithe_lsp_transport::process::{LspProcessHandle, LspProcessSpec}; +use lithe_plugin_rpc::{ + codes, AGENTS_DID_CANCEL, AGENTS_DID_DECIDE_PERMISSION, AGENTS_DID_EXIT, AGENTS_DID_OUTPUT, + AGENTS_DID_PROMPT, AGENTS_DID_START, +}; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_request_context::Source; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, VecDeque}; +use std::io::{self, BufRead, BufReader, Read}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread; +use std::time::{Duration, Instant}; + +/// Most sessions of one agent that run at once. +pub(crate) const MAX_SESSIONS_PER_AGENT: usize = 4; + +/// Most lines one `lithe/host/agents/write` carries. +const MAX_LINES_PER_WRITE: usize = 256; + +/// Most bytes one `lithe/host/agents/write` carries. +const MAX_WRITE_BYTES: usize = 16 * 1024 * 1024; + +/// Writes the input thread holds before `lithe/host/agents/write` answers +/// that the CLI is not keeping up. +const WRITE_QUEUE: usize = 64; + +/// Longest stdout line handed to the backend. A longer line is dropped and +/// the host is told. +const MAX_OUTPUT_LINE_BYTES: usize = 16 * 1024 * 1024; + +/// Most lines of one `didOutput`. +const MAX_OUTPUT_BATCH_LINES: usize = 64; + +/// Most bytes of one `didOutput`; a single longer line still goes alone. +const MAX_OUTPUT_BATCH_BYTES: usize = 4 * 1024 * 1024; + +/// Bytes of stderr kept for the user. +const STDERR_TAIL_BYTES: usize = 8 * 1024; + +/// How long a closed session has to exit by itself before Core ends it. +const CLOSE_GRACE: Duration = Duration::from_secs(3); + +/// How long Core waits for the exit status once stdout has ended. +const EXIT_WAIT: Duration = Duration::from_secs(3); + +/// How long Core waits for the process tree to be gone. +const DISPOSE_TIMEOUT: Duration = Duration::from_secs(5); + +/// Longest prompt, in bytes. +const MAX_PROMPT_BYTES: usize = 1024 * 1024; + +/// Most environment variables the host adds for a CLI. +const MAX_ENVIRONMENT_VARIABLES: usize = 256; + +/// Longest environment value the host adds for a CLI. +const MAX_ENVIRONMENT_VALUE_BYTES: usize = 32 * 1024; + +/// Why a session ended. The first reason recorded wins. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum EndReason { + /// The CLI exited by itself. + Exited, + /// The user closed the session. + Closed, + /// The plugin backend stopped. + BackendEnded, + /// Core could not reach the backend or the CLI. + Failed, +} + +impl EndReason { + fn token(self) -> &'static str { + match self { + EndReason::Exited => "exited", + EndReason::Closed => "closed", + EndReason::BackendEnded => "backendEnded", + EndReason::Failed => "failed", + } + } +} + +/// One running agent CLI. +pub(crate) struct LiveSession { + pub id: String, + pub plugin_id: String, + pub agent_id: String, + /// The engine session of the backend that translates this CLI. + pub backend: String, + started: Instant, + handle: Arc, + input: SyncSender>, + pub turns: Mutex, + end: Mutex>, + stderr_tail: Mutex>, +} + +impl LiveSession { + fn mark_end(&self, reason: EndReason) { + let mut end = self.end.lock().unwrap_or_else(PoisonError::into_inner); + if end.is_none() { + *end = Some(reason); + } + } + + fn end_reason(&self) -> EndReason { + self.end + .lock() + .unwrap_or_else(PoisonError::into_inner) + .unwrap_or(EndReason::Exited) + } + + fn owned_by(&self, backend: &AgentBackend<'_>) -> bool { + self.plugin_id == backend.plugin_id && self.backend == backend.session_id + } + + fn lock_turns(&self) -> std::sync::MutexGuard<'_, TurnState> { + self.turns.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn stderr_tail(&self) -> String { + let tail = self + .stderr_tail + .lock() + .unwrap_or_else(PoisonError::into_inner); + let bytes: Vec = tail.iter().copied().collect(); + String::from_utf8_lossy(&bytes).into_owned() + } +} + +/// Every running session and the events the host reads. +#[derive(Default)] +pub(crate) struct Live { + sessions: Mutex>>, + next_id: AtomicU64, + pub queue: EventQueue, +} + +impl Live { + fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap>> { + self.sessions.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn get(&self, session: &str) -> Option> { + self.lock().get(session).cloned() + } + + fn session(&self, session: &str) -> Result, CoreError> { + self.get(session).ok_or_else(|| { + CoreError::new( + ErrorCode::EntryNotFound, + "The agent session is not running.", + ) + .with_details("agents.unknownSession") + }) + } + + fn running(&self, plugin_id: &str, agent_id: &str) -> usize { + self.lock() + .values() + .filter(|session| session.plugin_id == plugin_id && session.agent_id == agent_id) + .count() + } + + /// The running sessions, for a host that opens its agent view again. + pub fn list(&self) -> Value { + let sessions: Vec = self + .lock() + .values() + .map(|session| { + let turns = session.lock_turns(); + let mut entry = json!({ + "session": session.id, + "pluginID": session.plugin_id, + "agentID": session.agent_id, + "pendingPermissions": turns.pending.keys().collect::>(), + }); + if let Some(turn) = turns.active_turn { + entry["activeTurn"] = json!(turn); + } + if let Some(id) = &turns.agent_session_id { + entry["agentSessionID"] = json!(id); + } + entry + }) + .collect(); + json!({ "sessions": sessions }) + } + + /// Ends the sessions of the agents `ending` selects, for example when the + /// user withdraws `agents.run` or removes the plugin. + pub fn end_where(&self, ending: impl Fn(&str, &str) -> bool) { + let ending: Vec> = self + .lock() + .values() + .filter(|session| ending(&session.plugin_id, &session.agent_id)) + .cloned() + .collect(); + for session in ending { + session.mark_end(EndReason::Closed); + session.handle.terminate(); + } + } + + /// The backend ended: its CLIs end too. Runs with the backend's session + /// lock held, so it only signals; the output threads clean up. + pub fn backend_ended(&self, backend: &str) { + let ending: Vec> = self + .lock() + .values() + .filter(|session| session.backend == backend) + .cloned() + .collect(); + for session in ending { + session.mark_end(EndReason::BackendEnded); + session.handle.terminate(); + } + } + + /// Answers `lithe/host/agents/write`. + pub fn write( + &self, + backend: AgentBackend<'_>, + params: &Value, + ) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct WriteParams { + session: String, + lines: Vec, + } + let params: WriteParams = serde_json::from_value(params.clone()).map_err(|error| { + AgentHostFailure::new( + codes::HOST_INVALID_PARAMS, + format!("Invalid write: {error}"), + ) + })?; + let session = self.owned(&backend, ¶ms.session)?; + if params.lines.is_empty() + || params.lines.len() > MAX_LINES_PER_WRITE + || params.lines.iter().map(String::len).sum::() > MAX_WRITE_BYTES + || params.lines.iter().any(|line| line.contains(['\n', '\r'])) + { + return Err(AgentHostFailure::new( + codes::HOST_INVALID_PARAMS, + "A write carries 1 to 256 lines of at most 16 MiB in total, without line breaks.", + )); + } + match session.input.try_send(params.lines) { + Ok(()) => Ok(json!({})), + Err(TrySendError::Full(_)) => Err(AgentHostFailure::new( + codes::HOST_LIMIT_EXCEEDED, + "The agent CLI is not reading its input; try again later.", + )), + Err(TrySendError::Disconnected(_)) => Err(AgentHostFailure::new( + codes::HOST_NOT_FOUND, + "The agent session has ended.", + )), + } + } + + /// Answers `lithe/host/agents/report`: checks the events against the + /// session's turns and queues them for the host. + pub fn report( + &self, + runtime: &Arc, + backend: AgentBackend<'_>, + params: &Value, + ) -> Result { + let refuse = |code: &'static str, message: String| { + log( + "agent.report.rejected", + [("plugin", json!(backend.plugin_id)), ("code", json!(code))], + ); + AgentHostFailure::new(code, message) + }; + let session_id = params + .get("session") + .and_then(Value::as_str) + .unwrap_or_default(); + let session = self.owned(&backend, session_id)?; + let Some(raw) = params.get("events").and_then(Value::as_array) else { + return Err(refuse( + codes::HOST_INVALID_PARAMS, + "A report carries an events array.".to_string(), + )); + }; + if params.as_object().is_some_and(|object| object.len() != 2) + || raw.is_empty() + || raw.len() > MAX_EVENTS_PER_REPORT + { + return Err(refuse( + codes::HOST_INVALID_PARAMS, + "A report carries session and 1 to 256 events.".to_string(), + )); + } + let mut events = Vec::with_capacity(raw.len()); + for (index, event) in raw.iter().enumerate() { + let event: SessionEvent = serde_json::from_value(event.clone()).map_err(|error| { + refuse( + codes::HOST_INVALID_PARAMS, + format!("Event {index} of the report is malformed: {error}"), + ) + })?; + events.push(event); + } + session + .lock_turns() + .apply(&events) + .map_err(|ReportRefusal { code, message }| refuse(code, message))?; + for event in &events { + if let SessionEvent::RateLimits(limits) = event { + runtime.records.note_rate_limits( + &crate::catalog::record_key(&session.plugin_id, &session.agent_id), + limits.clone(), + crate::now_ms(), + ); + } + let value = serde_json::to_value(event).unwrap_or(Value::Null); + self.queue.push(&session.id, value); + } + Ok(json!({})) + } + + fn owned( + &self, + backend: &AgentBackend<'_>, + session: &str, + ) -> Result, AgentHostFailure> { + self.get(session) + .filter(|live| live.owned_by(backend)) + .ok_or_else(|| { + AgentHostFailure::new( + codes::HOST_NOT_FOUND, + "The backend runs no agent session with this ID.", + ) + }) + } +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct StartRequest { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, + /// The directory the agent works in. + cwd: String, + /// The agent's tool as the host resolved it from the plugin's + /// `requiresTools`. + tool_path: String, + /// The workspace root the session belongs to, so the backend of that + /// workspace translates it. + #[serde(rename = "rootURI", default)] + root_uri: Option, + /// The agent CLI's own ID of a session to resume. + #[serde(default)] + resume: Option, + /// Whether the user trusts the workspace. + #[serde(default)] + workspace_trusted: bool, + /// Variables the host adds to the CLI's environment, for example the + /// login shell's `PATH`. + #[serde(default)] + environment: BTreeMap, +} + +fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { + CoreError::new(code, message).with_details(details) +} + +fn require_user(action: &str) -> Result<(), CoreError> { + if lithe_request_context::trace::current().source == Source::User { + Ok(()) + } else { + Err(refusal( + ErrorCode::PermissionDenied, + "agents.userActionRequired", + &format!("Only the user can {action} an agent session."), + )) + } +} + +/// `agents.start`: starts a native session of an agent. +pub(crate) fn start(runtime: &Arc, payload: Value) -> Result { + let request: StartRequest = crate::decode(payload)?; + let plugin_id = request.plugin_id.clone(); + let agent_id = request.agent_id.clone(); + let outcome = start_checked(runtime, request); + if let Err(error) = &outcome { + log( + "agent.session.start_failed", + [ + ("plugin", json!(plugin_id)), + ("agent", json!(agent_id)), + ( + "reason", + json!(error.details.as_deref().unwrap_or("agents.startFailed")), + ), + ], + ); + } + outcome +} + +fn start_checked(runtime: &Arc, request: StartRequest) -> Result { + require_user("start")?; + if lithe_workspace::is_remote() { + return Err(refusal( + ErrorCode::NotSupported, + "agents.remoteWorkspace", + "Agent sessions run only in local workspaces.", + )); + } + if !request.workspace_trusted { + return Err(refusal( + ErrorCode::PermissionDenied, + "agents.untrustedWorkspace", + "Agent sessions run only in trusted workspaces.", + )); + } + let Some(agent) = runtime.catalog.find(&request.plugin_id, &request.agent_id) else { + return Err(refusal( + ErrorCode::EntryNotFound, + "agents.unknownAgent", + "No installed plugin declares this agent.", + )); + }; + if !agent.may_run { + return Err(refusal( + ErrorCode::PermissionDenied, + "agents.runNotGranted", + "The user has not allowed this plugin to run its agents.", + )); + } + let Some(native) = agent.agent.native.clone() else { + return Err(refusal( + ErrorCode::NotSupported, + "agents.noNativeMode", + "The agent has no native session mode.", + )); + }; + if runtime.live.running(&request.plugin_id, &request.agent_id) >= MAX_SESSIONS_PER_AGENT { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.tooManySessions", + "This agent already runs as many sessions as Lithe allows.", + )); + } + let cwd = PathBuf::from(&request.cwd); + if !cwd.is_absolute() || !cwd.is_dir() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.invalidDirectory", + "The agent's working directory is not an existing absolute directory.", + )); + } + let tool = PathBuf::from(&request.tool_path); + if !tool.is_absolute() || !tool.is_file() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.toolNotFound", + "The agent's tool is not an existing absolute file.", + )); + } + check_environment(&request.environment)?; + if request + .resume + .as_deref() + .is_some_and(|resume| resume.is_empty() || resume.len() > 1024) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.invalidResume", + "The session to resume has an empty or overlong ID.", + )); + } + + let link = &runtime.link; + let Some(backend) = link.session_for( + &request.plugin_id, + &native.function, + request.root_uri.as_deref(), + ) else { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.backendUnavailable", + "The agent plugin's backend is not running.", + )); + }; + let answer = link + .call( + &backend, + &request.plugin_id, + &native.function, + lithe_plugin_agents::launch_params( + &request.agent_id, + &request.cwd, + request.resume.as_deref(), + ), + Duration::from_millis(native.timeout_milliseconds()), + ) + .map_err(|failure| { + CoreError::new( + ErrorCode::ProcessFailed, + "The agent plugin could not prepare the session.", + ) + .with_details(launch_failure_code(&failure.code)) + })?; + let launch = + lithe_plugin_agents::decode_native_launch(&agent.agent, answer).map_err(|rejection| { + CoreError::new(ErrorCode::InvalidRequest, rejection.message) + .with_details(rejection.code) + })?; + + let streams = link + .launcher() + .launch(LspProcessSpec { + executable: tool, + arguments: launch.arguments, + working_directory: cwd, + environment: request.environment, + }) + .map_err(|_| { + refusal( + ErrorCode::ProcessStartFailed, + "agents.processStartFailed", + "Could not start the agent CLI.", + ) + })?; + + let id = format!( + "agent-{}", + runtime.live.next_id.fetch_add(1, Ordering::Relaxed) + 1 + ); + let (input, input_queue) = mpsc::sync_channel(WRITE_QUEUE); + let session = Arc::new(LiveSession { + id: id.clone(), + plugin_id: request.plugin_id.clone(), + agent_id: request.agent_id.clone(), + backend: backend.clone(), + started: Instant::now(), + handle: streams.handle.clone(), + input, + turns: Mutex::new(TurnState::default()), + end: Mutex::new(None), + stderr_tail: Mutex::new(VecDeque::new()), + }); + runtime.live.lock().insert(id.clone(), session.clone()); + + let mut started = lithe_plugin_agents::launch_params( + &request.agent_id, + &request.cwd, + request.resume.as_deref(), + ); + started["session"] = json!(id); + if link.notify(&backend, AGENTS_DID_START, started).is_err() { + runtime.live.lock().remove(&id); + streams.handle.terminate(); + let _ = streams.handle.dispose(DISPOSE_TIMEOUT); + return Err(refusal( + ErrorCode::ProcessFailed, + "agents.backendUnavailable", + "The agent plugin's backend stopped while the session started.", + )); + } + + let mut event = json!({ + "kind": "started", + "pluginID": request.plugin_id, + "agentID": request.agent_id, + "mode": "native", + }); + if let Some(resume) = &request.resume { + event["resume"] = json!(resume); + } + runtime.live.queue.push(&id, event); + log( + "agent.session.started", + [ + ("plugin", json!(session.plugin_id)), + ("agent", json!(session.agent_id)), + ("session", json!(id)), + ("mode", json!("native")), + ], + ); + + let handle = streams.handle.clone(); + spawn("agent-input", move || write_input(handle, input_queue)); + let errors_session = session.clone(); + let errors = streams.errors; + spawn("agent-errors", move || read_errors(&errors_session, errors)); + let output_runtime = runtime.clone(); + let output = streams.output; + spawn("agent-output", move || { + read_output(&output_runtime, &session, output); + finish(&output_runtime, &session); + }); + Ok(json!({ "session": id, "mode": "native" })) +} + +fn launch_failure_code(code: &str) -> &'static str { + if code == "requestTimeout" || code.ends_with(".timeout") { + "agents.launchTimeout" + } else { + "agents.launchFailed" + } +} + +fn check_environment(environment: &BTreeMap) -> Result<(), CoreError> { + let valid = environment.len() <= MAX_ENVIRONMENT_VARIABLES + && environment.iter().all(|(name, value)| { + !name.is_empty() + && name.len() <= 256 + && !name.contains(['=', '\0']) + && value.len() <= MAX_ENVIRONMENT_VALUE_BYTES + && !value.contains('\0') + }); + if valid { + Ok(()) + } else { + Err(refusal( + ErrorCode::InvalidRequest, + "agents.invalidEnvironment", + "The environment for the agent CLI is invalid.", + )) + } +} + +fn spawn(name: &str, work: impl FnOnce() + Send + 'static) { + // A thread that cannot start leaves the session without that stream; the + // output thread is the one that matters, and its failure ends the session + // through the process's own exit. + let _ = thread::Builder::new().name(name.to_string()).spawn(work); +} + +fn write_input(handle: Arc, queue: Receiver>) { + for lines in queue { + for line in lines { + let mut frame = line.into_bytes(); + frame.push(b'\n'); + if handle.write_input(&frame).is_err() { + return; + } + } + } +} + +fn read_errors(session: &LiveSession, mut errors: Box) { + let mut buffer = [0u8; 4096]; + loop { + match errors.read(&mut buffer) { + Ok(0) => return, + Ok(count) => { + let mut tail = session + .stderr_tail + .lock() + .unwrap_or_else(PoisonError::into_inner); + tail.extend(&buffer[..count]); + let excess = tail.len().saturating_sub(STDERR_TAIL_BYTES); + tail.drain(..excess); + } + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(_) => return, + } + } +} + +enum Line { + Text(String), + TooLong, + End, +} + +/// Reads one line of at most `limit` bytes, without its line break. A longer +/// line is consumed and reported as [`Line::TooLong`]. +fn read_line(reader: &mut impl BufRead, limit: usize) -> io::Result { + let mut bytes = Vec::new(); + let mut too_long = false; + let mut read_any = false; + loop { + let available = match reader.fill_buf() { + Ok(available) => available, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + }; + if available.is_empty() { + if !read_any { + return Ok(Line::End); + } + break; + } + read_any = true; + let (used, found) = match available.iter().position(|byte| *byte == b'\n') { + Some(index) => (index + 1, true), + None => (available.len(), false), + }; + let content = &available[..if found { used - 1 } else { used }]; + if !too_long { + if bytes.len() + content.len() > limit { + too_long = true; + bytes = Vec::new(); + } else { + bytes.extend_from_slice(content); + } + } + reader.consume(used); + if found { + break; + } + } + if too_long { + return Ok(Line::TooLong); + } + if bytes.last() == Some(&b'\r') { + bytes.pop(); + } + Ok(Line::Text(String::from_utf8(bytes).unwrap_or_else( + |error| String::from_utf8_lossy(error.as_bytes()).into_owned(), + ))) +} + +fn read_output(runtime: &Arc, session: &Arc, output: Box) { + let mut reader = BufReader::with_capacity(64 * 1024, output); + let mut batch: Vec = Vec::new(); + let mut batch_bytes = 0usize; + loop { + let line = read_line(&mut reader, MAX_OUTPUT_LINE_BYTES); + let ended = match line { + Ok(Line::Text(line)) => { + batch_bytes += line.len(); + batch.push(line); + false + } + Ok(Line::TooLong) => { + runtime + .live + .queue + .push(&session.id, json!({ "kind": "outputLineDropped" })); + false + } + Ok(Line::End) | Err(_) => true, + }; + let flush = ended + || batch.len() >= MAX_OUTPUT_BATCH_LINES + || batch_bytes >= MAX_OUTPUT_BATCH_BYTES + || reader.buffer().is_empty(); + if flush && !batch.is_empty() { + let lines = std::mem::take(&mut batch); + batch_bytes = 0; + let params = json!({ "session": session.id, "lines": lines }); + if runtime + .link + .notify(&session.backend, AGENTS_DID_OUTPUT, params) + .is_err() + { + // The backend can no longer translate the CLI: end it rather + // than let it act without anyone seeing what it does. + session.mark_end(EndReason::Failed); + session.handle.terminate(); + return; + } + } + if ended { + return; + } + } +} + +fn finish(runtime: &Arc, session: &Arc) { + let handle = &session.handle; + let deadline = Instant::now() + EXIT_WAIT; + let mut status = handle.exit_status(); + while status.is_none() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(20)); + status = handle.exit_status(); + } + if status.is_none() { + handle.terminate(); + } + let disposed = handle.dispose(DISPOSE_TIMEOUT).is_ok(); + let exit_code = status.or_else(|| handle.exit_status()).flatten(); + session.mark_end(EndReason::Exited); + let reason = if disposed { + session.end_reason() + } else { + EndReason::Failed + }; + + runtime.live.lock().remove(&session.id); + if reason != EndReason::BackendEnded { + let mut params = json!({ "session": session.id }); + if let Some(code) = exit_code { + params["exitCode"] = json!(code); + } + let _ = runtime + .link + .notify(&session.backend, AGENTS_DID_EXIT, params); + } + let mut event = json!({ "kind": "exited", "reason": reason.token() }); + if let Some(code) = exit_code { + event["exitCode"] = json!(code); + } + let tail = session.stderr_tail(); + if !tail.trim().is_empty() { + event["stderrTail"] = json!(tail); + } + runtime.live.queue.push(&session.id, event); + + let mut fields = vec![ + ("session", json!(session.id)), + ("reason", json!(reason.token())), + ( + "duration", + json!(u64::try_from(session.started.elapsed().as_millis()).unwrap_or(u64::MAX)), + ), + ]; + if let Some(code) = exit_code { + fields.push(("exit_code", json!(code))); + } + log_fields("agent.session.finished", fields.into_iter()); +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SessionRequest { + session: String, +} + +/// `agents.prompt`: sends the user's prompt as the next turn. +pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct PromptRequest { + session: String, + text: String, + } + let request: PromptRequest = crate::decode(payload)?; + require_user("prompt")?; + if request.text.trim().is_empty() || request.text.len() > MAX_PROMPT_BYTES { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.invalidPrompt", + "A prompt has text of at most 1 MiB.", + )); + } + let session = runtime.live.session(&request.session)?; + let Some(turn) = session.lock_turns().start_turn() else { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.turnInProgress", + "The agent is still working on the previous prompt.", + )); + }; + runtime + .live + .queue + .push(&session.id, json!({ "kind": "turnStarted", "turn": turn })); + let params = json!({ "session": session.id, "turn": turn, "text": request.text }); + if runtime + .link + .notify(&session.backend, AGENTS_DID_PROMPT, params) + .is_err() + { + let mut turns = session.lock_turns(); + if turns.active_turn == Some(turn) { + turns.active_turn = None; + } + drop(turns); + runtime.live.queue.push( + &session.id, + json!({ "kind": "turnEnded", "turn": turn, "reason": "failed" }), + ); + return Err(refusal( + ErrorCode::ProcessFailed, + "agents.backendUnavailable", + "The agent plugin's backend did not take the prompt.", + )); + } + Ok(json!({ "turn": turn })) +} + +/// `agents.cancel`: asks the agent to stop the turn in progress. +pub(crate) fn cancel(runtime: &Arc, payload: Value) -> Result { + let request: SessionRequest = crate::decode(payload)?; + let session = runtime.live.session(&request.session)?; + let Some(turn) = session.lock_turns().active_turn else { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.noTurnInProgress", + "The agent is not working on a prompt.", + )); + }; + runtime + .link + .notify( + &session.backend, + AGENTS_DID_CANCEL, + json!({ "session": session.id, "turn": turn }), + ) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agents.backendUnavailable", + "The agent plugin's backend did not take the cancellation.", + ) + })?; + Ok(json!({ "turn": turn })) +} + +/// `agents.respondPermission`: the user's answer to a permission request. +pub(crate) fn respond_permission( + runtime: &Arc, + payload: Value, +) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct PermissionAnswer { + session: String, + permission: String, + option: String, + } + let request: PermissionAnswer = crate::decode(payload)?; + require_user("answer a permission request of")?; + let session = runtime.live.session(&request.session)?; + let turn = session + .lock_turns() + .decide(&request.permission, &request.option) + .map_err(|code| { + refusal( + ErrorCode::InvalidRequest, + code, + "The agent is not waiting for this answer.", + ) + })?; + runtime.live.queue.push( + &session.id, + json!({ + "kind": "permissionDecided", + "turn": turn, + "permission": request.permission, + "option": request.option, + }), + ); + runtime + .link + .notify( + &session.backend, + AGENTS_DID_DECIDE_PERMISSION, + json!({ + "session": session.id, + "turn": turn, + "permission": request.permission, + "option": request.option, + }), + ) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agents.backendUnavailable", + "The agent plugin's backend did not take the answer.", + ) + })?; + Ok(json!({ "turn": turn })) +} + +/// `agents.close`: closes the CLI's input, then ends it if it does not exit. +pub(crate) fn close(runtime: &Arc, payload: Value) -> Result { + let request: SessionRequest = crate::decode(payload)?; + let session = runtime.live.session(&request.session)?; + session.mark_end(EndReason::Closed); + session.handle.close_input(); + let handle = session.handle.clone(); + spawn("agent-close", move || { + let deadline = Instant::now() + CLOSE_GRACE; + while handle.exit_status().is_none() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(50)); + } + if handle.exit_status().is_none() { + handle.terminate(); + } + }); + Ok(json!({})) +} + +/// `agents.waitEvents`: the next session events for the host. +pub(crate) fn wait_events(runtime: &Arc, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct WaitRequest { + #[serde(default)] + after: u64, + #[serde(default)] + timeout_milliseconds: u64, + #[serde(default)] + limit: Option, + } + let request: WaitRequest = crate::decode(payload)?; + Ok(runtime.live.queue.wait( + request.after, + Duration::from_millis(request.timeout_milliseconds), + request.limit.unwrap_or(256), + )) +} diff --git a/rust/crates/agent-runtime/src/records.rs b/rust/crates/agent-runtime/src/records.rs new file mode 100644 index 00000000..b095b319 --- /dev/null +++ b/rust/crates/agent-runtime/src/records.rs @@ -0,0 +1,1165 @@ +//! The local session records of agent CLIs: syncing the cache from the files +//! the agents keep, and the lists, searches, reads and statistics the host and +//! plugins ask for. +//! +//! Core reads the files; the agent's plugin only interprets lines Core hands +//! it, through the `scan` and `read` functions its session sources declare. +//! The cache lives in the directory the host names, which is in the platform's +//! Caches directory and never in the application bundle; deleting it loses +//! nothing the agents' own files do not hold, except the last rate-limit +//! snapshots in `rate-limits.json`. +//! +//! Two connections to the cache keep a long sync from blocking the views: the +//! 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. + +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::pricing::PriceTable; +use lithe_agent_sessions::stats::{GroupBy, Summarizer}; +use lithe_agent_sessions::{ + discover, ByteRange, CallFilter, ScanChunk, ScanOutput, SearchQuery, SessionFilter, + SessionParser, SessionSource, SessionStore, MAX_SEARCH_HITS, MAX_SESSIONS_PAGE, +}; +use lithe_lsp_engine::agent_host::AgentHostFailure; +use lithe_plugin_agents::SessionSourceDeclaration; +use lithe_plugin_rpc::codes; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard, PoisonError, RwLock}; +use std::time::{Duration, Instant}; + +/// How long one `scan` call may take. +const SCAN_TIMEOUT: Duration = Duration::from_secs(30); + +/// How long one `read` call may take. +const READ_TIMEOUT: Duration = Duration::from_secs(15); + +/// Longest title Core passes on, in bytes. +const MAX_TITLE_BYTES: usize = 512; + +/// Most messages one read item returns. +const MAX_MESSAGES_PER_ITEM: usize = 2048; + +/// Longest text of one read message, in bytes. +const MAX_MESSAGE_TEXT_BYTES: usize = 1024 * 1024; + +/// Longest range `lithe/host/agents/usage` sums, in days. +const MAX_USAGE_DAYS: i64 = 366; + +/// Largest `rate-limits.json` Core loads. +const MAX_RATE_FILE_BYTES: u64 = 1024 * 1024; + +const RATE_FILE: &str = "rate-limits.json"; + +const MILLISECONDS_PER_DAY: i64 = 86_400_000; + +/// Where the cache is and what the session roots resolve against. +#[derive(Debug, Clone)] +struct Config { + cache_directory: PathBuf, + user_home: String, + /// The variables the agents' session roots name, from the host. + environment: BTreeMap, +} + +/// The latest rate-limit state of one agent. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct RateSnapshot { + /// When the agent reported it, in Unix milliseconds. + at_ms: i64, + windows: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + plan: Option, +} + +impl RateSnapshot { + fn new(limits: RateLimits, at_ms: i64) -> Self { + Self { + at_ms, + windows: limits.windows, + plan: limits.plan, + } + } + + fn check(&self) -> Result<(), String> { + check_rate_limits(&RateLimits { + windows: self.windows.clone(), + plan: self.plan.clone(), + }) + } +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct RateFile { + version: u32, + agents: BTreeMap, +} + +#[derive(Default)] +pub(crate) struct Records { + writer: Mutex>, + reader: Mutex>, + config: RwLock>, + prices: RwLock>, + rate_limits: Mutex>, +} + +fn not_configured() -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "The agent session cache is not configured.", + ) + .with_details("agentSessions.notConfigured") +} + +fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { + CoreError::new(code, message).with_details(details) +} + +impl Records { + fn config(&self) -> Option { + self.config + .read() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + fn lock_reader(&self) -> MutexGuard<'_, Option> { + self.reader.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn lock_writer(&self) -> MutexGuard<'_, Option> { + self.writer.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn lock_rates(&self) -> MutexGuard<'_, BTreeMap> { + self.rate_limits + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + /// `agentSessions.configure`. + pub fn configure(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ConfigureRequest { + /// A directory of the platform's Caches directory for the cache. + cache_directory: String, + user_home: String, + /// Values of the variables in the catalog's + /// `sessionRootVariables`. + #[serde(default)] + environment: BTreeMap, + /// A models.dev `api.json` the host keeps, to price calls. + #[serde(default)] + prices_file: Option, + } + let request: ConfigureRequest = crate::decode(payload)?; + let cache_directory = PathBuf::from(&request.cache_directory); + if !cache_directory.is_absolute() || !Path::new(&request.user_home).is_absolute() { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidDirectory", + "The cache directory and user home must be absolute paths.", + )); + } + if request.environment.len() > 256 + || request + .environment + .iter() + .any(|(name, value)| name.is_empty() || name.len() > 256 || value.len() > 32 * 1024) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidEnvironment", + "The environment for session roots is invalid.", + )); + } + + let same_directory = self + .config() + .is_some_and(|config| config.cache_directory == cache_directory); + if !same_directory { + let writer = SessionStore::open(&cache_directory)?; + let reader = SessionStore::open(&cache_directory)?; + *self.lock_writer() = Some(writer); + *self.lock_reader() = Some(reader); + *self.lock_rates() = load_rate_file(&cache_directory); + } + *self.config.write().unwrap_or_else(PoisonError::into_inner) = Some(Config { + cache_directory, + user_home: request.user_home, + environment: request.environment, + }); + + let mut answer = json!({}); + match request.prices_file.as_deref().map(load_prices) { + None => { + *self.prices.write().unwrap_or_else(PoisonError::into_inner) = None; + } + Some(Ok(table)) => { + answer["pricedModels"] = json!(table.len()); + *self.prices.write().unwrap_or_else(PoisonError::into_inner) = Some(table); + } + Some(Err(error)) => { + *self.prices.write().unwrap_or_else(PoisonError::into_inner) = None; + answer["pricesError"] = json!(error.code); + } + } + Ok(answer) + } + + /// `agentSessions.sync`: brings the records of one agent up to date. + pub fn sync(&self, runtime: &Runtime, payload: Value) -> Result { + let request: AgentRequest = crate::decode(payload)?; + let started = Instant::now(); + let outcome = self.sync_checked(runtime, &request); + match &outcome { + Ok(report) => log( + "agent.records.updated", + [ + ("plugin", json!(request.plugin_id)), + ("agent", json!(request.agent_id)), + ("files_read", report["filesRead"].clone()), + ("files_failed", report["filesFailed"].clone()), + ( + "duration", + json!(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)), + ), + ], + ), + Err(error) => log( + "agent.records.sync_failed", + [ + ("plugin", json!(request.plugin_id)), + ("agent", json!(request.agent_id)), + ( + "reason", + json!(error + .details + .as_deref() + .unwrap_or("agentSessions.syncFailed")), + ), + ], + ), + } + outcome + } + + fn sync_checked(&self, runtime: &Runtime, request: &AgentRequest) -> Result { + let config = self.config().ok_or_else(not_configured)?; + let agent = readable_agent(runtime, &request.plugin_id, &request.agent_id)?; + let mut routes = Vec::new(); + let mut files = Vec::new(); + let mut truncated = Vec::new(); + let mut unreadable_entries = 0u64; + for source in &agent.agent.session_sources { + let Some(root) = lithe_plugin_agents::resolve_root( + &source.roots, + &config.user_home, + &config.environment, + ) else { + continue; + }; + let discovery = discover(&SessionSource { + root: root.clone(), + include: source.include.clone(), + }) + .map_err(|error| { + let code = error.code; + CoreError::new(code, "Could not list the agent's session files.") + .with_details("agentSessions.discoveryFailed") + })?; + if discovery.truncated { + truncated.push(source.id.clone()); + } + unreadable_entries += discovery.unreadable_entries; + files.extend(discovery.files); + let backend = backend_for(&*runtime.link, &agent.plugin_id, &source.scan)?; + routes.push(Route { + root, + source: source.clone(), + backend, + }); + } + + let key = agent.record_key(); + let mut parser = PluginParser { + link: &*runtime.link, + plugin_id: &agent.plugin_id, + agent_id: &agent.agent.id, + routes: &routes, + rate_limits: None, + }; + let report = { + let mut writer = self.lock_writer(); + let store = writer.as_mut().ok_or_else(not_configured)?; + store.sync_agent(&key, &files, &mut parser)? + }; + if let Some(snapshot) = parser.rate_limits.take() { + self.keep_rate_snapshot(&key, snapshot); + } + let mut answer = serde_json::to_value(&report).unwrap_or_else(|_| json!({})); + answer["truncatedSources"] = json!(truncated); + answer["unreadableEntries"] = json!(unreadable_entries); + Ok(answer) + } + + /// `agentSessions.forget`: drops the records of one agent, for example + /// when the user withdraws access to its sessions. + pub fn forget(&self, payload: Value) -> Result { + let request: AgentRequest = crate::decode(payload)?; + let key = record_key(&request.plugin_id, &request.agent_id); + let files = { + let mut writer = self.lock_writer(); + let store = writer.as_mut().ok_or_else(not_configured)?; + store.remove_agent(&key)? + }; + let removed_limits = self.lock_rates().remove(&key).is_some(); + if removed_limits { + self.save_rate_file(); + } + log( + "agent.records.removed", + [ + ("plugin", json!(request.plugin_id)), + ("agent", json!(request.agent_id)), + ("files", json!(files)), + ], + ); + Ok(json!({ "files": files })) + } + + /// `agentSessions.list`: the sessions of the readable agents, newest + /// first, with their titles when asked. + pub fn list(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ListRequest { + #[serde(default)] + agents: Option>, + #[serde(default)] + cwd: Option, + #[serde(default)] + active_since_ms: Option, + #[serde(default)] + offset: u64, + #[serde(default)] + limit: Option, + #[serde(default)] + titles: bool, + } + let request: ListRequest = crate::decode(payload)?; + let Some(agents) = allowed_agents(runtime, request.agents) else { + return Ok(json!({ "sessions": [] })); + }; + let filter = SessionFilter { + agents, + cwd: request.cwd, + active_since_ms: request.active_since_ms, + offset: request.offset, + limit: request.limit.unwrap_or(100).clamp(1, MAX_SESSIONS_PAGE), + }; + let (entries, title_bytes) = { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + let entries = store.sessions(&filter)?; + let mut title_bytes = Vec::with_capacity(entries.len()); + for entry in &entries { + let bytes = match (request.titles, entry.title_range) { + (true, Some(range)) => store + .read_range(&entry.agent, &entry.path, range) + .ok() + .flatten(), + _ => None, + }; + title_bytes.push(bytes); + } + (entries, title_bytes) + }; + + let mut titles: Vec> = vec![None; entries.len()]; + if request.titles { + let config = self.config().ok_or_else(not_configured)?; + // One read call per agent and source, with every title of it. + let mut groups: BTreeMap<(String, usize), Vec> = BTreeMap::new(); + let mut routes: BTreeMap)>> = + BTreeMap::new(); + for (index, entry) in entries.iter().enumerate() { + if title_bytes[index].is_none() { + continue; + } + let rooted = routes.entry(entry.agent.clone()).or_insert_with(|| { + let agent = runtime.catalog.find_key(&entry.agent)?; + let sources = rooted_sources(&agent, &config); + Some((agent, sources)) + }); + let Some((_, sources)) = rooted else { continue }; + if let Some(source) = source_index(sources, Path::new(&entry.path)) { + groups + .entry((entry.agent.clone(), source)) + .or_default() + .push(index); + } + } + for ((key, source), indexes) in groups { + let Some(Some((agent, sources))) = routes.get(&key) else { + continue; + }; + let items: Vec = indexes + .iter() + .map(|index| { + json!({ + "path": entries[*index].path, + "lines": text_lines(title_bytes[*index].as_deref().unwrap_or_default()), + }) + }) + .collect(); + let Ok(answers) = call_read( + &*runtime.link, + agent, + &sources[source].source, + "titles", + items, + ) else { + continue; + }; + for (index, answer) in indexes.iter().zip(answers) { + titles[*index] = decode_title(&answer); + } + } + } + + let sessions: Vec = entries + .iter() + .zip(titles) + .map(|(entry, title)| { + let mut value = serde_json::to_value(entry).unwrap_or_else(|_| json!({})); + add_agent_ids(&mut value, &entry.agent); + if let Some(title) = title { + value["title"] = json!(title); + } + value + }) + .collect(); + Ok(json!({ "sessions": sessions })) + } + + /// `agentSessions.search`: where the readable agents' sessions contain + /// the words of a query. The host reads the hits it shows. + pub fn search(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct SearchRequest { + text: String, + #[serde(default)] + agents: Option>, + #[serde(rename = "sessionID", default)] + session_id: Option, + #[serde(default)] + limit: Option, + } + let request: SearchRequest = crate::decode(payload)?; + let Some(agents) = allowed_agents(runtime, request.agents) else { + return Ok(json!({ "hits": [] })); + }; + let hits = { + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + store.search(&SearchQuery { + text: request.text, + agents, + session_id: request.session_id, + limit: request.limit.unwrap_or(50).clamp(1, MAX_SEARCH_HITS), + })? + }; + let hits: Vec = hits + .iter() + .map(|hit| { + let mut value = serde_json::to_value(hit).unwrap_or_else(|_| json!({})); + add_agent_ids(&mut value, &hit.agent); + value + }) + .collect(); + Ok(json!({ "hits": hits })) + } + + /// `agentSessions.read`: the messages of a byte range of a session file, + /// as the agent's plugin reads them. + pub fn read(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct ReadRequest { + agent: String, + path: String, + range: ByteRange, + } + 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 sources = rooted_sources(&agent, &config); + let source = source_index(&sources, Path::new(&request.path)).ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.outsideSources", + "The file is not in a session directory of the agent.", + ) + })?; + let bytes = { + 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 Some(bytes) = bytes else { + return Ok(json!({ "changed": true, "messages": [] })); + }; + let items = vec![json!({ "path": request.path, "lines": text_lines(&bytes) })]; + let answers = call_read( + &*runtime.link, + &agent, + &sources[source].source, + "messages", + items, + )?; + let messages = answers + .into_iter() + .next() + .map(decode_messages) + .transpose()? + .unwrap_or_default(); + Ok(json!({ "changed": false, "messages": messages })) + } + + /// `agentSessions.stats`: usage of the readable agents for the host. + pub fn stats(&self, runtime: &Runtime, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct StatsRequest { + #[serde(default)] + agents: Option>, + #[serde(rename = "sessionID", default)] + session_id: Option, + #[serde(default)] + since_ms: Option, + #[serde(default)] + until_ms: Option, + group_by: String, + #[serde(default)] + utc_offset_seconds: i32, + } + let request: StatsRequest = crate::decode(payload)?; + let group_by = parse_group_by(&request.group_by, request.utc_offset_seconds, true) + .ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.invalidGroup", + "Group by day, agent, model, session or cwd.", + ) + })?; + let summaries = match allowed_agents(runtime, request.agents) { + None => json!([]), + Some(agents) => { + let filter = CallFilter { + agents, + session_id: request.session_id, + since_ms: request.since_ms, + until_ms: request.until_ms, + }; + let reader = self.lock_reader(); + let store = reader.as_ref().ok_or_else(not_configured)?; + self.summarize(store, &filter, group_by)? + } + }; + Ok(json!({ + "summaries": summaries, + "rateLimits": self.rate_limit_entries(runtime), + })) + } + + fn summarize( + &self, + store: &SessionStore, + filter: &CallFilter, + group_by: GroupBy, + ) -> Result { + let prices = self.prices.read().unwrap_or_else(PoisonError::into_inner); + let mut summarizer = Summarizer::new(group_by, prices.as_ref()); + store.for_each_call(filter, |entry| { + summarizer.add(&entry); + Ok(()) + })?; + Ok(serde_json::to_value(summarizer.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, + /// 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 { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct UsageRequest { + #[serde(default)] + since_ms: Option, + #[serde(default)] + until_ms: Option, + group_by: String, + #[serde(default)] + utc_offset_seconds: i32, + } + let invalid = |message: &str| AgentHostFailure::new(codes::HOST_INVALID_PARAMS, message); + let request: UsageRequest = serde_json::from_value(params.clone()) + .map_err(|error| invalid(&format!("Invalid usage request: {error}")))?; + let group_by = parse_group_by(&request.group_by, request.utc_offset_seconds, false) + .ok_or_else(|| invalid("Group usage by day, agent or model."))?; + let until_ms = request + .until_ms + .unwrap_or_else(|| now_ms() + MILLISECONDS_PER_DAY); + let since_ms = request + .since_ms + .unwrap_or(until_ms - 30 * MILLISECONDS_PER_DAY); + if since_ms >= until_ms || until_ms - since_ms > MAX_USAGE_DAYS * MILLISECONDS_PER_DAY { + return Err(invalid("The usage range is empty or longer than 366 days.")); + } + let agents: Vec = runtime + .catalog + .readable() + .iter() + .map(CatalogAgent::record_key) + .collect(); + let summaries = if agents.is_empty() { + json!([]) + } else { + let reader = match self.reader.try_lock() { + Ok(reader) => reader, + Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + return Err(AgentHostFailure::new( + codes::HOST_BUSY, + "The session records are busy; try again shortly.", + )) + } + }; + let Some(store) = reader.as_ref() else { + return Err(AgentHostFailure::new( + codes::HOST_UNAVAILABLE, + "The session records are not available yet.", + )); + }; + let filter = CallFilter { + agents, + session_id: None, + since_ms: Some(since_ms), + until_ms: Some(until_ms), + }; + self.summarize(store, &filter, group_by).map_err(|_| { + AgentHostFailure::new(codes::HOST_FAILED, "Could not sum the session records.") + })? + }; + Ok(json!({ + "sinceMs": since_ms, + "untilMs": until_ms, + "summaries": summaries, + "rateLimits": self.rate_limit_entries(runtime), + })) + } + + /// Keeps a rate-limit snapshot an agent reported while it ran. + pub fn note_rate_limits(&self, key: &str, limits: RateLimits, at_ms: i64) { + self.keep_rate_snapshot(key, RateSnapshot::new(limits, at_ms)); + } + + fn keep_rate_snapshot(&self, key: &str, snapshot: RateSnapshot) { + let changed = { + let mut rates = self.lock_rates(); + match rates.get(key) { + Some(current) if current.at_ms > snapshot.at_ms || *current == snapshot => false, + _ => { + rates.insert(key.to_string(), snapshot); + true + } + } + }; + if changed { + self.save_rate_file(); + } + } + + /// The latest rate limits of the agents the user enabled. + fn rate_limit_entries(&self, runtime: &Runtime) -> Vec { + let rates = self.lock_rates().clone(); + rates + .into_iter() + .filter_map(|(key, snapshot)| { + let agent = runtime.catalog.find_key(&key)?; + if !agent.may_run && !agent.may_read_sessions { + return None; + } + let mut value = serde_json::to_value(&snapshot).ok()?; + value["pluginID"] = json!(agent.plugin_id); + value["agentID"] = json!(agent.agent.id); + Some(value) + }) + .collect() + } + + fn save_rate_file(&self) { + let Some(config) = self.config() else { return }; + let file = RateFile { + version: 1, + agents: self.lock_rates().clone(), + }; + let Ok(bytes) = serde_json::to_vec(&file) else { + return; + }; + // Best effort: a lost snapshot comes back with the agent's next report. + 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); + } + } +} + +fn load_rate_file(directory: &Path) -> BTreeMap { + let path = directory.join(RATE_FILE); + let readable = fs::metadata(&path).is_ok_and(|meta| meta.len() <= MAX_RATE_FILE_BYTES); + let file: Option = readable + .then(|| fs::read(&path).ok()) + .flatten() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()); + let Some(file) = file.filter(|file| file.version == 1) else { + return BTreeMap::new(); + }; + file.agents + .into_iter() + .filter(|(key, snapshot)| split_record_key(key).is_some() && snapshot.check().is_ok()) + .collect() +} + +fn load_prices(path: &str) -> Result { + let path = Path::new(path); + if !path.is_absolute() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The price table path must be absolute.", + )); + } + let bytes = fs::read(path) + .map_err(|_| CoreError::new(ErrorCode::EntryNotFound, "Could not read the price table."))?; + PriceTable::from_models_dev(&bytes) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct AgentRequest { + #[serde(rename = "pluginID")] + plugin_id: String, + #[serde(rename = "agentID")] + agent_id: String, +} + +/// 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.", + ) + })?; + if !agent.may_read_sessions { + return Err(refusal( + ErrorCode::PermissionDenied, + "agentSessions.readNotGranted", + "The user has not allowed Lithe to read this agent's sessions.", + )); + } + if agent.agent.session_sources.is_empty() { + return Err(refusal( + ErrorCode::NotSupported, + "agentSessions.noSources", + "The agent declares no session records.", + )); + } + Ok(agent) +} + +/// The record keys a request may cover: the requested agents the user lets +/// Lithe read, or all of them. `None` when that leaves none, because an empty +/// filter would cover every agent in the cache. +fn allowed_agents(runtime: &Runtime, requested: Option>) -> Option> { + let readable: Vec = runtime + .catalog + .readable() + .iter() + .map(CatalogAgent::record_key) + .collect(); + let agents = match requested { + Some(requested) => requested + .into_iter() + .filter(|key| readable.contains(key)) + .collect(), + None => readable, + }; + (!agents.is_empty()).then_some(agents) +} + +fn add_agent_ids(value: &mut Value, key: &str) { + if let Some((plugin_id, agent_id)) = split_record_key(key) { + value["pluginID"] = json!(plugin_id); + value["agentID"] = json!(agent_id); + } +} + +fn parse_group_by(name: &str, utc_offset_seconds: i32, host: bool) -> Option { + if !(-14 * 3600..=14 * 3600).contains(&utc_offset_seconds) { + return None; + } + match name { + "day" => Some(GroupBy::Day { utc_offset_seconds }), + "agent" => Some(GroupBy::Agent), + "model" => Some(GroupBy::Model), + "session" if host => Some(GroupBy::Session), + "cwd" if host => Some(GroupBy::Cwd), + _ => None, + } +} + +/// A session source with its root resolved. +struct RootedSource { + root: PathBuf, + source: SessionSourceDeclaration, +} + +fn rooted_sources(agent: &CatalogAgent, config: &Config) -> Vec { + agent + .agent + .session_sources + .iter() + .filter_map(|source| { + let root = lithe_plugin_agents::resolve_root( + &source.roots, + &config.user_home, + &config.environment, + )?; + Some(RootedSource { + root, + source: source.clone(), + }) + }) + .collect() +} + +/// The source whose root holds `path`, the deepest one when roots nest. +fn source_index(sources: &[RootedSource], path: &Path) -> Option { + if !path.is_absolute() { + return None; + } + sources + .iter() + .enumerate() + .filter(|(_, source)| path.starts_with(&source.root)) + .max_by_key(|(_, source)| source.root.components().count()) + .map(|(index, _)| index) +} + +fn backend_for( + link: &dyn BackendLink, + plugin_id: &str, + function_id: &str, +) -> Result { + link.session_for(plugin_id, function_id, None) + .ok_or_else(|| { + refusal( + ErrorCode::InvalidRequest, + "agentSessions.backendUnavailable", + "The agent plugin's backend is not running.", + ) + }) +} + +/// The lines of `bytes` as text, without their line breaks. +fn text_lines(bytes: &[u8]) -> Vec { + if bytes.is_empty() { + return Vec::new(); + } + let body = bytes.strip_suffix(b"\n").unwrap_or(bytes); + body.split(|byte| *byte == b'\n') + .map(|line| String::from_utf8_lossy(line.strip_suffix(b"\r").unwrap_or(line)).into_owned()) + .collect() +} + +/// Calls a source's `read` function with `items` and returns one answer +/// item per request item. +fn call_read( + link: &dyn BackendLink, + agent: &CatalogAgent, + source: &SessionSourceDeclaration, + mode: &str, + items: Vec, +) -> Result, CoreError> { + let backend = backend_for(link, &agent.plugin_id, &source.read)?; + let count = items.len(); + let params = json!({ + "agentID": agent.agent.id, + "sourceID": source.id, + "mode": mode, + "items": items, + }); + let answer = link + .call( + &backend, + &agent.plugin_id, + &source.read, + params, + READ_TIMEOUT, + ) + .map_err(|_| { + refusal( + ErrorCode::ProcessFailed, + "agentSessions.readFailed", + "The agent plugin could not read the session.", + ) + })?; + let invalid = || { + refusal( + ErrorCode::ParseFailed, + "agentSessions.invalidRead", + "The agent plugin returned an invalid reading of the session.", + ) + }; + let Some(Value::Array(items)) = answer.get("items").cloned() else { + return Err(invalid()); + }; + if items.len() != count || answer.as_object().is_some_and(|object| object.len() != 1) { + return Err(invalid()); + } + Ok(items) +} + +fn decode_title(item: &Value) -> Option { + let title = item.get("title")?.as_str()?.trim(); + if title.is_empty() { + return None; + } + let mut end = title.len().min(MAX_TITLE_BYTES); + while !title.is_char_boundary(end) { + end -= 1; + } + Some(title[..end].to_string()) +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ReadMessage { + /// `user`, `assistant`, `thought` or `tool`. + role: String, + text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + at_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + tool_name: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ReadItem { + #[serde(default)] + messages: Vec, +} + +fn decode_messages(item: Value) -> Result, CoreError> { + let invalid = || { + refusal( + ErrorCode::ParseFailed, + "agentSessions.invalidRead", + "The agent plugin returned an invalid reading of the session.", + ) + }; + let item: ReadItem = serde_json::from_value(item).map_err(|_| invalid())?; + let valid = item.messages.len() <= MAX_MESSAGES_PER_ITEM + && item.messages.iter().all(|message| { + matches!( + message.role.as_str(), + "user" | "assistant" | "thought" | "tool" + ) && message.text.len() <= MAX_MESSAGE_TEXT_BYTES + && message + .tool_name + .as_deref() + .is_none_or(|name| !name.is_empty() && name.len() <= 256) + }); + if valid { + Ok(item.messages) + } else { + Err(invalid()) + } +} + +/// Where the files of one source go to be scanned. +struct Route { + root: PathBuf, + source: SessionSourceDeclaration, + backend: String, +} + +/// A [`SessionParser`] that asks the agent plugin's backend. +struct PluginParser<'a> { + link: &'a dyn BackendLink, + plugin_id: &'a str, + agent_id: &'a str, + routes: &'a [Route], + /// The newest rate-limit snapshot the scans found. + rate_limits: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ScannedRateLimits { + at_ms: i64, + windows: Vec, + #[serde(default)] + plan: Option, +} + +impl PluginParser<'_> { + fn route(&self, path: &Path) -> Option<&Route> { + self.routes + .iter() + .filter(|route| path.starts_with(&route.root)) + .max_by_key(|route| route.root.components().count()) + } + + fn note(&mut self, limits: Value) -> Result<(), CoreError> { + let invalid = || { + CoreError::new( + ErrorCode::ParseFailed, + "The agent plugin returned invalid rate limits.", + ) + .with_details("agentSessions.invalidScan") + }; + let limits: ScannedRateLimits = serde_json::from_value(limits).map_err(|_| invalid())?; + if limits.windows.len() > MAX_RATE_WINDOWS { + return Err(invalid()); + } + let snapshot = RateSnapshot { + at_ms: limits.at_ms, + windows: limits.windows, + plan: limits.plan, + }; + snapshot.check().map_err(|_| invalid())?; + if self + .rate_limits + .as_ref() + .is_none_or(|current| current.at_ms <= snapshot.at_ms) + { + self.rate_limits = Some(snapshot); + } + Ok(()) + } +} + +/// The whole lines of a chunk: each line's file offset, its length with the +/// line break, and its text. Text that is not UTF-8 is replaced, so a parser +/// computes ranges from `offset` and `length`, never from the text. +fn chunk_lines(offset: u64, bytes: &[u8]) -> Vec { + let mut lines = Vec::new(); + let mut start = 0usize; + while start < bytes.len() { + let end = bytes[start..] + .iter() + .position(|byte| *byte == b'\n') + .map_or(bytes.len(), |index| start + index + 1); + let line = &bytes[start..end]; + let content = line.strip_suffix(b"\n").unwrap_or(line); + let content = content.strip_suffix(b"\r").unwrap_or(content); + lines.push(json!({ + "offset": offset + start as u64, + "length": line.len(), + "text": String::from_utf8_lossy(content), + })); + start = end; + } + lines +} + +impl SessionParser for PluginParser<'_> { + fn scan(&mut self, chunk: ScanChunk<'_>) -> Result { + let Some(route) = self.route(chunk.path) else { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The file is not in a session directory of the agent.", + )); + }; + 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), + }); + if let Some(state) = chunk.state { + params["state"] = state.clone(); + } + let mut answer = self + .link + .call( + &route.backend, + self.plugin_id, + &route.source.scan, + params, + SCAN_TIMEOUT, + ) + .map_err(|_| { + CoreError::new( + ErrorCode::ProcessFailed, + "The agent plugin could not read a session file.", + ) + .with_details("agentSessions.scanFailed") + })?; + if let Some(limits) = answer + .as_object_mut() + .and_then(|object| object.remove("rateLimits")) + { + self.note(limits)?; + } + serde_json::from_value(answer).map_err(|_| { + CoreError::new( + ErrorCode::ParseFailed, + "The agent plugin returned invalid session records.", + ) + .with_details("agentSessions.invalidScan") + }) + } +} + +#[cfg(test)] +pub(crate) fn chunk_lines_for_test(offset: u64, bytes: &[u8]) -> Vec { + chunk_lines(offset, bytes) +} + +#[cfg(test)] +pub(crate) fn text_lines_for_test(bytes: &[u8]) -> Vec { + text_lines(bytes) +} diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs new file mode 100644 index 00000000..b8a388c6 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests.rs @@ -0,0 +1,1410 @@ +//! Tests of the agent runtime with a scripted backend and agent CLI. +//! +//! A fake [`BackendLink`] stands in for the engine: it answers plugin +//! functions as a synthetic agent's backend would and records every +//! notification Core sends. Every agent CLI is a [`ScriptedServer`], so no +//! process starts. Every wait has its own deadline, and a harness that is +//! dropped ends its sessions and waits, bounded, for them to finish. + +use crate::backend::BackendLink; +use crate::{Host, Runtime}; +use lithe_diagnostics::core_events::capture; +use lithe_lsp_engine::agent_host::{AgentBackend, AgentCallFailure, AgentHost, AgentHostFailure}; +use lithe_lsp_transport::process::{LspProcessLauncher, LspProcessSpec, LspProcessStreams}; +use lithe_lsp_transport::scripted::ScriptedServer; +use lithe_plugin_rpc::{ + codes, AGENTS_DID_CANCEL, AGENTS_DID_DECIDE_PERMISSION, AGENTS_DID_EXIT, AGENTS_DID_OUTPUT, + AGENTS_DID_PROMPT, AGENTS_DID_START, AGENTS_REPORT, AGENTS_USAGE, AGENTS_WRITE, +}; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_request_context::{trace, Source}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +const PLUGIN: &str = "dev.lithe.test.agents"; +const AGENT: &str = "sample"; +const AGENT_KEY: &str = "dev.lithe.test.agents/sample"; +const BACKEND: &str = "backend-1"; +const WAIT: Duration = Duration::from_secs(5); +const ALL_GRANTS: &[&str] = &[ + "agents.native", + "agents.run", + "agents.sessions.read", + "backend.launch", +]; + +/// A directory under the system temporary directory, removed on drop. +struct TempDir(PathBuf); + +impl TempDir { + fn new(prefix: &str) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "lithe-agent-runtime {prefix} {} {}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + // A crashed earlier run with the same process ID may have left it. + if path.exists() { + fs::remove_dir_all(&path).expect("remove a stale temporary directory"); + } + fs::create_dir_all(&path).expect("create a temporary directory"); + Self(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + eprintln!("could not remove {}: {error}", self.0.display()); + } + } +} + +/// A synthetic agent plugin: one agent with a native mode, a terminal form, +/// an update command and one session source. +fn manifest() -> Value { + json!({ + "schemaVersion": 0, + "id": PLUGIN, + "displayName": "Agent runtime test plugin", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": { "agents": 0, "backend": 0 }, + "requiresTools": ["sample-cli"], + "vendor": { + "id": "dev.lithe.test", + "displayName": "Lithe tests", + "signatureRequirement": "publisherPackage" + }, + "permissions": ALL_GRANTS, + "activationEvents": ["onAgent:sample"], + "agents": [{ + "id": AGENT, + "displayName": "Sample Agent", + "tool": "sample-cli", + "native": { "function": "agent.launch" }, + "terminal": { "arguments": [] }, + "update": { "arguments": ["update"] }, + "sessionSources": [{ + "id": "projects", + "roots": ["${env:SAMPLE_HOME}/sessions", "${userHome}/.sample/sessions"], + "include": ["**/*.jsonl"], + "format": "jsonLines", + "scan": "sessions.scan", + "read": "sessions.read" + }] + }], + "backend": { "launch": { "kind": "packaged", "path": "bin/backend" }, "arguments": ["--stdio"] } + }) +} + +fn path_text(path: &Path) -> String { + path.to_str().expect("test paths are UTF-8").to_string() +} + +fn failure(code: &str) -> AgentCallFailure { + AgentCallFailure { + code: code.to_string(), + message: "The test backend failed.".to_string(), + plugin_error_code: None, + } +} + +/// How the synthetic agent's backend answers its functions. +fn sample_backend(function: &str, params: &Value) -> Result { + match function { + "agent.launch" => Ok(json!({ + "executable": { "kind": "tool", "tool": "sample-cli" }, + "arguments": ["--stream"] + })), + "sessions.scan" => Ok(scan(params)), + "sessions.read" => Ok(read(params)), + _ => Err(failure("plugin.function.unknown")), + } +} + +/// Parses the synthetic session format: one JSON object per line, with a +/// `type` of `session`, `user`, `call` or `limits`. +fn scan(params: &Value) -> Value { + let mut sessions = Vec::new(); + let mut calls = Vec::new(); + let mut spans = Vec::new(); + let mut rate_limits = None; + for line in params["lines"].as_array().expect("scan lines") { + let offset = line["offset"].as_u64().expect("line offset"); + let length = line["length"].as_u64().expect("line length"); + let range = json!({ "start": offset, "end": offset + length }); + let Ok(record) = serde_json::from_str::(line["text"].as_str().unwrap_or_default()) + else { + continue; + }; + match record["type"].as_str() { + Some("session") => sessions.push(json!({ + "sessionId": record["id"], + "cwd": record["cwd"], + "startedAtMs": record["at"], + "updatedAtMs": record["at"], + })), + Some("user") => { + sessions.push(json!({ + "sessionId": record["session"], + "updatedAtMs": record["at"], + "titleRange": range, + })); + spans.push(json!({ + "sessionId": record["session"], + "atMs": record["at"], + "range": range, + "text": record["text"], + })); + } + Some("call") => calls.push(json!({ + "key": record["key"], + "sessionId": record["session"], + "startedAtMs": record["at"], + "model": record["model"], + "tokens": { "input": record["input"], "output": record["output"] }, + "range": range, + })), + Some("limits") => { + rate_limits = Some(json!({ + "atMs": record["at"], + "windows": [{ "id": "5h", "usedPercent": record["used"], "windowMinutes": 300 }], + "plan": "pro", + })); + } + _ => {} + } + } + let mut answer = json!({ "sessions": sessions, "calls": calls, "spans": spans }); + if let Some(limits) = rate_limits { + answer["rateLimits"] = limits; + } + answer +} + +/// Reads items of the synthetic format: the first user text as the title, or +/// every user text as a message. +fn read(params: &Value) -> Value { + let titles = params["mode"] == "titles"; + let items: Vec = params["items"] + .as_array() + .expect("read items") + .iter() + .map(|item| { + let texts: Vec = item["lines"] + .as_array() + .expect("item lines") + .iter() + .filter_map(|line| serde_json::from_str::(line.as_str()?).ok()) + .filter(|record| record["type"] == "user") + .filter_map(|record| record["text"].as_str().map(str::to_string)) + .collect(); + if titles { + json!({ "title": texts.first() }) + } else { + let messages: Vec = texts + .iter() + .map(|text| json!({ "role": "user", "text": text })) + .collect(); + json!({ "messages": messages }) + } + }) + .collect(); + json!({ "items": items }) +} + +/// One CLI the runtime started. +struct Launch { + executable: PathBuf, + arguments: Vec, + working_directory: PathBuf, + environment: BTreeMap, + server: Arc, +} + +/// Starts a new scripted CLI for every launch and keeps what it was given. +#[derive(Default)] +struct RecordingLauncher { + launches: Mutex>, +} + +impl LspProcessLauncher for RecordingLauncher { + fn launch(&self, spec: LspProcessSpec) -> Result { + let server = Arc::new(ScriptedServer::new()); + let launch = Launch { + executable: spec.executable.clone(), + arguments: spec.arguments.clone(), + working_directory: spec.working_directory.clone(), + environment: spec.environment.clone(), + server: server.clone(), + }; + let streams = server.launcher().launch(spec)?; + self.launches + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(launch); + Ok(streams) + } +} + +type Answer = Box Result + Send + Sync>; + +/// A notification Core sent to a backend. +struct Notice { + backend: String, + method: String, + params: Value, +} + +/// The engine as the runtime sees it, with one backend of [`PLUGIN`]. +struct FakeLink { + backend: Mutex>, + answer: Mutex, + calls: Mutex>, + notices: Mutex>, + notices_changed: Condvar, + /// A notification method the backend refuses, as a backend that stopped. + refused: Mutex>, + launcher: Arc, +} + +impl FakeLink { + fn new() -> Arc { + Arc::new(Self { + backend: Mutex::new(Some(BACKEND.to_string())), + answer: Mutex::new(Box::new(sample_backend)), + calls: Mutex::new(Vec::new()), + notices: Mutex::new(Vec::new()), + notices_changed: Condvar::new(), + refused: Mutex::new(None), + launcher: Arc::new(RecordingLauncher::default()), + }) + } + + fn set_backend(&self, backend: Option<&str>) { + *self.backend.lock().unwrap() = backend.map(str::to_string); + } + + fn set_answer( + &self, + answer: impl Fn(&str, &Value) -> Result + Send + Sync + 'static, + ) { + *self.answer.lock().unwrap() = Box::new(answer); + } + + fn refuse(&self, method: Option<&'static str>) { + *self.refused.lock().unwrap() = method; + } + + fn launch_count(&self) -> usize { + self.launcher.launches.lock().unwrap().len() + } + + fn server(&self, index: usize) -> Arc { + self.launcher.launches.lock().unwrap()[index].server.clone() + } + + fn calls_of(&self, function: &str) -> Vec { + self.calls + .lock() + .unwrap() + .iter() + .filter(|(called, _)| called == function) + .map(|(_, params)| params.clone()) + .collect() + } + + fn notices_of(&self, method: &str) -> Vec { + self.notices + .lock() + .unwrap() + .iter() + .filter(|notice| notice.method == method) + .map(|notice| notice.params.clone()) + .collect() + } + + /// Waits for a notification of `method` whose params `matches` accepts. + fn await_notice(&self, method: &str, matches: impl Fn(&Value) -> bool) -> Value { + let deadline = Instant::now() + WAIT; + let mut notices = self.notices.lock().unwrap(); + loop { + if let Some(notice) = notices + .iter() + .find(|notice| notice.method == method && matches(¬ice.params)) + { + assert_eq!(notice.backend, BACKEND); + return notice.params.clone(); + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + drop(notices); + panic!("no {method} notification arrived in time"); + } + notices = self + .notices_changed + .wait_timeout(notices, remaining) + .unwrap() + .0; + } + } + + /// Waits until the `didOutput` notifications of `session` carry `count` + /// lines, and returns them in order. + fn await_output(&self, session: &str, count: usize) -> Vec { + let deadline = Instant::now() + WAIT; + let mut notices = self.notices.lock().unwrap(); + loop { + let lines: Vec = notices + .iter() + .filter(|notice| { + notice.method == AGENTS_DID_OUTPUT && notice.params["session"] == session + }) + .flat_map(|notice| { + notice.params["lines"] + .as_array() + .cloned() + .unwrap_or_default() + }) + .filter_map(|line| line.as_str().map(str::to_string)) + .collect(); + if lines.len() >= count { + return lines; + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + drop(notices); + panic!("{count} output lines of {session} did not arrive in time"); + } + notices = self + .notices_changed + .wait_timeout(notices, remaining) + .unwrap() + .0; + } + } +} + +impl BackendLink for FakeLink { + fn session_for( + &self, + plugin_id: &str, + _function_id: &str, + _root_uri: Option<&str>, + ) -> Option { + if plugin_id != PLUGIN { + return None; + } + self.backend.lock().unwrap().clone() + } + + fn call( + &self, + session_id: &str, + plugin_id: &str, + function_id: &str, + params: Value, + _timeout: Duration, + ) -> Result { + assert_eq!(session_id, BACKEND); + assert_eq!(plugin_id, PLUGIN); + self.calls + .lock() + .unwrap() + .push((function_id.to_string(), params.clone())); + let answer = self.answer.lock().unwrap(); + answer(function_id, ¶ms) + } + + fn notify(&self, session_id: &str, method: &str, params: Value) -> Result<(), CoreError> { + if self + .refused + .lock() + .unwrap() + .is_some_and(|refused| refused == method) + { + return Err(CoreError::new( + ErrorCode::ProcessFailed, + "The test backend refused the notification.", + )); + } + self.notices.lock().unwrap().push(Notice { + backend: session_id.to_string(), + method: method.to_string(), + params, + }); + self.notices_changed.notify_all(); + Ok(()) + } + + fn launcher(&self) -> Arc { + self.launcher.clone() + } +} + +/// A runtime with the synthetic plugin configured, a tool file, a working +/// directory and a session cache, driven as a user request. +struct Harness { + dir: TempDir, + runtime: Arc, + link: Arc, + host: Host, + tool: PathBuf, + work: PathBuf, + /// The last event sequence [`Harness::next_event`] looked at. + cursor: u64, + trace: Option, +} + +impl Harness { + fn new(name: &str, grants: &[&str]) -> Self { + let dir = TempDir::new(name); + let tool = dir.path().join("bin").join("sample-cli"); + fs::create_dir_all(tool.parent().unwrap()).unwrap(); + fs::write(&tool, b"").unwrap(); + let work = dir.path().join("work"); + fs::create_dir_all(&work).unwrap(); + fs::create_dir_all(dir.path().join("cache")).unwrap(); + fs::create_dir_all(dir.path().join("home")).unwrap(); + let link = FakeLink::new(); + let runtime = Runtime::new(link.clone()); + let host = Host(runtime.clone()); + let previous = trace::replace(trace::Context { + op: None, + source: Source::User, + }); + let harness = Self { + dir, + runtime, + link, + host, + tool, + work, + cursor: 0, + trace: Some(previous), + }; + harness.grant(grants); + harness.configure_records(); + harness + } + + fn grant(&self, grants: &[&str]) -> Value { + self.run( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest(), "grantedPermissions": grants }] }), + ) + } + + fn configure_records(&self) -> Value { + self.run( + "agentSessions.configure", + json!({ + "cacheDirectory": path_text(&self.dir.path().join("cache")), + "userHome": path_text(&self.dir.path().join("home")), + }), + ) + } + + fn run(&self, command: &str, payload: Value) -> Value { + self.runtime + .execute(command, payload) + .unwrap_or_else(|error| panic!("{command} failed: {error:?}")) + } + + /// The `details` code of a refused command. + fn refused(&self, command: &str, payload: Value) -> String { + match self.runtime.execute(command, payload) { + Ok(answer) => panic!("{command} was not refused: {answer}"), + Err(error) => error.details.unwrap_or_default(), + } + } + + fn start_payload(&self) -> Value { + json!({ + "pluginID": PLUGIN, + "agentID": AGENT, + "cwd": path_text(&self.work), + "toolPath": path_text(&self.tool), + "workspaceTrusted": true, + "environment": { "PATH": "/usr/bin" }, + }) + } + + fn start(&self) -> String { + let answer = self.run("agents.start", self.start_payload()); + assert_eq!(answer["mode"], "native"); + answer["session"].as_str().expect("session ID").to_string() + } + + fn answer(&self, method: &str, params: Value) -> Result { + self.answer_as(BACKEND, PLUGIN, method, params) + } + + fn answer_as( + &self, + backend: &str, + plugin: &str, + method: &str, + params: Value, + ) -> Result { + self.host.answer( + AgentBackend { + session_id: backend, + plugin_id: plugin, + }, + method, + ¶ms, + ) + } + + fn report(&self, session: &str, events: Value) -> Result { + self.answer( + AGENTS_REPORT, + json!({ "session": session, "events": events }), + ) + } + + /// The next event of `kind` for `session` after the ones already looked + /// at. Events of other kinds are passed over. + fn next_event(&mut self, session: &str, kind: &str) -> Value { + let deadline = Instant::now() + WAIT; + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + assert!( + !remaining.is_zero(), + "no {kind} event of {session} arrived in time" + ); + let batch = self.run( + "agents.waitEvents", + json!({ + "after": self.cursor, + "timeoutMilliseconds": u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX), + }), + ); + for entry in batch["events"].as_array().expect("events") { + self.cursor = entry["sequence"].as_u64().expect("sequence"); + if entry["session"] == session && entry["event"]["kind"] == kind { + return entry["event"].clone(); + } + } + } + } + + fn sessions(&self) -> Vec { + self.run("agents.sessions", json!({}))["sessions"] + .as_array() + .cloned() + .unwrap_or_default() + } + + /// Waits until no session runs. + fn settle(&self) -> bool { + let deadline = Instant::now() + WAIT; + let mut after = 0; + loop { + if self.runtime.live.list()["sessions"] + .as_array() + .is_some_and(Vec::is_empty) + { + return true; + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return false; + } + // A session leaves the list before its `exited` event is queued, + // so waiting for the next event cannot miss the change. + let batch = self.runtime.live.queue.wait(after, remaining, 512); + after = batch["next"].as_u64().unwrap_or(after); + } + } +} + +impl Drop for Harness { + fn drop(&mut self) { + let servers: Vec> = self + .link + .launcher + .launches + .lock() + .unwrap_or_else(PoisonError::into_inner) + .iter() + .map(|launch| launch.server.clone()) + .collect(); + for server in servers { + if server.was_launched() { + server.exit(Some(0)); + } + } + let settled = self.settle(); + trace::replace(self.trace.take().unwrap_or_default()); + if !std::thread::panicking() { + assert!(settled, "agent sessions still ran after the test"); + } + } +} + +#[test] +fn configure_lists_agents_with_their_grants_and_reports_invalid_manifests() { + let harness = Harness::new("configure", ALL_GRANTS); + let mut broken = manifest(); + broken["id"] = json!("dev.lithe.test.broken"); + // Agents need agents.run declared. + broken["permissions"] = json!(["agents.native", "agents.sessions.read", "backend.launch"]); + let answer = harness.run( + "agents.configure", + json!({ "plugins": [ + { + "manifest": manifest(), + // A grant the manifest does not declare is ignored. + "grantedPermissions": ["agents.sessions.read", "agents.usage.read"], + }, + { "manifest": broken }, + ]}), + ); + let agents = answer["agents"].as_array().expect("agents"); + assert_eq!(agents.len(), 1); + assert_eq!(agents[0]["pluginID"], PLUGIN); + assert_eq!(agents[0]["agentID"], AGENT); + assert_eq!(agents[0]["mayRun"], false); + assert_eq!(agents[0]["mayReadSessions"], true); + assert_eq!(agents[0]["sessionRootVariables"], json!(["SAMPLE_HOME"])); + let rejected = answer["rejected"].as_array().expect("rejected"); + assert_eq!(rejected.len(), 1); + assert_eq!(rejected[0]["pluginID"], "dev.lithe.test.broken"); + assert!(rejected[0]["code"] + .as_str() + .is_some_and(|code| code.starts_with("plugin."))); + assert_eq!( + harness.run("agents.catalog", json!({}))["agents"], + answer["agents"] + ); + + assert_eq!( + harness.refused( + "agents.configure", + json!({ "plugins": [], "unknown": true }) + ), + "agents.invalidPayload" + ); + assert_eq!( + harness.refused("agents.unknown", json!({})), + "agents.unknownCommand" + ); +} + +#[test] +fn start_refuses_before_anything_runs() { + let harness = Harness::new("refusals", ALL_GRANTS); + let refused_with = |change: &dyn Fn(&mut Value)| { + let mut payload = harness.start_payload(); + change(&mut payload); + harness.refused("agents.start", payload) + }; + + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + assert_eq!(refused_with(&|_| {}), "agents.userActionRequired"); + trace::replace(previous); + + assert_eq!( + refused_with(&|payload| payload["workspaceTrusted"] = json!(false)), + "agents.untrustedWorkspace" + ); + assert_eq!( + refused_with(&|payload| payload["agentID"] = json!("missing")), + "agents.unknownAgent" + ); + assert_eq!( + refused_with(&|payload| payload["cwd"] = json!("work")), + "agents.invalidDirectory" + ); + assert_eq!( + refused_with(&|payload| payload["toolPath"] = json!(path_text(&harness.work))), + "agents.toolNotFound" + ); + assert_eq!( + refused_with(&|payload| payload["environment"] = json!({ "A=B": "value" })), + "agents.invalidEnvironment" + ); + assert_eq!( + refused_with(&|payload| payload["resume"] = json!("")), + "agents.invalidResume" + ); + + harness.link.set_backend(None); + assert_eq!(refused_with(&|_| {}), "agents.backendUnavailable"); + harness.link.set_backend(Some(BACKEND)); + + harness.link.set_answer(|_, _| { + Ok(json!({ + "executable": { "kind": "tool", "tool": "sample-cli" }, + "arguments": [], + "environment": { "SAMPLE_TOKEN": "value" } + })) + }); + assert_eq!(refused_with(&|_| {}), "plugin.agents.launchEnvironment"); + harness.link.set_answer(|_, _| { + Ok(json!({ "executable": { "kind": "tool", "tool": "other-cli" }, "arguments": [] })) + }); + assert_eq!(refused_with(&|_| {}), "plugin.agents.undeclaredTool"); + harness + .link + .set_answer(|_, _| Ok(json!({ "arguments": "--stream" }))); + assert_eq!(refused_with(&|_| {}), "plugin.agents.invalidLaunch"); + harness + .link + .set_answer(|_, _| Err(failure("requestTimeout"))); + assert_eq!(refused_with(&|_| {}), "agents.launchTimeout"); + harness + .link + .set_answer(|_, _| Err(failure("plugin.function.failed"))); + assert_eq!(refused_with(&|_| {}), "agents.launchFailed"); + + harness.grant(&["agents.sessions.read", "backend.launch"]); + assert_eq!(refused_with(&|_| {}), "agents.runNotGranted"); + + assert_eq!(harness.link.launch_count(), 0); + assert!(harness.link.notices_of(AGENTS_DID_START).is_empty()); +} + +#[test] +fn native_session_relays_the_cli_and_checks_reports_against_turns() { + let mut harness = Harness::new("native", ALL_GRANTS); + let (session, logs) = capture::run(false, || harness.start()); + assert_eq!(session, "agent-1"); + let started_log = logs + .iter() + .find(|log| log.event == "agent.session.started") + .expect("the start is logged"); + assert_eq!(started_log.fields["session"], json!(session)); + + let launches = harness.link.launcher.launches.lock().unwrap(); + assert_eq!(launches.len(), 1); + assert_eq!(launches[0].executable, harness.tool); + assert_eq!(launches[0].arguments, ["--stream"]); + assert_eq!(launches[0].working_directory, harness.work); + assert_eq!( + launches[0].environment, + BTreeMap::from([("PATH".to_string(), "/usr/bin".to_string())]) + ); + drop(launches); + let server = harness.link.server(0); + assert_eq!( + harness.link.calls_of("agent.launch"), + [json!({ "agentID": AGENT, "cwd": path_text(&harness.work) })] + ); + assert_eq!( + harness.link.await_notice(AGENTS_DID_START, |_| true), + json!({ "agentID": AGENT, "cwd": path_text(&harness.work), "session": session }) + ); + let started = harness.next_event(&session, "started"); + assert_eq!(started["pluginID"], PLUGIN); + assert_eq!(started["agentID"], AGENT); + assert_eq!(started["mode"], "native"); + + // The CLI's stdout reaches the backend line by line. + server.send_raw(b"{\"a\":1}\r\n{\"b\":2}\n"); + assert_eq!( + harness.link.await_output(&session, 2), + ["{\"a\":1}", "{\"b\":2}"] + ); + + // What the backend writes reaches the CLI's stdin, one line each. + harness + .answer( + AGENTS_WRITE, + json!({ "session": session, "lines": ["{\"x\":1}", "{\"y\":2}"] }), + ) + .expect("write"); + assert!(server.await_written_bytes(|bytes| bytes == b"{\"x\":1}\n{\"y\":2}\n")); + let refusal = harness + .answer( + AGENTS_WRITE, + json!({ "session": session, "lines": ["a\nb"] }), + ) + .expect_err("a line break is refused"); + assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS); + for (backend, plugin) in [("backend-2", PLUGIN), (BACKEND, "dev.lithe.test.other")] { + let refusal = harness + .answer_as( + backend, + plugin, + AGENTS_WRITE, + json!({ "session": session, "lines": ["x"] }), + ) + .expect_err("only the session's backend writes"); + assert_eq!(refusal.code, codes::HOST_NOT_FOUND); + } + + // A prompt starts a turn. + let prompt = "Explain the private build script"; + assert_eq!( + harness.run( + "agents.prompt", + json!({ "session": session, "text": prompt }) + ), + json!({ "turn": 1 }) + ); + assert_eq!( + harness.link.await_notice(AGENTS_DID_PROMPT, |_| true), + json!({ "session": session, "turn": 1, "text": prompt }) + ); + assert_eq!(harness.next_event(&session, "turnStarted")["turn"], 1); + assert_eq!( + harness.refused( + "agents.prompt", + json!({ "session": session, "text": "again" }) + ), + "agents.turnInProgress" + ); + assert_eq!( + harness.refused("agents.prompt", json!({ "session": session, "text": " " })), + "agents.invalidPrompt" + ); + + // Reports must fit the turn in progress. + harness + .report( + &session, + json!([ + { "kind": "session", "agentSessionID": "cli-123", "model": "sample-model" }, + { "kind": "message", "turn": 1, "role": "assistant", "messageID": "m1", "text": "Hi", "delta": true }, + { + "kind": "permissionRequested", + "turn": 1, + "permission": "p1", + "title": "Run ls", + "options": [ + { "id": "allow", "label": "Allow", "optionKind": "allowOnce" }, + { "id": "deny", "label": "Deny", "optionKind": "rejectOnce" } + ] + } + ]), + ) + .expect("report"); + assert_eq!(harness.next_event(&session, "message")["text"], "Hi"); + assert_eq!( + harness.next_event(&session, "permissionRequested")["permission"], + "p1" + ); + let sessions = harness.sessions(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0]["pendingPermissions"], json!(["p1"])); + assert_eq!(sessions[0]["activeTurn"], 1); + assert_eq!(sessions[0]["agentSessionID"], "cli-123"); + + let (refusal, logs) = capture::run(false, || { + harness + .report( + &session, + json!([{ "kind": "message", "turn": 2, "role": "assistant", "messageID": "m2", "text": "x" }]), + ) + .expect_err("a later turn is refused") + }); + assert_eq!(refusal.code, codes::HOST_PRECONDITION_FAILED); + let rejected = logs + .iter() + .find(|log| log.event == "agent.report.rejected") + .expect("the rejection is logged"); + assert_eq!( + rejected.fields["code"], + json!(codes::HOST_PRECONDITION_FAILED) + ); + let refusal = harness + .answer( + AGENTS_REPORT, + json!({ "session": session, "events": [{ "kind": "notice", "level": "info", "text": "x" }], "extra": 1 }), + ) + .expect_err("an unknown field is refused"); + assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS); + let refusal = harness + .report(&session, json!([{ "kind": "unknown" }])) + .expect_err("an unknown event is refused"); + assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS); + let refusal = harness + .answer_as( + "backend-2", + PLUGIN, + AGENTS_REPORT, + json!({ "session": session, "events": [{ "kind": "notice", "level": "info", "text": "x" }] }), + ) + .expect_err("only the session's backend reports"); + assert_eq!(refusal.code, codes::HOST_NOT_FOUND); + // Nothing of a refused report was applied. + assert_eq!(harness.sessions()[0]["activeTurn"], 1); + + // The user answers the permission request with one of its options. + let answer = |option: &str| json!({ "session": session, "permission": "p1", "option": option }); + assert_eq!( + harness.refused("agents.respondPermission", answer("maybe")), + "agents.unknownPermissionOption" + ); + assert_eq!( + harness.run("agents.respondPermission", answer("allow")), + json!({ "turn": 1 }) + ); + assert_eq!( + harness + .link + .await_notice(AGENTS_DID_DECIDE_PERMISSION, |_| true), + json!({ "session": session, "turn": 1, "permission": "p1", "option": "allow" }) + ); + assert_eq!( + harness.next_event(&session, "permissionDecided")["option"], + "allow" + ); + assert_eq!( + harness.refused("agents.respondPermission", answer("allow")), + "agents.permissionNotPending" + ); + + // Cancelling asks the backend; the backend ends the turn. + assert_eq!( + harness.run("agents.cancel", json!({ "session": session })), + json!({ "turn": 1 }) + ); + assert_eq!( + harness.link.await_notice(AGENTS_DID_CANCEL, |_| true), + json!({ "session": session, "turn": 1 }) + ); + harness + .report( + &session, + json!([ + { "kind": "usage", "turn": 1, "model": "sample-model", "tokens": { "input": 10, "output": 2 } }, + { "kind": "rateLimits", "windows": [{ "id": "5h", "usedPercent": 25.0 }], "plan": "pro" }, + { "kind": "turnEnded", "turn": 1, "reason": "cancelled" } + ]), + ) + .expect("the turn ends"); + assert_eq!( + harness.next_event(&session, "turnEnded")["reason"], + "cancelled" + ); + assert_eq!( + harness.refused("agents.cancel", json!({ "session": session })), + "agents.noTurnInProgress" + ); + assert_eq!( + harness.run( + "agents.prompt", + json!({ "session": session, "text": "Next" }) + ), + json!({ "turn": 2 }) + ); + + // The latest rate limits are kept for the usage views. + let stats = harness.run("agentSessions.stats", json!({ "groupBy": "agent" })); + let limits = stats["rateLimits"].as_array().expect("rate limits"); + assert_eq!(limits.len(), 1); + assert_eq!(limits[0]["pluginID"], PLUGIN); + assert_eq!(limits[0]["windows"][0]["usedPercent"], 25.0); + assert!(harness + .dir + .path() + .join("cache") + .join("rate-limits.json") + .is_file()); + + // The CLI exits by itself. + server.exit(Some(0)); + assert_eq!( + harness.link.await_notice(AGENTS_DID_EXIT, |_| true), + json!({ "session": session, "exitCode": 0 }) + ); + let exited = harness.next_event(&session, "exited"); + assert_eq!(exited["reason"], "exited"); + assert_eq!(exited["exitCode"], 0); + assert!(harness.sessions().is_empty()); + assert_eq!( + harness.refused( + "agents.prompt", + json!({ "session": session, "text": "Late" }) + ), + "agents.unknownSession" + ); + let refusal = harness + .answer(AGENTS_WRITE, json!({ "session": session, "lines": ["x"] })) + .expect_err("an ended session takes no input"); + assert_eq!(refusal.code, codes::HOST_NOT_FOUND); + + // Lithe's logs carry IDs and codes, never what flowed through the session. + for log in &logs { + let text = serde_json::to_string(&log.fields).unwrap(); + assert!(!text.contains("cli-123") && !text.contains("private build")); + } +} + +#[test] +fn a_prompt_the_backend_does_not_take_ends_its_turn() { + let mut harness = Harness::new("prompt-refused", ALL_GRANTS); + let session = harness.start(); + harness.link.refuse(Some(AGENTS_DID_PROMPT)); + assert_eq!( + harness.refused( + "agents.prompt", + json!({ "session": session, "text": "Hello" }) + ), + "agents.backendUnavailable" + ); + let ended = harness.next_event(&session, "turnEnded"); + assert_eq!( + ended, + json!({ "kind": "turnEnded", "turn": 1, "reason": "failed" }) + ); + assert!(harness.sessions()[0].get("activeTurn").is_none()); + harness.link.refuse(None); + assert_eq!( + harness.run( + "agents.prompt", + json!({ "session": session, "text": "Hello" }) + ), + json!({ "turn": 2 }) + ); +} + +#[test] +fn only_a_user_request_prompts_or_answers_permissions() { + let harness = Harness::new("background", ALL_GRANTS); + let session = harness.start(); + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + let prompt = harness.refused("agents.prompt", json!({ "session": session, "text": "Hi" })); + let permission = harness.refused( + "agents.respondPermission", + json!({ "session": session, "permission": "p1", "option": "allow" }), + ); + trace::replace(previous); + assert_eq!(prompt, "agents.userActionRequired"); + assert_eq!(permission, "agents.userActionRequired"); + assert!(harness.link.notices_of(AGENTS_DID_PROMPT).is_empty()); +} + +#[test] +fn an_agent_runs_at_most_four_sessions() { + let harness = Harness::new("limit", ALL_GRANTS); + let sessions: Vec = (0..4).map(|_| harness.start()).collect(); + assert_eq!(sessions, ["agent-1", "agent-2", "agent-3", "agent-4"]); + assert_eq!( + harness.refused("agents.start", harness.start_payload()), + "agents.tooManySessions" + ); + assert_eq!(harness.link.launch_count(), 4); +} + +#[test] +fn a_backend_that_ends_takes_its_sessions_with_it() { + let mut harness = Harness::new("backend-ended", ALL_GRANTS); + let session = harness.start(); + harness.host.backend_ended("backend-2"); + assert_eq!(harness.sessions().len(), 1); + harness.host.backend_ended(BACKEND); + let exited = harness.next_event(&session, "exited"); + assert_eq!(exited["reason"], "backendEnded"); + // The backend is gone, so it is not told. + assert!(harness.link.notices_of(AGENTS_DID_EXIT).is_empty()); + assert!(harness.sessions().is_empty()); +} + +#[test] +fn closing_ends_input_and_withdrawing_the_grant_ends_sessions() { + let mut harness = Harness::new("close", ALL_GRANTS); + let first = harness.start(); + let second = harness.start(); + + assert_eq!( + harness.run("agents.close", json!({ "session": first })), + json!({}) + ); + let server = harness.link.server(0); + assert!(server.input_was_closed()); + server.exit(Some(0)); + let exited = harness.next_event(&first, "exited"); + assert_eq!(exited["reason"], "closed"); + assert_eq!(exited["exitCode"], 0); + + harness.grant(&["agents.sessions.read", "backend.launch"]); + let exited = harness.next_event(&second, "exited"); + assert_eq!(exited["reason"], "closed"); + assert_eq!( + harness + .link + .await_notice(AGENTS_DID_EXIT, |params| params["session"] == second)["session"], + json!(second) + ); + assert!(harness.sessions().is_empty()); + assert_eq!( + harness.refused("agents.close", json!({ "session": first })), + "agents.unknownSession" + ); +} + +#[test] +fn output_the_backend_cannot_take_ends_the_session() { + let mut harness = Harness::new("output-refused", ALL_GRANTS); + let session = harness.start(); + harness.link.refuse(Some(AGENTS_DID_OUTPUT)); + harness.link.server(0).send_raw(b"{\"a\":1}\n"); + let exited = harness.next_event(&session, "exited"); + assert_eq!(exited["reason"], "failed"); + assert_eq!( + harness.link.await_notice(AGENTS_DID_EXIT, |_| true)["session"], + json!(session) + ); +} + +#[test] +fn a_backend_that_stops_while_the_session_starts_ends_the_cli() { + let harness = Harness::new("start-refused", ALL_GRANTS); + harness.link.refuse(Some(AGENTS_DID_START)); + assert_eq!( + harness.refused("agents.start", harness.start_payload()), + "agents.backendUnavailable" + ); + assert_eq!(harness.link.launch_count(), 1); + assert!(harness.link.server(0).input_was_closed()); + assert!(harness.sessions().is_empty()); +} + +fn write_session_file(harness: &Harness, now: i64) -> PathBuf { + let directory = harness + .dir + .path() + .join("home") + .join(".sample") + .join("sessions") + .join("project"); + fs::create_dir_all(&directory).unwrap(); + let path = directory.join("s1.jsonl"); + 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": "limits", "at": now, "used": 40.0 }), + ]; + let text: String = lines.iter().map(|line| format!("{line}\n")).collect(); + fs::write(&path, text).unwrap(); + path +} + +#[test] +fn records_sync_list_search_read_and_sum_through_the_plugin() { + let harness = Harness::new("records", ALL_GRANTS); + let now = crate::now_ms(); + let file = write_session_file(&harness, now); + + let report = harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + assert_eq!(report["filesRead"], 1, "{report}"); + assert_eq!(report["filesFailed"], 0, "{report}"); + let scans = harness.link.calls_of("sessions.scan"); + assert_eq!(scans.len(), 1); + assert_eq!(scans[0]["agentID"], AGENT); + assert_eq!(scans[0]["sourceID"], "projects"); + assert_eq!(scans[0]["path"], path_text(&file)); + assert_eq!(scans[0]["lines"].as_array().map(Vec::len), Some(4)); + assert_eq!(scans[0]["lines"][0]["offset"], 0); + let again = harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + assert_eq!(again["filesUnchanged"], 1, "{again}"); + + let sessions = harness.run("agentSessions.list", json!({ "titles": true }))["sessions"].clone(); + assert_eq!(sessions.as_array().map(Vec::len), Some(1), "{sessions}"); + assert_eq!(sessions[0]["sessionId"], "s1"); + assert_eq!(sessions[0]["pluginID"], PLUGIN); + assert_eq!(sessions[0]["agentID"], AGENT); + assert_eq!(sessions[0]["cwd"], "/work/project"); + assert_eq!(sessions[0]["title"], "hello from the user"); + let reads = harness.link.calls_of("sessions.read"); + assert_eq!(reads[0]["mode"], "titles"); + + let hits = harness.run("agentSessions.search", json!({ "text": "hello" }))["hits"].clone(); + assert_eq!(hits.as_array().map(Vec::len), Some(1), "{hits}"); + assert_eq!(hits[0]["sessionId"], "s1"); + let read = harness.run( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": hits[0]["path"], "range": hits[0]["range"] }), + ); + assert_eq!( + read, + json!({ "changed": false, "messages": [{ "role": "user", "text": "hello from the user" }] }) + ); + assert_eq!( + harness.refused( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": "/etc/hosts", "range": { "start": 0, "end": 1 } }), + ), + "agentSessions.outsideSources" + ); + + 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}"); + assert_eq!( + stats["rateLimits"][0]["windows"][0]["usedPercent"], 40.0, + "{stats}" + ); + assert_eq!(stats["rateLimits"][0]["plan"], "pro"); + + // A plugin granted agents.usage.read sees totals, never what the + // sessions hold. + let usage = harness + .answer(AGENTS_USAGE, json!({ "groupBy": "agent" })) + .expect("usage"); + assert_eq!(usage["summaries"][0]["calls"], 1, "{usage}"); + let text = usage.to_string(); + for private in ["\"s1\"", "/work/project", "hello", "s1.jsonl"] { + assert!(!text.contains(private), "usage carries {private}: {text}"); + } + let refusal = harness + .answer(AGENTS_USAGE, json!({ "groupBy": "session" })) + .expect_err("plugins cannot sum by session"); + assert_eq!(refusal.code, codes::HOST_INVALID_PARAMS); + + assert_eq!( + harness.run( + "agentSessions.forget", + json!({ "pluginID": PLUGIN, "agentID": AGENT }) + ), + json!({ "files": 1 }) + ); + assert_eq!( + harness.run("agentSessions.list", json!({}))["sessions"], + json!([]) + ); +} + +#[test] +fn rate_limits_survive_a_restart() { + let dir; + { + let harness = Harness::new("rates", ALL_GRANTS); + write_session_file(&harness, crate::now_ms()); + harness.run( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }), + ); + dir = harness.dir.path().join("cache"); + let restarted = Runtime::new(FakeLink::new()); + restarted + .execute( + "agents.configure", + json!({ "plugins": [{ "manifest": manifest(), "grantedPermissions": ALL_GRANTS }] }), + ) + .unwrap(); + restarted + .execute( + "agentSessions.configure", + json!({ + "cacheDirectory": path_text(&dir), + "userHome": path_text(&harness.dir.path().join("home")), + }), + ) + .unwrap(); + let stats = restarted + .execute("agentSessions.stats", json!({ "groupBy": "day" })) + .unwrap(); + assert_eq!(stats["rateLimits"][0]["windows"][0]["id"], "5h", "{stats}"); + } + assert!(!dir.exists()); +} + +#[test] +fn records_stay_closed_without_the_read_grant() { + let harness = Harness::new( + "no-read", + &["agents.native", "agents.run", "backend.launch"], + ); + write_session_file(&harness, crate::now_ms()); + assert_eq!( + harness.refused( + "agentSessions.sync", + json!({ "pluginID": PLUGIN, "agentID": AGENT }) + ), + "agentSessions.readNotGranted" + ); + assert_eq!( + harness.run("agentSessions.list", json!({}))["sessions"], + json!([]) + ); + assert_eq!( + harness.run("agentSessions.search", json!({ "text": "hello" }))["hits"], + json!([]) + ); + assert_eq!( + harness.run("agentSessions.stats", json!({ "groupBy": "day" }))["summaries"], + json!([]) + ); + assert_eq!( + harness + .answer(AGENTS_USAGE, json!({ "groupBy": "day" })) + .expect("usage")["summaries"], + json!([]) + ); + assert_eq!( + harness.refused( + "agentSessions.read", + json!({ "agent": AGENT_KEY, "path": "/tmp/x", "range": { "start": 0, "end": 1 } }), + ), + "agentSessions.readNotGranted" + ); + assert!(harness.link.calls_of("sessions.scan").is_empty()); +} + +#[test] +fn wait_events_says_when_events_were_dropped() { + let harness = Harness::new("missed", ALL_GRANTS); + for _ in 0..8200 { + harness + .runtime + .live + .queue + .push("agent-0", json!({ "kind": "notice" })); + } + let batch = harness.run("agents.waitEvents", json!({ "after": 0, "limit": 10 })); + assert_eq!(batch["missed"], true); + assert_eq!(batch["events"].as_array().map(Vec::len), Some(10)); + let next = batch["next"].as_u64().unwrap(); + let batch = harness.run("agents.waitEvents", json!({ "after": next, "limit": 10 })); + assert_eq!(batch["missed"], false); + let caught_up = harness.run( + "agents.waitEvents", + json!({ "after": 8200, "timeoutMilliseconds": 0 }), + ); + assert_eq!(caught_up["events"], json!([])); + assert_eq!(caught_up["next"], 8200); +} + +#[test] +fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { + assert_eq!( + crate::records::chunk_lines_for_test(10, b"a\r\nbb\nccc"), + [ + json!({ "offset": 10, "length": 3, "text": "a" }), + json!({ "offset": 13, "length": 3, "text": "bb" }), + json!({ "offset": 16, "length": 3, "text": "ccc" }), + ] + ); + assert_eq!(crate::records::text_lines_for_test(b"a\r\nb\n"), ["a", "b"]); + assert!(crate::records::text_lines_for_test(b"").is_empty()); +} diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index e7252238..1da75087 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -6,6 +6,107 @@ use super::{EventMetadata, FieldMetadata, FieldType, LogLevel, SpanPhase}; /// Sorted, immutable metadata for every expanded catalog event. #[rustfmt::skip] pub static EVENTS: &[EventMetadata] = &[ + EventMetadata { + id: "agent.records.removed", + channel: "agent", + level: LogLevel::Info, + message: "Agent session records removed from the cache", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "files", field_type: FieldType::Int, required: true, description: "Session files whose records were dropped", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.records.sync_failed", + channel: "agent", + level: LogLevel::Warn, + message: "Agent session records could not be synchronized", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable failure code; excludes paths and session content", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.records.updated", + channel: "agent", + level: LogLevel::Info, + message: "Agent session records synchronized", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the sync took", reason: None }, + FieldMetadata { name: "files_failed", field_type: FieldType::Int, required: true, description: "Session files that could not be read or parsed", reason: None }, + FieldMetadata { name: "files_read", field_type: FieldType::Int, required: true, description: "Session files read in this sync", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.report.rejected", + channel: "agent", + level: LogLevel::Warn, + message: "Agent plugin reported an invalid session event", + fields: &[ + FieldMetadata { name: "code", field_type: FieldType::Token, required: true, description: "Stable rejection code; the event content is never logged", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity of the reporting backend", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.session.finished", + channel: "agent", + level: LogLevel::Info, + message: "Agent session ended", + fields: &[ + FieldMetadata { name: "duration", field_type: FieldType::Duration, required: true, description: "Milliseconds the session ran", reason: None }, + FieldMetadata { name: "exit_code", field_type: FieldType::Int, required: false, description: "Exit code of the agent CLI; absent when a signal ended it", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Why the session ended: exited, closed, backendEnded or failed", reason: None }, + FieldMetadata { name: "session", field_type: FieldType::Id, required: true, description: "Opaque session ID Core assigned", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.session.start_failed", + channel: "agent", + level: LogLevel::Warn, + message: "Agent session could not start", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Stable refusal or failure code; excludes paths, arguments and CLI output", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, + EventMetadata { + id: "agent.session.started", + channel: "agent", + level: LogLevel::Info, + message: "Agent session started", + fields: &[ + FieldMetadata { name: "agent", field_type: FieldType::Id, required: true, description: "Agent ID the plugin declares", reason: None }, + FieldMetadata { name: "mode", field_type: FieldType::Token, required: true, description: "Connection mode Core selected, e.g. native", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity that declares the agent", reason: None }, + FieldMetadata { name: "session", field_type: FieldType::Id, required: true, description: "Opaque session ID Core assigned; never the agent CLI's own session ID", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "app.action.performed", channel: "app", diff --git a/rust/crates/lsp-client/src/client/server_messages.rs b/rust/crates/lsp-client/src/client/server_messages.rs index fe8e4865..20a7271b 100644 --- a/rust/crates/lsp-client/src/client/server_messages.rs +++ b/rust/crates/lsp-client/src/client/server_messages.rs @@ -325,6 +325,21 @@ pub fn client_apply_server_message_for_plugin( })), error: None, }), + // An agent-session method: Core's agent runtime answers it, + // so like a relayed call it never reaches the host. + Ok(lithe_plugin_rpc::HostRoute::Agents) => events.push(LspClientEvent { + kind: crate::AGENT_HOST_REQUEST_EVENT.to_string(), + request_id: None, + method: Some(method.to_string()), + uri: None, + version: None, + diagnostics: None, + result: Some(json!({ + "id": id, + "params": message.get("params").cloned().unwrap_or(Value::Null), + })), + error: None, + }), Err(refusal) => { let mut data = json!({ "code": refusal.code }); if let Some(details) = refusal.details { diff --git a/rust/crates/lsp-client/src/lib.rs b/rust/crates/lsp-client/src/lib.rs index 8e99a46f..a1b9e49f 100644 --- a/rust/crates/lsp-client/src/lib.rs +++ b/rust/crates/lsp-client/src/lib.rs @@ -19,5 +19,9 @@ pub use client::*; use lithe_plugin_model::capabilities::offered_versions; pub use types::*; +/// Event kind of a backend's `lithe/host/agents/*` request (plan API-45), +/// which the engine hands to Core's agent runtime instead of the host. +pub const AGENT_HOST_REQUEST_EVENT: &str = "agentHostRequest"; + #[cfg(test)] mod tests; diff --git a/rust/crates/lsp-engine/src/agent_host.rs b/rust/crates/lsp-engine/src/agent_host.rs new file mode 100644 index 00000000..ba958a05 --- /dev/null +++ b/rust/crates/lsp-engine/src/agent_host.rs @@ -0,0 +1,335 @@ +//! Engine side of agent sessions (plan API-45). +//! +//! Core's agent runtime owns the agent CLI processes; the plugin backend only +//! translates between the CLI's own protocol and Lithe's session events. Three +//! paths connect the two, and each stays inside Core: +//! +//! - A backend's `lithe/host/agents/*` requests reach the installed +//! [`AgentHost`], which checks that the session is the backend's own and +//! answers. The host application never sees them. +//! - The runtime sends the backend the agent-session notifications with +//! [`notify_agent_backend`]. The host may not send them. +//! - The runtime calls the backend's launch and session-file functions with +//! [`call_agent_function`], a blocking call whose answer never becomes a host +//! event. +//! +//! The runtime's threads call into the engine with no lock of their own held, +//! and the engine calls the [`AgentHost`] while it holds the backend's session +//! lock, so an `AgentHost` must never call back into the engine from +//! [`AgentHost::answer`] or [`AgentHost::backend_ended`]. + +use super::{ + engine, json_rpc_error_with_data, json_rpc_notification, json_rpc_result, LspLifecycleState, + LspRuntimeError, PluginFunctionRequest, RuntimeSession, +}; +use lithe_plugin_rpc::{codes, host_rpc_code, FunctionReference, AGENTS_WRITE, INVOKE_METHOD}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc, Mutex, PoisonError, RwLock}; +use std::time::Duration; + +/// Operation IDs of the calls the agent runtime makes. The host may not use +/// them, so a host event never answers one of these calls. +pub const AGENT_OPERATION_PREFIX: &str = "agent-call:"; + +/// Time a call may still take after its own deadline before the caller stops +/// waiting: the session monitor ends an overdue call itself, so this only +/// guards against an answer that is lost. +const CALL_GRACE: Duration = Duration::from_secs(5); + +/// The backend that sent a `lithe/host/agents/*` request. +#[derive(Debug, Clone, Copy)] +pub struct AgentBackend<'a> { + /// The engine session of the backend process. + pub session_id: &'a str, + /// The plugin that owns the backend. + pub plugin_id: &'a str, +} + +/// Why the agent runtime refused a backend request. `code` is a stable +/// `plugin.host.*` or `plugin.agents.*` code, sent as `error.data.code`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AgentHostFailure { + pub code: String, + pub message: String, +} + +impl AgentHostFailure { + pub fn new(code: impl Into, message: impl Into) -> Self { + Self { + code: code.into(), + message: message.into(), + } + } +} + +/// The agent runtime as the engine reaches it. +pub trait AgentHost: Send + Sync { + /// Answers one `lithe/host/agents/*` request of a backend. Called with the + /// backend's session lock held: it must not block on the backend or call + /// into the engine. + fn answer( + &self, + backend: AgentBackend<'_>, + method: &str, + params: &Value, + ) -> Result; + + /// The backend session is stopping or has stopped; the agent sessions it + /// translated end. Called with the session lock held, like `answer`. + fn backend_ended(&self, session_id: &str); +} + +static AGENT_HOST: RwLock>> = RwLock::new(None); + +/// Installs the agent runtime. A later call replaces it. +pub fn install_agent_host(host: Arc) { + *AGENT_HOST.write().unwrap_or_else(PoisonError::into_inner) = Some(host); +} + +fn agent_host() -> Option> { + AGENT_HOST + .read() + .unwrap_or_else(PoisonError::into_inner) + .clone() +} + +/// Answers a backend's `lithe/host/agents/*` request. Returns the message to +/// write to that backend. +pub(crate) fn answer_request( + session: &RuntimeSession, + method: &str, + request: &Value, +) -> Result, CoreError> { + let rpc_id = request.get("id").cloned().unwrap_or(Value::Null); + let params = request.get("params").unwrap_or(&Value::Null); + let outcome = match (agent_host(), session.plugin_id.as_deref()) { + (Some(host), Some(plugin_id)) => host.answer( + AgentBackend { + session_id: &session.id, + plugin_id, + }, + method, + params, + ), + _ => Err(AgentHostFailure::new( + codes::HOST_UNAVAILABLE, + "This Lithe build does not run agent sessions.", + )), + }; + let message = match outcome { + Ok(result) => json_rpc_result(&rpc_id, result)?, + Err(failure) => json_rpc_error_with_data( + &rpc_id, + host_rpc_code(&failure.code), + &lithe_plugin_rpc::bounded_host_message(&failure.message), + json!({ "code": failure.code }), + )?, + }; + Ok(vec![message]) +} + +/// Tells the agent runtime that a backend is ending. +pub(crate) fn observe_lifecycle(session: &RuntimeSession, lifecycle: LspLifecycleState) { + if !matches!( + lifecycle, + LspLifecycleState::Stopping | LspLifecycleState::Stopped | LspLifecycleState::Failed + ) || session.plugin_id.is_none() + { + return; + } + if let Some(host) = agent_host() { + host.backend_ended(&session.id); + } +} + +/// The ready backend session of `plugin_id` that serves `function_id`, if one +/// runs. A session of the same workspace root is preferred when `root_uri` +/// names one. +pub fn agent_backend_session( + plugin_id: &str, + function_id: &str, + root_uri: Option<&str>, +) -> Option { + let candidates: Vec> = { + let sessions = engine() + .sessions + .lock() + .unwrap_or_else(PoisonError::into_inner); + sessions + .values() + .filter(|session| { + session.function_relay_enabled && session.plugin_id.as_deref() == Some(plugin_id) + }) + .cloned() + .collect() + }; + let serving: Vec<_> = candidates + .into_iter() + .filter(|session| session.serves_function(function_id)) + .collect(); + serving + .iter() + .find(|session| Some(session.root_uri.as_str()) == root_uri) + .or_else(|| serving.first()) + .map(|session| session.id.clone()) +} + +/// Sends one agent-session notification to a backend that holds the agents +/// grant. The write is bounded like a relayed call's: a backend that stops +/// reading its input fails and its process is killed. +pub fn notify_agent_backend( + session_id: &str, + method: &str, + params: Value, +) -> Result<(), CoreError> { + if !lithe_plugin_rpc::is_agent_notification(method) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "This is not an agent-session notification.", + )); + } + let session = engine().session(session_id)?; + session.bounded_relay_write(|| session.agent_notify(method, params)) +} + +impl RuntimeSession { + fn agent_notify(&self, method: &str, params: Value) -> Result<(), CoreError> { + let outbound_order = self.lock_outbound_order()?; + let message = { + let state = self.lock_state()?; + if self.plugin_id.is_none() + || state.lifecycle != LspLifecycleState::Ready + || !state.client.initialized + || state.client.plugin_function_version.is_none() + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The agent plugin's backend is not ready.", + )); + } + if !state.client.host_services.contains(AGENTS_WRITE) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "The plugin backend was not granted agent sessions.", + )); + } + json_rpc_notification(method, params)? + }; + self.send_messages_or_fail(&outbound_order, vec![message], "agentNotify") + } +} + +/// How a call the agent runtime made ended without a result. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AgentCallFailure { + /// A `plugin.function.*` code, or the engine's code when the call could + /// not be sent. + pub code: String, + pub message: String, + /// The plugin's own error code, when the function returned one. + pub plugin_error_code: Option, +} + +type Waiters = Mutex>>>; + +static WAITERS: Waiters = Mutex::new(BTreeMap::new()); +static NEXT_CALL: AtomicU64 = AtomicU64::new(1); + +/// Calls one function of a backend and waits for its answer. `timeout` is the +/// call's deadline; the session ends an overdue call with +/// `plugin.function.timeout`. +pub fn call_agent_function( + session_id: &str, + plugin_id: &str, + function_id: &str, + params: Value, + context: Option, + timeout: Duration, +) -> Result { + let operation_id = format!( + "{AGENT_OPERATION_PREFIX}{}", + NEXT_CALL.fetch_add(1, Ordering::Relaxed) + ); + let (sender, receiver) = mpsc::channel(); + lock_waiters().insert(operation_id.clone(), sender); + let request = PluginFunctionRequest { + session_id: session_id.to_string(), + operation_id: Some(operation_id.clone()), + function: FunctionReference { + plugin_id: plugin_id.to_string(), + function_id: function_id.to_string(), + }, + params, + timeout_milliseconds: Some(u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX)), + context, + }; + let sent = engine() + .session(session_id) + .and_then(|session| session.function_request(request, operation_id.clone(), None)); + if let Err(error) = sent { + lock_waiters().remove(&operation_id); + return Err(AgentCallFailure { + code: error + .details + .clone() + .unwrap_or_else(|| codes::UNAVAILABLE.to_string()), + message: error.message, + plugin_error_code: None, + }); + } + match receiver.recv_timeout(timeout + CALL_GRACE) { + Ok(outcome) => outcome, + Err(_) => { + lock_waiters().remove(&operation_id); + if let Ok(session) = engine().session(session_id) { + let _ = session.cancel_operation(&operation_id); + } + Err(AgentCallFailure { + code: "requestTimeout".to_string(), + message: "The agent plugin did not answer in time.".to_string(), + plugin_error_code: None, + }) + } + } +} + +/// Whether the host may not use this operation ID. +pub(crate) fn is_agent_operation_id(operation_id: &str) -> bool { + operation_id.starts_with(AGENT_OPERATION_PREFIX) +} + +/// Hands the end of an agent call to its caller. Returns `false` when the +/// operation is not one; the event then goes on as usual. +pub(crate) fn finish_call( + operation_id: &str, + method: &str, + result: Option, + error: Option, +) -> bool { + if method != INVOKE_METHOD || !is_agent_operation_id(operation_id) { + return false; + } + let outcome = match error { + Some(error) => Err(AgentCallFailure { + code: error.code, + message: error.message, + plugin_error_code: error.plugin_error_code, + }), + None => Ok(result + .and_then(|wrapped| wrapped.get("value").cloned()) + .unwrap_or(Value::Null)), + }; + if let Some(waiter) = lock_waiters().remove(operation_id) { + let _ = waiter.send(outcome); + } + true +} + +fn lock_waiters( +) -> std::sync::MutexGuard<'static, BTreeMap>>> +{ + WAITERS.lock().unwrap_or_else(PoisonError::into_inner) +} diff --git a/rust/crates/lsp-engine/src/events.rs b/rust/crates/lsp-engine/src/events.rs index 1af22a30..dee24b34 100644 --- a/rust/crates/lsp-engine/src/events.rs +++ b/rust/crates/lsp-engine/src/events.rs @@ -75,6 +75,11 @@ pub(crate) fn push_request_event( ); return; } + // A call of Core's agent runtime: its caller waits for it, not the host. + if agent_host::is_agent_operation_id(operation_id) { + agent_host::finish_call(operation_id, method, result, error); + return; + } enqueue_request_completed(session, state, operation_id, method, result, error); } diff --git a/rust/crates/lsp-engine/src/lib.rs b/rust/crates/lsp-engine/src/lib.rs index f2ebfb8e..57db4ac5 100644 --- a/rust/crates/lsp-engine/src/lib.rs +++ b/rust/crates/lsp-engine/src/lib.rs @@ -69,6 +69,7 @@ static ENGINE: OnceLock = OnceLock::new(); mod relay_hub; use relay_hub::RelayHub; +pub mod agent_host; mod function_provider; pub use function_provider::function_provider_command; @@ -278,12 +279,24 @@ pub fn plugin_function_request( .operation_id .clone() .unwrap_or_else(|| engine().next_operation_id()); + refuse_agent_operation(&operation_id)?; engine() .session(&request.session_id)? .function_request(request, operation_id.clone(), None)?; Ok(OperationResponse { operation_id }) } +/// The host may not start or cancel a call of Core's agent runtime. +fn refuse_agent_operation(operation_id: &str) -> Result<(), CoreError> { + if agent_host::is_agent_operation_id(operation_id) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "This language-server operation ID is reserved for agent sessions.", + )); + } + Ok(()) +} + /// Sends one request of a plugin backend to the plugin's own language server. pub fn plugin_server_request(request: PluginServerRequest) -> Result { let operation_id = request @@ -317,6 +330,7 @@ pub fn configure_function_relay( /// Cancels a pending semantic request in both client state and the server. pub fn cancel_operation(request: CancelOperationRequest) -> Result<(), CoreError> { + refuse_agent_operation(&request.operation_id)?; engine() .session(&request.session_id)? .cancel_operation(&request.operation_id) diff --git a/rust/crates/lsp-engine/src/lifecycle.rs b/rust/crates/lsp-engine/src/lifecycle.rs index 17da34a0..ec57a4b9 100644 --- a/rust/crates/lsp-engine/src/lifecycle.rs +++ b/rust/crates/lsp-engine/src/lifecycle.rs @@ -802,6 +802,7 @@ pub(crate) fn transition_locked( ) { state.lifecycle = lifecycle; relay_hub::observe_lifecycle(session, lifecycle); + agent_host::observe_lifecycle(session, lifecycle); let (id, fields) = EngineLog::SessionUpdated.fact( &session.log_identity, &json!({"state": lifecycle}), diff --git a/rust/crates/lsp-engine/src/relay_hub.rs b/rust/crates/lsp-engine/src/relay_hub.rs index ca1e30bb..e24bcac8 100644 --- a/rust/crates/lsp-engine/src/relay_hub.rs +++ b/rust/crates/lsp-engine/src/relay_hub.rs @@ -666,7 +666,7 @@ impl RuntimeSession { /// process when the write is still running after the session's request /// timeout, which releases a write blocked on a backend that stopped /// reading its stdin. `write` runs with no session lock held. - fn bounded_relay_write(&self, write: impl FnOnce() -> T) -> T { + pub(super) fn bounded_relay_write(&self, write: impl FnOnce() -> T) -> T { if let Ok(mut state) = self.lock_state() { state.relay_write_deadline = Some(Instant::now() + state.request_timeout); } diff --git a/rust/crates/lsp-engine/src/server_messages.rs b/rust/crates/lsp-engine/src/server_messages.rs index c3d9f297..433fc3a5 100644 --- a/rust/crates/lsp-engine/src/server_messages.rs +++ b/rust/crates/lsp-engine/src/server_messages.rs @@ -408,6 +408,12 @@ impl RuntimeSession { event.method.as_deref().unwrap_or_default(), &event.result.unwrap_or_default(), )?); + } else if event.kind == lithe_lsp_client::AGENT_HOST_REQUEST_EVENT { + outbound.extend(agent_host::answer_request( + self, + event.method.as_deref().unwrap_or_default(), + &event.result.unwrap_or_default(), + )?); } else if event.kind == "functionProgress" { push_function_progress_locked(self, &mut state, event.result); } else if event.kind == "buildProgress" { diff --git a/rust/crates/lsp-transport/src/scripted.rs b/rust/crates/lsp-transport/src/scripted.rs index 09993968..cf652d57 100644 --- a/rust/crates/lsp-transport/src/scripted.rs +++ b/rust/crates/lsp-transport/src/scripted.rs @@ -193,6 +193,28 @@ impl ScriptedServer { }) } + /// Blocks until the raw bytes written so far satisfy `done`, for + /// processes that are not framed as JSON-RPC, such as line-based CLIs. + pub fn await_written_bytes(&self, done: impl Fn(&[u8]) -> bool) -> bool { + let deadline = Instant::now() + Duration::from_secs(5); + let mut written = self.shared.written.lock().unwrap(); + loop { + if done(&written) { + return true; + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return false; + } + written = self + .shared + .written_changed + .wait_timeout(written, remaining) + .unwrap() + .0; + } + } + fn await_written_message(&self, find: impl Fn(&[Value]) -> Option) -> Option { let deadline = Instant::now() + Duration::from_secs(5); let mut written = self.shared.written.lock().unwrap(); diff --git a/rust/crates/plugin-agents/Cargo.toml b/rust/crates/plugin-agents/Cargo.toml new file mode 100644 index 00000000..6f153554 --- /dev/null +++ b/rust/crates/plugin-agents/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "lithe-plugin-agents" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "agents[] of a plugin manifest (plan API-45): the agent CLIs a plugin drives, how Core starts them, and where their local session files are" + +[dependencies] +globset = "0.4" +lithe-plugin-model = { path = "../plugin-model" } +serde = { version = "1.0", features = ["derive"] } +serde_json = { version = "1.0", features = ["preserve_order"] } diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs new file mode 100644 index 00000000..0f15fca5 --- /dev/null +++ b/rust/crates/plugin-agents/src/lib.rs @@ -0,0 +1,635 @@ +//! `agents[]` of a plugin manifest (plan API-45): the agent command-line +//! tools a plugin drives, how Core starts them, and where they keep their +//! local session files. +//! +//! Core knows no agent. Everything agent-specific comes from the plugin: +//! +//! - `tool` names one of the plugin's required tools. The host discovers it +//! and probes its version like any other tool, so the command is always the +//! official CLI the user installed, never a path the plugin chose. +//! - `native.function` is a backend function that answers the command line +//! of a native session. The answer can only run `tool` and carries no +//! environment, so a plugin cannot redirect the CLI's model traffic. +//! - `acp.arguments` runs `tool` as an Agent Client Protocol server, and +//! `terminal.arguments` runs its interactive interface in a terminal. +//! - `update.arguments` runs `tool` to update itself, after the user +//! confirms. +//! - `sessionSources` names the directories of the CLI's session files and +//! the backend functions that parse and display them. Core reads the files +//! only after the user consents, per agent. +//! +//! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md + +use globset::Glob; +use lithe_plugin_model::{ + invalid, is_environment_name, is_function_id, is_identifier, PluginRejection, UIIcon, + Validation, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +/// Most agents one plugin declares. +pub const MAX_AGENTS: usize = 8; + +/// Most session sources one agent declares. +pub const MAX_SESSION_SOURCES: usize = 4; + +/// Most root candidates of one session source. +const MAX_ROOTS: usize = 4; + +/// Most include patterns of one session source. +const MAX_INCLUDES: usize = 16; + +/// Longest agent or session-source ID, in bytes. +const MAX_ID_BYTES: usize = 64; + +/// Longest display name, in characters. +const MAX_DISPLAY_NAME_CHARS: usize = 64; + +/// Most fixed arguments of `acp`, `terminal` or `update`. +const MAX_DECLARED_ARGUMENTS: usize = 64; + +/// Longest fixed argument, in bytes. +const MAX_DECLARED_ARGUMENT_BYTES: usize = 4096; + +/// Most arguments a launch function may answer. +pub const MAX_LAUNCH_ARGUMENTS: usize = 1024; + +/// Longest argument a launch function may answer, in bytes. +pub const MAX_LAUNCH_ARGUMENT_BYTES: usize = 32 * 1024; + +/// Default and bounds of `native.timeoutMilliseconds`. +pub const DEFAULT_LAUNCH_TIMEOUT_MILLISECONDS: u64 = 15_000; +const MIN_LAUNCH_TIMEOUT_MILLISECONDS: u64 = 1_000; +const MAX_LAUNCH_TIMEOUT_MILLISECONDS: u64 = 120_000; + +/// Prefix of the activation event of one agent, `onAgent:`. +pub const ON_AGENT_PREFIX: &str = "onAgent:"; + +/// Manifest permission of `agents[]`: Core may run each agent's tool in the +/// forms it declares, after the user starts a session. +pub const PERMISSION_AGENTS_RUN: &str = "agents.run"; + +/// Manifest permission of `sessionSources`: after the user consents per +/// agent, Core reads the listed session files and the backend parses them. +pub const PERMISSION_AGENTS_SESSIONS: &str = "agents.sessions.read"; + +/// Template variable of the user's home directory in a session root. +const USER_HOME_VARIABLE: &str = "${userHome}"; + +/// One agent a plugin drives. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AgentDeclaration { + pub id: String, + pub display_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + /// One of the plugin's `requiresTools`: the only executable any form of + /// this agent runs. + pub tool: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub native: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub acp: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub terminal: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub update: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub session_sources: Vec, +} + +/// The backend function that answers a native session's command line. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeDeclaration { + pub function: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout_milliseconds: Option, +} + +impl NativeDeclaration { + /// How long Core waits for the launch function. + pub fn timeout_milliseconds(&self) -> u64 { + self.timeout_milliseconds + .unwrap_or(DEFAULT_LAUNCH_TIMEOUT_MILLISECONDS) + } +} + +/// Fixed arguments Core passes to the agent's tool. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ArgumentsDeclaration { + pub arguments: Vec, +} + +/// How the user updates the agent's CLI: arguments for its own tool, such +/// as `update`. A CLI without a self-update command declares none. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UpdateDeclaration { + pub arguments: Vec, +} + +/// The format of a session source's files. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum SessionFormat { + /// One JSON value per line. + JsonLines, +} + +/// One directory of an agent's session files. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SessionSourceDeclaration { + pub id: String, + /// Root candidates. The first one whose variables all resolve is used. + pub roots: Vec, + /// Root-relative glob patterns of the files to read. + pub include: Vec, + pub format: SessionFormat, + /// Backend function that parses new lines of one file. + pub scan: String, + /// Backend function that turns a byte range of one file into messages. + pub read: String, +} + +/// What the rest of the manifest offers the agents. +pub struct DeclarationContext<'a> { + /// The plugin's `requiresTools`. + pub required_tools: &'a BTreeSet, + /// Whether the plugin declares a backend, the only process that serves + /// launch, scan and read functions. + pub has_backend: bool, +} + +impl AgentDeclaration { + /// Whether Core starts the backend for this agent: a native session or a + /// session source is served by backend functions. A terminal or ACP agent + /// alone runs only its tool. + pub fn needs_backend(&self) -> bool { + self.native.is_some() || !self.session_sources.is_empty() + } +} + +/// The activation event that starts the backend for `agent`, declared by +/// every agent that [needs the backend](AgentDeclaration::needs_backend). +pub fn activation_event(agent: &AgentDeclaration) -> String { + format!("{ON_AGENT_PREFIX}{}", agent.id) +} + +/// Whether any agent needs the backend. +pub fn uses_backend(agents: &[AgentDeclaration]) -> bool { + agents.iter().any(AgentDeclaration::needs_backend) +} + +/// Whether any agent has a native session, which needs `agents.native`. +pub fn has_native(agents: &[AgentDeclaration]) -> bool { + agents.iter().any(|agent| agent.native.is_some()) +} + +/// Checks the section and sorts it by agent ID. +pub fn validate_declarations( + agents: &mut [AgentDeclaration], + context: &DeclarationContext<'_>, +) -> Validation<()> { + if agents.len() > MAX_AGENTS { + return Err(invalid( + "agents", + format!("A plugin declares at most {MAX_AGENTS} agents."), + )); + } + let mut ids = BTreeSet::new(); + for (index, agent) in agents.iter().enumerate() { + let field = format!("agents[{index}]"); + if !is_short_id(&agent.id) { + return Err(invalid( + format!("{field}.id"), + "An agent ID uses lowercase letters, digits and hyphens.", + )); + } + if !ids.insert(agent.id.as_str()) { + return Err(invalid( + format!("{field}.id"), + "An agent is declared more than once.", + )); + } + check_display_name(&agent.display_name, &format!("{field}.displayName"))?; + if let Some(icon) = &agent.icon { + icon.validate_at(&format!("{field}.icon"))?; + } + if !context.required_tools.contains(&agent.tool) { + return Err(invalid( + format!("{field}.tool"), + "An agent's tool must be one of the plugin's requiresTools.", + )); + } + if agent.native.is_none() && agent.acp.is_none() && agent.terminal.is_none() { + return Err(invalid( + field.clone(), + "An agent declares at least one of native, acp and terminal.", + )); + } + if let Some(native) = &agent.native { + if !is_function_id(&native.function) { + return Err(invalid( + format!("{field}.native.function"), + "A launch function ID is dot-separated lowerCamelCase segments.", + )); + } + if let Some(timeout) = native.timeout_milliseconds { + if !(MIN_LAUNCH_TIMEOUT_MILLISECONDS..=MAX_LAUNCH_TIMEOUT_MILLISECONDS) + .contains(&timeout) + { + return Err(invalid( + format!("{field}.native.timeoutMilliseconds"), + "A launch timeout is between 1000 and 120000 milliseconds.", + )); + } + } + } + if let Some(acp) = &agent.acp { + check_arguments(&acp.arguments, &format!("{field}.acp.arguments"))?; + } + if let Some(terminal) = &agent.terminal { + check_arguments(&terminal.arguments, &format!("{field}.terminal.arguments"))?; + } + if let Some(update) = &agent.update { + check_arguments(&update.arguments, &format!("{field}.update.arguments"))?; + if update.arguments.is_empty() { + return Err(invalid( + format!("{field}.update.arguments"), + "An update runs the tool with at least one argument.", + )); + } + } + check_session_sources(&agent.session_sources, &field)?; + if (agent.native.is_some() || !agent.session_sources.is_empty()) && !context.has_backend { + return Err(invalid( + field, + "Native sessions and session sources are served by the plugin backend.", + )); + } + } + agents.sort_by(|left, right| left.id.cmp(&right.id)); + Ok(()) +} + +fn is_short_id(value: &str) -> bool { + value.len() <= MAX_ID_BYTES + && is_identifier(value) + && !value.starts_with('-') + && !value.ends_with('-') +} + +fn check_display_name(name: &str, field: &str) -> Validation<()> { + let trimmed = name.trim(); + if trimmed.is_empty() + || trimmed.len() != name.len() + || name.chars().count() > MAX_DISPLAY_NAME_CHARS + || name.chars().any(char::is_control) + { + return Err(invalid( + field, + "A display name is 1 to 64 characters without surrounding spaces or control characters.", + )); + } + Ok(()) +} + +fn check_arguments(arguments: &[String], field: &str) -> Validation<()> { + if arguments.len() > MAX_DECLARED_ARGUMENTS + || arguments + .iter() + .any(|argument| argument.len() > MAX_DECLARED_ARGUMENT_BYTES || argument.contains('\0')) + { + return Err(invalid( + field, + "At most 64 arguments of at most 4 KiB each, without NUL, are allowed.", + )); + } + Ok(()) +} + +fn check_session_sources( + sources: &[SessionSourceDeclaration], + agent_field: &str, +) -> Validation<()> { + if sources.len() > MAX_SESSION_SOURCES { + return Err(invalid( + format!("{agent_field}.sessionSources"), + format!("An agent declares at most {MAX_SESSION_SOURCES} session sources."), + )); + } + let mut ids = BTreeSet::new(); + for (index, source) in sources.iter().enumerate() { + let field = format!("{agent_field}.sessionSources[{index}]"); + if !is_short_id(&source.id) { + return Err(invalid( + format!("{field}.id"), + "A session source ID uses lowercase letters, digits and hyphens.", + )); + } + if !ids.insert(source.id.as_str()) { + return Err(invalid( + format!("{field}.id"), + "A session source is declared more than once.", + )); + } + if source.roots.is_empty() || source.roots.len() > MAX_ROOTS { + return Err(invalid( + format!("{field}.roots"), + format!("A session source has 1 to {MAX_ROOTS} root candidates."), + )); + } + for (root_index, root) in source.roots.iter().enumerate() { + parse_root(root).ok_or_else(|| { + invalid( + format!("{field}.roots[{root_index}]"), + "A root starts with ${userHome} or ${env:NAME}, followed by relative path segments without `..`.", + ) + })?; + } + if source.include.is_empty() || source.include.len() > MAX_INCLUDES { + return Err(invalid( + format!("{field}.include"), + format!("A session source has 1 to {MAX_INCLUDES} include patterns."), + )); + } + for (pattern_index, pattern) in source.include.iter().enumerate() { + let relative = !pattern.is_empty() + && !pattern.starts_with('/') + && !pattern.contains('\\') + && !pattern.contains('\0') + && !pattern.split('/').any(|segment| segment == ".."); + if !relative || Glob::new(pattern).is_err() { + return Err(invalid( + format!("{field}.include[{pattern_index}]"), + "An include pattern is a root-relative glob without `..`.", + )); + } + } + for (name, function) in [("scan", &source.scan), ("read", &source.read)] { + if !is_function_id(function) { + return Err(invalid( + format!("{field}.{name}"), + "A session function ID is dot-separated lowerCamelCase segments.", + )); + } + } + } + Ok(()) +} + +/// The first part of a root: where it starts. +#[derive(Debug, Clone, PartialEq, Eq)] +enum RootBase { + UserHome, + Environment(String), +} + +/// Splits a root template into its base variable and relative segments. +fn parse_root(root: &str) -> Option<(RootBase, Vec<&str>)> { + let (base, rest) = if let Some(rest) = root.strip_prefix(USER_HOME_VARIABLE) { + (RootBase::UserHome, rest) + } else { + let inner = root.strip_prefix("${env:")?; + let (name, rest) = inner.split_once('}')?; + if !is_environment_name(name) { + return None; + } + (RootBase::Environment(name.to_string()), rest) + }; + if rest.contains('$') || rest.contains('\\') || rest.contains('\0') { + return None; + } + if !rest.is_empty() && !rest.starts_with('/') { + return None; + } + let segments: Vec<&str> = rest + .split('/') + .filter(|segment| !segment.is_empty()) + .collect(); + if segments + .iter() + .any(|segment| *segment == ".." || *segment == ".") + { + return None; + } + Some((base, segments)) +} + +/// The environment variables the session roots of `agent` read, so the host +/// passes only those to [`resolve_root`]. +pub fn root_variables(agent: &AgentDeclaration) -> BTreeSet { + agent + .session_sources + .iter() + .flat_map(|source| source.roots.iter()) + .filter_map(|root| match parse_root(root)?.0 { + RootBase::Environment(name) => Some(name), + RootBase::UserHome => None, + }) + .collect() +} + +/// Resolves the first root candidate whose variable has a value. An +/// environment variable that is unset or empty skips its candidate. `None` +/// when no candidate resolves. +pub fn resolve_root( + roots: &[String], + user_home: &str, + environment: &BTreeMap, +) -> Option { + roots.iter().find_map(|root| { + let (base, segments) = parse_root(root)?; + let mut path = match base { + RootBase::UserHome => PathBuf::from(user_home), + RootBase::Environment(name) => { + let value = environment.get(&name)?.trim(); + if value.is_empty() { + return None; + } + PathBuf::from(value) + } + }; + if !path.is_absolute() { + return None; + } + for segment in segments { + path.push(segment); + } + Some(path) + }) +} + +/// A checked launch answer of a native session: the arguments for the +/// agent's tool. The tool itself is not in the answer's control. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeLaunch { + pub arguments: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LaunchAnswer { + executable: LaunchExecutable, + #[serde(default)] + arguments: Vec, +} + +#[derive(Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +enum LaunchExecutable { + Tool { tool: String }, +} + +/// Checks what a native launch function answered for `agent`. The answer +/// may name only the agent's own tool and carries no environment. +pub fn decode_native_launch(agent: &AgentDeclaration, answer: Value) -> Validation { + if let Some(object) = answer.as_object() { + if object.contains_key("environment") || object.contains_key("env") { + return Err(PluginRejection::new( + "plugin.agents.launchEnvironment", + "An agent launch cannot set environment variables.", + )); + } + } + let answer: LaunchAnswer = serde_json::from_value(answer).map_err(|error| { + PluginRejection::new( + "plugin.agents.invalidLaunch", + format!("The agent launch answer is malformed: {error}"), + ) + })?; + let LaunchExecutable::Tool { tool } = answer.executable; + if tool != agent.tool { + return Err(PluginRejection::new( + "plugin.agents.undeclaredTool", + "An agent launch runs only the agent's own tool.", + )); + } + if answer.arguments.len() > MAX_LAUNCH_ARGUMENTS + || answer + .arguments + .iter() + .any(|argument| argument.len() > MAX_LAUNCH_ARGUMENT_BYTES || argument.contains('\0')) + { + return Err(PluginRejection::new( + "plugin.agents.invalidLaunch", + "At most 1024 arguments of at most 32 KiB each, without NUL, are allowed.", + )); + } + Ok(NativeLaunch { + arguments: answer.arguments, + }) +} + +/// The params Core passes to a native launch function. +pub fn launch_params(agent_id: &str, cwd: &str, resume: Option<&str>) -> Value { + let mut params = json!({ "agentID": agent_id, "cwd": cwd }); + if let Some(resume) = resume { + params["resume"] = json!(resume); + } + params +} + +/// What the host shows of one agent: its forms and how it updates. The +/// session functions stay inside Core. +pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { + let mut entry = json!({ + "pluginID": plugin_id, + "agentID": agent.id, + "displayName": agent.display_name, + "tool": agent.tool, + "modes": modes(agent), + "forms": forms(agent), + "readsSessions": !agent.session_sources.is_empty(), + }); + if let Some(icon) = &agent.icon { + entry["icon"] = json!(icon); + } + if let Some(terminal) = &agent.terminal { + entry["terminalArguments"] = json!(terminal.arguments); + } + if let Some(update) = &agent.update { + entry["update"] = json!(update); + } + let variables = root_variables(agent); + if !variables.is_empty() { + entry["sessionRootVariables"] = json!(variables); + } + entry +} + +/// The programs an agent runs, for the install review: each form with its +/// fixed arguments, the update command, and where its session records are +/// read. A native launch's arguments come from the backend at start, so the +/// entry names the function that decides them. +pub fn programs(agent: &AgentDeclaration) -> Vec { + let entry = |form: &str| { + json!({ + "kind": "agent", + "agentID": agent.id, + "tool": agent.tool, + "form": form, + }) + }; + let mut programs = Vec::new(); + if let Some(native) = &agent.native { + let mut program = entry("native"); + program["launchFunction"] = json!(native.function); + programs.push(program); + } + for (form, arguments) in [ + ("acp", agent.acp.as_ref().map(|acp| &acp.arguments)), + ("terminal", agent.terminal.as_ref().map(|t| &t.arguments)), + ("update", agent.update.as_ref().map(|u| &u.arguments)), + ] { + if let Some(arguments) = arguments { + let mut program = entry(form); + program["arguments"] = json!(arguments); + programs.push(program); + } + } + for source in &agent.session_sources { + programs.push(json!({ + "kind": "agentSessions", + "agentID": agent.id, + "tool": agent.tool, + "source": source.id, + "roots": source.roots, + "include": source.include, + })); + } + programs +} + +/// The connection modes in the order Core prefers them. +fn modes(agent: &AgentDeclaration) -> Vec<&'static str> { + let mut modes = Vec::new(); + if agent.native.is_some() { + modes.push("native"); + } + if agent.acp.is_some() { + modes.push("acp"); + } + modes +} + +fn forms(agent: &AgentDeclaration) -> Vec<&'static str> { + let mut forms = Vec::new(); + if agent.native.is_some() || agent.acp.is_some() { + forms.push("conversation"); + } + if agent.terminal.is_some() { + forms.push("terminal"); + } + forms +} + +#[cfg(test)] +mod tests; diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs new file mode 100644 index 00000000..caced74a --- /dev/null +++ b/rust/crates/plugin-agents/src/tests.rs @@ -0,0 +1,249 @@ +use super::*; +use serde_json::json; + +fn agent(value: Value) -> AgentDeclaration { + serde_json::from_value(value).expect("agent declaration decodes") +} + +fn sample() -> Value { + json!({ + "id": "sample", + "displayName": "Sample Agent", + "tool": "sample-cli", + "native": { "function": "agent.launch" }, + "terminal": { "arguments": [] }, + "update": { "arguments": ["update"] }, + "sessionSources": [{ + "id": "projects", + "roots": ["${env:SAMPLE_HOME}/sessions", "${userHome}/.sample/sessions"], + "include": ["**/*.jsonl"], + "format": "jsonLines", + "scan": "sessions.scan", + "read": "sessions.read" + }] + }) +} + +fn tools() -> BTreeSet { + BTreeSet::from(["sample-cli".to_string()]) +} + +fn check(agents: &mut [AgentDeclaration], has_backend: bool) -> Validation<()> { + let required_tools = tools(); + validate_declarations( + agents, + &DeclarationContext { + required_tools: &required_tools, + has_backend, + }, + ) +} + +fn rejected_field(value: Value, has_backend: bool) -> String { + let error = check(&mut [agent(value)], has_backend).expect_err("declaration is refused"); + assert_eq!(error.code, "plugin.manifest.invalid"); + error.field.expect("rejection names a field") +} + +#[test] +fn accepts_a_complete_agent_and_sorts_by_id() { + let mut second = sample(); + second["id"] = json!("another"); + let mut agents = [agent(sample()), agent(second)]; + check(&mut agents, true).expect("agents validate"); + assert_eq!(agents[0].id, "another"); + assert_eq!(activation_event(&agents[1]), "onAgent:sample"); + assert!(uses_backend(&agents)); + assert!(has_native(&agents)); +} + +#[test] +fn rejects_unknown_fields() { + let mut value = sample(); + value["environment"] = json!({}); + assert!(serde_json::from_value::(value).is_err()); +} + +#[test] +fn tool_must_be_a_required_tool() { + let mut value = sample(); + value["tool"] = json!("other-cli"); + assert_eq!(rejected_field(value, true), "agents[0].tool"); +} + +#[test] +fn an_agent_declares_at_least_one_form() { + let value = json!({ "id": "sample", "displayName": "Sample", "tool": "sample-cli" }); + assert_eq!(rejected_field(value, true), "agents[0]"); +} + +#[test] +fn native_sessions_and_sources_need_a_backend() { + assert_eq!(rejected_field(sample(), false), "agents[0]"); + let terminal_only = json!({ + "id": "sample", + "displayName": "Sample", + "tool": "sample-cli", + "terminal": { "arguments": ["--interactive"] } + }); + check(&mut [agent(terminal_only)], false).expect("terminal agents need no backend"); +} + +#[test] +fn duplicate_ids_are_refused() { + let mut agents = [agent(sample()), agent(sample())]; + let error = check(&mut agents, true).expect_err("duplicate is refused"); + assert_eq!(error.field.as_deref(), Some("agents[1].id")); +} + +#[test] +fn launch_timeout_is_bounded() { + let mut value = sample(); + value["native"]["timeoutMilliseconds"] = json!(500); + assert_eq!( + rejected_field(value, true), + "agents[0].native.timeoutMilliseconds" + ); + let native: NativeDeclaration = + serde_json::from_value(json!({ "function": "agent.launch" })).unwrap(); + assert_eq!( + native.timeout_milliseconds(), + DEFAULT_LAUNCH_TIMEOUT_MILLISECONDS + ); +} + +#[test] +fn update_runs_the_tool_with_arguments() { + let mut empty = sample(); + empty["update"] = json!({ "arguments": [] }); + assert_eq!(rejected_field(empty, true), "agents[0].update.arguments"); + + let mut installer = sample(); + installer["update"] = json!({ "installer": "sample-installer" }); + assert!(serde_json::from_value::(installer).is_err()); +} + +#[test] +fn roots_start_with_a_variable_and_stay_relative() { + for root in [ + "/etc/sessions", + "${userHome}/../other", + "${env:lower}/x", + "${userHome}x", + "${userHome}/${env:HOME}", + "~/sessions", + ] { + let mut value = sample(); + value["sessionSources"][0]["roots"] = json!([root]); + assert_eq!( + rejected_field(value, true), + "agents[0].sessionSources[0].roots[0]", + "{root} is refused" + ); + } +} + +#[test] +fn include_patterns_are_relative_globs() { + for pattern in ["/abs/*.jsonl", "../*.jsonl", "a[", ""] { + let mut value = sample(); + value["sessionSources"][0]["include"] = json!([pattern]); + assert_eq!( + rejected_field(value, true), + "agents[0].sessionSources[0].include[0]", + "{pattern} is refused" + ); + } +} + +#[test] +fn resolves_the_first_root_with_a_value() { + let source = &agent(sample()).session_sources[0]; + let unset = BTreeMap::new(); + assert_eq!( + resolve_root(&source.roots, "/home/user", &unset), + Some(PathBuf::from("/home/user/.sample/sessions")) + ); + let set = BTreeMap::from([("SAMPLE_HOME".to_string(), "/data/sample".to_string())]); + assert_eq!( + resolve_root(&source.roots, "/home/user", &set), + Some(PathBuf::from("/data/sample/sessions")) + ); + let relative = BTreeMap::from([("SAMPLE_HOME".to_string(), "relative".to_string())]); + assert_eq!( + resolve_root(&source.roots, "/home/user", &relative), + Some(PathBuf::from("/home/user/.sample/sessions")) + ); + assert_eq!( + root_variables(&agent(sample())), + BTreeSet::from(["SAMPLE_HOME".to_string()]) + ); +} + +#[test] +fn launch_answer_runs_only_the_agent_tool() { + let declaration = agent(sample()); + let launch = decode_native_launch( + &declaration, + json!({ "executable": { "kind": "tool", "tool": "sample-cli" }, "arguments": ["-p"] }), + ) + .expect("own tool is accepted"); + assert_eq!(launch.arguments, vec!["-p".to_string()]); + + let other = decode_native_launch( + &declaration, + json!({ "executable": { "kind": "tool", "tool": "other" } }), + ) + .expect_err("another tool is refused"); + assert_eq!(other.code, "plugin.agents.undeclaredTool"); + + let packaged = decode_native_launch( + &declaration, + json!({ "executable": { "kind": "packaged", "path": "bin/cli" } }), + ) + .expect_err("packaged executables are refused"); + assert_eq!(packaged.code, "plugin.agents.invalidLaunch"); + + let environment = decode_native_launch( + &declaration, + json!({ + "executable": { "kind": "tool", "tool": "sample-cli" }, + "environment": { "ANTHROPIC_BASE_URL": "http://proxy" } + }), + ) + .expect_err("environment is refused"); + assert_eq!(environment.code, "plugin.agents.launchEnvironment"); + + let oversized = decode_native_launch( + &declaration, + json!({ + "executable": { "kind": "tool", "tool": "sample-cli" }, + "arguments": ["x".repeat(MAX_LAUNCH_ARGUMENT_BYTES + 1)] + }), + ) + .expect_err("oversized argument is refused"); + assert_eq!(oversized.code, "plugin.agents.invalidLaunch"); +} + +#[test] +fn catalog_entry_hides_session_functions() { + let entry = catalog_entry("dev.lithe.test.agents", &agent(sample())); + assert_eq!(entry["modes"], json!(["native"])); + assert_eq!(entry["forms"], json!(["conversation", "terminal"])); + assert_eq!(entry["readsSessions"], json!(true)); + assert_eq!(entry["sessionRootVariables"], json!(["SAMPLE_HOME"])); + assert!(entry.get("sessionSources").is_none()); + assert!(entry.get("native").is_none()); +} + +#[test] +fn launch_params_carry_resume_only_when_given() { + assert_eq!( + launch_params("sample", "/work", None), + json!({ "agentID": "sample", "cwd": "/work" }) + ); + assert_eq!( + launch_params("sample", "/work", Some("abc"))["resume"], + json!("abc") + ); +} diff --git a/rust/crates/plugin-manifest/Cargo.toml b/rust/crates/plugin-manifest/Cargo.toml index 1effaba3..e3bb55ee 100644 --- a/rust/crates/plugin-manifest/Cargo.toml +++ b/rust/crates/plugin-manifest/Cargo.toml @@ -9,6 +9,7 @@ description = "Declarative plugin manifests: validation, normalization and the r lithe-build = { path = "../build" } lithe-debug = { path = "../debug" } lithe-platform = { path = "../platform" } +lithe-plugin-agents = { path = "../plugin-agents" } lithe-plugin-backend = { path = "../plugin-backend" } lithe-plugin-functions = { path = "../plugin-functions" } lithe-plugin-grammar = { path = "../plugin-grammar" } diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index aa906a18..7ae63e2d 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -102,6 +102,9 @@ pub struct DeclarativePluginManifest { /// functions it calls; see `lithe_plugin_functions`. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) plugin_functions: Option, + /// Agent command-line tools the plugin drives; see `lithe_plugin_agents`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) agents: Vec, } /// UI supplied by plugins. The host owns every window shell: docking, title, @@ -388,6 +391,11 @@ impl DeclarativePluginManifest { &self.requires } + /// The agent command-line tools the plugin drives (plan API-45). + pub fn agents(&self) -> &[lithe_plugin_agents::AgentDeclaration] { + &self.agents + } + /// Host services the plugin's backend may request, sorted; empty without /// a backend. Each is granted by one permission. pub(crate) fn backend_host_services(&self) -> Vec<&'static str> { @@ -480,6 +488,9 @@ impl DeclarativePluginManifest { if let Some(runtimes) = &self.managed_runtimes { programs.extend(runtimes.programs()); } + for agent in &self.agents { + programs.extend(lithe_plugin_agents::programs(agent)); + } // Order by kind, then language or tool, then the full serialized // value as a total tie-breaker; duplicates (two servers needing the // same runtime) collapse to one entry. diff --git a/rust/crates/plugin-manifest/src/permissions.rs b/rust/crates/plugin-manifest/src/permissions.rs index a57aa139..5e16a0b0 100644 --- a/rust/crates/plugin-manifest/src/permissions.rs +++ b/rust/crates/plugin-manifest/src/permissions.rs @@ -64,6 +64,8 @@ const PERMISSION_COMMAND_INSTALL: &str = "commands.install"; const PERMISSION_RUNTIME_INSTALL: &str = "runtimes.install"; const KNOWN_PERMISSIONS: &[&str] = &[ + lithe_plugin_agents::PERMISSION_AGENTS_RUN, + lithe_plugin_agents::PERMISSION_AGENTS_SESSIONS, PERMISSION_BACKEND, PERMISSION_BUILD, PERMISSION_COMMAND_INSTALL, @@ -265,6 +267,7 @@ impl DeclarativePluginManifest { "debug.start starts the plugin's own debug adapters; declare one or remove the permission.", )); } + self.require_agent_permissions(&mut required)?; // The backend reaches only the servers whose session fields expose // them; the grant without one would show the user a capability // nothing exercises. @@ -300,4 +303,37 @@ impl DeclarativePluginManifest { } Ok(()) } + + /// Ties `agents[]` to its permissions: running the agents' tools, reading + /// their session files, and translating native sessions. A permission + /// nothing exercises is refused. + fn require_agent_permissions(&self, required: &mut BTreeSet<&'static str>) -> Validation<()> { + let needs = [ + ( + lithe_plugin_agents::PERMISSION_AGENTS_RUN, + !self.agents.is_empty(), + ), + ( + lithe_plugin_agents::PERMISSION_AGENTS_SESSIONS, + self.agents + .iter() + .any(|agent| !agent.session_sources.is_empty()), + ), + ( + lithe_plugin_rpc::PERMISSION_AGENTS_NATIVE, + lithe_plugin_agents::has_native(&self.agents), + ), + ]; + for (permission, used) in needs { + if used { + required.insert(permission); + } else if self.permissions.iter().any(|p| p == permission) { + return Err(invalid( + "permissions", + format!("{permission} is used by an agent that needs it; declare one or remove the permission."), + )); + } + } + Ok(()) + } } diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 5d43a1be..8881e718 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -44,6 +44,7 @@ pub fn validate_manifest_value(value: Value) -> Validation = self.activation_events.iter().cloned().collect(); // The backend may start once a workspace opens. The event is optional diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 81ba20c2..945a81ca 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -129,10 +129,16 @@ pub const TOOLCHAIN_PROVIDERS: &str = "toolchainProviders"; /// `outputLinkMatchers[]`: patterns that turn console output into links; see /// `lithe_plugin_output_links`. pub const OUTPUT_LINK_MATCHERS: &str = "outputLinkMatchers"; +/// `agents[]`: agent command-line tools the plugin drives, their native, +/// ACP and terminal forms, and the session files Core indexes; see +/// `lithe_plugin_agents`. The native relay (`lithe/host/agents/*`) speaks +/// this version. +pub const AGENTS: &str = "agents"; /// Capability versions this Core build validates and plans. A later version /// of a capability is appended to its list. pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ + (AGENTS, &[0]), (BACKEND, &[0]), (BEFORE_LAUNCH_TASKS, &[0]), (BUILD_MODEL_INPUTS, &[0]), diff --git a/rust/crates/plugin-rpc/src/host_api.rs b/rust/crates/plugin-rpc/src/host_api.rs index 19db0388..1a15e63f 100644 --- a/rust/crates/plugin-rpc/src/host_api.rs +++ b/rust/crates/plugin-rpc/src/host_api.rs @@ -4,7 +4,7 @@ //! method table and grant decisions stay with the same Core code that already //! validates backend requests, so a new method cannot widen an old grant. -use crate::{capabilities_answer, HOST_METHODS, HOST_SERVICE_FUNCTIONS}; +use crate::{capabilities_answer, HOST_METHODS, HOST_SERVICE_AGENTS, HOST_SERVICE_FUNCTIONS}; use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; @@ -30,7 +30,7 @@ pub fn describe_command(payload: Value) -> Result { Some(entry.service) }; json!({"method":entry.method,"service":entry.service,"grant":grant, - "coreServed":entry.service == HOST_SERVICE_FUNCTIONS}) + "coreServed":entry.service == HOST_SERVICE_FUNCTIONS || entry.service == HOST_SERVICE_AGENTS}) }) .collect(); Ok(json!({"methods":methods})) @@ -104,6 +104,11 @@ mod tests { ); assert!(method("lithe/host/subscriptions/dispose")["grant"].is_null()); assert_eq!(method("lithe/host/functions/invoke")["coreServed"], true); + assert_eq!(method("lithe/host/agents/write")["coreServed"], true); + assert_eq!( + method("lithe/host/agents/write")["grant"], + "lithe/host/agents/write" + ); } #[test] diff --git a/rust/crates/plugin-rpc/src/host_notifications.rs b/rust/crates/plugin-rpc/src/host_notifications.rs index d28c5505..9e004907 100644 --- a/rust/crates/plugin-rpc/src/host_notifications.rs +++ b/rust/crates/plugin-rpc/src/host_notifications.rs @@ -31,6 +31,10 @@ pub(crate) enum NotificationParams { /// `{ context, serverID, generation, method, params? | truncated }`: a /// forwarded server notification, without params when too large. LanguageServerNotification, + /// A notification about one of the backend's agent sessions (plan + /// API-45). Only Core's agent runtime sends it, in session order; the + /// host may not, so `host_notification` refuses it. + Agent, } /// One row of the host-notification table. @@ -75,6 +79,21 @@ const MAX_RUN_ID_BYTES: usize = 128; /// plugin-owned session has it; a command names only the plugin's own IDs. pub(crate) const HOST_SERVICE_COMMANDS: &str = "commands"; +/// The agent CLI of a session started (plan API-45). The agent-session +/// notifications below are sent by Core's agent runtime, in session order, to +/// the backend that translates the session. +pub const AGENTS_DID_START: &str = "lithe/host/agents/didStart"; +/// Lines the agent CLI wrote to standard output, in order. +pub const AGENTS_DID_OUTPUT: &str = "lithe/host/agents/didOutput"; +/// A prompt the user sent to the session. +pub const AGENTS_DID_PROMPT: &str = "lithe/host/agents/didPrompt"; +/// The user cancelled a turn. +pub const AGENTS_DID_CANCEL: &str = "lithe/host/agents/didCancel"; +/// The user answered a permission request the backend reported. +pub const AGENTS_DID_DECIDE_PERMISSION: &str = "lithe/host/agents/didDecidePermission"; +/// The agent CLI exited. +pub const AGENTS_DID_EXIT: &str = "lithe/host/agents/didExit"; + /// Every host-to-backend notification the host may send through /// `lsp.hostNotify`. A notification missing here never reaches a backend, /// so the host cannot use the channel to call into the backend's own @@ -116,8 +135,53 @@ pub(crate) const HOST_NOTIFICATIONS: &[HostNotification] = &[ grant: None, params: NotificationParams::LanguageServerNotification, }, + // Listed so `getCapabilities` shows them; the host may not send them. + HostNotification { + method: AGENTS_DID_START, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, + HostNotification { + method: AGENTS_DID_OUTPUT, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, + HostNotification { + method: AGENTS_DID_PROMPT, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, + HostNotification { + method: AGENTS_DID_CANCEL, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, + HostNotification { + method: AGENTS_DID_DECIDE_PERMISSION, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, + HostNotification { + method: AGENTS_DID_EXIT, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, ]; +/// Whether `method` is one of the agent-session notifications only Core's +/// agent runtime sends. +pub fn is_agent_notification(method: &str) -> bool { + HOST_NOTIFICATIONS + .iter() + .any(|entry| entry.method == method && entry.params == NotificationParams::Agent) +} + /// Whether the session holds a service: its aggregate grant, or, for a /// service granted per method, any of its methods. fn holds_service(service: &str, granted: &BTreeSet) -> bool { @@ -159,6 +223,13 @@ pub fn host_notification( codes::HOST_UNAVAILABLE, )); }; + if entry.params == NotificationParams::Agent { + return Err(refusal( + ErrorCode::InvalidRequest, + "Only Core's agent runtime sends agent-session notifications.", + codes::HOST_UNAVAILABLE, + )); + } if !entry.admitted(granted) { return Err(refusal( ErrorCode::InvalidRequest, @@ -229,6 +300,7 @@ pub fn host_notification( .is_some_and(is_language_server_state) && positive("generation") } + NotificationParams::Agent => false, NotificationParams::LanguageServerNotification => { let truncated = object.get("truncated"); only(&[ diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index e5e801f2..e1651e91 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -27,6 +27,10 @@ pub enum HostRoute { /// answers it. The host sees only the start request for a provider whose /// backend is not running. Relay, + /// An agent-session method (plan API-45): Core's agent runtime checks + /// that the session belongs to the backend and answers it. The host never + /// sees the request. + Agents, } /// How Core checks the params of one host method before the host sees them. @@ -579,8 +583,38 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ permission: Some(PERMISSION_DOCUMENTS_CONTENT_PROVIDER), params: HostParams::ContentProvider, }, + // Plan API-45: the native relay of the plugin's own agent sessions, and + // the usage totals of consented agents. Core's agent runtime answers + // them and checks session ownership. + HostMethod { + method: AGENTS_WRITE, + service: HOST_SERVICE_AGENTS, + permission: Some(PERMISSION_AGENTS_NATIVE), + params: HostParams::Object, + }, + HostMethod { + method: AGENTS_REPORT, + service: HOST_SERVICE_AGENTS, + permission: Some(PERMISSION_AGENTS_NATIVE), + params: HostParams::Object, + }, + HostMethod { + method: AGENTS_USAGE, + service: HOST_SERVICE_AGENTS, + permission: Some(PERMISSION_AGENTS_USAGE), + params: HostParams::Object, + }, ]; +/// Writes lines to the standard input of one of the backend's agent CLIs. +pub const AGENTS_WRITE: &str = "lithe/host/agents/write"; + +/// Reports session events the backend translated from CLI output. +pub const AGENTS_REPORT: &str = "lithe/host/agents/report"; + +/// Reads usage and quota totals of the agents the user consented to. +pub const AGENTS_USAGE: &str = "lithe/host/agents/usage"; + /// Host service of the plugin's own language servers (plan API-25). pub(crate) const HOST_SERVICE_LANGUAGE_SERVER: &str = "languageServer"; @@ -661,6 +695,9 @@ pub fn host_request( if entry.service == HOST_SERVICE_FUNCTIONS { return Ok(HostRoute::Relay); } + if entry.service == HOST_SERVICE_AGENTS { + return Ok(HostRoute::Agents); + } Ok(HostRoute::Forward(entry.service)) } diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index 239abcb3..99f6a25b 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -169,8 +169,23 @@ pub const HOST_PERMISSIONS: &[&str] = &[ PERMISSION_DOCUMENTS_CONTENT_PROVIDER, PERMISSION_DOCUMENTS_SAVE, PERMISSION_WORKSPACE_FILES_WRITE, + PERMISSION_AGENTS_NATIVE, + PERMISSION_AGENTS_USAGE, ]; +/// Host service of agent sessions (plan API-45). Core answers its methods +/// itself; the host never sees them. +pub const HOST_SERVICE_AGENTS: &str = "agents"; + +/// Permission of `lithe/host/agents/write` and `lithe/host/agents/report` +/// (plan API-45): the backend translates the native sessions of its own +/// agents and receives their `lithe/host/agents/did*` notifications. +pub const PERMISSION_AGENTS_NATIVE: &str = "agents.native"; + +/// Permission of `lithe/host/agents/usage` (plan API-45): usage and quota +/// totals of the agents the user consented to, numbers and model names only. +pub const PERMISSION_AGENTS_USAGE: &str = "agents.usage.read"; + /// Permission of the `languageServer` host service (plan API-25): a backend /// may send requests and notifications to, and report the status of, the /// language servers its own plugin declares. diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index d18bda37..5ec47cd8 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -1,5 +1,100 @@ { "version": 1, "root": "agent", - "events": [] + "events": [ + { + "id": "agent.session.started", + "channel": "agent", + "level": "info", + "message": "Agent session started", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, + "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, + "session": {"type": "id", "required": true, "description": "Opaque session ID Core assigned; never the agent CLI's own session ID"}, + "mode": {"type": "token", "required": true, "description": "Connection mode Core selected, e.g. native"} + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.session.start_failed", + "channel": "agent", + "level": "warn", + "message": "Agent session could not start", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, + "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, + "reason": {"type": "token", "required": true, "description": "Stable refusal or failure code; excludes paths, arguments and CLI output"} + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.session.finished", + "channel": "agent", + "level": "info", + "message": "Agent session ended", + "fields": { + "session": {"type": "id", "required": true, "description": "Opaque session ID Core assigned"}, + "reason": {"type": "token", "required": true, "description": "Why the session ended: exited, closed, backendEnded or failed"}, + "exit_code": {"type": "int", "required": false, "description": "Exit code of the agent CLI; absent when a signal ended it"}, + "duration": {"type": "duration", "required": true, "description": "Milliseconds the session ran"} + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.report.rejected", + "channel": "agent", + "level": "warn", + "message": "Agent plugin reported an invalid session event", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity of the reporting backend"}, + "code": {"type": "token", "required": true, "description": "Stable rejection code; the event content is never logged"} + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.records.updated", + "channel": "agent", + "level": "info", + "message": "Agent session records synchronized", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, + "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, + "files_read": {"type": "int", "required": true, "description": "Session files read in this sync"}, + "files_failed": {"type": "int", "required": true, "description": "Session files that could not be read or parsed"}, + "duration": {"type": "duration", "required": true, "description": "Milliseconds the sync took"} + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.records.sync_failed", + "channel": "agent", + "level": "warn", + "message": "Agent session records could not be synchronized", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, + "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, + "reason": {"type": "token", "required": true, "description": "Stable failure code; excludes paths and session content"} + }, + "rate": 60, + "owner": "lithe-core" + }, + { + "id": "agent.records.removed", + "channel": "agent", + "level": "info", + "message": "Agent session records removed from the cache", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity that declares the agent"}, + "agent": {"type": "id", "required": true, "description": "Agent ID the plugin declares"}, + "files": {"type": "int", "required": true, "description": "Session files whose records were dropped"} + }, + "rate": 60, + "owner": "lithe-core" + } + ] } From 5fbc6fbb228bccdbd604cb21a05661a77fdd0cb8 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 03:33:41 +0800 Subject: [PATCH 2/7] =?UTF-8?q?feat(agents):=20=E6=8E=A5=E5=85=A5=20agents?= =?UTF-8?q?.*=20=E4=B8=8E=20agentSessions.*=20=E5=91=BD=E4=BB=A4=EF=BC=8C?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=BC=9A=E8=AF=9D=E8=AE=B0=E5=BD=95=20ID=20?= =?UTF-8?q?=E5=AD=97=E6=AE=B5=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 16 ++++ rust/crates/agent-runtime/src/tests.rs | 12 +-- rust/crates/agent-sessions/src/model.rs | 6 ++ rust/crates/agent-sessions/src/store.rs | 13 +-- rust/crates/core/Cargo.toml | 1 + rust/crates/core/src/protocol/command.rs | 81 +++++++++++++++++++ rust/crates/core/src/runtime/dispatcher.rs | 4 +- .../core/src/runtime/dispatcher/agents.rs | 14 ++++ .../crates/plugin-manifest/src/permissions.rs | 2 +- 9 files changed, 136 insertions(+), 13 deletions(-) create mode 100644 rust/crates/core/src/runtime/dispatcher/agents.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 72882654..7b921b28 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -480,6 +480,22 @@ or removing a command fails until the table changes in the same commit. | `ai.pullRequest.decode` | Decode a strict pull request title and description | | `ai.inlineEdit.plan` | Plan a credential-free inline edit request | | `ai.inlineEdit.decode` | Decode the replacement text of an inline edit response | +| `agents.configure` | Load the agents enabled plugins declare, with the permissions the user granted | +| `agents.catalog` | List the configured agents | +| `agents.sessions` | List the live agent sessions | +| `agents.start` | Start a native agent session the user asked for | +| `agents.prompt` | Send the user's prompt to a live agent session | +| `agents.cancel` | Ask the agent backend to cancel the turn in progress | +| `agents.respondPermission` | Answer a pending agent permission request | +| `agents.close` | End a live agent session | +| `agents.waitEvents` | Wait, bounded, for agent session events after a sequence | +| `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.search` | Search recorded agent session text | +| `agentSessions.read` | Read one recorded range as messages | +| `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 | | `plugins.web.open` | Register a plugin page for a web tool window | diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index b8a388c6..d49250cd 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -150,19 +150,19 @@ fn scan(params: &Value) -> Value { }; match record["type"].as_str() { Some("session") => sessions.push(json!({ - "sessionId": record["id"], + "sessionID": record["id"], "cwd": record["cwd"], "startedAtMs": record["at"], "updatedAtMs": record["at"], })), Some("user") => { sessions.push(json!({ - "sessionId": record["session"], + "sessionID": record["session"], "updatedAtMs": record["at"], "titleRange": range, })); spans.push(json!({ - "sessionId": record["session"], + "sessionID": record["session"], "atMs": record["at"], "range": range, "text": record["text"], @@ -170,7 +170,7 @@ fn scan(params: &Value) -> Value { } Some("call") => calls.push(json!({ "key": record["key"], - "sessionId": record["session"], + "sessionID": record["session"], "startedAtMs": record["at"], "model": record["model"], "tokens": { "input": record["input"], "output": record["output"] }, @@ -1230,7 +1230,7 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() { let sessions = harness.run("agentSessions.list", json!({ "titles": true }))["sessions"].clone(); assert_eq!(sessions.as_array().map(Vec::len), Some(1), "{sessions}"); - assert_eq!(sessions[0]["sessionId"], "s1"); + assert_eq!(sessions[0]["sessionID"], "s1"); assert_eq!(sessions[0]["pluginID"], PLUGIN); assert_eq!(sessions[0]["agentID"], AGENT); assert_eq!(sessions[0]["cwd"], "/work/project"); @@ -1240,7 +1240,7 @@ fn records_sync_list_search_read_and_sum_through_the_plugin() { let hits = harness.run("agentSessions.search", json!({ "text": "hello" }))["hits"].clone(); assert_eq!(hits.as_array().map(Vec::len), Some(1), "{hits}"); - assert_eq!(hits[0]["sessionId"], "s1"); + assert_eq!(hits[0]["sessionID"], "s1"); let read = harness.run( "agentSessions.read", json!({ "agent": AGENT_KEY, "path": hits[0]["path"], "range": hits[0]["range"] }), diff --git a/rust/crates/agent-sessions/src/model.rs b/rust/crates/agent-sessions/src/model.rs index 7d3c31f9..4fb1771d 100644 --- a/rust/crates/agent-sessions/src/model.rs +++ b/rust/crates/agent-sessions/src/model.rs @@ -73,9 +73,11 @@ pub struct CallRecord { /// once. pub key: String, /// The session the request belongs to, in the agent's own ID format. + #[serde(rename = "sessionID")] pub session_id: String, /// The thread or sub-agent within the session, when the agent has them. #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(rename = "threadID")] pub thread_id: Option, /// When the request started, in milliseconds since the Unix epoch (UTC). pub started_at_ms: i64, @@ -113,6 +115,7 @@ pub struct CallRecord { pub compaction: bool, /// The provider's request ID, kept for matching with provider dashboards. #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(rename = "requestID")] pub request_id: Option, /// A short category of the failure when the request failed, as the agent /// names it (for example `rateLimited`). Never the error message. @@ -128,9 +131,11 @@ pub struct CallRecord { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SessionMeta { /// The session, in the agent's own ID format. + #[serde(rename = "sessionID")] pub session_id: String, /// The session this one was resumed or forked from. #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(rename = "parentSessionID")] pub parent_session_id: Option, /// The working directory the agent ran in. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -155,6 +160,7 @@ pub struct SessionMeta { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct IndexSpan { /// The session the text belongs to. + #[serde(rename = "sessionID")] pub session_id: String, /// When the text was written, in milliseconds since the Unix epoch. /// Search lists newer text first. diff --git a/rust/crates/agent-sessions/src/store.rs b/rust/crates/agent-sessions/src/store.rs index f884264b..51d25337 100644 --- a/rust/crates/agent-sessions/src/store.rs +++ b/rust/crates/agent-sessions/src/store.rs @@ -252,6 +252,7 @@ pub struct SessionEntry { /// The agent that ran the session. pub agent: String, /// The session, in the agent's own ID format. + #[serde(rename = "sessionID")] pub session_id: String, /// The file the other fields come from: the first, by path, of the files /// that describe the session, or of those that only mention it. @@ -260,6 +261,7 @@ pub struct SessionEntry { pub file_count: u64, /// The session this one was resumed or forked from. #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "parentSessionID")] pub parent_session_id: Option, /// The working directory the agent ran in. #[serde(skip_serializing_if = "Option::is_none")] @@ -302,6 +304,7 @@ pub struct SearchHit { /// The session file. pub path: String, /// The session the text belongs to. + #[serde(rename = "sessionID")] pub session_id: String, /// When the text was written, when the parser knew. #[serde(skip_serializing_if = "Option::is_none")] @@ -1191,7 +1194,7 @@ fn validate(output: ScanOutput, start: u64, end: u64) -> Result Result Result &'static str { + match self { + Self::Configure => "agents.configure", + Self::Catalog => "agents.catalog", + Self::Sessions => "agents.sessions", + Self::Start => "agents.start", + Self::Prompt => "agents.prompt", + Self::Cancel => "agents.cancel", + Self::RespondPermission => "agents.respondPermission", + Self::Close => "agents.close", + Self::WaitEvents => "agents.waitEvents", + Self::RecordsConfigure => "agentSessions.configure", + Self::RecordsSync => "agentSessions.sync", + Self::RecordsForget => "agentSessions.forget", + Self::RecordsList => "agentSessions.list", + Self::RecordsSearch => "agentSessions.search", + Self::RecordsRead => "agentSessions.read", + Self::RecordsStats => "agentSessions.stats", + } + } +} + #[derive(Debug, Clone)] /// The `plugins.*` commands; their names live in [`CoreCommand::parse`]. pub enum PluginsCommand { @@ -1180,6 +1245,22 @@ impl CoreCommand { "ai.pullRequest.decode" => Some(Self::Ai(AiCommand::PullRequestDecode)), "ai.inlineEdit.plan" => Some(Self::Ai(AiCommand::InlineEditPlan)), "ai.inlineEdit.decode" => Some(Self::Ai(AiCommand::InlineEditDecode)), + "agents.configure" => Some(Self::Agents(AgentsCommand::Configure)), + "agents.catalog" => Some(Self::Agents(AgentsCommand::Catalog)), + "agents.sessions" => Some(Self::Agents(AgentsCommand::Sessions)), + "agents.start" => Some(Self::Agents(AgentsCommand::Start)), + "agents.prompt" => Some(Self::Agents(AgentsCommand::Prompt)), + "agents.cancel" => Some(Self::Agents(AgentsCommand::Cancel)), + "agents.respondPermission" => Some(Self::Agents(AgentsCommand::RespondPermission)), + "agents.close" => Some(Self::Agents(AgentsCommand::Close)), + "agents.waitEvents" => Some(Self::Agents(AgentsCommand::WaitEvents)), + "agentSessions.configure" => Some(Self::Agents(AgentsCommand::RecordsConfigure)), + "agentSessions.sync" => Some(Self::Agents(AgentsCommand::RecordsSync)), + "agentSessions.forget" => Some(Self::Agents(AgentsCommand::RecordsForget)), + "agentSessions.list" => Some(Self::Agents(AgentsCommand::RecordsList)), + "agentSessions.search" => Some(Self::Agents(AgentsCommand::RecordsSearch)), + "agentSessions.read" => Some(Self::Agents(AgentsCommand::RecordsRead)), + "agentSessions.stats" => Some(Self::Agents(AgentsCommand::RecordsStats)), "plugins.declarative.validate" => { Some(Self::Plugins(PluginsCommand::DeclarativeValidate)) } diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index ed3d7792..1ae32463 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -14,6 +14,7 @@ use lithe_github::{NormalizeResponseRequest, ParseRemoteRequest, RequestPlanRequ use lithe_plugin_manifest::DeclarativePluginManifest as Manifest; use serde_json::json; +mod agents; mod ai; mod build; mod debug; @@ -46,7 +47,7 @@ pub(crate) fn execute_document_json(request: &str, document: Option<&str>) -> St }) } -/// Decode an agent management payload and run `operation` on it. +/// Runs a plugin domain `operation` on its payload. /// Declarative plugin commands decode their own payloads so manifest content /// problems surface as `rejected` outcomes rather than Core failures. fn plugin_response( @@ -192,6 +193,7 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon }), ), CoreCommand::Ai(command) => ai::dispatch(command, id, parsed.payload), + CoreCommand::Agents(command) => agents::dispatch(command, id, parsed.payload), CoreCommand::Plugins(command) => plugins::dispatch(command, id, parsed.payload), CoreCommand::Debug(command) => debug::dispatch(command, id, parsed.payload), CoreCommand::Keymap(command) => keymap::dispatch(command, id, parsed.payload), diff --git a/rust/crates/core/src/runtime/dispatcher/agents.rs b/rust/crates/core/src/runtime/dispatcher/agents.rs new file mode 100644 index 00000000..103b3d65 --- /dev/null +++ b/rust/crates/core/src/runtime/dispatcher/agents.rs @@ -0,0 +1,14 @@ +//! `agents.*` and `agentSessions.*` commands, run by `lithe-agent-runtime` +//! (plan API-45). + +use crate::protocol::{AgentsCommand, CoreResponse}; +use serde_json::Value; + +/// Runs one agent command. `agents.waitEvents` blocks for at most the +/// timeout it was given, so the host calls it off its UI thread. +pub(super) fn dispatch(command: AgentsCommand, id: Option, payload: Value) -> CoreResponse { + match lithe_agent_runtime::execute(command.name(), payload) { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + } +} diff --git a/rust/crates/plugin-manifest/src/permissions.rs b/rust/crates/plugin-manifest/src/permissions.rs index 5e16a0b0..d21c9326 100644 --- a/rust/crates/plugin-manifest/src/permissions.rs +++ b/rust/crates/plugin-manifest/src/permissions.rs @@ -330,7 +330,7 @@ impl DeclarativePluginManifest { } else if self.permissions.iter().any(|p| p == permission) { return Err(invalid( "permissions", - format!("{permission} is used by an agent that needs it; declare one or remove the permission."), + format!("{permission} is declared, but no agent needs it."), )); } } From 607be1ac172b12b5dd083c7950562f6d695db990 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 03:57:29 +0800 Subject: [PATCH 3/7] =?UTF-8?q?docs(agents):=20API-45=20=E5=A5=91=E7=BA=A6?= =?UTF-8?q?=E3=80=81=E6=B8=85=E5=8D=95=20schema=E3=80=81fixture=20?= =?UTF-8?q?=E4=B8=8E=E5=8F=82=E8=80=83=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 契约 README 新增 Agents 章节:声明、四个权限与 onAgent 激活、宿主命令、 原生会话、会话记录、隐私与日志、版本 0 限制 - plugin-manifest.schema.json 加入 agents、requires.agents、四个权限与 onAgent - 新增 fixtures/agents 两个清单和 23 个拒绝用例,Core 测试逐个对照 - 参考页新增 domains/agents.md,API 总表、更新记录、能力版本表加入 API-45 - 会话统计按会话分组时字段名统一为 sessionID --- rust/Cargo.lock | 1 + rust/crates/agent-sessions/src/stats.rs | 2 +- .../core/src/tests/declarative_plugins.rs | 56 +++ shared/plugins/README.md | 12 +- shared/plugins/contract/v1/README.md | 366 +++++++++++++++++- .../v1/fixtures/agents/agents.plugin.json | 73 ++++ .../agents/terminal-agent.plugin.json | 35 ++ .../fixtures/manifest/invalid-manifests.json | 25 +- .../contract/v1/plugin-manifest.schema.json | 192 ++++++++- .../guides/plugin-api-pr-guide.zh-CN.md | 12 +- shared/plugins/reference/README.md | 6 +- shared/plugins/reference/api-catalog.md | 48 ++- .../reference/capabilities-and-versions.md | 10 +- shared/plugins/reference/domains/agents.md | 113 ++++++ .../reference/domains/keymap-import.md | 4 +- shared/plugins/reference/domains/manifest.md | 4 +- .../plugins/reference/domains/marketplace.md | 4 +- .../reference/domains/package-trust.md | 4 +- .../plugins/reference/protocol-changelog.md | 18 +- 19 files changed, 938 insertions(+), 47 deletions(-) create mode 100644 shared/plugins/contract/v1/fixtures/agents/agents.plugin.json create mode 100644 shared/plugins/contract/v1/fixtures/agents/terminal-agent.plugin.json create mode 100644 shared/plugins/reference/domains/agents.md diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 2124d248..559fb5d9 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1003,6 +1003,7 @@ name = "lithe-core" version = "0.1.0" dependencies = [ "base64", + "lithe-agent-runtime", "lithe-ai", "lithe-build", "lithe-core-rules", diff --git a/rust/crates/agent-sessions/src/stats.rs b/rust/crates/agent-sessions/src/stats.rs index 4bf2fb9d..da658894 100644 --- a/rust/crates/agent-sessions/src/stats.rs +++ b/rust/crates/agent-sessions/src/stats.rs @@ -73,11 +73,11 @@ pub enum GroupKey { model: Option, }, /// A session of an agent. - #[serde(rename_all = "camelCase")] Session { /// The agent. agent: String, /// The session. + #[serde(rename = "sessionID")] session_id: String, }, /// A working directory; absent for sessions that do not record it. diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 89bd1f6c..990e9c82 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -78,6 +78,8 @@ const RUN_CONFIGURATION_TYPES_FIXTURE: &str = const BEFORE_LAUNCH_TASKS_FIXTURE: &str = contract_file!("fixtures/before-launch-tasks/before-launch-tasks.plugin.json"); const INVALID_MANIFESTS: &str = contract_file!("fixtures/manifest/invalid-manifests.json"); +const AGENTS_FIXTURE: &str = contract_file!("fixtures/agents/agents.plugin.json"); +const TERMINAL_AGENT_FIXTURE: &str = contract_file!("fixtures/agents/terminal-agent.plugin.json"); const COMMAND_PLANS: &str = contract_file!("fixtures/languages/command-plans.json"); fn fixture(name: &str) -> Value { @@ -114,6 +116,8 @@ fn fixture(name: &str) -> Value { "command-installer-download.plugin.json" => COMMAND_INSTALLER_DOWNLOAD_FIXTURE, "run-configuration-types.plugin.json" => RUN_CONFIGURATION_TYPES_FIXTURE, "before-launch-tasks.plugin.json" => BEFORE_LAUNCH_TASKS_FIXTURE, + "agents.plugin.json" => AGENTS_FIXTURE, + "terminal-agent.plugin.json" => TERMINAL_AGENT_FIXTURE, other => panic!("unknown fixture {other}"), }; serde_json::from_str(source).expect("fixture manifest is JSON") @@ -150,6 +154,8 @@ fn contract_fixtures_and_official_plugins_validate() { COMMAND_INSTALLER_DOWNLOAD_FIXTURE, RUN_CONFIGURATION_TYPES_FIXTURE, BEFORE_LAUNCH_TASKS_FIXTURE, + AGENTS_FIXTURE, + TERMINAL_AGENT_FIXTURE, ] { let outcome = validate(serde_json::from_str(source).unwrap()); assert_eq!(outcome["status"], "ok", "{outcome}"); @@ -277,6 +283,56 @@ fn invalid_manifest_fixtures_report_their_stable_codes() { } } +/// The install review shows every form an agent runs and every directory its +/// session sources read, so the user sees them before installing. +#[test] +fn agents_are_reviewed_programs() { + let review = |name: &str| { + let outcome = lithe_plugin_marketplace::install_review_command(json!({ + "manifest": fixture(name), + })) + .expect("payload is well formed"); + outcome["review"]["programs"].as_array().unwrap().clone() + }; + let programs: Vec = review("agents.plugin.json") + .iter() + .filter(|program| { + matches!( + program["kind"].as_str(), + Some("agent") | Some("agentSessions") + ) + }) + .cloned() + .collect(); + assert_eq!( + programs, + vec![ + json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "native", "launchFunction": "example.launch"}), + json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "terminal", "arguments": []}), + json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "update", "arguments": ["update"]}), + json!({ + "kind": "agentSessions", + "agentID": "example", + "tool": "example-agent", + "source": "projects", + "roots": ["${env:EXAMPLE_HOME}/sessions", "${userHome}/.example/sessions"], + "include": ["**/*.jsonl"] + }), + ] + ); + + let forms: Vec = review("terminal-agent.plugin.json") + .into_iter() + .filter(|program| program["kind"] == "agent") + .collect(); + assert_eq!( + forms, + vec![ + json!({"kind": "agent", "agentID": "example", "tool": "example-agent", "form": "terminal", "arguments": ["--interactive"]}) + ] + ); +} + /// The command-installer commands answer the golden cases for this host's /// platform; `lithe-plugin-manifest` checks the same cases for every /// platform. diff --git a/shared/plugins/README.md b/shared/plugins/README.md index 4a69da49..adc85665 100644 --- a/shared/plugins/README.md +++ b/shared/plugins/README.md @@ -15,7 +15,7 @@ | 需要自己的后端进程 | [插件后端 SDK](#插件后端-sdk可选) | | 接入宿主日志、排查插件故障 | [插件接入统一日志](guides/plugin-logging.md) | | 参考现成插件 | [示例插件](#示例插件) | -| 查 API-01–44 现在能用什么、每种能力和协议的版本、Core 和 Lithe 桌面端支持哪些 | [插件参考](reference/README.md) | +| 查 API-01–45 现在能用什么、每种能力和协议的版本、Core 和 Lithe 桌面端支持哪些 | [插件参考](reference/README.md) | | 查字段的准确含义 | [插件契约](#插件契约) | | 为插件需要的公共 API 提 PR | [API PR 提交指南(中文)](guides/plugin-api-pr-guide.zh-CN.md) | | 修改契约、指南或 SDK,在本地验证 | [贡献与维护](#贡献与维护) | @@ -62,7 +62,7 @@ Lithe 读取并校验 `plugin.json`,然后自己启动其中声明的外部进 `requires` 必须**恰好**列出实际用到的能力:漏一个或多列一个,清单都会被拒绝。例如只用声明式构建系统时写 `"requires": { "buildSystems": 0 }`,不要多写。 -已有的能力版本继续保留,按实际用法选择最低可用版本;用到 `1`、`2` 才有的行为时如实声明,不强制填 `0`。新增能力先复用 API-01–44,在所属领域兼容扩展;工具特有需求不得提升任何系统 API 版本,公共变化也要先证明兼容扩展不足,详见 [API PR 提交指南](guides/plugin-api-pr-guide.zh-CN.md)。每个能力的内容、Core 的支持表和 Lithe 桌面端是否声明它,见[能力与协议版本对照](reference/capabilities-and-versions.md#能力版本requires);Lithe 桌面端没有声明的能力,需要它的插件不会被提供安装。 +已有的能力版本继续保留,按实际用法选择最低可用版本;用到 `1`、`2` 才有的行为时如实声明,不强制填 `0`。新增能力先复用 API-01–45,在所属领域兼容扩展;工具特有需求不得提升任何系统 API 版本,公共变化也要先证明兼容扩展不足,详见 [API PR 提交指南](guides/plugin-api-pr-guide.zh-CN.md)。每个能力的内容、Core 的支持表和 Lithe 桌面端是否声明它,见[能力与协议版本对照](reference/capabilities-and-versions.md#能力版本requires);Lithe 桌面端没有声明的能力,需要它的插件不会被提供安装。 ### 在编辑器里校验 plugin.json @@ -167,7 +167,7 @@ SDK 与插件后端在构建时下载,并按锁定的 SHA-256(或 Git commit | 页面 | 内容 | | --- | --- | -| [插件 API 总表](reference/api-catalog.md) | API-01–44 每一项现在能用的方法、尚未提供的部分和对应功能页 | +| [插件 API 总表](reference/api-catalog.md) | API-01–45 每一项现在能用的方法、尚未提供的部分和对应功能页 | | [能力与协议版本对照](reference/capabilities-and-versions.md) | `requires` 能力版本、进程协议版本、文档格式版本,对照 Core 和 Lithe 桌面端支持哪些 | | [插件协议更新记录](reference/protocol-changelog.md) | 每个协议、能力和 API 是哪天、哪个 PR 改的,以及每个版本首次出现在哪个 PR;只有中文 | | [功能页](reference/README.md#功能页) | 15 个功能各一页:字段、宿主现状、契约章节、示例与用例 | @@ -239,7 +239,7 @@ Writing, testing, and publishing a plugin all happen in **your own repository**. | Run a backend process of your own | [Plugin backend SDKs](#plugin-backend-sdks-optional) | | Connect to host logging and diagnose plugin failures | [Plugin logging](guides/plugin-logging.md) | | Learn from existing plugins | [Example plugins](#example-plugins) | -| See what API-01–44 offer today, the version of each capability and protocol, and what Core and the Lithe desktop client support | [Plugin reference](reference/README.md) | +| See what API-01–45 offer today, the version of each capability and protocol, and what Core and the Lithe desktop client support | [Plugin reference](reference/README.md) | | Look up the exact meaning of a field | [Plugin contract](#plugin-contract) | | Propose a public API extension for a plugin | [API PR guide (Chinese)](guides/plugin-api-pr-guide.zh-CN.md) | | Change the contract, guides, or SDKs and verify locally | [Contributing and maintenance](#contributing-and-maintenance) | @@ -286,7 +286,7 @@ When you need run, test, or build tool integration, read the [build, run, and te `requires` must list **exactly** the capabilities you use: leaving one out or listing one extra gets the manifest rejected. For example, a plugin that only uses declarative build systems writes `"requires": { "buildSystems": 0 }` and nothing more. -Keep existing capability versions and select the lowest that covers the actual use; declare `1` or `2` when its behavior is needed rather than forcing every value to `0`. Reuse API-01–44 and extend the appropriate domain compatibly. Tool-specific requirements must not raise any system API version; even a public change must first show why a compatible extension is insufficient. See the [API PR guide (Chinese)](guides/plugin-api-pr-guide.zh-CN.md). For what each capability covers, Core's support table, and whether the Lithe desktop client declares it, see [Capability and protocol versions](reference/capabilities-and-versions.md#capability-versions-requires); a plugin that needs a capability the Lithe desktop client does not declare is not offered for installation there. +Keep existing capability versions and select the lowest that covers the actual use; declare `1` or `2` when its behavior is needed rather than forcing every value to `0`. Reuse API-01–45 and extend the appropriate domain compatibly. Tool-specific requirements must not raise any system API version; even a public change must first show why a compatible extension is insufficient. See the [API PR guide (Chinese)](guides/plugin-api-pr-guide.zh-CN.md). For what each capability covers, Core's support table, and whether the Lithe desktop client declares it, see [Capability and protocol versions](reference/capabilities-and-versions.md#capability-versions-requires); a plugin that needs a capability the Lithe desktop client does not declare is not offered for installation there. ### Validate plugin.json in your editor @@ -391,7 +391,7 @@ Lithe Store maintains the listing rules: [Publishing community plugins](https:// | Page | Covers | | --- | --- | -| [Plugin API catalog](reference/api-catalog.md) | For each of API-01–44, the methods usable today, what is still missing, and its feature page | +| [Plugin API catalog](reference/api-catalog.md) | For each of API-01–45, the methods usable today, what is still missing, and its feature page | | [Capability and protocol versions](reference/capabilities-and-versions.md) | `requires` capability versions, process protocol versions, and document format versions, compared across Core and the Lithe desktop client | | [Plugin protocol changelog](reference/protocol-changelog.md) | When, and in which PR, each protocol, capability, and API changed, and the PR that introduced each version; Chinese only | | [Feature pages](reference/README.md#feature-pages) | One page for each of 15 features: fields, host status, contract sections, examples and cases | diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 5b8a7db1..b99d63d6 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -34,6 +34,7 @@ This directory is the cross-platform source of truth: | `fixtures/run/` | Run sessions and console links: `tool-reference-launch` names its runtimes by tool-definition ID and declares output link matchers; `run-start.json` holds what `run.decodeStart` returns for each case, including the rejections, and `output-link-matchers.json` the golden matches and resolutions | | `fixtures/vcs/` | A version control provider | | `fixtures/keymap-import/` | Two independent shortcut import providers sharing one packaged backend | +| `fixtures/agents/` | `agents.plugin.json`: an agent with native, terminal and update forms and a session source, served by its backend; `terminal-agent.plugin.json`: a terminal-only agent without a backend. Their rejections are in `fixtures/manifest/invalid-manifests.json` | | `fixtures/project-generators/` | Project generators: template files (`templates/`), a scaffolding command, and an archive download; `project-generator-tool-field.plugin.json` with `templates/tool-field/` picks tool installations with `tool` fields; `project-plans.json` holds golden `project.*` form evaluations, generation plans, and name checks, and a case's optional `manifest` names the fixture it runs against (`project-generator.plugin.json` by default) | | `fixtures/toolchains/` | Production-shape fixtures for tool definitions and a packaged toolchain provider; they require `toolDefinitions` and `toolchainProviders`, which a host advertises only when it implements them | | `fixtures/package-trust/` | `publisher-bundled.plugin.json` and `signature-vectors.json`: public cross-platform vectors for the package publisher signature: the RFC 8032 test key, a fixed package with non-ASCII file names, its canonical payload, RFC 8032 deterministic signature, and content digest. Both platforms must build the same canonical payload and digest and accept the recorded signature; signers that add randomness, such as CryptoKit, check the signature by verification instead of byte comparison | @@ -979,7 +980,7 @@ what it needs and a host states what it runs, each per capability. all the others are `0`. 3. **A host declares a capability version when it can serve every form of it.** See [Host capabilities](#host-capabilities). -4. **Reuse and compatible extension come first.** API-01–44 classify domains, +4. **Reuse and compatible extension come first.** API-01–45 classify domains, not a closed method list. Add general methods, notifications, optional fields, or declarations within the appropriate domain when existing interfaces are insufficient. An additive optional field preserves its omission behavior @@ -1075,6 +1076,7 @@ belongs to one capability: | `toolchainProviders` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](toolchains/README.md) | toolchain provider protocol (`litheToolchains`) | Starts the provider and validates its answers. | | `pluginFunctions` | [`pluginFunctions`](#cross-plugin-calls): exported functions and declared calls between plugins | — (the relay methods are part of `litheFunctions`) | Relays calls between plugins. | | `keymapImportProviders` | `keymapImportProviders[]`: [independent shortcut import providers](#shortcut-import-providers-core-foundation) | `litheKeymapImport` | Starts the provider and imports the shortcuts it reads. | +| `agents` | [`agents[]`](#agents): agent command-line tools, their forms and session sources | Existing backend functions and the [`agents` host service](#native-sessions) | Runs the agents' tools in Core after the user starts a session, relays native sessions through the backend, and reads session records after the user consents. | ### Host capabilities @@ -1826,6 +1828,10 @@ Older hosts that do not advertise this capability reject | `debug.start` | the backend starts a [debug session](#run-and-debug-sessions) on one of its own adapters; grants only `lithe/host/debug/start`; requires `backend` and a declared `debugAdapters` entry | | `languageServer.request` | a language server lists `requestMethods` or `forwardNotifications`, and only then; requires `backend`. Grants the [`languageServer` host methods](#language-server-host-methods) for the plugin's own servers and their two notifications, nothing else | | `documents.contentProvider` | the backend registers a [content provider](#content-providers); requires `backend`. Grants `documents/registerContentProvider` only, not reading or editing documents | +| `agents.run` | `agents` is not empty (and only then); permits Core to run each agent's tool in its declared forms after the user starts a session or confirms an update. See [Agent permissions and activation](#agent-permissions-and-activation) | +| `agents.native` | an agent declares `native` (and only then); grants `lithe/host/agents/write`, `lithe/host/agents/report` and the `lithe/host/agents/did*` notifications for the plugin's own sessions | +| `agents.sessions.read` | an agent declares `sessionSources` (and only then); after the user consents, Core reads the declared session files and hands their lines to the backend | +| `agents.usage.read` | the backend reads [usage totals](#native-sessions) with `lithe/host/agents/usage`; requires `backend`. Grants numbers and model names only, no conversation text, titles, session IDs or directories | | Activation event | Meaning | | --- | --- | @@ -1836,6 +1842,7 @@ Older hosts that do not advertise this capability reject | `onVcsRoot:` | Start the VCS provider once a root of its VCS is detected in the workspace. | | `onDebug:` | Start the debug adapter when a debug session needs it. | | `onWorkspaceOpen` | Start the [`backend`](#backend-lifecycle-and-workspace-contexts) process once a workspace is open. Optional, names no ID, refused without `backend`. | +| `onAgent:` | Start the backend before a native session of the agent starts or its session records sync. Required for, and only for, an agent that declares `native` or `sessionSources`. | Each provider needs its event and each event needs a provider; the only optional event is `onWorkspaceOpen`. There is no event that starts a plugin @@ -3629,9 +3636,10 @@ contexts. `fixtures/backend/backend-workspace.plugin.json` is the example. tool window (first page call), a `ui.commands[]` entry (its `onCommand:` also starts the backend), the `onWorkspaceOpen` event, or a provider the host queries: a toolchain or keymap import - provider, or a language server with `launch.kind: "backend"`, whose start - asks the backend for its command line. A backend with none of them is - `plugin.manifest.invalid`. + provider, a language server with `launch.kind: "backend"`, whose start + asks the backend for its command line, or an [agent](#agents) whose native + sessions or session records the backend serves (`onAgent:`). A backend + with none of them is `plugin.manifest.invalid`. - It is one process per plugin, shared by every open workspace and window, on the machine that runs Lithe, also for remote workspaces. No workspace is process state: each call names its workspace explicitly @@ -3652,6 +3660,353 @@ contexts. `fixtures/backend/backend-workspace.plugin.json` is the example. runs or changes something asks the user per operation, as the host's own controls do. +## Agents + +`agents` (requires `agents: 0` in `requires` and the `agents.run` +permission) declares the agent command-line tools a plugin drives: coding +agents such as a chat CLI that edits the workspace. Core knows no agent. +The plugin names the tool, how a session of it starts, and where the tool +keeps its own session files; Core owns every process, every consent and +every record. `fixtures/agents/agents.plugin.json` is the example, +`fixtures/agents/terminal-agent.plugin.json` an agent without a backend, and +the agent cases of `fixtures/manifest/invalid-manifests.json` are the +rejections. + +```json +"requires": { "agents": 0, "backend": 0 }, +"requiresTools": ["example-agent"], +"permissions": ["agents.run", "agents.native", "agents.sessions.read", "backend.launch"], +"activationEvents": ["onAgent:example"], +"agents": [{ + "id": "example", + "displayName": "Example Agent", + "tool": "example-agent", + "native": { "function": "example.launch" }, + "terminal": { "arguments": [] }, + "update": { "arguments": ["update"] }, + "sessionSources": [{ + "id": "projects", + "roots": ["${env:EXAMPLE_HOME}/sessions", "${userHome}/.example/sessions"], + "include": ["**/*.jsonl"], + "format": "jsonLines", + "scan": "example.sessions.scan", + "read": "example.sessions.read" + }] +}] +``` + +### Agent declarations + +| Field | Meaning | +| --- | --- | +| `id` | 1–64 bytes of lowercase ASCII letters, digits and `-`, not starting or ending with `-`; unique in the plugin. | +| `displayName` | 1–64 characters without leading or trailing spaces or control characters. | +| `icon` | Optional [UI icon](#ui-icons). | +| `tool` | One of the plugin's `requiresTools`: the only executable any form of the agent runs. The host discovers it and probes its version like any other tool, so a session always runs the CLI the user installed, never a path the plugin chooses. | +| `native` | `{function, timeoutMilliseconds?}`: a [native session](#native-sessions). `function` is a backend function that answers the command line; Core waits `timeoutMilliseconds` (1000–120000, default 15000) for it. | +| `acp` | `{arguments}`: runs `tool` with these arguments as an Agent Client Protocol server. See [Limits of version 0](#limits-of-version-0). | +| `terminal` | `{arguments}`: runs `tool` with these arguments in a host terminal, the CLI's own interactive interface. | +| `update` | `{arguments}`, nonempty: runs `tool` with these arguments to update the CLI, after the user confirms. A CLI without a self-update command declares none. | +| `sessionSources` | Up to four [session sources](#session-records): where the CLI keeps its session files and the backend functions that parse them. | + +- A plugin declares at most eight agents; the host shows them sorted by + `id`. Each agent declares at least one of `native`, `acp` and `terminal`. +- `acp`, `terminal` and `update` hold at most 64 arguments of at most 4 KiB + each, without NUL. Arguments are fixed: they take no templates. +- A function ID is dot-separated lowerCamelCase segments, as in + [plugin functions](#plugin-functions). `native` and `sessionSources` are + served by the plugin backend, so they need `backend`. +- Every rejection is `plugin.manifest.invalid` with `field` naming the + place, such as `agents[0].tool` or `agents[0].sessionSources[1].include[0]`. + +The install review lists one program per form: `kind: "agent"` with +`agentID`, `tool`, `form` (`native`, `acp`, `terminal` or `update`), and +`launchFunction` for `native` or the fixed `arguments` otherwise; and one +`kind: "agentSessions"` entry per source with `agentID`, `tool`, `source`, +`roots` and `include`, so the user sees every directory the plugin asks to +read before installing it. + +### Agent permissions and activation + +| Permission | Required when | Grants | +| --- | --- | --- | +| `agents.run` | `agents` is not empty | Core may run each agent's tool in the declared forms, after the user starts a session or confirms an update | +| `agents.native` | an agent declares `native` | `lithe/host/agents/write`, `lithe/host/agents/report` and the `lithe/host/agents/did*` notifications, only for the plugin's own sessions | +| `agents.sessions.read` | an agent declares `sessionSources` | after the user consents, Core reads the declared session files and the backend parses them | +| `agents.usage.read` | the backend sums agent usage; needs `backend` | `lithe/host/agents/usage`: numbers and model names of the agents the user enabled, no conversation text, titles, session IDs or directories | + +A missing permission is `plugin.permission.undeclared`; a permission no +agent needs is `plugin.manifest.invalid` (`" is declared, but no +agent needs it."`). `agents.usage.read` is the exception, since a plugin +without agents of its own may read the totals. Every agent that declares +`native` or `sessionSources` needs the activation event `onAgent:`, and +the event is refused for an agent that needs no backend +(`plugin.activation.invalid` either way): a terminal-only or +ACP-only agent runs only its tool, and a plugin of such agents alone needs no +`backend`. `onAgent:` is one of the ways a +[backend](#backend-lifecycle-and-workspace-contexts) starts: the host starts +the backend before it starts a native session of the agent or syncs its +records. + +### Host commands + +The host loads every installed plugin with `agents.configure { plugins: +[{manifest, grantedPermissions}] }` (at most 1024), again whenever a plugin +is installed, updated, enabled, disabled, removed or its grants change. Core +validates each manifest itself, keeps the grants the manifest declares, and +answers `{agents, rejected: [{pluginID, code, message}]}`. `agents.catalog` +answers `{agents}` again. Each entry is `{pluginID, agentID, displayName, +tool, modes, forms, readsSessions, mayRun, mayReadSessions, icon?, +terminalArguments?, update?, sessionRootVariables?}`: `modes` lists +`native` and `acp`, `forms` lists `conversation` and `terminal`, and +`sessionRootVariables` names the environment variables the roots read. + +| Command | Payload | Result | +| --- | --- | --- | +| `agents.start` | `{pluginID, agentID, cwd, toolPath, rootURI?, resume?, workspaceTrusted, environment}` | `{session, mode: "native"}` | +| `agents.prompt` | `{session, text}` | `{turn}` | +| `agents.cancel` | `{session}` | `{turn}` | +| `agents.respondPermission` | `{session, permission, option}` | `{turn}` | +| `agents.close` | `{session}` | `{}` | +| `agents.sessions` | `{}` | `{sessions}`: the live sessions | +| `agents.waitEvents` | `{after?, timeoutMilliseconds?, limit?}` | `{events: [{sequence, session, event}], next, missed}` | + +- `agents.start`, `agents.prompt` and `agents.respondPermission` run only + for a request whose origin is the user (`agents.userActionRequired`): a + plugin cannot start a session, send a prompt or answer a permission + request. +- `agents.start` refuses, in this order: a request not from the user; a + remote workspace (`agents.remoteWorkspace`); an untrusted one + (`agents.untrustedWorkspace`); an agent no configured plugin declares + (`agents.unknownAgent`); a plugin not granted `agents.run` + (`agents.runNotGranted`); an agent without `native` + (`agents.noNativeMode`); a fifth live session of the agent + (`agents.tooManySessions`); a `cwd` that is not an existing absolute + directory (`agents.invalidDirectory`); a `toolPath` that is not an + executable file (`agents.toolNotFound`); a malformed `environment` + (`agents.invalidEnvironment`); a `resume` outside 1–1024 bytes + (`agents.invalidResume`); and a backend that is not running + (`agents.backendUnavailable`). +- `toolPath` is the host's resolution of the agent's `tool`; Core never + takes an executable from the plugin. `environment` is the environment the + host gives tools (at most 256 variables; a name is 1–256 bytes without `=` + or NUL, a value at most 32 KiB without NUL). The backend cannot add to it. +- `agents.prompt` takes 1 byte to 1 MiB of text and refuses a second turn + while one runs (`agents.invalidPrompt`, `agents.turnInProgress`); + `agents.cancel` refuses when no turn runs (`agents.noTurnInProgress`); + `agents.respondPermission` refuses a request that is not pending or an + option it does not offer (`agents.permissionNotPending`, + `agents.unknownPermissionOption`). A prompt, cancel or answer the backend + does not take is `agents.backendUnavailable`. An unknown session is + `agents.unknownSession`. +- `agents.close` closes the CLI's standard input and ends the process after + three seconds. +- `agents.waitEvents` waits at most `timeoutMilliseconds` (default 0, at + most 30000) for events after `after` and returns at most `limit` (default + 256, at most 512). Core keeps the latest 8192 events; `missed` counts those + dropped before the host read them. The host calls it off its UI thread. + +The `terminal` form needs no command: the host runs `toolPath` with +`terminalArguments` in its own terminal, in the workspace directory, with +the same trust and remote checks. `update` runs `toolPath` with the update +arguments in a host terminal after the user confirms the command line. + +### Native sessions + +A native session runs the CLI's own machine interface, such as a JSON-lines +stream on standard input and output. Core starts and owns the process; the +plugin backend only translates between the CLI's lines and Lithe's events: + +1. Core calls `native.function` through `lithe/function/invoke` with params + `{agentID, cwd, resume?}`. The backend answers `{executable: {kind: + "tool", tool}, arguments}`: `tool` must be the agent's `tool`, and + `arguments` holds at most 1024 strings of at most 32 KiB without NUL. An + answer with `environment` or `env` is `plugin.agents.launchEnvironment`, + another tool is `plugin.agents.undeclaredTool`, any other malformed + answer is `plugin.agents.invalidLaunch`; a function that fails or times + out is `agents.launchFailed` or `agents.launchTimeout`. The launch carries + no environment, so a plugin cannot redirect the CLI's model traffic or + inject credentials. +2. Core starts `toolPath` with the arguments in `cwd` and the host's + environment (`agents.processStartFailed` when it cannot), then sends + `lithe/host/agents/didStart`. If the backend does not take it, Core ends + the process and refuses with `agents.backendUnavailable`. +3. Core forwards each line the CLI writes to standard output with + `didOutput`; the backend translates them and reports events with + `lithe/host/agents/report`. It writes to the CLI's standard input with + `lithe/host/agents/write`. +4. A prompt, cancel or permission decision of the user reaches the backend + as `didPrompt`, `didCancel` or `didDecidePermission`; the backend writes + what the CLI expects. `didExit` follows the end of the process. + +Notifications Core sends (the host may not send them): + +| Notification | Params | +| --- | --- | +| `lithe/host/agents/didStart` | `{session, agentID, cwd, resume?}` | +| `lithe/host/agents/didOutput` | `{session, lines}` | +| `lithe/host/agents/didPrompt` | `{session, turn, text}` | +| `lithe/host/agents/didCancel` | `{session, turn}` | +| `lithe/host/agents/didDecidePermission` | `{session, turn, permission, option}` | +| `lithe/host/agents/didExit` | `{session, exitCode?}` | + +- `didOutput` carries at most 64 lines or 4 MiB per notification, in order. + A line longer than 16 MiB is dropped and the host receives the event + `outputLineDropped`; a notification the backend does not take ends the + session as failed. +- `didExit` is not sent when the session ended because the backend did. + +Host methods the backend sends (service `agents`; Core answers them, the +host never sees them): + +| Method | Permission | Params | Result | +| --- | --- | --- | --- | +| `lithe/host/agents/write` | `agents.native` | `{session, lines}` | `{}` | +| `lithe/host/agents/report` | `agents.native` | `{session, events}` | `{}` | +| `lithe/host/agents/usage` | `agents.usage.read` | `{sinceMs?, untilMs?, groupBy, utcOffsetSeconds?}` | `{sinceMs, untilMs, summaries, rateLimits}` | + +- `write` takes 1–256 lines of at most 16 MiB together, none with a line + break; Core adds the newline. More than 64 writes waiting for the CLI is + `-32014`; a session that ended, or one another backend owns, is `-32016`. +- `report` takes exactly `session` and 1–256 `events`. The events are + checked together: when one is refused, none is applied (`-32602`). An + event of a turn that is not the active one is `-32019`; more than 16 + pending permission requests is `-32014`. +- `usage` sums the [session records](#session-records) of the agents whose + records the user enabled, grouped by `day`, `agent` or `model`, between + `sinceMs` and `untilMs` (default the 30 days before tomorrow, at most 366 + days; `utcOffsetSeconds` within ±14 hours sets the day boundary). + `rateLimits` holds the latest quota windows of the agents the user may run + or read. While the records are being written the answer is `-32020`; before + they are opened, `-32601`; a failed read, `-32603`. It never carries + conversation text, titles, session IDs or working directories. +- Other refusals follow [Host services](#host-services): an ungranted + method is `-32010`, malformed params `-32602`. + +Session events (`report`'s `events[]`, each tagged by `kind`): + +| Kind | Fields | +| --- | --- | +| `session` | `agentSessionID, model?, effort?, agentVersion?`: the CLI's own session, for resume and the records | +| `message` | `turn, role` (`assistant` or `thought`), `messageID, text, delta`: `delta: true` appends `text` to the message | +| `toolCall` | `turn, toolCallID, status` (`pending`, `inProgress`, `completed`, `failed`), `toolKind?` (`read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `other`), `title?, locations?` (at most 64 `{path, line?}`), `diff?` (`{path, oldText?, newText}`), `output?` | +| `plan` | `turn, entries`: at most 256 `{content, status}` | +| `permissionRequested` | `turn, permission, title, toolCallID?, options`: 1–8 `{id, label, optionKind}` with unique IDs, `optionKind` one of `allowOnce`, `allowAlways`, `rejectOnce`, `rejectAlways` | +| `usage` | `turn?, model?, tokens, contextUsed?, contextWindow?, costUsd?` (finite, not negative) | +| `rateLimits` | `windows`: 1–8 `{id, label?, usedPercent (0–100), windowMinutes?, resetsAtMs?}`, `plan?` | +| `turnEnded` | `turn, reason` (`completed`, `cancelled`, `maxTokens`, `maxTurns`, `refused`, `failed`), `message?` | +| `notice` | `level` (`info`, `warning`, `error`), `text, code?` | + +- Labels and IDs are 1 byte to 1 KiB; texts at most 1 MiB. +- `message`, `toolCall`, `plan`, `permissionRequested` and `turnEnded` name + the active turn; a `usage` turn is at most the latest one. `turnEnded` + ends the turn and drops its pending permission requests. +- Only the user answers a permission request, with one of its options. + Core sends the decision to the backend; the backend never decides. + +Besides the backend's events, `agents.waitEvents` carries Core's own: +`started {pluginID, agentID, mode, resume?}`, `turnStarted {turn}`, +`permissionDecided {turn, permission, option}`, `outputLineDropped`, a +`turnEnded` with reason `failed` when `didPrompt` cannot be delivered, and +`exited {reason, exitCode?, stderrTail?}`, where `reason` is `exited`, +`closed`, `failed` or `backendEnded` and `stderrTail` is the last 8 KiB the +CLI wrote to standard error. + +### Session records + +An agent's CLI keeps its sessions in its own files. `sessionSources` lets +Lithe list, search and sum them without the CLI running: + +| Field | Meaning | +| --- | --- | +| `id` | Source ID, as an agent ID; unique in the agent. | +| `roots` | 1–4 candidates. Each starts with `${userHome}` or `${env:NAME}` (`NAME` is 1–64 uppercase ASCII letters, digits and `_`, not starting with a digit) and continues with relative segments without `.`, `..`, `$`, `\` or NUL. The first candidate whose variable resolves to a nonempty value is the root. | +| `include` | 1–16 root-relative glob patterns without `..`. Only matching regular files are read; symbolic links are not followed. | +| `format` | `jsonLines`: one JSON value per line. | +| `scan` | Backend function that turns new lines of one file into records. | +| `read` | Backend function that turns recorded ranges into titles or messages. | + +- Nothing is read before the user consents. The host grants + `agents.sessions.read` only after the user enables the plugin's records, + and syncs only the agents the user enabled. Core reads the files; the + backend sees only the lines Core hands it. +- The host opens the cache with `agentSessions.configure {cacheDirectory, + userHome, environment?, pricesFile?}`. `cacheDirectory` is a writable + platform cache directory, never in the package or the installation. The + answer reports `pricedModels` or `pricesError`. +- `agentSessions.sync {pluginID, agentID}` reads the files that changed since + the last sync and answers the counts, `truncatedSources` and + `unreadableEntries`. Lines reach `scan` in chunks of at most 4 MiB; a line + longer than 16 MiB is skipped. `agentSessions.forget {pluginID, agentID}` + drops the agent's records and answers `{files}`. +- `agentSessions.list {agents?, cwd?, activeSinceMs?, offset, limit, + titles}` (at most 500), `agentSessions.search {text, agents?, sessionID?, + limit}` (at most 200), `agentSessions.read {agent, path, range}` and + `agentSessions.stats {agents?, sessionID?, sinceMs?, untilMs?, groupBy, + utcOffsetSeconds}` serve the host's own views; `agent` is + `/`, and `stats` groups by `day`, `agent`, `model`, + `session` or `cwd`. + +`scan` receives `{agentID, sourceID, path, lines: [{offset, length, text}], +state?}` and has 30 seconds. It answers: + +- `sessions`: `{sessionID, parentSessionID?, cwd?, startedAtMs?, + updatedAtMs?, agentVersion?, titleRange?}`; +- `calls`: one per model call, `{key, sessionID, threadID?, startedAtMs, + requestedModel?, model?, contextWindow?, effort?, provider?, tokens: + {input?, output?, cacheRead?, cacheWrite5m?, cacheWrite1h?, reasoning?}, + firstTokenMs?, durationMs?, compaction, requestID?, errorCategory?, range: + {start, end}}`, `key` unique in the file; +- `spans`: `{sessionID, atMs?, range, text}`, the searchable text, of which + Core indexes at most 256 KiB per span; +- `state`: at most 64 KiB the next scan of the file receives, never + conversation text; +- `rateLimits`: `{atMs, windows, plan?}`, the latest quota the file shows. + +`read` receives `{agentID, sourceID, mode, items: [{path, lines}]}` and has +15 seconds. It answers exactly `{items}`, one per request item: in `titles` +mode `{title}` (cut to 512 bytes), in `messages` mode `{messages}`, at most +2048 `{role, text, atMs?, toolName?}` with `role` one of `user`, +`assistant`, `thought` and `tool`, `text` at most 1 MiB and `toolName` 1–256 +bytes. + +A summary is `{key, calls, failedCalls, compactionCalls, tokens: {input, +output, cacheRead, cacheWrite5m, cacheWrite1h, reasoning}, cacheHitRate?, +cost?, firstStartedAtMs, lastStartedAtMs}`. `key` is `{kind: "day", date}`, +`{kind: "agent", agent}`, `{kind: "model", model?}`, `{kind: "session", +agent, sessionID}` or `{kind: "cwd", cwd?}`. `cost` is `{usd, basis: +"apiPriceEquivalent", pricedCalls, unpricedCalls, approximateCalls}`: what +the tokens would cost at the API prices of `pricesFile`, not what the user +paid. Rate limits are `{atMs, windows, plan?, pluginID, agentID}`; Core keeps +the latest per agent in `rate-limits.json` in the cache directory. + +`agentSessions.*` refusals: `agentSessions.notConfigured`, +`agentSessions.invalidDirectory`, `agentSessions.invalidEnvironment`, +`agentSessions.unknownAgent`, `agentSessions.outsideSources` (a read path not +under the agent's roots), `agentSessions.discoveryFailed`, +`agentSessions.backendUnavailable`, `agentSessions.scanFailed`, +`agentSessions.invalidScan`, `agentSessions.readFailed`, +`agentSessions.invalidRead` and `agentSessions.invalidGroup`. + +### Privacy and logging + +- Core and the host log only session IDs, plugin and agent IDs, counts, + durations and outcomes. Prompts, messages, tool arguments and output, CLI + output, titles, accounts and credentials are never logged. +- No part of the contract reads a CLI's credential files. A backend that + reads them is outside the contract; the review lists every directory a + source reads. +- A plugin never learns another plugin's sessions. `usage` gives a plugin + without agents of its own numbers and model names only. + +### Limits of version 0 + +- `acp` is validated, listed in the review and in the catalog's `modes`, but + version 0 of Core runs no Agent Client Protocol client: `agents.start` of + an agent without `native` is `agents.noNativeMode`. An agent that offers + only ACP today should also declare `terminal`. +- Sessions run only in trusted local workspaces. + ## Project generators `projectGenerators` (requires `projectGenerators: 0` in `requires` and the @@ -5601,6 +5956,9 @@ command payload is a Core `invalid_request` failure instead. | `plugin.launch.invalidRequest` | Core | A launch plan request has an unusable directory or an unknown architecture | | `plugin.launch.untrustedWorkspace` | Core | The process would run project code and the user has not trusted the workspace; see [Workspace trust](#workspace-trust) | | `plugin.launch.notBackend` | Core | `decodeLaunch` named a language server that the plugin backend does not launch | +| `plugin.agents.launchEnvironment` | Core | An agent's native launch function answered environment variables (`environment` or `env`) | +| `plugin.agents.undeclaredTool` | Core | An agent's native launch function answered a tool other than the agent's `tool` | +| `plugin.agents.invalidLaunch` | Core | An agent's native launch function answered another malformed command line | | `plugin.launch.invalidResult` | Core | A [backend-resolved launch](#backend-resolved-launch) answer is malformed, unknown in a field, or over a bound | | `plugin.launch.outsidePackage` | Core | The answer's packaged executable leaves the plugin package | | `plugin.launch.undeclaredTool` | Core | The answer's tool is not one of the plugin's tool definitions | diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json new file mode 100644 index 00000000..7c0e5b45 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -0,0 +1,73 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.agents", + "displayName": "Agents", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": { + "agents": 0, + "backend": 0 + }, + "requiresTools": [ + "example-agent" + ], + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "agents.native", + "agents.run", + "agents.sessions.read", + "agents.usage.read", + "backend.launch" + ], + "activationEvents": [ + "onAgent:example" + ], + "languages": [], + "agents": [ + { + "id": "example", + "displayName": "Example Agent", + "tool": "example-agent", + "native": { + "function": "example.launch", + "timeoutMilliseconds": 20000 + }, + "terminal": { + "arguments": [] + }, + "update": { + "arguments": [ + "update" + ] + }, + "sessionSources": [ + { + "id": "projects", + "roots": [ + "${env:EXAMPLE_HOME}/sessions", + "${userHome}/.example/sessions" + ], + "include": [ + "**/*.jsonl" + ], + "format": "jsonLines", + "scan": "example.sessions.scan", + "read": "example.sessions.read" + } + ] + } + ], + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/backend" + }, + "arguments": [ + "--stdio" + ] + } +} diff --git a/shared/plugins/contract/v1/fixtures/agents/terminal-agent.plugin.json b/shared/plugins/contract/v1/fixtures/agents/terminal-agent.plugin.json new file mode 100644 index 00000000..a678b47c --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/terminal-agent.plugin.json @@ -0,0 +1,35 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.terminal-agent", + "displayName": "Terminal agent", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": { + "agents": 0 + }, + "requiresTools": [ + "example-agent" + ], + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "agents.run" + ], + "activationEvents": [], + "languages": [], + "agents": [ + { + "id": "example", + "displayName": "Example Agent", + "tool": "example-agent", + "terminal": { + "arguments": [ + "--interactive" + ] + } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index dbecee8d..849134f6 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -972,6 +972,29 @@ {"name": "a download mirror differs from the primary URL", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/mirrors", "value": ["https://downloads.example.org/sample-lldb/1.2.3/sample-lldb-darwin-arm64.zip"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].mirrors[0]"}, {"name": "a download archive pins its SHA-256 digest", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/sha256", "value": "2f114a99"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].sha256"}, {"name": "a download archive is zip or tar.gz", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/0/archive", "value": "7z"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[0].archive"}, - {"name": "a download strip prefix stays inside the archive", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/1/stripPrefix", "value": "../sample-lldb"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[1].stripPrefix"} + {"name": "a download strip prefix stays inside the archive", "base": "command-installer-download.plugin.json", "edits": [{"op": "set", "path": "/commandInstallers/0/download/artifacts/1/stripPrefix", "value": "../sample-lldb"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "commandInstallers[0].download.artifacts[1].stripPrefix"}, + {"name": "agents need requires.agents", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/requires/agents"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "agents need agents.run", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "a native agent needs agents.native", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.run", "agents.sessions.read", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "session sources need agents.sessions.read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run", "agents.usage.read", "backend.launch"]}], "expectedCode": "plugin.permission.undeclared", "expectedField": "permissions"}, + {"name": "agents.native without a native agent", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "permissions"}, + {"name": "agents.sessions.read without a session source", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["agents.run", "agents.sessions.read"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "permissions"}, + {"name": "an agent runs one of the required tools", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/tool", "value": "other-agent"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].tool"}, + {"name": "an agent ID is lowercase", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/id", "value": "Example"}, {"op": "set", "path": "/activationEvents", "value": ["onAgent:Example"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].id"}, + {"name": "an agent ID does not end with a hyphen", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/id", "value": "example-"}, {"op": "set", "path": "/activationEvents", "value": ["onAgent:example-"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].id"}, + {"name": "an agent display name has no surrounding spaces", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/displayName", "value": " Example"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].displayName"}, + {"name": "an agent declares a form", "base": "terminal-agent.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/terminal"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0]"}, + {"name": "a native launch timeout is at least one second", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/native/timeoutMilliseconds", "value": 500}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].native.timeoutMilliseconds"}, + {"name": "a native launch function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/native/function", "value": "Example Launch"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].native.function"}, + {"name": "an update declares arguments", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/update/arguments", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].update.arguments"}, + {"name": "a declared argument has no NUL", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/terminal/arguments", "value": ["a\u0000b"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].terminal.arguments"}, + {"name": "a session root starts with a variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/roots", "value": ["/var/sessions"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].sessionSources[0].roots[0]"}, + {"name": "a session root does not leave its variable", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/roots", "value": ["${userHome}/../sessions"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].sessionSources[0].roots[0]"}, + {"name": "a session include pattern stays in the root", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/include", "value": ["../**/*.jsonl"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].sessionSources[0].include[0]"}, + {"name": "a session source format is jsonLines", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/sessionSources/0/format", "value": "json"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a native agent needs a backend", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/backend"}, {"op": "remove", "path": "/requires/backend"}, {"op": "set", "path": "/permissions", "value": ["agents.native", "agents.run", "agents.sessions.read", "agents.usage.read"]}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a backend agent declares onAgent", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/activationEvents", "value": []}], "expectedCode": "plugin.activation.invalid", "expectedField": "activationEvents"}, + {"name": "a terminal-only agent declares no onAgent", "base": "terminal-agent.plugin.json", "edits": [{"op": "set", "path": "/activationEvents", "value": ["onAgent:example"]}], "expectedCode": "plugin.activation.invalid", "expectedField": "activationEvents"}, + {"name": "an agent field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/environment", "value": {"EXAMPLE": "1"}}], "expectedCode": "plugin.manifest.invalid"} ] } diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 679257d1..28366284 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -7,6 +7,10 @@ "additionalProperties": false, "required": ["schemaVersion", "id", "displayName", "version", "pluginAPIVersion", "requires", "vendor"], "allOf": [ + {"if": {"required": ["agents"]}, "then": {"required": ["permissions", "requiresTools"], "properties": {"requires": {"required": ["agents"]}, "permissions": {"contains": {"const": "agents.run"}}}}}, + {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["native"]}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}, "permissions": {"contains": {"const": "agents.native"}}}}}, + {"if": {"required": ["agents"], "properties": {"agents": {"contains": {"required": ["sessionSources"]}}}}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["backend"]}, "permissions": {"contains": {"const": "agents.sessions.read"}}}}}, + {"if": {"required": ["permissions"], "properties": {"permissions": {"contains": {"const": "agents.usage.read"}}}}, "then": {"required": ["backend"]}}, {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["runConfigurationTypes"]}}}}, "then": {"properties": {"requires": {"required": ["runConfigurationTypes"]}}}}, @@ -33,6 +37,7 @@ "minProperties": 1, "additionalProperties": false, "properties": { + "agents": { "description": "Required exactly when agents is non-empty: agent command-line tools Core runs in the declared forms after the user starts a session, native sessions the backend translates, and session records Core reads after the user consents (plan API-45). Version 0 validates acp but runs no Agent Client Protocol client.", "enum": [0] }, "backend": { "description": "Required exactly when backend is present: the plugin's own process. It serves its web pages, may also start on onWorkspaceOpen or a plugin command, receives workspace contexts through the litheFunctions protocol, and may be granted workspace.metadata.", "enum": [0] }, "beforeLaunchTasks": { "description": "Required exactly when any buildSystems[].beforeLaunchTasks is non-empty: kinds of step a run configuration's Before Launch list runs first, offered in its Add New Task menu, drawn from declared fields and run through a declared command line. Needs buildSystems.", "enum": [0] }, "buildModelInputs": {"description": "Optional public model sharing between already enabled workspace plugins; no installation, private function, or process authority. Required exactly when modelSharing or modelInputs is used. Consumers require buildProviders. A producer cannot also consume inputs.", "enum": [0]}, @@ -102,14 +107,14 @@ "languageServer.request", "documents.contentProvider", "documents.save", - "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "network.request"] } + "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "network.request", "agents.run", "agents.native", "agents.sessions.read", "agents.usage.read"] } }, "activationEvents": { "type": "array", "items": { "type": "string", - "description": "onWorkspaceOpen names no ID and needs requires.backend; it starts the backend once a workspace is open.", - "pattern": "^((onLanguage|onRun|onTest|onView|onCommand|onBuildSystem|onVcsRoot|onDebug):[a-z0-9.+_-]+|onWorkspaceOpen)$" + "description": "onWorkspaceOpen names no ID and needs requires.backend; it starts the backend once a workspace is open. onAgent: starts the backend for an agent that declares native or sessionSources, and only for one.", + "pattern": "^((onLanguage|onRun|onTest|onView|onCommand|onBuildSystem|onVcsRoot|onDebug|onAgent):[a-z0-9.+_-]+|onWorkspaceOpen)$" } }, "toolDefinitions": { "type": "array", "minItems": 1, "maxItems": 32, "items": { "$ref": "#/$defs/toolchainToolDefinition" } }, @@ -130,6 +135,13 @@ }, "toolchainProviders": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "$ref": "#/$defs/toolchainProvider" } }, "keymapImportProviders": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "$ref": "#/$defs/keymapImportProvider" } }, + "agents": { + "description": "requires.agents and agents.run: agent command-line tools the plugin drives (plan API-45). IDs are unique; the host shows the agents sorted by ID.", + "type": "array", + "minItems": 1, + "maxItems": 8, + "items": { "$ref": "#/$defs/agent" } + }, "pluginFunctions": { "$ref": "#/$defs/pluginFunctions" }, "languages": { "type": "array", @@ -313,6 +325,180 @@ } }, "$defs": { + "agentID": { + "description": "Agent or session-source ID: lowercase ASCII letters, digits and hyphens, not starting or ending with a hyphen.", + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?![\\s\\S])" + }, + "agentArguments": { + "description": "Fixed arguments of the agent's tool, without templates. Each is at most 4 KiB, without NUL.", + "type": "object", + "additionalProperties": false, + "required": [ + "arguments" + ], + "properties": { + "arguments": { + "type": "array", + "maxItems": 64, + "items": { + "type": "string", + "maxLength": 4096, + "pattern": "^[^\\u0000]*(?![\\s\\S])" + } + } + } + }, + "agent": { + "description": "One agent command-line tool. It declares at least one of native, acp and terminal. native and sessionSources are served by the plugin backend and need the activation event onAgent:.", + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "displayName", + "tool" + ], + "anyOf": [ + { + "required": [ + "native" + ] + }, + { + "required": [ + "acp" + ] + }, + { + "required": [ + "terminal" + ] + } + ], + "properties": { + "id": { + "$ref": "#/$defs/agentID" + }, + "displayName": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^\\S(?:[^\\u0000-\\u001f\\u007f]*\\S)?(?![\\s\\S])" + }, + "icon": { + "$ref": "#/$defs/uiIcon" + }, + "tool": { + "description": "One of requiresTools: the only executable any form of the agent runs. The host resolves it; the plugin never names a path.", + "$ref": "#/$defs/toolchainToolID" + }, + "native": { + "description": "A native session: Core calls function, a backend function, for the command line ({executable: {kind: tool, tool}, arguments}, no environment), starts the tool itself, and relays its standard input and output through the backend. Needs agents.native.", + "type": "object", + "additionalProperties": false, + "required": [ + "function" + ], + "properties": { + "function": { + "$ref": "#/$defs/pluginFunctionID" + }, + "timeoutMilliseconds": { + "type": "integer", + "minimum": 1000, + "maximum": 120000, + "default": 15000 + } + } + }, + "acp": { + "description": "Runs the tool with these arguments as an Agent Client Protocol server. Version 0 lists the mode but runs no ACP client.", + "$ref": "#/$defs/agentArguments" + }, + "terminal": { + "description": "Runs the tool with these arguments in a host terminal: the CLI's own interactive interface.", + "$ref": "#/$defs/agentArguments" + }, + "update": { + "description": "Runs the tool with these arguments to update the CLI, after the user confirms the command line.", + "allOf": [ + { + "$ref": "#/$defs/agentArguments" + }, + { + "properties": { + "arguments": { + "minItems": 1 + } + } + } + ] + }, + "sessionSources": { + "description": "Where the CLI keeps its session files. Core reads them only after the user consents; needs agents.sessions.read.", + "type": "array", + "minItems": 1, + "maxItems": 4, + "items": { + "$ref": "#/$defs/agentSessionSource" + } + } + } + }, + "agentSessionSource": { + "description": "One directory of an agent's session files and the backend functions that parse them.", + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "roots", + "include", + "format", + "scan", + "read" + ], + "properties": { + "id": { + "$ref": "#/$defs/agentID" + }, + "roots": { + "description": "Root candidates; the first whose variable resolves is the root. Each starts with ${userHome} or ${env:NAME} (NAME: uppercase letters, digits and _, not starting with a digit) and continues with relative segments without . or ..", + "type": "array", + "minItems": 1, + "maxItems": 4, + "items": { + "type": "string", + "pattern": "^(?:\\$\\{userHome\\}|\\$\\{env:[A-Z_][A-Z0-9_]{0,63}\\})(?:/(?!\\.\\.?(?:/|$))[^/$\\\\\\u0000]*)*(?![\\s\\S])" + } + }, + "include": { + "description": "Root-relative glob patterns of the files to read, without ..", + "type": "array", + "minItems": 1, + "maxItems": 16, + "items": { + "type": "string", + "minLength": 1, + "not": { + "pattern": "(?:^|/)\\.\\.(?:/|$)" + } + } + }, + "format": { + "const": "jsonLines" + }, + "scan": { + "description": "Backend function that turns new lines of one file into records.", + "$ref": "#/$defs/pluginFunctionID" + }, + "read": { + "description": "Backend function that turns recorded ranges into titles or messages.", + "$ref": "#/$defs/pluginFunctionID" + } + } + }, "pluginView": { "description": "A plugin view: the host calls function, one of the plugin's own plugin functions, with each view event and draws the view or patches it returns (plugin-ui.schema.json). Needs a backend.", "type": "object", diff --git a/shared/plugins/guides/plugin-api-pr-guide.zh-CN.md b/shared/plugins/guides/plugin-api-pr-guide.zh-CN.md index fabbba9a..b3461654 100644 --- a/shared/plugins/guides/plugin-api-pr-guide.zh-CN.md +++ b/shared/plugins/guides/plugin-api-pr-guide.zh-CN.md @@ -1,6 +1,6 @@ # 为插件扩展公共 API:PR 提交指南 -当新插件需要的能力在现有接口中找不到时,先调查已有 API,再提出最小的公共扩展。**API-01–44 划分领域,允许在领域内持续增加方法、通知、可选字段和声明;它们不是封闭的方法清单。先复用已有能力,缺什么就补到合适的领域中。** +当新插件需要的能力在现有接口中找不到时,先调查已有 API,再提出最小的公共扩展。**API-01–45 划分领域,允许在领域内持续增加方法、通知、可选字段和声明;它们不是封闭的方法清单。先复用已有能力,缺什么就补到合适的领域中。** **允许扩展不等于允许升版。** 插件、语言服务器、构建工具等特有需求,不得提升任何系统 API 版本。只有公共、非特有的接口发生变化,才具备讨论升版的条件;能兼容扩展的仍不升版。 @@ -21,7 +21,7 @@ | [专题指南](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/shared/plugins/guides)、[官方 SDK](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/shared/plugins/sdk) | 查当前推荐用法及 SDK 的实际支持范围 | | [日志目录与脱敏规则](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/logging/README.md)、[插件日志协议](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/shared/plugins/contract/v1/README.md#structured-plugin-diagnostics) | 查统一日志接入、字段语义、记录责任和敏感信息处理 | -API-01–44 是 **44 类规划能力**,既不是 44 个方法,也不是 44 个已经全部实现的 API。一个分类可以逐步增加多个方法,当前总表未列出的方法也可以通过 PR 补充;不要因为它尚未列出就判定“不允许”。历史实施计划中的版本和完成状态不能代替当前契约与运行时能力发现。 +API-01–45 是 **45 类规划能力**,既不是 45 个方法,也不是 45 个已经全部实现的 API。一个分类可以逐步增加多个方法,当前总表未列出的方法也可以通过 PR 补充;不要因为它尚未列出就判定“不允许”。历史实施计划中的版本和完成状态不能代替当前契约与运行时能力发现。 ## 2. 先复用,缺口在所属领域扩展 @@ -35,7 +35,7 @@ API-01–44 是 **44 类规划能力**,既不是 44 个方法,也不是 44 复用必须符合语义。例如语言服务器接入归 API-25,构建、测试和运行准备归 API-29,调试适配器归 API-30;HTTP 文档旁绑定插件函数的按钮属于 API-27 编辑器动作。按下“运行”图标本身,不要求插件成为构建提供者。 -新方法归入现有 API-01–44 中合适的一类;确实不属于任何编号时标 `—` 并解释原因,**不得自行编出 API-45**。先查 [Core Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 和 [现有 PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pulls),避免重复实现。 +新方法归入现有 API-01–45 中合适的一类;确实不属于任何编号时标 `—` 并解释原因,**不得自行编出 API-46 等新编号**。先查 [Core Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 和 [现有 PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pulls),避免重复实现。 ## 3. API 版本怎么处理 @@ -135,7 +135,7 @@ PR 必须逐项回答: | --- | --- | --- | ``` -编号使用 API-01–44;没有对应项写 `—`。方法名写真实协议名,通知也要列出,不能只写“补了构建 API”作为整组概括。 +编号使用 API-01–45;没有对应项写 `—`。方法名写真实协议名,通知也要列出,不能只写“补了构建 API”作为整组概括。 ## 8. 日志、错误码和四语 SDK 的交付要求 @@ -212,7 +212,7 @@ node shared/plugins/scripts/sdk-e2e.mjs PR 类型: 用户流程与缺口: -已调查的 API-01–44 分类、现有方法/声明、上游能力,以及无法复用的原因: +已调查的 API-01–45 分类、现有方法/声明、上游能力,以及无法复用的原因: 公共接口如何供第二个语义不同的工具使用: 工具特有知识留在哪个插件或上游: @@ -240,7 +240,7 @@ example 的情况(不要求本次新增,不代替 SDK 实现): ## 11. 交给 AI 开发时,必须附上的约束 -> API-01–44 划分领域,允许在领域内持续扩展,不是封闭的方法清单。先调查并复用现有接口、对应契约和成熟上游;有公共缺口时在所属领域增加方法、通知、可选字段或声明。插件、语言服务器、构建工具等特有需求不得提升任何系统 API 版本,包括单个能力或进程协议,也不得换名绕过。只有公共、非特有的接口变化且无法兼容表达时,才可提出升版方案;可选字段、能力发现等足够时保持现有版本。保留已有 1、2 等版本,按实际用法选择已有最低版本,不强制填 0。不升版也要同步契约、校验、schema、fixture、消费者、SDK、API 登记及相关验证,并说明旧宿主的降级或拒绝行为。 +> API-01–45 划分领域,允许在领域内持续扩展,不是封闭的方法清单。先调查并复用现有接口、对应契约和成熟上游;有公共缺口时在所属领域增加方法、通知、可选字段或声明。插件、语言服务器、构建工具等特有需求不得提升任何系统 API 版本,包括单个能力或进程协议,也不得换名绕过。只有公共、非特有的接口变化且无法兼容表达时,才可提出升版方案;可选字段、能力发现等足够时保持现有版本。保留已有 1、2 等版本,按实际用法选择已有最低版本,不强制填 0。不升版也要同步契约、校验、schema、fixture、消费者、SDK、API 登记及相关验证,并说明旧宿主的降级或拒绝行为。 > 新增 API 必须接入统一日志系统,真实失败能从具体 API、阶段、稳定原因、处理结果及操作 ID 定位,不能只记模糊错误;敏感上下文走共享脱敏并保留允许的定位线索。错误码语义清晰,新增自定义码和业务编号经全插件契约查重,不冲突、不改旧含义。Rust、Go、Node、Java 四个官方 SDK 在同一 Core PR 中补齐接口、数据、通知、错误和日志支持及相关验证;example 可以后补,SDK 支持不能推迟。 diff --git a/shared/plugins/reference/README.md b/shared/plugins/reference/README.md index cd74a8a3..f0a1eaf0 100644 --- a/shared/plugins/reference/README.md +++ b/shared/plugins/reference/README.md @@ -10,7 +10,7 @@ | 想知道 | 看这里 | | --- | --- | -| API-01–44 每一项现在能用什么、还缺什么 | [插件 API 总表](api-catalog.md) | +| API-01–45 每一项现在能用什么、还缺什么 | [插件 API 总表](api-catalog.md) | | `requires` 能力版本、进程协议版本、文档格式版本,以及 Core 和 Lithe 桌面端支持哪些 | [能力与协议版本对照](capabilities-and-versions.md) | | 每个协议、能力和 API 是哪天、哪个 PR 改的 | [插件协议更新记录](protocol-changelog.md)(只有中文) | | 某个功能的字段、宿主现状、契约章节和示例 | 下方的功能页 | @@ -33,6 +33,7 @@ | [版本控制提供者](domains/vcs.md) | VCS 提供者进程和协议 | API-31 | `vcsProviders` | | [项目生成器](domains/project-generators.md) | 新建项目的模板和步骤 | API-33 | `projectGenerators` | | [工具链](domains/toolchains.md) | 工具定义、可执行文件候选、工具链提供者、Core 命令 | API-23 | `toolDefinitions`、`toolchainProviders` | +| [Agent](domains/agents.md) | 用户自己安装的 Agent CLI:原生会话、终端形式、更新命令、会话记录与用量汇总 | API-45 | `agents` | | [快捷键导入](domains/keymap-import.md) | 从其他编辑器导入快捷键的提供者 | 不在编号内 | `keymapImportProviders` | | [包信任](domains/package-trust.md) | 签名要求、签名文件格式、随应用发布的插件 | 不在编号内 | `packageTrust` | | [插件市场](domains/marketplace.md) | 索引来源和格式、可用性判断、安装审查和确认 | 不在编号内 | — | @@ -57,7 +58,7 @@ This directory organizes the plugin contract by feature: what each numbered API | To find | Go to | | --- | --- | -| What each of API-01–44 offers today and what is missing | [Plugin API catalog](api-catalog.md) | +| What each of API-01–45 offers today and what is missing | [Plugin API catalog](api-catalog.md) | | `requires` capability versions, process protocol versions, document format versions, and which of them Core and the Lithe desktop client support | [Capability and protocol versions](capabilities-and-versions.md) | | When, and in which PR, each protocol, capability, and API changed | [Plugin protocol changelog](protocol-changelog.md) (Chinese only) | | A feature's fields, host status, contract sections, and examples | The feature pages below | @@ -80,6 +81,7 @@ This directory organizes the plugin contract by feature: what each numbered API | [VCS providers](domains/vcs.md) | VCS provider processes and protocol | API-31 | `vcsProviders` | | [Project generators](domains/project-generators.md) | New-project templates and steps | API-33 | `projectGenerators` | | [Toolchains](domains/toolchains.md) | Tool definitions, executable candidates, toolchain providers, Core commands | API-23 | `toolDefinitions`, `toolchainProviders` | +| [Agents](domains/agents.md) | Agent CLIs the user installed: native sessions, terminal forms, update commands, session records, and usage totals | API-45 | `agents` | | [Shortcut import](domains/keymap-import.md) | Providers that import shortcuts from other editors | Not numbered | `keymapImportProviders` | | [Package trust](domains/package-trust.md) | Signature requirements, the signature file format, plugins bundled with the application | Not numbered | `packageTrust` | | [Marketplace](domains/marketplace.md) | Index sources and format, availability, install review and confirmation | Not numbered | — | diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 5a63e271..b7dd21f1 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -1,10 +1,10 @@ -# 插件 API 总表(API-01–44) / Plugin API catalog (API-01–44) +# 插件 API 总表(API-01–45) / Plugin API catalog (API-01–45) [中文](#中文) · [English](#english) ## 中文 -Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md)统一编号为 API-01 到 API-44。本页列出每个编号**现在能用什么**、**还没有什么**,并把能用的部分链接到契约章节和功能页。参数、返回值、错误码以 [`contract/v1/README.md`](../contract/v1/README.md) 为准;版本号见[能力与协议版本对照](capabilities-and-versions.md)。内容以本仓库 `main` 上的契约和 Core 源码为准。 +Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md)统一编号为 API-01 到 API-45。本页列出每个编号**现在能用什么**、**还没有什么**,并把能用的部分链接到契约章节和功能页。参数、返回值、错误码以 [`contract/v1/README.md`](../contract/v1/README.md) 为准;版本号见[能力与协议版本对照](capabilities-and-versions.md)。内容以本仓库 `main` 上的契约和 Core 源码为准。 读这张表前先知道三件事: @@ -61,6 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录 | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -76,14 +77,14 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-43 | 保存前事件 | 未做 | 保存前事件,以及有时限的保存前编辑 | | API-44 | Agent 侧贡献 | 未做 | 插件贡献 Skills、Hooks、MCP,并单独审查授权 | -清单、市场、包信任、快捷键导入是安装和打包层面的契约,不在 API-01–44 编号内,见各自的功能页:[清单](domains/manifest.md)、[市场](domains/marketplace.md)、[包信任](domains/package-trust.md)、[快捷键导入](domains/keymap-import.md)。 +清单、市场、包信任、快捷键导入是安装和打包层面的契约,不在 API-01–45 编号内,见各自的功能页:[清单](domains/manifest.md)、[市场](domains/marketplace.md)、[包信任](domains/package-trust.md)、[快捷键导入](domains/keymap-import.md)。 ### 已公开的宿主方法 后端向宿主发送的请求,前缀都是 `lithe/host/`,下表省略前缀。一个 API 编号下可以有多个方法,每个方法单独一行,按 API 编号排列。 - **“API”列是规划编号**,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md),和“协议”列的 `litheFunctions` 版本、清单里的能力版本分开记录。同一个 API 的方法可以分几个 PR 陆续加入;向后兼容地新增方法不升协议版本(见契约 [Extending the host services](../contract/v1/README.md#extending-the-host-services))。每个方法哪天、由哪个 PR 首次加入,见[插件协议更新记录](protocol-changelog.md#宿主方法按-api-编号)。 -- **“协议”列**是方法所属的 `litheFunctions` 版本,现在都是 0。除 `getCapabilities`、`subscriptions/dispose`、`workspace/listContexts`、`credentials/*`、`run/stop`、`functions/providers` 外,其余方法都要带 `context: {contextID, generation}`。`functions/*` 只对声明了至少一个 `calls` 的后端开放;官方 SDK 都已封装 `functions/providers` 和 `functions/invoke`。 +- **“协议”列**是方法所属的 `litheFunctions` 版本,现在都是 0。除 `getCapabilities`、`subscriptions/dispose`、`workspace/listContexts`、`credentials/*`、`run/stop`、`functions/providers`、`agents/*` 外,其余方法都要带 `context: {contextID, generation}`;`agents/*` 改用 `session` 指明会话,由 Core 直接回答,不经过宿主。`functions/*` 只对声明了至少一个 `calls` 的后端开放;官方 SDK 都已封装 `functions/providers` 和 `functions/invoke`。 - **“权限”列**:每个权限都要求清单声明 `backend`(`requires.backend` 为 0),否则安装时拒绝。`functions/*` 没有清单权限,由清单 `pluginFunctions` 段的 `calls` 是否声明了该函数决定。另有两条前置条件:`debug.start` 还要求已声明的 `debugAdapters` 条目;`languageServer.request` 只在某个语言服务器列出 `requestMethods` 或 `forwardNotifications` 时才能声明。 | API | 方法 | 用途 | 权限 | 协议 | @@ -163,8 +164,11 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-35 | `functions/invoke` | 经 Core 调用另一个插件导出的函数,可带 `parentOperationID` 标明所属调用链,返回 `{value}` | 无清单权限,需在 `pluginFunctions.calls` 声明该函数 | 0 | | API-38 | `network/request` | 使用宿主代理策略发送有界 HTTP 请求 | `network.request` | 0 | | API-40 | `workspace/getHostPaths` | 远程上下文的根目录在远端主机上的绝对路径 `hostPath`,可用 `rootIDs` 指定根目录和顺序;只用在远端运行的进程参数、工作目录和语言服务器、调试器配置里;本地上下文返回 `plugin.host.authorityUnsupported` | `workspace.metadata`,单独的方法授权(只有服务授权得到 `permissionDenied`) | 0 | +| API-45 | `agents/write` | 写本插件原生会话里 CLI 的标准输入:1–256 行,合计不超过 16 MiB,不含换行符,由 Core 补上;Core 直接回答 | `agents.native`,单独的方法授权 | 0 | +| API-45 | `agents/report` | 报告本插件原生会话的事件(会话、消息、工具调用、计划、权限请求、用量、额度、回合结束、提示):1–256 个,一起校验,一个被拒就全部不生效;Core 直接回答 | `agents.native`,单独的方法授权 | 0 | +| API-45 | `agents/usage` | 按天、Agent 或模型汇总用户已开启记录的 Agent 的用量,带最近的额度窗口;只有数字和模型名,不含对话正文、标题、会话 ID 和目录;Core 直接回答 | `agents.usage.read`,单独的方法授权 | 0 | -快捷键导入提供者另有 `lithe/host/keymapImport/listInputs`、`lithe/host/keymapImport/readChunk` 两个方法,属于 `litheKeymapImport` 协议,不在 API-01–44 内,见[快捷键导入](domains/keymap-import.md)。 +快捷键导入提供者另有 `lithe/host/keymapImport/listInputs`、`lithe/host/keymapImport/readChunk` 两个方法,属于 `litheKeymapImport` 协议,不在 API-01–45 内,见[快捷键导入](domains/keymap-import.md)。 宿主发给后端的通知(后端不回复),前缀同样是 `lithe/host/`: @@ -176,6 +180,12 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-23 | `run/didExit` | 后端用 `run/start` 启动的运行结束,带 `exitCode` 或 `signal`(宿主丢失进程时两者都没有);每次运行只发一次 | `run.start` | | API-25 | `languageServer/didChangeState` | 本插件某个语言服务器的状态变化(`starting`、`running`、`stopped`、`crashed`),带 `generation` | `languageServer.request` | | API-25 | `languageServer/didReceiveNotification` | 转发服务器发出、`forwardNotifications` 列出的通知;超过 `limits.notificationBytes` 时只送一次 `truncated: true`,不带 `params` | `languageServer.request` | +| API-45 | `agents/didStart` | Core 为本插件启动了一个原生会话,带 `session`、`agentID`、`cwd`,续接时带 `resume` | `agents.native` | +| API-45 | `agents/didOutput` | CLI 标准输出的完整行,按顺序;每条最多 64 行或 4 MiB | `agents.native` | +| API-45 | `agents/didPrompt` | 用户在会话里发了提示,开始新回合 `turn`,带提示正文 | `agents.native` | +| API-45 | `agents/didCancel` | 用户取消了当前回合 | `agents.native` | +| API-45 | `agents/didDecidePermission` | 用户回答了权限请求,带所选的 `option`;后端照此回复 CLI,自己不做决定 | `agents.native` | +| API-45 | `agents/didExit` | CLI 进程退出,可能带 `exitCode`;会话因后端结束而结束时不发 | `agents.native` | ### 限制 @@ -199,6 +209,11 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | `debug/start` | `configuration` ≤256 KiB | | 内容提供者 | 提供的内容 ≤1 MiB,宿主等待 30 秒 | | `functions/invoke` | `timeoutMilliseconds` 默认 60000 ms,上限 600000 ms;`parentOperationID` 1–128 字节 | +| `agents/write` | 1–256 行,合计 16 MiB;等待 CLI 读取的写入最多 64 个 | +| `agents/report` | 1–256 个事件;标签和 ID 1 字节到 1 KiB,正文最多 1 MiB;待回答的权限请求最多 16 个 | +| `agents/didOutput` | 每条最多 64 行或 4 MiB;超过 16 MiB 的单行被丢弃 | +| `agents/usage` | 默认 30 天,最多 366 天 | +| Agent 原生启动函数 | `timeoutMilliseconds` 1000–120000 ms,默认 15000 | 失败时的错误码和处理方式见契约的 [Outcomes and error codes](../contract/v1/README.md#outcomes-and-error-codes) 与[宿主失败码表](../contract/v1/README.md#workspace-contexts-and-capability-discovery)。取消或超时**不保证回滚**:编辑可能已经生效,不要自动重放。 @@ -206,7 +221,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I ## English -Lithe numbers its public plugin APIs API-01 to API-44 in the [API implementation plan](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md). This page lists, for each ID, **what is usable now** and **what is still missing**, and links the usable parts to contract sections and domain pages. [`contract/v1/README.md`](../contract/v1/README.md) is normative for params, results, and error codes; versions are in [Capability and protocol versions](capabilities-and-versions.md). It follows the contract and Core source on this repository's `main`. +Lithe numbers its public plugin APIs API-01 to API-45 in the [API implementation plan](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md). This page lists, for each ID, **what is usable now** and **what is still missing**, and links the usable parts to contract sections and domain pages. [`contract/v1/README.md`](../contract/v1/README.md) is normative for params, results, and error codes; versions are in [Capability and protocol versions](capabilities-and-versions.md). It follows the contract and Core source on this repository's `main`. Three things to know before reading the tables: @@ -263,6 +278,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs @@ -278,14 +294,14 @@ Status meanings: | API-43 | Will-save events | Not started | Will-save events and time-bounded edits before save | | API-44 | Agent contributions | Not started | Skills, hooks, and MCP contributed by plugins, with separate authorization review | -The manifest, marketplace, package trust, and shortcut import are installation and packaging contracts outside API-01–44; see their domain pages: [Manifest](domains/manifest.md), [Marketplace](domains/marketplace.md), [Package trust](domains/package-trust.md), [Shortcut import](domains/keymap-import.md). +The manifest, marketplace, package trust, and shortcut import are installation and packaging contracts outside API-01–45; see their domain pages: [Manifest](domains/manifest.md), [Marketplace](domains/marketplace.md), [Package trust](domains/package-trust.md), [Shortcut import](domains/keymap-import.md). ### Public host methods Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omit the prefix. One API ID can cover several methods; each method has its own row, ordered by API ID. - **The “API” column holds planning IDs** from the [API implementation plan](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md). They are recorded separately from the `litheFunctions` version in the “Protocol” column and from manifest capability versions. The methods of one API can arrive over several PRs, and adding a backward-compatible method does not bump the protocol version (see [Extending the host services](../contract/v1/README.md#extending-the-host-services) in the contract). The date and PR that first added each method are in the [protocol changelog](protocol-changelog.md#宿主方法按-api-编号) (Chinese only). -- **The “Protocol” column** is the `litheFunctions` version the method belongs to, and is 0 for every method today. Apart from `getCapabilities`, `subscriptions/dispose`, `workspace/listContexts`, `credentials/*`, `run/stop`, and `functions/providers`, every method takes `context: {contextID, generation}`. `functions/*` is open only to a backend whose plugin declares at least one `calls` entry; the official SDKs all wrap `functions/providers` and `functions/invoke`. +- **The “Protocol” column** is the `litheFunctions` version the method belongs to, and is 0 for every method today. Apart from `getCapabilities`, `subscriptions/dispose`, `workspace/listContexts`, `credentials/*`, `run/stop`, `functions/providers`, and `agents/*`, every method takes `context: {contextID, generation}`; `agents/*` names its session with `session` instead and is answered by Core, never reaching the host. `functions/*` is open only to a backend whose plugin declares at least one `calls` entry; the official SDKs all wrap `functions/providers` and `functions/invoke`. - **The “Permission” column**: every permission requires the manifest to declare `backend` (`requires.backend` is 0), or installation refuses it. `functions/*` has no manifest permission; whether the manifest's `pluginFunctions` section lists the function under `calls` decides. Two more preconditions: `debug.start` also requires a declared `debugAdapters` entry, and `languageServer.request` can be declared only when a language server lists `requestMethods` or `forwardNotifications`. | API | Method | Purpose | Permission | Protocol | @@ -365,8 +381,11 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-35 | `functions/invoke` | Calls a function another plugin exports, relayed by Core; can carry `parentOperationID` to name the call chain it belongs to, and returns `{value}` | No manifest permission; the function must be declared in `pluginFunctions.calls` | 0 | | API-38 | `network/request` | Send a bounded HTTP request with host proxy policy | `network.request` | 0 | | API-40 | `workspace/getHostPaths` | Gives the absolute paths `hostPath` of a remote context's root folders on the remote host, optionally for the roots `rootIDs` names, in that order; used only in the arguments, working directories, and language server or debugger configuration of what runs on that host; a local context gets `plugin.host.authorityUnsupported` | `workspace.metadata`, as a method grant of its own (the service grant alone gets `permissionDenied`) | 0 | +| API-45 | `agents/write` | Writes the standard input of the CLI in one of this plugin's native sessions: 1–256 lines of at most 16 MiB together, without line breaks, which Core adds; answered by Core | `agents.native`, as a method grant of its own | 0 | +| API-45 | `agents/report` | Reports the events of one of this plugin's native sessions (session, message, tool call, plan, permission request, usage, rate limits, turn end, notice): 1–256, checked together, so when one is refused none applies; answered by Core | `agents.native`, as a method grant of its own | 0 | +| API-45 | `agents/usage` | Sums the usage of the agents whose records the user enabled, by day, agent, or model, with the latest quota windows; only numbers and model names, never conversation text, titles, session IDs, or directories; answered by Core | `agents.usage.read`, as a method grant of its own | 0 | -Shortcut import providers also have two methods, `lithe/host/keymapImport/listInputs` and `lithe/host/keymapImport/readChunk`. They belong to the `litheKeymapImport` protocol, outside API-01–44; see [Shortcut import](domains/keymap-import.md). +Shortcut import providers also have two methods, `lithe/host/keymapImport/listInputs` and `lithe/host/keymapImport/readChunk`. They belong to the `litheKeymapImport` protocol, outside API-01–45; see [Shortcut import](domains/keymap-import.md). Notifications the host sends to a backend (the backend answers none), also prefixed `lithe/host/`: @@ -378,6 +397,12 @@ Notifications the host sends to a backend (the backend answers none), also prefi | API-23 | `run/didExit` | A run the backend started with `run/start` ended, with `exitCode` or `signal` (neither when the host lost the process); sent once per run | `run.start` | | API-25 | `languageServer/didChangeState` | The state of one of this plugin's language servers changed (`starting`, `running`, `stopped`, `crashed`), with `generation` | `languageServer.request` | | API-25 | `languageServer/didReceiveNotification` | Forwards a notification the server sent and `forwardNotifications` lists; past `limits.notificationBytes` it is delivered once with `truncated: true` and without `params` | `languageServer.request` | +| API-45 | `agents/didStart` | Core started a native session for this plugin, with `session`, `agentID`, `cwd`, and `resume` when it continues one | `agents.native` | +| API-45 | `agents/didOutput` | Complete lines of the CLI's standard output, in order; at most 64 lines or 4 MiB per notification | `agents.native` | +| API-45 | `agents/didPrompt` | The user sent a prompt in the session, starting the new turn `turn`, with the prompt text | `agents.native` | +| API-45 | `agents/didCancel` | The user cancelled the active turn | `agents.native` | +| API-45 | `agents/didDecidePermission` | The user answered a permission request with `option`; the backend relays it to the CLI and decides nothing itself | `agents.native` | +| API-45 | `agents/didExit` | The CLI process exited, with `exitCode` when there is one; not sent when the session ended because the backend did | `agents.native` | ### Limits @@ -401,6 +426,11 @@ Notifications the host sends to a backend (the backend answers none), also prefi | `debug/start` | `configuration` up to 256 KiB | | Content providers | Provided content up to 1 MiB; the host waits 30 seconds | | `functions/invoke` | `timeoutMilliseconds` defaults to 60000 ms, capped at 600000 ms; `parentOperationID` is 1–128 bytes | +| `agents/write` | 1–256 lines, 16 MiB together; at most 64 writes waiting for the CLI | +| `agents/report` | 1–256 events; labels and IDs 1 byte to 1 KiB, texts at most 1 MiB; at most 16 pending permission requests | +| `agents/didOutput` | At most 64 lines or 4 MiB per notification; a single line over 16 MiB is dropped | +| `agents/usage` | 30 days by default, at most 366 days | +| Agent native launch function | `timeoutMilliseconds` 1000–120000 ms, default 15000 | For failure codes and how to handle them, see the contract's [Outcomes and error codes](../contract/v1/README.md#outcomes-and-error-codes) and the [host failure table](../contract/v1/README.md#workspace-contexts-and-capability-discovery). Cancellation or timeout **does not promise rollback**: an edit may already have taken effect, so do not replay it automatically. diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index eaece6e4..cd629fe1 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -21,7 +21,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https 以后的变化遵循契约的规则: -- 先在 API-01–44 所属领域复用和兼容扩展。插件、语言服务器、构建工具等特有需求不得提升任何系统 API 版本;公共、非特有的变化也只有在兼容扩展无法安全表达时才可提出升版,见 [API PR 提交指南](../guides/plugin-api-pr-guide.zh-CN.md#3-api-版本怎么处理)。 +- 先在 API-01–45 所属领域复用和兼容扩展。插件、语言服务器、构建工具等特有需求不得提升任何系统 API 版本;公共、非特有的变化也只有在兼容扩展无法安全表达时才可提出升版,见 [API PR 提交指南](../guides/plugin-api-pr-guide.zh-CN.md#3-api-版本怎么处理)。 - 确需引入新版本时,只涉及拥有公共变化的版本,清单段与所属协议保持一致;其他插件继续选择原来所需的已有版本,不回退或删除已有的 `1`、`2` 等版本。 - 已发布的能力版本不改变含义,宿主一直支持它。 - 插件只声明自己用到的能力,每个能力取能覆盖它用法的**最低**版本。没用到新内容就提高版本,只会让旧宿主装不上。 @@ -67,6 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -90,7 +91,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | 版本 | 内容 | Core | Lithe 桌面端 | 详见 | | --- | --- | --- | --- | --- | -| `litheFunctions` `0`(`backend`) | 插件函数:注册、撤回、调用、结果、进度、取消;宿主服务 `lithe/host/*`(凭据、工作区上下文与能力发现、宿主通知、公共文档/文件/窗口方法、插件自有原生终端、独立编辑器动作、编辑器语言功能 Provider、运行与调试会话、语言服务器方法、内容提供者);跨插件调用 `functions/providers`、`functions/invoke`。提供给插件拥有的会话 | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | +| `litheFunctions` `0`(`backend`) | 插件函数:注册、撤回、调用、结果、进度、取消;宿主服务 `lithe/host/*`(凭据、工作区上下文与能力发现、宿主通知、公共文档/文件/窗口方法、插件自有原生终端、独立编辑器动作、编辑器语言功能 Provider、运行与调试会话、语言服务器方法、内容提供者,以及由 Core 回答的 Agent 原生会话 `agents/write`、`agents/report`、`agents/usage` 和 `agents/did*` 通知);跨插件调用 `functions/providers`、`functions/invoke`。提供给插件拥有的会话 | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | | `litheBuild` `0`(`buildProviders`) | `lithe/build/*`:模型与依赖、任务执行、测试执行与发现、运行准备、原生调试准备、只读模型输入、原生配置、内联测试报告、语义测试选择器、类型化运行选项、注册表连接调试。提供给构建提供者 | ✅ | ✅¹ | [Build providers](../contract/v1/README.md#build-providers) | | `litheBuild` `1`(`buildProviders`) | 在 `0` 之上加 `lithe/build/runEntrypoints`:按源文件找运行入口 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `litheVcs` `0`(`vcsProviders`) | VCS 提供者的能力和请求(`lithe/vcs/*`)。提供给 VCS 提供者 | ✅ | ✅¹ | [VCS providers](../contract/v1/README.md#vcs-providers) | @@ -141,7 +142,7 @@ A capability version decides **whether a plugin installs**; a protocol version d Future changes follow the contract's rules: -- Reuse and compatibly extend the appropriate API-01–44 domain first. A requirement specific to a plugin, language server, or build tool must not raise any system API version. Even a public, non-specific change may propose a new version only when compatible extensions cannot express it safely; see the [API PR guide (Chinese)](../guides/plugin-api-pr-guide.zh-CN.md#3-api-版本怎么处理). +- Reuse and compatibly extend the appropriate API-01–45 domain first. A requirement specific to a plugin, language server, or build tool must not raise any system API version. Even a public, non-specific change may propose a new version only when compatible extensions cannot express it safely; see the [API PR guide (Chinese)](../guides/plugin-api-pr-guide.zh-CN.md#3-api-版本怎么处理). - A necessary new version affects only the owner of that public change, with its manifest section and protocol kept together. Other plugins retain the existing versions they need; existing `1`, `2`, or later versions are not reset or removed. - A released capability version never changes meaning, and hosts keep supporting it. - A plugin declares only the capabilities it uses, each at the **lowest** version that covers its use. Raising one without using what it adds only cuts off older hosts. @@ -187,6 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | @@ -210,7 +212,7 @@ These protocols are negotiated when a process starts and never appear in the man | Version | Content | Core | Lithe desktop | See | | --- | --- | --- | --- | --- | -| `litheFunctions` `0` (`backend`) | Plugin functions: register, withdraw, invoke, results, progress, cancellation; the `lithe/host/*` host services (credentials, workspace contexts and capability discovery, host notifications, public document, file, and window methods, plugin-owned native terminals, independent editor actions, editor language-feature providers, run and debug sessions, language server methods, content providers); cross-plugin calls `functions/providers` and `functions/invoke`. Offered to plugin-owned sessions | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | +| `litheFunctions` `0` (`backend`) | Plugin functions: register, withdraw, invoke, results, progress, cancellation; the `lithe/host/*` host services (credentials, workspace contexts and capability discovery, host notifications, public document, file, and window methods, plugin-owned native terminals, independent editor actions, editor language-feature providers, run and debug sessions, language server methods, content providers, and the Core-answered agent native sessions `agents/write`, `agents/report`, `agents/usage`, and the `agents/did*` notifications); cross-plugin calls `functions/providers` and `functions/invoke`. Offered to plugin-owned sessions | ✅ | ✅¹ | [Plugin functions](../contract/v1/README.md#plugin-functions) | | `litheBuild` `0` (`buildProviders`) | `lithe/build/*`: model and dependencies, task execution, test execution and discovery, run preparation, native debug preparation, read-only model inputs, native configuration, inline test reports, semantic test selectors, typed run options, registry connection debugging. Offered to build providers | ✅ | ✅¹ | [Build providers](../contract/v1/README.md#build-providers) | | `litheBuild` `1` (`buildProviders`) | Adds `lithe/build/runEntrypoints` to `0`: the run entrypoints of a source file | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `litheVcs` `0` (`vcsProviders`) | VCS provider capabilities and requests (`lithe/vcs/*`). Offered to VCS providers | ✅ | ✅¹ | [VCS providers](../contract/v1/README.md#vcs-providers) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md new file mode 100644 index 00000000..c60d8c40 --- /dev/null +++ b/shared/plugins/reference/domains/agents.md @@ -0,0 +1,113 @@ +# Agent / Agents + +[中文](#中文) · [English](#english) + +## 中文 + +插件可以把用户自己安装、自己登录的 Agent 命令行工具接进 Lithe。插件只声明这个 CLI 是哪个工具、可以用哪几种形式运行、会话文件放在哪里;Core 启动和回收 CLI 进程,插件后端只在 CLI 自己的协议和 Lithe 的会话事件之间翻译。插件拿不到 CLI 的凭据,启动结果不能带环境变量;只有用户的操作能开始会话、发送提示和回答权限请求。 + +| 项目 | 内容 | +| --- | --- | +| 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?}`,每个插件最多 8 个 | +| 能力版本 | `agents` 0;有 Agent 声明 `native` 或 `sessionSources` 时还需要 `backend` 0。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| API 编号 | API-45 | +| 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | +| 激活事件 | 声明了 `native` 或 `sessionSources` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | +| 后端启动 | 只有终端形式的 Agent 不需要后端 | +| 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录会被读取 | +| Lithe 桌面端 | 接入中,尚未声明 `agents` | + +### 运行形式 + +| 形式 | 谁做什么 | +| --- | --- | +| `native` | Core 调用后端函数拿到命令行(只能是 `{executable: {kind: "tool", tool}, arguments}`,不能带环境变量),自己启动 CLI;CLI 的标准输出经 `lithe/host/agents/didOutput` 交给后端,后端用 `lithe/host/agents/report` 报告会话事件,用 `lithe/host/agents/write` 写 CLI 的标准输入 | +| `terminal` | 宿主在终端里用声明的参数运行 CLI,用的是 CLI 自己的交互界面 | +| `acp` | 版本 0 只校验、列入审查和目录,不运行 Agent Client Protocol 客户端;只提供 ACP 的 Agent 应同时声明 `terminal` | +| `update` | 用户确认命令行后,用声明的参数运行 CLI 的自更新命令 | + +工具一律来自插件的 `requiresTools`:宿主发现并探测版本,会话运行的始终是用户装好的那份 CLI,插件不能指定路径。会话只在可信的本地工作区运行,远程工作区按 API-40 拒绝。 + +### 会话记录与用量 + +- 用户逐个 Agent 同意后,Core 才读取 `sessionSources` 声明的目录:只读匹配 `include` 的普通文件,不跟随符号链接;后端的 `scan` 函数把新增的行变成记录,`read` 函数把记录的范围变成标题或消息。 +- Core 缓存记录,负责列表、全文搜索和统计;缓存不存正文,可以删除重建。 +- `lithe/host/agents/usage` 按天、Agent 或模型汇总用户已开启记录的 Agent 的用量,并带上最近的额度窗口。它只给数字和模型名,不含对话正文、标题、会话 ID 或工作目录,适合做跨 Agent 的统计和额度面板。 + +### 契约章节 + +| 章节 | 内容 | +| --- | --- | +| [Agents](../../contract/v1/README.md#agents) | 总览和清单示例 | +| [Agent declarations](../../contract/v1/README.md#agent-declarations) | 字段、限制、安装审查列出的程序 | +| [Agent permissions and activation](../../contract/v1/README.md#agent-permissions-and-activation) | 四个权限、`onAgent:`、拒绝码 | +| [Host commands](../../contract/v1/README.md#host-commands) | 宿主调用的 `agents.*` 命令和事件队列 | +| [Native sessions](../../contract/v1/README.md#native-sessions) | 启动流程、通知、宿主方法、会话事件 | +| [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | +| [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | 日志只记 ID 和元数据,不读凭据文件 | +| [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | 不运行 ACP 客户端,只在可信本地工作区运行 | +| [Rust Core API:Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | `agents.*` 与 `agentSessions.*` 命令(Rust Core API 文档) | + +### 示例与用例 + +| 文件 | 内容 | +| --- | --- | +| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | 一个带原生会话、终端形式、更新命令和一个会话来源的 Agent | +| [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | 只有终端形式、不需要后端的 Agent | +| [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | 以这两个清单为基础的拒绝用例 | + +--- + +## English + +A plugin can connect an agent command-line tool that the user installed and signed in to themselves. The plugin declares only which tool the CLI is, the forms it can run in, and where it keeps its session files. Core starts and reaps the CLI process; the plugin backend only translates between the CLI's own protocol and Lithe's session events. The plugin never gets the CLI's credentials, and a launch answer cannot carry environment variables. Only the user's actions start a session, send a prompt, or answer a permission request. + +| Item | Value | +| --- | --- | +| Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?}`, at most 8 per plugin | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native` or `sessionSources`. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| API IDs | API-45 | +| Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | +| Activation events | An agent that declares `native` or `sessionSources` needs `onAgent:`; other agents may not have one | +| Backend launch | A terminal-only agent needs no backend | +| Install review | Each form is an `agent` program and each session source an `agentSessions` program, so the user sees how the CLI will run and which directories will be read before installing | +| Lithe desktop | Integration in progress; does not declare `agents` yet | + +### Forms + +| Form | Who does what | +| --- | --- | +| `native` | Core calls a backend function for the command line (only `{executable: {kind: "tool", tool}, arguments}`, no environment variables) and starts the CLI itself. The CLI's standard output reaches the backend through `lithe/host/agents/didOutput`; the backend reports session events with `lithe/host/agents/report` and writes the CLI's standard input with `lithe/host/agents/write` | +| `terminal` | The host runs the CLI with the declared arguments in a terminal: the CLI's own interactive interface | +| `acp` | Version 0 validates it and lists it in the review and the catalog, but runs no Agent Client Protocol client; an agent that offers only ACP should also declare `terminal` | +| `update` | After the user confirms the command line, runs the CLI's self-update command with the declared arguments | + +The tool always comes from the plugin's `requiresTools`: the host discovers it and probes its version, so a session always runs the CLI the user installed and the plugin cannot name a path. Sessions run only in trusted local workspaces; remote workspaces are refused as API-40 describes. + +### Session records and usage + +- Core reads the directories `sessionSources` declares only after the user consents for that agent. It reads only regular files that match `include` and does not follow symbolic links. The backend's `scan` function turns new lines into records, and its `read` function turns recorded ranges into titles or messages. +- Core caches the records and answers lists, full-text search, and statistics. The cache stores no message text and can be deleted and rebuilt. +- `lithe/host/agents/usage` sums the usage of the agents whose records the user enabled, by day, agent, or model, with the latest quota windows. It carries only numbers and model names, never conversation text, titles, session IDs, or working directories, so it suits cross-agent statistics and quota panels. + +### Contract sections + +| Section | Content | +| --- | --- | +| [Agents](../../contract/v1/README.md#agents) | Overview and manifest example | +| [Agent declarations](../../contract/v1/README.md#agent-declarations) | Fields, limits, and the programs the install review lists | +| [Agent permissions and activation](../../contract/v1/README.md#agent-permissions-and-activation) | The four permissions, `onAgent:`, and refusal codes | +| [Host commands](../../contract/v1/README.md#host-commands) | The `agents.*` commands the host calls and the event queue | +| [Native sessions](../../contract/v1/README.md#native-sessions) | Launch flow, notifications, host methods, session events | +| [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | +| [Privacy and logging](../../contract/v1/README.md#privacy-and-logging) | Logs carry only IDs and metadata; no credential file is read | +| [Limits of version 0](../../contract/v1/README.md#limits-of-version-0) | No ACP client; trusted local workspaces only | +| [Rust Core API: Commands](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/contracts/rust-core-api.md#commands) | The `agents.*` and `agentSessions.*` commands (Rust Core API document) | + +### Examples and cases + +| File | Content | +| --- | --- | +| [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | An agent with a native session, a terminal form, an update command, and one session source | +| [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | A terminal-only agent without a backend | +| [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | Rejection cases built on these two manifests | diff --git a/shared/plugins/reference/domains/keymap-import.md b/shared/plugins/reference/domains/keymap-import.md index 3dd91bda..93c126cf 100644 --- a/shared/plugins/reference/domains/keymap-import.md +++ b/shared/plugins/reference/domains/keymap-import.md @@ -11,7 +11,7 @@ | 清单字段 | `keymapImportProviders[]`:`{id, displayName, recognition, inputs}` | | 能力版本 | `keymapImportProviders` 0,同时需要 `backend` 0。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | 协议 | `litheKeymapImport` 0:Core 只向声明了提供者的插件会话提供 `experimental.litheKeymapImport: {versions: [0], providers}`,后端回答 `{version: 0, providers}`(非空、无重复的子集),见[进程协议版本](../capabilities-and-versions.md#进程协议版本) | -| API 编号 | 不在 API-01–44 内(安装和导入层面的契约),见 [API 总表](../api-catalog.md#计划中的-api)下方的说明 | +| API 编号 | 不在 API-01–45 内(安装和导入层面的契约),见 [API 总表](../api-catalog.md#计划中的-api)下方的说明 | | 权限 | `backend.launch`、`keymaps.provide`、`keymaps.readSelectedSources` | | 激活事件 | 没有;宿主只在用户发起导入时启动后端 | | 后端启动 | 包内可执行文件或包内运行时,不能依赖需要发现的运行时 | @@ -60,7 +60,7 @@ A plugin can convert another editor's shortcut configuration into Lithe shortcut | Manifest field | `keymapImportProviders[]`: `{id, displayName, recognition, inputs}` | | Capability versions | `keymapImportProviders` 0, together with `backend` 0. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | Protocols | `litheKeymapImport` 0: Core offers `experimental.litheKeymapImport: {versions: [0], providers}` only to a plugin session that declares providers, and the backend answers `{version: 0, providers}` (a nonempty, duplicate-free subset); see [process protocol versions](../capabilities-and-versions.md#process-protocol-versions) | -| API IDs | Outside API-01–44 (an installation and import contract); see the note under the [API catalog](../api-catalog.md#planned-apis) | +| API IDs | Outside API-01–45 (an installation and import contract); see the note under the [API catalog](../api-catalog.md#planned-apis) | | Permissions | `backend.launch`, `keymaps.provide`, `keymaps.readSelectedSources` | | Activation events | None; the host starts the backend only when the user starts an import | | Backend launch | A packaged executable or packaged runtime, without discovered runtime dependencies | diff --git a/shared/plugins/reference/domains/manifest.md b/shared/plugins/reference/domains/manifest.md index 6dd66f9c..16715c05 100644 --- a/shared/plugins/reference/domains/manifest.md +++ b/shared/plugins/reference/domains/manifest.md @@ -11,7 +11,7 @@ | 文件 | `plugin.json`([`plugin-manifest.schema.json`](../../contract/v1/plugin-manifest.schema.json));发布者签名 `lithe-plugin-signature.json`(见[包信任](package-trust.md)) | | 基础字段 | `schemaVersion`、`id`、`displayName`、`version`、`pluginAPIVersion`、`requires`、`requiresTools`、`vendor`、`permissions`、`activationEvents` | | 版本 | `schemaVersion` 和 `pluginAPIVersion` 都固定为 `0`。`requires` 列出清单用到的每个能力,版本都是 `0`。新的能力版本只加给发生变化的那一个能力,其他能力仍写 `0`(规则见[版本与能力](../capabilities-and-versions.md)) | -| API 编号 | 不在 API-01–44 内,属于安装和打包层面的契约 | +| API 编号 | 不在 API-01–45 内,属于安装和打包层面的契约 | | 宿主 | Lithe 桌面端。声明的能力见下文“能力与宿主” | ### 清单字段归属 @@ -123,7 +123,7 @@ Every plugin package has a `plugin.json` at its root. It says who the plugin is, | Files | `plugin.json` ([`plugin-manifest.schema.json`](../../contract/v1/plugin-manifest.schema.json)); publisher signature `lithe-plugin-signature.json` (see [Package trust](package-trust.md)) | | Base fields | `schemaVersion`, `id`, `displayName`, `version`, `pluginAPIVersion`, `requires`, `requiresTools`, `vendor`, `permissions`, `activationEvents` | | Versions | `schemaVersion` and `pluginAPIVersion` are always `0`. `requires` lists every capability the manifest uses, each at version `0`. A new capability version is added only to the one capability that changes; the others stay `0` (rules in [Versions and capabilities](../capabilities-and-versions.md)) | -| API IDs | Outside API-01–44; this is an installation and packaging contract | +| API IDs | Outside API-01–45; this is an installation and packaging contract | | Host | Lithe desktop. The capabilities it declares are listed below under "Capabilities and host" | ### Which page owns each manifest field diff --git a/shared/plugins/reference/domains/marketplace.md b/shared/plugins/reference/domains/marketplace.md index d8711358..3680c19c 100644 --- a/shared/plugins/reference/domains/marketplace.md +++ b/shared/plugins/reference/domains/marketplace.md @@ -12,7 +12,7 @@ | 社区索引文件名 | 仓库根目录的 `lithe-plugin-index.json` | | Core 命令 | `plugins.marketplace.resolveSource`、`plugins.marketplace.validateIndex`、`plugins.marketplace.installReview` | | 能力 | 没有单独的能力;版本能不能装按 `pluginAPIVersion` 和 `requires` 判断,见[能力与协议版本](../capabilities-and-versions.md) | -| API 编号 | 不在 API-01–44 内(安装和打包层面的契约),见 [API 总表](../api-catalog.md) | +| API 编号 | 不在 API-01–45 内(安装和打包层面的契约),见 [API 总表](../api-catalog.md) | | 信任 | 见[包信任](package-trust.md);社区包使用 `vendor.signatureRequirement: "none"` | | Lithe 桌面端 | 把自己声明的能力作为 `hostCapabilities` 传给 `validateIndex` 和 `installReview`,见[宿主现状](#宿主现状) | | 官方 SDK | 与 SDK 无关 | @@ -151,7 +151,7 @@ A marketplace is a JSON index that lists plugins and the release archives of eac | Community index file name | `lithe-plugin-index.json` at the repository root | | Core commands | `plugins.marketplace.resolveSource`, `plugins.marketplace.validateIndex`, `plugins.marketplace.installReview` | | Capability | None of its own; whether a version can be installed follows its `pluginAPIVersion` and `requires`. See [capabilities and protocol versions](../capabilities-and-versions.md) | -| API number | Outside API-01–44 (an installation and packaging contract); see the [API catalog](../api-catalog.md) | +| API number | Outside API-01–45 (an installation and packaging contract); see the [API catalog](../api-catalog.md) | | Trust | See [Package trust](package-trust.md); community packages use `vendor.signatureRequirement: "none"` | | Lithe desktop | Passes the capabilities it declares as `hostCapabilities` to `validateIndex` and `installReview`. See [Host status](#host-status) | | Official SDKs | Not SDK-related | diff --git a/shared/plugins/reference/domains/package-trust.md b/shared/plugins/reference/domains/package-trust.md index c9599a7d..69d458cf 100644 --- a/shared/plugins/reference/domains/package-trust.md +++ b/shared/plugins/reference/domains/package-trust.md @@ -11,7 +11,7 @@ | 清单字段 | `vendor.id`、`vendor.displayName`、`vendor.signatureRequirement`;官方副本可以再加 `vendor.bundledSignatureRequirement` | | 能力 | `packageTrust` 0,只用于 `vendor.bundledSignatureRequirement`。见[能力与协议版本](../capabilities-and-versions.md) | | 签名文件 | 包根目录的 `lithe-plugin-signature.json`,Ed25519 签名,覆盖包里其他所有文件 | -| API 编号 | 不在 API-01–44 内(安装和打包层面的契约),见 [API 总表](../api-catalog.md) | +| API 编号 | 不在 API-01–45 内(安装和打包层面的契约),见 [API 总表](../api-catalog.md) | | 权限、激活事件 | 没有 | | 宿主信任的密钥 | 由宿主决定;宿主固定自己官方插件 ID 的签名要求,社区包使用 `none` | | Lithe 桌面端 | 未声明 `packageTrust`:要求它的包不会被提供安装,见[宿主现状](#宿主现状) | @@ -112,7 +112,7 @@ This page covers the package layout, the signature requirement in the manifest, | Manifest fields | `vendor.id`, `vendor.displayName`, `vendor.signatureRequirement`; an official copy may add `vendor.bundledSignatureRequirement` | | Capability | `packageTrust` 0, only for `vendor.bundledSignatureRequirement`. See [capabilities and protocol versions](../capabilities-and-versions.md) | | Signature file | `lithe-plugin-signature.json` at the package root, an Ed25519 signature over every other file in the package | -| API number | Outside API-01–44 (an installation and packaging contract); see the [API catalog](../api-catalog.md) | +| API number | Outside API-01–45 (an installation and packaging contract); see the [API catalog](../api-catalog.md) | | Permissions, activation events | None | | Keys hosts trust | The host decides; it pins the signature requirement of its official plugin IDs, and community packages use `none` | | Lithe desktop | Does not declare `packageTrust`: packages that require it are not offered for installation. See [Host status](#host-status) | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 8dd915f5..078ff25a 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -9,11 +9,13 @@ 时间线的两列这样读: -- **API 编号**:这个 PR 涉及的 API-01–44 规划编号,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md),和协议版本、能力版本分开记录。— 表示没有改到具体 API,例如清单、市场、包信任、SDK 或契约文档整理。 +- **API 编号**:这个 PR 涉及的 API-01–45 规划编号,来自 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md),和协议版本、能力版本分开记录。— 表示没有改到具体 API,例如清单、市场、包信任、SDK 或契约文档整理。 - **协议 / 能力**:**加粗**的是这个 PR 新增的版本号;没有加粗的,是同一版本内的补充、宿主接入或说明修正。 ## 待合入 +- [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 + - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 - [#198](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/198)(2026-11-24),[@1lck](https://github.com/1lck),`pluginAPIVersion` 0 / `litheFunctions` 0 内补充(API-27):`editor/registerActions` 的 `services.editor.options.actionIcons` 新增四个通用行首导航图标 token:`navigate-implemented`(接口/契约有子实现,向下)、`navigate-implementing`(实现接口/契约,向上)、`navigate-overridden`(父类/方法被覆写,向下)、`navigate-overriding`(覆写父类声明,向上),保留已有 `navigate-super` 与 `navigate-implementations` 向后兼容。`plugins.editorActions.decode` 仍由宿主声明的 `actionIcons` 列表动态校验,插件通过 `getCapabilities` 发现是否支持新 token,在旧宿主上回退到原有图标;契约 README、领域参考与 `fixtures/editor/editor-actions.json` 同步更新。没有新增能力版本、协议版本、宿主方法、通知或 SDK 版本。 @@ -69,6 +71,7 @@ | 能力 | 版本 | 日期 | PR | | --- | --- | --- | --- | | `backend` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `agents` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | | `buildModelInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | @@ -118,7 +121,7 @@ ### 宿主方法(按 API 编号) -向后兼容地新增宿主方法、通知或可选字段时不升版本(见契约 [Extending the host services](../contract/v1/README.md#extending-the-host-services)),上面的版本表看不出某个方法是什么时候加的,所以宿主方法和通知在这里逐个登记。一个 API 编号下可以有多个方法,每个方法一行,记首次加入的日期和 PR;后续的执行或行为补充另加一行,保留首次记录。方法名省略前缀 `lithe/host/`;用途和权限见 [API 总表](api-catalog.md#已公开的宿主方法)。`keymapImport/*` 属于 `litheKeymapImport` 协议,不在 API-01–44 内。`functions/providers`、`functions/invoke` 是 `litheFunctions` 里的跨插件调用,只对声明了至少一个 `calls` 的后端开放。 +向后兼容地新增宿主方法、通知或可选字段时不升版本(见契约 [Extending the host services](../contract/v1/README.md#extending-the-host-services)),上面的版本表看不出某个方法是什么时候加的,所以宿主方法和通知在这里逐个登记。一个 API 编号下可以有多个方法,每个方法一行,记首次加入的日期和 PR;后续的执行或行为补充另加一行,保留首次记录。方法名省略前缀 `lithe/host/`;用途和权限见 [API 总表](api-catalog.md#已公开的宿主方法)。`keymapImport/*` 属于 `litheKeymapImport` 协议,不在 API-01–45 内。`functions/providers`、`functions/invoke` 是 `litheFunctions` 里的跨插件调用,只对声明了至少一个 `calls` 的后端开放。 | API | 方法 | 协议 | 日期 | PR | | --- | --- | --- | --- | --- | @@ -217,6 +220,15 @@ | API-35 | `functions/invoke` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-38 | `network/request` | 0 | 2026-11-23 | [#193](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/193) | | API-40 | `workspace/getHostPaths` | 0 | 待合入 | [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151) | +| API-45 | `agents/write` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/report` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/usage` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/didStart`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/didOutput`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/didPrompt`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/didCancel`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/didDecidePermission`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/didExit`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | | — | `keymapImport/listInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | — | `keymapImport/readChunk` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -334,7 +346,7 @@ 修改 `shared/plugins/contract/v1/`、`rust/crates/plugin-model/src/capabilities.rs` 或 `rust/crates/plugin-rpc/src/` 的 Core PR,在**同一个 PR** 里更新本页: 1. 把这个 PR 补到时间线最上面(按合入日期分组):PR、修改人、API 编号、协议 / 能力、改了什么。不升版的兼容扩展同样登记;是否允许引入新版本,先按契约 [Versioning](../contract/v1/README.md#versioning) 和 [API PR 提交指南](../guides/plugin-api-pr-guide.zh-CN.md#3-api-版本怎么处理) 判断,不能照搬历史升版先例。确有新版本时才加粗,并写进“按协议查首次出现”里的对应表;所属能力与进程协议保持一致。 -2. “API 编号”填这个 PR 涉及的全部 API-01–44 编号,取自 PR 描述里的“原计划编号”。PR 没写时按 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md) 判断,不要自编新号;不属于任何编号的写 —。 +2. “API 编号”填这个 PR 涉及的全部 API-01–45 编号,取自 PR 描述里的“原计划编号”。PR 没写时按 [API 实施计划](https://github.com/1lck/Lithe-IDEA/blob/main/docs/development/macos-plugin-api-plan.md) 判断,不要自编新号;不属于任何编号的写 —。 3. PR 新增或修改了宿主方法或通知时,每个方法在“宿主方法(按 API 编号)”表里加一行,写明 API 编号、协议、日期和 PR;同时在 [API 总表](api-catalog.md#已公开的宿主方法)的中英两张方法表里各加一行,写明用途、权限和协议。同一个 API 下的方法分几个 PR 加入时,各自登记自己的 PR。 4. “修改人”填 PR 作者的 GitHub 账号,写成 `[@账号](https://github.com/账号)`。账号可以这样查: From c71e101de8a3336f75d1fb78a1f6726719840a29 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 04:27:24 +0800 Subject: [PATCH 4/7] =?UTF-8?q?feat(sdk):=20=E5=9B=9B=E4=B8=AA=E5=AE=98?= =?UTF-8?q?=E6=96=B9=20SDK=20=E6=94=AF=E6=8C=81=20API-45=20=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=20Agent=20=E4=BC=9A=E8=AF=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rust、Go、Node、Java SDK 新增 onAgentSessions(Rust 为 on_agent_sessions):每个会话一个有序 worker,didStart 创建处理器,之后按 Core 发送顺序投递 didOutput、didPrompt、didCancel、didDecidePermission、didExit;启动或提示失败时报告 turnEnded failed 并记日志。agents/did* 通知只能走这个接口,onHostNotification 注册会以 sdk.method.reserved 拒绝。 新增 agents 宿主服务封装:write、report、usage。 新增契约 fixture fixtures/agents/native-session.json,四个 SDK 的测试共用;测试改为确定性等待(闸门与事件驱动),不再用固定时长的 sleep。 README、契约 Native sessions 一节和 Agent 领域参考页补充用法与 fixture 说明。 --- shared/plugins/contract/v1/README.md | 6 +- .../v1/fixtures/agents/native-session.json | 88 ++++ shared/plugins/reference/domains/agents.md | 4 + shared/plugins/sdk/go/README.md | 85 ++++ shared/plugins/sdk/go/lithe/agents.go | 380 ++++++++++++++++++ shared/plugins/sdk/go/lithe/agents_test.go | 269 +++++++++++++ shared/plugins/sdk/go/lithe/backend.go | 13 +- shared/plugins/sdk/java/README.md | 77 ++++ .../litheidea/plugin/sdk/AgentSession.java | 32 ++ .../plugin/sdk/AgentSessionHandle.java | 38 ++ .../plugin/sdk/AgentSessionStart.java | 36 ++ .../litheidea/plugin/sdk/AgentSessions.java | 244 +++++++++++ .../github/litheidea/plugin/sdk/Backend.java | 41 +- .../litheidea/plugin/sdk/Diagnostics.java | 5 + .../io/github/litheidea/plugin/sdk/Host.java | 43 ++ .../github/litheidea/plugin/sdk/Protocol.java | 11 + .../litheidea/plugin/sdk/AgentsTest.java | 270 +++++++++++++ shared/plugins/sdk/node/README.md | 64 +++ shared/plugins/sdk/node/src/backend.mjs | 125 +++++- shared/plugins/sdk/node/src/host.mjs | 22 + shared/plugins/sdk/node/src/index.d.ts | 74 +++- shared/plugins/sdk/node/src/protocol.mjs | 13 + shared/plugins/sdk/node/test/agents.test.mjs | 160 ++++++++ shared/plugins/sdk/node/test/types/agents.mts | 44 ++ .../plugins/sdk/node/test/types/tsconfig.json | 2 +- shared/plugins/sdk/rust/README.md | 84 ++++ .../plugins/sdk/rust/plugin-sdk/src/agents.rs | 328 +++++++++++++++ .../sdk/rust/plugin-sdk/src/backend.rs | 45 ++- .../plugins/sdk/rust/plugin-sdk/src/host.rs | 7 + shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 6 + .../sdk/rust/plugin-sdk/src/protocol.rs | 9 + .../sdk/rust/plugin-sdk/tests/agents.rs | 294 ++++++++++++++ .../sdk/rust/plugin-sdk/tests/common/mod.rs | 18 + 33 files changed, 2929 insertions(+), 8 deletions(-) create mode 100644 shared/plugins/contract/v1/fixtures/agents/native-session.json create mode 100644 shared/plugins/sdk/go/lithe/agents.go create mode 100644 shared/plugins/sdk/go/lithe/agents_test.go create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionHandle.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionStart.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java create mode 100644 shared/plugins/sdk/node/test/agents.test.mjs create mode 100644 shared/plugins/sdk/node/test/types/agents.mts create mode 100644 shared/plugins/sdk/rust/plugin-sdk/src/agents.rs create mode 100644 shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index b99d63d6..bbfd4026 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -34,7 +34,7 @@ This directory is the cross-platform source of truth: | `fixtures/run/` | Run sessions and console links: `tool-reference-launch` names its runtimes by tool-definition ID and declares output link matchers; `run-start.json` holds what `run.decodeStart` returns for each case, including the rejections, and `output-link-matchers.json` the golden matches and resolutions | | `fixtures/vcs/` | A version control provider | | `fixtures/keymap-import/` | Two independent shortcut import providers sharing one packaged backend | -| `fixtures/agents/` | `agents.plugin.json`: an agent with native, terminal and update forms and a session source, served by its backend; `terminal-agent.plugin.json`: a terminal-only agent without a backend. Their rejections are in `fixtures/manifest/invalid-manifests.json` | +| `fixtures/agents/` | `agents.plugin.json`: an agent with native, terminal and update forms and a session source, served by its backend; `terminal-agent.plugin.json`: a terminal-only agent without a backend. Their rejections are in `fixtures/manifest/invalid-manifests.json`; `native-session.json` holds golden native-session notifications with the calls each session's handler receives, the reports of failed starts and prompts, and the `agents` host method requests | | `fixtures/project-generators/` | Project generators: template files (`templates/`), a scaffolding command, and an archive download; `project-generator-tool-field.plugin.json` with `templates/tool-field/` picks tool installations with `tool` fields; `project-plans.json` holds golden `project.*` form evaluations, generation plans, and name checks, and a case's optional `manifest` names the fixture it runs against (`project-generator.plugin.json` by default) | | `fixtures/toolchains/` | Production-shape fixtures for tool definitions and a packaged toolchain provider; they require `toolDefinitions` and `toolchainProviders`, which a host advertises only when it implements them | | `fixtures/package-trust/` | `publisher-bundled.plugin.json` and `signature-vectors.json`: public cross-platform vectors for the package publisher signature: the RFC 8032 test key, a fixed package with non-ASCII file names, its canonical payload, RFC 8032 deterministic signature, and content digest. Both platforms must build the same canonical payload and digest and accept the recorded signature; signers that add randomness, such as CryptoKit, check the signature by verification instead of byte comparison | @@ -3855,6 +3855,10 @@ Notifications Core sends (the host may not send them): `outputLineDropped`; a notification the backend does not take ends the session as failed. - `didExit` is not sent when the session ended because the backend did. +- The official SDKs route these notifications to one handler per session, + in order, and report `turnEnded` with reason `failed` when the handler + cannot be made or a prompt fails. Fixture: + `fixtures/agents/native-session.json`. Host methods the backend sends (service `agents`; Core answers them, the host never sees them): diff --git a/shared/plugins/contract/v1/fixtures/agents/native-session.json b/shared/plugins/contract/v1/fixtures/agents/native-session.json new file mode 100644 index 00000000..28555fcd --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/agents/native-session.json @@ -0,0 +1,88 @@ +{ + "description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.", + "sessions": { + "notifications": [ + { "method": "lithe/host/agents/didStart", "params": { "session": "agent-1", "agentID": "example", "cwd": "/work/orders" } }, + { "method": "lithe/host/agents/didStart", "params": { "session": "agent-2", "agentID": "example", "cwd": "/work/orders", "resume": "previous-session" } }, + { "method": "lithe/host/agents/didOutput", "params": { "session": "agent-1", "lines": ["one", "two"] } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-1", "turn": 1, "text": "hello" } }, + { "method": "lithe/host/agents/didOutput", "params": { "session": "agent-2", "lines": ["other"] } }, + { "method": "lithe/host/agents/didOutput", "params": { "session": "agent-1", "lines": ["three"] } }, + { "method": "lithe/host/agents/didDecidePermission", "params": { "session": "agent-1", "turn": 1, "permission": "permission-1", "option": "allow" } }, + { "method": "lithe/host/agents/didCancel", "params": { "session": "agent-1", "turn": 1 } }, + { "method": "lithe/host/agents/didOutput", "params": { "session": "agent-9", "lines": ["never started"] } }, + { "method": "lithe/host/agents/didExit", "params": { "session": "agent-1", "exitCode": 0 } }, + { "method": "lithe/host/agents/didExit", "params": { "session": "agent-2" } } + ], + "calls": { + "agent-1": [ + ["start", { "session": "agent-1", "agentID": "example", "cwd": "/work/orders", "resume": null }], + ["output", ["one", "two"]], + ["prompt", 1, "hello"], + ["output", ["three"]], + ["decidePermission", 1, "permission-1", "allow"], + ["cancel", 1], + ["exited", 0] + ], + "agent-2": [ + ["start", { "session": "agent-2", "agentID": "example", "cwd": "/work/orders", "resume": "previous-session" }], + ["output", ["other"]], + ["exited", null] + ] + } + }, + "failures": { + "notifications": [ + { "method": "lithe/host/agents/didStart", "params": { "session": "agent-3", "agentID": "example", "cwd": "/work/broken" } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-3", "turn": 1, "text": "hello" } }, + { "method": "lithe/host/agents/didExit", "params": { "session": "agent-3", "exitCode": 1 } }, + { "method": "lithe/host/agents/didStart", "params": { "session": "agent-4", "agentID": "example", "cwd": "/work/orders" } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-4", "turn": 1, "text": "fail" } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-4", "turn": 2, "text": "hello" } }, + { "method": "lithe/host/agents/didExit", "params": { "session": "agent-4", "exitCode": 0 } } + ], + "reports": [ + { "session": "agent-3", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] }, + { "session": "agent-4", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] } + ], + "calls": { + "agent-4": [ + ["start", { "session": "agent-4", "agentID": "example", "cwd": "/work/orders", "resume": null }], + ["prompt", 1, "fail"], + ["prompt", 2, "hello"], + ["exited", 0] + ] + } + }, + "methods": [ + { + "call": "write", + "session": "agent-1", + "lines": ["{\"type\":\"user\",\"message\":\"hello\"}"], + "request": { "method": "lithe/host/agents/write", "params": { "session": "agent-1", "lines": ["{\"type\":\"user\",\"message\":\"hello\"}"] } } + }, + { + "call": "report", + "session": "agent-1", + "events": [ + { "kind": "session", "agentSessionID": "cli-session-1", "model": "example-model" }, + { "kind": "message", "turn": 1, "role": "assistant", "messageID": "m1", "text": "Hi", "delta": false } + ], + "request": { + "method": "lithe/host/agents/report", + "params": { + "session": "agent-1", + "events": [ + { "kind": "session", "agentSessionID": "cli-session-1", "model": "example-model" }, + { "kind": "message", "turn": 1, "role": "assistant", "messageID": "m1", "text": "Hi", "delta": false } + ] + } + } + }, + { + "call": "usage", + "params": { "groupBy": "day", "sinceMs": 1764460800000, "utcOffsetSeconds": 28800 }, + "request": { "method": "lithe/host/agents/usage", "params": { "groupBy": "day", "sinceMs": 1764460800000, "utcOffsetSeconds": 28800 } } + } + ] +} diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index c60d8c40..93ee8051 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -14,6 +14,7 @@ | 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | | 激活事件 | 声明了 `native` 或 `sessionSources` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | | 后端启动 | 只有终端形式的 Agent 不需要后端 | +| 官方 SDK | [Rust](../../sdk/rust/README.md#native-agent-sessions)、[Go](../../sdk/go/README.md#native-agent-sessions)、[Node.js](../../sdk/node/README.md#native-agent-sessions)、[Java](../../sdk/java/README.md#native-agent-sessions) 的 `main` 源码都有原生会话接口(`onAgentSessions`,Rust 是 `on_agent_sessions`)和 `agents` 宿主服务(`write`、`report`、`usage`),随各 SDK 的下一次发布提供;已发布的 SDK 版本没有 | | 安装审查 | 每种运行形式列成一条 `agent` 程序,每个会话来源列成一条 `agentSessions` 程序,用户安装前看到 CLI 会被怎样运行、哪些目录会被读取 | | Lithe 桌面端 | 接入中,尚未声明 `agents` | @@ -55,6 +56,7 @@ | [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | 一个带原生会话、终端形式、更新命令和一个会话来源的 Agent | | [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | 只有终端形式、不需要后端的 Agent | | [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | 以这两个清单为基础的拒绝用例 | +| [`agents/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | 原生会话通知和每个会话的处理器依次收到的调用、启动或提示失败时报告的 `turnEnded`、`agents` 宿主方法的请求;四个 SDK 的测试都用它 | --- @@ -70,6 +72,7 @@ A plugin can connect an agent command-line tool that the user installed and sign | Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | | Activation events | An agent that declares `native` or `sessionSources` needs `onAgent:`; other agents may not have one | | Backend launch | A terminal-only agent needs no backend | +| Official SDKs | The [Rust](../../sdk/rust/README.md#native-agent-sessions), [Go](../../sdk/go/README.md#native-agent-sessions), [Node.js](../../sdk/node/README.md#native-agent-sessions), and [Java](../../sdk/java/README.md#native-agent-sessions) SDK sources on `main` have the native session interface (`onAgentSessions`, `on_agent_sessions` in Rust) and the `agents` host service (`write`, `report`, `usage`), shipping in each SDK's next release; released SDK versions do not | | Install review | Each form is an `agent` program and each session source an `agentSessions` program, so the user sees how the CLI will run and which directories will be read before installing | | Lithe desktop | Integration in progress; does not declare `agents` yet | @@ -111,3 +114,4 @@ The tool always comes from the plugin's `requiresTools`: the host discovers it a | [`agents/agents.plugin.json`](../../contract/v1/fixtures/agents/agents.plugin.json) | An agent with a native session, a terminal form, an update command, and one session source | | [`agents/terminal-agent.plugin.json`](../../contract/v1/fixtures/agents/terminal-agent.plugin.json) | A terminal-only agent without a backend | | [`manifest/invalid-manifests.json`](../../contract/v1/fixtures/manifest/invalid-manifests.json) | Rejection cases built on these two manifests | +| [`agents/native-session.json`](../../contract/v1/fixtures/agents/native-session.json) | Native-session notifications with the calls each session's handler receives, the `turnEnded` reports of failed starts and prompts, and the `agents` host method requests; all four SDKs test against it | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index 5e2304bf..e2b8bb5f 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -208,6 +208,7 @@ fallback and no plugin-owned file writer. | `handle.FunctionIDs()`, `handle.FunctionsVersion()` | What the backend serves, and `0, true` when the host offered `litheFunctions`. | | `backend.OnCommand(id, handler)` | Runs `func(commandID string, context *WorkspaceContext) error` when the user runs one of the plugin's commands. | | `backend.OnContextsChanged(handler)`, `backend.OnHostNotification(method, handler)` | Handle `lithe/host/workspace/didChangeContexts` and any other `lithe/host/*` notification a later host adds. | +| `backend.OnAgentSessions(start)` | Translates the native sessions of the plugin's agents; see [Native agent sessions](#native-agent-sessions). | | `handle.Host()`, `call.Host()` | The [host services](#host-services). `handle.Host()` is bound to no call. | | `handle.Credentials()`, `call.Credentials()` | Shorthand for `Host().Credentials()`. | | `lithe.NewPluginError(code, message)` | A failure meant for your own UI. | @@ -277,6 +278,7 @@ must(backend.OnCommand("db.refresh", func(_ string, workspace *lithe.WorkspaceCo | `Documents().Save`, `.SaveAs`, `.Close`; `Workspace().Create`, `.Rename`, `.Copy`, `.Trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | | `Preview().OpenHTML`, `Browser().OpenExternal`, `Window().ShowInformation`, `.ShowWarning`, `.ShowError` | Preview, browser, and messages. | | `Terminal().Create`, `.Show`, `.Close`, `.Reopen`, `.Dispose`, `.OnExit` | Native terminals; see [Native terminal API](#native-terminal-api). | +| `Agents().Write(session, lines)`, `.Report(session, events)`, `.Usage(params)` | Native agent sessions and usage totals; see [Native agent sessions](#native-agent-sessions). | | `Functions().Providers(functionID)`, `.Invoke(context, call)` | The plugins that export a function, and a call to one of them; see [Calling other plugins](#calling-other-plugins). | | `Request(method, params)`, `Subscribe(method, params)` | Any `lithe/host/*` method, including ones a later host adds. | | `Subscriptions().Dispose(id)` | Ends a subscription; `Subscription.Dispose()` does the same. | @@ -553,6 +555,89 @@ host methods discovered through `Capabilities()`; they require a host that offers them and the `terminal.create` permission. See [the native terminal guide](../../guides/native-terminals.md). +## Native agent sessions + +A plugin whose [agent](../../contract/v1/README.md#agents) declares `native` +(plan API-45) translates between the agent CLI's own protocol and Lithe's +[session events](../../contract/v1/README.md#native-sessions). Core starts the +CLI with the command line the `native` function answered; the backend only +reads the lines the CLI writes, reports events, and writes the CLI's standard +input. It never sees the CLI's environment or credentials. + +The example below is for a fictional CLI that writes JSON lines +`{"type":"text","text":…}` and `{"type":"done"}` and reads `{"prompt":…}`. + +```go +type translator struct { + lithe.AgentSessionBase // empty Cancel and Exited + session *lithe.AgentSessionHandle + turn uint64 +} + +func (t *translator) Prompt(turn uint64, text string) error { + t.turn = turn + line, _ := json.Marshal(map[string]any{"prompt": text}) + return t.session.Write([]string{string(line)}) +} + +func (t *translator) Output(lines []string) error { + var events []any + for _, raw := range lines { + var line struct{ Type, Text string } + if json.Unmarshal([]byte(raw), &line) != nil { + continue + } + switch line.Type { + case "text": + events = append(events, map[string]any{"kind": "message", "turn": t.turn, "role": "assistant", + "messageID": fmt.Sprintf("reply-%d", t.turn), "text": line.Text, "delta": true}) + case "done": + events = append(events, map[string]any{"kind": "turnEnded", "turn": t.turn, "reason": "completed"}) + } + } + if len(events) == 0 { + return nil + } + return t.session.Report(events) +} + +func (t *translator) DecidePermission(turn uint64, permission, option string) error { + line, _ := json.Marshal(map[string]any{"permission": permission, "option": option}) + return t.session.Write([]string{string(line)}) +} + +func main() { + backend := lithe.NewBackend("example-agent") + backend.OnAgentSessions(func(start lithe.AgentSessionStart, session *lithe.AgentSessionHandle) (lithe.AgentSession, error) { + return &translator{session: session}, nil + }) + os.Exit(backend.Listen()) +} +``` + +`AgentSessionStart` carries `Session`, `AgentID`, `Cwd` and `Resume` (the +CLI's own session ID when the user resumes one, or nil). Embed +`AgentSessionBase` for empty `Cancel` and `Exited`. `Host().Agents()` offers +the same `Write` and `Report` for any session ID, and `Usage(params)` for +usage totals. + +- Each session has its own worker. `didStart` makes the session's handler; + the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission` + and `didExit` then reach it one at a time, in the order Core sent them, so + a handler may wait for host requests. Other sessions keep running. +- When making the handler fails, or a prompt fails, the SDK reports + `turnEnded` with reason `failed` for the turn and logs the failure. Other + failures are only logged; a cancellation is not logged. +- A notification for a session that never started, or one that already + exited, is logged as `agent_session_unknown`. A started session without a + registration is logged as `agent_unhandled`. +- The six `lithe/host/agents/did*` notifications reach only this API; + registering one with `OnHostNotification` fails with `sdk.method.reserved`. +- `write` and `report` need `agents.native` and act only on the plugin's own + sessions. `usage` needs `agents.usage.read` and answers + `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + never conversation text, titles, session IDs or directories. + ## Testing Run these from this directory: diff --git a/shared/plugins/sdk/go/lithe/agents.go b/shared/plugins/sdk/go/lithe/agents.go new file mode 100644 index 00000000..74ca3551 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/agents.go @@ -0,0 +1,380 @@ +package lithe + +// Native agent sessions and the agents host service (plan API-45). +// +// Core starts an agent's CLI and relays it through the plugin backend: the +// CLI's standard output arrives as lithe/host/agents/didOutput, the user's +// prompts, cancellations and permission decisions as didPrompt, didCancel and +// didDecidePermission, and the backend answers with lithe/host/agents/write +// (the CLI's standard input) and lithe/host/agents/report (session events). A +// translation is only right when it sees the CLI's lines in order, so the SDK +// gives every session one goroutine that runs its handler's methods one at a +// time, in the order Core sent the notifications. + +import ( + "encoding/json" + "errors" + "sync" +) + +const ( + methodAgentsWrite = "lithe/host/agents/write" + methodAgentsReport = "lithe/host/agents/report" + methodAgentsUsage = "lithe/host/agents/usage" + methodAgentsDidStart = "lithe/host/agents/didStart" + methodAgentsDidOutput = "lithe/host/agents/didOutput" + methodAgentsDidPrompt = "lithe/host/agents/didPrompt" + methodAgentsDidCancel = "lithe/host/agents/didCancel" + methodAgentsDidDecide = "lithe/host/agents/didDecidePermission" + methodAgentsDidExit = "lithe/host/agents/didExit" +) + +func isAgentNotification(method string) bool { + switch method { + case methodAgentsDidStart, methodAgentsDidOutput, methodAgentsDidPrompt, + methodAgentsDidCancel, methodAgentsDidDecide, methodAgentsDidExit: + return true + } + return false +} + +// AgentSessionStart is what lithe/host/agents/didStart says about a session +// Core started. +type AgentSessionStart struct { + // Session is Core's ID of the session, such as agent-1. + Session string + // AgentID is the agents[].id from the manifest. + AgentID string + // Cwd is the working directory the CLI runs in. + Cwd string + // Resume is the CLI's own session ID to resume, when the user resumes one. + Resume *string +} + +// AgentSession is the plugin's translation of one native session. Every +// method runs on the session's own goroutine, one at a time and in the order +// Core sent the notifications, so a method may block on host requests. +// +// A failing Prompt ends its turn: the SDK reports turnEnded with reason +// failed. Other failures are only logged. Embed [AgentSessionBase] for the +// methods a translation does not need. +type AgentSession interface { + // Output gets lines the CLI wrote to standard output, without line breaks. + Output(lines []string) error + // Prompt gets the user's prompt for turn; write what the CLI expects. + Prompt(turn uint64, text string) error + // Cancel says the user cancelled turn. + Cancel(turn uint64) error + // DecidePermission says the user answered permission request permission + // with option. + DecidePermission(turn uint64, permission, option string) error + // Exited says the CLI ended; the session gets no further calls. + Exited(exitCode *int64) +} + +// AgentSessionBase answers Cancel and Exited without doing anything. +type AgentSessionBase struct{} + +// Cancel does nothing. +func (AgentSessionBase) Cancel(uint64) error { return nil } + +// Exited does nothing. +func (AgentSessionBase) Exited(*int64) {} + +// AgentSessionStarter makes the translation of a session Core started. An +// error leaves the session without a handler: its turns end as failed. +type AgentSessionStarter func(start AgentSessionStart, session *AgentSessionHandle) (AgentSession, error) + +// AgentSessionHandle is the host methods of one session. +type AgentSessionHandle struct { + id string + host *Host +} + +// ID is Core's ID of the session. +func (s *AgentSessionHandle) ID() string { return s.id } + +// Host is the host services outside the session, such as other plugins' +// functions. +func (s *AgentSessionHandle) Host() *Host { return s.host } + +// Write sends lithe/host/agents/write: 1-256 lines for the CLI's standard +// input, without line breaks; Core adds the newline. +func (s *AgentSessionHandle) Write(lines []string) error { + return s.host.Agents().Write(s.id, lines) +} + +// Report sends lithe/host/agents/report: 1-256 session events, applied +// together. +func (s *AgentSessionHandle) Report(events []any) error { + return s.host.Agents().Report(s.id, events) +} + +// Agents is the host's agents service. Core answers it; each method needs +// its own grant: Write and Report agents.native, Usage agents.usage.read. +type Agents struct{ host *Host } + +// Agents returns the agents service of native agent sessions and usage +// totals (plan API-45). +func (h *Host) Agents() *Agents { return &Agents{host: h} } + +// Write writes lines to the standard input of session's CLI. +func (a *Agents) Write(session string, lines []string) error { + _, err := a.host.Request(methodAgentsWrite, map[string]any{"session": session, "lines": lines}) + return err +} + +// Report reports events of session; one refused event refuses them all. +// events is a JSON array of session events. +func (a *Agents) Report(session string, events any) error { + _, err := a.host.Request(methodAgentsReport, map[string]any{"session": session, "events": events}) + return err +} + +// Usage answers { sinceMs, untilMs, summaries, rateLimits } for +// { groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }. +func (a *Agents) Usage(params any) (json.RawMessage, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + return a.host.requestObject(methodAgentsUsage, value) +} + +// OnAgentSessions translates the native sessions of the plugin's agents +// (plan API-45). For each lithe/host/agents/didStart, start makes the +// session's [AgentSession] on a goroutine of the session's own, which then +// gets the session's didOutput, didPrompt, didCancel, didDecidePermission and +// didExit one at a time, in the order Core sent them. When start fails, or a +// prompt fails, the SDK reports turnEnded with reason failed for the turn. A +// later registration replaces the earlier one. +func (b *Backend) OnAgentSessions(start AgentSessionStarter) { + b.agentSessions = start +} + +// agentNotice is one notification for a session's worker. +type agentNotice struct { + method string + lines []string + turn uint64 + text string + permission string + option string + exitCode *int64 +} + +// agentQueue is an unbounded queue of one session's notifications, so the +// reading goroutine never waits for a handler. +type agentQueue struct { + mu sync.Mutex + ready *sync.Cond + items []agentNotice + closed bool +} + +func newAgentQueue() *agentQueue { + q := &agentQueue{} + q.ready = sync.NewCond(&q.mu) + return q +} + +func (q *agentQueue) push(notice agentNotice) { + q.mu.Lock() + defer q.mu.Unlock() + if !q.closed { + q.items = append(q.items, notice) + q.ready.Signal() + } +} + +func (q *agentQueue) close() { + q.mu.Lock() + defer q.mu.Unlock() + q.closed = true + q.ready.Signal() +} + +// pop waits for the next notification; false once the queue is closed and +// empty. +func (q *agentQueue) pop() (agentNotice, bool) { + q.mu.Lock() + defer q.mu.Unlock() + for len(q.items) == 0 && !q.closed { + q.ready.Wait() + } + if len(q.items) == 0 { + return agentNotice{}, false + } + notice := q.items[0] + q.items = q.items[1:] + return notice, true +} + +// agentWorkers is the queues of the live sessions, by session ID. +type agentWorkers struct { + mu sync.Mutex + sessions map[string]*agentQueue +} + +// closeAll ends every worker after its queued notifications; used when the +// backend stops serving. +func (w *agentWorkers) closeAll() { + w.mu.Lock() + sessions := w.sessions + w.sessions = nil + w.mu.Unlock() + for _, queue := range sessions { + queue.close() + } +} + +// route hands one lithe/host/agents/did* notification to its session. Core +// checked its shape; a notification of a session the SDK did not start is +// dropped. +func (b *Backend) routeAgentNotification(method string, params map[string]any) { + s := b.shared + w := &b.agentWorkers + session, _ := params["session"].(string) + if method == methodAgentsDidStart { + if b.agentSessions == nil { + s.failed("notification", "agent_unhandled") + return + } + start := AgentSessionStart{Session: session} + start.AgentID, _ = params["agentID"].(string) + start.Cwd, _ = params["cwd"].(string) + if resume, ok := params["resume"].(string); ok { + start.Resume = &resume + } + queue := newAgentQueue() + w.mu.Lock() + if w.sessions == nil { + w.sessions = map[string]*agentQueue{} + } + w.sessions[session] = queue + w.mu.Unlock() + go runAgentSession(s, b.agentSessions, start, queue) + return + } + notice := agentNotice{method: method} + notice.turn = unsigned(params["turn"]) + notice.text, _ = params["text"].(string) + notice.permission, _ = params["permission"].(string) + notice.option, _ = params["option"].(string) + if lines, ok := params["lines"].([]any); ok { + for _, line := range lines { + text, _ := line.(string) + notice.lines = append(notice.lines, text) + } + } + if number, ok := params["exitCode"].(json.Number); ok { + if code, err := number.Int64(); err == nil { + notice.exitCode = &code + } + } + w.mu.Lock() + queue := w.sessions[session] + if method == methodAgentsDidExit { + delete(w.sessions, session) + } + w.mu.Unlock() + if queue == nil { + if b.agentSessions != nil { + s.failed("notification", "agent_session_unknown") + } + return + } + queue.push(notice) + if method == methodAgentsDidExit { + queue.close() + } +} + +func unsigned(value any) uint64 { + number, _ := value.(json.Number) + turn, err := number.Int64() + if err != nil || turn < 0 { + return 0 + } + return uint64(turn) +} + +// errNoHandler marks a notification of a session whose start failed. +var errNoHandler = errors.New("agent session has no handler") + +// runAgentSession starts the session's handler, then runs its notifications +// in order. +func runAgentSession(s *shared, starter AgentSessionStarter, start AgentSessionStart, queue *agentQueue) { + handle := &AgentSessionHandle{id: start.Session, host: &Host{shared: s}} + handler, err := startAgentSession(starter, start, handle) + if err != nil { + logAgentFailure(s, err) + } + for { + notice, ok := queue.pop() + if !ok { + return + } + err := errNoHandler + if handler != nil { + err = deliverAgentNotice(handler, notice) + if err != nil { + logAgentFailure(s, err) + } + } + if err != nil && notice.method == methodAgentsDidPrompt { + // No handler runs the turn, so it ends here. The handler may have + // ended it already; Core then refuses the second end. + _ = handle.Report([]any{map[string]any{"kind": "turnEnded", "turn": notice.turn, "reason": "failed"}}) + } + } +} + +func startAgentSession(starter AgentSessionStarter, start AgentSessionStart, handle *AgentSessionHandle) (handler AgentSession, err error) { + defer func() { + if recover() != nil { + handler, err = nil, errPanicked + } + }() + handler, err = starter(start, handle) + if err == nil && handler == nil { + err = errNoHandler + } + return handler, err +} + +var errPanicked = errors.New("panic") + +func deliverAgentNotice(handler AgentSession, notice agentNotice) (err error) { + defer func() { + if recover() != nil { + err = errPanicked + } + }() + switch notice.method { + case methodAgentsDidOutput: + return handler.Output(notice.lines) + case methodAgentsDidPrompt: + return handler.Prompt(notice.turn, notice.text) + case methodAgentsDidCancel: + return handler.Cancel(notice.turn) + case methodAgentsDidDecide: + return handler.DecidePermission(notice.turn, notice.permission, notice.option) + default: + handler.Exited(notice.exitCode) + return nil + } +} + +func logAgentFailure(s *shared, err error) { + switch { + case errors.Is(err, errPanicked): + s.failed("notification", "panic") + case errors.Is(err, errNoHandler): + s.failed("notification", "internal_error") + default: + if kind, _ := classify(err); kind != kindCancelled { + s.failed("notification", failureKind(err)) + } + } +} diff --git a/shared/plugins/sdk/go/lithe/agents_test.go b/shared/plugins/sdk/go/lithe/agents_test.go new file mode 100644 index 00000000..0ba668f2 --- /dev/null +++ b/shared/plugins/sdk/go/lithe/agents_test.go @@ -0,0 +1,269 @@ +package lithe_test + +// Native agent sessions and the agents host service (plan API-45), driven by +// the scripted host and fixtures/agents/native-session.json. + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "sort" + "sync" + "testing" + "time" + + "github.com/Lithe-IDEA/Lithe-core-rust/shared/plugins/sdk/go/lithe" +) + +func agentsFixture(t *testing.T) map[string]any { + t.Helper() + path := filepath.Join("..", "..", "..", "contract", "v1", "fixtures", "agents", "native-session.json") + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var fixture map[string]any + must(t, json.Unmarshal(data, &fixture)) + return fixture +} + +// gate opens once agent-2 exited. agent-1's first output waits for it, so +// sessions sharing one worker never get past it. +type gate struct { + once sync.Once + opened chan struct{} +} + +func (g *gate) open() { g.once.Do(func() { close(g.opened) }) } + +// recorder records every call as [session, call, args...], as the fixture +// lists them; it fails prompts that say fail. +type recorder struct { + session string + calls chan<- []any + otherExited *gate +} + +func (r *recorder) record(call ...any) { + r.calls <- append([]any{r.session}, call...) +} + +func (r *recorder) Output(lines []string) error { + if r.session == "agent-1" && slices.Contains(lines, "one") { + select { + case <-r.otherExited.opened: + case <-time.After(wait): + return errors.New("agent-2 did not exit in time") + } + } + r.record("output", lines) + return nil +} + +func (r *recorder) Prompt(turn uint64, text string) error { + r.record("prompt", turn, text) + if text == "fail" { + return errors.New("prompt_failed") + } + return nil +} + +func (r *recorder) Cancel(turn uint64) error { + r.record("cancel", turn) + return nil +} + +func (r *recorder) DecidePermission(turn uint64, permission, option string) error { + r.record("decidePermission", turn, permission, option) + return nil +} + +func (r *recorder) Exited(exitCode *int64) { + r.record("exited", exitCode) + if r.session == "agent-2" { + r.otherExited.open() + } +} + +// recordingBackend fails to start sessions in /work/broken. +func recordingBackend(t *testing.T, calls chan<- []any) *lithe.Backend { + backend := lithe.NewBackend("agents-test") + otherExited := &gate{opened: make(chan struct{})} + backend.OnAgentSessions(func(start lithe.AgentSessionStart, session *lithe.AgentSessionHandle) (lithe.AgentSession, error) { + if session.ID() != start.Session { + t.Errorf("handle %s for session %s", session.ID(), start.Session) + } + if start.Cwd == "/work/broken" { + return nil, errors.New("start_failed") + } + r := &recorder{session: start.Session, calls: calls, otherExited: otherExited} + r.record("start", map[string]any{ + "session": start.Session, "agentID": start.AgentID, "cwd": start.Cwd, "resume": start.Resume, + }) + return r, nil + }) + return backend +} + +func sendAll(host *testHost, notifications any) { + host.t.Helper() + for _, notification := range notifications.([]any) { + host.notify(at(notification, "method").(string), at(notification, "params")) + } +} + +// callsBySession is the calls of every session, in the order each session +// received them. Every session's last call is its exit, so nothing follows +// the count. +func callsBySession(t *testing.T, calls <-chan []any, count int) map[string][]any { + t.Helper() + sessions := map[string][]any{} + for range count { + call := within(t, calls) + session := call[0].(string) + sessions[session] = append(sessions[session], call[1:]) + } + return sessions +} + +func callCount(calls any) int { + count := 0 + for _, session := range calls.(map[string]any) { + count += len(session.([]any)) + } + return count +} + +// failureCodes is every operationFailed code among the frames not read yet, +// once the session closed and the backend closed its output. +func failureCodes(t *testing.T, host *testHost) []string { + t.Helper() + var codes []string + for { + select { + case frame, ok := <-host.frames: + if !ok { + return codes + } + if frame["method"] == "lithe/log" && at(frame, "params", "kind") == "operationFailed" { + codes = append(codes, at(frame, "params", "code").(string)) + } + case <-time.After(wait): + t.Fatalf("the backend did not close its output in time") + return nil + } + } +} + +func TestEachAgentSessionGetsItsNotificationsInOrderFromStartToExit(t *testing.T) { + fixture := agentsFixture(t) + expected := at(fixture, "sessions", "calls") + calls := make(chan []any, 64) + host := startHost(t, recordingBackend(t, calls)) + host.initialize([]any{0}) + sendAll(host, at(fixture, "sessions", "notifications")) + eq(t, callsBySession(t, calls, callCount(expected)), encode(t, expected)) + if code := host.close(); code != 1 { + t.Errorf("exit code %d", code) + } + // agent-9 never started, so its output reaches no handler. + eq(t, failureCodes(t, host), `["agent_session_unknown"]`) +} + +func TestAFailedAgentStartOrPromptEndsTheTurnAsFailed(t *testing.T) { + fixture := agentsFixture(t) + failures := at(fixture, "failures") + expected := at(failures, "calls") + calls := make(chan []any, 64) + host := startHost(t, recordingBackend(t, calls)) + host.initialize([]any{0}) + sendAll(host, at(failures, "notifications")) + + wanted := at(failures, "reports").([]any) + var reports []string + for len(reports) < len(wanted) { + frame := host.next() + if frame["method"] == "lithe/host/agents/report" { + reports = append(reports, encode(t, frame["params"])) + host.reply(frame, map[string]any{}) + } + } + var expectedReports []string + for _, report := range wanted { + expectedReports = append(expectedReports, encode(t, report)) + } + sort.Strings(reports) + sort.Strings(expectedReports) + eq(t, reports, encode(t, expectedReports)) + eq(t, callsBySession(t, calls, callCount(expected)), encode(t, expected)) + if code := host.close(); code != 1 { + t.Errorf("exit code %d", code) + } +} + +func TestAgentHostMethodsSendTheFixtureRequests(t *testing.T) { + fixture := agentsFixture(t) + backend := lithe.NewBackend("agents-test") + handle := backend.Handle() + host := startHost(t, backend) + host.initialize([]any{0}) + for _, test := range at(fixture, "methods").([]any) { + agents := handle.Host().Agents() + session, _ := at(test, "session").(string) + done := make(chan error, 1) + result := make(chan json.RawMessage, 1) + go func() { + switch at(test, "call") { + case "write": + var lines []string + for _, line := range at(test, "lines").([]any) { + lines = append(lines, line.(string)) + } + done <- agents.Write(session, lines) + case "report": + done <- agents.Report(session, at(test, "events")) + default: + answer, err := agents.Usage(at(test, "params")) + result <- answer + done <- err + } + }() + request := host.next() + eq(t, request["method"], encode(t, at(test, "request", "method"))) + eq(t, request["params"], encode(t, at(test, "request", "params"))) + answer := map[string]any{} + if at(test, "call") == "usage" { + answer = map[string]any{"sinceMs": 1, "untilMs": 2, "summaries": []any{}, "rateLimits": []any{}} + } + host.reply(request, answer) + must(t, within(t, done)) + if at(test, "call") == "usage" { + eq(t, within(t, result), encode(t, answer)) + } + } + if code := host.close(); code != 1 { + t.Errorf("exit code %d", code) + } +} + +func TestAgentNotificationsAreRoutedOnlyThroughAgentSessions(t *testing.T) { + backend := lithe.NewBackend("agents-test") + for _, method := range []string{"lithe/host/agents/didStart", "lithe/host/agents/didOutput", "lithe/host/agents/didExit"} { + err := backend.OnHostNotification(method, func(json.RawMessage) error { return nil }) + if code(err) != "sdk.method.reserved" { + t.Errorf("%s: %v", method, err) + } + } + // Without a registration a started session is only logged. + host := startHost(t, backend) + host.initialize([]any{0}) + host.notify("lithe/host/agents/didStart", map[string]any{"session": "agent-1", "agentID": "example", "cwd": "/work/orders"}) + host.notify("lithe/host/agents/didOutput", map[string]any{"session": "agent-1", "lines": []any{"one"}}) + // The reader logs both before it reads the end of the input. + if code := host.close(); code != 1 { + t.Errorf("exit code %d", code) + } + eq(t, failureCodes(t, host), `["agent_unhandled"]`) +} diff --git a/shared/plugins/sdk/go/lithe/backend.go b/shared/plugins/sdk/go/lithe/backend.go index 2710c3c7..04000a6d 100644 --- a/shared/plugins/sdk/go/lithe/backend.go +++ b/shared/plugins/sdk/go/lithe/backend.go @@ -244,6 +244,8 @@ type Backend struct { commands map[string]CommandHandler contextsChanged NotificationHandler hostNotifications map[string]NotificationHandler + agentSessions AgentSessionStarter + agentWorkers agentWorkers } // NewBackend returns a backend; name is reported as serverInfo.name. @@ -369,7 +371,8 @@ func (b *Backend) OnContextsChanged(handler NotificationHandler) { } // OnHostNotification handles a lithe/host/* notification a later host adds. -// Commands, context changes and subscription events have their own APIs. +// Commands, context changes, subscription events and agent sessions have +// their own APIs. func (b *Backend) OnHostNotification(method string, handler NotificationHandler) error { if !strings.HasPrefix(method, hostPrefix) { return newSdkError("sdk.method.invalid", method+" is not a host notification.") @@ -377,6 +380,9 @@ func (b *Backend) OnHostNotification(method string, handler NotificationHandler) if method == methodContexts || method == methodNotify || method == methodCommandRan { return newSdkError("sdk.method.reserved", method+" is routed by the SDK; use OnCommand, OnContextsChanged, or Host.Subscribe.") } + if isAgentNotification(method) { + return newSdkError("sdk.method.reserved", method+" is routed by the SDK; use OnAgentSessions.") + } b.hostNotifications[method] = handler return nil } @@ -407,6 +413,8 @@ func (b *Backend) Serve(input io.Reader, output io.Writer) int { s.outputMu.Lock() s.output = bufio.NewWriter(output) s.outputMu.Unlock() + // Agent sessions still open when serving ends get no further notices. + defer b.agentWorkers.closeAll() reader := bufio.NewReader(input) for { message, err := readFrame(reader) @@ -517,6 +525,9 @@ func (b *Backend) hostNotification(method string, params any) { switch method { case methodNotify: s.deliver(object) + case methodAgentsDidStart, methodAgentsDidOutput, methodAgentsDidPrompt, + methodAgentsDidCancel, methodAgentsDidDecide, methodAgentsDidExit: + b.routeAgentNotification(method, object) case methodCommandRan: commandID, _ := object["commandID"].(string) handler := b.commands[commandID] diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 7429eb79..686d312b 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -204,6 +204,7 @@ stderr fallback and no plugin-owned file writer. | `onCommand(commandId, handler)` | Runs `handler.handle(commandId, workspaceContext)` when the user runs one of the plugin's commands. | | `onContextsChanged(handler)` | `lithe/host/workspace/didChangeContexts` with its `{ revision }`. | | `onHostNotification(method, handler)` | A `lithe/host/*` notification a later host adds. The three this SDK routes itself are reserved. | +| `onAgentSessions(start)` | Translates the native sessions of the plugin's agents; see [Native agent sessions](#native-agent-sessions). | | `onInitialize(hook)`, `onShutdown(hook)` | Lifecycle hooks. `onInitialize` receives the `initialize` params and what was negotiated. | | `onRequest(method, handler)`, `onNotification(method, handler)` | Ordinary LSP methods. Lifecycle and `lithe/*` methods are reserved. | | `sendRequest`, `sendNotification` | Ordinary LSP messages to the host. `lithe/*` methods are reserved. | @@ -299,6 +300,7 @@ call. See the [build configuration contract](../../contract/v1/README.md#build-c | `documents().save`, `.saveAs`, `.close`; `workspace().create`, `.rename`, `.copy`, `.trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | | `preview().openHtml`, `browser().openExternal`, `window().showInformation`, `.showWarning`, `.showError` | Preview, browser, and messages. | | `functions().providers(functionId)`, `.invoke(context, call)` | [Calls to other plugins' functions](#calling-other-plugins), relayed by Core. | +| `agents().write(session, lines)`, `.report(session, events)`, `.usage(params)` | Native agent sessions and usage totals, as `CompletableFuture`s; see [Native agent sessions](#native-agent-sessions). | | `request(method, params)`, `subscribe(method, params, listener)` | Any `lithe/host/*` method, including ones a later host adds. | | `subscriptions().dispose(id)` | Ends a subscription; `Subscription.dispose()` does the same. | | `withCancellation(cancellation)` | The same services, cancelled together with `cancellation`. | @@ -529,6 +531,81 @@ reopen with bounded display history, disposal and exit subscriptions. They require `terminal.create`. See [the native terminal guide](../../guides/native-terminals.md). +## Native agent sessions + +A plugin whose [agent](../../contract/v1/README.md#agents) declares `native` +(plan API-45) translates between the agent CLI's own protocol and Lithe's +[session events](../../contract/v1/README.md#native-sessions). Core starts the +CLI with the command line the `native` function answered; the backend only +reads the lines the CLI writes, reports events, and writes the CLI's standard +input. It never sees the CLI's environment or credentials. + +The example below is for a fictional CLI that writes JSON lines +`{"type":"text","text":…}` and `{"type":"done"}` and reads `{"prompt":…}`. + +```java +backend.onAgentSessions((start, session) -> new AgentSession() { + private long turn; + + @Override + public void prompt(long next, String text) throws Exception { + turn = next; + session.write(Collections.singletonList(Json.stringify(map("prompt", text)))).join(); + } + + @Override + public void output(List lines) throws Exception { + List events = new ArrayList<>(); + for (String raw : lines) { + Map line; + try { + line = Json.object(Json.parse(raw)); + } catch (Json.JsonException notJson) { + continue; + } + if ("text".equals(line.get("type"))) { + events.add(map("kind", "message", "turn", turn, "role", "assistant", + "messageID", "reply-" + turn, "text", line.get("text"), "delta", true)); + } else if ("done".equals(line.get("type"))) { + events.add(map("kind", "turnEnded", "turn", turn, "reason", "completed")); + } + } + if (!events.isEmpty()) { + session.report(events).join(); + } + } + + @Override + public void decidePermission(long turn, String permission, String option) throws Exception { + session.write(Collections.singletonList(Json.stringify(map("permission", permission, "option", option)))) + .join(); + } +}); +``` + +`map` stands for a helper that builds a `LinkedHashMap` from key-value pairs. +`AgentSessionStart` carries `session()`, `agentId()`, `cwd()` and `resume()` +(the CLI's own session ID when the user resumes one, or null). `cancel` and +`exited` have empty defaults. `host().agents()` offers the same `write` and +`report` for any session ID, and `usage(params)` for usage totals. + +- Each session has its own worker. `didStart` makes the session's handler; + the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission` + and `didExit` then reach it one at a time, in the order Core sent them, so + a handler may wait for host requests. Other sessions keep running. +- When making the handler fails, or a prompt fails, the SDK reports + `turnEnded` with reason `failed` for the turn and logs the failure. Other + failures are only logged; a cancellation is not logged. +- A notification for a session that never started, or one that already + exited, is logged as `agent_session_unknown`. A started session without a + registration is logged as `agent_unhandled`. +- The six `lithe/host/agents/did*` notifications reach only this API; + registering one with `onHostNotification` fails with `sdk.method.reserved`. +- `write` and `report` need `agents.native` and act only on the plugin's own + sessions. `usage` needs `agents.usage.read` and answers + `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + never conversation text, titles, session IDs or directories. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java new file mode 100644 index 00000000..e55bade9 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java @@ -0,0 +1,32 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.List; + +/** + * The plugin's translation of one native agent session (plan API-45). Core + * runs the agent's CLI; the SDK calls these methods on the session's own + * worker, one at a time and in the order Core sent the notifications, so a + * method may wait for host requests. + * + *

A failing {@link #prompt} ends its turn: the SDK reports + * {@code turnEnded} with reason {@code failed}. Other failures are only logged. + */ +public interface AgentSession { + /** Lines the CLI wrote to standard output, without line breaks. */ + void output(List lines) throws Exception; + + /** The user's prompt for {@code turn}; write what the CLI expects. */ + void prompt(long turn, String text) throws Exception; + + /** The user cancelled {@code turn}. Does nothing unless overridden. */ + default void cancel(long turn) throws Exception {} + + /** The user answered permission request {@code permission} with {@code option}. */ + void decidePermission(long turn, String permission, String option) throws Exception; + + /** + * The CLI ended, with its exit code when it had one; the session gets no + * further calls. Does nothing unless overridden. + */ + default void exited(Long exitCode) {} +} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionHandle.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionHandle.java new file mode 100644 index 00000000..3fde0dfa --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionHandle.java @@ -0,0 +1,38 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.List; +import java.util.concurrent.CompletableFuture; + +/** The host methods of one native agent session. */ +public final class AgentSessionHandle { + private final String id; + private final Host host; + + AgentSessionHandle(String id, Host host) { + this.id = id; + this.host = host; + } + + /** Core's ID of the session. */ + public String id() { + return id; + } + + /** The host services outside the session, such as other plugins' functions. */ + public Host host() { + return host; + } + + /** + * Sends {@code lithe/host/agents/write}: 1-256 lines for the CLI's + * standard input, without line breaks; Core adds the newline. + */ + public CompletableFuture write(List lines) { + return host.agents().write(id, lines); + } + + /** Sends {@code lithe/host/agents/report}: 1-256 session events, applied together. */ + public CompletableFuture report(List events) { + return host.agents().report(id, events); + } +} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionStart.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionStart.java new file mode 100644 index 00000000..755da2d0 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessionStart.java @@ -0,0 +1,36 @@ +package io.github.litheidea.plugin.sdk; + +/** What {@code lithe/host/agents/didStart} says about a session Core started. */ +public final class AgentSessionStart { + private final String session; + private final String agentId; + private final String cwd; + private final String resume; + + AgentSessionStart(String session, String agentId, String cwd, String resume) { + this.session = session; + this.agentId = agentId; + this.cwd = cwd; + this.resume = resume; + } + + /** Core's ID of the session, such as {@code agent-1}. */ + public String session() { + return session; + } + + /** The {@code agents[].id} from the manifest. */ + public String agentId() { + return agentId; + } + + /** The working directory the CLI runs in. */ + public String cwd() { + return cwd; + } + + /** The CLI's own session ID to resume when the user resumes one, or null. */ + public String resume() { + return resume; + } +} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java new file mode 100644 index 00000000..b24993f6 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java @@ -0,0 +1,244 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Executor; +import java.util.concurrent.LinkedBlockingQueue; + +/** + * Native agent sessions (plan API-45). Core starts an agent's CLI and relays + * it through the plugin backend: the CLI's standard output arrives as + * {@code lithe/host/agents/didOutput}, the user's prompts, cancellations and + * permission decisions as {@code didPrompt}, {@code didCancel} and + * {@code didDecidePermission}, and the backend answers with + * {@code lithe/host/agents/write} (the CLI's standard input) and + * {@code lithe/host/agents/report} (session events). A translation is only + * right when it sees the CLI's lines in order, so every session gets one + * worker that runs its handler's methods one at a time, in the order Core + * sent the notifications. + */ +final class AgentSessions { + static final Set NOTIFICATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + Protocol.HOST_AGENTS_DID_START, Protocol.HOST_AGENTS_DID_OUTPUT, Protocol.HOST_AGENTS_DID_PROMPT, + Protocol.HOST_AGENTS_DID_CANCEL, Protocol.HOST_AGENTS_DID_DECIDE_PERMISSION, + Protocol.HOST_AGENTS_DID_EXIT))); + private static final String OPERATION = "notification"; + + private final Backend backend; + private final Map sessions = new HashMap<>(); + private Backend.AgentSessionStarter starter; + + AgentSessions(Backend backend) { + this.backend = backend; + } + + synchronized void starter(Backend.AgentSessionStarter starter) { + this.starter = starter; + } + + /** + * Routes one notification. It runs on the reader thread, so it only + * queues work and never waits for a handler. + */ + void route(String method, Map params, Executor executor) { + String session = string(params, "session"); + boolean start = method.equals(Protocol.HOST_AGENTS_DID_START); + Backend.AgentSessionStarter registered; + Worker worker; + synchronized (this) { + registered = starter; + if (start) { + worker = registered == null ? null : new Worker(); + if (worker != null) { + sessions.put(session, worker); + } + } else if (method.equals(Protocol.HOST_AGENTS_DID_EXIT)) { + worker = sessions.remove(session); + } else { + worker = sessions.get(session); + } + } + if (start) { + if (worker == null) { + backend.diagnostics().failed(OPERATION, "agent_unhandled"); + return; + } + Object resume = params.get("resume"); + AgentSessionStart started = new AgentSessionStart(session, string(params, "agentID"), + string(params, "cwd"), resume instanceof String ? (String) resume : null); + Worker queue = worker; + executor.execute(() -> run(registered, started, queue)); + return; + } + if (worker == null) { + if (registered != null) { + backend.diagnostics().failed(OPERATION, "agent_session_unknown"); + } + return; + } + worker.push(notice(method, params)); + if (method.equals(Protocol.HOST_AGENTS_DID_EXIT)) { + worker.close(); + } + } + + /** Ends every open session; its worker stops after the notices already queued. */ + void closeAll() { + List open; + synchronized (this) { + open = new ArrayList<>(sessions.values()); + sessions.clear(); + } + for (Worker worker : open) { + worker.close(); + } + } + + /** Starts the session's handler, then runs its notifications in order. */ + private void run(Backend.AgentSessionStarter starter, AgentSessionStart start, Worker worker) { + AgentSessionHandle handle = new AgentSessionHandle(start.session(), backend.host()); + AgentSession handler = null; + try { + handler = starter.start(start, handle); + if (handler == null) { + backend.diagnostics().failed(OPERATION, "internal_error"); + } + } catch (Throwable error) { + failed(error); + } + for (;;) { + Notice notice; + try { + notice = worker.take(); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + return; + } + if (notice == Notice.CLOSED) { + return; + } + boolean handled = false; + if (handler != null) { + try { + deliver(handler, notice); + handled = true; + } catch (Throwable error) { + failed(error); + } + } + if (!handled && notice.method.equals(Protocol.HOST_AGENTS_DID_PROMPT)) { + endTurn(handle, notice.turn); + } + } + } + + private static void deliver(AgentSession handler, Notice notice) throws Exception { + switch (notice.method) { + case Protocol.HOST_AGENTS_DID_OUTPUT: + handler.output(notice.lines); + return; + case Protocol.HOST_AGENTS_DID_PROMPT: + handler.prompt(notice.turn, notice.text); + return; + case Protocol.HOST_AGENTS_DID_CANCEL: + handler.cancel(notice.turn); + return; + case Protocol.HOST_AGENTS_DID_DECIDE_PERMISSION: + handler.decidePermission(notice.turn, notice.permission, notice.option); + return; + default: + handler.exited(notice.exitCode); + } + } + + /** + * No handler ran the turn, so it ends here. The handler may have ended it + * already; Core then refuses the second end, which changes nothing. + */ + private static void endTurn(AgentSessionHandle handle, long turn) { + Map event = new LinkedHashMap<>(); + event.put("kind", "turnEnded"); + event.put("turn", turn); + event.put("reason", "failed"); + try { + handle.report(Collections.singletonList(event)).join(); + } catch (RuntimeException refused) { + // Core refused the end or the session closed; the turn is over either way. + } + } + + private void failed(Throwable error) { + if (!(Backend.unwrap(error) instanceof CancelledException)) { + backend.diagnostics().terminal(OPERATION, error, System.nanoTime()); + } + } + + private static Notice notice(String method, Map params) { + List lines = new ArrayList<>(); + Object raw = params.get("lines"); + if (raw instanceof List) { + for (Object line : (List) raw) { + lines.add(line instanceof String ? (String) line : ""); + } + } + Object turn = params.get("turn"); + Object exit = params.get("exitCode"); + return new Notice(method, Collections.unmodifiableList(lines), + turn instanceof Long && (Long) turn >= 0 ? (Long) turn : 0L, + string(params, "text"), string(params, "permission"), string(params, "option"), + exit instanceof Long ? (Long) exit : null); + } + + private static String string(Map params, String key) { + Object value = params.get(key); + return value instanceof String ? (String) value : ""; + } + + /** One notification for a session's worker. */ + private static final class Notice { + static final Notice CLOSED = new Notice("", Collections.emptyList(), 0, "", "", "", null); + + final String method; + final List lines; + final long turn; + final String text; + final String permission; + final String option; + final Long exitCode; + + Notice(String method, List lines, long turn, String text, String permission, String option, + Long exitCode) { + this.method = method; + this.lines = lines; + this.turn = turn; + this.text = text; + this.permission = permission; + this.option = option; + this.exitCode = exitCode; + } + } + + /** An unbounded queue of one session's notifications, so the reader never waits for a handler. */ + private static final class Worker { + private final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); + + void push(Notice notice) { + queue.add(notice); + } + + void close() { + queue.add(Notice.CLOSED); + } + + Notice take() throws InterruptedException { + return queue.take(); + } + } +} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java index 6ea46ba5..890898e1 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -144,6 +144,15 @@ public interface CommandHandler { void handle(String commandId, Map workspaceContext) throws Exception; } + /** + * Makes the translation of a native agent session Core started. A failure + * or null leaves the session without a handler: its turns end as failed. + */ + @FunctionalInterface + public interface AgentSessionStarter { + AgentSession start(AgentSessionStart start, AgentSessionHandle session) throws Exception; + } + /** Runs before the {@code initialize} answer. */ @FunctionalInterface public interface InitializeHook { @@ -219,6 +228,7 @@ private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED private final Map notificationHandlers = new HashMap<>(); private final Map commandHandlers = new HashMap<>(); private final Map hostNotificationHandlers = new HashMap<>(); + private final AgentSessions agentSessions = new AgentSessions(this); private NotificationHandler contextsHandler; private final List initializeHooks = new ArrayList<>(); private final List shutdownHooks = new ArrayList<>(); @@ -443,7 +453,8 @@ public Backend onContextsChanged(NotificationHandler handler) { /** * Handles a {@code lithe/host/*} notification a later host adds. Commands, - * context changes, and subscription events have their own APIs. + * context changes, subscription events, and agent sessions have their own + * APIs. */ public Backend onHostNotification(String method, NotificationHandler handler) { if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { @@ -454,6 +465,9 @@ public Backend onHostNotification(String method, NotificationHandler handler) { throw new PluginSdkError("sdk.method.reserved", method + " is routed by the SDK; use onCommand, onContextsChanged, or Host.subscribe."); } + if (AgentSessions.NOTIFICATIONS.contains(method)) { + throw new PluginSdkError("sdk.method.reserved", method + " is routed by the SDK; use onAgentSessions."); + } if (handler == null) { throw new IllegalArgumentException("A handler must not be null."); } @@ -463,6 +477,25 @@ public Backend onHostNotification(String method, NotificationHandler handler) { return this; } + /** + * Translates the native sessions of the plugin's agents (plan API-45). + * For each {@code lithe/host/agents/didStart}, {@code starter} makes the + * session's {@link AgentSession} on a worker of the session's own, which + * then gets the session's {@code didOutput}, {@code didPrompt}, + * {@code didCancel}, {@code didDecidePermission} and {@code didExit} one + * at a time, in the order Core sent them. When the start fails, or a + * prompt fails, the SDK reports {@code turnEnded} with reason + * {@code failed} for the turn. A later registration replaces the earlier + * one. + */ + public Backend onAgentSessions(AgentSessionStarter starter) { + if (starter == null) { + throw new IllegalArgumentException("A starter must not be null."); + } + agentSessions.starter(starter); + return this; + } + /** Runs before the {@code initialize} answer, with the host's params and the negotiation. */ public Backend onInitialize(InitializeHook hook) { synchronized (lock) { @@ -791,6 +824,10 @@ private void hostNotification(String method, Object raw) { notifyHandler(method, () -> handler.handle((String) commandId, context)); return; } + if (AgentSessions.NOTIFICATIONS.contains(method)) { + agentSessions.route(method, params, executor); + return; + } NotificationHandler handler; synchronized (lock) { handler = method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) ? contextsHandler : hostNotificationHandlers.get(method); @@ -1266,6 +1303,8 @@ private void finish(int code) { } channel.close(); cancelAll("The session ended."); + // Agent sessions still open get no further notices. + agentSessions.closeAll(); Processes.killAll(); for (Pending request : pending) { request.future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java index 77f422a6..22817a66 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java @@ -47,6 +47,11 @@ static String requestOperationId(String operationId, Object requestId) { return token(fallback, 128) ? fallback : null; } + /** {@code operationFailed} with a fixed code, for a failure no exception carries. */ + void failed(String operation, String code) { + record("operationFailed", operation, code, null, 0L); + } + void terminal(String operation, Throwable failure, long started) { String code = null; if (failure != null) { diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index 1e8ce7f7..251db210 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -1014,6 +1014,49 @@ public final class Clipboard { /** Write system clipboard text. Permission clipboard.write. */ public CompletableFuture> writeText(Map context,Map params) {return scoped(Protocol.HOST_CLIPBOARD_WRITE_TEXT,context,params);} } + /** + * Native agent sessions and agent usage totals (plan API-45). Core answers + * them; {@code write} and {@code report} need {@code agents.native}, + * {@code usage} needs {@code agents.usage.read}. + */ + public Agents agents() { + return new Agents(); + } + + public final class Agents { + /** Writes 1-256 lines, without line breaks, to the standard input of {@code session}'s CLI. */ + public CompletableFuture write(String session, List lines) { + return sessionRequest(Protocol.HOST_AGENTS_WRITE, session, "lines", lines); + } + + /** Reports 1-256 session events of {@code session}; one refused event refuses them all. */ + public CompletableFuture report(String session, List events) { + return sessionRequest(Protocol.HOST_AGENTS_REPORT, session, "events", events); + } + + /** + * {@code { sinceMs, untilMs, summaries, rateLimits }} for + * {@code { groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }}. + */ + public CompletableFuture> usage(Map params) { + Object message = params == null ? new LinkedHashMap() : params; + return channel.request(Protocol.HOST_AGENTS_USAGE, message, scope).thenApply(result -> { + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.host.invalidResult", + Protocol.HOST_AGENTS_USAGE + " answered with something other than an object."); + } + return Json.object(result); + }); + } + + private CompletableFuture sessionRequest(String method, String session, String key, List values) { + Map message = new LinkedHashMap<>(); + message.put("session", session); + message.put(key, values); + return channel.request(method, message, scope).thenApply(result -> null); + } + } + /** Native network services. */ public Network network() {return new Network();} public final class Network { diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java index 0e76f3b6..497f3642 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -117,10 +117,21 @@ public final class Protocol { public static final String HOST_FUNCTIONS_PROVIDERS = "lithe/host/functions/providers"; public static final String HOST_FUNCTIONS_INVOKE = "lithe/host/functions/invoke"; + /** Native agent sessions and agent usage totals (plan API-45), which Core answers. */ + public static final String HOST_AGENTS_WRITE = "lithe/host/agents/write"; + public static final String HOST_AGENTS_REPORT = "lithe/host/agents/report"; + public static final String HOST_AGENTS_USAGE = "lithe/host/agents/usage"; + /** Host-to-backend notifications. */ public static final String HOST_DID_CHANGE_CONTEXTS = "lithe/host/workspace/didChangeContexts"; public static final String HOST_SUBSCRIPTION_NOTIFY = "lithe/host/subscriptions/notify"; public static final String HOST_COMMAND_DID_RUN = "lithe/host/commands/didRun"; + public static final String HOST_AGENTS_DID_START = "lithe/host/agents/didStart"; + public static final String HOST_AGENTS_DID_OUTPUT = "lithe/host/agents/didOutput"; + public static final String HOST_AGENTS_DID_PROMPT = "lithe/host/agents/didPrompt"; + public static final String HOST_AGENTS_DID_CANCEL = "lithe/host/agents/didCancel"; + public static final String HOST_AGENTS_DID_DECIDE_PERMISSION = "lithe/host/agents/didDecidePermission"; + public static final String HOST_AGENTS_DID_EXIT = "lithe/host/agents/didExit"; /** JSON-RPC and LSP error codes the SDK answers with. */ public static final int PARSE_ERROR = -32700; diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java new file mode 100644 index 00000000..b32a2721 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java @@ -0,0 +1,270 @@ +package io.github.litheidea.plugin.sdk; + +import static io.github.litheidea.plugin.sdk.Fixtures.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +/** + * Native agent sessions and the agents host service (plan API-45), driven by + * {@code contract/v1/fixtures/agents/native-session.json}; mirrors + * {@code sdk/node/test/agents.test.mjs}. + */ +@Timeout(value = 30, unit = TimeUnit.SECONDS) +class AgentsTest { + private static final Map FIXTURE = loadFixture(); + + private static Map loadFixture() { + try { + return object(Json.parse(new String(Files.readAllBytes( + Paths.get("../../../contract/v1/fixtures/agents/native-session.json")), StandardCharsets.UTF_8))); + } catch (IOException error) { + throw new UncheckedIOException(error); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return (Map) value; + } + + @SuppressWarnings("unchecked") + private static List list(Object value) { + return (List) value; + } + + /** + * A backend whose handlers record every call as {@code [session, call, + * args...]}, as the fixture lists them. It fails to start sessions in + * /work/broken and fails prompts that say fail. agent-1's first output + * waits until agent-2 exited, so sessions sharing one worker never get + * past it. + */ + private static final class Recorder { + private final List> calls = new ArrayList<>(); + private final CountDownLatch otherExited = new CountDownLatch(1); + final Backend backend = Backend.create("agents-test", null); + + Recorder() { + backend.onAgentSessions((start, session) -> { + if (!session.id().equals(start.session())) { + throw new PluginError("test.wrongHandle", "The handle belongs to another session."); + } + if ("/work/broken".equals(start.cwd())) { + throw new PluginError("test.startFailed", "The start failed."); + } + String id = start.session(); + record(id, "start", map("session", id, "agentID", start.agentId(), "cwd", start.cwd(), + "resume", start.resume())); + return new AgentSession() { + @Override + public void output(List lines) { + if (id.equals("agent-1") && lines.contains("one")) { + Fixtures.await(otherExited, "agent-2 to exit while agent-1 waits"); + } + record(id, "output", lines); + } + + @Override + public void prompt(long turn, String text) { + record(id, "prompt", turn, text); + if (text.equals("fail")) { + throw new PluginError("test.promptFailed", "The prompt failed."); + } + } + + @Override + public void cancel(long turn) { + record(id, "cancel", turn); + } + + @Override + public void decidePermission(long turn, String permission, String option) { + record(id, "decidePermission", turn, permission, option); + } + + @Override + public void exited(Long exitCode) { + record(id, "exited", exitCode); + if (id.equals("agent-2")) { + otherExited.countDown(); + } + } + }; + }); + } + + private void record(Object... call) { + synchronized (calls) { + calls.add(Arrays.asList(call)); + calls.notifyAll(); + } + } + + /** The calls of every session, once {@code wanted} calls arrived. */ + Map bySession(int wanted) { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(TestHost.WAIT_MILLIS); + synchronized (calls) { + while (calls.size() < wanted) { + long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (remaining <= 0) { + throw new AssertionError("Timed out waiting for " + wanted + " session calls; got " + calls); + } + try { + calls.wait(remaining); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted waiting for session calls.", error); + } + } + Map sessions = new LinkedHashMap<>(); + for (List call : calls) { + list(sessions.computeIfAbsent((String) call.get(0), session -> new ArrayList<>())) + .add(call.subList(1, call.size())); + } + return sessions; + } + } + } + + private static int count(Object expected) { + int count = 0; + for (Object calls : object(expected).values()) { + count += list(calls).size(); + } + return count; + } + + private static void sendAll(TestHost host, Object notifications) { + for (Object notification : list(notifications)) { + Map entry = object(notification); + host.notify((String) entry.get("method"), entry.get("params")); + } + } + + private static List failureCodes(TestHost host) { + List codes = new ArrayList<>(); + for (Map message : host.messages()) { + if ("lithe/log".equals(message.get("method")) + && "operationFailed".equals(object(message.get("params")).get("kind"))) { + codes.add(object(message.get("params")).get("code")); + } + } + return codes; + } + + private static TestHost session(Backend backend) { + TestHost host = new TestHost(backend); + host.initialize(); + return host; + } + + @Test + void eachAgentSessionGetsItsNotificationsInOrderFromStartToExit() { + Recorder recorder = new Recorder(); + TestHost host = session(recorder.backend); + Map sessions = object(FIXTURE.get("sessions")); + sendAll(host, sessions.get("notifications")); + // Every session's last call is its exit, so nothing follows the count. + assertEquals(sessions.get("calls"), recorder.bySession(count(sessions.get("calls")))); + assertEquals(1, host.close()); + // agent-9 never started, so its output reaches no handler. + assertEquals(Collections.singletonList("agent_session_unknown"), failureCodes(host)); + } + + @Test + void aFailedAgentStartOrPromptEndsTheTurnAsFailed() { + Recorder recorder = new Recorder(); + TestHost host = session(recorder.backend); + Map failures = object(FIXTURE.get("failures")); + sendAll(host, failures.get("notifications")); + // Each worker waits for Core's answer, so answer the reports as they come. + Set answered = new HashSet<>(); + Set reports = new HashSet<>(); + for (int index = 0; index < list(failures.get("reports")).size(); index++) { + Map report = host.waitFor(message -> "lithe/host/agents/report".equals(message.get("method")) + && !answered.contains(message.get("id")), "a turnEnded report"); + answered.add(report.get("id")); + reports.add(report.get("params")); + host.send(map("id", report.get("id"), "result", map())); + } + assertEquals(new HashSet<>(list(failures.get("reports"))), reports); + assertEquals(failures.get("calls"), recorder.bySession(count(failures.get("calls")))); + assertEquals(1, host.close()); + } + + @Test + void agentHostMethodsSendTheFixtureRequests() { + Backend backend = Backend.create("agents-test", null); + TestHost host = session(backend); + Host.Agents agents = backend.host().agents(); + for (Object raw : list(FIXTURE.get("methods"))) { + Map entry = object(raw); + String call = (String) entry.get("call"); + String session = (String) entry.get("session"); + CompletableFuture pending; + if (call.equals("write")) { + List lines = new ArrayList<>(); + for (Object line : list(entry.get("lines"))) { + lines.add((String) line); + } + pending = agents.write(session, lines); + } else if (call.equals("report")) { + pending = agents.report(session, list(entry.get("events"))); + } else { + pending = agents.usage(object(entry.get("params"))); + } + Map request = object(entry.get("request")); + Map sent = host.waitFor(message -> request.get("method").equals(message.get("method")), + (String) request.get("method")); + assertEquals(request.get("params"), sent.get("params")); + Map answer = call.equals("usage") + ? map("sinceMs", 1L, "untilMs", 2L, "summaries", new ArrayList<>(), "rateLimits", new ArrayList<>()) + : map(); + host.send(map("id", sent.get("id"), "result", answer)); + Object result = Fixtures.await(pending, call); + if (call.equals("usage")) { + assertEquals(answer, result); + } else { + assertNull(result); + } + } + assertEquals(1, host.close()); + } + + @Test + void agentNotificationsAreRoutedOnlyThroughAgentSessions() { + Backend backend = Backend.create("agents-test", null); + for (String method : Arrays.asList("lithe/host/agents/didStart", "lithe/host/agents/didOutput", + "lithe/host/agents/didExit")) { + assertEquals("sdk.method.reserved", assertThrows(PluginSdkError.class, + () -> backend.onHostNotification(method, params -> {})).code()); + } + // Without a registration a started session is only logged. + TestHost host = session(backend); + host.notify("lithe/host/agents/didStart", map("session", "agent-1", "agentID", "example", "cwd", "/work/orders")); + host.notify("lithe/host/agents/didOutput", map("session", "agent-1", "lines", Collections.singletonList("one"))); + // The reader logs both before it reads the end of the input. + assertEquals(1, host.close()); + assertEquals(Collections.singletonList("agent_unhandled"), failureCodes(host)); + } +} diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index c7b07beb..2f3af9ed 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -213,6 +213,7 @@ stderr fallback and no plugin-owned file writer. | `backend.onCommand(commandID, handler)` | One of the plugin's commands ran; the handler gets `{ commandID, workspaceContext }`. | | `backend.onContextsChanged(handler)` | Workspace contexts opened, closed, or changed; the handler gets `{ revision }`. | | `backend.onHostNotification(method, handler)` | A `lithe/host/*` notification a later host adds. Unknown ones are ignored. | +| `backend.onAgentSessions(start)` | Translates the native sessions of the plugin's agents; see [Native agent sessions](#native-agent-sessions). | | `backend.vcs(id, handlers, traits?)` | Implements the typed VCS requests; see [A VCS provider](#a-vcs-provider). `litheVcs` is answered only when the host offers it. | | `backend.function(id, handler)` | Declares a function offered in `initialize`. | | `backend.view(id, handler)` | Declares a view function; see [Plugin views](#plugin-views). | @@ -293,6 +294,7 @@ backend.onCommand('db.refresh', async ({ workspaceContext }) => { | `documents.save`, `.saveAs`, `.close`; `workspace.create`, `.rename`, `.copy`, `.trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | | `preview.openHTML`, `browser.openExternal`, `window.showInformation`, `.showWarning`, `.showError` | Preview, browser, and messages. | | `functions.providers(functionID)` | The enabled plugins that export a function: `{ providers: [{ pluginID, version }] }`. See [Calling other plugins](#calling-other-plugins). | +| `agents.write(session, lines)`, `.report(session, events)`, `.usage(params)` | Native agent sessions and usage totals; see [Native agent sessions](#native-agent-sessions). | | `functions.invoke(context, call)` | Calls one provider's exported function in a workspace context: `{ value }`. `call` is `{ pluginID, functionID, params?, timeoutMilliseconds?, parentOperationID? }`. | | `request(method, params?)`, `subscribe(method, params, onEvent?)` | Any `lithe/host/*` method, including ones a later host adds. | | `subscriptions.dispose(id)` | Ends a subscription; `Subscription.dispose()` does the same. | @@ -555,6 +557,68 @@ reopen with bounded display history, disposal and exit subscriptions. They require `terminal.create`. See [the native terminal guide](../../guides/native-terminals.md). +## Native agent sessions + +A plugin whose [agent](../../contract/v1/README.md#agents) declares `native` +(plan API-45) translates between the agent CLI's own protocol and Lithe's +[session events](../../contract/v1/README.md#native-sessions). Core starts the +CLI with the command line the `native` function answered; the backend only +reads the lines the CLI writes, reports events, and writes the CLI's standard +input. It never sees the CLI's environment or credentials. + +The example below is for a fictional CLI that writes JSON lines +`{"type":"text","text":…}` and `{"type":"done"}` and reads `{"prompt":…}`. + +```js +backend.onAgentSessions((start, session) => { + let turn = 0; + return { + async prompt(next, text) { + turn = next; + await session.write([JSON.stringify({ prompt: text })]); + }, + async output(lines) { + const events = []; + for (const raw of lines) { + let line; + try { line = JSON.parse(raw); } catch { continue; } + if (line.type === 'text') { + events.push({ kind: 'message', turn, role: 'assistant', messageID: `reply-${turn}`, text: line.text, delta: true }); + } else if (line.type === 'done') { + events.push({ kind: 'turnEnded', turn, reason: 'completed' }); + } + } + if (events.length > 0) await session.report(events); + }, + async decidePermission(_turn, permission, option) { + await session.write([JSON.stringify({ permission, option })]); + }, + }; +}); +``` + +`start` carries `session`, `agentID`, `cwd` and `resume` (the CLI's own +session ID when the user resumes one). `cancel` and `exited` are optional. +`backend.host.agents` offers the same `write` and `report` for any session +ID, and `usage(params)` for usage totals. + +- Each session has its own worker. `didStart` makes the session's handler; + the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission` + and `didExit` then reach it one at a time, in the order Core sent them, so + a handler may wait for host requests. Other sessions keep running. +- When making the handler fails, or a prompt fails, the SDK reports + `turnEnded` with reason `failed` for the turn and logs the failure. Other + failures are only logged; a cancellation is not logged. +- A notification for a session that never started, or one that already + exited, is logged as `agent_session_unknown`. A started session without a + registration is logged as `agent_unhandled`. +- The six `lithe/host/agents/did*` notifications reach only this API; + registering one with `onHostNotification` fails with `sdk.method.reserved`. +- `write` and `report` need `agents.native` and act only on the plugin's own + sessions. `usage` needs `agents.usage.read` and answers + `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + never conversation text, titles, session IDs or directories. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index 472b6d01..8c462704 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -16,6 +16,7 @@ import { HostError, PluginError, PluginSdkError, toResponseError } from './error import { createHost, HostChannel } from './host.mjs'; import { killAllProcesses, runProcess } from './process.mjs'; import { + AGENT_NOTIFICATIONS, BUILD_VERSION, boundedText, ERROR_CODES, @@ -49,6 +50,9 @@ const BUILD_FORMATS = Object.freeze({ /** Host notifications the SDK routes itself; see `onCommand`, `onContextsChanged`, and `host.subscribe`. */ const ROUTED_NOTIFICATIONS = Object.freeze(Object.values(HOST_NOTIFICATIONS)); +/** Native agent session notifications, routed by `onAgentSessions`. */ +const AGENT_METHODS = Object.freeze(Object.values(AGENT_NOTIFICATIONS)); + /** VCS capabilities that describe the VCS rather than a request it answers. */ const VCS_TRAITS = Object.freeze(['push', 'staging']); @@ -88,6 +92,10 @@ class Backend { #commandHandlers = new Map(); #contextsHandler = null; #hostNotificationHandlers = new Map(); + /** `onAgentSessions`'s start function, or null. */ + #agentStarter = null; + /** Live agent sessions by session ID: `{ handler, tail }`, where `tail` runs its notifications in order. */ + #agentSessions = new Map(); #channel; #initializeHooks = []; #shutdownHooks = []; @@ -298,9 +306,28 @@ class Backend { return this; } + /** + * Translates the native sessions of the plugin's agents (plan API-45). For + * each `lithe/host/agents/didStart`, `start({ session, agentID, cwd, + * resume }, handle)` makes the session's handler, which then gets the + * session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission` + * and `didExit` one at a time, in the order Core sent them: each call + * waits for the promise of the one before. The handler has + * `output(lines)`, `prompt(turn, text)` and `decidePermission(turn, + * permission, option)`, and may have `cancel(turn)` and `exited(exitCode)`. + * `handle` has `id`, `host`, `write(lines)` and `report(events)`. When + * `start` fails, or a prompt fails, the SDK reports `turnEnded` with reason + * `failed` for the turn. A later registration replaces the earlier one. + */ + onAgentSessions(start) { + if (typeof start !== 'function') throw new TypeError('An agent session start must be a function.'); + this.#agentStarter = start; + return this; + } + /** * Handles a `lithe/host/*` notification a later host adds. Commands, - * context changes, and subscription events have their own APIs. + * context changes, subscription events, and agent sessions have their own APIs. */ onHostNotification(method, handler) { if (typeof method !== 'string' || !method.startsWith('lithe/host/')) { @@ -309,6 +336,9 @@ class Backend { if (ROUTED_NOTIFICATIONS.includes(method)) { throw new PluginSdkError('sdk.method.reserved', `${method} is routed by the SDK; use onCommand, onContextsChanged, or host.subscribe.`); } + if (AGENT_METHODS.includes(method)) { + throw new PluginSdkError('sdk.method.reserved', `${method} is routed by the SDK; use onAgentSessions.`); + } if (typeof handler !== 'function') throw new TypeError('A handler must be a function.'); this.#hostNotificationHandlers.set(method, handler); return this; @@ -438,6 +468,8 @@ class Backend { pending.reject(new PluginSdkError('sdk.session.closed', 'The session ended.')); } this.#outgoing.clear(); + // Sessions still open get no further notifications. + this.#agentSessions.clear(); input.off?.('data', onData); resolve(code); exit?.(code); @@ -557,6 +589,10 @@ class Backend { this.#channel.deliver(params); return; } + if (AGENT_METHODS.includes(method)) { + this.#agentNotification(method, params); + return; + } let handler; let event = params; if (method === HOST_NOTIFICATIONS.commandDidRun) { @@ -577,6 +613,64 @@ class Backend { .catch((error) => this.#diagnostics().terminal('notification', { code: failureKind(error) }, 0)); } + /** + * Hands one `lithe/host/agents/did*` notification to its session. Core + * checked its shape; a notification of a session the SDK did not start is + * dropped. + */ + #agentNotification(method, params) { + const session = typeof params.session === 'string' ? params.session : ''; + const failed = (code) => this.#diagnostics().terminal('notification', { code }, 0); + if (method === AGENT_NOTIFICATIONS.didStart) { + const start = this.#agentStarter; + if (!start) { + failed('agent_unhandled'); + return; + } + const handle = agentSessionHandle(session, this.host); + const entry = { handler: null, tail: null }; + entry.tail = Promise.resolve() + .then(() => start({ + session, + agentID: typeof params.agentID === 'string' ? params.agentID : '', + cwd: typeof params.cwd === 'string' ? params.cwd : '', + resume: typeof params.resume === 'string' ? params.resume : null, + }, handle)) + .then((handler) => { + if (!isObject(handler)) throw new TypeError('An agent session start returned no handler.'); + entry.handler = handler; + }) + .catch((error) => failed(failureKind(error))); + this.#agentSessions.set(session, entry); + return; + } + const entry = this.#agentSessions.get(session); + if (method === AGENT_NOTIFICATIONS.didExit) this.#agentSessions.delete(session); + if (!entry) { + if (this.#agentStarter) failed('agent_session_unknown'); + return; + } + const prompt = method === AGENT_NOTIFICATIONS.didPrompt; + const turn = Number.isSafeInteger(params.turn) ? params.turn : 0; + entry.tail = entry.tail.then(async () => { + const { handler } = entry; + let ok = handler !== null; + if (ok) { + try { + await deliverAgentNotification(handler, method, params, turn); + } catch (error) { + ok = false; + failed(failureKind(error)); + } + } + if (!ok && prompt) { + // No handler runs the turn, so it ends here. The handler may have + // ended it already; Core then refuses the second end. + await this.host.agents.report(session, [{ kind: 'turnEnded', turn, reason: 'failed' }]).catch(() => {}); + } + }); + } + async #initialize(id, params) { if (this.#phase !== 'listening') { this.#respond(id, undefined, { code: ERROR_CODES.invalidRequest, message: 'initialize was already received.' }); @@ -1012,6 +1106,35 @@ function buildResult(method, result) { return document; } +/** The host methods of one agent session. */ +function agentSessionHandle(session, host) { + return Object.freeze({ + id: session, + host, + /** `lithe/host/agents/write`: 1-256 lines for the CLI's standard input, without line breaks. */ + write: (lines, options) => host.agents.write(session, lines, options), + /** `lithe/host/agents/report`: 1-256 session events, applied together. */ + report: (events, options) => host.agents.report(session, events, options), + }); +} + +/** Calls the handler method one agent notification is for. */ +async function deliverAgentNotification(handler, method, params, turn) { + const text = (value) => (typeof value === 'string' ? value : ''); + switch (method) { + case AGENT_NOTIFICATIONS.didOutput: + return handler.output(Array.isArray(params.lines) ? params.lines.map(text) : []); + case AGENT_NOTIFICATIONS.didPrompt: + return handler.prompt(turn, text(params.text)); + case AGENT_NOTIFICATIONS.didCancel: + return handler.cancel?.(turn); + case AGENT_NOTIFICATIONS.didDecidePermission: + return handler.decidePermission(turn, text(params.permission), text(params.option)); + default: + return handler.exited?.(Number.isSafeInteger(params.exitCode) ? params.exitCode : null); + } +} + function isObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index 1116e6c5..0e03cc92 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -310,6 +310,28 @@ export function createHost(channel, callSignal, parentOperationId) { copy: scoped(HOST_METHODS.workspaceCopy), trash: scoped(HOST_METHODS.workspaceTrash), }), + /** + * Native agent sessions and usage totals (plan API-45). Core answers it; + * `write` and `report` need `agents.native`, `usage` `agents.usage.read`. + */ + agents: Object.freeze({ + /** Writes 1-256 lines, without line breaks, to the standard input of `session`'s CLI. */ + write: async (session, lines, options) => { + await request(HOST_METHODS.agentsWrite, { session, lines }, options); + }, + /** Reports 1-256 events of `session`; one refused event refuses them all. */ + report: async (session, events, options) => { + await request(HOST_METHODS.agentsReport, { session, events }, options); + }, + /** `{ sinceMs, untilMs, summaries, rateLimits }` for `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }`. */ + usage: async (params, options) => { + const result = await request(HOST_METHODS.agentsUsage, params, options); + if (typeof result !== 'object' || result === null || Array.isArray(result)) { + throw new PluginSdkError('sdk.host.invalidResult', `${HOST_METHODS.agentsUsage} answered with something other than an object.`); + } + return result; + }, + }), functions: Object.freeze({ providers: async (functionID, options) => { checkRelayFunctionId(functionID); diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 428b07f2..2c234a0f 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -434,6 +434,18 @@ export interface Host { * `sdk.functions.invalidCall`, or `sdk.host.invalidContext` for the * context, before anything is sent. */ + /** + * Native agent sessions and usage totals (plan API-45). Core answers it; + * `write` and `report` need `agents.native`, `usage` `agents.usage.read`. + */ + readonly agents: { + /** Writes 1-256 lines, without line breaks, to the standard input of `session`'s CLI. */ + write(session: string, lines: string[], options?: HostRequestOptions): Promise; + /** Reports 1-256 events of `session`; one refused event refuses them all. */ + report(session: string, events: AgentSessionEvent[], options?: HostRequestOptions): Promise; + /** Usage totals of the agents' sessions. */ + usage(params: AgentUsageParams, options?: HostRequestOptions): Promise; + }; readonly functions: { /** The enabled plugins other than this one that export `functionID`. */ providers(functionID: string, options?: HostRequestOptions): Promise; @@ -888,6 +900,11 @@ export interface Backend { onCommand(commandID: string, handler: (event: CommandEvent) => unknown): Backend; /** Handles `lithe/host/workspace/didChangeContexts`. */ onContextsChanged(handler: (event: { revision: number }) => unknown): Backend; + /** + * Translates the native sessions of the plugin's agents (plan API-45): one + * handler per session, called one notification at a time in Core's order. + */ + onAgentSessions(start: (start: AgentSessionStart, session: AgentSessionHandle) => AgentSession | Promise): Backend; /** Handles a `lithe/host/*` notification a later host adds. */ onHostNotification(method: string, handler: (params: JsonObject) => unknown): Backend; onInitialize(hook: (event: { params: JsonObject; negotiated: Negotiated }) => unknown): Backend; @@ -901,6 +918,60 @@ export interface Backend { export function createBackend(options?: BackendOptions): Backend; +/** What `lithe/host/agents/didStart` says about a session Core started. */ +export interface AgentSessionStart { + /** Core's ID of the session, such as `agent-1`. */ + session: string; + /** The `agents[].id` from the manifest. */ + agentID: string; + /** The working directory the CLI runs in. */ + cwd: string; + /** The CLI's own session ID to resume, or null. */ + resume: string | null; +} + +/** + * The plugin's translation of one native session. Each call waits for the + * one before; a rejected `prompt` ends its turn as failed. + */ +export interface AgentSession { + /** Lines the CLI wrote to standard output, without line breaks. */ + output(lines: string[]): unknown; + /** The user's prompt for `turn`; write what the CLI expects. */ + prompt(turn: number, text: string): unknown; + /** The user cancelled `turn`. */ + cancel?(turn: number): unknown; + /** The user answered permission request `permission` with `option`. */ + decidePermission(turn: number, permission: string, option: string): unknown; + /** The CLI ended; the session gets no further calls. */ + exited?(exitCode: number | null): unknown; +} + +/** The host methods of one agent session. */ +export interface AgentSessionHandle { + readonly id: string; + readonly host: Host; + write(lines: string[], options?: HostRequestOptions): Promise; + report(events: AgentSessionEvent[], options?: HostRequestOptions): Promise; +} + +/** A session event, as the contract README's Native sessions lists them, such as `{ kind: 'turnEnded', turn, reason }`. */ +export type AgentSessionEvent = JsonObject & { kind: string }; + +export interface AgentUsageParams { + groupBy: 'day' | 'agent' | 'model'; + sinceMs?: number; + untilMs?: number; + utcOffsetSeconds?: number; +} + +export interface AgentUsageResult extends JsonObject { + sinceMs: number; + untilMs: number; + summaries: JsonObject[]; + rateLimits: JsonObject[]; +} + export class PluginError extends Error { constructor(code: string, message: string, options?: { cause?: unknown }); readonly code: string; @@ -990,7 +1061,8 @@ export const HOST_METHODS: Readonly>; diff --git a/shared/plugins/sdk/node/src/protocol.mjs b/shared/plugins/sdk/node/src/protocol.mjs index 373b508e..a60d2561 100644 --- a/shared/plugins/sdk/node/src/protocol.mjs +++ b/shared/plugins/sdk/node/src/protocol.mjs @@ -105,6 +105,9 @@ export const HOST_METHODS = Object.freeze({ terminalOnExit: 'lithe/host/terminal/onExit', functionsProviders: 'lithe/host/functions/providers', functionsInvoke: 'lithe/host/functions/invoke', + agentsWrite: 'lithe/host/agents/write', + agentsReport: 'lithe/host/agents/report', + agentsUsage: 'lithe/host/agents/usage', }); /** Host-to-backend notifications. */ @@ -114,6 +117,16 @@ export const HOST_NOTIFICATIONS = Object.freeze({ commandDidRun: 'lithe/host/commands/didRun', }); +/** Native agent session notifications (plan API-45); see `onAgentSessions`. */ +export const AGENT_NOTIFICATIONS = Object.freeze({ + didStart: 'lithe/host/agents/didStart', + didOutput: 'lithe/host/agents/didOutput', + didPrompt: 'lithe/host/agents/didPrompt', + didCancel: 'lithe/host/agents/didCancel', + didDecidePermission: 'lithe/host/agents/didDecidePermission', + didExit: 'lithe/host/agents/didExit', +}); + /** * Host failure codes (`error.data.code`) and the JSON-RPC number Core sends * with each to a backend. A number never changes meaning; a later host adds diff --git a/shared/plugins/sdk/node/test/agents.test.mjs b/shared/plugins/sdk/node/test/agents.test.mjs new file mode 100644 index 00000000..bb36e03a --- /dev/null +++ b/shared/plugins/sdk/node/test/agents.test.mjs @@ -0,0 +1,160 @@ +// Native agent sessions and the agents host service (plan API-45), driven by +// the test host and contract/v1/fixtures/agents/native-session.json. + +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import { createBackend } from '../src/index.mjs'; +import { gate, TestHost, withTimeout } from './harness.mjs'; + +const fixture = JSON.parse( + readFileSync(new URL('../../../contract/v1/fixtures/agents/native-session.json', import.meta.url), 'utf8'), +); + +/** + * A backend whose handlers record every call as `[session, call, args...]`, + * as the fixture lists them. It fails to start sessions in /work/broken and + * fails prompts that say fail. agent-1's first output waits until agent-2 + * exited, so sessions sharing one queue never get past it. + */ +function recordingBackend() { + const calls = []; + const waiters = []; + const otherExited = gate(); + const backend = createBackend({ name: 'agents-test' }); + backend.onAgentSessions(async (start, session) => { + assert.equal(session.id, start.session); + if (start.cwd === '/work/broken') throw new Error('start_failed'); + const record = (...call) => { + calls.push([start.session, ...call]); + for (const waiter of waiters.splice(0)) waiter(); + }; + record('start', { ...start }); + return { + async output(lines) { + if (start.session === 'agent-1' && lines.includes('one')) { + await withTimeout(otherExited.opened, 'agent-2 to exit while agent-1 waits'); + } + record('output', lines); + }, + async prompt(turn, text) { + record('prompt', turn, text); + if (text === 'fail') throw new Error('prompt_failed'); + }, + cancel(turn) { + record('cancel', turn); + }, + decidePermission(turn, permission, option) { + record('decidePermission', turn, permission, option); + }, + exited(exitCode) { + record('exited', exitCode); + if (start.session === 'agent-2') otherExited.open(); + }, + }; + }); + + /** + * The calls of every session once `wanted` calls arrived. Every session's + * last call is its exit, so nothing follows the count. + */ + async function bySession(wanted) { + await withTimeout(new Promise((resolve) => { + const check = () => (calls.length >= wanted ? resolve() : waiters.push(check)); + check(); + }), `${wanted} session calls`); + const sessions = {}; + for (const [session, ...call] of calls) (sessions[session] ??= []).push(call); + return sessions; + } + + return { backend, bySession }; +} + +function sendAll(host, notifications) { + for (const { method, params } of notifications) host.notify(method, params); +} + +function count(expected) { + return Object.values(expected).reduce((sum, calls) => sum + calls.length, 0); +} + +function failureCodes(host) { + return host.messages + .filter((message) => message.method === 'lithe/log' && message.params.kind === 'operationFailed') + .map((message) => message.params.code); +} + +test('each agent session gets its notifications in order from start to exit', async () => { + const { backend, bySession } = recordingBackend(); + const host = new TestHost(backend); + await host.initialize(); + sendAll(host, fixture.sessions.notifications); + const expected = fixture.sessions.calls; + assert.deepEqual(await bySession(count(expected)), expected); + assert.equal(await host.close(), 1); + // agent-9 never started, so its output reaches no handler. + assert.deepEqual(failureCodes(host), ['agent_session_unknown']); +}); + +test('a failed agent start or prompt ends the turn as failed', async () => { + const { backend, bySession } = recordingBackend(); + const host = new TestHost(backend); + await host.initialize(); + const { failures } = fixture; + sendAll(host, failures.notifications); + // Each session waits for Core's answer, so answer the reports as they come. + const answered = new Set(); + const reports = []; + for (let index = 0; index < failures.reports.length; index += 1) { + const report = await host.waitFor( + (message) => message.method === 'lithe/host/agents/report' && !answered.has(message.id), + 'a turnEnded report', + ); + answered.add(report.id); + reports.push(report.params); + host.send({ id: report.id, result: {} }); + } + const sorted = (list) => list.map((report) => JSON.stringify(report)).sort(); + assert.deepEqual(sorted(reports), sorted(failures.reports)); + assert.deepEqual(await bySession(count(failures.calls)), failures.calls); + assert.equal(await host.close(), 1); +}); + +test('agent host methods send the fixture requests', async () => { + const backend = createBackend({ name: 'agents-test' }); + const host = new TestHost(backend); + await host.initialize(); + for (const entry of fixture.methods) { + const before = host.messages.length; + const call = entry.call === 'write' + ? backend.host.agents.write(entry.session, entry.lines) + : entry.call === 'report' + ? backend.host.agents.report(entry.session, entry.events) + : backend.host.agents.usage(entry.params); + const request = await host.waitFor( + (message) => host.messages.indexOf(message) >= before && message.method === entry.request.method, + entry.request.method, + ); + assert.deepEqual(request.params, entry.request.params); + const answer = entry.call === 'usage' ? { sinceMs: 1, untilMs: 2, summaries: [], rateLimits: [] } : {}; + host.send({ id: request.id, result: answer }); + assert.deepEqual(await withTimeout(call, entry.call), entry.call === 'usage' ? answer : undefined); + } + assert.equal(await host.close(), 1); +}); + +test('agent notifications are routed only through agent sessions', async () => { + const backend = createBackend({ name: 'agents-test' }); + for (const method of ['lithe/host/agents/didStart', 'lithe/host/agents/didOutput', 'lithe/host/agents/didExit']) { + assert.throws(() => backend.onHostNotification(method, () => {}), { code: 'sdk.method.reserved' }); + } + // Without a registration a started session is only logged. + const host = new TestHost(backend); + await host.initialize(); + host.notify('lithe/host/agents/didStart', { session: 'agent-1', agentID: 'example', cwd: '/work/orders' }); + host.notify('lithe/host/agents/didOutput', { session: 'agent-1', lines: ['one'] }); + // The backend reads both before it reads the end of the input. + assert.equal(await host.close(), 1); + assert.deepEqual(failureCodes(host), ['agent_unhandled']); +}); diff --git a/shared/plugins/sdk/node/test/types/agents.mts b/shared/plugins/sdk/node/test/types/agents.mts new file mode 100644 index 00000000..a16cff19 --- /dev/null +++ b/shared/plugins/sdk/node/test/types/agents.mts @@ -0,0 +1,44 @@ +// Check the agent-session declarations the way an agent plugin uses them. +import { + createBackend, + HOST_METHODS, + type AgentSession, + type AgentSessionHandle, + type AgentSessionStart, + type AgentUsageResult, +} from '@lithe/plugin-sdk'; + +const backend = createBackend(); +const usageMethod: string = HOST_METHODS.agentsUsage; +void usageMethod; + +backend.onAgentSessions((start: AgentSessionStart, session: AgentSessionHandle): AgentSession => { + const resume: string | null = start.resume; + void resume; + return { + async output(lines: string[]) { + for (const line of lines) { + await session.report([{ kind: 'message', turn: 1, role: 'assistant', messageID: 'm1', text: line, delta: true }]); + } + }, + async prompt(turn: number, text: string) { + await session.write([JSON.stringify({ type: 'user', turn, text })]); + }, + async decidePermission(turn: number, permission: string, option: string) { + await session.write([JSON.stringify({ turn, permission, option })]); + }, + exited(exitCode: number | null) { + void exitCode; + }, + }; +}); + +backend.function('usage.today', async (_params, context) => { + const usage: AgentUsageResult = await context.host.agents.usage({ groupBy: 'day', utcOffsetSeconds: 28800 }); + return { summaries: usage.summaries.length }; +}); + +// @ts-expect-error groupBy is day, agent or model. +void backend.host.agents.usage({ groupBy: 'session' }); +// @ts-expect-error a handler answers prompts. +backend.onAgentSessions(() => ({ output() {}, decidePermission() {} })); diff --git a/shared/plugins/sdk/node/test/types/tsconfig.json b/shared/plugins/sdk/node/test/types/tsconfig.json index 7be8dfa8..a9fb611c 100644 --- a/shared/plugins/sdk/node/test/types/tsconfig.json +++ b/shared/plugins/sdk/node/test/types/tsconfig.json @@ -7,5 +7,5 @@ "noEmit": true, "types": ["node"] }, - "files": ["build.mts", "host.mts", "keymap.mts", "view.mts"] + "files": ["agents.mts", "build.mts", "host.mts", "keymap.mts", "view.mts"] } diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 3ce69dcc..8d8ea037 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -316,6 +316,7 @@ fallback and no plugin-owned file writer. | `handle.function_ids()`, `handle.functions_version()` | What the backend serves, and `Some(0)` when the host offered `litheFunctions` (otherwise `None`). | | `backend.on_command(id, handler)` | Runs `Fn(&str, Option)` when the user runs one of the plugin's commands. | | `backend.on_contexts_changed(handler)`, `backend.on_host_notification(method, handler)` | Handle `lithe/host/workspace/didChangeContexts` and any other `lithe/host/*` notification a later host adds. | +| `backend.on_agent_sessions(start)` | Translates the native sessions of the plugin's agents; see [Native agent sessions](#native-agent-sessions). | | `handle.host()`, `context.host()` | The [host services](#host-services). `handle.host()` is bound to no call. | | `handle.credentials()`, `context.credentials()` | Shorthand for `host().credentials()`. | | `backend.build_model(handler)` and the other `build_*` methods | Declare the typed build requests; see [Build providers](#build-providers). | @@ -378,6 +379,7 @@ backend | `Host` member | Purpose | | --- | --- | | `credentials().get(key)`, `.set(key, secret)`, `.delete(key)` | Secrets in the platform's store; see [Credentials](#credentials). | +| `agents().write(session, lines)`, `.report(session, events)`, `.usage(params)` | Native agent sessions and usage totals; see [Native agent sessions](#native-agent-sessions). | | `capabilities()`, `supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | | `workspace().list_contexts()`, `.get_context(&context)`, `.get_folders(&context)` | Workspace contexts; only `get_context` returns, and creates, the context's `stateDirectory`. | | `workspace().read_directory`, `.stat`, `.read_file`, `.find_files`, `.find_text`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `get_folders`. | @@ -646,6 +648,88 @@ host methods discovered through `capabilities()`; they require a host that offers them and the `terminal.create` permission. See [the native terminal guide](../../guides/native-terminals.md). +## Native agent sessions + +A plugin whose [agent](../../contract/v1/README.md#agents) declares `native` +(plan API-45) translates between the agent CLI's own protocol and Lithe's +[session events](../../contract/v1/README.md#native-sessions). Core starts the +CLI with the command line the `native` function answered; the backend only +reads the lines the CLI writes, reports events, and writes the CLI's standard +input. It never sees the CLI's environment or credentials. + +The example below is for a fictional CLI that writes JSON lines +`{"type":"text","text":…}` and `{"type":"done"}` and reads `{"prompt":…}`. + +```rust +use lithe_plugin_sdk::{AgentSession, AgentSessionHandle, Backend, FunctionError}; +use serde_json::{json, Value}; + +struct Translator { + session: AgentSessionHandle, + turn: u64, +} + +impl AgentSession for Translator { + fn prompt(&mut self, turn: u64, text: String) -> Result<(), FunctionError> { + self.turn = turn; + self.session.write(&[json!({ "prompt": text }).to_string()])?; + Ok(()) + } + + fn output(&mut self, lines: Vec) -> Result<(), FunctionError> { + let mut events = Vec::new(); + for line in lines { + let Ok(line) = serde_json::from_str::(&line) else { continue }; + match line["type"].as_str() { + Some("text") => events.push(json!({ + "kind": "message", "turn": self.turn, "role": "assistant", + "messageID": format!("reply-{}", self.turn), "text": line["text"], "delta": true, + })), + Some("done") => events.push(json!({ "kind": "turnEnded", "turn": self.turn, "reason": "completed" })), + _ => {} + } + } + if !events.is_empty() { + self.session.report(&events)?; + } + Ok(()) + } + + fn decide_permission(&mut self, _turn: u64, permission: String, option: String) -> Result<(), FunctionError> { + self.session.write(&[json!({ "permission": permission, "option": option }).to_string()])?; + Ok(()) + } +} + +fn main() { + let mut backend = Backend::new("example-agent"); + backend.on_agent_sessions(|_start, session| Ok(Box::new(Translator { session, turn: 0 }))); + std::process::exit(backend.listen()); +} +``` + +`AgentSessionStart` carries `session`, `agent_id`, `cwd` and `resume` (the +CLI's own session ID when the user resumes one). `cancel` and `exited` have +empty defaults. `handle.host().agents()` offers the same `write` and `report` +for any session ID, and `usage(params)` for usage totals. + +- Each session has its own worker. `didStart` makes the session's handler; + the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission` + and `didExit` then reach it one at a time, in the order Core sent them, so + a handler may wait for host requests. Other sessions keep running. +- When making the handler fails, or a prompt fails, the SDK reports + `turnEnded` with reason `failed` for the turn and logs the failure. Other + failures are only logged; a cancellation is not logged. +- A notification for a session that never started, or one that already + exited, is logged as `agent_session_unknown`. A started session without a + registration is logged as `agent_unhandled`. +- The six `lithe/host/agents/did*` notifications reach only this API; + registering one with `on_host_notification` fails with `sdk.method.reserved`. +- `write` and `report` need `agents.native` and act only on the plugin's own + sessions. `usage` needs `agents.usage.read` and answers + `{sinceMs, untilMs, summaries, rateLimits}`: numbers and model names only, + never conversation text, titles, session IDs or directories. + ## Testing Run these from the root of this repository: diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs new file mode 100644 index 00000000..3c771f3c --- /dev/null +++ b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs @@ -0,0 +1,328 @@ +//! Native agent sessions and the `agents` host service (plan API-45). +//! +//! Core starts an agent's CLI and relays it through the plugin backend: the +//! CLI's standard output arrives as `lithe/host/agents/didOutput`, the user's +//! prompts, cancellations and permission decisions as `didPrompt`, +//! `didCancel` and `didDecidePermission`, and the backend answers with +//! `lithe/host/agents/write` (the CLI's standard input) and +//! `lithe/host/agents/report` (session events). A translation is only right +//! when it sees the CLI's lines in order, so the SDK gives every session one +//! worker thread that runs its handler's methods one at a time, in the order +//! Core sent the notifications. + +use crate::backend::{failure_kind, Shared}; +use crate::error::FunctionError; +use crate::host::Host; +use crate::panic_boundary::catch as catch_unwind; +use crate::protocol::methods; +use crate::SdkError; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::panic::AssertUnwindSafe; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread; + +/// What `lithe/host/agents/didStart` says about a session Core started. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AgentSessionStart { + /// Core's ID of the session, such as `agent-1`. + pub session: String, + /// The `agents[].id` from the manifest. + pub agent_id: String, + /// The working directory the CLI runs in. + pub cwd: String, + /// The CLI's own session ID to resume, when the user resumes one. + pub resume: Option, +} + +/// The plugin's translation of one native session. Every method runs on +/// the session's own thread, one at a time and in the order Core sent the +/// notifications, so a method may block on host requests. +/// +/// A failing [`prompt`](Self::prompt) ends its turn: the SDK reports +/// `turnEnded` with reason `failed`. Other failures are only logged. +pub trait AgentSession: Send { + /// Lines the CLI wrote to standard output, without line breaks. + fn output(&mut self, lines: Vec) -> Result<(), FunctionError>; + /// The user's prompt for `turn`; write what the CLI expects. + fn prompt(&mut self, turn: u64, text: String) -> Result<(), FunctionError>; + /// The user cancelled `turn`. + fn cancel(&mut self, _turn: u64) -> Result<(), FunctionError> { + Ok(()) + } + /// The user answered permission request `permission` with `option`. + fn decide_permission( + &mut self, + turn: u64, + permission: String, + option: String, + ) -> Result<(), FunctionError>; + /// The CLI ended; the session gets no further calls. + fn exited(&mut self, _exit_code: Option) {} +} + +/// The host methods of one session: [`write`](Self::write) to the CLI's +/// standard input and [`report`](Self::report) session events. +#[derive(Clone)] +pub struct AgentSessionHandle { + id: String, + host: Host, +} + +impl AgentSessionHandle { + /// Core's ID of the session. + pub fn id(&self) -> &str { + &self.id + } + + /// Host services outside the session, such as other plugins' functions. + pub fn host(&self) -> &Host { + &self.host + } + + /// `lithe/host/agents/write`: 1-256 lines for the CLI's standard input, + /// without line breaks; Core adds the newline. + pub fn write>(&self, lines: &[S]) -> Result<(), SdkError> { + self.host.agents().write(&self.id, lines) + } + + /// `lithe/host/agents/report`: 1-256 session events, applied together. + pub fn report(&self, events: &[Value]) -> Result<(), SdkError> { + self.host.agents().report(&self.id, events) + } +} + +/// The host's `agents` service. Core answers it; each method needs its own +/// grant: `write` and `report` `agents.native`, `usage` `agents.usage.read`. +pub struct Agents { + pub(crate) host: Host, +} + +impl Agents { + /// Writes `lines` to the standard input of `session`'s CLI. + pub fn write>(&self, session: &str, lines: &[S]) -> Result<(), SdkError> { + let lines: Vec<&str> = lines.iter().map(AsRef::as_ref).collect(); + self.host + .request( + methods::AGENTS_WRITE, + json!({ "session": session, "lines": lines }), + ) + .map(drop) + } + + /// Reports `events` of `session`; one refused event refuses them all. + pub fn report(&self, session: &str, events: &[Value]) -> Result<(), SdkError> { + self.host + .request( + methods::AGENTS_REPORT, + json!({ "session": session, "events": events }), + ) + .map(drop) + } + + /// The usage totals `{ sinceMs, untilMs, summaries, rateLimits }` for + /// `{ groupBy, sinceMs?, untilMs?, utcOffsetSeconds? }`. + pub fn usage(&self, params: Value) -> Result { + match self.host.request(methods::AGENTS_USAGE, params)? { + result @ Value::Object(_) => Ok(result), + _ => Err(SdkError::new( + "sdk.host.invalidResult", + "lithe/host/agents/usage answered with something other than an object.", + )), + } + } +} + +pub(crate) type AgentFactory = Arc< + dyn Fn(AgentSessionStart, AgentSessionHandle) -> Result, FunctionError> + + Send + + Sync, +>; + +/// One notification for a session's worker. +enum Notice { + Output(Vec), + Prompt(u64, String), + Cancel(u64), + Decide(u64, String, String), + Exit(Option), +} + +/// The workers of the live sessions, by session ID. When the backend stops +/// serving, the queues are dropped and each worker ends after its current +/// call. +#[derive(Default)] +pub(crate) struct AgentWorkers { + sessions: Mutex>>, +} + +pub(crate) fn is_agent_notification(method: &str) -> bool { + [ + methods::AGENTS_DID_START, + methods::AGENTS_DID_OUTPUT, + methods::AGENTS_DID_PROMPT, + methods::AGENTS_DID_CANCEL, + methods::AGENTS_DID_DECIDE_PERMISSION, + methods::AGENTS_DID_EXIT, + ] + .contains(&method) +} + +impl AgentWorkers { + /// Routes one `lithe/host/agents/did*` notification. Core checked its + /// shape; a notification of a session the SDK did not start is dropped. + pub(crate) fn route( + &self, + shared: &Arc, + factory: Option<&AgentFactory>, + method: &str, + params: &Value, + ) { + let session = params["session"].as_str().unwrap_or_default().to_string(); + if method == methods::AGENTS_DID_START { + let Some(factory) = factory else { + return shared.failed("notification", "agent_unhandled"); + }; + let start = AgentSessionStart { + session: session.clone(), + agent_id: text(¶ms["agentID"]), + cwd: text(¶ms["cwd"]), + resume: params["resume"].as_str().map(str::to_string), + }; + let (sender, receiver) = mpsc::channel(); + let spawned = { + let shared = Arc::clone(shared); + let factory = Arc::clone(factory); + thread::Builder::new() + .name(format!("lithe-agent-{session}")) + .spawn(move || run(&shared, &factory, start, &receiver)) + }; + match spawned { + Ok(_) => { + lock(&self.sessions).insert(session, sender); + } + Err(_) => shared.failed("notification", "worker_start_failed"), + } + return; + } + let notice = match method { + methods::AGENTS_DID_OUTPUT => Notice::Output( + params["lines"] + .as_array() + .map(|lines| lines.iter().map(text).collect()) + .unwrap_or_default(), + ), + methods::AGENTS_DID_PROMPT => { + Notice::Prompt(turn(¶ms["turn"]), text(¶ms["text"])) + } + methods::AGENTS_DID_CANCEL => Notice::Cancel(turn(¶ms["turn"])), + methods::AGENTS_DID_DECIDE_PERMISSION => Notice::Decide( + turn(¶ms["turn"]), + text(¶ms["permission"]), + text(¶ms["option"]), + ), + _ => Notice::Exit(params["exitCode"].as_i64()), + }; + let exit = matches!(notice, Notice::Exit(_)); + let mut sessions = lock(&self.sessions); + let sender = if exit { + sessions.remove(&session) + } else { + sessions.get(&session).cloned() + }; + drop(sessions); + match sender { + Some(sender) => { + // A worker that already ended has nothing left to run. + let _ = sender.send(notice); + } + None if factory.is_some() => shared.failed("notification", "agent_session_unknown"), + None => {} + } + } +} + +/// Runs one session: starts its handler, then its notifications in order. +fn run( + shared: &Arc, + factory: &AgentFactory, + start: AgentSessionStart, + receiver: &mpsc::Receiver, +) { + let handle = AgentSessionHandle { + id: start.session.clone(), + host: Host::new(Arc::clone(shared), Vec::new()), + }; + let mut handler = match catch_unwind(AssertUnwindSafe(|| factory(start, handle.clone()))) { + Ok(Ok(handler)) => Some(handler), + Ok(Err(error)) => { + shared.failed("notification", failure_kind(&error)); + None + } + Err(_) => { + shared.failed("notification", "panic"); + None + } + }; + while let Ok(notice) = receiver.recv() { + let prompt = match ¬ice { + Notice::Prompt(turn, _) => Some(*turn), + _ => None, + }; + let exit = matches!(notice, Notice::Exit(_)); + let outcome = match handler.as_mut() { + Some(handler) => catch_unwind(AssertUnwindSafe(|| deliver(handler.as_mut(), notice))), + None => Ok(Err(FunctionError::Cancelled)), + }; + let failed = match outcome { + Ok(Ok(())) => false, + Ok(Err(FunctionError::Cancelled)) => true, + Ok(Err(error)) => { + shared.failed("notification", failure_kind(&error)); + true + } + Err(_) => { + shared.failed("notification", "panic"); + true + } + }; + if let (true, Some(turn)) = (failed, prompt) { + // No handler runs the turn, so it ends here. The handler may + // have ended it already; Core then refuses the second end. + let _ = + handle.report(&[json!({ "kind": "turnEnded", "turn": turn, "reason": "failed" })]); + } + if exit { + break; + } + } +} + +fn deliver(handler: &mut dyn AgentSession, notice: Notice) -> Result<(), FunctionError> { + match notice { + Notice::Output(lines) => handler.output(lines), + Notice::Prompt(turn, text) => handler.prompt(turn, text), + Notice::Cancel(turn) => handler.cancel(turn), + Notice::Decide(turn, permission, option) => { + handler.decide_permission(turn, permission, option) + } + Notice::Exit(code) => { + handler.exited(code); + Ok(()) + } + } +} + +fn text(value: &Value) -> String { + value.as_str().unwrap_or_default().to_string() +} + +fn turn(value: &Value) -> u64 { + value.as_u64().unwrap_or_default() +} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs index 46995599..89a6fa11 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs @@ -7,6 +7,10 @@ //! Contract: `contract/v1/README.md` ("Plugin backend", "Plugin functions", //! and "Host services"). +use crate::agents::{ + is_agent_notification, AgentFactory, AgentSession, AgentSessionHandle, AgentSessionStart, + AgentWorkers, +}; use crate::build::{self, BuildContext}; use crate::diagnostics::{Diagnostics, OPERATIONS}; use crate::error::{ @@ -157,6 +161,8 @@ pub struct Backend { commands: HashMap, contexts_changed: Option, host_notifications: HashMap, + agent_sessions: Option, + agent_workers: AgentWorkers, } impl Backend { @@ -196,6 +202,8 @@ impl Backend { commands: HashMap::new(), contexts_changed: None, host_notifications: HashMap::new(), + agent_sessions: None, + agent_workers: AgentWorkers::default(), } } @@ -475,8 +483,31 @@ impl Backend { self } + /// Translates the native sessions of the plugin's agents (plan API-45). + /// For each `lithe/host/agents/didStart`, `start` makes the session's + /// [`AgentSession`] on a thread of the session's own, which then gets the + /// session's `didOutput`, `didPrompt`, `didCancel`, + /// `didDecidePermission` and `didExit` one at a time, in the order Core + /// sent them. When `start` fails, or a prompt fails, the SDK reports + /// `turnEnded` with reason `failed` for the turn. A later registration + /// replaces the earlier one. + pub fn on_agent_sessions(&mut self, start: F) -> &mut Self + where + F: Fn( + AgentSessionStart, + AgentSessionHandle, + ) -> Result, FunctionError> + + Send + + Sync + + 'static, + { + self.agent_sessions = Some(Arc::new(start)); + self + } + /// Handles a `lithe/host/*` notification a later host adds. Commands, - /// context changes, and subscription events have their own APIs. + /// context changes, subscription events and agent sessions have their + /// own APIs. pub fn on_host_notification( &mut self, method: &str, @@ -503,6 +534,12 @@ impl Backend { format!("{method} is routed by the SDK; use on_command, on_contexts_changed, or Host::subscribe."), )); } + if is_agent_notification(method) { + return Err(SdkError::new( + "sdk.method.reserved", + format!("{method} is routed by the SDK; use on_agent_sessions."), + )); + } self.host_notifications .insert(method.to_string(), Arc::new(handler)); Ok(self) @@ -667,6 +704,10 @@ impl Backend { } match method { methods::SUBSCRIPTION_NOTIFY => self.shared.deliver(params), + method if is_agent_notification(method) => { + self.agent_workers + .route(&self.shared, self.agent_sessions.as_ref(), method, params) + } methods::COMMAND_DID_RUN => { let command_id = params["commandID"].as_str().unwrap_or_default(); let Some(handler) = self.commands.get(command_id).cloned() else { @@ -1458,7 +1499,7 @@ fn check_new_function(id: &str, functions: &BTreeMap) -> Result // Failure values can contain user data. Never format their messages or panic payloads // into diagnostics; preserve the existing response contract separately. -fn failure_kind(error: &FunctionError) -> &'static str { +pub(crate) fn failure_kind(error: &FunctionError) -> &'static str { match error { FunctionError::Plugin(_) => "plugin_error", FunctionError::Internal(_) => "internal_error", diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index 5b19ebab..f7ccad36 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -8,6 +8,7 @@ //! Contract: `contract/v1/README.md`, "Host services" and the host sections //! after it. +use crate::agents::Agents; use crate::backend::{lock, Cancellation, Phase, Shared, State}; use crate::error::{sdk_codes, SdkError}; use crate::protocol::{ @@ -539,6 +540,12 @@ impl Host { Window { host: self.clone() } } + /// The `agents` service of native agent sessions and usage totals + /// (plan API-45); Core answers it, and each method needs its own grant. + pub fn agents(&self) -> Agents { + Agents { host: self.clone() } + } + /// Calls to other plugins' functions through Core. pub fn functions(&self) -> Functions { Functions { host: self.clone() } diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index c9c5dbbe..84a85b49 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -15,6 +15,10 @@ //! subscriptions, the commands and context changes the host notifies, and //! calls to the functions other plugins export through Core's relay //! ([`Functions`]) with the [`Caller`] of a function called that way; +//! - **[Agent sessions](Backend::on_agent_sessions)**: native sessions of +//! the plugin's agent CLIs, translated in order, and the [`Agents`] +//! service that writes to the CLI, reports session events, and reads +//! usage totals (plan API-45); //! - **`litheKeymapImport`**: shortcut import providers; //! - **`litheToolchains`**: [toolchain discovery providers](toolchains); //! - **`litheBuild`**: a build provider's typed `lithe/build/*` requests, @@ -33,6 +37,7 @@ //! //! See [`Backend`] for a minimal backend. +mod agents; mod backend; mod build; mod diagnostics; @@ -45,6 +50,7 @@ mod stdio; pub mod toolchains; pub mod view; +pub use agents::{AgentSession, AgentSessionHandle, AgentSessionStart, Agents}; pub use backend::{ Backend, BackendHandle, Caller, Cancellation, Context, Initialize, KeymapImportRequest, KeymapSourceFile, diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index 902b2a2a..c80c66a5 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -103,6 +103,15 @@ pub(crate) mod methods { pub const SUBSCRIPTION_NOTIFY: &str = "lithe/host/subscriptions/notify"; pub const COMMAND_DID_RUN: &str = "lithe/host/commands/didRun"; pub const FUNCTIONS_PROVIDERS: &str = "lithe/host/functions/providers"; + pub const AGENTS_WRITE: &str = "lithe/host/agents/write"; + pub const AGENTS_REPORT: &str = "lithe/host/agents/report"; + pub const AGENTS_USAGE: &str = "lithe/host/agents/usage"; + pub const AGENTS_DID_START: &str = "lithe/host/agents/didStart"; + pub const AGENTS_DID_OUTPUT: &str = "lithe/host/agents/didOutput"; + pub const AGENTS_DID_PROMPT: &str = "lithe/host/agents/didPrompt"; + pub const AGENTS_DID_CANCEL: &str = "lithe/host/agents/didCancel"; + pub const AGENTS_DID_DECIDE_PERMISSION: &str = "lithe/host/agents/didDecidePermission"; + pub const AGENTS_DID_EXIT: &str = "lithe/host/agents/didExit"; pub const FUNCTIONS_INVOKE: &str = "lithe/host/functions/invoke"; pub const BUILD_MODEL: &str = "lithe/build/model"; pub const BUILD_DEPENDENCIES: &str = "lithe/build/dependencies"; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs new file mode 100644 index 00000000..bc7fc86a --- /dev/null +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs @@ -0,0 +1,294 @@ +//! Native agent sessions and the `agents` host service (plan API-45), driven +//! by a scripted host and `fixtures/agents/native-session.json`. + +mod common; + +use common::{Host, WAIT}; +use lithe_plugin_sdk::{ + AgentSession, AgentSessionHandle, AgentSessionStart, Backend, FunctionError, +}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::Path; +use std::sync::{mpsc, Arc, Condvar, Mutex}; +use std::thread; + +fn fixture() -> Value { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../../contract/v1/fixtures/agents/native-session.json"); + let text = + fs::read_to_string(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display())); + serde_json::from_str(&text).expect("the fixture is JSON") +} + +/// Opens once agent-2 exited. agent-1's first output waits for it, so +/// sessions sharing one worker never get past it. +#[derive(Clone, Default)] +struct Gate(Arc<(Mutex, Condvar)>); + +impl Gate { + fn open(&self) { + *self.0 .0.lock().unwrap() = true; + self.0 .1.notify_all(); + } + + fn wait(&self) { + let (open, ready) = &*self.0; + let (open, timeout) = ready + .wait_timeout_while(open.lock().unwrap(), WAIT, |open| !*open) + .unwrap(); + assert!(*open && !timeout.timed_out(), "agent-2 to exit in time"); + } +} + +/// Records every call as `[session, call, args...]`, as the fixture lists +/// them; fails sessions in `/work/broken` and prompts that say `fail`. +struct Recorder { + session: String, + calls: mpsc::Sender, + other_exited: Gate, +} + +impl Recorder { + fn record(&self, call: Value) { + let mut entry = vec![json!(self.session)]; + entry.extend(call.as_array().unwrap().iter().cloned()); + self.calls.send(Value::Array(entry)).unwrap(); + } +} + +impl AgentSession for Recorder { + fn output(&mut self, lines: Vec) -> Result<(), FunctionError> { + if self.session == "agent-1" && lines.iter().any(|line| line == "one") { + self.other_exited.wait(); + } + self.record(json!(["output", lines])); + Ok(()) + } + + fn prompt(&mut self, turn: u64, text: String) -> Result<(), FunctionError> { + self.record(json!(["prompt", turn, text])); + if text == "fail" { + return Err(FunctionError::internal("prompt_failed")); + } + Ok(()) + } + + fn cancel(&mut self, turn: u64) -> Result<(), FunctionError> { + self.record(json!(["cancel", turn])); + Ok(()) + } + + fn decide_permission( + &mut self, + turn: u64, + permission: String, + option: String, + ) -> Result<(), FunctionError> { + self.record(json!(["decidePermission", turn, permission, option])); + Ok(()) + } + + fn exited(&mut self, exit_code: Option) { + self.record(json!(["exited", exit_code])); + if self.session == "agent-2" { + self.other_exited.open(); + } + } +} + +fn recording_backend(calls: mpsc::Sender) -> Backend { + let mut backend = Backend::new("agents-test"); + let other_exited = Gate::default(); + backend.on_agent_sessions( + move |start: AgentSessionStart, session: AgentSessionHandle| { + assert_eq!(session.id(), start.session); + if start.cwd == "/work/broken" { + return Err(FunctionError::internal("start_failed")); + } + let recorder = Recorder { + session: start.session.clone(), + calls: calls.clone(), + other_exited: other_exited.clone(), + }; + recorder.record(json!([ + "start", + { + "session": start.session, + "agentID": start.agent_id, + "cwd": start.cwd, + "resume": start.resume, + } + ])); + Ok(Box::new(recorder)) + }, + ); + backend +} + +fn started(backend: Backend) -> Host { + let mut host = Host::start(backend); + host.initialize(json!([0])); + host +} + +fn send_all(host: &mut Host, notifications: &Value) { + for notification in notifications.as_array().unwrap() { + host.notify( + notification["method"].as_str().unwrap(), + notification["params"].clone(), + ); + } +} + +/// The calls of every session, in the order each session received them. +/// Every session's last call is its exit, so nothing follows the count. +fn calls_by_session(calls: &mpsc::Receiver, count: usize) -> BTreeMap> { + let mut sessions: BTreeMap> = BTreeMap::new(); + for _ in 0..count { + let call = calls.recv_timeout(WAIT).expect("a session call in time"); + let mut call = call.as_array().unwrap().clone(); + let session = call.remove(0).as_str().unwrap().to_string(); + sessions + .entry(session) + .or_default() + .push(Value::Array(call)); + } + sessions +} + +fn expected_calls(calls: &Value) -> BTreeMap> { + calls + .as_object() + .unwrap() + .iter() + .map(|(session, calls)| (session.clone(), calls.as_array().unwrap().clone())) + .collect() +} + +fn count(calls: &BTreeMap>) -> usize { + calls.values().map(Vec::len).sum() +} + +/// Every `operationFailed` code among `frames`. +fn failure_codes(frames: &[Value]) -> Vec { + frames + .iter() + .filter(|frame| { + frame["method"] == "lithe/log" && frame["params"]["kind"] == "operationFailed" + }) + .map(|frame| frame["params"]["code"].as_str().unwrap().to_string()) + .collect() +} + +#[test] +fn each_session_gets_its_notifications_in_order_from_start_to_exit() { + let fixture = fixture(); + let expected = expected_calls(&fixture["sessions"]["calls"]); + let (sender, calls) = mpsc::channel(); + let mut host = started(recording_backend(sender)); + send_all(&mut host, &fixture["sessions"]["notifications"]); + assert_eq!(calls_by_session(&calls, count(&expected)), expected); + let (code, frames) = host.finish(); + assert_eq!(code, 1); + // agent-9 never started, so its output reaches no handler. + assert_eq!(failure_codes(&frames), ["agent_session_unknown"]); +} + +#[test] +fn a_session_that_fails_to_start_or_a_failed_prompt_ends_the_turn_as_failed() { + let fixture = fixture(); + let failures = &fixture["failures"]; + let expected = expected_calls(&failures["calls"]); + let (sender, calls) = mpsc::channel(); + let mut host = started(recording_backend(sender)); + send_all(&mut host, &failures["notifications"]); + + let mut reports = BTreeSet::new(); + let wanted = failures["reports"].as_array().unwrap().len(); + while reports.len() < wanted { + let frame = host.next(); + if frame["method"] == "lithe/host/agents/report" { + reports.insert(frame["params"].to_string()); + host.send(json!({ "jsonrpc": "2.0", "id": frame["id"], "result": {} })); + } + } + let expected_reports: BTreeSet = failures["reports"] + .as_array() + .unwrap() + .iter() + .map(Value::to_string) + .collect(); + assert_eq!(reports, expected_reports); + assert_eq!(calls_by_session(&calls, count(&expected)), expected); + assert_eq!(host.close(), 1); +} + +#[test] +fn agent_host_methods_send_the_fixture_requests() { + let fixture = fixture(); + let backend = Backend::new("agents-test"); + let handle = backend.handle(); + let mut host = started(backend); + for case in fixture["methods"].as_array().unwrap() { + let agents = handle.host().agents(); + let case_clone = case.clone(); + let (done, result) = mpsc::channel(); + thread::spawn(move || { + let session = case_clone["session"].as_str().unwrap_or_default(); + let outcome = match case_clone["call"].as_str().unwrap() { + "write" => { + let lines: Vec = + serde_json::from_value(case_clone["lines"].clone()).unwrap(); + agents.write(session, &lines).map(|()| json!({})) + } + "report" => agents + .report(session, case_clone["events"].as_array().unwrap()) + .map(|()| json!({})), + _ => agents.usage(case_clone["params"].clone()), + }; + done.send(outcome.map_err(|error| error.code().to_string())) + .unwrap(); + }); + let request = host.next(); + assert_eq!(request["method"], case["request"]["method"]); + assert_eq!(request["params"], case["request"]["params"]); + let answer = if case["call"] == "usage" { + json!({ "sinceMs": 1, "untilMs": 2, "summaries": [], "rateLimits": [] }) + } else { + json!({}) + }; + host.send(json!({ "jsonrpc": "2.0", "id": request["id"], "result": answer })); + let outcome = result.recv_timeout(WAIT).expect("the request to finish"); + assert_eq!(outcome, Ok(answer)); + } + assert_eq!(host.close(), 1); +} + +#[test] +fn agent_notifications_are_routed_only_through_agent_sessions() { + let mut backend = Backend::new("agents-test"); + for method in [ + "lithe/host/agents/didStart", + "lithe/host/agents/didOutput", + "lithe/host/agents/didExit", + ] { + let refused = backend.on_host_notification(method, |_| Ok(())); + assert_eq!(refused.err().unwrap().code(), "sdk.method.reserved"); + } + // Without a registration a started session is only logged. + let mut host = started(backend); + host.notify( + "lithe/host/agents/didStart", + json!({ "session": "agent-1", "agentID": "example", "cwd": "/work/orders" }), + ); + host.notify( + "lithe/host/agents/didOutput", + json!({ "session": "agent-1", "lines": ["one"] }), + ); + // The reader logs both before it reads the end of the input. + let (code, frames) = host.finish(); + assert_eq!(code, 1); + assert_eq!(failure_codes(&frames), ["agent_unhandled"]); +} diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/common/mod.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/common/mod.rs index 919ac36d..54b8692b 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/common/mod.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/common/mod.rs @@ -127,6 +127,24 @@ impl Host { self.exit.recv_timeout(WAIT).expect("the backend to end") } + /// Ends the input stream and returns the backend's exit code with every + /// frame it sent that was not read yet. Its output closes once nothing + /// holds the session, so a test that kept a handle cannot use it. + pub fn finish(mut self) -> (i32, Vec) { + self.input = None; + let code = self.exit.recv_timeout(WAIT).expect("the backend to end"); + let mut frames = Vec::new(); + loop { + match self.frames.recv_timeout(WAIT) { + Ok(frame) => frames.push(frame), + Err(mpsc::RecvTimeoutError::Disconnected) => return (code, frames), + Err(mpsc::RecvTimeoutError::Timeout) => { + panic!("the backend did not close its output in time") + } + } + } + } + /// The next frame, if the backend sends one within `timeout`. pub fn next_within(&self, timeout: Duration) -> Option { self.frames.recv_timeout(timeout).ok() From 75aa40efb8c69426da2fe1b6fd8f392e47fd73f6 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 04:29:00 +0800 Subject: [PATCH 5/7] =?UTF-8?q?fix(sdk):=20Node=20=E6=8E=A5=E5=8F=97?= =?UTF-8?q?=E6=A0=91=E8=A7=86=E5=9B=BE=E4=BA=8B=E4=BB=B6=EF=BC=8C=E6=9C=AA?= =?UTF-8?q?=E5=A4=84=E7=90=86=E7=9A=84=E5=91=BD=E4=BB=A4=E5=9B=9B=E4=B8=AA?= =?UTF-8?q?=20SDK=20=E7=BB=9F=E4=B8=80=E8=AE=B0=E4=B8=BA=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Node SDK 的 checkViewEvent 拒绝 refresh、expand、loadMore 和 cursor 字段,而类型声明和 Rust、Go、Java SDK 都接受它们,树视图展开和加载更多在 Node 后端会直接失败。补上这三种事件和 cursor,并加测试。 用户运行的命令没有处理器时,Rust、Go 记 operationFailed,Node、Java 记 degraded;命令没有执行,按失败记录,四个 SDK 统一为 operationFailed。 --- .../java/io/github/litheidea/plugin/sdk/Backend.java | 2 +- shared/plugins/sdk/node/src/backend.mjs | 2 +- shared/plugins/sdk/node/src/view.mjs | 7 +++++-- shared/plugins/sdk/node/test/backend.test.mjs | 9 +++++++++ 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java index 890898e1..0908cef2 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -817,7 +817,7 @@ private void hostNotification(String method, Object raw) { handler = commandId instanceof String ? commandHandlers.get(commandId) : null; } if (handler == null) { - diagnostics().degraded("notification", "command_unhandled"); + diagnostics().failed("notification", "command_unhandled"); return; } Map context = workspaceContext(params.get("context")); diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index 8c462704..7b70e065 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -599,7 +599,7 @@ class Backend { handler = this.#commandHandlers.get(params.commandID); event = { commandID: params.commandID, workspaceContext: isContextReference(params.context) ? params.context : null }; if (!handler) { - this.#diagnostics().degraded('notification', 'command_unhandled'); + this.#diagnostics().terminal('notification', { code: 'command_unhandled' }, 0); return; } } else if (method === HOST_NOTIFICATIONS.didChangeContexts) { diff --git a/shared/plugins/sdk/node/src/view.mjs b/shared/plugins/sdk/node/src/view.mjs index a82d756a..157c9756 100644 --- a/shared/plugins/sdk/node/src/view.mjs +++ b/shared/plugins/sdk/node/src/view.mjs @@ -4,8 +4,11 @@ import { PluginSdkError } from './errors.mjs'; -const KINDS = new Set(['open', 'close', 'click', 'change', 'select', 'activate', 'viewport', 'resize', 'settings']); -const OPTIONAL_TEXT = ['node', 'canvas', 'setting', 'item']; +const KINDS = new Set([ + 'open', 'close', 'click', 'change', 'select', 'activate', 'viewport', 'resize', 'settings', + 'refresh', 'expand', 'loadMore', +]); +const OPTIONAL_TEXT = ['node', 'canvas', 'setting', 'item', 'cursor']; const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value); const isAbsent = (value) => value === undefined || value === null; diff --git a/shared/plugins/sdk/node/test/backend.test.mjs b/shared/plugins/sdk/node/test/backend.test.mjs index 04d53a0b..79c1479d 100644 --- a/shared/plugins/sdk/node/test/backend.test.mjs +++ b/shared/plugins/sdk/node/test/backend.test.mjs @@ -154,6 +154,14 @@ test('a view event without its required shape is refused', () => { assert.equal(checkViewEvent(parsed), parsed); const resize = event({ event: 'resize', width: 340 }); assert.equal(checkViewEvent(resize), resize); + // Tree events, as the Rust, Go and Java SDKs parse them. + for (const tree of [ + event({ event: 'refresh' }), + event({ event: 'expand', node: 'files', item: 'src', value: true }), + event({ event: 'loadMore', node: 'files', cursor: 'page-2' }), + ]) { + assert.equal(checkViewEvent(tree), tree); + } for (const params of [ null, [], @@ -164,6 +172,7 @@ test('a view event without its required shape is refused', () => { event({ surface: {} }), event({ settings: { effective: {} } }), event({ node: 3 }), + event({ event: 'loadMore', node: 'files', cursor: 2 }), event({ value: ['a'] }), event({ viewport: { x: 0 } }), event({ width: 'wide' }), From 3e3c7d1c7f4b3f6f4821659a23a31b55642f91d8 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 04:35:55 +0800 Subject: [PATCH 6/7] fix(agents): end a session whose stream thread cannot start A native session whose output thread could not start stayed in the live list forever with no exited event, and one without its stderr reader could block on a full pipe. Such a session now ends as failed. A close whose grace-period thread cannot start ends the CLI at once. Also documents the public items of plugin-agents and lsp-engine's agent host that rustdoc flagged. --- rust/crates/agent-runtime/src/lib.rs | 4 +- rust/crates/agent-runtime/src/live.rs | 54 +++++++++++++++++++----- rust/crates/agent-runtime/src/tests.rs | 27 ++++++++++++ rust/crates/lsp-engine/src/agent_host.rs | 4 ++ rust/crates/plugin-agents/src/lib.rs | 16 +++++++ 5 files changed, 92 insertions(+), 13 deletions(-) diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 0d4a59bf..d02559f9 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -5,7 +5,7 @@ //! everything that touches the machine. It starts the CLI, writes its input //! and reads its output, reads the session files, and keeps the cache; the //! plugin backend only translates. It turns the CLI's lines into Lithe's -//! session events ([`events`]) and session-file lines into records. +//! session events (the `events` module) and session-file lines into records. //! //! Core knows no agent: every agent-specific name, argument, protocol and file //! layout comes from a plugin manifest and its backend. @@ -20,7 +20,7 @@ //! //! - Only a request the user started may start a session, send a prompt or //! answer a permission request. Sessions run only in trusted local -//! workspaces, at most [`live::MAX_SESSIONS_PER_AGENT`] per agent. +//! workspaces, at most four per agent. //! - The executable is always the agent's declared tool, as the host resolved //! it. The plugin chooses arguments only, never the environment. //! - Session records are read only for agents the user granted diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index dabbd900..da419923 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -607,17 +607,32 @@ fn start_checked(runtime: &Arc, request: StartRequest) -> Result) -> Result<(), CoreE } } -fn spawn(name: &str, work: impl FnOnce() + Send + 'static) { - // A thread that cannot start leaves the session without that stream; the - // output thread is the one that matters, and its failure ends the session - // through the process's own exit. - let _ = thread::Builder::new().name(name.to_string()).spawn(work); +#[cfg(test)] +thread_local! { + /// Thread names [`spawn`] refuses on this thread, standing in for a + /// thread the system cannot start. + pub(crate) static REFUSED_THREADS: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Starts a named thread; false when the system could not start it. +fn spawn(name: &'static str, work: impl FnOnce() + Send + 'static) -> bool { + #[cfg(test)] + if REFUSED_THREADS.with(|refused| refused.borrow().contains(&name)) { + return false; + } + thread::Builder::new() + .name(name.to_string()) + .spawn(work) + .is_ok() } fn write_input(handle: Arc, queue: Receiver>) { @@ -993,7 +1021,7 @@ pub(crate) fn close(runtime: &Arc, payload: Value) -> Result, payload: Value) -> Result { /// `plugin.host.*` or `plugin.agents.*` code, sent as `error.data.code`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AgentHostFailure { + /// The stable refusal code. pub code: String, + /// English text sent to the backend as the error message. pub message: String, } impl AgentHostFailure { + /// A refusal with `code` and `message`. pub fn new(code: impl Into, message: impl Into) -> Self { Self { code: code.into(), @@ -228,6 +231,7 @@ pub struct AgentCallFailure { /// A `plugin.function.*` code, or the engine's code when the call could /// not be sent. pub code: String, + /// The error message the call ended with. pub message: String, /// The plugin's own error code, when the function returned one. pub plugin_error_code: Option, diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index 0f15fca5..bc3a3c2a 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -83,21 +83,29 @@ const USER_HOME_VARIABLE: &str = "${userHome}"; #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AgentDeclaration { + /// The agent's ID, unique within the plugin. pub id: String, + /// The name Lithe shows for the agent. pub display_name: String, + /// The icon Lithe shows for the agent. #[serde(default, skip_serializing_if = "Option::is_none")] pub icon: Option, /// One of the plugin's `requiresTools`: the only executable any form of /// this agent runs. pub tool: String, + /// The native form: the backend speaks the CLI's own protocol. #[serde(default, skip_serializing_if = "Option::is_none")] pub native: Option, + /// The ACP form: the arguments that start the CLI's ACP server. #[serde(default, skip_serializing_if = "Option::is_none")] pub acp: Option, + /// The terminal form: the arguments that start the CLI's own interface. #[serde(default, skip_serializing_if = "Option::is_none")] pub terminal: Option, + /// How the user updates the CLI. #[serde(default, skip_serializing_if = "Option::is_none")] pub update: Option, + /// Where the CLI keeps its session files. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub session_sources: Vec, } @@ -106,7 +114,10 @@ pub struct AgentDeclaration { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct NativeDeclaration { + /// The backend function that answers the launch arguments. pub function: String, + /// How long Core waits for that function; see + /// [`NativeDeclaration::timeout_milliseconds`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout_milliseconds: Option, } @@ -123,6 +134,7 @@ impl NativeDeclaration { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ArgumentsDeclaration { + /// The arguments, after the tool's path. pub arguments: Vec, } @@ -131,6 +143,7 @@ pub struct ArgumentsDeclaration { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UpdateDeclaration { + /// The arguments of the update command, after the tool's path. pub arguments: Vec, } @@ -146,11 +159,13 @@ pub enum SessionFormat { #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SessionSourceDeclaration { + /// The source's ID, unique within the agent. pub id: String, /// Root candidates. The first one whose variables all resolve is used. pub roots: Vec, /// Root-relative glob patterns of the files to read. pub include: Vec, + /// The format of the files. pub format: SessionFormat, /// Backend function that parses new lines of one file. pub scan: String, @@ -471,6 +486,7 @@ pub fn resolve_root( /// agent's tool. The tool itself is not in the answer's control. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NativeLaunch { + /// The arguments, after the tool's path. pub arguments: Vec, } From 6763fb4621608cd5ebebdff426629b07e2535aa5 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 28 Nov 2026 04:42:07 +0800 Subject: [PATCH 7/7] =?UTF-8?q?docs(agents):=20=E6=9B=B4=E6=96=B0=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E9=93=BE=E6=8E=A5=20#216?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugins/reference/protocol-changelog.md | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index e7e27c1e..a517c02d 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 +- [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),新增能力 **`agents` 0**(API-45):清单 `agents[]` 声明用户自己安装的 Agent CLI、它的运行形式(`native`、`acp`、`terminal`、`update`)和会话来源 `sessionSources`;新增权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read` 与激活事件 `onAgent:`,多声明或少声明都拒绝。`litheFunctions` 0 内新增宿主方法 `agents/write`、`agents/report`、`agents/usage`(Core 直接回答,宿主收不到)和通知 `agents/didStart`、`didOutput`、`didPrompt`、`didCancel`、`didDecidePermission`、`didExit`。Core 新增 `agent-runtime`(启动和回收 CLI 进程、校验会话事件、有界事件队列)与宿主命令 `agents.*`、`agentSessions.*`,会话记录的分组键改为 `sessionID`;安装审查新增 `agent`、`agentSessions` 两类程序;新增 `fixtures/agents/` 两个清单和 23 个拒绝用例,四种官方 SDK 同步封装。版本 0 不运行 ACP 客户端,会话只在可信的本地工作区运行。 - [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 / `litheFunctions` 0 内补充(API-05):新增宿主方法 `workspace/setDirectoryTypes` 与 `workspace/setDirectoryMarks`(新权限 `workspace.directoryMarks`),允许插件后端在当前工作区上下文注册自定义目录类型(最多 32 个,`id` 以 `plugin.` 开头)与动态目录标记(最多 500 条);`workspace.resolveDirectoryPresentation` 新增可选 `pluginTypes` 与 `pluginMarks` 字段及输出可选 `pluginId`,按 `user > shared > plugin > glob > vcs > plain` 确定性合并呈现与索引排除,并允许用户手动分配 `plugin.*` 角色;插件提交时的校验与解析器一致,宿主保存下来的登记不会让整次解析失败;清单 schema 与四种官方 SDK(Rust、Go、Node、Java)同步补齐。无新增能力版本、协议版本或 SDK 版本。 @@ -73,7 +73,7 @@ | 能力 | 版本 | 日期 | PR | | --- | --- | --- | --- | | `backend` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | -| `agents` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| `agents` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | `buildModelInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | @@ -224,15 +224,15 @@ | API-35 | `functions/invoke` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-38 | `network/request` | 0 | 2026-11-23 | [#193](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/193) | | API-40 | `workspace/getHostPaths` | 0 | 待合入 | [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151) | -| API-45 | `agents/write` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/report` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/usage` | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/didStart`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/didOutput`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/didPrompt`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/didCancel`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/didDecidePermission`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | -| API-45 | `agents/didExit`(通知) | 0 | 待合入 | [#AGENTSPR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/AGENTSPR) | +| API-45 | `agents/write` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/report` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/usage` | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didStart`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didOutput`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didPrompt`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didCancel`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didDecidePermission`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didExit`(通知) | 0 | 待合入 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | — | `keymapImport/listInputs` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | — | `keymapImport/readChunk` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) |