diff --git a/config.toml.example b/config.toml.example index c3d1df7b2..f6a25469f 100644 --- a/config.toml.example +++ b/config.toml.example @@ -207,6 +207,12 @@ working_dir = "/home/agent" # [pool] # default_config_options = { mode = "agent-full-access" } +# [agent] +# kiro-cli v3 engine with Kiro workflows (see docs/kiro-v3.md): +# command = "kiro-cli" +# args = ["acp", "--agent-engine=v3"] +# session_new_meta = { kiro = { settings = { workflows = { enabled = true } } } } + # [agent] # command = "gemini" # args = ["--acp"] @@ -271,6 +277,12 @@ session_ttl_hours = 24 # Grace (sec) past prompt_hard_timeout_secs before a hung in-flight session is # force-evicted from the pool. Default: 120. # hung_grace_secs = 120 +# kiro-cli v3 (see docs/kiro-v3.md): select the agent mode and fail fast when it is missing. +# default_config_options = { mode = "openab-bot" } +# strict_default_config_options = true +# Late Kiro workflow output relay (needs [agent].session_new_meta above). +# workflow_tail_quiet_secs = 20 +# workflow_tail_max_secs = 900 [markdown] tables = "code" # "code" (default) | "bullets" | "off" diff --git a/crates/openab-core/src/acp/connection.rs b/crates/openab-core/src/acp/connection.rs index d98a07713..38e6c1ccb 100644 --- a/crates/openab-core/src/acp/connection.rs +++ b/crates/openab-core/src/acp/connection.rs @@ -2,6 +2,7 @@ use crate::acp::protocol::{ parse_config_options, parse_usage_report, ConfigOption, JsonRpcErrorResponse, JsonRpcId, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse, UsageReport, }; +use crate::workflow_tail::{relay_channel, RelayReceiver, RelaySender}; use anyhow::{anyhow, Result}; use serde::Serialize; use serde_json::{json, Value}; @@ -171,6 +172,27 @@ impl SessionActivity { } } +/// Where the reader loop forwards notifications. `Prompt` is the foreground +/// prompt's unbounded queue. `Relay` is the bounded queue that takes over +/// after the reply for late workflow output (see `prompt_done_keep_subscriber`). +pub(crate) enum NotifySink { + Prompt(mpsc::UnboundedSender), + Relay(RelaySender), +} + +impl NotifySink { + fn push(&self, msg: JsonRpcMessage) { + match self { + Self::Prompt(tx) => { + let _ = tx.send(msg); + } + Self::Relay(tx) => { + let _ = tx.send(msg); + } + } + } +} + pub struct AcpConnection { _proc: Child, /// PID of the direct child, used as the process group ID for cleanup. @@ -178,7 +200,7 @@ pub struct AcpConnection { stdin: Arc>, next_id: AtomicU64, pending: Arc>>>, - notify_tx: Arc>>>, + notify_tx: Arc>>, pub acp_session_id: Option, pub supports_load_session: bool, /// Agent name from `initialize` (`agentInfo.name`), e.g. "Kiro CLI Agent". @@ -188,8 +210,14 @@ pub struct AcpConnection { pub last_active: Instant, pub activity: Arc, pub session_reset: bool, - _reader_handle: JoinHandle<()>, - _stderr_handle: Option>, + /// Completion of the workflow tail that took over the previous turn's late + /// output. The next turn waits for it before posting its own reply. + pub tail_done: Option>, + /// Cancel signal of that tail. Dropping the sender cancels the tail: it discards + /// buffered text and ends. `session_prompt` drops it before the next prompt replaces + /// the subscriber, and dropping the connection drops it on teardown. + pub tail_cancel: Option>, + _reader_handle: JoinHandle<()>, _stderr_handle: Option>, /// Revokes this session's facade token when the connection is dropped, on any evict path. /// Held only for its `Drop` side effect (never read). /// @@ -239,6 +267,52 @@ where } } +/// Params for `session/new`. `_meta` is added only when configured, so the +/// default request is byte-identical to the legacy one. +pub(crate) fn build_session_new_params(cwd: &str, meta: Option<&Value>) -> Value { + let mut params = json!({"cwd": cwd, "mcpServers": []}); + if let Some(meta) = meta { + params["_meta"] = meta.clone(); + } + params +} + +/// Check that `session/set_config_option` really applied `requested` for +/// `config_id`, using the option list the agent returned. +/// +/// An option list without `config_id` (including an empty list, which is what +/// a response with no `result` yields) is an error: the agent did not report +/// the option, so nothing confirms it. A different `currentValue` is accepted +/// only when the returned option lists a value whose display `name` equals +/// `requested` and whose `value` is the current one (agents that normalize +/// aliases). +pub(crate) fn verify_config_option_applied( + options: &[ConfigOption], + config_id: &str, + requested: &str, +) -> std::result::Result<(), String> { + let Some(opt) = options.iter().find(|o| o.id == config_id) else { + return Err(format!( + "default_config_options `{config_id}` = `{requested}` was not verified: the agent did not report the `{config_id}` option in its response" + )); + }; + if opt.current_value == requested { + return Ok(()); + } + if opt + .options + .iter() + .any(|v| v.name == requested && v.value == opt.current_value) + { + return Ok(()); + } + Err(format!( + "default_config_options `{config_id}` = `{requested}` was not applied: the agent reports `{}`. \ + Check that the value exists for this agent (for kiro v3, that `~/.kiro/agents/{requested}.md` is present in the bot's HOME).", + opt.current_value + )) +} + /// Reader loop body: reads JSON-RPC messages from `reader`, auto-replies /// `session/request_permission` via `writer`, resolves pending responses, /// and forwards notifications + stale id-bearing messages to the active @@ -248,7 +322,7 @@ pub(crate) async fn run_reader_loop( reader: R, writer: Arc>, pending: Arc>>>, - notify_tx: Arc>>>, + notify_tx: Arc>>, ) where R: AsyncRead + Unpin + Send + 'static, W: AsyncWrite + Unpin + Send + 'static, @@ -313,7 +387,7 @@ pub(crate) async fn run_reader_loop( let sub = notify_tx.lock().await; if let Some(ntx) = sub.as_ref() { // Clone the essential fields for the subscriber - let _ = ntx.send(JsonRpcMessage { + ntx.push(JsonRpcMessage { id: msg.id.clone(), method: None, result: msg.result.clone(), @@ -333,7 +407,7 @@ pub(crate) async fn run_reader_loop( // Notification → forward to subscriber let sub = notify_tx.lock().await; if let Some(tx) = sub.as_ref() { - let _ = tx.send(msg); + tx.push(msg); } } @@ -490,8 +564,7 @@ impl AcpConnection { let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let reader_handle = tokio::spawn(run_reader_loop( stdout, @@ -516,6 +589,8 @@ impl AcpConnection { last_active: Instant::now(), activity, session_reset: false, + tail_done: None, + tail_cancel: None, _reader_handle: reader_handle, _stderr_handle: stderr_handle, #[cfg(feature = "acp-mcp")] @@ -604,8 +679,17 @@ impl AcpConnection { } pub async fn session_new(&mut self, cwd: &str) -> Result { + self.session_new_with_meta(cwd, None).await + } + + /// `session/new` with an optional `_meta` object (`[agent].session_new_meta`). + pub async fn session_new_with_meta( + &mut self, + cwd: &str, + meta: Option<&Value>, + ) -> Result { let resp = self - .send_request("session/new", Some(json!({"cwd": cwd, "mcpServers": []}))) + .send_request("session/new", Some(build_session_new_params(cwd, meta))) .await?; let session_id = resp @@ -633,6 +717,28 @@ impl AcpConnection { &mut self, config_id: &str, value: &str, + ) -> Result> { + self.set_config_option_inner(config_id, value, true).await + } + + /// Like [`Self::set_config_option`] but without the slash-command + /// fallback: an error from `session/set_config_option` is returned, and + /// the option list is exactly what the agent reported. Used by + /// `[pool] strict_default_config_options`, where a locally synthesized + /// value must not count as confirmation. + pub async fn set_config_option_reported( + &mut self, + config_id: &str, + value: &str, + ) -> Result> { + self.set_config_option_inner(config_id, value, false).await + } + + async fn set_config_option_inner( + &mut self, + config_id: &str, + value: &str, + allow_fallback: bool, ) -> Result> { let session_id = self .acp_session_id @@ -655,9 +761,13 @@ impl AcpConnection { Ok(r) => { if let Some(result) = r.result.as_ref() { self.config_options = parse_config_options(result); + } else if !allow_fallback { + // Strict path: never compare against pre-switch cached options. + self.config_options.clear(); } info!(config_id, value, "config option set"); } + Err(e) if !allow_fallback => return Err(e), Err(_) => { // Fall back: send as a slash command (e.g. "/model claude-sonnet-4") let cmd = format!("/{config_id} {value}"); @@ -745,8 +855,11 @@ impl AcpConnection { .as_ref() .ok_or_else(|| anyhow!("no session"))?; + // Cancel the previous turn's tail before its subscriber is replaced, so it posts + // nothing from this point on. Its buffered text is discarded. + self.tail_cancel.take(); let (tx, rx) = mpsc::unbounded_channel(); - *self.notify_tx.lock().await = Some(tx); + *self.notify_tx.lock().await = Some(NotifySink::Prompt(tx)); let id = self.next_id(); @@ -770,6 +883,30 @@ impl AcpConnection { Ok((rx, id)) } + /// Like [`Self::prompt_done`] but keeps a subscriber installed so late + /// frames (Kiro workflow output) keep arriving. The foreground `prompt_rx` + /// (from `session_prompt`) is replaced by a bounded relay queue: frames + /// still queued in `prompt_rx` move to the new queue first, under the + /// subscriber lock, so their order is kept. The next `session_prompt` + /// replaces the subscriber, which closes the relay receiver. + pub async fn prompt_done_keep_subscriber( + &mut self, + prompt_rx: &mut mpsc::UnboundedReceiver, + ) -> RelayReceiver { + let (tx, rx) = relay_channel(); + { + let mut sub = self.notify_tx.lock().await; + while let Ok(msg) = prompt_rx.try_recv() { + let _ = tx.send(msg); + } + *sub = Some(NotifySink::Relay(tx)); + } + self.activity.touch(); + self.activity.set_in_flight(false); + self.last_active = Instant::now(); + rx + } + /// Call after prompt streaming is done to clean up subscriber. pub async fn prompt_done(&mut self) { *self.notify_tx.lock().await = None; @@ -1032,11 +1169,10 @@ mod reader_loop_tests { let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let (sub_tx, mut sub_rx) = mpsc::unbounded_channel(); - *notify_tx.lock().await = Some(sub_tx); + *notify_tx.lock().await = Some(NotifySink::Prompt(sub_tx)); let writer = Arc::new(Mutex::new(agent_stdin_writer)); let handle = tokio::spawn(run_reader_loop( @@ -1072,14 +1208,13 @@ mod reader_loop_tests { let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let (resp_tx, resp_rx) = oneshot::channel(); pending.lock().await.insert(7, resp_tx); let (sub_tx, mut sub_rx) = mpsc::unbounded_channel(); - *notify_tx.lock().await = Some(sub_tx); + *notify_tx.lock().await = Some(NotifySink::Prompt(sub_tx)); let writer = Arc::new(Mutex::new(agent_stdin_writer)); let handle = tokio::spawn(run_reader_loop( @@ -1119,8 +1254,7 @@ mod reader_loop_tests { Arc::new(Mutex::new(HashMap::new())); let (resp_tx, mut resp_rx) = oneshot::channel(); pending.lock().await.insert(7, resp_tx); - let notify_tx: Arc>>> = - Arc::new(Mutex::new(None)); + let notify_tx: Arc>> = Arc::new(Mutex::new(None)); let handle = tokio::spawn(run_reader_loop( agent_stdout_reader, @@ -1164,7 +1298,7 @@ mod reader_loop_tests { let (resp_tx, mut resp_rx) = oneshot::channel(); pending.lock().await.insert(u64::MAX, resp_tx); let (sub_tx, mut sub_rx) = mpsc::unbounded_channel(); - let notify_tx = Arc::new(Mutex::new(Some(sub_tx))); + let notify_tx = Arc::new(Mutex::new(Some(NotifySink::Prompt(sub_tx)))); let handle = tokio::spawn(run_reader_loop( agent_stdout_reader, @@ -1344,3 +1478,339 @@ mod reader_loop_tests { assert!(!activity.in_flight()); } } + +/// `sh -c` stand-in for an ACP agent, with fixed request ids +/// (initialize = 1, session/new = 2, first set_config_option = 3, and the +/// slash-command fallback prompt = 4), shared with the pool tests. +#[cfg(all(test, unix))] +pub(crate) mod mock_agent { + /// `set_cfg_reply` is the full JSON-RPC line answering the first + /// `session/set_config_option` (it must contain no single quote). When + /// `require_meta` is set, `session/new` fails unless the request carries + /// `"workflows":{"enabled":true}`. + pub(crate) fn script(set_cfg_reply: &str, require_meta: bool) -> String { + script_with_prompt(set_cfg_reply, require_meta, false) + } + + /// Like [`script`]; `prompt_ok` makes the slash-command fallback prompt + /// (id 4) succeed instead of failing. + pub(crate) fn script_with_prompt( + set_cfg_reply: &str, + require_meta: bool, + prompt_ok: bool, + ) -> String { + let prompt_reply = if prompt_ok { + r#"{"jsonrpc":"2.0","id":4,"result":{"stopReason":"end_turn"}}"# + } else { + r#"{"jsonrpc":"2.0","id":4,"error":{"code":-32000,"message":"unsupported"}}"# + }; + let new_ok = r#"echo '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"s-1"}}'"#; + let new_err = + r#"echo '{"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"missing _meta"}}'"#; + let session_new = if require_meta { + format!( + r#"case "$l" in *'"workflows":{{"enabled":true}}'*) {new_ok};; *) {new_err};; esac"# + ) + } else { + new_ok.to_string() + }; + format!( + r#"while IFS= read -r l; do +case "$l" in +*'"method":"initialize"'*) echo '{{"jsonrpc":"2.0","id":1,"result":{{"agentInfo":{{"name":"mock"}}}}}}';; +*'"method":"session/new"'*) {session_new};; +*'"method":"session/set_config_option"'*) echo '{set_cfg_reply}';; +*'"method":"session/prompt"'*) echo '{prompt_reply}';; +esac +done"# + ) + } + + pub(crate) fn args(script: String) -> Vec { + vec!["-c".to_string(), script] + } + + /// A `set_config_option` reply whose `mode` option reports `current`. + pub(crate) fn mode_reply(current: &str) -> String { + format!( + r#"{{"jsonrpc":"2.0","id":3,"result":{{"configOptions":[{{"type":"select","id":"mode","name":"Mode","currentValue":"{current}","options":[{{"value":"vibe","name":"Default"}},{{"value":"e2e","name":"e2e"}}]}}]}}}}"# + ) + } +} + +#[cfg(test)] +mod workflow_meta_tests { + use super::*; + use crate::acp::protocol::ConfigOptionValue; + + fn opt(id: &str, current: &str, values: &[(&str, &str)]) -> ConfigOption { + ConfigOption { + id: id.into(), + name: id.into(), + description: None, + category: None, + option_type: "select".into(), + current_value: current.into(), + options: values + .iter() + .map(|(value, name)| ConfigOptionValue { + value: (*value).into(), + name: (*name).into(), + description: None, + }) + .collect(), + } + } + + #[test] + fn session_new_params_without_meta_match_legacy_shape() { + assert_eq!( + build_session_new_params("/w", None), + json!({"cwd": "/w", "mcpServers": []}) + ); + } + + #[test] + fn session_new_params_with_meta_carry_underscore_meta() { + let meta = json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); + let params = build_session_new_params("/w", Some(&meta)); + assert_eq!( + params["_meta"]["kiro"]["settings"]["workflows"]["enabled"], + true + ); + assert_eq!(params["cwd"], "/w"); + assert_eq!(params["mcpServers"], json!([])); + } + + #[test] + fn verify_accepts_equal_value() { + let o = [opt("mode", "e2e", &[("vibe", "Default"), ("e2e", "e2e")])]; + assert!(verify_config_option_applied(&o, "mode", "e2e").is_ok()); + } + + #[test] + fn verify_rejects_different_value_with_clear_error() { + let o = [opt("mode", "vibe", &[("vibe", "Default"), ("e2e", "e2e")])]; + let err = verify_config_option_applied(&o, "mode", "e2e").unwrap_err(); + assert!(err.contains("`mode`"), "{err}"); + assert!(err.contains("`e2e`"), "{err}"); + assert!(err.contains("`vibe`"), "{err}"); + assert!(err.contains("was not applied"), "{err}"); + } + + #[test] + fn verify_rejects_missing_option_or_empty_list() { + let err = verify_config_option_applied(&[], "mode", "e2e").unwrap_err(); + assert!(err.contains("did not report the `mode` option"), "{err}"); + let o = [opt("model", "x", &[])]; + let err = verify_config_option_applied(&o, "mode", "e2e").unwrap_err(); + assert!(err.contains("did not report the `mode` option"), "{err}"); + } + + #[test] + fn verify_accepts_alias_by_option_name() { + // agy-acp style: the row name is requested, the id is reported. + let o = [opt( + "model", + "gemini-3.8-flash-high", + &[("gemini-3.8-flash-high", "Gemini 3.8 Flash (High)")], + )]; + assert!(verify_config_option_applied(&o, "model", "Gemini 3.8 Flash (High)").is_ok()); + assert!(verify_config_option_applied(&o, "model", "something-else").is_err()); + } + + #[test] + fn verify_rejects_kiro_v2_agent_option_for_mode_key() { + // kiro v2 reports modes under id `agent`, so `mode` is absent: not verified. + let o = [opt("agent", "kiro_default", &[("kiro_default", "default")])]; + assert!(verify_config_option_applied(&o, "mode", "openab-bot").is_err()); + } + + /// Step sessions ask for permission too; the answer goes out by request id + /// regardless of the `sessionId` the request carries. + #[tokio::test] + async fn permission_request_from_another_session_is_still_answered() { + use tokio::io::{duplex, AsyncWriteExt}; + let (mut agent_out, agent_out_r) = duplex(8 * 1024); + let (agent_in_w, agent_in_r) = duplex(8 * 1024); + let pending = Arc::new(Mutex::new(HashMap::new())); + let notify_tx = Arc::new(Mutex::new(None)); + let handle = tokio::spawn(run_reader_loop( + agent_out_r, + Arc::new(Mutex::new(agent_in_w)), + pending, + notify_tx, + )); + let req = json!({"jsonrpc": "2.0", "id": 9, "method": "session/request_permission", + "params": {"sessionId": "step-session", + "toolCall": {"title": "run"}, + "options": [{"optionId": "ao", "kind": "allow_once"}, + {"optionId": "aa", "kind": "allow_always"}]}}); + agent_out + .write_all(format!("{req}\n").as_bytes()) + .await + .unwrap(); + agent_out.flush().await.unwrap(); + let mut line = String::new(); + tokio::time::timeout( + std::time::Duration::from_secs(2), + BufReader::new(agent_in_r).read_line(&mut line), + ) + .await + .expect("permission request must be answered") + .unwrap(); + let reply: Value = serde_json::from_str(line.trim()).unwrap(); + assert_eq!(reply["id"], 9); + assert_eq!(reply["result"]["outcome"]["optionId"], "aa"); + drop(agent_out); + handle.await.unwrap(); + } + + #[cfg(unix)] + async fn spawn_mock(script: String) -> AcpConnection { + let mut conn = AcpConnection::spawn( + "sh", + &mock_agent::args(script), + "/tmp", + &HashMap::new(), + &[], + ) + .await + .expect("spawn mock agent"); + conn.initialize().await.expect("initialize"); + conn + } + + #[cfg(unix)] + #[tokio::test] + async fn session_new_with_meta_sends_underscore_meta() { + let script = mock_agent::script(&mock_agent::mode_reply("vibe"), true); + let meta = json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); + let mut conn = spawn_mock(script.clone()).await; + assert_eq!( + conn.session_new_with_meta("/tmp", Some(&meta)) + .await + .unwrap(), + "s-1" + ); + // Without meta the mock (which requires it) refuses: nothing is sent. + let mut conn = spawn_mock(script).await; + assert!(conn.session_new("/tmp").await.is_err()); + } + + #[cfg(unix)] + #[tokio::test] + async fn set_config_option_returns_agent_reported_value() { + let script = mock_agent::script(&mock_agent::mode_reply("vibe"), false); + let mut conn = spawn_mock(script).await; + conn.session_new("/tmp").await.unwrap(); + let opts = conn.set_config_option("mode", "e2e").await.unwrap(); + assert!(verify_config_option_applied(&opts, "mode", "e2e").is_err()); + } + + /// Mock agent for the subscriber hand-off: each `session/prompt` is answered + /// by a response (ids 3, 4, ...) followed by a late `agent_message_chunk` + /// of the parent session `s-1` ("late-"). + #[cfg(unix)] + fn late_chunk_script() -> String { + r#"n=3 +while IFS= read -r l; do +case "$l" in +*'"method":"initialize"'*) echo '{"jsonrpc":"2.0","id":1,"result":{"agentInfo":{"name":"mock"}}}';; +*'"method":"session/new"'*) echo '{"jsonrpc":"2.0","id":2,"result":{"sessionId":"s-1"}}';; +*'"method":"session/prompt"'*) +echo '{"jsonrpc":"2.0","id":'$n',"result":{"stopReason":"end_turn"}}' +echo '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late-'$n'"}}}}' +n=$((n+1));; +esac +done"# + .to_string() + } + + /// The next `session_prompt` cancels the running tail: it posts nothing, + /// its buffered text is discarded, and the new receiver sees only the new + /// turn's frames. + #[cfg(unix)] + #[tokio::test] + async fn next_prompt_replaces_subscriber_and_ends_the_tail() { + use super::ContentBlock; + use crate::workflow_tail::{run_tail, TailControl, WorkflowRelayConfig}; + use std::time::Duration; + + let mut conn = spawn_mock(late_chunk_script()).await; + conn.session_new("/tmp").await.unwrap(); + + let (mut prompt_rx, id1) = conn + .session_prompt(vec![ContentBlock::Text { text: "one".into() }]) + .await + .unwrap(); + loop { + let m = tokio::time::timeout(Duration::from_secs(5), prompt_rx.recv()) + .await + .expect("response") + .expect("open"); + if m.id.as_ref().and_then(|i| i.as_u64()) == Some(id1) { + break; + } + } + let rx1 = conn.prompt_done_keep_subscriber(&mut prompt_rx).await; + + let out = Arc::new(std::sync::Mutex::new(Vec::::new())); + let sink = out.clone(); + let (gate_tx, gate_rx) = tokio::sync::oneshot::channel(); + gate_tx.send(()).unwrap(); + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); + conn.tail_cancel = Some(cancel_tx); + let tail = tokio::spawn(run_tail( + rx1, + "s-1".to_string(), + ["wf".to_string()].into_iter().collect(), + WorkflowRelayConfig { + tail_quiet: Duration::from_secs(60), + tail_max: Duration::from_secs(60), + }, + tokio::time::Instant::now(), + TailControl { + gate: gate_rx, + cancel: cancel_rx, + }, + move |t| { + sink.lock().unwrap().push(t); + std::future::ready(()) + }, + )); + // Let late-3 reach the tail's buffer before the cancel. The assertion + // below holds whether or not it got there. + tokio::time::sleep(Duration::from_millis(500)).await; + + let (mut rx2, id2) = conn + .session_prompt(vec![ContentBlock::Text { text: "two".into() }]) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), tail) + .await + .expect("tail must end when the next prompt cancels it") + .unwrap(); + assert!( + out.lock().unwrap().is_empty(), + "a cancelled tail posts nothing" + ); + + let mut texts = Vec::new(); + let mut got_response = false; + while !(got_response && !texts.is_empty()) { + let m = tokio::time::timeout(Duration::from_secs(5), rx2.recv()) + .await + .expect("frame") + .expect("open"); + if m.id.as_ref().and_then(|i| i.as_u64()) == Some(id2) { + got_response = true; + } else if let Some(crate::acp::AcpEvent::Text(t)) = + crate::acp::classify_notification(&m) + { + texts.push(t); + } + } + assert_eq!(texts, vec!["late-4".to_string()]); + } +} diff --git a/crates/openab-core/src/acp/mod.rs b/crates/openab-core/src/acp/mod.rs index 7919c6d3d..0972ae731 100644 --- a/crates/openab-core/src/acp/mod.rs +++ b/crates/openab-core/src/acp/mod.rs @@ -6,4 +6,7 @@ pub mod protocol; pub use connection::ContentBlock; pub use pool::SessionPool; -pub use protocol::{classify_notification, parse_turn_result, AcpEvent, TurnResult}; +pub use protocol::{ + classify_notification, classify_workflow_signal, is_foreign_session_update, parse_turn_result, + AcpEvent, TurnResult, WorkflowSignal, +}; diff --git a/crates/openab-core/src/acp/pool.rs b/crates/openab-core/src/acp/pool.rs index a3a28f87c..f8d6d679c 100644 --- a/crates/openab-core/src/acp/pool.rs +++ b/crates/openab-core/src/acp/pool.rs @@ -63,6 +63,8 @@ pub struct SessionPool { mapping_path: PathBuf, meta_path: PathBuf, default_config_options: HashMap, + /// Fail session creation when a default config option is not applied. + strict_default_config_options: bool, #[cfg(feature = "acp-mcp")] session_registrar: Option>, #[cfg(feature = "acp-mcp")] @@ -334,6 +336,7 @@ impl SessionPool { mapping_path, meta_path, default_config_options, + strict_default_config_options: false, #[cfg(feature = "acp-mcp")] session_registrar: None, #[cfg(feature = "acp-mcp")] @@ -341,6 +344,18 @@ impl SessionPool { } } + /// Verify `default_config_options` after `session/set_config_option` + /// (`[pool] strict_default_config_options`). Default: off. + pub fn with_strict_default_config_options(mut self, strict: bool) -> Self { + self.strict_default_config_options = strict; + self + } + + /// True when `[agent].session_new_meta` enables Kiro workflows. + pub fn workflows_enabled(&self) -> bool { + crate::config::meta_enables_workflows(self.config.session_new_meta.as_ref()) + } + /// Wire the facade session-token registrar + facade URL, set by the root /// when `[mcp]` is running. With both present the pool does its half: mints /// one token per session, injects it as `OPENAB_SESSION_TOKEN` in the agent @@ -627,12 +642,37 @@ impl SessionPool { } if !resumed { - new_conn.session_new(&effective_workdir).await?; + new_conn + .session_new_with_meta(&effective_workdir, self.config.session_new_meta.as_ref()) + .await?; // Apply default config options (e.g. mode=bypass, model=swe-1-6) for (config_id, value) in &self.default_config_options { - if let Err(e) = new_conn.set_config_option(config_id, value).await { - warn!(config_id, value, error = %e, "failed to set default config option"); + let result = if self.strict_default_config_options { + // No slash-command fallback: only a value the agent + // reports counts as applied. + new_conn.set_config_option_reported(config_id, value).await + } else { + new_conn.set_config_option(config_id, value).await + }; + match result { + Ok(opts) => { + if self.strict_default_config_options { + // Returning drops `new_conn`, which kills the agent process group. + super::connection::verify_config_option_applied( + &opts, config_id, value, + ) + .map_err(|msg| anyhow!(msg))?; + } + } + Err(e) => { + if self.strict_default_config_options { + return Err(anyhow!( + "failed to set default config option `{config_id}`: {e}" + )); + } + warn!(config_id, value, error = %e, "failed to set default config option"); + } } } @@ -1559,3 +1599,171 @@ mod tests { ); } } + +#[cfg(all(test, unix))] +mod config_option_tests { + use super::SessionPool; + use crate::acp::connection::mock_agent; + use crate::config::AgentConfig; + use std::collections::HashMap; + + fn pool( + dir: &std::path::Path, + set_cfg_reply: &str, + require_meta: bool, + meta: Option, + strict: bool, + ) -> SessionPool { + pool_with_prompt(dir, set_cfg_reply, require_meta, meta, strict, false) + } + + fn pool_with_prompt( + dir: &std::path::Path, + set_cfg_reply: &str, + require_meta: bool, + meta: Option, + strict: bool, + prompt_ok: bool, + ) -> SessionPool { + let agent = AgentConfig { + command: "sh".into(), + args: mock_agent::args(mock_agent::script_with_prompt( + set_cfg_reply, + require_meta, + prompt_ok, + )), + working_dir: "/tmp".into(), + env: HashMap::new(), + inherit_env: vec![], + command_explicit: true, + session_new_meta: meta, + }; + SessionPool::new_in( + agent, + 1, + 60, + HashMap::from([("mode".to_string(), "e2e".to_string())]), + dir.to_path_buf(), + ) + .with_strict_default_config_options(strict) + } + + #[tokio::test] + async fn mismatch_is_ignored_by_default() { + let dir = tempfile::tempdir().unwrap(); + let p = pool( + dir.path(), + &mock_agent::mode_reply("vibe"), + false, + None, + false, + ); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn strict_mismatch_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let p = pool( + dir.path(), + &mock_agent::mode_reply("vibe"), + false, + None, + true, + ); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("was not applied"), "{err}"); + assert!(err.contains("`e2e`") && err.contains("`vibe`"), "{err}"); + assert!(p.state.read().await.active.is_empty()); + } + + #[tokio::test] + async fn strict_match_succeeds() { + let dir = tempfile::tempdir().unwrap(); + let p = pool( + dir.path(), + &mock_agent::mode_reply("e2e"), + false, + None, + true, + ); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn strict_response_without_options_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; + let p = pool(dir.path(), reply, false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("did not report the `mode` option"), "{err}"); + assert!(p.state.read().await.active.is_empty()); + } + + #[tokio::test] + async fn strict_response_lacking_the_requested_option_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"result":{"configOptions":[{"type":"select","id":"model","name":"Model","currentValue":"x","options":[]}]}}"#; + let p = pool(dir.path(), reply, false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("did not report the `mode` option"), "{err}"); + } + + #[tokio::test] + async fn non_strict_response_without_options_is_accepted() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"result":{}}"#; + let p = pool(dir.path(), reply, false, None, false); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn strict_error_response_fails_session_creation() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; + let p = pool(dir.path(), reply, false, None, true); + let err = p.get_or_create("t", None).await.unwrap_err().to_string(); + assert!(err.contains("failed to set default config option"), "{err}"); + } + + #[tokio::test] + async fn non_strict_error_response_is_only_a_warning() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; + let p = pool(dir.path(), reply, false, None, false); + assert!(p.get_or_create("t", None).await.is_ok()); + } + + #[tokio::test] + async fn session_new_meta_is_sent_when_configured() { + let dir = tempfile::tempdir().unwrap(); + let meta = serde_json::json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}); + let reply = mock_agent::mode_reply("e2e"); + // The mock refuses session/new without the meta. + let with = pool(dir.path(), &reply, true, Some(meta), true); + assert!(with.workflows_enabled()); + assert!(with.get_or_create("t", None).await.is_ok()); + let dir2 = tempfile::tempdir().unwrap(); + let without = pool(dir2.path(), &reply, true, None, true); + assert!(!without.workflows_enabled()); + assert!(without.get_or_create("t", None).await.is_err()); + } + + #[tokio::test] + async fn strict_error_is_not_masked_by_a_successful_slash_fallback() { + let dir = tempfile::tempdir().unwrap(); + let reply = r#"{"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"bad"}}"#; + // The fallback prompt (id 4) succeeds, yet strict mode must still fail. + let strict = pool_with_prompt(dir.path(), reply, false, None, true, true); + let err = strict + .get_or_create("t", None) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("failed to set default config option"), "{err}"); + // Non-strict keeps the legacy fallback behaviour. + let dir2 = tempfile::tempdir().unwrap(); + let lenient = pool_with_prompt(dir2.path(), reply, false, None, false, true); + assert!(lenient.get_or_create("t", None).await.is_ok()); + } +} diff --git a/crates/openab-core/src/acp/protocol.rs b/crates/openab-core/src/acp/protocol.rs index 456245cae..88d3733f0 100644 --- a/crates/openab-core/src/acp/protocol.rs +++ b/crates/openab-core/src/acp/protocol.rs @@ -409,6 +409,51 @@ pub enum AcpEvent { Status, } +/// True for a `session/update` notification whose `params.sessionId` is not the +/// string `expected_session_id`. Such frames come from another session of the +/// same agent process (e.g. Kiro workflow step sessions), or cannot be tied to +/// the served session: a missing, null or non-string `sessionId` also counts. +/// Other methods and responses are never foreign. +pub fn is_foreign_session_update(msg: &JsonRpcMessage, expected_session_id: &str) -> bool { + if msg.id.is_some() || msg.method.as_deref() != Some("session/update") { + return false; + } + let session_id = msg + .params + .as_ref() + .and_then(|p| p.get("sessionId")) + .and_then(Value::as_str); + session_id != Some(expected_session_id) +} + +/// Kiro workflow lifecycle signal relevant to the served (parent) session. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WorkflowSignal { + RunStart { workflow_id: String }, + RunComplete { workflow_id: String }, +} + +/// Classify `_kiro/workflow/run_start` (only when its `parentSessionId` is +/// `parent_session_id`) and `_kiro/workflow/run_complete` notifications. +pub fn classify_workflow_signal( + msg: &JsonRpcMessage, + parent_session_id: &str, +) -> Option { + if msg.id.is_some() { + return None; + } + let params = msg.params.as_ref()?; + let workflow_id = params.get("workflowId")?.as_str()?.to_string(); + match msg.method.as_deref()? { + "_kiro/workflow/run_start" => { + let parent = params.get("parentSessionId")?.as_str()?; + (parent == parent_session_id).then_some(WorkflowSignal::RunStart { workflow_id }) + } + "_kiro/workflow/run_complete" => Some(WorkflowSignal::RunComplete { workflow_id }), + _ => None, + } +} + pub fn classify_notification(msg: &JsonRpcMessage) -> Option { let params = msg.params.as_ref()?; let update = params.get("update")?; @@ -476,6 +521,66 @@ mod tests { use super::*; use serde_json::json; + fn msg(v: Value) -> JsonRpcMessage { + serde_json::from_value(v).unwrap() + } + + fn chunk(session_id: Option<&str>, text: &str) -> JsonRpcMessage { + let mut params = json!({"update": {"sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": text}}}); + if let Some(sid) = session_id { + params["sessionId"] = json!(sid); + } + msg(json!({"jsonrpc": "2.0", "method": "session/update", "params": params})) + } + + #[test] + fn foreign_session_update_detection() { + assert!(!is_foreign_session_update(&chunk(Some("p"), "x"), "p")); + assert!(is_foreign_session_update(&chunk(Some("step"), "x"), "p")); + // A frame that cannot be tied to the parent session is not parent traffic. + assert!(is_foreign_session_update(&chunk(None, "x"), "p")); + let null_id = msg(json!({"method": "session/update", + "params": {"sessionId": null, "update": {}}})); + assert!(is_foreign_session_update(&null_id, "p")); + let numeric_id = msg(json!({"method": "session/update", + "params": {"sessionId": 7, "update": {}}})); + assert!(is_foreign_session_update(&numeric_id, "p")); + let no_params = msg(json!({"method": "session/update"})); + assert!(is_foreign_session_update(&no_params, "p")); + let other_method = msg(json!({"method": "_kiro/other", + "params": {"sessionId": "step"}})); + assert!(!is_foreign_session_update(&other_method, "p")); + let response = msg(json!({"id": 3, "result": {"sessionId": "step"}})); + assert!(!is_foreign_session_update(&response, "p")); + } + + #[test] + fn workflow_signal_classification() { + let start = msg( + json!({"jsonrpc": "2.0", "method": "_kiro/workflow/run_start", + "params": {"workflowId": "wf_1", "workflowName": "w", "parentSessionId": "p"}}), + ); + assert_eq!( + classify_workflow_signal(&start, "p"), + Some(WorkflowSignal::RunStart { + workflow_id: "wf_1".into() + }) + ); + assert_eq!(classify_workflow_signal(&start, "other"), None); + let done = msg(json!({"method": "_kiro/workflow/run_complete", + "params": {"workflowId": "wf_1", "status": "completed"}})); + assert_eq!( + classify_workflow_signal(&done, "p"), + Some(WorkflowSignal::RunComplete { + workflow_id: "wf_1".into() + }) + ); + let unrelated = msg(json!({"method": "_kiro/workflow/node_start", + "params": {"workflowId": "wf_1"}})); + assert_eq!(classify_workflow_signal(&unrelated, "p"), None); + } + #[test] fn json_rpc_ids_preserve_all_supported_integer_ranges() { for value in [0, i64::MAX as u64, (i64::MAX as u64) + 1, u64::MAX] { diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 7d9841070..e4a0d23c5 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -5,7 +5,8 @@ use std::sync::Arc; use tracing::{error, warn}; use crate::acp::{ - classify_notification, parse_turn_result, AcpEvent, ContentBlock, SessionPool, TurnResult, + classify_notification, is_foreign_session_update, parse_turn_result, AcpEvent, ContentBlock, + SessionPool, TurnResult, }; use crate::config::{ReactionsConfig, ToolDisplay}; use crate::error_display::{format_coded_error, format_user_error}; @@ -490,6 +491,10 @@ pub struct AdapterRouter { /// [`AdapterRouter::with_trust`]; empty default = deny-all per platform /// (only consulted by paths wired to the gate — currently the gateway path). trust: crate::trust::PlatformTrustConfigs, + /// Set only when `[agent].session_new_meta` enables Kiro workflows. Turns on + /// the step-session frame filter and, unless `tail_max` is zero, the relay + /// of late workflow output. `None` = legacy behaviour. + workflow_relay: Option, } impl AdapterRouter { @@ -520,9 +525,18 @@ impl AdapterRouter { workspace_aliases, bot_home, trust: crate::trust::PlatformTrustConfigs::default(), + workflow_relay: None, } } + /// Enable Kiro workflow handling (builder style, before `Arc`-wrapping): + /// drop `session/update` frames of other sessions and relay late workflow + /// output. Only call when workflows are enabled in `session/new` meta. + pub fn with_workflow_relay(mut self, cfg: crate::workflow_tail::WorkflowRelayConfig) -> Self { + self.workflow_relay = Some(cfg); + self + } + /// Attach the per-platform trust registry (builder style, before `Arc`-wrapping). /// Keeps `new()`'s signature stable across its many call sites. pub fn with_trust(mut self, trust: crate::trust::PlatformTrustConfigs) -> Self { @@ -759,6 +773,7 @@ impl AdapterRouter { let platform_is_acp = thread_channel.platform == "acp"; let prompt_hard_timeout = self.prompt_hard_timeout; let liveness_check_interval = self.liveness_check_interval; + let relay = self.workflow_relay; self.pool .with_connection(thread_key, |conn| { @@ -768,6 +783,13 @@ impl AdapterRouter { conn.session_reset = false; let (mut rx, request_id) = conn.session_prompt(content_blocks).await?; + // This prompt cancelled the previous turn's tail (see + // `session_prompt`). Let its final post, if any, land before this reply. + if let Some(done) = conn.tail_done.take() { + crate::workflow_tail::wait_for_previous_tail(done).await; + } + let parent_sid = conn.acp_session_id.clone(); + let mut wf_state = crate::workflow_tail::TurnWorkflowState::default(); if assistant_status { let _ = adapter.set_status(&thread_channel, "Thinking…").await; } else { @@ -897,6 +919,15 @@ impl AdapterRouter { break; } + if let (Some(_), Some(sid)) = (relay, parent_sid.as_deref()) { + // Workflow step sessions share this agent process; their + // frames must not reach the parent's reply. + if is_foreign_session_update(¬ification, sid) { + continue; + } + wf_state.observe(¬ification, sid); + } + if let Some(event) = classify_notification(¬ification) { match event { AcpEvent::Text(t) => { @@ -1039,7 +1070,64 @@ impl AdapterRouter { } } - conn.prompt_done().await; + // Late workflow output: keep the subscriber and hand the + // receiver to a detached tail after the reply is delivered. + let tail_cfg = relay.filter(|c| { + !c.tail_max.is_zero() + && response_error.is_none() + && !platform_is_acp + && wf_state.armed() + }); + let tail_started = tokio::time::Instant::now(); + // Hand the receiver to the tail right away so it drains + // frames while the original reply is finalized; it posts + // only after `gate_tx` fires below. + let tail_rx = if tail_cfg.is_some() { + Some(conn.prompt_done_keep_subscriber(&mut rx).await) + } else { + conn.prompt_done().await; + None + }; + let mut gate_tx = None; + if let (Some(cfg), Some(rx), Some(sid)) = (tail_cfg, tail_rx, parent_sid) { + let (g_tx, gate_rx) = tokio::sync::oneshot::channel::<()>(); + gate_tx = Some(g_tx); + // Dropping `cancel_tx` (next prompt or connection teardown) cancels the tail. + let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel::<()>(); + conn.tail_cancel = Some(cancel_tx); + let tail_adapter = adapter.clone(); + let tail_channel = thread_channel.clone(); + conn.tail_done = Some(crate::workflow_tail::spawn_tail( + rx, + sid, + std::mem::take(&mut wf_state).into_open(), + cfg, + tail_started, + crate::workflow_tail::TailControl { + gate: gate_rx, + cancel: cancel_rx, + }, + move |text| { + let adapter = tail_adapter.clone(); + let channel = tail_channel.clone(); + async move { + let text = format!("_Workflow update:_\n\n{text}"); + let chunks = crate::workflow_tail::limit_flush_messages( + format::split_message(&text, message_limit), + crate::workflow_tail::MAX_FLUSH_MESSAGES, + crate::workflow_tail::TRUNCATED_NOTE, + ); + for chunk in chunks { + if let Err(e) = adapter.send_message(&channel, &chunk).await + { + warn!(error = ?e, "workflow tail delivery failed"); + break; + } + } + } + }, + )); + } // Stop the cosmetic edit loop and let any in-flight edit // finish before the authoritative finalize write, so in the // normal case a stale preview does not overwrite it. Dropping @@ -1303,6 +1391,11 @@ impl AdapterRouter { } } + // Original reply is out: let the tail start posting. + if let Some(g) = gate_tx.take() { + let _ = g.send(()); + } + if delivery_failed { Err(anyhow::anyhow!( "streaming finalization had delivery failures; user view is incomplete" diff --git a/crates/openab-core/src/config.rs b/crates/openab-core/src/config.rs index fdd89dcb3..e9062eb3f 100644 --- a/crates/openab-core/src/config.rs +++ b/crates/openab-core/src/config.rs @@ -1668,6 +1668,7 @@ struct AgentConfigRaw { working_dir: String, env: HashMap, inherit_env: Vec, + session_new_meta: Option, } impl Default for AgentConfigRaw { @@ -1678,6 +1679,7 @@ impl Default for AgentConfigRaw { working_dir: default_working_dir(), env: HashMap::new(), inherit_env: Vec::new(), + session_new_meta: None, } } } @@ -1691,6 +1693,18 @@ pub struct AgentConfig { pub inherit_env: Vec, /// Whether the command was explicitly set in config (vs defaulted from env/fallback). pub command_explicit: bool, + /// Optional `_meta` object sent verbatim in every `session/new` request. + /// Default: none (nothing is added to the request). Example for kiro-cli v3: + /// `{ kiro = { settings = { workflows = { enabled = true } } } }`. + pub session_new_meta: Option, +} + +/// True when `meta` (the `[agent].session_new_meta` table) switches on Kiro +/// workflows (`kiro.settings.workflows.enabled = true`). +pub fn meta_enables_workflows(meta: Option<&serde_json::Value>) -> bool { + meta.and_then(|m| m.pointer("/kiro/settings/workflows/enabled")) + .and_then(serde_json::Value::as_bool) + == Some(true) } impl Default for AgentConfig { @@ -1702,6 +1716,7 @@ impl Default for AgentConfig { env: HashMap::new(), inherit_env: Vec::new(), command_explicit: false, + session_new_meta: None, } } } @@ -1721,6 +1736,13 @@ impl<'de> serde::Deserialize<'de> for AgentConfig { (true, None) => Vec::new(), // command set, args omitted → empty (false, None) => default_agent_args(), // neither set → env var }; + if let Some(meta) = &raw.session_new_meta { + if !meta.is_object() { + return Err(serde::de::Error::custom( + "[agent].session_new_meta must be a table", + )); + } + } Ok(AgentConfig { command, args, @@ -1728,6 +1750,7 @@ impl<'de> serde::Deserialize<'de> for AgentConfig { env: raw.env, inherit_env: raw.inherit_env, command_explicit: cmd_explicit, + session_new_meta: raw.session_new_meta, }) } } @@ -1762,6 +1785,28 @@ pub struct PoolConfig { /// Sent via `session/set_config_option` after each `session/new`. #[serde(default)] pub default_config_options: HashMap, + /// When true, `default_config_options` entries are verified: after each + /// `session/set_config_option` the returned `currentValue` must equal the + /// requested value (or be the value behind a matching option name), else + /// session creation fails. Default false (legacy: mismatches are ignored). + #[serde(default)] + pub strict_default_config_options: bool, + /// Seconds without agent output after which late workflow output is + /// flushed to the thread (only with `[agent].session_new_meta` enabling + /// Kiro workflows). Must be > 0 when `workflow_tail_max_secs` > 0. + #[serde(default = "default_workflow_tail_quiet_secs")] + pub workflow_tail_quiet_secs: u64, + /// Hard cap (seconds, from the prompt response) on how long openab keeps + /// relaying late workflow output. 0 disables the relay. + #[serde(default = "default_workflow_tail_max_secs")] + pub workflow_tail_max_secs: u64, +} + +fn default_workflow_tail_quiet_secs() -> u64 { + 20 +} +fn default_workflow_tail_max_secs() -> u64 { + 900 } #[derive(Debug, Clone, Deserialize)] @@ -1994,6 +2039,9 @@ impl Default for PoolConfig { liveness_check_secs: default_liveness_check_secs(), hung_grace_secs: default_hung_grace_secs(), default_config_options: HashMap::new(), + strict_default_config_options: false, + workflow_tail_quiet_secs: default_workflow_tail_quiet_secs(), + workflow_tail_max_secs: default_workflow_tail_max_secs(), } } } @@ -2307,10 +2355,16 @@ fn parse_config_inner(expanded: &str, source: &str) -> anyhow::Result { env: config.agent.env.clone(), inherit_env: config.agent.inherit_env.clone(), command_explicit: true, // synthesized counts as explicit + session_new_meta: config.agent.session_new_meta.clone(), }; } } + anyhow::ensure!( + config.pool.workflow_tail_max_secs == 0 || config.pool.workflow_tail_quiet_secs > 0, + "pool.workflow_tail_quiet_secs must be > 0 when pool.workflow_tail_max_secs > 0" + ); + // Validate max_buffered_messages > 0 (tokio::sync::mpsc::channel panics on 0) // and max_batch_tokens > 0 (otherwise the consumer's token-cap check forces every // batch to size 1 — functionally per-message via a confusing path). @@ -2502,6 +2556,78 @@ fn default_ambient_context_flushes() -> usize { mod tests { use super::*; + const DISCORD_STUB: &str = "[discord]\nbot_token = \"x\"\n"; + + #[test] + fn session_new_meta_defaults_to_none() { + let cfg = parse_config_str(DISCORD_STUB, "test").unwrap(); + assert!(cfg.agent.session_new_meta.is_none()); + assert!(!meta_enables_workflows(cfg.agent.session_new_meta.as_ref())); + } + + #[test] + fn session_new_meta_table_parses() { + let toml_str = format!( + "{DISCORD_STUB}[agent]\ncommand = \"kiro-cli\"\n\ + session_new_meta = {{ kiro = {{ settings = {{ workflows = {{ enabled = true }} }} }} }}\n" + ); + let cfg = parse_config_str(&toml_str, "test").unwrap(); + assert_eq!( + cfg.agent.session_new_meta, + Some(serde_json::json!({"kiro": {"settings": {"workflows": {"enabled": true}}}})) + ); + assert!(meta_enables_workflows(cfg.agent.session_new_meta.as_ref())); + } + + #[test] + fn session_new_meta_must_be_a_table() { + let toml_str = format!("{DISCORD_STUB}[agent]\nsession_new_meta = \"x\"\n"); + let err = parse_config_str(&toml_str, "test").unwrap_err(); + assert!(format!("{err:#}").contains("session_new_meta must be a table")); + } + + #[test] + fn meta_enables_workflows_requires_boolean_true() { + use serde_json::json; + assert!(meta_enables_workflows(Some( + &json!({"kiro": {"settings": {"workflows": {"enabled": true}}}}) + ))); + assert!(!meta_enables_workflows(Some( + &json!({"kiro": {"settings": {"workflows": {"enabled": false}}}}) + ))); + assert!(!meta_enables_workflows(Some( + &json!({"kiro": {"settings": {"workflows": {"enabled": "true"}}}}) + ))); + assert!(!meta_enables_workflows(Some(&json!({"other": 1})))); + assert!(!meta_enables_workflows(None)); + } + + #[test] + fn pool_workflow_and_strict_defaults() { + let cfg = parse_config_str(DISCORD_STUB, "test").unwrap(); + assert!(!cfg.pool.strict_default_config_options); + assert_eq!(cfg.pool.workflow_tail_quiet_secs, 20); + assert_eq!(cfg.pool.workflow_tail_max_secs, 900); + let toml_str = format!( + "{DISCORD_STUB}[pool]\nstrict_default_config_options = true\n\ + workflow_tail_quiet_secs = 5\nworkflow_tail_max_secs = 60\n" + ); + let cfg = parse_config_str(&toml_str, "test").unwrap(); + assert!(cfg.pool.strict_default_config_options); + assert_eq!(cfg.pool.workflow_tail_quiet_secs, 5); + assert_eq!(cfg.pool.workflow_tail_max_secs, 60); + } + + #[test] + fn workflow_tail_quiet_zero_is_rejected_unless_tail_disabled() { + let bad = format!("{DISCORD_STUB}[pool]\nworkflow_tail_quiet_secs = 0\n"); + assert!(parse_config_str(&bad, "test").is_err()); + let ok = format!( + "{DISCORD_STUB}[pool]\nworkflow_tail_quiet_secs = 0\nworkflow_tail_max_secs = 0\n" + ); + assert!(parse_config_str(&ok, "test").is_ok()); + } + #[test] fn mcp_facade_absent_by_default() { // Backward compat: no [mcp] section → no facade, no listener. diff --git a/crates/openab-core/src/dispatch.rs b/crates/openab-core/src/dispatch.rs index c3a20d263..d405287db 100644 --- a/crates/openab-core/src/dispatch.rs +++ b/crates/openab-core/src/dispatch.rs @@ -1197,6 +1197,7 @@ mod tests { env: std::collections::HashMap::new(), inherit_env: vec![], command_explicit: true, + session_new_meta: None, }; let pool = Arc::new(SessionPool::new( agent_cfg, diff --git a/crates/openab-core/src/lib.rs b/crates/openab-core/src/lib.rs index 0e61e7cb2..7c226f40c 100644 --- a/crates/openab-core/src/lib.rs +++ b/crates/openab-core/src/lib.rs @@ -27,6 +27,7 @@ pub mod setup; pub mod stt; pub mod timestamp; pub mod trust; +pub mod workflow_tail; #[cfg(feature = "discord")] pub mod discord; diff --git a/crates/openab-core/src/workflow_tail.rs b/crates/openab-core/src/workflow_tail.rs new file mode 100644 index 000000000..4a36b404a --- /dev/null +++ b/crates/openab-core/src/workflow_tail.rs @@ -0,0 +1,1177 @@ +//! Relay of late Kiro workflow output. +//! +//! With `[agent].session_new_meta` enabling Kiro workflows, `session/prompt` +//! can return before a workflow finishes. The workflow's summary then arrives +//! later as unsolicited `agent_message_chunk` frames of the parent session +//! (no request id). The adapter keeps the notify receiver after the reply is +//! delivered and hands it to [`run_tail`], which buffers that text and posts +//! it as a follow-up message. +//! +//! The tail holds no connection lock. The connection cancels the tail before +//! the next prompt on the same session replaces the subscriber, and when the +//! connection is torn down (see [`TailControl`]). A cancelled tail discards +//! its buffered text and posts nothing more. + +use crate::acp::protocol::JsonRpcMessage; +use crate::acp::{ + classify_notification, classify_workflow_signal, is_foreign_session_update, AcpEvent, + WorkflowSignal, +}; +use std::collections::HashSet; +use std::future::Future; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::mpsc::{self, error::TrySendError}; +use tokio::sync::oneshot; +use tokio::time::{sleep_until, timeout_at, Instant}; + +/// Bounds for the late-output relay (`[pool] workflow_tail_*`). +#[derive(Debug, Clone, Copy)] +pub struct WorkflowRelayConfig { + /// Flush buffered text after this long without relevant frames. + pub tail_quiet: Duration, + /// Hard cap from the prompt response. Zero disables the relay (the + /// session-id filter stays on). + pub tail_max: Duration, +} + +/// Workflow bookkeeping for one turn, fed with every frame of the turn. +#[derive(Debug, Default)] +pub struct TurnWorkflowState { + open: HashSet, + seen: bool, +} + +impl TurnWorkflowState { + pub fn observe(&mut self, msg: &JsonRpcMessage, parent_session_id: &str) { + match classify_workflow_signal(msg, parent_session_id) { + Some(WorkflowSignal::RunStart { workflow_id }) => { + self.seen = true; + self.open.insert(workflow_id); + } + Some(WorkflowSignal::RunComplete { workflow_id }) => { + self.open.remove(&workflow_id); + } + None => {} + } + } + + /// A workflow started for this session during the turn. + pub fn armed(&self) -> bool { + self.seen + } + + pub fn into_open(self) -> HashSet { + self.open + } +} + +/// Most frames queued between the connection reader and the tail. A full queue +/// drops the newest frame and marks the next flush as truncated. +pub const RELAY_QUEUE_CAPACITY: usize = 1024; + +/// Producer side of the relay queue. `send` never waits. +#[derive(Debug, Clone)] +pub struct RelaySender { + tx: mpsc::Sender, + overflow: Arc, +} + +/// A frame was not queued: the queue was full or the tail has ended. +#[derive(Debug)] +pub struct RelayDropped; + +impl RelaySender { + pub fn send(&self, msg: JsonRpcMessage) -> Result<(), RelayDropped> { + match self.tx.try_send(msg) { + Ok(()) => Ok(()), + Err(TrySendError::Full(_)) => { + self.overflow.store(true, Ordering::Relaxed); + Err(RelayDropped) + } + Err(TrySendError::Closed(_)) => Err(RelayDropped), + } + } +} + +/// Consumer side of the relay queue, read by [`run_tail`]. +#[derive(Debug)] +pub struct RelayReceiver { + rx: mpsc::Receiver, + overflow: Arc, +} + +impl RelayReceiver { + pub async fn recv(&mut self) -> Option { + self.rx.recv().await + } + + pub fn try_recv(&mut self) -> Option { + self.rx.try_recv().ok() + } + + /// True once if a frame was dropped on a full queue since the last call. + fn take_overflow(&self) -> bool { + self.overflow.swap(false, Ordering::Relaxed) + } +} + +/// A bounded relay queue of [`RELAY_QUEUE_CAPACITY`] frames. +pub fn relay_channel() -> (RelaySender, RelayReceiver) { + let (tx, rx) = mpsc::channel(RELAY_QUEUE_CAPACITY); + let overflow = Arc::new(AtomicBool::new(false)); + ( + RelaySender { + tx, + overflow: overflow.clone(), + }, + RelayReceiver { rx, overflow }, + ) +} + +/// Most text the tail buffers between flushes. Further text is dropped and a +/// truncation note is appended to the flushed message. +pub const MAX_BUFFER_BYTES: usize = 256 * 1024; + +/// Bound on one `deliver` call, so a stalled platform call cannot keep the +/// tail (and its deadline checks) blocked. +pub const DELIVER_TIMEOUT: Duration = Duration::from_secs(30); + +/// Most platform messages one late-output flush may post. When the text needs +/// more, the last message is [`TRUNCATED_NOTE`] and the rest is not posted. +pub const MAX_FLUSH_MESSAGES: usize = 16; + +/// Posted in place of the chunks that do not fit into [`MAX_FLUSH_MESSAGES`]. +pub const TRUNCATED_NOTE: &str = "…(output truncated: this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed)"; + +/// Apply the per-flush message cap to already platform-split `chunks`. The +/// note takes the last slot, so it is always posted when anything is dropped. +pub fn limit_flush_messages(mut chunks: Vec, max: usize, note: &str) -> Vec { + if chunks.len() <= max { + return chunks; + } + chunks.truncate(max.saturating_sub(1)); + chunks.push(note.to_string()); + chunks +} + +/// Gate and cancel signals of one tail. +/// +/// `gate` resolves once the original reply has been delivered. `cancel` ends +/// the tail: it is cancelled when its sender is dropped, which the connection +/// does before the next prompt on the session and on teardown. Both a sent +/// value and a dropped sender count as a signal for `cancel`, and a dropped +/// `gate` counts as open. +pub struct TailControl { + pub gate: oneshot::Receiver<()>, + pub cancel: oneshot::Receiver<()>, +} + +/// Read late frames from `rx` and hand text to `deliver`. +/// +/// `started` is when the prompt response arrived: the hard cap is measured +/// from it, not from when this task starts. The tail starts draining `rx` +/// immediately (so the queue does not grow while the reply is finalized) but +/// posts nothing before `control.gate` opens. +/// +/// Quiet time only decides when buffered text is posted. The tail does not end +/// on quiet, so output that arrives after a gap is still delivered. It ends +/// when the channel closes (flushing what is buffered), at the hard cap +/// (flushing, and reporting through `deliver` if a run is still open), or when +/// `control.cancel` fires. A cancel discards buffered text, drops an in-flight +/// `deliver`, and posts nothing afterwards; it does not flush. Any +/// parent-session `session/update` restarts the quiet timer. Buffered text is +/// limited to [`MAX_BUFFER_BYTES`] and each `deliver` to [`DELIVER_TIMEOUT`]. +/// Frames dropped on a full queue ([`RELAY_QUEUE_CAPACITY`]) mark the flushed +/// text as truncated. +pub async fn run_tail( + mut rx: RelayReceiver, + parent_session_id: String, + open: HashSet, + cfg: WorkflowRelayConfig, + started: Instant, + control: TailControl, + mut deliver: F, +) where + F: FnMut(String) -> Fut, + Fut: Future, +{ + let TailControl { mut gate, cancel } = control; + let mut gated = true; + let hard = started + cfg.tail_max; + let mut st = TailState { + parent: parent_session_id, + open, + buf: String::new(), + truncated: false, + last_event: Instant::now(), + closed: false, + ending: false, + cancel, + cancelled: false, + }; + loop { + let quiet_applies = !st.buf.is_empty() || st.open.is_empty(); + let deadline = if quiet_applies { + (st.last_event + cfg.tail_quiet).min(hard) + } else { + hard + }; + tokio::select! { + biased; + _ = &mut st.cancel => { + // Discard what is buffered and end. Nothing is posted. + st.cancelled = true; + return; + } + _ = &mut gate, if gated => { + gated = false; + } + msg = rx.recv() => { + let Some(msg) = msg else { + if gated { + // Wait for the original reply, but not past the cap or + // a cancel. + tokio::select! { + biased; + _ = &mut st.cancel => { + st.cancelled = true; + return; + } + r = timeout_at(hard, &mut gate) => { + if r.is_err() { + return; + } + } + } + } + flush(&mut st, &mut rx, &mut deliver).await; + return; + }; + st.ingest(msg); + } + _ = sleep_until(deadline) => { + let at_cap = Instant::now() >= hard; + if gated && !at_cap { + // Reply still being delivered: keep buffering. + st.last_event = Instant::now(); + continue; + } + if gated { + // Cap reached before the reply was delivered; drop. + return; + } + flush(&mut st, &mut rx, &mut deliver).await; + if st.cancelled { + return; + } + if at_cap || Instant::now() >= hard { + // Frames drained while that delivery was pending are still + // buffered: one bounded final flush (frames arriving during + // it are dropped, the tail ends here). + st.ending = true; + flush(&mut st, &mut rx, &mut deliver).await; + if st.cancelled { + return; + } + if !st.open.is_empty() { + send(&mut st, &mut rx, &mut deliver, format!( + "⚠ workflow still running after {}s; further output is not relayed", + cfg.tail_max.as_secs() + )) + .await; + } + return; + } + st.last_event = Instant::now(); + } + } + } +} + +/// Start [`run_tail`] on a detached task. The returned receiver resolves once +/// the tail has returned: after its final flush, or right after a cancel. The +/// next turn on the same connection waits on it with +/// [`wait_for_previous_tail`] before posting. +pub fn spawn_tail( + rx: RelayReceiver, + parent_session_id: String, + open: HashSet, + cfg: WorkflowRelayConfig, + started: Instant, + control: TailControl, + deliver: F, +) -> oneshot::Receiver<()> +where + F: FnMut(String) -> Fut + Send + 'static, + Fut: Future + Send + 'static, +{ + let (done_tx, done_rx) = oneshot::channel(); + tokio::spawn(async move { + run_tail(rx, parent_session_id, open, cfg, started, control, deliver).await; + let _ = done_tx.send(()); + }); + done_rx +} + +/// Wait until a previous tail has finished, so the next reply is not posted +/// into the middle of it. There is no timeout. The connection cancels the +/// previous tail before the next prompt, and a cancelled tail returns as soon +/// as its in-flight delivery is dropped, so this wait cannot hang on a stalled +/// platform call. A tail that is not cancelled is still running and this +/// waits for it. +pub async fn wait_for_previous_tail(done: oneshot::Receiver<()>) { + let _ = done.await; +} + +/// Mutable bookkeeping of one tail. +struct TailState { + parent: String, + open: HashSet, + buf: String, + truncated: bool, + last_event: Instant, + /// The sender side closed while a delivery was pending. + closed: bool, + /// The final delivery is running: queued frames are read and dropped so + /// the queue keeps draining until the tail returns. + ending: bool, + /// Fires when the connection cancels this tail. Polled by every wait. + cancel: oneshot::Receiver<()>, + /// Set once a cancel was observed. Nothing is posted afterwards. + cancelled: bool, +} + +impl TailState { + fn ingest(&mut self, msg: JsonRpcMessage) { + if is_foreign_session_update(&msg, &self.parent) { + return; + } + if msg.id.is_none() && msg.method.as_deref() == Some("session/update") { + // Thinking and tool frames are not relayed, but they count as + // activity so a pause inside a summary does not split it. + self.last_event = Instant::now(); + } + match classify_workflow_signal(&msg, &self.parent) { + Some(WorkflowSignal::RunStart { workflow_id }) => { + self.open.insert(workflow_id); + self.last_event = Instant::now(); + return; + } + Some(WorkflowSignal::RunComplete { workflow_id }) => { + self.open.remove(&workflow_id); + self.last_event = Instant::now(); + return; + } + None => {} + } + if msg.id.is_none() { + if let Some(AcpEvent::Text(t)) = classify_notification(&msg) { + // Once text is cut, later text is dropped too, so the flushed + // message stays a contiguous prefix before the truncation note. + if !self.truncated && self.buf.len() + t.len() <= MAX_BUFFER_BYTES { + self.buf.push_str(&t); + } else { + self.truncated = true; + } + self.last_event = Instant::now(); + } + } + } +} + +/// Run one delivery (bounded by [`DELIVER_TIMEOUT`]) while still draining +/// `rx` into the capped buffer, so the notification queue cannot grow while +/// the platform call is pending. +async fn send(st: &mut TailState, rx: &mut RelayReceiver, deliver: &mut F, text: String) +where + F: FnMut(String) -> Fut, + Fut: Future, +{ + if st.cancelled { + return; + } + let fut = tokio::time::timeout(DELIVER_TIMEOUT, deliver(text)); + tokio::pin!(fut); + loop { + tokio::select! { + biased; + _ = &mut st.cancel => { + // Drops the in-flight delivery: the platform call stops at its + // next await, and nothing else is posted. + st.cancelled = true; + return; + } + _ = &mut fut => return, + msg = rx.recv(), if !st.closed => match msg { + Some(m) => { + if !st.ending { + st.ingest(m); + } + } + None => st.closed = true, + }, + } + } +} + +async fn flush(st: &mut TailState, rx: &mut RelayReceiver, deliver: &mut F) +where + F: FnMut(String) -> Fut, + Fut: Future, +{ + let mut text = std::mem::take(&mut st.buf); + let dropped = rx.take_overflow(); + if std::mem::take(&mut st.truncated) || dropped { + text.push_str("\n\n…(output truncated)"); + } + if !text.trim().is_empty() { + send(st, rx, deliver, text).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::sync::{Arc, Mutex}; + use tokio::sync::oneshot; + + const PARENT: &str = "parent"; + + fn cfg() -> WorkflowRelayConfig { + WorkflowRelayConfig { + tail_quiet: Duration::from_secs(20), + tail_max: Duration::from_secs(900), + } + } + + fn frame(v: serde_json::Value) -> JsonRpcMessage { + serde_json::from_value(v).unwrap() + } + + fn run_start(parent: &str) -> JsonRpcMessage { + frame(json!({"method": "_kiro/workflow/run_start", + "params": {"workflowId": "wf_1", "parentSessionId": parent}})) + } + + fn run_complete() -> JsonRpcMessage { + frame(json!({"method": "_kiro/workflow/run_complete", + "params": {"workflowId": "wf_1", "status": "completed"}})) + } + + fn chunk(session: &str, text: &str) -> JsonRpcMessage { + frame( + json!({"method": "session/update", "params": {"sessionId": session, + "update": {"sessionUpdate": "agent_message_chunk", + "content": {"type": "text", "text": text}}}}), + ) + } + + fn collector() -> ( + Arc>>, + impl FnMut(String) -> std::future::Ready<()>, + ) { + let out = Arc::new(Mutex::new(Vec::new())); + let sink = out.clone(); + (out, move |t| { + sink.lock().unwrap().push(t); + std::future::ready(()) + }) + } + + fn open_gate() -> oneshot::Receiver<()> { + let (tx, rx) = oneshot::channel(); + tx.send(()).unwrap(); + rx + } + + /// A cancel signal that never fires. Its sender is leaked on purpose so the + /// receiver stays open for the whole test. + fn never_cancelled() -> oneshot::Receiver<()> { + let (tx, rx) = oneshot::channel(); + std::mem::forget(tx); + rx + } + + fn open_control() -> TailControl { + TailControl { + gate: open_gate(), + cancel: never_cancelled(), + } + } + + fn open_set(ids: &[&str]) -> HashSet { + ids.iter().map(|s| s.to_string()).collect() + } + + #[tokio::test(start_paused = true)] + async fn late_parent_text_is_delivered_after_run_complete_and_quiet() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "all ")).unwrap(); + tx.send(chunk(PARENT, "done")).unwrap(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert_eq!(*out.lock().unwrap(), vec!["all done".to_string()]); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn step_session_text_is_dropped() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + tx.send(run_complete()).unwrap(); + tx.send(chunk("step-1", "internal")).unwrap(); + tx.send(chunk(PARENT, "summary")).unwrap(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert_eq!(*out.lock().unwrap(), vec!["summary".to_string()]); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn closed_channel_flushes_buffer_and_ends() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + tx.send(chunk(PARENT, "partial")).unwrap(); + drop(tx); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert_eq!(*out.lock().unwrap(), vec!["partial".to_string()]); + } + + #[tokio::test(start_paused = true)] + async fn run_that_never_completes_reports_at_the_cap() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let started = Instant::now(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert_eq!(started.elapsed(), Duration::from_secs(900)); + let got = out.lock().unwrap().clone(); + assert_eq!(got.len(), 1); + assert!(got[0].contains("still running after 900s"), "{got:?}"); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn text_during_open_run_is_flushed_after_quiet_and_tail_continues() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + )); + tx.send(chunk(PARENT, "first")).unwrap(); + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(*out.lock().unwrap(), vec!["first".to_string()]); + assert!(!handle.is_finished(), "run is still open"); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "second")).unwrap(); + handle.await.unwrap(); + assert_eq!( + *out.lock().unwrap(), + vec!["first".to_string(), "second".to_string()] + ); + } + + #[tokio::test(start_paused = true)] + async fn idle_tail_without_open_run_ends_at_cap_with_no_delivery() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let started = Instant::now(); + run_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert_eq!(started.elapsed(), Duration::from_secs(900)); + assert!(out.lock().unwrap().is_empty()); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn summary_after_a_quiet_gap_is_delivered() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + open_control(), + deliver, + )); + tx.send(run_complete()).unwrap(); + tokio::time::sleep(Duration::from_secs(25)).await; + tx.send(chunk(PARENT, "summary")).unwrap(); + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(*out.lock().unwrap(), vec!["summary".to_string()]); + drop(tx); + handle.await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn thought_and_tool_frames_keep_a_summary_in_one_message() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + )); + tx.send(chunk(PARENT, "A")).unwrap(); + // Thinking and tool calls arrive every 15 s, each inside the quiet + // window, so "A" and "B" stay in one message. + tokio::time::sleep(Duration::from_secs(15)).await; + tx.send(frame(json!({"method": "session/update", "params": { + "sessionId": PARENT, + "update": {"sessionUpdate": "agent_thought_chunk", + "content": {"type": "text", "text": "thinking"}}}}))) + .unwrap(); + tokio::time::sleep(Duration::from_secs(15)).await; + tx.send(frame(json!({"method": "session/update", "params": { + "sessionId": PARENT, + "update": {"sessionUpdate": "tool_call", "toolCallId": "t1", + "title": "read"}}}))) + .unwrap(); + tokio::time::sleep(Duration::from_secs(10)).await; + tx.send(chunk(PARENT, "B")).unwrap(); + tokio::time::sleep(Duration::from_secs(40)).await; + assert_eq!(*out.lock().unwrap(), vec!["AB".to_string()]); + drop(tx); + handle.await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn closed_channel_with_empty_buffer_ends_without_delivery() { + let (tx, rx) = relay_channel(); + drop(tx); + let (out, deliver) = collector(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert!(out.lock().unwrap().is_empty()); + } + + #[tokio::test(start_paused = true)] + async fn buffered_text_is_capped_and_marked_truncated() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let big = "x".repeat(MAX_BUFFER_BYTES / 2 + 1); + tx.send(chunk(PARENT, &big)).unwrap(); + tx.send(chunk(PARENT, &big)).unwrap(); + tx.send(chunk(PARENT, &big)).unwrap(); + drop(tx); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + let got = out.lock().unwrap().clone(); + assert_eq!(got.len(), 1); + assert!(got[0].len() <= MAX_BUFFER_BYTES + 64, "{}", got[0].len()); + assert!(got[0].ends_with("…(output truncated)")); + } + + #[tokio::test(start_paused = true)] + async fn text_after_a_cut_is_not_appended_out_of_order() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + tx.send(chunk(PARENT, &"a".repeat(MAX_BUFFER_BYTES - 10))) + .unwrap(); + // Does not fit: the buffer is cut here. + tx.send(chunk(PARENT, &"b".repeat(100))).unwrap(); + // Would fit in the 10 bytes left, but must not follow the cut. + tx.send(chunk(PARENT, "ccccc")).unwrap(); + drop(tx); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ) + .await; + assert_eq!( + *out.lock().unwrap(), + vec![format!( + "{}\n\n…(output truncated)", + "a".repeat(MAX_BUFFER_BYTES - 10) + )] + ); + } + + #[tokio::test(start_paused = true)] + async fn hard_cap_counts_from_the_prompt_response() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + // The prompt response arrived 800 s ago (original reply was slow). + let started = Instant::now(); + tokio::time::advance(Duration::from_secs(800)).await; + let t0 = Instant::now(); + run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + started, + open_control(), + deliver, + ) + .await; + assert_eq!(t0.elapsed(), Duration::from_secs(100)); + assert!(out.lock().unwrap()[0].contains("still running")); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn nothing_is_posted_before_the_original_reply_is_delivered() { + let (tx, rx) = relay_channel(); + let (gate_tx, gate_rx) = oneshot::channel(); + let (out, deliver) = collector(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + TailControl { + gate: gate_rx, + cancel: never_cancelled(), + }, + deliver, + )); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "late")).unwrap(); + tokio::time::sleep(Duration::from_secs(60)).await; + assert!(out.lock().unwrap().is_empty(), "gate still closed"); + assert!(!handle.is_finished()); + gate_tx.send(()).unwrap(); + handle.await.unwrap(); + assert_eq!(*out.lock().unwrap(), vec!["late".to_string()]); + } + + #[tokio::test(start_paused = true)] + async fn next_reply_waits_for_the_previous_tail_final_flush() { + let (tx, rx) = relay_channel(); + let log = Arc::new(Mutex::new(Vec::::new())); + let sink = log.clone(); + // The tail's delivery takes 5 s and records itself only when it completes. + let deliver = move |t: String| { + let sink = sink.clone(); + async move { + tokio::time::sleep(Duration::from_secs(5)).await; + sink.lock().unwrap().push(format!("tail: {t}")); + } + }; + tx.send(chunk(PARENT, "late")).unwrap(); + // The next prompt on the session replaces the subscriber: the tail ends. + drop(tx); + let done = spawn_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + open_control(), + deliver, + ); + wait_for_previous_tail(done).await; + log.lock().unwrap().push("next reply".into()); + assert_eq!( + *log.lock().unwrap(), + vec!["tail: late".to_string(), "next reply".to_string()] + ); + } + + #[tokio::test(start_paused = true)] + async fn cancelled_tail_discards_buffered_text() { + let (tx, rx) = relay_channel(); + let (out, deliver) = collector(); + let (cancel_tx, cancel_rx) = oneshot::channel(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + TailControl { + gate: open_gate(), + cancel: cancel_rx, + }, + deliver, + )); + tx.send(chunk(PARENT, "buffered")).unwrap(); + // Buffered, but the 20 s quiet mark has not come yet. + tokio::time::sleep(Duration::from_secs(5)).await; + drop(cancel_tx); + handle.await.unwrap(); + assert!(out.lock().unwrap().is_empty()); + drop(tx); + } + + #[tokio::test(start_paused = true)] + async fn teardown_cancels_an_in_progress_tail_and_nothing_posts_after_the_next_reply() { + let (tx, rx) = relay_channel(); + let log = Arc::new(Mutex::new(Vec::::new())); + let sink = log.clone(); + // The platform call for the flush never returns on its own. + let deliver = move |t: String| { + let sink = sink.clone(); + async move { + sink.lock().unwrap().push(format!("post: {t}")); + std::future::pending::<()>().await; + } + }; + tx.send(chunk(PARENT, "late")).unwrap(); + let (cancel_tx, cancel_rx) = oneshot::channel(); + let done = spawn_tail( + rx, + PARENT.into(), + HashSet::new(), + cfg(), + Instant::now(), + TailControl { + gate: open_gate(), + cancel: cancel_rx, + }, + deliver, + ); + // Quiet mark (20 s) passed: the flush is in flight and blocked. + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(*log.lock().unwrap(), vec!["post: late".to_string()]); + + // Teardown: the connection drops its cancel sender. + drop(cancel_tx); + let waited = Instant::now(); + wait_for_previous_tail(done).await; + assert!( + waited.elapsed() < DELIVER_TIMEOUT, + "the wait must end on cancel, not after the delivery timeout" + ); + log.lock().unwrap().push("next reply".into()); + + // Well past the delivery timeout, the cancelled tail still posts nothing. + tokio::time::sleep(Duration::from_secs(120)).await; + drop(tx); + assert_eq!( + *log.lock().unwrap(), + vec!["post: late".to_string(), "next reply".to_string()] + ); + } + + #[tokio::test(start_paused = true)] + async fn stalled_delivery_does_not_hold_the_tail_forever() { + let (tx, rx) = relay_channel(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + std::future::pending::<()>().await; + } + } + }; + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "late")).unwrap(); + let handle = tokio::spawn(run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + )); + // Quiet (20 s) plus one delivery timeout (30 s); the tail must still + // post output that arrives after that. + tokio::time::sleep(Duration::from_secs(60)).await; + tx.send(chunk(PARENT, "later")).unwrap(); + tokio::time::sleep(Duration::from_secs(40)).await; + drop(tx); + handle.await.unwrap(); + assert_eq!( + *calls.lock().unwrap(), + vec!["late".to_string(), "later".to_string()] + ); + } + + #[tokio::test(start_paused = true)] + async fn frames_sent_during_a_pending_delivery_are_drained_and_capped() { + let (tx, rx) = relay_channel(); + tx.send(run_complete()).unwrap(); + tx.send(chunk(PARENT, "first")).unwrap(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + // Platform call that hangs until the delivery timeout. + std::future::pending::<()>().await; + } + } + }; + let flood = async move { + // Quiet period (20 s) has passed; the first delivery is pending. + tokio::time::sleep(Duration::from_secs(25)).await; + let big = "x".repeat(MAX_BUFFER_BYTES / 2 + 1); + for _ in 0..50 { + tx.send(chunk(PARENT, &big)).unwrap(); + } + // Let the tail drain the queue while the delivery is pending. + tokio::task::yield_now().await; + drop(tx); + }; + let tail = run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ); + tokio::join!(tail, flood); + let got = calls.lock().unwrap().clone(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0], "first"); + assert!(got[1].len() <= MAX_BUFFER_BYTES + 64, "{}", got[1].len()); + assert!(got[1].ends_with("…(output truncated)")); + } + + #[tokio::test(start_paused = true)] + async fn queue_overflow_while_delivery_is_stalled_is_bounded_and_marked() { + let (tx, rx) = relay_channel(); + tx.send(chunk(PARENT, "first")).unwrap(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + std::future::pending::<()>().await; + } + } + }; + let flood = async move { + // The first delivery is pending from the 20 s quiet mark. + tokio::time::sleep(Duration::from_secs(25)).await; + // One synchronous burst: the tail cannot drain until this task + // yields, so the queue fills and the surplus is dropped. + let mut dropped = 0; + for _ in 0..RELAY_QUEUE_CAPACITY + 500 { + if tx.send(chunk(PARENT, "x")).is_err() { + dropped += 1; + } + } + assert_eq!(dropped, 500); + tokio::task::yield_now().await; + drop(tx); + }; + let tail = run_tail( + rx, + PARENT.into(), + open_set(&["wf_1"]), + cfg(), + Instant::now(), + open_control(), + deliver, + ); + tokio::join!(tail, flood); + let got = calls.lock().unwrap().clone(); + assert_eq!(got.len(), 2, "{got:?}"); + assert_eq!(got[0], "first"); + assert_eq!( + got[1], + format!( + "{}\n\n…(output truncated)", + "x".repeat(RELAY_QUEUE_CAPACITY) + ) + ); + } + + #[tokio::test(start_paused = true)] + async fn text_buffered_while_a_delivery_crosses_the_hard_cap_is_flushed() { + let (tx, rx) = relay_channel(); + tx.send(chunk(PARENT, "first")).unwrap(); + let calls = Arc::new(Mutex::new(Vec::::new())); + let sink = calls.clone(); + let deliver = move |t: String| { + let first = { + let mut g = sink.lock().unwrap(); + g.push(t); + g.len() == 1 + }; + async move { + if first { + // Hangs until DELIVER_TIMEOUT, which ends after the cap. + std::future::pending::<()>().await; + } + } + }; + let late = async move { + // Delivery started at the 20 s quiet mark and is still pending. + tokio::time::sleep(Duration::from_secs(25)).await; + tx.send(chunk(PARENT, "late")).unwrap(); + tokio::time::sleep(Duration::from_secs(1000)).await; + drop(tx); + }; + let mut c = cfg(); + c.tail_max = Duration::from_secs(40); + let tail = run_tail( + rx, + PARENT.into(), + HashSet::new(), + c, + Instant::now(), + open_control(), + deliver, + ); + tokio::join!(tail, late); + let got = calls.lock().unwrap().clone(); + assert_eq!( + got, + vec!["first".to_string(), "late".to_string()], + "{got:?}" + ); + } + + #[test] + fn flush_messages_are_capped_with_a_note_in_the_last_slot() { + let short = vec!["a".to_string(), "b".to_string()]; + assert_eq!( + limit_flush_messages(short.clone(), MAX_FLUSH_MESSAGES, TRUNCATED_NOTE), + short + ); + + // Exactly the cap: nothing is dropped, so no note. + let exact: Vec = (0..MAX_FLUSH_MESSAGES).map(|i| i.to_string()).collect(); + assert_eq!( + limit_flush_messages(exact.clone(), MAX_FLUSH_MESSAGES, TRUNCATED_NOTE), + exact + ); + + let long: Vec = (0..100).map(|i| i.to_string()).collect(); + let got = limit_flush_messages(long, MAX_FLUSH_MESSAGES, TRUNCATED_NOTE); + assert_eq!(got.len(), MAX_FLUSH_MESSAGES); + assert_eq!( + got[MAX_FLUSH_MESSAGES - 2], + (MAX_FLUSH_MESSAGES - 2).to_string() + ); + assert_eq!(got[MAX_FLUSH_MESSAGES - 1], TRUNCATED_NOTE); + assert_eq!( + TRUNCATED_NOTE, + "…(output truncated: this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed)" + ); + } + + #[test] + fn full_buffer_splits_into_at_most_the_cap_on_a_discord_sized_limit() { + // 256 KiB of text at Discord's 2000-character message limit would be + // about 130 messages; the cap keeps 15 of them plus the note. + let text = "line of late output\n".repeat(MAX_BUFFER_BYTES / 20); + let chunks = crate::format::split_message(&text, 2000); + assert!(chunks.len() > MAX_FLUSH_MESSAGES); + let got = limit_flush_messages(chunks, MAX_FLUSH_MESSAGES, TRUNCATED_NOTE); + assert_eq!(got.len(), MAX_FLUSH_MESSAGES); + assert_eq!(got.last().unwrap(), TRUNCATED_NOTE); + assert!(got[..MAX_FLUSH_MESSAGES - 1] + .iter() + .all(|c| c.chars().count() <= 2000)); + } + + #[test] + fn turn_state_arms_only_for_own_session() { + let mut state = TurnWorkflowState::default(); + state.observe(&run_start("someone-else"), PARENT); + assert!(!state.armed()); + state.observe(&run_start(PARENT), PARENT); + assert!(state.armed()); + assert_eq!(state.into_open(), open_set(&["wf_1"])); + + let mut state = TurnWorkflowState::default(); + state.observe(&run_start(PARENT), PARENT); + state.observe(&run_complete(), PARENT); + assert!(state.armed()); + assert!(state.into_open().is_empty()); + } +} diff --git a/docs/config-reference.md b/docs/config-reference.md index 0d3362076..22ed10493 100644 --- a/docs/config-reference.md +++ b/docs/config-reference.md @@ -338,6 +338,7 @@ The AI agent subprocess that OpenAB spawns to handle messages via ACP. | `working_dir` | string | `$HOME` | Working directory for the agent process. Optional — defaults to container's `$HOME`. | | `env` | map | `{}` | Extra environment variables (e.g. `{ OPENAI_API_KEY = "${OPENAI_API_KEY}" }`). | | `inherit_env` | string[] | `[]` | Env var names to inherit from the OAB process (e.g. vars injected via K8s `envFrom`). Keys in `env` take precedence. | +| `session_new_meta` | table | none | Optional `_meta` object sent verbatim in every `session/new` request. For Kiro workflows: `{ kiro = { settings = { workflows = { enabled = true } } } }`. Enabling workflows also turns on the step-session frame filter and the late-output relay (see [kiro-v3.md](kiro-v3.md)). Must be a table. | > **Default inherited vars:** After `env_clear()`, the agent always receives `HOME`, `PATH`, and `USER` (on Windows: `USERPROFILE`, `USERNAME`, `PATH`, `SystemRoot`, `SystemDrive`). Use `inherit_env` to pass additional vars beyond this baseline. @@ -429,6 +430,9 @@ Session pool settings for managing concurrent agent sessions. | `session_ttl_hours` | u64 | `4` | Session time-to-live in hours. Idle sessions are reclaimed after this period. The example config uses `24`. | | `hung_grace_secs` | u64 | `120` | Grace period after `prompt_hard_timeout_secs` before a session stuck with its connection mutex held (in-flight prompt) is force-evicted from the pool. Eviction threshold: `prompt_hard_timeout_secs + hung_grace_secs`. | | `default_config_options` | map | `{}` | Config options to set automatically after session creation. Keys are config option IDs (e.g. `mode`, `model`), values are the desired values (e.g. `bypass`, `swe-1-6`). Sent via ACP `session/set_config_option` after each `session/new`. | +| `strict_default_config_options` | bool | `false` | When `true`, session creation fails if the agent's `session/set_config_option` response reports a `currentValue` different from the requested value (an alias given as the option's display name is accepted), or if the call errors. Responses without that option are accepted. Recommended for kiro-cli v3, which answers success for an unknown agent. Not applied when a session is resumed via `session/load`. | +| `workflow_tail_quiet_secs` | u64 | `20` | Only with Kiro workflows enabled in `[agent].session_new_meta`. Seconds without agent output after which buffered late workflow text is posted to the thread. Must be `> 0` unless `workflow_tail_max_secs = 0`. | +| `workflow_tail_max_secs` | u64 | `900` | Only with Kiro workflows enabled. Hard cap (seconds from the prompt response) on relaying late workflow output. `0` disables the relay. | **Example** — force Devin to bypass mode and use a specific model: diff --git a/docs/kiro-v3.md b/docs/kiro-v3.md new file mode 100644 index 000000000..820098c9f --- /dev/null +++ b/docs/kiro-v3.md @@ -0,0 +1,119 @@ +# Kiro CLI v3 engine and Kiro workflows + +kiro-cli 3.x ships a second engine, selected with `--agent-engine=v3`. It changes how agents are +selected and adds Kiro workflows over ACP. openab supports both, and every setting below is +opt-in: with none of them set, a kiro-cli v2 bot behaves as before. + +## What changes with v3 + +- Agents appear as ACP **modes**. The flags `--agent`, `--trust-all-tools` and `--model` are + rejected, and v2 JSON agents (`~/.kiro/agents/*.json`) are not read. +- A custom agent is a Markdown file `~/.kiro/agents/.md`. Select it with + `[pool] default_config_options = { mode = "" }`. +- A session is created in the default mode (`vibe`) and then switched. An unknown mode name is + **not** an error: kiro-cli answers success and the session stays in `vibe` with its default tool + set. Turn on `strict_default_config_options` so openab refuses such a session. +- Each `kiro-cli` process uses about 0.5 GB of memory, and openab starts one per session. Size + the container and `[pool] max_sessions` for the peak (about 2 GiB for 4 sessions plus openab). + +## Configuration + +```toml +[agent] +command = "kiro-cli" +args = ["acp", "--agent-engine=v3"] +# Optional, only for Kiro workflows: +session_new_meta = { kiro = { settings = { workflows = { enabled = true } } } } + +[pool] +max_sessions = 2 +default_config_options = { mode = "openab-bot" } +strict_default_config_options = true +``` + +Agent file `~/.kiro/agents/openab-bot.md` (in the bot's `HOME`): + +```markdown +--- +name: openab-bot +description: Chat bot agent +tools: ["*"] +includeMcpJson: false +--- + +You are a helpful assistant in a chat thread. +``` + +Restrict `tools` to what the bot needs. openab auto-approves every permission request, so the +tool list is the only limit on what the agent can do. + +Create an empty user MCP config, `~/.kiro/settings/mcp.json`: + +```json +{"mcpServers": {}} +``` + +`includeMcpJson: false` does not stop user-level MCP servers from starting at `session/new`, so +an empty file is the reliable way to run without them. + +## What the openab settings do + +| Setting | Effect | +|---------|--------| +| `[agent] session_new_meta` | Sent as the `_meta` field of the `session/new` request. kiro-cli only honours the workflows switch there (not in `initialize`). Not sent on `session/load`. | +| `[pool] strict_default_config_options` | After each `session/set_config_option`, compares the returned `currentValue` with the requested value. Session creation fails when the agent returns an error, when the response does not list the requested option id (including a response with no result), or when the value does not match. The error says the agent did not report the option, or that the value was not applied. In this mode the legacy slash-command fallback is not used, so only a value the agent reports counts. An alias given as the option's display name is accepted. Default `false`. Without strict mode, an error from `set_config_option` is logged as a warning and the session is created anyway; the returned value is not checked. +| `[pool] workflow_tail_quiet_secs` / `workflow_tail_max_secs` | Bounds of the late-output relay below. | + +## Workflows + +With workflows enabled, a prompt can start a workflow and `session/prompt` returns **before** the +workflow ends. The summary arrives later as unsolicited message chunks of the same session. When +workflows are enabled openab: + +1. **Filters step sessions.** Each workflow step runs in its own ACP session and streams + `session/update` frames with a different `params.sessionId`. openab accepts a `session/update` + only when its `params.sessionId` is the string id of the served session, and drops every other + one: another id, or a missing, null or non-string `sessionId`. The check applies to + notifications only; responses and other methods are not affected. The ACP schema in this repo + (`crates/openab-gateway/schemas/acp-v1.schema.json`) requires `sessionId` on + `SessionNotification`, and the existing mock agents and tests send it. No kiro-cli frame is known + to omit it. If a kiro-cli release starts omitting it, parent text is dropped and this rule needs + revisiting. Permission requests from step sessions are still auto-answered. +2. **Relays the late summary.** If a workflow started for the session during the turn, openab + keeps reading after delivering the reply and posts the late text as a new message in the same + thread, prefixed `_Workflow update:_`. Text is posted after `workflow_tail_quiet_secs` without + new output, so text that arrives after a long pause is still delivered. Thinking and tool + activity count as output for this timer but are not posted. The relay ends when the channel closes + (flushing what it holds), at `workflow_tail_max_secs`, measured from the prompt response, or when + it is cancelled (see the cancel path below). If a run is still open at the cap, a warning message + says that further output is not relayed. Setting `workflow_tail_max_secs = 0` disables the relay + and keeps the filter. + Ordering: the next prompt's reply is not posted until the previous relay has finished. That wait + has no timeout. The next prompt cancels the previous relay first, so the wait ends as soon as the + relay drops its in-flight post. + + **Cancel path.** A relay is cancelled by two events. The first is the next `session/prompt` on + the same connection: `session_prompt` drops the connection's cancel sender before it replaces the + subscriber. The second is teardown of the connection (reset, idle cleanup, pool eviction, or + shutdown): dropping the connection drops the same sender. A cancelled relay discards its + buffered, unposted text, drops any platform call still in flight at its next await, and returns. + It posts nothing after the cancel, and it signals completion so the next reply can start. A + cancel does not flush. Buffered text is therefore lost when the user sends another message before + the quiet time has passed. A connection whose streaming task is stuck still holds its + connection, so its relay is cancelled only when that task releases it. + +Limits: openab buffers at most 256 KiB of late text per flush. Text past that cap is dropped and the posted text ends with `…(output truncated)`, so the posted text is always a contiguous prefix. One flush posts at most 16 platform messages, split to the platform's message limit. When the text needs more, the first 15 messages are posted and the 16th says that this flush was cut at 16 platform messages and the rest of this flush was not sent; later output is still relayed, so a dropped part is always announced. The relay queue between the connection and the tail holds at most 1024 frames. Frames past that are dropped and also mark the next flush as truncated. A flush has a 30 s budget in total, not per message. If the platform is slower than that, the flush stops and the note may not be posted. Messages are sent one at a time, and rate limiting is left to the platform client. The relay lasts up to `workflow_tail_max_secs` (default 900) from the prompt response. While it lasts, parent-session text caused by other requests on the same connection (for example the slash-command fallback that applies a runtime `/model` change) is also posted, as a workflow update. If the agent pauses for longer than the quiet time, the text before the pause is posted as its own message, whether or not a run is still open, and later text starts a new one. Only workflows started during a turn are tracked. A workflow that is still running when the next prompt starts has its later output delivered with that prompt, not as a workflow update. +Late text that arrives after the next prompt started is part of that prompt's reply. The relay is +not used on the `acp` gateway platform. `session_new_meta` and `default_config_options` are +applied when a session is created with `session/new` only, not when a session is restored with `session/load`. + +## Security notes + +- Workflow steps run shell commands, and openab answers every permission request with + "allow always". Each step session asks two to three times per command. +- Text from the chat reaches workflow steps as user text. Allow only fixed, reviewed workflow + files, use a private channel, and keep step agents (`.md` files) to the minimum tool set. +- Custom agent `resources` are not loaded inside workflow steps. +- Upstream issues to know about: a workflow result can be lost when the parent session is busy, + and a run can hang if a permission request is never answered. openab bounds the wait but does + not fix either. diff --git a/docs/kiro.md b/docs/kiro.md index 60813272d..40737f716 100644 --- a/docs/kiro.md +++ b/docs/kiro.md @@ -41,6 +41,8 @@ To override a single agent's image instead of the global tag: > ⚠️ There is no `latest` tag. Use `beta` or `stable`, or pin to an exact version. +> Using kiro-cli 3.x (`--agent-engine=v3`) or Kiro workflows? See [kiro-v3.md](kiro-v3.md). + ## Manual config.toml ```toml diff --git a/src/main.rs b/src/main.rs index f49879778..0356e42fa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -566,7 +566,8 @@ async fn main() -> anyhow::Result<()> { .prompt_hard_timeout_secs .saturating_add(cfg.pool.hung_grace_secs), cfg.pool.default_config_options, - ); + ) + .with_strict_default_config_options(cfg.pool.strict_default_config_options); // Facade session wiring: only when the facade is actually serving. With no `[mcp]` there is // no registrar and no facade url, and the pool simply starts sessions without browser // capabilities — there is no longer a proxy path for it to fall back to. @@ -855,24 +856,32 @@ async fn main() -> anyhow::Result<()> { reg }; - let router = Arc::new( - AdapterRouter::new( - pool.clone(), - cfg.reactions, - cfg.markdown.tables, - cfg.pool.prompt_hard_timeout_secs, - cfg.pool.liveness_check_secs, - cfg.workspace.aliases, - std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| { - tracing::warn!( - "HOME environment variable is not set — falling back to /tmp as bot_home. \ + let workflow_relay = + pool.workflows_enabled() + .then(|| openab_core::workflow_tail::WorkflowRelayConfig { + tail_quiet: std::time::Duration::from_secs(cfg.pool.workflow_tail_quiet_secs), + tail_max: std::time::Duration::from_secs(cfg.pool.workflow_tail_max_secs), + }); + let router = AdapterRouter::new( + pool.clone(), + cfg.reactions, + cfg.markdown.tables, + cfg.pool.prompt_hard_timeout_secs, + cfg.pool.liveness_check_secs, + cfg.workspace.aliases, + std::path::PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| { + tracing::warn!( + "HOME environment variable is not set — falling back to /tmp as bot_home. \ This weakens the workspace security boundary." - ); - "/tmp".into() - })), - ) - .with_trust(gateway_trust), - ); + ); + "/tmp".into() + })), + ) + .with_trust(gateway_trust); + let router = Arc::new(match workflow_relay { + Some(relay) => router.with_workflow_relay(relay), + None => router, + }); // Shutdown signal for Slack adapter let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);