diff --git a/RUST-BASE.md b/RUST-BASE.md index 5b6ec046fbf..a37744922f7 100644 --- a/RUST-BASE.md +++ b/RUST-BASE.md @@ -86,7 +86,7 @@ ancestry with merge commits; never rebase or squash the integration history. | Headless exit follows the answer | `crates/pa-cli/src/headless_exit.rs`, `crates/pa-core/src/kernel/bootstrap/venv/subprocess.rs`, `KernelPrewarm` in `crates/pa-core/src/session_engine/engine.rs` | Upstream's print runtime started the kernel bootstrap in the background and dropped its Tokio runtime implicitly, which waits without bound for the bootstrap's blocking `uv`/interpreter children: a fresh home's first one-shot exited 43 s after its answer. Print/json now set the kernel environment up before the first turn (`KernelPrewarm::BeforeFirstTurn`), run every setup child as an owned, cancellable tokio child, abandon the kernel boot after the last output and shut the runtime down within 300 ms; the hosted client's detach waits the same budget. `--verbose` traces the exit phases. Resident sessions keep `KernelPrewarm::Background`. Either mode runs only when the Python REPL tool (`python_repl`, with `ipython`/`python` selection aliases) is active after the launch tool selection (`--tools`/`--no-tools`/`--no-builtin-tools`). | | `--tools`/`--no-tools`/`--no-builtin-tools` honoured (kept against upstream #3211, `a3700282c`, which deletes them) | `crates/pa-core/src/session_engine/tool_selection.rs`, `crates/pa-core/src/prompts/no_repl.rs`, `crates/pa-core/src/session_engine/engine.rs`, `crates/pa-types/src/daemon/tool_selection.rs`, `crates/pa-cli/src/{args,mode,prompt_command}.rs`, the daemon create/summary/headless client, `crates/pa-tui/src/interactive.rs` | Upstream parsed the flags but always added the Python tool (`python_repl`, `ipython` before the rename) and the harness prompt; `sol` and the factory pass `--no-tools` for plain calls. TS semantics: an explicit list wins over both disable flags, then `--no-tools`, then `--no-builtin-tools`. A session with no active tools sends no tool definitions; any session without `python_repl` prepares no kernel environment, starts no kernel and gets the TS no-tools prompt byte for byte (`crates/pa-core/tests/golden/corpus/no-tools-prompt-ts.txt`). Daemon wire: introduced in fork schema revision 31 and carried in the combined revision 33 (fork-only id), capability `session_tool_selection`, create keys `tools`/`noTools`/`noBuiltinTools` (durable for respawns, and kept with the session policy in the per-session record, so a passivated session wakes, a session moved onto by `new_session`/fork keeps, and an RLM child inherits the selection; a record without the keys reads as the defaults), summary `toolSelection`. A merge that includes #3211 must keep the flags, their help rows and this implementation. | | Unknown model ids on a models.json provider resolve as custom models (#32) | `build_fallback_model` in `crates/pa-core/src/models/resolver.rs` | TS sends any `--model` id to a provider defined in models.json; the port's fallback returned `None` for every provider without a compiled-in default (every models.json provider: cpa, cpa-r, cpa-a), so CPA's per-login prefix routing (`--provider cpa-r --model antevon/gpt-6.1-sol`, the proxy strips the prefix upstream) failed with `Model ... not found`. The fallback template is the provider's own entry for the id behind one routing prefix (only the first path segment is a prefix: `antevon/openai/gpt-4o` keeps its namespace), else the provider's first model; a provider with a compiled-in default keeps that template (TS parity). Resolver tests cover the boundaries. An upstream merge must keep this. | -| Helper model for spawned agents | `crates/pa-core/src/session_engine/helper_model.rs`, `resolve_helper` in `crates/pa-daemon/src/rlm_child_model.rs`, `crates/pa-daemon/src/rlm_children/host.rs`, `crates/pa-cli/src/print_rlm.rs`, `crates/pa-daemon/src/rlm_surface.rs`, `crates/pa-tui/src/session_ui/settings.rs`, `docs/oneiron/HELPER-MODEL.md` | Upstream runs a spawned agent on its parent's model unless the call names one, and never reads its own `subagentDefaultModel` (TS read it, and failed the spawn on an unavailable default). The fork resolves each field in order: the spawn call, the session override (`--subagent-model`/`--subagent-thinking`, `PRIME_SUBAGENT_MODEL`/`PRIME_SUBAGENT_THINKING`, TUI `/subagent-model`), the settings file (`subagentDefaultModel` plus the fork's `subagentDefaultThinking`), the parent. An unknown default warns once and falls back to the parent's model (a TS divergence, by ruling); a default level clamps to the model. The override rides RLM child creates (`subagentModel`/`subagentThinking`) and persists as a `subagent_model_state` session row. Daemon wire: capability `subagent_model`, commands `get_subagent_model_status`/`set_subagent_model` (no schema bump). The spawn and create-session handles add `thinking`. `/settings` gains "Helper model" and "Helper thinking". An upstream merge must keep all of it. | +| Helper model for spawned agents | `crates/pa-core/src/session_engine/helper_model.rs`, `resolve_helper` in `crates/pa-daemon/src/rlm_child_model.rs`, `crates/pa-daemon/src/rlm_children/host.rs`, `crates/pa-cli/src/print_rlm.rs`, `crates/pa-daemon/src/rlm_surface.rs`, `crates/pa-tui/src/session_ui/settings.rs`, `docs/oneiron/HELPER-MODEL.md` | Upstream runs a spawned agent on its parent's model unless the call names one, and never reads its own `subagentDefaultModel` (TS read it, and failed the spawn on an unavailable default). The fork resolves each field in order: the spawn call, the session override (`--subagent-model`/`--subagent-thinking`, `PRIME_SUBAGENT_MODEL`/`PRIME_SUBAGENT_THINKING`, TUI `/subagent-model`), the settings file (`subagentDefaultModel` plus the fork's `subagentDefaultThinking`), the parent. An unknown default warns once and falls back to the parent's model (a TS divergence, by ruling); a default level clamps to the model. The override rides RLM child creates (`subagentModel`/`subagentThinking`) and persists as a `subagent_model_state` session row. Daemon wire: capability `subagent_model`, commands `get_subagent_model_status`/`set_subagent_model` (no schema bump). The spawn and create-session handles add `thinking`. `/settings` gains "Helper model" and "Helper thinking". The helper model list (`subagentModels`, global settings only) limits what spawned agents may run on: a spawn call naming a model off it is refused with the allowed models named, a settings default or parent model off it falls to its first entry, and a person's choice (the session override, or `--subagent-models`/`PRIME_SUBAGENT_MODELS`/TUI `/subagent-models`) is allowed; `rlm.find_models` lists only its models (`RlmSubagentHost::helper_model_list`), and `set_subagent_models` sits behind the capability `subagent_models`. An upstream merge must keep all of it. | | Side-by-side install + probe | `scripts/oneiron/side_by_side.py` | Installs a staged release beside the TS build and writes receipts. | | Release feed, rollout, rollback, status | `scripts/oneiron/release_feed.py`, `rollout.py`, `daemon_idle.py` (subcommands of `side_by_side.py`), `docs/oneiron/RELEASE.md`, `docs/oneiron/ROLLBACK.md` | Stamps a `package_release.py` build into a versioned feed release (`feed/releases/v/`), rolls it out with verified sums, a probe before selection and an idle-only Rust daemon check, and rolls back to the previous install; every step writes a receipt. `crates/pa-core/tests/oneiron_feed_manifest.rs` checks the feed manifest against the native updater's parser. | | Test-policy gate | `scripts/check-test-policy.mjs` (from the TS fork), `scripts/oneiron/test_policy_gate.py` | Runs the fork's test policy with `TEST_POLICY_BASE=oneiron/main` and fails only on violations beyond the reviewed upstream baseline (`scripts/oneiron/test-policy-baseline.txt`): 4 original entries plus 8 occurrences in 3 byte-identical upstream tests at the 2026-10-24 sync. | diff --git a/crates/pa-cli/README.md b/crates/pa-cli/README.md index c02ceb5e365..2b1fde26095 100644 --- a/crates/pa-cli/README.md +++ b/crates/pa-cli/README.md @@ -49,9 +49,14 @@ process). A child that names no model or thinking level runs on the helper model (fork-only, `docs/oneiron/HELPER-MODEL.md`): the invocation's `--subagent-model`/`--subagent-thinking` (else `PRIME_SUBAGENT_MODEL`/ `PRIME_SUBAGENT_THINKING`), then the settings file's -`subagentDefaultModel`/`subagentDefaultThinking`, then the parent's. +`subagentDefaultModel`/`subagentDefaultThinking`, then the parent's. The +helper model list (`subagentModels`, widened for the run by +`--subagent-models`/`PRIME_SUBAGENT_MODELS`) refuses a spawn naming a model +off it, moves a default off it to its first entry, and limits +`rlm.find_models` (the inline host's `helper_model_list`). `--daemon-hosted` and the interactive launch set the same override on their -session (`set_subagent_model`, behind the `subagent_model` capability). +session (`set_subagent_model`/`set_subagent_models`, behind the +`subagent_model`/`subagent_models` capabilities). Session slash commands (`print_session_command.rs`, the #253 residue): print prompts that are `/compact`, `/refine`, `/goal`, or `/autonomous` execute through the pa-core session-command executor (the daemon worker's seam — no diff --git a/crates/pa-cli/src/args.rs b/crates/pa-cli/src/args.rs index 7e3de8e5cb4..bbe3cc771c3 100644 --- a/crates/pa-cli/src/args.rs +++ b/crates/pa-cli/src/args.rs @@ -149,6 +149,8 @@ pub struct Args { pub subagent_model: Option, /// `--subagent-thinking`: this session's helper thinking level (a level or `parent`). pub subagent_thinking: Option, + /// `--subagent-models a,b`: this session's additions to the helper model list. + pub subagent_models: Option>, pub continue_: bool, /// `true` when `--resume` was given without a selector. pub resume_bare: bool, @@ -368,6 +370,11 @@ pub fn parse_args(args: &[String]) -> Args { } } "--subagent-model" => result.subagent_model = Some(require_value!(arg)), + "--subagent-models" => { + result.subagent_models = Some( + pa_core::session_engine::helper_model::parse_model_list(&require_value!(arg)), + ); + } "--subagent-thinking" => { let level = require_value!(arg); if level == pa_core::session_engine::helper_model::INHERIT_PARENT @@ -645,6 +652,10 @@ mod tests { let expected = Args { subagent_model: Some("cpa-r/deepseek-flash-1017".to_string()), subagent_thinking: Some("max".to_string()), + subagent_models: Some(vec![ + "cpa-a/claude-opus-5".to_string(), + "cpa-a/gpt-6".to_string(), + ]), print: true, messages: vec!["hi".to_string()], ..Args::default() @@ -657,6 +668,8 @@ mod tests { "cpa-r/deepseek-flash-1017", "--subagent-thinking", "max", + "--subagent-models", + "cpa-a/claude-opus-5, cpa-a/gpt-6", "-p", "hi" ]) diff --git a/crates/pa-cli/src/client_settings.rs b/crates/pa-cli/src/client_settings.rs index 3178b4db148..b0c7f545129 100644 --- a/crates/pa-cli/src/client_settings.rs +++ b/crates/pa-cli/src/client_settings.rs @@ -7,6 +7,9 @@ use std::sync::Arc; use pa_tui::client_settings::ClientSettings; +#[cfg(all(test, unix))] +mod helper_launch_tests; + /// The seam handle the interactive run carries. #[derive(Clone)] pub struct CliClientSettings { @@ -114,6 +117,10 @@ impl ClientSettings for CliClientSettings { self.manager().get_subagent_default_thinking() } + fn subagent_models(&self) -> Option> { + self.manager().get_subagent_models() + } + fn set_subagent_default_thinking(&self, level: Option<&str>) -> Result<()> { if let Some(level) = level.filter(|level| pa_types::ai::thinking_level_from_str(level).is_none()) diff --git a/crates/pa-cli/src/client_settings/helper_launch_tests.rs b/crates/pa-cli/src/client_settings/helper_launch_tests.rs new file mode 100644 index 00000000000..fb664c9113f --- /dev/null +++ b/crates/pa-cli/src/client_settings/helper_launch_tests.rs @@ -0,0 +1,134 @@ +//! Launch overrides still reach a daemon that supports helper defaults but not helper lists. +use std::io::{BufRead, BufReader, Write}; +use std::os::unix::net::UnixListener; +use std::path::PathBuf; + +use pa_tui::interactive::{ + run_interactive, HeadlessPlan, InteractiveOptions, ModelSelection, SessionSelection, UiMode, +}; +use serde_json::{json, Value}; + +fn options(socket: PathBuf) -> InteractiveOptions { + InteractiveOptions { + tool_selection: pa_types::daemon::ToolSelectionFlags::default(), + models: None, + socket_path: socket, + cwd: PathBuf::from("/tmp"), + session_dir: None, + script_path: None, + model_selection: ModelSelection::default(), + model_catalog: Vec::new(), + model_configured_providers: std::collections::HashSet::default(), + model_recent_models: Vec::new(), + default_thinking_level: None, + no_session: false, + session: SessionSelection::New, + restore_dock_focus: false, + initial_message: None, + show_images: true, + fullscreen_mouse: true, + theme: "prime".to_string(), + code_block_indent: " ".to_string(), + tree_filter_mode: String::new(), + branch_summary_skip_prompt: false, + version: "0.0.0".to_string(), + onboarding: None, + telemetry_disabled: None, + client_auth: None, + traces: None, + provider_auth: None, + update_commands: None, + telemetry: None, + keybindings: pa_tui::keybindings::KeybindingsManager::new(), + session_rlm_depth: None, + prompt_stash: std::sync::Arc::default(), + session_has_children: false, + client_settings: None, + } +} + +#[test] +fn helper_launch_override_survives_an_old_daemon_with_a_settings_list() { + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join("tui.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut writer = stream.try_clone().unwrap(); + let mut reader = BufReader::new(stream); + let hello = json!({ + "type": "daemon_hello", + "protocol": {"name": "prime-agent.daemon", "version": 7}, + "serverCapabilities": ["subagent_model"], + "clientId": "mock", + }); + writeln!(writer, "{hello}").unwrap(); + let mut overrides = Vec::new(); + let mut line = String::new(); + while reader.read_line(&mut line).unwrap() != 0 { + if line.trim().is_empty() { + line.clear(); + continue; + } + let envelope: Value = serde_json::from_str(line.trim()).unwrap(); + line.clear(); + let command = &envelope["command"]; + let kind = command["type"].as_str().unwrap(); + let data = match kind { + "create" => json!({"activeSessionId": "s1", "sessionId": "saved"}), + "attach" => json!({ + "activeSessionId": "s1", + "snapshot": {"state": {"sessionId": "saved"}, "messages": []}, + }), + "set_subagent_model" => { + overrides.push(command.clone()); + json!({"model": command["model"], "modelSource": "session", "thinking": command["thinking"], "thinkingSource": "session"}) + } + _ => json!({}), + }; + let response = json!({"type": "response", "id": envelope["id"], "command": kind, "success": true, "data": data}); + if writeln!(writer, "{response}").is_err() { + break; + } + } + overrides + }); + std::fs::write( + dir.path().join("settings.json"), + json!({"subagentModels": ["test-provider/listed"]}).to_string(), + ) + .unwrap(); + let mut options = options(socket); + options.client_settings = Some(super::CliClientSettings::new( + dir.path().to_path_buf(), + dir.path().to_path_buf(), + )); + options.model_selection.subagent_model = Some("test-provider/chosen".to_string()); + options.model_selection.subagent_thinking = Some("max".to_string()); + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap(); + let outcome = runtime + .block_on(run_interactive( + options, + UiMode::Headless(HeadlessPlan { + steps: Vec::new(), + width: 160, + height: 40, + }), + )) + .unwrap(); + let overrides = server.join().unwrap(); + assert_eq!( + overrides, + vec![json!({ + "type": "set_subagent_model", "activeSessionId": "s1", + "model": "test-provider/chosen", "thinking": "max", + })] + ); + assert!(outcome + .frames + .join("\n") + .contains("does not enforce subagentModels")); +} diff --git a/crates/pa-cli/src/command_registry.rs b/crates/pa-cli/src/command_registry.rs index 36fb95a8dca..2a5163a89d4 100644 --- a/crates/pa-cli/src/command_registry.rs +++ b/crates/pa-cli/src/command_registry.rs @@ -367,6 +367,10 @@ const TOP_LEVEL_OPTION_GROUPS: &[OptionGroup] = &[ "--subagent-thinking ", "Set this session's reasoning for spawned agents (or parent)", ), + ( + "--subagent-models ", + "Add models spawned agents may run on, this session (comma-separated)", + ), ], }, OptionGroup { diff --git a/crates/pa-cli/src/global_flags.rs b/crates/pa-cli/src/global_flags.rs index f213a4c53e0..cd5cf7ed2d3 100644 --- a/crates/pa-cli/src/global_flags.rs +++ b/crates/pa-cli/src/global_flags.rs @@ -4,7 +4,7 @@ use std::collections::HashSet; /// Global flags that consume the next argument as their value. -pub const GLOBAL_VALUE_FLAGS: [&str; 27] = [ +pub const GLOBAL_VALUE_FLAGS: [&str; 28] = [ "--mode", "--json-event-profile", "--daemon-socket", @@ -21,6 +21,7 @@ pub const GLOBAL_VALUE_FLAGS: [&str; 27] = [ "--thinking", "--subagent-model", "--subagent-thinking", + "--subagent-models", "--skill", "--prompt-template", "--theme", diff --git a/crates/pa-cli/src/hosted_print.rs b/crates/pa-cli/src/hosted_print.rs index 05e99838b2c..1ce1a0fb802 100644 --- a/crates/pa-cli/src/hosted_print.rs +++ b/crates/pa-cli/src/hosted_print.rs @@ -155,6 +155,13 @@ async fn hosted_print_main(options: &RunOptions) -> Result { no_skills: config.no_skills, }, subagent_override: config.subagent_override.clone(), + enforce_helper_model_list: + pa_core::session_engine::helper_model::HelperDefaults::load_settings( + &cwd, + &config.agent_dir, + ) + .models + .is_some(), }) .await .map_err(|error| format!("{error:#}"))?; diff --git a/crates/pa-cli/src/interactive_mode.rs b/crates/pa-cli/src/interactive_mode.rs index f7d237ac194..f4a66744e9f 100644 --- a/crates/pa-cli/src/interactive_mode.rs +++ b/crates/pa-cli/src/interactive_mode.rs @@ -240,9 +240,10 @@ async fn run_agents_view_flow( notice: Option, ) -> Result<()> { // The launch helper-model override belongs to the session the launch opened; a session - // opened from the view keeps its own (`/subagent-model` changes it there). + // opened from the view keeps its own (`/subagent-model`/`/subagent-models` change it there). base.model_selection.subagent_model = None; base.model_selection.subagent_thinking = None; + base.model_selection.subagent_models = None; let mut anchor = anchor; // Every view run reuses the roster connection (a chat run hands it // back), so a switch back from a chat skips the handshake. @@ -496,6 +497,7 @@ fn build_tui_options( // The launch helper-model override, set on the opened session. subagent_model: config.subagent_override.model.clone(), subagent_thinking: config.subagent_override.thinking.clone(), + subagent_models: config.subagent_override.models.clone(), }, // The raw `--models` patterns ride the create config (the daemon // owns the resolution). diff --git a/crates/pa-cli/src/mode.rs b/crates/pa-cli/src/mode.rs index 6dbdade14b8..892f9736804 100644 --- a/crates/pa-cli/src/mode.rs +++ b/crates/pa-cli/src/mode.rs @@ -93,7 +93,8 @@ pub struct RuntimeConfig { pub serialized_refine: bool, pub initial_goal: Option, /// The session's helper-model override for spawned agents: `--subagent-model`/ - /// `--subagent-thinking`, else `PRIME_SUBAGENT_MODEL`/`PRIME_SUBAGENT_THINKING`. + /// `--subagent-thinking`/`--subagent-models`, else `PRIME_SUBAGENT_MODEL`/ + /// `PRIME_SUBAGENT_THINKING`/`PRIME_SUBAGENT_MODELS`. pub subagent_override: pa_core::session_engine::helper_model::HelperDefaults, } @@ -387,21 +388,27 @@ pub fn runtime_config_from_args( }), subagent_override: { use pa_core::session_engine::helper_model::{ - HelperDefaults, SUBAGENT_MODEL_ENV, SUBAGENT_THINKING_ENV, + parse_model_list, HelperDefaults, SUBAGENT_MODELS_ENV, SUBAGENT_MODEL_ENV, + SUBAGENT_THINKING_ENV, }; // Each flag beats its env var; an invalid env level warns and is ignored. let env_model = std::env::var(SUBAGENT_MODEL_ENV).ok(); let env_thinking = std::env::var(SUBAGENT_THINKING_ENV).ok(); + let env_models = std::env::var(SUBAGENT_MODELS_ENV) + .ok() + .map(|text| parse_model_list(&text)); let env_layer = HelperDefaults::new(env_model.as_deref(), env_thinking.as_deref()) .unwrap_or_else(|error| { eprintln!("Warning: {SUBAGENT_THINKING_ENV}: {error}"); HelperDefaults::new(env_model.as_deref(), None).unwrap_or_default() - }); + }) + .with_models(env_models); HelperDefaults::new( parsed.subagent_model.as_deref(), parsed.subagent_thinking.as_deref(), ) .unwrap_or_default() + .with_models(parsed.subagent_models.clone()) .or(&env_layer) }, } @@ -447,17 +454,20 @@ pub(crate) mod tests { #[test] fn subagent_flags_beat_their_env_vars_field_by_field() { use pa_core::session_engine::helper_model::{ - HelperDefaults, SUBAGENT_MODEL_ENV, SUBAGENT_THINKING_ENV, + HelperDefaults, SUBAGENT_MODELS_ENV, SUBAGENT_MODEL_ENV, SUBAGENT_THINKING_ENV, }; - let resolve = |argv: &[&str], model: Option<&str>, thinking: Option<&str>| { - let saved: Vec<(&str, Option)> = [SUBAGENT_MODEL_ENV, SUBAGENT_THINKING_ENV] + // `env` holds the model, thinking and models env values. + let resolve = |argv: &[&str], env: [Option<&str>; 3]| { + let keys = [ + SUBAGENT_MODEL_ENV, + SUBAGENT_THINKING_ENV, + SUBAGENT_MODELS_ENV, + ]; + let saved: Vec<(&str, Option)> = keys .iter() .map(|key| (*key, std::env::var(key).ok())) .collect(); - for (key, value) in [ - (SUBAGENT_MODEL_ENV, model), - (SUBAGENT_THINKING_ENV, thinking), - ] { + for (key, value) in keys.into_iter().zip(env) { match value { Some(value) => std::env::set_var(key, value), None => std::env::remove_var(key), @@ -483,40 +493,53 @@ pub(crate) mod tests { let layer = |model: Option<&str>, thinking: Option<&str>| { HelperDefaults::new(model, thinking).unwrap() }; + let models = |models: &[&str]| Some(models.iter().map(ToString::to_string).collect()); assert_eq!( resolve( &["-p", "hi"], - Some("cpa-r/deepseek-flash-1017"), - Some("max") + [ + Some("cpa-r/deepseek-flash-1017"), + Some("max"), + Some("cpa-a/gpt-6, cpa-a/claude-opus-5") + ] ), layer(Some("cpa-r/deepseek-flash-1017"), Some("max")) + .with_models(models(&["cpa-a/gpt-6", "cpa-a/claude-opus-5"])) ); assert_eq!( resolve( - &["--subagent-model", "cpa-r/kimi-k3.1", "-p", "hi"], - Some("cpa-r/deepseek-flash-1017"), - Some("max") + &[ + "--subagent-model", + "cpa-r/kimi-k3.1", + "--subagent-models", + "cpa-a/gpt-6", + "-p", + "hi" + ], + [ + Some("cpa-r/deepseek-flash-1017"), + Some("max"), + Some("cpa-a/claude-opus-5") + ] ), - layer(Some("cpa-r/kimi-k3.1"), Some("max")) + layer(Some("cpa-r/kimi-k3.1"), Some("max")).with_models(models(&["cpa-a/gpt-6"])) ); assert_eq!( resolve( &["--subagent-thinking", "parent", "-p", "hi"], - None, - Some("max") + [None, Some("max"), None] ), layer(None, Some("parent")) ); assert_eq!( resolve( &["-p", "hi"], - Some("cpa-r/deepseek-flash-1017"), - Some("loud") + [Some("cpa-r/deepseek-flash-1017"), Some("loud"), None] ), layer(Some("cpa-r/deepseek-flash-1017"), None) ); assert_eq!( - resolve(&["-p", "hi"], None, None), + resolve(&["-p", "hi"], [None, None, None]), HelperDefaults::default() ); } diff --git a/crates/pa-cli/src/print_rlm.rs b/crates/pa-cli/src/print_rlm.rs index ada6385c59d..57c9e92d403 100644 --- a/crates/pa-cli/src/print_rlm.rs +++ b/crates/pa-cli/src/print_rlm.rs @@ -671,10 +671,29 @@ impl RlmSubagentHost for InlineHost { .as_deref() .and_then(pa_ai::models::thinking_level_from_str) .unwrap_or(parent_thinking); + // The settings layer of the helper order and the helper model list. + let settings = pa_core::session_engine::helper_model::HelperDefaults::load_settings( + &config.cwd, + &config.agent_dir, + ); // The model lane: a scripted child runs its own faux queue under // `children.`; a real-provider child resolves against // the catalog, inheriting the parent's selector. let (selector, lane, thinking) = if let Some(script) = recipe.faux.as_ref() { + // A scripted child runs the faux model whatever the call names, but a named + // model off the helper model list is refused as on the real lane. + if let (Some(reference), Some(list)) = ( + request.model.as_deref(), + pa_daemon::rlm_child_model::helper_model_list( + &config.agent_dir, + &config.subagent_override, + &settings, + ), + ) { + if !list.allows(reference) { + anyhow::bail!(list.refusal(reference, "subagent")); + } + } let queue = script .get("children") .and_then(|children| children.get(&name)) @@ -710,11 +729,8 @@ impl RlmSubagentHost for InlineHost { ) } else { // The helper order: the call, the invocation's override (`--subagent-model`, - // `PRIME_SUBAGENT_MODEL`), the settings file, the parent. - let settings = pa_core::session_engine::helper_model::HelperDefaults::load_settings( - &config.cwd, - &config.agent_dir, - ); + // `PRIME_SUBAGENT_MODEL`), the settings file, the parent; then the helper model + // list (`subagentModels` plus `--subagent-models`). let parent_selector = node.model_selector.lock().unwrap().clone(); let helper = pa_daemon::rlm_child_model::resolve_helper_unchecked( &config.agent_dir, @@ -1020,6 +1036,21 @@ impl RlmSubagentHost for InlineHost { Ok(name) }) } + + fn helper_model_list( + &self, + ) -> RlmHostFuture> { + let config = &self.0.recipe.options.config; + let list = pa_daemon::rlm_child_model::helper_model_list( + &config.agent_dir, + &config.subagent_override, + &pa_core::session_engine::helper_model::HelperDefaults::load_settings( + &config.cwd, + &config.agent_dir, + ), + ); + Box::pin(async move { Ok(list) }) + } } /// Append one durable `session_info` name row to a node's session. diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rs index 89e3cf2b907..2d590e162f7 100644 --- a/crates/pa-cli/tests/interactive_daemon_e2e.rs +++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs @@ -4864,6 +4864,7 @@ fn subscription_options( thinking: None, subagent_model: None, subagent_thinking: None, + subagent_models: None, }; options.provider_auth = Some(pa_tui::provider_auth::ProviderAuthCommandsHandle( std::sync::Arc::new(E2ESubscriptionAuth), diff --git a/crates/pa-cli/tests/print_inline_subagents_e2e.rs b/crates/pa-cli/tests/print_inline_subagents_e2e.rs index dcddd072907..b9033bf2639 100644 --- a/crates/pa-cli/tests/print_inline_subagents_e2e.rs +++ b/crates/pa-cli/tests/print_inline_subagents_e2e.rs @@ -442,6 +442,86 @@ fn print_inline_subagents_enforce_the_depth_limit() { ); } +/// The helper model list (settings `subagentModels`) in the in-process host: a spawn naming a +/// model off the list fails in the agent's tool result, naming the allowed models, and starts no +/// child; a spawn naming a listed model starts; `rlm.find_models` lists only the listed models. +#[test] +fn print_inline_spawns_off_the_helper_model_list_are_refused() { + let lane = lane(); + let kernel = PrintLane::kernel_python(); + std::fs::write( + lane.agent_dir.join("models.json"), + serde_json::json!({ + "providers": { + "test-provider": { + "baseUrl": "http://localhost:9", + "apiKey": "test-key", + "api": "openai-completions", + "models": [ + { "id": "helper-flash", "name": "Helper", "contextWindow": 1000, "maxTokens": 100 }, + { "id": "paid-route", "name": "Paid", "contextWindow": 1000, "maxTokens": 100 } + ] + } + } + }) + .to_string(), + ) + .unwrap(); + std::fs::write( + lane.agent_dir.join("settings.json"), + serde_json::json!({ "subagentModels": ["test-provider/helper-flash"] }).to_string(), + ) + .unwrap(); + let cell = "try:\n await rlm.spawn(\"use the paid route\", name=\"paid\", model=\"test-provider/paid-route\")\n print(\"PAID_SPAWNED\")\nexcept Exception as error:\n print(\"PAID_REFUSED:\", error)\nprint(\"ROSTER\", \",\".join(m.selector for m in await rlm.find_models(\"\")))\nkid = await rlm.spawn(\"run the kid task\", name=\"kid\", model=\"test-provider/helper-flash\")\nprint(\"KID\", kid.rlm_child_id)"; + let script = serde_json::json!({ + "responses": [ + { "content": [ + { "type": "toolCall", "name": "ipython", "arguments": { "code": cell } }, + ] }, + "PARENT DONE", + ], + "repeatLastResponse": true, + "children": { + "kid": { "responses": ["kid finished"] }, + }, + }); + let (stdout, stderr, code) = lane.run(&["-p", "delegate once"], &script, &kernel, &[]); + assert_eq!(code, 0, "stderr: {stderr}\nstdout: {stdout}"); + assert_eq!(stdout.trim_end(), "PARENT DONE"); + + let parent_file = lane.parent_session_file(); + let parent_text = serde_json::to_string(&PrintLane::entries(&parent_file)).unwrap(); + assert!( + parent_text.contains("PAID_REFUSED:") + && parent_text.contains( + "is not on the helper model list; use one of: test-provider/helper-flash (or omit model= for the default)" + ), + "the off-list spawn failed with the refusal: {parent_text}" + ); + // The printed line, not the cell's source. + assert!(!parent_text.contains("PAID_SPAWNED\\n"), "{parent_text}"); + assert!( + parent_text.contains("ROSTER test-provider/helper-flash\\n"), + "the roster lists only the listed model: {parent_text}" + ); + assert!( + parent_text.contains("KID sub-"), + "the listed spawn started: {parent_text}" + ); + // One child session: the refused spawn left none. + let parent_id = parent_file + .file_stem() + .and_then(|stem| stem.to_str()) + .expect("the parent session id") + .to_string(); + let child_dirs = std::fs::read_dir(lane.agent_dir.join("session-artifacts").join(&parent_id)) + .expect("the kid's session dir exists") + .flatten() + .filter(|entry| entry.file_name().to_string_lossy().starts_with("sub-")) + .count(); + assert_eq!(child_dirs, 1); +} + /// A settled child re-tasked by its parent must keep the run open: the /// parent sends the follow-up, ends its turn, and the print run waits /// for the re-tasked child's second reply before the terminal answer. diff --git a/crates/pa-core/README.md b/crates/pa-core/README.md index 9fd8e4ce4ea..0b225cd026b 100644 --- a/crates/pa-core/README.md +++ b/crates/pa-core/README.md @@ -111,7 +111,7 @@ only: nothing wires it to a user-facing cloud toggle yet. No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-daemon), no TUI (pa-tui). No update coordination (the pa-cli coordinator owns the FSM; the update-flow seam here is the daemon-free support layer: `update::version` (semver/channel policy), `update::install` (the managed install-root layout), `update::release` (the channel manifest fetch), `update::download` (sha256-verified archive download + staging)). The package manager installs sources and resolves resource paths only. No workspace snapshot upload, transport, or remote materialization (staging and verification live here; the cloud attach surface owns the transport when it ships). ## Public API -`SessionEngine` (message in -> events out; `SessionEngine::dispose` ends a session: its provider connection state, then its kernel), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager (with its memory ceiling: `KernelManagerOptions`/`IpythonKernelProvisionerOptions` `memory_limit_gb`/`memory_backstop` and the telemetry-only `on_memory_action`/`on_snapshot_guard` seams with their `KernelMemoryActionStats`/`KernelSnapshotGuardStats` primitives, `KernelCellLine` on kernel errors, and the `queued_memory_notices`/`memory_notices` result fields; the ladder itself - policy, process tree, watcher, messages - stays `pub(crate)` in `kernel::memory_guard`), settings (`SettingsManager`, including `get_kernel_memory_limit_gb`/`get_kernel_memory_backstop` and the fork's `get_`/`set_subagent_default_model`/`_thinking`), `session_engine::helper_model` (fork-only: the helper-model order for a spawn that names no model or thinking level - `HelperDefaults` layers, `plan_helper`, the `subagent_model_state` row reader, the env/create-key names and the once-per-process unknown-model warning; the hosts resolve the picked reference against their catalogs), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children and pa-cli for inline print children; also owns the shared spawn/depth facts, child session directories and depth precedence), `session_engine::semantic_edges` (the TS `semantic-edges.ts` WRITER: `SemanticEdgeRecorder`/`SemanticEdgeIdentity`, `semantic_edge_ledger_path` + `last_committed_request_id`, and the `X-ACP-Model-Request-ID`/`Idempotency-Key` constants — one durable per-session ledger of model-request events, byte-compatible with the TS lines; the fold and any publishing stay downstream), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`, carrying the session's transport preference into every request; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, owed RLM continuation deferral and wake-up ownership, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill_use_count` session counter counts at the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). `resources::{ResourceLoadingPolicy, ResourceDiscovery}` (the session's resource-discovery policy, `SessionEngineConfig::resource_loading`: the TS `--no-skills`/`--no-prompt-templates`/`--no-context-files` switches reach the one resource loader at session assembly; explicit skill and prompt-template paths still load). Kernel preparation and exit: `SessionEngineConfig::prewarm_ipython_kernel` takes a `session_engine::engine::KernelPrewarm` (`Background`: the whole boot in the background, for resident sessions - the daemon worker, RPC, ACP; `BeforeFirstTurn`: `create_session` finishes the kernel environment setup - a fresh home's venv build, missing skill installs, the readiness probe - and only the process boot stays in the background, for one-shot print/json runs), `SessionEngine::abandon_kernel` (a one-shot host's last step: abandon the boot - the host's runtime shutdown drops it, killing any setup child - and kill the kernel without a final snapshot; an abandoned boot reports no `kernel bootstrap` outcome), `IpythonKernelProvisioner::{prepare_environment, abandon}`, `kernel::bootstrap::prepare_kernel_environment` (fails when a fresh setup leaves the venv unready), and `EnsureKernelPythonOptions::cancel` (every `uv` step and interpreter probe is an owned tokio child, killed when its future drops; an explicit cancel also kills and reaps it, and a cancelled probe never triggers a rebuild; the provisioner never passes one - the venv is shared by every session, so one session's dispose does not cancel its setup), and `kernel::bootstrap::{set_kernel_setup_trace, KernelSetupTrace}` (the opt-in, process-wide setup trace the CLI's `--verbose` routes to stderr). `session_engine::tool_selection::ToolSelection` (the launch tool-selection policy, `SessionEngineConfig::tool_selection` with `ToolSelection::from_flags` over the `pa_types::daemon::ToolSelectionFlags` vocabulary: an explicit `--tools` list wins, then `--no-tools`, then `--no-builtin-tools`; the engine filters both the request's tool definitions and the executable tools through it, a session without `ipython` asks for no kernel, prepares no kernel environment under either `KernelPrewarm` mode and gets the TS no-tools prompt, and `SessionEngineConfig::append_system_prompt` carries the `--append-system-prompt` sources). `kernel::provisioner::IpythonKernelProvisioner::start_requests` (the synchronous start-request receipt verifiers read to prove a session never asked for Python). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only). +`SessionEngine` (message in -> events out; `SessionEngine::dispose` ends a session: its provider connection state, then its kernel), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager (with its memory ceiling: `KernelManagerOptions`/`IpythonKernelProvisionerOptions` `memory_limit_gb`/`memory_backstop` and the telemetry-only `on_memory_action`/`on_snapshot_guard` seams with their `KernelMemoryActionStats`/`KernelSnapshotGuardStats` primitives, `KernelCellLine` on kernel errors, and the `queued_memory_notices`/`memory_notices` result fields; the ladder itself - policy, process tree, watcher, messages - stays `pub(crate)` in `kernel::memory_guard`), settings (`SettingsManager`, including `get_kernel_memory_limit_gb`/`get_kernel_memory_backstop` and the fork's `get_`/`set_subagent_default_model`/`_thinking` and `get_subagent_models`), `session_engine::helper_model` (fork-only: the helper-model order for a spawn that names no model or thinking level - `HelperDefaults` layers, `plan_helper`, the `subagent_model_state` row reader, the env/create-key names and the once-per-process warnings - plus the helper model list `HelperModelList` with `normalize_model_list`/`parse_model_list`; the hosts resolve the picked reference against their catalogs and enforce the list), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children and pa-cli for inline print children; its fork-only `helper_model_list` limits the `rlm.find_models` roster; also owns the shared spawn/depth facts, child session directories and depth precedence), `session_engine::semantic_edges` (the TS `semantic-edges.ts` WRITER: `SemanticEdgeRecorder`/`SemanticEdgeIdentity`, `semantic_edge_ledger_path` + `last_committed_request_id`, and the `X-ACP-Model-Request-ID`/`Idempotency-Key` constants — one durable per-session ledger of model-request events, byte-compatible with the TS lines; the fold and any publishing stay downstream), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`, carrying the session's transport preference into every request; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, owed RLM continuation deferral and wake-up ownership, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill_use_count` session counter counts at the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). `resources::{ResourceLoadingPolicy, ResourceDiscovery}` (the session's resource-discovery policy, `SessionEngineConfig::resource_loading`: the TS `--no-skills`/`--no-prompt-templates`/`--no-context-files` switches reach the one resource loader at session assembly; explicit skill and prompt-template paths still load). Kernel preparation and exit: `SessionEngineConfig::prewarm_ipython_kernel` takes a `session_engine::engine::KernelPrewarm` (`Background`: the whole boot in the background, for resident sessions - the daemon worker, RPC, ACP; `BeforeFirstTurn`: `create_session` finishes the kernel environment setup - a fresh home's venv build, missing skill installs, the readiness probe - and only the process boot stays in the background, for one-shot print/json runs), `SessionEngine::abandon_kernel` (a one-shot host's last step: abandon the boot - the host's runtime shutdown drops it, killing any setup child - and kill the kernel without a final snapshot; an abandoned boot reports no `kernel bootstrap` outcome), `IpythonKernelProvisioner::{prepare_environment, abandon}`, `kernel::bootstrap::prepare_kernel_environment` (fails when a fresh setup leaves the venv unready), and `EnsureKernelPythonOptions::cancel` (every `uv` step and interpreter probe is an owned tokio child, killed when its future drops; an explicit cancel also kills and reaps it, and a cancelled probe never triggers a rebuild; the provisioner never passes one - the venv is shared by every session, so one session's dispose does not cancel its setup), and `kernel::bootstrap::{set_kernel_setup_trace, KernelSetupTrace}` (the opt-in, process-wide setup trace the CLI's `--verbose` routes to stderr). `session_engine::tool_selection::ToolSelection` (the launch tool-selection policy, `SessionEngineConfig::tool_selection` with `ToolSelection::from_flags` over the `pa_types::daemon::ToolSelectionFlags` vocabulary: an explicit `--tools` list wins, then `--no-tools`, then `--no-builtin-tools`; the engine filters both the request's tool definitions and the executable tools through it, a session without `ipython` asks for no kernel, prepares no kernel environment under either `KernelPrewarm` mode and gets the TS no-tools prompt, and `SessionEngineConfig::append_system_prompt` carries the `--append-system-prompt` sources). `kernel::provisioner::IpythonKernelProvisioner::start_requests` (the synchronous start-request receipt verifiers read to prove a session never asked for Python). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only). ## Depends on pa-types, pa-ai, pa-agent (one-way). diff --git a/crates/pa-core/src/session_engine/helper_model.rs b/crates/pa-core/src/session_engine/helper_model.rs index 44f8de43e73..aa22efd122e 100644 --- a/crates/pa-core/src/session_engine/helper_model.rs +++ b/crates/pa-core/src/session_engine/helper_model.rs @@ -12,6 +12,11 @@ //! The value `parent` at layer 2 or 3 stops the walk there and keeps the parent's value. Pure //! decisions live here; each host resolves the picked model reference against its catalog (an //! unknown default warns once and falls back to the parent's model). +//! +//! The helper model list ([`HelperModelList`], settings `subagentModels`) limits what spawned +//! agents may run on: a spawn call naming a model outside it is refused, a settings default or +//! parent model outside it falls to its first entry, and a person's choice (the session override, +//! or the session's own additions to the list) is always allowed. use std::collections::HashSet; use std::sync::{Mutex, OnceLock}; @@ -33,6 +38,10 @@ pub const SUBAGENT_MODEL_STATE_CUSTOM_TYPE: &str = "subagent_model_state"; pub const SUBAGENT_MODEL_CONFIG_KEY: &str = "subagentModel"; /// The create-config key carrying the session override's thinking level. pub const SUBAGENT_THINKING_CONFIG_KEY: &str = "subagentThinking"; +/// The env var a headless invocation reads as its session's additions to the helper model list. +pub const SUBAGENT_MODELS_ENV: &str = "PRIME_SUBAGENT_MODELS"; +/// The create-config key carrying the session's additions to the helper model list. +pub const SUBAGENT_MODELS_CONFIG_KEY: &str = "subagentModels"; /// The layer a resolved helper value came from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -45,6 +54,9 @@ pub enum HelperSource { Settings, /// The parent's own value. Parent, + /// The helper model list's first entry: the settings default or the parent's model fell + /// outside the list. + List, } impl HelperSource { @@ -56,18 +68,24 @@ impl HelperSource { HelperSource::Session => "session", HelperSource::Settings => "settings", HelperSource::Parent => "parent", + HelperSource::List => "list", } } } -/// One layer of helper defaults: a model reference (`provider/model-id` or `parent`) and a -/// thinking level (a level name or `parent`). `None` leaves the field to the next layer. +/// One layer of helper defaults: a model reference (`provider/model-id` or `parent`), a +/// thinking level (a level name or `parent`), and models for the helper model list. `None` +/// leaves the field to the next layer. #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct HelperDefaults { #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub thinking: Option, + /// The settings layer: the file's `subagentModels`. The session layer: the session's + /// additions to that list (`--subagent-models`, `PRIME_SUBAGENT_MODELS`, `/subagent-models`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub models: Option>, } impl HelperDefaults { @@ -95,13 +113,24 @@ impl HelperDefaults { Ok(Self { model: trimmed(model), thinking, + models: None, }) } - /// True when the layer names neither field. + /// The layer with its model list replaced: entries are normalized + /// ([`normalize_model_list`]), and a list with no entries left is unset. + #[must_use] + pub fn with_models(self, models: Option>) -> Self { + let models = models + .map(|models| normalize_model_list(models.iter().map(String::as_str))) + .filter(|models| !models.is_empty()); + Self { models, ..self } + } + + /// True when the layer names no field. #[must_use] pub fn is_empty(&self) -> bool { - self.model.is_none() && self.thinking.is_none() + self.model.is_none() && self.thinking.is_none() && self.models.is_none() } /// Fill each field this layer lacks from `fallback`. @@ -110,15 +139,18 @@ impl HelperDefaults { Self { model: self.model.or_else(|| fallback.model.clone()), thinking: self.thinking.or_else(|| fallback.thinking.clone()), + models: self.models.or_else(|| fallback.models.clone()), } } - /// The settings-file layer (`subagentDefaultModel`/`subagentDefaultThinking`). + /// The settings-file layer (`subagentDefaultModel`/`subagentDefaultThinking`/ + /// `subagentModels`). #[must_use] pub fn from_settings(settings: &SettingsManager) -> Self { Self { model: settings.get_subagent_default_model(), thinking: settings.get_subagent_default_thinking(), + models: settings.get_subagent_models(), } } @@ -128,8 +160,8 @@ impl HelperDefaults { Self::from_settings(&SettingsManager::create(cwd, agent_dir)) } - /// The layer a create config carries (`subagentModel`/`subagentThinking`); a key of the - /// wrong type or an invalid level reads as unset. + /// The layer a create config carries (`subagentModel`/`subagentThinking`/`subagentModels`); + /// a key of the wrong type or an invalid level reads as unset. #[must_use] pub fn from_create_config(config: &Map) -> Self { let field = |key: &str| config.get(key).and_then(Value::as_str); @@ -138,10 +170,17 @@ impl HelperDefaults { field(SUBAGENT_THINKING_CONFIG_KEY), ) .unwrap_or_default() + .with_models(string_list(config.get(SUBAGENT_MODELS_CONFIG_KEY))) } /// Write the layer into a create config; unset fields write nothing. pub fn write_into(&self, config: &mut Map) { + if let Some(models) = &self.models { + config.insert( + SUBAGENT_MODELS_CONFIG_KEY.to_string(), + serde_json::json!(models), + ); + } if let Some(model) = &self.model { config.insert( SUBAGENT_MODEL_CONFIG_KEY.to_string(), @@ -157,6 +196,115 @@ impl HelperDefaults { } } +/// The string entries of a JSON array (other entries dropped); `None` for a missing or non-array +/// value. +fn string_list(value: Option<&Value>) -> Option> { + value.and_then(Value::as_array).map(|entries| { + entries + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) +} + +/// Model-list entries as stored: trimmed, blanks dropped, repeats (ignoring case) dropped, order +/// kept. +#[must_use] +pub fn normalize_model_list<'a>(entries: impl IntoIterator) -> Vec { + let mut models: Vec = Vec::new(); + for entry in entries.into_iter().map(str::trim) { + if !entry.is_empty() && !models.iter().any(|model| model.eq_ignore_ascii_case(entry)) { + models.push(entry.to_string()); + } + } + models +} + +/// A typed model list (`--subagent-models a,b`, `PRIME_SUBAGENT_MODELS`, `/subagent-models`): +/// entries split on commas or whitespace, then normalized. +#[must_use] +pub fn parse_model_list(text: &str) -> Vec { + normalize_model_list(text.split(|c: char| c == ',' || c.is_whitespace())) +} + +/// The helper model list of one session (Oneiron fork): the models spawned agents may run on. +/// The settings file's `subagentModels` come first (so its first entry is the fallback), then the +/// session's additions and its person-set helper model, which a person chose and so are always +/// allowed. Built only by [`HelperModelList::active`], so it is never empty. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HelperModelList { + entries: Vec, + widened: bool, +} + +impl HelperModelList { + /// The list a session's spawns check; `None` when the settings file sets none (no limit: + /// the session's additions widen a list, they never start one). + #[must_use] + pub fn active(session: &HelperDefaults, settings: &HelperDefaults) -> Option { + let base = normalize_model_list(settings.models.iter().flatten().map(String::as_str)); + if base.is_empty() { + return None; + } + let person_model = session + .model + .as_deref() + .filter(|model| *model != INHERIT_PARENT); + let entries = normalize_model_list( + base.iter() + .chain(session.models.iter().flatten()) + .map(String::as_str) + .chain(person_model), + ); + Some(Self { + widened: entries.len() > base.len(), + entries, + }) + } + + /// The entries in order. + #[must_use] + pub fn entries(&self) -> &[String] { + &self.entries + } + + /// The fallback for a settings default or parent model outside the list. + #[must_use] + pub fn first(&self) -> &str { + &self.entries[0] + } + + /// Whether a model reference is on the list (an exact, case-insensitive match). + #[must_use] + pub fn allows(&self, selector: &str) -> bool { + self.entries + .iter() + .any(|entry| entry.eq_ignore_ascii_case(selector)) + } + + /// The status label of where the list came from: `settings`, or `settings+session` when the + /// session added entries. + #[must_use] + pub fn source(&self) -> &'static str { + if self.widened { + "settings+session" + } else { + "settings" + } + } + + /// The refusal of a spawn call naming a model outside the list: it names the allowed models + /// so the agent can retry with one. + #[must_use] + pub fn refusal(&self, reference: &str, target: &str) -> String { + format!( + "Requested {target} model \"{reference}\" is not on the helper model list; use one of: {} (or omit model= for the default)", + self.entries.join(", ") + ) + } +} + /// One field's pick: the value the winning layer names, `None` for the parent's own value. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HelperPick { @@ -223,15 +371,15 @@ pub fn plan_helper( } } -/// Record that a default model reference failed to resolve: `true` the first time this process -/// sees the reference from this layer, so the caller warns once. +/// Record one helper-model warning line: `true` the first time this process sees it, so the +/// caller warns once. #[must_use] -pub fn first_unknown_helper_model(reference: &str, source: HelperSource) -> bool { +pub fn first_helper_notice(line: &str) -> bool { static SEEN: OnceLock>> = OnceLock::new(); SEEN.get_or_init(|| Mutex::new(HashSet::new())) .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(format!("{}\u{0}{reference}", source.wire_name())) + .insert(line.to_string()) } /// The warning line for a default helper model the catalog does not know. @@ -240,7 +388,7 @@ pub fn unknown_helper_model_warning(reference: &str, source: HelperSource) -> St let origin = match source { HelperSource::Settings => "subagentDefaultModel", HelperSource::Session => "The session's helper model", - HelperSource::Spawn | HelperSource::Parent => "The helper model", + HelperSource::Spawn | HelperSource::Parent | HelperSource::List => "The helper model", }; format!( "Warning: {origin} \"{reference}\" is not in the model catalog (models.json); spawned agents use the parent's model" @@ -271,7 +419,11 @@ fn parse_override_row(line: &str) -> Option { } let data = value.get("data").and_then(Value::as_object); let field = |key: &str| data.and_then(|data| data.get(key)).and_then(Value::as_str); - Some(HelperDefaults::new(field("model"), field("thinking")).unwrap_or_default()) + Some( + HelperDefaults::new(field("model"), field("thinking")) + .unwrap_or_default() + .with_models(string_list(data.and_then(|data| data.get("models")))), + ) } /// The fields of the `custom` session entry that persists one override (the worker's @@ -280,7 +432,7 @@ fn parse_override_row(line: &str) -> Option { pub fn session_override_row(layer: &HelperDefaults) -> Value { serde_json::json!({ "customType": SUBAGENT_MODEL_STATE_CUSTOM_TYPE, - "data": { "model": layer.model, "thinking": layer.thinking }, + "data": { "model": layer.model, "thinking": layer.thinking, "models": layer.models }, }) } @@ -376,18 +528,20 @@ mod tests { #[test] fn the_create_config_round_trips_the_override() { - let override_layer = layer(Some("cpa-r/deepseek-flash-1017"), Some("max")); + let override_layer = layer(Some("cpa-r/deepseek-flash-1017"), Some("max")) + .with_models(Some(vec!["cpa-a/gpt-6".to_string()])); let mut config = Map::new(); override_layer.write_into(&mut config); assert_eq!(HelperDefaults::from_create_config(&config), override_layer); - // A malformed level reads as no override, never a create failure. + // A malformed level reads as no model or thinking override, never a create failure; the + // list keeps its own key. config.insert( SUBAGENT_THINKING_CONFIG_KEY.to_string(), Value::String("loud".into()), ); assert_eq!( HelperDefaults::from_create_config(&config), - HelperDefaults::default() + list_layer(&["cpa-a/gpt-6"]) ); } @@ -454,7 +608,8 @@ mod tests { [ r#"{"type":"session","id":"s"}"#.to_string(), row(&layer(Some("cpa-r/kimi"), None)), - row(&layer(Some("cpa-r/deepseek-flash-1017"), Some("max"))), + row(&layer(Some("cpa-r/deepseek-flash-1017"), Some("max")) + .with_models(Some(vec!["cpa-a/gpt-6".to_string()]))), r#"{"type":"message","id":"m"}"#.to_string(), ] .join("\n"), @@ -463,7 +618,10 @@ mod tests { let path = file.to_string_lossy().to_string(); assert_eq!( persisted_session_override(Some(&path)), - Some(layer(Some("cpa-r/deepseek-flash-1017"), Some("max"))) + Some( + layer(Some("cpa-r/deepseek-flash-1017"), Some("max")) + .with_models(Some(vec!["cpa-a/gpt-6".to_string()])) + ) ); // A cleared override is an explicit, empty row. let mut content = std::fs::read_to_string(&file).unwrap(); @@ -480,14 +638,116 @@ mod tests { #[test] fn an_unknown_default_warns_once_per_reference_and_layer() { let reference = "cpa-r/warn-once-probe"; - assert!(first_unknown_helper_model( - reference, - HelperSource::Settings - )); - assert!(!first_unknown_helper_model( + let settings = unknown_helper_model_warning(reference, HelperSource::Settings); + assert!(first_helper_notice(&settings)); + assert!(!first_helper_notice(&settings)); + assert!(first_helper_notice(&unknown_helper_model_warning( reference, - HelperSource::Settings - )); - assert!(first_unknown_helper_model(reference, HelperSource::Session)); + HelperSource::Session + ))); + } + + fn list_layer(models: &[&str]) -> HelperDefaults { + HelperDefaults::default() + .with_models(Some(models.iter().map(ToString::to_string).collect())) + } + + /// The settings file's list comes first; the session's additions and its person-set model + /// widen it; a session list alone starts no limit. + #[test] + fn the_helper_model_list_is_the_settings_list_widened_by_the_session() { + let settings = list_layer(&["cpa-r/deepseek-flash-1017", "cpa-r/kimi-k3.1"]); + let list = HelperModelList::active(&HelperDefaults::default(), &settings).unwrap(); + assert_eq!( + list.entries(), + ["cpa-r/deepseek-flash-1017", "cpa-r/kimi-k3.1"] + ); + assert_eq!(list.first(), "cpa-r/deepseek-flash-1017"); + assert_eq!(list.source(), "settings"); + assert!(list.allows("CPA-R/Kimi-K3.1")); + assert!(!list.allows("cpa-a/claude-opus-5")); + assert!(!list.allows("kimi-k3.1"), "a short form is not an entry"); + assert_eq!( + list.refusal("cpa-a/claude-opus-5", "subagent"), + "Requested subagent model \"cpa-a/claude-opus-5\" is not on the helper model list; use one of: cpa-r/deepseek-flash-1017, cpa-r/kimi-k3.1 (or omit model= for the default)" + ); + + // A person's choices widen the list: the session's own entries and its helper model. + let session = layer(Some("cpa-a/claude-opus-5"), None).with_models(Some(vec![ + "cpa-a/gpt-6".to_string(), + "cpa-r/kimi-k3.1".to_string(), + ])); + let list = HelperModelList::active(&session, &settings).unwrap(); + assert_eq!( + list.entries(), + [ + "cpa-r/deepseek-flash-1017", + "cpa-r/kimi-k3.1", + "cpa-a/gpt-6", + "cpa-a/claude-opus-5" + ] + ); + assert_eq!(list.source(), "settings+session"); + // `parent` is no model. + let list = HelperModelList::active(&layer(Some(INHERIT_PARENT), None), &settings).unwrap(); + assert_eq!(list.source(), "settings"); + + // No settings list: no limit, whatever the session adds. + assert_eq!( + HelperModelList::active(&session, &HelperDefaults::default()), + None + ); + assert_eq!( + HelperModelList::active(&session, &list_layer(&[" ", ""])), + None + ); + } + + #[test] + fn model_lists_parse_trim_and_drop_repeats() { + assert_eq!( + parse_model_list(" cpa-r/a, cpa-r/b CPA-R/A,,cpa-r/c "), + ["cpa-r/a", "cpa-r/b", "cpa-r/c"] + ); + assert_eq!(parse_model_list(" , "), Vec::::new()); + assert_eq!(list_layer(&[" ", ""]).models, None); + } + + /// The settings list is global only, accepts an array (non-strings dropped) or one + /// comma-separated string, and a project file cannot widen it. + #[test] + fn the_settings_list_is_global_only() { + let dir = tempfile::TempDir::new().unwrap(); + let agent_dir = dir.path().join("agent"); + std::fs::create_dir_all(&agent_dir).unwrap(); + let project = dir.path().join(".prime").join("agent"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write( + project.join("settings.json"), + r#"{"subagentModels":["cpa-a/claude-opus-5"]}"#, + ) + .unwrap(); + assert_eq!( + HelperDefaults::load_settings(dir.path(), &agent_dir), + HelperDefaults::default() + ); + std::fs::write( + agent_dir.join("settings.json"), + r#"{"subagentModels":[" cpa-r/deepseek-flash-1017 ", 42, "cpa-r/kimi-k3.1"]}"#, + ) + .unwrap(); + assert_eq!( + HelperDefaults::load_settings(dir.path(), &agent_dir), + list_layer(&["cpa-r/deepseek-flash-1017", "cpa-r/kimi-k3.1"]) + ); + std::fs::write( + agent_dir.join("settings.json"), + r#"{"subagentModels":"cpa-r/deepseek-flash-1017, cpa-r/kimi-k3.1"}"#, + ) + .unwrap(); + assert_eq!( + HelperDefaults::load_settings(dir.path(), &agent_dir), + list_layer(&["cpa-r/deepseek-flash-1017", "cpa-r/kimi-k3.1"]) + ); } } diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rs index 0eb38155690..f1a8dadeba7 100644 --- a/crates/pa-core/src/session_engine/rlm_host.rs +++ b/crates/pa-core/src/session_engine/rlm_host.rs @@ -185,6 +185,12 @@ pub trait RlmSubagentHost: Send + Sync { /// Rename the current session (`session_id` absent) or one direct /// child (TS `rlm.rename`); answers the applied name. fn rename(&self, name: String, session_id: Option) -> RlmHostFuture; + /// The helper model list this host's spawns check (Oneiron fork, settings `subagentModels` + /// plus the session's additions): `rlm.find_models` lists only its models. `None` when no + /// list limits spawns; the default suits hosts that cannot spawn. + fn helper_model_list(&self) -> RlmHostFuture> { + Box::pin(async { Ok(None) }) + } } /// Host behavior for sessions with no child runtime: truthful empties and the @@ -524,10 +530,12 @@ pub fn register_rlm_host_handlers(handlers: &mut HostRequestHandlers, bridge: &A fn register_find_models(handlers: &mut HostRequestHandlers, bridge: &Arc) { let registry = Arc::clone(&bridge.registry); + let host = Arc::clone(&bridge.host); handlers.register( "rlm.find_models", host_handler(move |payload| { let registry = Arc::clone(®istry); + let host = Arc::clone(&host); Box::pin(async move { let data = &payload.data; let Some(query) = data.get("query").and_then(Value::as_str) else { @@ -544,9 +552,17 @@ fn register_find_models(handlers: &mut HostRequestHandlers, bridge: &Arc = registry .get_rlm_searchable_models() .into_iter() + .filter(|model| { + list.as_ref().is_none_or(|list| { + list.allows(&format!("{}/{}", model.provider, model.id)) + }) + }) .map(|model| RlmModelInfo { provider: model.provider.clone(), id: model.id.clone(), @@ -900,16 +916,24 @@ mod tests { targets: Arc>>, collects: Arc>>, renames: Arc>>, + helper_models: Option, } impl RecordingHost { fn new() -> Arc { + Self::with_helper_models(None) + } + + fn with_helper_models( + helper_models: Option, + ) -> Arc { Arc::new(Self { spawn_requests: Arc::new(Mutex::new(Vec::new())), create_requests: Arc::new(Mutex::new(Vec::new())), targets: Arc::new(Mutex::new(Vec::new())), collects: Arc::new(Mutex::new(Vec::new())), renames: Arc::new(Mutex::new(Vec::new())), + helper_models, }) } } @@ -1025,6 +1049,12 @@ mod tests { Ok(name) }) } + fn helper_model_list( + &self, + ) -> RlmHostFuture> { + let list = self.helper_models.clone(); + Box::pin(async move { Ok(list) }) + } } fn persisted_session(dir: &std::path::Path) -> SessionManager { @@ -1198,6 +1228,33 @@ mod tests { ); } + /// With a helper model list set, the roster lists only the models a spawn may name. + #[tokio::test] + async fn find_models_lists_only_the_helper_model_list() { + use crate::session_engine::helper_model::{HelperDefaults, HelperModelList}; + let dir = tempfile::TempDir::new().unwrap(); + let settings = + HelperDefaults::default().with_models(Some(vec!["test-provider/glm-5.3".to_string()])); + let list = HelperModelList::active(&HelperDefaults::default(), &settings); + let wiring = wired(dir.path(), Some(RecordingHost::with_helper_models(list))); + let response = call( + &wiring, + "rlm.find_models", + json!({ "type": "rlm.find_models", "query": "" }), + ) + .await + .unwrap(); + assert_eq!( + response["models"], + json!([{ + "provider": "test-provider", + "id": "glm-5.3", + "name": "GLM 5.3", + "selector": "test-provider/glm-5.3", + }]) + ); + } + #[tokio::test] async fn progress_note_throttles_and_stores() { let dir = tempfile::TempDir::new().unwrap(); diff --git a/crates/pa-core/src/settings/load.rs b/crates/pa-core/src/settings/load.rs index 690c58f3aa6..7c64901794a 100644 --- a/crates/pa-core/src/settings/load.rs +++ b/crates/pa-core/src/settings/load.rs @@ -14,6 +14,7 @@ const KNOWN_FIELDS: &[&str] = &[ "defaultModel", "subagentDefaultModel", "subagentDefaultThinking", + "subagentModels", "updateChannel", "recentModels", "auxiliaryModel", diff --git a/crates/pa-core/src/settings/manager.rs b/crates/pa-core/src/settings/manager.rs index 0e94a1bbeb7..692f97d08b3 100644 --- a/crates/pa-core/src/settings/manager.rs +++ b/crates/pa-core/src/settings/manager.rs @@ -588,6 +588,23 @@ impl SettingsManager { }) } + /// The helper model list (`subagentModels`): the models spawned agents may run on, trimmed, + /// blanks, non-strings and repeats dropped. Global scope only, like `allowedModels`: a project + /// file (which an agent can write) cannot widen it. `None` (absent, or a list that trims to + /// empty) is no limit. + #[must_use] + pub fn get_subagent_models(&self) -> Option> { + use crate::session_engine::helper_model::{normalize_model_list, parse_model_list}; + let models = match self.global.subagent_models.as_ref()? { + serde_json::Value::Array(entries) => { + normalize_model_list(entries.iter().filter_map(serde_json::Value::as_str)) + } + serde_json::Value::String(text) => parse_model_list(text), + _ => Vec::new(), + }; + (!models.is_empty()).then_some(models) + } + /// Set (or, with `None`, remove) the global `subagentDefaultModel`. /// /// # Errors diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rs index a38dac996eb..83bd79d8a78 100644 --- a/crates/pa-core/src/settings/types.rs +++ b/crates/pa-core/src/settings/types.rs @@ -313,6 +313,12 @@ pub struct Settings { /// parent's level. Clamped to what the helper's model supports. Raw text: the getter /// validates it. pub subagent_default_thinking: Option, + /// The helper model list (fork-only): the models ("provider/model-id") spawned agents may run + /// on, in order. A spawn call naming another model is refused; a default or parent model + /// outside it falls to the first entry. Raw JSON (an array of strings, or one comma-separated + /// string) so a malformed entry drops alone instead of the whole list; the getter validates. + /// Absent or empty: no limit. + pub subagent_models: Option, pub update_channel: Option, pub recent_models: Option>, pub auxiliary_model: Option, diff --git a/crates/pa-daemon/README.md b/crates/pa-daemon/README.md index 251f4bc5a18..9c07f6ee769 100644 --- a/crates/pa-daemon/README.md +++ b/crates/pa-daemon/README.md @@ -86,10 +86,13 @@ parent-side registry serves `rlm.list_subagents`/`rlm.collect`/ and thinking-level validation live in `rlm_child_model.rs`, including the fork's helper-model order for a spawn that names no model (`resolve_helper`: the session override, then `subagentDefaultModel`/`subagentDefaultThinking`, -then the parent; the override rides the child create as -`subagentModel`/`subagentThinking`, persists as a `subagent_model_state` -row, and `get_subagent_model_status`/`set_subagent_model` serve it behind -the `subagent_model` capability); the create +then the parent, and the helper model list `subagentModels`: a spawn naming a +model off it is refused, a default off it falls to its first entry; the +override rides the child create as +`subagentModel`/`subagentThinking`/`subagentModels`, persists as a +`subagent_model_state` row, and `get_subagent_model_status`/ +`set_subagent_model` serve it behind the `subagent_model` capability, +`set_subagent_models` behind `subagent_models`); the create command carries the RLM recursion identity (`rlmDepth`/`rlmMaxDepth`/ `parentSessionPath`/`thinking`) so respawned children keep their depth. Per-session model binding: the create-config `provider`/`model`/`apiKey` are authoritative for worker model diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs index 00232bc88f1..d50b065381f 100644 --- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs +++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs @@ -1355,11 +1355,9 @@ impl SessionEngine for AgentSessionEngine { } fn subagent_model_status(&self) -> Value { - let session = self - .children - .as_ref() - .map(|children| children.subagent_override()) - .unwrap_or_default(); + use pa_core::session_engine::helper_model::{HelperModelList, HelperSource}; + let agent_dir = &self.config.agent_dir; + let session = crate::engine::SessionEngine::subagent_override(self); let settings = pa_core::session_engine::helper_model::HelperDefaults::load_settings( &self.cwd(), &self.config.agent_dir, @@ -1369,17 +1367,52 @@ impl SessionEngine for AgentSessionEngine { let model_known = plan.model.value.as_deref().map(|reference| { crate::rlm_child_model::helper_model_known(&self.config.agent_dir, reference) }); + let list = crate::rlm_child_model::helper_model_list(agent_dir, &session, &settings); + // Whether the model the spawns default to is on the list (`null` without a list, or when + // the parent's model is unknown); off it, they run on the list's first entry. + let parent_model = self + .children + .as_ref() + .and_then(|children| children.parent_model()); + let model_allowed = list.as_ref().and_then(|list| match plan.model.source { + HelperSource::Session if model_known != Some(false) => Some(true), + HelperSource::Settings => plan.model.value.as_deref().and_then(|reference| { + crate::rlm_child_model::resolve_child_model_unchecked( + &self.config.agent_dir, + Some(reference), + parent_model.as_deref(), + "subagent", + ) + .ok() + .or_else(|| parent_model.clone()) + .map(|model| list.allows(&model)) + }), + HelperSource::Session + | HelperSource::Parent + | HelperSource::Spawn + | HelperSource::List => parent_model.as_deref().map(|model| list.allows(model)), + }); json!({ "model": plan.model.value, "modelSource": plan.model.source.wire_name(), "modelKnown": model_known, + "modelAllowed": model_allowed, "thinking": plan.thinking.value, "thinkingSource": plan.thinking.source.wire_name(), + "models": list.as_ref().map(HelperModelList::entries), + "modelsSource": list.as_ref().map(HelperModelList::source), "session": session, "settings": settings, }) } + fn subagent_override(&self) -> pa_core::session_engine::helper_model::HelperDefaults { + self.children + .as_ref() + .map(|children| children.subagent_override()) + .unwrap_or_default() + } + fn set_subagent_model( &self, layer: pa_core::session_engine::helper_model::HelperDefaults, diff --git a/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs b/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs index ae3b4715ed3..d63bd2990a7 100644 --- a/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs +++ b/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs @@ -421,7 +421,7 @@ fn the_session_override_beats_the_settings_file_and_reseeds_from_the_session_fil .unwrap(); let engine = AgentSessionEngine::new(AgentEngineConfig { cwd: dir.path().to_path_buf(), - agent_dir, + agent_dir: agent_dir.clone(), provider: None, model: None, api_key: None, @@ -445,12 +445,72 @@ fn the_session_override_beats_the_settings_file_and_reseeds_from_the_session_fil "model": "test-provider/helper-flash", "modelSource": "settings", "modelKnown": true, + "modelAllowed": null, "thinking": "high", "thinkingSource": "settings", + "models": null, + "modelsSource": null, "session": {}, "settings": { "model": "test-provider/helper-flash", "thinking": "high" }, }) ); + // A helper model list without the settings default: the status names the list and flags + // the default (spawns run on the list's first entry). + let with_list = json!({ + "subagentDefaultModel": "test-provider/helper-flash", + "subagentDefaultThinking": "high", + "subagentModels": ["test-provider/listed"], + }); + std::fs::write(agent_dir.join("settings.json"), with_list.to_string()).unwrap(); + let status = crate::engine::SessionEngine::subagent_model_status(&engine); + assert_eq!( + [ + &status["models"], + &status["modelsSource"], + &status["modelAllowed"] + ], + [ + &json!(["test-provider/listed"]), + &json!("settings"), + &json!(false) + ] + ); + let children = engine.children.as_ref().unwrap(); + children.set_model("test-provider/helper-flash".to_string()); + std::fs::write( + agent_dir.join("settings.json"), + json!({ + "subagentDefaultModel": "test-provider/unknown", + "subagentDefaultThinking": "high", + "subagentModels": ["test-provider/listed", "test-provider/helper-flash"], + }) + .to_string(), + ) + .unwrap(); + assert_eq!( + crate::engine::SessionEngine::subagent_model_status(&engine), + json!({ + "model": "test-provider/unknown", + "modelSource": "settings", + "modelKnown": false, + "modelAllowed": true, + "thinking": "high", + "thinkingSource": "settings", + "models": ["test-provider/listed", "test-provider/helper-flash"], + "modelsSource": "settings", + "session": {}, + "settings": { + "model": "test-provider/unknown", "thinking": "high", + "models": ["test-provider/listed", "test-provider/helper-flash"], + }, + }) + ); + std::fs::write( + agent_dir.join("settings.json"), + json!({ "subagentDefaultModel": "test-provider/helper-flash", "subagentDefaultThinking": "high" }) + .to_string(), + ) + .unwrap(); let unknown = HelperDefaults::new(Some("cpa-r/not-in-catalog"), None).unwrap(); crate::engine::SessionEngine::set_subagent_model(&engine, unknown.clone()).unwrap(); assert_eq!( @@ -459,8 +519,11 @@ fn the_session_override_beats_the_settings_file_and_reseeds_from_the_session_fil "model": "cpa-r/not-in-catalog", "modelSource": "session", "modelKnown": false, + "modelAllowed": null, "thinking": "high", "thinkingSource": "settings", + "models": null, + "modelsSource": null, "session": { "model": "cpa-r/not-in-catalog" }, "settings": { "model": "test-provider/helper-flash", "thinking": "high" }, }) diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rs index b2650b31633..303ac2834da 100644 --- a/crates/pa-daemon/src/engine.rs +++ b/crates/pa-daemon/src/engine.rs @@ -513,21 +513,31 @@ pub trait SessionEngine: Send + Sync { } /// The helper model and thinking level this session's spawns resolve to when the call names - /// none (`get_subagent_model_status`): `{ model, modelSource, modelKnown, thinking, - /// thinkingSource, session, settings }`. A session without a settings surface (the scripted - /// harness engine) answers the parent's values. + /// none, and the helper model list they may run on (`get_subagent_model_status`): `{ model, + /// modelSource, modelKnown, modelAllowed, thinking, thinkingSource, models, modelsSource, + /// session, settings }`. A session without a settings surface (the scripted harness engine) + /// answers the parent's values and no list. fn subagent_model_status(&self) -> Value { json!({ "model": null, "modelSource": "parent", "modelKnown": null, + "modelAllowed": null, "thinking": null, "thinkingSource": "parent", + "models": null, + "modelsSource": null, "session": {}, "settings": {}, }) } + /// This session's live helper-model override (the layer `set_subagent_model` and + /// `set_subagent_models` each replace part of). Lock-only: no I/O. + fn subagent_override(&self) -> pa_core::session_engine::helper_model::HelperDefaults { + pa_core::session_engine::helper_model::HelperDefaults::default() + } + /// Replace this session's live helper-model override (`set_subagent_model`; the worker writes /// the durable row under the same lock). Cheap and lock-only: no I/O. /// diff --git a/crates/pa-daemon/src/headless_client.rs b/crates/pa-daemon/src/headless_client.rs index c75f0f58c7b..5656d734d2e 100644 --- a/crates/pa-daemon/src/headless_client.rs +++ b/crates/pa-daemon/src/headless_client.rs @@ -81,6 +81,9 @@ pub struct HostedSessionOptions { /// The session's helper-model override (`--subagent-model`/`--subagent-thinking` or their /// env vars): set on the session right after its create, before any prompt. pub subagent_override: pa_core::session_engine::helper_model::HelperDefaults, + /// The global settings set a helper model list (`subagentModels`): a daemon without the + /// `subagent_models` capability would ignore it, so the open refuses one. + pub enforce_helper_model_list: bool, } /// What the daemon reported for the hosted session. @@ -198,19 +201,30 @@ impl HostedHeadlessSession { anyhow::bail!("{refusal}"); } // A daemon without `subagent_model` would run the session's helpers on the parent's - // model: refuse instead of dropping the override. - if !options.subagent_override.is_empty() - && !self - .link + // model, one without `subagent_models` ignores the helper model list: refuse instead of + // dropping the override. + let advertises = |wanted: &str| { + self.link .server_capabilities .iter() - .any(|capability| capability == pa_types::daemon::SUBAGENT_MODEL_CAPABILITY) - { + .any(|capability| capability == wanted) + }; + let override_model = options.subagent_override.model.is_some() + || options.subagent_override.thinking.is_some(); + if override_model && !advertises(pa_types::daemon::SUBAGENT_MODEL_CAPABILITY) { anyhow::bail!( "The running daemon cannot apply --subagent-model/--subagent-thinking to a hosted session (it does not advertise {}); stop it so a current one starts, or run without --daemon-hosted", pa_types::daemon::SUBAGENT_MODEL_CAPABILITY ); } + if (options.subagent_override.models.is_some() || options.enforce_helper_model_list) + && !advertises(pa_types::daemon::SUBAGENT_MODELS_CAPABILITY) + { + anyhow::bail!( + "The running daemon cannot enforce the helper model list (subagentModels, --subagent-models) on a hosted session (it does not advertise {}); stop it so a current one starts, or run without --daemon-hosted", + pa_types::daemon::SUBAGENT_MODELS_CAPABILITY + ); + } let policy_supported = self .link .server_capabilities @@ -281,7 +295,7 @@ impl HostedHeadlessSession { .ok_or_else(|| anyhow::anyhow!("Daemon returned an invalid create response"))?; // The override lands before the first prompt and persists in the session file (the // latest explicit choice wins on a resume). - if !options.subagent_override.is_empty() { + if override_model { let set = DaemonCommand::SetSubagentModel { id: None, active_session_id: active_session_id.clone(), @@ -291,6 +305,15 @@ impl HostedHeadlessSession { }; success_data(self.link.request(set, REQUEST_BOUND).await?)?; } + if let Some(models) = &options.subagent_override.models { + let set = DaemonCommand::SetSubagentModels { + id: None, + active_session_id: active_session_id.clone(), + models: models.clone(), + rest: Map::default(), + }; + success_data(self.link.request(set, REQUEST_BOUND).await?)?; + } let attach = DaemonCommand::Attach { id: None, active_session_id: active_session_id.clone(), diff --git a/crates/pa-daemon/src/headless_client/tests.rs b/crates/pa-daemon/src/headless_client/tests.rs index decf38caeb1..5e61c279923 100644 --- a/crates/pa-daemon/src/headless_client/tests.rs +++ b/crates/pa-daemon/src/headless_client/tests.rs @@ -105,6 +105,7 @@ impl FakeSupervisor { telemetry_disabled: false, session_policy: SessionPolicy::default(), subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), + enforce_helper_model_list: false, } } @@ -601,6 +602,25 @@ async fn same_file_resume_attaches_the_live_worker() { assert_eq!(fake.commands(), ["list", "attach"]); } +/// A helper model list (global `subagentModels`, or `--subagent-models`): a daemon without +/// `subagent_models` would ignore it, so the open is refused before any command. +#[tokio::test] +async fn a_helper_model_list_needs_the_daemon_capability() { + let old = FakeSupervisor::start(Box::new(|kind, _| panic!("unexpected command {kind}"))); + let error = bounded(HostedHeadlessSession::open(HostedSessionOptions { + enforce_helper_model_list: true, + ..old.options() + })) + .await + .err() + .expect("an older daemon is refused"); + assert_eq!( + error.to_string(), + "The running daemon cannot enforce the helper model list (subagentModels, --subagent-models) on a hosted session (it does not advertise subagent_models); stop it so a current one starts, or run without --daemon-hosted" + ); + assert_eq!(old.commands(), Vec::::new()); +} + /// The launch tool selection: an older daemon (no /// `session_tool_selection`) gets nothing, not even a create it would run /// with every tool; a current daemon receives the keys on the create. diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rs index 9941234632b..9344bf34fc0 100644 --- a/crates/pa-daemon/src/protocol.rs +++ b/crates/pa-daemon/src/protocol.rs @@ -171,6 +171,8 @@ pub const KNOWN_COMMAND_TYPES: &[&str] = &[ // Oneiron fork (capability `subagent_model`): the session's helper-model override. "get_subagent_model_status", "set_subagent_model", + // Oneiron fork (capability `subagent_models`): the session's helper model list additions. + "set_subagent_models", ]; /// Parsed client command envelope. @@ -369,6 +371,8 @@ pub fn default_server_capabilities() -> Vec { // Fork-only: `get_subagent_model_status`/`set_subagent_model`, the // session's helper-model override. pa_types::daemon::SUBAGENT_MODEL_CAPABILITY, + // Fork-only: the helper model list and `set_subagent_models`. + pa_types::daemon::SUBAGENT_MODELS_CAPABILITY, ] .iter() .map(std::string::ToString::to_string), @@ -878,6 +882,9 @@ pub fn command_active_session_id(command: &DaemonCommand) -> Option<&str> { | DaemonCommand::SetSubagentModel { active_session_id, .. } + | DaemonCommand::SetSubagentModels { + active_session_id, .. + } | DaemonCommand::GetSessionContext { active_session_id, .. } @@ -1070,6 +1077,7 @@ pub fn command_type_name(command: &DaemonCommand) -> &'static str { DaemonCommand::SetRlmMaxDepth { .. } => "set_rlm_max_depth", DaemonCommand::GetSubagentModelStatus { .. } => "get_subagent_model_status", DaemonCommand::SetSubagentModel { .. } => "set_subagent_model", + DaemonCommand::SetSubagentModels { .. } => "set_subagent_models", DaemonCommand::RenameSavedSession { .. } => "rename_saved_session", DaemonCommand::DeleteSavedSession { .. } => "delete_saved_session", DaemonCommand::GetSessionContext { .. } => "get_session_context", diff --git a/crates/pa-daemon/src/rlm_child_model.rs b/crates/pa-daemon/src/rlm_child_model.rs index 7aba7be3288..6de67ea7766 100644 --- a/crates/pa-daemon/src/rlm_child_model.rs +++ b/crates/pa-daemon/src/rlm_child_model.rs @@ -7,8 +7,8 @@ use anyhow::{anyhow, bail, Result}; use pa_ai::models::{get_supported_thinking_levels, thinking_level_from_str}; use pa_core::kernel::rlm_runtime::{find_rlm_model_matches, RlmModelInfo}; use pa_core::session_engine::helper_model::{ - first_unknown_helper_model, plan_helper, unknown_helper_model_warning, HelperDefaults, - HelperSource, + first_helper_notice, plan_helper, unknown_helper_model_warning, HelperDefaults, + HelperModelList, HelperSource, INHERIT_PARENT, }; /// Close matches listed in model-resolution errors. @@ -120,6 +120,36 @@ pub fn resolve_child_model_unchecked( Err(model_unavailable_error(reference, target, &candidates)) } +/// The helper model list a session's spawns check (the roster, the spawn check and the status +/// read the same one): [`HelperModelList::active`] with the person's own helper model resolved +/// to its catalog selector first, so a short form the person typed matches the selector an agent +/// names. A model the catalog does not know stays as typed. +#[must_use] +pub fn helper_model_list( + agent_dir: &Path, + session: &HelperDefaults, + settings: &HelperDefaults, +) -> Option { + settings.models.as_ref()?; + let person = session + .model + .as_deref() + .filter(|model| *model != INHERIT_PARENT) + .and_then(|model| { + resolve_child_model_unchecked(agent_dir, Some(model), None, "subagent").ok() + }); + match person { + Some(selector) => HelperModelList::active( + &HelperDefaults { + model: Some(selector), + ..session.clone() + }, + settings, + ), + None => HelperModelList::active(session, settings), + } +} + /// What one spawn resolves its helper model and thinking from: the call's own values, the /// parent's model, and the two default layers (`pa_core::session_engine::helper_model`). #[derive(Debug, Clone, Copy)] @@ -148,12 +178,13 @@ pub struct ResolvedHelper { } /// Resolve a child's model and thinking through the helper order (the spawn call, the session -/// override, the settings file, the parent), then enforce the daemon `allowedModels` allowlist -/// on the selector. +/// override, the settings file, the parent) and the helper model list, then enforce the daemon +/// `allowedModels` allowlist on the selector. /// /// # Errors -/// Returns an error when the spawn call's own model or thinking level does not resolve, when no -/// model resolves at all, or when the selector is outside the allowlist. +/// Returns an error when the spawn call's own model or thinking level does not resolve or is off +/// the helper model list, when no model resolves at all, or when the selector is outside the +/// allowlist. pub fn resolve_helper( agent_dir: &Path, request: HelperRequest<'_>, @@ -170,9 +201,14 @@ pub fn resolve_helper( /// warns once on stderr and falls back to the parent's model; a default thinking level, or the /// parent's, clamps to what the resolved model supports. /// +/// With a helper model list ([`HelperModelList`]) set, a spawn call naming a model off the list +/// is refused, and a settings default or the parent's model off the list falls to the list's +/// first entry with a warning once on stderr. The session override is a person's choice: always +/// allowed. +/// /// # Errors -/// Returns an error when the spawn call's own model or thinking level does not resolve, or when -/// no model resolves at all. +/// Returns an error when the spawn call's own model or thinking level does not resolve or is off +/// the helper model list, or when no model resolves at all. pub fn resolve_helper_unchecked( agent_dir: &Path, request: HelperRequest<'_>, @@ -184,17 +220,31 @@ pub fn resolve_helper_unchecked( request.session, request.settings, ); + let list = helper_model_list(agent_dir, request.session, request.settings); let parent = || resolve_child_model_unchecked(agent_dir, None, request.parent_model, target); let (selector, model_source) = match (plan.model.value.as_deref(), plan.model.source) { - (Some(reference), HelperSource::Spawn) => ( - resolve_child_model_unchecked( + (Some(reference), HelperSource::Spawn) => { + let resolved = resolve_child_model_unchecked( agent_dir, Some(reference), request.parent_model, target, - )?, - HelperSource::Spawn, - ), + ); + // Off the list, the refusal names the allowed models so the agent retries with one. + // An unresolved reference gets a list-scoped error too: the catalog's close matches + // would name models off the list. + if let Some(list) = &list { + match &resolved { + Ok(selector) if list.allows(selector) => {} + Err(_) if list.allows(reference) => bail!( + "Requested {target} model \"{reference}\" is unavailable, unauthenticated, or expired; use one of: {} (or omit model= for the default)", + list.entries().join(", ") + ), + Ok(_) | Err(_) => bail!(list.refusal(reference, target)), + } + } + (resolved?, HelperSource::Spawn) + } (Some(reference), source) => { if let Ok(selector) = resolve_child_model_unchecked( agent_dir, @@ -204,14 +254,50 @@ pub fn resolve_helper_unchecked( ) { (selector, source) } else { - if first_unknown_helper_model(reference, source) { - eprintln!("{}", unknown_helper_model_warning(reference, source)); + let warning = unknown_helper_model_warning(reference, source); + if first_helper_notice(&warning) { + eprintln!("{warning}"); } (parent()?, HelperSource::Parent) } } (None, _) => (parent()?, HelperSource::Parent), }; + // The defaults stay on the list too: a settings default or the parent's model off it falls to + // the list's first entry. + let (selector, model_source) = match &list { + Some(list) + if matches!(model_source, HelperSource::Settings | HelperSource::Parent) + && !list.allows(&selector) => + { + let origin = if model_source == HelperSource::Settings { + "subagentDefaultModel" + } else { + "The parent's model" + }; + let warning = format!( + "Warning: {origin} \"{selector}\" is not on the helper model list (subagentModels); spawned agents use \"{}\"", + list.first() + ); + if first_helper_notice(&warning) { + eprintln!("{warning}"); + } + // The first entry must resolve to itself: a short-form or nested-provider match + // would run a route off the list. + let first = list.first(); + let fallback = + resolve_child_model_unchecked(agent_dir, Some(first), request.parent_model, target) + .ok() + .filter(|fallback| list.allows(fallback)) + .ok_or_else(|| { + anyhow!( + "Spawned agents fall back to the helper model list's first entry \"{first}\", which is not in the model catalog; fix subagentModels or name a listed model" + ) + })?; + (fallback, HelperSource::List) + } + _ => (selector, model_source), + }; let thinking = match (plan.thinking.value, plan.thinking.source) { (Some(level), HelperSource::Spawn) => { assert_thinking_supported(agent_dir, Some(&level), &selector)?; @@ -260,9 +346,11 @@ pub fn unknown_helper_model_notice( let settings = HelperDefaults::load_settings(cwd, agent_dir); let plan = plan_helper(None, None, session, &settings); let reference = plan.model.value.as_deref()?; - (!helper_model_known(agent_dir, reference) - && first_unknown_helper_model(reference, plan.model.source)) - .then(|| unknown_helper_model_warning(reference, plan.model.source)) + if helper_model_known(agent_dir, reference) { + return None; + } + let warning = unknown_helper_model_warning(reference, plan.model.source); + first_helper_notice(&warning).then_some(warning) } /// Whether a default helper model reference resolves against the catalog the spawns use @@ -921,6 +1009,160 @@ mod tests { assert!(!helper_model_known(dir.path(), "cpa-r/missing-helper")); } + /// The helper model list: a spawn call naming a model off it is refused with the allowed + /// models named; a settings default or the parent's model off it falls to its first entry; a + /// person's choice (the session override or the session's own list) is allowed. + #[test] + fn the_helper_model_list_refuses_off_list_spawns_and_keeps_defaults_on_it() { + let dir = tempfile::TempDir::new().unwrap(); + write_catalog(dir.path()); + let none = HelperDefaults::default(); + let listed = |model: Option<&str>| { + helper_layer(model, None) + .with_models(Some(vec!["test-provider/glm-5.3-turbo".to_string()])) + }; + let settings = listed(None); + let refusal = "Requested subagent model \"test-provider/glm-5.3\" is not on the helper model list; use one of: test-provider/glm-5.3-turbo (or omit model= for the default)"; + let error = helper( + dir.path(), + (Some("test-provider/glm-5.3"), None), + &none, + &settings, + ) + .unwrap_err(); + assert_eq!(error.to_string(), refusal); + // An unresolved reference gets the same refusal, never catalog matches off the list. + let error = helper(dir.path(), (Some("zzz"), None), &none, &settings).unwrap_err(); + assert!( + error + .to_string() + .contains("use one of: test-provider/glm-5.3-turbo"), + "{error}" + ); + // A listed model, by selector or short form. + let on_list = ResolvedHelper { + selector: "test-provider/glm-5.3-turbo".to_string(), + model_source: HelperSource::Spawn, + thinking: None, + thinking_source: HelperSource::Parent, + }; + assert_eq!( + helper(dir.path(), (Some("glm-5.3-turbo"), None), &none, &settings).unwrap(), + on_list + ); + // The parent's model and a settings default off the list fall to its first entry. + let fallback = ResolvedHelper { + model_source: HelperSource::List, + ..on_list + }; + assert_eq!( + helper(dir.path(), (None, None), &none, &settings).unwrap(), + fallback + ); + assert_eq!( + helper( + dir.path(), + (None, None), + &none, + &listed(Some("test-provider/glm-5.3")) + ) + .unwrap(), + fallback + ); + // A person's choices are allowed: the session override, by default or by name, and the + // session's own list. + let session = helper_layer(Some("test-provider/glm-5.3"), None); + assert_eq!( + helper(dir.path(), (None, None), &session, &settings).unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3".to_string(), + model_source: HelperSource::Session, + thinking: None, + thinking_source: HelperSource::Parent, + } + ); + let widened = none + .clone() + .with_models(Some(vec!["test-provider/glm-5.3".to_string()])); + for session in [&session, &widened] { + assert_eq!( + helper( + dir.path(), + (Some("test-provider/glm-5.3"), None), + session, + &settings + ) + .unwrap() + .selector, + "test-provider/glm-5.3" + ); + } + // No settings list: the session's list limits nothing. + assert_eq!( + helper( + dir.path(), + (Some("test-provider/glm-5.3"), None), + &widened, + &none + ) + .unwrap() + .selector, + "test-provider/glm-5.3" + ); + // The fallback is the first entry itself: one the catalog lacks fails the spawn, and so + // does one that only resolves to another route (a short form here). + let fallback_error = |first: &str| { + let settings = none.clone().with_models(Some(vec![ + first.to_string(), + "cpa-r/other-helper".to_string(), + ])); + helper(dir.path(), (None, None), &none, &settings) + .unwrap_err() + .to_string() + }; + for first in ["cpa-r/missing-helper", "glm-5.3-turbo"] { + assert_eq!( + fallback_error(first), + format!("Spawned agents fall back to the helper model list's first entry \"{first}\", which is not in the model catalog; fix subagentModels or name a listed model") + ); + } + // A listed model the catalog lacks: a list-scoped error, no catalog close matches. + let listed_missing = none.clone().with_models(Some(vec![ + "test-provider/glm-5.3-turbo".to_string(), + "test-provider/glm-5.3-t".to_string(), + ])); + let error = helper( + dir.path(), + (Some("test-provider/glm-5.3-t"), None), + &none, + &listed_missing, + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "Requested subagent model \"test-provider/glm-5.3-t\" is unavailable, unauthenticated, or expired; use one of: test-provider/glm-5.3-turbo, test-provider/glm-5.3-t (or omit model= for the default)" + ); + // A person's short form joins the list as its catalog selector. + let short = helper_layer(Some("glm-5.3"), None); + assert_eq!( + helper_model_list(dir.path(), &short, &settings) + .unwrap() + .entries(), + ["test-provider/glm-5.3-turbo", "test-provider/glm-5.3"] + ); + assert_eq!( + helper( + dir.path(), + (Some("test-provider/glm-5.3"), None), + &short, + &settings + ) + .unwrap() + .selector, + "test-provider/glm-5.3" + ); + } + /// The daemon allowlist gates the helper model like any resolved model. #[test] fn the_allowlist_refuses_a_helper_model_outside_it() { diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rs index 82339942ccf..57aabc07602 100644 --- a/crates/pa-daemon/src/rlm_children.rs +++ b/crates/pa-daemon/src/rlm_children.rs @@ -637,8 +637,11 @@ impl SupervisorChildSessions { .rlm_max_depth } - /// Test-only read of the identity's model selector (for the regression test). - #[cfg(test)] + /// The identity's model selector: the parent's model a spawn inherits. + /// + /// # Panics + /// + /// Panics when the identity mutex is poisoned. pub(crate) fn parent_model(&self) -> Option { self.inner .identity diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs index 337ec60d9bd..4b98ded56db 100644 --- a/crates/pa-daemon/src/rlm_children/host.rs +++ b/crates/pa-daemon/src/rlm_children/host.rs @@ -2,7 +2,9 @@ //! (`spawn`, `create_session`, `list_subagents`, `delete_subagent`, //! `collect`, `rename`) over the supervisor's child-sessions registry, //! with the spawn-admission helpers only this surface uses. -use pa_core::session_engine::helper_model::HelperDefaults; +use pa_core::session_engine::helper_model::{HelperDefaults, HelperModelList}; + +use super::ParentIdentity; use crate::rlm_child_model::{resolve_helper, HelperRequest, ResolvedHelper}; @@ -19,15 +21,16 @@ use super::{ /// Resolve the child's model and thinking through the helper order (the call, the session /// override, the settings file, the parent) with the daemon `allowedModels` allowlist enforced, /// refusing loudly with the typed error and the `model refused` event; the settings reads run on -/// the blocking pool. +/// the blocking pool. `identity` is the admission's one snapshot: the child inherits the same +/// override its model resolved under. async fn resolve_child_helper( this: &SupervisorChildSessionsInner, + identity: &ParentIdentity, model: Option<&str>, thinking: Option<&str>, surface: &'static str, target: &str, ) -> Result { - let identity = this.identity.lock().expect("identity lock").clone(); let cwd = identity.cwd.clone().unwrap_or_else(|| "/".to_string()); let load_cwd = cwd.clone(); let agent_dir = this.agent_dir.clone(); @@ -124,6 +127,7 @@ impl RlmSubagentHost for SupervisorChildSessions { .await?; let helper = resolve_child_helper( &this, + &identity, request.model.as_deref(), request.thinking.as_deref(), "spawn", @@ -330,6 +334,7 @@ impl RlmSubagentHost for SupervisorChildSessions { } let helper = resolve_child_helper( &this, + &identity, request.model.as_deref(), request.thinking.as_deref(), "create_session", @@ -756,6 +761,25 @@ impl RlmSubagentHost for SupervisorChildSessions { Ok(name) }) } + + fn helper_model_list(&self) -> RlmHostFuture> { + let this = Arc::clone(&self.inner); + Box::pin(async move { + let identity = this.identity.lock().expect("identity lock").clone(); + let cwd = identity.cwd.unwrap_or_else(|| "/".to_string()); + let agent_dir = this.agent_dir.clone(); + // The list the spawn checks; the settings file and the catalog on the blocking pool. + tokio::task::spawn_blocking(move || { + crate::rlm_child_model::helper_model_list( + &agent_dir, + &identity.subagent_override, + &HelperDefaults::load_settings(Path::new(&cwd), &agent_dir), + ) + }) + .await + .context("the settings load task join failed") + }) + } } /// Whether the child's durable session file already carries the spawn diff --git a/crates/pa-daemon/src/rlm_surface.rs b/crates/pa-daemon/src/rlm_surface.rs index d6aa6525a3c..130c4182487 100644 --- a/crates/pa-daemon/src/rlm_surface.rs +++ b/crates/pa-daemon/src/rlm_surface.rs @@ -1,6 +1,6 @@ //! The RLM child-management surface: the worker arms for //! `cancel_rlm_child`, `delete_rlm_subagent`, and `set_rlm_max_depth`, -//! plus the fork's `get_subagent_model_status`/`set_subagent_model`. +//! plus the fork's `get_subagent_model_status`/`set_subagent_model`/`set_subagent_models`. //! Each handler answers the exact TS wire shape; the behavior lives in //! the engine seams and the supervisor-backed children registry. @@ -116,9 +116,10 @@ impl Worker { } } - /// `set_subagent_model` (fork-only): replace this session's helper-model override with - /// `{ model, thinking }` (an absent or null field leaves it to the settings file; `parent` - /// keeps the parent's value) and answer the resulting status. The override persists as a + /// `set_subagent_model` (fork-only): replace the model and thinking level of this session's + /// helper-model override with `{ model, thinking }` (an absent or null field leaves it to the + /// settings file; `parent` keeps the parent's value) and answer the resulting status; the + /// session's helper model list additions stay. The override persists as a /// `subagent_model_state` row in the session file; an unknown model is kept and reported as /// `modelKnown: false`. pub(crate) async fn handle_set_subagent_model(&self, payload: &Value) -> DaemonResponse { @@ -133,6 +134,51 @@ impl Worker { Ok(layer) => layer, Err(error) => return response_failure(None, "set_subagent_model", &error, None), }; + self.apply_subagent_override("set_subagent_model", |current| { + layer.with_models(current.models) + }) + .await + } + + /// `set_subagent_models` (fork-only): replace this session's additions to the helper model + /// list with `{ models }` (an empty or absent list clears them) and answer the resulting + /// status; the override's model and thinking level stay. Persisted like + /// `set_subagent_model`. + pub(crate) async fn handle_set_subagent_models(&self, payload: &Value) -> DaemonResponse { + if let Err(response) = self.require_created("set_subagent_models") { + return response; + } + let models: Vec = match payload.get("models") { + None | Some(Value::Null) => Vec::new(), + Some(Value::Array(entries)) if entries.iter().all(Value::is_string) => entries + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + Some(_) => { + return response_failure( + None, + "set_subagent_models", + "set_subagent_models models must be an array of strings", + None, + ) + } + }; + self.apply_subagent_override("set_subagent_models", |current| { + current.with_models(Some(models)) + }) + .await + } + + /// Replace this session's helper-model override with `compose(current)` and answer the + /// resulting status. + async fn apply_subagent_override( + &self, + command: &'static str, + compose: impl FnOnce( + pa_core::session_engine::helper_model::HelperDefaults, + ) -> pa_core::session_engine::helper_model::HelperDefaults, + ) -> DaemonResponse { // The live override and its durable row change together under the core lock, so // concurrent setters (and a session replacement's store swap) leave the latest row equal // to the live value. The row goes to the worker-owned session file (a cleared override is @@ -140,15 +186,16 @@ impl Worker { // file keeps the override for this worker only. { let mut core = self.core.lock().unwrap(); + let layer = compose(self.engine.subagent_override()); let row = pa_core::session_engine::helper_model::session_override_row(&layer); if let Err(error) = self.engine.set_subagent_model(layer) { - return response_failure(None, "set_subagent_model", &error.to_string(), None); + return response_failure(None, command, &error.to_string(), None); } if let Some(store) = core.store.as_mut() { if let Err(error) = store.persist_entry("custom", row) { return response_failure( None, - "set_subagent_model", + command, &format!( "the helper model applies to this worker but was not saved: {error}" ), @@ -165,13 +212,13 @@ impl Worker { Err(error) => { return response_failure( None, - "set_subagent_model", + command, &format!("helper model status task failed: {error}"), None, ) } }; - response_success(None, "set_subagent_model", Some(status)) + response_success(None, command, Some(status)) } } @@ -331,10 +378,86 @@ mod tests { entry["data"]["thinking"].as_str(), ) .unwrap() + .with_models(serde_json::from_value(entry["data"]["models"].clone()).ok()) }) .collect() } + /// `set_subagent_models` replaces only the session's additions to the helper model list and + /// `set_subagent_model` only the model and thinking level; each row carries the whole + /// override, and the status names the active list and where it came from. + #[tokio::test] + async fn the_list_and_the_model_override_replace_only_their_own_fields() { + use pa_core::session_engine::helper_model::HelperDefaults; + let root = std::env::temp_dir().join(format!("pa-worker-list-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(root.join("agent")).unwrap(); + std::fs::write( + root.join("agent").join("settings.json"), + json!({ "subagentModels": ["cpa-r/deepseek-flash-1017"] }).to_string(), + ) + .unwrap(); + let worker = agent_worker_at(&root, &json!({})).await; + let set_models = |models: Value| { + let worker = Arc::clone(&worker); + async move { + let mut payload = json!({ "activeSessionId": "helper-session" }); + payload["models"] = models; + worker.dispatch("set_subagent_models", &payload).await + } + }; + let widened = set_models(json!(["cpa-a/gpt-6", " cpa-a/gpt-6 "])).await; + assert!(widened.success, "{widened:?}"); + let status = widened.data.unwrap(); + assert_eq!( + [ + &status["models"], + &status["modelsSource"], + &status["session"] + ], + [ + &json!(["cpa-r/deepseek-flash-1017", "cpa-a/gpt-6"]), + &json!("settings+session"), + &json!({ "models": ["cpa-a/gpt-6"] }) + ] + ); + let set = worker + .dispatch( + "set_subagent_model", + &json!({ "activeSessionId": "helper-session", "model": "parent", "thinking": "max" }), + ) + .await; + assert_eq!( + set.data.map(|status| status["session"].clone()), + Some(json!({ "model": "parent", "thinking": "max", "models": ["cpa-a/gpt-6"] })) + ); + let cleared = set_models(Value::Null).await; + let status = cleared.data.unwrap(); + assert_eq!( + [ + &status["models"], + &status["modelsSource"], + &status["session"] + ], + [ + &json!(["cpa-r/deepseek-flash-1017"]), + &json!("settings"), + &json!({ "model": "parent", "thinking": "max" }) + ] + ); + let invalid = set_models(json!("cpa-a/gpt-6")).await; + assert!(!invalid.success); + let pinned = HelperDefaults::new(Some("parent"), Some("max")).unwrap(); + let gpt = Some(vec!["cpa-a/gpt-6".to_string()]); + assert_eq!( + override_rows(&root), + vec![ + HelperDefaults::default().with_models(gpt.clone()), + pinned.clone().with_models(gpt), + pinned, + ] + ); + } + /// `set_subagent_model` writes its row to the worker-owned session file (the row a resume, /// respawn or wake re-seeds from); a clear is a row too. The scripted harness engine refuses /// and writes nothing. diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs index 06a4938b3c1..4aaadb3fd0b 100644 --- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs +++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs @@ -323,6 +323,7 @@ impl Supervisor { // The helper-model override an RLM parent passes down. pa_core::session_engine::helper_model::SUBAGENT_MODEL_CONFIG_KEY, pa_core::session_engine::helper_model::SUBAGENT_THINKING_CONFIG_KEY, + pa_core::session_engine::helper_model::SUBAGENT_MODELS_CONFIG_KEY, ] { if let Some(value) = config_object.and_then(|config| config.get(key)) { durable_rest.insert(key.to_string(), value.clone()); diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs index 49f2b277f70..db90c205ab0 100644 --- a/crates/pa-daemon/src/worker/commands.rs +++ b/crates/pa-daemon/src/worker/commands.rs @@ -173,6 +173,7 @@ impl Worker { "set_rlm_max_depth" => self.handle_set_rlm_max_depth(payload).await, "get_subagent_model_status" => self.handle_get_subagent_model_status().await, "set_subagent_model" => self.handle_set_subagent_model(payload).await, + "set_subagent_models" => self.handle_set_subagent_models(payload).await, "acquire_session_input_pause" => self.handle_acquire_session_input_pause(payload), "release_session_input_pause" => self.handle_release_session_input_pause(payload), "cancel_prompt_admission" => self.handle_cancel_prompt_admission(payload), diff --git a/crates/pa-daemon/tests/command_breadth.rs b/crates/pa-daemon/tests/command_breadth.rs index 079b1a58603..39ae71149e0 100644 --- a/crates/pa-daemon/tests/command_breadth.rs +++ b/crates/pa-daemon/tests/command_breadth.rs @@ -454,6 +454,10 @@ const WIRE_FIXTURES: &[(&str, &str)] = &[ "set_subagent_model", r#"{"type": "set_subagent_model", "activeSessionId": "sess", "model": "cpa-r/deepseek-flash-1017", "thinking": "max"}"#, ), + ( + "set_subagent_models", + r#"{"type": "set_subagent_models", "activeSessionId": "sess", "models": ["cpa-a/claude-opus-5"]}"#, + ), ( "rename_saved_session", r#"{"type": "rename_saved_session", "sessionPath": "/tmp/x.jsonl", "name": "x"}"#, @@ -574,6 +578,7 @@ fn known_command_types_match_the_ts_list() { // Oneiron fork: the helper-model override. | "get_subagent_model_status" | "set_subagent_model" + | "set_subagent_models" ), "unexpected non-TS command type: {extra}" ); diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rs index e99ffecd81b..822acf01012 100644 --- a/crates/pa-daemon/tests/rlm_children_e2e.rs +++ b/crates/pa-daemon/tests/rlm_children_e2e.rs @@ -686,6 +686,122 @@ async fn an_unpinned_spawn_runs_on_the_helper_model() { children.notify_turn_done(); } +/// The helper model list (settings `subagentModels`): a spawn naming a model off the list is +/// refused with the allowed models named and starts no child; a listed model starts; an unpinned +/// spawn whose parent model is off the list runs on the list's first entry; a person's session +/// additions widen the list. `rlm.create_session` checks the same list. +#[tokio::test] +async fn a_spawn_off_the_helper_model_list_is_refused() { + let dir = tempfile::TempDir::new().expect("temp dir"); + let socket = dir.path().join("daemon.sock"); + let agent_dir = dir.path().join("agent"); + std::fs::create_dir_all(&agent_dir).expect("agent dir"); + std::fs::write( + agent_dir.join("models.json"), + json!({ + "providers": { + "test-provider": { + "baseUrl": "http://localhost:9", + "apiKey": "test-key", + "api": "openai-completions", + "models": [ + { "id": "helper-flash", "name": "Helper", "contextWindow": 1000, "maxTokens": 100 }, + { "id": "helper-pro", "name": "Helper Pro", "contextWindow": 1000, "maxTokens": 100 }, + { "id": "paid-route", "name": "Paid", "contextWindow": 1000, "maxTokens": 100 } + ] + } + } + }) + .to_string(), + ) + .expect("models.json"); + std::fs::write( + agent_dir.join("settings.json"), + json!({ "subagentModels": ["test-provider/helper-flash", "test-provider/helper-pro"] }) + .to_string(), + ) + .expect("settings.json"); + let _daemon = spawn_daemon(&socket, &agent_dir); + let script = write_script(dir.path(), "helper answer"); + let children = children(&socket, &agent_dir, &script, 0); + + let error = children + .spawn(RlmSpawnRequest { + model: Some("test-provider/paid-route".to_string()), + ..spawn_request("paid", "use the paid route") + }) + .await + .expect_err("a model off the list is refused"); + assert_eq!( + error.to_string(), + "Requested subagent model \"test-provider/paid-route\" is not on the helper model list; use one of: test-provider/helper-flash, test-provider/helper-pro (or omit model= for the default)" + ); + assert!( + children.list_subagents().await.expect("roster").is_empty(), + "a refused spawn starts no child" + ); + + let handle = children + .spawn(RlmSpawnRequest { + model: Some("test-provider/helper-pro".to_string()), + ..spawn_request("listed", "use a listed model") + }) + .await + .expect("a listed model starts"); + assert_eq!(handle.model, "test-provider/helper-pro"); + // The parent's model (`scripted/faux-1`) is off the list: the list's first entry. + let handle = children + .spawn(spawn_request("unpinned", "use the default")) + .await + .expect("an unpinned spawn starts"); + assert_eq!(handle.model, "test-provider/helper-flash"); + + let error = children + .create_session(RlmCreateSessionRequest { + prompt: "use the paid route".to_string(), + name: None, + model: Some("test-provider/paid-route".to_string()), + thinking: None, + cwd: None, + }) + .await + .expect_err("create_session checks the list too"); + assert!( + error + .to_string() + .starts_with("Requested top-level session model \"test-provider/paid-route\" is not on the helper model list"), + "{error}" + ); + + // A person's addition widens the list for this session: the roster and the spawn agree. + children.set_subagent_override( + pa_core::session_engine::helper_model::HelperDefaults::default() + .with_models(Some(vec!["test-provider/paid-route".to_string()])), + ); + let list = children + .helper_model_list() + .await + .expect("list") + .expect("a list is set"); + assert_eq!( + list.entries(), + [ + "test-provider/helper-flash", + "test-provider/helper-pro", + "test-provider/paid-route" + ] + ); + let handle = children + .spawn(RlmSpawnRequest { + model: Some("test-provider/paid-route".to_string()), + ..spawn_request("widened", "use the person's addition") + }) + .await + .expect("a person's addition starts"); + assert_eq!(handle.model, "test-provider/paid-route"); + children.notify_turn_done(); +} + /// TS #2396's daemon-wide half: the supervisor holds a subagent spawn's name under a /// reservation for the whole fresh-launch admission; once the winner is gone, the name /// admits again. diff --git a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs index 02c3ae25fa3..947fa6453ea 100644 --- a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs +++ b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs @@ -73,6 +73,7 @@ fn supervisor_end_to_end_scripted_session_lifecycle() { "session_tool_selection", "session_policy", "subagent_model", + "subagent_models", ]) ); diff --git a/crates/pa-tui/src/client_settings.rs b/crates/pa-tui/src/client_settings.rs index 541b4826396..bb8348cbe2a 100644 --- a/crates/pa-tui/src/client_settings.rs +++ b/crates/pa-tui/src/client_settings.rs @@ -35,6 +35,10 @@ pub trait ClientSettings: Send + Sync { fn subagent_default_thinking(&self) -> Option { None } + /// `subagentModels`: the helper model list spawned agents may run on; `None` is no limit. + fn subagent_models(&self) -> Option> { + None + } /// Persist (or, with `None`, remove) `subagentDefaultThinking` globally. /// /// # Errors diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs index bd2c5bde345..537ae2d570a 100644 --- a/crates/pa-tui/src/interactive.rs +++ b/crates/pa-tui/src/interactive.rs @@ -115,6 +115,9 @@ pub struct ModelSelection { pub subagent_model: Option, /// The launch helper thinking level (`--subagent-thinking`, `PRIME_SUBAGENT_THINKING`). pub subagent_thinking: Option, + /// The launch additions to the helper model list (`--subagent-models`, + /// `PRIME_SUBAGENT_MODELS`): set on the opened session like `/subagent-models`. + pub subagent_models: Option>, } /// Adoption telemetry for interactive-view interactions: the composition diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rs index f00e375f6b1..1a53c382c69 100644 --- a/crates/pa-tui/src/session_ui/commands.rs +++ b/crates/pa-tui/src/session_ui/commands.rs @@ -788,6 +788,10 @@ impl SessionUi { self.handle_subagent_model_command(view, &resolved.args) .await; } + "subagent-models" => { + self.handle_subagent_models_command(view, &resolved.args) + .await; + } "speed" => { let arg = resolved.args.trim().to_lowercase(); if !arg.is_empty() && arg != "on" && arg != "off" { diff --git a/crates/pa-tui/src/session_ui/settings.rs b/crates/pa-tui/src/session_ui/settings.rs index 2a7ae694614..efc3ceca25f 100644 --- a/crates/pa-tui/src/session_ui/settings.rs +++ b/crates/pa-tui/src/session_ui/settings.rs @@ -1,5 +1,5 @@ //! The `/settings` menu and its row-apply/persist switches, the `/import` -//! confirm flow, and the fast/rlm-max-depth/subagent-model/reload command surface. The +//! confirm flow, and the fast/rlm-max-depth/subagent-model(s)/reload command surface. The //! fullscreen toggle is retired (the operator's 2026-09-28 ruling removed //! the setting and the command). use super::{ @@ -803,7 +803,7 @@ impl SessionUi { } } - // Helper model (/subagent-model) + // Helper model (/subagent-model, /subagent-models) /// No argument reports the helper model and thinking level this session's spawns resolve to /// when the call names none, with the layer each comes from; ` []` replaces @@ -846,66 +846,149 @@ impl SessionUi { return; } }; - self.subagent_model_request(command, view).await; + if let Some(status) = self.subagent_model_request(command, view).await { + self.report_subagent_model_status(&status, view); + } } - /// The launch override (`--subagent-model`/`--subagent-thinking` or their env vars) lands on - /// the opened session before the first prompt; a session whose settings name a helper model - /// checks it, so an unknown default warns at open. Sessions without either skip the round - /// trip. + /// No argument reports the helper model list this session's spawns may run on (settings + /// `subagentModels`); `,...` replaces the session's additions to it + /// immediately, and `default` clears them, leaving the settings file's list. + pub(super) async fn handle_subagent_models_command( + &mut self, + view: &mut AgentView, + args: &str, + ) { + let command = match args.trim() { + "" => DaemonCommand::GetSubagentModelStatus { + id: None, + active_session_id: self.active_session_id.clone(), + rest: Map::default(), + }, + list => DaemonCommand::SetSubagentModels { + id: None, + active_session_id: self.active_session_id.clone(), + // Entries split on commas or whitespace; the daemon trims and drops repeats. + models: if list == "default" { + Vec::new() + } else { + list.split(|c: char| c == ',' || c.is_whitespace()) + .filter(|entry| !entry.is_empty()) + .map(str::to_string) + .collect() + }, + rest: Map::default(), + }, + }; + if let Some(status) = self.subagent_model_request(command, view).await { + self.report_subagent_model_status(&status, view); + } + } + + /// The launch override (`--subagent-model`/`--subagent-thinking`/`--subagent-models` or their + /// env vars) lands on the opened session before the first prompt; a session whose settings + /// name a helper model or a helper model list checks them, so an unknown default or one off + /// the list warns at open. Sessions without either skip the round trip. pub(crate) async fn apply_launch_subagent_model(&mut self, view: &mut AgentView) { - let model = self.model_selection.subagent_model.clone(); - let thinking = self.model_selection.subagent_thinking.clone(); - let launch = model.is_some() || thinking.is_some(); - let configured = self + // A daemon without `subagent_models` ignores the settings list: say so before anything. + let list_configured = self .client_settings .as_ref() - .is_some_and(|settings| settings.subagent_default_model().is_some()); - if !launch && !configured { - return; + .is_some_and(|settings| settings.subagent_models().is_some()); + if list_configured + && !self + .client + .supports_server_capability(pa_types::daemon::SUBAGENT_MODELS_CAPABILITY) + { + self.note_as( + "The running daemon does not enforce subagentModels (no subagent_models capability): spawned agents may run on any model; stop it so a current one starts", + StatusKind::Warning, + view, + ); } - let command = if launch { - DaemonCommand::SetSubagentModel { + let model = self.model_selection.subagent_model.clone(); + let thinking = self.model_selection.subagent_thinking.clone(); + let mut commands = Vec::new(); + if model.is_some() || thinking.is_some() { + commands.push(DaemonCommand::SetSubagentModel { id: None, active_session_id: self.active_session_id.clone(), model, thinking, rest: Map::default(), - } - } else { - DaemonCommand::GetSubagentModelStatus { + }); + } + if let Some(models) = self.model_selection.subagent_models.clone() { + commands.push(DaemonCommand::SetSubagentModels { + id: None, + active_session_id: self.active_session_id.clone(), + models, + rest: Map::default(), + }); + } + let configured = list_configured + || self + .client_settings + .as_ref() + .is_some_and(|settings| settings.subagent_default_model().is_some()); + if commands.is_empty() && configured { + commands.push(DaemonCommand::GetSubagentModelStatus { id: None, active_session_id: self.active_session_id.clone(), rest: Map::default(), + }); + } + // Each command answers the whole status: report the last one. + let mut status = None; + for command in commands { + match self.subagent_model_request(command, view).await { + Some(answer) => status = Some(answer), + None => return, } - }; - self.subagent_model_request(command, view).await; + } + if let Some(status) = status { + self.report_subagent_model_status(&status, view); + } } - /// Send one helper-model command and report the resulting status: the status row, plus a - /// warning when the model the spawns default to is not in the catalog (they use the parent's). - async fn subagent_model_request(&mut self, command: DaemonCommand, view: &mut AgentView) { - if !self - .client - .supports_server_capability(pa_types::daemon::SUBAGENT_MODEL_CAPABILITY) - { + /// Send one helper-model command and answer the resulting status; a daemon without the + /// command's capability, or a failed request, reports a row and answers `None`. + async fn subagent_model_request( + &mut self, + command: DaemonCommand, + view: &mut AgentView, + ) -> Option { + let capability = if matches!(command, DaemonCommand::SetSubagentModels { .. }) { + pa_types::daemon::SUBAGENT_MODELS_CAPABILITY + } else { + pa_types::daemon::SUBAGENT_MODEL_CAPABILITY + }; + if !self.client.supports_server_capability(capability) { self.note_as( - "The running daemon does not support helper-model overrides (no subagent_model capability); stop it so a current one starts", + &format!( + "The running daemon does not support this helper-model setting (no {capability} capability); stop it so a current one starts" + ), StatusKind::Warning, view, ); - return; + return None; } - let status = match self + match self .bounded_request(Duration::from_millis(UI_REQUEST_TIMEOUT_MS), command) .await { - Ok(status) => status, + Ok(status) => Some(status), Err(error) => { self.error_row(&format!("{error:#}"), view); - return; + None } - }; + } + } + + /// Report one helper-model status: the helper model row, the helper model list row when a + /// list is set, and a warning when the model the spawns default to is not in the catalog + /// (they use the parent's) or not on the list (they use its first entry). + fn report_subagent_model_status(&mut self, status: &Value, view: &mut AgentView) { let described = |value: &str, source: &str, fallback: &str| match status .get(value) .and_then(Value::as_str) @@ -922,10 +1005,34 @@ impl SessionUi { let model = described("model", "modelSource", "the parent's model"); let thinking = described("thinking", "thinkingSource", "the parent's level"); self.plain_row(&format!("Helper model: {model}, thinking {thinking}"), view); + let models: Vec<&str> = status + .get("models") + .and_then(Value::as_array) + .map(|models| models.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + if let Some(first) = models.first() { + let source = status + .get("modelsSource") + .and_then(Value::as_str) + .unwrap_or_default(); + self.plain_row( + &format!("Helper model list: {} ({source})", models.join(", ")), + view, + ); + if status.get("modelAllowed").and_then(Value::as_bool) == Some(false) { + self.note_as( + &format!( + "The resolved default helper model is not on the helper model list; spawned agents use {first}" + ), + StatusKind::Warning, + view, + ); + } + } if status.get("modelKnown").and_then(Value::as_bool) == Some(false) { self.note_as( &format!( - "Helper model {model} is not in the model catalog; spawned agents use the parent's model" + "Helper model {model} is not in the model catalog; spawned agents fall back to the parent's model, subject to the helper model list" ), StatusKind::Warning, view, diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs index 670a29adc8f..40310deb3e3 100644 --- a/crates/pa-types/src/daemon/command.rs +++ b/crates/pa-types/src/daemon/command.rs @@ -1145,6 +1145,18 @@ pub enum DaemonCommand { #[serde(flatten)] rest: JsonMap, }, + /// Fork-only (capability `subagent_models`): replace the session's additions to the helper + /// model list (settings `subagentModels`). An empty list clears them; the override's model + /// and thinking level stay. + SetSubagentModels { + #[serde(default, skip_serializing_if = "Option::is_none")] + id: Option, + active_session_id: String, + #[serde(default)] + models: Vec, + #[serde(flatten)] + rest: JsonMap, + }, RenameSavedSession { #[serde(default, skip_serializing_if = "Option::is_none")] id: Option, diff --git a/crates/pa-types/src/daemon/mod.rs b/crates/pa-types/src/daemon/mod.rs index a71c33d5328..3cf5a170999 100644 --- a/crates/pa-types/src/daemon/mod.rs +++ b/crates/pa-types/src/daemon/mod.rs @@ -47,6 +47,11 @@ pub const DAEMON_SCHEMA_ID: &str = "protocol-7-schema-33-20261024a1f7"; /// session's helper-model override, and its RLM creates carry `subagentModel`/`subagentThinking`. pub const SUBAGENT_MODEL_CAPABILITY: &str = "subagent_model"; +/// Fork-only server capability (no schema bump): the daemon enforces the helper model list +/// (settings `subagentModels`) on spawns, answers `set_subagent_models`, reports the list in +/// `get_subagent_model_status`, and its RLM creates carry `subagentModels`. +pub const SUBAGENT_MODELS_CAPABILITY: &str = "subagent_models"; + pub type DaemonClientId = String; pub type DaemonCommandId = String; pub type DaemonEventId = String; diff --git a/crates/pa-types/src/daemon/plane.rs b/crates/pa-types/src/daemon/plane.rs index 85d56e8862d..a5bd06a727c 100644 --- a/crates/pa-types/src/daemon/plane.rs +++ b/crates/pa-types/src/daemon/plane.rs @@ -91,6 +91,7 @@ pub fn command_plane(command_type: &str) -> DaemonCommandPlane { // Oneiron fork: the helper-model override serves one session. | "get_subagent_model_status" | "set_subagent_model" + | "set_subagent_models" | "get_session_context" | "get_session_tree" | "get_user_messages_for_forking" diff --git a/crates/pa-types/src/slash_commands.rs b/crates/pa-types/src/slash_commands.rs index 099387f6062..7c2f73e75cd 100644 --- a/crates/pa-types/src/slash_commands.rs +++ b/crates/pa-types/src/slash_commands.rs @@ -74,6 +74,7 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: &[BuiltinSlashCommand] = &[ BuiltinSlashCommand { name: "autonomous", description: "Set or view autonomous mode with an optional budget", execution: SlashCommandExecution::Session, argument_hint: Some("[status|off|on [--max-continuations ] [--max-turns ] [--max-tokens ] [--timeout-ms ] [--gate ]]"), aliases: &[], takes_argument: true }, BuiltinSlashCommand { name: "rlm-max-depth", description: "Set/view the per-chat persistent RLM max depth immediately; never interrupts or queues the running turn", execution: SlashCommandExecution::Client, argument_hint: Some("[ [--global]]"), aliases: &[], takes_argument: true }, BuiltinSlashCommand { name: "subagent-model", description: "Set/view this session's model and thinking level for spawned agents; the settings file and the parent are the fallbacks", execution: SlashCommandExecution::Client, argument_hint: Some("[|parent|default] [|parent]"), aliases: &[], takes_argument: true }, + BuiltinSlashCommand { name: "subagent-models", description: "Set/view this session's additions to the helper model list, the models spawned agents may run on (settings subagentModels)", execution: SlashCommandExecution::Client, argument_hint: Some("[,...|default]"), aliases: &[], takes_argument: true }, BuiltinSlashCommand { name: "heartbeat", description: "Set or view a persistent heartbeat; delivery defaults to steer, use --follow-up to queue; supports pause, resume, stop, and clear", execution: SlashCommandExecution::Client, argument_hint: Some("[status|pause|resume|stop|[every ] [--steer|--follow-up] ]"), aliases: &[], takes_argument: true }, BuiltinSlashCommand { name: "heartbeats", description: "View and manage all user and agent heartbeats", execution: SlashCommandExecution::Client, argument_hint: None, aliases: &[], takes_argument: false }, BuiltinSlashCommand { name: "factory", description: "Show or set the agent factory opt-in gate (off by default)", execution: SlashCommandExecution::Client, argument_hint: Some("[on|off|status]"), aliases: &[], takes_argument: true }, diff --git a/docs/oneiron/HELPER-MODEL.md b/docs/oneiron/HELPER-MODEL.md index 450af4e71fd..41874536495 100644 --- a/docs/oneiron/HELPER-MODEL.md +++ b/docs/oneiron/HELPER-MODEL.md @@ -2,7 +2,8 @@ An agent can start helper agents with `rlm.spawn` or `rlm.create_session`. When the call names no model, upstream runs the helper on the parent's model. The fork adds a helper model: a -setting, a per-session override, and a GUI to change both. +setting, a per-session override, and a GUI to change both. It also adds a helper model list: +the models spawned agents may run on, kept apart from the full model catalog. ## Resolution order @@ -21,6 +22,7 @@ The value `parent` at layer 2 or 3 stops the walk and keeps the parent's value. - A default model (layer 2 or 3) that the model catalog does not know never fails a spawn. The process warns once and the helper runs on the parent's model. - A default thinking level, and the parent's own, is clamped to what the helper's model supports. +- The helper model list (below) then applies to the model. - The daemon's `allowedModels` allowlist applies to the helper model like any model. The same order applies on every path that starts a child agent: the daemon's `rlm.spawn` and @@ -28,6 +30,40 @@ The same order applies on every path that starts a child agent: the daemon's `rl host's `rlm.spawn` (`crates/pa-cli/src/print_rlm.rs`; it has no `rlm.create_session`). Factory states and goal runs spawn through these hosts. +## Helper model list + +`subagentModels` is an ordered list of `provider/model-id` references. When it is set, spawned +agents may run only on these models. Every model stays in the catalog, so a person can still +pick any of them with `--model` or `/model`. Absent or empty: no limit (upstream behavior). + +- A spawn call that names a model off the list is refused. The error names the allowed models, + so the agent retries with one: + `Requested subagent model "cpa-a/claude-opus-5" is not on the helper model list; use one of: + cpa-r/deepseek-flash-1017, cpa-r/kimi-k3.1 (or omit model= for the default)`. +- A settings default (`subagentDefaultModel`) or a parent model off the list falls to the + list's first entry. The process warns once on stderr; the status reports it. +- A person's choice is always allowed: the session override (`--subagent-model`, + `PRIME_SUBAGENT_MODEL`, `/subagent-model`) may name a model off the list, and an agent may + then name that model too. A short form the person typed joins the list as its catalog + selector. +- A person can widen the list for one session: `--subagent-models a,b`, the env var + `PRIME_SUBAGENT_MODELS=a,b`, or `/subagent-models a,b` in the TUI. The session's entries + follow the settings file's, so the first entry stays the settings file's first. With no + settings list there is no limit to widen. +- `rlm.find_models` lists only the models on the list. A listed model the catalog does not + have fails with the allowed models named, never catalog close matches. +- Entries match the resolved selector exactly (case-insensitive). Write the full + `provider/model-id`: a short form is not an entry. +- `subagentModels` is read from the global settings file only, like `allowedModels`. A project + file, which an agent can write, cannot widen it. +- The list's first entry must be in the catalog under that exact selector: a fallback to an + unknown first entry fails the spawn instead of running another route. +- A daemon that predates the list ignores it. `--daemon-hosted` refuses such a daemon when a + list is set, and the TUI warns when the session opens; stop the daemon so a current one starts. + +The list covers the whole agent tree: an RLM child carries its parent's session additions +(create key `subagentModels`), and the daemon persists them in the `subagent_model_state` row. + ## Settings file `~/.prime/agent/settings.json` (the Rust side-by-side install reads `~/.prime/agent-rs/`): @@ -36,13 +72,22 @@ states and goal runs spawn through these hosts. |---|---|---|---| | `subagentDefaultModel` | string | unset | `provider/model-id` for a spawn that names no model; unset or `parent` keeps the parent's model | | `subagentDefaultThinking` | `off` ... `max`, or `parent` | unset | thinking level for a spawn that names none; unset or `parent` keeps the parent's level (a project file's `parent` overrides a global level) | +| `subagentModels` | array of strings | unset | the helper model list: the models spawned agents may run on, first entry the fallback; global file only; unset or empty is no limit (one comma-separated string also works) | + +Example: -Example: `{"subagentDefaultModel": "cpa-r/deepseek-flash-1017", "subagentDefaultThinking": "max"}`. +```json +{ + "subagentDefaultModel": "cpa-r/deepseek-flash-1017", + "subagentDefaultThinking": "max", + "subagentModels": ["cpa-r/deepseek-flash-1017", "cpa-r/kimi-k3.1"] +} +``` A spawn reads the file when it runs, so a change applies to the next spawn of every session. At startup the CLI checks the model against the catalog (models.json plus the built-in models) and prints a warning when the catalog does not know it; the TUI shows the same warning as a -row when the session opens. +row when the session opens, and a warning when the default is off the helper model list. ## Session override @@ -51,29 +96,36 @@ Headless runs (`-p`, `--mode json`, `--autonomous`, `--daemon-hosted`): ``` prime-agent -p --subagent-model cpa-r/deepseek-flash-1017 --subagent-thinking max "..." PRIME_SUBAGENT_MODEL=cpa-r/deepseek-flash-1017 PRIME_SUBAGENT_THINKING=max prime-agent -p "..." +prime-agent -p --subagent-models cpa-a/claude-opus-5 "..." +PRIME_SUBAGENT_MODELS=cpa-a/claude-opus-5 prime-agent -p "..." ``` Each flag beats its env var. An invalid `PRIME_SUBAGENT_THINKING` warns and is ignored. In interactive mode the flags and env vars apply to the session the launch opens. The override covers the whole agent tree: an RLM child carries its parent's override (create -keys `subagentModel`/`subagentThinking`), so grandchildren resolve the same way. The daemon -worker persists the override as a `subagent_model_state` row in the session file it owns (every -`set_subagent_model`, a clear included, and an RLM child's inherited override once, at birth), -so a resume, a respawn or an idle wake keeps it; the latest row wins over the create keys. -`--daemon-hosted` refuses to run against a daemon that does not advertise the `subagent_model` -capability. +keys `subagentModel`/`subagentThinking`/`subagentModels`), so grandchildren resolve the same +way. The daemon worker persists the override as a `subagent_model_state` row in the session +file it owns (every `set_subagent_model` and `set_subagent_models`, a clear included, and an RLM +child's inherited override once, at birth), so a resume, a respawn or an idle wake keeps it; the +latest row wins over the create keys. `--daemon-hosted` refuses to run against a daemon that +does not advertise the `subagent_model` capability (or `subagent_models`, for +`--subagent-models`). ## TUI - `/subagent-model` shows the helper model and thinking level this session's spawns resolve to, - with the layer each comes from, and warns when the model is not in the catalog. + with the layer each comes from, and the helper model list with its source. It warns when the + model is not in the catalog or not on the list. - `/subagent-model []` sets the session override. `parent` keeps the parent's value; `default` leaves the field to the settings file. `/subagent-model default` - clears the override. + clears the override. The session's list additions stay. +- `/subagent-models` shows the same status. `/subagent-models a,b` replaces the session's + additions to the helper model list; `/subagent-models default` clears them. The override's + model and thinking level stay. - `/settings`, Models tab: "Helper model" (a list: `parent` plus the signed-in providers' models) and "Helper thinking" (`parent`, `off` ... `max`) write the two settings keys. - `parent` removes the key. + `parent` removes the key. Edit `subagentModels` in the settings file. ## Visibility @@ -81,15 +133,22 @@ capability. child runs at, clamped to its model (absent only when neither a default nor the parent names a level). - The agents view lists each child's real model and thinking level (`model:level`). -- `/subagent-model` names the layer each value came from. +- `/subagent-model` and `/subagent-models` name the layer each value came from and the list's + source. ## Daemon wire -Fork-only, behind the server capability `subagent_model` (no schema bump): - -- `get_subagent_model_status { activeSessionId }` and - `set_subagent_model { activeSessionId, model?, thinking? }` answer - `{ model, modelSource, modelKnown, thinking, thinkingSource, session, settings }`; the sources - are `session`, `settings` or `parent`. -- RLM child creates carry `subagentModel`/`subagentThinking`; the supervisor keeps both in the - durable create command. +Fork-only, no schema bump: + +- Capability `subagent_model`: `get_subagent_model_status { activeSessionId }` and + `set_subagent_model { activeSessionId, model?, thinking? }`. +- Capability `subagent_models`: `set_subagent_models { activeSessionId, models? }` (an empty or + absent list clears the session's additions), and the daemon enforces the helper model list. +- Each command answers `{ model, modelSource, modelKnown, modelAllowed, thinking, + thinkingSource, models, modelsSource, session, settings }`. The model and thinking sources are + `session`, `settings` or `parent`. `models` is the active list (`null`: no limit) and + `modelsSource` is `settings`, or `settings+session` when the session added entries. + `modelAllowed` is `false` when the model the spawns default to is off the list (they run on + its first entry), `null` without a list. +- RLM child creates carry `subagentModel`/`subagentThinking`/`subagentModels`; the supervisor + keeps all three in the durable create command.