From 1f843f8ee3aac802cda17ad8df43b51e30862b0d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 00:40:46 +0800 Subject: [PATCH 1/3] feat(agent): add live turn interaction primitives --- rust/contracts/application-boundary.md | 14 + rust/contracts/rust-core-api.md | 6 +- rust/crates/agent-runtime/src/events.rs | 77 ++ rust/crates/agent-runtime/src/interaction.rs | 582 +++++++++++++++ rust/crates/agent-runtime/src/lib.rs | 5 + rust/crates/agent-runtime/src/live.rs | 290 ++++++-- rust/crates/agent-runtime/src/tests.rs | 350 ++++++++- rust/crates/core/src/protocol/command.rs | 8 + .../diagnostics/src/catalog_generated.rs | 15 + .../plugin-rpc/src/host_notifications.rs | 8 + rust/fixtures/agents/turn-interaction-v1.json | 85 +++ rust/logging/events/agent.json | 14 + shared/plugins/contract/v1/README.md | 126 +++- .../v1/fixtures/agents/native-session.json | 671 ++++++++++++++++-- shared/plugins/reference/api-catalog.md | 14 +- shared/plugins/reference/domains/agents.md | 39 + .../plugins/reference/protocol-changelog.md | 4 + shared/plugins/sdk/go/README.md | 20 +- shared/plugins/sdk/go/lithe/agents.go | 97 ++- shared/plugins/sdk/go/lithe/agents_test.go | 41 ++ shared/plugins/sdk/java/README.md | 19 +- .../plugin/sdk/AgentQuestionAnswer.java | 20 + .../litheidea/plugin/sdk/AgentSession.java | 9 + .../litheidea/plugin/sdk/AgentSessions.java | 67 +- .../github/litheidea/plugin/sdk/Protocol.java | 1 + .../litheidea/plugin/sdk/AgentsTest.java | 33 + shared/plugins/sdk/node/README.md | 19 +- shared/plugins/sdk/node/src/backend.mjs | 24 +- shared/plugins/sdk/node/src/index.d.ts | 6 + shared/plugins/sdk/node/src/protocol.mjs | 1 + shared/plugins/sdk/node/test/agents.test.mjs | 26 + shared/plugins/sdk/rust/README.md | 20 +- .../plugins/sdk/rust/plugin-sdk/src/agents.rs | 118 ++- shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 3 +- .../sdk/rust/plugin-sdk/src/protocol.rs | 1 + .../sdk/rust/plugin-sdk/tests/agents.rs | 64 +- 36 files changed, 2717 insertions(+), 180 deletions(-) create mode 100644 rust/crates/agent-runtime/src/interaction.rs create mode 100644 rust/fixtures/agents/turn-interaction-v1.json create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentQuestionAnswer.java diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 05117e4d..9548daa0 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -69,6 +69,7 @@ this lifecycle protection; actual symbol computation remains upstream-owned. | Git | workspace commit plans with optional immutable ChangeList path scopes, dependency ordering, guarded steps and partial-success retry, changes, commits, branches, diffs, reviewed history actions and recovery, worktree listing and safe management, worktree-aware PR publication context, validation, and mutation results | Git executable discovery, credentials, process environment, opening checkout paths, local ChangeList selection and preference persistence | | GitHub | remote parsing, trusted request plans, normalized branch comparisons and pull requests/reviews/comments, deterministic ordering, and stable errors | OAuth configuration, HTTPS, browser opening, and operating-system credential storage | | [AI commit messages](ai-commit.md) | provider configuration parsing, commit rules, bounded diff evidence, request plans, and response text | local configuration discovery, credentials, HTTP, cancellation, and draft UI | +| Agent sessions | bounded FIFO, current-turn steering reservations, stop/pause transitions, structured-question validation and delivery confirmations, projected action availability | tool/environment discovery, event presentation, input and answer drafts; CLI protocol translation belongs to each plugin | | [IDE capability API / MCP](ide-api/v1.md) | canonical tool schemas, narrowing host selection, permission/argument validation, stable execution IDs, bounded output cursors and errors | implemented workflow inventory, explicit project authorization, live environment/Build/Run application actions, helper discovery and writable connection storage | | Runtime | tool requirements, normalized candidates, effective toolchain references, pinned managed-runtime plans and bounded resolver answers | tool probing, executable paths, approved HTTPS downloads, safe archive extraction, native integrity, interprocess cache locks and atomic set publication | | Language tooling | provider catalog, local fallback results, complete LSP process/session runtime, capabilities, diagnostics, UTF-16 edits, and normalized feature results | executable/environment discovery and UI provider routing | @@ -87,6 +88,19 @@ that its editor snapshots still match those versions before touching files or buffers, and stops pending work when Core revokes a delivered request. The [Core commands reference](rust-core-api.md#commands) specifies the event and reply shapes. +### Agent turn interaction + +Core owns live session action eligibility. Sending, steering and queueing are +distinct user actions; a stopped turn cannot resume queued work even if its +completion races the stop. A rejected or unacknowledged running-turn input +returns its original content, and failed answer delivery retains the question +for retry. CLI support comes from explicit interaction capabilities, never a +tool name. Hosts render `interactionState` and retain presentation drafts; +plugins translate opaque turn, question and option IDs into their CLI's real +protocol. No input content is logged or persisted by this interaction layer. +See [the native session contract](../../shared/plugins/contract/v1/README.md#native-sessions) +and [the shared fixture](../fixtures/agents/turn-interaction-v1.json). + ### Dev Container configuration and execution environment The same explicit runtime target follows discovery, configuration lookup, build, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 59fc5f66..843fc7b7 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -484,8 +484,10 @@ or removing a command fails until the table changes in the same commit. | `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, with the files, folders and images the user attached, to a live agent session | -| `agents.cancel` | Ask the agent backend to cancel the turn in progress | +| `agents.prompt` | Send, queue or steer the user's prompt and attachments, retaining queued or unconfirmed input until its outcome | +| `agents.cancel` | Mark the current turn stopping and pause the queue until a real turn-end event | +| `agents.updateQueue` | Remove a queued input or resume the user's paused FIFO | +| `agents.respondQuestion` | Validate and reserve an answer or cancellation to a pending structured question | | `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 | diff --git a/rust/crates/agent-runtime/src/events.rs b/rust/crates/agent-runtime/src/events.rs index d8498d90..de0cdc51 100644 --- a/rust/crates/agent-runtime/src/events.rs +++ b/rust/crates/agent-runtime/src/events.rs @@ -69,6 +69,11 @@ pub(crate) enum SessionEvent { TurnEnded(TurnEnded), Notice(Notice), ConfigOptions(ConfigOptions), + InteractionCapabilities(crate::interaction::Capabilities), + QuestionRequested(crate::interaction::QuestionRequest), + QuestionClosed(crate::interaction::QuestionClosed), + QuestionAnswered(crate::interaction::QuestionAnswered), + InputResolved(crate::interaction::InputResolved), } /// What the agent says about its session. @@ -384,6 +389,8 @@ pub(crate) struct TurnState { pub agent_session_id: Option, /// The settings the backend last reported: ID to the values it may take. pub config: BTreeMap>, + /// User collaboration state; queued bodies are shared across atomic report checks. + pub interaction: crate::interaction::Interaction, } impl TurnState { @@ -418,6 +425,54 @@ impl TurnState { SessionEvent::Session(info) => { self.agent_session_id = Some(info.agent_session_id.clone()); } + SessionEvent::InteractionCapabilities(capabilities) => { + self.interaction.capabilities = capabilities.clone(); + } + SessionEvent::QuestionRequested(request) => { + self.require_active(request.turn)?; + self.interaction + .ask(request) + .map_err(|code| (code, "has an invalid question request".to_string()))?; + } + SessionEvent::QuestionAnswered(answer) => { + self.require_active(answer.turn)?; + if !self.interaction.answering.remove(&answer.request) { + return Err(( + PRECONDITION_FAILED, + "names an answer not being delivered".to_string(), + )); + } + if answer.accepted { + self.interaction.questions.remove(&answer.request); + } + } + SessionEvent::QuestionClosed(request) => { + self.interaction.answering.remove(&request.request); + self.require_active(request.turn)?; + if self + .interaction + .questions + .remove(&request.request) + .is_none() + { + return Err(( + PRECONDITION_FAILED, + "names a question no longer pending".to_string(), + )); + } + } + SessionEvent::InputResolved(input) => { + let Some(pending) = &self.interaction.steering else { + return Err(( + PRECONDITION_FAILED, + "names an input no longer pending".to_string(), + )); + }; + if pending.id != input.input || pending.turn != input.turn { + return Err((PRECONDITION_FAILED, "names a different input".to_string())); + } + self.interaction.steering = None; + } SessionEvent::Message(message) => self.require_active(message.turn)?, SessionEvent::ToolCall(call) => self.require_active(call.turn)?, SessionEvent::Plan(plan) => self.require_active(plan.turn)?, @@ -464,6 +519,12 @@ impl TurnState { SessionEvent::TurnEnded(ended) => { self.require_active(ended.turn)?; self.active_turn = None; + self.interaction.stopping = false; + self.interaction.questions.clear(); + self.interaction.answering.clear(); + if ended.reason != StopReason::Completed { + self.interaction.paused = true; + } self.pending.retain(|_, (turn, _)| *turn != ended.turn); } } @@ -603,6 +664,22 @@ fn check_bounds(event: &SessionEvent) -> Result<(), String> { optional_label(¬ice.code, "code")?; } SessionEvent::ConfigOptions(options) => check_config_options(options)?, + SessionEvent::InteractionCapabilities(_) => {} + SessionEvent::QuestionRequested(request) => request.check_bounds()?, + SessionEvent::QuestionAnswered(request) => label(&request.request, "request")?, + SessionEvent::QuestionClosed(request) => label(&request.request, "request")?, + SessionEvent::InputResolved(input) => { + label(&input.input, "input")?; + text(input.message.as_deref().unwrap_or_default(), "message")?; + if input.code.as_deref().is_some_and(|code| { + !matches!( + code, + "plugin_error" | "internal_error" | "panic" | "cancelled" + ) + }) { + return Err("has an invalid SDK input failure category".into()); + } + } } Ok(()) } diff --git a/rust/crates/agent-runtime/src/interaction.rs b/rust/crates/agent-runtime/src/interaction.rs new file mode 100644 index 00000000..182a93dc --- /dev/null +++ b/rust/crates/agent-runtime/src/interaction.rs @@ -0,0 +1,582 @@ +//! Bounded user collaboration for live sessions. Core owns queue order, +//! stopping and question validation; plugins translate only the CLI protocol. +//! An ordered worker delivers notifications without holding runtime locks, +//! because the engine may call back while holding its own backend lock. + +use crate::live::{self, LiveSession}; +use crate::Runtime; +use lithe_plugin_rpc::{codes, AGENTS_DID_ANSWER_QUESTION, AGENTS_DID_CANCEL, AGENTS_DID_PROMPT}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::sync::{mpsc, Arc, Weak}; + +/// Maximum retained queued content, including an in-flight dispatch. +pub(crate) const MAX_QUEUE_BYTES: usize = 4 * 1024 * 1024; + +/// Maximum queue length, including a dispatch awaiting backend delivery. +pub(crate) const MAX_QUEUED_INPUTS: usize = 8; +/// Maximum outstanding question batches and questions within one batch. +const MAX_QUESTIONS: usize = 8; +/// Maximum options in one question. +const MAX_QUESTION_OPTIONS: usize = 16; +/// Maximum UTF-8 bytes in a question ID, title or option label. +const MAX_LABEL_BYTES: usize = 1024; +/// Maximum UTF-8 bytes in a question or answer body. +const MAX_QUESTION_TEXT_BYTES: usize = 16 * 1024; +/// Maximum UTF-8 bytes in an option description. +const MAX_DESCRIPTION_BYTES: usize = 4 * 1024; + +/// Optional live interactions. Omission preserves the original plugin behavior. +#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Capabilities { + #[serde(default)] + pub steering: bool, + #[serde(default)] + pub questions: bool, +} + +/// One option of a structured question. IDs are opaque and unique per question. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct QuestionOption { + pub id: String, + pub label: String, + #[serde(default)] + pub description: String, +} + +/// One question: zero options means free text is required. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct Question { + pub id: String, + pub title: String, + pub text: String, + #[serde(default)] + pub options: Vec, + #[serde(default)] + pub multiple: bool, + #[serde(default)] + pub allow_text: bool, +} + +/// A request belongs to one turn and is removed on answer, withdrawal or turn end. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct QuestionRequest { + pub turn: u64, + pub request: String, + pub questions: Vec, +} + +impl QuestionRequest { + pub fn check_bounds(&self) -> Result<(), String> { + let label = |s: &str| !s.is_empty() && s.len() <= MAX_LABEL_BYTES; + let mut ids = BTreeSet::new(); + if !label(&self.request) + || self.questions.is_empty() + || self.questions.len() > MAX_QUESTIONS + { + return Err("needs a request ID and one to eight questions".into()); + } + for q in &self.questions { + if !label(&q.id) + || !label(&q.title) + || q.text.len() > MAX_QUESTION_TEXT_BYTES + || !ids.insert(&q.id) + || q.options.len() > MAX_QUESTION_OPTIONS + || (q.options.is_empty() && !q.allow_text) + { + return Err("has an invalid or repeated question".into()); + } + let mut options = BTreeSet::new(); + for option in &q.options { + if !label(&option.id) + || !label(&option.label) + || option.description.len() > MAX_DESCRIPTION_BYTES + || !options.insert(&option.id) + { + return Err("has an invalid or repeated question option".into()); + } + } + } + Ok(()) + } +} + +/// A backend withdrew a question, for example when its tool call was cancelled. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct QuestionClosed { + pub turn: u64, + pub request: String, +} + +/// The plugin delivered or failed to deliver a reserved question answer. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct QuestionAnswered { + pub turn: u64, + pub request: String, + pub accepted: bool, +} + +/// The CLI acknowledged or refused a running-turn input; never inferred by Core. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct InputResolved { + pub turn: u64, + pub input: String, + pub accepted: bool, + /// Optional SDK failure category; constrained by the report contract. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +/// User content is retained in memory, bounded by eight inputs / four MiB. +#[derive(Debug, Clone, Serialize)] +pub(crate) struct Input { + pub id: String, + pub text: String, + pub attachments: Vec, + #[serde(skip)] + pub turn: u64, +} + +impl Input { + pub fn bytes(&self) -> usize { + self.text.len() + + self + .attachments + .iter() + .map(|a| a.to_string().len()) + .sum::() + } +} + +/// Queue and question state, cloned atomically with a report. Large input +/// bodies use Arc so token reports do not copy the user's queued content. +#[derive(Debug, Clone, Default)] +pub(crate) struct Interaction { + pub capabilities: Capabilities, + pub queue: VecDeque>, + pub paused: bool, + pub stopping: bool, + pub steering: Option>, + pub questions: BTreeMap>, + pub answering: BTreeSet, + pub dispatching: Option>, + pub closed: bool, + pub next_input: u64, +} + +impl Interaction { + pub fn queued_bytes(&self) -> usize { + self.queue + .iter() + .chain(self.dispatching.iter()) + .map(|input| input.bytes()) + .sum() + } + + pub fn queued_count(&self) -> usize { + self.queue.len() + usize::from(self.dispatching.is_some()) + } + + pub fn ask(&mut self, request: &QuestionRequest) -> Result<(), &'static str> { + if !self.capabilities.questions || self.stopping { + return Err(codes::HOST_PRECONDITION_FAILED); + } + if self.questions.contains_key(&request.request) { + return Err(codes::HOST_INVALID_PARAMS); + } + if self.questions.len() >= MAX_QUESTIONS { + return Err(codes::HOST_LIMIT_EXCEEDED); + } + self.questions + .insert(request.request.clone(), Arc::new(request.clone())); + Ok(()) + } + + /// Only interaction changes emit this small projection, never text deltas. + pub fn projection(&self, active: Option) -> Value { + json!({ + "kind": "interactionState", "activeTurn": active.unwrap_or(0), + "canPrompt": !self.closed && active.is_none() && self.queue.is_empty(), + "canSteer": !self.closed && active.is_some() && self.capabilities.steering && !self.stopping && self.steering.is_none(), + "canQueue": !self.closed && self.queued_count() < MAX_QUEUED_INPUTS && self.queued_bytes() < MAX_QUEUE_BYTES, + "canStop": !self.closed && active.is_some() && !self.stopping, + "stopping": self.stopping, "paused": self.paused, + "queue": self.queue.iter().map(|v| &**v).collect::>(), + "questions": self.questions.values().map(|v| &**v).collect::>(), + "steering": self.steering.as_deref(), "answering": self.answering, + }) + } +} + +/// Ordered notifications awaiting delivery. Shutdown releases the worker. +pub(crate) enum Delivery { + Notify { + method: &'static str, + params: Value, + input: Option>, + question: Option>, + ack: Option>, + }, + Shutdown, +} + +pub(crate) fn send(session: &LiveSession, delivery: Delivery) -> Result<(), CoreError> { + session.interaction_sender.try_send(delivery).map_err(|_| { + live::refusal( + ErrorCode::InvalidRequest, + "agents.interactionBusy", + "The agent input queue is busy; try again.", + ) + }) +} + +pub(crate) fn publish(runtime: &Runtime, session: &LiveSession, state: &crate::events::TurnState) { + runtime + .live + .queue + .push(&session.id, state.interaction.projection(state.active_turn)); +} + +/// Reserves the next queued turn while locked, preserving FIFO against a +/// simultaneous user action. Delivery itself runs without the state lock. +pub(crate) fn advance( + runtime: &Runtime, + session: &LiveSession, + state: &mut crate::events::TurnState, +) { + if state.interaction.closed + || state.interaction.dispatching.is_some() + || state.active_turn.is_some() + || state.interaction.paused + || state.interaction.queue.is_empty() + { + return; + } + let mut input = (**state.interaction.queue.front().expect("nonempty queue")).clone(); + input.turn = state.last_turn + 1; + let input = Arc::new(input); + if send_prompt(session, &input, "queued", None).is_err() { + state.interaction.paused = true; + failed(session, AGENTS_DID_PROMPT, "agents.interactionBusy"); + return; + } + state.start_turn(); + state.interaction.queue.pop_front(); + state.interaction.dispatching = Some(input.clone()); + runtime.live.queue.push( + &session.id, + json!({"kind":"promptDispatched", "turn":input.turn, "input":input.id, "content":&*input}), + ); + runtime.live.queue.push( + &session.id, + json!({"kind":"turnStarted", "turn":input.turn}), + ); +} + +/// Records transport failures and unaccepted inputs. SDKs delegate steering +/// failures here; question handler failures remain owned by the SDK. +pub(crate) fn failed(session: &LiveSession, method: &str, code: &str) { + crate::log( + "agent.interaction.failed", + [ + ("plugin", json!(session.plugin_id)), + ("session", json!(session.id)), + ("method", json!(method)), + ("code", json!(code)), + ], + ); +} + +pub(crate) fn send_prompt( + session: &LiveSession, + input: &Arc, + mode: &str, + ack: Option>, +) -> Result<(), CoreError> { + let mut params = json!({"session":session.id, "turn":input.turn, "text":input.text}); + if !input.attachments.is_empty() { + params["attachments"] = json!(input.attachments); + } + if mode == "steer" { + params["mode"] = json!("steer"); + params["input"] = json!(input.id); + } + send( + session, + Delivery::Notify { + method: AGENTS_DID_PROMPT, + params, + input: Some(input.clone()), + question: None, + ack, + }, + ) +} + +pub(crate) fn worker( + runtime: Weak, + session: Weak, + receiver: mpsc::Receiver, +) { + while let Ok(delivery) = receiver.recv() { + let Delivery::Notify { + method, + params, + input, + question, + ack, + } = delivery + else { + return; + }; + let (Some(runtime), Some(session)) = (runtime.upgrade(), session.upgrade()) else { + return; + }; + // Publish the caller's reservation before the backend can answer it. + // Never keep the runtime lock across an engine call. + let state = session.lock_turns(); + let valid = !state.interaction.closed && state.active_turn == params["turn"].as_u64(); + drop(state); + let delivered = valid + && runtime + .link + .notify(&session.backend, method, params.clone()) + .is_ok(); + if delivered { + if method == AGENTS_DID_PROMPT && params["mode"] != "steer" { + let mut state = session.lock_turns(); + if state + .interaction + .dispatching + .as_ref() + .is_some_and(|input| Some(input.turn) == params["turn"].as_u64()) + { + state.interaction.dispatching = None; + } + advance(&runtime, &session, &mut state); + publish(&runtime, &session, &state); + } + if let Some(ack) = ack { + // log-exempt: expected absence: The caller may have stopped waiting for delivery. + let _ = ack.try_send(true); + } + continue; + } + let mut state = session.lock_turns(); + if valid { + failed(&session, method, "agents.backendUnavailable"); + } + if method == AGENTS_DID_PROMPT { + if params["mode"] == "steer" { + if state + .interaction + .steering + .as_ref() + .is_some_and(|v| Some(&v.id) == input.as_ref().map(|i| &i.id)) + { + state.interaction.steering = None; + runtime.live.queue.push(&session.id, json!({"kind":"inputResolved", "turn":params["turn"], "input":params["input"], "accepted":false, "content":input})); + } + } else if state.active_turn == params["turn"].as_u64() { + let event = json!({"kind":"turnEnded", "turn":params["turn"], "reason":"failed"}); + state.active_turn = None; + state.interaction.stopping = false; + state.interaction.paused = true; + state.interaction.dispatching = None; + if let Some(input) = input.filter(|i| !i.id.is_empty()) { + runtime.live.queue.push( + &session.id, + json!({"kind":"promptRetracted","input":input.id}), + ); + state.interaction.queue.push_front(input); + } + runtime.live.queue.push(&session.id, event); + } + } else if method == AGENTS_DID_CANCEL { + if params["turn"] + .as_u64() + .filter(|turn| *turn > 0) + .is_some_and(|turn| state.active_turn == Some(turn)) + { + state.interaction.stopping = false; + } + } else if method == AGENTS_DID_ANSWER_QUESTION { + if let Some(question) = question { + if state.interaction.answering.remove(&question.request) { + runtime.live.queue.push(&session.id, json!({"kind":"questionAnswered", "turn":question.turn, "request":question.request, "accepted":false})); + } + } + } + publish(&runtime, &session, &state); + if let Some(ack) = ack { + if ack.try_send(false).is_err() && valid { + runtime.live.queue.push(&session.id, json!({"kind":"interactionFailed", "turn":params["turn"], "method":method, "code":"agents.backendUnavailable"})); + } + } + } +} + +/// Waits briefly for transport errors. A timeout means the reservation is +/// still accepted, not a safe-to-retry failure: the worker owns its outcome. +/// The engine bounds the underlying write and ends an unresponsive backend. +pub(crate) fn delivered(receiver: mpsc::Receiver) -> Result<(), CoreError> { + match receiver.recv_timeout(std::time::Duration::from_secs(5)) { + Ok(true) | Err(mpsc::RecvTimeoutError::Timeout) => Ok(()), + _ => Err(live::refusal( + ErrorCode::ProcessFailed, + "agents.backendUnavailable", + "The agent backend did not acknowledge the input.", + )), + } +} + +/// Validated answer IDs and optional text, never logged or persisted by Core. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Answer { + pub question: String, + #[serde(default)] + pub options: Vec, + #[serde(default)] + pub text: String, +} + +pub(crate) fn respond_question(runtime: &Arc, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Request { + session: String, + request: String, + #[serde(default)] + answers: Vec, + #[serde(default)] + cancelled: bool, + } + let request: Request = crate::decode(payload)?; + live::require_user("answer a question of")?; + let session = runtime.live.session(&request.session)?; + let mut state = session.lock_turns(); + let pending = state + .interaction + .questions + .get(&request.request) + .ok_or_else(|| { + live::refusal( + ErrorCode::InvalidRequest, + "agents.questionNotPending", + "This question is no longer waiting for an answer.", + ) + })?; + if state.interaction.closed + || state.interaction.answering.contains(&request.request) + || state.interaction.stopping + || state.active_turn != Some(pending.turn) + { + return Err(live::refusal( + ErrorCode::InvalidRequest, + "agents.questionNotPending", + "The question's turn is stopping or ended.", + )); + } + let valid = if request.cancelled { + request.answers.is_empty() + } else { + request.answers.len() == pending.questions.len() + && pending.questions.iter().all(|q| { + let matches: Vec<_> = request + .answers + .iter() + .filter(|a| a.question == q.id) + .collect(); + matches.len() == 1 && { + let a = matches[0]; + let unique: BTreeSet<_> = a.options.iter().collect(); + unique.len() == a.options.len() + && (q.multiple || a.options.len() <= 1) + && a.options + .iter() + .all(|id| q.options.iter().any(|o| &o.id == id)) + && a.text.len() <= MAX_QUESTION_TEXT_BYTES + && (a.text.is_empty() || q.allow_text) + && (!a.options.is_empty() || !a.text.trim().is_empty()) + } + }) + }; + if !valid { + return Err(live::refusal( + ErrorCode::InvalidRequest, + "agents.invalidQuestionAnswer", + "Answer each question using its options or allowed text.", + )); + } + let turn = pending.turn; + let pending = pending.clone(); + send( + &session, + Delivery::Notify { + method: AGENTS_DID_ANSWER_QUESTION, + params: json!({"session":session.id, "turn":turn, "request":request.request, "answers":request.answers, "cancelled":request.cancelled}), + input: None, + question: Some(pending), + ack: None, + }, + )?; + state.interaction.answering.insert(request.request.clone()); + publish(runtime, &session, &state); + Ok(json!({"turn":turn})) +} + +pub(crate) fn update_queue(runtime: &Arc, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Request { + session: String, + #[serde(default)] + remove: Option, + #[serde(default)] + resume: bool, + } + let request: Request = crate::decode(payload)?; + live::require_user("change the queue of")?; + let session = runtime.live.session(&request.session)?; + let mut state = session.lock_turns(); + if state.interaction.closed || (request.resume && state.interaction.stopping) { + return Err(live::refusal( + ErrorCode::InvalidRequest, + "agents.turnStopping", + "Wait for the current turn to stop.", + )); + } + if let Some(id) = request.remove { + let at = state + .interaction + .queue + .iter() + .position(|v| v.id == id) + .ok_or_else(|| { + live::refusal( + ErrorCode::InvalidRequest, + "agents.inputNotQueued", + "This input is no longer queued.", + ) + })?; + state.interaction.queue.remove(at); + } + if request.resume { + state.interaction.paused = false; + advance(runtime, &session, &mut state); + } + publish(runtime, &session, &state); + Ok(json!({})) +} diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 1ceaa170..930f4d25 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -38,6 +38,7 @@ mod backend; mod catalog; mod events; +mod interaction; mod library; mod live; mod records; @@ -67,6 +68,8 @@ pub const AGENT_COMMANDS: &[&str] = &[ "agents.start", "agents.prompt", "agents.cancel", + "agents.updateQueue", + "agents.respondQuestion", "agents.respondPermission", "agents.setConfigOption", "agents.close", @@ -137,6 +140,8 @@ impl Runtime { "agents.start" => live::start(self, payload), "agents.prompt" => live::prompt(self, payload), "agents.cancel" => live::cancel(self, payload), + "agents.updateQueue" => interaction::update_queue(self, payload), + "agents.respondQuestion" => interaction::respond_question(self, payload), "agents.respondPermission" => live::respond_permission(self, payload), "agents.setConfigOption" => live::set_config_option(self, payload), "agents.close" => live::close(self, payload), diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index ea321ed4..d1fe5218 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -1,7 +1,8 @@ //! 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 +//! Each session has three I/O threads and one ordered interaction worker. +//! 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 @@ -122,15 +123,30 @@ pub(crate) struct LiveSession { handle: Arc, input: SyncSender>, pub turns: Mutex, + pub interaction_sender: SyncSender, end: Mutex>, stderr_tail: Mutex>, } impl LiveSession { - fn mark_end(&self, reason: EndReason) { + fn mark_end(&self, reason: EndReason, queue: &EventQueue) { let mut end = self.end.lock().unwrap_or_else(PoisonError::into_inner); - if end.is_none() { - *end = Some(reason); + let reason = *end.get_or_insert(reason); + drop(end); + let mut state = self.lock_turns(); + state.interaction.closed = true; + state.interaction.paused = true; + // Closing and recovering are one transition. A report or delivery + // worker cannot claim the same input after it has been returned. + if let Some(input) = state.interaction.steering.take() { + let cancelled = reason == EndReason::Closed || state.interaction.stopping; + let mut event = json!({"kind":"inputResolved", "turn":input.turn,"input":input.id,"accepted":false,"content":&*input}); + if cancelled { + event["code"] = json!("cancelled"); + } else { + crate::interaction::failed(self, AGENTS_DID_PROMPT, "agents.sessionEnded"); + } + queue.push(&self.id, event); } } @@ -145,7 +161,7 @@ impl LiveSession { self.plugin_id == backend.plugin_id && self.backend == backend.session_id } - fn lock_turns(&self) -> std::sync::MutexGuard<'_, TurnState> { + pub(crate) fn lock_turns(&self) -> std::sync::MutexGuard<'_, TurnState> { self.turns.lock().unwrap_or_else(PoisonError::into_inner) } @@ -176,7 +192,7 @@ impl Live { self.lock().get(session).cloned() } - fn session(&self, session: &str) -> Result, CoreError> { + pub(crate) fn session(&self, session: &str) -> Result, CoreError> { self.get(session).ok_or_else(|| { CoreError::new( ErrorCode::EntryNotFound, @@ -212,6 +228,7 @@ impl Live { if let Some(id) = &turns.agent_session_id { entry["agentSessionID"] = json!(id); } + entry["interaction"] = turns.interaction.projection(turns.active_turn); entry }) .collect(); @@ -228,7 +245,7 @@ impl Live { .cloned() .collect(); for session in ending { - session.mark_end(EndReason::Closed); + session.mark_end(EndReason::Closed, &self.queue); session.handle.terminate(); } } @@ -243,7 +260,7 @@ impl Live { .cloned() .collect(); for session in ending { - session.mark_end(EndReason::BackendEnded); + session.mark_end(EndReason::BackendEnded, &self.queue); session.handle.terminate(); } } @@ -335,11 +352,25 @@ impl Live { })?; events.push(event); } - session - .lock_turns() + let mut state = session.lock_turns(); + let steering = state.interaction.steering.clone(); + let cancelled = state.interaction.stopping + || events.iter().any(|event| { + matches!(event, SessionEvent::TurnEnded(ended) if ended.reason == crate::events::StopReason::Cancelled) + }); + state .apply(&events) .map_err(|ReportRefusal { code, message }| refuse(code, message))?; for event in &events { + if let SessionEvent::InputResolved(input) = event { + if !input.accepted && input.code.as_deref() != Some("cancelled") { + crate::interaction::failed( + &session, + AGENTS_DID_PROMPT, + input.code.as_deref().unwrap_or("agents.inputRejected"), + ); + } + } if let SessionEvent::RateLimits(limits) = event { runtime.records.note_rate_limits( &crate::catalog::record_key(&session.plugin_id, &session.agent_id), @@ -347,9 +378,44 @@ impl Live { crate::now_ms(), ); } - let value = serde_json::to_value(event).unwrap_or(Value::Null); + let mut value = serde_json::to_value(event).expect("session events serialize to JSON"); + if matches!(event, SessionEvent::InputResolved(_)) { + value["content"] = json!(steering); + } self.queue.push(&session.id, value); } + let changed = events.iter().any(|event| { + matches!( + event, + SessionEvent::InteractionCapabilities(_) + | SessionEvent::QuestionRequested(_) + | SessionEvent::QuestionClosed(_) + | SessionEvent::QuestionAnswered(_) + | SessionEvent::InputResolved(_) + | SessionEvent::TurnEnded(_) + ) + }); + if changed { + // A steer with no CLI acknowledgement must remain recoverable when its + // target turn ends; do not carry it into the next turn. + if state.active_turn.is_none() { + if let Some(input) = state.interaction.steering.take() { + let mut event = json!({"kind":"inputResolved", "turn":input.turn,"input":input.id,"accepted":false,"content":&*input}); + if cancelled { + event["code"] = json!("cancelled"); + } else { + crate::interaction::failed( + &session, + AGENTS_DID_PROMPT, + "agents.turnChanged", + ); + } + self.queue.push(&session.id, event); + } + } + crate::interaction::advance(runtime, &session, &mut state); + crate::interaction::publish(runtime, &session, &state); + } Ok(json!({})) } @@ -397,11 +463,11 @@ struct StartRequest { environment: BTreeMap, } -fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { +pub(crate) fn refusal(code: ErrorCode, details: &'static str, message: &str) -> CoreError { CoreError::new(code, message).with_details(details) } -fn require_user(action: &str) -> Result<(), CoreError> { +pub(crate) fn require_user(action: &str) -> Result<(), CoreError> { if lithe_request_context::trace::current().source == Source::User { Ok(()) } else { @@ -566,6 +632,7 @@ fn start_checked(runtime: &Arc, request: StartRequest) -> Result, request: StartRequest) -> Result, request: StartRequest) -> Result, request: StartRequest) -> Result, request: StartRequest) -> Result, session: &Arc, output: Box, session: &Arc) { } let disposed = handle.dispose(DISPOSE_TIMEOUT).is_ok(); let exit_code = status.or_else(|| handle.exit_status()).flatten(); - session.mark_end(EndReason::Exited); + session.mark_end(EndReason::Exited, &runtime.live.queue); let reason = if disposed { session.end_reason() } else { EndReason::Failed }; + // log-exempt: expected absence: The interaction worker may already have ended. + let _ = session + .interaction_sender + .try_send(crate::interaction::Delivery::Shutdown); runtime.live.lock().remove(&session.id); if reason != EndReason::BackendEnded { let mut params = json!({ "session": session.id }); @@ -966,6 +1049,13 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, + #[serde(default = "default_input_mode")] + mode: String, + #[serde(rename = "expectedTurn", default)] + expected_turn: Option, + } + fn default_input_mode() -> String { + "send".into() } #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -996,70 +1086,144 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, _>>()?; - let Some(turn) = session.lock_turns().start_turn() else { + let mut state = session.lock_turns(); + if state.interaction.closed { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.unknownSession", + "The agent session is closing.", + )); + } + let mode = request.mode.as_str(); + if !matches!(mode, "send" | "queue" | "steer") { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.invalidInputMode", + "Input mode must be send, queue or steer.", + )); + } + if mode == "steer" + && (!state.interaction.capabilities.steering + || state.interaction.stopping + || state.interaction.steering.is_some()) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.steeringUnavailable", + "The agent cannot take a running-turn input now.", + )); + } + if mode == "steer" + && (request.expected_turn.is_none() || request.expected_turn != state.active_turn) + { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.turnChanged", + "The active turn changed; send this as a new prompt or queue it.", + )); + } + if mode == "send" && (state.active_turn.is_some() || !state.interaction.queue.is_empty()) { return Err(refusal( ErrorCode::InvalidRequest, "agents.turnInProgress", - "The agent is still working on the previous prompt.", + "Send a running-turn input or queue this prompt.", )); - }; - runtime - .live - .queue - .push(&session.id, json!({ "kind": "turnStarted", "turn": turn })); - let mut params = json!({ "session": session.id, "turn": turn, "text": request.text }); - if !attachments.is_empty() { - params["attachments"] = json!(attachments); - } - if runtime - .link - .notify(&session.backend, AGENTS_DID_PROMPT, params) - .is_err() + } + let bytes = request.text.len() + + attachments + .iter() + .map(|v| v.to_string().len()) + .sum::(); + if mode == "queue" + && (state.interaction.queued_count() >= crate::interaction::MAX_QUEUED_INPUTS + || state.interaction.queued_bytes() + bytes > crate::interaction::MAX_QUEUE_BYTES) { - 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.", + ErrorCode::InvalidRequest, + "agents.queueFull", + "The queue holds at most eight prompts and four MiB; remove or send an entry first.", )); } - Ok(json!({ "turn": turn })) + state.interaction.next_input += 1; + let turn = if mode == "steer" { + state.active_turn.unwrap_or(0) + } else { + state.last_turn + 1 + }; + let input = Arc::new(crate::interaction::Input { + id: if mode == "send" { + String::new() + } else { + format!("input-{}", state.interaction.next_input) + }, + text: request.text, + attachments, + turn, + }); + let (ack, receiver) = mpsc::sync_channel(1); + if mode == "queue" { + state.interaction.queue.push_back(input.clone()); + crate::interaction::advance(runtime, &session, &mut state); + } else { + crate::interaction::send_prompt(&session, &input, mode, (mode == "send").then_some(ack))?; + if mode == "steer" { + state.interaction.steering = Some(input.clone()); + } else { + state.interaction.paused = false; + state.start_turn(); + runtime + .live + .queue + .push(&session.id, json!({"kind":"turnStarted", "turn":turn})); + } + } + crate::interaction::publish(runtime, &session, &state); + drop(state); + if mode == "send" { + crate::interaction::delivered(receiver)?; + } + if mode == "send" { + Ok(json!({"turn":turn})) + } else { + Ok(json!({"turn":turn,"input":input.id})) + } } -/// `agents.cancel`: asks the agent to stop the turn in progress. +/// `agents.cancel`: pauses the queue and waits for the CLI's turn end. pub(crate) fn cancel(runtime: &Arc, payload: Value) -> Result { let request: SessionRequest = crate::decode(payload)?; + require_user("stop")?; let session = runtime.live.session(&request.session)?; - let Some(turn) = session.lock_turns().active_turn else { + let mut state = session.lock_turns(); + let Some(turn) = state.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 })) + let (ack, receiver) = mpsc::sync_channel(1); + let wait = !state.interaction.stopping; + if wait { + crate::interaction::send( + &session, + crate::interaction::Delivery::Notify { + method: AGENTS_DID_CANCEL, + params: json!({"session":session.id,"turn":turn}), + input: None, + question: None, + ack: Some(ack), + }, + )?; + state.interaction.stopping = true; + state.interaction.paused = true; + crate::interaction::publish(runtime, &session, &state); + } + drop(state); + if wait { + crate::interaction::delivered(receiver)?; + } + Ok(json!({"turn":turn})) } /// `agents.respondPermission`: the user's answer to a permission request. @@ -1170,7 +1334,7 @@ pub(crate) fn set_config_option( 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.mark_end(EndReason::Closed, &runtime.live.queue); session.handle.close_input(); let handle = session.handle.clone(); let waiting = spawn("agent-close", move || { diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 038589bd..437e1f55 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -13,9 +13,9 @@ use lithe_lsp_engine::agent_host::{AgentBackend, AgentCallFailure, AgentHost, Ag 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_SET_CONFIG_OPTION, AGENTS_DID_START, AGENTS_REPORT, AGENTS_USAGE, - AGENTS_WRITE, + codes, AGENTS_DID_ANSWER_QUESTION, AGENTS_DID_CANCEL, AGENTS_DID_DECIDE_PERMISSION, + AGENTS_DID_EXIT, AGENTS_DID_OUTPUT, AGENTS_DID_PROMPT, AGENTS_DID_SET_CONFIG_OPTION, + AGENTS_DID_START, AGENTS_REPORT, AGENTS_USAGE, AGENTS_WRITE, }; use lithe_protocol::{CoreError, ErrorCode}; use lithe_request_context::{trace, Source}; @@ -1837,3 +1837,347 @@ fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { } mod library; + +#[test] +fn turn_interaction_follows_the_shared_application_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/agents/turn-interaction-v1.json" + )) + .unwrap(); + let harness = Harness::new("interaction-fixture", ALL_GRANTS); + let session = harness.start(); + let mut cursor = 0; + for phase in fixture["phases"].as_array().unwrap() { + for action in phase["actions"].as_array().unwrap() { + if let Some(command) = action["command"].as_str() { + let mut payload = action["payload"].clone(); + payload["session"] = json!(session); + let result = harness.run(command, payload); + if command == "agents.prompt" && action["payload"]["mode"] == "steer" { + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["input"] == result["input"]); + } + } else { + harness.report(&session, action["report"].clone()).unwrap(); + } + } + let active = &phase["interaction"]["activeTurn"]; + if active.as_u64().unwrap() > 1 { + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| &p["turn"] == active); + } + assert_eq!(harness.sessions()[0]["interaction"], phase["interaction"]); + let batch = harness.run("agents.waitEvents", json!({"after":cursor})); + cursor = batch["next"].as_u64().unwrap(); + let events: Vec<_> = batch["events"] + .as_array() + .unwrap() + .iter() + .map(|entry| &entry["event"]) + .filter(|event| { + matches!( + event["kind"].as_str(), + Some( + "turnStarted" + | "turnEnded" + | "promptDispatched" + | "promptRetracted" + | "inputResolved" + | "questionRequested" + | "questionAnswered" + ) + ) + }) + .cloned() + .collect(); + assert_eq!(json!(events), phase["events"]); + } + assert_eq!(harness.link.notices_of(AGENTS_DID_PROMPT).len(), 3); +} + +#[test] +fn queued_inputs_follow_fifo_and_stop_pauses_even_a_completed_turn() { + let harness = Harness::new("queue-stop", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + let second = harness.run( + "agents.prompt", + json!({"session":session,"text":"second","mode":"queue"}), + ); + let third = harness.run( + "agents.prompt", + json!({"session":session,"text":"third","mode":"queue"}), + ); + assert_eq!(harness.link.notices_of(AGENTS_DID_PROMPT).len(), 1); + harness + .report( + &session, + json!([{"kind":"turnEnded","turn":1,"reason":"completed"}]), + ) + .unwrap(); + harness.link.await_notice(AGENTS_DID_PROMPT, |p| { + p["turn"] == 2 && p["text"] == "second" + }); + harness.run("agents.cancel", json!({"session":session})); + assert_eq!(harness.sessions()[0]["interaction"]["stopping"], true); + // A result racing the stop cannot silently restart the queue. + harness + .report( + &session, + json!([{"kind":"turnEnded","turn":2,"reason":"completed"}]), + ) + .unwrap(); + let state = &harness.sessions()[0]["interaction"]; + assert_eq!(state["paused"], true); + assert_eq!(state["queue"][0]["id"], third["input"]); + assert_eq!(harness.link.notices_of(AGENTS_DID_PROMPT).len(), 2); + harness.run( + "agents.updateQueue", + json!({"session":session,"remove":third["input"]}), + ); + assert_eq!(harness.sessions()[0]["interaction"]["queue"], json!([])); + harness.run( + "agents.prompt", + json!({"session":session,"mode":"queue","text":"fourth"}), + ); + harness.run( + "agents.updateQueue", + json!({"session":session,"resume":true}), + ); + harness.link.await_notice(AGENTS_DID_PROMPT, |p| { + p["turn"] == 3 && p["text"] == "fourth" + }); + assert_ne!(second["input"], third["input"]); +} + +#[test] +fn steering_requires_capability_and_expected_turn_and_retains_rejected_content() { + let mut harness = Harness::new("steering", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + let input = + json!({"session":session,"mode":"steer","expectedTurn":1,"text":"also keep comments"}); + assert_eq!( + harness.refused("agents.prompt", input.clone()), + "agents.steeringUnavailable" + ); + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","steering":true}]), + ) + .unwrap(); + let mut stale = input.clone(); + stale["expectedTurn"] = json!(2); + assert_eq!( + harness.refused("agents.prompt", stale), + "agents.turnChanged" + ); + let sent = harness.run("agents.prompt", input.clone()); + let notice = harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["mode"] == "steer"); + assert_eq!(notice["turn"], 1); + assert_eq!(notice["input"], sent["input"]); + assert_eq!( + harness.refused("agents.prompt", input), + "agents.steeringUnavailable" + ); + let invalid = harness + .report( + &session, + json!([{ + "kind":"inputResolved", "turn":1, "input":sent["input"], + "accepted":false, "code":"private details" + }]), + ) + .expect_err("failure categories are closed"); + assert_eq!(invalid.code, codes::HOST_INVALID_PARAMS); + assert_eq!( + harness.sessions()[0]["interaction"]["steering"]["id"], + sent["input"] + ); + let (result, logs) = + capture::run(false, || { + harness.report(&session, json!([{ + "kind":"inputResolved", "turn":1, "input":sent["input"], + "accepted":false, "code":"internal_error", "message":"private failure explanation" + }])) + }); + result.unwrap(); + let failures: Vec<_> = logs + .iter() + .filter(|log| log.event == "agent.interaction.failed") + .collect(); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].fields["code"], "internal_error"); + let fields = serde_json::to_string(&failures[0].fields).unwrap(); + assert!( + !fields.contains("private failure explanation") && !fields.contains("also keep comments") + ); + let event = harness.next_event(&session, "inputResolved"); + assert_eq!(event["content"]["text"], "also keep comments"); + assert_eq!(harness.sessions()[0]["activeTurn"], 1); + assert_eq!(harness.sessions()[0]["interaction"]["canSteer"], true); + + let cancelled = harness.run( + "agents.prompt", + json!({ + "session":session, "mode":"steer", "expectedTurn":1, "text":"cancel this input" + }), + ); + let (result, logs) = capture::run(false, || { + harness.report(&session, json!([{ + "kind":"inputResolved", "turn":1, "input":cancelled["input"], "accepted":false, "code":"cancelled" + }])) + }); + result.unwrap(); + assert!(!logs + .iter() + .any(|log| log.event == "agent.interaction.failed")); +} + +#[test] +fn questions_validate_every_answer_and_retry_failed_delivery_without_losing_the_request() { + let harness = Harness::new("questions", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + harness.report(&session, json!([ + {"kind":"interactionCapabilities","questions":true}, + {"kind":"questionRequested","turn":1,"request":"q1","questions":[ + {"id":"one","title":"Choice","text":"Choose one","options":[{"id":"a","label":"A"},{"id":"b","label":"B"}]}, + {"id":"two","title":"Details","text":"Why?","allowText":true} + ]} + ])).unwrap(); + let mut answer = json!({"session":session,"request":"q1","answers":[{"question":"one","options":["a","b"]},{"question":"two","text":"reason"}]}); + assert_eq!( + harness.refused("agents.respondQuestion", answer.clone()), + "agents.invalidQuestionAnswer" + ); + answer["answers"][0]["options"] = json!(["a"]); + harness.run("agents.respondQuestion", answer.clone()); + assert_eq!( + harness.sessions()[0]["interaction"]["answering"], + json!(["q1"]) + ); + assert_eq!( + harness.refused("agents.respondQuestion", answer.clone()), + "agents.questionNotPending" + ); + harness + .link + .await_notice(AGENTS_DID_ANSWER_QUESTION, |p| p["request"] == "q1"); + // The SDK reports failure and the same card becomes answerable again. + harness + .report( + &session, + json!([{"kind":"questionAnswered","turn":1,"request":"q1","accepted":false}]), + ) + .unwrap(); + assert_eq!( + harness.sessions()[0]["interaction"]["questions"][0]["request"], + "q1" + ); + harness.run("agents.respondQuestion", answer); + harness + .report( + &session, + json!([{"kind":"questionAnswered","turn":1,"request":"q1","accepted":true}]), + ) + .unwrap(); + assert_eq!(harness.sessions()[0]["interaction"]["questions"], json!([])); + let previous = trace::replace(trace::Context { + op: None, + source: Source::Background, + }); + for (command, payload) in [ + ("agents.cancel", json!({"session":session})), + ( + "agents.updateQueue", + json!({"session":session,"resume":true}), + ), + ( + "agents.respondQuestion", + json!({"session":session,"request":"q1","cancelled":true}), + ), + ] { + assert_eq!( + harness.refused(command, payload), + "agents.userActionRequired" + ); + } + trace::replace(previous); +} + +#[test] +fn user_cancellation_restores_unconfirmed_input_without_a_failure() { + for action in ["stop", "close"] { + let mut harness = Harness::new("steer-cancelled", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","steering":true}]), + ) + .unwrap(); + let sent = harness.run( + "agents.prompt", + json!({"session":session,"mode":"steer","expectedTurn":1,"text":"keep this input"}), + ); + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["input"] == sent["input"]); + let (_, logs) = capture::run(false, || { + if action == "stop" { + harness.run("agents.cancel", json!({"session":session})); + // A completed report racing Stop is still a user cancellation. + harness + .report( + &session, + json!([{"kind":"turnEnded","turn":1,"reason":"completed"}]), + ) + .unwrap(); + } else { + harness.run("agents.close", json!({"session":session})); + } + }); + assert!( + !logs + .iter() + .any(|log| log.event == "agent.interaction.failed"), + "{action} must not record a rejected input" + ); + let restored = harness.next_event(&session, "inputResolved"); + assert_eq!(restored["code"], "cancelled"); + assert_eq!(restored["accepted"], false); + assert_eq!(restored["content"]["text"], "keep this input"); + } +} + +#[test] +fn exiting_before_steering_acknowledgement_returns_the_original_input() { + let mut harness = Harness::new("steer-exit", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","steering":true}]), + ) + .unwrap(); + let sent = harness.run( + "agents.prompt", + json!({"session":session,"mode":"steer","expectedTurn":1,"text":"keep this input"}), + ); + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["input"] == sent["input"]); + harness.link.server(0).exit(Some(1)); + let restored = harness.next_event(&session, "inputResolved"); + assert_eq!(restored["accepted"], false); + assert_eq!(restored["content"]["text"], "keep this input"); + assert_eq!(harness.next_event(&session, "exited")["exitCode"], 1); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 2df08078..6cfa8eb5 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -236,6 +236,10 @@ pub enum AgentsCommand { Cancel, /// Answers a pending permission request (`agents.respondPermission`). RespondPermission, + /// Removes a queued prompt or resumes its paused queue (`agents.updateQueue`). + UpdateQueue, + /// Answers a structured question of the active turn (`agents.respondQuestion`). + RespondQuestion, /// Picks a value of a session setting the backend reported (`agents.setConfigOption`). SetConfigOption, /// Ends a live session (`agents.close`). @@ -283,6 +287,8 @@ impl AgentsCommand { Self::Prompt => "agents.prompt", Self::Cancel => "agents.cancel", Self::RespondPermission => "agents.respondPermission", + Self::UpdateQueue => "agents.updateQueue", + Self::RespondQuestion => "agents.respondQuestion", Self::SetConfigOption => "agents.setConfigOption", Self::Close => "agents.close", Self::WaitEvents => "agents.waitEvents", @@ -1287,6 +1293,8 @@ impl CoreCommand { "agents.prompt" => Some(Self::Agents(AgentsCommand::Prompt)), "agents.cancel" => Some(Self::Agents(AgentsCommand::Cancel)), "agents.respondPermission" => Some(Self::Agents(AgentsCommand::RespondPermission)), + "agents.updateQueue" => Some(Self::Agents(AgentsCommand::UpdateQueue)), + "agents.respondQuestion" => Some(Self::Agents(AgentsCommand::RespondQuestion)), "agents.setConfigOption" => Some(Self::Agents(AgentsCommand::SetConfigOption)), "agents.close" => Some(Self::Agents(AgentsCommand::Close)), "agents.waitEvents" => Some(Self::Agents(AgentsCommand::WaitEvents)), diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index ba17c287..365971de 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -6,6 +6,21 @@ use super::{EventMetadata, FieldMetadata, FieldType, LogLevel, SpanPhase}; /// Sorted, immutable metadata for every expanded catalog event. #[rustfmt::skip] pub static EVENTS: &[EventMetadata] = &[ + EventMetadata { + id: "agent.interaction.failed", + channel: "agent", + level: LogLevel::Error, + message: "Agent interaction failed", + fields: &[ + FieldMetadata { name: "code", field_type: FieldType::Token, required: true, description: "Stable transport or input refusal category; never user content", reason: None }, + FieldMetadata { name: "method", field_type: FieldType::Token, required: true, description: "Agent notification being delivered", reason: None }, + FieldMetadata { name: "plugin", field_type: FieldType::Id, required: true, description: "Validated plugin identity", reason: None }, + FieldMetadata { name: "session", field_type: FieldType::Id, required: true, description: "Opaque Core session ID", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "agent.library.change_applied", channel: "agent", diff --git a/rust/crates/plugin-rpc/src/host_notifications.rs b/rust/crates/plugin-rpc/src/host_notifications.rs index e56f1e54..bd13bf38 100644 --- a/rust/crates/plugin-rpc/src/host_notifications.rs +++ b/rust/crates/plugin-rpc/src/host_notifications.rs @@ -87,6 +87,8 @@ pub const AGENTS_DID_START: &str = "lithe/host/agents/didStart"; 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 answered or cancelled a structured question. +pub const AGENTS_DID_ANSWER_QUESTION: &str = "lithe/host/agents/didAnswerQuestion"; /// The user cancelled a turn. pub const AGENTS_DID_CANCEL: &str = "lithe/host/agents/didCancel"; /// The user answered a permission request the backend reported. @@ -156,6 +158,12 @@ pub(crate) const HOST_NOTIFICATIONS: &[HostNotification] = &[ grant: Some(AGENTS_WRITE), params: NotificationParams::Agent, }, + HostNotification { + method: AGENTS_DID_ANSWER_QUESTION, + service: HOST_SERVICE_AGENTS, + grant: Some(AGENTS_WRITE), + params: NotificationParams::Agent, + }, HostNotification { method: AGENTS_DID_CANCEL, service: HOST_SERVICE_AGENTS, diff --git a/rust/fixtures/agents/turn-interaction-v1.json b/rust/fixtures/agents/turn-interaction-v1.json new file mode 100644 index 00000000..7df9f0b3 --- /dev/null +++ b/rust/fixtures/agents/turn-interaction-v1.json @@ -0,0 +1,85 @@ +{ + "description": "Core and desktop share this synthetic session: queued prompts appear only on dispatch, rejected steering returns its content, failed answers remain retryable, and stopping wins over a racing completed result.", + "initialPrompt": "First task", + "phases": [ + { + "actions": [ + {"command": "agents.prompt", "payload": {"text": "First task"}}, + {"command": "agents.prompt", "payload": {"mode": "queue", "text": "Second task"}}, + {"command": "agents.prompt", "payload": {"mode": "queue", "text": "Third task"}}, + {"report": [ + {"kind": "interactionCapabilities", "steering": true, "questions": true}, + {"kind": "questionRequested", "turn": 1, "request": "q1", "questions": [ + {"id": "scope", "title": "Scope", "text": "Which scope?", "options": [{"id": "file", "label": "Current file"}], "allowText": true} + ]} + ]} + ], + "events": [ + {"kind": "turnStarted", "turn": 1}, + {"kind": "questionRequested", "turn": 1, "request": "q1", "questions": [ + {"id": "scope", "title": "Scope", "text": "Which scope?", "options": [{"id": "file", "label": "Current file", "description": ""}], "multiple": false, "allowText": true} + ]} + ], + "interaction": { + "kind": "interactionState", "activeTurn": 1, "canPrompt": false, "canSteer": true, "canQueue": true, "canStop": true, + "stopping": false, "paused": false, + "queue": [{"id": "input-2", "text": "Second task", "attachments": []}, {"id": "input-3", "text": "Third task", "attachments": []}], + "questions": [{"turn": 1, "request": "q1", "questions": [ + {"id": "scope", "title": "Scope", "text": "Which scope?", "options": [{"id": "file", "label": "Current file", "description": ""}], "multiple": false, "allowText": true} + ]}], "steering": null, "answering": [] + } + }, + { + "actions": [ + {"command": "agents.prompt", "payload": {"mode": "steer", "expectedTurn": 1, "text": "Keep this input"}}, + {"report": [{"kind": "inputResolved", "turn": 1, "input": "input-4", "accepted": false}]}, + {"command": "agents.respondQuestion", "payload": {"request": "q1", "answers": [{"question": "scope", "options": ["file"]}]}}, + {"report": [{"kind": "questionAnswered", "turn": 1, "request": "q1", "accepted": false}]} + ], + "events": [ + {"kind": "inputResolved", "turn": 1, "input": "input-4", "accepted": false, "content": {"id": "input-4", "text": "Keep this input", "attachments": []}}, + {"kind": "questionAnswered", "turn": 1, "request": "q1", "accepted": false} + ], + "interaction": { + "kind": "interactionState", "activeTurn": 1, "canPrompt": false, "canSteer": true, "canQueue": true, "canStop": true, + "stopping": false, "paused": false, + "queue": [{"id": "input-2", "text": "Second task", "attachments": []}, {"id": "input-3", "text": "Third task", "attachments": []}], + "questions": [{"turn": 1, "request": "q1", "questions": [ + {"id": "scope", "title": "Scope", "text": "Which scope?", "options": [{"id": "file", "label": "Current file", "description": ""}], "multiple": false, "allowText": true} + ]}], "steering": null, "answering": [] + } + }, + { + "actions": [ + {"command": "agents.respondQuestion", "payload": {"request": "q1", "answers": [{"question": "scope", "options": ["file"]}]}}, + {"report": [{"kind": "questionAnswered", "turn": 1, "request": "q1", "accepted": true}]}, + {"report": [{"kind": "turnEnded", "turn": 1, "reason": "completed"}]} + ], + "events": [ + {"kind": "questionAnswered", "turn": 1, "request": "q1", "accepted": true}, + {"kind": "turnEnded", "turn": 1, "reason": "completed"}, + {"kind": "promptDispatched", "turn": 2, "input": "input-2", "content": {"id": "input-2", "text": "Second task", "attachments": []}}, + {"kind": "turnStarted", "turn": 2} + ], + "interaction": { + "kind": "interactionState", "activeTurn": 2, "canPrompt": false, "canSteer": true, "canQueue": true, "canStop": true, + "stopping": false, "paused": false, + "queue": [{"id": "input-3", "text": "Third task", "attachments": []}], "questions": [], "steering": null, "answering": [] + } + }, + { + "actions": [ + {"command": "agents.cancel", "payload": {}}, + {"report": [{"kind": "turnEnded", "turn": 2, "reason": "completed"}]} + ], + "events": [{"kind": "turnEnded", "turn": 2, "reason": "completed"}], + "interaction": { + "kind": "interactionState", "activeTurn": 0, "canPrompt": false, "canSteer": false, "canQueue": true, "canStop": false, + "stopping": false, "paused": true, + "queue": [{"id": "input-3", "text": "Third task", "attachments": []}], "questions": [], "steering": null, "answering": [] + } + } + ], + "expectedPrompts": ["First task", "Second task"], + "expectedDraft": "Keep this input" +} diff --git a/rust/logging/events/agent.json b/rust/logging/events/agent.json index 34df3c20..88a536ed 100644 --- a/rust/logging/events/agent.json +++ b/rust/logging/events/agent.json @@ -87,6 +87,20 @@ "rate": 60, "owner": "lithe-core" }, + { + "id": "agent.interaction.failed", + "channel": "agent", + "level": "error", + "message": "Agent interaction failed", + "fields": { + "plugin": {"type": "id", "required": true, "description": "Validated plugin identity"}, + "session": {"type": "id", "required": true, "description": "Opaque Core session ID"}, + "method": {"type": "token", "required": true, "description": "Agent notification being delivered"}, + "code": {"type": "token", "required": true, "description": "Stable transport or input refusal category; never user content"} + }, + "rate": 60, + "owner": "lithe-core" + }, { "id": "agent.report.rejected", "channel": "agent", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 882bac2e..c7737bcb 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3808,18 +3808,22 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. | Command | Payload | Result | | --- | --- | --- | | `agents.start` | `{pluginID, agentID, cwd, toolPath, rootURI?, resume?, workspaceTrusted, environment}` | `{session, mode: "native"}` | -| `agents.prompt` | `{session, text, attachments?}` | `{turn}` | +| `agents.prompt` | `{session, text, attachments?, mode?, expectedTurn?}` | `{turn}` for `send`; `{turn, input}` for `steer` or `queue` (a queued `turn` is provisional until dispatch) | | `agents.cancel` | `{session}` | `{turn}` | +| `agents.updateQueue` | `{session, remove?, resume?}` | `{}` | +| `agents.respondQuestion` | `{session, request, answers?, cancelled?}` | `{turn}` | | `agents.respondPermission` | `{session, permission, option}` | `{turn}` | | `agents.setConfigOption` | `{session, option, value}` | `{}` | | `agents.close` | `{session}` | `{}` | | `agents.sessions` | `{}` | `{sessions}`: the live sessions | | `agents.waitEvents` | `{after?, timeoutMilliseconds?, limit?}` | `{events: [{sequence, session, event}], next, missed}` | -- `agents.start`, `agents.prompt`, `agents.respondPermission` and +- `agents.start`, `agents.prompt`, `agents.cancel`, `agents.updateQueue`, + `agents.respondQuestion`, `agents.respondPermission` and `agents.setConfigOption` run only for a request whose origin is the user (`agents.userActionRequired`): a plugin cannot start a session, send a - prompt, answer a permission request or change a session setting. + prompt, stop a turn, alter the queue, answer a question or permission + request, or change a session setting. - `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 @@ -3838,7 +3842,8 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. or NUL, a value at most 32 KiB without NUL). The backend cannot add to it. - `agents.prompt` takes at most 1 MiB of text, which may be empty only when the prompt carries attachments (`agents.invalidPrompt`), and refuses - a second turn while one runs (`agents.turnInProgress`). `attachments` is + a second `send` while one runs (`agents.turnInProgress`). `mode` defaults + to `send`; other modes are defined below. `attachments` is the files, folders and images the user picked, pasted or dropped, in the user's order: at most 64 `{path}` (`agents.tooManyAttachments`), each an absolute path to an existing file or directory @@ -3860,6 +3865,45 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. does not list (`agents.unknownConfigOption`, `agents.unknownConfigValue`). A prompt, cancel, answer or setting the backend does not take is `agents.backendUnavailable`. An unknown session is `agents.unknownSession`. +- `mode: "send"` starts a turn only when no turn runs and no input is queued; + otherwise it is `agents.turnInProgress`. `mode: "steer"` targets the + active turn and requires the exact `expectedTurn` plus the backend's + `interactionCapabilities.steering`. A missing or stale turn is + `agents.turnChanged`; an unsupported, stopping or already-reserved input + is `agents.steeringUnavailable`. Core retains the content until the CLI + confirms `inputResolved`; returning from the prompt command does not + confirm the CLI accepted it. Unknown modes are `agents.invalidInputMode`. +- `mode: "queue"` appends to a FIFO of at most eight inputs and 4 MiB of + retained text plus attachment metadata, including an input being + dispatched (`agents.queueFull`). Queued content is in memory only. + An idle, unpaused queue dispatches immediately; each completed turn + dispatches its next entry. Failed, refused, limited or cancelled turns + pause it and retain the remaining entries. `agents.updateQueue` removes + one queued `input` by `remove` (`agents.inputNotQueued` if it already + left the queue) and/or clears the pause with `resume: true`. The actual + turn number is assigned at dispatch, never by the provisional queue result. +- `agents.cancel` is idempotent for the current turn: it marks `stopping` + and pauses the queue before delivery. The turn ends only on a real + `turnEnded` or session exit. Even a racing `completed` result cannot + restart a stopped queue. A resume while stopping is `agents.turnStopping`. + New queued input may be retained while stopping; it does not resume the queue. +- Ordinary prompt and cancel commands wait at most five seconds for + backend transport delivery. A wait timeout means the reservation is + accepted and its outcome remains with Core's worker; it is not permission + to retry. Delivery failure is `agents.backendUnavailable`; Core retracts + a queued dispatch to the queue head and pauses it. A full delivery worker + is `agents.interactionBusy`. No runtime state lock is held across backend I/O. +- `agents.respondQuestion` reserves an answer to a pending request of the + active, non-stopping turn. An absent, expired or already-reserved request + is `agents.questionNotPending`. With `cancelled: false` (default), + `answers` has exactly one `{question, options?, text?}` per question, + unique offered option IDs, at most one choice unless `multiple`, and at + most 16 KiB of UTF-8 text only when `allowText`. Every question needs a + selection or nonblank text; malformed answers are + `agents.invalidQuestionAnswer`. `cancelled: true` requires no answers and + asks the backend to cancel this question, not the turn. The request stays + visible in `answering` until `questionAnswered`: success removes it; + failure releases the reservation and permits retry with the same draft. - `agents.close` closes the CLI's standard input and ends the process after three seconds. - `agents.waitEvents` waits at most `timeoutMilliseconds` (default 0, at @@ -3896,8 +3940,9 @@ plugin backend only translates between the CLI's lines and Lithe's events: `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, permission decision or setting change of the user - reaches the backend as `didPrompt`, `didCancel`, `didDecidePermission` or +4. A prompt, running-turn input, question answer, cancel, permission decision + or setting change reaches the backend as `didPrompt`, + `didAnswerQuestion`, `didCancel`, `didDecidePermission` or `didSetConfigOption`; the backend writes what the CLI expects. `didExit` follows the end of the process. @@ -3907,8 +3952,9 @@ Notifications Core sends (the host may not send them): | --- | --- | | `lithe/host/agents/didStart` | `{session, agentID, cwd, resume?}` | | `lithe/host/agents/didOutput` | `{session, lines}` | -| `lithe/host/agents/didPrompt` | `{session, turn, text, attachments?}` | +| `lithe/host/agents/didPrompt` | `{session, turn, text, attachments?, mode?: "steer", input?}`; `mode` and `input` occur together only for running-turn input | | `lithe/host/agents/didCancel` | `{session, turn}` | +| `lithe/host/agents/didAnswerQuestion` | `{session, turn, request, answers: [{question, options, text}], cancelled}` | | `lithe/host/agents/didDecidePermission` | `{session, turn, permission, option}` | | `lithe/host/agents/didSetConfigOption` | `{session, option, value}` | | `lithe/host/agents/didExit` | `{session, exitCode?}` | @@ -3935,6 +3981,16 @@ Notifications Core sends (the host may not send them): the next turn, and reports `configOptions` again with the new current value; when the CLI refuses it, the backend reports the unchanged settings and a `notice`. +- `didPrompt` without `mode` starts a new turn, including a queued prompt. + With `mode: "steer"`, it must target the CLI's still-active turn and + preserve that turn's identity. The backend reports `inputResolved` only + after the CLI accepts or rejects it. Never emulate steering by starting + a new turn or by acknowledging a write before the CLI responds. +- `didAnswerQuestion` contains opaque IDs from `questionRequested`. The + plugin maps them back to the CLI's original request and option values. + Its handler succeeds only once the response is delivered to the CLI; + official SDKs then report `questionAnswered` automatically (false on + handler failure). Do not also report this acknowledgement in the handler. - `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 @@ -3983,6 +4039,44 @@ Session events (`report`'s `events[]`, each tagged by `kind`): | `turnEnded` | `turn, reason` (`completed`, `cancelled`, `maxTokens`, `maxTurns`, `refused`, `failed`), `message?` | | `notice` | `level` (`info`, `warning`, `error`), `text, code?` | | `configOptions` | `configOptions`: at most 16 `{id, name, description?, category?, currentValue, options}`, `category` one of `model`, `thoughtLevel`, `mode`, `options` 1–128 `{value, name, description?}` | +| `interactionCapabilities` | `steering?, questions?`, both default false; replaces the session's supported interactions | +| `questionRequested` | `turn, request, questions`: 1–8 `{id, title, text, options?, multiple?, allowText?}`, `options` at most 16 `{id, label, description?}` | +| `questionClosed` | `turn, request`: withdraws a pending question batch | +| `questionAnswered` | `turn, request, accepted`: confirms delivery of a reserved answer; emitted by the official SDKs | +| `inputResolved` | `turn, input, accepted, code?, message?`: confirms or rejects the reserved running-turn input; `code` is one of `plugin_error`, `internal_error`, `panic`, `cancelled` | + +Running-turn input is identified only by notification method +`lithe/host/agents/didPrompt` together with `mode: "steer"` (the Rust SDK +decodes precisely that pair into its `Notice::Steer` variant). On a steering +handler failure all four SDKs report `inputResolved` with the controlled +failure `code`, delegating the single terminal diagnostic to Core instead +of also logging a handler failure. A CLI refusal may omit `code`, in which +case Core records `agents.inputRejected`. `cancelled` restores the input +without an error diagnostic. `message` is for display only and never logged. +Question-answer handler failures remain diagnosed by the SDK. + +Only advertise interaction capabilities the CLI really supports. Questions +are plain text forms, never a way to collect passwords or credentials; +secret questions must be rejected by the plugin rather than converted to +text input. At most eight question batches may be pending. Request IDs, +question IDs and option IDs are opaque; request IDs are unique while +pending, question IDs within their batch, option IDs within their question. +Titles and option labels are 1–1024 bytes, question bodies and answers at +most 16 KiB, descriptions at most 4 KiB. A question with no options must +allow text. `multiple` and `allowText` default false; missing options and +descriptions default to empty. Requests belong to the active turn and are +cleared on turn end, withdrawal or exit. Expired or duplicate delivery +acknowledgements are `-32019`; they cannot consume another pending input. +All report objects remain strictly decoded, including the controlled +`inputResolved.code` values. A refused report applies nothing. + +These are additions within API-45, `agents` 0 and `litheFunctions` 0; +`pluginAPIVersion` and `schemaVersion` remain 0. The first Core revision +and desktop release containing these interactions have not been published; +use matching Core/SDK sources for local development. Older Core revisions +strictly reject the new events and command fields, so capability version 0 +alone does not prove support. A plugin targeting them must retain its +original interactions and handle rejection before advertising the extension. - Labels and IDs are 1 byte to 1 KiB; texts at most 1 MiB. - `configOptions` lists the settings of the session the user may change, @@ -4007,6 +4101,24 @@ Besides the backend's events, `agents.waitEvents` carries Core's own: `closed`, `failed` or `backendEnded` and `stderrTail` is the last 8 KiB the CLI wrote to standard error. +Core also emits `interactionState {activeTurn, canPrompt, canSteer, canQueue, +canStop, stopping, paused, queue, questions, steering, answering}` when an +interaction changes, not for token deltas. `activeTurn` is 0 when idle; +`queue` and `steering` carry `{id, text, attachments}` (`steering` is null +when absent), `questions` carries pending request objects, and `answering` +lists request IDs awaiting delivery confirmation. `agents.sessions` includes +the same projection as `interaction` for each live session. The host renders +these action flags instead of deriving its own queue or stop state. + +A queued prompt adds `promptDispatched {turn, input, content}` before +`turnStarted`; `promptRetracted {turn, input}` removes it if delivery fails. +`inputResolved` exposed to the host includes the original `content`, so an +accepted steer appears in the current turn and a rejected or unacknowledged +one returns to the draft, once. A turn ending or session exiting before +acknowledgement restores this input. `interactionFailed {method, code}` +reports asynchronous transport failures. Content never enters diagnostics. +Shared application fixture: [`turn-interaction-v1.json`](../../../../rust/fixtures/agents/turn-interaction-v1.json). + ### Session records An agent's CLI keeps its sessions in its own files. `sessionSources` lets diff --git a/shared/plugins/contract/v1/fixtures/agents/native-session.json b/shared/plugins/contract/v1/fixtures/agents/native-session.json index e3358ef7..753047a0 100644 --- a/shared/plugins/contract/v1/fixtures/agents/native-session.json +++ b/shared/plugins/contract/v1/fixtures/agents/native-session.json @@ -2,71 +2,430 @@ "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 prompt with attachments reaches the handler's attachment method with each attachment as Core described it (type, path, name, uri, and mimeType for an image), recorded as a fourth element; a prompt without attachments reaches the plain prompt method. A test backend gives every session of agent plain a handler with only the plain prompt method; for it the SDK's default passes a prompt whose attachments are all file links to that method as the text, then a blank line unless the text is blank, then each attachment's link [@name](uri) on its own line, and ends a turn whose prompt has an image as failed. 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/didSetConfigOption", "params": { "session": "agent-1", "option": "effort", "value": "high" } }, - { "method": "lithe/host/agents/didCancel", "params": { "session": "agent-1", "turn": 1 } }, - { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-1", "turn": 2, "text": "look", "attachments": [{ "type": "image", "path": "/work/orders/shot.png", "name": "shot.png", "uri": "file:///work/orders/shot.png", "mimeType": "image/png" }, { "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }] } }, - { "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" } } + { + "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/didSetConfigOption", + "params": { + "session": "agent-1", + "option": "effort", + "value": "high" + } + }, + { + "method": "lithe/host/agents/didCancel", + "params": { + "session": "agent-1", + "turn": 1 + } + }, + { + "method": "lithe/host/agents/didPrompt", + "params": { + "session": "agent-1", + "turn": 2, + "text": "look", + "attachments": [ + { + "type": "image", + "path": "/work/orders/shot.png", + "name": "shot.png", + "uri": "file:///work/orders/shot.png", + "mimeType": "image/png" + }, + { + "type": "file", + "path": "/work/orders/notes final.md", + "name": "notes final.md", + "uri": "file:///work/orders/notes%20final.md" + } + ] + } + }, + { + "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"], - ["setConfigOption", "effort", "high"], - ["cancel", 1], - ["prompt", 2, "look", [{ "type": "image", "path": "/work/orders/shot.png", "name": "shot.png", "uri": "file:///work/orders/shot.png", "mimeType": "image/png" }, { "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }]], - ["exited", 0] + [ + "start", + { + "session": "agent-1", + "agentID": "example", + "cwd": "/work/orders", + "resume": null + } + ], + [ + "output", + [ + "one", + "two" + ] + ], + [ + "prompt", + 1, + "hello" + ], + [ + "output", + [ + "three" + ] + ], + [ + "decidePermission", + 1, + "permission-1", + "allow" + ], + [ + "setConfigOption", + "effort", + "high" + ], + [ + "cancel", + 1 + ], + [ + "prompt", + 2, + "look", + [ + { + "type": "image", + "path": "/work/orders/shot.png", + "name": "shot.png", + "uri": "file:///work/orders/shot.png", + "mimeType": "image/png" + }, + { + "type": "file", + "path": "/work/orders/notes final.md", + "name": "notes final.md", + "uri": "file:///work/orders/notes%20final.md" + } + ] + ], + [ + "exited", + 0 + ] ], "agent-2": [ - ["start", { "session": "agent-2", "agentID": "example", "cwd": "/work/orders", "resume": "previous-session" }], - ["output", ["other"]], - ["exited", null] + [ + "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 } }, - { "method": "lithe/host/agents/didStart", "params": { "session": "agent-5", "agentID": "plain", "cwd": "/work/orders" } }, - { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-5", "turn": 1, "text": "look", "attachments": [{ "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }, { "type": "file", "path": "/work/orders/src", "name": "src", "uri": "file:///work/orders/src/" }] } }, - { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-5", "turn": 2, "text": "", "attachments": [{ "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }] } }, - { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-5", "turn": 3, "text": "look", "attachments": [{ "type": "image", "path": "/work/orders/shot.png", "name": "shot.png", "uri": "file:///work/orders/shot.png", "mimeType": "image/png" }] } }, - { "method": "lithe/host/agents/didExit", "params": { "session": "agent-5", "exitCode": 0 } } + { + "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 + } + }, + { + "method": "lithe/host/agents/didStart", + "params": { + "session": "agent-5", + "agentID": "plain", + "cwd": "/work/orders" + } + }, + { + "method": "lithe/host/agents/didPrompt", + "params": { + "session": "agent-5", + "turn": 1, + "text": "look", + "attachments": [ + { + "type": "file", + "path": "/work/orders/notes final.md", + "name": "notes final.md", + "uri": "file:///work/orders/notes%20final.md" + }, + { + "type": "file", + "path": "/work/orders/src", + "name": "src", + "uri": "file:///work/orders/src/" + } + ] + } + }, + { + "method": "lithe/host/agents/didPrompt", + "params": { + "session": "agent-5", + "turn": 2, + "text": "", + "attachments": [ + { + "type": "file", + "path": "/work/orders/notes final.md", + "name": "notes final.md", + "uri": "file:///work/orders/notes%20final.md" + } + ] + } + }, + { + "method": "lithe/host/agents/didPrompt", + "params": { + "session": "agent-5", + "turn": 3, + "text": "look", + "attachments": [ + { + "type": "image", + "path": "/work/orders/shot.png", + "name": "shot.png", + "uri": "file:///work/orders/shot.png", + "mimeType": "image/png" + } + ] + } + }, + { + "method": "lithe/host/agents/didExit", + "params": { + "session": "agent-5", + "exitCode": 0 + } + } ], "reports": [ - { "session": "agent-3", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] }, - { "session": "agent-4", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] }, - { "session": "agent-5", "events": [{ "kind": "turnEnded", "turn": 3, "reason": "failed" }] } + { + "session": "agent-3", + "events": [ + { + "kind": "turnEnded", + "turn": 1, + "reason": "failed" + } + ] + }, + { + "session": "agent-4", + "events": [ + { + "kind": "turnEnded", + "turn": 1, + "reason": "failed" + } + ] + }, + { + "session": "agent-5", + "events": [ + { + "kind": "turnEnded", + "turn": 3, + "reason": "failed" + } + ] + } ], "calls": { "agent-4": [ - ["start", { "session": "agent-4", "agentID": "example", "cwd": "/work/orders", "resume": null }], - ["prompt", 1, "fail"], - ["prompt", 2, "hello"], - ["exited", 0] + [ + "start", + { + "session": "agent-4", + "agentID": "example", + "cwd": "/work/orders", + "resume": null + } + ], + [ + "prompt", + 1, + "fail" + ], + [ + "prompt", + 2, + "hello" + ], + [ + "exited", + 0 + ] ], "agent-5": [ - ["start", { "session": "agent-5", "agentID": "plain", "cwd": "/work/orders", "resume": null }], - ["prompt", 1, "look\n\n[@notes final.md](file:///work/orders/notes%20final.md)\n[@src](file:///work/orders/src/)"], - ["prompt", 2, "[@notes final.md](file:///work/orders/notes%20final.md)"], - ["exited", 0] + [ + "start", + { + "session": "agent-5", + "agentID": "plain", + "cwd": "/work/orders", + "resume": null + } + ], + [ + "prompt", + 1, + "look\n\n[@notes final.md](file:///work/orders/notes%20final.md)\n[@src](file:///work/orders/src/)" + ], + [ + "prompt", + 2, + "[@notes final.md](file:///work/orders/notes%20final.md)" + ], + [ + "exited", + 0 + ] ] } }, @@ -74,33 +433,227 @@ { "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\"}"] } } + "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": "configOptions", "configOptions": [{ "id": "effort", "name": "Reasoning", "category": "thoughtLevel", "currentValue": "medium", "options": [{ "value": "medium", "name": "Medium" }, { "value": "high", "name": "High" }] }] }, - { "kind": "message", "turn": 1, "role": "assistant", "messageID": "m1", "text": "Hi", "delta": false } + { + "kind": "session", + "agentSessionID": "cli-session-1", + "model": "example-model" + }, + { + "kind": "configOptions", + "configOptions": [ + { + "id": "effort", + "name": "Reasoning", + "category": "thoughtLevel", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "Medium" + }, + { + "value": "high", + "name": "High" + } + ] + } + ] + }, + { + "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": "configOptions", "configOptions": [{ "id": "effort", "name": "Reasoning", "category": "thoughtLevel", "currentValue": "medium", "options": [{ "value": "medium", "name": "Medium" }, { "value": "high", "name": "High" }] }] }, - { "kind": "message", "turn": 1, "role": "assistant", "messageID": "m1", "text": "Hi", "delta": false } + { + "kind": "session", + "agentSessionID": "cli-session-1", + "model": "example-model" + }, + { + "kind": "configOptions", + "configOptions": [ + { + "id": "effort", + "name": "Reasoning", + "category": "thoughtLevel", + "currentValue": "medium", + "options": [ + { + "value": "medium", + "name": "Medium" + }, + { + "value": "high", + "name": "High" + } + ] + } + ] + }, + { + "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 } } + "params": { + "groupBy": "day", + "sinceMs": 1764460800000, + "utcOffsetSeconds": 28800 + }, + "request": { + "method": "lithe/host/agents/usage", + "params": { + "groupBy": "day", + "sinceMs": 1764460800000, + "utcOffsetSeconds": 28800 + } + } } - ] + ], + "collaboration": { + "notifications": [ + { + "method": "lithe/host/agents/didStart", + "params": { + "session": "agent-6", + "agentID": "example", + "cwd": "/work/orders" + } + }, + { + "method": "lithe/host/agents/didPrompt", + "params": { + "session": "agent-6", + "turn": 1, + "mode": "steer", + "input": "input-1", + "text": "also check refunds" + } + }, + { + "method": "lithe/host/agents/didPrompt", + "params": { + "session": "agent-6", "turn": 1, "mode": "steer", + "input": "input-2", "text": "fail" + } + }, + { + "method": "lithe/host/agents/didAnswerQuestion", + "params": { + "session": "agent-6", + "turn": 1, + "request": "q1", + "answers": [ + { + "question": "choice", + "options": [ + "one" + ], + "text": "" + } + ], + "cancelled": false + } + }, + { + "method": "lithe/host/agents/didExit", + "params": { + "session": "agent-6", + "exitCode": 0 + } + } + ], + "calls": { + "agent-6": [ + [ + "start", + { + "session": "agent-6", + "agentID": "example", + "cwd": "/work/orders", + "resume": null + } + ], + [ + "steer", + 1, + "input-1", + "also check refunds", + [] + ], + ["steer", 1, "input-2", "fail", []], + [ + "answerQuestion", + 1, + "q1", + [ + { + "question": "choice", + "options": [ + "one" + ], + "text": "" + } + ], + false + ], + [ + "exited", + 0 + ] + ] + }, + "reports": [ + { + "session": "agent-6", + "events": [{"kind": "inputResolved", "turn": 1, "input": "input-2", "accepted": false, "code": "internal_error"}] + }, + { + "session": "agent-6", + "events": [ + { + "kind": "questionAnswered", + "turn": 1, + "request": "q1", + "accepted": true + } + ] + } + ] + } } diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 5cca1867..65777f4d 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -167,7 +167,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | 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/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–45 内,见[快捷键导入](domains/keymap-import.md)。 @@ -184,8 +184,9 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | 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`,带提示正文和附件(按 ACP 的方式分成图片和文件链接,各带路径、名称和 URI) | `agents.native` | +| API-45 | `agents/didPrompt` | 提示正文和附件;省略 `mode` 开始新回合(包括队列派发),`mode: "steer"` 与 `input` 向当前 `turn` 补充,插件在 CLI 确认后报告 `inputResolved` | `agents.native` | | API-45 | `agents/didCancel` | 用户取消了当前回合 | `agents.native` | +| API-45 | `agents/didAnswerQuestion` | 用户回答或取消结构化提问,带 `turn`、`request`、`answers`、`cancelled`;SDK 在处理器成功交付后自动报告 `questionAnswered`,失败保留提问供重试 | `agents.native` | | API-45 | `agents/didDecidePermission` | 用户回答了权限请求,带所选的 `option`;后端照此回复 CLI,自己不做决定 | `agents.native` | | API-45 | `agents/didSetConfigOption` | 用户为后端报告的会话设置(模型、推理等级、模式等)选了一个值,带 `option` 和 `value`;后端在 CLI 能接受时应用,再报告一次设置 | `agents.native` | | API-45 | `agents/didExit` | CLI 进程退出,可能带 `exitCode`;会话因后端结束而结束时不发 | `agents.native` | @@ -213,7 +214,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | 内容提供者 | 提供的内容 ≤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/report` | 1–256 个事件;标签和 ID 1 字节到 1 KiB,正文最多 1 MiB;待回答权限请求最多 16 个;提问批次最多 8 个,每批 1–8 题,每题最多 16 选项;问题/回答正文 16 KiB,选项说明 4 KiB | | `agents/didOutput` | 每条最多 64 行或 4 MiB;超过 16 MiB 的单行被丢弃 | | `agents/usage` | 默认 30 天,最多 366 天 | | Agent 原生启动函数 | `timeoutMilliseconds` 1000–120000 ms,默认 15000 | @@ -387,7 +388,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | 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, session settings the user may change): 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/report` | Reports native-session events (session, message, tool call, plan, permission request, usage, rate limits, turn end, notice, settings, interaction capabilities, structured questions and delivery confirmations): 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–45; see [Shortcut import](domains/keymap-import.md). @@ -404,8 +405,9 @@ Notifications the host sends to a backend (the backend answers none), also prefi | 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 and its attachments (images and file links, the way ACP sends them, each with path, name and URI) | `agents.native` | +| API-45 | `agents/didPrompt` | Prompt text and attachments; absent `mode` starts a new turn (including queued dispatch), while `mode: "steer"` and `input` supplement the current `turn`, confirmed by the plugin's `inputResolved` after the CLI responds | `agents.native` | | API-45 | `agents/didCancel` | The user cancelled the active turn | `agents.native` | +| API-45 | `agents/didAnswerQuestion` | The user's answer or cancellation of a structured question, with `turn`, `request`, `answers`, `cancelled`; the SDK reports `questionAnswered` after handler delivery, retaining failed questions for retry | `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/didSetConfigOption` | The user picked a value, `value`, for a session setting the backend reported, `option` (a model, reasoning level, mode, and so on); the backend applies it when the CLI can take it and reports the settings again | `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` | @@ -433,7 +435,7 @@ Notifications the host sends to a backend (the backend answers none), also prefi | 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/report` | 1–256 events; labels and IDs 1 byte to 1 KiB, texts at most 1 MiB; 16 pending permission requests; 8 pending question batches, 1–8 questions per batch, 16 options each; question/answer bodies 16 KiB, option descriptions 4 KiB | | `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 | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 102ebf8d..46253b4a 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -29,6 +29,16 @@ 工具一律来自插件的 `requiresTools`:宿主发现并探测版本,会话运行的始终是用户装好的那份 CLI,插件不能指定路径。会话只在可信的本地工作区运行,远程工作区按 API-40 拒绝。 +### 进行中的输入、队列和问答 + +Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮,`queue` 排到下一轮,`steer` 携带 `expectedTurn` 补充当前轮。插件先根据 CLI 的真实能力报告 `interactionCapabilities`;没有报告的能力默认关闭。立即补充必须等 CLI 确认后报告 `inputResolved`,拒绝时由 Core 把原输入交回宿主草稿,不把一次普通写入当作接收成功。 + +队列是 Core 内存中的 FIFO,最多 8 条、正文与附件元数据合计 4 MiB。成功结束自动推进,失败或停止保留并暂停;用户用 `agents.updateQueue` 移除或继续。`agents.cancel` 先进入 stopping,等真实 `turnEnded`,停止与完成竞争时仍保持队列暂停。宿主直接显示 Core 的 `interactionState`,不在界面维护第二套可用性规则。 + +支持提问的插件用 `questionRequested` 报告普通文本问题及不透明选项 ID,最多 8 批、每批 8 题、每题 16 选项。`agents.respondQuestion` 校验单选、多选、允许的文字及取消操作,然后通过 `didAnswerQuestion` 发给插件。四语 SDK 在处理器真正交付后报告 `questionAnswered`,失败保留请求和用户草稿供重试;插件不要重复确认。秘密输入不得转成普通文本提问。 + +本次扩展仍是 API-45 / `agents` 0 / `litheFunctions` 0。首个支持这些交互的 Core revision 和桌面版本尚未发布;旧 Core 严格拒绝新字段和事件,插件不能仅凭能力版本 0 推断支持。字段、失败分类与日志归属见[正式契约](../../contract/v1/README.md#native-sessions)。四语 SDK 读取[同一组通知用例](../../contract/v1/fixtures/agents/native-session.json),Core 和宿主读取[同一组应用交互用例](../../../../rust/fixtures/agents/turn-interaction-v1.json)。 + ### 会话记录与用量 - 用户逐个 Agent 同意后,Core 才读取 `sessionSources` 声明的目录:只读匹配 `include` 的普通文件,不跟随符号链接;后端的 `scan` 函数把新增的行变成记录,`read` 函数把记录的范围变成标题或消息。 @@ -100,6 +110,35 @@ A plugin can connect an agent command-line tool that the user installed and sign 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. +### Running input, queue and questions + +Core distinguishes default `send` (a new turn only when idle with no queued input), +`queue` (a later turn), and `steer` (the current turn, guarded by `expectedTurn`). +The plugin reports only real CLI support through `interactionCapabilities`, +whose absent flags default to false. It reports `inputResolved` only after +the CLI accepts or rejects steering; refusal returns the retained content +to the host draft. + +Core's in-memory FIFO holds eight inputs and 4 MiB of text plus attachment +metadata. Completed turns advance it; failure and stop pause and retain it. +The user removes or resumes entries with `agents.updateQueue`. Cancel marks +stopping until a real `turnEnded`; a racing completion cannot resume the +queue. Hosts render Core's `interactionState` action flags. + +Plugins supporting questions report `questionRequested` with opaque IDs: +eight pending batches, eight questions per batch, sixteen options per question. +Core validates choices, allowed text and cancellation before +`didAnswerQuestion`. SDKs report `questionAnswered` after handler delivery; +failure retains the question and draft for retry. Handlers must not duplicate +that report. Secret input must never become an ordinary text question. + +This extends API-45 / `agents` 0 / `litheFunctions` 0 without new versions. +The first supporting Core revision and desktop release are not published. +Older Core strictly rejects the new fields and events; capability 0 alone +does not establish support. See the [contract](../../contract/v1/README.md#native-sessions), +the [four-SDK notification fixture](../../contract/v1/fixtures/agents/native-session.json), +and the [shared Core/desktop fixture](../../../../rust/fixtures/agents/turn-interaction-v1.json). + ### 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. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 09204084..79111891 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| 待提交(待合入) | 待提交时登记 PR 作者 | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision、桌面版本待真实提交与发布后回填。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | @@ -215,13 +216,16 @@ | API-45 | `agents/write` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0(事件新增 `configOptions`) | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | +| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类) | 待合入 | 待提交 | | API-45 | `agents/usage` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0(回答新增 `speeds`) | 2026-11-28 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | | API-45 | `agents/didStart`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didOutput`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0(有附件时带 `attachments`) | 2026-11-28 | [#224](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/224) | +| API-45 | `agents/didPrompt`(通知) | 0(`mode: "steer"`、`input` 保留当前轮次身份) | 待合入 | 待提交 | | API-45 | `agents/didCancel`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | +| API-45 | `agents/didAnswerQuestion`(通知) | 0(`turn`、`request`、`answers`、`cancelled`,SDK 确认交付) | 待合入 | 待提交 | | API-45 | `agents/didDecidePermission`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didSetConfigOption`(通知) | 0 | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | | API-45 | `agents/didExit`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index fc7e16a9..846c807e 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -635,18 +635,32 @@ instead of failing), and name a file link in the text with `Link()`, `PromptAttachments` gets a prompt of file links in `Prompt` as `lithe.TextWithLinks(text, attachments)` and fails a turn with an image. +Implement optional `AgentSteerer.Steer(turn, input, text, attachments)` and +`AgentQuestionAnswerer.AnswerQuestion(turn, request, []AgentQuestionAnswer, cancelled)` +for running-turn input and question answers; the existing `AgentSession` +interface is unchanged. Report `interactionCapabilities` only for real CLI +support. Steering preserves the active turn and reports `inputResolved` only +after the CLI responds; handler failure delegates its one terminal diagnostic +to Core with a controlled failure code. Return from `AnswerQuestion` only +after CLI delivery: the SDK automatically reports `questionAnswered` (false +on failure). Do not duplicate that report; retain opaque ID mappings until +delivery succeeds. Bounds and retry rules are in the +[contract](../../contract/v1/README.md#native-sessions). + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, - `didSetConfigOption` and `didExit` then reach it one at a time, in the order + `didAnswerQuestion`, `didSetConfigOption` 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. + failures are logged except steering, diagnosed by Core through + `inputResolved`; question failure also releases its reservation through + `questionAnswered`. 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; +- The `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 diff --git a/shared/plugins/sdk/go/lithe/agents.go b/shared/plugins/sdk/go/lithe/agents.go index 279e7905..f64debf4 100644 --- a/shared/plugins/sdk/go/lithe/agents.go +++ b/shared/plugins/sdk/go/lithe/agents.go @@ -27,6 +27,7 @@ const ( methodAgentsDidStart = "lithe/host/agents/didStart" methodAgentsDidOutput = "lithe/host/agents/didOutput" methodAgentsDidPrompt = "lithe/host/agents/didPrompt" + methodAgentsDidAnswer = "lithe/host/agents/didAnswerQuestion" methodAgentsDidCancel = "lithe/host/agents/didCancel" methodAgentsDidDecide = "lithe/host/agents/didDecidePermission" methodAgentsDidConfig = "lithe/host/agents/didSetConfigOption" @@ -36,7 +37,7 @@ const ( func isAgentNotification(method string) bool { switch method { case methodAgentsDidStart, methodAgentsDidOutput, methodAgentsDidPrompt, - methodAgentsDidCancel, methodAgentsDidDecide, methodAgentsDidConfig, methodAgentsDidExit: + methodAgentsDidAnswer, methodAgentsDidCancel, methodAgentsDidDecide, methodAgentsDidConfig, methodAgentsDidExit: return true } return false @@ -80,6 +81,24 @@ type AgentSession interface { Exited(exitCode *int64) } +// AgentQuestionAnswer is one validated question answer. IDs remain opaque. +type AgentQuestionAnswer struct { + Question string `json:"question"` + Options []string `json:"options"` + Text string `json:"text"` +} + +// AgentSteerer optionally supplements the active turn, without starting another. +// Report inputResolved only after the CLI accepts or refuses the input. +type AgentSteerer interface { + Steer(turn uint64, input, text string, attachments []AgentAttachment) error +} + +// AgentQuestionAnswerer optionally answers or cancels a structured question. +type AgentQuestionAnswerer interface { + AnswerQuestion(turn uint64, request string, answers []AgentQuestionAnswer, cancelled bool) error +} + // AgentAttachment is one attachment of a prompt, the way an ACP client sends // prompt content: an image of a type the agent declared in // native.imageTypes, or a link to any other file or a directory, like ACP's @@ -224,15 +243,18 @@ func (b *Backend) OnAgentSessions(start AgentSessionStarter) { // agentNotice is one notification for a session's worker. type agentNotice struct { - method string - lines []string - turn uint64 - text string - attachments []AgentAttachment - permission string - option string - value string - exitCode *int64 + mode, input, request string + answers []AgentQuestionAnswer + cancelled bool + method string + lines []string + turn uint64 + text string + attachments []AgentAttachment + permission string + option string + value string + exitCode *int64 } // agentQueue is an unbounded queue of one session's notifications, so the @@ -331,6 +353,26 @@ func (b *Backend) routeAgentNotification(method string, params map[string]any) { notice := agentNotice{method: method} notice.turn = unsigned(params["turn"]) notice.text, _ = params["text"].(string) + notice.mode, _ = params["mode"].(string) + notice.input, _ = params["input"].(string) + notice.request, _ = params["request"].(string) + notice.cancelled, _ = params["cancelled"].(bool) + if answers, ok := params["answers"].([]any); ok { + for _, raw := range answers { + fields, _ := raw.(map[string]any) + answer := AgentQuestionAnswer{} + answer.Question, _ = fields["question"].(string) + answer.Text, _ = fields["text"].(string) + if options, ok := fields["options"].([]any); ok { + for _, raw := range options { + if option, ok := raw.(string); ok { + answer.Options = append(answer.Options, option) + } + } + } + notice.answers = append(notice.answers, answer) + } + } notice.permission, _ = params["permission"].(string) notice.option, _ = params["option"].(string) notice.value, _ = params["value"].(string) @@ -402,13 +444,20 @@ func runAgentSession(s *shared, starter AgentSessionStarter, start AgentSessionS return } err := errNoHandler + steering := notice.method == methodAgentsDidPrompt && notice.mode == "steer" if handler != nil { err = deliverAgentNotice(handler, notice) - if err != nil { + if err != nil && !steering { logAgentFailure(s, err) } } - if err != nil && notice.method == methodAgentsDidPrompt { + if notice.method == methodAgentsDidAnswer { + reportAgentInteraction(s, handle, map[string]any{"kind": "questionAnswered", "turn": notice.turn, "request": notice.request, "accepted": err == nil}) + } + if err != nil && steering { + reportAgentInteraction(s, handle, map[string]any{"kind": "inputResolved", "turn": notice.turn, "input": notice.input, "accepted": false, "code": failureKind(err)}) + } + if err != nil && notice.method == methodAgentsDidPrompt && notice.mode != "steer" { // 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"}}) @@ -416,6 +465,19 @@ func runAgentSession(s *shared, starter AgentSessionStarter, start AgentSessionS } } +func reportAgentInteraction(s *shared, handle *AgentSessionHandle, event map[string]any) { + if err := handle.Report([]any{event}); err != nil { + var sdk *SdkError + if errors.As(err, &sdk) { + switch sdk.Code() { + case "plugin.host.notFound", "plugin.host.preconditionFailed", "sdk.session.closed": + return + } + } + s.failed("notification", "agent_interaction_report_failed") + } +} + func startAgentSession(starter AgentSessionStarter, start AgentSessionStart, handle *AgentSessionHandle) (handler AgentSession, err error) { defer func() { if recover() != nil { @@ -441,6 +503,12 @@ func deliverAgentNotice(handler AgentSession, notice agentNotice) (err error) { case methodAgentsDidOutput: return handler.Output(notice.lines) case methodAgentsDidPrompt: + if notice.mode == "steer" { + if handler, ok := handler.(AgentSteerer); ok { + return handler.Steer(notice.turn, notice.input, notice.text, notice.attachments) + } + return errors.New("agent_steering_unsupported") + } if len(notice.attachments) == 0 { return handler.Prompt(notice.turn, notice.text) } @@ -451,6 +519,11 @@ func deliverAgentNotice(handler AgentSession, notice agentNotice) (err error) { return errNoImages } return handler.Prompt(notice.turn, TextWithLinks(notice.text, notice.attachments)) + case methodAgentsDidAnswer: + if handler, ok := handler.(AgentQuestionAnswerer); ok { + return handler.AnswerQuestion(notice.turn, notice.request, notice.answers, notice.cancelled) + } + return errors.New("agent_questions_unsupported") case methodAgentsDidCancel: return handler.Cancel(notice.turn) case methodAgentsDidDecide: diff --git a/shared/plugins/sdk/go/lithe/agents_test.go b/shared/plugins/sdk/go/lithe/agents_test.go index e15693f4..dad44075 100644 --- a/shared/plugins/sdk/go/lithe/agents_test.go +++ b/shared/plugins/sdk/go/lithe/agents_test.go @@ -87,6 +87,19 @@ func (r *recorder) PromptAttachments(turn uint64, text string, attachments []lit // gets: the SDK's default turns file links into prompt text. type plain struct{ lithe.AgentSession } +func (r *recorder) Steer(turn uint64, input, text string, attachments []lithe.AgentAttachment) error { + r.record("steer", turn, input, text, []any{}) + if text == "fail" { + return errors.New("steer_failed") + } + return nil +} + +func (r *recorder) AnswerQuestion(turn uint64, request string, answers []lithe.AgentQuestionAnswer, cancelled bool) error { + r.record("answerQuestion", turn, request, answers, cancelled) + return nil +} + func (r *recorder) Cancel(turn uint64) error { r.record("cancel", turn) return nil @@ -292,3 +305,31 @@ func TestAgentNotificationsAreRoutedOnlyThroughAgentSessions(t *testing.T) { } eq(t, failureCodes(t, host), `["agent_unhandled"]`) } + +func TestCollaborationRoutesSteeringAndConfirmsQuestionDelivery(t *testing.T) { + fixture := agentsFixture(t) + part := at(fixture, "collaboration") + expected := at(part, "calls") + calls := make(chan []any, 64) + host := startHost(t, recordingBackend(t, calls)) + host.initialize([]any{0}) + sendAll(host, at(part, "notifications")) + for _, expectedReport := range at(part, "reports").([]any) { + for { + report := host.next() + if report["method"] != "lithe/host/agents/report" { + continue + } + eq(t, report["params"], encode(t, expectedReport)) + host.reply(report, map[string]any{}) + break + } + } + eq(t, callsBySession(t, calls, callCount(expected)), encode(t, expected)) + if code := host.close(); code != 1 { + t.Errorf("exit code %d", code) + } + if failures := failureCodes(t, host); len(failures) != 0 { + t.Fatalf("steering failure must be diagnosed by Core only: %v", failures) + } +} diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index de76b97e..de82763e 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -603,18 +603,31 @@ the CLI reads it with its own tools. The default passes a prompt of file links to `prompt` as `AgentAttachment.textWithLinks(text, attachments)` and fails a turn with an image. +Override default `steer(turn, input, text, List)` and +`answerQuestion(turn, request, List, cancelled)` for +running-turn input and question answers. Defaults throw unsupported errors. +Report `interactionCapabilities` only for real CLI support. Steering preserves +the active turn and reports `inputResolved` after the CLI responds; handler +failure delegates the one terminal diagnostic to Core using a controlled +failure code. Return from `answerQuestion` only after CLI delivery: the SDK +automatically reports `questionAnswered` (false on failure). Do not duplicate +it; retain opaque ID mappings until delivery succeeds. Bounds and retries are +in the [contract](../../contract/v1/README.md#native-sessions). + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, - `didSetConfigOption` and `didExit` then reach it one at a time, in the order + `didAnswerQuestion`, `didSetConfigOption` 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. + failures are logged except steering, diagnosed by Core through + `inputResolved`; question failure also releases its reservation through + `questionAnswered`. 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; +- The `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 diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentQuestionAnswer.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentQuestionAnswer.java new file mode 100644 index 00000000..53f98fc7 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentQuestionAnswer.java @@ -0,0 +1,20 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** One validated answer; question and option IDs remain opaque. */ +public final class AgentQuestionAnswer { + private final String question; + private final List options; + private final String text; + public AgentQuestionAnswer(String question, List options, String text) { + this.question = question; + this.options = Collections.unmodifiableList(new ArrayList<>(options)); + this.text = text; + } + public String question() { return question; } + public List options() { return options; } + public String text() { return text; } +} 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 index c232aa6f..0b001621 100644 --- 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 @@ -36,6 +36,15 @@ default void promptAttachments(long turn, String text, List att prompt(turn, AgentAttachment.textWithLinks(text, attachments)); } + /** Supplements the active turn; report inputResolved after the CLI acknowledges it. */ + default void steer(long turn, String input, String text, List attachments) throws Exception { + throw new UnsupportedOperationException("agent_steering_unsupported"); + } + /** Answers or cancels a structured question reported by this session. */ + default void answerQuestion(long turn, String request, List answers, boolean cancelled) throws Exception { + throw new UnsupportedOperationException("agent_questions_unsupported"); + } + /** The user cancelled {@code turn}. Does nothing unless overridden. */ default void cancel(long turn) throws Exception {} 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 index 5ca3d6d5..66065ca2 100644 --- 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 @@ -28,7 +28,7 @@ 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_ANSWER_QUESTION, Protocol.HOST_AGENTS_DID_CANCEL, Protocol.HOST_AGENTS_DID_DECIDE_PERMISSION, Protocol.HOST_AGENTS_DID_SET_CONFIG_OPTION, Protocol.HOST_AGENTS_DID_EXIT))); private static final String OPERATION = "notification"; @@ -126,32 +126,71 @@ private void run(Backend.AgentSessionStarter starter, AgentSessionStart start, W return; } boolean handled = false; + boolean steering = notice.method.equals(Protocol.HOST_AGENTS_DID_PROMPT) && notice.mode.equals("steer"); + String failureCode = "cancelled"; if (handler != null) { try { deliver(handler, notice); handled = true; } catch (Throwable error) { - failed(error); + Throwable cause = Backend.unwrap(error); + failureCode = cause instanceof CancelledException ? "cancelled" + : cause instanceof PluginError ? "plugin_error" : "internal_error"; + if (!steering) failed(error); } } - if (!handled && notice.method.equals(Protocol.HOST_AGENTS_DID_PROMPT)) { + if (notice.method.equals(Protocol.HOST_AGENTS_DID_ANSWER_QUESTION)) { + Map event = new LinkedHashMap<>(); + event.put("kind", "questionAnswered"); event.put("turn", notice.turn); + event.put("request", notice.request); event.put("accepted", handled); + reportInteraction(handle, event); + } + if (!handled && steering) { + Map event = new LinkedHashMap<>(); + event.put("kind", "inputResolved"); event.put("turn", notice.turn); + event.put("input", notice.input); event.put("accepted", false); + event.put("code", failureCode); + reportInteraction(handle, event); + } + if (!handled && notice.method.equals(Protocol.HOST_AGENTS_DID_PROMPT) && !notice.mode.equals("steer")) { endTurn(handle, notice.turn); } } } + private void reportInteraction(AgentSessionHandle handle, Map event) { + try { + handle.report(Collections.singletonList(event)).join(); + } catch (RuntimeException error) { + Throwable cause = Backend.unwrap(error); + if (cause instanceof PluginSdkError) { + String code = ((PluginSdkError) cause).code(); + if (code.equals("plugin.host.notFound") || code.equals("plugin.host.preconditionFailed") + || code.equals("sdk.session.closed")) return; + } + failed(cause); + } + } + 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: + if (notice.mode.equals("steer")) { + handler.steer(notice.turn, notice.input, notice.text, notice.attachments); + return; + } if (notice.attachments.isEmpty()) { handler.prompt(notice.turn, notice.text); } else { handler.promptAttachments(notice.turn, notice.text, notice.attachments); } return; + case Protocol.HOST_AGENTS_DID_ANSWER_QUESTION: + handler.answerQuestion(notice.turn, notice.request, notice.answers, notice.cancelled); + return; case Protocol.HOST_AGENTS_DID_CANCEL: handler.cancel(notice.turn); return; @@ -211,10 +250,27 @@ private static Notice notice(String method, Map params) { } Object turn = params.get("turn"); Object exit = params.get("exitCode"); - return new Notice(method, Collections.unmodifiableList(lines), + List answers = new ArrayList<>(); + Object rawAnswers = params.get("answers"); + if (rawAnswers instanceof List) { + for (Object rawAnswer : (List)rawAnswers) { + if (!(rawAnswer instanceof Map)) continue; + @SuppressWarnings("unchecked") Map fields = (Map)rawAnswer; + List options = new ArrayList<>(); + if (fields.get("options") instanceof List) { + for (Object option : (List)fields.get("options")) if (option instanceof String) options.add((String)option); + } + answers.add(new AgentQuestionAnswer(string(fields,"question"), options, string(fields,"text"))); + } + } + Notice result = new Notice(method, Collections.unmodifiableList(lines), turn instanceof Long && (Long) turn >= 0 ? (Long) turn : 0L, string(params, "text"), Collections.unmodifiableList(attachments), string(params, "permission"), string(params, "option"), string(params, "value"), exit instanceof Long ? (Long) exit : null); + result.mode = string(params,"mode"); result.input = string(params,"input"); + result.request = string(params,"request"); result.answers = Collections.unmodifiableList(answers); + result.cancelled = Boolean.TRUE.equals(params.get("cancelled")); + return result; } private static String string(Map params, String key) { @@ -227,6 +283,9 @@ private static final class Notice { static final Notice CLOSED = new Notice("", Collections.emptyList(), 0, "", Collections.emptyList(), "", "", "", null); + String mode = "", input = "", request = ""; + List answers = Collections.emptyList(); + boolean cancelled; final String method; final List lines; final long turn; 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 c8cf7032..828768c4 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 @@ -131,6 +131,7 @@ public final class Protocol { 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_ANSWER_QUESTION = "lithe/host/agents/didAnswerQuestion"; 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_SET_CONFIG_OPTION = "lithe/host/agents/didSetConfigOption"; 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 index b84bf16e..9bc809c5 100644 --- 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 @@ -109,6 +109,19 @@ public void promptAttachments(long turn, String text, List atta record(id, "prompt", turn, text, shown); } + @Override + public void steer(long turn, String input, String text, List attachments) { + record(id, "steer", turn, input, text, Collections.emptyList()); + if (text.equals("fail")) throw new IllegalStateException("steer_failed"); + } + + @Override + public void answerQuestion(long turn, String request, List answers, boolean cancelled) { + List values = new ArrayList<>(); + for (AgentQuestionAnswer answer : answers) { values.add(map("question",answer.question(),"options",answer.options(),"text",answer.text())); } + record(id, "answerQuestion", turn, request, values, cancelled); + } + @Override public void cancel(long turn) { record(id, "cancel", turn); @@ -299,6 +312,26 @@ void agentHostMethodsSendTheFixtureRequests() { assertEquals(1, host.close()); } + @Test + void collaborationRoutesSteeringAndConfirmsQuestionDelivery() { + Recorder recorder = new Recorder(); + TestHost host = session(recorder.backend); + Map collaboration = object(FIXTURE.get("collaboration")); + sendAll(host, collaboration.get("notifications")); + Set answered = new HashSet<>(); + for (Object expected : list(collaboration.get("reports"))) { + Map report = host.waitFor( + message -> "lithe/host/agents/report".equals(message.get("method")) + && !answered.contains(message.get("id")), "interaction delivery"); + answered.add(report.get("id")); + assertEquals(expected, report.get("params")); + host.send(map("id", report.get("id"), "result", map())); + } + assertEquals(collaboration.get("calls"), recorder.bySession(count(collaboration.get("calls")))); + assertEquals(1, host.close()); + assertEquals(Collections.emptyList(), failureCodes(host)); + } + @Test void agentNotificationsAreRoutedOnlyThroughAgentSessions() { Backend backend = Backend.create("agents-test", null); diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 59b410ba..f7ecbc0f 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -617,18 +617,31 @@ failing), and name a file link in the text with `attachmentLink(attachment)`, `promptAttachments` gets a prompt of file links in `prompt` as `textWithLinks(text, attachments)` and fails a turn with an image. +Optional `steer(turn, input, text, attachments)` and +`answerQuestion(turn, request, answers, cancelled)` handle running-turn input +and question answers. Each answer is `{question, options, text}`. Report +`interactionCapabilities` only for real CLI support. Steering preserves the +active turn and reports `inputResolved` after the CLI responds; a handler +failure reports a controlled failure code and delegates the one terminal +diagnostic to Core. Resolve `answerQuestion` only after CLI delivery: the SDK +automatically reports `questionAnswered` (false on failure). Do not duplicate +it; retain opaque ID mappings until delivery succeeds. See the +[contract](../../contract/v1/README.md#native-sessions) for bounds and retries. + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, - `didSetConfigOption` and `didExit` then reach it one at a time, in the order + `didAnswerQuestion`, `didSetConfigOption` 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. + failures are logged except steering, diagnosed by Core through + `inputResolved`; question failure also releases its reservation through + `questionAnswered`. 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; +- The `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 diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index e22f6b38..972ebb91 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -655,19 +655,32 @@ class Backend { if (this.#agentStarter) failed('agent_session_unknown'); return; } - const prompt = method === AGENT_NOTIFICATIONS.didPrompt; + const prompt = method === AGENT_NOTIFICATIONS.didPrompt && params.mode !== 'steer'; + const steering = method === AGENT_NOTIFICATIONS.didPrompt && params.mode === 'steer'; const turn = Number.isSafeInteger(params.turn) ? params.turn : 0; entry.tail = entry.tail.then(async () => { const { handler } = entry; let ok = handler !== null; + let code = 'cancelled'; if (ok) { try { await deliverAgentNotification(handler, method, params, turn); } catch (error) { ok = false; - failed(failureKind(error)); + code = failureKind(error); + if (!steering) failed(code); } } + if (method === AGENT_NOTIFICATIONS.didAnswerQuestion) { + await this.host.agents.report(session, [{kind: 'questionAnswered', turn, request: params.request, accepted: ok}]).catch(error => { + if (!['plugin.host.notFound', 'plugin.host.preconditionFailed', 'sdk.session.closed'].includes(error?.code)) failed('agent_interaction_report_failed'); + }); + } + if (!ok && steering) { + await this.host.agents.report(session, [{kind: 'inputResolved', turn, input: params.input, accepted: false, code}]).catch(error => { + if (!['plugin.host.notFound', 'plugin.host.preconditionFailed', 'sdk.session.closed'].includes(error?.code)) failed('agent_interaction_report_failed'); + }); + } 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. @@ -1165,6 +1178,10 @@ async function deliverAgentNotification(handler, method, params, turn) { const attachments = Array.isArray(params.attachments) ? params.attachments.map((fields) => promptAttachment(fields, text)) : []; + if (params.mode === 'steer') { + if (typeof handler.steer !== 'function') throw new Error('agent_steering_unsupported'); + return handler.steer(turn, text(params.input), text(params.text), attachments); + } if (attachments.length === 0) return handler.prompt(turn, text(params.text)); if (typeof handler.promptAttachments === 'function') { return handler.promptAttachments(turn, text(params.text), attachments); @@ -1174,6 +1191,9 @@ async function deliverAgentNotification(handler, method, params, turn) { } return handler.prompt(turn, textWithLinks(text(params.text), attachments)); } + case AGENT_NOTIFICATIONS.didAnswerQuestion: + if (typeof handler.answerQuestion !== 'function') throw new Error('agent_questions_unsupported'); + return handler.answerQuestion(turn, text(params.request), params.answers ?? [], params.cancelled === true); case AGENT_NOTIFICATIONS.didCancel: return handler.cancel?.(turn); case AGENT_NOTIFICATIONS.didDecidePermission: diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index d8078f4b..24c93f1c 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -980,6 +980,8 @@ export function textWithLinks(text: string, attachments: AgentAttachment[]): str * one before; a rejected `prompt` or `promptAttachments` ends its turn as * failed. */ +export interface AgentQuestionAnswer { question: string; options: string[]; text: string; } + export interface AgentSession { /** Lines the CLI wrote to standard output, without line breaks. */ output(lines: string[]): unknown; @@ -994,6 +996,10 @@ export interface AgentSession { * turn. */ promptAttachments?(turn: number, text: string, attachments: AgentAttachment[]): unknown; + /** Supplements the active turn; report inputResolved after the CLI acknowledges it. */ + steer?(turn: number, input: string, text: string, attachments: AgentAttachment[]): unknown; + /** Answers or cancels a structured question. */ + answerQuestion?(turn: number, request: string, answers: AgentQuestionAnswer[], cancelled: boolean): unknown; /** The user cancelled `turn`. */ cancel?(turn: number): unknown; /** The user answered permission request `permission` with `option`. */ diff --git a/shared/plugins/sdk/node/src/protocol.mjs b/shared/plugins/sdk/node/src/protocol.mjs index 760e4d55..ed0aa690 100644 --- a/shared/plugins/sdk/node/src/protocol.mjs +++ b/shared/plugins/sdk/node/src/protocol.mjs @@ -124,6 +124,7 @@ export const AGENT_NOTIFICATIONS = Object.freeze({ didStart: 'lithe/host/agents/didStart', didOutput: 'lithe/host/agents/didOutput', didPrompt: 'lithe/host/agents/didPrompt', + didAnswerQuestion: 'lithe/host/agents/didAnswerQuestion', didCancel: 'lithe/host/agents/didCancel', didDecidePermission: 'lithe/host/agents/didDecidePermission', didSetConfigOption: 'lithe/host/agents/didSetConfigOption', diff --git a/shared/plugins/sdk/node/test/agents.test.mjs b/shared/plugins/sdk/node/test/agents.test.mjs index 1cbb388a..b2b2d7bb 100644 --- a/shared/plugins/sdk/node/test/agents.test.mjs +++ b/shared/plugins/sdk/node/test/agents.test.mjs @@ -44,6 +44,11 @@ function recordingBackend() { promptAttachments(turn, text, attachments) { record('prompt', turn, text, attachments); }, + steer(turn, input, text, attachments) { + record('steer',turn,input,text,attachments); + if (text === 'fail') throw new Error('steer_failed'); + }, + answerQuestion(turn, request, answers, cancelled) { record('answerQuestion',turn,request,answers,cancelled); }, cancel(turn) { record('cancel', turn); }, @@ -168,3 +173,24 @@ test('agent notifications are routed only through agent sessions', async () => { assert.equal(await host.close(), 1); assert.deepEqual(failureCodes(host), ['agent_unhandled']); }); + +test('collaboration routes steering and confirms question delivery', async () => { + const { backend, bySession } = recordingBackend(); + const host = new TestHost(backend); + await host.initialize(); + const part = fixture.collaboration; + sendAll(host, part.notifications); + const answered = new Set(); + for (const expected of part.reports) { + const report = await host.waitFor( + message => message.method === 'lithe/host/agents/report' && !answered.has(message.id), + 'interaction delivery', + ); + answered.add(report.id); + assert.deepEqual(report.params, expected); + host.send({ id: report.id, result: {} }); + } + assert.deepEqual(await bySession(count(part.calls)), part.calls); + assert.equal(await host.close(), 1); + assert.deepEqual(failureCodes(host), []); +}); diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index a2bfb349..5b254025 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -726,18 +726,32 @@ a file link in the text with `link()`, `[@name](file:///…)`, so the CLI reads with its own tools. The default passes a prompt of file links to `prompt` as `text_with_links(text, attachments)` and fails a turn with an image. +Running-turn input reaches `steer(turn, input, text, attachments)`; question +answers reach `answer_question(turn, request, Vec, cancelled)`. +Their defaults return unsupported errors. Report `interactionCapabilities` +with `steering` / `questions` only when the CLI supports them. A steering +handler must preserve the active turn and report `inputResolved` after the +CLI responds, even if it finishes asynchronously. Handler failure is reported +with a controlled failure code and diagnosed once by Core. Answer handlers +return success only after delivery to the CLI; the SDK automatically reports +`questionAnswered` (false on failure), so do not report it yourself. IDs remain +opaque; keep CLI request mappings until successful delivery. See the +[contract](../../contract/v1/README.md#native-sessions) for bounds and retry rules. + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, - `didSetConfigOption` and `didExit` then reach it one at a time, in the order + `didAnswerQuestion`, `didSetConfigOption` 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. + failures are logged except steering, whose terminal diagnostic belongs to + Core through `inputResolved`; question failures also release their reservation + through `questionAnswered`. 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; +- The `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 diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs index 95d5bbac..7cc75790 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs @@ -84,12 +84,28 @@ pub fn text_with_links(text: &str, attachments: &[AgentAttachment]) -> String { } } +/// A validated answer to one question; option IDs stay opaque to the SDK. +#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +pub struct AgentQuestionAnswer { + /// Opaque ID of the question being answered. + pub question: String, + /// Opaque IDs of the selected options, in user-selected order. + #[serde(default)] + pub options: Vec, + /// User-authored text when the question permits it. + #[serde(default)] + pub text: String, +} + /// 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. +/// `turnEnded` with reason `failed`. A failing [`steer`](Self::steer) restores +/// the input through `inputResolved`; [`answer_question`](Self::answer_question) +/// reports delivery so Core can retain a failed answer for retry. Other +/// failures are logged without ending the turn. pub trait AgentSession: Send { /// Lines the CLI wrote to standard output, without line breaks. fn output(&mut self, lines: Vec) -> Result<(), FunctionError>; @@ -113,6 +129,27 @@ pub trait AgentSession: Send { let text = text_with_links(&text, &attachments); self.prompt(turn, text) } + /// Supplements the active turn. Report `inputResolved` only after the CLI + /// accepts or refuses it; this must never start another turn. + fn steer( + &mut self, + _turn: u64, + _input: String, + _text: String, + _attachments: Vec, + ) -> Result<(), FunctionError> { + Err(FunctionError::internal("agent_steering_unsupported")) + } + /// Answers or cancels a structured question previously reported by this session. + fn answer_question( + &mut self, + _turn: u64, + _request: String, + _answers: Vec, + _cancelled: bool, + ) -> Result<(), FunctionError> { + Err(FunctionError::internal("agent_questions_unsupported")) + } /// The user cancelled `turn`. fn cancel(&mut self, _turn: u64) -> Result<(), FunctionError> { Ok(()) @@ -216,6 +253,8 @@ pub(crate) type AgentFactory = Arc< enum Notice { Output(Vec), Prompt(u64, String, Vec), + Steer(u64, String, String, Vec), + Answer(u64, String, Vec, bool), Cancel(u64), Decide(u64, String, String), Configure(String, String), @@ -236,6 +275,7 @@ pub(crate) fn is_agent_notification(method: &str) -> bool { methods::AGENTS_DID_OUTPUT, methods::AGENTS_DID_PROMPT, methods::AGENTS_DID_CANCEL, + methods::AGENTS_DID_ANSWER_QUESTION, methods::AGENTS_DID_DECIDE_PERMISSION, methods::AGENTS_DID_SET_CONFIG_OPTION, methods::AGENTS_DID_EXIT, @@ -287,10 +327,8 @@ impl AgentWorkers { .map(|lines| lines.iter().map(text).collect()) .unwrap_or_default(), ), - methods::AGENTS_DID_PROMPT => Notice::Prompt( - turn(¶ms["turn"]), - text(¶ms["text"]), - params["attachments"] + methods::AGENTS_DID_PROMPT => { + let attachments = params["attachments"] .as_array() .map(|attachments| { attachments @@ -304,7 +342,23 @@ impl AgentWorkers { }) .collect() }) - .unwrap_or_default(), + .unwrap_or_default(); + if params["mode"] == "steer" { + Notice::Steer( + turn(¶ms["turn"]), + text(¶ms["input"]), + text(¶ms["text"]), + attachments, + ) + } else { + Notice::Prompt(turn(¶ms["turn"]), text(¶ms["text"]), attachments) + } + } + methods::AGENTS_DID_ANSWER_QUESTION => Notice::Answer( + turn(¶ms["turn"]), + text(¶ms["request"]), + serde_json::from_value(params["answers"].clone()).unwrap_or_default(), + params["cancelled"] == true, ), methods::AGENTS_DID_CANCEL => Notice::Cancel(turn(¶ms["turn"])), methods::AGENTS_DID_DECIDE_PERMISSION => Notice::Decide( @@ -363,20 +417,35 @@ fn run( Notice::Prompt(turn, ..) => Some(*turn), _ => None, }; + let answering = match ¬ice { + Notice::Answer(turn, request, ..) => Some((*turn, request.clone())), + _ => None, + }; + let steering = match ¬ice { + Notice::Steer(turn, input, ..) => Some((*turn, input.clone())), + _ => 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 mut failure_code = "cancelled"; let failed = match outcome { Ok(Ok(())) => false, Ok(Err(FunctionError::Cancelled)) => true, Ok(Err(error)) => { - shared.failed("notification", failure_kind(&error)); + failure_code = failure_kind(&error); + if steering.is_none() { + shared.failed("notification", failure_code); + } true } Err(_) => { - shared.failed("notification", "panic"); + failure_code = "panic"; + if steering.is_none() { + shared.failed("notification", failure_code); + } true } }; @@ -386,12 +455,39 @@ fn run( let _ = handle.report(&[json!({ "kind": "turnEnded", "turn": turn, "reason": "failed" })]); } + if let Some((turn, request)) = answering { + report_interaction( + shared, + &handle, + json!({"kind":"questionAnswered", "turn":turn, "request":request, "accepted":!failed}), + ); + } + if let (true, Some((turn, input))) = (failed, steering) { + report_interaction( + shared, + &handle, + json!({"kind":"inputResolved","turn":turn,"input":input,"accepted":false,"code":failure_code}), + ); + } if exit { break; } } } +/// A withdrawn request or ended session may refuse its confirmation; other +/// errors mean the SDK could not report the interaction's delivery result. +fn report_interaction(shared: &Shared, handle: &AgentSessionHandle, event: Value) { + if let Err(error) = handle.report(&[event]) { + if !matches!( + error.code(), + "plugin.host.notFound" | "plugin.host.preconditionFailed" | "sdk.session.closed" + ) { + shared.failed("notification", "agent_interaction_report_failed"); + } + } +} + fn deliver(handler: &mut dyn AgentSession, notice: Notice) -> Result<(), FunctionError> { match notice { Notice::Output(lines) => handler.output(lines), @@ -401,6 +497,12 @@ fn deliver(handler: &mut dyn AgentSession, notice: Notice) -> Result<(), Functio Notice::Prompt(turn, text, attachments) => { handler.prompt_attachments(turn, text, attachments) } + Notice::Steer(turn, input, text, attachments) => { + handler.steer(turn, input, text, attachments) + } + Notice::Answer(turn, request, answers, cancelled) => { + handler.answer_question(turn, request, answers, cancelled) + } Notice::Cancel(turn) => handler.cancel(turn), Notice::Decide(turn, permission, option) => { handler.decide_permission(turn, permission, option) diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index c11c4f1e..a789092a 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -51,7 +51,8 @@ pub mod toolchains; pub mod view; pub use agents::{ - text_with_links, AgentAttachment, AgentSession, AgentSessionHandle, AgentSessionStart, Agents, + text_with_links, AgentAttachment, AgentQuestionAnswer, AgentSession, AgentSessionHandle, + AgentSessionStart, Agents, }; pub use backend::{ Backend, BackendHandle, Caller, Cancellation, Context, Initialize, KeymapImportRequest, diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index f887012a..bd369d35 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -111,6 +111,7 @@ pub(crate) mod methods { 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_ANSWER_QUESTION: &str = "lithe/host/agents/didAnswerQuestion"; 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_SET_CONFIG_OPTION: &str = "lithe/host/agents/didSetConfigOption"; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs index e403a5d7..232a8538 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs @@ -5,7 +5,8 @@ mod common; use common::{Host, WAIT}; use lithe_plugin_sdk::{ - AgentAttachment, AgentSession, AgentSessionHandle, AgentSessionStart, Backend, FunctionError, + AgentAttachment, AgentQuestionAnswer, AgentSession, AgentSessionHandle, AgentSessionStart, + Backend, FunctionError, }; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -86,6 +87,37 @@ impl AgentSession for Recorder { Ok(()) } + fn steer( + &mut self, + turn: u64, + input: String, + text: String, + attachments: Vec, + ) -> Result<(), FunctionError> { + self.record(json!([ + "steer", + turn, + input, + text, + attachments.iter().map(shown).collect::>() + ])); + if text == "fail" { + return Err(FunctionError::internal("steer_failed")); + } + Ok(()) + } + + fn answer_question( + &mut self, + turn: u64, + request: String, + answers: Vec, + cancelled: bool, + ) -> Result<(), FunctionError> { + self.record(json!(["answerQuestion", turn, request, answers, cancelled])); + Ok(()) + } + fn cancel(&mut self, turn: u64) -> Result<(), FunctionError> { self.record(json!(["cancel", turn])); Ok(()) @@ -352,3 +384,33 @@ fn agent_notifications_are_routed_only_through_agent_sessions() { assert_eq!(code, 1); assert_eq!(failure_codes(&frames), ["agent_unhandled"]); } + +#[test] +fn collaboration_routes_steering_and_confirms_question_delivery() { + let f = fixture(); + let case = &f["collaboration"]; + let (sender, receiver) = mpsc::channel(); + let mut host = started(recording_backend(sender)); + send_all(&mut host, &case["notifications"]); + let mut frames = Vec::new(); + for expected_report in case["reports"].as_array().unwrap() { + let report = loop { + let frame = host.next(); + if frame["method"] == "lithe/host/agents/report" { + break frame; + } + frames.push(frame); + }; + assert_eq!(&report["params"], expected_report); + host.send(json!({ "jsonrpc": "2.0", "id": report["id"], "result": {} })); + } + let expected = expected_calls(&case["calls"]); + assert_eq!(calls_by_session(&receiver, count(&expected)), expected); + let (code, remaining) = host.finish(); + frames.extend(remaining); + assert_eq!(code, 1); + assert!( + failure_codes(&frames).is_empty(), + "steering failure belongs to Core's inputResolved handler" + ); +} From a38b3fc3867a85cb9aa27fb53bcd0541708db497 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 00:51:53 +0800 Subject: [PATCH 2/3] docs(agents): register interaction protocol PR and support revision --- shared/plugins/reference/api-catalog.md | 4 ++-- shared/plugins/reference/protocol-changelog.md | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 65777f4d..a445755d 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -185,7 +185,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | 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` | 提示正文和附件;省略 `mode` 开始新回合(包括队列派发),`mode: "steer"` 与 `input` 向当前 `turn` 补充,插件在 CLI 确认后报告 `inputResolved` | `agents.native` | -| API-45 | `agents/didCancel` | 用户取消了当前回合 | `agents.native` | +| API-45 | `agents/didCancel` | 用户停止当前回合并暂停剩余队列;Core 等待工具报告真实结束,主动取消不记错误终态 | `agents.native` | | API-45 | `agents/didAnswerQuestion` | 用户回答或取消结构化提问,带 `turn`、`request`、`answers`、`cancelled`;SDK 在处理器成功交付后自动报告 `questionAnswered`,失败保留提问供重试 | `agents.native` | | API-45 | `agents/didDecidePermission` | 用户回答了权限请求,带所选的 `option`;后端照此回复 CLI,自己不做决定 | `agents.native` | | API-45 | `agents/didSetConfigOption` | 用户为后端报告的会话设置(模型、推理等级、模式等)选了一个值,带 `option` 和 `value`;后端在 CLI 能接受时应用,再报告一次设置 | `agents.native` | @@ -406,7 +406,7 @@ Notifications the host sends to a backend (the backend answers none), also prefi | 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` | Prompt text and attachments; absent `mode` starts a new turn (including queued dispatch), while `mode: "steer"` and `input` supplement the current `turn`, confirmed by the plugin's `inputResolved` after the CLI responds | `agents.native` | -| API-45 | `agents/didCancel` | The user cancelled the active turn | `agents.native` | +| API-45 | `agents/didCancel` | The user stopped the active turn and paused the remaining queue; Core waits for the tool to report its actual end, without an error outcome for user cancellation | `agents.native` | | API-45 | `agents/didAnswerQuestion` | The user's answer or cancellation of a structured question, with `turn`, `request`, `answers`, `cancelled`; the SDK reports `questionAnswered` after handler delivery, retaining failed questions for retry | `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/didSetConfigOption` | The user picked a value, `value`, for a session setting the backend reported, `option` (a model, reasoning level, mode, and so on); the backend applies it when the CLI can take it and reports the settings again | `agents.native` | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 79111891..2b87329d 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| 待提交(待合入) | 待提交时登记 PR 作者 | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision、桌面版本待真实提交与发布后回填。 | +| [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision 为 [`1f843f8ee3aac802cda17ad8df43b51e30862b0d`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/1f843f8ee3aac802cda17ad8df43b51e30862b0d)(本 PR,尚未合入);桌面端尚未发布。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | @@ -216,16 +216,17 @@ | API-45 | `agents/write` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0(事件新增 `configOptions`) | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | -| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类) | 待合入 | 待提交 | +| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | | API-45 | `agents/usage` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0(回答新增 `speeds`) | 2026-11-28 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | | API-45 | `agents/didStart`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didOutput`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didPrompt`(通知) | 0(有附件时带 `attachments`) | 2026-11-28 | [#224](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/224) | -| API-45 | `agents/didPrompt`(通知) | 0(`mode: "steer"`、`input` 保留当前轮次身份) | 待合入 | 待提交 | +| API-45 | `agents/didPrompt`(通知) | 0(`mode: "steer"`、`input` 保留当前轮次身份) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | | API-45 | `agents/didCancel`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | -| API-45 | `agents/didAnswerQuestion`(通知) | 0(`turn`、`request`、`answers`、`cancelled`,SDK 确认交付) | 待合入 | 待提交 | +| API-45 | `agents/didCancel`(通知) | 0(停止后暂停队列,等待真实轮次结束;主动取消不记错误终态) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | +| API-45 | `agents/didAnswerQuestion`(通知) | 0(`turn`、`request`、`answers`、`cancelled`,SDK 确认交付) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | | API-45 | `agents/didDecidePermission`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/didSetConfigOption`(通知) | 0 | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | | API-45 | `agents/didExit`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | From f8fe577e316caff5c72063083ffede8fe859f413 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 1 Dec 2026 11:28:42 +0800 Subject: [PATCH 3/3] fix(agents): bound interaction replay and preserve stop completion --- rust/contracts/application-boundary.md | 6 + rust/crates/agent-runtime/Cargo.toml | 2 +- rust/crates/agent-runtime/src/events.rs | 198 +++++++++++-- rust/crates/agent-runtime/src/interaction.rs | 8 +- rust/crates/agent-runtime/src/live.rs | 49 +++- rust/crates/agent-runtime/src/tests.rs | 262 ++++++++++++++++++ rust/fixtures/agents/turn-interaction-v1.json | 7 +- shared/plugins/contract/v1/README.md | 33 ++- shared/plugins/reference/api-catalog.md | 4 +- shared/plugins/reference/domains/agents.md | 6 + .../plugins/reference/protocol-changelog.md | 4 +- 11 files changed, 531 insertions(+), 48 deletions(-) diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 9548daa0..128574e2 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -98,6 +98,12 @@ for retry. CLI support comes from explicit interaction capabilities, never a tool name. Hosts render `interactionState` and retain presentation drafts; plugins translate opaque turn, question and option IDs into their CLI's real protocol. No input content is logged or persisted by this interaction layer. +Replay has both count and byte bounds; only the latest interaction snapshot of +each live session is retained. Rejected drafts use separately reserved recovery +storage and explicit sequence acknowledgements, so replay eviction cannot lose +them. Hosts deduplicate recoveries independently of the replay cursor and flush +acknowledgements even after session exit. A valid late question of the stopping +turn is suppressed, allowing a same-batch terminal result to finish Stop. See [the native session contract](../../shared/plugins/contract/v1/README.md#native-sessions) and [the shared fixture](../fixtures/agents/turn-interaction-v1.json). diff --git a/rust/crates/agent-runtime/Cargo.toml b/rust/crates/agent-runtime/Cargo.toml index fe9c5975..e2595eac 100644 --- a/rust/crates/agent-runtime/Cargo.toml +++ b/rust/crates/agent-runtime/Cargo.toml @@ -20,7 +20,7 @@ lithe-protocol = { path = "../protocol" } lithe-request-context = { path = "../request-context" } lithe-workspace = { path = "../workspace" } serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" +serde_json = { version = "1.0", features = ["raw_value"] } sha2 = "0.10" url = "2.5" diff --git a/rust/crates/agent-runtime/src/events.rs b/rust/crates/agent-runtime/src/events.rs index de0cdc51..8a0bdcc1 100644 --- a/rust/crates/agent-runtime/src/events.rs +++ b/rust/crates/agent-runtime/src/events.rs @@ -49,6 +49,15 @@ const MAX_CONFIG_VALUES: usize = 128; /// says so. const MAX_QUEUED_EVENTS: usize = 8192; +/// Encoded replay payload budget. Current live interaction snapshots are held +/// once per session, separately, so output eviction cannot hide action state. +const MAX_REPLAY_BYTES: usize = 16 * 1024 * 1024; + +/// Reserved before accepting steering, including inputs awaiting resolution. +/// Unacknowledged recovery cannot be evicted to make room for another input. +const MAX_RECOVERY_BYTES: usize = 16 * 1024 * 1024; +const MAX_RECOVERY_INPUTS: usize = 64; + /// Most events one `agents.waitEvents` returns. const MAX_EVENTS_PER_WAIT: usize = 512; @@ -406,7 +415,10 @@ impl TurnState { /// 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> { + pub fn apply<'a>( + &mut self, + events: &'a [SessionEvent], + ) -> Result, ReportRefusal> { let mut next = self.clone(); for (index, event) in events.iter().enumerate() { next.apply_one(event) @@ -415,8 +427,21 @@ impl TurnState { message: format!("Event {index} of the report {problem}."), })?; } + // A stopping CLI may ask and withdraw a question in its final batch. + // Suppress those cards while preserving atomic validation and turn end. + let stopping = self.interaction.stopping; + let visible = events + .iter() + .filter(|event| { + !stopping + || !matches!( + event, + SessionEvent::QuestionRequested(_) | SessionEvent::QuestionClosed(_) + ) + }) + .collect(); *self = next; - Ok(()) + Ok(visible) } fn apply_one(&mut self, event: &SessionEvent) -> Result<(), (&'static str, String)> { @@ -430,6 +455,9 @@ impl TurnState { } SessionEvent::QuestionRequested(request) => { self.require_active(request.turn)?; + if self.interaction.stopping && self.interaction.capabilities.questions { + return Ok(()); + } self.interaction .ask(request) .map_err(|code| (code, "has an invalid question request".to_string()))?; @@ -454,6 +482,7 @@ impl TurnState { .questions .remove(&request.request) .is_none() + && !self.interaction.stopping { return Err(( PRECONDITION_FAILED, @@ -758,23 +787,41 @@ pub(crate) fn check_rate_limits(limits: &RateLimits) -> Result<(), 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)] +/// One compact event the host reads, ordered by Core's acceptance sequence. +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub(crate) struct HostEvent { pub sequence: u64, pub session: String, - pub event: Value, + pub event: Box, +} + +impl HostEvent { + fn bytes(&self) -> usize { + self.event.get().len() + self.session.len() + std::mem::size_of::() + } +} + +/// A steering input reserves space before it leaves the user's draft. Only +/// explicit host acknowledgement releases a rejected input's recovery copy. +struct RecoverySlot { + bytes: usize, + event: Option, } #[derive(Default)] struct QueueState { events: VecDeque, + replay_bytes: usize, + dropped_through: u64, + snapshots: BTreeMap, + recoveries: BTreeMap<(String, String), RecoverySlot>, + recovery_bytes: usize, next_sequence: u64, } -/// The events of every session, for `agents.waitEvents`. +/// Bounded replay plus one current interaction snapshot per live session and +/// a separately reserved, acknowledged recovery channel for rejected drafts. #[derive(Default)] pub(crate) struct EventQueue { state: Mutex, @@ -782,25 +829,114 @@ pub(crate) struct EventQueue { } impl EventQueue { - /// Queues `event` of `session` and wakes a waiting reader. + /// Reserves a recovery before sending an input. The fixed headroom covers + /// Core's bounded failure code and envelope; recovery omits backend prose. + pub fn reserve_input(&self, session: &str, input: &crate::interaction::Input) -> bool { + let content = serde_json::to_string(input).expect("agent input serializes"); + let bytes = content.len() + session.len() + input.id.len() + 512; + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + if state.recoveries.len() >= MAX_RECOVERY_INPUTS + || state.recovery_bytes + bytes > MAX_RECOVERY_BYTES + { + return false; + } + state.recovery_bytes += bytes; + state.recoveries.insert( + (session.into(), input.id.clone()), + RecoverySlot { bytes, event: None }, + ); + true + } + + /// Releases an unsent input's reservation when the delivery queue refuses it. + pub fn release_input(&self, session: &str, input: &str) { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(slot) = state.recoveries.remove(&(session.into(), input.into())) { + state.recovery_bytes -= slot.bytes; + } + } + + /// Acknowledges only recovery events the host has restored, independently + /// of its replay cursor. Other windows cannot acknowledge by reading ahead. + pub fn acknowledge(&self, sequences: &[u64]) { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let mut released = 0; + state.recoveries.retain(|_, slot| { + let acknowledged = slot + .event + .as_ref() + .is_some_and(|e| sequences.contains(&e.sequence)); + if acknowledged { + released += slot.bytes; + } + !acknowledged + }); + state.recovery_bytes -= released; + } + + /// Stores compact encoded payloads. Superseded interaction snapshots are + /// replaced; only replay eviction marks a gap, not snapshot compaction. pub fn push(&self, session: &str, event: Value) { + let snapshot = event["kind"] == "interactionState"; + let exited = event["kind"] == "exited"; + let resolved = event["kind"] == "inputResolved"; + let encoded = serde_json::value::to_raw_value(&event).expect("session event serializes"); 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 { + if resolved { + let key = ( + session.to_string(), + event["input"].as_str().unwrap_or_default().to_string(), + ); + if event["accepted"] == true { + if let Some(slot) = state.recoveries.remove(&key) { + state.recovery_bytes -= slot.bytes; + } + } else if let Some(slot) = state.recoveries.get_mut(&key) { + // The recovery channel guarantees original content, not an + // unbounded diagnostic message. Full prose remains in replay. + let mut recovery = event; + recovery + .as_object_mut() + .expect("input resolution is an object") + .remove("message"); + let recovery = HostEvent { + sequence, + session: session.into(), + event: serde_json::value::to_raw_value(&recovery).expect("recovery serializes"), + }; + debug_assert!(recovery.bytes() <= slot.bytes); + slot.event = Some(recovery); + } + } + let entry = HostEvent { sequence, - session: session.to_string(), - event, - }); - while state.events.len() > MAX_QUEUED_EVENTS { - state.events.pop_front(); + session: session.into(), + event: encoded, + }; + if snapshot { + state.snapshots.insert(session.into(), entry); + } else { + if exited { + state.snapshots.remove(session); + } + state.replay_bytes += entry.bytes(); + state.events.push_back(entry); + while state.events.len() > MAX_QUEUED_EVENTS || state.replay_bytes > MAX_REPLAY_BYTES { + if let Some(dropped) = state.events.pop_front() { + state.replay_bytes -= dropped.bytes(); + state.dropped_through = dropped.sequence; + } + } } 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. + /// Reads ordered replay and current snapshots after `after`. Recoveries + /// also travel outside the cursor until acknowledged, including after an + /// output gap or a lost response. A future cursor only probes the latest ID. 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); @@ -816,17 +952,31 @@ impl EventQueue { .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 + let missed = after < state.dropped_through; + let mut events: Vec<&HostEvent> = state .events .iter() + .chain(state.snapshots.values()) + .chain( + state + .recoveries + .values() + .filter_map(|slot| slot.event.as_ref()), + ) .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 }) + events.sort_by_key(|event| event.sequence); + events.dedup_by_key(|event| event.sequence); + events.truncate(limit); + let next = events.last().map_or(state.next_sequence, |e| e.sequence); + let recoveries: Vec<_> = state + .recoveries + .values() + .filter_map(|slot| slot.event.as_ref()) + .filter(|event| after <= state.next_sequence && event.sequence <= next) + .collect(); + let mut recoveries = recoveries; + recoveries.sort_by_key(|event| event.sequence); + json!({"events":events,"next":next,"missed":missed,"recoveries":recoveries}) } } diff --git a/rust/crates/agent-runtime/src/interaction.rs b/rust/crates/agent-runtime/src/interaction.rs index 182a93dc..0af00618 100644 --- a/rust/crates/agent-runtime/src/interaction.rs +++ b/rust/crates/agent-runtime/src/interaction.rs @@ -189,7 +189,7 @@ impl Interaction { } pub fn ask(&mut self, request: &QuestionRequest) -> Result<(), &'static str> { - if !self.capabilities.questions || self.stopping { + if !self.capabilities.questions { return Err(codes::HOST_PRECONDITION_FAILED); } if self.questions.contains_key(&request.request) { @@ -203,7 +203,8 @@ impl Interaction { Ok(()) } - /// Only interaction changes emit this small projection, never text deltas. + /// Only interaction changes emit this projection, never text deltas. + /// The event queue retains only the latest snapshot for each live session. pub fn projection(&self, active: Option) -> Value { json!({ "kind": "interactionState", "activeTurn": active.unwrap_or(0), @@ -242,6 +243,9 @@ pub(crate) fn send(session: &LiveSession, delivery: Delivery) -> Result<(), Core } pub(crate) fn publish(runtime: &Runtime, session: &LiveSession, state: &crate::events::TurnState) { + if state.interaction.closed { + return; // An exiting worker must not recreate the disposed snapshot. + } runtime .live .queue diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index d1fe5218..cd759535 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -358,7 +358,18 @@ impl Live { || events.iter().any(|event| { matches!(event, SessionEvent::TurnEnded(ended) if ended.reason == crate::events::StopReason::Cancelled) }); - state + let changed = events.iter().any(|event| { + matches!( + event, + SessionEvent::InteractionCapabilities(_) + | SessionEvent::QuestionRequested(_) + | SessionEvent::QuestionClosed(_) + | SessionEvent::QuestionAnswered(_) + | SessionEvent::InputResolved(_) + | SessionEvent::TurnEnded(_) + ) + }); + let events = state .apply(&events) .map_err(|ReportRefusal { code, message }| refuse(code, message))?; for event in &events { @@ -384,17 +395,6 @@ impl Live { } self.queue.push(&session.id, value); } - let changed = events.iter().any(|event| { - matches!( - event, - SessionEvent::InteractionCapabilities(_) - | SessionEvent::QuestionRequested(_) - | SessionEvent::QuestionClosed(_) - | SessionEvent::QuestionAnswered(_) - | SessionEvent::InputResolved(_) - | SessionEvent::TurnEnded(_) - ) - }); if changed { // A steer with no CLI acknowledgement must remain recoverable when its // target turn ends; do not carry it into the next turn. @@ -1165,7 +1165,21 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, payload: Value) -> Result, + #[serde(default)] + acknowledge: Vec, } let request: WaitRequest = crate::decode(payload)?; + if request.acknowledge.len() > 512 { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "At most 512 recovery sequences may be acknowledged.", + )); + } + runtime.live.queue.acknowledge(&request.acknowledge); Ok(runtime.live.queue.wait( request.after, Duration::from_millis(request.timeout_milliseconds), diff --git a/rust/crates/agent-runtime/src/tests.rs b/rust/crates/agent-runtime/src/tests.rs index 437e1f55..20042b4d 100644 --- a/rust/crates/agent-runtime/src/tests.rs +++ b/rust/crates/agent-runtime/src/tests.rs @@ -1822,6 +1822,268 @@ fn wait_events_says_when_events_were_dropped() { assert_eq!(caught_up["next"], 8200); } +#[test] +fn event_replay_is_bounded_by_bytes_and_reports_an_oversized_gap() { + let queue = crate::events::EventQueue::default(); + for _ in 0..20 { + queue.push( + "agent-0", + json!({"kind":"notice", "text":"x".repeat(1024 * 1024)}), + ); + } + let batch = queue.wait(0, Duration::ZERO, 512); + let bytes = serde_json::to_vec(&batch["events"]).unwrap().len(); + eprintln!("retained replay JSON: {bytes} bytes"); + assert!(bytes <= 16 * 1024 * 1024, "replay retained {bytes} bytes"); + assert_eq!(batch["missed"], true); + queue.push( + "agent-0", + json!({"kind":"notice", "text":"x".repeat(17 * 1024 * 1024)}), + ); + let gap = queue.wait(20, Duration::ZERO, 512); + assert_eq!(gap["missed"], true); + assert_eq!(gap["next"], 21); +} + +#[test] +fn interaction_replay_keeps_one_current_snapshot_without_losing_queued_content() { + let harness = Harness::new("snapshot-memory", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + for _ in 0..3 { + harness.run( + "agents.prompt", + json!({"session":session,"mode":"queue","text":"x".repeat(128 * 1024)}), + ); + } + for _ in 0..64 { + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","questions":true}]), + ) + .unwrap(); + } + let batch = harness.run("agents.waitEvents", json!({"limit":512})); + let snapshots: Vec<_> = batch["events"] + .as_array() + .unwrap() + .iter() + .filter(|entry| entry["event"]["kind"] == "interactionState") + .collect(); + let bytes = serde_json::to_vec(&snapshots).unwrap().len(); + eprintln!( + "retained interaction JSON: {bytes} bytes in {} snapshots", + snapshots.len() + ); + assert_eq!( + snapshots.len(), + 1, + "only the latest interaction is replayable" + ); + assert_eq!( + snapshots[0]["event"]["queue"], + harness.sessions()[0]["interaction"]["queue"] + ); + assert_eq!( + batch["missed"], false, + "superseding a snapshot loses no current state" + ); +} + +#[test] +fn stopping_suppresses_late_questions_but_validates_the_report_and_allows_resume() { + let harness = Harness::new("stop-question", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + harness.run( + "agents.prompt", + json!({"session":session,"mode":"queue","text":"next"}), + ); + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","questions":true}]), + ) + .unwrap(); + harness.run("agents.cancel", json!({"session":session})); + let question = json!({"kind":"questionRequested","turn":1,"request":"late","questions":[ + {"id":"scope","title":"Scope","text":"Which scope?","allowText":true} + ]}); + let ended = json!({"kind":"turnEnded","turn":1,"reason":"cancelled"}); + let mut foreign = question.clone(); + foreign["turn"] = json!(2); + assert_eq!( + harness + .report(&session, json!([foreign, ended])) + .unwrap_err() + .code, + codes::HOST_PRECONDITION_FAILED + ); + let mut malformed = question.clone(); + malformed["questions"] = json!([]); + assert_eq!( + harness + .report(&session, json!([malformed, ended])) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + harness.report(&session, json!([question])).unwrap(); + assert_eq!(harness.sessions()[0]["interaction"]["questions"], json!([])); + assert_eq!( + harness.refused( + "agents.respondQuestion", + json!({"session":session,"request":"late","cancelled":true}) + ), + "agents.questionNotPending" + ); + harness + .report( + &session, + json!([question, {"kind":"questionClosed","turn":1,"request":"late"}, ended]), + ) + .unwrap(); + let state = &harness.sessions()[0]["interaction"]; + assert_eq!(state["activeTurn"], 0); + assert_eq!(state["stopping"], false); + assert_eq!(state["paused"], true); + assert_eq!(state["questions"], json!([])); + assert_eq!(state["answering"], json!([])); + let batch = harness.run("agents.waitEvents", json!({})); + assert!(!batch["events"] + .as_array() + .unwrap() + .iter() + .any(|entry| entry["event"]["kind"] == "questionRequested")); + harness.run( + "agents.updateQueue", + json!({"session":session,"resume":true}), + ); + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["turn"] == 2 && p["text"] == "next"); +} + +#[test] +fn rejected_input_recovery_survives_eviction_lost_reads_exit_and_explicit_acknowledgement() { + let harness = Harness::new("recovery-replay", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","steering":true}]), + ) + .unwrap(); + let sent = harness.run("agents.prompt", json!({"session":session,"mode":"steer","expectedTurn":1,"text":"keep this original input"})); + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["input"] == sent["input"]); + harness.report(&session, json!([{"kind":"inputResolved","turn":1,"input":sent["input"],"accepted":false,"code":"cancelled"}])).unwrap(); + let first = harness.run("agents.waitEvents", json!({})); + let recovery = first["recoveries"][0].clone(); + let sequence = recovery["sequence"].as_u64().unwrap(); + assert_eq!( + recovery["event"]["content"]["text"], + "keep this original input" + ); + // Another window's future probe neither consumes nor receives the draft. + let probe = harness.run("agents.waitEvents", json!({"after":1_u64 << 53})); + assert_eq!(probe["recoveries"], json!([])); + harness.run("agents.close", json!({"session":session})); + harness.link.server(0).exit(Some(0)); + assert!(harness.settle(), "closed synthetic CLI must end"); + for _ in 0..8200 { + harness + .runtime + .live + .queue + .push("other-window", json!({"kind":"notice"})); + } + let batch = harness.run("agents.waitEvents", json!({"after":first["next"]})); + assert_eq!(batch["missed"], true); + assert!(!batch["events"] + .as_array() + .unwrap() + .iter() + .any(|event| event["sequence"] == sequence)); + assert_eq!(batch["recoveries"], json!([recovery])); + // Losing an entire response cannot consume its one-shot recovery. + assert_eq!( + harness.run("agents.waitEvents", json!({"after":batch["next"]}))["recoveries"], + batch["recoveries"] + ); + let acknowledged = harness.run( + "agents.waitEvents", + json!({"after":batch["next"],"acknowledge":[sequence]}), + ); + assert_eq!(acknowledged["recoveries"], json!([])); +} + +#[test] +fn recovery_capacity_refuses_new_steering_before_delivery_until_a_draft_is_acknowledged() { + let harness = Harness::new("recovery-limit", ALL_GRANTS); + let session = harness.start(); + harness.run("agents.prompt", json!({"session":session,"text":"first"})); + harness + .report( + &session, + json!([{"kind":"interactionCapabilities","steering":true}]), + ) + .unwrap(); + let queue = &harness.runtime.live.queue; + for index in 0..64 { + let input = crate::interaction::Input { + id: format!("reserved-{index}"), + text: "retained".into(), + attachments: vec![], + turn: 1, + }; + assert!(queue.reserve_input("closed-session", &input)); + queue.push("closed-session", json!({"kind":"inputResolved","turn":1,"input":input.id,"accepted":false,"content":input})); + } + let request = + json!({"session":session,"mode":"steer","expectedTurn":1,"text":"must remain in draft"}); + assert_eq!( + harness.refused("agents.prompt", request.clone()), + "agents.interactionBusy" + ); + assert!(!harness + .link + .notices_of(AGENTS_DID_PROMPT) + .iter() + .any(|p| p["mode"] == "steer")); + let batch = queue.wait(0, Duration::ZERO, 512); + let sequence = batch["recoveries"][0]["sequence"].as_u64().unwrap(); + queue.acknowledge(&[sequence]); + let sent = harness.run("agents.prompt", request); + harness + .link + .await_notice(AGENTS_DID_PROMPT, |p| p["input"] == sent["input"]); + harness + .report( + &session, + json!([{"kind":"inputResolved","turn":1,"input":sent["input"],"accepted":true}]), + ) + .unwrap(); + // Successful input consumes no recovery capacity, even without host ack. + assert!(queue.reserve_input( + "closed-session", + &crate::interaction::Input { + id: "next".into(), + text: "retained".into(), + attachments: vec![], + turn: 1 + } + )); + let invalid = harness + .runtime + .execute("agents.waitEvents", json!({"acknowledge":vec![0;513]})) + .unwrap_err(); + assert!(matches!(invalid.code, ErrorCode::InvalidRequest)); +} + #[test] fn chunk_lines_keep_byte_offsets_and_text_lines_drop_line_breaks() { assert_eq!( diff --git a/rust/fixtures/agents/turn-interaction-v1.json b/rust/fixtures/agents/turn-interaction-v1.json index 7df9f0b3..bf0c64d7 100644 --- a/rust/fixtures/agents/turn-interaction-v1.json +++ b/rust/fixtures/agents/turn-interaction-v1.json @@ -70,7 +70,12 @@ { "actions": [ {"command": "agents.cancel", "payload": {}}, - {"report": [{"kind": "turnEnded", "turn": 2, "reason": "completed"}]} + {"report": [ + {"kind": "questionRequested", "turn": 2, "request": "late", "questions": [ + {"id": "scope", "title": "Scope", "text": "Which scope?", "allowText": true} + ]}, + {"kind": "turnEnded", "turn": 2, "reason": "completed"} + ]} ], "events": [{"kind": "turnEnded", "turn": 2, "reason": "completed"}], "interaction": { diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index c7737bcb..8e8adc9d 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3816,7 +3816,7 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. | `agents.setConfigOption` | `{session, option, value}` | `{}` | | `agents.close` | `{session}` | `{}` | | `agents.sessions` | `{}` | `{sessions}`: the live sessions | -| `agents.waitEvents` | `{after?, timeoutMilliseconds?, limit?}` | `{events: [{sequence, session, event}], next, missed}` | +| `agents.waitEvents` | `{after?, timeoutMilliseconds?, limit?, acknowledge?: [sequence]}` | `{events: [{sequence, session, event}], next, missed, recoveries: [{sequence, session, event}]}` | - `agents.start`, `agents.prompt`, `agents.cancel`, `agents.updateQueue`, `agents.respondQuestion`, `agents.respondPermission` and @@ -3908,8 +3908,28 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. 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. + 256, at most 512). Ordinary replay retains at most 8192 events and 16 MiB + of encoded payload plus envelope storage, evicting oldest first. `missed` + is a boolean indicating an evicted sequence after `after`; an oversized + event can be skipped entirely, and `next` still advances past the gap. + Per-session `interactionState` snapshots are compacted to the latest one, + separately from replay, until the session exits. Compaction does not set + `missed`: the latest snapshot replaces all preceding action state. The + host calls this off its UI thread. +- `recoveries` repeats rejected/unacknowledged steering input events until + the owning host restores their drafts and explicitly includes their + sequences in `acknowledge` (default empty, at most 512). A replay cursor, + read by another window, or session exit never acknowledges a recovery. + Recoveries may precede `after`; merge them by sequence and restore each + once, independently of the output cursor. A future-cursor probe returns + only the latest `next`, without recovering or consuming other windows' + drafts. Recovery storage is reserved before steering is accepted: at most + 64 inputs / 16 MiB globally, including unresolved inputs. Exhaustion is + `agents.interactionBusy` before delivery, leaving the new draft with the + host. Success releases its reservation; rejection retains original content + in memory until acknowledgement or runtime disposal. Recovery copies omit + optional backend `message` prose, preserve controlled codes, and are not + persisted. A host must flush acknowledgements after its last session exits. The `terminal` form needs no command: the host runs `toolPath` with `terminalArguments` in its own terminal, in the workspace directory, with @@ -4101,6 +4121,13 @@ Besides the backend's events, `agents.waitEvents` carries Core's own: `closed`, `failed` or `backendEnded` and `stderrTail` is the last 8 KiB the CLI wrote to standard error. +Valid `questionRequested` events for the active stopping turn are checked for +shape, bounds, capability and turn identity, then suppressed without becoming +pending or reaching the host. A withdrawal for that turn may follow without +finding a pending question. Neither event prevents a same-batch `turnEnded` +from completing Stop. Malformed or foreign-turn events still reject the whole +report; reserved answer delivery confirmations keep their normal validation. + Core also emits `interactionState {activeTurn, canPrompt, canSteer, canQueue, canStop, stopping, paused, queue, questions, steering, answering}` when an interaction changes, not for token deltas. `activeTurn` is 0 when idle; diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index a445755d..727099e9 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -167,7 +167,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | 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/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–45 内,见[快捷键导入](domains/keymap-import.md)。 @@ -388,7 +388,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | 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 native-session events (session, message, tool call, plan, permission request, usage, rate limits, turn end, notice, settings, interaction capabilities, structured questions and delivery confirmations): 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/report` | Reports native-session events (session, message, tool call, plan, permission request, usage, rate limits, turn end, notice, settings, interaction capabilities, structured questions and delivery confirmations): 1–256, checked together, so when one is refused none applies; valid stopping-turn questions are suppressed without blocking a same-batch turn end; 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–45; see [Shortcut import](domains/keymap-import.md). diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 46253b4a..9d8fd07e 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -180,3 +180,9 @@ Every change comes only from a user action. Core reads and writes only the decla | [`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 | + +### 停止竞争和事件恢复 + +停止中的当前轮次仍可能报告问题。Core 校验问题的结构、限额、能力和轮次,随后抑制它;同一批的结束事件继续生效。插件可以撤回该问题,不能因为用户已停止就反复重报整个结束批次。畸形或其他轮次的事件仍使整批报告失败,四语 SDK 的报告类型和调用接口均不变。 + +桌面宿主的事件重放同时受 8192 条和 16 MiB 限额约束,每个活动会话只保留最新交互快照。被拒绝的补充通过独立 `recoveries` 返回,宿主恢复后在下次 `agents.waitEvents` 用 `acknowledge` 确认序列;仅推进游标不代表恢复成功。预留恢复容量耗尽时,新的补充会在交付前返回 `agents.interactionBusy`。详情见[原生会话契约](../../contract/v1/README.md#native-sessions)。 diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 2b87329d..fa615e4d 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision 为 [`1f843f8ee3aac802cda17ad8df43b51e30862b0d`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/1f843f8ee3aac802cda17ad8df43b51e30862b0d)(本 PR,尚未合入);桌面端尚未发布。 | +| [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。事件重放同时限制 8192 条 / 16 MiB,交互状态只保留每会话最新快照;`agents.waitEvents` 增加 `recoveries` 与可选 `acknowledge`,拒绝的补充在预留的 64 条 / 16 MiB 容量中保留,直到宿主恢复并显式确认。停止后的有效当前轮次问题被抑制,不阻塞同批结束事件。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision 为 [`1f843f8ee3aac802cda17ad8df43b51e30862b0d`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/1f843f8ee3aac802cda17ad8df43b51e30862b0d)(本 PR,尚未合入);桌面端尚未发布。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | @@ -216,7 +216,7 @@ | API-45 | `agents/write` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/report` | 0(事件新增 `configOptions`) | 2026-11-28 | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | -| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | +| API-45 | `agents/report` | 0(交互能力、提问/撤回、回答交付与立即补充确认;封闭失败分类;停止中抑制当前轮次问题,保留整批结束) | 待合入 | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239) | | API-45 | `agents/usage` | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) | | API-45 | `agents/usage` | 0(回答新增 `speeds`) | 2026-11-28 | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | | API-45 | `agents/didStart`(通知) | 0 | 2026-11-27 | [#216](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/216) |