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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
26 changes: 26 additions & 0 deletions rust/crates/agent-runtime/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"] }
73 changes: 73 additions & 0 deletions rust/crates/agent-runtime/src/backend.rs
Original file line number Diff line number Diff line change
@@ -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<String>;

/// 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<Value, AgentCallFailure>;

/// 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<dyn LspProcessLauncher>;
}

/// 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<String> {
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<Value, AgentCallFailure> {
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<dyn LspProcessLauncher> {
Arc::new(SystemProcessLauncher)
}
}
192 changes: 192 additions & 0 deletions rust/crates/agent-runtime/src/catalog.rs
Original file line number Diff line number Diff line change
@@ -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<AgentDeclaration>,
pub granted: BTreeSet<String>,
}

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<BTreeMap<String, PluginAgents>>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ConfigureRequest {
plugins: Vec<ConfiguredPlugin>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ConfiguredPlugin {
manifest: Value,
#[serde(default)]
granted_permissions: Vec<String>,
}

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<Value, CoreError> {
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<Value> {
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<CatalogAgent> {
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<CatalogAgent> {
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<CatalogAgent> {
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()
}
}
Loading
Loading