diff --git a/oxa/docs/lead.md b/oxa/docs/lead.md index 1a3cba68f..1e10dc0c8 100644 --- a/oxa/docs/lead.md +++ b/oxa/docs/lead.md @@ -4,9 +4,31 @@ The lead is an ordinary oxa session with an embedded, lead-only `lead` skill. Its instructions are exported as `oxa_resources::LEAD_SKILL` for the preset; ordinary sessions neither discover nor install this skill. It does not enable runner access by itself. -`oxa lead`, its restricted session preset, the `work` tool and the commands below -are pending integration with the runner. Do not use this document as a list of -commands supported by the current binary. +Shadow is disabled by default. Enable `"oxa.lead.shadow": true` in the user's +`settings.json`; project settings cannot enable it. Then `oxa lead --shadow` +opens an ordinary TUI or print session restricted to +`read`, `grep`, `find` and `ls`. It embeds the lead instructions in every prefix +epoch and enforces the proposal schema. For example: + +```console +$ oxa lead --shadow -p "Read the bounded exports in ./state and propose the next action." +``` + +It emits proposals only. `oxa lead` without `--shadow` refuses explicitly until +live runner coordination is available. The `work` tool, live `/status`, `/asks`, +`/hold`, `/decide` and event wake-up remain pending. Shadow mode neither executes +proposals nor establishes that a supplied export is current. + +The preset removes mutating tools from the registry, bypasses external hook, +extension, MCP, subagent and codemode construction, and refuses typed shell +escapes. It accepts model/session/TUI flags, but owns its schema and resource +selection; explicit extension/skill/template/schema overrides and mutating tool +requests are rejected. The same restrictions apply on continuation and reopen. +Reload retains the preset's resources, and resuming an ordinary session rebuilds +its prefix with the lead instructions and restricted declarations. Goal mode is +not supported: `--goal` and saved sessions containing a goal refuse explicitly. +Project executable resources are not trusted by this preset. Read tools still +use ordinary path permissions; no sandbox or secret policy is relaxed. The preset must work with both the TUI and print driver, using the same session store, engine selection, turn loop and result contract as ordinary oxa. It adds diff --git a/oxa/docs/pages/cli.md b/oxa/docs/pages/cli.md index 3de205b04..2ba86c6b2 100644 --- a/oxa/docs/pages/cli.md +++ b/oxa/docs/pages/cli.md @@ -175,6 +175,7 @@ $ oxa mcp logout | `--list-models [search]` | list the models the engine serves, optionally filtered by a fuzzy search, and exit | | `--thinking ` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh` or `max` | | `--mode ` | output mode: `text` (default), `json` or `rpc` ([rpc.md](rpc.md)) | +| `--shadow` | required with `oxa lead`; read-only proposal preset, enabled only by user setting `oxa.lead.shadow` (default false) | | `--output-schema ` | check the final answer against a JSON schema file (a supported subset), retrying once on mismatch | | `--print`, `-p` | non-interactive: process the prompts and exit | | `--goal ` | pursue a stored UTF-8 objective in print/JSON mode; continue the saved pursuing goal after restart | diff --git a/oxa/docs/pages/settings.md b/oxa/docs/pages/settings.md index 72e99e30b..5e5990b77 100644 --- a/oxa/docs/pages/settings.md +++ b/oxa/docs/pages/settings.md @@ -27,7 +27,7 @@ Settings that older files may contain but oxa does not implement are not listed Where the user file alone counts, the table says so: -- user settings only: `defaultProjectTrust`, `httpProxy`, `oxa.allowHomeCwd`, `oxa.offline`, `oxa.engine.allowRemote`, `oxa.engine.inProcessCloud`, `oxa.cloud`, `oxa.engine.inProcessLocal`, `oxa.local`, `oxa.lead.serve`, and every `oxa.sandbox.*` key. A project file cannot set them, because a project file cannot widen what the model can reach. +- user settings only: `defaultProjectTrust`, `httpProxy`, `oxa.allowHomeCwd`, `oxa.offline`, `oxa.engine.allowRemote`, `oxa.engine.inProcessCloud`, `oxa.cloud`, `oxa.engine.inProcessLocal`, `oxa.local`, `oxa.lead.shadow`, `oxa.lead.serve`, and every `oxa.sandbox.*` key. A project file cannot set them, because a project file cannot widen what the model can reach. - project settings are trust-gated. In an untrusted project they are not read. Project files that run or load code (`hooks`, `shellPath`, `shellCommandPrefix`, `packages`, `extensions`, `skills`, `prompts`) also need the content approval described in [security.md](security.md#project-trust). Interactive selectors (`/settings`, `/thinking` and `/model` with Ctrl+S) write the user file. @@ -170,6 +170,7 @@ The compaction rules are in [compaction.md](compaction.md). | `oxa.engine.allowRemote` | bool | `false` | allow an engine on another host; user settings only | | `oxa.engine.inProcessLocal` | bool | `false` | select the in-process owned local engine, including offline; user settings only | | `oxa.local` | object | `{}` | literal native binary/model/arguments/environment and model limits; user settings only; see [native local configuration](../../oxc-local/CONFIGURATION.md) | +| `oxa.lead.shadow` | bool | `false` | enable the read-only `oxa lead --shadow` proposal preset; user settings only; no live runner actions | | `oxa.engine.inProcessCloud` | bool | `false` | select the in-process Rust cloud gateway for sessions and model discovery; user settings only | | `oxa.cloud` | object | `{}` | native cloud models, prices, USD budget and subscription caps; user settings only; see below | | `oxa.lead.serve` | object | `{}` | the lead web access scaffold: `enabled`, `identity` (`local` or `tailscale`), `bind` (a loopback address), `port`, `allowed_identities`. Off by default and no listener is installed yet; user settings only. See [lead-web.md](lead-web.md) | diff --git a/oxa/oxa-cli/src/args.rs b/oxa/oxa-cli/src/args.rs index 0015e4ac5..dd79524a5 100644 --- a/oxa/oxa-cli/src/args.rs +++ b/oxa/oxa-cli/src/args.rs @@ -61,6 +61,9 @@ impl std::fmt::Debug for ApiKey { /// Every flag of cli.md that oxa keeps. Field comments give the spellings. #[derive(Debug, Clone, PartialEq, Default)] pub struct Args { + /// Explicit lead shadow preset; ordinary sessions retain their existing tools. + pub lead: bool, + pub shadow: bool, pub subcommand: Option, /// Positional prompt words (each is one prompt in print/json mode, as pi). pub messages: Vec, @@ -322,6 +325,7 @@ const OPTIONS: &[(&str, &str)] = &[ "Disable built-in tools by default, keep extension and custom tools", ), ("--no-tools, -nt", "Disable all tools by default"), + ("--shadow", "Lead preset only: return proposals without executing actions"), ( "--no-mcp", "Disable MCP support: no servers connect and no MCP tools", @@ -541,6 +545,10 @@ pub fn parse_args(argv: &[String], ext_flags: &[FlagSpec]) -> Result Result Result<(), OxaError> { match flag { + "--shadow" => { + no_value(inline, flag)?; + a.shadow = true; + } "-h" | "--help" => { no_value(inline, flag)?; a.help = true; @@ -926,7 +939,7 @@ fn present_flags<'a>(flags: &[(bool, &'a str)]) -> Vec<&'a str> { pub fn usage_text(ext_flags: &[FlagSpec]) -> String { let mut out = String::new(); out.push_str("oxa - coding agent with read, bash, edit and write tools\n\n"); - out.push_str("Usage:\n oxa [options] [--] [@files...] [messages...]\n\n"); + out.push_str("Usage:\n oxa [options] [--] [@files...] [messages...]\n oxa lead --shadow [options] [messages...]\n\n"); out.push_str("Commands:\n"); for (left, desc) in COMMANDS { out.push_str(&format!(" {left:<36}{desc}\n")); diff --git a/oxa/oxa-cli/src/dispatch.rs b/oxa/oxa-cli/src/dispatch.rs index 3a2f65b13..0cba9e76a 100644 --- a/oxa/oxa-cli/src/dispatch.rs +++ b/oxa/oxa-cli/src/dispatch.rs @@ -465,6 +465,7 @@ fn open_named( /// `reopen` closure, which builds sessions for `/new`, `/resume`, fork and import. #[derive(Clone)] struct Built { + lead: bool, status: Option>, result_facts: Arc, output_schema: Option, @@ -530,6 +531,9 @@ impl Built { .with_owner_present(self.ask_owner_present), )); } + if self.lead { + tools.retain(|tool| crate::lead_preset::READ_TOOLS.contains(&tool.spec().name.as_str())); + } Deps { engine: self.engine.clone(), store: self.store.clone(), @@ -590,20 +594,33 @@ fn prepare( )); } let goal = crate::goal_cmd::load(a, cwd)?; - let output_schema = a - .output_schema - .as_ref() - .map(|file| { - let path = cwd.join(file); - let text = std::fs::read_to_string(&path) - .map_err(|e| OxaError::io(&format!("read output schema {}", path.display()), &e))?; - let value = serde_json::from_str(&text) - .map_err(|e| OxaError::new(codes::USAGE, format!("Invalid output schema JSON: {e}")))?; - oxa_core::output_schema::OutputSchema::new(value) - }) - .transpose()?; + let output_schema = if a.lead { + Some(crate::lead_preset::schema()?) + } else { + a.output_schema + .as_ref() + .map(|file| { + let path = cwd.join(file); + let text = std::fs::read_to_string(&path) + .map_err(|e| OxaError::io(&format!("read output schema {}", path.display()), &e))?; + let value = serde_json::from_str(&text) + .map_err(|e| OxaError::new(codes::USAGE, format!("Invalid output schema JSON: {e}")))?; + oxa_core::output_schema::OutputSchema::new(value) + }) + .transpose()? + }; let mut notices: Vec<(Level, String)> = Vec::new(); let user_settings = Settings::load(dirs, cwd, false); + // Only user settings may enable this default-off proposal session. + if a.lead && !user_settings.bool(crate::lead_preset::SETTING, false) { + return Err(OxaError::new( + codes::USAGE, + format!( + "lead --shadow is disabled; set \"{}\": true in the user settings.json to enable it", + crate::lead_preset::SETTING + ), + )); + } let (models, diags) = ModelsConfig::load(dirs, env); notices.extend( diags @@ -903,6 +920,7 @@ fn prepare( crate::result_facts::ResultFacts::new(status.clone()).with_billing(cloud_diagnostics.clone()), ); let built = Built { + lead: a.lead, status, result_facts, output_schema, @@ -1089,6 +1107,9 @@ fn discover_opts(a: &Args, dirs: &Dirs, cwd: &Path, trusted: bool) -> Result Vec { + if a.lead { + return Vec::new(); + } let Ok(dirs) = dirs_from_env(env, a.session_dir.as_deref()) else { return Vec::new(); }; @@ -2324,6 +2345,7 @@ mod session_scratch_tests { let base: Arc = Arc::new(NetSandbox::new(Arc::new(bwrap), true, false)); let yolo = oxa_proto::YoloSwitch::new(oxa_proto::Autonomy::Standard); let built = Built { + lead: false, status: None, result_facts: Arc::new(crate::result_facts::ResultFacts::default()), output_schema: None, diff --git a/oxa/oxa-cli/src/hooks.rs b/oxa/oxa-cli/src/hooks.rs index c2ed8fe03..5b78a52ed 100644 --- a/oxa/oxa-cli/src/hooks.rs +++ b/oxa/oxa-cli/src/hooks.rs @@ -80,6 +80,12 @@ pub struct HookInputs<'a> { /// Build the hook sets. Problems that do not stop the start (a failed extension, a bad hook /// entry, an `mcp.json` diagnostic) are pushed to `notices`. pub fn build_hooks(i: &HookInputs<'_>, notices: &mut Vec<(Level, String)>) -> Result { + if i.args.lead { + return Ok(HookSets { + hooks: vec![Arc::new(crate::lead_preset::LeadHooks)], + ..HookSets::default() + }); + } let mut sets = HookSets::default(); // ---- extensions ---- diff --git a/oxa/oxa-cli/src/lead_peer.rs b/oxa/oxa-cli/src/lead_peer.rs index 47e6bd4b3..0ae2c01c2 100644 --- a/oxa/oxa-cli/src/lead_peer.rs +++ b/oxa/oxa-cli/src/lead_peer.rs @@ -122,6 +122,22 @@ pub fn owner_uid(stream: &TcpStream) -> Result { mod tests { use super::*; + #[cfg(target_os = "linux")] + fn sample_live_owner(stream: &TcpStream) -> Result { + // The kernel table is live. An ambiguous observation remains a refusal; + // real-socket liveness controls may obtain another sample for at most one second. + // Wrong/missing ownership and every other error still fail immediately. + let start = std::time::Instant::now(); + loop { + match owner_uid(stream) { + Err("ambiguous peer ownership") if start.elapsed() < std::time::Duration::from_secs(1) => { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + result => return result, + } + } + } + fn pair(local: &str, peer: &str) -> (SocketAddr, SocketAddr) { (local.parse().unwrap(), peer.parse().unwrap()) } @@ -192,7 +208,7 @@ mod tests { let listener = std::net::TcpListener::bind(bind).unwrap(); let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); let (server, _) = listener.accept().unwrap(); - assert_eq!(owner_uid(&server), Ok(uid)); + assert_eq!(sample_live_owner(&server), Ok(uid)); drop(client); } } @@ -211,7 +227,7 @@ mod tests { let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); let (server, peer) = listener.accept().unwrap(); assert!(peer.ip().is_ipv6(), "the kernel reports the mapped IPv4 client"); - assert_eq!(owner_uid(&server), Ok(uid)); + assert_eq!(sample_live_owner(&server), Ok(uid)); drop(client); } } diff --git a/oxa/oxa-cli/src/lead_preset.rs b/oxa/oxa-cli/src/lead_preset.rs new file mode 100644 index 000000000..2c892e1ee --- /dev/null +++ b/oxa/oxa-cli/src/lead_preset.rs @@ -0,0 +1,197 @@ +//! Explicit ordinary-session shadow preset. No runner state or action authority. +use crate::Args; +use oxa_proto::{codes, CommandSpec, HookPoint, HookReply, Hooks, NoHooks, OxaError, Tool, Ui, Value}; +use std::sync::Arc; + +pub(crate) const READ_TOOLS: &[&str] = &["read", "grep", "find", "ls"]; +pub(crate) const SETTING: &str = "oxa.lead.shadow"; +const SCHEMA: &str = include_str!("../../docs/lead-proposals.schema.json"); + +pub(crate) fn apply(a: &mut Args) -> Result<(), OxaError> { + if !a.lead { + return if a.shadow { + Err(OxaError::new(codes::USAGE, "--shadow requires oxa lead")) + } else { + Ok(()) + }; + } + if !a.shadow { + return Err(OxaError::new( + codes::USAGE, + "Live lead coordination is unavailable; use oxa lead --shadow for proposals only", + )); + } + if a.goal.is_some() { + return Err(OxaError::new( + codes::USAGE, + "The lead shadow preset does not support --goal", + )); + } + if a.output_schema.is_some() + || a.system_prompt.is_some() + || !a.append_system_prompt.is_empty() + || !a.extensions.is_empty() + || !a.skills.is_empty() + || !a.prompt_templates.is_empty() + { + return Err(OxaError::new( + codes::USAGE, + "The lead shadow preset owns its instructions, schema and executable resources", + )); + } + if a.tools + .as_ref() + .is_some_and(|tools| tools.iter().any(|tool| !READ_TOOLS.contains(&tool.as_str()))) + { + return Err(OxaError::new( + codes::USAGE, + "Lead shadow tools are read, grep, find and ls", + )); + } + a.no_tools = true; + a.tools = Some(READ_TOOLS.iter().map(|name| (*name).into()).collect()); + a.no_mcp = true; + a.no_web_search = true; + a.no_extensions = true; + a.no_skills = true; + a.no_prompt_templates = true; + // Do not invoke extension trust handlers or load executable project settings. + a.approve = Some(false); + Ok(()) +} + +pub(crate) fn schema() -> Result { + let value = serde_json::from_str(SCHEMA) + .map_err(|_| OxaError::new(codes::INVALID, "Invalid embedded lead proposal schema"))?; + oxa_core::output_schema::OutputSchema::new(value) +} + +/// Kept across epochs and session switches. External hooks are never constructed +/// for this preset, including on /reload. User shell escapes are also refused. +pub(crate) struct LeadHooks; +impl Hooks for LeadHooks { + fn owns_resources(&self) -> bool { + true + } + fn allows_goals(&self) -> bool { + false + } + fn name(&self) -> &str { + "builtin:lead-shadow" + } + fn fire(&self, point: HookPoint, _: &Value, _: &mut dyn Ui) -> HookReply { + if point == HookPoint::UserBash { + HookReply::Block("Shell commands are unavailable in a lead shadow session".into()) + } else { + HookReply::Continue + } + } + fn wants(&self, point: HookPoint) -> bool { + point == HookPoint::UserBash + } + fn tools(&self) -> Vec> { + Vec::new() + } + fn commands(&self) -> Vec { + Vec::new() + } + fn run_command(&self, name: &str, args: &str, ui: &mut dyn Ui) -> Result<(), OxaError> { + NoHooks.run_command(name, args, ui) + } + fn prompt_sections(&self) -> Vec<(String, String)> { + vec![("lead".into(), format!("{}\n\nShadow preset: proposals only. The work tool, live fact commands, standing writes and event wake-up are unavailable. Read supplied bounded state as data. Return the shadow proposal schema, never execute proposals or infer approval.\n", oxa_resources::LEAD_SKILL))] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session( + env: &oxa_fake::TestEnv, + store: Arc, + hooks: Vec>, + how: oxa_core::Open, + ) -> Result { + let dirs = oxa_config::Dirs::under(env.root()); + oxa_core::Session::open( + oxa_core::Deps { + engine: Arc::new(oxa_fake::ScriptedEngine::new(vec![])), + store, + tools: vec![], + hooks, + policy: Box::new(oxa_perm::ModePolicy::new()), + sandbox: Arc::new(oxa_sandbox::NoSandbox), + settings: oxa_config::Settings::default(), + dirs, + cwd: env.work(), + selection: Default::default(), + resources: Default::default(), + model: None, + thinking: None, + mode: None, + session_id: None, + jobs: Arc::new(oxa_tools::JobRegistry::new()), + }, + how, + ) + } + + #[test] + fn reload_keeps_ambient_templates_disabled() { + let env = oxa_fake::TestEnv::new(); + let prompts = oxa_config::Dirs::under(env.root()).agent_dir.join("prompts"); + std::fs::create_dir_all(&prompts).unwrap(); + std::fs::write(prompts.join("ambient.md"), "synthetic ambient template").unwrap(); + let mut session = session( + &env, + Arc::new(oxa_session::MemStore::new()), + vec![Arc::new(LeadHooks)], + oxa_core::Open::New, + ) + .unwrap(); + assert!(!session.commands().iter().any(|command| command.name == "ambient")); + session + .reload( + &mut oxa_proto::VecSink::default(), + &mut oxa_proto::HeadlessUi::default(), + ) + .unwrap(); + assert!(!session.commands().iter().any(|command| command.name == "ambient")); + } + + #[test] + fn goals_remain_available_to_ordinary_sessions_but_not_shadow_presets() { + let env = oxa_fake::TestEnv::new(); + let store = Arc::new(oxa_session::MemStore::new()); + let goal = oxa_session::Goal::new("synthetic objective".into(), Default::default(), 1).unwrap(); + let mut sink = oxa_proto::VecSink::default(); + let mut ui = oxa_proto::HeadlessUi::default(); + let mut ordinary = + session(&env, store.clone(), vec![Arc::new(NoHooks)], oxa_core::Open::New).unwrap(); + ordinary.set_goal(Some(goal.clone()), &mut sink).unwrap(); + ordinary.close(&mut ui); + let error = session( + &env, + store.clone(), + vec![Arc::new(LeadHooks)], + oxa_core::Open::Continue, + ) + .err() + .expect("shadow must refuse a stored goal"); + assert_eq!(error.code, codes::USAGE); + assert!(error.message.contains("goal")); + let resumed = session(&env, store, vec![Arc::new(NoHooks)], oxa_core::Open::Continue).unwrap(); + assert_eq!(resumed.goal().unwrap(), goal); + let mut lead = session( + &env, + Arc::new(oxa_session::MemStore::new()), + vec![Arc::new(LeadHooks)], + oxa_core::Open::New, + ) + .unwrap(); + let error = lead.set_goal(Some(goal), &mut sink).unwrap_err(); + assert_eq!(error.code, codes::USAGE); + assert!(lead.goal().is_none()); + } +} diff --git a/oxa/oxa-cli/src/lib.rs b/oxa/oxa-cli/src/lib.rs index 4c5fc7805..618fd0df0 100644 --- a/oxa/oxa-cli/src/lib.rs +++ b/oxa/oxa-cli/src/lib.rs @@ -31,6 +31,7 @@ pub mod lead_access; pub mod lead_input; pub mod lead_page; pub mod lead_peer; +mod lead_preset; mod limits; mod login_cmd; mod mcp_cmd; diff --git a/oxa/oxa-cli/tests/lead_preset.rs b/oxa/oxa-cli/tests/lead_preset.rs new file mode 100644 index 000000000..57ebd8e89 --- /dev/null +++ b/oxa/oxa-cli/tests/lead_preset.rs @@ -0,0 +1,220 @@ +use oxa_cli::parse_args; +use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; +use oxa_proto::Value; +use std::io::Write; +use std::process::Command; +use std::process::Stdio; + +const EMPTY: &str = r#"{"mode":"shadow","as_of_seq":0,"proposals":[]}"#; + +#[test] +fn shadow_setting_is_off_and_project_settings_cannot_enable_it() { + for project_enable in [false, true] { + let env = TestEnv::new(); + if project_enable { + env.write("work/.oxa/settings.json", r#"{"oxa":{"lead":{"shadow":true}}}"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always","oxa":{"lead":{"shadow":false}}}"#, + ); + } + let server = FakeServer::start(vec![ScriptTurn::text(EMPTY)], FakeOpts::default()).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["lead", "--shadow", "-p", "--model", "fake-model", "check"]) + .env_clear() + .envs(env.envs(&server.url())) + .current_dir(env.work()) + .output() + .unwrap(); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("oxa.lead.shadow")); + assert!(server.requests().is_empty(), "gate precedes provider discovery"); + } +} + +#[test] +fn shadow_is_explicit_and_cannot_add_executable_resources() { + let parse = |args: &[&str]| parse_args(&args.iter().map(|s| (*s).into()).collect::>(), &[]); + assert!(!parse(&["-p", "ordinary"]).unwrap().lead); + assert!(parse(&["lead"]).unwrap_err().message.contains("unavailable")); + assert!(parse(&["--shadow"]).is_err()); + for args in [ + vec!["lead", "--shadow", "--tools", "bash"], + vec!["lead", "--shadow", "--extension", "evil.js"], + vec!["lead", "--shadow", "--skill", "other.md"], + vec!["lead", "--shadow", "--output-schema", "other.json"], + vec!["lead", "--shadow", "--system-prompt", "override"], + vec!["lead", "--shadow", "--append-system-prompt", "override"], + vec!["lead", "--shadow", "-p", "--goal", "objective.txt"], + ] { + assert!(parse(&args).is_err(), "{args:?}"); + } + let a = parse(&["lead", "--shadow", "-p", "check"]).unwrap(); + assert_eq!(a.messages, ["check"]); + assert!(a.no_mcp && a.no_extensions && a.no_skills && a.no_tools); + assert_eq!(a.approve, Some(false)); +} + +#[test] +fn entering_an_ordinary_saved_session_rebuilds_the_lead_prefix() { + let env = TestEnv::new(); + env.write( + "home/.oxa/agent/settings.json", + r#"{"oxa":{"lead":{"shadow":true}}}"#, + ); + let server = FakeServer::start( + vec![ScriptTurn::text("ordinary answer"), ScriptTurn::text(EMPTY)], + FakeOpts::default(), + ) + .unwrap(); + for words in [ + vec!["-p", "--session-id", "ordinary-test", "ordinary prompt"], + vec!["lead", "--shadow", "-p", "--continue=ordinary-test", "propose"], + ] { + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(words) + .env_clear() + .envs(env.envs(&server.url())) + .current_dir(env.work()) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + } + let requests: Vec<_> = server + .requests() + .into_iter() + .filter(|request| request.max_tokens > 0) + .collect(); + assert_eq!(requests.len(), 2); + assert!(requests[1].system.contains("Shadow preset: proposals only")); + let tools: Value = serde_json::from_str(&requests[1].tools_json).unwrap(); + let mut names: Vec<_> = tools + .as_array() + .unwrap() + .iter() + .map(|tool| tool["function"]["name"].as_str().unwrap()) + .collect(); + names.sort_unstable(); + assert_eq!(names, ["find", "grep", "ls", "read"]); +} + +#[test] +fn real_print_preset_refuses_write_and_keeps_read_tools_on_continue() { + let env = TestEnv::new(); + env.write("work/evidence.txt", "synthetic bounded observation"); + env.write( + "home/.oxa/agent/settings.json", + r#"{"codemode":{"enabled":true},"oxa":{"lead":{"shadow":true},"subagent":{"enabled":true}}}"#, + ); + let server = FakeServer::start( + vec![ + ScriptTurn::tool("forbidden", "write", r#"{"path":"marker","content":"bad"}"#), + ScriptTurn::tool("evidence", "read", r#"{"path":"evidence.txt"}"#), + ScriptTurn::text(EMPTY), + ScriptTurn::text(EMPTY), + ], + FakeOpts::default(), + ) + .unwrap(); + for words in [ + vec!["lead", "--shadow", "-p", "--session-id", "lead-test", "check"], + vec!["lead", "--shadow", "-p", "--continue=lead-test", "again"], + ] { + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(words) + .env_clear() + .envs(env.envs(&server.url())) + .current_dir(env.work()) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!( + serde_json::from_slice::(&out.stdout).unwrap(), + serde_json::from_str::(EMPTY).unwrap() + ); + } + assert!(!env.work().join("marker").exists()); + let requests: Vec<_> = server + .requests() + .into_iter() + .filter(|r| r.max_tokens > 0) + .collect(); + assert_eq!(requests.len(), 4); + for request in &requests { + let tools: Value = serde_json::from_str(&request.tools_json).unwrap(); + let mut names: Vec<_> = tools + .as_array() + .unwrap() + .iter() + .map(|tool| tool["function"]["name"].as_str().unwrap()) + .collect(); + names.sort_unstable(); + assert_eq!(names, ["find", "grep", "ls", "read"]); + assert!(request.system.contains("# Lead session")); + assert!(request.system.contains("Shadow preset: proposals only")); + } + assert!(requests[2].messages.iter().any(|m| m + .content + .as_deref() + .is_some_and(|s| s.contains("synthetic bounded observation")))); +} + +#[test] +fn rpc_shell_escape_is_blocked_without_starting_a_process() { + let env = TestEnv::new(); + env.write( + "home/.oxa/agent/settings.json", + r#"{"oxa":{"lead":{"shadow":true}}}"#, + ); + let server = FakeServer::start(Vec::new(), FakeOpts::default()).unwrap(); + let mut child = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["lead", "--shadow", "--mode", "rpc", "--no-session"]) + .env_clear() + .envs(env.envs(&server.url())) + .current_dir(env.work()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(b"{\"id\":\"shell\",\"type\":\"bash\",\"command\":\"touch marker\"}\n") + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(!env.work().join("marker").exists()); + assert!(String::from_utf8_lossy(&out.stdout).contains("Shell commands are unavailable")); +} + +#[test] +fn embedded_shadow_schema_repairs_an_unbound_action() { + let env = TestEnv::new(); + env.write( + "home/.oxa/agent/settings.json", + r#"{"oxa":{"lead":{"shadow":true}}}"#, + ); + let server = FakeServer::start( + vec![ + ScriptTurn::text(r#"{"mode":"shadow","as_of_seq":0,"proposals":[{"action":"merge"}]}"#), + ScriptTurn::text(EMPTY), + ], + FakeOpts::default(), + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["lead", "--shadow", "-p", "--no-session", "propose"]) + .env_clear() + .envs(env.envs(&server.url())) + .current_dir(env.work()) + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), EMPTY); + assert_eq!( + server.requests().into_iter().filter(|r| r.max_tokens > 0).count(), + 2 + ); +} diff --git a/oxa/oxa-config/src/schema.rs b/oxa/oxa-config/src/schema.rs index bdec8ea07..f31ac8585 100644 --- a/oxa/oxa-config/src/schema.rs +++ b/oxa/oxa-config/src/schema.rs @@ -162,6 +162,8 @@ const SCHEMA: &[KeyDef] = &[ // Lead web access scaffold: user-layer object, disabled by default, no listener installed yet. // The CLI validates the fields it reads (identity mode, loopback bind, port, allow-list). key("oxa.lead.serve", Kind::Object, "{}"), + // Read-only lead shadow preset; user settings only, default off. + key("oxa.lead.shadow", Kind::Bool, "false"), // Model replies per run before it ends with `turn_limit`; unset or 0 = no limit (#507). key("oxa.local", Kind::Object, "{}"), key("oxa.maxTurns", Kind::Number, "null"), diff --git a/oxa/oxa-core/src/epoch.rs b/oxa/oxa-core/src/epoch.rs index c9aead94c..299ce5ef8 100644 --- a/oxa/oxa-core/src/epoch.rs +++ b/oxa/oxa-core/src/epoch.rs @@ -259,7 +259,11 @@ pub fn reload(st: &mut SessionState, sink: &mut dyn EventSink, ui: &mut dyn Ui) ..DiscoverOpts::default() }; // Packages, extension and theme paths included (E10). - let resources = discover(&st.dirs, &st.cwd, &settings, &opts); + let resources = if st.hooks.iter().any(|hook| hook.owns_resources()) { + st.resources.clone() + } else { + discover(&st.dirs, &st.cwd, &settings, &opts) + }; for d in &resources.diagnostics { sink.emit(&AgentEvent::Notice { level: d.level, diff --git a/oxa/oxa-core/src/session.rs b/oxa/oxa-core/src/session.rs index 7fc5c873b..a156fdd8c 100644 --- a/oxa/oxa-core/src/session.rs +++ b/oxa/oxa-core/src/session.rs @@ -759,6 +759,12 @@ impl Session { if self.st.shared.busy.load(Ordering::SeqCst) { return Err(OxaError::new(codes::BUSY, "Cannot change a goal during a run.")); } + if goal.is_some() && self.st.hooks.iter().any(|hook| !hook.allows_goals()) { + return Err(OxaError::new( + codes::USAGE, + "The active session preset does not support goal mode", + )); + } let body = goal .as_ref() .map_or_else(oxa_session::Goal::clear_body, oxa_session::Goal::body); @@ -1449,6 +1455,12 @@ fn restore_locked( } let tree = Tree::new(st.store.load(&sref)?); let goal = oxa_session::Goal::latest(tree.entries())?.map(|g| Arc::new(crate::goal::GoalRuntime::new(g))); + if goal.is_some() && st.hooks.iter().any(|hook| !hook.allows_goals()) { + return Err(OxaError::new( + codes::USAGE, + "The active session preset does not support goal mode", + )); + } let branch: Vec = tree.branch(tree.leaf()).into_iter().cloned().collect(); let replayed = { let refs: Vec<&Entry> = branch.iter().collect(); @@ -1500,6 +1512,9 @@ fn restore_locked( crate::resume::close_interrupted(st, sink)?; // R1 // pi fires `session_start` (and `resources_discover`) for a resumed session too. crate::fire::session_start(st, start, sink, ui); + if st.hooks.iter().any(|hook| hook.owns_resources()) { + crate::open_epoch(st, "preset_resume", false, sink)?; + } Ok(()) } diff --git a/oxa/oxa-proto/src/hook.rs b/oxa/oxa-proto/src/hook.rs index f50fd2e9f..f6a5a1a57 100644 --- a/oxa/oxa-proto/src/hook.rs +++ b/oxa/oxa-proto/src/hook.rs @@ -421,6 +421,15 @@ pub trait Hooks: Send + Sync { fn prompt_sections(&self) -> Vec<(String, String)>; // ---- optional surface ---- + /// A host preset owns the supplied resources: keep them on reload and + /// rebuild restored prefixes from its current hooks and tool selection. + fn owns_resources(&self) -> bool { + false + } + /// Whether this preset supports session-local goal controls. + fn allows_goals(&self) -> bool { + true + } /// A stable name for logs and error events. fn name(&self) -> &str { "hooks"