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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 3 additions & 21 deletions rustcode/engine/src/acp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod agents;
mod attachments;
pub(crate) mod builtin;
mod builtin_open;
mod capabilities;
pub(crate) mod clients;
mod commands;
Expand Down Expand Up @@ -36,13 +37,15 @@ mod session_repair;
mod session_replay;
mod session_transfer;
pub(crate) mod settings;
mod share;
pub(crate) mod steer;
mod stop;
mod streaming;
mod telemetry;
mod themes;
pub(crate) mod usage;
mod workflows;
pub(crate) use builtin_open::*;
pub(crate) use session_load::*;
mod extensions;
pub(crate) use extensions::*;
Expand Down Expand Up @@ -474,27 +477,6 @@ async fn close_builtin(server: &AcpServer, session_id: &str) -> Option<std::path
cwd
}

/// A built-in `session/new` honours `_meta.rustcode.model` and `effort` the
/// same way external harnesses do (docs/harnesses.md). Model first, since
/// the effort choices depend on it; an unknown value is ignored and the
/// session keeps its default.
fn apply_requested_model_and_effort(
state: &mut crate::app::AppState,
asked: &crate::harness::HarnessRequest,
) {
for (id, value) in [("model", &asked.model), ("effort", &asked.effort)] {
if let Some(value) = value {
let _ = handle_set_config_option(
state,
&agent_client_protocol::schema::v1::SessionConfigId::new(id),
&agent_client_protocol::schema::v1::SessionConfigOptionValue::value_id(
value.clone(),
),
);
}
}
}

fn unknown_session(session_id: &str) -> agent_client_protocol::Error {
agent_client_protocol::Error::invalid_params()
.data(format!("unknown ACP session: {session_id}"))
Expand Down
73 changes: 73 additions & 0 deletions rustcode/engine/src/acp/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,53 @@ pub(crate) trait BuiltinAgent: Send + Sync {
/// Whether a queued prompt waits and no turn is running.
fn has_queued_work(&self) -> AgentFuture<'_, bool>;

/// Start sharing `session_id` with the remote gateway under
/// `registration`: the publisher and the message that opens the link.
/// `None` when the thread no longer shows that session.
fn share<'a>(
&'a self,
session_id: &'a str,
registration: crate::remote::SessionRegistration,
) -> AgentFuture<
'a,
Option<(
Box<dyn BuiltinPublisher>,
crate::remote::owner::OwnerMessage,
)>,
>;

/// Apply a device's mutation (prompt, cancel, answer, settings) to the
/// shared thread.
fn remote_mutation<'a>(
&'a self,
cancel_token: &'a mut tokio_util::sync::CancellationToken,
registration: &'a crate::remote::SessionRegistration,
request: &'a crate::remote::RemoteRequest,
) -> AgentFuture<'a, Result<crate::remote::SessionMutation, crate::remote::RemoteError>>;

/// Answer a device's read of the shared thread.
fn remote_read<'a>(
&'a self,
registration: &'a crate::remote::SessionRegistration,
request: &'a crate::remote::RemoteRequest,
) -> AgentFuture<'a, Result<crate::remote::RemoteResult, crate::remote::RemoteError>>;

/// The workspace a device's `get_changes` reads, checked like any read.
fn remote_changes_workspace<'a>(
&'a self,
registration: &'a crate::remote::SessionRegistration,
request: &'a crate::remote::RemoteRequest,
) -> AgentFuture<'a, Result<PathBuf, crate::remote::RemoteError>>;

/// The thread's model, read without waiting: `None` while a turn holds
/// the thread.
fn selected_model(&self) -> Option<String>;

/// The thread's state, for the agent tests that still live in the
/// engine until the agent gets its own crate.
#[cfg(test)]
fn test_state(&self) -> Arc<tokio::sync::Mutex<crate::app::AppState>>;

/// The thread's transcript.
fn history(&self) -> AgentFuture<'_, rustcode_core::History>;

Expand All @@ -164,3 +211,29 @@ pub(crate) struct AttachSnapshot {
pub(crate) config_options: Vec<SessionConfigOption>,
pub(crate) usage: agent_client_protocol::schema::v1::SessionUpdate,
}

/// Publishes a shared built-in thread to the remote gateway.
pub(crate) trait BuiltinPublisher: Send {
/// Note an agent event the thread has applied.
fn observe(&mut self, event: &crate::controller::AgentUiEvent);

/// Send a full snapshot on the next publish.
fn request_snapshot(&mut self);

/// Drop events until the next resync snapshot: the link fell behind.
fn mark_lagging(&mut self);

/// Sequence of the last event published.
fn sequence(&self) -> u64;

/// What changed since the last publish. `None` when the thread no longer
/// shows the shared session.
fn publish(&mut self, room_for_resync: bool) -> AgentFuture<'_, Option<Published>>;
}

/// One publish pass of a shared built-in thread.
pub(crate) struct Published {
pub(crate) messages: Vec<crate::remote::owner::OwnerMessage>,
/// A prompt is queued and no turn runs, so the turn loop should start.
pub(crate) queued_while_idle: bool,
}
151 changes: 151 additions & 0 deletions rustcode/engine/src/acp/builtin_open.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
//! Opening a built-in thread: the agent builds the state of a new or loaded
//! session and hands the server the trait object that runs it.

use super::*;

/// A built-in thread the agent opened, with what its first client gets.
pub(crate) struct OpenedThread {
pub(crate) session_id: String,
pub(crate) agent: Arc<dyn builtin::BuiltinAgent>,
pub(crate) clients: clients::SessionClients,
pub(crate) snapshot: builtin::AttachSnapshot,
}

/// Open a new thread in `cwd` with the model and effort `start` names.
/// `attach` gives the clients of the session id the agent picked.
pub(super) fn create_thread(
cwd: &std::path::Path,
start: &crate::harness::HarnessRequest,
info: clients::ClientInfo,
attach: impl FnOnce(&str) -> clients::SessionClients,
) -> OpenedThread {
let mut state = new_session_state(cwd);
let session_id = state.active_session_id.clone();
let clients = attach(&session_id);
apply_client_info(&mut state, info, &clients);
state.raw_cli_mode = false;
state.task_working_directory = Some(cwd.to_path_buf());
// ACP's requested cwd is both the task's initial location
// and its hard filesystem boundary, independent of the
// directory from which RustCode itself was launched.
state.workspace_root = Some(cwd.to_path_buf());
apply_requested_model_and_effort(&mut state, start);
opened(state, clients)
}

/// Open the saved thread `session_id` in `cwd` with `history`.
pub(super) fn load_thread(
session_id: &str,
cwd: &std::path::Path,
history: Vec<crate::app::ChatMessage>,
info: clients::ClientInfo,
clients: clients::SessionClients,
) -> OpenedThread {
let mut state = build_loaded_app_state(session_id, cwd, history);
apply_client_info(&mut state, info, &clients);
opened(state, clients)
}

fn opened(state: crate::app::AppState, clients: clients::SessionClients) -> OpenedThread {
let snapshot = builtin::AttachSnapshot {
compaction: state.last_compaction.clone(),
config_options: build_session_config_options(&state),
usage: usage::usage_update(&state),
};
let session_id = state.active_session_id.clone();
OpenedThread {
session_id,
agent: super::prompt::builtin_agent(Arc::new(Mutex::new(state))),
clients,
snapshot,
}
}

pub(crate) fn build_loaded_app_state(
session_id: &str,
cwd: &std::path::Path,
history: Vec<crate::app::ChatMessage>,
) -> crate::app::AppState {
let mut state = crate::app::AppState::new_with_workspace_session(cwd, Some(session_id));
state.restore_session_model();
state.restore_session_compaction();
state.task_working_directory = Some(cwd.to_path_buf());
state.workspace_root = Some(cwd.to_path_buf());
// Reattach the session's recorded task worktree so resume reuses its
// writable roots and cwd instead of starting over in the source checkout
// (#1496). A missing or foreign worktree falls back to `cwd`.
if let Some(workspace) = crate::sessions::load_session_workspace(session_id)
&& let Some(descriptor_id) = workspace.task_workspace_id
&& let Some(manager) = crate::sessions::workspace_manager()
&& let Ok(descriptor) = manager.resume(&descriptor_id)
{
state.workspace_root = Some(descriptor.workspace_path.clone());
state.task_working_directory = Some(descriptor.workspace_path.clone());
}
state.history.replace(history);
state
}

/// State for `session/new`. The id is always fresh: reusing the shared
/// last-active session, as the TUI does when it is still empty, would hand two
/// ACP sessions (or two processes) the same history file.
pub(super) fn new_session_state(cwd: &std::path::Path) -> crate::app::AppState {
let session_id = crate::sessions::create_detached_session();
let state = crate::app::AppState::new_with_workspace_session(cwd, Some(&session_id));
if !session_id.is_empty() {
crate::sessions::record_session_settings(&session_id, &state.config);
state.record_session_model();
}
state
}

/// Give a session the client half of what its client advertised: how replies
/// are drawn, and the preview, desktop, orchestration and Smart UI requests.
/// Read once, from the client that created or loaded it, so its prompt never
/// changes mid-session; each request goes to whichever client has the
/// session then.
pub(super) fn apply_client_info(
state: &mut crate::app::AppState,
info: clients::ClientInfo,
clients: &clients::SessionClients,
) {
let secret_clients = clients.clone();
state.secret_asker = Some(std::sync::Arc::new(move |request| {
let clients = secret_clients.clone();
Box::pin(async move { clients.request(None, request).await.ok() })
}));
state.visualization_level = info.visualization_level;
state.smart_ui = info.smart_ui;
state.preview_client = preview::preview_client_for(info.preview, clients);
state.desktop_client = preview::desktop_client_for(info.desktop, clients);
(state.orchestration_client, state.orchestration_version) =
preview::orchestration_for(info.orchestration, clients);
// No app hosting the tools: this engine serves the reads and names the app
// for the rest (#3422). An app that turned them off keeps them off.
state.local_orchestration = info.engine_hosts_orchestration(clients);
state.smart_ui_client = preview::smart_ui_client_for(
info.smart_ui == crate::app::SmartUi::On && info.smart_ui_preview,
clients,
);
}

/// A built-in `session/new` honours `_meta.rustcode.model` and `effort` the
/// same way external harnesses do (docs/harnesses.md). Model first, since
/// the effort choices depend on it; an unknown value is ignored and the
/// session keeps its default.
pub(super) fn apply_requested_model_and_effort(
state: &mut crate::app::AppState,
asked: &crate::harness::HarnessRequest,
) {
for (id, value) in [("model", &asked.model), ("effort", &asked.effort)] {
if let Some(value) = value {
let _ = handle_set_config_option(
state,
&agent_client_protocol::schema::v1::SessionConfigId::new(id),
&agent_client_protocol::schema::v1::SessionConfigOptionValue::value_id(
value.clone(),
),
);
}
}
}
64 changes: 64 additions & 0 deletions rustcode/engine/src/acp/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,70 @@ impl super::builtin::BuiltinAgent for StateAgent {
})
}

fn share<'a>(
&'a self,
session_id: &'a str,
registration: crate::remote::SessionRegistration,
) -> super::builtin::AgentFuture<
'a,
Option<(
Box<dyn super::builtin::BuiltinPublisher>,
crate::remote::owner::OwnerMessage,
)>,
> {
Box::pin(super::share::share(&self.state, session_id, registration))
}

fn remote_mutation<'a>(
&'a self,
cancel_token: &'a mut tokio_util::sync::CancellationToken,
registration: &'a crate::remote::SessionRegistration,
request: &'a crate::remote::RemoteRequest,
) -> super::builtin::AgentFuture<
'a,
Result<crate::remote::SessionMutation, crate::remote::RemoteError>,
> {
Box::pin(super::share::mutate(
&self.state,
cancel_token,
registration,
request,
))
}

fn remote_read<'a>(
&'a self,
registration: &'a crate::remote::SessionRegistration,
request: &'a crate::remote::RemoteRequest,
) -> super::builtin::AgentFuture<
'a,
Result<crate::remote::RemoteResult, crate::remote::RemoteError>,
> {
Box::pin(super::share::read(&self.state, registration, request))
}

fn remote_changes_workspace<'a>(
&'a self,
registration: &'a crate::remote::SessionRegistration,
request: &'a crate::remote::RemoteRequest,
) -> super::builtin::AgentFuture<'a, Result<std::path::PathBuf, crate::remote::RemoteError>>
{
Box::pin(super::share::changes_workspace(
&self.state,
registration,
request,
))
}

fn selected_model(&self) -> Option<String> {
super::share::selected_model(&self.state)
}

#[cfg(test)]
fn test_state(&self) -> Arc<Mutex<crate::app::AppState>> {
Arc::clone(&self.state)
}

fn last_active(&self) -> Option<String> {
self.state.try_lock().ok().and_then(|state| {
state
Expand Down
Loading
Loading