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
1 change: 1 addition & 0 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,7 @@ or removing a command fails until the table changes in the same commit.
| `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.setConfigOption` | Pick a value of a session setting the agent backend reported |
| `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 |
Expand Down
125 changes: 125 additions & 0 deletions rust/crates/agent-runtime/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ const MAX_PLAN_ENTRIES: usize = 256;
/// Most windows of a rate-limit snapshot.
pub(crate) const MAX_RATE_WINDOWS: usize = 8;

/// Most settings a session reports at once.
const MAX_CONFIG_OPTIONS: usize = 16;

/// Most values of one setting.
const MAX_CONFIG_VALUES: usize = 128;

/// 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.
Expand All @@ -62,6 +68,7 @@ pub(crate) enum SessionEvent {
RateLimits(RateLimits),
TurnEnded(TurnEnded),
Notice(Notice),
ConfigOptions(ConfigOptions),
}

/// What the agent says about its session.
Expand Down Expand Up @@ -308,6 +315,53 @@ pub(crate) struct Notice {
pub code: Option<String>,
}

/// What a setting means to the host, so it can place the setting where users
/// expect it. The names are ACP's categories: ACP's `thought_level` is
/// `thoughtLevel`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum ConfigCategory {
/// The model the session uses.
Model,
/// How hard the model thinks, its values listed from least to most.
ThoughtLevel,
/// The agent's mode, for example asking before edits or planning only.
Mode,
}

/// One value a setting may take.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct ConfigValue {
pub value: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}

/// A setting of the session the user may change, as ACP's session config
/// option: the value it has now and the values it may take.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct ConfigOption {
pub id: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub category: Option<ConfigCategory>,
pub current_value: String,
pub options: Vec<ConfigValue>,
}

/// The settings of the session the user may change. Each report replaces the
/// last; an empty list means there are none.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct ConfigOptions {
pub config_options: Vec<ConfigOption>,
}

/// 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)]
Expand All @@ -328,6 +382,8 @@ pub(crate) struct TurnState {
pub pending: BTreeMap<String, (u64, Vec<PermissionOption>)>,
/// The agent CLI's own session ID, once reported.
pub agent_session_id: Option<String>,
/// The settings the backend last reported: ID to the values it may take.
pub config: BTreeMap<String, Vec<String>>,
}

impl TurnState {
Expand Down Expand Up @@ -395,6 +451,16 @@ impl TurnState {
}
}
SessionEvent::RateLimits(_) | SessionEvent::Notice(_) => {}
SessionEvent::ConfigOptions(options) => {
self.config = options
.config_options
.iter()
.map(|option| {
let values = option.options.iter().map(|v| v.value.clone()).collect();
(option.id.clone(), values)
})
.collect();
}
SessionEvent::TurnEnded(ended) => {
self.require_active(ended.turn)?;
self.active_turn = None;
Expand Down Expand Up @@ -428,6 +494,19 @@ impl TurnState {
self.pending.remove(permission);
Ok(turn)
}

/// Checks a value the user picked for a setting: the setting and the
/// value must be ones the backend last reported.
pub fn check_config(&self, option: &str, value: &str) -> Result<(), &'static str> {
let Some(values) = self.config.get(option) else {
return Err("agents.unknownConfigOption");
};
if values.iter().any(|candidate| candidate == value) {
Ok(())
} else {
Err("agents.unknownConfigValue")
}
}
}

const INVALID_PARAMS: &str = lithe_plugin_rpc::codes::HOST_INVALID_PARAMS;
Expand Down Expand Up @@ -523,6 +602,52 @@ fn check_bounds(event: &SessionEvent) -> Result<(), String> {
text(&notice.text, "text")?;
optional_label(&notice.code, "code")?;
}
SessionEvent::ConfigOptions(options) => check_config_options(options)?,
}
Ok(())
}

/// Checks the settings a session reports: bounded labels, IDs and values
/// unique, and each current value one of the setting's values.
fn check_config_options(options: &ConfigOptions) -> Result<(), String> {
let label = |value: &str| !value.is_empty() && value.len() <= MAX_LABEL_BYTES;
let optional = |value: &Option<String>| value.as_deref().is_none_or(label);
if options.config_options.len() > MAX_CONFIG_OPTIONS {
return Err("has more than 16 settings".to_string());
}
let mut ids = Vec::with_capacity(options.config_options.len());
for option in &options.config_options {
if !label(&option.id)
|| !label(&option.name)
|| !optional(&option.description)
|| !label(&option.current_value)
{
return Err("has a setting with an empty or overlong label".to_string());
}
if option.options.is_empty() || option.options.len() > MAX_CONFIG_VALUES {
return Err("has a setting without 1 to 128 values".to_string());
}
let mut values = Vec::with_capacity(option.options.len());
for value in &option.options {
if !label(&value.value) || !label(&value.name) || !optional(&value.description) {
return Err("has a setting value with an empty or overlong label".to_string());
}
values.push(value.value.as_str());
}
if !values.contains(&option.current_value.as_str()) {
return Err("has a setting whose current value is not one of its values".to_string());
}
values.sort_unstable();
values.dedup();
if values.len() != option.options.len() {
return Err("repeats a setting value".to_string());
}
ids.push(option.id.as_str());
}
ids.sort_unstable();
ids.dedup();
if ids.len() != options.config_options.len() {
return Err("repeats a setting ID".to_string());
}
Ok(())
}
Expand Down
7 changes: 5 additions & 2 deletions rust/crates/agent-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
//!
//! 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
//! - Only a request the user started may start a session, send a prompt,
//! answer a permission request or change a session setting. Sessions run
//! only in trusted local
//! 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.
Expand Down Expand Up @@ -60,6 +61,7 @@ pub const AGENT_COMMANDS: &[&str] = &[
"agents.prompt",
"agents.cancel",
"agents.respondPermission",
"agents.setConfigOption",
"agents.close",
"agents.waitEvents",
];
Expand Down Expand Up @@ -115,6 +117,7 @@ impl Runtime {
"agents.prompt" => live::prompt(self, payload),
"agents.cancel" => live::cancel(self, payload),
"agents.respondPermission" => live::respond_permission(self, payload),
"agents.setConfigOption" => live::set_config_option(self, payload),
"agents.close" => live::close(self, payload),
"agents.waitEvents" => live::wait_events(self, payload),
"agentSessions.configure" => self.records.configure(payload),
Expand Down
50 changes: 49 additions & 1 deletion rust/crates/agent-runtime/src/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ 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,
AGENTS_DID_PROMPT, AGENTS_DID_SET_CONFIG_OPTION, AGENTS_DID_START,
};
use lithe_protocol::{CoreError, ErrorCode};
use lithe_request_context::Source;
Expand Down Expand Up @@ -1014,6 +1014,54 @@ pub(crate) fn respond_permission(
Ok(json!({ "turn": turn }))
}

/// `agents.setConfigOption`: the value the user picked for one of the
/// session's settings. The backend applies it when the agent can take it,
/// which may be the next turn, and reports the settings again.
pub(crate) fn set_config_option(
runtime: &Arc<Runtime>,
payload: Value,
) -> Result<Value, CoreError> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfigAnswer {
session: String,
option: String,
value: String,
}
let request: ConfigAnswer = crate::decode(payload)?;
require_user("change a setting of")?;
let session = runtime.live.session(&request.session)?;
session
.lock_turns()
.check_config(&request.option, &request.value)
.map_err(|code| {
refusal(
ErrorCode::InvalidRequest,
code,
"The agent did not offer this setting or value.",
)
})?;
runtime
.link
.notify(
&session.backend,
AGENTS_DID_SET_CONFIG_OPTION,
json!({
"session": session.id,
"option": request.option,
"value": request.value,
}),
)
.map_err(|_| {
refusal(
ErrorCode::ProcessFailed,
"agents.backendUnavailable",
"The agent plugin's backend did not take the setting.",
)
})?;
Ok(json!({}))
}

/// `agents.close`: closes the CLI's input, then ends it if it does not exit.
pub(crate) fn close(runtime: &Arc<Runtime>, payload: Value) -> Result<Value, CoreError> {
let request: SessionRequest = crate::decode(payload)?;
Expand Down
Loading
Loading