Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

acp: single daemon path — session semantics, e2e migration, in-process transport deletion, event parity (#3264)

Sebastian Müller15929ad03783
diff --git a/.changes/acp-daemon-initialize-validation.md b/.changes/acp-daemon-initialize-validation.md
new file mode 100644
index 0000000000..21100365c3
--- /dev/null
+++ b/.changes/acp-daemon-initialize-validation.md
@@ -0,0 +1 @@
+- ACP mode over the daemon now rejects an `initialize` request with invalid params (for example a string `protocolVersion`), as the TypeScript version does.
diff --git a/.changes/acp-delete-in-process-fallback.md b/.changes/acp-delete-in-process-fallback.md
new file mode 100644
index 0000000000..ca58f4dacd
--- /dev/null
+++ b/.changes/acp-delete-in-process-fallback.md
@@ -0,0 +1 @@
+- `--mode acp` no longer falls back to a separate in-process engine when the background service cannot start: it now requires the daemon, and a startup failure prints `Error:` and exits 1, like the TypeScript version. A `session/cancel` sent as a request instead of a notification now answers "method not found", like the TypeScript version.
diff --git a/.changes/acp-heartbeat-bash-updates.md b/.changes/acp-heartbeat-bash-updates.md
new file mode 100644
index 0000000000..9f408776ef
--- /dev/null
+++ b/.changes/acp-heartbeat-bash-updates.md
@@ -0,0 +1 @@
+- ACP mode now reports heartbeat schedule changes and shell commands that another client runs in the session (as tool calls), and leaves out empty tool output, like the TypeScript version.
diff --git a/.changes/acp-mcp-replace-cleanup.md b/.changes/acp-mcp-replace-cleanup.md
new file mode 100644
index 0000000000..ecaee2816b
--- /dev/null
+++ b/.changes/acp-mcp-replace-cleanup.md
@@ -0,0 +1 @@
+- ACP `session/new` now clears the connection's MCP servers when admitting them fails or times out, so servers the worker applied before a lost acknowledgement no longer stay admitted, matching the TypeScript behavior.
diff --git a/.changes/acp-rlm-quiescence.md b/.changes/acp-rlm-quiescence.md
new file mode 100644
index 0000000000..9bdbf62dcc
--- /dev/null
+++ b/.changes/acp-rlm-quiescence.md
@@ -0,0 +1 @@
+- ACP prompts now finish only once the subagents they started have finished: the completion update reports how many were still running, the final update reports zero, and cancelling or closing the session cancels them. Closing stdin no longer waits for running work to finish.
diff --git a/.changes/acp-session-flags.md b/.changes/acp-session-flags.md
new file mode 100644
index 0000000000..28c1950fd5
--- /dev/null
+++ b/.changes/acp-session-flags.md
@@ -0,0 +1 @@
+- ACP mode over the daemon now honors the session flags: without `--no-session` the conversation is saved like any other session and `--resume`, `--continue`, `--fork` and `--session-dir` open or place it; only `--no-session` sessions belong to the editor's connection and end when it disconnects, and `session/close` stops the running work without ending the session. Startup failures (an unknown or busy session) now exit with an error instead of starting, and `DO_NOT_TRACK` / the telemetry setting now also disable the daemon session's telemetry.
diff --git a/.changes/long-turn-routes.md b/.changes/long-turn-routes.md
new file mode 100644
index 0000000000..a37ed6fcf8
--- /dev/null
+++ b/.changes/long-turn-routes.md
@@ -0,0 +1 @@
+- ACP prompts and other long daemon requests (waiting for a turn, idle or headless completion, compaction, tree navigation, session start) now wait up to 24 hours like the TypeScript daemon instead of failing with "Session worker timed out" after 10 minutes, and a session worker that dies mid-request now fails it right away instead of after its restart.
diff --git a/.changes/supervisor-event-order.md b/.changes/supervisor-event-order.md
new file mode 100644
index 0000000000..3682f6fa83
--- /dev/null
+++ b/.changes/supervisor-event-order.md
@@ -0,0 +1 @@
+- The daemon now always delivers a turn's events before the reply that ends the turn, and ACP mode no longer waits up to 30 seconds after some turns before answering.
diff --git a/crates/pa-agent/src/agent.rs b/crates/pa-agent/src/agent.rs
index 1d14cfe799..974d3e1bfc 100644
--- a/crates/pa-agent/src/agent.rs
+++ b/crates/pa-agent/src/agent.rs
@@ -1066,11 +1066,6 @@ impl Agent {
self.inner.follow_up_queue.lock().unwrap().clear();
}
- pub fn clear_all_queues(&self) {
- self.clear_steering_queue();
- self.clear_follow_up_queue();
- }
-
/// Previews of the queued steering batches (TS
/// `getSteeringMessagePreviews`): one text preview per queued batch,
/// in queue order.
diff --git a/crates/pa-cli/src/interactive_mode.rs b/crates/pa-cli/src/interactive_mode.rs
index 650c74c24a..d37a75c726 100644
--- a/crates/pa-cli/src/interactive_mode.rs
+++ b/crates/pa-cli/src/interactive_mode.rs
@@ -591,17 +591,7 @@ fn build_tui_options(
// gates the completion marker, and the auth handle serves the
// not-ready branch's sign-in steps.
onboarding,
- // Only Some(true) rides the wire (TS `telemetryDisabled`), and only
- // for an environment opt-out: a settings opt-out stays the live
- // switch the session's client re-reads, so `/telemetry on`
- // resumes the running session instead of waiting for a new one.
- telemetry_disabled: matches!(
- pa_core::session_engine::telemetry::telemetry_switch(
- &pa_core::settings::SettingsManager::create(&config.cwd, &config.agent_dir)
- ),
- pa_core::session_engine::telemetry::TelemetrySwitch::Env { enabled: false, .. }
- )
- .then_some(true),
+ telemetry_disabled: crate::mode::create_telemetry_disabled(config),
// `/mcp login` / `/mcp logout`: the client-side auth flows run in
// this process (the TS interactive client's placement) and persist
// through the shared auth store the daemon's sessions read.
diff --git a/crates/pa-cli/src/mode.rs b/crates/pa-cli/src/mode.rs
index b24e995052..d8b2ba1169 100644
--- a/crates/pa-cli/src/mode.rs
+++ b/crates/pa-cli/src/mode.rs
@@ -210,6 +210,20 @@ pub fn telemetry_disabled(settings: &pa_core::settings::SettingsManager) -> bool
!pa_core::session_engine::telemetry::telemetry_switch(settings).enabled()
}
+/// The daemon session create's `telemetry_disabled` (TS `telemetryDisabled`):
+/// only an environment opt-out rides the wire. A settings opt-out stays the
+/// live switch the session's client re-reads, so `/telemetry on` resumes the
+/// running session instead of waiting for a new one.
+pub(crate) fn create_telemetry_disabled(config: &RuntimeConfig) -> Option<bool> {
+ matches!(
+ pa_core::session_engine::telemetry::telemetry_switch(
+ &pa_core::settings::SettingsManager::create(&config.cwd, &config.agent_dir)
+ ),
+ pa_core::session_engine::telemetry::TelemetrySwitch::Env { enabled: false, .. }
+ )
+ .then_some(true)
+}
+
/// Build the runtime config from parsed args, mirroring `runtimeConfigFromArgs`.
pub fn runtime_config_from_args(
parsed: &Args,
diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rs
index 411e919a17..96a2b2be53 100644
--- a/crates/pa-cli/src/print_runtime.rs
+++ b/crates/pa-cli/src/print_runtime.rs
@@ -66,8 +66,8 @@ impl crate::mode::Runtime for PrintRuntime {
}
}
}
- // ACP mode: a thin JSON-RPC stdio transport over the same
- // in-process session engine the print mode uses.
+ // ACP mode: a thin JSON-RPC stdio transport over a daemon
+ // session.
AppMode::Acp => match run_acp_mode(options) {
Ok(code) => Ok(code),
Err(error) => {
@@ -89,9 +89,11 @@ impl crate::mode::Runtime for PrintRuntime {
}
}
-/// The ACP headless mode: build the in-process session engine the same way
-/// the print mode does, then serve the ACP JSON-RPC surface over stdio until
-/// the client disconnects.
+/// The ACP headless mode (TS main.ts, `useDaemonClient`): ensure a
+/// supervisor is listening (spawning one detached), create the daemon
+/// session the CLI session flags select, and serve the ACP surface over it
+/// until the client disconnects. Any startup failure is an `Error:` exit 1
+/// before the first ACP frame.
fn run_acp_mode(options: &RunOptions) -> Result<i32, String> {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
@@ -102,113 +104,131 @@ fn run_acp_mode(options: &RunOptions) -> Result<i32, String> {
async fn acp_mode_main(options: &RunOptions) -> Result<i32, String> {
// The disclosure prints on the ACP client's stderr before any
- // transport starts, so a daemon-attached run shows it too (TS pushes
- // the daemon-created session's diagnostics to the client; the Rust
- // stderr surface prints it here without that round-trip).
+ // transport starts (TS pushes the daemon-created session's diagnostics
+ // to the client; the Rust stderr surface prints it here).
crate::telemetry_notice::print_if_due(&options.config);
- // TS `shouldUseDaemonClient` is true for the ACP mode: the daemon is
- // the preferred transport, and the in-process engine stays the
- // fallback when no daemon can be reached or served.
- if let Some(exit_code) = try_daemon_attached_acp(options).await {
- return Ok(exit_code);
- }
- let config = &options.config;
- let engine = build_headless_engine_parts(options, "acp").await?;
- let exit_code = pa_daemon::acp::run_acp_mode(pa_daemon::acp::AcpOptions {
- engine: std::sync::Arc::new(engine.engine),
- actual_cwd: config.cwd.clone(),
+ // Flag > env > default: the same `PRIME_AGENT_DAEMON_SOCKET` contract
+ // as every other mode (the `prime-agent` launcher written by
+ // install-rust.sh pins that env, so the ACP path must honor it or it
+ // would target the TypeScript default socket and treat the schema
+ // mismatch as a stale daemon).
+ let socket_path = crate::config::resolve_daemon_socket_path(options.daemon_socket.as_deref());
+ crate::interactive_mode::ensure_daemon_running(&socket_path, &options.config.cwd)
+ .await
+ .map_err(|error| format!("{error:#}"))?;
+ let (actual_cwd, create) = daemon_acp_create(options)?;
+ pa_daemon::acp::daemon::run_daemon_attached_acp_mode(pa_daemon::acp::daemon::DaemonAcpOptions {
+ socket_path,
+ actual_cwd,
product_version: crate::config::version().to_string(),
- model: Some(engine.model),
- api_key: engine.api_key,
- agent_dir: config.agent_dir.clone(),
- provider_target: engine.provider_target,
- autonomous_config: options
- .config
- .autonomous
- .as_ref()
- .map(autonomous_runtime_config),
+ create,
})
.await
- .map_err(|error| format!("{error:#}"))?;
- Ok(exit_code)
+ .map_err(|error| format!("{error:#}"))
}
-/// Try the daemon-attached ACP transport: ensure a supervisor is
-/// listening (spawning one detached, TS daemon-launch semantics), then
-/// serve the ACP surface over a client-owned daemon session. `None` means
-/// the daemon path is unavailable and the in-process engine serves the
-/// connection instead (the failure is logged to stderr, never stdout).
-async fn try_daemon_attached_acp(options: &RunOptions) -> Option<i32> {
- if std::env::var_os("PRIME_AGENT_FAUX_SCRIPT").is_some() {
- return None;
- }
- // Flag > env > default: the ACP transport resolves the same
- // `PRIME_AGENT_DAEMON_SOCKET` contract as every other mode (the
- // `prime-agent` launcher written by install-rust.sh pins that env,
- // so the ACP path must honor it or it would target the TypeScript
- // default socket and treat the schema mismatch as a stale daemon).
- let socket_path = crate::config::resolve_daemon_socket_path(options.daemon_socket.as_deref());
- let cwd = options.config.cwd.clone();
- let result = async {
- crate::interactive_mode::ensure_daemon_running(&socket_path, &cwd)
- .await
- .map_err(|error| format!("{error:#}"))?;
- let config = &options.config;
- // The session flags the in-process engine honors, under the TS
- // `runtimeConfigFromArgs` names. `--api-key` stays off: the
- // in-process path ignores it too, and the create config is persisted.
- let mut create_config = serde_json::json!({ "cwd": config.cwd.display().to_string() });
- if let Some(provider) = &config.provider {
- create_config["provider"] = serde_json::json!(provider);
- }
- if let Some(model) = &config.model {
- create_config["model"] = serde_json::json!(model);
- }
- if let Some(thinking) = config.thinking {
- create_config["thinking"] = serde_json::json!(thinking.wire_name());
- }
- if let Some(system_prompt) = &config.system_prompt {
- create_config["systemPrompt"] = serde_json::json!(system_prompt);
- }
- if !config.append_system_prompt.is_empty() {
- create_config["appendSystemPrompt"] = serde_json::json!(config.append_system_prompt);
- }
- for (key, paths) in [
- ("skills", &config.skills),
- ("promptTemplates", &config.prompt_templates),
- ] {
- if !paths.is_empty() {
- create_config[key] = paths
- .iter()
- .map(|path| path.display().to_string())
- .collect::<Vec<_>>()
- .into();
- }
- }
- if let Some(autonomous) = &config.autonomous {
- create_config["autonomous"] = serde_json::json!(autonomous_runtime_config(autonomous));
- }
- pa_daemon::acp::daemon::run_daemon_attached_acp_mode(
- pa_daemon::acp::daemon::DaemonAcpOptions {
- socket_path,
- actual_cwd: config.cwd.clone(),
- product_version: crate::config::version().to_string(),
- create_config,
- },
+/// The ACP daemon session's create (TS main.ts `defaultSessionConfig` +
+/// the startup create): the session the flags select, client-owned only
+/// for `--no-session`, plus the session's cwd. The worker opens and
+/// leases the selected file itself.
+fn daemon_acp_create(
+ options: &RunOptions,
+) -> Result<(std::path::PathBuf, pa_types::daemon::DaemonCommand), String> {
+ use pa_types::daemon::DaemonSessionLifecycle;
+ let config = &options.config;
+ let session_dir = replacement_session_dir(options);
+ let (cwd, session_path, lifecycle) = if options.session.no_session {
+ (
+ config.cwd.clone(),
+ None,
+ DaemonSessionLifecycle::ClientOwned,
)
- .await
- .map_err(|error| format!("{error:#}"))
+ } else {
+ let (cwd, session_path) = match select_headless_session(options)? {
+ HeadlessSession::Fork(source) => {
+ let fork = pa_core::session::manager::SessionManager::fork_from(
+ &source,
+ &config.cwd,
+ &session_dir,
+ )?;
+ (
+ config.cwd.clone(),
+ fork.get_session_file().map(std::path::Path::to_path_buf),
+ )
+ }
+ HeadlessSession::Open(path) => (
+ stored_session_cwd(&path, &config.cwd, explicit_cwd_override(options))?,
+ Some(path),
+ ),
+ HeadlessSession::Fresh => (config.cwd.clone(), None),
+ };
+ (cwd, session_path, DaemonSessionLifecycle::Resident)
+ };
+ // The CLI session flags, under the TS `runtimeConfigFromArgs`
+ // names. `--api-key` stays off: the create config is persisted.
+ let mut create_config = serde_json::json!({
+ "cwd": cwd.display().to_string(),
+ "sessionDir": session_dir.display().to_string(),
+ // The telemetry execution mode (TS main.ts `executionMode: appMode`).
+ "executionMode": "acp",
+ });
+ if let Some(provider) = &config.provider {
+ create_config["provider"] = serde_json::json!(provider);
}
- .await;
- match result {
- Ok(code) => Some(code),
- Err(error) => {
- eprintln!(
- "prime-agent: daemon-attached ACP unavailable, using in-process mode: {error}"
- );
- None
+ if let Some(model) = &config.model {
+ create_config["model"] = serde_json::json!(model);
+ }
+ if let Some(thinking) = config.thinking {
+ create_config["thinking"] = serde_json::json!(thinking.wire_name());
+ }
+ if let Some(system_prompt) = &config.system_prompt {
+ create_config["systemPrompt"] = serde_json::json!(system_prompt);
+ }
+ if !config.append_system_prompt.is_empty() {
+ create_config["appendSystemPrompt"] = serde_json::json!(config.append_system_prompt);
+ }
+ for (key, paths) in [
+ ("skills", &config.skills),
+ ("promptTemplates", &config.prompt_templates),
+ ] {
+ if !paths.is_empty() {
+ create_config[key] = paths
+ .iter()
+ .map(|path| path.display().to_string())
+ .collect::<Vec<_>>()
+ .into();
}
}
+ if let Some(autonomous) = &config.autonomous {
+ create_config["autonomous"] = serde_json::json!(autonomous_runtime_config(autonomous));
+ }
+ // Verification seam (the interactive mode's contract): a scripted daemon
+ // session from a script FILE path. The product never sets it.
+ if let Some(script) = std::env::var_os("PRIME_AGENT_FAUX_SCRIPT") {
+ create_config["script"] = serde_json::Value::String(script.to_string_lossy().to_string());
+ }
+ // Verification seam (the TS child runtime inherits the parent's
+ // `sessionConfig`): a scripted parent session's children run this script
+ // FILE. The product never sets it.
+ if let Some(child_script) = std::env::var_os("PRIME_AGENT_FAUX_CHILD_SCRIPT") {
+ create_config["childScript"] =
+ serde_json::Value::String(child_script.to_string_lossy().to_string());
+ }
+ let create = pa_types::daemon::DaemonCommand::Create {
+ id: None,
+ session_path: session_path.map(|path| path.display().to_string()),
+ continue_recent: None,
+ no_session: options.session.no_session.then_some(true),
+ name: None,
+ config: Some(create_config),
+ telemetry_disabled: crate::mode::create_telemetry_disabled(config),
+ runtime_metadata: None,
+ lifecycle: Some(lifecycle),
+ env: None,
+ launch_env: None,
+ rest: serde_json::Map::default(),
+ };
+ Ok((cwd, create))
}
/// The RPC headless mode: build the in-process session engine the print
@@ -417,7 +437,7 @@ async fn print_mode_main(options: &RunOptions) -> Result<i32, String> {
/// network; verification harness only, never set by the product.
///
/// The switchable provider target the session's stream reads per call
-/// (shared with the ACP mode, whose picker model switches swap it live).
+/// (shared with the RPC mode, whose picker model switches swap it live).
pub type ProviderTargetSlot = std::sync::Arc<std::sync::RwLock<Option<ProviderTarget>>>;
/// The assembled headless engine plus the model and request auth it runs
@@ -428,7 +448,7 @@ struct HeadlessEngine {
model: Model,
api_key: Option<String>,
/// The live provider target: the stream reads it per call, and the
- /// ACP mode's picker switches swap it (TS `setModel`'s stream
+ /// RPC mode's picker switches swap it (TS `setModel`'s stream
/// re-registration; `set_model` swaps it without rebuilding the
/// session).
provider_target: ProviderTargetSlot,
@@ -1000,29 +1020,30 @@ fn resolve_thinking_level(
map_thinking_level(clamped)
}
-/// The headless session-manager resolution, mirroring the flag order of
-/// TS `createSessionManager` (noSession -> fork -> resume -> continue ->
-/// create). `--no-session` never reaches here: the caller passes `None` to
-/// the engine, which builds the in-memory manager itself. The opened
-/// session's runtime lease returns alongside (a long-lived connection
-/// holds it on the engine handle; the one-shot modes forget it for the
-/// process lifetime).
-fn build_session_manager_with_lease(
- options: &RunOptions,
-) -> Result<
- (
- pa_core::session::manager::SessionManager,
- Option<pa_daemon::lease::SessionLease>,
- ),
- String,
-> {
- use pa_core::session::manager::SessionManager;
- let cwd = options.config.cwd.clone();
- let session_dir = options
+/// The headless session selection, in the flag order of TS
+/// `createSessionManager` (noSession -> fork -> resume -> continue ->
+/// create). `--no-session` never reaches here: its callers skip the
+/// selection.
+enum HeadlessSession {
+ /// Fork this source session into a fresh file.
+ Fork(std::path::PathBuf),
+ /// Open this existing session file.
+ Open(std::path::PathBuf),
+ Fresh,
+}
+
+/// main.ts `explicitCwdOverride`: with --cwd, the flag's directory wins
+/// over the stored session cwd on resume.
+fn explicit_cwd_override(options: &RunOptions) -> Option<&std::path::Path> {
+ options
.session
- .session_dir
- .clone()
- .unwrap_or_else(|| options.config.agent_dir.join("sessions"));
+ .cwd_from_flag
+ .then_some(options.config.cwd.as_path())
+}
+
+fn select_headless_session(options: &RunOptions) -> Result<HeadlessSession, String> {
+ let cwd = &options.config.cwd;
+ let session_dir = replacement_session_dir(options);
// TS `createSessionManager`'s fork arm: every resolution shape forks —
// a GLOBAL session is exactly what --fork is for (a different
// project's session copied into this cwd) — with no daemon-active
@@ -1032,39 +1053,29 @@ fn build_session_manager_with_lease(
// selector's convention; the interactive fork arm matches).
let expanded = crate::config::expand_tilde_path(selector);
let selector = expanded.to_string_lossy();
- let resolved = resolve_session_path(&selector, &cwd, &session_dir)
+ let resolved = resolve_session_path(&selector, cwd, &session_dir)
.map_err(|error| render_selector_error(&error))?;
let source = match resolved {
ResolvedSession::Path(path)
| ResolvedSession::Local(path)
| ResolvedSession::Global { path, .. } => path,
};
- let manager = SessionManager::fork_from(&source, &cwd, &session_dir)?;
- // The materialized fork leases its own file before the engine
- // writes it (the fresh-session rule): another process resuming
- // the new file can never become a second writer while this
- // engine appends — the source was only read, never leased.
- return Ok(lease_fresh_manager(manager));
+ return Ok(HeadlessSession::Fork(source));
}
- // main.ts `explicitCwdOverride`: with --cwd, the flag's directory wins
- // over the stored session cwd on resume.
- let explicit_cwd_override = options.session.cwd_from_flag.then_some(cwd.as_path());
if let Some(selector) = &options.session.resume {
- let resolved = resolve_session_path(selector, &cwd, &session_dir)
+ let resolved = resolve_session_path(selector, cwd, &session_dir)
.map_err(|error| render_selector_error(&error))?;
return match resolved {
ResolvedSession::Path(path) | ResolvedSession::Local(path) => {
- let lease = session_open_guard(options.daemon_socket.as_deref(), &path)?;
- // A failed open's early return drops the lease (released),
- // never leaving an orphaned hold behind.
- let manager = open_session_file(&path, &session_dir, &cwd, explicit_cwd_override)?;
- Ok((manager, Some(lease)))
+ Ok(HeadlessSession::Open(
+ std::path::absolute(&path).map_err(|error| error.to_string())?,
+ ))
}
ResolvedSession::Global {
path: _,
cwd: session_cwd,
} => {
- // Print mode has no fork prompt; mirror the TS non-TTY path.
+ // Headless modes have no fork prompt; mirror the TS non-TTY path.
Err(format!(
"session {selector} belongs to a different project ({}). Pass --fork {selector} to use it here, or run from that project's directory.",
session_cwd.display()
@@ -1073,17 +1084,51 @@ fn build_session_manager_with_lease(
};
}
if options.session.continue_recent {
- let most_recent = find_most_recent_session_for_cwd(&session_dir, &cwd);
- return match most_recent {
- Some(path) => {
- let lease = session_open_guard(options.daemon_socket.as_deref(), &path)?;
- let manager = open_session_file(&path, &session_dir, &cwd, explicit_cwd_override)?;
- Ok((manager, Some(lease)))
- }
- None => Ok(fresh_session_with_lease(&cwd, &session_dir)),
- };
+ // Absolute like the resume arm (TS `setSessionFile` resolves it).
+ if let Some(path) = find_most_recent_session_for_cwd(&session_dir, cwd) {
+ return Ok(HeadlessSession::Open(
+ std::path::absolute(&path).map_err(|error| error.to_string())?,
+ ));
+ }
+ }
+ Ok(HeadlessSession::Fresh)
+}
+
+/// The in-process session manager for the selected session. The opened
+/// session's runtime lease returns alongside (a long-lived connection
+/// holds it on the engine handle; the one-shot modes forget it for the
+/// process lifetime).
+fn build_session_manager_with_lease(
+ options: &RunOptions,
+) -> Result<
+ (
+ pa_core::session::manager::SessionManager,
+ Option<pa_daemon::lease::SessionLease>,
+ ),
+ String,
+> {
+ let cwd = options.config.cwd.clone();
+ let session_dir = replacement_session_dir(options);
+ match select_headless_session(options)? {
+ HeadlessSession::Fork(source) => {
+ let manager =
+ pa_core::session::manager::SessionManager::fork_from(&source, &cwd, &session_dir)?;
+ // The materialized fork leases its own file before the engine
+ // writes it (the fresh-session rule): another process resuming
+ // the new file can never become a second writer while this
+ // engine appends — the source was only read, never leased.
+ Ok(lease_fresh_manager(manager))
+ }
+ HeadlessSession::Open(path) => {
+ let lease = session_open_guard(options.daemon_socket.as_deref(), &path)?;
+ // A failed open's early return drops the lease (released),
+ // never leaving an orphaned hold behind.
+ let manager =
+ open_session_file(&path, &session_dir, &cwd, explicit_cwd_override(options))?;
+ Ok((manager, Some(lease)))
+ }
+ HeadlessSession::Fresh => Ok(fresh_session_with_lease(&cwd, &session_dir)),
}
- Ok(fresh_session_with_lease(&cwd, &session_dir))
}
/// Build a FRESH persisted manager and lease its eagerly selected file
@@ -1244,6 +1289,23 @@ fn open_session_file(
fallback_cwd: &std::path::Path,
explicit_cwd_override: Option<&std::path::Path>,
) -> Result<pa_core::session::manager::SessionManager, String> {
+ let session_cwd = stored_session_cwd(path, fallback_cwd, explicit_cwd_override)?;
+ Ok(pa_core::session::manager::SessionManager::open(
+ &session_cwd,
+ session_dir,
+ path,
+ ))
+}
+
+/// The cwd an opened session runs in: the explicit override (main.ts
+/// `explicitCwdOverride`), else the stored session cwd, else the
+/// fallback. A session stored against a deleted directory must not
+/// silently continue somewhere else (main.ts `getMissingSessionCwdIssue`).
+fn stored_session_cwd(
+ path: &std::path::Path,
+ fallback_cwd: &std::path::Path,
+ explicit_cwd_override: Option<&std::path::Path>,
+) -> Result<std::path::PathBuf, String> {
let session_cwd = explicit_cwd_override.map_or_else(
|| {
let header = pa_core::session::manager::read_session_header(path);
@@ -1254,21 +1316,15 @@ fn open_session_file(
},
std::path::Path::to_path_buf,
);
- let manager = pa_core::session::manager::SessionManager::open(&session_cwd, session_dir, path);
- // main.ts getMissingSessionCwdIssue: a session stored against a deleted
- // directory must not silently continue somewhere else.
- if !manager.get_cwd().exists() {
- let session_file = manager
- .get_session_file()
- .map(|path| format!("\nSession file: {}", path.display()))
- .unwrap_or_default();
+ if !session_cwd.exists() {
return Err(format!(
- "Stored session working directory does not exist: {}{session_file}\nCurrent working directory: {}",
- manager.get_cwd().display(),
+ "Stored session working directory does not exist: {}\nSession file: {}\nCurrent working directory: {}",
+ session_cwd.display(),
+ path.display(),
fallback_cwd.display()
));
}
- Ok(manager)
+ Ok(session_cwd)
}
/// Render a selector failure with the main.ts formatting: the error message
diff --git a/crates/pa-cli/tests/acp_config_option_e2e.rs b/crates/pa-cli/tests/acp_config_option_e2e.rs
index c3ab8675b4..abc0db9d7d 100644
--- a/crates/pa-cli/tests/acp_config_option_e2e.rs
+++ b/crates/pa-cli/tests/acp_config_option_e2e.rs
@@ -19,14 +19,17 @@
//! ACP picker e2e (the TS #2455 port): `session/new` advertises the
//! standard `model` and `thought_level` select options, and
-//! `session/set_config_option` applies selections — the effort picker
-//! follows the selected model's supported levels, invalid values are
+//! `session/set_config_option` applies selections — the effort select
+//! offers the session model's supported levels, invalid values are
//! `-32602` invalid params, and real selections publish the
-//! `config_option_update` notification.
+//! `config_option_update` notification. Model switches are observable:
+//! the faux worker resolves a switched selection through the registry
+//! (a models.json faux-api model streams through the same scripted
+//! provider), so the pickers follow the switch.
//!
-//! Both transports are covered: the in-process mode (the faux provider
-//! with a models.json fixture model, so a switch is observable end to
-//! end) and the daemon-attached mode (the worker's own wire commands).
+//! The daemon-attached transport covers the surface: the pickers ride
+//! the worker's own wire commands, with a models.json fixture in the
+//! agent dir for discovery.
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, Command, Stdio};
@@ -42,71 +45,11 @@ struct AcpChild {
stdin: std::process::ChildStdin,
lines: Receiver<String>,
next_id: u64,
- /// Held so the child's cwd outlives the process.
- home: tempfile::TempDir,
+ /// Held (never read) so the child's cwd outlives the process.
+ _home: tempfile::TempDir,
}
impl AcpChild {
- /// Spawn the ACP binary with a models.json fixture in place before the
- /// process starts (discovery reads it through the registry).
- fn spawn_with_models(
- args: &[&str],
- script: &serde_json::Value,
- models_json: Option<serde_json::Value>,
- extra_env: &[(String, String)],
- ) -> AcpChild {
- let home = tempfile::TempDir::new().unwrap();
- let agent_dir = home.path().join("agent");
- std::fs::create_dir_all(&agent_dir).unwrap();
- if let Some(models) = models_json {
- std::fs::write(agent_dir.join("models.json"), models.to_string()).unwrap();
- }
- let bin = env!("CARGO_BIN_EXE_prime-agent");
- let mut command = Command::new(bin);
- command
- .args(args)
- .env("HOME", home.path())
- // The CLI's agent dir (`PRIME_AGENT_CODING_AGENT_DIR`) is where
- // the registry reads models.json from; the runtime env name
- // rides along for the kernel-side paths.
- .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)
- .env("PRIME_AGENT_AGENT_DIR", &agent_dir)
- .env("PRIME_AGENT_FAUX_SCRIPT", script.to_string());
- for (key, value) in extra_env {
- command.env(key, value);
- }
- let mut child = command
- .current_dir(home.path())
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .expect("binary present");
- let stdin = child.stdin.take().expect("stdin piped");
- let stdout = child.stdout.take().expect("stdout piped");
- let (tx, lines) = channel();
- std::thread::spawn(move || {
- let reader = BufReader::new(stdout);
- for line in reader.lines() {
- match line {
- Ok(line) => {
- if tx.send(line).is_err() {
- return;
- }
- }
- Err(_) => return,
- }
- }
- });
- AcpChild {
- child,
- stdin,
- lines,
- next_id: 0,
- home,
- }
- }
-
fn send(&mut self, frame: &Value) {
let mut line = serde_json::to_string(&frame).unwrap();
line.push('\n');
@@ -236,67 +179,104 @@ fn faux_models_fixture() -> serde_json::Value {
"maxTokens": 4_096,
}
],
- },
- // A provider whose models discovery admits (the `authHeader`
- // config counts as configured request auth) but whose
- // credential cannot resolve at request time (a set-but-empty
- // env var is a missing credential): a switch to it must refuse
- // before anything moves, not install an unauthenticated
- // target.
- "locked": {
- "api": "faux",
- "baseUrl": "http://localhost:0",
- "authHeader": true,
- "apiKey": "PROBE_LOCKED_KEY",
- "models": [
- {
- "id": "locked-model",
- "name": "Locked Model",
- "api": "faux",
- "baseUrl": "http://localhost:0",
- "contextWindow": 128_000,
- "maxTokens": 4_096,
- }
- ],
}
}
})
}
-/// The in-process transport: the pickers are advertised at `session/new`,
-/// applied through `session/set_config_option` (a real model switch —
-/// the engine and the provider target follow), invalid values are invalid
-/// params, and changes publish `config_option_update`.
+/// The daemon-attached transport: the pickers ride the worker's own wire
+/// commands — advertised at `session/new`, the effort selection applied
+/// through `set_thinking_level`, invalid values refused, and a real
+/// model switch observable (the plain model drops the effort picker, the
+/// map model accepts `xhigh`, and the turn after a switch settles).
#[test]
-fn acp_in_process_config_option_advertises_and_applies() {
- let script = json!({
- "reasoning": true,
- "responses": ["one answer", "the switched model still streams"],
- });
- let mut client = AcpChild::spawn_with_models(
- &["--mode", "acp", "--no-session"],
- &script,
- Some(faux_models_fixture()),
- // The locked provider's credential reference resolves to nothing:
- // a set-but-empty env var is a missing credential.
- &[("PROBE_LOCKED_KEY".to_string(), String::new())],
- );
+fn acp_daemon_attached_config_option_pickers() {
+ let home = tempfile::TempDir::new().unwrap();
+ let socket = home.path().join("daemon.sock");
+ let agent_dir = home.path().join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ // The worker inherits the CLI's agent dir, so the fixture models ride
+ // the same discovery.
+ std::fs::write(
+ agent_dir.join("models.json"),
+ faux_models_fixture().to_string(),
+ )
+ .unwrap();
+ let script_path = home.path().join("worker-script.json");
+ std::fs::write(
+ &script_path,
+ json!({
+ "engine": "faux",
+ "reasoning": true,
+ "responses": ["The Thames flows through London.", "The switched model still streams."],
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let bin = env!("CARGO_BIN_EXE_prime-agent");
+ let mut child = Command::new(bin)
+ .args([
+ "--mode",
+ "acp",
+ "--no-session",
+ "--daemon-socket",
+ socket.to_str().unwrap(),
+ ])
+ .env("HOME", home.path())
+ .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)
+ .env("PRIME_AGENT_FAUX_SCRIPT", &script_path)
+ .env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ )
+ .current_dir(home.path())
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("binary present");
+ let stdin = child.stdin.take().expect("stdin piped");
+ let stdout = child.stdout.take().expect("stdout piped");
+ let mut client = {
+ let (tx, rx) = channel();
+ std::thread::spawn(move || {
+ let reader = BufReader::new(stdout);
+ for line in reader.lines() {
+ match line {
+ Ok(line) => {
+ if tx.send(line).is_err() {
+ return;
+ }
+ }
+ Err(_) => return,
+ }
+ }
+ });
+ AcpChild {
+ child,
+ stdin,
+ lines: rx,
+ next_id: 0,
+ _home: home,
+ }
+ };
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
let new = client.request("session/new", &json!({ "mcpServers": [] }));
let (new_response, _) = client.wait_response(new, TIMEOUT);
let result = &new_response["result"];
+ assert!(
+ result["sessionId"].is_string(),
+ "daemon-attached admission succeeds: {new_response}"
+ );
let session_id = result["sessionId"].as_str().unwrap().to_string();
- // Both pickers advertised: the model select (current model always
- // selectable, the discovered fixture model listed) and the effort
- // select on the reasoning model's supported levels.
+ // Both pickers advertised off the worker's connection state: the
+ // model select (current model always selectable, the discovered
+ // fixture model listed) and the effort select on the reasoning
+ // model's supported levels.
let options = &result["configOptions"];
- assert_eq!(
- options.as_array().map(Vec::len),
- Some(2),
- "two options: {options}"
- );
+ assert_eq!(options.as_array().map(Vec::len), Some(2), "{options}");
let model_option = &options[0];
assert_eq!(model_option["id"], "model");
assert_eq!(model_option["type"], "select");
@@ -324,7 +304,8 @@ fn acp_in_process_config_option_advertises_and_applies() {
.collect();
assert_eq!(levels, vec!["off", "minimal", "low", "medium", "high"]);
- // A valid effort selection applies and publishes the change.
+ // An effort selection applies through the worker's switch and
+ // publishes the change.
let select = client.request(
"session/set_config_option",
&select_params(&session_id, "thought_level", &json!("high")),
@@ -332,7 +313,7 @@ fn acp_in_process_config_option_advertises_and_applies() {
let (response, notifications) = client.wait_response(select, TIMEOUT);
assert_eq!(
response["result"]["configOptions"][1]["currentValue"], "high",
- "the effort picker follows the selection: {response}"
+ "{response}"
);
let updates = config_updates(&notifications);
assert!(
@@ -342,14 +323,14 @@ fn acp_in_process_config_option_advertises_and_applies() {
"the change publishes config_option_update: {notifications:?}"
);
- // Invalid selections are invalid params with the TS reasons.
+ // Unsupported levels and models are refused with the TS reasons.
for (config_id, value, reason) in [
- ("model", json!("missing"), "Unavailable model: missing"),
(
"thought_level",
json!("sideways"),
"Unsupported reasoning effort: sideways",
),
+ ("model", json!("missing"), "Unavailable model: missing"),
(
"unknown",
json!("high"),
@@ -375,7 +356,6 @@ fn acp_in_process_config_option_advertises_and_applies() {
response["error"]["data"]["reason"],
"Unknown ACP session: missing-session"
);
-
// A real model switch: the plain model drops the effort picker (its
// supported levels are `off` only) and the effort selection now
// refuses.
@@ -412,7 +392,7 @@ fn acp_in_process_config_option_advertises_and_applies() {
"session/prompt",
&json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "hello" }] }),
);
- let (prompt_response, _) = client.wait_response(prompt, TIMEOUT);
+ let (prompt_response, _) = client.wait_response(prompt, Duration::from_mins(2));
assert_eq!(prompt_response["result"]["stopReason"], "end_turn");
// Switching back restores the effort picker at the persisted default
@@ -480,273 +460,6 @@ fn acp_in_process_config_option_advertises_and_applies() {
"the mapped level publishes config_option_update: {notifications:?}"
);
- // An uncredentialed model discovery admits (the locked provider's
- // auth cannot resolve): the switch refuses BEFORE anything moves —
- // the next turn keeps running on the model it still reports.
- let locked = r#"["locked","locked-model"]"#;
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "model", &json!(locked)),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(response["error"]["code"], -32603, "{response}");
- assert!(
- response["error"]["data"]["details"]
- .as_str()
- .unwrap_or_default()
- .contains("No API key found"),
- "the refusal names the missing credentials: {response}"
- );
- // Nothing moved: the map model is still the live selection (the
- // no-op re-selection refreshes and reports it).
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "model", &json!(map)),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(
- response["result"]["configOptions"][0]["currentValue"], map,
- "the uncredentialed switch mutated nothing: {response}"
- );
-
- let close = client.request("session/close", &json!({ "sessionId": session_id }));
- let (close_response, _) = client.wait_response(close, TIMEOUT);
- assert_eq!(close_response["result"], json!({}));
-}
-
-/// The in-process transport's failed settings persist: the switch's live
-/// state is applied COHERENTLY (TS `setModel` rejects after the model
-/// assignment and the durable row, with the switched session applied),
-/// never split — `current_model()` and the agent agree on the switched
-/// model even when the settings write fails, so the effort gate answers
-/// for the model the turns run on. The settings write fails because the
-/// global settings file is a directory (the lock step cannot read it).
-#[test]
-fn acp_in_process_failed_settings_persist_keeps_the_session_coherent() {
- let script = json!({
- "reasoning": true,
- "responses": ["one answer", "still streaming on the switched model"],
- });
- let mut client = AcpChild::spawn_with_models(
- &["--mode", "acp", "--no-session"],
- &script,
- Some(faux_models_fixture()),
- &[],
- );
- // The global settings file as a directory: every settings write
- // fails at its read step, deterministically.
- std::fs::create_dir_all(client.home.path().join("agent").join("settings.json")).unwrap();
- let init = client.request("initialize", &initialize_params());
- let _ = client.wait_response(init, TIMEOUT);
- let new = client.request("session/new", &json!({ "mcpServers": [] }));
- let (new_response, _) = client.wait_response(new, TIMEOUT);
- let result = &new_response["result"];
- let session_id = result["sessionId"].as_str().unwrap().to_string();
- assert_eq!(
- result["configOptions"].as_array().map(Vec::len),
- Some(2),
- "the admission is unaffected: {result}"
- );
-
- // The switch fails at the settings persist (the live switch and the
- // durable row already ran): the RPC reports the failure...
- let plain = r#"["faux","plain-model"]"#;
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "model", &json!(plain)),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(response["error"]["code"], -32603, "{response}");
- assert!(
- response["error"]["data"]["details"]
- .as_str()
- .unwrap_or_default()
- .contains("model switch failed"),
- "the refusal names the switch: {response}"
- );
-
- // ...but the session is NOT split: the effort gate answers for the
- // model the turns run on (the switched plain model), so `high` is
- // unsupported — a stale pre-switch slot would have accepted it.
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "thought_level", &json!("high")),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(response["error"]["code"], -32602, "{response}");
- assert_eq!(
- response["error"]["data"]["reason"],
- "Unsupported reasoning effort: high"
- );
-
- // The live session runs the switched model (TS's reject-with-state-
- // applied): the no-op re-selection refreshes and reports it...
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "model", &json!(plain)),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(
- response["result"]["configOptions"][0]["currentValue"], plain,
- "the switched model is live and reported: {response}"
- );
- assert_eq!(
- response["result"]["configOptions"].as_array().map(Vec::len),
- Some(1),
- "the plain model serves no effort picker: {response}"
- );
-
- // ...and the next turn still streams on it.
- let prompt = client.request(
- "session/prompt",
- &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "hello" }] }),
- );
- let (prompt_response, _) = client.wait_response(prompt, TIMEOUT);
- assert_eq!(prompt_response["result"]["stopReason"], "end_turn");
-
- let close = client.request("session/close", &json!({ "sessionId": session_id }));
- let (close_response, _) = client.wait_response(close, TIMEOUT);
- assert_eq!(close_response["result"], json!({}));
-}
-
-/// The daemon-attached transport: the pickers ride the worker's own wire
-/// commands — advertised at `session/new`, the effort selection applied
-/// through `set_thinking_level`, invalid values refused, and the turn
-/// after a switch still settles.
-#[test]
-fn acp_daemon_attached_config_option_pickers() {
- let home = tempfile::TempDir::new().unwrap();
- let socket = home.path().join("daemon.sock");
- let script_path = home.path().join("worker-script.json");
- std::fs::write(
- &script_path,
- json!({
- "engine": "faux",
- "reasoning": true,
- "responses": ["The Thames flows through London."],
- })
- .to_string(),
- )
- .unwrap();
- let bin = env!("CARGO_BIN_EXE_prime-agent");
- let mut child = Command::new(bin)
- .args([
- "--mode",
- "acp",
- "--no-session",
- "--daemon-socket",
- socket.to_str().unwrap(),
- ])
- .env("HOME", home.path())
- .env("PRIME_AGENT_CODING_AGENT_DIR", home.path().join("agent"))
- .env("PRIME_AGENT_AGENT_DIR", home.path().join("agent"))
- .env("PRIME_AGENT_ACP_DAEMON_SCRIPT", &script_path)
- .env(
- pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
- "15000",
- )
- .current_dir(home.path())
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .expect("binary present");
- let stdin = child.stdin.take().expect("stdin piped");
- let stdout = child.stdout.take().expect("stdout piped");
- let mut client = {
- let (tx, rx) = channel();
- std::thread::spawn(move || {
- let reader = BufReader::new(stdout);
- for line in reader.lines() {
- match line {
- Ok(line) => {
- if tx.send(line).is_err() {
- return;
- }
- }
- Err(_) => return,
- }
- }
- });
- AcpChild {
- child,
- stdin,
- lines: rx,
- next_id: 0,
- home,
- }
- };
- let init = client.request("initialize", &initialize_params());
- let _ = client.wait_response(init, TIMEOUT);
- let new = client.request("session/new", &json!({ "mcpServers": [] }));
- let (new_response, _) = client.wait_response(new, TIMEOUT);
- let result = &new_response["result"];
- assert!(
- result["sessionId"].is_string(),
- "daemon-attached admission succeeds: {new_response}"
- );
- let session_id = result["sessionId"].as_str().unwrap().to_string();
-
- // Both pickers advertised off the worker's connection state.
- let options = &result["configOptions"];
- assert_eq!(options.as_array().map(Vec::len), Some(2), "{options}");
- assert_eq!(options[0]["id"], "model");
- assert_eq!(options[0]["currentValue"], r#"["faux","faux-1"]"#);
- assert_eq!(options[1]["id"], "thought_level");
- assert_eq!(options[1]["currentValue"], "medium");
-
- // An effort selection applies through the worker's switch and
- // publishes the change.
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "thought_level", &json!("high")),
- );
- let (response, notifications) = client.wait_response(select, TIMEOUT);
- assert_eq!(
- response["result"]["configOptions"][1]["currentValue"], "high",
- "{response}"
- );
- let updates = config_updates(&notifications);
- assert!(
- updates
- .iter()
- .any(|update| update["params"]["update"]["configOptions"][1]["currentValue"] == "high"),
- "the change publishes config_option_update: {notifications:?}"
- );
-
- // Unsupported levels and models are refused with the TS reasons; the
- // current model re-selects cleanly.
- for (config_id, value, reason) in [
- (
- "thought_level",
- json!("sideways"),
- "Unsupported reasoning effort: sideways",
- ),
- ("model", json!("missing"), "Unavailable model: missing"),
- (
- "unknown",
- json!("high"),
- "Invalid configuration option: unknown",
- ),
- ] {
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, config_id, &value),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(response["error"]["code"], -32602, "{config_id}: {response}");
- assert_eq!(response["error"]["data"]["reason"], reason);
- }
- let select = client.request(
- "session/set_config_option",
- &select_params(&session_id, "model", &json!(r#"["faux","faux-1"]"#)),
- );
- let (response, _) = client.wait_response(select, TIMEOUT);
- assert_eq!(
- response["result"]["configOptions"][0]["currentValue"],
- r#"["faux","faux-1"]"#
- );
-
// The switched level survives a turn: the prompt still settles.
let prompt = client.request(
"session/prompt",
diff --git a/crates/pa-cli/tests/acp_mode_e2e.rs b/crates/pa-cli/tests/acp_mode_e2e.rs
index 188e999195..d53e3c3959 100644
--- a/crates/pa-cli/tests/acp_mode_e2e.rs
+++ b/crates/pa-cli/tests/acp_mode_e2e.rs
@@ -17,9 +17,10 @@
clippy::cast_precision_loss
)]
-//! End-to-end ACP-mode verification: the real binary speaks the ACP
-//! JSON-RPC surface over stdio, driven by the scripted faux provider, and
-//! the emitted frames are checked against the TS capture corpus
+//! End-to-end ACP-mode verification: the real binary serves the ACP
+//! JSON-RPC surface over stdio on the daemon-attached transport (a
+//! sandboxed supervisor hosting a scripted faux worker), and the emitted
+//! frames are checked against the TS capture corpus
//! (`crates/pa-daemon/testdata/acp`).
use std::io::{BufRead, BufReader, Write};
@@ -33,25 +34,31 @@ use serde_json::{json, Value};
/// child process (its cwd), so it is held on the struct.
struct AcpChild {
child: Child,
- stdin: std::process::ChildStdin,
+ /// `None` once [`AcpChild::close_stdin`] sent EOF.
+ stdin: Option<std::process::ChildStdin>,
lines: Receiver<String>,
next_id: u64,
/// Held (never read) so the child's cwd directory outlives the process:
/// dropping the tempdir deletes it and the child's `current_dir` fails.
- _home: tempfile::TempDir,
+ /// `None` for a second child sharing another child's home.
+ _home: Option<tempfile::TempDir>,
spawn_stderr: Option<std::process::ChildStderr>,
- /// The sandboxed supervisor socket a daemon-attached child spawned:
- /// set only by [`AcpChild::spawn_daemon_attached`], and the drop shuts
+ /// The sandboxed supervisor socket the child spawned: the drop shuts
/// the supervisor down with it (a killed child must not leak the
/// supervisor into later test binaries).
- daemon_socket: Option<std::path::PathBuf>,
+ socket: std::path::PathBuf,
}
impl AcpChild {
/// Wire one spawned process into the reader thread and the handle:
/// the tempdir is held on the struct so the child's cwd directory
- /// outlives the process.
- fn wrap(mut child: std::process::Child, home: tempfile::TempDir) -> AcpChild {
+ /// outlives the process, and the supervisor socket is the one the
+ /// drop shuts down.
+ fn wrap(
+ mut child: std::process::Child,
+ home: Option<tempfile::TempDir>,
+ socket: std::path::PathBuf,
+ ) -> AcpChild {
let stdin = child.stdin.take().expect("stdin piped");
let stdout = child.stdout.take().expect("stdout piped");
let stderr = child.stderr.take().expect("stderr piped");
@@ -71,78 +78,65 @@ impl AcpChild {
});
AcpChild {
child,
- stdin,
+ stdin: Some(stdin),
lines,
next_id: 0,
_home: home,
spawn_stderr: Some(stderr),
- daemon_socket: None,
+ socket,
}
}
+ /// The daemon-attached transport: the child spawns its own sandboxed
+ /// supervisor on `<home>/daemon.sock` and hosts the scripted worker
+ /// through the `PRIME_AGENT_FAUX_SCRIPT` create-config seam;
+ /// the drop shuts the supervisor down. The socket sits on the struct
+ /// for tests that speak raw daemon commands alongside the ACP frames.
fn spawn(args: &[&str], script: &serde_json::Value) -> AcpChild {
let home = tempfile::TempDir::new().unwrap();
- let bin = env!("CARGO_BIN_EXE_prime-agent");
- let child = Command::new(bin)
- .args(args)
- .env("HOME", home.path())
- .env("PRIME_AGENT_AGENT_DIR", home.path().join("agent"))
- .env("PRIME_AGENT_FAUX_SCRIPT", script.to_string())
- .current_dir(home.path())
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
+ let socket = home.path().join("daemon.sock");
+ std::fs::write(home.path().join("worker-script.json"), script.to_string()).unwrap();
+ let child = daemon_attached_command(home.path(), &socket, args)
.spawn()
.expect("binary present");
- Self::wrap(child, home)
+ Self::wrap(child, Some(home), socket)
}
- /// The daemon-attached transport: the child spawns its own sandboxed
- /// supervisor on `<home>/daemon.sock` and hosts the scripted worker
- /// through the `PRIME_AGENT_ACP_DAEMON_SCRIPT` create-config seam;
- /// the drop shuts the supervisor down. The socket path is returned
- /// for tests that speak raw daemon commands alongside the ACP frames.
- fn spawn_daemon_attached(
+ /// The daemon-attached lane whose `rlm.spawn` children are scripted:
+ /// `<home>/child-script.json` rides the `PRIME_AGENT_FAUX_CHILD_SCRIPT`
+ /// create-config seam (the worker already consumes the key), and the
+ /// parent worker's kernel runs the given interpreter (the env flows
+ /// ACP -> supervisor -> worker).
+ fn spawn_with_child_script(
args: &[&str],
script: &serde_json::Value,
- ) -> (AcpChild, std::path::PathBuf) {
+ child_script: &serde_json::Value,
+ kernel_python: &std::path::Path,
+ ) -> AcpChild {
let home = tempfile::TempDir::new().unwrap();
let socket = home.path().join("daemon.sock");
- let script_path = home.path().join("worker-script.json");
- std::fs::write(&script_path, script.to_string()).unwrap();
- let bin = env!("CARGO_BIN_EXE_prime-agent");
- let child = Command::new(bin)
- .args(args)
- .arg("--daemon-socket")
- .arg(&socket)
- .env("HOME", home.path())
- .env("PRIME_AGENT_AGENT_DIR", home.path().join("agent"))
- .env("PRIME_AGENT_ACP_DAEMON_SCRIPT", &script_path)
- // The ACP child spawns the sandboxed supervisor, which spawns
- // the session worker; the supervisor-lost exit (TS
- // `exitIfSupervisorOrphanedForTooLong`) runs on this short
- // window (the env flows child -> supervisor -> worker)
- // instead of the 5-minute default.
- .env(
- pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
- "15000",
- )
- .current_dir(home.path())
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
+ let child_script_path = home.path().join("child-script.json");
+ std::fs::write(home.path().join("worker-script.json"), script.to_string()).unwrap();
+ std::fs::write(&child_script_path, child_script.to_string()).unwrap();
+ let child = daemon_attached_command(home.path(), &socket, args)
+ .env("PRIME_AGENT_FAUX_CHILD_SCRIPT", &child_script_path)
+ .env("PRIME_AGENT_KERNEL_PYTHON", kernel_python)
.spawn()
.expect("binary present");
- let mut client = Self::wrap(child, home);
- client.daemon_socket = Some(socket.clone());
- (client, socket)
+ Self::wrap(child, Some(home), socket)
}
fn send(&mut self, frame: &Value) {
let mut line = serde_json::to_string(&frame).unwrap();
line.push('\n');
- self.stdin.write_all(line.as_bytes()).unwrap();
- self.stdin.flush().unwrap();
+ let stdin = self.stdin.as_mut().expect("stdin open");
+ stdin.write_all(line.as_bytes()).unwrap();
+ stdin.flush().unwrap();
+ }
+
+ /// Send EOF: the client disconnects.
+ fn close_stdin(&mut self) {
+ self.stdin = None;
}
fn request(&mut self, method: &str, params: &Value) -> u64 {
@@ -187,27 +181,84 @@ impl AcpChild {
}
}
- /// Read frames until one `sessionUpdate` of `kind` arrives — the
- /// observed-event readiness signal, never a timer. The frames
- /// before it are dropped.
- fn wait_update(&mut self, kind: &str, timeout: Duration) {
+ /// Read frames until one matches — the predicate readiness signal,
+ /// never a timer. The frames before it are dropped.
+ fn wait_frame(
+ &mut self,
+ timeout: Duration,
+ mut frame_matches: impl FnMut(&Value) -> bool,
+ ) -> Value {
let deadline = Instant::now() + timeout;
loop {
let timeout_left = deadline.saturating_duration_since(Instant::now());
assert!(
!timeout_left.is_zero(),
- "the stream never published a {kind} update"
+ "the stream never published the awaited frame"
);
let line = self
.lines
.recv_timeout(timeout_left)
.expect("the ACP stream stayed open");
let frame: Value = serde_json::from_str(&line).expect("valid JSON line");
- if frame["params"]["update"]["sessionUpdate"] == kind {
- return;
+ if frame_matches(&frame) {
+ return frame;
}
}
}
+
+ /// Read frames until one `sessionUpdate` of `kind` arrives — the
+ /// observed-event readiness signal, never a timer. The frames
+ /// before it are dropped.
+ fn wait_update(&mut self, kind: &str, timeout: Duration) {
+ self.wait_frame(timeout, |frame| {
+ frame["params"]["update"]["sessionUpdate"] == kind
+ });
+ }
+}
+
+/// The daemon-attached child's command on `home` and `socket`: the
+/// supervisor-lost exit (TS `exitIfSupervisorOrphanedForTooLong`) runs on
+/// a short window (the env flows child -> supervisor -> worker) instead
+/// of the 5-minute default, and the worker script is
+/// `<home>/worker-script.json`.
+fn daemon_attached_command(
+ home: &std::path::Path,
+ socket: &std::path::Path,
+ args: &[&str],
+) -> Command {
+ let mut command = Command::new(env!("CARGO_BIN_EXE_prime-agent"));
+ command
+ .args(args)
+ .arg("--daemon-socket")
+ .arg(socket)
+ .env("HOME", home)
+ .env("PRIME_AGENT_FAUX_SCRIPT", home.join("worker-script.json"))
+ .env(
+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
+ "15000",
+ )
+ .current_dir(home)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ command
+}
+
+/// The sandbox's single worker descriptor.
+fn worker_descriptor(home: &std::path::Path) -> Value {
+ std::fs::read_dir(home.join(".prime/agent/daemon-workers"))
+ .expect("descriptor instances")
+ .flatten()
+ .flat_map(|instance| {
+ std::fs::read_dir(instance.path())
+ .expect("instance dir")
+ .flatten()
+ })
+ .filter_map(|file| {
+ serde_json::from_str::<Value>(&std::fs::read_to_string(file.path()).ok()?).ok()
+ })
+ .find(|descriptor| descriptor.get("authenticationToken").is_some())
+ .expect("the worker descriptor")
}
impl Drop for AcpChild {
@@ -222,9 +273,7 @@ impl Drop for AcpChild {
eprintln!("ACP child stderr: {text}");
}
}
- if let Some(socket) = self.daemon_socket.take() {
- shutdown_sandboxed_daemon(&socket);
- }
+ shutdown_sandboxed_daemon(&self.socket);
}
}
@@ -281,7 +330,7 @@ fn acp_second_initialize_is_served() {
#[test]
fn acp_prompt_stream_completion_envelope_and_stop_reason_match_ts() {
- let script = json!({ "responses": ["ACP-OK"] });
+ let script = json!({ "engine": "faux", "responses": ["ACP-OK"] });
let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
@@ -368,7 +417,7 @@ fn acp_prompt_stream_completion_envelope_and_stop_reason_match_ts() {
#[test]
fn acp_prompt_chunk_carries_the_assistant_message_id() {
- let script = json!({ "responses": ["ACP-OK"] });
+ let script = json!({ "engine": "faux", "responses": ["ACP-OK"] });
let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
@@ -541,18 +590,6 @@ fn acp_cancel_without_an_active_turn_is_a_noop() {
assert_eq!(close_response["result"], json!({}));
}
-#[test]
-fn acp_initialize_advertises_mcp_capabilities() {
- let script = json!({ "responses": ["unused"] });
- let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
- let init = client.request("initialize", &initialize_params());
- let (response, _) = client.wait_response(init, TIMEOUT);
- assert_eq!(
- response["result"]["agentCapabilities"]["mcpCapabilities"],
- json!({ "http": true })
- );
-}
-
#[test]
fn acp_mcp_admission_accepts_valid_servers_and_close_releases() {
let script = json!({ "responses": ["unused"] });
@@ -723,99 +760,12 @@ fn acp_mcp_long_names_fail_at_tool_derivation_with_internal_error() {
);
}
-#[test]
-fn acp_daemon_attached_serves_a_client_owned_session() {
- // The daemon-attached transport: the binary spawns a supervisor on
- // the sandboxed socket, hosts a client-owned scripted session, and
- // serves the same ACP surface (chunk + settle envelope + end_turn).
- let script = json!({ "engine": "faux", "responses": ["The Thames flows through London."] });
- let (mut client, socket) =
- AcpChild::spawn_daemon_attached(&["--mode", "acp", "--no-session"], &script);
- let init = client.request("initialize", &initialize_params());
- let _ = client.wait_response(init, TIMEOUT);
- let new = client.request("session/new", &json!({ "mcpServers": [] }));
- let (new_response, _) = client.wait_response(new, Duration::from_mins(1));
- assert!(
- new_response["result"]["sessionId"].is_string(),
- "daemon-attached admission succeeds: {new_response}"
- );
- let session_id = new_response["result"]["sessionId"]
- .as_str()
- .unwrap()
- .to_string();
- // Read before session/close: its Kill removes the descriptor.
- let home = socket.parent().expect("the sandbox home");
- let descriptor = std::fs::read_dir(home.join(".prime/agent/daemon-workers"))
- .expect("descriptor instances")
- .flatten()
- .flat_map(|instance| {
- std::fs::read_dir(instance.path())
- .expect("instance dir")
- .flatten()
- })
- .filter_map(|file| {
- serde_json::from_str::<Value>(&std::fs::read_to_string(file.path()).ok()?).ok()
- })
- .find(|descriptor| descriptor.get("authenticationToken").is_some())
- .expect("the worker descriptor");
- let acp_pid = client.child.id();
- assert_eq!(descriptor["ownerClientId"], json!(format!("acp:{acp_pid}")));
- let prompt = client.request(
- "session/prompt",
- &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "Name a river." }] }),
- );
- let (prompt_response, updates) = client.wait_response(prompt, Duration::from_mins(2));
- assert_eq!(prompt_response["result"]["stopReason"], "end_turn");
- let chunk = updates
- .iter()
- .find(|update| update["params"]["update"]["sessionUpdate"] == "agent_message_chunk");
- assert!(chunk.is_some(), "the daemon stream maps to ACP chunks");
- let close = client.request("session/close", &json!({ "sessionId": session_id }));
- let (close_response, _) = client.wait_response(close, Duration::from_mins(1));
- assert_eq!(close_response["result"], json!({}));
- drop(client);
-}
-
-#[test]
-fn acp_daemon_attached_admits_mcp_servers_through_the_wire() {
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
- &["--mode", "acp", "--no-session"],
- &json!({ "responses": ["unused"] }),
- );
- let init = client.request("initialize", &initialize_params());
- let _ = client.wait_response(init, TIMEOUT);
- // The admission validation runs in the transport; the servers ride
- // the replace_acp_mcp_servers wire command to the worker.
- let new = client.request(
- "session/new",
- &json!({ "mcpServers": [
- { "name": "capture-stdio", "type": "stdio", "command": "cat", "args": [], "env": [] },
- ]}),
- );
- let (new_response, _) = client.wait_response(new, Duration::from_mins(1));
- assert!(
- new_response["result"]["sessionId"].is_string(),
- "{}",
- new_response
- );
- // A schema-invalid entry is dropped before the wire, exactly like
- // the in-process path.
- let close_id = new_response["result"]["sessionId"]
- .as_str()
- .unwrap()
- .to_string();
- let close = client.request("session/close", &json!({ "sessionId": close_id }));
- let (close_response, _) = client.wait_response(close, Duration::from_mins(1));
- assert_eq!(close_response["result"], json!({}));
- drop(client);
-}
-
#[test]
fn acp_daemon_attached_cancels_mid_turn() {
// A scripted worker with a slow turn: the cancel lands while the
// turn runs, and the prompt resolves `{stopReason: "cancelled"}`
// with no boundary frames — the TS daemon-attached cancel shape.
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "responses": [{ "text": "a slow answer", "delayMs": 8000 }] }),
);
@@ -849,7 +799,7 @@ fn acp_daemon_attached_cancels_mid_turn() {
fn acp_daemon_attached_overlapping_prompt_is_refused() {
// A second prompt while the first runs is refused; the running turn
// is untouched and the next prompt after its settle runs.
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
{ "text": "a paced answer that streams slowly enough to overlap a prompt" },
@@ -912,7 +862,7 @@ fn acp_daemon_attached_overlapping_prompt_is_refused() {
#[test]
fn acp_daemon_attached_close_mid_turn_answers_cancelled() {
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
{ "text": "a paced answer that streams slowly enough to close mid-turn" },
@@ -944,12 +894,255 @@ fn acp_daemon_attached_close_mid_turn_answers_cancelled() {
assert_eq!(close_response["result"], json!({}));
}
+/// `initialize` + `session/new` on a daemon-attached child; the ACP session id.
+fn initialize_and_new_session(client: &mut AcpChild) -> String {
+ let init = client.request("initialize", &initialize_params());
+ let _ = client.wait_response(init, TIMEOUT);
+ new_session(client)
+}
+
+fn new_session(client: &mut AcpChild) -> String {
+ let new = client.request("session/new", &json!({ "mcpServers": [] }));
+ let (new_response, _) = client.wait_response(new, TIMEOUT);
+ new_response["result"]["sessionId"]
+ .as_str()
+ .unwrap_or_else(|| panic!("session/new succeeds: {new_response}"))
+ .to_string()
+}
+
+fn assert_prompt_ends_turn(client: &mut AcpChild, session_id: &str, text: &str) -> Vec<Value> {
+ let prompt = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": text }] }),
+ );
+ let (prompt_response, updates) = client.wait_response(prompt, Duration::from_mins(2));
+ assert_eq!(
+ prompt_response["result"]["stopReason"], "end_turn",
+ "{prompt_response}"
+ );
+ updates
+}
+
+/// The supervisor's live sessions (`list`).
+fn live_sessions(socket: &std::path::Path) -> Vec<Value> {
+ let list = daemon_request(
+ socket,
+ "live-sessions",
+ &json!({ "type": "list", "includeClientOwned": true }),
+ );
+ list["data"]["sessions"]
+ .as_array()
+ .unwrap_or_else(|| panic!("a session list: {list}"))
+ .clone()
+}
+
+#[test]
+fn acp_daemon_attached_default_session_persists_and_resumes() {
+ // Without --no-session the daemon session is saved and resident: it
+ // survives the client's EOF, and --resume binds the same live worker.
+ let home = tempfile::TempDir::new().unwrap();
+ let home_path = home.path().to_path_buf();
+ let socket = home_path.join("daemon.sock");
+ std::fs::write(
+ home_path.join("worker-script.json"),
+ json!({ "engine": "faux", "responses": ["The Nile.", "Everest."] }).to_string(),
+ )
+ .unwrap();
+ let child = daemon_attached_command(&home_path, &socket, &["--mode", "acp"])
+ .env("DO_NOT_TRACK", "1")
+ .spawn()
+ .expect("binary present");
+ let mut first = AcpChild::wrap(child, Some(home), socket.clone());
+ let session_id = initialize_and_new_session(&mut first);
+ assert_prompt_ends_turn(&mut first, &session_id, "Name a river.");
+
+ let sessions = live_sessions(&socket);
+ assert_eq!(sessions.len(), 1, "{sessions:?}");
+ let active_session_id = sessions[0]["activeSessionId"].clone();
+ let session_file = sessions[0]["sessionFile"]
+ .as_str()
+ .unwrap_or_else(|| panic!("a saved session: {sessions:?}"))
+ .to_string();
+ assert!(
+ std::path::Path::new(&session_file)
+ .parent()
+ .is_some_and(|dir| dir.ends_with("agent/sessions")),
+ "the session is saved in the session dir: {session_file}"
+ );
+ assert!(std::fs::read_to_string(&session_file)
+ .unwrap()
+ .contains("Name a river."));
+ let descriptor = worker_descriptor(&home_path);
+ assert_eq!(descriptor["telemetryDisabled"], json!(true), "{descriptor}");
+ assert!(
+ descriptor.get("ownerClientId").is_none(),
+ "a resident session has no owner: {descriptor}"
+ );
+
+ first.close_stdin();
+ assert!(first.child.wait().expect("the ACP child exits").success());
+ let sessions = live_sessions(&socket);
+ assert_eq!(
+ sessions.len(),
+ 1,
+ "a resident session survives EOF: {sessions:?}"
+ );
+ assert_eq!(sessions[0]["activeSessionId"], active_session_id);
+
+ // A relative `--resume` selector resolves against the CLI's working
+ // directory: the agent dir here, not the stored session cwd.
+ let file_name = std::path::Path::new(&session_file)
+ .file_name()
+ .and_then(std::ffi::OsStr::to_str)
+ .expect("a session file name");
+ let agent_dir = std::path::Path::new(&session_file)
+ .parent()
+ .and_then(std::path::Path::parent)
+ .expect("the agent dir holding the session dir");
+ let child = daemon_attached_command(
+ &home_path,
+ &socket,
+ &[
+ "--mode",
+ "acp",
+ "--resume",
+ &format!("sessions/{file_name}"),
+ ],
+ )
+ .current_dir(agent_dir)
+ .spawn()
+ .expect("binary present");
+ let mut second = AcpChild::wrap(child, None, socket.clone());
+ let session_id = initialize_and_new_session(&mut second);
+ assert_prompt_ends_turn(&mut second, &session_id, "Name a mountain.");
+ let sessions = live_sessions(&socket);
+ assert_eq!(sessions.len(), 1, "{sessions:?}");
+ assert_eq!(
+ sessions[0]["activeSessionId"], active_session_id,
+ "--resume binds the live worker"
+ );
+ let saved = std::fs::read_to_string(&session_file).unwrap();
+ assert!(saved.contains("Name a river.") && saved.contains("Name a mountain."));
+}
+
+#[test]
+fn acp_daemon_attached_resident_eof_mid_turn_cancels_the_prompt() {
+ let answer = "a paced answer that streams slowly enough to close mid-turn";
+ let mut client = AcpChild::spawn(
+ &["--mode", "acp"],
+ &json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [{ "text": answer }] }),
+ );
+ let socket = client.socket.clone();
+ let session_id = initialize_and_new_session(&mut client);
+ let _ = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "a slow question" }] }),
+ );
+ client.wait_update("agent_message_chunk", TIMEOUT);
+ let session = live_sessions(&socket).remove(0);
+ let active_session_id = session["activeSessionId"].clone();
+ let session_file = session["sessionFile"]
+ .as_str()
+ .unwrap_or_else(|| panic!("a saved session: {session}"))
+ .to_string();
+
+ client.close_stdin();
+ assert!(client.child.wait().expect("the ACP child exits").success());
+ let idle = daemon_request(
+ &socket,
+ "idle",
+ &json!({ "type": "wait_for_idle", "activeSessionId": active_session_id }),
+ );
+ assert_eq!(idle["success"], true, "{idle}");
+ let sessions = live_sessions(&socket);
+ assert_eq!(
+ sessions.len(),
+ 1,
+ "a resident session survives EOF: {sessions:?}"
+ );
+ assert_eq!(sessions[0]["activeSessionId"], active_session_id);
+ let saved = std::fs::read_to_string(&session_file).unwrap();
+ assert!(saved.contains("a slow question"), "{saved}");
+ assert!(
+ !saved.contains(answer),
+ "the EOF cancelled the running prompt: {saved}"
+ );
+}
+
+/// EOF while `session/new` is still running: the reader awaits the
+/// handler before it reads further, so the teardown at EOF releases the
+/// session it installs and the process exits.
+#[test]
+fn acp_daemon_attached_eof_during_session_new_exits() {
+ let mut client = AcpChild::spawn(
+ &["--mode", "acp"],
+ &json!({ "engine": "faux", "responses": ["The Nile."] }),
+ );
+ let init = client.request("initialize", &initialize_params());
+ let _ = client.wait_response(init, TIMEOUT);
+ let new = client.request("session/new", &json!({ "mcpServers": [] }));
+ client.close_stdin();
+ let (new_response, _) = client.wait_response(new, TIMEOUT);
+ assert!(
+ new_response["result"]["sessionId"].is_string(),
+ "session/new answers: {new_response}"
+ );
+ assert!(client.child.wait().expect("the ACP child exits").success());
+}
+
+#[test]
+fn acp_daemon_attached_close_keeps_the_worker_and_new_rebinds_it() {
+ let mut client = AcpChild::spawn(
+ &["--mode", "acp", "--no-session"],
+ &json!({ "engine": "faux", "responses": ["The Nile.", "Everest."] }),
+ );
+ let socket = client.socket.clone();
+ let first = initialize_and_new_session(&mut client);
+ let wrong = client.request("session/close", &json!({ "sessionId": "not-the-session" }));
+ let (wrong_response, _) = client.wait_response(wrong, TIMEOUT);
+ assert_eq!(
+ wrong_response["error"]["data"]["details"], "Unknown ACP session: not-the-session",
+ "{wrong_response}"
+ );
+ assert_prompt_ends_turn(&mut client, &first, "Name a river.");
+ let active_session_id = live_sessions(&socket)[0]["activeSessionId"].clone();
+ let descriptor = worker_descriptor(socket.parent().unwrap());
+ let owner = json!(format!("acp:{}", client.child.id()));
+ assert_eq!(descriptor["ownerClientId"], owner, "{descriptor}");
+
+ let close = client.request("session/close", &json!({ "sessionId": first }));
+ let (close_response, _) = client.wait_response(close, TIMEOUT);
+ assert_eq!(close_response["result"], json!({}));
+ let sessions = live_sessions(&socket);
+ assert_eq!(sessions.len(), 1, "close keeps the worker: {sessions:?}");
+ assert_eq!(sessions[0]["activeSessionId"], active_session_id);
+
+ let second = new_session(&mut client);
+ assert_ne!(second, first);
+ let updates = assert_prompt_ends_turn(&mut client, &second, "Name a mountain.");
+ let chunk = updates
+ .iter()
+ .find(|update| update["params"]["update"]["sessionUpdate"] == "agent_message_chunk")
+ .expect("a message chunk");
+ // The event mapping restarts with the session, like TS.
+ assert_eq!(
+ chunk["params"]["update"]["messageId"],
+ "prime-agent-assistant-1"
+ );
+ let sessions = live_sessions(&socket);
+ assert_eq!(sessions.len(), 1, "{sessions:?}");
+ assert_eq!(
+ sessions[0]["activeSessionId"], active_session_id,
+ "session/new binds the same daemon session"
+ );
+}
+
#[test]
fn acp_daemon_attached_prompt_during_cancel_is_refused() {
// A prompt behind a cancel is refused while the stop runs, and the
// cancelled response comes after the stop, so a resend right after it
// runs.
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
{ "text": "a paced answer that streams slowly enough to cancel mid-turn" },
@@ -1014,7 +1207,7 @@ fn acp_daemon_attached_prompt_during_cancel_is_refused() {
fn acp_daemon_attached_failed_turn_publishes_only_the_error_boundary() {
// A failed turn (here: the empty-prompt rejection) publishes one
// error boundary and no terminal-quiescence update (TS settle catch).
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "responses": [] }),
);
@@ -1072,12 +1265,13 @@ fn acp_daemon_attached_supervisor_loss_fails_the_prompt() {
// request must fail fast with an error response, never hang, because
// the link close is the turn's liveness bound (turn-long requests
// carry no timer).
- let (mut client, socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "tokensPerSecond": 2, "responses": [
{ "text": "a paced answer that streams slowly enough to outlive the supervisor" },
] }),
);
+ let socket = client.socket.clone();
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
let new = client.request("session/new", &json!({ "mcpServers": [] }));
@@ -1127,10 +1321,11 @@ fn acp_daemon_attached_supervisor_loss_fails_the_prompt() {
#[test]
fn acp_daemon_attached_image_only_prompt_reaches_the_session() {
- let (mut client, socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "responses": ["SAW-IMAGE"] }),
);
+ let socket = client.socket.clone();
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
let new = client.request("session/new", &json!({ "mcpServers": [] }));
@@ -1201,7 +1396,7 @@ fn acp_compact_command_publishes_the_compaction_meta_and_end_turn() {
// The faux session is short, so `/compact` skips (TS
// `CompactionSkippedError`): the observable parity is the
// `compaction: {}` namespaced update and the normal end_turn response.
- let script = json!({ "responses": ["one answer"] });
+ let script = json!({ "engine": "faux", "responses": ["one answer"] });
let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
@@ -1250,12 +1445,12 @@ fn acp_goal_command_publishes_goal_meta_and_runs_the_continuation() {
// `/goal` start schedules its continuation as the turn's model segment:
// the goal meta frame precedes the streamed answer, and the usage
// accounting publishes a second goal frame after the message settles.
- // The tiny budget bounds the goal loop the direct-ACP settle loop now
+ // The tiny budget bounds the goal loop the worker turn loop
// hosts (TS parity: the continuation loop runs inside the same
// session/prompt request): the crossing turn's budget-limit steer is
// the second model segment, and the budget_limited goal settles the
// prompt with end_turn instead of looping forever.
- let script = json!({ "responses": ["GOAL-PROGRESS", "WRAP-UP"] });
+ let script = json!({ "engine": "faux", "responses": ["GOAL-PROGRESS", "WRAP-UP"] });
let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
@@ -1284,6 +1479,7 @@ fn acp_goal_command_publishes_goal_meta_and_runs_the_continuation() {
&goal_frames[0]["params"]["update"]["_meta"]["ai.primeintellect.prime-agent"]["goal"];
assert_eq!(first["status"], "active");
assert_eq!(first["objective"], "reply with exactly: GOAL-PROGRESS");
+ assert_eq!(first["tokenBudget"], 5);
assert_eq!(first["tokensUsed"], 0);
// A usage update follows the settled message: the tiny budget
// crosses at the first turn, so the goal is budget_limited before
@@ -1314,7 +1510,7 @@ fn acp_autonomous_token_limit_maps_to_max_tokens_stop_reason() {
// A one-token budget is exhausted by the first turn: the driver stops
// with the token limit, the completion envelope carries the autonomous
// accounting, and the stop reason is `max_tokens`.
- let script = json!({ "responses": ["an answer"] });
+ let script = json!({ "engine": "faux", "responses": ["an answer"] });
let mut client = AcpChild::spawn(
&[
"--mode",
@@ -1366,7 +1562,7 @@ fn acp_autonomous_token_limit_maps_to_max_tokens_stop_reason() {
fn acp_autonomous_disabled_reports_end_turn_without_accounting() {
// Without autonomous flags the completion envelope carries no autonomous
// meta and the stop reason is end_turn.
- let script = json!({ "responses": ["an answer"] });
+ let script = json!({ "engine": "faux", "responses": ["an answer"] });
let mut client = AcpChild::spawn(&["--mode", "acp", "--no-session"], &script);
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
@@ -1396,60 +1592,13 @@ fn acp_autonomous_disabled_reports_end_turn_without_accounting() {
);
}
-#[test]
-fn acp_daemon_attached_publishes_the_goal_update_meta() {
- // The daemon worker executes `/goal` and emits the `goal_update`
- // session event; the daemon-attached ACP surface maps it to the
- // namespaced `_meta.goal` update (TS acp-events.ts case "goal_update").
- // A goal start schedules its continuation as the turn's model segment,
- // so the faux engine needs one response.
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
- &["--mode", "acp", "--no-session"],
- &json!({ "engine": "faux", "responses": ["the goal turn settled"] }),
- );
- let init = client.request("initialize", &initialize_params());
- let _ = client.wait_response(init, TIMEOUT);
- let new = client.request("session/new", &json!({ "mcpServers": [] }));
- let (new_response, _) = client.wait_response(new, Duration::from_mins(1));
- assert!(
- new_response["result"]["sessionId"].is_string(),
- "daemon-attached admission succeeds: {new_response}"
- );
- let session_id = new_response["result"]["sessionId"]
- .as_str()
- .unwrap()
- .to_string();
- let prompt = client.request(
- "session/prompt",
- &json!({
- "sessionId": session_id,
- "prompt": [{ "type": "text", "text": "/goal --budget 500 make the daemon publish goal state" }],
- }),
- );
- let (prompt_response, updates) = client.wait_response(prompt, Duration::from_mins(2));
- assert_eq!(prompt_response["result"]["stopReason"], "end_turn");
- let goal = updates.iter().find_map(|update| {
- let meta = &update["params"]["update"]["_meta"]["ai.primeintellect.prime-agent"]["goal"];
- (!meta.is_null()).then(|| meta.clone())
- });
- let goal = goal.expect("a _meta.goal update reached the ACP surface");
- assert_eq!(goal["status"], "active");
- assert_eq!(goal["objective"], "make the daemon publish goal state");
- assert_eq!(goal["tokenBudget"], 500);
- assert_eq!(goal["tokensUsed"], 0);
- let close = client.request("session/close", &json!({ "sessionId": session_id }));
- let (close_response, _) = client.wait_response(close, Duration::from_mins(1));
- assert_eq!(close_response["result"], json!({}));
- drop(client);
-}
-
#[test]
fn acp_daemon_attached_reports_autonomous_accounting_and_limit_stop_reason() {
// An autonomous run with --max-turns 1: the completion envelope carries
// the _meta.autonomous accounting (TS waitForHeadlessCompletion), the
// quiescence observation counts the remaining continuations, and the
// turn limit surfaces as max_turn_requests (TS acpStopReason).
- let (mut client, _socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&["--mode", "acp", "--no-session"],
&json!({ "engine": "faux", "responses": [
"enabling the run",
@@ -1563,7 +1712,7 @@ fn acp_daemon_attached_forwards_cli_session_options() {
)
.unwrap();
let skill = skill_dir.to_str().unwrap().to_string();
- let (mut client, socket) = AcpChild::spawn_daemon_attached(
+ let mut client = AcpChild::spawn(
&[
"--mode",
"acp",
@@ -1578,6 +1727,7 @@ fn acp_daemon_attached_forwards_cli_session_options() {
],
&json!({ "engine": "faux", "responses": ["one turn, then the limit stops"] }),
);
+ let socket = client.socket.clone();
let init = client.request("initialize", &initialize_params());
let _ = client.wait_response(init, TIMEOUT);
let new = client.request("session/new", &json!({ "mcpServers": [] }));
@@ -1609,8 +1759,8 @@ fn acp_daemon_attached_forwards_cli_session_options() {
drop(client);
}
-/// Spawn with compaction settings written into the agent dir (the
-/// in-process session resolves them at session assembly).
+/// Spawn with compaction settings written into the worker's agent dir
+/// (`<home>/.prime/agent`: the worker inherits the child's HOME).
fn spawn_with_compaction_settings(
args: &[&str],
script: &serde_json::Value,
@@ -1618,10 +1768,9 @@ fn spawn_with_compaction_settings(
keep_recent_tokens: u64,
) -> AcpChild {
let home = tempfile::TempDir::new().unwrap();
- let agent_dir = home.path().join("agent");
- std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ std::fs::create_dir_all(home.path().join(".prime/agent")).expect("agent dir");
std::fs::write(
- agent_dir.join("settings.json"),
+ home.path().join(".prime/agent/settings.json"),
json!({
"compaction": {
"enabled": true,
@@ -1632,19 +1781,12 @@ fn spawn_with_compaction_settings(
.to_string(),
)
.expect("write settings.json");
- let bin = env!("CARGO_BIN_EXE_prime-agent");
- let child = Command::new(bin)
- .args(args)
- .env("HOME", home.path())
- .env("PRIME_AGENT_CODING_AGENT_DIR", &agent_dir)
- .env("PRIME_AGENT_FAUX_SCRIPT", script.to_string())
- .current_dir(home.path())
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
+ let socket = home.path().join("daemon.sock");
+ std::fs::write(home.path().join("worker-script.json"), script.to_string()).unwrap();
+ let child = daemon_attached_command(home.path(), &socket, args)
.spawn()
.expect("binary present");
- AcpChild::wrap(child, home)
+ AcpChild::wrap(child, Some(home), socket)
}
/// The compaction metas among a turn's updates (the ACP `compaction_end`
@@ -1674,7 +1816,9 @@ fn compaction_metas(updates: &[Value]) -> Vec<Value> {
#[test]
fn acp_threshold_auto_compaction_publishes_the_compaction_meta() {
let script = json!({
+ "engine": "faux",
"contextWindow": 128_000,
+ "maxTokens": 4_096,
"responses": [
{ "text": "turn one reply" },
{ "text": "turn two reply" },
@@ -1746,6 +1890,7 @@ fn acp_threshold_auto_compaction_publishes_the_compaction_meta() {
#[test]
fn acp_overflow_recovery_compacts_and_retries_the_turn() {
let script = json!({
+ "engine": "faux",
"contextWindow": 128_000,
"responses": [
{ "text": "seed reply" },
@@ -1786,37 +1931,16 @@ fn acp_overflow_recovery_compacts_and_retries_the_turn() {
// The overflow probe: the arm compacts once (the summarizer consumed
// the third scripted response) and the retried turn recovers. The
- // seed turn's drain can outlive its response on a loaded runner (the
- // overflow retry then bounces off the still-running prompt guard) —
- // the probe is re-issued until the session settles (the recovered
- // turn's assertion itself is unchanged and strict).
- let mut probe_attempts = 0;
- let (prompt_response, updates) = loop {
- probe_attempts += 1;
- let prompt = client.request(
- "session/prompt",
- &json!({
- "sessionId": session_id,
- "prompt": [{ "type": "text", "text": format!("overflow probe {}", "x".repeat(2_000)) }],
- }),
- );
- let (response, prompt_updates) = client.wait_response(prompt, TIMEOUT);
- // ACP `internal_error` carries the refusal text in `data.details`
- // (`Internal error` is the generic message) — match both fields.
- let refusal_text = response["error"]["data"]["details"]
- .as_str()
- .or_else(|| response["error"]["message"].as_str())
- .unwrap_or_default();
- let refused = response["error"].is_object() && refusal_text.contains("already running");
- if !refused {
- break (response, prompt_updates);
- }
- assert!(
- probe_attempts < 40,
- "the session never settled after the seed turn: {response}"
- );
- std::thread::sleep(std::time::Duration::from_millis(250));
- };
+ // daemon path releases the prompt slot before it answers the seed
+ // turn, so the probe cannot bounce off the running-turn guard.
+ let prompt = client.request(
+ "session/prompt",
+ &json!({
+ "sessionId": session_id,
+ "prompt": [{ "type": "text", "text": format!("overflow probe {}", "x".repeat(2_000)) }],
+ }),
+ );
+ let (prompt_response, updates) = client.wait_response(prompt, TIMEOUT);
assert_eq!(
prompt_response["result"],
json!({ "stopReason": "end_turn" }),
@@ -1827,3 +1951,310 @@ fn acp_overflow_recovery_compacts_and_retries_the_turn() {
assert_eq!(metas[0]["summary"], "the summary");
assert!(metas[0]["tokensBefore"].as_u64().unwrap() > 0);
}
+
+/// The kernel Python with prime-agent-runtime installed; set
+/// `PA_E2E_KERNEL_PYTHON` to point at an explicit interpreter instead.
+/// Without one, the live RLM quiescence lanes below skip (with a note).
+fn kernel_python() -> Option<std::path::PathBuf> {
+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {
+ let explicit = std::path::PathBuf::from(explicit);
+ assert!(
+ explicit.exists(),
+ "PA_E2E_KERNEL_PYTHON {} not found",
+ explicit.display()
+ );
+ return Some(explicit);
+ }
+ let candidate = std::path::PathBuf::from(std::env::var("HOME").map_or_else(
+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),
+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),
+ ));
+ if candidate.exists() {
+ return Some(candidate);
+ }
+ eprintln!(
+ "kernel python {} not found; skipping live RLM quiescence e2e",
+ candidate.display()
+ );
+ None
+}
+
+/// The namespaced prime-agent payload of one session/update frame.
+fn update_meta(frame: &Value) -> &Value {
+ &frame["params"]["update"]["_meta"]["ai.primeintellect.prime-agent"]
+}
+
+/// The kernel cell of the spawn turn (the worker's
+/// `rlm_quiescence_barrier_e2e` lane): spawn one RLM child through the
+/// product `rlm.spawn` surface and record its child id.
+fn spawn_cell() -> &'static str {
+ "handle = await rlm.spawn(\"run the lane task\", name=\"kid\")\nprint(handle.rlm_child_id)"
+}
+
+/// The parent faux script whose turns run the spawn cell; the third
+/// response answers the settled child's terminal-notice turn (the no-reply
+/// notice the watcher queues on the parent).
+fn spawn_parent_script(spawn_cell: &str) -> Value {
+ json!({
+ "engine": "faux",
+ "responses": [
+ { "content": [
+ { "type": "toolCall", "name": "ipython", "arguments": { "code": spawn_cell } },
+ ] },
+ { "text": "spawn turn done" },
+ { "text": "notice seen" },
+ ],
+ })
+}
+
+/// One scripted-children lane: a daemon-attached resident session whose
+/// parent turns spawn a held scripted child (resident because the RLM spawn
+/// ledger needs the parent's session file — a `--no-session` parent cannot
+/// spawn children). The parent's active session id is read at setup, before
+/// the spawn: once a child runs, `live_sessions` lists both workers.
+fn spawn_lane(
+ args: &[&str],
+ child_hold_ms: u64,
+ kernel_python: &std::path::Path,
+) -> (AcpChild, String, String) {
+ let parent = spawn_parent_script(spawn_cell());
+ let child_script = json!({ "responses": [ { "text": "kid done", "delayMs": child_hold_ms } ] });
+ let mut client = AcpChild::spawn_with_child_script(args, &parent, &child_script, kernel_python);
+ let init = client.request("initialize", &initialize_params());
+ let _ = client.wait_response(init, TIMEOUT);
+ let session_id = new_session(&mut client);
+ let socket = client.socket.clone();
+ let active_session_id = live_sessions(&socket).remove(0)["activeSessionId"]
+ .as_str()
+ .expect("the parent session id")
+ .to_string();
+ (client, session_id, active_session_id)
+}
+
+/// The ACP settle waits for RLM quiescence (TS #1612): the completion
+/// update reports the live outstanding-subagent count, the terminal update
+/// reports zero, and the settled child's terminal-notice turn ("notice
+/// seen") drains inside the barrier, between the two.
+#[test]
+fn acp_prompt_settles_after_rlm_quiescence() {
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let (mut client, session_id, _) = spawn_lane(&["--mode", "acp"], 5_000, &kernel_python);
+ let prompt = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "spawn the kid" }] }),
+ );
+ // Readiness is the completion update itself: the parent turn settled,
+ // the held child turn is still in flight.
+ let completion = client.wait_frame(TIMEOUT, |frame| {
+ let meta = update_meta(frame);
+ meta["phase"] == "event" && !meta["quiescence"].is_null()
+ });
+ assert_eq!(
+ update_meta(&completion)["quiescence"]["outstandingSubagents"],
+ 1,
+ "the completion reports the live child: {completion}"
+ );
+ // The settled child's terminal-notice turn drains inside the barrier:
+ // its streamed answer lands between the completion and the terminal.
+ let mut notice_seen = false;
+ let terminal = client.wait_frame(TIMEOUT, |frame| {
+ let meta = update_meta(frame);
+ if meta["phase"] != "terminalQuiescence" {
+ notice_seen |= frame["params"]["update"]["content"]["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("notice seen"));
+ return false;
+ }
+ true
+ });
+ assert!(
+ notice_seen,
+ "the settled child's notice turn drained inside the barrier: {terminal}"
+ );
+ assert_eq!(
+ update_meta(&terminal)["quiescence"]["outstandingSubagents"],
+ 0,
+ "the terminal reports a quiet family: {terminal}"
+ );
+ let (prompt_response, updates) = client.wait_response(prompt, TIMEOUT);
+ assert!(
+ updates.is_empty(),
+ "the terminal frame is the last notification before the response: {updates:?}"
+ );
+ assert_eq!(
+ prompt_response["result"],
+ json!({ "stopReason": "end_turn" })
+ );
+}
+
+/// A cancel during the settle cancels the outstanding subagents (TS
+/// `cancelOutstandingRlmChildren` inside `stopSessionWork`): the prompt
+/// answers cancelled once the stop sequence cancelled the held child, and
+/// the roster reports the child cancelled. Close goes through the same
+/// stop sequence, so it is not retested here.
+#[test]
+fn acp_cancel_during_settle_cancels_the_subagents() {
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let (mut client, session_id, active_session_id) =
+ spawn_lane(&["--mode", "acp"], 120_000, &kernel_python);
+ let socket = client.socket.clone();
+ let prompt = client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "spawn the kid" }] }),
+ );
+ // Readiness is the completion update with the held child outstanding:
+ // the settle is provably waiting on it.
+ client.wait_frame(TIMEOUT, |frame| {
+ let meta = update_meta(frame);
+ meta["phase"] == "event" && meta["quiescence"]["outstandingSubagents"] == 1
+ });
+ client.notify("session/cancel", &json!({ "sessionId": session_id }));
+ let (prompt_response, _) = client.wait_response(prompt, TIMEOUT);
+ assert_eq!(
+ prompt_response["result"],
+ json!({ "stopReason": "cancelled" }),
+ "the cancel settles the prompt: {prompt_response}"
+ );
+ // The roster shows the child the stop sequence cancelled.
+ let roster = daemon_request(
+ &socket,
+ "children",
+ &json!({ "type": "get_rlm_children", "activeSessionId": active_session_id }),
+ );
+ let children = roster["data"]["children"]
+ .as_array()
+ .unwrap_or_else(|| panic!("a children roster: {roster}"))
+ .clone();
+ assert_eq!(children.len(), 1, "one spawned child: {children:?}");
+ assert_eq!(
+ children[0]["status"], "cancelled",
+ "the stop cancelled the held child: {children:?}"
+ );
+}
+
+/// EOF during the settle exits without waiting for the outstanding
+/// subagents (TS aborts the controller and exits): the process is gone
+/// while the resident session's held child still runs — EOF does not
+/// cancel a resident session's children.
+#[test]
+fn acp_eof_during_settle_exits_and_leaves_resident_subagents() {
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let (mut client, session_id, active_session_id) =
+ spawn_lane(&["--mode", "acp"], 120_000, &kernel_python);
+ let socket = client.socket.clone();
+ client.request(
+ "session/prompt",
+ &json!({ "sessionId": session_id, "prompt": [{ "type": "text", "text": "spawn the kid" }] }),
+ );
+ client.wait_frame(TIMEOUT, |frame| {
+ let meta = update_meta(frame);
+ meta["phase"] == "event" && meta["quiescence"]["outstandingSubagents"] == 1
+ });
+ client.close_stdin();
+ assert!(client.child.wait().expect("the ACP child exits").success());
+ // The resident session survives with the held child still running.
+ let roster = daemon_request(
+ &socket,
+ "children",
+ &json!({ "type": "get_rlm_children", "activeSessionId": active_session_id }),
+ );
+ let children = roster["data"]["children"]
+ .as_array()
+ .unwrap_or_else(|| panic!("a children roster: {roster}"))
+ .clone();
+ assert_eq!(children.len(), 1, "one spawned child: {children:?}");
+ assert_eq!(
+ children[0]["status"], "running",
+ "EOF left the resident child running: {children:?}"
+ );
+}
+
+/// A heartbeat change on the bound session broadcasts
+/// `heartbeats_changed` to every client; the ACP link publishes the
+/// change at origin turn 0 (connection-scoped like TS, never the active
+/// prompt turn).
+#[test]
+fn acp_heartbeat_change_publishes_turn_zero_meta() {
+ let mut client = AcpChild::spawn(
+ &["--mode", "acp"],
+ &json!({ "engine": "faux", "responses": ["The Nile."] }),
+ );
+ let socket = client.socket.clone();
+ let _session_id = initialize_and_new_session(&mut client);
+ let active_session_id = live_sessions(&socket)[0]["activeSessionId"].clone();
+ let set = daemon_request(
+ &socket,
+ "heartbeat-set",
+ &json!({
+ "type": "heartbeat_set",
+ "activeSessionId": active_session_id,
+ "schedule": "every 90 seconds",
+ "prompt": "check in",
+ }),
+ );
+ assert_eq!(set["success"], true, "{set}");
+ let change = client.wait_frame(TIMEOUT, |frame| {
+ update_meta(frame)["heartbeatsChanged"] == json!(true)
+ });
+ assert_eq!(update_meta(&change)["promptTurnId"], 0, "{change}");
+ assert_eq!(update_meta(&change)["phase"], "event", "{change}");
+}
+
+/// A bash run another client started on the bound session (the daemon's
+/// `execute_bash`) surfaces as one synthetic tool call keyed by run id:
+/// the started run, the streamed chunk, and the settled status.
+#[test]
+fn acp_user_bash_maps_to_a_synthetic_tool_call() {
+ let mut client = AcpChild::spawn(
+ &["--mode", "acp"],
+ &json!({ "engine": "faux", "responses": ["The Nile."] }),
+ );
+ let socket = client.socket.clone();
+ let _session_id = initialize_and_new_session(&mut client);
+ let active_session_id = live_sessions(&socket)[0]["activeSessionId"].clone();
+ let run = daemon_request(
+ &socket,
+ "bash",
+ &json!({
+ "type": "execute_bash",
+ "activeSessionId": active_session_id,
+ "command": "printf hi",
+ "runId": "r1",
+ }),
+ );
+ assert_eq!(run["success"], true, "{run}");
+ let start = client.wait_frame(TIMEOUT, |frame| {
+ frame["params"]["update"]["sessionUpdate"] == "tool_call"
+ });
+ assert_eq!(
+ start["params"]["update"]["toolCallId"],
+ "prime-agent-bash-r1"
+ );
+ assert_eq!(start["params"]["update"]["title"], "printf hi");
+ assert_eq!(start["params"]["update"]["kind"], "execute");
+ assert_eq!(
+ start["params"]["update"]["rawInput"],
+ json!({ "command": "printf hi" })
+ );
+ let output = client.wait_frame(TIMEOUT, |frame| {
+ frame["params"]["update"]["sessionUpdate"] == "tool_call_update"
+ && frame["params"]["update"]["toolCallId"] == "prime-agent-bash-r1"
+ && frame["params"]["update"]["status"] == "in_progress"
+ });
+ assert_eq!(
+ output["params"]["update"]["content"][0]["content"]["text"], "hi",
+ "{output}"
+ );
+ let end = client.wait_frame(TIMEOUT, |frame| {
+ frame["params"]["update"]["sessionUpdate"] == "tool_call_update"
+ && frame["params"]["update"]["toolCallId"] == "prime-agent-bash-r1"
+ && frame["params"]["update"]["status"] == "completed"
+ });
+ assert!(end["params"]["update"].get("content").is_none(), "{end}");
+}
diff --git a/crates/pa-daemon/README.md b/crates/pa-daemon/README.md
index 38d297d965..b765102156 100644
--- a/crates/pa-daemon/README.md
+++ b/crates/pa-daemon/README.md
@@ -4,35 +4,17 @@ Session supervision and wire serving.
## Scope
ACP stdio transport (`acp`): the JSON-RPC serve surface for Agent
-Client Protocol clients - a thin transport over the pa-core session engine
-(initialize, session/new, session/prompt, session/close, session/cancel,
-and the outgoing session/update notification with namespaced `_meta`
-correlation), owned by this crate because wire-protocol serving is its area;
-the in-process transport hosts the automatic compaction arms at its turn
-boundaries (`acp/compaction_arms.rs`: the TS `_checkCompaction` /
-`_runPreTurnCompaction` / `_consumePendingRequestedRefine` flows — the
-overflow compact-and-retry, the model-requested arm, and the threshold
-arm, publishing the ACP `compaction_end` mapping and aborting an in-flight
-run on session/cancel+close; the daemon-attached transport runs the
-worker turn loop's arms instead), because the TS arms live in the session
-turn loop every transport shares and the in-process ACP path drives the
-pa-core engine directly. The compact-trigger auto-refine scheduling owns
-its surface here (`compact_autorefine.rs` for the daemon worker: every
-compaction arm plus the manual `compact` command arm the pa-core
-trigger, and the quiescent turn boundaries / the command path consume
-the gated review - TS `_scheduleAutoRefineAfterCompaction` plus the
-background `_maybeAutoRefine("compact")`; `acp/autorefine.rs` for ACP:
-the serialized checkpoint consumes the armed trigger after the
-requested refine.run and session close drains what no turn serviced -
-TS's serialized scheduling for the acp app mode). The direct-ACP goal
-continuation boundary owns its surface here too (`acp/goal_continuation.rs`:
-the TS session's continuation hook `_getContinuationMessages` runs inside
-the one `session/prompt` request on the in-process path — the goal arm with
-exclusive priority over the autonomous arm, the budget-limit wrap-up steer,
-the natural continuation mint per settled boundary, the terminal-error
-goal failure, the threshold-arm goal queue before its compaction (with
-the cancel rollback), and the compact-with-active-goal continue; the
-daemon-attached transport rides the worker's #244 loop instead).
+Client Protocol clients, served over a daemon session (initialize, session/new, session/prompt, session/close,
+session/cancel, and the outgoing session/update notification with
+namespaced `_meta` correlation), owned by this crate because
+wire-protocol serving is its area; the worker turn loop owns compaction
+arms, auto-refine, and goal continuation. The compact-trigger
+auto-refine scheduling owns its surface here (`compact_autorefine.rs`
+for the daemon worker: every compaction arm plus the manual `compact`
+command arm the pa-core trigger, and the quiescent turn boundaries /
+the command path consume the gated review - TS
+`_scheduleAutoRefineAfterCompaction` plus the background
+`_maybeAutoRefine("compact")`).
Supervisor process (one worker process per active session), restart/backoff
supervision, session registry/roster + worker self-registration (session
identity survives supervisor restarts: workers re-register with backoff and
@@ -271,7 +253,7 @@ attached UIs daemon-wide).
No agent behavior inside workers beyond hosting a pa-core engine; no UI.
## Public API
-Supervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_worker_mcp_login}` (the worker's browser+callback login behind `mcp.begin_login`; wired by the agent engine before sessions register host handlers), client connection API for pa-tui/pa-cli, `acp::{run_acp_mode, AcpOptions}` (pa-cli dispatches `--mode acp` through it), `agent_messaging::LinkAgentMessageController` + `rlm_children::{SupervisorChildSessions, ParentIdentity, RlmChildIdentity}` (e2e verifiers construct the worker-side family controller and the children registry; the engine wires the same types), `agent_engine::AgentSessionEngine::dispose_kernel` (the session-end kernel teardown the worker invokes at kill/shutdown/orphan exit — the engine outlives the session, so the pa-core engine-drop teardown cannot run there), the worker's `get_mcp_connections` command (`mcp_connections.rs`: the `/mcp` view's roster from the session's MCP manager overlaid with the session kernel's per-server tool listing, plus the api-key credential rows the same response serves — Rust-native session-plane extension; the TS daemon has no counterpart). Supervision internals `pub(crate)`.
+Supervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_worker_mcp_login}` (the worker's browser+callback login behind `mcp.begin_login`; wired by the agent engine before sessions register host handlers), client connection API for pa-tui/pa-cli, `acp::daemon::{run_daemon_attached_acp_mode, DaemonAcpOptions}` (pa-cli dispatches `--mode acp` through it), `agent_messaging::LinkAgentMessageController` + `rlm_children::{SupervisorChildSessions, ParentIdentity, RlmChildIdentity}` (e2e verifiers construct the worker-side family controller and the children registry; the engine wires the same types), `agent_engine::AgentSessionEngine::dispose_kernel` (the session-end kernel teardown the worker invokes at kill/shutdown/orphan exit — the engine outlives the session, so the pa-core engine-drop teardown cannot run there), the worker's `get_mcp_connections` command (`mcp_connections.rs`: the `/mcp` view's roster from the session's MCP manager overlaid with the session kernel's per-server tool listing, plus the api-key credential rows the same response serves — Rust-native session-plane extension; the TS daemon has no counterpart). Supervision internals `pub(crate)`.
## Depends on
diff --git a/crates/pa-daemon/src/acp/autorefine.rs b/crates/pa-daemon/src/acp/autorefine.rs
deleted file mode 100644
index e75a219e32..0000000000
--- a/crates/pa-daemon/src/acp/autorefine.rs
+++ /dev/null
@@ -1,626 +0,0 @@
-//! The compact-trigger auto-refine on the ACP turn path: the serialized
-//! scheduling TS gives the ACP mode (main.ts
-//! `serializedRefine: appMode !== "interactive" && appMode !== "daemon"`
-//! — true for ACP), mapped onto this transport's boundaries.
-//!
-//! TS ground truth: a successful compaction arms the trigger
-//! (`_scheduleAutoRefineAfterCompaction`'s serialized arm sets
-//! `_compactAutoRefinePending`); the serialized checkpoint between turns
-//! consumes it after servicing the requested `refine.run`
-//! (`_runSerializedRefineCheckpointAfterBackground`'s compact step, with
-//! its `enabled`/`compact` gates and the cooldown preserving the trigger),
-//! and session disposal drains a trigger no turn serviced (the
-//! serialized dispose drain). An approved round runs the refinement and
-//! publishes the same `refinement` meta the `/refine` command produces
-//! (`RefineComplete`/`RefineFailed`); a declined review surfaces
-//! nothing (TS: only the cooldown is stamped).
-
-use pa_core::refinement::RefinementResult;
-use pa_core::session_engine::auto_refine_trigger::CompactAutoRefineSurface;
-
-use super::events::AcpEngineEvent;
-use super::session::AcpSession;
-use super::AcpModeState;
-
-/// The namespaced `refinement` meta event one applied refinement
-/// publishes (the same shape the `/refine` command and the requested
-/// `refine.run` round publish).
-pub(super) fn refine_complete_event(result: &RefinementResult) -> AcpEngineEvent {
- let changes = result
- .applied_edits
- .iter()
- .filter(|edit| edit.applied)
- .map(|edit| {
- let action = serde_json::to_value(edit.action)
- .ok()
- .and_then(|value| value.as_str().map(str::to_string))
- .unwrap_or_default();
- let kind = serde_json::to_value(edit.kind)
- .ok()
- .and_then(|value| value.as_str().map(str::to_string))
- .unwrap_or_default();
- format!("{action} {kind}:{}", edit.id)
- })
- .collect();
- AcpEngineEvent::RefineComplete {
- summary: result.summary.clone(),
- changes,
- }
-}
-
-impl AcpSession {
- /// Consume an armed trigger at the serialized checkpoint between
- /// turns (TS `_runSerializedRefineCheckpointAfterBackground`'s
- /// compact step): the gates and the review run in the pa-core seam;
- /// an approved round publishes its `refinement` meta exactly like
- /// the requested refinement round, and a failed round publishes the
- /// `RefineFailed` mapping (TS emits `refine_failed` on the wire for
- /// a failed serialized round). A declined review stays silent.
- pub(super) async fn consume_compact_auto_refine(&self, mode: &AcpModeState) {
- // The config queue serializes the round against picker switches:
- // the armed trigger runs on the model the session reports, never
- // on the pre-switch pair mid-switch.
- let _guard = mode.config_queue.lock().await;
- let Some(model) = mode.current_model().await else {
- return;
- };
- let outcome = self
- .consume_compact_auto_refine_round(mode, &model, CompactAutoRefineSurface::Checkpoint)
- .await;
- self.publish_compact_auto_refine_outcome(outcome).await;
- }
-
- /// The disposal drain (TS `dispose`'s serialized arm: "a serialized
- /// compaction can finish without another model turn — drain its
- /// pending review here so disposal does not silently lose the
- /// trigger"): session close services an armed trigger one last
- /// time; a trigger under the cooldown drops without a review. The
- /// round is best-effort like the TS drain — close proceeds even
- /// when the review fails.
- pub(super) async fn drain_compact_auto_refine_at_close(&self, mode: &AcpModeState) {
- // Same serialization as the mid-session checkpoint (the close
- // path drains the queue first, then the round takes it cleanly).
- let _guard = mode.config_queue.lock().await;
- let Some(model) = mode.current_model().await else {
- return;
- };
- let outcome = self
- .consume_compact_auto_refine_round(mode, &model, CompactAutoRefineSurface::Dispose)
- .await;
- self.publish_compact_auto_refine_outcome(outcome).await;
- }
-
- /// The shared round body: the pa-core consumption with its
- /// gate/review/stamp sequence. `Ok(None)` is every silent outcome
- /// (no trigger armed, a gate dropping it, the cooldown holding it,
- /// or a declined review).
- async fn consume_compact_auto_refine_round(
- &self,
- mode: &AcpModeState,
- model: &pa_types::ai::Model,
- surface: CompactAutoRefineSurface,
- ) -> anyhow::Result<Option<RefinementResult>> {
- mode.engine
- .session
- .consume_compact_auto_refine(
- model,
- mode.current_api_key().await,
- mode.agent_dir.as_path().to_path_buf(),
- surface,
- )
- .await
- }
-
- /// One round's `refinement` meta surface: an approved round
- /// publishes the complete mapping, a failed round the failure
- /// mapping, and every silent outcome nothing.
- async fn publish_compact_auto_refine_outcome(
- &self,
- outcome: anyhow::Result<Option<RefinementResult>>,
- ) {
- match outcome {
- Ok(Some(result)) => {
- let event = refine_complete_event(&result);
- self.publish_engine_event(&event).await;
- }
- Ok(None) => {}
- Err(error) => {
- self.publish_engine_event(&AcpEngineEvent::RefineFailed {
- error: format!("{error:#}"),
- })
- .await;
- }
- }
- }
-}
-
-#[cfg(test)]
-// The faux provider registry is process-global and shared with the
-// daemon engine tests: the std lock serializes every test that drives
-// it, and the async tests here hold it across their awaits on purpose
-// (the tests are the only contenders, so no cross-task deadlock).
-#[allow(clippy::await_holding_lock)]
-mod tests {
- use super::*;
- use crate::agent_engine::FAUX_TEST_LOCK;
-
- /// The faux model's per-request output budget (maxTokens `16_384` under the
- /// `32_000` request cap): threshold fixtures subtract it from the window
- /// alongside the headroom (the combined input+output ceiling).
- const FAUX_REQUEST_BUDGET: u64 = 16_384;
-
- use pa_core::session::manager::SessionManager;
- use pa_core::session_engine::engine::{create_session, SessionEngineConfig};
- use pa_core::session_engine::provider_adapter::{json_round_trip, real_stream_fn};
- use serde_json::json;
- use tokio::sync::{mpsc, Mutex};
-
- use super::super::producer::UpdateProducer;
- use super::super::prompt::handle_session_prompt;
- use super::super::{ConnectionState, SessionEntry};
-
- /// The ACP meta namespace on the wire.
- const META: &str = "ai.primeintellect.prime-agent";
-
- /// A declining review reply.
- const DECLINE: &str = r#"{"shouldRefine": false, "rationale": "one-off tool output"}"#;
-
- /// One armed ACP prompt turn over an in-process faux engine whose
- /// session is persisted (the CLI-built ACP engine shape: a material
- /// session file, hence the local harness dir the refine surface
- /// gates on).
- struct AcpAutorefineBed {
- mode: AcpModeState,
- state: std::sync::Arc<Mutex<ConnectionState>>,
- session_id: String,
- tx: super::super::producer::FrameSink,
- frames: mpsc::UnboundedReceiver<serde_json::Value>,
- next_request_id: u64,
- engine: std::sync::Arc<pa_core::session_engine::engine::SessionEngine>,
- /// Held so the engine's cwd outlives the test.
- _dir: tempfile::TempDir,
- }
-
- async fn acp_autorefine_bed(
- script: serde_json::Value,
- reserve_tokens: u64,
- ) -> AcpAutorefineBed {
- let dir = tempfile::TempDir::new().unwrap();
- let agent_dir = dir.path().join("agent");
- std::fs::create_dir_all(&agent_dir).unwrap();
- std::fs::write(
- agent_dir.join("settings.json"),
- json!({
- "compaction": {
- "enabled": true,
- "reserveTokens": reserve_tokens,
- "keepRecentTokens": 10,
- }
- })
- .to_string(),
- )
- .unwrap();
- let parsed = pa_ai::faux::script::parse_faux_script(&script)
- .map_err(anyhow::Error::msg)
- .unwrap();
- let registration = pa_ai::faux::script::register_faux_provider_from_script(&parsed);
- let model = registration.get_model();
- let agent_model: pa_agent::types::Model =
- json_round_trip(&model).expect("model conversion");
- let stream_fn = real_stream_fn(None, model.clone());
- let mut session_manager = SessionManager::in_memory(dir.path());
- session_manager.materialize_session_file(Some(dir.path().join("sessions")));
- let engine = std::sync::Arc::new(
- create_session(SessionEngineConfig {
- semantic_edges: None,
- cron_store: None,
- queued_steering_probe: None,
- image_model_router: None,
- steering_mode: None,
- follow_up_mode: None,
- telemetry: None,
- cwd: dir.path().to_path_buf(),
- agent_dir: agent_dir.clone(),
- mcp_manager: None,
- model: Some(agent_model),
- thinking_level: None,
- stream_fn: Some(stream_fn),
- tools: Vec::new(),
- custom_system_prompt: None,
- prompt_guidelines: Vec::new(),
- generic_mcp_servers: Vec::new(),
- allow_recursion: None,
- session_manager: Some(session_manager),
- extra_host_handlers: None,
- conversation_log_path: None,
- additional_skill_paths: Vec::new(),
- additional_prompt_paths: Vec::new(),
- extra_builtin_skill_overrides: Vec::new(),
- rlm_subagent_host: None,
- rlm_depth: None,
- model_info: Some(model.clone()),
- // The settings default (no prewarm); the ACP autorefine
- // tests do not exercise kernel boot paths.
- prewarm_ipython_kernel: None,
- on_background_work_settled: None,
- queued_goal_context_purge: None,
- })
- .await
- .unwrap(),
- );
- let (tx, frames) = mpsc::unbounded_channel::<serde_json::Value>();
- let session_id = "acp-autorefine-session".to_string();
- let producer = UpdateProducer::new(session_id.clone(), tx.clone());
- let autonomous = std::sync::Arc::new(Mutex::new(
- pa_core::autonomous::create_autonomous_runtime_state(None, None),
- ));
- let driver: std::sync::Arc<dyn pa_core::autonomous::AutonomousDriver> =
- std::sync::Arc::new(pa_core::autonomous::ShellAutonomousDriver::new(dir.path()));
- let session = std::sync::Arc::new(
- super::AcpSession::new(
- session_id.clone(),
- engine.clone(),
- producer.clone(),
- autonomous,
- driver,
- )
- .await,
- );
- producer.commit_session_new_response().await;
- let state = std::sync::Arc::new(Mutex::new(ConnectionState {
- session: Some(SessionEntry {
- session,
- prompt_task: None,
- config: std::sync::Arc::new(super::super::InProcessConfig {
- published: tokio::sync::Mutex::new(Vec::new()),
- models: tokio::sync::Mutex::new(Vec::new()),
- }),
- config_refresh: None,
- }),
- session_new_in_flight: false,
- session_close_in_flight: false,
- }));
- let mode = AcpModeState {
- engine: engine.clone(),
- actual_cwd: std::sync::Arc::new(dir.path().to_path_buf()),
- product_version: std::sync::Arc::new("test".to_string()),
- model: std::sync::Arc::new(Mutex::new(Some(model))),
- api_key: std::sync::Arc::new(Mutex::new(None)),
- config_queue: std::sync::Arc::new(tokio::sync::Mutex::new(())),
- agent_dir: std::sync::Arc::new(agent_dir),
- provider_target: std::sync::Arc::new(std::sync::RwLock::new(None)),
- autonomous_config: None,
- mcp: engine.mcp_manager.clone(),
- mcp_owner_id: std::sync::Arc::new("acp-autorefine-owner".to_string()),
- mcp_server_names: std::sync::Arc::new(Mutex::new(Vec::new())),
- };
- AcpAutorefineBed {
- mode,
- state,
- session_id,
- tx,
- frames,
- next_request_id: 0,
- engine,
- _dir: dir,
- }
- }
-
- impl AcpAutorefineBed {
- /// Admit one prompt through the real ACP prompt handler and read
- /// frames until its response: (response, notifications in order).
- async fn prompt(&mut self, text: String) -> (serde_json::Value, Vec<serde_json::Value>) {
- self.next_request_id += 1;
- let id = serde_json::Value::from(self.next_request_id);
- handle_session_prompt(
- id.clone(),
- json!({
- "sessionId": self.session_id,
- "prompt": [{ "type": "text", "text": text }],
- }),
- self.state.clone(),
- self.mode.clone(),
- self.tx.clone(),
- )
- .await;
- let mut notifications = Vec::new();
- loop {
- let Some(frame) = self.frames.recv().await else {
- panic!("ACP frame channel closed before the response");
- };
- if frame.get("id") == Some(&id)
- && (frame.get("result").is_some() || frame.get("error").is_some())
- {
- return (frame, notifications);
- }
- notifications.push(frame);
- }
- }
-
- /// The hosted session handle (the close-drain caller's shape).
- async fn session(&self) -> std::sync::Arc<super::AcpSession> {
- self.state
- .lock()
- .await
- .session
- .as_ref()
- .expect("the session is hosted")
- .session
- .clone()
- }
-
- /// The published `refinement` metas among a turn's notifications.
- fn refinement_metas(notifications: &[serde_json::Value]) -> Vec<serde_json::Value> {
- notifications
- .iter()
- .filter_map(|frame| {
- Some(
- frame
- .get("params")?
- .get("update")?
- .get("_meta")?
- .get(META)?
- .get("refinement")?
- .clone(),
- )
- })
- .collect()
- }
-
- /// The published `compaction` metas.
- fn compaction_metas(notifications: &[serde_json::Value]) -> Vec<serde_json::Value> {
- notifications
- .iter()
- .filter_map(|frame| {
- Some(
- frame
- .get("params")?
- .get("update")?
- .get("_meta")?
- .get(META)?
- .get("compaction")?
- .clone(),
- )
- })
- .collect()
- }
-
- /// The settled assistant usage of the newest assistant turn.
- async fn latest_usage(&self) -> u64 {
- super::super::session::latest_assistant_message(self.engine.session.agent())
- .await
- .expect("an assistant message")
- .usage
- .total_tokens
- }
- }
-
- /// The threshold compaction at the settled boundary arms the trigger
- /// and the serialized checkpoint consumes it in the same prompt: the
- /// review declines (the queued reply after it serves the next turn)
- /// and nothing surfaces.
- #[tokio::test]
- async fn threshold_compaction_consumes_the_trigger_at_the_checkpoint() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- // Probe: the seed turn's usage.
- let mut probe =
- acp_autorefine_bed(json!({ "responses": [{ "text": "seed reply" }] }), 1).await;
- probe
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- let seed_usage = probe.latest_usage().await;
- assert!(
- seed_usage > 0 && seed_usage < 100_000,
- "usage: {seed_usage}"
- );
- drop(probe);
-
- let crossing_delta = (8_000 + "seed turn crossing".len() as u64).div_ceil(4);
- let mut bed = acp_autorefine_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- { "text": "crossing reply" },
- { "text": "the summary" },
- { "text": DECLINE },
- { "text": "third reply" },
- ]
- }),
- 128_000u64
- .saturating_sub(FAUX_REQUEST_BUDGET + seed_usage + crossing_delta / 4)
- .max(1),
- )
- .await;
- let (response, notifications) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- assert!(AcpAutorefineBed::compaction_metas(&notifications).is_empty());
- // The crossing turn compacts and the checkpoint consumes the
- // armed trigger: the decline review ran and surfaced nothing.
- let (response, notifications) = bed
- .prompt(format!("crossing turn {}", "x".repeat(8_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- assert_eq!(AcpAutorefineBed::compaction_metas(&notifications).len(), 1);
- assert!(
- AcpAutorefineBed::refinement_metas(&notifications).is_empty(),
- "the decline surfaced nothing"
- );
- assert!(
- !bed.engine.session.compact_auto_refine_pending(),
- "the trigger was consumed"
- );
- // The review consumed the decline: the next turn sees the reply
- // queued after it (a missed review would answer with the decline
- // text).
- let (response, _) = bed.prompt("third turn".to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let latest = super::super::session::latest_assistant_message(bed.engine.session.agent())
- .await
- .expect("an assistant message");
- let reply = match &latest.content[0] {
- pa_types::ai::AssistantContentBlock::Text(text) => text.text.clone(),
- _ => String::new(),
- };
- assert_eq!(
- reply, "third reply",
- "the review consumed the queued decline"
- );
- }
-
- /// An approving checkpoint round publishes the `refinement` complete
- /// meta (the same mapping the `/refine` command produces) and applies
- /// the durable rows.
- #[tokio::test]
- async fn an_approving_checkpoint_round_publishes_the_refinement_meta() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- // Probe: the seed turn's usage.
- let mut probe =
- acp_autorefine_bed(json!({ "responses": [{ "text": "seed reply" }] }), 1).await;
- probe
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- let seed_usage = probe.latest_usage().await;
- drop(probe);
-
- let review = r#"{"shouldRefine": true, "rationale": "the turn shows a reusable tactic"}"#;
- let plan = r#"{"summary":"note the tactic","rationale":"repeated","expectedOutcome":"recall","edits":[{"action":"create","kind":"memory","id":"m1","title":"Tactic","content":"Use tactic A"}]}"#;
- let crossing_delta = (8_000 + "seed turn crossing".len() as u64).div_ceil(4);
- let mut bed = acp_autorefine_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- { "text": "crossing reply" },
- { "text": "the summary" },
- { "text": review },
- { "text": plan },
- ]
- }),
- 128_000u64
- .saturating_sub(FAUX_REQUEST_BUDGET + seed_usage + crossing_delta / 4)
- .max(1),
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let (response, notifications) = bed
- .prompt(format!("crossing turn {}", "x".repeat(8_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let metas = AcpAutorefineBed::refinement_metas(&notifications);
- assert_eq!(metas.len(), 1, "one refinement meta: {metas:?}");
- assert_eq!(metas[0]["status"], "complete");
- assert_eq!(metas[0]["summary"], "note the tactic");
- assert_eq!(metas[0]["changes"], json!(["create memory:m1"]));
- // The durable rows persisted.
- let rows: Vec<String> = bed
- .engine
- .session
- .shared_persistence()
- .lock()
- .await
- .get_entries()
- .iter()
- .filter_map(|entry| match entry {
- pa_types::session::FileEntry::CustomMessage { payload, .. } => {
- Some(payload.custom_type.clone())
- }
- _ => None,
- })
- .collect();
- assert!(
- rows.iter().any(|kind| kind == "refinement_outcome")
- && rows.iter().any(|kind| kind == "refinement_notice"),
- "the refinement rows persisted: {rows:?}"
- );
- }
-
- /// The session-close drain (TS `dispose`): a `/compact` session
- /// command arms the trigger no turn services, and the close runs the
- /// round — an approving review publishes its refinement meta before
- /// the subscription tears down.
- #[tokio::test]
- async fn session_close_drains_an_armed_trigger() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let review = r#"{"shouldRefine": true, "rationale": "the turn shows a reusable tactic"}"#;
- let plan = r#"{"summary":"note the tactic","rationale":"repeated","expectedOutcome":"recall","edits":[{"action":"create","kind":"memory","id":"m1","title":"Tactic","content":"Use tactic A"}]}"#;
- let mut bed = acp_autorefine_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- { "text": "second reply" },
- { "text": "the summary" },
- { "text": review },
- { "text": plan },
- ]
- }),
- // reserve 1: the threshold headroom never crosses, so only
- // the `/compact` session command compacts and arms.
- 1,
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let (response, _) = bed
- .prompt(format!("second turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- // The `/compact` session command: the compaction runs, no turn
- // follows, and the trigger stays armed for the close drain.
- let (response, notifications) = bed.prompt("/compact".to_string()).await;
- for entry in bed
- .engine
- .session
- .shared_persistence()
- .lock()
- .await
- .get_entries()
- {
- if let pa_types::session::FileEntry::CustomMessage { payload, .. } = entry {
- eprintln!(
- "CLOSE-TEST row {} {:?}",
- payload.custom_type, payload.content
- );
- }
- }
- assert_eq!(response["result"]["stopReason"], "end_turn");
- assert_eq!(AcpAutorefineBed::compaction_metas(&notifications).len(), 1);
- assert!(
- bed.engine.session.compact_auto_refine_pending(),
- "the session command armed the trigger"
- );
- let session = bed.session().await;
- session.drain_compact_auto_refine_at_close(&bed.mode).await;
- assert!(
- !bed.engine.session.compact_auto_refine_pending(),
- "the drain consumed the trigger"
- );
- // The approved round published its refinement meta.
- let mut metas = Vec::new();
- while let Ok(frame) = bed.frames.try_recv() {
- if let Some(meta) = frame
- .get("params")
- .and_then(|params| params.get("update"))
- .and_then(|update| update.get("_meta"))
- .and_then(|meta| meta.get(META))
- .and_then(|meta| meta.get("refinement"))
- .cloned()
- {
- metas.push(meta);
- }
- }
- assert_eq!(metas.len(), 1, "one refinement meta: {metas:?}");
- assert_eq!(metas[0]["status"], "complete");
- }
-}
diff --git a/crates/pa-daemon/src/acp/compaction_arms.rs b/crates/pa-daemon/src/acp/compaction_arms.rs
deleted file mode 100644
index 3aba8f80ef..0000000000
--- a/crates/pa-daemon/src/acp/compaction_arms.rs
+++ /dev/null
@@ -1,672 +0,0 @@
-//! The automatic compaction arms on the in-process ACP turn path: the TS
-//! `_checkCompaction` boundary (overflow Case 1, the model-requested arm,
-//! and the threshold arm) plus `_runPreTurnCompaction` and
-//! `_consumePendingRequestedRefine`, ported onto the ACP transport.
-//!
-//! TS ground truth: the arms live inside the `AgentSession` turn loop
-//! (agent-session.ts), so every transport that drives the session —
-//! interactive, daemon, RPC, and ACP — runs them. TS acp-mode.ts relies on
-//! it (its turn-boundary keying documents that auto-compaction rebuilds
-//! the transcript mid-turn) and its event adapter maps the `compaction_end`
-//! session event to the namespaced `compaction` meta. The Rust
-//! in-process ACP transport drives the pa-core session engine directly,
-//! so the arms run here, at its turn boundaries; the daemon-attached ACP
-//! transport already hosts the worker turn loop with its arms
-//! (`agent_engine.rs` / `auto_compaction.rs` / `overflow_compaction.rs`).
-//!
-//! Wire shapes: every arm outcome publishes the ACP `compaction_end`
-//! mapping — a ran compaction carries `tokensBefore`/`summary`, every
-//! skipped, failed, or cancelled run carries the empty payload (TS
-//! `compaction_end` with `result: undefined`). `compaction_start` has no
-//! ACP mapping (the TS adapter drops it), so no start frame goes out.
-//! The durable `compaction_outcome` disclosure row for unsuccessful runs
-//! is persisted through the pa-core session seam, exactly like the
-//! daemon arms.
-//!
-//! The compaction abort slot mirrors TS `_autoCompactionAbortController`:
-//! session/cancel and session/close abort an in-flight arm compaction (TS
-//! `requestAbort` calls `abortCompaction()`).
-
-use std::sync::Arc;
-
-use pa_agent::abort::AbortController;
-use pa_core::session_engine::compact_session::CompactOutcome;
-use pa_core::session_engine::compaction_exec::CompactionResult;
-use pa_core::session_engine::engine::SessionEngine;
-use pa_core::session_engine::messages::{CompactionOutcomeKind, CompactionOutcomeReason};
-use pa_types::ai::{AssistantMessage, Model};
-
-use crate::overflow_compaction::{OverflowRecovery, OVERFLOW_RECOVERY_FAILED_MESSAGE};
-
-use super::events::AcpEngineEvent;
-use super::session::AcpSession;
-use super::AcpModeState;
-
-/// Whether the threshold arm queues the goal continuation before it
-/// compacts (TS `_checkCompaction`'s `queueAutonomousContinuation`
-/// parameter): the settled-turn boundary queues (the minted turn drives
-/// the post-compaction continue), the pre-turn check does not.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) enum ThresholdGoalQueue {
- /// The settled-turn policy (TS default `true`): mint the goal
- /// continuation before the threshold compaction runs.
- Queue,
- /// The pre-turn policy (TS `_runPreTurnCompaction` passes `false`).
- Skip,
-}
-
-/// What the settled-turn check decided for the turn loop (the TS
-/// `_checkCompaction` outcome plus the stop semantics the TS loop derives
-/// from it).
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) enum CompactionCheckRun {
- /// The check finished without a will-retry (no arm fired, or an arm
- /// consumed the boundary without a retry): the turn loop consumes
- /// the requested refinement, then applies the turn's own semantics
- /// (a failed turn ends the run with its error, a settled turn
- /// reaches the autonomous decision).
- Proceed,
- /// The overflow arm compacted and the turn re-issues (TS
- /// `willRetry`: the model turn re-runs on the compacted context
- /// without a new user message). No refine consumption happens at a
- /// will-retry boundary (TS skips `_consumePendingRequestedRefine`
- /// when `compactionWillRetry`).
- OverflowRetry,
- /// A requested compaction consumed the boundary and stops the run on
- /// purpose: the model resumes on the next prompt.
- RequestedStop,
-}
-
-/// What one overflow Case-1 attempt decided (TS `_checkCompaction` Case 1
-/// returns `false` for every non-retry outcome, so the requested and
-/// threshold arms never fire after a matched case).
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum OverflowAttempt {
- /// The Case-1 guard did not match (no overflow, a different model, a
- /// stale pre-compaction error, or compaction disabled with no pending
- /// request): the check continues to the requested and threshold arms.
- Continue,
- /// The compact-and-retry ran: the turn re-issues.
- Retry,
- /// The case matched and is done (TS `return false`): the one-attempt
- /// state blocked a fresh run, or a compaction ran and ended without a
- /// retry.
- Done,
-}
-
-/// The arm state on one ACP session (TS session-lifetime state:
-/// `_overflowRecovery` and `_autoCompactionAbortController`).
-pub(super) struct CompactionArms {
- overflow_recovery: std::sync::Mutex<OverflowRecovery>,
- auto_compaction_abort: std::sync::Mutex<Option<Arc<AbortController>>>,
-}
-
-impl CompactionArms {
- pub(super) fn new() -> Self {
- Self {
- overflow_recovery: std::sync::Mutex::new(OverflowRecovery::Idle),
- auto_compaction_abort: std::sync::Mutex::new(None),
- }
- }
-
- /// Reset the overflow recovery state (TS `startsAgentRun` at
- /// `message_start`: a user row that starts an agent run resets
- /// `_overflowRecovery`, as does every settled non-error assistant
- /// message — the turn loop owns that reset).
- pub(super) fn reset(&self) {
- *self
- .overflow_recovery
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner) = OverflowRecovery::Idle;
- }
-
- fn overflow_recovery(&self) -> std::sync::MutexGuard<'_, OverflowRecovery> {
- self.overflow_recovery
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- }
-
- /// Abort an in-flight arm compaction (TS `abortCompaction`): the
- /// summarizer race drops the request and the arm settles its
- /// cancelled outcome.
- fn abort_in_flight(&self) {
- if let Some(controller) = self
- .auto_compaction_abort
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .take()
- {
- controller.abort();
- }
- }
-
- fn install_abort_controller(&self) -> Arc<AbortController> {
- let controller = Arc::new(AbortController::new());
- *self
- .auto_compaction_abort
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::clone(&controller));
- controller
- }
-
- fn clear_abort_controller(&self, controller: &Arc<AbortController>) {
- let mut slot = self
- .auto_compaction_abort
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- if slot
- .as_ref()
- .is_some_and(|live| Arc::ptr_eq(live, controller))
- {
- *slot = None;
- }
- }
-}
-
-impl AcpSession {
- /// TS `_checkCompaction` at the settled-turn boundary (`agent_end`):
- /// the overflow Case 1 first (it consumes any pending model request),
- /// then the requested arm (which never falls through to the threshold
- /// arm), then the threshold arm. `assistant` is the turn's settled
- /// message; an aborted message never reaches here (the turn loop
- /// classifies aborts first, dropping the boundary requests). The
- /// return carries the threshold arm's held goal continuation (the
- /// goal-queue mint before the compaction; the settle loop runs it as
- /// the post-compaction turn).
- pub(super) async fn check_compaction(
- &self,
- mode: &AcpModeState,
- assistant: &AssistantMessage,
- goal_queue: ThresholdGoalQueue,
- ) -> (CompactionCheckRun, Option<pa_types::session::CustomMessage>) {
- // The boundary reads the model and its request key as ONE pair
- // through the config queue: a concurrent picker switch holds the
- // same queue while it swaps the slots, so no arm can pair the
- // pre-switch model with the switched provider's key.
- let (model, api_key) = mode.model_and_api_key().await;
- let Some(model) = model else {
- // TS reads `this.model?.contextWindow ?? 0`: a session
- // without a resolvable model never crosses a threshold.
- return (CompactionCheckRun::Proceed, None);
- };
- match self
- .overflow_attempt(mode, assistant, &model, api_key.clone())
- .await
- {
- OverflowAttempt::Retry => return (CompactionCheckRun::OverflowRetry, None),
- // A matched case is done (TS `return false`): the requested
- // and threshold arms never fire after it.
- OverflowAttempt::Done => return (CompactionCheckRun::Proceed, None),
- OverflowAttempt::Continue => {}
- }
- if self
- .requested_arm(mode, &model, api_key.clone())
- .await
- .was_consumed()
- {
- return (CompactionCheckRun::RequestedStop, None);
- }
- let held = self
- .threshold_arm(mode, &model, api_key, assistant, goal_queue)
- .await;
- (CompactionCheckRun::Proceed, held)
- }
-
- /// TS `_runPreTurnCompaction` before an admitted prompt: the same
- /// check over the last assistant message of the loop context, with
- /// the pre-turn semantics — an aborted last assistant drops its
- /// pending requests but the checks still run, and an overflow
- /// recovery never re-issues (the admitted prompt proceeds on the
- /// compacted context; TS `resumeAfterFailure` excludes overflow).
- pub(super) async fn run_pre_turn_compaction(&self, mode: &AcpModeState) {
- let Some(assistant) =
- super::session::latest_assistant_message(mode.engine.session.agent()).await
- else {
- return;
- };
- if assistant.stop_reason == pa_types::ai::StopReason::Aborted {
- // TS `skipAbortedCheck = false`: the aborted turn's pending
- // requests drop, then the checks continue.
- mode.engine.turn_boundary.clear_pending().await;
- }
- // A pre-turn threshold compaction never queues the goal
- // continuation (TS `_runPreTurnCompaction` passes
- // `queueAutonomousContinuation = false`), so the check holds
- // nothing.
- let (_, held) = self
- .check_compaction(mode, &assistant, ThresholdGoalQueue::Skip)
- .await;
- drop(held);
- }
-
- /// TS `_consumePendingRequestedRefine`: taken regardless of outcome,
- /// so a failed run is not silently re-run on the next boundary. The
- /// outcomes publish like the `/refine` command events.
- pub(super) async fn consume_requested_refine(&self, mode: &AcpModeState) {
- // The config queue serializes the round against picker switches
- // (the review runs on the model the session reports).
- let _guard = mode.config_queue.lock().await;
- let Some(model) = mode.current_model().await else {
- return;
- };
- let Some(refinement) = mode
- .engine
- .consume_pending_refinement(
- &model,
- mode.current_api_key().await,
- mode.agent_dir.as_path().to_path_buf(),
- )
- .await
- else {
- return;
- };
- match refinement {
- Ok(result) => {
- let event = super::autorefine::refine_complete_event(&result);
- self.publish_engine_event(&event).await;
- }
- Err(error) => {
- self.publish_engine_event(&AcpEngineEvent::RefineFailed {
- error: format!("{error:#}"),
- })
- .await;
- }
- }
- }
-
- /// Drop pending turn-boundary requests (an aborted turn never
- /// services them; TS `_checkCompaction`'s abort arm clears both the
- /// compaction and the refine request).
- pub(super) async fn clear_turn_boundary_requests(&self, engine: &SessionEngine) {
- engine.turn_boundary.clear_pending().await;
- }
-
- /// Reset the overflow recovery state (the turn loop calls it at
- /// every settled non-error turn and every admitted prompt).
- pub(super) fn reset_overflow_recovery(&self) {
- self.arms.reset();
- }
-
- /// Abort an in-flight arm compaction (session/cancel, session/close,
- /// and stdin teardown).
- pub(super) fn abort_auto_compaction(&self) {
- self.arms.abort_in_flight();
- }
-
- /// The TS `_checkCompaction` threshold arm: the live context over
- /// the reserve headroom (the pa-core decision), one compaction when
- /// it crossed, the `compaction_end` mapping either way. Under the
- /// settled boundary's queue policy (TS
- /// `_queueGoalContinuationForThresholdCompaction`), an active goal's
- /// continuation is minted BEFORE the compaction runs — the minted
- /// turn is what drives the post-compaction continue, and the mint's
- /// `goal_update` publishes ahead of the compaction frames like the
- /// TS event order. A cancelled compaction withdraws the mint (the
- /// slot rolls back); skip and failure keep it (TS
- /// `resumeAfterFailure`).
- async fn threshold_arm(
- &self,
- mode: &AcpModeState,
- model: &Model,
- api_key: Option<String>,
- assistant: &AssistantMessage,
- goal_queue: ThresholdGoalQueue,
- ) -> Option<pa_types::session::CustomMessage> {
- let engine = &mode.engine;
- if !engine.session.auto_compaction_due(model).await {
- return None;
- }
- // TS's queue-site guard: error and aborted turns never queue the
- // goal continuation.
- let settled_turn = !matches!(
- assistant.stop_reason,
- pa_types::ai::StopReason::Error | pa_types::ai::StopReason::Aborted
- );
- let held = match goal_queue {
- ThresholdGoalQueue::Queue if settled_turn => {
- super::goal_continuation::mint_goal_continuation(mode, self).await
- }
- _ => None,
- };
- let outcome = run_compaction(self, engine, model, api_key, None).await;
- let cancelled = outcome
- .as_ref()
- .err()
- .is_some_and(pa_agent::abort::is_abort_error);
- self.finish_compaction(engine, CompactionOutcomeReason::Threshold, outcome)
- .await;
- if cancelled && held.is_some() {
- // TS `_clearQueuedGoalContinuationAfterCancelledThresholdCompaction`:
- // withdraw the queued continuation and roll the slot back.
- super::goal_continuation::rollback_goal_mint(mode).await;
- return None;
- }
- held
- }
-
- /// The TS `_checkCompaction` requested arm: a pending `compact.run`
- /// request consumed at the boundary (any outcome consumed it; the
- /// run stops the turn loop on purpose).
- async fn requested_arm(
- &self,
- mode: &AcpModeState,
- model: &Model,
- api_key: Option<String>,
- ) -> RequestedArmRun {
- let engine = &mode.engine;
- if !engine.turn_boundary.compaction_scheduled().await {
- return RequestedArmRun::None;
- }
- let instructions = engine
- .turn_boundary
- .take_compaction()
- .await
- .and_then(|pending| pending.instructions);
- let outcome = run_compaction(self, engine, model, api_key, instructions.as_deref()).await;
- self.finish_compaction(engine, CompactionOutcomeReason::Requested, outcome)
- .await;
- RequestedArmRun::Consumed
- }
-
- /// The shared outcome→event mapping for the threshold and requested
- /// arms (TS `_runAutoCompaction`'s success / catch arms): a ran
- /// compaction publishes its result (and counts adoption telemetry),
- /// a skip records the warning disclosure, a cancel records the
- /// aborted disclosure, and a failure records the error disclosure.
- async fn finish_compaction(
- &self,
- engine: &SessionEngine,
- reason: CompactionOutcomeReason,
- outcome: anyhow::Result<CompactOutcome>,
- ) {
- match outcome {
- Ok(CompactOutcome::Ran(run)) => {
- if let Some(telemetry) = &engine.telemetry {
- telemetry.note_compaction(Some(run.duration_ms));
- }
- // TS `_scheduleAutoRefineAfterCompaction`: the compaction
- // arms the compact-trigger review; the serialized
- // checkpoint consumes it (autorefine.rs).
- engine.session.mark_compact_auto_refine_pending();
- publish_compaction_end(self, Some(&run.result)).await;
- }
- Ok(CompactOutcome::Skipped(message)) => {
- let text = if reason == CompactionOutcomeReason::Requested {
- format!("Requested compaction skipped: {message}")
- } else {
- format!("Auto-compaction skipped: {message}")
- };
- end_compaction_unsuccessfully(
- self,
- engine,
- reason,
- CompactionOutcomeKind::Skipped,
- &text,
- )
- .await;
- }
- Err(error) if pa_agent::abort::is_abort_error(&error) => {
- let text = if reason == CompactionOutcomeReason::Requested {
- "Requested compaction cancelled"
- } else {
- "Compaction cancelled"
- };
- end_compaction_unsuccessfully(
- self,
- engine,
- reason,
- CompactionOutcomeKind::Cancelled,
- text,
- )
- .await;
- }
- Err(error) => {
- let text = match reason {
- CompactionOutcomeReason::Requested => {
- format!("Requested compaction failed: {error:#}")
- }
- _ => format!("Auto-compaction failed: {error:#}"),
- };
- end_compaction_unsuccessfully(
- self,
- engine,
- reason,
- CompactionOutcomeKind::Failed,
- &text,
- )
- .await;
- }
- }
- }
-
- /// The TS `_checkCompaction` Case 1 body: guards (same model, not
- /// before the latest compaction, enabled-or-requested, and an actual
- /// context overflow), the one-attempt state machine, and the
- /// compact-and-retry. The error turn leaves the loop context before
- /// the compaction runs (it stays in the session history), and a ran
- /// compaction drops it again from the rebuilt tail.
- async fn overflow_attempt(
- &self,
- mode: &AcpModeState,
- assistant: &AssistantMessage,
- model: &Model,
- api_key: Option<String>,
- ) -> OverflowAttempt {
- let engine = &mode.engine;
- // TS `sameModel`: a model switch must not compact for the old
- // model's overflow.
- if assistant.provider != model.provider || assistant.model != model.id {
- return OverflowAttempt::Continue;
- }
- // TS `assistantIsFromBeforeCompaction`: a stale pre-compaction
- // overflow must not retrigger.
- if engine
- .session
- .latest_compaction_timestamp()
- .await
- .is_some_and(|timestamp| assistant.timestamp <= timestamp)
- {
- return OverflowAttempt::Continue;
- }
- // Enablement: the compaction settings gate, or a pending model
- // request (the run below consumes it and honors its
- // instructions).
- let pending_scheduled = engine.turn_boundary.compaction_scheduled().await;
- let enabled = engine.session.auto_compaction_enabled();
- if !enabled && !pending_scheduled {
- return OverflowAttempt::Continue;
- }
- if !pa_ai::is_context_overflow(assistant, Some(model.context_window)) {
- return OverflowAttempt::Continue;
- }
- // One recovery attempt per overflow (TS `_overflowRecovery`): a
- // matched case with a non-idle state is done (TS `return false`)
- // — the reported state publishes nothing, the attempted state
- // reports its one failure disclosure.
- let first_attempt = {
- let mut recovery = self.arms.overflow_recovery();
- match *recovery {
- OverflowRecovery::Idle => {
- *recovery = OverflowRecovery::Attempted;
- true
- }
- OverflowRecovery::Attempted => {
- *recovery = OverflowRecovery::Reported;
- false
- }
- OverflowRecovery::Reported => return OverflowAttempt::Done,
- }
- };
- if !first_attempt {
- // The retry still overflows: report once (the durable
- // outcome row plus the empty ACP payload).
- end_compaction_unsuccessfully(
- self,
- engine,
- CompactionOutcomeReason::Overflow,
- CompactionOutcomeKind::Failed,
- OVERFLOW_RECOVERY_FAILED_MESSAGE,
- )
- .await;
- return OverflowAttempt::Done;
- }
- // Remove the error turn from the loop context first (TS: it
- // stays in the session history, but the retry must not re-send
- // it).
- engine
- .session
- .drop_trailing_assistant(pa_core::session_engine::TrailingAssistantFilter::Any)
- .await;
- // Any compaction consumes a pending model request (overflow can
- // fire first and take the request with it).
- let instructions = engine
- .turn_boundary
- .take_compaction()
- .await
- .and_then(|pending| pending.instructions);
- let outcome = run_compaction(self, engine, model, api_key, instructions.as_deref()).await;
- match outcome {
- Ok(CompactOutcome::Ran(run)) => {
- if let Some(telemetry) = &engine.telemetry {
- telemetry.note_compaction(Some(run.duration_ms));
- }
- // TS `_scheduleAutoRefineAfterCompaction`: the compaction
- // arms the compact-trigger review; the retried turn's
- // serialized checkpoint consumes it (TS defers behind the
- // will-retry continuation).
- engine.session.mark_compact_auto_refine_pending();
- publish_compaction_end(self, Some(&run.result)).await;
- // The compaction rebuild re-adds the error turn from the
- // kept tail: drop it again so the retried request is
- // free of it (TS will-retry branch).
- engine
- .session
- .drop_trailing_assistant(
- pa_core::session_engine::TrailingAssistantFilter::ErrorOnly,
- )
- .await;
- OverflowAttempt::Retry
- }
- // A skipped overflow recovery does not re-issue (TS excludes
- // overflow from `resumeAfterFailure`).
- Ok(CompactOutcome::Skipped(message)) => {
- end_compaction_unsuccessfully(
- self,
- engine,
- CompactionOutcomeReason::Overflow,
- CompactionOutcomeKind::Skipped,
- &format!("Auto-compaction skipped: {message}"),
- )
- .await;
- OverflowAttempt::Done
- }
- Err(error) if pa_agent::abort::is_abort_error(&error) => {
- end_compaction_unsuccessfully(
- self,
- engine,
- CompactionOutcomeReason::Overflow,
- CompactionOutcomeKind::Cancelled,
- "Compaction cancelled",
- )
- .await;
- OverflowAttempt::Done
- }
- Err(error) => {
- end_compaction_unsuccessfully(
- self,
- engine,
- CompactionOutcomeReason::Overflow,
- CompactionOutcomeKind::Failed,
- &format!("Context overflow recovery failed: {error:#}"),
- )
- .await;
- OverflowAttempt::Done
- }
- }
- }
-}
-
-/// Whether the requested arm consumed the boundary.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum RequestedArmRun {
- None,
- Consumed,
-}
-
-impl RequestedArmRun {
- fn was_consumed(self) -> bool {
- self == RequestedArmRun::Consumed
- }
-}
-
-/// One compaction run shared by every arm (TS `_runAutoCompaction`'s
-/// provider half): the abort slot is held for the run's duration and the
-/// summarizer races the abort signal. Returns the raw outcome; the caller
-/// maps it to its arm's event shapes.
-async fn run_compaction(
- session: &AcpSession,
- engine: &SessionEngine,
- model: &Model,
- api_key: Option<String>,
- instructions: Option<&str>,
-) -> anyhow::Result<CompactOutcome> {
- let controller = session.arms.install_abort_controller();
- let signal = controller.signal();
- let compact = async {
- engine
- .session
- .compact(instructions, model, api_key, Some(&signal))
- .await
- };
- let outcome = pa_agent::abort::race_with_abort(compact, &signal).await;
- session.arms.clear_abort_controller(&controller);
- // The race's outer `Err` is the abort marker (the summarizer was
- // dropped); the inner `Err` is the compaction's own failure — both
- // surface as the caller's `Err` for `is_abort_error` to classify.
- outcome?
-}
-
-/// Publish the ACP `compaction_end` mapping for one arm outcome: a ran
-/// compaction carries its result, every other outcome carries the empty
-/// payload (TS `compaction_end` with `result: undefined`).
-async fn publish_compaction_end(session: &AcpSession, ran: Option<&CompactionResult>) {
- let event = match ran {
- Some(result) => AcpEngineEvent::CompactionEnd {
- tokens_before: Some(result.tokens_before),
- summary: Some(result.summary.clone()),
- },
- None => AcpEngineEvent::CompactionEnd {
- tokens_before: None,
- summary: None,
- },
- };
- session.publish_engine_event(&event).await;
-}
-
-/// Record the durable `compaction_outcome` disclosure row for an
-/// unsuccessful run (TS `_persistCompactionOutcome` via
-/// `_endCompactionUnsuccessfully`), then publish the empty ACP payload.
-async fn end_compaction_unsuccessfully(
- session: &AcpSession,
- engine: &SessionEngine,
- reason: CompactionOutcomeReason,
- outcome: CompactionOutcomeKind,
- message: &str,
-) {
- engine
- .session
- .record_compaction_outcome(reason, outcome, message)
- .await
- .inspect_err(|error| {
- eprintln!("pa-daemon: compaction outcome persistence failed: {error:#}");
- })
- .ok();
- publish_compaction_end(session, None).await;
-}
-// The unit battery lives in the child module (compaction_arms::tests);
-// the faux-provider std lock note moves with it (the async tests hold
-// it across their awaits on purpose; the tests are the only contenders,
-// so no cross-task deadlock).
-#[cfg(test)]
-#[allow(clippy::await_holding_lock)]
-mod tests;
diff --git a/crates/pa-daemon/src/acp/compaction_arms/tests.rs b/crates/pa-daemon/src/acp/compaction_arms/tests.rs
deleted file mode 100644
index acf910a5c8..0000000000
--- a/crates/pa-daemon/src/acp/compaction_arms/tests.rs
+++ /dev/null
@@ -1,630 +0,0 @@
-//! The compaction-arms unit battery: the threshold arm, the overflow
-//! attempts, the requested arm, and the abort slot.
-use super::*;
-use crate::agent_engine::FAUX_TEST_LOCK;
-
-/// The faux model's per-request output budget (maxTokens `16_384` under the
-/// `32_000` request cap): threshold fixtures subtract it from the window
-/// alongside the headroom (the combined input+output ceiling).
-const FAUX_REQUEST_BUDGET: u64 = 16_384;
-
-use pa_core::session_engine::engine::{create_session, SessionEngineConfig};
-use pa_core::session_engine::provider_adapter::{json_round_trip, real_stream_fn};
-use serde_json::json;
-use tokio::sync::{mpsc, Mutex};
-
-use super::super::producer::UpdateProducer;
-use super::super::prompt::handle_session_prompt;
-use super::super::session::AcpSession;
-use super::super::{AcpModeState, ConnectionState, SessionEntry};
-
-/// The ACP meta namespace on the wire.
-const META: &str = "ai.primeintellect.prime-agent";
-
-/// One armed ACP prompt turn over an in-process faux engine. The faux
-/// provider registry is process-global, so every test holds the
-/// shared lock like the daemon engine tests.
-struct AcpTestBed {
- mode: AcpModeState,
- state: std::sync::Arc<Mutex<ConnectionState>>,
- session_id: String,
- tx: super::super::producer::FrameSink,
- frames: mpsc::UnboundedReceiver<serde_json::Value>,
- next_request_id: u64,
- engine: std::sync::Arc<SessionEngine>,
- /// Held so the engine's cwd outlives the test.
- _dir: tempfile::TempDir,
-}
-
-/// Build one bed: the faux script drives the provider, the compaction
-/// settings come from the agent dir, and the ACP session wraps the
-/// engine exactly like `session/new` does.
-async fn acp_test_bed(
- script: serde_json::Value,
- reserve_tokens: u64,
- keep_recent_tokens: u64,
-) -> AcpTestBed {
- let dir = tempfile::TempDir::new().unwrap();
- let agent_dir = dir.path().join("agent");
- std::fs::create_dir_all(&agent_dir).unwrap();
- std::fs::write(
- agent_dir.join("settings.json"),
- json!({
- "compaction": {
- "enabled": true,
- "reserveTokens": reserve_tokens,
- "keepRecentTokens": keep_recent_tokens,
- }
- })
- .to_string(),
- )
- .unwrap();
- let parsed = pa_ai::faux::script::parse_faux_script(&script)
- .map_err(anyhow::Error::msg)
- .unwrap();
- let registration = pa_ai::faux::script::register_faux_provider_from_script(&parsed);
- let model = registration.get_model();
- let agent_model: pa_agent::types::Model = json_round_trip(&model).expect("model conversion");
- let stream_fn = real_stream_fn(None, model.clone());
- let engine = std::sync::Arc::new(
- create_session(SessionEngineConfig {
- semantic_edges: None,
- cron_store: None,
- queued_steering_probe: None,
- image_model_router: None,
- steering_mode: None,
- follow_up_mode: None,
- telemetry: None,
- cwd: dir.path().to_path_buf(),
- agent_dir: agent_dir.clone(),
- mcp_manager: None,
- model: Some(agent_model),
- thinking_level: None,
- stream_fn: Some(stream_fn),
- tools: Vec::new(),
- custom_system_prompt: None,
- prompt_guidelines: Vec::new(),
- generic_mcp_servers: Vec::new(),
- allow_recursion: None,
- session_manager: None,
- extra_host_handlers: None,
- conversation_log_path: None,
- additional_skill_paths: Vec::new(),
- additional_prompt_paths: Vec::new(),
- extra_builtin_skill_overrides: Vec::new(),
- rlm_subagent_host: None,
- rlm_depth: None,
- model_info: Some(model.clone()),
- prewarm_ipython_kernel: None,
- on_background_work_settled: None,
- queued_goal_context_purge: None,
- })
- .await
- .unwrap(),
- );
- let (tx, frames) = mpsc::unbounded_channel::<serde_json::Value>();
- let session_id = "acp-test-session".to_string();
- let producer = UpdateProducer::new(session_id.clone(), tx.clone());
- let autonomous = std::sync::Arc::new(Mutex::new(
- pa_core::autonomous::create_autonomous_runtime_state(None, None),
- ));
- let driver: std::sync::Arc<dyn pa_core::autonomous::AutonomousDriver> =
- std::sync::Arc::new(pa_core::autonomous::ShellAutonomousDriver::new(dir.path()));
- let session = std::sync::Arc::new(
- AcpSession::new(
- session_id.clone(),
- engine.clone(),
- producer.clone(),
- autonomous,
- driver,
- )
- .await,
- );
- producer.commit_session_new_response().await;
- let state = std::sync::Arc::new(Mutex::new(ConnectionState {
- session: Some(SessionEntry {
- session,
- prompt_task: None,
- config: std::sync::Arc::new(super::super::InProcessConfig {
- published: tokio::sync::Mutex::new(Vec::new()),
- models: tokio::sync::Mutex::new(Vec::new()),
- }),
- config_refresh: None,
- }),
- session_new_in_flight: false,
- session_close_in_flight: false,
- }));
- let mode = AcpModeState {
- engine: engine.clone(),
- actual_cwd: std::sync::Arc::new(dir.path().to_path_buf()),
- product_version: std::sync::Arc::new("test".to_string()),
- model: std::sync::Arc::new(Mutex::new(Some(model))),
- api_key: std::sync::Arc::new(Mutex::new(None)),
- config_queue: std::sync::Arc::new(tokio::sync::Mutex::new(())),
- agent_dir: std::sync::Arc::new(agent_dir),
- provider_target: std::sync::Arc::new(std::sync::RwLock::new(None)),
- autonomous_config: None,
- mcp: engine.mcp_manager.clone(),
- mcp_owner_id: std::sync::Arc::new("acp-test-owner".to_string()),
- mcp_server_names: std::sync::Arc::new(Mutex::new(Vec::new())),
- };
- AcpTestBed {
- mode,
- state,
- session_id,
- tx,
- frames,
- next_request_id: 0,
- engine,
- _dir: dir,
- }
-}
-
-impl AcpTestBed {
- /// Admit one prompt through the real ACP prompt handler and read
- /// frames until its response: (response, notifications in order).
- async fn prompt(&mut self, text: String) -> (serde_json::Value, Vec<serde_json::Value>) {
- self.next_request_id += 1;
- let id = serde_json::Value::from(self.next_request_id);
- handle_session_prompt(
- id.clone(),
- json!({
- "sessionId": self.session_id,
- "prompt": [{ "type": "text", "text": text }],
- }),
- self.state.clone(),
- self.mode.clone(),
- self.tx.clone(),
- )
- .await;
- let mut notifications = Vec::new();
- loop {
- let Some(frame) = self.frames.recv().await else {
- panic!("ACP frame channel closed before the response");
- };
- if frame.get("id") == Some(&id)
- && (frame.get("result").is_some() || frame.get("error").is_some())
- {
- return (frame, notifications);
- }
- notifications.push(frame);
- }
- }
-
- /// The published `compaction` metas (the ACP `compaction_end`
- /// mapping) among a turn's notifications.
- fn compaction_metas(notifications: &[serde_json::Value]) -> Vec<serde_json::Value> {
- notifications
- .iter()
- .filter_map(|frame| {
- Some(
- frame
- .get("params")?
- .get("update")?
- .get("_meta")?
- .get(META)?
- .get("compaction")?
- .clone(),
- )
- })
- .collect()
- }
-
- /// The settled assistant usage of the newest assistant turn.
- async fn latest_usage(&self) -> u64 {
- super::super::session::latest_assistant_message(self.engine.session.agent())
- .await
- .expect("an assistant message")
- .usage
- .total_tokens
- }
-
- /// The durable entry chain.
- async fn entries(&self) -> Vec<pa_types::session::FileEntry> {
- self.engine
- .session
- .shared_persistence()
- .lock()
- .await
- .get_entries()
- }
-}
-
-/// The TS overflow error shape: an Anthropic token-overflow message.
-/// The retry-turn entry paces the stream (`delayMs`) so its settled
-/// message timestamp lands strictly after the compaction entry's (the
-/// `assistantIsFromBeforeCompaction` guard compares millisecond
-/// timestamps; a real provider round-trip spans more than one).
-fn overflow_error(delay_ms: u64) -> serde_json::Value {
- let mut entry = json!({
- "text": "",
- "stopReason": "error",
- "errorMessage": "prompt is too long: 213462 tokens > 200000 maximum",
- });
- if delay_ms > 0 {
- entry["delayMs"] = json!(delay_ms);
- }
- entry
-}
-
-/// The threshold arm on the ACP turn path: a settled turn whose usage
-/// crosses the reserve headroom runs one compaction at the boundary
-/// and publishes the `compaction` meta (tokensBefore + summary), and
-/// the turn still settles with `end_turn`. The faux provider
-/// estimates usage from the serialized context, so the probe measures
-/// one seed turn's usage and the reserve sits between the two turns'
-/// usage (the daemon engine tests' environment-independent recipe).
-#[tokio::test]
-async fn threshold_arm_compacts_and_publishes_the_acp_meta() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- // Probe: the seed turn's total usage (system prompt included).
- let mut probe = acp_test_bed(json!({ "responses": [{ "text": "seed reply" }] }), 1, 10).await;
- probe
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- let seed_usage = probe.latest_usage().await;
- assert!(
- seed_usage > 0 && seed_usage < 100_000,
- "usage: {seed_usage}"
- );
- drop(probe);
-
- // The crossing prompt adds ~2000 tokens; the headroom sits
- // between the two turns' usage (500-token margins on both
- // sides).
- let crossing_delta = (8_000 + "seed turn crossing".len() as u64).div_ceil(4);
- let mut bed = acp_test_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- { "text": "crossing reply" },
- { "text": "the summary" },
- ]
- }),
- 128_000u64
- .saturating_sub(FAUX_REQUEST_BUDGET + seed_usage + crossing_delta / 4)
- .max(1),
- 10,
- )
- .await;
- // The seed turn stays below the headroom: no compaction.
- let (response, notifications) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- assert!(AcpTestBed::compaction_metas(&notifications).is_empty());
- // The threshold-crossing turn: the settled usage fires one
- // compaction at the boundary (the summarizer consumed the third
- // scripted response).
- let (response, notifications) = bed
- .prompt(format!("crossing turn {}", "x".repeat(8_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let metas = AcpTestBed::compaction_metas(&notifications);
- assert_eq!(metas.len(), 1, "one compaction meta: {metas:?}");
- assert_eq!(metas[0]["summary"], "the summary");
- assert!(metas[0]["tokensBefore"].as_u64().unwrap() > 0);
- assert!(
- bed.entries()
- .await
- .iter()
- .any(|entry| matches!(entry, pa_types::session::FileEntry::Compaction { .. })),
- "the compaction persisted"
- );
-}
-
-/// Below the headroom nothing fires: no compaction meta, no entry.
-#[tokio::test]
-async fn below_headroom_no_arm_fires() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = acp_test_bed(json!({ "responses": [{ "text": "small reply" }] }), 1, 10).await;
- let (response, notifications) = bed.prompt("small turn".to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- assert!(AcpTestBed::compaction_metas(&notifications).is_empty());
- assert!(!bed
- .entries()
- .await
- .iter()
- .any(|entry| matches!(entry, pa_types::session::FileEntry::Compaction { .. })));
-}
-
-/// The overflow arm on the ACP turn path: an overflow error turn
-/// compacts once (the compact-and-retry) and the retried turn settles
-/// the prompt with `end_turn` instead of the error.
-#[tokio::test]
-async fn overflow_arm_compacts_and_retries_the_turn() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = acp_test_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- overflow_error(0),
- { "text": "the summary" },
- { "text": "recovered reply" },
- ]
- }),
- 1,
- 10,
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let (response, notifications) = bed
- .prompt(format!("overflow probe {}", "x".repeat(2_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let metas = AcpTestBed::compaction_metas(&notifications);
- assert_eq!(metas.len(), 1, "one compaction meta: {metas:?}");
- assert_eq!(metas[0]["summary"], "the summary");
- assert!(metas[0]["tokensBefore"].as_u64().unwrap() > 0);
- // The retried turn is the settled outcome: no failure rows on the
- // recovered run (the daemon worker's contract).
- let latest = super::super::session::latest_assistant_message(bed.engine.session.agent())
- .await
- .expect("an assistant message");
- assert_eq!(latest.stop_reason, pa_types::ai::StopReason::Stop);
- assert!(
- bed.entries()
- .await
- .iter()
- .any(|entry| matches!(entry, pa_types::session::FileEntry::Compaction { .. })),
- "the compaction persisted"
- );
-}
-
-/// A retry that still overflows reports once (the TS failure text) and
-/// ends the run with the overflow error: the successful
-/// compact-and-retry publishes the result meta, the report publishes
-/// the empty payload, and the prompt errors.
-#[tokio::test]
-async fn overflow_retry_that_overflows_again_reports_once() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = acp_test_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- overflow_error(0),
- { "text": "the summary" },
- overflow_error(25),
- ]
- }),
- 1,
- 10,
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let (response, notifications) = bed
- .prompt(format!("overflow probe {}", "x".repeat(2_000)))
- .await;
- assert_eq!(response["error"]["code"], -32603, "the turn failed");
- let details = response["error"]["data"]["details"]
- .as_str()
- .unwrap_or_default();
- assert!(
- details.contains("prompt is too long"),
- "the overflow error text surfaces: {response}"
- );
- let metas = AcpTestBed::compaction_metas(&notifications);
- assert_eq!(metas.len(), 2, "the run + the report: {metas:?}");
- assert_eq!(metas[0]["summary"], "the summary");
- assert_eq!(metas[1], json!({}));
- // The durable disclosure row carries the TS report text.
- let entries = bed.entries().await;
- let rows = entries
- .iter()
- .filter_map(|entry| match entry {
- pa_types::session::FileEntry::CustomMessage { payload, .. } => Some(payload),
- _ => None,
- })
- .filter(|payload| payload.custom_type == "compaction_outcome")
- .collect::<Vec<_>>();
- assert_eq!(rows.len(), 1, "one disclosure row");
- assert_eq!(
- serde_json::to_value(&rows[0].content).unwrap(),
- json!("Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.")
- );
-}
-
-/// The requested arm on the ACP turn path: a scheduled `compact.run`
-/// request is consumed at the next admitted prompt's pre-turn boundary
-/// (TS `_runPreTurnCompaction` runs the requested arm too), publishes
-/// the compaction meta, and stops the turn loop on purpose (the run
-/// still settles `end_turn`); the request is taken regardless of
-/// outcome.
-#[tokio::test]
-async fn requested_arm_consumes_the_scheduled_compaction() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = acp_test_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- { "text": "turn two reply" },
- { "text": "the requested summary" },
- { "text": "turn three reply" },
- ]
- }),
- 1,
- 10,
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let (response, _) = bed.prompt(format!("turn two {}", "x".repeat(2_000))).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- // Schedule a requested compaction (the `compact.run` write path):
- // the next prompt's pre-turn boundary consumes it. The session
- // carries two settled turns, so the keep-recent cut leaves the
- // first turn summarizable.
- bed.engine
- .turn_boundary
- .schedule_compaction(Some("keep the checklist".to_string()))
- .await;
- let (response, notifications) = bed.prompt("turn three".to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let metas = AcpTestBed::compaction_metas(&notifications);
- assert_eq!(metas.len(), 1, "one compaction meta: {metas:?}");
- assert_eq!(metas[0]["summary"], "the requested summary");
- assert!(!bed.engine.turn_boundary.compaction_scheduled().await);
- assert!(
- bed.entries()
- .await
- .iter()
- .any(|entry| matches!(entry, pa_types::session::FileEntry::Compaction { .. })),
- "the requested compaction persisted"
- );
-}
-
-/// A skipped requested compaction still consumes the request and
-/// publishes the empty payload (the TS `compaction_end` with
-/// `result: undefined`), plus the durable disclosure row with the
-/// requested-skip message.
-#[tokio::test]
-async fn requested_arm_skip_publishes_the_empty_payload() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- // `keepRecentTokens` beyond the whole session: the cut keeps
- // everything, so the compaction skips as too short.
- let mut bed = acp_test_bed(
- json!({ "responses": [{ "text": "seed reply" }, { "text": "turn two reply" }] }),
- 1,
- 100_000,
- )
- .await;
- let (response, _) = bed.prompt("seed turn".to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- bed.engine.turn_boundary.schedule_compaction(None).await;
- let (response, notifications) = bed.prompt("turn two".to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let metas = AcpTestBed::compaction_metas(&notifications);
- assert_eq!(metas.len(), 1, "the skip is observable: {metas:?}");
- assert_eq!(metas[0], json!({}));
- assert!(!bed.engine.turn_boundary.compaction_scheduled().await);
- let entries = bed.entries().await;
- let row = entries
- .iter()
- .filter_map(|entry| match entry {
- pa_types::session::FileEntry::CustomMessage { payload, .. } => Some(payload),
- _ => None,
- })
- .find(|payload| payload.custom_type == "compaction_outcome")
- .expect("the disclosure row persisted");
- assert_eq!(
- serde_json::to_value(&row.content).unwrap(),
- json!("Requested compaction skipped: Session is too short to compact — try again once it grows")
- );
-}
-
-/// The overflow machine resets at a user row that starts an agent run
-/// (TS `startsAgentRun` at `message_start`): the reported state from
-/// the previous prompt's failed recovery never suppresses the next
-/// prompt's fresh attempt, and the fresh turn's overflow recovers at
-/// its own boundary.
-#[tokio::test]
-async fn overflow_state_resets_per_agent_run() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = acp_test_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- overflow_error(0),
- { "text": "the summary" },
- overflow_error(25),
- overflow_error(25),
- { "text": "the second summary" },
- { "text": "recovered after the stale overflow" },
- ]
- }),
- 1,
- 10,
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- // Prompt two: attempt, the retry overflows, reported — the run
- // ends with the error.
- let (response, notifications) = bed
- .prompt(format!("overflow probe {}", "x".repeat(2_000)))
- .await;
- assert_eq!(response["error"]["code"], -32603);
- assert_eq!(
- AcpTestBed::compaction_metas(&notifications).len(),
- 2,
- "the run + the report"
- );
- // Prompt three: the fresh user row reset the machine, so the
- // turn's own overflow gets a fresh attempt and the retry
- // recovers.
- let (response, notifications) = bed.prompt("second prompt".to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let metas = AcpTestBed::compaction_metas(&notifications);
- assert_eq!(metas.len(), 1, "a fresh attempt ran: {metas:?}");
- assert_eq!(metas[0]["summary"], "the second summary");
-}
-
-/// The overflow retry re-issues without re-adding the user message (TS
-/// `agent.continue()`): the durable chain carries the seed and probe
-/// rows only.
-#[tokio::test]
-async fn overflow_retry_turn_adds_no_user_row() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = acp_test_bed(
- json!({
- "responses": [
- { "text": "seed reply" },
- overflow_error(0),
- { "text": "the summary" },
- { "text": "recovered reply" },
- ]
- }),
- 1,
- 10,
- )
- .await;
- let (response, _) = bed
- .prompt(format!("seed turn {}", "x".repeat(48_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let (response, _) = bed
- .prompt(format!("overflow probe {}", "x".repeat(2_000)))
- .await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- let users = bed
- .entries()
- .await
- .iter()
- .filter(|entry| {
- matches!(
- entry,
- pa_types::session::FileEntry::Message {
- message: pa_types::session::AgentMessage::User(_),
- ..
- }
- )
- })
- .count();
- assert_eq!(users, 2, "the retry added no user row");
-}
diff --git a/crates/pa-daemon/src/acp/config_options.rs b/crates/pa-daemon/src/acp/config_options.rs
index 0b2e6873aa..0cb2ca65c6 100644
--- a/crates/pa-daemon/src/acp/config_options.rs
+++ b/crates/pa-daemon/src/acp/config_options.rs
@@ -8,13 +8,11 @@
//! round-trips the value it was handed); effort choices follow the
//! selected model's supported levels.
//!
-//! Both transports serve the same computation: the in-process mode
-//! reads the live agent state (plus the switchable provider target), the
-//! daemon-attached transport rides the `get_connection_state` /
-//! `get_available_models` / `set_model` / `set_thinking_level` wire
-//! commands — the rust forms of the TS `AgentConnection` seams.
+//! The computation rides the daemon wire commands
+//! (`get_connection_state` / `get_available_models` / `set_model` /
+//! `set_thinking_level`) — the rust forms of the TS `AgentConnection`
+//! seams.
-use std::path::Path;
use std::sync::Arc;
use pa_types::ai::Model;
@@ -68,18 +66,6 @@ impl PickerModel {
}
}
- /// The agent-state model's view (the in-process refresh reads the live
- /// agent model, which an out-of-band failover switch can move without
- /// the picker's tracked slot).
- pub fn from_agent_model(model: &pa_agent::types::Model) -> PickerModel {
- PickerModel {
- id: model.id.clone(),
- name: model.name.clone(),
- provider: model.provider.clone(),
- reasoning: model.reasoning,
- }
- }
-
/// Parse the `get_connection_state` `model` metadata (the daemon
/// engine's `{ id, name, provider, reasoning }`).
pub fn from_connection_state(value: &Value) -> Option<PickerModel> {
@@ -152,10 +138,8 @@ pub fn session_config_options(
})
.collect(),
}];
- // #2858's map-driven capability: the levels list is the capability on
- // both transports (the in-process side computes
- // `get_supported_thinking_levels`, the daemon side carries the
- // worker's #2858-computed `availableThinkingLevels`), so a model with
+ // #2858's map-driven capability: the levels list is the capability
+ // (the worker's #2858-computed `availableThinkingLevels`), so a model with
// an addressable thinking-level map shows its effort picker even when
// the coarse `reasoning` flag is false. A list without a non-`off`
// entry (the `["off"]`-only or empty shape) is no selectable surface.
@@ -212,37 +196,6 @@ pub async fn publish_config_options(
.await;
}
-/// The in-process transport's model discovery: the registry the CLI
-/// composition resolved against (auth storage + `models.json`, with the
-/// private-authorization cache adopted), reading the auth-configured
-/// available models (the TS `refreshAvailableModels` seam).
-pub(crate) fn acp_model_registry(agent_dir: &Path) -> pa_core::models::ModelRegistry {
- let auth = pa_core::auth::AuthStorage::create(agent_dir);
- let mut registry = pa_core::models::ModelRegistry::create(auth, agent_dir.join("models.json"));
- registry.load_private_authorization_from_cache();
- registry
-}
-
-/// The in-process transport's discovery result (TS
-/// `getAvailableModels`): `Err` carries the discovery failure the
-/// caller reports as "unavailable, try again later".
-pub(crate) fn discover_available_models(agent_dir: &Path) -> anyhow::Result<Vec<Model>> {
- let registry = acp_model_registry(agent_dir);
- // A malformed models.json must surface as a discovery failure (the
- // handler's "try again later"), never as an empty catalog the picker
- // then answers with "Unavailable model".
- if let Some(error) = registry.get_error() {
- anyhow::bail!("{error}");
- }
- Ok(registry.get_available().into_iter().cloned().collect())
-}
-
-/// The switchable provider target the in-process session's stream reads
-/// per call: the type the composition passes in so a picker model switch
-/// swaps the live target (TS `setModel`'s stream re-registration).
-pub type ProviderTargetSlot =
- Arc<std::sync::RwLock<Option<pa_core::session_engine::provider_adapter::ProviderTarget>>>;
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/pa-daemon/src/acp/daemon.rs b/crates/pa-daemon/src/acp/daemon.rs
index 4cfdf12b48..7457679df8 100644
--- a/crates/pa-daemon/src/acp/daemon.rs
+++ b/crates/pa-daemon/src/acp/daemon.rs
@@ -1,13 +1,15 @@
//! The daemon-attached ACP transport: the same ACP JSON-RPC surface served
-//! over a client-owned daemon session (TS
+//! over a daemon session (TS
//! `runAcpModeWithConnection(DaemonAgentConnection)`).
//!
-//! `session/new` creates the client-owned daemon session (`--no-session`
-//! semantics), admits its MCP servers through the
+//! Startup creates and attaches the daemon session the CLI session flags
+//! select. `session/new` binds it, admits its MCP servers through the
//! `replace_acp_mcp_servers` wire command, and every prompt runs
//! `prompt_and_wait` while the streamed session events fan out as ACP
-//! updates. The turn settlement (response boundary, quiescence envelope,
-//! stop reason) mirrors the in-process mode: both serve the same captures.
+//! updates. The turn settlement (response boundary, completion envelope
+//! with the live outstanding-subagent count, terminal frame after the RLM
+//! family settles, stop reason) mirrors the TS captures, and the stop
+//! sequence cancels the outstanding children (TS #1612).
//! The daemon worker's `goal_update` session events surface through the
//! wire mapping (`wire_events.rs`), and the autonomous accounting rides the
//! `wait_for_headless_completion` response into the completion envelope
@@ -47,6 +49,9 @@ const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
enum LinkFrame {
Event(Value),
Response(DaemonResponse),
+ /// The daemon-global heartbeat-catalog broadcast the supervisor
+ /// re-broadcasts to every client (`heartbeats_changed`).
+ HeartbeatsChanged,
}
/// A client connection to the supervisor socket: JSONL command envelopes
@@ -129,6 +134,9 @@ impl DaemonLink {
"session_event" => {
let _ = frame_tx.send(LinkFrame::Event(value));
}
+ "heartbeats_changed" => {
+ let _ = frame_tx.send(LinkFrame::HeartbeatsChanged);
+ }
_ => {}
}
}
@@ -228,8 +236,18 @@ pub struct DaemonAcpOptions {
pub socket_path: PathBuf,
pub actual_cwd: PathBuf,
pub product_version: String,
- /// The daemon create config built from the CLI flags (TS `defaultSessionConfig`).
- pub create_config: Value,
+ /// The startup `create` built from the CLI session flags.
+ pub create: DaemonCommand,
+}
+
+/// The daemon session this connection created at startup; every
+/// `session/new` binds it.
+#[derive(Clone)]
+struct DaemonBinding {
+ active_session_id: String,
+ /// The create's `client_owned` lifecycle (`--no-session`): the
+ /// session ends with the connection.
+ client_owned: bool,
}
/// The hosted daemon session: the ACP identity, the daemon routing id, the
@@ -248,19 +266,8 @@ pub(crate) struct HostedSession {
turn: Option<ActiveTurn>,
/// The newest assistant stop reason observed on the event stream.
assistant_stop_reason: Option<String>,
- /// Resolved when the worker emits the turn's last `agent_end` event:
- /// the worker sends its `prompt_and_wait` response BEFORE that marker,
- /// so the marker is the deterministic "every turn frame is on the
- /// wire" signal the settlement waits for (the supervisor's event relay
- /// may otherwise trail the response). One `agent_end` per agent run —
- /// retried and continued runs restart with their own pair — so the
- /// marker resolves only when every started run ended (a fallback
- /// `agent_end` for a run without a model turn settles immediately).
- turn_emitted: Option<oneshot::Sender<()>>,
- /// `agent_start` frames seen since the marker armed.
- agent_runs_started: u64,
- /// `agent_end` frames seen since the marker armed.
- agent_runs_ended: u64,
+ /// The event mapping state lives and dies with the session, like TS.
+ mapping: WireMappingState,
}
struct ActiveTurn {
@@ -273,8 +280,7 @@ struct ActiveTurn {
stop_done_rx: Option<oneshot::Receiver<()>>,
}
-/// The daemon-attached transport state: one hosted session at most, like
-/// the in-process connection state.
+/// The ACP transport state: one hosted session at most.
#[derive(Default)]
pub(crate) struct DaemonAcpState {
pub(crate) session: Option<HostedSession>,
@@ -284,12 +290,12 @@ pub(crate) struct DaemonAcpState {
/// Serve the daemon-attached ACP mode until stdin closes. The caller
/// guarantees the socket answers (the composition spawns a supervisor
-/// when none is listening); a daemon that drops mid-session fails the
-/// hosted session's requests, exactly like the TS daemon connection.
+/// when none is listening).
///
/// # Errors
///
-/// Returns an error when the daemon socket connect fails; a daemon that
+/// Returns an error, before any ACP frame is written, when the daemon
+/// socket connect, the startup create, or its attach fails; a daemon that
/// drops mid-session fails the hosted session's requests instead, exactly
/// like the TS daemon connection.
///
@@ -326,7 +332,6 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
let link = Arc::clone(&link);
let state = Arc::clone(&state);
tokio::spawn(async move {
- let mut mapping = WireMappingState::default();
let mut frames = link.frames.lock().await;
while let Some(frame) = frames.recv().await {
match frame {
@@ -347,27 +352,8 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
if let Some(stop) = wire_events::assistant_stop(&event) {
current.assistant_stop_reason = stop.stop_reason;
}
- // The worker's post-turn marker: the settlement
- // waiting on it may resume once every agent run of
- // the turn ended (a retried or continued run
- // restarts with its own `agent_start`, so the LAST
- // `agent_end` is the marker — an early one leaves
- // the trailing retry frames behind the settlement).
- match event.get("type").and_then(Value::as_str) {
- Some("agent_start") => current.agent_runs_started += 1,
- Some("agent_end") => {
- current.agent_runs_ended += 1;
- if current.agent_runs_ended >= current.agent_runs_started.max(1)
- {
- if let Some(emitted) = current.turn_emitted.take() {
- let _ = emitted.send(());
- }
- }
- }
- _ => {}
- }
let turn_id = current.producer.active_prompt_turn().await;
- for update in wire_events::wire_updates(&event, &mut mapping) {
+ for update in wire_events::wire_updates(&event, &mut current.mapping) {
let _ = current
.producer
.publish(&update, turn_id, PrimeAgentEventPhase::Event, None)
@@ -409,6 +395,29 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
let _ = tx.send(response);
}
}
+ // Heartbeats are connection-scoped, not session events,
+ // so the consumer maps the broadcast directly instead of
+ // `wire_updates`: TS publishes the change at origin turn 0
+ // even while a prompt runs.
+ LinkFrame::HeartbeatsChanged => {
+ let guard = state.lock().await;
+ if let Some(current) = guard.session.as_ref() {
+ let _ = current
+ .producer
+ .publish(
+ &types::AcpSessionUpdate::SessionInfoUpdate {
+ meta: meta::prime_agent_meta(&PrimeAgentSessionMeta {
+ heartbeats_changed: Some(true),
+ ..Default::default()
+ }),
+ },
+ 0,
+ PrimeAgentEventPhase::Event,
+ None,
+ )
+ .await;
+ }
+ }
}
}
// The reader hit the socket close and every frame it read
@@ -420,7 +429,14 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
link.pending.lock().unwrap().clear();
});
}
+ let binding = bind_daemon_session(&link, &state, options.create.clone()).await?;
+ // Only the prompt handlers stay owned: EOF aborts them (TS aborts the
+ // controller and exits), so the process never waits on a prompt still
+ // settling its subagents. The other handlers spawn detached: a close
+ // in flight at EOF finishes — its `tx` clone holds `writer.await` — so
+ // its session still stops and releases its servers.
+ let mut handlers = tokio::task::JoinSet::new();
let mut stdin = BufReader::new(tokio::io::stdin());
let mut input_line = String::new();
loop {
@@ -448,13 +464,23 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
// frame's handler).
match frame_order_prefix(&incoming, &state).await {
FrameOrder::Spawn => {
- let link = Arc::clone(&link);
- let state = Arc::clone(&state);
- let options = options.clone();
- let options_tx = tx.clone();
- tokio::spawn(async move {
- handle_incoming(incoming, &link, &state, &options, options_tx).await;
- });
+ // `session/new` settles before the next frame is read, so
+ // EOF's teardown always sees the session it installs.
+ if matches!(&incoming, Incoming::Request { method, .. } if method == "session/new")
+ {
+ let options_tx = tx.clone();
+ handle_incoming(incoming, &link, &state, &options, &binding, options_tx).await;
+ } else {
+ let link = Arc::clone(&link);
+ let state = Arc::clone(&state);
+ let options = options.clone();
+ let binding = binding.clone();
+ let options_tx = tx.clone();
+ tokio::spawn(async move {
+ handle_incoming(incoming, &link, &state, &options, &binding, options_tx)
+ .await;
+ });
+ }
}
FrameOrder::AdmitPrompt {
id,
@@ -464,7 +490,7 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
let link = Arc::clone(&link);
let state = Arc::clone(&state);
let options_tx = tx.clone();
- tokio::spawn(async move {
+ handlers.spawn(async move {
handle_session_prompt(id, params, admission_id, &link, &state, options_tx)
.await;
});
@@ -474,30 +500,87 @@ pub async fn run_daemon_attached_acp_mode(options: DaemonAcpOptions) -> anyhow::
FrameOrder::Refused { id, message } => {
let _ = tx.send(super::internal_error(&id, &message));
}
- // A cancel arms the stop task; the request form answers `{}`
- // immediately (the notification form has no response).
- FrameOrder::Cancel { request_id, stop } => {
+ // A cancel arms the stop task (the notification form has no
+ // response).
+ FrameOrder::Cancel(stop) => {
if let Some(stop) = stop {
let link = Arc::clone(&link);
tokio::spawn(async move {
run_cancel_stop(stop, &link).await;
});
}
- if let Some(id) = request_id {
- let _ = tx.send(jsonrpc::response(&id, &json!({})));
- }
}
}
+ // Reap finished prompt handlers.
+ while handlers.try_join_next().is_some() {}
}
- // A client-owned session dies with the connection: stop the work,
- // release the servers, and kill the worker (TS dispose semantics).
- teardown(&link, &state).await;
+ handlers.shutdown().await;
+ teardown(&link, &state, &binding).await;
drop(tx);
let _ = writer.await;
Ok(0)
}
+/// Create and attach the startup daemon session (TS main.ts, before the
+/// ACP connection serves). A failed attach releases the created session
+/// the way EOF does.
+async fn bind_daemon_session(
+ link: &Arc<DaemonLink>,
+ state: &Arc<Mutex<DaemonAcpState>>,
+ create: DaemonCommand,
+) -> anyhow::Result<DaemonBinding> {
+ let client_owned = matches!(
+ create,
+ DaemonCommand::Create {
+ lifecycle: Some(DaemonSessionLifecycle::ClientOwned),
+ ..
+ }
+ );
+ let created = link.request(create).await?;
+ if !created.success {
+ anyhow::bail!(created.error.unwrap_or_else(|| "unknown error".to_string()));
+ }
+ let binding = DaemonBinding {
+ active_session_id: created
+ .data
+ .as_ref()
+ .and_then(|summary| summary.get("activeSessionId"))
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ client_owned,
+ };
+ let attached = link
+ .request(DaemonCommand::Attach {
+ id: None,
+ active_session_id: binding.active_session_id.clone(),
+ client_id: None,
+ capabilities: None,
+ resume_cursor: None,
+ telemetry_disabled: None,
+ recovery_config: None,
+ env: None,
+ launch_env: None,
+ rest: Map::default(),
+ })
+ .await
+ .and_then(|response| {
+ if response.success {
+ Ok(())
+ } else {
+ Err(anyhow::anyhow!(response
+ .error
+ .unwrap_or_else(|| "unknown error".to_string())))
+ }
+ });
+ if let Err(error) = attached {
+ teardown(link, state, &binding).await;
+ return Err(error);
+ }
+ Ok(binding)
+}
+
enum FrameOrder {
Spawn,
AdmitPrompt {
@@ -509,12 +592,7 @@ enum FrameOrder {
id: Value,
message: String,
},
- /// `request_id` is set for the request form, which answers `{}` (TS
- /// only registers the notification form).
- Cancel {
- request_id: Option<Value>,
- stop: Option<CancelStop>,
- },
+ Cancel(Option<CancelStop>),
}
struct CancelStop {
@@ -539,19 +617,8 @@ async fn frame_order_prefix(incoming: &Incoming, state: &Arc<Mutex<DaemonAcpStat
},
}
}
- Incoming::Request { id, method, params } if method == "session/cancel" => {
- let stop = arm_cancel(params, state).await;
- FrameOrder::Cancel {
- request_id: Some(id.clone()),
- stop,
- }
- }
Incoming::Notification { method, params } if method == "session/cancel" => {
- let stop = arm_cancel(params, state).await;
- FrameOrder::Cancel {
- request_id: None,
- stop,
- }
+ FrameOrder::Cancel(arm_cancel(params, state).await)
}
_ => FrameOrder::Spawn,
}
@@ -617,72 +684,104 @@ async fn arm_cancel(params: &Value, state: &Arc<Mutex<DaemonAcpState>>) -> Optio
})
}
-/// TS `stopSessionWork`, without the RLM child cancellations. The owned
-/// admission cancel stops a prompt that was sent before the cancel but
-/// committed after the abort. Dropping `stop_done_tx` releases the
-/// cancelled turn's response.
+/// The cancelled turn's stop sequence. Dropping `stop_done_tx` releases
+/// the cancelled turn's response.
async fn run_cancel_stop(stop: CancelStop, link: &Arc<DaemonLink>) {
+ stop_session_work(link, &stop.daemon_session_id, Some(stop.admission_id)).await;
+ drop(stop.stop_done_tx);
+}
+
+/// TS `stopSessionWork`: abort the worker's running and queued work, stop
+/// the owned admission (a prompt sent before the stop but committed after
+/// the abort), wait the idle, then cancel the RLM children.
+async fn stop_session_work(
+ link: &Arc<DaemonLink>,
+ daemon_session_id: &str,
+ admission_id: Option<String>,
+) {
let _ = link
.request(DaemonCommand::AbortAndClearQueue {
id: None,
- active_session_id: stop.daemon_session_id.clone(),
+ active_session_id: daemon_session_id.to_string(),
rest: Map::default(),
})
.await;
+ if let Some(admission_id) = admission_id {
+ cancel_owned_admission(link, daemon_session_id, admission_id).await;
+ }
let _ = link
- .request(DaemonCommand::CancelPromptAdmission {
+ .request(DaemonCommand::WaitForIdle {
id: None,
- active_session_id: stop.daemon_session_id.clone(),
- admission_id: stop.admission_id,
- cancel_owned: Some(true),
+ active_session_id: daemon_session_id.to_string(),
+ wait_for_rlm_quiescence: None,
rest: Map::default(),
})
.await;
+ cancel_outstanding_rlm_children(link, daemon_session_id).await;
+}
+
+/// TS `cancelOutstandingRlmChildren`: cancel every roster row, no status
+/// filter — a row already settling keeps its own settle, and the cancels
+/// run one after another (TS `Promise.allSettled` is the declared
+/// divergence). A failed roster fetch or cancel is ignored, like every
+/// other stop step.
+async fn cancel_outstanding_rlm_children(link: &Arc<DaemonLink>, daemon_session_id: &str) {
+ let Ok(children) = fetch_rlm_children(link, daemon_session_id).await else {
+ return;
+ };
+ for child in children {
+ let child_id = child
+ .get("id")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ let _ = link
+ .request(DaemonCommand::CancelRlmChild {
+ id: None,
+ active_session_id: daemon_session_id.to_string(),
+ child_id,
+ rest: Map::default(),
+ })
+ .await;
+ }
+}
+
+/// TS `cancel_prompt_admission` with `cancelOwned`: a committed prompt's
+/// running turn aborts.
+async fn cancel_owned_admission(
+ link: &Arc<DaemonLink>,
+ daemon_session_id: &str,
+ admission_id: String,
+) {
let _ = link
- .request(DaemonCommand::WaitForIdle {
+ .request(DaemonCommand::CancelPromptAdmission {
id: None,
- active_session_id: stop.daemon_session_id,
- wait_for_rlm_quiescence: None,
+ active_session_id: daemon_session_id.to_string(),
+ admission_id,
+ cancel_owned: Some(true),
rest: Map::default(),
})
.await;
- drop(stop.stop_done_tx);
}
-/// One incoming ACP frame. Requests answer; notifications may drive state.
+/// One incoming ACP frame. Requests answer.
async fn handle_incoming(
incoming: Incoming,
link: &Arc<DaemonLink>,
state: &Arc<Mutex<DaemonAcpState>>,
options: &DaemonAcpOptions,
+ binding: &DaemonBinding,
tx: producer::FrameSink,
) {
- match incoming {
- Incoming::Request { id, method, params } => {
- handle_request(id, method, params, link, state, options, tx).await;
- }
- // `session/cancel` is handled in the reader loop.
- Incoming::Notification { .. } => {}
- }
-}
-
-async fn handle_request(
- id: Value,
- method: String,
- params: Value,
- link: &Arc<DaemonLink>,
- state: &Arc<Mutex<DaemonAcpState>>,
- options: &DaemonAcpOptions,
- tx: producer::FrameSink,
-) {
+ let Incoming::Request { id, method, params } = incoming else {
+ return;
+ };
match method.as_str() {
"initialize" => {
- let result = serde_json::to_value(types::initialize_result(&options.product_version))
- .expect("serializes");
- let _ = tx.send(jsonrpc::response(&id, &result));
+ handle_initialize(&id, &params, &options.product_version, &tx);
}
"session/new" => {
- handle_session_new(id, params, link, state, options, tx).await;
+ handle_session_new(id, params, link, state, options, binding, tx).await;
}
"session/set_config_option" => {
handle_set_config_option(id, params, link, state, tx).await;
@@ -701,14 +800,51 @@ async fn handle_request(
}
}
-/// Admit one session: create the client-owned daemon session, attach, and
-/// admit the MCP servers through the wire command.
+fn handle_initialize(id: &Value, params: &Value, product_version: &str, tx: &producer::FrameSink) {
+ if let Err(error_response) = validate_initialize(id, params) {
+ let _ = tx.send(error_response);
+ return;
+ }
+ let result =
+ serde_json::to_value(types::initialize_result(product_version)).expect("serializes");
+ let _ = tx.send(jsonrpc::response(id, &result));
+}
+
+/// The `initialize` schema check the TS SDK performs: the protocol version
+/// must be a number. The error body mirrors the observed TS response.
+fn validate_initialize(id: &Value, params: &Value) -> std::result::Result<(), Value> {
+ let field_error = |received: &str| {
+ jsonrpc::error_response(
+ id,
+ jsonrpc::INVALID_PARAMS,
+ "Invalid params",
+ Some(&json!({
+ "_errors": [],
+ "protocolVersion": {
+ "_errors": [format!("Invalid input: expected number, received {received}")]
+ },
+ })),
+ )
+ };
+ match params.get("protocolVersion") {
+ None => Err(field_error("undefined")),
+ Some(value) if value.is_number() => Ok(()),
+ Some(Value::String(_)) => Err(field_error("string")),
+ Some(Value::Bool(_)) => Err(field_error("boolean")),
+ Some(Value::Null) => Err(field_error("null")),
+ Some(_) => Err(field_error("object")),
+ }
+}
+
+/// Admit one session over the startup daemon session and admit its MCP
+/// servers through the wire command.
async fn handle_session_new(
id: Value,
params: Value,
link: &Arc<DaemonLink>,
state: &Arc<Mutex<DaemonAcpState>>,
options: &DaemonAcpOptions,
+ binding: &DaemonBinding,
tx: producer::FrameSink,
) {
{
@@ -725,8 +861,8 @@ async fn handle_session_new(
// Failures below clear the in-flight flag on the way out; on success
// the hosted session takes the slot.
let params = types::NewSessionParams::parse(&params);
- // MCP admission runs first, exactly like the in-process path: a
- // rejected list fails the request with the same error payloads.
+ // MCP admission runs first: a rejected list fails the request with
+ // the same error payloads.
let resolved =
match super::mcp::resolve_acp_mcp_servers(&params.mcp_servers, &options.actual_cwd) {
Ok(resolved) => resolved,
@@ -747,93 +883,14 @@ async fn handle_session_new(
return;
}
- // The client-owned daemon session: `--no-session` semantics.
- let mut config = options.create_config.clone();
- // The telemetry execution mode (TS main.ts `executionMode: appMode`).
- config["executionMode"] = Value::String("acp".to_string());
- // Verification seam: a scripted daemon session (the same `{"engine":
- // "faux", ...}` form the in-process e2e rides). The product never sets
- // it; the supervisor turns the path into the worker's script env.
- if let Some(script) = std::env::var_os("PRIME_AGENT_ACP_DAEMON_SCRIPT") {
- config["script"] = Value::String(script.to_string_lossy().to_string());
- }
- let create = DaemonCommand::Create {
- id: None,
- session_path: None,
- continue_recent: None,
- no_session: Some(true),
- name: None,
- config: Some(config),
- // ACP-created sessions follow the worker's own telemetry posture
- // (settings + env); external clients never toggle telemetry.
- telemetry_disabled: None,
- runtime_metadata: None,
- lifecycle: Some(DaemonSessionLifecycle::ClientOwned),
- env: None,
- launch_env: None,
- rest: Map::default(),
- };
- let create_response = match link.request(create).await {
- Ok(response) => response,
- Err(error) => {
- *state.lock().await = DaemonAcpState::default();
- let _ = tx.send(super::internal_error(&id, &error.to_string()));
- return;
- }
- };
- if !create_response.success {
- let failure = create_response
- .error
- .unwrap_or_else(|| "unknown error".to_string());
- *state.lock().await = DaemonAcpState::default();
- let _ = tx.send(super::internal_error(&id, &failure));
- return;
- }
- let summary = create_response.data.unwrap_or(Value::Null);
- let daemon_active_session_id = summary
- .get("activeSessionId")
- .and_then(Value::as_str)
- .map(str::to_string)
- .unwrap_or_default();
-
- let attach = DaemonCommand::Attach {
- id: None,
- active_session_id: daemon_active_session_id.clone(),
- client_id: None,
- capabilities: None,
- resume_cursor: None,
- telemetry_disabled: None,
- recovery_config: None,
- env: None,
- launch_env: None,
- rest: Map::default(),
- };
- if let Ok(response) = link.request(attach).await {
- if !response.success {
- let failure = response
- .error
- .unwrap_or_else(|| "unknown error".to_string());
- let _ = link
- .request(DaemonCommand::Kill {
- id: None,
- active_session_id: daemon_active_session_id.clone(),
- rest: Map::default(),
- })
- .await;
- *state.lock().await = DaemonAcpState::default();
- let _ = tx.send(super::internal_error(&id, &failure));
- return;
- }
- }
-
let acp_session_id = uuid::Uuid::new_v4().to_string();
let producer = UpdateProducer::new(acp_session_id.clone(), tx.clone());
// The pickers ride the worker's own state and discovery seams: neither
// fetch may fail the admission (TS catches discovery failures to an
// empty list, and a state fetch failure degrades to no options).
let (state_value, models) = (
- fetch_connection_state(link, &daemon_active_session_id).await,
- fetch_available_models(link, &daemon_active_session_id)
+ fetch_connection_state(link, &binding.active_session_id).await,
+ fetch_available_models(link, &binding.active_session_id)
.await
.unwrap_or_default(),
);
@@ -846,29 +903,24 @@ async fn handle_session_new(
let mcp_owner_id = uuid::Uuid::new_v4().to_string();
let mut hosted = HostedSession {
acp_session_id: acp_session_id.clone(),
- daemon_active_session_id,
+ daemon_active_session_id: binding.active_session_id.clone(),
producer,
config,
mcp_owner_id,
mcp_server_names: Vec::new(),
turn: None,
assistant_stop_reason: None,
- turn_emitted: None,
- agent_runs_started: 0,
- agent_runs_ended: 0,
+ mapping: WireMappingState::default(),
};
// The ACP MCP servers ride the wire command, not a local manager.
if let Err(error) = replace_session_servers(link, &hosted, &resolved).await {
- let failure = error.to_string();
- let _ = link
- .request(DaemonCommand::Kill {
- id: None,
- active_session_id: hosted.daemon_active_session_id.clone(),
- rest: Map::default(),
- })
- .await;
+ // The worker may have applied the list before this failed (a lost
+ // acknowledgement); the clear is best-effort, like TS.
+ if !resolved.is_empty() {
+ let _ = replace_session_servers(link, &hosted, &[]).await;
+ }
*state.lock().await = DaemonAcpState::default();
- let _ = tx.send(super::internal_error(&id, &failure));
+ let _ = tx.send(super::internal_error(&id, &error.to_string()));
return;
}
hosted.mcp_server_names = resolved
@@ -911,8 +963,7 @@ async fn handle_session_new(
producer.commit_session_new_response().await;
}
-/// Send the MCP replacement for one hosted session (the wire form of the
-/// in-process manager call).
+/// Send the MCP replacement for one hosted session.
async fn replace_session_servers(
link: &Arc<DaemonLink>,
hosted: &HostedSession,
@@ -996,6 +1047,18 @@ fn cancelled_response(id: &Value) -> Value {
)
}
+/// Render a prompt-block failure as the ACP invalid-params error. The TS
+/// SDK validates the request schema; the Rust port validates the blocks it
+/// actually reads.
+fn prompt_block_error(id: &Value, error: &types::PromptBlockError) -> Value {
+ jsonrpc::error_response(
+ id,
+ jsonrpc::INVALID_PARAMS,
+ "Invalid params",
+ Some(&json!({ "reason": error.to_string() })),
+ )
+}
+
/// Run one admitted prompt turn and return its reply frame.
async fn prompt_turn(
id: Value,
@@ -1005,9 +1068,9 @@ async fn prompt_turn(
state: &Arc<Mutex<DaemonAcpState>>,
) -> Value {
let params = types::PromptParams::parse(&params);
- let admitted = match super::session::AdmittedPrompt::parse(&params.prompt) {
+ let admitted = match types::AdmittedPrompt::parse(&params.prompt) {
Ok(admitted) => admitted,
- Err(error) => return super::session::prompt_block_error(&id, &error),
+ Err(error) => return prompt_block_error(&id, &error),
};
let (producer, hosted_daemon_session_id) = {
let guard = state.lock().await;
@@ -1021,22 +1084,8 @@ async fn prompt_turn(
}
};
let turn_id = producer.begin_prompt().await;
- // The turn-end marker: the consumer loop resolves it on the worker's
- // post-turn `agent_end` event (after the `prompt_and_wait` response).
- let (emitted_tx, emitted_rx) = oneshot::channel::<()>();
// TS `abort.signal.aborted` before `promptAndWait`.
- let cancelled = {
- let mut guard = state.lock().await;
- let cancelled = turn_cancelled(&guard, admission_id);
- if !cancelled {
- if let Some(hosted) = guard.session.as_mut() {
- hosted.turn_emitted = Some(emitted_tx);
- hosted.agent_runs_started = 0;
- hosted.agent_runs_ended = 0;
- }
- }
- cancelled
- };
+ let cancelled = turn_cancelled(&*state.lock().await, admission_id);
if cancelled {
producer.finish_prompt(turn_id).await;
return cancelled_response(&id);
@@ -1082,29 +1131,11 @@ async fn prompt_turn(
return super::internal_error(&id, &error.to_string());
}
};
- // The worker answers the response before its post-turn marker; wait
- // for the marker so every turn frame is published before the settle
- // (the event relay may otherwise trail the response). A prompt that
- // failed before any run started (the aborted-before-delivery cancel:
- // no agent_start/agent_end ever follows) resolves the marker now -
- // the settle must not pay the full marker window for a turn that
- // never ran.
- let marker_resolved = {
- let guard = state.lock().await;
- matches!(
- guard.session.as_ref(),
- Some(hosted) if hosted.agent_runs_started == 0
- )
- };
- if !response.success && marker_resolved {
- let mut guard = state.lock().await;
- if let Some(hosted) = guard.session.as_mut() {
- if let Some(emitted) = hosted.turn_emitted.take() {
- let _ = emitted.send(());
- }
- }
- }
- let _ = tokio::time::timeout(std::time::Duration::from_secs(30), emitted_rx).await;
+ // TS `abort.signal.aborted` after `promptAndWait`: every turn frame
+ // is published by now - the worker flushes its session events before
+ // the response leaves its socket, and the supervisor's per-client
+ // writer writes a queued event ahead of a queued response - so the
+ // settle reads the stream directly, with no marker wait.
let cancelled = {
let guard = state.lock().await;
turn_cancelled(&guard, admission_id)
@@ -1124,33 +1155,39 @@ async fn prompt_turn(
}
// The autonomous accounting for the completion envelope: the daemon's
// headless-completion status (TS `waitForHeadlessCompletion`), fetched
- // after the turn marker settled the run. A failed fetch degrades to no
- // autonomous meta (the envelope still settles, like an in-process
- // session without a run).
- let autonomous_status = fetch_autonomous_status(link, &hosted_daemon_session_id).await;
+ // after the turn settled (the response is the run's end). A failed
+ // fetch degrades to no autonomous meta (the envelope still settles
+ // without a run).
+ let autonomous_status = fetch_autonomous_status(link, &hosted_daemon_session_id, false)
+ .await
+ .ok();
// TS `abort.signal.aborted` after `waitForHeadlessCompletion`: queued
// continuations (goal, post-compaction autonomous) run inside that wait.
if turn_cancelled(&*state.lock().await, admission_id) {
producer.finish_prompt(turn_id).await;
return cancelled_response(&id);
}
+ // The completion observation's roster read (TS `getRlmChildSnapshots`
+ // throws): a failed read errors the prompt before the boundary, never
+ // publishes a wrong count.
+ let children = match fetch_rlm_children(link, &hosted_daemon_session_id).await {
+ Ok(children) => children,
+ Err(error) => {
+ publish_error_boundary(&producer, turn_id).await;
+ producer.finish_prompt(turn_id).await;
+ return super::internal_error(&id, &error.to_string());
+ }
+ };
+ if turn_cancelled(&*state.lock().await, admission_id) {
+ producer.finish_prompt(turn_id).await;
+ return cancelled_response(&id);
+ }
let autonomous_meta = autonomous_status
.as_ref()
.filter(|status| status.enabled)
.map(meta::autonomous_meta);
- // The remaining continuation slots the quiescence observation reports
- // (the in-process settlement computes the same subtraction).
- let remaining_continuations = autonomous_status
- .as_ref()
- .filter(|status| status.enabled)
- .map_or(0, |status| {
- status
- .limits
- .max_continuations
- .saturating_sub(status.continuations_used)
- });
// The boundary, completion, and terminal quiescence frames match the
- // in-process settlement because both serve the same captures.
+ // TS captures.
let boundary = types::AcpSessionUpdate::SessionInfoUpdate {
meta: meta::prime_agent_meta(&PrimeAgentSessionMeta {
terminal_quiescence_expected: Some(true),
@@ -1165,47 +1202,87 @@ async fn prompt_turn(
Some(PrimeAgentOutcome::Result),
)
.await;
- // The completion envelope mirrors the in-process settlement: the
- // autonomous accounting rides the quiescence event, then the terminal
- // quiescence envelope repeats the observation.
+ // The completion envelope: the turn's own observation, with the
+ // live outstanding-subagent count the settle loop then waits down to
+ // zero.
let quiescence = types::AcpSessionUpdate::SessionInfoUpdate {
meta: meta::prime_agent_meta(&PrimeAgentSessionMeta {
- autonomous: autonomous_meta.clone(),
- quiescence: Some(meta::PrimeAgentQuiescenceMeta {
- outstanding_subagents: 0,
- remaining_autonomous_continuations: remaining_continuations,
- }),
+ autonomous: autonomous_meta,
+ quiescence: Some(quiescence_meta(autonomous_status.as_ref(), &children)),
..Default::default()
}),
};
let completion_published = producer
.publish(&quiescence, turn_id, PrimeAgentEventPhase::Event, None)
.await;
- let terminal = types::AcpSessionUpdate::SessionInfoUpdate {
- meta: meta::prime_agent_meta(&PrimeAgentSessionMeta {
- autonomous: autonomous_meta.clone(),
- quiescence: Some(meta::PrimeAgentQuiescenceMeta {
- outstanding_subagents: 0,
- remaining_autonomous_continuations: remaining_continuations,
+ // The settlement loop (TS `finalizePendingTerminal`): the barrier is
+ // the event, no timer, and the roster re-read is the response-cut
+ // telemetry (a child can publish a terminal status before its result
+ // reaches the parent). A failed barrier or read errors the prompt; a
+ // degraded status would spin the loop.
+ let settled_status = loop {
+ let status = match fetch_autonomous_status(link, &hosted_daemon_session_id, true).await {
+ Ok(status) => status,
+ Err(error) => {
+ producer.finish_prompt(turn_id).await;
+ return super::internal_error(
+ &id,
+ &format!("ACP lifecycle reconciliation failed: {error}"),
+ );
+ }
+ };
+ if turn_cancelled(&*state.lock().await, admission_id) {
+ producer.finish_prompt(turn_id).await;
+ return cancelled_response(&id);
+ }
+ let children = match fetch_rlm_children(link, &hosted_daemon_session_id).await {
+ Ok(children) => children,
+ Err(error) => {
+ producer.finish_prompt(turn_id).await;
+ return super::internal_error(
+ &id,
+ &format!("ACP lifecycle reconciliation failed: {error}"),
+ );
+ }
+ };
+ if turn_cancelled(&*state.lock().await, admission_id) {
+ producer.finish_prompt(turn_id).await;
+ return cancelled_response(&id);
+ }
+ let terminal_quiescence = quiescence_meta(Some(&status), &children);
+ if terminal_quiescence.outstanding_subagents != 0 {
+ continue;
+ }
+ // TS `sealTerminal`: the terminal frame is the last update stamped
+ // with this turn; later events resume turn 0.
+ producer.finish_prompt(turn_id).await;
+ let terminal = types::AcpSessionUpdate::SessionInfoUpdate {
+ meta: meta::prime_agent_meta(&PrimeAgentSessionMeta {
+ autonomous: status.enabled.then(|| meta::autonomous_meta(&status)),
+ quiescence: Some(terminal_quiescence),
+ ..Default::default()
}),
- ..Default::default()
- }),
+ };
+ let terminal_published = producer
+ .publish(
+ &terminal,
+ turn_id,
+ PrimeAgentEventPhase::TerminalQuiescence,
+ Some(PrimeAgentOutcome::Result),
+ )
+ .await;
+ if !published || !completion_published || !terminal_published {
+ return super::internal_error(&id, "Failed to publish ACP completion");
+ }
+ break status;
};
- let terminal_published = producer
- .publish(
- &terminal,
- turn_id,
- PrimeAgentEventPhase::TerminalQuiescence,
- Some(PrimeAgentOutcome::Result),
- )
- .await;
- producer.finish_prompt(turn_id).await;
- if !published || !completion_published || !terminal_published {
- return super::internal_error(&id, "Failed to publish ACP completion");
- }
- // The stop reason follows the TS mapping (acp-stop-reason.ts): a limit
- // reached on the enabled run is the only non-end_turn outcome.
- let stop_reason = meta::acp_stop_reason_for_status(false, autonomous_status.as_ref());
+ // The stop reason follows the TS mapping (acp-stop-reason.ts): the
+ // abort flag read after the settlement, and the settlement's status
+ // (`pending.status`), not the first observation's.
+ let stop_reason = meta::acp_stop_reason_for_status(
+ turn_cancelled(&*state.lock().await, admission_id),
+ Some(&settled_status),
+ );
jsonrpc::response(
&id,
&serde_json::to_value(types::AcpStopReasonResponse { stop_reason }).expect("serializes"),
@@ -1232,29 +1309,111 @@ async fn publish_error_boundary(producer: &Arc<UpdateProducer>, turn_id: u64) {
}
/// Fetch the session's autonomous-run status (`wait_for_headless_completion`
-/// on the daemon wire; TS `waitForHeadlessCompletion`). `None` degrades the
-/// settlement to no autonomous meta, never to a failed prompt.
+/// on the daemon wire; TS `waitForHeadlessCompletion`), once the daemon's
+/// headless run settled. With `wait_for_rlm_quiescence`, the answer comes
+/// from the quiescence barrier instead: it holds past the parent's idle
+/// until every tracked child run settled, so it is the RLM-quiescence
+/// event the settlement loop waits on. A failure is the caller's policy
+/// (TS throws for both callers): the completion observation degrades, the
+/// settlement loop errors the prompt.
+///
+/// # Errors
+///
+/// Returns an error when the daemon connection fails or closes mid-request,
+/// when the response reports a failure, or when the status payload does not
+/// deserialize.
async fn fetch_autonomous_status(
link: &Arc<DaemonLink>,
active_session_id: &str,
-) -> Option<pa_core::autonomous::AgentAutonomousStatus> {
+ wait_for_rlm_quiescence: bool,
+) -> anyhow::Result<pa_core::autonomous::AgentAutonomousStatus> {
let response = link
.request_until_close(DaemonCommand::WaitForHeadlessCompletion {
id: None,
active_session_id: active_session_id.to_string(),
- wait_for_rlm_quiescence: None,
+ wait_for_rlm_quiescence: wait_for_rlm_quiescence.then_some(true),
rest: Map::default(),
})
- .await
- .ok()?;
+ .await?;
if !response.success {
- return None;
+ anyhow::bail!(response
+ .error
+ .unwrap_or_else(|| "unknown error".to_string()));
}
- serde_json::from_value(response.data.unwrap_or(Value::Null)).ok()
+ Ok(serde_json::from_value(
+ response.data.unwrap_or(Value::Null),
+ )?)
}
-/// Close: abort, release the servers, kill the client-owned worker, fence
-/// the producer.
+/// The live child roster (`get_rlm_children` on the daemon wire; TS
+/// `getRlmChildSnapshots` throws).
+///
+/// # Errors
+///
+/// Returns an error when the daemon connection fails or closes mid-request,
+/// when the response reports a failure, or when the answer carries no
+/// children array.
+async fn fetch_rlm_children(
+ link: &Arc<DaemonLink>,
+ active_session_id: &str,
+) -> anyhow::Result<Vec<Value>> {
+ let response = link
+ .request(DaemonCommand::GetRlmChildren {
+ id: None,
+ active_session_id: active_session_id.to_string(),
+ rest: Map::default(),
+ })
+ .await?;
+ if !response.success {
+ anyhow::bail!(response
+ .error
+ .unwrap_or_else(|| "unknown error".to_string()));
+ }
+ response
+ .data
+ .unwrap_or(Value::Null)
+ .get("children")
+ .cloned()
+ .and_then(|children| children.as_array().cloned())
+ .ok_or_else(|| anyhow::anyhow!("get_rlm_children answered no children array"))
+}
+
+/// TS `outstandingSubagentCount`: the roster's live statuses, verbatim.
+fn outstanding_subagents(children: &[Value]) -> u64 {
+ children
+ .iter()
+ .filter(|child| {
+ matches!(
+ child.get("status").and_then(Value::as_str),
+ Some("queued" | "running")
+ )
+ })
+ .count() as u64
+}
+
+/// TS `quiescenceMeta`: the outstanding-subagent count plus the run's
+/// remaining continuation slots, observed together at one completion point.
+fn quiescence_meta(
+ status: Option<&pa_core::autonomous::AgentAutonomousStatus>,
+ children: &[Value],
+) -> meta::PrimeAgentQuiescenceMeta {
+ meta::PrimeAgentQuiescenceMeta {
+ outstanding_subagents: outstanding_subagents(children),
+ remaining_autonomous_continuations: status.filter(|status| status.enabled).map_or(
+ 0,
+ |status| {
+ status
+ .limits
+ .max_continuations
+ .saturating_sub(status.continuations_used)
+ },
+ ),
+ }
+}
+
+/// Close: stop the session's work, release the servers, and fence the
+/// producer. The daemon session stays; a later `session/new` binds it
+/// again (TS `closeSession`).
async fn handle_session_close(
id: Value,
params: Value,
@@ -1269,13 +1428,13 @@ async fn handle_session_close(
.to_string();
let taken = {
let mut guard = state.lock().await;
- match guard.session.take() {
- Some(hosted) if hosted.acp_session_id == session_id => {
- guard.session_close_in_flight = true;
- Some(hosted)
- }
- _ => None,
+ let taken = guard
+ .session
+ .take_if(|hosted| hosted.acp_session_id == session_id);
+ if taken.is_some() {
+ guard.session_close_in_flight = true;
}
+ taken
};
let Some(hosted) = taken else {
let _ = tx.send(super::internal_error(
@@ -1284,28 +1443,13 @@ async fn handle_session_close(
));
return;
};
- let _ = link
- .request(DaemonCommand::Abort {
- id: None,
- active_session_id: hosted.daemon_active_session_id.clone(),
- rest: Map::default(),
- })
- .await;
+ let admission_id = hosted.turn.as_ref().map(|turn| turn.admission_id.clone());
+ stop_session_work(link, &hosted.daemon_active_session_id, admission_id).await;
if !hosted.mcp_server_names.is_empty() {
let _ = replace_session_servers(link, &hosted, &[]).await;
}
- // The worker dies before the config queue drains: a stalled
- // `set_model`/`set_thinking_level` (holding the queue on a wire
- // request) fails fast once the worker is gone instead of parking
- // the close on the request timeout. Then the serialized config work
- // settles before the producer fences (TS `await configTask`).
- let _ = link
- .request(DaemonCommand::Kill {
- id: None,
- active_session_id: hosted.daemon_active_session_id.clone(),
- rest: Map::default(),
- })
- .await;
+ // The serialized config work settles before the producer fences (TS
+ // `await configTask`).
let _ = hosted.config.queue.lock().await;
hosted.producer.close().await;
let _ = tx.send(jsonrpc::response(&id, &json!({})));
@@ -1313,29 +1457,38 @@ async fn handle_session_close(
guard.session_close_in_flight = false;
}
-/// Stop everything after stdin closes (TS dispose semantics).
-async fn teardown(link: &Arc<DaemonLink>, state: &Arc<Mutex<DaemonAcpState>>) {
+/// Release the connection's hold after stdin closes (TS dispose): the
+/// running prompt is cancelled (TS EOF abort → `cancel_prompt_admission`
+/// with `cancelOwned`), the MCP servers go and the producer fences. A
+/// client-owned session ends with the connection; a resident one stays
+/// and is detached when the link drops.
+async fn teardown(
+ link: &Arc<DaemonLink>,
+ state: &Arc<Mutex<DaemonAcpState>>,
+ binding: &DaemonBinding,
+) {
let hosted = state.lock().await.session.take();
- let Some(hosted) = hosted else {
- return;
- };
- // The worker dies before the config queue drains (a stalled config
- // operation holding the queue releases once the wire peer is gone),
- // then the serialized config work settles before the producer fences.
- let _ = link
- .request(DaemonCommand::Abort {
- id: None,
- active_session_id: hosted.daemon_active_session_id.clone(),
- rest: Map::default(),
- })
- .await;
- let _ = link
- .request(DaemonCommand::Kill {
- id: None,
- active_session_id: hosted.daemon_active_session_id.clone(),
- rest: Map::default(),
- })
- .await;
- let _ = hosted.config.queue.lock().await;
- hosted.producer.close().await;
+ if let Some(turn) = hosted.as_ref().and_then(|hosted| hosted.turn.as_ref()) {
+ cancel_owned_admission(link, &binding.active_session_id, turn.admission_id.clone()).await;
+ }
+ if let Some(hosted) = &hosted {
+ if !hosted.mcp_server_names.is_empty() {
+ let _ = replace_session_servers(link, hosted, &[]).await;
+ }
+ }
+ // The owned worker stops before the config queue drains: a stalled
+ // config operation holding the queue on a wire request fails fast.
+ if binding.client_owned {
+ let _ = link
+ .request(DaemonCommand::CompleteOwnedSession {
+ id: None,
+ active_session_id: binding.active_session_id.clone(),
+ rest: Map::default(),
+ })
+ .await;
+ }
+ if let Some(hosted) = hosted {
+ let _ = hosted.config.queue.lock().await;
+ hosted.producer.close().await;
+ }
}
diff --git a/crates/pa-daemon/src/acp/events.rs b/crates/pa-daemon/src/acp/events.rs
deleted file mode 100644
index 4f0107ba15..0000000000
--- a/crates/pa-daemon/src/acp/events.rs
+++ /dev/null
@@ -1,836 +0,0 @@
-//! Translate agent-loop events into ACP `session/update` payloads.
-//!
-//! Pure mapping: one loop event fans out to zero or more updates. The
-//! mapping state correlates streamed chunks with their owning assistant
-//! message, exactly like the TS event adapter.
-
-use serde_json::{json, Value};
-
-use super::meta::PrimeAgentSessionMeta;
-use super::types::{AcpSessionUpdate, TextBlock, ToolCallContent};
-pub use super::types::{AcpToolKind, AcpToolStatus};
-
-/// The model-facing Python REPL tool.
-pub const IPYTHON_TOOL_NAME: &str = "ipython";
-
-/// Correlates streamed assistant chunks with their owning message and bash
-/// output chunks with the run that produced them.
-#[derive(Debug, Default)]
-pub struct MappingState {
- next_assistant_message_sequence: u64,
- active_assistant_message_id: Option<String>,
- active_bash_run_id: Option<String>,
-}
-
-impl MappingState {
- fn start_assistant_message(&mut self) -> String {
- self.next_assistant_message_sequence += 1;
- let id = format!(
- "prime-agent-assistant-{}",
- self.next_assistant_message_sequence
- );
- self.active_assistant_message_id = Some(id.clone());
- id
- }
-
- /// The owning message id for a streamed chunk, allocating one lazily if
- /// the stream began without a `message_start` (the TS adapter does the
- /// same, so a missed start never crashes the stream).
- fn message_started(&mut self) -> &str {
- if self.active_assistant_message_id.is_none() {
- self.start_assistant_message();
- }
- self.active_assistant_message_id
- .as_deref()
- .expect("a started message id exists")
- }
-}
-
-/// The event kinds the ACP adapter consumes from the agent loop.
-///
-/// A thin projection of the loop's `AgentEvent`: only the discriminants the
-/// adapter maps to ACP updates, with the fields the mapping reads. Keeping
-/// it as a value enum makes the mapping testable without a live agent.
-#[derive(Debug, Clone, PartialEq)]
-pub enum AcpEngineEvent {
- MessageStart {
- role: String,
- },
- /// One streaming assistant delta: reasoning or visible text.
- AssistantDelta {
- thinking: bool,
- delta: String,
- },
- MessageEnd {
- role: String,
- },
- ToolExecutionStart {
- tool_call_id: String,
- tool_name: String,
- args: Value,
- },
- ToolExecutionEnd {
- tool_call_id: String,
- tool_name: String,
- result: Value,
- is_error: bool,
- },
- /// A compaction ran (session `/compact` or an auto-compaction cut).
- CompactionEnd {
- tokens_before: Option<u64>,
- summary: Option<String>,
- },
- /// The session goal changed (`/goal` commands and driver turns).
- GoalUpdate {
- status: String,
- objective: Option<String>,
- token_budget: Option<u64>,
- tokens_used: Option<u64>,
- },
- /// A continual-harness refinement completed.
- RefineComplete {
- summary: String,
- changes: Vec<String>,
- },
- /// A continual-harness refinement failed.
- RefineFailed {
- error: String,
- },
- /// One RLM subagent roster change.
- ///
- /// No in-process producer yet: in-process sessions have no RLM
- /// children. The mapping is the daemon-attached parity contract
- /// (slice 4) and is locked by unit tests.
- #[allow(dead_code)]
- RlmChildUpdate {
- child: RlmChildRow,
- },
- /// A kernel cell sent an agent-to-agent message. No in-process producer
- /// yet (the messaging host is daemon-wired); mapping locked by tests.
- #[allow(dead_code)]
- IpythonSentAgentMessage {
- tool_call_id: String,
- target: Option<String>,
- delivery_status: Option<String>,
- },
- /// The session's heartbeat/cron schedule changed (connection-scoped).
- /// No in-process producer yet; mapping locked by tests.
- #[allow(dead_code)]
- HeartbeatsChanged,
- /// A user-level bash run started: outside the tool-call lifecycle, so
- /// it gets a synthetic tool call keyed by run id. No in-process
- /// producer yet (user bash is an interactive/daemon surface); mapping
- /// locked by tests.
- #[allow(dead_code)]
- BashStart {
- command: String,
- run_id: Option<String>,
- },
- /// Incremental output of the active user-level bash run.
- #[allow(dead_code)]
- BashOutput {
- chunk: String,
- },
- /// The active user-level bash run finished.
- #[allow(dead_code)]
- BashEnd {
- run_id: Option<String>,
- exit_code: Option<i64>,
- cancelled: bool,
- },
-}
-
-/// One RLM subagent roster row in the `_meta.subagents` payload.
-#[derive(Debug, Clone, PartialEq)]
-pub struct RlmChildRow {
- pub id: String,
- pub session_name: Option<String>,
- pub status: String,
- pub model: Option<String>,
- pub token_count: Option<u64>,
- pub error: Option<String>,
-}
-
-/// Map one loop event to zero or more ACP updates.
-///
-/// - Assistant reasoning deltas become `agent_thought_chunk` and visible
-/// text deltas become `agent_message_chunk`, so a client can render or
-/// hide them separately.
-/// - Tool calls become `tool_call` / `tool_call_update` pairs keyed by the
-/// loop's tool-call id.
-/// - Everything else has no ACP representation and maps to nothing.
-pub fn acp_updates_for_event(
- event: &AcpEngineEvent,
- state: &mut MappingState,
-) -> Vec<AcpSessionUpdate> {
- match event {
- AcpEngineEvent::MessageStart { role } if role == "assistant" => {
- state.start_assistant_message();
- Vec::new()
- }
- AcpEngineEvent::AssistantDelta {
- thinking: true,
- delta,
- } if !delta.is_empty() => {
- vec![AcpSessionUpdate::AgentThoughtChunk {
- message_id: state.message_started().to_string(),
- content: TextBlock::new(delta.clone()),
- }]
- }
- AcpEngineEvent::AssistantDelta {
- thinking: false,
- delta,
- } if !delta.is_empty() => {
- vec![AcpSessionUpdate::AgentMessageChunk {
- message_id: state.message_started().to_string(),
- content: TextBlock::new(delta.clone()),
- }]
- }
- AcpEngineEvent::MessageEnd { role } if role == "assistant" => {
- state.active_assistant_message_id = None;
- Vec::new()
- }
- AcpEngineEvent::MessageStart { .. }
- | AcpEngineEvent::AssistantDelta { .. }
- | AcpEngineEvent::MessageEnd { .. } => Vec::new(),
- AcpEngineEvent::ToolExecutionStart {
- tool_call_id,
- tool_name,
- args,
- } => {
- let cell = if tool_name == IPYTHON_TOOL_NAME {
- args.get("code").and_then(Value::as_str)
- } else {
- None
- };
- let title = if tool_name == IPYTHON_TOOL_NAME {
- "Python cell"
- } else {
- tool_name
- };
- vec![AcpSessionUpdate::ToolCall {
- tool_call_id: tool_call_id.clone(),
- title: title.to_string(),
- kind: AcpToolKind::of_tool(tool_name),
- status: AcpToolStatus::InProgress,
- raw_input: match cell {
- Some(code) => json!({ "code": code }),
- None => args.clone(),
- },
- }]
- }
- AcpEngineEvent::CompactionEnd {
- tokens_before,
- summary,
- } => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- compaction: Some(super::meta::PrimeAgentCompactionMeta {
- tokens_before: *tokens_before,
- summary: summary.clone(),
- }),
- ..Default::default()
- })]
- }
- AcpEngineEvent::GoalUpdate {
- status,
- objective,
- token_budget,
- tokens_used,
- } => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- goal: Some(super::meta::PrimeAgentGoalMeta {
- status: status.clone(),
- objective: objective.clone(),
- token_budget: *token_budget,
- tokens_used: *tokens_used,
- }),
- ..Default::default()
- })]
- }
- AcpEngineEvent::RefineComplete { summary, changes } => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- refinement: Some(super::meta::PrimeAgentRefinementMeta {
- status: "complete".to_string(),
- summary: Some(summary.clone()),
- changes: Some(changes.clone()),
- error: None,
- }),
- ..Default::default()
- })]
- }
- AcpEngineEvent::RefineFailed { error } => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- refinement: Some(super::meta::PrimeAgentRefinementMeta {
- status: "failed".to_string(),
- summary: None,
- changes: None,
- error: Some(error.clone()),
- }),
- ..Default::default()
- })]
- }
- AcpEngineEvent::RlmChildUpdate { child } => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- subagents: Some(vec![super::meta::PrimeAgentSubagentMeta {
- id: child.id.clone(),
- session_name: child.session_name.clone(),
- status: child.status.clone(),
- model: child.model.clone(),
- depth: None,
- token_count: child.token_count,
- error: child.error.clone(),
- }]),
- ..Default::default()
- })]
- }
- AcpEngineEvent::IpythonSentAgentMessage {
- tool_call_id,
- target,
- delivery_status,
- } => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- agent_message: Some(super::meta::PrimeAgentAgentMessageMeta {
- tool_call_id: tool_call_id.clone(),
- target: target.clone(),
- delivery_status: delivery_status.clone(),
- }),
- ..Default::default()
- })]
- }
- AcpEngineEvent::HeartbeatsChanged => {
- vec![session_info_update(&PrimeAgentSessionMeta {
- heartbeats_changed: Some(true),
- ..Default::default()
- })]
- }
- AcpEngineEvent::BashStart { command, run_id } => {
- state.active_bash_run_id.clone_from(run_id);
- vec![AcpSessionUpdate::ToolCall {
- tool_call_id: bash_tool_call_id(run_id.clone()),
- title: command.clone(),
- kind: AcpToolKind::Execute,
- status: AcpToolStatus::InProgress,
- raw_input: json!({ "command": command }),
- }]
- }
- AcpEngineEvent::BashOutput { chunk } => {
- vec![AcpSessionUpdate::ToolCallUpdate {
- tool_call_id: bash_tool_call_id(state.active_bash_run_id.clone()),
- status: Some(AcpToolStatus::InProgress),
- content: Some(vec![ToolCallContent::new(chunk.clone())]),
- meta: None,
- }]
- }
- AcpEngineEvent::BashEnd {
- run_id,
- exit_code,
- cancelled,
- } => {
- if state.active_bash_run_id == *run_id {
- state.active_bash_run_id = None;
- }
- let completed = *exit_code == Some(0) && !cancelled;
- vec![AcpSessionUpdate::ToolCallUpdate {
- tool_call_id: bash_tool_call_id(run_id.clone()),
- status: Some(if completed {
- AcpToolStatus::Completed
- } else {
- AcpToolStatus::Failed
- }),
- content: None,
- meta: None,
- }]
- }
- AcpEngineEvent::ToolExecutionEnd {
- tool_call_id,
- tool_name,
- result,
- is_error,
- } => {
- let text = tool_result_text(result);
- let rich = if tool_name == IPYTHON_TOOL_NAME {
- ipython_rich_output(result)
- } else {
- None
- };
- vec![AcpSessionUpdate::ToolCallUpdate {
- tool_call_id: tool_call_id.clone(),
- status: Some(if *is_error {
- AcpToolStatus::Failed
- } else {
- AcpToolStatus::Completed
- }),
- content: text.map(|text| vec![ToolCallContent::new(text)]),
- meta: rich.map(|rich| {
- super::meta::prime_agent_meta(&super::meta::PrimeAgentSessionMeta {
- ipython: Some(rich),
- ..Default::default()
- })
- }),
- }]
- }
- }
-}
-
-/// A `session_info_update` carrying one namespaced payload.
-fn session_info_update(meta: &PrimeAgentSessionMeta) -> AcpSessionUpdate {
- AcpSessionUpdate::SessionInfoUpdate {
- meta: super::meta::prime_agent_meta(meta),
- }
-}
-
-/// The synthetic tool-call id for a bash run: `prime-agent-bash-<runId>`.
-fn bash_tool_call_id(run_id: Option<String>) -> String {
- match run_id {
- Some(run_id) => format!("prime-agent-bash-{run_id}"),
- None => "prime-agent-bash".to_string(),
- }
-}
-
-/// Extract the text of a tool result: a plain string, an `output` field, or
-/// joined text blocks of a `content` array. Rich media has no text form and
-/// yields `None`.
-fn tool_result_text(result: &Value) -> Option<String> {
- if let Some(text) = result.as_str() {
- return Some(text.to_string());
- }
- let object = result.as_object()?;
- if let Some(output) = object.get("output").and_then(Value::as_str) {
- return Some(output.to_string());
- }
- let content = object.get("content")?.as_array()?;
- let parts: Vec<&str> = content
- .iter()
- .filter(|block| block.get("type").and_then(Value::as_str) == Some("text"))
- .filter_map(|block| block.get("text").and_then(Value::as_str))
- .filter(|text| !text.is_empty())
- .collect();
- (!parts.is_empty()).then(|| parts.join("\n"))
-}
-
-/// Rich kernel output that ACP has no content type for: media the cell loaded
-/// into context plus the number of diffs it displayed, reported under the
-/// `_meta` namespace. Attachment payloads are never inlined (ACP already
-/// carries images as content blocks); the decoded byte length is reported
-/// instead of a `bytes` field the kernel never sends.
-fn ipython_rich_output(result: &Value) -> Option<Value> {
- let details = result.get("details")?.as_object()?;
- let attachments = details
- .get("attachments")
- .and_then(Value::as_array)
- .map(|attachments| {
- attachments
- .iter()
- .map(|attachment| {
- let mut meta = serde_json::Map::new();
- if let Some(mime_type) = attachment.get("mimeType").and_then(Value::as_str) {
- meta.insert("mimeType".to_string(), json!(mime_type));
- }
- if let Some(path) = attachment.get("path").and_then(Value::as_str) {
- meta.insert("path".to_string(), json!(path));
- }
- if let Some(data) = attachment.get("data").and_then(Value::as_str) {
- meta.insert("bytes".to_string(), json!(base64_byte_length(data)));
- }
- Value::Object(meta)
- })
- .collect::<Vec<_>>()
- })
- .unwrap_or_default();
- let diff_count = details
- .get("diffs")
- .and_then(Value::as_array)
- .map(std::vec::Vec::len);
- if attachments.is_empty() && diff_count.is_none() {
- return None;
- }
- let mut rich = serde_json::Map::new();
- if !attachments.is_empty() {
- rich.insert("attachments".to_string(), Value::Array(attachments));
- }
- if let Some(diff_count) = diff_count {
- rich.insert("diffCount".to_string(), json!(diff_count));
- }
- Some(Value::Object(rich))
-}
-
-/// Decoded byte length of a base64 payload, without materializing it.
-fn base64_byte_length(data: &str) -> usize {
- let padding = if data.ends_with("==") {
- 2
- } else {
- usize::from(data.ends_with('='))
- };
- ((data.len() * 3) / 4).saturating_sub(padding)
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn update_values(event: &AcpEngineEvent) -> Vec<Value> {
- let mut state = MappingState::default();
- acp_updates_for_event(event, &mut state)
- .iter()
- .map(AcpSessionUpdate::to_bare_value)
- .collect()
- }
-
- fn full_turn() -> Vec<Value> {
- let mut state = MappingState::default();
- let events = [
- AcpEngineEvent::MessageStart {
- role: "assistant".into(),
- },
- AcpEngineEvent::AssistantDelta {
- thinking: true,
- delta: "hmm".into(),
- },
- AcpEngineEvent::AssistantDelta {
- thinking: false,
- delta: "hello".into(),
- },
- AcpEngineEvent::ToolExecutionStart {
- tool_call_id: "t1".into(),
- tool_name: "ipython".into(),
- args: json!({ "code": "1+1" }),
- },
- AcpEngineEvent::ToolExecutionEnd {
- tool_call_id: "t1".into(),
- tool_name: "ipython".into(),
- result: json!({ "output": "2" }),
- is_error: false,
- },
- AcpEngineEvent::MessageEnd {
- role: "assistant".into(),
- },
- ];
- events
- .iter()
- .flat_map(|event| {
- acp_updates_for_event(event, &mut state)
- .iter()
- .map(AcpSessionUpdate::to_bare_value)
- .collect::<Vec<_>>()
- })
- .collect()
- }
-
- #[test]
- fn assistant_deltas_map_to_distinct_chunk_kinds() {
- let values = update_values(&AcpEngineEvent::AssistantDelta {
- thinking: true,
- delta: "think".into(),
- });
- assert_eq!(values[0]["sessionUpdate"], "agent_thought_chunk");
- let values = update_values(&AcpEngineEvent::AssistantDelta {
- thinking: false,
- delta: "say".into(),
- });
- assert_eq!(values[0]["sessionUpdate"], "agent_message_chunk");
- }
-
- #[test]
- fn empty_deltas_map_to_nothing() {
- let mut state = MappingState::default();
- state.start_assistant_message();
- let updates = acp_updates_for_event(
- &AcpEngineEvent::AssistantDelta {
- thinking: false,
- delta: String::new(),
- },
- &mut state,
- );
- assert!(updates.is_empty());
- }
-
- #[test]
- fn one_turn_yields_the_ts_frame_sequence() {
- let values = full_turn();
- let tags: Vec<&str> = values
- .iter()
- .map(|value| value["sessionUpdate"].as_str().expect("tagged"))
- .collect();
- assert_eq!(
- tags,
- vec![
- "agent_thought_chunk",
- "agent_message_chunk",
- "tool_call",
- "tool_call_update"
- ]
- );
- // The thought and the message share the turn's assistant message id.
- assert_eq!(values[0]["messageId"], "prime-agent-assistant-1");
- assert_eq!(values[1]["messageId"], "prime-agent-assistant-1");
- assert_eq!(values[2]["title"], "Python cell");
- assert_eq!(values[2]["rawInput"], json!({ "code": "1+1" }));
- assert_eq!(values[3]["status"], "completed");
- assert_eq!(values[3]["content"][0]["content"]["text"], "2");
- }
-
- #[test]
- fn second_turn_allocates_a_new_message_id() {
- let values = full_turn();
- let _ = values;
- let mut state = MappingState::default();
- for event in [
- AcpEngineEvent::MessageStart {
- role: "assistant".into(),
- },
- AcpEngineEvent::MessageEnd {
- role: "assistant".into(),
- },
- AcpEngineEvent::MessageStart {
- role: "assistant".into(),
- },
- ] {
- acp_updates_for_event(&event, &mut state);
- }
- assert_eq!(
- state.active_assistant_message_id.as_deref(),
- Some("prime-agent-assistant-2")
- );
- }
-
- #[test]
- fn failed_tool_result_reports_failed_status() {
- let mut state = MappingState::default();
- let updates = acp_updates_for_event(
- &AcpEngineEvent::ToolExecutionEnd {
- tool_call_id: "t9".into(),
- tool_name: "bash".into(),
- result: json!("boom"),
- is_error: true,
- },
- &mut state,
- );
- let value = updates[0].to_bare_value();
- assert_eq!(value["sessionUpdate"], "tool_call_update");
- assert_eq!(value["status"], "failed");
- assert_eq!(value["content"][0]["content"]["text"], "boom");
- }
-
- #[test]
- fn ipython_rich_output_rides_under_the_namespace() {
- let mut state = MappingState::default();
- let result = json!({
- "output": "42",
- "details": {
- "attachments": [ { "mimeType": "image/png", "data": "QUJD" } ],
- "diffs": [ {}, {} ],
- },
- });
- let updates = acp_updates_for_event(
- &AcpEngineEvent::ToolExecutionEnd {
- tool_call_id: "t2".into(),
- tool_name: "ipython".into(),
- result,
- is_error: false,
- },
- &mut state,
- );
- let value = updates[0].to_bare_value();
- let meta = &value["_meta"]["ai.primeintellect.prime-agent"]["ipython"];
- assert_eq!(meta["diffCount"], 2);
- assert_eq!(meta["attachments"][0]["mimeType"], "image/png");
- // "QUJD" decodes to 3 bytes ("ABC").
- assert_eq!(meta["attachments"][0]["bytes"], 3);
- assert!(meta["attachments"][0].get("data").is_none());
- }
-
- fn meta_of(value: &Value) -> Value {
- value["_meta"]["ai.primeintellect.prime-agent"].clone()
- }
-
- #[test]
- fn compaction_maps_to_namespaced_meta() {
- let mut state = MappingState::default();
- let updates = acp_updates_for_event(
- &AcpEngineEvent::CompactionEnd {
- tokens_before: Some(1234),
- summary: Some("a summary".into()),
- },
- &mut state,
- );
- let value = updates[0].to_bare_value();
- assert_eq!(value["sessionUpdate"], "session_info_update");
- assert_eq!(
- meta_of(&value)["compaction"],
- json!({ "tokensBefore": 1234, "summary": "a summary" })
- );
- // A skipped compaction still publishes the empty payload, matching
- // the TS compaction_end with result undefined.
- let updates = acp_updates_for_event(
- &AcpEngineEvent::CompactionEnd {
- tokens_before: None,
- summary: None,
- },
- &mut state,
- );
- assert_eq!(
- meta_of(&updates[0].to_bare_value())["compaction"],
- json!({})
- );
- }
-
- #[test]
- fn goal_update_maps_to_namespaced_meta() {
- let mut state = MappingState::default();
- let updates = acp_updates_for_event(
- &AcpEngineEvent::GoalUpdate {
- status: "active".into(),
- objective: Some("ship it".into()),
- token_budget: Some(1000),
- tokens_used: Some(42),
- },
- &mut state,
- );
- let meta = meta_of(&updates[0].to_bare_value());
- assert_eq!(
- meta["goal"],
- json!({ "status": "active", "objective": "ship it", "tokenBudget": 1000, "tokensUsed": 42 })
- );
- }
-
- #[test]
- fn refinement_outcomes_map_to_namespaced_meta() {
- let mut state = MappingState::default();
- let updates = acp_updates_for_event(
- &AcpEngineEvent::RefineComplete {
- summary: "applied 2 edits".into(),
- changes: vec!["create memory:x".into(), "update skill:y".into()],
- },
- &mut state,
- );
- assert_eq!(
- meta_of(&updates[0].to_bare_value())["refinement"],
- json!({ "status": "complete", "summary": "applied 2 edits", "changes": ["create memory:x", "update skill:y"] })
- );
- let updates = acp_updates_for_event(
- &AcpEngineEvent::RefineFailed {
- error: "boom".into(),
- },
- &mut state,
- );
- assert_eq!(
- meta_of(&updates[0].to_bare_value())["refinement"],
- json!({ "status": "failed", "error": "boom" })
- );
- }
-
- #[test]
- fn rlm_child_and_agent_message_map_to_namespaced_meta() {
- let mut state = MappingState::default();
- let updates = acp_updates_for_event(
- &AcpEngineEvent::RlmChildUpdate {
- child: RlmChildRow {
- id: "child-1".into(),
- session_name: Some("worker-a".into()),
- status: "running".into(),
- model: Some("z-ai/glm-5.3-flash".into()),
- token_count: Some(500),
- error: None,
- },
- },
- &mut state,
- );
- assert_eq!(
- meta_of(&updates[0].to_bare_value())["subagents"][0],
- json!({
- "id": "child-1",
- "sessionName": "worker-a",
- "status": "running",
- "model": "z-ai/glm-5.3-flash",
- "tokenCount": 500,
- })
- );
- let updates = acp_updates_for_event(
- &AcpEngineEvent::IpythonSentAgentMessage {
- tool_call_id: "t3".into(),
- target: Some("worker-a".into()),
- delivery_status: Some("delivered".into()),
- },
- &mut state,
- );
- assert_eq!(
- meta_of(&updates[0].to_bare_value())["agentMessage"],
- json!({ "toolCallId": "t3", "target": "worker-a", "deliveryStatus": "delivered" })
- );
- }
-
- #[test]
- fn heartbeats_changed_maps_to_namespaced_meta() {
- let mut state = MappingState::default();
- let updates = acp_updates_for_event(&AcpEngineEvent::HeartbeatsChanged, &mut state);
- assert_eq!(
- meta_of(&updates[0].to_bare_value())["heartbeatsChanged"],
- true
- );
- }
-
- #[test]
- fn bash_runs_map_to_synthetic_tool_calls() {
- let mut state = MappingState::default();
- let start = acp_updates_for_event(
- &AcpEngineEvent::BashStart {
- command: "echo hi".into(),
- run_id: Some("run-7".into()),
- },
- &mut state,
- );
- let value = start[0].to_bare_value();
- assert_eq!(value["sessionUpdate"], "tool_call");
- assert_eq!(value["toolCallId"], "prime-agent-bash-run-7");
- assert_eq!(value["title"], "echo hi");
- assert_eq!(value["kind"], "execute");
- assert_eq!(value["status"], "in_progress");
- assert_eq!(value["rawInput"], json!({ "command": "echo hi" }));
-
- let output = acp_updates_for_event(
- &AcpEngineEvent::BashOutput {
- chunk: "hi\n".into(),
- },
- &mut state,
- );
- let value = output[0].to_bare_value();
- assert_eq!(value["sessionUpdate"], "tool_call_update");
- assert_eq!(value["toolCallId"], "prime-agent-bash-run-7");
- assert_eq!(value["status"], "in_progress");
- assert_eq!(value["content"][0]["content"]["text"], "hi\n");
-
- let end = acp_updates_for_event(
- &AcpEngineEvent::BashEnd {
- run_id: Some("run-7".into()),
- exit_code: Some(0),
- cancelled: false,
- },
- &mut state,
- );
- let value = end[0].to_bare_value();
- assert_eq!(value["status"], "completed");
- assert!(value.get("content").is_none());
- // The active run cleared, so later output keys the bare id.
- assert_eq!(state.active_bash_run_id, None);
-
- let end = acp_updates_for_event(
- &AcpEngineEvent::BashEnd {
- run_id: None,
- exit_code: Some(1),
- cancelled: true,
- },
- &mut state,
- );
- let value = end[0].to_bare_value();
- assert_eq!(value["toolCallId"], "prime-agent-bash");
- assert_eq!(value["status"], "failed");
- }
-
- #[test]
- fn non_assistant_roles_map_to_nothing() {
- let values = update_values(&AcpEngineEvent::MessageStart {
- role: "user".into(),
- });
- assert!(values.is_empty());
- }
-}
diff --git a/crates/pa-daemon/src/acp/goal_continuation.rs b/crates/pa-daemon/src/acp/goal_continuation.rs
deleted file mode 100644
index 7221fb747c..0000000000
--- a/crates/pa-daemon/src/acp/goal_continuation.rs
+++ /dev/null
@@ -1,739 +0,0 @@
-//! The direct-ACP goal continuation boundary: the goal arms of the
-//! settled-turn loop on the in-process ACP transport.
-//!
-//! TS ruling (the #244 direct-ACP gap, read off agent-session.ts,
-//! agent-loop.ts, and in-process-agent-connection.ts): the TS ACP mode
-//! hosts the goal continuation loop — not as a mode-level construct, but
-//! inside the session's own turn run. `AgentSession` installs
-//! `agent.getContinuationMessages` (`_installAgentContinuationHook`), the
-//! agent loop consults the hook at its natural turn end (`runLoop`), and
-//! the in-process `promptAndWait` runs that loop directly, so the direct
-//! ACP path drives every continuation INSIDE the one `session/prompt`
-//! request: continuation turns surface as events of the same prompt turn,
-//! and the response settles only after the goal run ends (complete /
-//! paused / `budget_limited` / error, or genuinely nothing more to do). The
-//! daemon-attached transport rides the worker's queue (the #244 lane);
-//! this module is the in-process counterpart: the prompt turn's settle
-//! loop consults the same arms at each settled boundary.
-//!
-//! Arms ported per settled boundary (TS `_shouldStopAfterTurn`'s goal arms
-//! plus `_getContinuationMessages`'s goal arm, which takes exclusive
-//! priority over the autonomous arm):
-//! - the budget-limit wrap-up steer: the turn that crossed the goal's
-//! token budget runs the budget-limit context as the next turn (TS
-//! `_accountGoalUsageForAssistantMessage` arming the steer),
-//! - the natural continuation mint (TS `_getGoalContinuationMessages`):
-//! an active goal mints one goal-context turn per settled boundary.
-//!
-//! Two TS gates hold trivially on this surface: the RLM quiescence
-//! deferral (`_hasUnsettledRlmQuiescenceWork` — the in-process engine
-//! runs with `NoRlmChildren`, so no descendant work can exist) and the
-//! queued-input deferral (`queuedActionCount > 0` — the ACP connection
-//! admits one prompt turn at a time, so no session input can queue behind
-//! the running turn). Neither mint therefore defers or rolls back here.
-
-use pa_core::goals::{create_goal_context_message, GoalContextKind, GoalStatus};
-use pa_types::session::CustomMessage;
-
-use super::session::AcpSession;
-use super::AcpModeState;
-
-/// The goal boundary's decision for the settle loop: one minted turn to
-/// run as the next turn of the same prompt, or nothing (the boundary
-/// proceeds to the autonomous arm).
-pub(super) enum GoalFollowUp {
- None,
- /// Boxed: the message's insertion-ordered JSON maps (`preserve_order`,
- /// wire parity) would dwarf the empty variant (`large_enum_variant`).
- Turn(Box<CustomMessage>),
-}
-
-/// Mint one goal continuation and announce it (the shared
-/// `continuationsUsed` bump publishes before the continuation turn
-/// starts, mirroring the TS `_setGoalState` -> `_emitGoalUpdate` at every
-/// mint site). `None` when the goal cannot mint (inactive, or no
-/// objective); the caller decides what that means at its own site.
-pub(super) async fn mint_goal_continuation(
- mode: &AcpModeState,
- session: &AcpSession,
-) -> Option<CustomMessage> {
- // The progress check's input (the 402 diagnosis's (a)) + the failed
- // pair's drop ((c)), read before the driver lock.
- let last_turn =
- mode.engine
- .session
- .last_assistant_message()
- .await
- .and_then(|wire| match wire {
- pa_types::session::AgentMessage::Assistant(assistant) => {
- pa_core::session_engine::provider_adapter::json_round_trip(&assistant)
- }
- _ => None,
- });
- if last_turn
- .as_ref()
- .is_some_and(|turn: &pa_agent::types::AssistantMessage| {
- turn.stop_reason == pa_agent::types::StopReason::Error
- || pa_core::session_engine::goal_driver::turn_produced_no_output(turn)
- })
- {
- mode.engine.session.drop_failed_goal_continuation().await;
- }
- let persistence = mode.engine.session.shared_persistence();
- let mut driver = mode.engine.goal_driver.lock().await;
- if !driver.owns_continuation_wakeup() {
- return None;
- }
- let mut persistence = persistence.lock().await;
- let message = match driver.next_continuation_message(&mut persistence, last_turn.as_ref()) {
- Ok(message) => message,
- Err(error) => {
- // TS `_getGoalContinuationMessages`'s catch arm: a failed
- // persist fails the goal with the write error and mints
- // nothing (the settle hook must not reject).
- let error_text = format!("{error:#}");
- eprintln!("pa-daemon: goal continuation mint persist failed: {error_text}");
- if let Err(finish_error) = driver.finish_for_terminal_message(
- &mut persistence,
- pa_types::ai::StopReason::Error,
- Some(&error_text),
- ) {
- eprintln!("pa-daemon: goal error finish also failed: {finish_error:#}");
- }
- drop(driver);
- session.publish_goal_update().await;
- return None;
- }
- };
- // The minted continuation is handed to the settle loop as the very
- // next turn of the same prompt (the in-run model, TS
- // `pendingMessages`): the admission is immediate, so the pending
- // guard releases here — no queued window exists on this surface. A
- // refused mint (`Ok(None)`: the driver's pending guard held) keeps
- // the guard armed.
- if message.is_some() {
- driver.continuation_consumed();
- }
- drop(driver);
- session.publish_goal_update().await;
- message
-}
-
-/// The goal boundary consult for the settle loop: the budget steer runs
-/// first (TS `_shouldStopAfterTurn` precedes the continuation hook), then
-/// the natural mint (TS `_getGoalContinuationMessages`). The budget
-/// crossing is the settle loop's read of the usage listener's flag; a
-/// false alarm (the goal since completed or cleared) falls through to the
-/// natural mint.
-pub(super) async fn goal_follow_up(mode: &AcpModeState, session: &AcpSession) -> GoalFollowUp {
- if session.take_goal_budget_crossed() {
- let steer = {
- let driver = mode.engine.goal_driver.lock().await;
- let state = driver.state_with_creation_elapsed();
- match state.status {
- GoalStatus::BudgetLimited => {
- create_goal_context_message(&state, GoalContextKind::BudgetLimit).ok()
- }
- _ => None,
- }
- };
- if let Some(message) = steer {
- return GoalFollowUp::Turn(Box::new(message));
- }
- }
- match mint_goal_continuation(mode, session).await {
- Some(message) => GoalFollowUp::Turn(Box::new(message)),
- None => GoalFollowUp::None,
- }
-}
-
-/// Withdraw a threshold-queue mint whose compaction was cancelled (TS
-/// `_clearQueuedGoalContinuationAfterCancelledThresholdCompaction`): the
-/// slot rolls back so the next natural stop re-mints without
-/// double-counting.
-pub(super) async fn rollback_goal_mint(mode: &AcpModeState) {
- let persistence = mode.engine.session.shared_persistence();
- let mut driver = mode.engine.goal_driver.lock().await;
- let mut persistence = persistence.lock().await;
- if let Err(error) = driver.rollback_continuation_mint(&mut persistence) {
- // The restore hook must not reject: warn and keep the slot as-is.
- eprintln!("pa-daemon: goal mint rollback persist failed: {error:#}");
- }
-}
-
-/// TS `_finishGoalForTerminalAssistantMessage` for a failed run: an
-/// error assistant message fails an active goal (an abort keeps it). The
-/// state change announces through the shared goal-update channel.
-pub(super) async fn fail_goal_for_terminal_error(
- mode: &AcpModeState,
- session: &AcpSession,
- error_message: Option<&str>,
-) {
- let persistence = mode.engine.session.shared_persistence();
- let mut driver = mode.engine.goal_driver.lock().await;
- let mut persistence = persistence.lock().await;
- if let Err(error) = driver.finish_for_terminal_message(
- &mut persistence,
- pa_types::ai::StopReason::Error,
- error_message,
- ) {
- // The terminal hook is best-effort (TS's throws out of the
- // agent-end handler): the failed turn already carries the error.
- eprintln!("pa-daemon: goal terminal finish persist failed: {error:#}");
- }
- drop(driver);
- session.publish_goal_update().await;
-}
-
-#[cfg(test)]
-// The faux provider registry is process-global and shared across the
-// daemon engine tests: the std lock serializes every test that drives it,
-// and the async tests here hold it across their awaits on purpose (the
-// tests are the only contenders, so no cross-task deadlock).
-#[allow(clippy::await_holding_lock)]
-mod tests {
- use super::*;
- use crate::agent_engine::FAUX_TEST_LOCK;
-
- /// The faux model's per-request output budget (maxTokens `16_384` under the
- /// `32_000` request cap): threshold fixtures subtract it from the window
- /// alongside the headroom (the combined input+output ceiling).
- const FAUX_REQUEST_BUDGET: u64 = 16_384;
-
- use pa_core::session::manager::SessionManager;
- use pa_core::session_engine::engine::{create_session, SessionEngineConfig};
- use pa_core::session_engine::provider_adapter::{json_round_trip, real_stream_fn};
- use serde_json::json;
- use tokio::sync::{mpsc, Mutex};
-
- use super::super::producer::UpdateProducer;
- use super::super::prompt::handle_session_prompt;
- use super::super::{ConnectionState, SessionEntry};
-
- /// The ACP meta namespace on the wire.
- const META: &str = "ai.primeintellect.prime-agent";
-
- /// One armed ACP prompt turn over an in-process faux engine whose
- /// session is persisted (the CLI-built ACP engine shape).
- struct AcpGoalBed {
- mode: AcpModeState,
- state: std::sync::Arc<Mutex<ConnectionState>>,
- session_id: String,
- tx: super::super::producer::FrameSink,
- frames: mpsc::UnboundedReceiver<serde_json::Value>,
- next_request_id: u64,
- pending_id: Option<serde_json::Value>,
- engine: std::sync::Arc<pa_core::session_engine::engine::SessionEngine>,
- /// Held so the engine's cwd outlives the test.
- _dir: tempfile::TempDir,
- }
-
- impl AcpGoalBed {
- /// Build the bed: a faux engine with compaction enabled over the
- /// given reserve (the harness contract), one hosted session.
- async fn new(script: serde_json::Value, reserve_tokens: u64) -> AcpGoalBed {
- let dir = tempfile::TempDir::new().unwrap();
- let agent_dir = dir.path().join("agent");
- std::fs::create_dir_all(&agent_dir).unwrap();
- std::fs::write(
- agent_dir.join("settings.json"),
- json!({
- "compaction": {
- "enabled": true,
- "reserveTokens": reserve_tokens,
- "keepRecentTokens": 10,
- }
- })
- .to_string(),
- )
- .unwrap();
- let parsed = pa_ai::faux::script::parse_faux_script(&script)
- .map_err(anyhow::Error::msg)
- .unwrap();
- let registration = pa_ai::faux::script::register_faux_provider_from_script(&parsed);
- let model = registration.get_model();
- let agent_model: pa_agent::types::Model =
- json_round_trip(&model).expect("model conversion");
- let stream_fn = real_stream_fn(None, model.clone());
- let mut session_manager = SessionManager::in_memory(dir.path());
- session_manager.materialize_session_file(Some(dir.path().join("sessions")));
- let engine = std::sync::Arc::new(
- create_session(SessionEngineConfig {
- semantic_edges: None,
- cron_store: None,
- queued_steering_probe: None,
- image_model_router: None,
- steering_mode: None,
- follow_up_mode: None,
- telemetry: None,
- cwd: dir.path().to_path_buf(),
- agent_dir: agent_dir.clone(),
- mcp_manager: None,
- model: Some(agent_model),
- thinking_level: None,
- stream_fn: Some(stream_fn),
- tools: Vec::new(),
- custom_system_prompt: None,
- prompt_guidelines: Vec::new(),
- generic_mcp_servers: Vec::new(),
- allow_recursion: None,
- session_manager: Some(session_manager),
- extra_host_handlers: None,
- conversation_log_path: None,
- additional_skill_paths: Vec::new(),
- additional_prompt_paths: Vec::new(),
- extra_builtin_skill_overrides: Vec::new(),
- rlm_subagent_host: None,
- rlm_depth: None,
- model_info: Some(model.clone()),
- prewarm_ipython_kernel: None,
- on_background_work_settled: None,
- queued_goal_context_purge: None,
- })
- .await
- .unwrap(),
- );
- let (tx, frames) = mpsc::unbounded_channel::<serde_json::Value>();
- let session_id = "acp-goal-session".to_string();
- let producer = UpdateProducer::new(session_id.clone(), tx.clone());
- let autonomous = std::sync::Arc::new(Mutex::new(
- pa_core::autonomous::create_autonomous_runtime_state(None, None),
- ));
- let driver: std::sync::Arc<dyn pa_core::autonomous::AutonomousDriver> =
- std::sync::Arc::new(pa_core::autonomous::ShellAutonomousDriver::new(dir.path()));
- let session = std::sync::Arc::new(
- super::super::session::AcpSession::new(
- session_id.clone(),
- engine.clone(),
- producer.clone(),
- autonomous,
- driver,
- )
- .await,
- );
- producer.commit_session_new_response().await;
- let state = std::sync::Arc::new(Mutex::new(ConnectionState {
- session: Some(SessionEntry {
- session,
- prompt_task: None,
- config: std::sync::Arc::new(super::super::InProcessConfig {
- published: tokio::sync::Mutex::new(Vec::new()),
- models: tokio::sync::Mutex::new(Vec::new()),
- }),
- config_refresh: None,
- }),
- session_new_in_flight: false,
- session_close_in_flight: false,
- }));
- let mode = AcpModeState {
- engine: engine.clone(),
- actual_cwd: std::sync::Arc::new(dir.path().to_path_buf()),
- product_version: std::sync::Arc::new("test".to_string()),
- model: std::sync::Arc::new(Mutex::new(Some(model))),
- api_key: std::sync::Arc::new(Mutex::new(None)),
- config_queue: std::sync::Arc::new(tokio::sync::Mutex::new(())),
- agent_dir: std::sync::Arc::new(agent_dir),
- provider_target: std::sync::Arc::new(std::sync::RwLock::new(None)),
- autonomous_config: None,
- mcp: engine.mcp_manager.clone(),
- mcp_owner_id: std::sync::Arc::new("acp-goal-owner".to_string()),
- mcp_server_names: std::sync::Arc::new(Mutex::new(Vec::new())),
- };
- AcpGoalBed {
- mode,
- state,
- session_id,
- tx,
- frames,
- next_request_id: 0,
- pending_id: None,
- engine,
- _dir: dir,
- }
- }
-
- /// Admit one prompt through the real ACP prompt handler and read
- /// frames until its response: (response, notifications in order).
- async fn prompt(&mut self, text: String) -> (serde_json::Value, Vec<serde_json::Value>) {
- self.next_request_id += 1;
- let id = serde_json::Value::from(self.next_request_id);
- handle_session_prompt(
- id.clone(),
- json!({
- "sessionId": self.session_id,
- "prompt": [{ "type": "text", "text": text }],
- }),
- self.state.clone(),
- self.mode.clone(),
- self.tx.clone(),
- )
- .await;
- let mut notifications = Vec::new();
- loop {
- let Some(frame) = self.frames.recv().await else {
- panic!("ACP frame channel closed before the response");
- };
- if frame.get("id") == Some(&id)
- && (frame.get("result").is_some() || frame.get("error").is_some())
- {
- return (frame, notifications);
- }
- notifications.push(frame);
- }
- }
-
- /// Fire one prompt without waiting for its response (the settle
- /// loop may hold the turn open; pair with `next_response`).
- async fn fire_prompt(&mut self, text: String) {
- self.next_request_id += 1;
- let id = serde_json::Value::from(self.next_request_id);
- self.pending_id = Some(id.clone());
- handle_session_prompt(
- id,
- json!({
- "sessionId": self.session_id,
- "prompt": [{ "type": "text", "text": text }],
- }),
- self.state.clone(),
- self.mode.clone(),
- self.tx.clone(),
- )
- .await;
- }
-
- /// Send the `session/cancel` notification for the hosted session.
- async fn notify_cancel(&self) {
- super::super::handle_notification(
- "session/cancel".to_string(),
- json!({ "sessionId": self.session_id }),
- self.state.clone(),
- )
- .await;
- }
-
- /// Read frames until the pending fired prompt answers.
- async fn next_response(&mut self) -> serde_json::Value {
- let id = self.pending_id.clone().expect("a fired prompt");
- loop {
- let frame = self
- .frames
- .recv()
- .await
- .expect("ACP frame channel closed before the response");
- if frame.get("id") == Some(&id)
- && (frame.get("result").is_some() || frame.get("error").is_some())
- {
- return frame;
- }
- }
- }
-
- /// Start a goal directly on the engine's driver (no session-command
- /// segment runs, so no scripted response is consumed).
- async fn start_goal(&self, objective: &str, budget: Option<u64>) {
- let persistence = self.engine.session.shared_persistence();
- let mut driver = self.engine.goal_driver.lock().await;
- let mut persistence = persistence.lock().await;
- driver.start(&mut persistence, objective, budget).unwrap();
- }
-
- /// The goal driver's current state.
- async fn goal_state(&self) -> pa_core::goals::GoalState {
- self.engine.goal_driver.lock().await.state().clone()
- }
-
- /// The positions (notification indexes) of the goal-update and
- /// compaction frames, for ordering assertions.
- fn frame_kinds(notifications: &[serde_json::Value]) -> Vec<&'static str> {
- notifications
- .iter()
- .filter_map(|frame| {
- let meta = frame
- .get("params")?
- .get("update")?
- .get("_meta")?
- .get(META)?;
- if meta.get("goal").is_some_and(|value| !value.is_null()) {
- Some("goal")
- } else if meta.get("compaction").is_some_and(|value| !value.is_null()) {
- Some("compaction")
- } else {
- None
- }
- })
- .collect()
- }
-
- /// The streamed text answers among a turn's notifications.
- fn streamed_answers(notifications: &[serde_json::Value]) -> Vec<String> {
- notifications
- .iter()
- .filter_map(|frame| {
- frame
- .get("params")?
- .get("update")?
- .get("content")?
- .get("text")?
- .as_str()
- .map(str::to_string)
- })
- .collect()
- }
- }
-
- /// The turn-failure detail the settle loop reports (the wire shape
- /// the prompt response carries).
- fn turn_error_details(response: &serde_json::Value) -> String {
- response["error"]["data"]["details"]
- .as_str()
- .unwrap_or_default()
- .to_string()
- }
-
- /// The natural continuation loop: an active goal mints one
- /// continuation per settled turn, every minted turn runs inside the
- /// same prompt request, and a failed turn fails the goal. The
- /// scripted responses bound the run: the fourth minted turn errors
- /// (no responses left), which fails the goal and settles the prompt
- /// with the turn error.
- #[tokio::test]
- async fn goal_continuation_loop_mints_per_settled_turn() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed =
- AcpGoalBed::new(json!({ "responses": ["one", "two", "three"] }), 128_000).await;
- let (response, notifications) = bed.prompt("/goal keep working".to_string()).await;
- // Three settled continuation turns ran inside the one prompt;
- // the fourth minted turn hit the exhausted script and failed.
- assert_eq!(
- bed.goal_state().await.continuations_used,
- 3,
- "one mint per settled turn"
- );
- assert_eq!(
- bed.goal_state().await.status,
- pa_core::goals::GoalStatus::Error
- );
- let details = turn_error_details(&response);
- assert!(
- details.contains("No more faux responses queued"),
- "response: {response:?}"
- );
- let joined = AcpGoalBed::streamed_answers(&notifications).join("");
- assert!(
- joined.contains("one") && joined.contains("two") && joined.contains("three"),
- "every scripted answer ran: {notifications:?}"
- );
- // The goal-update frames: the start, the minted usage bumps, and
- // the terminal error state.
- let kinds = AcpGoalBed::frame_kinds(&notifications);
- assert!(
- kinds.iter().filter(|kind| **kind == "goal").count() >= 2,
- "frames: {kinds:?}"
- );
- }
-
- /// The budget-limit wrap-up steer: the turn whose usage crossed the
- /// goal budget runs the budget-limit context as the prompt's last
- /// model segment, the goal settles `budget_limited`, and no
- /// continuation is minted (the steer consumes no slot).
- #[tokio::test]
- async fn budget_crossing_runs_the_wrap_up_steer_and_settles() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = AcpGoalBed::new(
- json!({ "responses": ["GOAL-PROGRESS", "WRAP-UP"] }),
- 128_000,
- )
- .await;
- let (response, notifications) = bed
- .prompt("/goal --budget 5 reply with exactly: GOAL-PROGRESS".to_string())
- .await;
- assert_eq!(
- response["result"]["stopReason"], "end_turn",
- "response: {response:?}"
- );
- let goal = bed.goal_state().await;
- assert_eq!(goal.status, pa_core::goals::GoalStatus::BudgetLimited);
- assert_eq!(goal.continuations_used, 0, "the steer consumes no slot");
- // The two model segments streamed their scripted answers (the
- // faux pacing may split one answer into chunks, so the joined
- // text carries the observable contract).
- let joined = AcpGoalBed::streamed_answers(&notifications).join("");
- assert!(
- joined.contains("GOAL-PROGRESS") && joined.contains("WRAP-UP"),
- "the steer ran as the second segment: {notifications:?}"
- );
- }
-
- /// The threshold arm's goal queue: a crossing turn with an active
- /// goal mints the continuation BEFORE the compaction runs (the
- /// goal-update frame precedes the compaction frame), and the held
- /// turn runs as the post-compaction turn. A skipped compaction keeps
- /// the mint (TS `resumeAfterFailure`); the run continues until the
- /// scripted responses end and the failed turn fails the goal.
- #[tokio::test]
- async fn threshold_arm_queues_the_goal_continuation_before_compacting() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = AcpGoalBed::new(
- json!({
- "responses": [
- "seed reply",
- "one",
- "the summary",
- "two",
- ]
- }),
- // A 500-token combined ceiling (the window minus the faux
- // request budget and the reserve).
- 128_000u64.saturating_sub(FAUX_REQUEST_BUDGET + 500),
- )
- .await;
- // The harness shape: a seeded crossing turn whose boundary
- // compaction skips (a single-turn session has nothing to
- // summarize), then the goal's crossing turn whose boundary
- // compaction runs over the seeded turn.
- let (response, _) = bed.prompt(format!("turn one {}", "x".repeat(8_000))).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- bed.start_goal("keep working", None).await;
- let (response, notifications) = bed.prompt(format!("turn two {}", "x".repeat(8_000))).await;
- // The run continued over the threshold arm's minted turns until
- // the scripted responses ended.
- let details = turn_error_details(&response);
- assert!(
- details.contains("No more faux responses queued"),
- "response: {response:?}"
- );
- assert_eq!(
- bed.goal_state().await.status,
- pa_core::goals::GoalStatus::Error
- );
- assert!(
- bed.goal_state().await.continuations_used >= 2,
- "the queue minted"
- );
- // A compaction ran (the summary) and the goal mint's update frame
- // precedes it: the mint happens before the compaction like the TS
- // event order. (The pre-turn skip disclosure also carries the
- // empty compaction meta, so the ordering check targets the
- // summary-carrying frame.)
- let ran_compaction_at = notifications
- .iter()
- .position(|frame| {
- let meta = &frame["params"]["update"]["_meta"][META]["compaction"];
- meta.get("summary")
- .is_some_and(|s| s.as_str().unwrap_or_default().contains("the summary"))
- })
- .expect("the threshold compaction ran");
- let mint_goal_at = notifications
- .iter()
- .position(|frame| {
- let meta = &frame["params"]["update"]["_meta"][META];
- meta.get("goal").is_some_and(|value| !value.is_null())
- })
- .expect("a goal frame");
- assert!(
- mint_goal_at < ran_compaction_at,
- "the mint announces before the compaction: {notifications:?}"
- );
- }
-
- /// The compact-with-active-goal continue (TS `compact()`'s `didCompact`
- /// finally arm): a successful `/compact` with an active goal mints the
- /// continuation and runs it as the command turn's model segment.
- #[tokio::test]
- async fn compact_command_with_active_goal_mints_the_continue() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- // No threshold interference (reserve 0 keeps the full window
- // free), and two seeded turns so the manual compact runs (a
- // single-turn session skips).
- let mut bed = AcpGoalBed::new(
- json!({ "responses": ["seed reply", "second reply", "the summary", "continued", "next"] }),
- 0,
- )
- .await;
- for seed in ["seed turn one", "seed turn two"] {
- let (response, _) = bed.prompt(seed.to_string()).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- }
- bed.start_goal("keep working", None).await;
- let (response, notifications) = bed.prompt("/compact".to_string()).await;
- // The compact ran, the minted continue ran as the segment, and
- // the natural loop continued until the scripted responses ended.
- let details = turn_error_details(&response);
- assert!(
- details.contains("No more faux responses queued"),
- "response: {response:?}"
- );
- // The compact ran (its summary wraps the scripted reply) and the
- // minted continue ran as the command turn's model segment; the
- // armed compact-trigger review services at the continuation
- // turn's boundary (it consumes the next scripted reply), then
- // the natural mint continues the loop until the responses end.
- let compaction_ran = notifications.iter().any(|frame| {
- let meta = &frame["params"]["update"]["_meta"][META]["compaction"];
- meta.get("summary")
- .is_some_and(|s| s.as_str().unwrap_or_default().contains("the summary"))
- });
- assert!(compaction_ran, "the manual compact ran: {notifications:?}");
- let answers = AcpGoalBed::streamed_answers(&notifications);
- assert!(
- answers.contains(&"continued".to_string()),
- "the compact-site continue ran: {notifications:?}"
- );
- assert!(bed.goal_state().await.continuations_used >= 2);
- }
-
- /// A cancelled threshold compaction withdraws the queued mint: the
- /// slot rolls back (continuationsUsed never counted the withdrawn
- /// turn), and the cancellation settles the prompt.
- #[tokio::test]
- async fn cancelled_threshold_compaction_rolls_back_the_mint() {
- let _faux = FAUX_TEST_LOCK
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let mut bed = AcpGoalBed::new(
- json!({
- "responses": [
- "seed reply",
- { "text": "the summary", "delayMs": 30_000 },
- ]
- }),
- // A 500-token combined ceiling (the window minus the faux
- // request budget and the reserve).
- 128_000u64.saturating_sub(FAUX_REQUEST_BUDGET + 500),
- )
- .await;
- // The harness shape: a seeded crossing turn (its boundary
- // compaction skips — single turn), then the goal's crossing turn
- // whose boundary compaction runs over the seeded turn.
- let (response, _) = bed.prompt(format!("turn one {}", "x".repeat(8_000))).await;
- assert_eq!(response["result"]["stopReason"], "end_turn");
- bed.start_goal("keep working", None).await;
- // Fire the prompt (its settle loop holds in the threshold arm's
- // in-flight compaction), cancel mid-compaction, then read the
- // response: the held stream delays the summarizer long enough for
- // the cancel to land.
- bed.fire_prompt(format!("turn two {}", "x".repeat(8_000)))
- .await;
- tokio::time::sleep(std::time::Duration::from_millis(750)).await;
- bed.notify_cancel().await;
- let response = bed.next_response().await;
- assert_eq!(
- response["result"]["stopReason"], "cancelled",
- "response: {response:?}"
- );
- let goal = bed.goal_state().await;
- assert_eq!(goal.status, pa_core::goals::GoalStatus::Active);
- assert_eq!(
- goal.continuations_used, 0,
- "the cancelled arm's mint rolled back"
- );
- }
-}
diff --git a/crates/pa-daemon/src/acp/in_process_config.rs b/crates/pa-daemon/src/acp/in_process_config.rs
deleted file mode 100644
index 414f69e612..0000000000
--- a/crates/pa-daemon/src/acp/in_process_config.rs
+++ /dev/null
@@ -1,604 +0,0 @@
-//! The in-process ACP picker machinery (the TS #2455 port's engine side):
-//! the session's picker state and serialized config queue, the
-//! `session/set_config_option` handler over the session engine, the
-//! model/thinking-level application semantics, and the agent-run refresh
-//! that republishes `config_option_update` on change.
-//!
-//! The wire-shape builders and the compare-gated publisher live in
-//! [`super::config_options`]; this module owns the in-process state and
-//! the apply/refresh lifecycle over [`AcpModeState`] and [`AcpSession`].
-
-use std::sync::Arc;
-
-use serde_json::{json, Value};
-use tokio::sync::Mutex;
-
-use super::config_options::{
- acp_model_registry, config_options_value, discover_available_models, model_value,
- publish_config_options, session_config_options, PickerModel, SessionConfigOption,
-};
-use super::jsonrpc;
-use super::producer;
-use super::session::AcpSession;
-use super::types;
-use super::{internal_error, AcpModeState, ConnectionState};
-
-/// The in-process picker state: the published options, the discovered
-/// models, and the serialized queue every config operation runs through
-/// (TS `enqueueConfig`/`configTask` — close drains it before the
-/// producer fences).
-pub(crate) struct InProcessConfig {
- pub(crate) published: tokio::sync::Mutex<Vec<SessionConfigOption>>,
- pub(crate) models: tokio::sync::Mutex<Vec<pa_types::ai::Model>>,
-}
-
-/// Build the admitted session's picker state (TS `session/new`'s
-/// `entry.configOptions`/`entry.models`): discovery must not block
-/// admission (a failure degrades to an empty list), and the options come
-/// from the live model, its supported levels, and the agent's resolved
-/// thinking level.
-pub(super) async fn admit_session_config(mode: &AcpModeState) -> Arc<InProcessConfig> {
- let models = tokio::task::spawn_blocking({
- let agent_dir = Arc::clone(&mode.agent_dir);
- move || discover_available_models(&agent_dir)
- })
- .await
- .ok()
- .and_then(std::result::Result::ok)
- .unwrap_or_default();
- let published = {
- let current = mode.current_model().await;
- let state = mode.engine.session.agent().state().await;
- let thinking_level =
- pa_core::session_engine::provider_adapter::model_thinking_level(state.thinking_level)
- .wire_name()
- .to_string();
- let levels = supported_levels(current.as_ref());
- session_config_options(
- current.as_ref().map(PickerModel::from_model),
- &thinking_level,
- &levels,
- &models,
- )
- };
- Arc::new(InProcessConfig {
- published: tokio::sync::Mutex::new(published),
- models: tokio::sync::Mutex::new(models),
- })
-}
-
-/// `session/set_config_option`: apply one picker selection and answer the
-/// refreshed options (TS #2455). Config work is serialized through the
-/// session's queue, so selections and event-driven refreshes observe one
-/// another in arrival order.
-pub(super) async fn handle_set_config_option(
- id: Value,
- params: Value,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) {
- let params = types::SetConfigOptionParams::parse(&params);
- // The session resolves before the queue (TS reads `session?.id`).
- let resolved = {
- let state = state.lock().await;
- state
- .session
- .as_ref()
- .filter(|entry| entry.session.id == params.session_id)
- .map(|entry| (Arc::clone(&entry.session), Arc::clone(&entry.config)))
- };
- let Some((session, config)) = resolved else {
- let _ = tx.send(jsonrpc::error_response(
- &id,
- jsonrpc::INVALID_PARAMS,
- "Invalid params",
- Some(&json!({ "reason": format!("Unknown ACP session: {}", params.session_id) })),
- ));
- return;
- };
- // One config operation at a time (TS `enqueueConfig`): the queue also
- // serializes the agent-run refreshes and the trigger-consuming arms.
- let _guard = mode.config_queue.lock().await;
- // The queue can outlive the session: a close admitted between the
- // resolution and the run refuses further config work (TS
- // `sessionCloseInFlight`).
- let live = {
- let state = state.lock().await;
- !state.session_close_in_flight
- && state
- .session
- .as_ref()
- .is_some_and(|current| current.session.id == session.id)
- };
- let outcome = if live {
- apply_in_process_config(
- &session,
- &config,
- &mode,
- &params.config_id,
- params.value.as_str(),
- )
- .await
- } else {
- Err(ConfigOptionError::invalid_params(
- "ACP session is closed or closing",
- ))
- };
- let options = match outcome {
- Ok(options) => options,
- Err(error) => {
- let _ = tx.send(error.response(&id));
- return;
- }
- };
- let _ = tx.send(jsonrpc::response(&id, &config_options_value(&options)));
-}
-
-/// One failed config operation: the TS handler's `RequestError` shape.
-#[derive(Debug)]
-enum ConfigOptionError {
- InvalidParams(String),
- Internal(String),
-}
-
-impl ConfigOptionError {
- fn invalid_params(reason: &str) -> ConfigOptionError {
- ConfigOptionError::InvalidParams(reason.to_string())
- }
-
- /// The JSON-RPC error frame (the TS `invalidParams` data shape).
- fn response(self, id: &Value) -> Value {
- match self {
- ConfigOptionError::InvalidParams(reason) => jsonrpc::error_response(
- id,
- jsonrpc::INVALID_PARAMS,
- "Invalid params",
- Some(&json!({ "reason": reason })),
- ),
- ConfigOptionError::Internal(details) => internal_error(id, &details),
- }
- }
-}
-
-/// Apply one selection (TS `session/set_config_option`'s handler body):
-/// validate against the live session state, apply through the engine, then
-/// return the refreshed options with the change published.
-async fn apply_in_process_config(
- session: &Arc<AcpSession>,
- config: &Arc<InProcessConfig>,
- mode: &AcpModeState,
- config_id: &str,
- value: Option<&str>,
-) -> Result<Vec<SessionConfigOption>, ConfigOptionError> {
- match (config_id, value) {
- ("model", Some(value)) => {
- // The no-op check reads the agent's live model (TS
- // `getState().model`): the current model re-selected refreshes
- // only, no discovery (a resync during a discovery outage
- // still answers).
- let live = session.agent().state().await;
- if model_value(&live.model.provider, &live.model.id) == value {
- return Ok(refresh_in_process_config(session, config, mode).await);
- }
- // Discover the available models (TS `getAvailableModels`): the
- // registry the composition resolved against. Discovery failures
- // are the handler's "try again later" invalid-params.
- let models = tokio::task::spawn_blocking({
- let agent_dir = Arc::clone(&mode.agent_dir);
- move || discover_available_models(&agent_dir)
- })
- .await
- .map_err(|_| ConfigOptionError::Internal("model discovery task failed".to_string()))?
- .map_err(|_| {
- ConfigOptionError::invalid_params("Model discovery is unavailable; try again later")
- })?;
- let model = models
- .iter()
- .find(|model| model_value(&model.provider, &model.id) == value)
- .cloned()
- .ok_or_else(|| {
- ConfigOptionError::invalid_params(&format!("Unavailable model: {value}"))
- })?;
- apply_in_process_model_switch(session, mode, model)
- .await
- .map_err(|error| {
- ConfigOptionError::Internal(format!("model switch failed: {error:#}"))
- })?;
- *config.models.lock().await = models;
- Ok(refresh_in_process_config(session, config, mode).await)
- }
- ("thought_level", Some(value)) => {
- let current = mode.current_model().await;
- let levels = supported_levels(current.as_ref());
- // #2858's map-driven capability: an addressable
- // thinking-level map marks the model thinking-capable even
- // when the coarse `reasoning` flag is false, so the flag
- // must not veto a level the map advertises.
- let supported = current
- .as_ref()
- .is_some_and(pa_ai::models::supports_thinking)
- && levels.iter().any(|level| level == value);
- if !supported {
- return Err(ConfigOptionError::invalid_params(&format!(
- "Unsupported reasoning effort: {value}"
- )));
- }
- apply_in_process_thinking_level(session, mode, value).await?;
- Ok(refresh_in_process_config(session, config, mode).await)
- }
- _ => Err(ConfigOptionError::invalid_params(&format!(
- "Invalid configuration option: {config_id}"
- ))),
- }
-}
-
-/// The model's supported thinking levels as wire names (TS
-/// `availableThinkingLevels`).
-fn supported_levels(model: Option<&pa_types::ai::Model>) -> Vec<String> {
- model
- .map(|model| {
- pa_ai::models::get_supported_thinking_levels(model)
- .into_iter()
- .map(|level| level.wire_name().to_string())
- .collect()
- })
- .unwrap_or_default()
-}
-
-/// Switch the session's model (TS `setModel`): swap the provider stream
-/// target, set the agent's model, record the durable row and the settings
-/// default, and restore the thinking level against the new model.
-async fn apply_in_process_model_switch(
- session: &Arc<AcpSession>,
- mode: &AcpModeState,
- model: pa_types::ai::Model,
-) -> anyhow::Result<()> {
- // The request key for the switched model: the same registry resolution
- // the create-time composition ran (TS re-registers the stream with the
- // model's own auth).
- let mut registry = tokio::task::spawn_blocking({
- let agent_dir = Arc::clone(&mode.agent_dir);
- move || acp_model_registry(&agent_dir)
- })
- .await
- .map_err(|_| anyhow::anyhow!("model registry task failed"))?;
- let resolved = registry.get_api_key_and_headers(&model, model.headers.as_ref());
- // An unresolvable selection refuses the switch BEFORE anything
- // moves (the RPC path's own rule, `apply_model_selection`):
- // `get_api_key_and_headers` can answer `ok: false` even for a model
- // discovery admits, and installing it would leave the provider
- // target without usable authentication — the NEXT turn would fail
- // instead of this request. TS's `setModel` refuses the same way
- // ("No API key for ...").
- if !resolved.ok {
- anyhow::bail!(resolved.error.unwrap_or_else(|| {
- format!(
- "Model is not available: no credentials resolved for {}/{}",
- model.provider, model.id
- )
- }));
- }
- // The previous live state, for the rollback a failed durable write
- // takes (a failure would otherwise leave the target switched and the
- // session's model identity split).
- let previous_target = mode
- .provider_target
- .read()
- .expect("provider target lock")
- .clone();
- let previous_model = mode.current_model().await;
- let previous_api_key = mode.current_api_key().await;
- // The stream target swaps in place: the next turn streams on the
- // selected model (the service-tier preference survives the switch).
- {
- let mut target = mode.provider_target.write().expect("provider target lock");
- match target.as_mut() {
- Some(target) => {
- target.api_key.clone_from(&resolved.api_key);
- target.model = model.clone();
- target.headers.clone_from(&resolved.headers);
- }
- None => {
- *target = Some(pa_core::session_engine::provider_adapter::ProviderTarget {
- api_key: resolved.api_key.clone(),
- model: model.clone(),
- service_tier: None,
- headers: resolved.headers.clone(),
- });
- }
- }
- }
- // The agent's model plus the durable `model_change` row (TS records
- // every switch, even to the current model). A failed persist rolls
- // the live state back: the client sees the refusal and the session
- // keeps running on the model it still reports.
- if let Err(error) = mode
- .engine
- .session
- .set_model(&model, &model.provider, &model.id)
- .await
- {
- roll_back_model(
- session,
- mode,
- previous_model.as_ref(),
- previous_target,
- previous_api_key,
- )
- .await;
- anyhow::bail!(error);
- }
- // The session's live request key follows the switch (the
- // session-command executors authenticate against the switched
- // model's provider).
- *mode.api_key.lock().await = resolved.api_key.clone();
- // The live model slot follows with the same step, so the switch's
- // live trio (provider target, request key, model) never splits:
- // `current_model()` — picker validation, `/compact`, `/refine` —
- // always answers the model the turns stream on, before OR after a
- // later step fails (TS's `setModel` assigns the session model before
- // it persists, so a failed write rejects with the switched session
- // applied, never a split one).
- *mode.model.lock().await = Some(model.clone());
- // TS `session.setModel` persists the default provider/model so the
- // next session starts on the switched model. The settings store is
- // file-backed (reads, an atomic write, and lock-contention retries
- // that sleep), so the write runs off the Tokio worker — the config
- // queue this handler holds must not park a runtime thread other ACP
- // work shares (`spawn_blocking`'s contract).
- let persist = {
- let cwd = Arc::clone(&mode.actual_cwd);
- let agent_dir = Arc::clone(&mode.agent_dir);
- let provider = model.provider.clone();
- let id = model.id.clone();
- tokio::task::spawn_blocking(move || {
- let mut settings =
- pa_core::settings::SettingsManager::create(cwd.as_path(), agent_dir.as_path());
- settings.set_default_model_and_provider(&provider, &id)
- })
- .await
- .map_err(|error| anyhow::anyhow!("the settings persist task failed: {error}"))?
- };
- if let Err(error) = persist {
- anyhow::bail!(error);
- }
- // The thinking level follows the switch (TS
- // `_getThinkingLevelForModelSwitch` + `setThinkingLevel`): the current
- // level when the pre-switch model is thinking-capable, else the
- // settings default — always clamped to the switched model. TS reads
- // the decision off `this.model` BEFORE the assignment, so the
- // pre-switch capture (`previous_model`) is the source, not the live
- // slot (which already names the switched model). The capability is
- // #2858's map-driven one: an addressable thinking-level map marks
- // the model thinking-capable even when the coarse `reasoning` flag
- // is false.
- let current_level = session.agent().state().await.thinking_level;
- let requested = if previous_model
- .as_ref()
- .is_some_and(pa_ai::models::supports_thinking)
- {
- pa_core::session_engine::provider_adapter::model_thinking_level(current_level)
- } else {
- // The settings read runs off the worker like the write above.
- let default = {
- let cwd = Arc::clone(&mode.actual_cwd);
- let agent_dir = Arc::clone(&mode.agent_dir);
- tokio::task::spawn_blocking(move || {
- let settings =
- pa_core::settings::SettingsManager::create(cwd.as_path(), agent_dir.as_path());
- settings.get_default_thinking_level()
- })
- .await
- .map_err(|error| anyhow::anyhow!("the settings read task failed: {error}"))?
- };
- default.map_or(
- pa_types::ai::ModelThinkingLevel::Medium,
- pa_core::settings::ThinkingLevelSetting::model_level,
- )
- };
- let effective = pa_ai::models::clamp_thinking_level(&model, requested);
- // The failed-durable-write fallback for the switched model: the
- // pre-switch level clamped to the model the switch installed (the
- // raw pre-switch level can be one it does not support).
- let restore = pa_core::session_engine::provider_adapter::map_thinking_level(
- pa_ai::models::clamp_thinking_level(
- &model,
- pa_core::session_engine::provider_adapter::model_thinking_level(current_level),
- ),
- );
- apply_level_change(
- session,
- mode,
- effective,
- pa_ai::models::supports_thinking(&model),
- restore,
- )
- .await
- .map_err(|error| anyhow::anyhow!("{error:?}"))?;
- Ok(())
-}
-
-/// Roll the live session back to its previous model state after a failed
-/// durable `model_change` write: the provider target, the agent's model,
-/// and the mode's live slots all return to the pre-switch pair the client
-/// still sees.
-async fn roll_back_model(
- session: &Arc<AcpSession>,
- mode: &AcpModeState,
- previous_model: Option<&pa_types::ai::Model>,
- previous_target: Option<pa_core::session_engine::provider_adapter::ProviderTarget>,
- previous_api_key: Option<String>,
-) {
- {
- let mut target = mode.provider_target.write().expect("provider target lock");
- *target = previous_target;
- }
- *mode.api_key.lock().await = previous_api_key;
- if let Some(model) = previous_model {
- let wire: Option<pa_agent::types::Model> = serde_json::to_value(model)
- .ok()
- .and_then(|value| serde_json::from_value(value).ok());
- if let Some(wire) = wire {
- session.agent().set_model(wire).await;
- }
- *mode.model.lock().await = Some(model.clone());
- }
-}
-
-/// Apply a thinking-level selection (TS `setThinkingLevel`): the level was
-/// validated against the model's supported levels, so the agent follows it
-/// and the durable row plus the settings default record the change.
-async fn apply_in_process_thinking_level(
- session: &Arc<AcpSession>,
- mode: &AcpModeState,
- level: &str,
-) -> Result<(), ConfigOptionError> {
- let parsed = pa_types::ai::thinking_level_from_str(level)
- .ok_or_else(|| ConfigOptionError::invalid_params("Invalid thinking level"))?;
- let current = mode.current_model().await;
- // #2858's map-driven capability (see the validation gate).
- let thinking = current
- .as_ref()
- .is_some_and(pa_ai::models::supports_thinking);
- // The standalone change's fallback is the level it replaces — the
- // model did not change, so it is supported.
- let restore = session.agent().state().await.thinking_level;
- apply_level_change(session, mode, parsed, thinking, restore).await
-}
-
-/// The shared level application: agent + durable row when the effective
-/// level changed, settings default when the model has a thinking surface
-/// or the level is not `off` (TS `setThinkingLevel`'s persist gate, gated
-/// on #2858's map-driven capability rather than the coarse flag). A
-/// failed durable `thinking_level_change` write rolls the live agent back
-/// to `restore`: the caller names a level the model the agent now runs
-/// supports — a standalone change returns to the level it replaced; a
-/// model switch returns to the pre-switch level CLAMPED to the switched
-/// model (the raw pre-switch level can be one it does not support).
-async fn apply_level_change(
- session: &Arc<AcpSession>,
- mode: &AcpModeState,
- level: pa_types::ai::ModelThinkingLevel,
- thinking: bool,
- restore: pa_agent::types::ThinkingLevel,
-) -> Result<(), ConfigOptionError> {
- let mapped = pa_core::session_engine::provider_adapter::map_thinking_level(level);
- let current = session.agent().state().await.thinking_level;
- if current == mapped {
- return Ok(());
- }
- if let Err(error) = mode.engine.session.set_thinking_level(mapped).await {
- session.agent().set_thinking_level(restore).await;
- return Err(ConfigOptionError::Internal(format!(
- "thinking level switch failed: {error:#}"
- )));
- }
- if thinking || level != pa_types::ai::ModelThinkingLevel::Off {
- // The file-backed settings write runs off the Tokio worker, like
- // the model switch's persist (the queue this handler holds must
- // not park a runtime thread).
- let cwd = Arc::clone(&mode.actual_cwd);
- let agent_dir = Arc::clone(&mode.agent_dir);
- let setting = pa_core::settings::ThinkingLevelSetting::from_model_level(level);
- let persist = tokio::task::spawn_blocking(move || {
- let mut settings =
- pa_core::settings::SettingsManager::create(cwd.as_path(), agent_dir.as_path());
- settings.set_default_thinking_level(setting)
- })
- .await
- .map_err(|error| {
- ConfigOptionError::Internal(format!("the settings persist task failed: {error}"))
- })?;
- // TS `setThinkingLevel`'s chain rejects on a failed settings
- // write (the level assignment and the durable row already ran,
- // exactly like the model switch).
- persist.map_err(|error| {
- ConfigOptionError::Internal(format!("thinking level default persist failed: {error:#}"))
- })?;
- }
- Ok(())
-}
-
-/// Recompute the options from the live session state and publish the
-/// change (TS `refreshConfig`): the picker identity and the thinking
-/// level are the agent's own view, so an out-of-band model or level
-/// switch still republishes; the supported levels come from the full
-/// registry model (discovered or tracked) that matches the live agent
-/// model.
-async fn refresh_in_process_config(
- session: &Arc<AcpSession>,
- config: &Arc<InProcessConfig>,
- mode: &AcpModeState,
-) -> Vec<SessionConfigOption> {
- let tracked = mode.current_model().await;
- let state = session.agent().state().await;
- let thinking_level =
- pa_core::session_engine::provider_adapter::model_thinking_level(state.thinking_level)
- .wire_name()
- .to_string();
- // The picker's identity is the agent's live model (an out-of-band
- // failover switch moves it without the picker slot); the supported
- // levels need the full registry model, so the discovered list (or the
- // tracked slot) supplies the map when the agent's view matches.
- let models = config.models.lock().await;
- let live_model = PickerModel::from_agent_model(&state.model);
- let full_model = models
- .iter()
- .find(|model| model.provider == live_model.provider && model.id == live_model.id)
- .cloned()
- .or_else(|| {
- tracked
- .as_ref()
- .filter(|model| model.provider == live_model.provider && model.id == live_model.id)
- .cloned()
- });
- let levels = match full_model.as_ref() {
- Some(model) => supported_levels(Some(model)),
- // No registry entry: the agent model's reasoning flag alone decides
- // the no-map ladder (the map-less levels the registry would give).
- None if live_model.reasoning => [
- pa_types::ai::ModelThinkingLevel::Off,
- pa_types::ai::ModelThinkingLevel::Minimal,
- pa_types::ai::ModelThinkingLevel::Low,
- pa_types::ai::ModelThinkingLevel::Medium,
- pa_types::ai::ModelThinkingLevel::High,
- ]
- .iter()
- .map(|level| level.wire_name().to_string())
- .collect(),
- None => Vec::new(),
- };
- let options = session_config_options(Some(live_model), &thinking_level, &levels, &models);
- publish_config_options(session.producer(), &config.published, options.clone()).await;
- options
-}
-
-/// Wire the picker refresh to the end of every agent run (the TS
-/// `agent_end` trigger): the refresh is fire-and-forget through the
-/// serialized queue, so the agent loop never waits on config work.
-pub(super) async fn wire_config_refresh(
- session: &Arc<AcpSession>,
- config: Arc<InProcessConfig>,
- mode: AcpModeState,
-) -> pa_agent::agent::Subscription {
- let agent = Arc::clone(session.agent());
- // The owned clones the 'static listener captures (the borrow ends here).
- let session = Arc::clone(session);
- agent
- .subscribe(move |event, _signal| {
- let session = Arc::clone(&session);
- let config = Arc::clone(&config);
- let mode = mode.clone();
- Box::pin(async move {
- if matches!(event, pa_agent::types::AgentEvent::AgentEnd { .. }) {
- tokio::spawn(async move {
- let _guard = mode.config_queue.lock().await;
- let _ = refresh_in_process_config(&session, &config, &mode).await;
- });
- }
- Ok(())
- })
- })
- .await
-}
diff --git a/crates/pa-daemon/src/acp/mcp.rs b/crates/pa-daemon/src/acp/mcp.rs
index 7885cb7c55..87e2530352 100644
--- a/crates/pa-daemon/src/acp/mcp.rs
+++ b/crates/pa-daemon/src/acp/mcp.rs
@@ -5,7 +5,7 @@
//! Transport-level contract: validation failures are ACP `invalid params`
//! errors with a `reason` payload; admission failures (tool-name
//! conflicts, ownership fencing) are internal errors carrying the raw
-//! message, exactly like the TS in-process connection.
+//! message, like the TS connection.
use std::collections::HashSet;
use std::path::Path;
@@ -316,80 +316,6 @@ pub fn acp_mcp_tool_names(servers: &[AcpMcpServerConfig]) -> Result<Vec<String>,
Ok(names)
}
-/// Admit one session's `mcpServers` through the full TS pipeline:
-/// zod entry dropping, `resolveAcpMcpServers` validation, tool-name
-/// derivation, owner-scoped replace with cleanup on failure. Returns the
-/// queued JSON-RPC error response on rejection.
-pub async fn admit_session_servers(
- servers: &[Value],
- mode: &super::AcpModeState,
-) -> std::result::Result<(), Value> {
- let resolved = match resolve_acp_mcp_servers(servers, &mode.actual_cwd) {
- Ok(resolved) => resolved,
- Err(reason) => {
- return Err(jsonrpc_invalid_params(&reason));
- }
- };
- if let Err(details) = acp_mcp_tool_names(&resolved) {
- return Err(super::internal_error_value(&details));
- }
- // A second admission first clears the previous session's servers, even
- // when the new list is empty.
- let previous_names = std::mem::take(&mut *mode.mcp_server_names.lock().await);
- if previous_names.is_empty() && resolved.is_empty() {
- return Ok(());
- }
- // The manager guard must not cross an await: scope it tightly.
- let failure = {
- let manager = mode.mcp.lock().unwrap();
- manager
- .replace_acp_servers(&resolved, &mode.mcp_owner_id)
- .err()
- .map(|error| {
- // The daemon may have applied the configuration before its
- // acknowledgement was lost: always attempt owner-scoped
- // cleanup before rejecting admission.
- if manager.can_release_acp_servers(&mode.mcp_owner_id) {
- let _ = manager.replace_acp_servers(&[], &mode.mcp_owner_id);
- }
- error.to_string()
- })
- };
- if let Some(failure) = failure {
- return Err(super::internal_error_value(&failure));
- }
- if !resolved.is_empty() {
- *mode.mcp_server_names.lock().await = resolved
- .iter()
- .map(AcpMcpServerConfig::name)
- .map(str::to_string)
- .collect();
- }
- Ok(())
-}
-
-/// Release the admitted servers on `session/close` or a failed admission
-/// tail (TS `clearAcpMcpServers`): owner-fenced replace-with-empty.
-pub async fn release_session_servers(mode: &super::AcpModeState) {
- let names = std::mem::take(&mut *mode.mcp_server_names.lock().await);
- if names.is_empty() {
- return;
- }
- let manager = mode.mcp.lock().unwrap();
- if manager.can_release_acp_servers(&mode.mcp_owner_id) {
- let _ = manager.replace_acp_servers(&[], &mode.mcp_owner_id);
- }
-}
-
-fn jsonrpc_invalid_params(reason: &str) -> Value {
- super::jsonrpc::error_response(
- &Value::Null,
- super::jsonrpc::INVALID_PARAMS,
- "Invalid params",
- Some(&serde_json::json!({ "reason": reason })),
- )
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/pa-daemon/src/acp/meta.rs b/crates/pa-daemon/src/acp/meta.rs
index 767d8d0a5f..b98d3b8f66 100644
--- a/crates/pa-daemon/src/acp/meta.rs
+++ b/crates/pa-daemon/src/acp/meta.rs
@@ -179,7 +179,7 @@ pub struct PrimeAgentAutonomousMeta {
/// The `_meta.autonomous` accounting for a completion update: per-run usage
/// plus the latest gate attempt and failure (TS `autonomousMeta` in
-/// acp-mode.ts). Shared by the in-process and daemon-attached settlements.
+/// acp-mode.ts). The daemon-attached settlement's accounting.
pub fn autonomous_meta(
status: &pa_core::autonomous::AgentAutonomousStatus,
) -> PrimeAgentAutonomousMeta {
diff --git a/crates/pa-daemon/src/acp/mod.rs b/crates/pa-daemon/src/acp/mod.rs
index ef2f56b673..db93a84cda 100644
--- a/crates/pa-daemon/src/acp/mod.rs
+++ b/crates/pa-daemon/src/acp/mod.rs
@@ -1,597 +1,18 @@
-//! ACP stdio mode: a thin JSON-RPC transport over the session engine.
-//!
-//! One connection hosts at most one session. `session/new` admits the
-//! session (reporting a cwd mismatch instead of adopting one) and
-//! advertises the model and reasoning-effort pickers, `session/prompt`
-//! drives one engine turn with follow-up queueing semantics,
-//! `session/set_config_option` applies a picker selection, and
-//! `session/cancel` / `session/close` stop work. Every frame leaves
-//! through one ordered write queue, so responses and `session/update`
-//! notifications interleave exactly in publication order. The process
-//! exits when stdin closes.
+//! ACP stdio mode served over a daemon session; see `daemon.rs`.
-mod autorefine;
-mod compaction_arms;
mod config_options;
pub mod daemon;
-mod events;
-mod goal_continuation;
-mod in_process_config;
mod jsonrpc;
mod mcp;
mod meta;
mod producer;
-mod prompt;
-mod session;
mod types;
mod wire_config;
mod wire_events;
use std::path::{Path, PathBuf};
-use std::sync::Arc;
-use anyhow::Result;
use serde_json::{json, Value};
-use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-use tokio::sync::Mutex;
-
-use pa_core::autonomous::create_autonomous_runtime_state;
-use pa_core::session_engine::engine::SessionEngine;
-
-use jsonrpc::Incoming;
-use meta::PrimeAgentSessionMeta;
-use producer::UpdateProducer;
-use session::AcpSession;
-use types::{
- initialize_result, session_id_params, AcpStopReason, AcpStopReasonResponse, NewSessionParams,
-};
-
-use config_options::ProviderTargetSlot;
-use in_process_config::{admit_session_config, InProcessConfig};
-
-/// Everything the mode needs from the composition root.
-pub struct AcpOptions {
- /// The running session engine (`create_session` output).
- pub engine: Arc<SessionEngine>,
- /// The cwd the session actually runs in, fixed at startup.
- pub actual_cwd: PathBuf,
- /// The product version reported in `initialize`.
- pub product_version: String,
- /// The session's resolved model, for session-command executors
- /// (`/compact`, `/refine`) that run their own provider calls.
- pub model: Option<pa_types::ai::Model>,
- /// Resolved request API key for those executors.
- pub api_key: Option<String>,
- /// The agent dir: the global harness directory for refinement history.
- pub agent_dir: PathBuf,
- /// The autonomous runtime configuration from the CLI flags.
- pub autonomous_config: Option<pa_core::autonomous::AgentAutonomousConfig>,
- /// The switchable provider target the session's stream reads per call
- /// (the composition's create-time output): a picker model switch swaps
- /// it so the next turn streams on the selected model (TS `setModel`'s
- /// stream re-registration).
- pub provider_target: ProviderTargetSlot,
-}
-
-/// The hosted-session slot plus the in-flight admission bookkeeping.
-#[derive(Default)]
-struct ConnectionState {
- session: Option<SessionEntry>,
- session_new_in_flight: bool,
- session_close_in_flight: bool,
-}
-
-/// Composition-root inputs shared by every handler: the engine plus the
-/// fixed process identity (cwd, version) and the session-command inputs
-/// (resolved model, api key, agent dir, autonomous config).
-#[derive(Clone)]
-struct AcpModeState {
- engine: Arc<SessionEngine>,
- actual_cwd: Arc<PathBuf>,
- product_version: Arc<String>,
- /// The session's live model (TS `state.model`): the composition's
- /// resolved model at admission, updated by a picker model switch so
- /// the session-command executors (`/compact`, `/refine`) follow the
- /// switched model, exactly like the TS session's own calls.
- model: Arc<Mutex<Option<pa_types::ai::Model>>>,
- /// The session's live request key: follows a picker model switch's
- /// registry resolution, so the session-command executors authenticate
- /// against the switched model's provider (TS re-resolves auth with
- /// the model).
- api_key: Arc<Mutex<Option<String>>>,
- /// The serialized config queue (TS `configTask`): picker switches and
- /// the trigger-consuming arms observe one another through it, so an
- /// armed refinement never reads the pre-switch model mid-switch.
- config_queue: Arc<tokio::sync::Mutex<()>>,
- agent_dir: Arc<PathBuf>,
- provider_target: ProviderTargetSlot,
- autonomous_config: Option<pa_core::autonomous::AgentAutonomousConfig>,
- /// Session-scoped MCP servers live on the connection, exactly like the
- /// TS process-lifetime manager: one owner id fences them and
- /// `session/close` releases. Shared with the engine's prompt gating.
- mcp: Arc<std::sync::Mutex<pa_core::mcp::McpManager>>,
- mcp_owner_id: Arc<String>,
- mcp_server_names: Arc<Mutex<Vec<String>>>,
-}
-
-impl AcpModeState {
- /// The session's current model (the live slot the picker switch
- /// updates).
- async fn current_model(&self) -> Option<pa_types::ai::Model> {
- self.model.lock().await.clone()
- }
-
- /// The session's current request key (the live slot the picker switch
- /// updates).
- pub(super) async fn current_api_key(&self) -> Option<String> {
- self.api_key.lock().await.clone()
- }
-
- /// The session's model and request key read as ONE pair through the
- /// serialized config queue: a picker model switch holds the same
- /// queue while it swaps the slots, so a boundary arm or a
- /// session-command executor cannot authenticate with the pre-switch
- /// model and the switched provider's key (a torn pair).
- pub(super) async fn model_and_api_key(&self) -> (Option<pa_types::ai::Model>, Option<String>) {
- let _guard = self.config_queue.lock().await;
- (
- self.model.lock().await.clone(),
- self.api_key.lock().await.clone(),
- )
- }
-}
-
-/// One hosted session and its in-flight prompt turn, if any.
-struct SessionEntry {
- session: Arc<AcpSession>,
- prompt_task: Option<tokio::task::JoinHandle<()>>,
- /// The picker state (TS `AcpSessionEntry`'s configOptions/models).
- config: Arc<InProcessConfig>,
- /// The agent-end refresh subscription (unsubscribed at close so a
- /// closed session stops refreshing — the listener would otherwise
- /// outlive the session and pin its state).
- config_refresh: Option<pa_agent::agent::Subscription>,
-}
-
-/// Run the ACP stdio mode until stdin closes. Returns the process exit code.
-///
-/// # Errors
-///
-/// Never errors: parse failures answer on stdout and stdin close settles
-/// the loop (the `Result` return keeps the stdio entry points uniform).
-pub async fn run_acp_mode(options: AcpOptions) -> Result<i32> {
- let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Value>();
- let writer = tokio::spawn(async move {
- let mut stdout = tokio::io::stdout();
- while let Some(frame) = rx.recv().await {
- let Ok(mut line) = serde_json::to_string(&frame) else {
- continue;
- };
- line.push('\n');
- if stdout.write_all(line.as_bytes()).await.is_err() {
- break;
- }
- if stdout.flush().await.is_err() {
- break;
- }
- }
- });
-
- let state = Arc::new(Mutex::new(ConnectionState::default()));
- let mode = AcpModeState {
- engine: options.engine.clone(),
- actual_cwd: Arc::new(options.actual_cwd.clone()),
- product_version: Arc::new(options.product_version.clone()),
- model: Arc::new(Mutex::new(options.model.clone())),
- api_key: Arc::new(Mutex::new(options.api_key.clone())),
- config_queue: Arc::new(tokio::sync::Mutex::new(())),
- agent_dir: Arc::new(options.agent_dir.clone()),
- provider_target: options.provider_target.clone(),
- autonomous_config: options.autonomous_config.clone(),
- // One MCP store with the engine's prompt gating (the core engine
- // builds it at session assembly): admitted servers reach the model
- // through the same manager the kernel `mcp.*` handlers resolve.
- mcp: options.engine.mcp_manager.clone(),
- mcp_owner_id: Arc::new(uuid::Uuid::new_v4().to_string()),
- mcp_server_names: Arc::new(Mutex::new(Vec::new())),
- };
- let mut stdin = BufReader::new(tokio::io::stdin());
- let mut line = String::new();
- loop {
- line.clear();
- match stdin.read_line(&mut line).await {
- Ok(0) | Err(_) => break,
- Ok(_) => {}
- }
- if line.trim().is_empty() {
- continue;
- }
- let request = match jsonrpc::parse_line(&line) {
- Ok(incoming) => incoming,
- Err(error_response) => {
- let _ = tx.send(error_response);
- continue;
- }
- };
- let handler = spawn_handler(request, state.clone(), mode.clone(), tx.clone());
- handler.await.ok();
- }
-
- // Exit when the client disconnects: stop the resident work, release the
- // subscription, fence the producer, and let the writer drain.
- teardown(&state, &mode).await;
- drop(tx);
- let _ = writer.await;
- Ok(0)
-}
-
-/// Stop the hosted session after stdin closes: abort work, settle the prompt
-/// task, release the subscription, and fence the producer.
-async fn teardown(state: &Arc<Mutex<ConnectionState>>, mode: &AcpModeState) {
- let entry = {
- let mut state = state.lock().await;
- state.session.take()
- };
- let Some(mut entry) = entry else {
- return;
- };
- entry.session.abort_auto_compaction();
- entry.session.agent().abort();
- entry.session.agent().clear_all_queues();
- entry.session.agent().wait_for_idle().await;
- if let Some(task) = entry.prompt_task.take() {
- let _ = task.await;
- }
- // The refresh listener goes away with the session, then the
- // serialized config work settles before the producer fences.
- if let Some(subscription) = entry.config_refresh.take() {
- subscription.unsubscribe().await;
- }
- let _ = mode.config_queue.lock().await;
- // The serialized dispose drain (TS `dispose`): a compaction can arm
- // the compact-trigger review with no further turn to service it —
- // close runs the round one last time, best-effort, before the
- // subscription tears down.
- entry.session.drain_compact_auto_refine_at_close(mode).await;
- entry.session.unsubscribe().await;
- entry.session.close_producer().await;
-}
-
-#[allow(clippy::too_many_arguments)]
-fn spawn_handler(
- request: Incoming,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) -> tokio::task::JoinHandle<()> {
- tokio::spawn(async move {
- match request {
- Incoming::Request { id, method, params } => {
- handle_request(id, method, params, state, mode, tx).await;
- }
- Incoming::Notification { method, params } => {
- handle_notification(method, params, state).await;
- }
- }
- })
-}
-
-#[allow(clippy::too_many_arguments)]
-async fn handle_request(
- id: Value,
- method: String,
- params: Value,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) {
- match method.as_str() {
- "initialize" => handle_initialize(&id, &params, &mode.product_version, &tx),
- "session/new" => {
- handle_session_new(id, params, state, mode, tx).await;
- }
- "session/prompt" => {
- prompt::handle_session_prompt(id, params, state, mode, tx).await;
- }
- "session/set_config_option" => {
- in_process_config::handle_set_config_option(id, params, state, mode, tx).await;
- }
- "session/close" => {
- handle_session_close(id, params, state, mode, tx).await;
- }
- other => {
- let _ = tx.send(jsonrpc::error_response(
- &id,
- jsonrpc::METHOD_NOT_FOUND,
- &format!("\"Method not found\": {other}"),
- Some(&json!({ "method": other })),
- ));
- }
- }
-}
-
-fn handle_initialize(id: &Value, params: &Value, product_version: &str, tx: &producer::FrameSink) {
- if let Err(error_response) = validate_initialize(id, params) {
- let _ = tx.send(error_response);
- return;
- }
- let result = serde_json::to_value(initialize_result(product_version)).expect("serializes");
- let _ = tx.send(jsonrpc::response(id, &result));
-}
-
-/// The `initialize` schema check the TS SDK performs: the protocol version
-/// must be a number. The error body mirrors the observed TS response.
-fn validate_initialize(id: &Value, params: &Value) -> std::result::Result<(), Value> {
- let field_error = |received: &str| {
- jsonrpc::error_response(
- id,
- jsonrpc::INVALID_PARAMS,
- "Invalid params",
- Some(&json!({
- "_errors": [],
- "protocolVersion": {
- "_errors": [format!("Invalid input: expected number, received {received}")]
- },
- })),
- )
- };
- match params.get("protocolVersion") {
- None => Err(field_error("undefined")),
- Some(value) if value.is_number() => Ok(()),
- Some(Value::String(_)) => Err(field_error("string")),
- Some(Value::Bool(_)) => Err(field_error("boolean")),
- Some(Value::Null) => Err(field_error("null")),
- Some(_) => Err(field_error("object")),
- }
-}
-
-async fn handle_notification(method: String, params: Value, state: Arc<Mutex<ConnectionState>>) {
- if method != "session/cancel" {
- return;
- }
- let session_id = session_id_params(&params);
- // Only cancel the addressed session: aborting unconditionally would kill
- // whichever turn happens to be running, and leave the real turn's stop
- // reason wrong.
- let session = {
- let state = state.lock().await;
- let Some(entry) = state
- .session
- .as_ref()
- .filter(|entry| entry.session.id == session_id && entry.prompt_task.is_some())
- else {
- return;
- };
- if entry.session.cancel_requested() {
- return;
- }
- entry.session.clone()
- };
- session.request_cancel();
- // TS `requestAbort` aborts the in-flight auto-compaction too, not
- // just the agent loop: an arm summarizer must not outlive the turn
- // it was cancelling.
- session.abort_auto_compaction();
- session.agent().abort();
- session.agent().clear_all_queues();
-}
-
-#[allow(clippy::too_many_arguments)]
-async fn handle_session_new(
- id: Value,
- params: Value,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) {
- // Reserve the single-session slot before the first await: two
- // concurrent requests must not both pass the empty-slot check while
- // cwd reads are in flight.
- {
- let mut state = state.lock().await;
- if state.session.is_some() || state.session_new_in_flight || state.session_close_in_flight {
- let _ = tx.send(internal_error(
- &id,
- "prime-agent ACP mode hosts one session per connection; start another prime-agent process for a second session",
- ));
- return;
- }
- state.session_new_in_flight = true;
- }
-
- let result = session_new(&id, params, &mode, tx.clone()).await;
- match result {
- // An admission failure has already queued its own error response;
- // only the in-flight flag is left to clear.
- Err(()) => {
- let mut state = state.lock().await;
- state.session_new_in_flight = false;
- }
- Ok((entry, result)) => {
- // Install the session before the admission response leaves: a
- // client that immediately sends `session/set_config_option`
- // must resolve against the installed session, not "Unknown
- // ACP session" (TS assigns `session = entry` before returning
- // the response). The producer gate opens only after the
- // response is queued on the sink, so no held update can
- // precede the admission response.
- let producer = Arc::clone(entry.session.producer());
- let mut state = state.lock().await;
- state.session_new_in_flight = false;
- state.session = Some(entry);
- drop(state);
- let _ = tx.send(jsonrpc::response(&id, &result));
- producer.commit_session_new_response().await;
- }
- }
-}
-
-/// Admit one session. On failure the error response has already been
-/// queued; on success the admission response is returned UNSENT: the
-/// caller installs the entry, queues the response, then opens the
-/// producer gate, in that order.
-async fn session_new(
- id: &Value,
- params: Value,
- mode: &AcpModeState,
- tx: producer::FrameSink,
-) -> std::result::Result<(SessionEntry, Value), ()> {
- let params = NewSessionParams::parse(&params);
- // MCP admission precedes everything else in the session identity: a
- // rejected server list fails the request with the raw error payload.
- // The zod-shaped filter drops schema-invalid entries silently (SDK
- // `vecSkipError`); validation errors are `invalid params` with a
- // `reason`, admission failures internal errors with `details`.
- if let Err(mut response) = mcp::admit_session_servers(&params.mcp_servers, mode).await {
- if let Value::Object(_) = &response {
- if let Some(id_slot) = response.get_mut("id") {
- *id_slot = id.clone();
- }
- }
- let _ = tx.send(response);
- return Err(());
- }
- // The agent's cwd is fixed at startup; a client-supplied cwd is reported
- // back in `_meta` when it differs, never adopted.
- let mut cwd_mismatch = None;
- if let Some(requested) = params.cwd.as_deref().filter(|cwd| !cwd.is_empty()) {
- if !same_cwd(Path::new(requested), &mode.actual_cwd) {
- cwd_mismatch = Some(meta::PrimeAgentCwdMeta {
- requested: requested.to_string(),
- actual: mode.actual_cwd.display().to_string(),
- });
- }
- }
-
- // The session's picker state: discovery and the initial options must
- // not block admission (TS `entry.models = []` on a discovery failure).
- let config = admit_session_config(mode).await;
-
- let session_id = uuid::Uuid::new_v4().to_string();
- let producer = UpdateProducer::new(session_id.clone(), tx.clone());
- // Autonomous state is session-scoped, like the TS session it backs.
- let autonomous = Arc::new(tokio::sync::Mutex::new(create_autonomous_runtime_state(
- mode.autonomous_config.as_ref(),
- None,
- )));
- let driver: Arc<dyn pa_core::autonomous::AutonomousDriver> = Arc::new(
- pa_core::autonomous::ShellAutonomousDriver::new(mode.actual_cwd.as_path()),
- );
- let session = Arc::new(
- AcpSession::new(
- session_id.clone(),
- mode.engine.clone(),
- producer.clone(),
- autonomous,
- driver,
- )
- .await,
- );
- // The engine subscription refreshes the pickers at the end of every
- // agent run (the TS `agent_end` trigger), through the same serialized
- // queue as the request handler. The subscription is retained on the
- // entry so close removes it (a listener that outlives the session
- // keeps refreshing it).
- let config_refresh =
- in_process_config::wire_config_refresh(&session, Arc::clone(&config), mode.clone()).await;
-
- let mut result = json!({
- "sessionId": session_id,
- "configOptions": *config.published.lock().await,
- });
- if let Some(cwd_mismatch) = cwd_mismatch {
- result["_meta"] = meta::prime_agent_meta(&PrimeAgentSessionMeta {
- cwd: Some(cwd_mismatch),
- ..Default::default()
- });
- }
- Ok((
- SessionEntry {
- session,
- prompt_task: None,
- config,
- config_refresh: Some(config_refresh),
- },
- result,
- ))
-}
-
-async fn handle_session_close(
- id: Value,
- params: Value,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) {
- let session_id = session_id_params(&params);
- // Stop real work, not just local bookkeeping: closing aborts the
- // connection the same way session/cancel does.
- let taken = {
- let mut state = state.lock().await;
- if state.session_close_in_flight {
- None
- } else {
- match state.session.take() {
- Some(entry) if entry.session.id == session_id => {
- state.session_close_in_flight = true;
- Some(entry)
- }
- _ => {
- let _ = tx.send(internal_error(
- &id,
- &format!("Unknown ACP session: {session_id}"),
- ));
- return;
- }
- }
- }
- };
- let Some(mut entry) = taken else {
- let _ = tx.send(internal_error(
- &id,
- &format!("ACP session is already closing: {session_id}"),
- ));
- return;
- };
- entry.session.abort_auto_compaction();
- entry.session.agent().abort();
- entry.session.agent().clear_all_queues();
- entry.session.agent().wait_for_idle().await;
- // The cancelled prompt resolves before the close response: the turn task
- // is awaited first and its frames already sit in the write queue.
- if let Some(task) = entry.prompt_task.take() {
- let _ = task.await;
- }
- // The refresh listener goes away with the session (no later agent
- // run refreshes a closed session), then the serialized config work
- // settles before the producer fences (TS `await configTask` in
- // `session/close`).
- if let Some(subscription) = entry.config_refresh.take() {
- subscription.unsubscribe().await;
- }
- let _ = mode.config_queue.lock().await;
- // The serialized dispose drain (TS `dispose`): a compaction can arm
- // the compact-trigger review with no further turn to service it —
- // close runs the round one last time, best-effort, before the
- // subscription tears down.
- entry
- .session
- .drain_compact_auto_refine_at_close(&mode)
- .await;
- entry.session.unsubscribe().await;
- // Keep the backing session fenced until a replacement ACP session is
- // admitted.
- entry.session.close_producer().await;
- mcp::release_session_servers(&mode).await;
- let _ = tx.send(jsonrpc::response(&id, &json!({})));
- let mut state = state.lock().await;
- state.session_close_in_flight = false;
-}
-
-/// The `session/prompt` success response: the terminal stop reason.
-fn stop_reason_response(stop_reason: AcpStopReason) -> Value {
- serde_json::to_value(AcpStopReasonResponse { stop_reason }).expect("serializes")
-}
fn internal_error(id: &Value, details: &str) -> Value {
jsonrpc::error_response(
@@ -602,12 +23,6 @@ fn internal_error(id: &Value, details: &str) -> Value {
)
}
-/// The internal-error response with a null id, for handlers that apply the
-/// request id after an async admission decision.
-pub(super) fn internal_error_value(details: &str) -> Value {
- internal_error(&Value::Null, details)
-}
-
/// Two paths are the same cwd when their canonical forms match, or when they
/// are the same directory on disk (dev/inode) — the bind-mount and
/// case-normalized-FS cases a lexical comparison misses.
diff --git a/crates/pa-daemon/src/acp/prompt.rs b/crates/pa-daemon/src/acp/prompt.rs
deleted file mode 100644
index 7a8a6bfca3..0000000000
--- a/crates/pa-daemon/src/acp/prompt.rs
+++ /dev/null
@@ -1,686 +0,0 @@
-//! The prompt turn: admission, session-command execution, the autonomous
-//! continuation loop, and the correlated settlement in front of the
-//! response. One prompt turn at a time; the turn runs as its own task so
-//! the reader loop can keep serving session/cancel and session/close.
-
-use std::sync::Arc;
-
-use serde_json::Value;
-use tokio::sync::Mutex;
-
-use pa_core::autonomous::{AgentAutonomousStatus, AutonomousFollowUp, AutonomousStopReason};
-use pa_core::session_engine::session_commands::execute_session_command;
-use pa_core::session_engine::session_commands::SessionCommandParams;
-use pa_core::session_engine::{PromptOptions, PromptOutcome, StreamingBehavior};
-
-use super::compaction_arms::{CompactionCheckRun, ThresholdGoalQueue};
-use super::goal_continuation;
-use super::internal_error;
-use super::meta::{self, PrimeAgentAutonomousMeta, PrimeAgentEventPhase, PrimeAgentOutcome};
-use super::session::{self, AcpSession, TurnBoundary};
-use super::stop_reason_response;
-use super::types::PromptParams;
-use super::{events, jsonrpc, producer, AcpModeState, AcpStopReason, ConnectionState};
-
-/// The `_meta.autonomous` accounting for a completion update: shared with
-/// the daemon-attached settlement (meta.rs).
-fn autonomous_meta(status: &AgentAutonomousStatus) -> PrimeAgentAutonomousMeta {
- meta::autonomous_meta(status)
-}
-
-pub(super) async fn handle_session_prompt(
- id: Value,
- params: Value,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) {
- let params = PromptParams::parse(&params);
- // Admission: one prompt turn at a time, behind any started cancellation.
- let (session, turn_id) = {
- let mut state = state.lock().await;
- let closing = state.session_close_in_flight;
- let Some(entry) = state.session.as_mut() else {
- let _ = tx.send(internal_error(
- &id,
- &format!("Unknown ACP session: {}", params.session_id),
- ));
- return;
- };
- if closing {
- let _ = tx.send(internal_error(
- &id,
- &format!("ACP session is closing: {}", params.session_id),
- ));
- return;
- }
- if entry.prompt_task.is_some() {
- let _ = tx.send(internal_error(
- &id,
- "A prompt turn is already running for this ACP session",
- ));
- return;
- }
- let turn_id = entry.session.producer().begin_prompt().await;
- (entry.session.clone(), turn_id)
- };
- if session.cancel_requested() {
- // This prompt was admitted after a cancellation started; it is
- // dropped by the cancel, so report the protocol stop reason instead
- // of a request error.
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(jsonrpc::response(
- &id,
- &stop_reason_response(AcpStopReason::Cancelled),
- ));
- return;
- }
-
- let admitted_prompt = match session::AdmittedPrompt::parse(&params.prompt) {
- Ok(prompt) => prompt,
- Err(error) => {
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(session::prompt_block_error(&id, &error));
- return;
- }
- };
-
- // The turn runs as its own task so the reader loop can keep serving
- // session/cancel and session/close while it settles.
- let task = tokio::spawn(run_prompt_turn(
- id,
- params.session_id.clone(),
- turn_id,
- admitted_prompt,
- session,
- state.clone(),
- mode,
- tx.clone(),
- ));
- let mut state = state.lock().await;
- if let Some(entry) = state.session.as_mut() {
- if entry.session.id == params.session_id {
- entry.prompt_task = Some(task);
- }
- }
-}
-
-/// One prompt turn: admission into the engine (a model turn or a session
-/// command), the autonomous continuation loop, and the correlated boundary /
-/// completion envelope in front of the response.
-#[allow(clippy::too_many_arguments)]
-async fn run_prompt_turn(
- id: Value,
- session_id: String,
- turn_id: u64,
- admitted_prompt: session::AdmittedPrompt,
- session: Arc<AcpSession>,
- state: Arc<Mutex<ConnectionState>>,
- mode: AcpModeState,
- tx: producer::FrameSink,
-) {
- let boundary = TurnBoundary::capture(mode.engine.session.agent()).await;
- // The pre-turn compaction arms (TS `_runPreTurnCompaction`,
- // `beforeModelSelection`): a stale overflow from the previous run
- // recovers on the newly admitted prompt, then a threshold crossing
- // compacts before the turn runs. Session commands never reach the
- // prompt commit in TS, so they never fire the arms; a busy agent
- // queues the prompt below without a session-level boundary (the
- // settled-turn check after the drain covers the turn).
- if mode
- .engine
- .session
- .classify_session_command(&admitted_prompt.text)
- .is_none()
- {
- let busy = mode.engine.session.agent().state().await.is_streaming;
- if !busy {
- session.run_pre_turn_compaction(&mode).await;
- }
- }
- let admission = mode
- .engine
- .session
- .prompt_with_images(
- &admitted_prompt.text,
- admitted_prompt
- .images
- .into_iter()
- .map(|image| pa_agent::types::ImageContent {
- data: image.data,
- mime_type: image.mime_type,
- })
- .collect(),
- PromptOptions {
- streaming_behavior: Some(StreamingBehavior::FollowUp),
- queue_if_busy: true,
- ..Default::default()
- },
- )
- .await;
-
- // The settled-turn outcome: the failure text (a failed turn errors the
- // request), the autonomous stop, and whether the turn ran at all.
- let mut turn_failure: Option<String> = None;
- let mut autonomous_stop: Option<(
- pa_core::autonomous::AutonomousStopReason,
- Box<AgentAutonomousStatus>,
- )> = None;
- let ran_model_turn;
-
- match admission {
- // Session commands (compact/refine/goal/autonomous) never admit a
- // model turn: the durable echo row replaces the user row. Execute
- // them and publish their namespaced events.
- Ok(PromptOutcome::SessionCommand(command)) => {
- match run_session_command_segment(&mode, &session, &command, &mut turn_failure).await {
- Ok(ran) => ran_model_turn = ran,
- Err(error) => {
- // Command execution could not start (no resolved model):
- // an admission-style error boundary, never an invented
- // terminal-quiescence update.
- let _ = session::publish_response_boundary(
- &session,
- turn_id,
- false,
- PrimeAgentOutcome::Error,
- )
- .await;
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(internal_error(&id, &format!("{error:#}")));
- clear_prompt_slot(&state, &session_id).await;
- return;
- }
- }
- }
- Ok(PromptOutcome::Prompt) => {
- ran_model_turn = true;
- }
- Err(error) => {
- // Failed prompt admission gets one correlated error boundary; it
- // never gets an invented terminal-quiescence update.
- let _ = session::publish_response_boundary(
- &session,
- turn_id,
- false,
- PrimeAgentOutcome::Error,
- )
- .await;
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(internal_error(&id, &format!("{error:#}")));
- clear_prompt_slot(&state, &session_id).await;
- return;
- }
- }
-
- if ran_model_turn {
- mode.engine.session.agent().wait_for_idle().await;
- }
-
- // The turn-settlement loop: classify each settled turn, run the
- // automatic compaction arms at its boundary (TS `_checkCompaction` at
- // `agent_end`), consume the requested refinement (TS
- // `_consumePendingRequestedRefine`), then ask the autonomous driver
- // what follows. A continuation runs as the next turn of the same
- // prompt, so every boundary in the run hosts its arms.
- loop {
- if session.cancel_requested() || !ran_model_turn {
- break;
- }
- let Some(final_message) =
- session::latest_assistant_message(mode.engine.session.agent()).await
- else {
- break;
- };
- // The newest assistant predates the turn: the turn appended
- // none, so there is nothing to classify.
- if boundary.contains_wire(&final_message) {
- break;
- }
- // An aborted turn never services its boundary requests (TS
- // `_checkCompaction`'s abort arm): drop the pending compaction
- // and refine requests, reset the overflow machine, and settle.
- if final_message.stop_reason == pa_types::ai::StopReason::Aborted {
- session.reset_overflow_recovery();
- session.clear_turn_boundary_requests(&mode.engine).await;
- break;
- }
- // A settled non-error assistant message resets the overflow
- // machine (TS resets `_overflowRecovery` at every non-error
- // assistant `message_end`) and counts into the auto-refine
- // review prompt's turn line (TS `_assistantTurnsSinceAutoRefine`'s
- // message_end increment), then the boundary check runs.
- if final_message.stop_reason != pa_types::ai::StopReason::Error {
- session.reset_overflow_recovery();
- mode.engine
- .session
- .note_settled_turn_since_auto_refine_review();
- }
- // TS `_checkCompaction` at `agent_end`: the overflow arm (Case 1,
- // with its compact-and-retry), then the requested arm (which
- // stops the run on purpose), then the threshold arm (which, under
- // the settled boundary's queue policy, mints the goal continuation
- // before it compacts — the held turn runs after the boundary like
- // the TS post-compaction continue).
- let (check, threshold_continuation) = session
- .check_compaction(&mode, &final_message, ThresholdGoalQueue::Queue)
- .await;
- if session.cancel_requested() {
- if threshold_continuation.is_some() {
- // A cancellation between the mint and the run withdraws
- // the queued continuation (the TS cancel clears the
- // queue and rolls the slot back).
- goal_continuation::rollback_goal_mint(&mode).await;
- }
- break;
- }
- if check == CompactionCheckRun::OverflowRetry {
- // The compacted context re-issues the turn without a new
- // user message (TS `agent.continue()`); the settled retry
- // re-enters this loop through its own boundary.
- if let Err(error) = mode.engine.session.agent().continue_run().await {
- turn_failure = Some(format!("{error:#}"));
- break;
- }
- mode.engine.session.agent().wait_for_idle().await;
- continue;
- }
- // TS consumes the requested refinement whenever the compaction
- // check did not report a will-retry (`_consumePendingRequestedRefine`
- // at `agent_end`), then the serialized checkpoint's compact step
- // services an armed compact-trigger review (autorefine.rs). The
- // compact-trigger round defers behind a held goal continuation
- // (TS `_scheduleAutoRefineAfterCompaction(willContinue)`): the
- // continuation turn's own boundary services it.
- session.consume_requested_refine(&mode).await;
- if threshold_continuation.is_none() {
- session.consume_compact_auto_refine(&mode).await;
- }
- // A failed turn ends the run with its error once the boundary
- // check could not save it (an overflow recovery that re-issued
- // handled it above).
- if final_message.stop_reason == pa_types::ai::StopReason::Error {
- // TS `_finishGoalForTerminalAssistantMessage` at `agent_end`:
- // the failed turn fails an active goal (the state change
- // publishes before the response settles).
- goal_continuation::fail_goal_for_terminal_error(
- &mode,
- &session,
- final_message.error_message.as_deref(),
- )
- .await;
- turn_failure = Some(
- final_message
- .error_message
- .clone()
- .unwrap_or_else(|| "the model request failed".to_string()),
- );
- break;
- }
- // A requested compaction stops the run on purpose: the model
- // resumes on the next prompt.
- if check == CompactionCheckRun::RequestedStop {
- break;
- }
- // The threshold arm's held goal continuation runs as the
- // post-compaction turn (TS `_schedulePostCompactionContinue` over
- // the queued follow-up): the pre-turn compaction arms run before
- // it like any admitted prompt, and its own settled boundary
- // re-enters this loop.
- if let Some(message) = threshold_continuation {
- session.run_pre_turn_compaction(&mode).await;
- if let Err(error) = mode.engine.session.prompt_injected_message(&message).await {
- turn_failure = Some(format!("{error:#}"));
- break;
- }
- mode.engine.session.agent().wait_for_idle().await;
- continue;
- }
- if session.cancel_requested() {
- break;
- }
- // TS `_getContinuationMessages` at the agent loop's natural turn
- // end: the goal arm runs before the autonomous arm with exclusive
- // priority — the budget-limit wrap-up steer first (the turn that
- // crossed the goal budget), then the natural continuation mint
- // (an active goal mints one continuation per settled boundary).
- // A minted turn runs as the next turn of the same prompt (the
- // pre-turn compaction arms run before it like any admitted
- // prompt); no active goal falls through to the autonomous arm.
- match goal_continuation::goal_follow_up(&mode, &session).await {
- goal_continuation::GoalFollowUp::Turn(message) => {
- let message = *message;
- session.run_pre_turn_compaction(&mode).await;
- if let Err(error) = mode.engine.session.prompt_injected_message(&message).await {
- turn_failure = Some(format!("{error:#}"));
- break;
- }
- mode.engine.session.agent().wait_for_idle().await;
- }
- goal_continuation::GoalFollowUp::None => {
- match session.autonomous_follow_up(&final_message).await {
- AutonomousFollowUp::Inactive => break,
- AutonomousFollowUp::Continue { text } => {
- // An injected continuation runs as the next turn
- // of the same prompt (a fresh user row: the
- // pre-turn compaction arms run before it, like
- // any admitted prompt); its failure settles the
- // prompt.
- session.run_pre_turn_compaction(&mode).await;
- if let Err(error) = mode
- .engine
- .session
- .prompt(
- &text,
- PromptOptions {
- streaming_behavior: Some(StreamingBehavior::FollowUp),
- queue_if_busy: true,
- ..Default::default()
- },
- )
- .await
- {
- turn_failure = Some(format!("{error:#}"));
- break;
- }
- mode.engine.session.agent().wait_for_idle().await;
- }
- AutonomousFollowUp::Stop { reason, status } => {
- // The stop writes no row (the TS shape): the stop
- // reason and status ride the completion update and
- // the response's stop reason.
- autonomous_stop = Some((reason, status));
- break;
- }
- }
- }
- }
- }
-
- settle_turn(
- &state,
- &session,
- &id,
- &session_id,
- turn_id,
- turn_failure,
- autonomous_stop,
- tx,
- )
- .await;
-}
-
-/// Execute one session command and publish its namespaced events:
-/// compaction and refinement outcomes, plus any goal state change. A goal
-/// start/resume schedules its continuation context as the turn's model
-/// segment after the command settles.
-async fn run_session_command_segment(
- mode: &AcpModeState,
- session: &Arc<AcpSession>,
- command: &pa_core::session_engine::slash_commands::SessionSlashCommand,
- turn_failure: &mut Option<String>,
-) -> anyhow::Result<bool> {
- // The command executor runs on one model/key pair read through the
- // config queue: a concurrent picker switch cannot hand `/compact`
- // or `/refine` the pre-switch model with the switched provider's
- // key.
- let (model, api_key) = mode.model_and_api_key().await;
- let Some(model) = model else {
- // Unreachable in practice (the engine assembly requires a model);
- // fail as a request error instead of a turn failure.
- anyhow::bail!("No model available to run the session command");
- };
- // The autonomous guard scopes tightly around the executor call: a
- // scheduled continuation prompts the model below, and the event
- // listener's per-message accounting must be able to take the same
- // mutex while that turn runs.
- let execution = {
- let mut autonomous = session.autonomous.lock().await;
- let mut params = SessionCommandParams {
- model: &model,
- api_key,
- global_harness_dir: mode.agent_dir.as_path().to_path_buf(),
- autonomous: &mut autonomous,
- };
- execute_session_command(&mode.engine, &mut params, command).await
- };
-
- // A compaction publishes its namespaced event whether it ran (result
- // fields present) or skipped (the TS compaction_end with an undefined
- // result): the skip is observable, not silent.
- let compaction_event = if command.name == "compact" {
- Some(match &execution.compaction {
- Some(compaction) => events::AcpEngineEvent::CompactionEnd {
- tokens_before: Some(compaction.result.tokens_before),
- summary: Some(compaction.result.summary.clone()),
- },
- None => events::AcpEngineEvent::CompactionEnd {
- tokens_before: None,
- summary: None,
- },
- })
- } else {
- None
- };
- if let Some(event) = compaction_event {
- publish_engine_event(session, &event).await;
- }
- // TS `compact()` schedules the compact-trigger auto-refine review
- // after every successful compaction: a session command never runs a
- // turn, so the armed trigger waits for the next serialized checkpoint
- // or the session-close drain (autorefine.rs).
- if command.name == "compact" && execution.compaction.is_some() {
- mode.engine.session.mark_compact_auto_refine_pending();
- // TS `compact()`'s `didCompact` + active-goal finally arm: a
- // successful manual compact with an active goal mints the owed
- // continuation (the `||= !hasQueuedMessages()` arm — the direct
- // ACP never queues work behind a session command) and the
- // continuation runs as the turn's model segment, the scheduled
- // continue over the queued follow-up. The compact-trigger review
- // defers behind it (the continuation turn's boundary services
- // it, like the goal-start segment below).
- if let Some(message) = goal_continuation::mint_goal_continuation(mode, session).await {
- return run_goal_continuation_segment(mode, session, message, turn_failure).await;
- }
- }
-
- // Refinement outcomes publish complete/failed events; option-parse
- // failures are command failures without a refinement event.
- if let Some(result) = &execution.refinement {
- publish_engine_event(
- session,
- &events::AcpEngineEvent::RefineComplete {
- summary: result.summary.clone(),
- changes: result
- .applied_edits
- .iter()
- .filter(|edit| edit.applied)
- .map(|edit| {
- let action = serde_json::to_value(edit.action)
- .ok()
- .and_then(|value| value.as_str().map(str::to_string))
- .unwrap_or_default();
- let kind = serde_json::to_value(edit.kind)
- .ok()
- .and_then(|value| value.as_str().map(str::to_string))
- .unwrap_or_default();
- format!("{action} {kind}:{}", edit.id)
- })
- .collect(),
- },
- )
- .await;
- }
- if let Some(error) = &execution.refinement_failed {
- publish_engine_event(
- session,
- &events::AcpEngineEvent::RefineFailed {
- error: error.clone(),
- },
- )
- .await;
- }
-
- // Any goal state change (start/status/clear/pause/resume) publishes.
- session.publish_goal_update().await;
-
- // A scheduled goal continuation runs as the turn's model segment; its
- // settled turn participates in the settle loop like any model turn.
- if let Some(message) = execution.continuation_message {
- return run_goal_continuation_segment(mode, session, message, turn_failure).await;
- }
- Ok(false)
-}
-
-/// Run one goal-continuation segment (a goal-context row minted by the
-/// goal commands or the compact-with-active-goal continue) as the turn's
-/// model segment: the pre-turn compaction arms run before it like any
-/// admitted prompt (TS `_runPreTurnCompaction`), the injected custom row
-/// is the turn's one representation (TS's prepared-turn primary record),
-/// and the settled turn's boundary re-enters the settle loop.
-async fn run_goal_continuation_segment(
- mode: &AcpModeState,
- session: &Arc<AcpSession>,
- message: pa_types::session::CustomMessage,
- turn_failure: &mut Option<String>,
-) -> anyhow::Result<bool> {
- session.run_pre_turn_compaction(mode).await;
- if let Err(error) = mode.engine.session.prompt_injected_message(&message).await {
- *turn_failure = Some(format!("{error:#}"));
- return Ok(false);
- }
- mode.engine.session.agent().wait_for_idle().await;
- Ok(true)
-}
-
-/// Publish one adapter event through the session producer at the active
-/// turn.
-async fn publish_engine_event(session: &Arc<AcpSession>, event: &events::AcpEngineEvent) {
- let turn_id = session.producer().active_prompt_turn().await;
- let mut mapping = events::MappingState::default();
- let updates = events::acp_updates_for_event(event, &mut mapping);
- for update in updates {
- session
- .producer()
- .publish(&update, turn_id, PrimeAgentEventPhase::Event, None)
- .await;
- }
-}
-
-/// Settle one finished turn: the correlated boundary envelope, the response,
-/// and the slot bookkeeping. The autonomous status rides the completion
-/// update while a run is enabled, and the stop reason maps the driver's
-/// stop outcome (`max_tokens` for token exhaustion, `max_turn_requests`
-/// for every other limit, `end_turn` otherwise).
-#[allow(clippy::too_many_arguments)]
-async fn settle_turn(
- state: &Arc<Mutex<ConnectionState>>,
- session: &Arc<AcpSession>,
- id: &Value,
- session_id: &str,
- turn_id: u64,
- turn_failure: Option<String>,
- autonomous_stop: Option<(
- pa_core::autonomous::AutonomousStopReason,
- Box<AgentAutonomousStatus>,
- )>,
- tx: producer::FrameSink,
-) {
- if session.cancel_requested() {
- // A cancellation before the response boundary resolves the request
- // with the protocol stop reason and no boundary frames.
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(jsonrpc::response(
- id,
- &stop_reason_response(AcpStopReason::Cancelled),
- ));
- clear_prompt_slot(state, session_id).await;
- return;
- }
-
- let outcome = if turn_failure.is_some() {
- PrimeAgentOutcome::Error
- } else {
- PrimeAgentOutcome::Result
- };
- // The response boundary precedes the correlated response; the completion
- // event and terminal quiescence envelope follow it in publication order.
- if session::publish_response_boundary(session, turn_id, true, outcome)
- .await
- .is_err()
- {
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(internal_error(
- id,
- "Failed to publish ACP response boundary",
- ));
- clear_prompt_slot(state, session_id).await;
- return;
- }
-
- // The completion update carries the autonomous accounting while a run
- // is enabled (the stop status when the driver stopped the run, the live
- // snapshot otherwise).
- let autonomous_status = if let Some((_, status)) = &autonomous_stop {
- Some((**status).clone())
- } else {
- let status = session.autonomous_status().await;
- status.enabled.then_some(status)
- };
- let autonomous_meta = autonomous_status.as_ref().map(autonomous_meta);
- // The remaining continuation slots the quiescence observation reports:
- // the configured budget minus what the run consumed (zero when no
- // autonomous run is active).
- let remaining_continuations = autonomous_status.as_ref().map_or(0, |status| {
- status
- .limits
- .max_continuations
- .saturating_sub(status.continuations_used)
- });
- if session::publish_completion_envelope(
- session,
- turn_id,
- outcome,
- autonomous_meta.as_ref(),
- remaining_continuations,
- )
- .await
- .is_err()
- {
- session.producer().finish_prompt(turn_id).await;
- let _ = tx.send(internal_error(
- id,
- "Failed to publish ACP completion update",
- ));
- clear_prompt_slot(state, session_id).await;
- return;
- }
-
- session.producer().finish_prompt(turn_id).await;
- let stop_reason = match autonomous_stop.as_ref().map(|(reason, _)| reason) {
- None => AcpStopReason::EndTurn,
- Some(AutonomousStopReason::Limit(
- pa_core::autonomous::AutonomousLimitReason::MaxTokens,
- )) => AcpStopReason::MaxTokens,
- Some(AutonomousStopReason::Limit(_)) => AcpStopReason::MaxTurnRequests,
- Some(AutonomousStopReason::GatePassed | AutonomousStopReason::GateRetryExhausted) => {
- AcpStopReason::EndTurn
- }
- };
- let response = match turn_failure {
- Some(failure) => internal_error(id, &format!("prime-agent turn failed: {failure}")),
- None => jsonrpc::response(id, &stop_reason_response(stop_reason)),
- };
- let _ = tx.send(response);
- clear_prompt_slot(state, session_id).await;
-}
-
-/// The running turn released the prompt slot; close/EOF no longer awaits it.
-async fn clear_prompt_slot(state: &Arc<Mutex<ConnectionState>>, session_id: &str) {
- let mut state = state.lock().await;
- if let Some(entry) = state.session.as_mut() {
- if entry.session.id == session_id {
- entry.prompt_task = None;
- }
- }
-}
diff --git a/crates/pa-daemon/src/acp/session.rs b/crates/pa-daemon/src/acp/session.rs
deleted file mode 100644
index d0f82dc6cf..0000000000
--- a/crates/pa-daemon/src/acp/session.rs
+++ /dev/null
@@ -1,552 +0,0 @@
-//! The single-session ACP state machine: admission, prompt lifecycle,
-//! cancel, and close over the in-process session engine.
-//!
-//! One ACP connection drives one session. A second `session/new` is refused
-//! rather than silently sharing conversation state, cwd, and queues.
-
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Arc;
-
-use pa_agent::agent::{Agent, Subscription};
-use pa_agent::stream::AssistantMessageEvent;
-use pa_agent::types::{AgentEvent, AgentMessage, Message};
-use serde_json::{json, Value};
-use tokio::sync::Mutex;
-
-use super::compaction_arms::CompactionArms;
-use super::events::{acp_updates_for_event, AcpEngineEvent, MappingState};
-use super::jsonrpc;
-use super::meta::{
- PrimeAgentAutonomousMeta, PrimeAgentEventPhase, PrimeAgentOutcome, PrimeAgentQuiescenceMeta,
- PrimeAgentSessionMeta,
-};
-use super::producer::UpdateProducer;
-use super::types::{parse_prompt_blocks, AcpSessionUpdate, ImageBlock, PromptBlockError};
-
-/// One hosted ACP session: the producer, the engine event subscription, the
-/// autonomous run state, and the prompt-lifecycle bookkeeping.
-pub struct AcpSession {
- pub id: String,
- producer: Arc<UpdateProducer>,
- subscription: Mutex<Option<Subscription>>,
- agent: Arc<Agent>,
- cancel_requested: AtomicBool,
- /// The autonomous run state (`/autonomous` flags and commands mutate it).
- pub autonomous: Arc<Mutex<pa_core::autonomous::AutonomousRuntimeState>>,
- /// The autonomous continuation policy (shell gates in the session cwd).
- autonomous_driver: Arc<dyn pa_core::autonomous::AutonomousDriver>,
- /// The engine handle for goal usage recording on settled messages.
- engine: Arc<pa_core::session_engine::engine::SessionEngine>,
- /// The last goal state published as `_meta.goal`, to detect changes.
- /// Shared with the event subscription so mid-turn changes publish too.
- last_published_goal: Arc<Mutex<pa_core::goals::GoalState>>,
- /// The automatic compaction arm state (the overflow recovery machine
- /// and the in-flight compaction abort slot), TS session-lifetime
- /// state. Shared with the arm implementation
- /// (`compaction_arms.rs`).
- pub(super) arms: Arc<CompactionArms>,
- /// Whether the latest turn's usage crossed the goal's token budget
- /// (the usage listener arms it on `BudgetReached`, the settle loop's
- /// goal boundary consumes it): TS `_shouldStopAfterTurn`'s budget arm.
- goal_budget_crossed: Arc<AtomicBool>,
-}
-
-impl AcpSession {
- /// Admit a session: subscribe the engine event feed (with the
- /// autonomous accounting and goal usage hooks) before anything can
- /// publish, so no update is lost between admission and the response.
- pub async fn new(
- id: String,
- engine: Arc<pa_core::session_engine::engine::SessionEngine>,
- producer: Arc<UpdateProducer>,
- autonomous: Arc<Mutex<pa_core::autonomous::AutonomousRuntimeState>>,
- autonomous_driver: Arc<dyn pa_core::autonomous::AutonomousDriver>,
- ) -> AcpSession {
- let mapping = Arc::new(Mutex::new(MappingState::default()));
- let last_published_goal =
- Arc::new(Mutex::new(engine.goal_driver.lock().await.state().clone()));
- // The compaction arm state is shared with the event subscription:
- // a user row that starts an agent run resets the overflow
- // recovery machine at its `message_start` (TS `startsAgentRun`).
- let arms = Arc::new(CompactionArms::new());
- let goal_budget_crossed = Arc::new(AtomicBool::new(false));
- let subscription = subscribe_engine_events(
- &engine,
- producer.clone(),
- mapping,
- autonomous.clone(),
- autonomous_driver.clone(),
- last_published_goal.clone(),
- arms.clone(),
- goal_budget_crossed.clone(),
- )
- .await;
- AcpSession {
- id,
- producer,
- subscription: Mutex::new(Some(subscription)),
- agent: engine.session.agent().clone(),
- cancel_requested: AtomicBool::new(false),
- autonomous,
- autonomous_driver,
- engine,
- last_published_goal,
- arms,
- goal_budget_crossed,
- }
- }
-
- /// Release the engine event subscription; no further updates flow.
- pub async fn unsubscribe(&self) {
- let subscription = self.subscription.lock().await.take();
- if let Some(subscription) = subscription {
- subscription.unsubscribe().await;
- }
- }
-
- /// Fence the producer (a closed session publishes nothing until a
- /// replacement `session/new` is admitted).
- pub async fn close_producer(&self) {
- self.producer.close().await;
- }
-
- pub fn cancel_requested(&self) -> bool {
- self.cancel_requested.load(Ordering::SeqCst)
- }
-
- pub fn request_cancel(&self) {
- self.cancel_requested.store(true, Ordering::SeqCst);
- }
-
- /// Consume the goal-budget crossing the latest turn's usage armed
- /// (the settle loop's budget-steer read; TS `_shouldStopAfterTurn`'s
- /// budget arm).
- pub fn take_goal_budget_crossed(&self) -> bool {
- self.goal_budget_crossed.swap(false, Ordering::SeqCst)
- }
-
- pub fn producer(&self) -> &Arc<UpdateProducer> {
- &self.producer
- }
-
- pub fn agent(&self) -> &Arc<Agent> {
- &self.agent
- }
-
- /// Consult the autonomous driver for one settled turn (gate evaluation
- /// runs inside the driver).
- pub async fn autonomous_follow_up(
- &self,
- message: &pa_types::ai::AssistantMessage,
- ) -> pa_core::autonomous::AutonomousFollowUp {
- let mut state = self.autonomous.lock().await;
- self.autonomous_driver.after_turn(&mut state, message).await
- }
-
- /// The current autonomous status snapshot (the completion envelope
- /// publishes it while a run is enabled).
- pub async fn autonomous_status(&self) -> pa_core::autonomous::AgentAutonomousStatus {
- let state = self.autonomous.lock().await;
- pa_core::autonomous::autonomous_status(&state)
- }
-
- /// Publish the current goal state as a `_meta.goal` update when it
- /// differs from the last one published on this connection.
- pub async fn publish_goal_update(&self) {
- let goal = self.engine.goal_driver.lock().await.state().clone();
- let changed = {
- let mut last = self.last_published_goal.lock().await;
- if *last == goal {
- return;
- }
- *last = goal.clone();
- true
- };
- if !changed {
- return;
- }
- self.publish_engine_event(&AcpEngineEvent::GoalUpdate {
- status: goal.status.slug().to_string(),
- objective: goal.objective.clone(),
- token_budget: goal.token_budget,
- tokens_used: Some(goal.tokens_used),
- })
- .await;
- }
-
- /// Publish one adapter event at the active turn (namespaced metas).
- pub async fn publish_engine_event(&self, event: &AcpEngineEvent) {
- let turn_id = self.producer.active_prompt_turn().await;
- let mut mapping = MappingState::default();
- let updates = acp_updates_for_event(event, &mut mapping);
- for update in updates {
- self.producer
- .publish(&update, turn_id, PrimeAgentEventPhase::Event, None)
- .await;
- }
- }
-}
-
-/// Map the engine loop events onto ACP updates for the session lifetime.
-///
-/// Message-end hooks mirror the TS session's `message_end` listeners:
-/// per-message autonomous usage accounting, and goal usage recording with a
-/// `_meta.goal` update whenever the goal state changes mid-turn.
-#[allow(clippy::too_many_arguments)]
-async fn subscribe_engine_events(
- engine: &Arc<pa_core::session_engine::engine::SessionEngine>,
- producer: Arc<UpdateProducer>,
- mapping: Arc<Mutex<MappingState>>,
- autonomous: Arc<Mutex<pa_core::autonomous::AutonomousRuntimeState>>,
- autonomous_driver: Arc<dyn pa_core::autonomous::AutonomousDriver>,
- last_published_goal: Arc<Mutex<pa_core::goals::GoalState>>,
- arms: Arc<CompactionArms>,
- goal_budget_crossed: Arc<AtomicBool>,
-) -> Subscription {
- let agent = engine.session.agent().clone();
- let goal_driver = engine.goal_driver.clone();
- let session = engine.session.shared_persistence();
- agent
- .subscribe(move |event, _signal| {
- let producer = producer.clone();
- let mapping = mapping.clone();
- let autonomous = autonomous.clone();
- let autonomous_driver = autonomous_driver.clone();
- let goal_driver = goal_driver.clone();
- let session = session.clone();
- let last_published_goal = last_published_goal.clone();
- let arms = arms.clone();
- let goal_budget_crossed = goal_budget_crossed.clone();
- Box::pin(async move {
- // A user row that starts an agent run resets the overflow
- // recovery machine (TS `startsAgentRun` at
- // `message_start`): the stale attempt state from the
- // previous run never suppresses a fresh overflow.
- if let AgentEvent::MessageStart {
- message: AgentMessage::Standard(Message::User(_)),
- } = &event
- {
- arms.reset();
- }
- let turn_id = producer.active_prompt_turn().await;
- let engine_events: Vec<AcpEngineEvent> = project_event(&event);
- for engine_event in engine_events {
- let updates = {
- let mut mapping = mapping.lock().await;
- acp_updates_for_event(&engine_event, &mut mapping)
- };
- for update in updates {
- producer
- .publish(&update, turn_id, PrimeAgentEventPhase::Event, None)
- .await;
- }
- }
- if let pa_agent::types::AgentEvent::MessageEnd {
- message:
- pa_agent::types::AgentMessage::Standard(pa_agent::types::Message::Assistant(
- assistant,
- )),
- } = &event
- {
- if let Some(wire) = serde_json::to_value(assistant).ok().and_then(|value| {
- serde_json::from_value::<pa_types::ai::AssistantMessage>(value).ok()
- }) {
- // Autonomous per-message accounting (non-error turns).
- {
- let mut state = autonomous.lock().await;
- autonomous_driver.account_message(&mut state, &wire);
- }
- // Goal usage recording mirrors the TS guard
- // (`_accountGoalUsageForAssistantMessage`): only
- // turns that were neither errors nor aborted spend
- // the goal's budget, and only while the goal is
- // active; a budget crossing moves the goal to
- // `budget_limited` (the state change publishes
- // below) and arms the settle loop's wrap-up steer.
- if !matches!(
- wire.stop_reason,
- pa_types::ai::StopReason::Error | pa_types::ai::StopReason::Aborted
- ) {
- let mut driver = goal_driver.lock().await;
- let mut persistence = session.lock().await;
- // Timestamp is the message identity for the
- // double-counting guard: the loop does not
- // assign message ids in-process.
- let message_id = format!("a-{}", wire.timestamp);
- // TS `_shouldStopAfterTurn`'s catch: goal
- // accounting must not interrupt the loop; a
- // failed persist only warns.
- match driver
- .record_assistant_usage(&mut persistence, &message_id, &wire.usage)
- {
- Ok(
- pa_core::session_engine::goal_driver::UsageOutcome::BudgetReached,
- ) => {
- goal_budget_crossed.store(true, Ordering::SeqCst);
- }
- Ok(_) => {}
- Err(error) => {
- eprintln!(
- "pa-daemon: goal usage accounting persist failed: {error:#}"
- );
- }
- }
- }
- }
- }
- // A goal state change (usage recorded, budget reached, or a
- // kernel-side complete) publishes a `_meta.goal` update.
- let goal_now = goal_driver.lock().await.state().clone();
- let changed = {
- let mut last = last_published_goal.lock().await;
- if *last == goal_now {
- false
- } else {
- *last = goal_now.clone();
- true
- }
- };
- if changed {
- let mut mapping = MappingState::default();
- let event = AcpEngineEvent::GoalUpdate {
- status: goal_now.status.slug().to_string(),
- objective: goal_now.objective.clone(),
- token_budget: goal_now.token_budget,
- tokens_used: Some(goal_now.tokens_used),
- };
- for update in acp_updates_for_event(&event, &mut mapping) {
- producer
- .publish(&update, turn_id, PrimeAgentEventPhase::Event, None)
- .await;
- }
- }
- Ok(())
- })
- })
- .await
-}
-
-/// Project one loop event onto the ACP adapter's input vocabulary. Streaming
-/// deltas carry a plain string; the discriminator (reasoning vs visible
-/// text) lives in the stream event variant.
-fn project_event(event: &AgentEvent) -> Vec<AcpEngineEvent> {
- match event {
- AgentEvent::MessageStart { message } => vec![AcpEngineEvent::MessageStart {
- role: message.role().to_string(),
- }],
- AgentEvent::MessageUpdate {
- assistant_message_event,
- ..
- } => match assistant_message_event.as_ref() {
- AssistantMessageEvent::TextDelta { delta, .. } if !delta.is_empty() => {
- vec![AcpEngineEvent::AssistantDelta {
- thinking: false,
- delta: delta.clone(),
- }]
- }
- AssistantMessageEvent::ThinkingDelta { delta, .. } if !delta.is_empty() => {
- vec![AcpEngineEvent::AssistantDelta {
- thinking: true,
- delta: delta.clone(),
- }]
- }
- _ => Vec::new(),
- },
- AgentEvent::MessageEnd { message } => vec![AcpEngineEvent::MessageEnd {
- role: message.role().to_string(),
- }],
- AgentEvent::ToolExecutionStart {
- tool_call_id,
- tool_name,
- args,
- } => vec![AcpEngineEvent::ToolExecutionStart {
- tool_call_id: tool_call_id.clone(),
- tool_name: tool_name.clone(),
- args: args.clone(),
- }],
- AgentEvent::ToolExecutionEnd {
- tool_call_id,
- tool_name,
- result,
- is_error,
- } => vec![AcpEngineEvent::ToolExecutionEnd {
- tool_call_id: tool_call_id.clone(),
- tool_name: tool_name.clone(),
- result: serde_json::to_value(result).unwrap_or(Value::Null),
- is_error: *is_error,
- }],
- _ => Vec::new(),
- }
-}
-
-/// The transcript as it stood before a turn started, recorded so the turn's
-/// own messages can be told apart from everything older. Compaction can fire
-/// during a turn and rebuild the message list, so membership is tracked by
-/// a content key the rebuild preserves, not by index.
-#[derive(Debug, Default)]
-pub struct TurnBoundary {
- keys: Vec<String>,
-}
-
-impl TurnBoundary {
- pub async fn capture(agent: &Agent) -> TurnBoundary {
- let state = agent.state().await;
- TurnBoundary {
- keys: state.messages.iter().filter_map(message_key).collect(),
- }
- }
-
- /// Membership check for the wire shape of an assistant message (the
- /// turn loop classifies the latest assistant against the pre-turn
- /// transcript; the key composition is the one `message_key` builds —
- /// compaction drops messages, it does not rewrite them, so the keys
- /// survive the compaction rebuild).
- pub fn contains_wire(&self, assistant: &pa_types::ai::AssistantMessage) -> bool {
- let stop_reason = serde_json::to_value(assistant.stop_reason).unwrap_or(Value::Null);
- let key = json!([
- "assistant",
- assistant.timestamp,
- stop_reason,
- assistant.error_message,
- ])
- .to_string();
- self.keys.contains(&key)
- }
-}
-
-/// Key for a kept message: (role, timestamp, stopReason, errorMessage) as the
-/// wire tuple. Compaction drops messages; it does not rewrite them.
-fn message_key(message: &AgentMessage) -> Option<String> {
- let AgentMessage::Standard(Message::Assistant(assistant)) = message else {
- return None;
- };
- let stop_reason = serde_json::to_value(assistant.stop_reason).unwrap_or(Value::Null);
- Some(
- json!([
- "assistant",
- assistant.timestamp,
- stop_reason,
- assistant.error_message,
- ])
- .to_string(),
- )
-}
-
-/// The newest assistant message of the transcript, when one exists (the
-/// autonomous driver consults it for the settled turn).
-pub async fn latest_assistant_message(agent: &Agent) -> Option<pa_types::ai::AssistantMessage> {
- let state = agent.state().await;
- state.messages.iter().rev().find_map(|message| {
- let AgentMessage::Standard(Message::Assistant(assistant)) = message else {
- return None;
- };
- serde_json::to_value(assistant)
- .ok()
- .and_then(|value| serde_json::from_value::<pa_types::ai::AssistantMessage>(value).ok())
- })
-}
-
-/// The frame pair that brackets every settled turn: the completion event and
-/// the terminal quiescence envelope. In-process sessions have no RLM
-/// children, so quiescence is trivially reached at settlement; the
-/// autonomous accounting rides the completion update while a run is
-/// enabled.
-pub async fn publish_completion_envelope(
- session: &AcpSession,
- turn_id: u64,
- outcome: PrimeAgentOutcome,
- autonomous: Option<&PrimeAgentAutonomousMeta>,
- remaining_autonomous_continuations: u64,
-) -> anyhow::Result<()> {
- let quiescence = PrimeAgentQuiescenceMeta {
- outstanding_subagents: 0,
- remaining_autonomous_continuations,
- };
- let info_meta = PrimeAgentSessionMeta {
- quiescence: Some(quiescence),
- autonomous: autonomous.cloned(),
- ..Default::default()
- };
- let completion = AcpSessionUpdate::SessionInfoUpdate {
- meta: super::meta::prime_agent_meta(&info_meta),
- };
- if !session
- .producer()
- .publish(&completion, turn_id, PrimeAgentEventPhase::Event, None)
- .await
- {
- anyhow::bail!("Failed to publish ACP completion update");
- }
- let terminal = AcpSessionUpdate::SessionInfoUpdate {
- meta: super::meta::prime_agent_meta(&info_meta),
- };
- if !session
- .producer()
- .publish(
- &terminal,
- turn_id,
- PrimeAgentEventPhase::TerminalQuiescence,
- Some(outcome),
- )
- .await
- {
- anyhow::bail!("Failed to publish ACP terminal quiescence update");
- }
- Ok(())
-}
-
-/// Publish the correlated response boundary in front of a prompt response.
-/// `expected` tells the client whether a terminal quiescence envelope
-/// follows (an accepted turn) or not (failed admission).
-pub async fn publish_response_boundary(
- session: &AcpSession,
- turn_id: u64,
- expected: bool,
- outcome: PrimeAgentOutcome,
-) -> anyhow::Result<()> {
- let boundary = AcpSessionUpdate::SessionInfoUpdate {
- meta: super::meta::prime_agent_meta(&PrimeAgentSessionMeta {
- terminal_quiescence_expected: Some(expected),
- ..Default::default()
- }),
- };
- if !session
- .producer()
- .publish(
- &boundary,
- turn_id,
- PrimeAgentEventPhase::ResponseBoundary,
- Some(outcome),
- )
- .await
- {
- anyhow::bail!("Failed to publish ACP response boundary");
- }
- Ok(())
-}
-
-/// Render a prompt-block failure as the ACP invalid-params error. The TS
-/// SDK validates the request schema; the Rust port validates the blocks it
-/// actually reads.
-pub fn prompt_block_error(id: &Value, error: &PromptBlockError) -> Value {
- jsonrpc::error_response(
- id,
- jsonrpc::INVALID_PARAMS,
- "Invalid params",
- Some(&json!({ "reason": error.to_string() })),
- )
-}
-
-/// The prompt content admitted into a turn.
-#[derive(Debug, Clone, PartialEq)]
-pub struct AdmittedPrompt {
- pub text: String,
- pub images: Vec<ImageBlock>,
-}
-
-impl AdmittedPrompt {
- pub fn parse(prompt: &[Value]) -> Result<AdmittedPrompt, PromptBlockError> {
- let (text, images) = parse_prompt_blocks(prompt)?;
- Ok(AdmittedPrompt { text, images })
- }
-}
diff --git a/crates/pa-daemon/src/acp/types.rs b/crates/pa-daemon/src/acp/types.rs
index 4c373fc618..66247ed1f9 100644
--- a/crates/pa-daemon/src/acp/types.rs
+++ b/crates/pa-daemon/src/acp/types.rs
@@ -300,6 +300,20 @@ pub struct ImageBlock {
pub mime_type: String,
}
+/// The prompt content admitted into a turn.
+#[derive(Debug, Clone, PartialEq)]
+pub struct AdmittedPrompt {
+ pub text: String,
+ pub images: Vec<ImageBlock>,
+}
+
+impl AdmittedPrompt {
+ pub fn parse(prompt: &[Value]) -> Result<AdmittedPrompt, PromptBlockError> {
+ let (text, images) = parse_prompt_blocks(prompt)?;
+ Ok(AdmittedPrompt { text, images })
+ }
+}
+
/// The `session/new` request params.
#[derive(Debug, Clone, PartialEq)]
pub struct NewSessionParams {
@@ -375,15 +389,6 @@ impl SetConfigOptionParams {
}
}
-/// A bare `{ "sessionId": ... }` params reader shared by close and cancel.
-pub fn session_id_params(params: &Value) -> String {
- params
- .get("sessionId")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string()
-}
-
/// The initialize result with the served capability set.
pub fn initialize_result(product_version: &str) -> InitializeResult {
InitializeResult {
diff --git a/crates/pa-daemon/src/acp/wire_events.rs b/crates/pa-daemon/src/acp/wire_events.rs
index bf78117235..14a76aa008 100644
--- a/crates/pa-daemon/src/acp/wire_events.rs
+++ b/crates/pa-daemon/src/acp/wire_events.rs
@@ -1,9 +1,7 @@
//! Daemon session-event mapping: the TS `acpUpdatesForSessionEvent` port
//! for the wire shapes a daemon worker streams (`message_start/update/end`,
-//! `tool_execution_*`, `compaction_end`, `goal_update`, ...). The
-//! daemon-attached ACP transport rides this instead of the in-process
-//! loop-event projection (`events.rs`): same ACP frames, different producer
-//! side.
+//! `tool_execution_*`, `bash_*`, `compaction_end`, `goal_update`, ...): the
+//! ACP frames the daemon worker's session events produce.
//!
//! Events with no ACP counterpart (`turn_end`, `auto_retry_*`,
//! `agent_begin/end`, `session_action_update`) map to nothing, exactly like
@@ -11,16 +9,20 @@
use serde_json::{json, Value};
-use super::events::{AcpToolKind, AcpToolStatus, IPYTHON_TOOL_NAME};
use super::meta::{prime_agent_meta, PrimeAgentCompactionMeta, PrimeAgentSessionMeta};
-use super::types::{AcpSessionUpdate, TextBlock};
+use super::types::{AcpSessionUpdate, AcpToolKind, AcpToolStatus, TextBlock};
+
+/// The model-facing Python REPL tool.
+const IPYTHON_TOOL_NAME: &str = "ipython";
/// Correlates streamed chunks with their owning assistant message (the
-/// daemon stream carries the delta on `assistantMessageEvent`).
+/// daemon stream carries the delta on `assistantMessageEvent`) and bash
+/// output chunks with the run that produced them.
#[derive(Debug, Default)]
pub struct WireMappingState {
next_assistant_message_sequence: u64,
active_assistant_message_id: Option<String>,
+ active_bash_run_id: Option<String>,
}
impl WireMappingState {
@@ -190,6 +192,64 @@ pub fn wire_updates(event: &Value, state: &mut WireMappingState) -> Vec<AcpSessi
};
vec![update]
}
+ // User-level bash runs outside the tool-call lifecycle: a synthetic
+ // tool call keyed by run id keeps the streamed chunks addressable.
+ "bash_start" => {
+ let command = event
+ .get("command")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ let run_id = event
+ .get("runId")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ state.active_bash_run_id.clone_from(&run_id);
+ vec![AcpSessionUpdate::ToolCall {
+ tool_call_id: bash_tool_call_id(run_id),
+ title: command.clone(),
+ kind: AcpToolKind::Execute,
+ status: AcpToolStatus::InProgress,
+ raw_input: json!({ "command": command }),
+ }]
+ }
+ "bash_output" => {
+ let chunk = event
+ .get("chunk")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ vec![AcpSessionUpdate::ToolCallUpdate {
+ tool_call_id: bash_tool_call_id(state.active_bash_run_id.clone()),
+ status: Some(AcpToolStatus::InProgress),
+ content: Some(vec![super::types::ToolCallContent::new(chunk)]),
+ meta: None,
+ }]
+ }
+ "bash_end" => {
+ let run_id = event
+ .get("runId")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ if state.active_bash_run_id == run_id {
+ state.active_bash_run_id = None;
+ }
+ let completed = event.get("exitCode").and_then(Value::as_i64) == Some(0)
+ && !event
+ .get("cancelled")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ vec![AcpSessionUpdate::ToolCallUpdate {
+ tool_call_id: bash_tool_call_id(run_id),
+ status: Some(if completed {
+ AcpToolStatus::Completed
+ } else {
+ AcpToolStatus::Failed
+ }),
+ content: None,
+ meta: None,
+ }]
+ }
"goal_update" => {
let goal = event.get("goal");
vec![AcpSessionUpdate::SessionInfoUpdate {
@@ -236,15 +296,27 @@ pub fn wire_updates(event: &Value, state: &mut WireMappingState) -> Vec<AcpSessi
}
}
+/// The synthetic tool-call id of a user-level bash run:
+/// `prime-agent-bash-<runId>`; a run without an id keys the bare prefix
+/// (TS `bashToolCallId`).
+fn bash_tool_call_id(run_id: Option<String>) -> String {
+ match run_id {
+ Some(run_id) => format!("prime-agent-bash-{run_id}"),
+ None => "prime-agent-bash".to_string(),
+ }
+}
+
/// TS `toolResultText`: the text of a tool result, wherever the engine
-/// carries it.
+/// carries it. Empty text blocks drop out before the join and an empty
+/// text yields `None`, so no update carries empty content (the TS call
+/// site's `text ? { content } : {}`).
fn tool_result_text(result: Option<&Value>) -> Option<String> {
let result = result?;
if let Some(text) = result.as_str() {
- return Some(text.to_string());
+ return (!text.is_empty()).then(|| text.to_string());
}
if let Some(output) = result.get("output").and_then(Value::as_str) {
- return Some(output.to_string());
+ return (!output.is_empty()).then(|| output.to_string());
}
let content = result.get("content")?.as_array()?;
let parts: Vec<String> = content
@@ -259,6 +331,7 @@ fn tool_result_text(result: Option<&Value>) -> Option<String> {
})
.flatten()
})
+ .filter(|text| !text.is_empty())
.collect();
(!parts.is_empty()).then(|| parts.join("\n"))
}
@@ -471,4 +544,41 @@ mod tests {
}))
.is_none());
}
+
+ #[test]
+ fn empty_tool_results_carry_no_content() {
+ let mut state = WireMappingState::default();
+ let updates = wire_updates(
+ &json!({
+ "type": "tool_execution_end",
+ "toolCallId": "t1",
+ "result": { "output": "" },
+ "isError": false,
+ }),
+ &mut state,
+ );
+ let value = serde_json::to_value(&updates[0]).unwrap();
+ assert_eq!(value["sessionUpdate"], "tool_call_update");
+ assert_eq!(value["status"], "completed");
+ assert!(value.get("content").is_none(), "no empty content: {value}");
+ }
+
+ #[test]
+ fn empty_text_blocks_drop_out_of_the_joined_result() {
+ let mut state = WireMappingState::default();
+ let updates = wire_updates(
+ &json!({
+ "type": "tool_execution_end",
+ "toolCallId": "t1",
+ "result": { "content": [
+ { "type": "text", "text": "" },
+ { "type": "text", "text": "a" },
+ ] },
+ "isError": false,
+ }),
+ &mut state,
+ );
+ let value = serde_json::to_value(&updates[0]).unwrap();
+ assert_eq!(value["content"][0]["content"]["text"], "a");
+ }
}
diff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rs
index af1a7de400..59305d10ed 100644
--- a/crates/pa-daemon/src/agent_engine.rs
+++ b/crates/pa-daemon/src/agent_engine.rs
@@ -44,7 +44,7 @@ use crate::rlm_children::{ParentIdentity, SupervisorChildSessions, DEFAULT_RLM_M
// the child module at the same tree position (agent_engine::tests); the
// FAUX_TEST_LOCK re-export keeps the facade's FAUX_TEST_LOCK paths stable
// for the sibling test modules (overflow_compaction, compact_autorefine,
-// session_navigation, acp/{autorefine,compaction_arms,goal_continuation}).
+// session_navigation).
#[cfg(test)]
pub(crate) mod tests;
diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rs
index ab8d8e8175..90544c7b6c 100644
--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs
+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs
@@ -20,8 +20,8 @@ pub(crate) const BARE_SKILL_INVOCATION_INSTRUCTION: &str = "The user invoked thi
impl AgentSessionEngine {
/// Build the engine: the shared async runtime, the model selection
- /// (create config, else the process env pair), the supervisor link, the
- /// children registry, and the MCP store.
+ /// (create config), the supervisor link, the children registry, and the
+ /// MCP store.
///
/// # Errors
///
@@ -35,23 +35,11 @@ impl AgentSessionEngine {
pub fn new(config: AgentEngineConfig) -> anyhow::Result<Self> {
let runtime = crate::async_safe_runtime::AsyncSafeRuntime::new_multi_thread()?;
let session_file = std::sync::Mutex::new(config.session_file.clone());
- // Process-level fallback: the create config, else the worker env
- // pair. A create command with explicit wire flags overrides both.
- let thinking = config.thinking;
- let selection = if config.provider.is_some() || config.model.is_some() {
- EngineModelSelection {
- provider: config.provider.clone(),
- model: config.model.clone(),
- api_key: config.api_key.clone(),
- thinking,
- }
- } else {
- EngineModelSelection {
- provider: std::env::var("PRIME_AGENT_MODEL_PROVIDER").ok(),
- model: std::env::var("PRIME_AGENT_MODEL").ok(),
- api_key: None,
- thinking,
- }
+ let selection = EngineModelSelection {
+ provider: config.provider.clone(),
+ model: config.model.clone(),
+ api_key: config.api_key.clone(),
+ thinking: config.thinking,
};
// One shared supervisor-link client for the worker: agent messaging
// and supervisor-backed RLM children multiplex the same connection
diff --git a/crates/pa-daemon/src/agent_engine/model.rs b/crates/pa-daemon/src/agent_engine/model.rs
index 07dfc9e30a..72edf1a059 100644
--- a/crates/pa-daemon/src/agent_engine/model.rs
+++ b/crates/pa-daemon/src/agent_engine/model.rs
@@ -310,14 +310,33 @@ impl AgentSessionEngine {
/// registers once per engine: its queued responses then span the whole
/// session (multi-turn scripts), instead of replaying from the top on
/// every model resolution.
+ ///
+ /// The script model serves the session while the selection is unset or
+ /// names it; any other selection resolves through the registry (a
+ /// models.json faux-api model streams through the same registered
+ /// provider).
pub(crate) fn resolve_model(&self) -> anyhow::Result<Model> {
if let Some(script) = &self.config.faux_script {
- if let Some(model) = self.faux_model.get() {
- return Ok(model.clone());
+ let model = if let Some(model) = self.faux_model.get() {
+ model.clone()
+ } else {
+ let model = faux_model_from_script(script)?;
+ let _ = self.faux_model.set(model.clone());
+ model
+ };
+ let selection = self.current_selection();
+ let names_script_model = selection
+ .provider
+ .as_deref()
+ .is_none_or(|provider| provider == model.provider.as_str())
+ && selection
+ .model
+ .as_deref()
+ .is_none_or(|model_id| model_id == model.id.as_str());
+ if names_script_model {
+ return Ok(model);
}
- let model = faux_model_from_script(script)?;
- let _ = self.faux_model.set(model.clone());
- return Ok(model);
+ return self.resolve_registry_model();
}
self.resolve_registry_model()
}
diff --git a/crates/pa-daemon/src/prompt_admission.rs b/crates/pa-daemon/src/prompt_admission.rs
index 9a5786bf80..496bee51e3 100644
--- a/crates/pa-daemon/src/prompt_admission.rs
+++ b/crates/pa-daemon/src/prompt_admission.rs
@@ -24,7 +24,7 @@ use serde_json::{json, Value};
use crate::backpressure::RouteAdmission;
use crate::protocol::{response_failure, response_line, response_success, DaemonResponse};
use crate::supervisor::{
- client_command_payload, Supervisor, LONG_ROUTE_TIMEOUT_MS, ROUTE_TIMEOUT_MS,
+ client_command_payload, client_route_timeout, Supervisor, ROUTE_TIMEOUT_MS,
};
use crate::worker::Worker;
@@ -238,20 +238,9 @@ impl Supervisor {
"Prompt admission was cancelled.",
);
}
- let Some((worker_admission_id, timeout)) =
- connection.prompt_admissions.with(&key, |admission| {
- (
- admission.worker_admission_id.clone(),
- if matches!(
- command,
- pa_types::daemon::DaemonCommand::PromptAndWait { .. }
- ) {
- LONG_ROUTE_TIMEOUT_MS
- } else {
- ROUTE_TIMEOUT_MS
- },
- )
- })
+ let Some(worker_admission_id) = connection
+ .prompt_admissions
+ .with(&key, |admission| admission.worker_admission_id.clone())
else {
// An admission that vanished before the route: the prompt
// routes through the generic path (TS `admission undefined`).
@@ -259,6 +248,7 @@ impl Supervisor {
.route_client_command(command, client_id, attached, command_id, type_name, None)
.await;
};
+ let timeout = client_route_timeout(command);
// Resolve the session (the generic route's wake-aware resolution).
let mut rebound_to: Option<String> = None;
let resident = if let Ok(resident) = self.registry.resolve(active_session_id).await {
diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rs
index b5e6de0a1f..8e0243241e 100644
--- a/crates/pa-daemon/src/supervisor.rs
+++ b/crates/pa-daemon/src/supervisor.rs
@@ -60,7 +60,7 @@ pub(crate) use clients::client_command_payload;
// The routing consts and refusal string keep their crate::supervisor::* paths stable
// (external callers: supervisor_parent_death, create_reuse, prompt_admission, update_restore).
-pub(crate) use routing::{LONG_ROUTE_TIMEOUT_MS, ROUTE_TIMEOUT_MS, WORKER_NOT_CONNECTED};
+pub(crate) use routing::{client_route_timeout, ROUTE_TIMEOUT_MS, WORKER_NOT_CONNECTED};
// probe_worker_socket/worker_connect_deadline are called only by the supervision sibling
// module and this facade's in-file tests (through the module's pub(super) fns); the
diff --git a/crates/pa-daemon/src/supervisor/clients.rs b/crates/pa-daemon/src/supervisor/clients.rs
index 99a1cccc75..15b081de62 100644
--- a/crates/pa-daemon/src/supervisor/clients.rs
+++ b/crates/pa-daemon/src/supervisor/clients.rs
@@ -154,6 +154,7 @@ impl Supervisor {
loop {
line.clear();
tokio::select! {
+ biased;
read = reader.read_line(&mut line), if dispatch_slots.available_permits() > 0 => {
let Ok(read) = read else { break };
if read == 0 {
@@ -218,6 +219,37 @@ impl Supervisor {
drop(dispatch_slot);
});
}
+ targeted = targeted_rx.recv() => {
+ // A session event routed by the subscriber registry at
+ // publish time: the delivery decision already ran, the
+ // frame only writes (the queue preserves per-session
+ // publish order). The arm polls ahead of the response
+ // arm, so an event published before a response bundle
+ // is queued is written first - the worker's own
+ // event-before-response socket order survives the hop.
+ if let Some(payload) = targeted {
+ if let Err(error) = write_line(&mut writer, &payload).await {
+ // An event-write failure must not strand an
+ // accepted shutdown: if this connection owns
+ // the stop, it still starts the pass.
+ let is_shutdown_owner = self
+ .shutdown_owner
+ .lock()
+ .unwrap()
+ .as_deref()
+ == Some(connection_id.as_str());
+ if is_shutdown_owner
+ && self.shutting_down.load(Ordering::SeqCst)
+ && !self.accept_exit.load(Ordering::SeqCst)
+ {
+ self.ensure_shutdown_started().await;
+ }
+ return Err(error);
+ }
+ } else {
+ break;
+ }
+ }
dispatched = dispatch_rx.recv() => {
let Some((lines, stop)) = dispatched else { break };
for outbound in lines {
@@ -259,34 +291,6 @@ impl Supervisor {
break;
}
}
- targeted = targeted_rx.recv() => {
- // A session event routed by the subscriber registry at
- // publish time: the delivery decision already ran, the
- // frame only writes (the queue preserves per-session
- // publish order).
- if let Some(payload) = targeted {
- if let Err(error) = write_line(&mut writer, &payload).await {
- // An event-write failure must not strand an
- // accepted shutdown: if this connection owns
- // the stop, it still starts the pass.
- let is_shutdown_owner = self
- .shutdown_owner
- .lock()
- .unwrap()
- .as_deref()
- == Some(connection_id.as_str());
- if is_shutdown_owner
- && self.shutting_down.load(Ordering::SeqCst)
- && !self.accept_exit.load(Ordering::SeqCst)
- {
- self.ensure_shutdown_started().await;
- }
- return Err(error);
- }
- } else {
- break;
- }
- }
event = events.recv() => {
match event {
Ok((routing, payload)) => {
diff --git a/crates/pa-daemon/src/supervisor/handshake_tests.rs b/crates/pa-daemon/src/supervisor/handshake_tests.rs
index 89c0bc7a99..c48bbebb38 100644
--- a/crates/pa-daemon/src/supervisor/handshake_tests.rs
+++ b/crates/pa-daemon/src/supervisor/handshake_tests.rs
@@ -1,6 +1,7 @@
-//! The worker-handshake boundary oracles: the handshake owns its channel
+//! The worker-connection boundary oracles: the handshake owns its channel
//! privately until the auth answer installs it for routing — the TS
-//! `pendingClient`/`worker.client` boundary (one family per module).
+//! `pendingClient`/`worker.client` boundary — and a lost connection fails
+//! its in-flight routes (one family per module).
use super::*;
@@ -341,3 +342,95 @@ async fn a_stale_epoch_never_overwrites_the_installed_channel() {
.expect("the channel stays open");
assert_eq!(frame.command_type, "get_state");
}
+
+/// A lost worker connection fails its in-flight routes right away (TS
+/// `notifyClosed` -> `rejectAll`): the reader drains the connection's reply
+/// slots when the socket ends, so a route waiting on the worker's answer
+/// cannot outlive the connection it was sent on.
+#[tokio::test]
+async fn a_lost_worker_connection_fails_its_in_flight_route() {
+ let dir = std::env::temp_dir().join(format!("pa-lost-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let socket_path = dir.join("worker.sock");
+ let agent_dir = dir.join("agent");
+ std::fs::create_dir_all(&agent_dir).unwrap();
+ let supervisor = Arc::new(
+ Supervisor::new(SupervisorOptions {
+ socket_path: dir.join("daemon.sock"),
+ agent_dir,
+ })
+ .expect("supervisor"),
+ );
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(serde_json::json!({
+ "version": 2,
+ "workerId": "w-lost",
+ "pid": 4242,
+ "socketPath": socket_path.to_string_lossy(),
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "lost-token",
+ "rootActiveSessionId": "none",
+ "createdAt": "2026-09-23T00:00:00Z",
+ "updatedAt": "2026-09-23T00:00:00Z",
+ "lifecycle": "ready",
+ "createCommand": {},
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ let resident = ResidentWorker::new("w-lost".to_string(), descriptor, dir.join("w-lost.json"));
+ supervisor.registry.insert(Arc::clone(&resident)).await;
+
+ let listener = bind_fake_worker(&socket_path).await;
+ let connect = {
+ let supervisor = Arc::clone(&supervisor);
+ let resident = Arc::clone(&resident);
+ tokio::spawn(async move {
+ supervisor
+ .connect_worker(&resident, worker_connect_deadline())
+ .await
+ })
+ };
+ let mut fake = accept_fake_worker(listener).await;
+ let frame = read_supervisor_frame(&mut fake).await;
+ assert_eq!(frame.header.get("commandType"), Some(&json!("worker_auth")));
+ let request_id = frame
+ .header
+ .get("requestId")
+ .and_then(Value::as_str)
+ .expect("request id")
+ .to_string();
+ answer_supervisor_frame(&mut fake, &request_id, "worker_auth").await;
+ connect
+ .await
+ .expect("the connect task lives")
+ .expect("the handshake completes");
+
+ // A turn-long route in flight on the live connection.
+ let route = {
+ let supervisor = Arc::clone(&supervisor);
+ let resident = Arc::clone(&resident);
+ tokio::spawn(async move {
+ supervisor
+ .route_command_typed(
+ &resident,
+ "prompt_and_wait",
+ json!({ "activeSessionId": "w-lost", "message": "go" }),
+ super::routing::WORKER_REQUEST_TIMEOUT_MS,
+ RouteAdmission::ClientRequest,
+ )
+ .await
+ })
+ };
+ let frame = read_supervisor_frame(&mut fake).await;
+ assert_eq!(
+ frame.header.get("commandType"),
+ Some(&json!("prompt_and_wait"))
+ );
+ drop(fake);
+ let error = tokio::time::timeout(Duration::from_secs(5), route)
+ .await
+ .expect("the lost connection fails the in-flight route")
+ .expect("the route task lives")
+ .expect_err("the drained route fails");
+ assert_eq!(error.to_string(), "Session worker dropped the request");
+}
diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rs
index 41039911f5..8da3f72886 100644
--- a/crates/pa-daemon/src/supervisor/routing.rs
+++ b/crates/pa-daemon/src/supervisor/routing.rs
@@ -36,7 +36,28 @@ pub(super) async fn fail_unsent_request(resident: &Arc<ResidentWorker>, request_
)));
}
}
-pub(crate) const LONG_ROUTE_TIMEOUT_MS: u64 = 600_000;
+/// TS daemon-supervisor.ts:204 `WORKER_REQUEST_TIMEOUT_MS`.
+pub(crate) const WORKER_REQUEST_TIMEOUT_MS: u64 = 24 * 60 * 60 * 1000;
+
+/// The route budget of a client command: turn-long waits ride TS's 24 h
+/// worker-request budget; everything else is a short control route.
+pub(crate) fn client_route_timeout(command: &DaemonCommand) -> u64 {
+ if matches!(
+ command,
+ DaemonCommand::PromptAndWait { .. }
+ | DaemonCommand::WaitForIdle { .. }
+ // Headless completion settles a whole autonomous run.
+ | DaemonCommand::WaitForHeadlessCompletion { .. }
+ // Compaction runs a summarizer model call, like a turn.
+ | DaemonCommand::Compact { .. }
+ // A tree navigation may run a branch-summary model call.
+ | DaemonCommand::NavigateTree { .. }
+ ) {
+ WORKER_REQUEST_TIMEOUT_MS
+ } else {
+ ROUTE_TIMEOUT_MS
+ }
+}
impl Supervisor {
pub(crate) async fn route_command(
@@ -644,21 +665,7 @@ impl Supervisor {
);
}
}
- let timeout = if matches!(
- command,
- DaemonCommand::PromptAndWait { .. }
- | DaemonCommand::WaitForIdle { .. }
- // Headless completion settles a whole autonomous run.
- | DaemonCommand::WaitForHeadlessCompletion { .. }
- // Compaction runs a summarizer model call, like a turn.
- | DaemonCommand::Compact { .. }
- // A tree navigation may run a branch-summary model call.
- | DaemonCommand::NavigateTree { .. }
- ) {
- LONG_ROUTE_TIMEOUT_MS
- } else {
- ROUTE_TIMEOUT_MS
- };
+ let timeout = client_route_timeout(command);
let (worker_command, mut payload) = match client_command_payload(command, client_id) {
Ok(payload) => payload,
Err(error) => {
diff --git a/crates/pa-daemon/src/supervisor/supervision.rs b/crates/pa-daemon/src/supervisor/supervision.rs
index e8087d7a41..b440c4df59 100644
--- a/crates/pa-daemon/src/supervisor/supervision.rs
+++ b/crates/pa-daemon/src/supervisor/supervision.rs
@@ -1,13 +1,13 @@
//! Worker supervision: the watch loop, the restart backoff, and
//! the spawn/connect plumbing.
-use super::routing::fail_unsent_request;
+use super::routing::{fail_unsent_request, WORKER_REQUEST_TIMEOUT_MS};
use super::{
anyhow, connect_transport, create_command_payload, json, mpsc, persist_worker,
persist_worker_at, probe_worker_socket, util, write_frame, Arc, Child, ClientRouting, Command,
Context, DaemonWorkerLifecycle, Duration, Ordering, PathBuf, PrivateFrameReader,
ResidentWorker, Result, RouteAdmission, Supervisor, TempSync, TypedCreateRejection, Value,
- WorkerReply, WorkerRequest, DEFAULT_PRIVATE_FRAME_LIMITS, LONG_ROUTE_TIMEOUT_MS,
- ROUTE_TIMEOUT_MS, WORKER_AUTH_FLOOR_MS,
+ WorkerReply, WorkerRequest, DEFAULT_PRIVATE_FRAME_LIMITS, ROUTE_TIMEOUT_MS,
+ WORKER_AUTH_FLOOR_MS,
};
use crate::lease::is_process_alive;
use crate::registry::WorkerRelay;
@@ -303,7 +303,7 @@ impl Supervisor {
resident,
"create",
payload,
- LONG_ROUTE_TIMEOUT_MS,
+ WORKER_REQUEST_TIMEOUT_MS,
RouteAdmission::SupervisorInternal,
)
.await
@@ -784,6 +784,17 @@ impl Supervisor {
events.send((ClientRouting::Broadcast, std::sync::Arc::new(payload)));
}
}
+ // The connection is gone: no reply can arrive on it any
+ // more (TS `notifyClosed` -> `rejectAll`); each waiting
+ // route fails with the dropped-request error. A stale
+ // reader drops nothing - the newer connection's handshake
+ // inserts only after its epoch bump.
+ {
+ let mut pending = reader_resident.pending.lock().await;
+ if reader_resident.connection_is_current(connection_epoch) {
+ pending.clear();
+ }
+ }
reader_resident.note_connection_lost(connection_epoch);
// The connection ended (EOF or frame error): a run without
// an abort request dies with the worker and rides the
@@ -850,25 +861,22 @@ impl Supervisor {
)
.await
.map_err(|error| {
- // The handshake route's timeout is the connect budget
- // running out, not a session command timing out: report the
- // launch-budget failure so a loaded-box launch failure says
- // what actually happened (never the generic route timeout
- // text, which pointed triage at the wrong seam).
- if error.to_string() == "Session worker timed out" {
- // The worker answered nothing inside the launch budget:
- // its captured stderr tail rides the failure (the same
- // evidence the probe arm carries).
- crate::worker_stderr::not_ready_with_tail(
- anyhow!("session worker {} did not come up in time", resident.worker_id),
- &crate::worker_stderr::log_path(
- &self.options.agent_dir,
- &resident.worker_id,
- ),
- )
- } else {
- error
- }
+ // A handshake that never finishes is a launch failure, not a
+ // route timeout: report it with the worker's stderr tail.
+ let message = match error.to_string().as_str() {
+ "Session worker timed out" => {
+ format!("session worker {} did not come up in time", resident.worker_id)
+ }
+ "Session worker dropped the request" => format!(
+ "session worker {} exited before its handshake finished",
+ resident.worker_id
+ ),
+ _ => return error,
+ };
+ crate::worker_stderr::not_ready_with_tail(
+ anyhow!(message),
+ &crate::worker_stderr::log_path(&self.options.agent_dir, &resident.worker_id),
+ )
})?;
if !response.success {
return Err(anyhow!(
diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rs
index 1efade190c..ba81ea5543 100644
--- a/crates/pa-daemon/src/supervisor/tests.rs
+++ b/crates/pa-daemon/src/supervisor/tests.rs
@@ -996,6 +996,93 @@ async fn first_signal_drains_a_settling_turn_and_rejects_new_work() {
pump.abort();
}
+/// A turn-long client route rides TS's 24 h worker-request budget
+/// (`WORKER_REQUEST_TIMEOUT_MS`, daemon-supervisor.ts:204), not the
+/// invented ten-minute cap: a `prompt_and_wait` whose worker answers a
+/// virtual hour later still succeeds.
+#[tokio::test(start_paused = true)]
+async fn a_prompt_and_wait_route_outlives_the_old_ten_minute_cap() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let options = SupervisorOptions {
+ socket_path: dir.path().join("daemon.sock"),
+ agent_dir: dir.path().join("agent"),
+ };
+ let supervisor = Arc::new(Supervisor::new(options).expect("supervisor"));
+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(serde_json::json!({
+ "version": 2,
+ "workerId": "w-longroute",
+ "pid": 0,
+ "socketPath": "/tmp/none.sock",
+ "recoveryJournalPath": "/tmp/none.jsonl",
+ "supervisorSocketPath": "/tmp/none.sock",
+ "authenticationToken": "test",
+ "rootActiveSessionId": "w-longroute",
+ "createdAt": "t",
+ "updatedAt": "t",
+ "lifecycle": "ready",
+ "createCommand": {},
+ "consecutiveFailures": 0,
+ }))
+ .expect("descriptor");
+ let descriptor_dir = dir.path().join("descriptors");
+ std::fs::create_dir_all(&descriptor_dir).unwrap();
+ let resident = Arc::new(ResidentWorker::new(
+ "w-longroute".to_string(),
+ descriptor,
+ descriptor_dir.join("w-longroute.descriptor.json"),
+ ));
+ // The fake worker holds the turn for a virtual hour — past the old
+ // ten-minute cap, inside the 24 h worker-request budget.
+ let (cmd_tx, mut cmd_rx) = mpsc::channel::<WorkerRequest>(1);
+ *resident.cmd_tx.lock().await = Some(cmd_tx);
+ let pump_resident = Arc::clone(&resident);
+ tokio::spawn(async move {
+ let request = cmd_rx.recv().await.expect("the route lands the prompt");
+ tokio::time::sleep(Duration::from_hours(1)).await;
+ let reply = pump_resident
+ .pending
+ .lock()
+ .await
+ .remove(&request.request_id)
+ .expect("the routed prompt holds a reply slot");
+ let _ = reply.send(WorkerReply::Typed(crate::protocol::response_success(
+ None,
+ "prompt_and_wait",
+ None,
+ )));
+ });
+ supervisor.registry.insert(Arc::clone(&resident)).await;
+ resident.note_connection_live();
+ resident.note_session_ready();
+ let (targeted_tx, _targeted_rx) = tokio::sync::mpsc::channel::<Arc<Value>>(16);
+ let attached = subscribers::ClientSubscriptions::new("c".to_string(), targeted_tx);
+ let command: DaemonCommand = serde_json::from_value(serde_json::json!({
+ "type": "prompt_and_wait",
+ "activeSessionId": "w-longroute",
+ "message": "go",
+ }))
+ .expect("command");
+ let route = {
+ let supervisor = Arc::clone(&supervisor);
+ tokio::spawn(async move {
+ supervisor
+ .route_client_command(
+ &command,
+ "c",
+ &attached,
+ "p-1".to_string(),
+ "prompt_and_wait".to_string(),
+ None,
+ )
+ .await
+ })
+ };
+ let (lines, stop) = route.await.expect("the route task lives");
+ assert!(!stop);
+ let line = lines.first().expect("the route answers with one line");
+ assert_eq!(line["success"], json!(true));
+}
+
/// Every signal that finds a shutdown already in flight is the force
/// request: the drain's own second signal, a signal racing the
/// shutdown command's gate, and a signal racing an update exit - the
diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
index 2ce8ab0891..ff146b7c2f 100644
--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
@@ -8,11 +8,12 @@ use super::launch_budget::{
};
#[cfg(not(unix))]
use super::launch_budget::{WORKER_PROBE_BACKOFF_MAX_MS, WORKER_PROBE_BACKOFF_MIN_MS};
+use super::routing::WORKER_REQUEST_TIMEOUT_MS;
use super::{
anyhow, create_command_payload, json, persist_worker, socket, util, Arc, Context,
DaemonCommand, DaemonWorkerDescriptor, DaemonWorkerLifecycle, DurableDaemonCreateCommand,
Duration, EngineModelSelection, Map, Ordering, Path, ResidentWorker, Result, RouteAdmission,
- Supervisor, TempSync, TypedCreateRejection, Value, LONG_ROUTE_TIMEOUT_MS, ROUTE_TIMEOUT_MS,
+ Supervisor, TempSync, TypedCreateRejection, Value, ROUTE_TIMEOUT_MS,
};
use crate::lease::is_process_alive;
use crate::protocol::{response_failure, response_success, DaemonResponse};
@@ -374,7 +375,7 @@ impl Supervisor {
&resident,
"create",
create_payload,
- LONG_ROUTE_TIMEOUT_MS,
+ WORKER_REQUEST_TIMEOUT_MS,
RouteAdmission::SupervisorInternal,
)
.await
diff --git a/crates/pa-daemon/src/update_restore.rs b/crates/pa-daemon/src/update_restore.rs
index f30c20c289..46b4852176 100644
--- a/crates/pa-daemon/src/update_restore.rs
+++ b/crates/pa-daemon/src/update_restore.rs
@@ -574,7 +574,7 @@ async fn continuation_treatment(
resident,
"prompt",
json!({ "message": UPDATE_RESTART_CONTINUATION_PROMPT }),
- crate::supervisor::LONG_ROUTE_TIMEOUT_MS,
+ crate::supervisor::ROUTE_TIMEOUT_MS,
RouteAdmission::SupervisorInternal,
)
.await;
diff --git a/crates/pa-daemon/testdata/acp/README.md b/crates/pa-daemon/testdata/acp/README.md
index 61a8cdedd3..e3f5ed4d24 100644
--- a/crates/pa-daemon/testdata/acp/README.md
+++ b/crates/pa-daemon/testdata/acp/README.md
@@ -70,28 +70,25 @@ scenario client against the Rust build with the same provider/model
(`z-ai/glm-5.3-flash`) and the kernel sidecar resolved through
`PI_PACKAGE_DIR` (a cargo-built binary has no sidecar next to the exe).
-Since slice 4 the Rust ACP mode prefers the daemon-attached transport
+Since slice 4 the Rust ACP mode serves over the daemon-attached transport
(the TS `shouldUseDaemonClient` behavior): the binary spawns a supervisor
on the sandboxed `--daemon-socket`, hosts a client-owned daemon session,
and streams its session events as ACP updates. The daemon-attached
captures are: happy_path, cwd_mismatch, errors, second_initialize,
tool_call, compact_command, mcp_stdio, mcp_replace, mcp_errors — all
-MATCH in full mode. The in-process engine stays the fallback when no
-daemon is reachable, and three captures still ride it (they exercise
-surfaces the daemon plane serves differently today):
+MATCH in full mode. `cancel`, `goal_command`, `autonomous_limit`, and
+`autonomous_gate` were captured on the since-removed in-process
+transport; recapture is pending (the files stay):
-- `cancel`: the in-process capture matched in full mode; the
- daemon-attached run resolves the same `{stopReason: "cancelled"}` shape
- with no boundary frames, but a fresh worker's first-token latency
- exceeds the scenario's 2s cancel window, so the pre-cancel chunk count
- differs per run. The daemon-attached cancel semantics are locked by
- the deterministic e2e (`acp_daemon_attached_cancels_mid_turn`).
-- `goal_command` / `autonomous_limit`: the daemon worker executes the
- commands (durable rows, goal continuations, the autonomous loop) but
- does not yet emit `goal_update` / autonomous-accounting session events,
- so the namespaced metas are an in-process-only surface until the
- daemon event plane grows those producers. `autonomous_gate` matches in
- full mode on the in-process capture.
+- `cancel`: the capture matched in full mode; the daemon-attached run
+ resolves the same `{stopReason: "cancelled"}` shape with no boundary
+ frames, but a fresh worker's first-token latency exceeds the
+ scenario's 2s cancel window, so the pre-cancel chunk count differs
+ per run. The daemon-attached cancel semantics are locked by the
+ deterministic e2e (`acp_daemon_attached_cancels_mid_turn`).
+- `goal_command` / `autonomous_limit` / `autonomous_gate`: the captures
+ predate the daemon's `goal_update` / autonomous-accounting producers;
+ recapture is pending.
## Comparing a Rust run
@@ -104,9 +101,10 @@ binaries advertise `{ "http": true }`:
Both captures must come from the same scenario client with the same
request order. `crates/pa-cli/tests/acp_mode_e2e.rs` locks the deterministic
-scenarios offline against the scripted faux provider; the
-network-dependent scenarios (tool_call, cancel mid-turn) are verified by
-running the scenario client against both binaries on a networked box.
+scenarios offline over the daemon-attached transport (the scripted faux
+worker); the network-dependent scenarios (tool_call, cancel mid-turn) are
+verified by running the scenario client against both binaries on a
+networked box.
`--landmarks` drops model-behavior-dependent work frames (tool calls,
chunk streams, and mid-turn goal-usage updates) and compares the protocol
diff --git a/crates/pa-daemon/tests/supervisor_e2e/event_order.rs b/crates/pa-daemon/tests/supervisor_e2e/event_order.rs
new file mode 100644
index 0000000000..39e5ad63d3
--- /dev/null
+++ b/crates/pa-daemon/tests/supervisor_e2e/event_order.rs
@@ -0,0 +1,148 @@
+//! The per-client writer keeps the worker's event-before-response order:
+//! a slow reader's reply never jumps the session events queued ahead of it.
+
+use super::*;
+
+/// A wire offset no kernel socket buffer reaches: a blocked writer has
+/// handed the kernel at most its socket buffers plus one partial line
+/// (the defaults are far smaller - Linux ~208 KiB, macOS 8 KiB), so an
+/// event starting past this offset was queued in the supervisor behind
+/// the blocked write.
+const SOCKET_SLACK: usize = 1 << 20;
+
+/// A slow reader's `prompt_and_wait` reply trails every session event the
+/// turn emitted before it, even while the writer is backlogged: the worker
+/// writes a turn's frames before the reply on its own socket, and the
+/// per-client writer polls its session-event arm ahead of the response
+/// arm, so the reply cannot jump the events queued ahead of it.
+///
+/// The scripted faux provider streams one large response (a coalesced
+/// `message_update` per flush interval, each snapshot growing toward the
+/// full text), so a client that reads nothing blocks the writer mid-turn.
+/// A second connection's `wait_for_idle` answer is the readiness signal.
+/// The precondition: a blocked writer can have handed the kernel only its
+/// socket buffers plus one partial line, so a pre-reply session event at
+/// a wire offset past [`SOCKET_SLACK`] was still queued in the supervisor
+/// when `wait_for_idle` answered; the test asserts a minimum count of
+/// those, so a turn too small to build a queue fails loudly.
+#[test]
+fn slow_client_reads_turn_events_before_the_reply() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let socket = dir.path().join("daemon.sock");
+ let agent_dir = dir.path().join("agent");
+ std::fs::create_dir_all(&agent_dir).expect("agent dir");
+ // ~15 MB of coalesced `message_update` snapshots over ~3 s at 12000
+ // tokens/s, each growing toward the full 150 KB text: the wire volume
+ // far exceeds any socket buffer, so the write blocks early and most
+ // of the turn's ~200 events start past the slack - still far under
+ // the session-event queue's 4096-frame capacity, so no frame is
+ // dropped.
+ let script_path = dir.path().join("script.json");
+ std::fs::write(
+ &script_path,
+ serde_json::json!({
+ "engine": "faux",
+ "tokensPerSecond": 12000,
+ "responses": [{ "text": "y".repeat(150_000) }],
+ })
+ .to_string(),
+ )
+ .expect("write script");
+ let _daemon = spawn_daemon(&socket, &agent_dir);
+ let (mut slow, _hello) = Client::connect(&socket);
+ slow.send_command(
+ "c1",
+ &serde_json::json!({
+ "type": "create",
+ "config": {
+ "cwd": dir.path().to_string_lossy(),
+ "sessionDir": agent_dir.join("sessions").to_string_lossy(),
+ "script": script_path.to_string_lossy(),
+ },
+ }),
+ );
+ let created = slow.read_response("c1");
+ assert_eq!(created["success"], true, "create failed: {created}");
+ let session_id = created["data"]["id"]
+ .as_str()
+ .or_else(|| created["data"]["sessionId"].as_str())
+ .expect("session id in create response")
+ .to_string();
+ slow.send_command(
+ "a1",
+ &serde_json::json!({ "type": "attach", "activeSessionId": session_id }),
+ );
+ assert_eq!(slow.read_response("a1")["success"], true, "attach failed");
+ // The probe subscribes before the turn starts, and asks for idle only
+ // after reading the turn's `agent_start`: `wait_for_idle` on an idle
+ // session answers at once, and the observed `agent_start` is what
+ // orders the probe's dispatch behind the slow client's prompt.
+ let (mut probe, _hello) = Client::connect(&socket);
+ probe.send_command(
+ "a2",
+ &serde_json::json!({ "type": "attach", "activeSessionId": session_id }),
+ );
+ let (probe_attach, mut probe_lines) = probe.read_response_and_lines("a2");
+ assert_eq!(
+ probe_attach["success"], true,
+ "probe attach failed: {probe_attach}"
+ );
+ // The turn runs while this client reads nothing: the writer writes the
+ // growing snapshots until the socket buffer fills, then blocks with
+ // the turn's remaining events queued behind the blocked write.
+ slow.send_command(
+ "p1",
+ &serde_json::json!({
+ "type": "prompt_and_wait",
+ "activeSessionId": session_id,
+ "message": "give me a long answer",
+ }),
+ );
+ let _ = probe.take_session_event(&mut probe_lines, "agent_start");
+ // Readiness is observed, never timed: the probe's `wait_for_idle`
+ // answers once the worker settled the turn, so every frame of the
+ // turn is published and the reply is on its way through dispatch.
+ probe.send_command(
+ "w1",
+ &serde_json::json!({ "type": "wait_for_idle", "activeSessionId": session_id }),
+ );
+ let idle = probe.read_response("w1");
+ assert_eq!(idle["success"], true, "wait_for_idle failed: {idle}");
+ // Drain the backlog: the writer owes this client every queued event
+ // before the reply. The offset counts the wire bytes read since the
+ // backlog began: the kernel can be holding only a socket buffer's
+ // worth plus one partial line, so every counted event was still
+ // queued in the supervisor behind the blocked write when
+ // `wait_for_idle` answered; the turn's boundary frames must be among
+ // the pre-reply events.
+ let mut wire_offset = 0usize;
+ let mut queued_before_reply = 0usize;
+ let mut saw_turn_end = false;
+ let mut saw_agent_end = false;
+ let reply = loop {
+ let line = slow.read_line();
+ if line.get("id").and_then(|value| value.as_str()) == Some("p1") {
+ break line;
+ }
+ if line["type"] == "session_event" {
+ if wire_offset >= SOCKET_SLACK {
+ queued_before_reply += 1;
+ }
+ match line["event"]["type"].as_str() {
+ Some("turn_end") => saw_turn_end = true,
+ Some("agent_end") => saw_agent_end = true,
+ _ => {}
+ }
+ }
+ wire_offset += serde_json::to_string(&line)
+ .expect("re-serialize line")
+ .len();
+ };
+ assert_eq!(reply["success"], true, "prompt_and_wait failed: {reply}");
+ assert!(
+ queued_before_reply >= 8,
+ "the reply must trail >= 8 session events past the slack, got {queued_before_reply}"
+ );
+ assert!(saw_turn_end, "the turn's turn_end must precede the reply");
+ assert!(saw_agent_end, "the turn's agent_end must precede the reply");
+}
diff --git a/crates/pa-daemon/tests/supervisor_e2e/main.rs b/crates/pa-daemon/tests/supervisor_e2e/main.rs
index 3bcf2f063f..b54bde84f9 100644
--- a/crates/pa-daemon/tests/supervisor_e2e/main.rs
+++ b/crates/pa-daemon/tests/supervisor_e2e/main.rs
@@ -37,6 +37,7 @@ use std::time::{Duration, Instant};
mod attach;
mod compaction;
mod create;
+mod event_order;
mod lifecycle;
mod read_goldens;
mod shutdown;