feat(maestro): load existing ACP sessions
Resume a stored ACP session through session/load and discard the history replayed during the load handshake so the durable event log remains the single transcript source.
This commit is contained in:
@@ -19,6 +19,12 @@
|
||||
//! is dropped while nobody reads: #135 takes the receiver and persists each
|
||||
//! notification to the per-session event log before broadcasting it.
|
||||
//!
|
||||
//! A respawn after a daemon restart sets [`SpawnConfig::load_session`] and
|
||||
//! the handshake runs `session/load` with the stored id instead of
|
||||
//! `session/new`. The history the agent streams back while that request is
|
||||
//! in flight is *not* delivered: the daemon's event log already holds it,
|
||||
//! and replaying it would double every line.
|
||||
//!
|
||||
//! The child is a child of the daemon, full stop. It shares the daemon's
|
||||
//! process group, is marked to receive `SIGTERM` when the daemon dies
|
||||
//! (`PR_SET_PDEATHSIG` on Linux), and [`AcpSession::terminate`] is what both
|
||||
@@ -31,13 +37,14 @@ use std::collections::{HashMap, VecDeque};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{ExitStatus, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use agent_client_protocol::schema::v1::{
|
||||
CancelNotification, ClientCapabilities, FileSystemCapabilities, Implementation,
|
||||
InitializeRequest, NewSessionRequest, RequestPermissionOutcome, RequestPermissionRequest,
|
||||
RequestPermissionResponse, SessionId, SessionNotification,
|
||||
InitializeRequest, LoadSessionRequest, NewSessionRequest, RequestPermissionOutcome,
|
||||
RequestPermissionRequest, RequestPermissionResponse, SessionId, SessionNotification,
|
||||
};
|
||||
use agent_client_protocol::schema::ProtocolVersion;
|
||||
use agent_client_protocol::{ByteStreams, Client};
|
||||
@@ -82,6 +89,10 @@ pub struct SpawnConfig {
|
||||
pub env: HashMap<String, String>,
|
||||
/// Upper bound on the handshake; [`HANDSHAKE_TIMEOUT`] by default.
|
||||
pub handshake_timeout: Duration,
|
||||
/// An existing ACP session id to resume with `session/load` (#135)
|
||||
/// instead of opening a fresh one. The adapter must advertise
|
||||
/// `loadSession`; the handshake fails otherwise.
|
||||
pub load_session: Option<String>,
|
||||
}
|
||||
|
||||
impl SpawnConfig {
|
||||
@@ -90,8 +101,15 @@ impl SpawnConfig {
|
||||
cwd: cwd.into(),
|
||||
env,
|
||||
handshake_timeout: HANDSHAKE_TIMEOUT,
|
||||
load_session: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume `session_id` with `session/load` instead of `session/new`.
|
||||
pub fn load_session(mut self, session_id: impl Into<String>) -> Self {
|
||||
self.load_session = Some(session_id.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -296,6 +314,7 @@ pub async fn spawn(config: SpawnConfig) -> Result<AcpSession, AcpError> {
|
||||
tokio::spawn(run_connection(
|
||||
transport,
|
||||
config.cwd.clone(),
|
||||
config.load_session.clone(),
|
||||
updates_tx,
|
||||
commands_rx,
|
||||
ready_tx,
|
||||
@@ -375,17 +394,28 @@ fn client_capabilities() -> ClientCapabilities {
|
||||
async fn run_connection<T>(
|
||||
transport: T,
|
||||
cwd: PathBuf,
|
||||
load_session: Option<String>,
|
||||
updates_tx: mpsc::UnboundedSender<SessionNotification>,
|
||||
mut commands_rx: mpsc::UnboundedReceiver<Command>,
|
||||
ready_tx: oneshot::Sender<Result<String, ReadyError>>,
|
||||
) where
|
||||
T: agent_client_protocol::ConnectTo<Client> + 'static,
|
||||
{
|
||||
// Set while `session/load` is in flight. Notification handlers run in
|
||||
// the dispatch loop, in arrival order, so everything the agent streams
|
||||
// before its load response sees the flag up and is dropped: that is the
|
||||
// history the event log already holds (#135).
|
||||
let replaying = Arc::new(AtomicBool::new(false));
|
||||
let replaying_seen = replaying.clone();
|
||||
let result = Client
|
||||
.builder()
|
||||
.name("maestro")
|
||||
.on_receive_notification(
|
||||
async move |notification: SessionNotification, _cx| {
|
||||
if replaying_seen.load(Ordering::SeqCst) {
|
||||
tracing::trace!("dropping replayed notification during session/load");
|
||||
return Ok(());
|
||||
}
|
||||
// A dropped receiver only means nobody wants updates any more.
|
||||
let _ = updates_tx.send(notification);
|
||||
Ok(())
|
||||
@@ -410,22 +440,45 @@ async fn run_connection<T>(
|
||||
let init = InitializeRequest::new(ProtocolVersion::V1)
|
||||
.client_capabilities(client_capabilities())
|
||||
.client_info(Implementation::new("maestro", env!("CARGO_PKG_VERSION")));
|
||||
if let Err(e) = cx.send_request(init).block_task().await {
|
||||
let _ = ready_tx.send(Err(ready_error(e)));
|
||||
return Ok(());
|
||||
}
|
||||
let created = match cx
|
||||
.send_request(NewSessionRequest::new(cwd))
|
||||
.block_task()
|
||||
.await
|
||||
{
|
||||
let initialized = match cx.send_request(init).block_task().await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = ready_tx.send(Err(ready_error(e)));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let session_id = created.session_id.0.to_string();
|
||||
let session_id = match load_session {
|
||||
Some(existing) => {
|
||||
if !initialized.agent_capabilities.load_session {
|
||||
let _ = ready_tx.send(Err(ReadyError::Handshake(format!(
|
||||
"{ADAPTER_BIN} does not advertise loadSession; cannot resume session {existing}"
|
||||
))));
|
||||
return Ok(());
|
||||
}
|
||||
replaying.store(true, Ordering::SeqCst);
|
||||
let loaded = cx
|
||||
.send_request(LoadSessionRequest::new(existing.clone(), cwd))
|
||||
.block_task()
|
||||
.await;
|
||||
replaying.store(false, Ordering::SeqCst);
|
||||
if let Err(e) = loaded {
|
||||
let _ = ready_tx.send(Err(ready_error(e)));
|
||||
return Ok(());
|
||||
}
|
||||
existing
|
||||
}
|
||||
None => match cx
|
||||
.send_request(NewSessionRequest::new(cwd))
|
||||
.block_task()
|
||||
.await
|
||||
{
|
||||
Ok(created) => created.session_id.0.to_string(),
|
||||
Err(e) => {
|
||||
let _ = ready_tx.send(Err(ready_error(e)));
|
||||
return Ok(());
|
||||
}
|
||||
},
|
||||
};
|
||||
let _ = ready_tx.send(Ok(session_id.clone()));
|
||||
|
||||
loop {
|
||||
|
||||
@@ -20,6 +20,15 @@ Environment knobs, all optional:
|
||||
FAKE_ACP_EXIT_AFTER_NEW=1 exit 0 right after answering `session/new`
|
||||
FAKE_ACP_EXIT_ON_CANCEL=1 exit 0 on `session/cancel` (default: keep running
|
||||
so the SIGTERM path is exercised)
|
||||
FAKE_ACP_NO_LOAD=1 advertise `loadSession: false`
|
||||
FAKE_ACP_LOAD_REPLAY=n on `session/load`, replay n `agent_message_chunk`
|
||||
notifications ("replayed <i>") before answering,
|
||||
the way a real agent streams history back
|
||||
FAKE_ACP_LOAD_FAIL=1 answer `session/load` with a JSON-RPC error
|
||||
|
||||
Signals: SIGUSR1 emits one `agent_message_chunk` notification ("tick <n>",
|
||||
counting from 1) and logs `emit tick <n>`, so a test can make the agent
|
||||
speak on demand (#135).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
@@ -49,13 +58,32 @@ def on_sigterm(_signum, _frame):
|
||||
|
||||
signal.signal(signal.SIGTERM, on_sigterm)
|
||||
|
||||
session_id = f"fake-{os.getpid()}"
|
||||
ticks = 0
|
||||
|
||||
|
||||
def chunk(text):
|
||||
return {"jsonrpc": "2.0", "method": "session/update", "params": {
|
||||
"sessionId": session_id,
|
||||
"update": {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": text}},
|
||||
}}
|
||||
|
||||
|
||||
def on_sigusr1(_signum, _frame):
|
||||
global ticks
|
||||
ticks += 1
|
||||
send(chunk(f"tick {ticks}"))
|
||||
log(f"emit tick {ticks}")
|
||||
|
||||
|
||||
signal.signal(signal.SIGUSR1, on_sigusr1)
|
||||
|
||||
log(f"start pid={os.getpid()} cwd={os.getcwd()}")
|
||||
echo = os.environ.get("FAKE_ACP_ECHO_ENV")
|
||||
if echo:
|
||||
log(f"env {echo}={os.environ.get(echo, '')}")
|
||||
|
||||
session_id = f"fake-{os.getpid()}"
|
||||
|
||||
for raw in sys.stdin:
|
||||
raw = raw.strip()
|
||||
if not raw:
|
||||
@@ -77,19 +105,26 @@ for raw in sys.stdin:
|
||||
continue
|
||||
send({"jsonrpc": "2.0", "id": rid, "result": {
|
||||
"protocolVersion": params.get("protocolVersion", 1),
|
||||
"agentCapabilities": {"loadSession": True},
|
||||
"agentCapabilities": {
|
||||
"loadSession": os.environ.get("FAKE_ACP_NO_LOAD") != "1"},
|
||||
"agentInfo": {"name": "fake-acp-agent", "version": "0.0.0"},
|
||||
"authMethods": [],
|
||||
}})
|
||||
elif method == "session/new":
|
||||
send({"jsonrpc": "2.0", "id": rid, "result": {"sessionId": session_id}})
|
||||
send({"jsonrpc": "2.0", "method": "session/update", "params": {
|
||||
"sessionId": session_id,
|
||||
"update": {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "hello from fake"}},
|
||||
}})
|
||||
send(chunk("hello from fake"))
|
||||
if os.environ.get("FAKE_ACP_EXIT_AFTER_NEW") == "1":
|
||||
sys.exit(0)
|
||||
elif method == "session/load":
|
||||
session_id = params.get("sessionId")
|
||||
log(f"recv session/load sessionId={session_id}")
|
||||
if os.environ.get("FAKE_ACP_LOAD_FAIL") == "1":
|
||||
send({"jsonrpc": "2.0", "id": rid,
|
||||
"error": {"code": -32000, "message": "fake load failure"}})
|
||||
continue
|
||||
for i in range(int(os.environ.get("FAKE_ACP_LOAD_REPLAY", "0"))):
|
||||
send(chunk(f"replayed {i + 1}"))
|
||||
send({"jsonrpc": "2.0", "id": rid, "result": {}})
|
||||
elif method == "session/cancel":
|
||||
if os.environ.get("FAKE_ACP_EXIT_ON_CANCEL") == "1":
|
||||
sys.exit(0)
|
||||
|
||||
@@ -274,6 +274,79 @@ async fn child_exit_before_handshake_reports_exited_early() {
|
||||
}
|
||||
}
|
||||
|
||||
fn chunk_text(n: &maestro_acp::schema::SessionNotification) -> String {
|
||||
match &n.update {
|
||||
SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content {
|
||||
ContentBlock::Text(t) => t.text.clone(),
|
||||
other => panic!("unexpected content {other:?}"),
|
||||
},
|
||||
other => panic!("unexpected update {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_session_resumes_the_stored_id_and_drops_the_replay() {
|
||||
let fake = Fake::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let mut config = fake.config(cwd.path()).load_session("fake-old");
|
||||
config.env.insert("FAKE_ACP_LOAD_REPLAY".into(), "3".into());
|
||||
|
||||
let session = maestro_acp::spawn(config).await.expect("spawn");
|
||||
assert_eq!(session.session_id(), "fake-old");
|
||||
let log = fake.log();
|
||||
assert!(
|
||||
log.contains("recv session/load sessionId=fake-old"),
|
||||
"{log}"
|
||||
);
|
||||
assert!(!log.contains("recv session/new"), "{log}");
|
||||
|
||||
// The three replayed chunks never reach the receiver: the event log
|
||||
// already holds them. A notification emitted after the load does.
|
||||
let mut updates = session.take_updates().expect("updates");
|
||||
unsafe {
|
||||
libc::kill(session.pid() as libc::pid_t, libc::SIGUSR1);
|
||||
}
|
||||
let first = tokio::time::timeout(Duration::from_secs(5), updates.recv())
|
||||
.await
|
||||
.expect("update within 5s")
|
||||
.expect("channel open");
|
||||
assert_eq!(chunk_text(&first), "tick 1");
|
||||
// Nothing queued behind it either.
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert!(updates.try_recv().is_err(), "replay leaked through");
|
||||
|
||||
session
|
||||
.terminate(Duration::from_millis(100), Duration::from_secs(2))
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_session_requires_the_load_capability() {
|
||||
let fake = Fake::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let mut config = fake.config(cwd.path()).load_session("fake-old");
|
||||
config.env.insert("FAKE_ACP_NO_LOAD".into(), "1".into());
|
||||
|
||||
let err = maestro_acp::spawn(config)
|
||||
.await
|
||||
.expect_err("no loadSession");
|
||||
assert!(matches!(err, AcpError::Handshake(_)), "{err}");
|
||||
assert!(err.to_string().contains("loadSession"), "{err}");
|
||||
assert!(!fake.log().contains("recv session/load"), "{}", fake.log());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_session_error_fails_the_spawn() {
|
||||
let fake = Fake::new();
|
||||
let cwd = TempDir::new().unwrap();
|
||||
let mut config = fake.config(cwd.path()).load_session("fake-old");
|
||||
config.env.insert("FAKE_ACP_LOAD_FAIL".into(), "1".into());
|
||||
|
||||
let err = maestro_acp::spawn(config).await.expect_err("load fails");
|
||||
assert!(matches!(err, AcpError::Handshake(_)), "{err}");
|
||||
assert!(err.to_string().contains("fake load failure"), "{err}");
|
||||
}
|
||||
|
||||
/// End to end against the installed `claude-code-acp`. Needs Claude auth,
|
||||
/// takes seconds, so it is opt-in: `cargo test -p maestro-acp -- --ignored`.
|
||||
#[tokio::test]
|
||||
|
||||
Reference in New Issue
Block a user