From 6215c4d379eb12d55031100d6e3b99f88872e86b Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:29:43 -0400 Subject: [PATCH 1/3] Lend foreground subagent cohorts and withdraw held requests before a subtree stop A foreground agent call now lends its dispatched call's complete recorded input cohort to its child while it waits for it in this server process, so the child's requests carry root_session_id/root_input_message_ids like a background Job's. Running Jobs and the live call must agree on one link; a restart drops the link. A subtree stop now withdraws waiting requests before cancelling actors, and permission/question waits prefer an already delivered refusal over a later cancellation, so a call held at its request settles as refused instead of outcome_unknown and the stop can be acknowledged. An approval meeting a cancellation still aborts. --- .../src/runtime/foreground_children.rs | 159 ++++++++++++++++ .../cyber-server/src/runtime/input_clients.rs | 3 +- crates/cyber-server/src/runtime/jobs.rs | 12 ++ crates/cyber-server/src/runtime/mod.rs | 5 + crates/cyber-server/src/runtime/requests.rs | 6 +- .../src/runtime/requests/descendant_inputs.rs | 169 ++++++++++++++---- .../cyber-server/src/runtime/subtree_stop.rs | 11 ++ crates/cyber-tools/src/host.rs | 23 ++- crates/cyber-tools/src/tools/agent.rs | 6 + crates/cyber-tools/src/tools/session.rs | 4 +- sdk/openapi.json | 2 +- sdk/typescript/src/generated/types.ts | 3 +- 12 files changed, 354 insertions(+), 49 deletions(-) create mode 100644 crates/cyber-server/src/runtime/foreground_children.rs diff --git a/crates/cyber-server/src/runtime/foreground_children.rs b/crates/cyber-server/src/runtime/foreground_children.rs new file mode 100644 index 00000000..fbf679d2 --- /dev/null +++ b/crates/cyber-server/src/runtime/foreground_children.rs @@ -0,0 +1,159 @@ +//! Foreground (synchronous) subagent links that lend their parent call's input cohort. +//! +//! A foreground child has no Job: its parent's dispatched `agent` call drives it and +//! waits for its answer. While that call runs in this server process the child is the +//! call's work, so the call's complete recorded input cohort is the link's cohort, as +//! a running background Job's immutable origin is. The cohort itself comes from durable +//! step evidence ([`super::Runtime::reserve_child_job_for_call`]); only the link's +//! liveness is process-local, so a restart drops it and the child stamps nothing. +use std::collections::HashMap; +use std::sync::PoisonError; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The live foreground links of a runtime, by child Session. +#[derive(Default)] +pub(super) struct Links { + next: AtomicU64, + by_child: std::sync::Mutex>, +} + +#[derive(Clone)] +struct Link { + parent: String, + input_message_ids: Vec, + token: u64, +} + +/// What a foreground link lends: the parent Session and its call's input cohort. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct Lent { + by_child: HashMap)>, +} + +impl Lent { + /// The cohort `parent`'s live foreground call lends `child`, if any. + pub(crate) fn cohort(&self, parent: &str, child: &str) -> Option<&[String]> { + self.by_child + .get(child) + .filter(|(owner, _)| owner == parent) + .map(|(_, ids)| ids.as_slice()) + } + + #[cfg(test)] + pub(crate) fn with(mut self, parent: &str, child: &str, ids: &[&str]) -> Self { + self.by_child.insert( + child.into(), + ( + parent.into(), + ids.iter().map(|id| (*id).to_owned()).collect(), + ), + ); + self + } +} + +impl Links { + pub(super) fn lent(&self) -> Lent { + let links = self.by_child.lock().unwrap_or_else(PoisonError::into_inner); + Lent { + by_child: links + .iter() + .map(|(child, link)| { + ( + child.clone(), + (link.parent.clone(), link.input_message_ids.clone()), + ) + }) + .collect(), + } + } + + fn bind(&self, parent: &str, child: &str, input_message_ids: Vec) -> u64 { + let token = self.next.fetch_add(1, Ordering::Relaxed) + 1; + self.by_child + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert( + child.into(), + Link { + parent: parent.into(), + input_message_ids, + token, + }, + ); + token + } + + fn unbind(&self, child: &str, token: u64) { + let mut links = self.by_child.lock().unwrap_or_else(PoisonError::into_inner); + if links.get(child).is_some_and(|link| link.token == token) { + links.remove(child); + } + } +} + +/// A live foreground link; dropping it (the parent call returned, failed or was +/// cancelled) withdraws the lent cohort. +pub struct ForegroundChild { + runtime: super::WeakRuntime, + child: String, + token: Option, +} + +impl Drop for ForegroundChild { + fn drop(&mut self) { + if let (Some(token), Some(runtime)) = (self.token, self.runtime.upgrade()) { + runtime.inner.foreground_children.unbind(&self.child, token); + } + } +} + +impl super::jobs::JobAdmission { + /// Lend the reserved call's complete input cohort to `child` while it runs in the + /// foreground. A call without a complete recorded cohort lends nothing. + pub fn lend_foreground(&self, child: &str) -> ForegroundChild { + let runtime = self.runtime(); + let token = self + .origin() + .filter(|origin| super::requests::descendant_inputs::complete(origin)) + .zip(runtime.upgrade()) + .map(|(origin, runtime)| { + runtime.inner.foreground_children.bind( + self.parent(), + child, + origin.input_message_ids.clone(), + ) + }); + ForegroundChild { + runtime, + child: child.into(), + token, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_link_lends_only_while_bound_and_a_stale_unbind_keeps_a_newer_link() { + let links = Links::default(); + let first = links.bind("parent", "child", vec!["one".into()]); + assert_eq!( + links.lent().cohort("parent", "child"), + Some(&["one".to_owned()][..]) + ); + assert_eq!(links.lent().cohort("other", "child"), None); + // A later call of the same child replaces the link; the earlier guard's + // drop must not withdraw it. + let second = links.bind("parent", "child", vec!["two".into()]); + links.unbind("child", first); + assert_eq!( + links.lent().cohort("parent", "child"), + Some(&["two".to_owned()][..]) + ); + links.unbind("child", second); + assert_eq!(links.lent(), Lent::default()); + } +} diff --git a/crates/cyber-server/src/runtime/input_clients.rs b/crates/cyber-server/src/runtime/input_clients.rs index f621976e..25d43c83 100644 --- a/crates/cyber-server/src/runtime/input_clients.rs +++ b/crates/cyber-server/src/runtime/input_clients.rs @@ -219,9 +219,10 @@ fn asker_authority( call: &str, ) -> Result { let owner = session.to_owned(); + let foreground = inner.foreground_children.lent(); let root = inner .store - .read(move |db| super::requests::descendant_inputs::recorded(db, &owner))?; + .read(move |db| super::requests::descendant_inputs::recorded(db, &owner, &foreground))?; if let Some(root) = root { return attendance(&inner.store, &root.session_id, &root.input_message_ids); } diff --git a/crates/cyber-server/src/runtime/jobs.rs b/crates/cyber-server/src/runtime/jobs.rs index 4f6c5c14..4fd36480 100644 --- a/crates/cyber-server/src/runtime/jobs.rs +++ b/crates/cyber-server/src/runtime/jobs.rs @@ -137,6 +137,18 @@ pub struct JobAdmission { _guard: tokio::sync::OwnedMutexGuard<()>, } +impl JobAdmission { + pub(super) fn origin(&self) -> Option<&JobInputOrigin> { + self.input_origin.as_ref() + } + pub(super) fn parent(&self) -> &str { + &self.parent + } + pub(super) fn runtime(&self) -> WeakRuntime { + self.runtime.clone() + } +} + pub(super) struct Control { pub(super) stop: CancellationToken, pub(super) done: CancellationToken, diff --git a/crates/cyber-server/src/runtime/mod.rs b/crates/cyber-server/src/runtime/mod.rs index adb7381c..f1099aff 100644 --- a/crates/cyber-server/src/runtime/mod.rs +++ b/crates/cyber-server/src/runtime/mod.rs @@ -49,6 +49,7 @@ pub use deliveries::{FilesSent, Notification, SEND_LIMIT_BYTES, SEND_LIMIT_FILES mod drain; mod events; mod files; +mod foreground_children; mod fork; mod forked_skills; mod hook_tests; @@ -102,6 +103,7 @@ mod subtask; mod subtree_reopen; mod subtree_stop; pub use delegations::{Delegation, DelegationPhase, DelegationStatus}; +pub use foreground_children::ForegroundChild; pub use input_interrupt::{ InputInterrupt, InputInterruptProblem, InputInterruptReceipt, InputInterruptStatus, }; @@ -909,6 +911,8 @@ pub(crate) struct Inner { ptys: pty::Registry, delegations: StdMutex>>, child_executions: StdMutex>>>, + /// Foreground subagent calls that lend their input cohort to their child. + foreground_children: foreground_children::Links, /// Registration ID of the server lock this runtime holds (`adopt_server_lock`). server_holder: std::sync::OnceLock, child_preparations: StdMutex>>, @@ -1045,6 +1049,7 @@ impl Runtime { ptys: pty::Registry::default(), delegations: StdMutex::default(), child_executions: StdMutex::default(), + foreground_children: Default::default(), server_holder: std::sync::OnceLock::new(), child_preparations: StdMutex::default(), activities: StdMutex::default(), diff --git a/crates/cyber-server/src/runtime/requests.rs b/crates/cyber-server/src/runtime/requests.rs index 40ab2d91..e63f5a62 100644 --- a/crates/cyber-server/src/runtime/requests.rs +++ b/crates/cyber-server/src/runtime/requests.rs @@ -105,7 +105,8 @@ pub struct PendingRequest { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub input_message_ids: Vec, /// Root Session of a descendant (subagent) request whose every ancestor link is a - /// background subagent Job with one complete, bounded input cohort. + /// running background subagent Job or a running foreground subagent call with one + /// complete, bounded input cohort. #[serde(default, skip_serializing_if = "Option::is_none")] pub root_session_id: Option, /// That root link's immutable input cohort; scoped attendance uses it instead of @@ -468,9 +469,10 @@ impl Inner { return Ok(()); } let session = asker.session_id.clone(); + let foreground = self.foreground_children.lent(); if let Some(root) = self .store - .read(move |db| descendant_inputs::recorded(db, &session))? + .read(move |db| descendant_inputs::recorded(db, &session, &foreground))? { request.root_session_id = Some(root.session_id); request.root_input_message_ids = root.input_message_ids; diff --git a/crates/cyber-server/src/runtime/requests/descendant_inputs.rs b/crates/cyber-server/src/runtime/requests/descendant_inputs.rs index 6b3cad49..6f0db027 100644 --- a/crates/cyber-server/src/runtime/requests/descendant_inputs.rs +++ b/crates/cyber-server/src/runtime/requests/descendant_inputs.rs @@ -1,13 +1,17 @@ //! Root input provenance of descendant (subagent) requests: complete or nothing. //! //! A child Session's request inherits its root input cohort only when every link from -//! the asker up to the root Session is a *running* background subagent Job whose +//! the asker up to the root Session is proven: a *running* background subagent Job whose //! immutable `input_origin` is complete, bounded and identical across that link's running -//! Jobs. Only a running Job is driving the child: once it has settled (or a restart -//! interrupted it) a later foreground resume or other activity in the child is not that -//! Job's work, so it inherits nothing. A missing link (a foreground, detached or settled -//! child), a cycle, a mixed or malformed origin, or an over-deep chain stamps nothing; -//! this is provenance, never live attendance. +//! Jobs, or a foreground `agent` call of the parent that is running in this server +//! process and lends its call's complete recorded cohort +//! ([`super::super::foreground_children`]). When both prove one link they must agree. +//! Only running work is driving the child: once a Job has settled (or a restart +//! interrupted it) or a foreground call returned, later activity in the child is not +//! that work, so it inherits nothing. A missing link (a detached or settled child), a +//! cycle, a mixed or malformed origin, or an over-deep chain stamps nothing; this is +//! provenance, never live attendance. +use super::super::foreground_children::Lent; use super::super::jobs::JobInputOrigin; use cyber_store::StoreError; use rusqlite::{Connection, OptionalExtension, params}; @@ -27,7 +31,11 @@ pub(crate) struct RootCohort { } /// The root cohort of `session`'s subagent lineage, or `None` when any link is unproven. -pub(crate) fn recorded(db: &Connection, session: &str) -> Result, StoreError> { +pub(crate) fn recorded( + db: &Connection, + session: &str, + foreground: &Lent, +) -> Result, StoreError> { let mut child = session.to_owned(); let mut seen = HashSet::from([child.clone()]); let mut cohort = None; @@ -40,7 +48,7 @@ pub(crate) fn recorded(db: &Connection, session: &str) -> Result Result>, S .optional()?) } +/// The one cohort that every running proof of the `parent` → `child` link agrees on. fn link_cohort( db: &Connection, parent: &str, child: &str, + foreground: &Lent, ) -> Result>, StoreError> { - let mut statement = db.prepare( - "SELECT CASE WHEN length(CAST(json_extract(data,'$.input_origin') AS BLOB))<=?3 - THEN json_extract(data,'$.input_origin') ELSE NULL END - FROM job WHERE session_id=?1 AND child_id=?2 AND status='running' - AND json_extract(data,'$.kind')='subagent' ORDER BY id LIMIT ?4", - )?; - let origins = statement - .query_map( - params![parent, child, MAX_ORIGIN_BYTES, (MAX_LINK_JOBS + 1) as i64], - |row| row.get::<_, Option>(0), - )? - .collect::, _>>()?; - if origins.is_empty() || origins.len() > MAX_LINK_JOBS { + let Some(origins) = running_job_origins(db, parent, child)? else { + return Ok(None); + }; + let lent = foreground.cohort(parent, child).map(<[String]>::to_vec); + if origins.is_empty() && lent.is_none() { return Ok(None); } - let mut cohort: Option> = None; + let mut cohort = lent; for raw in origins { let Some(ids) = raw.as_deref().and_then(valid_origin) else { return Ok(None); @@ -96,10 +98,37 @@ fn link_cohort( Ok(cohort) } +/// The bounded raw origins of the link's running subagent Jobs; `None` when there +/// are more than a bounded proof allows. +fn running_job_origins( + db: &Connection, + parent: &str, + child: &str, +) -> Result>>, StoreError> { + let mut statement = db.prepare( + "SELECT CASE WHEN length(CAST(json_extract(data,'$.input_origin') AS BLOB))<=?3 + THEN json_extract(data,'$.input_origin') ELSE NULL END + FROM job WHERE session_id=?1 AND child_id=?2 AND status='running' + AND json_extract(data,'$.kind')='subagent' ORDER BY id LIMIT ?4", + )?; + let origins = statement + .query_map( + params![parent, child, MAX_ORIGIN_BYTES, (MAX_LINK_JOBS + 1) as i64], + |row| row.get::<_, Option>(0), + )? + .collect::, _>>()?; + Ok((origins.len() <= MAX_LINK_JOBS).then_some(origins)) +} + fn valid_origin(raw: &str) -> Option> { let origin: JobInputOrigin = serde_json::from_str(raw).ok()?; - let ids = origin.input_message_ids; - let complete = !origin.message_id.is_empty() + complete(&origin).then_some(origin.input_message_ids) +} + +/// Whether an origin names its exact dispatched call and a complete bounded cohort. +pub(crate) fn complete(origin: &JobInputOrigin) -> bool { + let ids = &origin.input_message_ids; + !origin.message_id.is_empty() && !origin.call_id.is_empty() && !origin.operation_key.is_empty() && origin.attempt >= 1 @@ -108,8 +137,7 @@ fn valid_origin(raw: &str) -> Option> { && ids .iter() .all(|id| !id.is_empty() && id.len() <= MAX_ID_BYTES) - && ids.iter().collect::>().len() == ids.len(); - complete.then_some(ids) + && ids.iter().collect::>().len() == ids.len() } #[cfg(test)] @@ -160,16 +188,26 @@ mod tests { session_id: "root".into(), input_message_ids: vec!["one".into(), "two".into()], }; - assert_eq!(recorded(&db, "grandchild").unwrap(), Some(expected.clone())); - assert_eq!(recorded(&db, "child").unwrap(), Some(expected)); assert_eq!( - recorded(&db, "root").unwrap(), + recorded(&db, "grandchild", &Lent::default()).unwrap(), + Some(expected.clone()) + ); + assert_eq!( + recorded(&db, "child", &Lent::default()).unwrap(), + Some(expected) + ); + assert_eq!( + recorded(&db, "root", &Lent::default()).unwrap(), None, "a root is no descendant" ); - assert_eq!(recorded(&db, "missing").unwrap(), None); + assert_eq!(recorded(&db, "missing", &Lent::default()).unwrap(), None); db.execute("DELETE FROM job WHERE id='j2'", []).unwrap(); - assert_eq!(recorded(&db, "grandchild").unwrap(), None, "detached link"); + assert_eq!( + recorded(&db, "grandchild", &Lent::default()).unwrap(), + None, + "detached link" + ); } #[test] @@ -196,14 +234,25 @@ mod tests { let db = chain(); db.execute("DELETE FROM job WHERE id='j1'", []).unwrap(); job(&db, "j1", "root", "child", bad.clone()); - assert_eq!(recorded(&db, "grandchild").unwrap(), None, "{bad}"); + assert_eq!( + recorded(&db, "grandchild", &Lent::default()).unwrap(), + None, + "{bad}" + ); } let db = chain(); job(&db, "j3", "root", "child", origin(json!(["three"]))); - assert_eq!(recorded(&db, "child").unwrap(), None, "mixed cohorts"); + assert_eq!( + recorded(&db, "child", &Lent::default()).unwrap(), + None, + "mixed cohorts" + ); let db = chain(); job(&db, "j3", "root", "child", origin(json!(["one", "two"]))); - assert!(recorded(&db, "child").unwrap().is_some(), "identical retry"); + assert!( + recorded(&db, "child", &Lent::default()).unwrap().is_some(), + "identical retry" + ); let db = chain(); db.execute( "UPDATE session SET parent_id='grandchild' WHERE id='root'", @@ -211,7 +260,11 @@ mod tests { ) .unwrap(); job(&db, "j0", "grandchild", "root", origin(json!(["one"]))); - assert_eq!(recorded(&db, "child").unwrap(), None, "cycle"); + assert_eq!( + recorded(&db, "child", &Lent::default()).unwrap(), + None, + "cycle" + ); } #[test] @@ -224,22 +277,62 @@ mod tests { let db = chain(); settle(&db, "j1", status); assert_eq!( - recorded(&db, "child").unwrap(), + recorded(&db, "child", &Lent::default()).unwrap(), None, "a {status} Job kept stamping a later resume" ); - assert_eq!(recorded(&db, "grandchild").unwrap(), None, "{status}"); + assert_eq!( + recorded(&db, "grandchild", &Lent::default()).unwrap(), + None, + "{status}" + ); } // A background resume: the settled Job's old cohort yields to the running one. let db = chain(); settle(&db, "j1", "completed"); job(&db, "j3", "root", "child", origin(json!(["resumed"]))); assert_eq!( - recorded(&db, "grandchild").unwrap(), + recorded(&db, "grandchild", &Lent::default()).unwrap(), Some(RootCohort { session_id: "root".into(), input_message_ids: vec!["resumed".into()], }) ); } + + #[test] + fn a_live_foreground_call_lends_its_cohort_and_must_agree_with_running_jobs() { + let db = chain(); + db.execute("DELETE FROM job WHERE id='j2'", []).unwrap(); + let none = Lent::default(); + assert_eq!(recorded(&db, "grandchild", &none).unwrap(), None); + let root = RootCohort { + session_id: "root".into(), + input_message_ids: vec!["one".into(), "two".into()], + }; + // child -> grandchild is a foreground call: the root cohort passes through it. + let lent = Lent::default().with("child", "grandchild", &["prompt"]); + assert_eq!( + recorded(&db, "grandchild", &lent).unwrap(), + Some(root.clone()) + ); + // A foreground link of another parent proves nothing for this child. + let foreign = Lent::default().with("root", "grandchild", &["prompt"]); + assert_eq!(recorded(&db, "grandchild", &foreign).unwrap(), None); + // A foreground root link alone proves the chain's top. + db.execute("DELETE FROM job WHERE id='j1'", []).unwrap(); + let both = lent.clone().with("root", "child", &["fg"]); + assert_eq!( + recorded(&db, "grandchild", &both).unwrap(), + Some(RootCohort { + session_id: "root".into(), + input_message_ids: vec!["fg".into()], + }) + ); + // A running Job and a foreground call proving one link must agree. + job(&db, "j1", "root", "child", origin(json!(["fg"]))); + assert!(recorded(&db, "grandchild", &both).unwrap().is_some()); + let disagree = lent.with("root", "child", &["other"]); + assert_eq!(recorded(&db, "grandchild", &disagree).unwrap(), None); + } } diff --git a/crates/cyber-server/src/runtime/subtree_stop.rs b/crates/cyber-server/src/runtime/subtree_stop.rs index 7d38e4b9..b30564b3 100644 --- a/crates/cyber-server/src/runtime/subtree_stop.rs +++ b/crates/cyber-server/src/runtime/subtree_stop.rs @@ -173,6 +173,17 @@ impl Runtime { sweep: &str, ) -> Result, RuntimeError> { let ids: HashSet = ids.iter().cloned().collect(); + // Withdraw waiting requests before cancelling: a call held at its permission + // request has not run, and receiving the withdrawal first lets it settle as + // refused rather than with an unknown outcome. Best effort and bounded, so the + // signal always follows; the sweep withdraws again and reports failures. + let withdraw = async { + for id in &ids { + self.inner.abandon_requests(id).await?; + } + Ok::<_, RuntimeError>(()) + }; + let _ = tokio::time::timeout(Duration::from_millis(500), withdraw).await; self.inner.signal_subtree(&ids, &self.jobs(None)?); let attempt = async { for id in &ids { diff --git a/crates/cyber-tools/src/host.rs b/crates/cyber-tools/src/host.rs index e90788aa..6a950646 100644 --- a/crates/cyber-tools/src/host.rs +++ b/crates/cyber-tools/src/host.rs @@ -2565,6 +2565,23 @@ impl Ctx<'_> { ToolError::Failed(message) } + /// Wait for the reply to `ask`. A refusal already delivered wins over a later + /// cancellation: a stop withdraws the request before it cancels the call, so the + /// call settles as refused (never run) instead of with an unknown outcome. An + /// approval never runs a cancelled call. + async fn await_reply(&self, ask: PermissionAsk) -> Result { + let reply = tokio::select! { + biased; + reply = self.inv.asker.permission(ask) => reply, + _ = self.cancel.cancelled() => return Err(ToolError::Aborted), + }; + let approved = matches!(reply, PermissionReply::Once | PermissionReply::Always); + if approved && self.cancel.is_cancelled() { + return Err(ToolError::Aborted); + } + Ok(reply) + } + /// Ask the user. A `tainted` ask (`permissions-modes` → Taint-aware approvals) is not /// answered by a PermissionRequest hook's allow, and with no approver attached it is /// denied as not pre-approved. An "always" reply still saves the approval; it covers @@ -2604,11 +2621,7 @@ impl Ctx<'_> { self.cancel.clone(), )) .await; - let reply = tokio::select! { - _ = self.cancel.cancelled() => return Err(ToolError::Aborted), - reply = self.inv.asker.permission(ask) => reply, - }; - match reply { + match self.await_reply(ask).await? { PermissionReply::Once => Ok(()), PermissionReply::Always => { let root = cyber_core::config::project_root(&self.location); diff --git a/crates/cyber-tools/src/tools/agent.rs b/crates/cyber-tools/src/tools/agent.rs index 190d2651..a9127c57 100644 --- a/crates/cyber-tools/src/tools/agent.rs +++ b/crates/cyber-tools/src/tools/agent.rs @@ -731,6 +731,12 @@ async fn execute_child( let mut spawn = spawn; let reservation = reserve_child(ctx, &runtime, &parent, &mut spawn).await?; let id = spawn.child_id.clone(); + // A foreground child is this call's work while the call waits for it, so its + // requests carry the call's input cohort; the link ends with the call. + let _foreground = reservation + .as_ref() + .filter(|_| !spawn.background) + .map(|reservation| reservation.lend_foreground(&id)); let execution = match execution { Some(execution) => execution, None => runtime diff --git a/crates/cyber-tools/src/tools/session.rs b/crates/cyber-tools/src/tools/session.rs index 4a6937bd..0950369c 100644 --- a/crates/cyber-tools/src/tools/session.rs +++ b/crates/cyber-tools/src/tools/session.rs @@ -243,9 +243,11 @@ async fn ask(ctx: &Ctx<'_>, questions: Vec) -> Result> .notification_hooks(ctx.inv, "question", message, ctx.cancel.clone()), ) .await; + // As for permissions, a delivered reply wins over a later cancellation. let reply = tokio::select! { - _ = ctx.cancel.cancelled() => return Err(ToolError::Aborted), + biased; r = ctx.inv.asker.question(questions) => r, + _ = ctx.cancel.cancelled() => return Err(ToolError::Aborted), }; match reply { QuestionReply::Answers { answers } => Ok(answers), diff --git a/sdk/openapi.json b/sdk/openapi.json index 7191712c..be61f1ca 100644 --- a/sdk/openapi.json +++ b/sdk/openapi.json @@ -10774,7 +10774,7 @@ "string", "null" ], - "description": "Root Session of a descendant (subagent) request whose every ancestor link is a\nbackground subagent Job with one complete, bounded input cohort." + "description": "Root Session of a descendant (subagent) request whose every ancestor link is a\nrunning background subagent Job or a running foreground subagent call with one\ncomplete, bounded input cohort." }, "root_input_message_ids": { "type": "array", diff --git a/sdk/typescript/src/generated/types.ts b/sdk/typescript/src/generated/types.ts index e833f4de..b8a4abcc 100644 --- a/sdk/typescript/src/generated/types.ts +++ b/sdk/typescript/src/generated/types.ts @@ -3864,7 +3864,8 @@ export type PendingRequest = { input_message_ids?: string[]; /** * Root Session of a descendant (subagent) request whose every ancestor link is a - * background subagent Job with one complete, bounded input cohort. + * running background subagent Job or a running foreground subagent call with one + * complete, bounded input cohort. */ root_session_id?: string | null; /** From 13ed5c76cbd49f202639a2e6706236f9796108e9 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:29:43 -0400 Subject: [PATCH 2/3] Bound owned JSONL requests, tag step lines and redact configured secrets in exec errors - At most 64 owned requests are tracked; a further one is declined at once with a non-fatal capacity error line. At most 16 parsed stdin lines wait. - Lines a driven step writes carry that step's input_message_ids. - Error fields use the configured tool_output.redact patterns and allow list plus known env/config secrets and the attach password, with built-in detectors always on; also for the json result and text-mode error lines. Real-binary coverage for foreground subagent ownership, EOF settlement, second-driver isolation and interruption, and for interrupting a subagent whose call awaits permission (regression: it reported unknown). --- crates/cyber-cli/src/commands/exec/driver.rs | 72 ++-- .../src/commands/exec/driver/interruption.rs | 2 +- .../src/commands/exec/driver/request_tests.rs | 47 +++ crates/cyber-cli/src/commands/exec/mod.rs | 5 + crates/cyber-cli/src/commands/exec/report.rs | 124 ++++++- crates/cyber-cli/tests/exec_stream_input.rs | 346 ++++++++++++++++++ 6 files changed, 561 insertions(+), 35 deletions(-) diff --git a/crates/cyber-cli/src/commands/exec/driver.rs b/crates/cyber-cli/src/commands/exec/driver.rs index 7f4b5acd..ce2dccd7 100644 --- a/crates/cyber-cli/src/commands/exec/driver.rs +++ b/crates/cyber-cli/src/commands/exec/driver.rs @@ -30,6 +30,9 @@ use crate::error::CliError; const LEASE_RENEWAL: Duration = Duration::from_secs(15); /// A fatal protocol error. const EXIT_PROTOCOL: u8 = 2; +/// At most this many owned requests wait for a reply at once (two per pending input); +/// a further one is declined at once with a `capacity` error line. +const MAX_ASKS: usize = 64; /// What the stdin task sends. enum Line { @@ -109,7 +112,9 @@ pub async fn execute( .await .map_err(api)?, ); - let (sender, mut lines) = mpsc::channel(64); + // At most this many parsed lines (each at most 1 MiB) wait for the control loop; + // a writer that runs further ahead blocks on its stdin pipe. + let (sender, mut lines) = mpsc::channel(16); tokio::spawn(read_stdin(sender)); let mut driver = Driver::new(client, &id, args, &mut out, run); driver.seen_seq = baseline["data"]["seq"].as_i64(); @@ -453,19 +458,25 @@ impl<'a> Driver<'a> { self.release().await; let asks = std::mem::take(&mut self.asks); for (request_id, ask) in asks { - let (route, body) = if ask.question { - ("questions", json!({ "answers": null })) - } else { - ( - "permissions", - json!({ "reply": "reject", "message": NO_APPROVER }), - ) - }; - let path = format!("/sessions/{}/{route}/{request_id}/reply", ask.session_id); - let _ = self.client.post(&path, body).await; + self.decline(&request_id, &ask).await; } } + /// Decline a request nobody here will answer: `reject` a permission, dismiss a + /// question. + async fn decline(&self, request_id: &str, ask: &Ask) { + let (route, body) = if ask.question { + ("questions", json!({ "answers": null })) + } else { + ( + "permissions", + json!({ "reply": "reject", "message": NO_APPROVER }), + ) + }; + let path = format!("/sessions/{}/{route}/{request_id}/reply", ask.session_id); + let _ = self.client.post(&path, body).await; + } + async fn event(&mut self, event: Event) { if self.routed_here(&event) { return self.descendant(&event).await; @@ -598,7 +609,7 @@ impl<'a> Driver<'a> { } } self.stage_answers(); - self.step = None; + self.set_step(None); self.refresh_background().await; } @@ -655,7 +666,10 @@ impl<'a> Driver<'a> { /// A failed Turn fails the inputs it was answering. fn failed(&mut self, data: &Value) { let message = data["message"].as_str().unwrap_or("error").to_owned(); - self.out.error(&message); + self.out.stream_line( + "error", + json!({ "message": message, "input_message_ids": self.answering }), + ); for message_id in &self.answering { if let Some(input) = self.inputs.get_mut(message_id) { input.error.get_or_insert_with(|| message.clone()); @@ -677,14 +691,20 @@ impl<'a> Driver<'a> { if !safe_id(request_id, prefix) || !safe_id(session_id, "ses") { return; } - self.asks.insert( - request_id.to_owned(), - Ask { - session_id: session_id.to_owned(), - question, - inputs, - }, - ); + let ask = Ask { + session_id: session_id.to_owned(), + question, + inputs, + }; + if self.asks.len() >= MAX_ASKS && !self.asks.contains_key(request_id) { + self.out.stream_line( + "error", + json!({ "code": "capacity", "request_id": request_id, + "message": format!("more than {MAX_ASKS} requests wait; {request_id} was declined") }), + ); + return self.decline(request_id, &ask).await; + } + self.asks.insert(request_id.to_owned(), ask); let line = if question { "question" } else { @@ -743,6 +763,12 @@ impl<'a> Driver<'a> { || (self.closed && self.inputs.is_empty() && self.interruptions.is_empty()) } + /// The driven step being followed, whose lines carry its input cohort. + fn set_step(&mut self, step: Option<(&str, &[String])>) { + self.step = step.map(|(message, _)| message.to_owned()); + self.out.correlate(step.map(|(_, roots)| roots)); + } + fn owns_step(&self, data: &Value) -> bool { self.step .as_deref() @@ -754,7 +780,7 @@ impl<'a> Driver<'a> { if self.answer_done { self.stage_answers(); } - self.step = None; + self.set_step(None); let Some(message) = data["message_id"].as_str().filter(|id| safe_id(id, "msg")) else { return; }; @@ -776,7 +802,7 @@ impl<'a> Driver<'a> { if !self.inputs.owns_cohort(&roots) { return; } - self.step = Some(message.to_owned()); + self.set_step(Some((message, &roots))); self.answer_done = false; self.run.text.clear(); for root in roots { diff --git a/crates/cyber-cli/src/commands/exec/driver/interruption.rs b/crates/cyber-cli/src/commands/exec/driver/interruption.rs index 9c93c2d1..ff70e7da 100644 --- a/crates/cyber-cli/src/commands/exec/driver/interruption.rs +++ b/crates/cyber-cli/src/commands/exec/driver/interruption.rs @@ -154,7 +154,7 @@ impl Driver<'_> { } self.answering.retain(|id| self.inputs.contains(id)); if self.answering.is_empty() { - self.step = None; + self.set_step(None); self.run.retire_driver_answer(); self.answer_done = false; } diff --git a/crates/cyber-cli/src/commands/exec/driver/request_tests.rs b/crates/cyber-cli/src/commands/exec/driver/request_tests.rs index e688c567..bb649cd7 100644 --- a/crates/cyber-cli/src/commands/exec/driver/request_tests.rs +++ b/crates/cyber-cli/src/commands/exec/driver/request_tests.rs @@ -685,3 +685,50 @@ async fn a_request_answered_elsewhere_leaves_the_drivers_asks() { driver.close().await; f.app.runtime.shutdown().await; } + +/// More owned requests than the bound: the next one is declined at once, so it +/// neither waits unseen nor grows the driver's tracked requests. +#[tokio::test] +async fn an_owned_request_beyond_the_bound_is_declined_at_once() { + let f = Fixture::new().await; + let args = ExecArgs::default(); + let session = json!({"id":f.session}); + let mut out = Out::new(Format::Text, &args, &session); + let mut driver = Driver::new( + &f.client, + &f.session, + &args, + &mut out, + Run::new(&args, Instant::now()), + ); + driver.attach().await; + driver + .admit( + None, + vec![json!({"type":"text","text":"PERMISSION_CASE"})], + "queue", + ) + .await; + let request = f.request().await; + for index in 0..MAX_ASKS { + driver.asks.insert( + format!("per_placeholder{index}"), + Ask { + session_id: f.session.clone(), + question: false, + inputs: request.input_message_ids.clone(), + }, + ); + } + let (base, data) = event(&request); + driver.asked(base, &data).await; + assert_eq!(driver.asks.len(), MAX_ASKS); + assert!(!driver.asks.contains_key(&request.id)); + tokio::time::timeout(Duration::from_secs(30), f.app.runtime.wait_idle(&f.session)) + .await + .expect("the declined request kept its Turn waiting"); + assert!(f.app.runtime.pending_requests(Some(&f.session)).is_empty()); + driver.asks.clear(); + driver.close().await; + f.app.runtime.shutdown().await; +} diff --git a/crates/cyber-cli/src/commands/exec/mod.rs b/crates/cyber-cli/src/commands/exec/mod.rs index fc0a927e..bb0a6161 100644 --- a/crates/cyber-cli/src/commands/exec/mod.rs +++ b/crates/cyber-cli/src/commands/exec/mod.rs @@ -298,6 +298,11 @@ fn launch( client }; let mut out = Out::new(format, &args, &session); + let config = ctx.config().ok().map(|resolved| resolved.value); + out.redact_errors(report::error_redactor( + config.as_ref(), + args.password.as_deref(), + )); let code = match (review, &args.workflow) { (_, Some(target)) => { workflow::execute(&client, ctx, &session, &args, target, out).await diff --git a/crates/cyber-cli/src/commands/exec/report.rs b/crates/cyber-cli/src/commands/exec/report.rs index be57b098..42c1f0e4 100644 --- a/crates/cyber-cli/src/commands/exec/report.rs +++ b/crates/cyber-cli/src/commands/exec/report.rs @@ -7,7 +7,7 @@ use std::io::Write; use std::time::Instant; use cyber_client::{Client, ClientError}; -use cyber_core::redact::Redactor; +use cyber_core::redact::{RedactSettings, Redactor}; use cyber_core::review::{Counts, ErrorCode, Findings, Target, TargetError}; use cyber_core::untrusted::UntrustedRecord; use serde_json::{Value, json}; @@ -310,8 +310,27 @@ pub struct Out { delegation: Option<(String, String)>, admission: Option<(String, String)>, review: Option, + /// Hides secrets in diagnostic fields; the built-in detectors until + /// [`Out::redact_errors`] supplies the run's configured policy. + redactor: Option>, + /// The input cohort of the driven step whose lines are being written + /// ([`Out::correlate`]). + correlation: Option, } +/// The lines a driven step produces, which name the inputs that step answers. +const STEP_LINES: [&str; 9] = [ + "assistant_text", + "reasoning", + "tool_use", + "tool_result", + "permission_denied", + "retry", + "text_delta", + "reasoning_delta", + "usage_limit", +]; + /// The `retry` stream-json payload of a `session.retry` event. fn retry_payload(data: &Value) -> Value { json!({ @@ -358,9 +377,26 @@ impl Out { delegation: None, admission: None, review: None, + redactor: None, + correlation: None, } } + /// Mark the lines of the step being written with the exact input cohort it + /// answers (`input_message_ids`), or stop marking them with `None`. + pub(super) fn correlate(&mut self, inputs: Option<&[String]>) { + self.correlation = inputs.map(|ids| json!(ids)); + } + + /// Redact diagnostic fields with `redactor` instead of the built-in detectors only. + pub fn redact_errors(&mut self, redactor: Redactor) { + self.redactor = Some(std::sync::Arc::new(redactor)); + } + + fn redactor(&self) -> &Redactor { + self.redactor.as_deref().unwrap_or(Redactor::builtin()) + } + /// Report this run as `cyber review` of `target`. pub fn review(&mut self, target: Target) { self.review = Some(Review { @@ -546,7 +582,13 @@ impl Out { if self.format != Format::StreamJson { return; } - secret_safe(&mut payload); + secret_safe(self.redactor(), &mut payload); + if let Some(inputs) = &self.correlation + && STEP_LINES.contains(&kind) + && payload.get("input_message_ids").is_none() + { + payload["input_message_ids"] = inputs.clone(); + } payload["type"] = json!(kind); payload["ts"] = json!(now_ms()); payload["session_id"] = json!(self.session_id); @@ -593,7 +635,7 @@ impl Out { pub fn error(&self, message: &str) { self.line("error", json!({ "message": message })); if self.format != Format::StreamJson && !self.quiet { - eprintln!("error: {message}"); + eprintln!("error: {}", self.redactor().redact(message).text); } } @@ -817,7 +859,11 @@ impl Out { fn emit(&self, result: Value, text: &str, args: &ExecArgs, session: &Value) { match self.format { Format::StreamJson => self.line("result", result), - Format::Json => println!("{result}"), + Format::Json => { + let mut result = result; + secret_safe(self.redactor(), &mut result); + println!("{result}"); + } _ => { if !text.is_empty() { println!("{}", text.trim_end()); @@ -1118,19 +1164,42 @@ fn summary(input: &Value) -> String { String::new() } -/// The diagnostic fields of a stream line (`error`, `message`) with every built-in -/// secret shape replaced by its marker: they carry provider, server and stdin text, +/// The diagnostic fields of a stream line (`error`, `message`) with every secret the +/// redactor finds replaced by its marker: they carry provider, server and stdin text, /// which is not otherwise filtered before it reaches the JSONL consumer. -fn secret_safe(payload: &mut Value) { +fn secret_safe(redactor: &Redactor, payload: &mut Value) { for field in ["error", "message"] { if let Some(text) = payload.get(field).and_then(Value::as_str) - && let Cow::Owned(redacted) = Redactor::builtin().redact(text).text + && let Cow::Owned(redacted) = redactor.redact(text).text { payload[field] = json!(redacted); } } } +/// The policy for diagnostic fields of a run: the built-in detectors (on even when +/// `tool_output.redact.enabled` is `false`, which governs tool output only), the +/// configured `tool_output.redact` patterns and allow list, and the exact values of +/// known secrets: secret-named environment variables, secret config entries (provider +/// keys, MCP environment and headers) and `extra` (the attach password). An unreadable +/// redaction section keeps the defaults, so a broken config still redacts. +pub fn error_redactor(config: Option<&Value>, extra: Option<&str>) -> Redactor { + let mut settings = config + .and_then(|config| RedactSettings::from_config(config).ok()) + .unwrap_or_default(); + settings.enabled = true; + let vars = std::env::vars_os() + .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?))); + let mut known = cyber_core::redact::env_secrets(vars); + known.extend( + config + .map(cyber_core::redact::config_secrets) + .unwrap_or_default(), + ); + known.extend(extra.map(str::to_owned)); + Redactor::new(&settings, known) +} + /// The `tool_result` stream line of a settlement, with its `redactions` when any. fn tool_result_line(id: &str, data: &Value) -> Value { let output = data["output"].as_str().unwrap_or_default(); @@ -1167,7 +1236,7 @@ mod tests { json!({"id": "one", "result": "kept AKIAZZZZEXAMPLE7QXYZ", "error": raw}), json!({"exit_code": 1, "error": format!("Background ownership could not be reconciled; inspect Session ses_1: {raw}")}), ] { - secret_safe(&mut line); + secret_safe(Redactor::builtin(), &mut line); let text = line.to_string(); assert!(!text.contains("sk-test-0123456789abcdef"), "{text}"); assert!(text.contains("[REDACTED:"), "{text}"); @@ -1175,16 +1244,49 @@ mod tests { assert!(!field.as_str().unwrap().contains("AKIAZZZZEXAMPLE7QXYZ")); } let mut answer = json!({"result": "AKIAZZZZEXAMPLE7QXYZ", "error": null}); - secret_safe(&mut answer); + secret_safe(Redactor::builtin(), &mut answer); assert_eq!( answer["result"], "AKIAZZZZEXAMPLE7QXYZ", "the answer is not an error" ); let mut plain = json!({"message": "unknown type \"shell\""}); - secret_safe(&mut plain); + secret_safe(Redactor::builtin(), &mut plain); assert_eq!(plain["message"], "unknown type \"shell\""); } + #[test] + fn error_fields_hide_configured_patterns_and_known_secret_values() { + let config = json!({ + "tool_output": {"redact": {"enabled": false, "patterns": ["corp-[0-9]{6}"]}}, + "providers": {"corp": {"api": {"api_key": "plainvalue-without-shape"}}}, + }); + let redactor = error_redactor(Some(&config), Some("attach-password-1")); + let raw = "id corp-123456 key plainvalue-without-shape pw attach-password-1 aws AKIAZZZZEXAMPLE7QXYZ"; + let mut line = json!({"code": "protocol", "message": raw, "error": raw}); + secret_safe(&redactor, &mut line); + for field in ["message", "error"] { + let text = line[field].as_str().unwrap(); + for secret in [ + "corp-123456", + "plainvalue-without-shape", + "attach-password-1", + "AKIAZZZZEXAMPLE7QXYZ", + ] { + assert!(!text.contains(secret), "{field}: {text}"); + } + } + // An unreadable section keeps the built-in detectors. + let broken = json!({"tool_output": {"redact": {"patterns": "not a list"}}}); + let mut line = json!({"message": raw}); + secret_safe(&error_redactor(Some(&broken), None), &mut line); + assert!( + !line["message"] + .as_str() + .unwrap() + .contains("AKIAZZZZEXAMPLE7QXYZ") + ); + } + #[test] fn settlements_with_redactions_report_them() { let data = json!({"call_id": "c1", "status": "ok", "output": "T=[REDACTED:assignment]", diff --git a/crates/cyber-cli/tests/exec_stream_input.rs b/crates/cyber-cli/tests/exec_stream_input.rs index d8dad76f..0de82a1b 100644 --- a/crates/cyber-cli/tests/exec_stream_input.rs +++ b/crates/cyber-cli/tests/exec_stream_input.rs @@ -532,6 +532,99 @@ fn jsonl_errors_do_not_echo_secrets() { } } +/// Built-in detectors do not recognise these values; the run's configured +/// `tool_output.redact` pattern and its known provider key still hide them. +#[test] +fn jsonl_errors_hide_configured_patterns_and_known_secret_values() { + const KEY: &str = "plainvalue-without-shape"; + const TICKET: &str = "corp-123456"; + let body = json!({"error":{"message":format!("rejected {TICKET} with key {KEY}"),"type":"invalid_request_error"}}); + let script = format!("fail:{body}"); + let provider = Provider::start(&[&script]); + let config = json!({ + "providers":{"corp":{"api_key":KEY,"api":{"type":"openai-compatible","url":provider.url},"models":{"main":{}}}}, + // Tool output redaction off does not turn off redaction of errors. + "tool_output":{"redact":{"enabled":false,"patterns":["corp-[0-9]{6}"]}}, + }); + let mut run = Driven::start_configured(&provider, &[], config); + let mut seen = Vec::new(); + run.send(r#"{"type":"user","id":"one","text":"go"}"#); + let result = run.until("result", &mut seen); + assert_ne!(result["exit_code"], 0, "{seen:#?}"); + assert!( + result["error"] + .as_str() + .unwrap_or_default() + .contains("rejected"), + "{seen:#?}" + ); + run.send(&format!(r#"{{"type":"ticket {TICKET} key {KEY}"}}"#)); + let end = run.until("end", &mut seen); + assert_eq!(run.exit(), Some(2)); + assert!(end["error"].as_str().is_some(), "{end}"); + let errors: Vec<&Value> = seen + .iter() + .filter(|line| ["error", "result", "end"].contains(&line["type"].as_str().unwrap_or(""))) + .collect(); + assert!(errors.len() >= 3, "{seen:#?}"); + for line in errors { + let text = line.to_string(); + assert!(!text.contains(KEY) && !text.contains(TICKET), "{text}"); + } +} + +/// Every line a driven step writes names the inputs that step answers. +#[test] +fn step_lines_name_the_inputs_they_answer() { + let provider = Provider::start(&[ + r#"bash {"command":"echo step"}"#, + "text:first answer", + "text:second answer", + ]); + let mut run = Driven::start_configured( + &provider, + &["--include-partial-messages"], + json!({"permissions":"allow"}), + ); + let mut seen = Vec::new(); + run.send(r#"{"type":"user","id":"one","text":"run it"}"#); + let first = run.until("input", &mut seen); + assert_eq!(run.until("result", &mut seen)["id"], "one"); + run.send(r#"{"type":"user","id":"two","text":"again"}"#); + let second = run.until("input", &mut seen); + assert_eq!(run.until("result", &mut seen)["id"], "two"); + run.send(r#"{"type":"end"}"#); + assert_eq!(run.until("end", &mut seen)["exit_code"], 0); + assert_eq!(run.exit(), Some(0)); + let owner = |line: &Value| line["input_message_ids"].clone(); + let lines = + |kind: &str| -> Vec<&Value> { seen.iter().filter(|line| line["type"] == kind).collect() }; + for kind in ["tool_use", "tool_result"] { + let found = lines(kind); + assert_eq!(found.len(), 1, "{seen:#?}"); + assert_eq!(owner(found[0]), json!([first["message_id"]]), "{kind}"); + } + let texts = lines("assistant_text"); + assert_eq!(texts.len(), 2, "{seen:#?}"); + assert_eq!(owner(texts[0]), json!([first["message_id"]])); + assert_eq!(owner(texts[1]), json!([second["message_id"]])); + assert!( + lines("text_delta") + .iter() + .all(|line| owner(line) == json!([first["message_id"]]) + || owner(line) == json!([second["message_id"]])), + "{seen:#?}" + ); + for kind in ["system", "input", "result", "end"] { + assert!( + lines(kind) + .iter() + .all(|line| line.get("input_message_ids").is_none()), + "{kind}: {seen:#?}" + ); + } +} + #[test] fn two_prompts_give_two_results_in_order_then_end() { let provider = Provider::start(&["text:first answer", "text:second answer"]); @@ -1837,3 +1930,256 @@ fn interrupt_stops_an_owned_subagent_and_keeps_stdin_live() { "the stopped subagent handed back" ); } + +/// The parent delegates [`CHILD_TASK`] to a foreground (synchronous) subagent and +/// answers once it returns. +const DELEGATE_FOREGROUND: [&str; 2] = [ + r#"gate:agent {"prompt":"CHILD_TASK: run it","description":"Run the child task"}"#, + "text:parent answer", +]; + +#[test] +fn a_foreground_subagent_permission_is_answered_over_stdin() { + let provider = Provider::start_split( + &DELEGATE_FOREGROUND, + &[r#"bash {"command":"echo from-child"}"#, "text:child done"], + ); + let mut run = Driven::start(&provider, &[]); + let mut seen = Vec::new(); + run.send(r#"{"type":"user","id":"delegate","text":"delegate it"}"#); + let input = run.until("input", &mut seen); + provider.release(); + approve_delegation(&mut run, &input, &mut seen); + let asked = run.until("permission_request", &mut seen); + assert_descendant(&asked, &input); + run.send( + &json!({"type":"permission_reply","request_id":asked["id"],"reply":"once"}).to_string(), + ); + let result = run.until("result", &mut seen); + assert_eq!(result["message_id"], input["message_id"], "{seen:#?}"); + assert_eq!(result["result"], "parent answer", "{seen:#?}"); + assert_eq!(result["exit_code"], 0, "{seen:#?}"); + run.send(r#"{"type":"end"}"#); + assert_eq!(run.until("end", &mut seen)["exit_code"], 0, "{seen:#?}"); + assert_eq!(run.exit(), Some(0)); + let child = child_turns(&provider); + assert_eq!(child.len(), 2, "{child:#?}"); + assert!( + child[1].to_string().contains("from-child"), + "{:#}", + child[1] + ); +} + +#[test] +fn eof_declines_a_foreground_subagent_question_and_settles_the_input() { + let provider = Provider::start_split( + &DELEGATE_FOREGROUND, + &[ + r#"question {"questions":[{"question":"Choose","header":"Choice","options":[{"label":"yes"},{"label":"no"}]}]}"#, + "text:child saw no answer", + ], + ); + let mut run = + Driven::start_configured(&provider, &[], json!({"permissions":{"question":"allow"}})); + let mut seen = Vec::new(); + run.send(r#"{"type":"user","id":"delegate","text":"delegate it"}"#); + let input = run.until("input", &mut seen); + provider.release(); + approve_delegation(&mut run, &input, &mut seen); + let asked = run.until("question", &mut seen); + assert_descendant(&asked, &input); + run.close(); + let result = run.until("result", &mut seen); + assert_eq!(result["message_id"], input["message_id"], "{seen:#?}"); + assert_eq!(result["result"], "parent answer", "{seen:#?}"); + assert_eq!(run.until("end", &mut seen)["exit_code"], 0, "{seen:#?}"); + assert_eq!(run.exit(), Some(0)); + let child = child_turns(&provider); + assert_eq!(child.len(), 2, "the child went on unanswered: {child:#?}"); + assert!( + child[1] + .to_string() + .contains("No interactive user is attached"), + "{:#}", + child[1] + ); +} + +/// Two drivers on one Session: the first driver's foreground subagent request is +/// neither shown to nor answerable by the second. +#[test] +fn a_second_driver_neither_sees_nor_answers_the_first_drivers_foreground_subagent_request() { + let provider = Provider::start_split( + &DELEGATE_FOREGROUND, + &[r#"bash {"command":"echo from-child"}"#, "text:child done"], + ); + let server = Server::start(&provider); + let url = format!("http://127.0.0.1:{}", server.port); + let attach = [ + "--attach", + url.as_str(), + "--password", + server.password.as_str(), + ]; + let mut first = Driven::start(&provider, &attach); + let mut seen = Vec::new(); + first.send(r#"{"type":"user","text":"delegate it","id":"first"}"#); + let input = first.until("input", &mut seen); + let session = input["session_id"].as_str().unwrap().to_owned(); + provider.wait_for_gate(); + let mut flags = attach.to_vec(); + flags.extend(["--session", session.as_str()]); + let mut second = Driven::start_beside(&provider, &flags, &first); + let mut other = Vec::new(); + second.until("system", &mut other); + provider.release(); + approve_delegation(&mut first, &input, &mut seen); + + let asked = first.until("permission_request", &mut seen); + assert_descendant(&asked, &input); + second.send( + &json!({"type":"permission_reply","request_id":asked["id"],"reply":"once"}).to_string(), + ); + assert_eq!(second.until("error", &mut other)["code"], "protocol"); + first.send( + &json!({"type":"permission_reply","request_id":asked["id"],"reply":"once"}).to_string(), + ); + let result = first.until("result", &mut seen); + assert_eq!( + (result["id"].as_str(), result["result"].as_str()), + (Some("first"), Some("parent answer")), + "{seen:#?}" + ); + first.send(r#"{"type":"end"}"#); + assert_eq!(first.until("end", &mut seen)["exit_code"], 0, "{seen:#?}"); + assert_eq!(first.exit(), Some(0)); + second.send(r#"{"type":"end"}"#); + assert_eq!(second.until("end", &mut other)["exit_code"], 0); + assert!( + other + .iter() + .all(|l| l["type"] != "permission_request" && l["type"] != "result"), + "{other:#?}" + ); + assert_eq!(second.exit(), Some(0)); + assert_eq!(child_turns(&provider).len(), 2, "the child's tool ran once"); +} + +/// The subagent's tool call is held at its permission request, so it has not run: +/// stopping it withdraws that request and the interruption is acknowledged. +#[test] +fn interrupt_stops_an_owned_subagent_awaiting_permission() { + let provider = Provider::start_split( + &[ + DELEGATE[0].strip_prefix("gate:").unwrap(), + DELEGATE[1], + "text:later answer", + ], + &[ + r#"bash {"command":"echo from-child > ran"}"#, + "text:child done", + ], + ); + let mut run = Driven::start(&provider, &[]); + let mut seen = Vec::new(); + run.send(r#"{"type":"user","id":"delegate","text":"delegate it"}"#); + let input = run.until("input", &mut seen); + approve_delegation(&mut run, &input, &mut seen); + let asked = run.until("permission_request", &mut seen); + assert_descendant(&asked, &input); + run.send(r#"{"type":"interrupt"}"#); + let stopped = run.until("result", &mut seen); + assert_eq!(stopped["id"], "delegate", "{seen:#?}"); + assert_eq!(stopped["error"], "Input interrupted", "{seen:#?}"); + // The withdrawn request is no longer answerable. + run.send( + &json!({"type":"permission_reply","request_id":asked["id"],"reply":"once"}).to_string(), + ); + assert_eq!( + run.until("error", &mut seen)["code"], + "protocol", + "{seen:#?}" + ); + run.send(r#"{"type":"user","id":"later","text":"continue"}"#); + assert_eq!(run.until("input", &mut seen)["status"], "admitted"); + let completed = run.until("result", &mut seen); + assert_eq!( + (completed["id"].as_str(), completed["result"].as_str()), + (Some("later"), Some("later answer")), + "{seen:#?}" + ); + run.send(r#"{"type":"end"}"#); + assert_eq!(run.until("end", &mut seen)["exit_code"], 1, "{seen:#?}"); + assert_eq!(run.exit(), Some(1)); + assert_eq!( + child_turns(&provider).len(), + 1, + "the stopped subagent went on" + ); + assert!( + !run_dir_has(&seen, "ran"), + "the withheld tool call ran: {seen:#?}" + ); +} + +/// Whether any tool result reports the marker file; the call must never run. +fn run_dir_has(seen: &[Value], marker: &str) -> bool { + seen.iter() + .any(|line| line["type"] == "tool_result" && line["output"].to_string().contains(marker)) +} + +/// Interrupting the input stops its foreground subagent with the parent's `agent` call. +/// The scoped interruption is acknowledged and stdin stays live; the child's withheld +/// call never runs. The parent's cancelled `agent` call itself settles as outcome +/// unknown: a call cancelled while its child ran cannot prove what the child did. +#[test] +fn interrupt_stops_a_foreground_subagent_awaiting_permission() { + let provider = Provider::start_split( + &[ + DELEGATE_FOREGROUND[0].strip_prefix("gate:").unwrap(), + "text:later answer", + ], + &[ + r#"bash {"command":"echo from-child > ran"}"#, + "text:child done", + ], + ); + let mut run = Driven::start(&provider, &[]); + let mut seen = Vec::new(); + run.send(r#"{"type":"user","id":"delegate","text":"delegate it"}"#); + let input = run.until("input", &mut seen); + approve_delegation(&mut run, &input, &mut seen); + let asked = run.until("permission_request", &mut seen); + assert_descendant(&asked, &input); + run.send(r#"{"type":"interrupt"}"#); + let stopped = run.until("result", &mut seen); + assert_eq!(stopped["id"], "delegate", "{seen:#?}"); + assert_eq!(stopped["exit_code"], 1, "{seen:#?}"); + let parent_call = seen + .iter() + .find(|line| line["type"] == "tool_result") + .expect("the agent call settled"); + assert_eq!(parent_call["status"], "outcome_unknown", "{seen:#?}"); + run.send(r#"{"type":"user","id":"later","text":"continue"}"#); + assert_eq!(run.until("input", &mut seen)["status"], "admitted"); + let completed = run.until("result", &mut seen); + assert_eq!( + (completed["id"].as_str(), completed["result"].as_str()), + (Some("later"), Some("later answer")), + "{seen:#?}" + ); + run.send(r#"{"type":"end"}"#); + let end = run.until("end", &mut seen); + assert_eq!( + (end["exit_code"].as_u64(), end["error"].as_str()), + (Some(1), None), + "the interruption was not acknowledged: {seen:#?}" + ); + assert_eq!(run.exit(), Some(1)); + assert_eq!( + child_turns(&provider).len(), + 1, + "the stopped subagent went on" + ); +} From a629183d9b8856589c4a1e65ac373ef588d6439f Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:29:43 -0400 Subject: [PATCH 3/3] Record foreground ownership, held-call interruption, bounds and redaction in exec-mode spec and docs Tick 5.4 and 6.2-6.4 locally; platform acceptance stays under 7.2. --- docs/features.md | 2 +- docs/local-core-guide.md | 29 ++++++++++--------- .../specs/exec-mode/spec.md | 25 ++++++++++++++-- .../complete-daily-coding-surfaces/tasks.md | 11 ++++--- 4 files changed, 46 insertions(+), 21 deletions(-) diff --git a/docs/features.md b/docs/features.md index 29ef5b81..23776074 100644 --- a/docs/features.md +++ b/docs/features.md @@ -25,7 +25,7 @@ Implemented behavior and remaining scope, reviewed on **2026-10-16** (Cross-sess | File recovery | Shadow-git snapshots, conflict-aware restore and [reviewed rewind](rewind.md) with explicit fingerprint confirmation | CLI and TUI code/conversation/both; idle Esc-Esc, staged `/undo`/`/redo` and guarded composer restoration. Private Linux/macOS file-copy snapshots, retained restore intents and read-only recovery inspection are implemented; managed resolution, journal reclamation and broader recovery acceptance remain | | Project collaboration | Self-hosted Git project hub, verified organization/friends membership, explicit published local agents, human/agent project and private conversations, held receiver consent, fenced shared tasks, CLI `/collab` TUI, the `/agents` Project hub group and typed SDK ([guide](collaboration.md), [evidence](implementation/project-collaboration.md)) | Experimental; off by default. Live Auth provisioning and multi-host deployment acceptance remain operator work | | Structured results | `cyber exec --output-schema ` and the prompt `format: {type: json_schema, schema}`: a `structured_output` finalizer with the schema as input, one submission plus two corrections (including answers without the call), `StructuredOutputError` and exit 1 after the third; the object is `result` (pretty JSON in text mode); schemas bounded to 64 KiB / 64 levels / local refs and checked before any work; per-prompt outcome in `session.structured_output.settled.1` and the inbox row ([guide](local-core-guide.md#structured-results)) | Available (P1, `complete-daily-coding-surfaces` §5); compaction and budget-exit acceptance remain | -| Driven exec | `cyber exec --input-format stream-json --format stream-json`: JSON-line prompts (`queue`/`steer`, correlation `id`), `interrupt`, owned `permission_reply`/`question_reply` through an interactive lease, `end`/EOF draining with waiting requests declined; per-prompt `input`/`result` lines and a final `end` line (`schema_version` 2); 1 MiB lines and 32 waiting prompts, fatal protocol errors exit 2; `--include-partial-messages`, atomic `--output-last-message`, per-prompt `--output-schema`; background subagent and `PreToolUse` hook asks owned through the root input cohort, scoped `interrupt` that also stops an owned background subagent subtree, and secret-redacted error, result and end lines ([guide](local-core-guide.md#driving-exec-over-stdin)) | Available (P1, `complete-daily-coding-surfaces` §6); Unix SIGINT, lost admission acknowledgements and server loss (a structured `server_lost` error with a resume hint, exit 2, no reconnect) are covered locally. Remaining: foreground-subagent ownership, `--include-hook-events` (separate change, PR #132), user-configured redaction patterns on JSONL lines, budgets and timeouts with stdin input, continuing across a server restart (needs a decision) and native platform acceptance | +| Driven exec | `cyber exec --input-format stream-json --format stream-json`: JSON-line prompts (`queue`/`steer`, correlation `id`), `interrupt`, owned `permission_reply`/`question_reply` through an interactive lease, `end`/EOF draining with waiting requests declined; per-prompt `input`/`result` lines and a final `end` line (`schema_version` 2); 1 MiB lines and 32 waiting prompts, fatal protocol errors exit 2; `--include-partial-messages`, atomic `--output-last-message`, per-prompt `--output-schema`; background and foreground subagent and `PreToolUse` hook asks owned through the root input cohort (at most 64 waiting, extras declined with a `capacity` error), step lines tagged with the `input_message_ids` they answer, scoped `interrupt` that also stops an owned subagent subtree (acknowledged when a subagent call was still waiting for permission), and error, result and end lines redacted with the built-in detectors, configured `tool_output.redact` patterns and known secret values ([guide](local-core-guide.md#driving-exec-over-stdin)) | Available (P1, `complete-daily-coding-surfaces` §6); Unix SIGINT, lost admission acknowledgements and server loss (a structured `server_lost` error with a resume hint, exit 2, no reconnect) are covered locally. Remaining: `--include-hook-events` (separate change, PR #132), budgets and timeouts with stdin input, redaction of the raw provider message the server records in `session.step.failed`, and native platform acceptance; the driver does not reconnect across a server restart (owner decision 2026-11-15) | | Clients | TUI, noninteractive `exec`, background service, HTTP/SSE/WebSocket/stdio API and generated TypeScript SDK | Available; complete P1 client surfaces remain | | Installation and upgrade | Signed releases from `.github/workflows/release.yml` on a `v*` tag: 6 macOS and Linux targets (Windows is built in CI but not released yet), `SHA256SUMS`, cosign keyless bundles and a rolling `channel-` manifest on GitHub Releases; `install.sh` (POSIX `sh`, SHA-256 and optional cosign checks, atomic install, marked PATH line, `CYBER_INSTALL_BASE_URL` mirrors); `cyber upgrade` (verified, atomic self-replace or the package manager's command), `cyber uninstall` (sizes, confirmation, no symlink following, keyring cleanup), background update notices and the `min_supported` warning; a `Dockerfile` running as uid 10001 with `CI=true` ([guide](local-core-guide.md#install-upgrade-and-uninstall)) | P0 done locally; Homebrew, npm, Scoop, WinGet, AUR, Nix and container-registry publishing are partial (manifests rendered, not published); no release has been tagged yet | | TUI | 18 built-in themes plus custom `themes/*.json` resolved to semantic tokens, truecolor/256/16-color depths, `tui.color` and `NO_COLOR` (no colors, reverse-video selection); CommonMark rendering with syntect-highlighted code blocks and `Ctrl+X y` copy (OSC 52 fallback); the composer, a status footer (cwd, context meter, cost, key hint) and a `▣ Agent · model · duration` marker after each run; the `Ctrl+P` command palette; a responsive sidebar (Context, MCP, LSP, Machine stats with CPU/memory/disk bars from `GET /system`, Modified files, branch, connection) docked from 120 columns and a drawer below; the theme switcher; the welcome screen; the `/files` explorer with permission-checked previews; the Settings panel (Status, Config with persisted preferences, Usage, Stats heatmap and book comparison line); the `/workflows` monitor (runs with live counts and per-row nyan bars, agents by phase, child transcripts, pause/resume/stop/revision/log/script keys, and a Library tab that starts library Workflows from an args form), with a sidebar Workflows section, a `⚙ 2 workflows` footer field, aggregate run progress on the progress line and run-end notices (`tui.workflow_notifications`); the Nyan progress indicator above the composer (`tui.spinner`, at most 12 frames a second, with 16-color, `NO_COLOR`, reduced-motion and screen-reader fallbacks); Session recaps after 30 minutes away (`tui.recap`); rebindable keys in `tui.keybinds`; mouse capture (`tui.mouse`) with a wheel that acts on the pane under the pointer and left clicks that do only what a key does: list rows select on the first click and activate on the second, controls (tabs, key chips, sidebar headers, explorer rows, collapsed transcript rows) act at once, a single click never answers a permission or question prompt, and clicks outside a modal panel do nothing. Model, tool and title text is drawn without control characters, and OSC 8 links are written only for safe URLs on known terminals; the sidebar has a bounded named local/team/remote Session overview sharing `/agents` data, with status/provenance and explicit directory navigation | Partial P1; the split-diff reader of `diff_style` and the `#` memory composer mode do not exist yet, and `tui.statusline.command` is not implemented | diff --git a/docs/local-core-guide.md b/docs/local-core-guide.md index 8a95aa82..a4444b70 100644 --- a/docs/local-core-guide.md +++ b/docs/local-core-guide.md @@ -703,12 +703,12 @@ cyber exec --output-schema findings.schema.json --format json "audit the depende {"type":"end"} no more input ``` -- **Output:** the `init` line has `schema_version: 2`. Each prompt gets an `input` line when it is admitted (`status: admitted` or `refused`; when a submission and its retry under the same message ID both lose the server's reply, the driver checks the Session inbox for that ID before choosing, and ends the run with exit 2 if the inbox cannot be read) and one `result` line when its answer ends, with its `id`, `message_id`, `result`, `error` and `exit_code`. Requests appear as `permission_request` and `question` lines; like every line their `session_id` is the driven Session, and `request_session_id` names the Session that asked (a subagent's child Session for a descendant request), which the reply goes to. The run ends with one `end` line: the aggregate `exit_code`, `inputs`, usage, cost and duration. `--include-partial-messages` adds `text_delta` and `reasoning_delta` lines. `--output-last-message ` writes the last answer's text to the file atomically when the run ends. -- **Requests:** the driver holds an input-only interactive lease while reading input, and starts in `default` mode unless `--mode` says otherwise. Direct permission/question lines carry server-derived `input_message_ids`: the complete input cohort recorded for their exact assistant step and tool call. The driver accepts a request only for its own Session when every identity is one of its pending admitted inputs. A background subagent's request (at any depth) reaches the driver routed to its Session; the driver claims it only when its `root_session_id` is the driven Session and every `root_input_message_ids` identity is one of its pending inputs, emits it with the child as `request_session_id`, and posts its reply to that child Session. An input stays pending while a request it owns waits, and its background subagent Job keeps it pending until the handback is answered. A permission a `PreToolUse` hook turns into `ask` is an ordinary request of its step and carries that step's cohort. A request answered elsewhere (a cascade or another route) is dropped from the driver's tracked requests. Missing or legacy request provenance stays unknown; a request ID from another input is a protocol error on reply. Each admission retains its client binding. Release/expiry settles that client's requests even while another driver, browser or stream remains attached. Reject/always replies do not cascade into another input client's requests. Nothing is ever approved automatically. +- **Output:** the `init` line has `schema_version: 2`. Each prompt gets an `input` line when it is admitted (`status: admitted` or `refused`; when a submission and its retry under the same message ID both lose the server's reply, the driver checks the Session inbox for that ID before choosing, and ends the run with exit 2 if the inbox cannot be read) and one `result` line when its answer ends, with its `id`, `message_id`, `result`, `error` and `exit_code`. Requests appear as `permission_request` and `question` lines; like every line their `session_id` is the driven Session, and `request_session_id` names the Session that asked (a subagent's child Session for a descendant request), which the reply goes to. The run ends with one `end` line: the aggregate `exit_code`, `inputs`, usage, cost and duration. `--include-partial-messages` adds `text_delta` and `reasoning_delta` lines. The lines a driven step writes (`assistant_text`, `reasoning`, `tool_use`, `tool_result`, `permission_denied`, `retry`, `text_delta`, `reasoning_delta`, `usage_limit`, and the `error` line of a failed step) carry `input_message_ids`: the exact inputs that step answers, so a program can attribute them when several prompts are queued or steered; `system`, `input`, `result`, `end` and protocol `error` lines do not. `--output-last-message ` writes the last answer's text to the file atomically when the run ends. +- **Requests:** the driver holds an input-only interactive lease while reading input, and starts in `default` mode unless `--mode` says otherwise. Direct permission/question lines carry server-derived `input_message_ids`: the complete input cohort recorded for their exact assistant step and tool call. The driver accepts a request only for its own Session when every identity is one of its pending admitted inputs. A subagent's request (at any depth, from a background subagent Job or a foreground subagent call that is still waiting for its child) reaches the driver routed to its Session; the driver claims it only when its `root_session_id` is the driven Session and every `root_input_message_ids` identity is one of its pending inputs, emits it with the child as `request_session_id`, and posts its reply to that child Session. An input stays pending while a request it owns waits, and its background subagent Job keeps it pending until the handback is answered. At most 64 owned requests wait at once; a further one is declined at once (`reject`, or a dismissed question) with an `error` line whose `code` is `capacity`, and the run goes on. A permission a `PreToolUse` hook turns into `ask` is an ordinary request of its step and carries that step's cohort. A request answered elsewhere (a cascade or another route) is dropped from the driver's tracked requests. Missing or legacy request provenance stays unknown; a request ID from another input is a protocol error on reply. Each admission retains its client binding. Release/expiry settles that client's requests even while another driver, browser or stream remains attached. Reject/always replies do not cascade into another input client's requests. Nothing is ever approved automatically. - **Ending:** after `end` or EOF nothing new is admitted and tracked owned requests, descendant ones included, are declined (`reject` for permissions, dismissed questions); the lease is released first, which settles requests bound to it (a claimed descendant request included) as unattended, so the asking Turn continues with a "no interactive user" answer. The process exits once its own inputs and retained controls settle, including while another driver still has active work in the Session. -- **Interruption:** `interrupt`, SIGINT and fatal protocol errors select only this driver's pending input identities. The runtime retains the request before stopping an owned Drain, direct process Jobs and background subagents whose Job belongs wholly to the selected inputs; queued inputs are refused. A subagent is stopped with its whole child subtree (its handback is suppressed and the child's admission stays closed) only when its child is a direct child of the Session and no other outside Job targets that subtree; a subagent shared with other work, or one whose stop leaves unknown execution such as a tool call cancelled mid-flight, is reported unknown and left for inspection. The driver polls that same request while continuing to read stdin and events, and waits through its acknowledged event revision before releasing input slots. Repeated controls without new inputs share the outstanding request. A later input keeps its own reply authority. Unknown/mixed ownership or a missing acknowledgement fails explicitly with Session/request identities for inspection and preserves recovery evidence; there is no fallback to Session-wide interruption. -- **Shared-Session work still in progress:** foreground subagents (no Job, so no root cohort), descendant work started outside a background subagent Job, complete mixed-cohort control and broader result/event and restart acceptance remain required. Direct input/Job interruption does not establish those remaining guarantees. -- **Limits and errors:** a line is at most 1 MiB and at most 32 prompts may wait for an answer. A line that is not a valid envelope, an over-long line or a 33rd waiting prompt is a fatal protocol error: an `error` line, no more input, interruption of the driver's owned inputs, and exit 2. Error text is secret-safe: the `message` of `error` lines and the `error` of `input`, `result` and `end` lines pass through the built-in secret detectors (the same `[REDACTED:]` markers as tool output), because they can carry provider error bodies, server responses or echoed stdin; answer text in `result` is not altered. +- **Interruption:** `interrupt`, SIGINT and fatal protocol errors select only this driver's pending input identities. The runtime retains the request before stopping an owned Drain, direct process Jobs and background subagents whose Job belongs wholly to the selected inputs; queued inputs are refused. A subagent is stopped with its whole child subtree (its handback is suppressed and the child's admission stays closed) only when its child is a direct child of the Session and no other outside Job targets that subtree; a subagent shared with other work, or one whose stop leaves unknown execution such as a tool call cancelled while it ran, is reported unknown and left for inspection. A subagent tool call still waiting for its permission or question reply has not run: the stop withdraws that request first, the call settles as refused, and the stop is acknowledged. A foreground subagent is stopped with the parent call that waits for it; that `agent` call settles as outcome unknown (a call cancelled while its child ran cannot itself prove what the child did) and the input fails, while the interruption is acknowledged and later input still runs. The driver polls that same request while continuing to read stdin and events, and waits through its acknowledged event revision before releasing input slots. Repeated controls without new inputs share the outstanding request. A later input keeps its own reply authority. Unknown/mixed ownership or a missing acknowledgement fails explicitly with Session/request identities for inspection and preserves recovery evidence; there is no fallback to Session-wide interruption. +- **Shared-Session work still in progress:** descendant work started outside a subagent Job or call of the driver's inputs, complete mixed-cohort control and native platform acceptance remain required. Direct input/Job interruption does not establish those remaining guarantees. +- **Limits and errors:** a line is at most 1 MiB, at most 32 prompts may wait for an answer, at most 64 owned requests wait for a reply, and at most 16 parsed lines wait for the driver (a writer further ahead blocks on its pipe). A line that is not a valid envelope, an over-long line or a 33rd waiting prompt is a fatal protocol error: an `error` line, no more input, interruption of the driver's owned inputs, and exit 2. Error text is secret-safe: the `message` of `error` lines and the `error` of `input`, `result` and `end` lines pass through the built-in secret detectors, the configured `tool_output.redact` patterns and allow list, and the exact values of known secrets (secret-named environment variables, secret config entries such as provider keys, and the `--password` of an attached server), with the same `[REDACTED:]` markers as tool output, because they can carry provider error bodies, server responses or echoed stdin. This applies even when `tool_output.redact.enabled` is `false`, which only governs tool output. Answer text in `result` is not altered. The same policy covers the `error` of a `--format json` result and the `error:` lines exec prints to stderr in text mode; other stderr notes and the raw provider message the server records in `session.step.failed` are unchanged. - **Server loss:** if the server's event stream closes (the server stops, crashes or restarts), the driver writes one `error` line with `code: "server_lost"` and a `resume` object (`session_id` and the `command` that continues the Session, with `--attach ` when attached and never the password). Inputs still waiting get a `result` line with `not answered before the run ended`, and the run ends with exit 2 and an `end` line whose `error` is `the server closed the event stream`, with the same `error_code` and `resume`. The driver does not reconnect, even when a restarted server answers at the same URL; admitted inputs stay in the Session, and running the resume command against the restarted server drives the same Session. - **Exit code:** 130 after SIGINT, 2 after a fatal protocol error or a lost server, otherwise the first failed prompt's code in admission order (1), else 0. Failure to publish `--output-last-message` makes an otherwise successful run exit 1 and reports the error in `end`; per-input results remain available. Publication uses an exclusively created sibling file, replaces a destination symlink without writing its target, and removes its temporary file on failure. `--output-schema` applies to every prompt, whose `result` is then the validated object. - **Not combined with:** a prompt argument, `--command`, `--goal`, `--timeout`, `--max-cost` or `--max-tokens` (exit 2 before any Session). `--include-hook-events` is not available yet. @@ -732,17 +732,20 @@ Session or native computer presence. A completed admission cannot switch clients on retry. Event observers can use `presence=false` with the Session replay/live stream; JSONL uses this setting while retaining its separate input lease. -A request from a background subagent's child Session (at any depth) also carries +A request from a subagent's child Session (at any depth) also carries `root_session_id` and `root_input_message_ids` when every link up to the root is -a running subagent Job with one complete, bounded input origin. If that root cohort is +a running subagent Job with one complete, bounded input origin, or a foreground +subagent call of the parent that is still waiting for the child in this server +process and whose dispatched call has a complete recorded input cohort (when both +prove one link they must agree). If that root cohort is bound to an input client, only that live client at the root's Location keeps the request waiting and can answer it; its release or expiry settles the request -unattended even while a browser or another client stays attached. Foreground or -detached children, children whose background Job has settled (for example a later -foreground resume), and mixed, malformed or oversized origins carry no root cohort -and keep their previous attendance. After a restart, requests already recorded keep -their root cohort and the Job keeps its durable input origin, but the interrupted -Job no longer lends its cohort to new requests and the old client's live attendance +unattended even while a browser or another client stays attached. Detached +children, children whose background Job has settled or whose foreground call has +returned, and mixed, malformed or oversized origins carry no root cohort and keep +their previous attendance. After a restart, requests already recorded keep +their root cohort and the Job keeps its durable input origin, but neither the interrupted +Job nor a foreground call the restart ended lends its cohort to new requests and the old client's live attendance is not recreated. The JSONL driver claims these descendant requests when their root cohort is entirely its own pending inputs (see the `Requests` item of the JSONL driver below). diff --git a/openspec/changes/complete-daily-coding-surfaces/specs/exec-mode/spec.md b/openspec/changes/complete-daily-coding-surfaces/specs/exec-mode/spec.md index 0ab8f775..f663c3b6 100644 --- a/openspec/changes/complete-daily-coding-surfaces/specs/exec-mode/spec.md +++ b/openspec/changes/complete-daily-coding-surfaces/specs/exec-mode/spec.md @@ -33,13 +33,14 @@ - **AND** scoped input leases SHALL grant neither Session-wide attendance nor native computer authority; malformed, missing scoped evidence and mixed bindings SHALL NOT fall back to legacy attendance #### Scenario: A descendant request carries its root input cohort -- **WHEN** a child Session asks for permission or a question and every link from it up to its root Session is a running background subagent Job whose immutable input origin is complete, bounded (1–32 unique identities of at most 256 UTF-8 bytes) and identical across that link's running Jobs +- **WHEN** a child Session asks for permission or a question and every link from it up to its root Session is proven, either by a running background subagent Job whose immutable input origin is complete, bounded (1–32 unique identities of at most 256 UTF-8 bytes) and identical across that link's running Jobs, or by the parent's foreground (synchronous) subagent call that is running in this server process and whose exact dispatched call has such a complete recorded input cohort +- **AND** when a running Job and a running foreground call both prove one link, their cohorts are identical - **THEN** the durable and routed request SHALL expose `root_session_id` and that root link's `root_input_message_ids` - **AND** when the root cohort is bound to an input client, only that live client at the bound Session and Location SHALL keep the request waiting and have its reply accepted; its release or expiry SHALL settle the request unattended without borrowing browser, stream or other client attendance -- **WHEN** a link is missing (a foreground or detached child, or one whose background Job is no longer running), mixed, malformed, oversized, cyclic or deeper than 32 links +- **WHEN** a link is missing (a detached child, one whose background Job is no longer running, or one whose foreground call has returned), mixed, malformed, oversized, cyclic or deeper than 32 links - **THEN** the request SHALL carry no root cohort and SHALL keep its existing attendance; it SHALL grant no inferred input ownership - **WHEN** the server restarts -- **THEN** the root cohort SHALL remain derivable from durable Job provenance and recorded requests, but SHALL NOT recreate the bound client's live attendance, and the interrupted Job SHALL NOT stamp new requests +- **THEN** the root cohort SHALL remain derivable from durable Job provenance and recorded requests, but SHALL NOT recreate the bound client's live attendance, and neither the interrupted Job nor the foreground call that the restart ended SHALL stamp new requests #### Scenario: The driver owns descendant and hook-originated requests - **WHEN** a request routed to the driven Session carries `root_session_id` equal to that Session and every `root_input_message_ids` identity is a pending input of the driver @@ -98,6 +99,10 @@ - **THEN** the interruption SHALL suppress that Job's handback and stop the child subtree through the subtree stop path, counting the Job only when that stop is acknowledged - **AND** a mixed, detached, oversized or otherwise unproven descendant SHALL remain running and the receipt SHALL report `descendant_job` with status unknown - **AND** a subtree stop that leaves unknown execution, such as a tool call cancelled mid-flight, SHALL report unknown and keep the child's admission closed for recovery +- **WHEN** a subtree tool call is still held at its permission or question request +- **THEN** the stop SHALL withdraw that request before cancelling the call, the call SHALL settle as refused without running, and that call SHALL NOT make the stop unknown +- **WHEN** the selected Drain is running a foreground subagent call +- **THEN** cancelling that Drain SHALL stop the child with the call, and the call SHALL settle as outcome unknown, because a call cancelled while its child ran cannot itself prove the child's effects; the input SHALL fail while later input stays admissible #### Scenario: Bounded background ownership lookup - **WHEN** an authenticated client queries Job state for 1–32 unique input identities, each at most 256 UTF-8 bytes @@ -141,6 +146,20 @@ - **AND** concurrent writers SHALL publish complete answers and clean up their own temporary files, including after publication failure - **AND** a publication failure SHALL preserve per-input results, report the error in `end`, and fail an otherwise successful aggregate run without replacing an existing interruption or protocol exit code +#### Scenario: Owned requests and buffered input stay bounded +- **WHEN** an owned request arrives while 64 owned requests already wait for this driver +- **THEN** the driver SHALL decline it at once (`reject` for a permission, dismissal for a question) and write an `error` line with code `capacity` naming the request, without tracking it or ending the run +- **AND** at most 16 parsed stdin lines SHALL wait for the control loop, so a writer that runs further ahead is held back by its own pipe + +#### Scenario: Step lines name the inputs they answer +- **WHEN** the driver writes an `assistant_text`, `reasoning`, `tool_use`, `tool_result`, `permission_denied`, `retry`, `text_delta`, `reasoning_delta` or `usage_limit` line for a step whose recorded input cohort belongs to it, or the `error` line of that step's failure +- **THEN** the line SHALL carry that step's `input_message_ids`; `system`, `input`, `result` and `end` lines and protocol errors SHALL NOT, and request lines keep their server-derived provenance + +#### Scenario: Error text is secret-safe +- **WHEN** a JSONL line carries diagnostic text in `error` or `message`, including provider error bodies, server responses and echoed stdin +- **THEN** the driver SHALL replace every secret found by the built-in detectors, the configured `tool_output.redact` patterns (minus its allow list) and the exact values of known secrets (secret-named environment variables, secret configuration entries and the attach password) with its redaction marker, also when `tool_output.redact.enabled` is `false` +- **AND** answer text in `result` SHALL NOT be altered + #### Scenario: Completed inputs do not consume pending capacity - **WHEN** a driver emits terminal results across a run longer than its pending-input limit - **THEN** it SHALL release completed text, structured results and correlation records, retaining only bounded aggregate accounting diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index ace4fe4b..bad4252d 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -182,12 +182,12 @@ proof/reconciliation for these cuts before claiming complete managed recovery. - [x] 5.1 Add validated per-prompt root format admission, bounded schema compilation and durable schema/attempt ownership without changing existing child contracts. - [x] 5.2 Add `structured_output` finalization, two correction retries, budget/interrupt handling and durable successful/error result settlement. - [x] 5.3 Add `--output-schema`, API/SDK result fields and text/JSON/stream rendering; preserve unstructured commands and validate option combinations before admission. -- [ ] 5.4 Test valid/invalid schemas, malformed results, retry exhaustion, missing finalizer, compaction, restart/retry identity, budget exits and independent queued prompts with a real server/scripted provider. Local functional cases pass: schema bounds, admission refusal, malformed/invalid submissions, retry exhaustion, missing finalizer, compaction during correction, independent queued schemas, shutdown/resume, interruption/budget outcomes, terminal writer cuts, post-commit acknowledgement loss, steering ownership, and CLI budget/timeout exit 4 and Unix SIGINT exit 130. Current-source platform acceptance remains required; this task is not accepted from local results alone. +- [x] 5.4 Test valid/invalid schemas, malformed results, retry exhaustion, missing finalizer, compaction, restart/retry identity, budget exits and independent queued prompts with a real server/scripted provider. Local functional cases pass: schema bounds, admission refusal, malformed/invalid submissions, retry exhaustion, missing finalizer, compaction during correction, independent queued schemas, shutdown/resume, interruption/budget outcomes, terminal writer cuts, post-commit acknowledgement loss, steering ownership, and CLI budget/timeout exit 4 and Unix SIGINT exit 130. 2026-11-16: no further gap found; every non-platform item is covered locally, so the task is ticked. Current-source platform acceptance is not claimed here and remains recorded under 7.2. ## 6. Streaming JSONL input - [x] 6.1 Define typed version-2 envelopes, correlation, resource bounds, aggregate exit rules and driver-owned interactive request lifetime; document compatibility and unsupported combinations. -- [ ] 6.2 Implement concurrent bounded parsing/admission and exact owned permission/question replies, retained request lookup, interrupt and end/EOF draining without stopping unrelated work. Basic parsing/admission merged in #117. Local continuations retire completed payloads and bind direct model requests to the complete recorded input cohort. Background-descendant and hook-ask ownership are implemented below; foreground-descendant ownership, broader event/result correlation and remaining resource bounds still need implementation and acceptance. Direct input presence is implemented below; full platform acceptance remains required. Direct scoped interruption integration is recorded below. Scoped interruption now also stops an owned background subagent: a running subagent Job whose complete durable cohort is within the selection, whose child is a direct child of the Session and whose bounded (256-Session) subtree no outside Job targets, has its handback suppressed and its child subtree stopped through the subtree stop path under the interruption's lifecycle lease; it counts in `jobs_cancelled` only when that stop acknowledges, and the receipt never acknowledges native effects (`interrupt_stops_an_owned_subagent_subtree`, real-binary `interrupt_stops_an_owned_subagent_and_keeps_stdin_live`). A child also targeted by another Job stays running and reports `descendant_job` unknown (`interrupt_leaves_a_mixed_cohort_subagent_running_and_reports_unknown`); a subagent stopped while one of its tool calls is in flight (for example awaiting permission) reports unknown because that call's outcome is unknown. Direct Job/handback retirement is implemented below; this task remains open. +- [x] 6.2 Implement concurrent bounded parsing/admission and exact owned permission/question replies, retained request lookup, interrupt and end/EOF draining without stopping unrelated work. Basic parsing/admission merged in #117. Local continuations retire completed payloads and bind direct model requests to the complete recorded input cohort. Background-descendant and hook-ask ownership are implemented below; foreground-descendant ownership, broader event/result correlation and remaining resource bounds still need implementation and acceptance. Direct input presence is implemented below; full platform acceptance remains required. Direct scoped interruption integration is recorded below. Scoped interruption now also stops an owned background subagent: a running subagent Job whose complete durable cohort is within the selection, whose child is a direct child of the Session and whose bounded (256-Session) subtree no outside Job targets, has its handback suppressed and its child subtree stopped through the subtree stop path under the interruption's lifecycle lease; it counts in `jobs_cancelled` only when that stop acknowledges, and the receipt never acknowledges native effects (`interrupt_stops_an_owned_subagent_subtree`, real-binary `interrupt_stops_an_owned_subagent_and_keeps_stdin_live`). A child also targeted by another Job stays running and reports `descendant_job` unknown (`interrupt_leaves_a_mixed_cohort_subagent_running_and_reports_unknown`); a subagent stopped while one of its tool calls runs reports unknown because that call's outcome is unknown, while a call still held at its permission or question request is now settled first (see the 2026-11-16 note below). Direct Job/handback retirement is implemented below. 2026-11-16: foreground-descendant ownership, the remaining resource bounds and step-line correlation are implemented (notes below), so every non-platform item is done and the task is ticked; native platform acceptance remains recorded under 7.2. - Process and subagent Jobs now persist the original dispatched step/call, attempt, operation key and complete input cohort. Direct/detached legacy calls retain unknown provenance. The CLI now uses this proof for bounded direct Job/handback retirement; descendant ownership and scoped cancellation remain open. - `POST /jobs/input-state` now aggregates running/unadmitted-handback state at the Store into at most 32 small records. Complete valid cohorts must belong to the supplied Session/input set; mixed, missing or malformed proof grants no inferred ownership. Authenticated HTTP, bounds/read-only, actual background dispatch/handback and large-payload lookup regressions pass. The query now also tracks pending handback steps and the observed Session revision; CLI adoption of those barriers is recorded below. Scoped control integration is recorded below. - Handback admission and notifier acceptance now commit together before inference; rejected notifier writes roll back both. Exact retry reconciles historical split admissions. Request/nested-Job input provenance resolves through the earlier matching admission/notification and immutable original Job cohort, including new steering and bounded union. Six provenance tests, 14 Job and 22 request integration tests and 26 actual process/subagent cases pass, including an owned permission after handback and a nested running Job retained by the original input query. CLI retirement and step correlation are implemented below; broader correlation and descendant scoped cancellation remain open. @@ -197,8 +197,11 @@ proof/reconciliation for these cuts before claiming complete managed recovery. - Direct input-client presence now uses separate expiring leases and atomic admission bindings, with observational JSONL event streams. Exact retry cannot rebind, restart cannot recreate live authority, missing scoped metadata cannot fall back to legacy attendance, and expiry/reply/cascade checks preserve other clients' requests. Local verification passes 472 server library (one subprocess fixture ignored), six input-client, ten browser, 22 request, nine interruption, 16 Goal, 88 HTTP, 19 client library, 105 CLI unit and 18 real JSONL cases; SDK typecheck and 139 tests pass with ten configured skips. Full descendant/hook ownership, mixed-cohort behavior, protocol restart/lost-ack and platform acceptance remain open. Native CI prerequisite failure is now explicit and dependent proofs require successful sandbox setup; this grants no acceptance from skipped cases. - Descendant request provenance: a permission/question request from a child Session now carries `root_session_id` and `root_input_message_ids` (durably in `permission.asked`/`question.asked`, in pending/routed requests, OpenAPI and the TS SDK) when every link up to the root is a running background subagent Job whose immutable `input_origin` is complete, bounded and identical across that link's running Jobs; a settled or restart-interrupted Job lends nothing, so a later foreground resume of the child is unstamped and a background resume uses the new running Job's cohort (`runtime/requests/descendant_inputs.rs`, at most 32 links and 8 Jobs per link). Scoped attendance (`input_clients::request_attendance`) then uses the root cohort: only the live input client bound to it at the root Location keeps the request waiting, accepts its reply and drives Goal unattended-ask timing; release/expiry settles it unattended without borrowing browser/stream/other-client attendance. Foreground/detached, mixed, malformed, oversized or cyclic lineage stamps nothing and keeps existing attendance. Evidenced by `a_subagent_request_carries_the_parents_input_cohort`, `a_descendant_request_waits_only_for_its_bound_input_client`, `mixed_or_detached_descendant_requests_grant_no_ownership` `descendant_cohort_survives_restart_as_provenance_not_attendance` (three fail without the stamp) and `a_foreground_resume_after_the_background_job_settled_inherits_no_cohort` (fails without the running-Job check, as does the restart case), three unit tests for complete/mixed/malformed/cyclic lineage and settled/resumed Jobs, 479 server library, 666 ci-profile server (lib + input-client, request, child-ownership, HTTP, Job, Goal, interruption, interactive-client, team suites), 12 background-subagent tool and 30 real JSONL cases; SDK typecheck and 139 tests pass with ten configured skips. Open: the JSONL driver does not yet claim or answer descendant requests, foreground subagents (no Job) carry no root cohort, descendant scoped interruption/cancellation, hook presence and full platform acceptance. - JSONL descendant/hook ownership: the driver (`exec/driver.rs`, `exec/inputs.rs` `request_cohort`) now claims a permission/question routed to its Session from a child Session when `root_session_id` is its Session and every `root_input_message_ids` identity is one of its pending inputs; the line keeps the run's `session_id` and adds `request_session_id` (the asking child), the retained Ask posts the reply to that child Session, an input stays pending while an Ask it owns waits (on top of the running-Job/handback hold), and EOF/end releases the lease (settling bound descendant asks unattended) then declines the rest. A `PreToolUse` hook `ask` opens an ordinary step-cohort request and is owned like a direct ask. Bug fixed: durable/routed `permission.replied`/`question.replied` carry `request_id`, not `id`, so a request answered elsewhere was never dropped from the driver's asks (regression `a_request_answered_elsewhere_leaves_the_drivers_asks`, fails without the fix). Evidenced by real-binary `a_subagent_permission_is_answered_over_stdin`, `eof_declines_a_subagent_question_and_settles_the_input`, `a_hook_ask_is_owned_by_the_driver` and, against a real `cyber serve`, `a_second_driver_neither_sees_nor_answers_the_first_drivers_subagent_request` (all four fail without the driver change), plus the unit test `a_descendant_request_is_owned_only_through_its_complete_root_cohort`; 34 real JSONL, 17 delegation, 18 lifecycle-hook and 117 CLI unit cases pass under nextest ci. Open: foreground subagents (no Job, no root cohort) are still not claimed, descendant scoped interruption/cancellation, and full platform acceptance. -- [ ] 6.3 Emit per-input results, optional partial/hook events and atomic last-message output with bounded backpressure and secret-safe errors. `--include-hook-events` is delivered by the separate `add-exec-hook-events` change (PR #132), which covers single-prompt and driven runs; this change does not implement it. Secret-safe errors: every JSONL line's `error`/`message` field is passed through the built-in `cyber-core` redactor (`exec/report.rs` `secret_safe`) before it is written, so provider error bodies, server/background reconciliation errors and echoed stdin in protocol errors show `[REDACTED:]` instead of the value; evidenced by the real-binary `jsonl_errors_do_not_echo_secrets` (a provider HTTP 400 body with `TOKEN=` and an AWS key, then a protocol error echoing an `api_key=` type, checked across `error`, `result` and `end`) and the unit test `error_result_and_end_fields_never_carry_a_secret_literally`. Open: user-configured redaction patterns and known config/env secrets are not applied on this path (built-in detectors only), text-mode stderr is unchanged, and the server still records the raw provider message in `session.step.failed`. -- [ ] 6.4 Test multiple inputs, steering/queueing, malformed/oversized input, capacity, stale/cross-request replies, EOF while awaiting input, slow stdout, SIGINT, server restart and lost admission acknowledgement. Done: multiple inputs in order, per-input structured results, structured/plain steering while inference is gated, long-run slot retirement, malformed and oversized input (exit 2), a 33rd pending input refused as a protocol error (exit 2) with every admitted input still settled, a stalled stdout reader that delays but neither loses nor reorders results, unknown request replies, EOF while a request waits, unsupported combinations, with the real binary (`cyber-cli/tests/exec_stream_input.rs`). Stale, wrong-kind and cross-driver replies are refused with a `protocol` error line while the run goes on: a second reply to an already answered permission (`a_second_reply_to_an_answered_request_is_a_protocol_error`), a `question_reply` naming a permission request, which leaves it pending so the correct `permission_reply` still runs the tool once (`a_question_reply_naming_a_permission_does_not_consume_it`), and, against a real `cyber serve`, a second driver attached to the same Session and Location that never sees the first driver's `permission_request` and whose reply to it is refused while the first driver still answers it (`a_second_driver_cannot_reply_to_the_first_drivers_request`). A lost admission acknowledgement is covered against a real `cyber serve` through a proxy that commits each prompt but drops its response: after the client's three same-key retries also lose theirs, the driver resends the same message identity and the input is admitted, answered and sent to the model once (`a_lost_admission_acknowledgement_is_retried_without_a_second_prompt`). When the retried admission loses its response too, the driver reads the Session inbox: the committed input is reported admitted and answered once (`an_admission_whose_retry_is_also_lost_is_confirmed_from_the_inbox`), and an unreadable inbox ends the run with exit 2 instead of a false `refused` (`an_unconfirmable_admission_fails_the_run`). A server killed under an attached driver ends the run with exit 2 (`the server closed the event stream`), settles the admitted input as unanswered without hanging, and the restarted server still holds that input in the Session inbox; the driver does not reconnect across a restart. Owner decision 2026-11-15 keeps that (no reconnect) and adds a structured `server_lost` `error` line and `end.error_code`/`end.resume` naming the Session and the command that continues it: the server is restarted while the driver is still attached through a proxy that already points at the new server, the driver still ends with exit 2, sends no second input, the inbox holds the input once, and the resume command drives the same Session (`a_server_restart_under_an_attached_driver_ends_with_a_resume_hint_and_keeps_the_input`). Descendant and hook-originated requests: a background subagent's permission answered over stdin (`a_subagent_permission_is_answered_over_stdin`), EOF settling a subagent's question and the input (`eof_declines_a_subagent_question_and_settles_the_input`), a `PreToolUse` hook `ask` owned by the driver (`a_hook_ask_is_owned_by_the_driver`) and a second driver that neither sees nor answers the first driver's subagent request (`a_second_driver_neither_sees_nor_answers_the_first_drivers_subagent_request`). Descendant interruption: an owned background subagent stopped by `interrupt` while stdin stays live for a later input (`interrupt_stops_an_owned_subagent_and_keeps_stdin_live`), with runtime cases for an owned nested subtree and a mixed-cohort child left running. Open: foreground-subagent ownership, acknowledged interruption of a subagent with an in-flight tool call, and continuing an attached run across a server restart if that is wanted. Current local evidence includes 35 real JSONL cases (including secret-safe error, result and end lines), Unix owned background SIGINT and seven actual shared-Session controller tests; foreground-descendant ownership, complete mixed-cohort behavior, full restart/lost-ack and platform acceptance remain open. + - 2026-11-16 foreground-descendant ownership: a foreground (synchronous) `agent` call now lends its exact dispatched call's complete recorded input cohort to its child while the call waits for it in this server process (`runtime/foreground_children.rs`, registered by `JobAdmission::lend_foreground` from `tools/agent.rs` before the child is created, withdrawn when the call returns, fails or is cancelled; a restart drops it). `descendant_inputs::recorded` accepts that live link as a proof of one parent/child link beside running background Jobs; when both prove a link they must agree. The JSONL driver needs no change: the child's requests carry `root_session_id`/`root_input_message_ids`, so they are claimed, answered over stdin, invisible to and unanswerable by a second driver, and settled by EOF exactly like background ones. Evidence: real-binary `a_foreground_subagent_permission_is_answered_over_stdin`, `eof_declines_a_foreground_subagent_question_and_settles_the_input`, `a_second_driver_neither_sees_nor_answers_the_first_drivers_foreground_subagent_request` (all three fail without the link: the request is never claimed and the driver times out) and `interrupt_stops_a_foreground_subagent_awaiting_permission` (the scoped interruption is acknowledged, the child stops without running its withheld call and later input runs; the parent's cancelled `agent` call settles as `outcome_unknown` because a call cancelled while its child ran cannot itself prove the child's effects, which the spec now states); unit `a_live_foreground_call_lends_its_cohort_and_must_agree_with_running_jobs` and `a_link_lends_only_while_bound_and_a_stale_unbind_keeps_a_newer_link`. + - 2026-11-16 acknowledged interruption with a held call: a subtree stop now withdraws the subtree's waiting requests before it cancels any actor, and the permission and question waits prefer an already delivered reply over a later cancellation (`biased` select in `host.rs` `ask` and `tools/session.rs`); an approval that meets a cancellation still aborts, so it never runs a cancelled call. A call held at its request therefore settles as refused without running instead of `outcome_unknown`, and the scoped interruption is acknowledged. A tool call that is actually running when cancelled still reports unknown. Bug fixed with regression `interrupt_stops_an_owned_subagent_awaiting_permission` (failed before with "Input interruption could not be reconciled"; it now checks the withdrawn request is refused as a protocol error, the call never ran and a later input still runs). + - 2026-11-16 resource bounds and correlation: at most 64 owned requests are tracked; a further owned request is declined at once (`reject`/dismissed) with a non-fatal `error` line of code `capacity` (`an_owned_request_beyond_the_bound_is_declined_at_once`). At most 16 parsed stdin lines (each ≤1 MiB) wait for the control loop, down from 64. Lines a driven step writes (`assistant_text`, `reasoning`, `tool_use`, `tool_result`, `permission_denied`, `retry`, `text_delta`, `reasoning_delta`, `usage_limit` and the failed step's `error`) now carry that step's `input_message_ids`; `system`, `input`, `result`, `end` and protocol errors do not (`step_lines_name_the_inputs_they_answer`). +- [x] 6.3 Emit per-input results, optional partial/hook events and atomic last-message output with bounded backpressure and secret-safe errors. `--include-hook-events` is delivered by the separate `add-exec-hook-events` change (PR #132), which covers single-prompt and driven runs; this change does not implement it. Secret-safe errors: every JSONL line's `error`/`message` field is passed through the built-in `cyber-core` redactor (`exec/report.rs` `secret_safe`) before it is written, so provider error bodies, server/background reconciliation errors and echoed stdin in protocol errors show `[REDACTED:]` instead of the value; evidenced by the real-binary `jsonl_errors_do_not_echo_secrets` (a provider HTTP 400 body with `TOKEN=` and an AWS key, then a protocol error echoing an `api_key=` type, checked across `error`, `result` and `end`) and the unit test `error_result_and_end_fields_never_carry_a_secret_literally`. 2026-11-16: the same lines now also apply the run's configured `tool_output.redact` patterns and allow list (built-in detectors stay on even with `enabled: false`) and the exact values of known secrets: secret-named environment variables, secret config entries and the `--password` of an attached server (`report::error_redactor`; real-binary `jsonl_errors_hide_configured_patterns_and_known_secret_values`, which fails without the change, and unit `error_fields_hide_configured_patterns_and_known_secret_values`). The `error` of a `--format json` result and the `error:` lines of text mode use the same policy (trivially in scope: the same `Out` path); other stderr notes are unchanged. Still open and outside this task's emitted-output scope: the server records the raw provider message in `session.step.failed`. `--include-hook-events` merged in #132. Every non-platform item is done, so the task is ticked; native platform acceptance remains recorded under 7.2. +- [x] 6.4 Test multiple inputs, steering/queueing, malformed/oversized input, capacity, stale/cross-request replies, EOF while awaiting input, slow stdout, SIGINT, server restart and lost admission acknowledgement. Done: multiple inputs in order, per-input structured results, structured/plain steering while inference is gated, long-run slot retirement, malformed and oversized input (exit 2), a 33rd pending input refused as a protocol error (exit 2) with every admitted input still settled, a stalled stdout reader that delays but neither loses nor reorders results, unknown request replies, EOF while a request waits, unsupported combinations, with the real binary (`cyber-cli/tests/exec_stream_input.rs`). Stale, wrong-kind and cross-driver replies are refused with a `protocol` error line while the run goes on: a second reply to an already answered permission (`a_second_reply_to_an_answered_request_is_a_protocol_error`), a `question_reply` naming a permission request, which leaves it pending so the correct `permission_reply` still runs the tool once (`a_question_reply_naming_a_permission_does_not_consume_it`), and, against a real `cyber serve`, a second driver attached to the same Session and Location that never sees the first driver's `permission_request` and whose reply to it is refused while the first driver still answers it (`a_second_driver_cannot_reply_to_the_first_drivers_request`). A lost admission acknowledgement is covered against a real `cyber serve` through a proxy that commits each prompt but drops its response: after the client's three same-key retries also lose theirs, the driver resends the same message identity and the input is admitted, answered and sent to the model once (`a_lost_admission_acknowledgement_is_retried_without_a_second_prompt`). When the retried admission loses its response too, the driver reads the Session inbox: the committed input is reported admitted and answered once (`an_admission_whose_retry_is_also_lost_is_confirmed_from_the_inbox`), and an unreadable inbox ends the run with exit 2 instead of a false `refused` (`an_unconfirmable_admission_fails_the_run`). A server killed under an attached driver ends the run with exit 2 (`the server closed the event stream`), settles the admitted input as unanswered without hanging, and the restarted server still holds that input in the Session inbox; the driver does not reconnect across a restart. Owner decision 2026-11-15 keeps that (no reconnect) and adds a structured `server_lost` `error` line and `end.error_code`/`end.resume` naming the Session and the command that continues it: the server is restarted while the driver is still attached through a proxy that already points at the new server, the driver still ends with exit 2, sends no second input, the inbox holds the input once, and the resume command drives the same Session (`a_server_restart_under_an_attached_driver_ends_with_a_resume_hint_and_keeps_the_input`). Descendant and hook-originated requests: a background subagent's permission answered over stdin (`a_subagent_permission_is_answered_over_stdin`), EOF settling a subagent's question and the input (`eof_declines_a_subagent_question_and_settles_the_input`), a `PreToolUse` hook `ask` owned by the driver (`a_hook_ask_is_owned_by_the_driver`) and a second driver that neither sees nor answers the first driver's subagent request (`a_second_driver_neither_sees_nor_answers_the_first_drivers_subagent_request`). Descendant interruption: an owned background subagent stopped by `interrupt` while stdin stays live for a later input (`interrupt_stops_an_owned_subagent_and_keeps_stdin_live`), with runtime cases for an owned nested subtree and a mixed-cohort child left running. 2026-11-16: foreground-subagent ownership (answer over stdin, EOF settlement, second-driver isolation, interruption) and acknowledged interruption of a subagent whose call awaits permission are covered (see 6.2 notes); continuing across a server restart is decided against (owner decision 2026-11-15, `server_lost` with resume hint). Current local evidence: 41 real JSONL cases, Unix owned background SIGINT and eight actual shared-Session controller tests. Mixed-cohort descendants stay running and report `descendant_job` unknown by design. Every non-platform item is done, so the task is ticked; native platform acceptance remains recorded under 7.2. ## 7. Review and delivery