diff --git a/RUST-BASE.md b/RUST-BASE.md index 23507ee3c7d..5b6ec046fbf 100644 --- a/RUST-BASE.md +++ b/RUST-BASE.md @@ -86,6 +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. | | 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 021fadadc4b..c02ceb5e365 100644 --- a/crates/pa-cli/README.md +++ b/crates/pa-cli/README.md @@ -45,7 +45,13 @@ the quiescence drive that holds the run open until every admitted descendant settles and its replies and notices drain (the #2270 fix), the goal/autonomous deferral behind unsettled work, and the exit disposal (kernels snapshotted, drivers joined; no child outlives the -process). +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. +`--daemon-hosted` and the interactive launch set the same override on their +session (`set_subagent_model`, behind the `subagent_model` capability). 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 78472558e13..7e3de8e5cb4 100644 --- a/crates/pa-cli/src/args.rs +++ b/crates/pa-cli/src/args.rs @@ -144,6 +144,11 @@ pub struct Args { pub system_prompt: Option, pub append_system_prompt: Vec, pub thinking: Option, + /// `--subagent-model`: this session's helper model for spawned agents (`provider/model-id` + /// or `parent`). + pub subagent_model: Option, + /// `--subagent-thinking`: this session's helper thinking level (a level or `parent`). + pub subagent_thinking: Option, pub continue_: bool, /// `true` when `--resume` was given without a selector. pub resume_bare: bool, @@ -362,6 +367,20 @@ pub fn parse_args(args: &[String]) -> Args { ))); } } + "--subagent-model" => result.subagent_model = Some(require_value!(arg)), + "--subagent-thinking" => { + let level = require_value!(arg); + if level == pa_core::session_engine::helper_model::INHERIT_PARENT + || parse_thinking_level(&level).is_some() + { + result.subagent_thinking = Some(level); + } else { + result.diagnostics.push(Diagnostic::error(format!( + "Invalid --subagent-thinking level \"{level}\". Valid values: parent, {}", + THINKING_LEVELS.join(", ") + ))); + } + } "--print" | "-p" => { result.print = true; if let Some(next) = args.get(i + 1) { @@ -620,6 +639,42 @@ mod tests { Diagnostic::error(message) } + /// The helper-model flags carry the session's override; an unknown level is an error. + #[test] + fn subagent_flags_carry_the_helper_override() { + let expected = Args { + subagent_model: Some("cpa-r/deepseek-flash-1017".to_string()), + subagent_thinking: Some("max".to_string()), + print: true, + messages: vec!["hi".to_string()], + ..Args::default() + }; + assert_eq!( + format!( + "{:?}", + parse(&[ + "--subagent-model", + "cpa-r/deepseek-flash-1017", + "--subagent-thinking", + "max", + "-p", + "hi" + ]) + ), + format!("{expected:?}") + ); + assert_eq!( + parse(&["--subagent-thinking", "parent"]) + .subagent_thinking + .as_deref(), + Some("parent") + ); + assert_eq!( + last_error(&parse(&["--subagent-thinking", "loud"])), + "Invalid --subagent-thinking level \"loud\". Valid values: parent, off, minimal, low, medium, high, xhigh, max" + ); + } + /// Both syntaxes select the profile on an explicit json run. #[test] fn json_event_profile_spaced_and_equals_syntax() { diff --git a/crates/pa-cli/src/client_settings.rs b/crates/pa-cli/src/client_settings.rs index bfd09b01545..3178b4db148 100644 --- a/crates/pa-cli/src/client_settings.rs +++ b/crates/pa-cli/src/client_settings.rs @@ -101,6 +101,29 @@ impl ClientSettings for CliClientSettings { self.manager().set_theme(theme.to_string()) } + fn subagent_default_model(&self) -> Option { + self.manager().get_subagent_default_model() + } + + fn set_subagent_default_model(&self, model: Option<&str>) -> Result<()> { + self.manager() + .set_subagent_default_model(model.map(str::to_string)) + } + + fn subagent_default_thinking(&self) -> Option { + self.manager().get_subagent_default_thinking() + } + + 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()) + { + anyhow::bail!("Invalid thinking level \"{level}\""); + } + self.manager() + .set_subagent_default_thinking(level.map(str::to_string)) + } + fn default_service_tier(&self) -> String { // The wire name of the persisted default tier; "default" when // unset or unreadable. diff --git a/crates/pa-cli/src/command_registry.rs b/crates/pa-cli/src/command_registry.rs index 6cbca038187..36fb95a8dca 100644 --- a/crates/pa-cli/src/command_registry.rs +++ b/crates/pa-cli/src/command_registry.rs @@ -359,6 +359,14 @@ const TOP_LEVEL_OPTION_GROUPS: &[OptionGroup] = &[ "--thinking ", "Set reasoning: off, minimal, low, medium, high, xhigh, max", ), + ( + "--subagent-model ", + "Set this session's model for spawned agents (or parent)", + ), + ( + "--subagent-thinking ", + "Set this session's reasoning for spawned agents (or parent)", + ), ], }, OptionGroup { diff --git a/crates/pa-cli/src/global_flags.rs b/crates/pa-cli/src/global_flags.rs index dad9ab2127e..f213a4c53e0 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; 25] = [ +pub const GLOBAL_VALUE_FLAGS: [&str; 27] = [ "--mode", "--json-event-profile", "--daemon-socket", @@ -19,6 +19,8 @@ pub const GLOBAL_VALUE_FLAGS: [&str; 25] = [ "--models", "--tools", "--thinking", + "--subagent-model", + "--subagent-thinking", "--skill", "--prompt-template", "--theme", diff --git a/crates/pa-cli/src/hosted_print.rs b/crates/pa-cli/src/hosted_print.rs index 8e25b794df1..05e99838b2c 100644 --- a/crates/pa-cli/src/hosted_print.rs +++ b/crates/pa-cli/src/hosted_print.rs @@ -154,6 +154,7 @@ async fn hosted_print_main(options: &RunOptions) -> Result { offline: options.offline, no_skills: config.no_skills, }, + subagent_override: config.subagent_override.clone(), }) .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 09821c42677..f7d237ac194 100644 --- a/crates/pa-cli/src/interactive_mode.rs +++ b/crates/pa-cli/src/interactive_mode.rs @@ -235,10 +235,14 @@ fn print_resume_hint(hint: Option<&str>) { /// The agents-view loop: open the view, run the session it opens, and return /// to the view on agents-back or bare `/resume`; every other exit ends the app. async fn run_agents_view_flow( - base: InteractiveOptions, + mut base: InteractiveOptions, anchor: Option, 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). + base.model_selection.subagent_model = None; + base.model_selection.subagent_thinking = 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. @@ -489,6 +493,9 @@ fn build_tui_options( api_key: config.api_key.clone(), // The worker clamps `--thinking` to the model's levels. thinking: config.thinking, + // The launch helper-model override, set on the opened session. + subagent_model: config.subagent_override.model.clone(), + subagent_thinking: config.subagent_override.thinking.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 cd132215fc0..6dbdade14b8 100644 --- a/crates/pa-cli/src/mode.rs +++ b/crates/pa-cli/src/mode.rs @@ -92,6 +92,9 @@ pub struct RuntimeConfig { pub telemetry_disabled: bool, 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`. + pub subagent_override: pa_core::session_engine::helper_model::HelperDefaults, } impl RuntimeConfig { @@ -382,6 +385,25 @@ pub fn runtime_config_from_args( objective: objective.clone(), token_budget: parsed.goal_token_budget, }), + subagent_override: { + use pa_core::session_engine::helper_model::{ + HelperDefaults, 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_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() + }); + HelperDefaults::new( + parsed.subagent_model.as_deref(), + parsed.subagent_thinking.as_deref(), + ) + .unwrap_or_default() + .or(&env_layer) + }, } } @@ -420,6 +442,85 @@ pub(crate) mod tests { } } + /// The helper-model override: each `--subagent-*` flag beats its `PRIME_SUBAGENT_*` env + /// var, field by field; an invalid env level is ignored, never fatal. + #[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, + }; + let resolve = |argv: &[&str], model: Option<&str>, thinking: Option<&str>| { + let saved: Vec<(&str, Option)> = [SUBAGENT_MODEL_ENV, SUBAGENT_THINKING_ENV] + .iter() + .map(|key| (*key, std::env::var(key).ok())) + .collect(); + for (key, value) in [ + (SUBAGENT_MODEL_ENV, model), + (SUBAGENT_THINKING_ENV, thinking), + ] { + match value { + Some(value) => std::env::set_var(key, value), + None => std::env::remove_var(key), + } + } + let args: Vec = argv.iter().map(ToString::to_string).collect(); + let config = runtime_config_from_args( + &crate::args::parse_args(&args), + PathBuf::from("/w"), + PathBuf::from("/agent"), + None, + AppMode::Print, + true, + ); + for (key, value) in saved { + match value { + Some(value) => std::env::set_var(key, value), + None => std::env::remove_var(key), + } + } + config.subagent_override + }; + let layer = |model: Option<&str>, thinking: Option<&str>| { + HelperDefaults::new(model, thinking).unwrap() + }; + assert_eq!( + resolve( + &["-p", "hi"], + Some("cpa-r/deepseek-flash-1017"), + Some("max") + ), + layer(Some("cpa-r/deepseek-flash-1017"), Some("max")) + ); + assert_eq!( + resolve( + &["--subagent-model", "cpa-r/kimi-k3.1", "-p", "hi"], + Some("cpa-r/deepseek-flash-1017"), + Some("max") + ), + layer(Some("cpa-r/kimi-k3.1"), Some("max")) + ); + assert_eq!( + resolve( + &["--subagent-thinking", "parent", "-p", "hi"], + None, + Some("max") + ), + layer(None, Some("parent")) + ); + assert_eq!( + resolve( + &["-p", "hi"], + Some("cpa-r/deepseek-flash-1017"), + Some("loud") + ), + layer(Some("cpa-r/deepseek-flash-1017"), None) + ); + assert_eq!( + resolve(&["-p", "hi"], None, None), + HelperDefaults::default() + ); + } + /// The opt-out chain (the operator's explicit ask): `DO_NOT_TRACK`/`PI_OFFLINE` disable /// even against `PRIME_AGENT_TELEMETRY=1`. #[test] diff --git a/crates/pa-cli/src/print_rlm.rs b/crates/pa-cli/src/print_rlm.rs index afe9cfd0871..ada6385c59d 100644 --- a/crates/pa-cli/src/print_rlm.rs +++ b/crates/pa-cli/src/print_rlm.rs @@ -659,15 +659,18 @@ impl RlmSubagentHost for InlineHost { } } } - // The child's thinking: the requested level, else the parent's - // effective one; a real-provider child clamps it to what its - // model supports. + // The parent's effective thinking: a scripted child's default, and a real-provider + // child's when the helper order names no level. + let parent_thinking = node + .thinking + .lock() + .unwrap() + .unwrap_or(pa_types::ai::ModelThinkingLevel::Medium); let thinking = request .thinking .as_deref() .and_then(pa_ai::models::thinking_level_from_str) - .or(*node.thinking.lock().unwrap()) - .unwrap_or(pa_types::ai::ModelThinkingLevel::Medium); + .unwrap_or(parent_thinking); // 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. @@ -706,19 +709,32 @@ impl RlmSubagentHost for InlineHost { thinking, ) } else { - let selector = pa_daemon::rlm_child_model::resolve_child_model_unchecked( + // 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, - request.model.as_deref(), - node.model_selector.lock().unwrap().as_deref(), - "subagent", - ) - .map_err(|error| anyhow::anyhow!("{error:#}"))?; - pa_daemon::rlm_child_model::assert_thinking_supported( + ); + let parent_selector = node.model_selector.lock().unwrap().clone(); + let helper = pa_daemon::rlm_child_model::resolve_helper_unchecked( &config.agent_dir, - request.thinking.as_deref(), - &selector, + pa_daemon::rlm_child_model::HelperRequest { + model: request.model.as_deref(), + thinking: request.thinking.as_deref(), + parent_model: parent_selector.as_deref(), + parent_thinking: Some(parent_thinking.wire_name()), + session: &config.subagent_override, + settings: &settings, + }, + "subagent", ) .map_err(|error| anyhow::anyhow!("{error:#}"))?; + let selector = helper.selector; + let thinking = helper + .thinking + .as_deref() + .and_then(pa_ai::models::thinking_level_from_str) + .unwrap_or(parent_thinking); let auth = pa_core::auth::AuthStorage::create(&config.agent_dir); let mut registry = pa_core::models::ModelRegistry::create( auth, @@ -856,6 +872,7 @@ impl RlmSubagentHost for InlineHost { name, session_dir: child_node.session_dir.clone(), model: selector, + thinking: Some(thinking.wire_name().to_string()), }) }) } diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rs index ab325af168a..3a22acc5ba1 100644 --- a/crates/pa-cli/src/print_runtime.rs +++ b/crates/pa-cli/src/print_runtime.rs @@ -50,6 +50,15 @@ impl crate::mode::Runtime for PrintRuntime { // Runtime failures print themselves and exit non-zero; the typed // MissingSubsystem channel stays reserved for unwired subsystems. AppMode::Print | AppMode::Json => { + // The helper model this run's spawns default to, checked against the catalog + // once at startup: an unknown one warns here and its spawns use the parent's. + if let Some(warning) = pa_daemon::rlm_child_model::unknown_helper_model_notice( + &options.config.cwd, + &options.config.agent_dir, + &options.config.subagent_override, + ) { + eprintln!("{warning}"); + } let run = match options.headless_hosting { crate::mode::HeadlessHosting::InProcess => run_print_mode(options), crate::mode::HeadlessHosting::Daemon => { diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rs index 9906d0e6067..89e3cf2b907 100644 --- a/crates/pa-cli/tests/interactive_daemon_e2e.rs +++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs @@ -4862,6 +4862,8 @@ fn subscription_options( model: Some("claude-test".to_string()), api_key: None, thinking: None, + subagent_model: None, + subagent_thinking: None, }; options.provider_auth = Some(pa_tui::provider_auth::ProviderAuthCommandsHandle( std::sync::Arc::new(E2ESubscriptionAuth), diff --git a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs index 116c402dd98..fe0cf6b0511 100644 --- a/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs +++ b/crates/pa-cli/tests/subagent_panel_nested_count_e2e.rs @@ -215,6 +215,7 @@ fn children_host( session_file: Some(parent.session_file.clone()), thinking: None, child_script: Some(script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); sessions } diff --git a/crates/pa-core/README.md b/crates/pa-core/README.md index bf47392c514..9fd8e4ce4ea 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`), 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`), `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). ## 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 new file mode 100644 index 00000000000..44f8de43e73 --- /dev/null +++ b/crates/pa-core/src/session_engine/helper_model.rs @@ -0,0 +1,493 @@ +//! The helper model of spawned agents (Oneiron fork): the model and thinking level an +//! `rlm.spawn` or `rlm.create_session` child runs on when the call names none. +//! +//! Each field resolves on its own; the first layer that names a value wins: +//! 1. the spawn call's `model=` / `thinking=`; +//! 2. the session override: `--subagent-model`/`--subagent-thinking`, the +//! `PRIME_SUBAGENT_MODEL`/`PRIME_SUBAGENT_THINKING` env vars, or the TUI's +//! `/subagent-model` (persisted in the session file as a `subagent_model_state` row); +//! 3. the settings file: `subagentDefaultModel`/`subagentDefaultThinking`; +//! 4. the parent's own model and thinking level (upstream behavior). +//! +//! 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). + +use std::collections::HashSet; +use std::sync::{Mutex, OnceLock}; + +use pa_types::ai::thinking_level_from_str; +use serde_json::{Map, Value}; + +use crate::settings::SettingsManager; + +/// The env var a headless invocation reads as its session's helper model. +pub const SUBAGENT_MODEL_ENV: &str = "PRIME_SUBAGENT_MODEL"; +/// The env var a headless invocation reads as its session's helper thinking level. +pub const SUBAGENT_THINKING_ENV: &str = "PRIME_SUBAGENT_THINKING"; +/// The value that pins a layer to the parent's model or thinking level. +pub const INHERIT_PARENT: &str = "parent"; +/// The custom session row that persists the session override. +pub const SUBAGENT_MODEL_STATE_CUSTOM_TYPE: &str = "subagent_model_state"; +/// The create-config key carrying the session override's model (RLM children, durable creates). +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 layer a resolved helper value came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HelperSource { + /// The spawn call named it. + Spawn, + /// The session override. + Session, + /// The settings file. + Settings, + /// The parent's own value. + Parent, +} + +impl HelperSource { + /// The wire label the status command and the spawn handle carry. + #[must_use] + pub fn wire_name(self) -> &'static str { + match self { + HelperSource::Spawn => "spawn", + HelperSource::Session => "session", + HelperSource::Settings => "settings", + HelperSource::Parent => "parent", + } + } +} + +/// 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. +#[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, +} + +impl HelperDefaults { + /// Validate one layer: values are trimmed, an empty value is unset, and the thinking level + /// must be a level name or `parent`. + /// + /// # Errors + /// + /// Returns the message for an unknown thinking level. + pub fn new(model: Option<&str>, thinking: Option<&str>) -> Result { + let trimmed = |value: Option<&str>| { + value + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }; + let thinking = trimmed(thinking); + if let Some(level) = &thinking { + if level != INHERIT_PARENT && thinking_level_from_str(level).is_none() { + return Err(format!( + "Invalid helper thinking level \"{level}\". Valid values: {INHERIT_PARENT}, off, minimal, low, medium, high, xhigh, max" + )); + } + } + Ok(Self { + model: trimmed(model), + thinking, + }) + } + + /// True when the layer names neither field. + #[must_use] + pub fn is_empty(&self) -> bool { + self.model.is_none() && self.thinking.is_none() + } + + /// Fill each field this layer lacks from `fallback`. + #[must_use] + pub fn or(self, fallback: &Self) -> Self { + Self { + model: self.model.or_else(|| fallback.model.clone()), + thinking: self.thinking.or_else(|| fallback.thinking.clone()), + } + } + + /// The settings-file layer (`subagentDefaultModel`/`subagentDefaultThinking`). + #[must_use] + pub fn from_settings(settings: &SettingsManager) -> Self { + Self { + model: settings.get_subagent_default_model(), + thinking: settings.get_subagent_default_thinking(), + } + } + + /// The settings-file layer read from disk for one cwd and agent dir. + #[must_use] + pub fn load_settings(cwd: &std::path::Path, agent_dir: &std::path::Path) -> Self { + 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. + #[must_use] + pub fn from_create_config(config: &Map) -> Self { + let field = |key: &str| config.get(key).and_then(Value::as_str); + Self::new( + field(SUBAGENT_MODEL_CONFIG_KEY), + field(SUBAGENT_THINKING_CONFIG_KEY), + ) + .unwrap_or_default() + } + + /// Write the layer into a create config; unset fields write nothing. + pub fn write_into(&self, config: &mut Map) { + if let Some(model) = &self.model { + config.insert( + SUBAGENT_MODEL_CONFIG_KEY.to_string(), + Value::String(model.clone()), + ); + } + if let Some(thinking) = &self.thinking { + config.insert( + SUBAGENT_THINKING_CONFIG_KEY.to_string(), + Value::String(thinking.clone()), + ); + } + } +} + +/// 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 { + pub value: Option, + pub source: HelperSource, +} + +/// The helper picks for one spawn, before the host resolves the model reference. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HelperPlan { + pub model: HelperPick, + pub thinking: HelperPick, +} + +/// Walk the layers for each field: the spawn call, the session override, the settings file, the +/// parent. A `parent` value stops the walk at the parent. +#[must_use] +pub fn plan_helper( + requested_model: Option<&str>, + requested_thinking: Option<&str>, + session: &HelperDefaults, + settings: &HelperDefaults, +) -> HelperPlan { + let pick = |requested: Option<&str>, session: Option<&str>, settings: Option<&str>| { + let parent = HelperPick { + value: None, + source: HelperSource::Parent, + }; + if let Some(value) = requested { + // The spawn call's own value goes to the host as given (its strict checks apply). + return HelperPick { + value: Some(value.to_string()), + source: HelperSource::Spawn, + }; + } + [ + (session, HelperSource::Session), + (settings, HelperSource::Settings), + ] + .into_iter() + .find_map(|(value, source)| value.map(|value| (value, source))) + .map_or(parent.clone(), |(value, source)| { + if value == INHERIT_PARENT { + parent.clone() + } else { + HelperPick { + value: Some(value.to_string()), + source, + } + } + }) + }; + HelperPlan { + model: pick( + requested_model, + session.model.as_deref(), + settings.model.as_deref(), + ), + thinking: pick( + requested_thinking, + session.thinking.as_deref(), + settings.thinking.as_deref(), + ), + } +} + +/// 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. +#[must_use] +pub fn first_unknown_helper_model(reference: &str, source: HelperSource) -> 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())) +} + +/// The warning line for a default helper model the catalog does not know. +#[must_use] +pub fn unknown_helper_model_warning(reference: &str, source: HelperSource) -> String { + let origin = match source { + HelperSource::Settings => "subagentDefaultModel", + HelperSource::Session => "The session's helper model", + HelperSource::Spawn | HelperSource::Parent => "The helper model", + }; + format!( + "Warning: {origin} \"{reference}\" is not in the model catalog (models.json); spawned agents use the parent's model" + ) +} + +/// The latest persisted `subagent_model_state` row of a session file: the session override a +/// resumed session re-seeds from. `Some` with both fields unset is an explicit clear; `None` +/// when the file has no row or cannot be read. +#[must_use] +pub fn persisted_session_override(path: Option<&str>) -> Option { + let content = std::fs::read_to_string(path?).ok()?; + content + .lines() + .rev() + // A matching row's raw text carries the `customType` literal or a `\u`-escape. + .filter(|line| line.contains(SUBAGENT_MODEL_STATE_CUSTOM_TYPE) || line.contains("\\u")) + .find_map(parse_override_row) +} + +/// One candidate line's override: `Some` for a `subagent_model_state` custom row. +fn parse_override_row(line: &str) -> Option { + let value: Value = serde_json::from_str(line.trim()).ok()?; + if value.get("type").and_then(Value::as_str) != Some("custom") + || value.get("customType").and_then(Value::as_str) != Some(SUBAGENT_MODEL_STATE_CUSTOM_TYPE) + { + return None; + } + 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()) +} + +/// The fields of the `custom` session entry that persists one override (the worker's +/// `SessionFile::persist_entry("custom", ...)`); unset fields persist as `null`. +#[must_use] +pub fn session_override_row(layer: &HelperDefaults) -> Value { + serde_json::json!({ + "customType": SUBAGENT_MODEL_STATE_CUSTOM_TYPE, + "data": { "model": layer.model, "thinking": layer.thinking }, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn layer(model: Option<&str>, thinking: Option<&str>) -> HelperDefaults { + HelperDefaults::new(model, thinking).unwrap() + } + + fn pick(value: Option<&str>, source: HelperSource) -> HelperPick { + HelperPick { + value: value.map(str::to_string), + source, + } + } + + #[test] + fn each_field_takes_the_first_layer_that_names_it() { + let session = layer(Some("cpa-r/kimi-k3.1"), None); + let settings = layer(Some("cpa-r/deepseek-flash-1017"), Some("max")); + // The spawn call wins both fields. + assert_eq!( + plan_helper(Some("cpa-r/astra"), Some("low"), &session, &settings), + HelperPlan { + model: pick(Some("cpa-r/astra"), HelperSource::Spawn), + thinking: pick(Some("low"), HelperSource::Spawn), + } + ); + // No spawn values: the session override's model, the settings file's thinking. + assert_eq!( + plan_helper(None, None, &session, &settings), + HelperPlan { + model: pick(Some("cpa-r/kimi-k3.1"), HelperSource::Session), + thinking: pick(Some("max"), HelperSource::Settings), + } + ); + // No override: the settings file. + assert_eq!( + plan_helper(None, None, &HelperDefaults::default(), &settings), + HelperPlan { + model: pick(Some("cpa-r/deepseek-flash-1017"), HelperSource::Settings), + thinking: pick(Some("max"), HelperSource::Settings), + } + ); + // Nothing configured: the parent's model and thinking (upstream behavior). + assert_eq!( + plan_helper( + None, + None, + &HelperDefaults::default(), + &HelperDefaults::default() + ), + HelperPlan { + model: pick(None, HelperSource::Parent), + thinking: pick(None, HelperSource::Parent), + } + ); + } + + #[test] + fn a_parent_value_stops_the_walk_at_the_parent() { + let session = layer(Some(INHERIT_PARENT), Some(INHERIT_PARENT)); + let settings = layer(Some("cpa-r/deepseek-flash-1017"), Some("max")); + assert_eq!( + plan_helper(None, None, &session, &settings), + HelperPlan { + model: pick(None, HelperSource::Parent), + thinking: pick(None, HelperSource::Parent), + } + ); + // The spawn call's own value is passed through for the host to resolve. + assert_eq!( + plan_helper(Some(INHERIT_PARENT), None, &session, &settings).model, + pick(Some(INHERIT_PARENT), HelperSource::Spawn) + ); + } + + #[test] + fn a_layer_trims_values_and_rejects_unknown_levels() { + assert_eq!( + HelperDefaults::new(Some(" cpa-r/deepseek-flash-1017 "), Some(" ")).unwrap(), + layer(Some("cpa-r/deepseek-flash-1017"), None) + ); + let error = HelperDefaults::new(None, Some("loud")).unwrap_err(); + assert!(error.contains("\"loud\""), "{error}"); + assert_eq!( + HelperDefaults::new(None, Some(INHERIT_PARENT)).unwrap(), + layer(None, Some(INHERIT_PARENT)) + ); + } + + #[test] + fn the_create_config_round_trips_the_override() { + let override_layer = layer(Some("cpa-r/deepseek-flash-1017"), Some("max")); + 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. + config.insert( + SUBAGENT_THINKING_CONFIG_KEY.to_string(), + Value::String("loud".into()), + ); + assert_eq!( + HelperDefaults::from_create_config(&config), + HelperDefaults::default() + ); + } + + #[test] + fn the_settings_layer_reads_both_keys() { + let dir = tempfile::TempDir::new().unwrap(); + let agent_dir = dir.path().join("agent"); + std::fs::create_dir_all(&agent_dir).unwrap(); + std::fs::write( + agent_dir.join("settings.json"), + r#"{"subagentDefaultModel":" cpa-r/deepseek-flash-1017 ","subagentDefaultThinking":"max"}"#, + ) + .unwrap(); + assert_eq!( + HelperDefaults::load_settings(dir.path(), &agent_dir), + layer(Some("cpa-r/deepseek-flash-1017"), Some("max")) + ); + // A wrong-typed value loads as unset (the lenient settings load). + std::fs::write( + agent_dir.join("settings.json"), + r#"{"subagentDefaultModel":42,"subagentDefaultThinking":"loud"}"#, + ) + .unwrap(); + assert_eq!( + HelperDefaults::load_settings(dir.path(), &agent_dir), + HelperDefaults::default() + ); + // A project's `parent` overrides a global level: the walk stops at the parent. + std::fs::write( + agent_dir.join("settings.json"), + r#"{"subagentDefaultThinking":"max"}"#, + ) + .unwrap(); + let project = dir.path().join(".prime").join("agent"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write( + project.join("settings.json"), + r#"{"subagentDefaultThinking":"parent"}"#, + ) + .unwrap(); + let settings = HelperDefaults::load_settings(dir.path(), &agent_dir); + assert_eq!(settings, layer(None, Some(INHERIT_PARENT))); + assert_eq!( + plan_helper(None, None, &HelperDefaults::default(), &settings).thinking, + HelperPick { + value: None, + source: HelperSource::Parent, + } + ); + } + + #[test] + fn the_latest_persisted_row_is_the_session_override() { + let dir = tempfile::TempDir::new().unwrap(); + let file = dir.path().join("session.jsonl"); + // The entry the worker's `persist_entry("custom", ...)` writes. + let row = |layer: &HelperDefaults| { + let mut entry = session_override_row(layer); + entry["type"] = Value::String("custom".to_string()); + entry.to_string() + }; + std::fs::write( + &file, + [ + r#"{"type":"session","id":"s"}"#.to_string(), + row(&layer(Some("cpa-r/kimi"), None)), + row(&layer(Some("cpa-r/deepseek-flash-1017"), Some("max"))), + r#"{"type":"message","id":"m"}"#.to_string(), + ] + .join("\n"), + ) + .unwrap(); + 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"))) + ); + // A cleared override is an explicit, empty row. + let mut content = std::fs::read_to_string(&file).unwrap(); + content.push('\n'); + content.push_str(&row(&HelperDefaults::default())); + std::fs::write(&file, content).unwrap(); + assert_eq!( + persisted_session_override(Some(&path)), + Some(HelperDefaults::default()) + ); + assert_eq!(persisted_session_override(None), None); + } + + #[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( + reference, + HelperSource::Settings + )); + assert!(first_unknown_helper_model(reference, HelperSource::Session)); + } +} diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rs index bdaec32e8ea..645ca846beb 100644 --- a/crates/pa-core/src/session_engine/mod.rs +++ b/crates/pa-core/src/session_engine/mod.rs @@ -20,6 +20,7 @@ pub mod goal_boundary; pub mod goal_driver; pub mod harness_digest; pub mod headless; +pub mod helper_model; pub mod host_requests; pub mod image_model_routing; pub mod ipython_state; diff --git a/crates/pa-core/src/session_engine/rlm_host.rs b/crates/pa-core/src/session_engine/rlm_host.rs index 1ec6eb484cd..0eb38155690 100644 --- a/crates/pa-core/src/session_engine/rlm_host.rs +++ b/crates/pa-core/src/session_engine/rlm_host.rs @@ -40,6 +40,10 @@ pub struct RlmSpawnHandle { pub name: String, pub session_dir: String, pub model: String, + /// The child's thinking level when the host resolved one (the spawn call, the helper + /// defaults, or the parent's known level); absent when the child's worker picks its default. + #[serde(skip_serializing_if = "Option::is_none")] + pub thinking: Option, } /// `rlm.create_session` handle: one resident depth-0 daemon session. @@ -50,6 +54,9 @@ pub struct RlmCreateSessionHandle { pub name: String, pub session_file: String, pub model: String, + /// The session's thinking level when the host resolved one (see [`RlmSpawnHandle`]). + #[serde(skip_serializing_if = "Option::is_none")] + pub thinking: Option, } /// One roster row of `rlm.list_subagents`. @@ -917,6 +924,7 @@ mod tests { name: "worker".into(), session_dir: "/tmp/sub-1".into(), model: "p/m".into(), + thinking: None, }) }) } @@ -933,6 +941,7 @@ mod tests { name: "root-2".into(), session_file: "/tmp/s-2.jsonl".into(), model: "p/m".into(), + thinking: None, }) }) } diff --git a/crates/pa-core/src/settings/load.rs b/crates/pa-core/src/settings/load.rs index da1f23394b8..690c58f3aa6 100644 --- a/crates/pa-core/src/settings/load.rs +++ b/crates/pa-core/src/settings/load.rs @@ -13,6 +13,7 @@ const KNOWN_FIELDS: &[&str] = &[ "defaultProvider", "defaultModel", "subagentDefaultModel", + "subagentDefaultThinking", "updateChannel", "recentModels", "auxiliaryModel", diff --git a/crates/pa-core/src/settings/manager.rs b/crates/pa-core/src/settings/manager.rs index 8ecd0f23248..0e94a1bbeb7 100644 --- a/crates/pa-core/src/settings/manager.rs +++ b/crates/pa-core/src/settings/manager.rs @@ -564,7 +564,7 @@ impl SettingsManager { self.merged.default_model.as_deref() } - /// Model for `rlm.spawn` without a pinned model; unset inherits parent. + /// Model for `rlm.spawn`/`rlm.create_session` without a pinned model; unset inherits parent. #[must_use] pub fn get_subagent_default_model(&self) -> Option { self.merged @@ -574,6 +574,40 @@ impl SettingsManager { .filter(|m| !m.is_empty()) } + /// Thinking level for spawns without a pinned level: a level name or `parent`; unset, blank + /// or unknown values read as unset (the parent's level). + #[must_use] + pub fn get_subagent_default_thinking(&self) -> Option { + self.merged + .subagent_default_thinking + .as_ref() + .map(|level| level.trim().to_string()) + .filter(|level| { + level == crate::session_engine::helper_model::INHERIT_PARENT + || pa_types::ai::thinking_level_from_str(level).is_some() + }) + } + + /// Set (or, with `None`, remove) the global `subagentDefaultModel`. + /// + /// # Errors + /// + /// Returns an error when the global settings file cannot be written. + pub fn set_subagent_default_model(&mut self, model: Option) -> Result<()> { + self.global.subagent_default_model = model; + self.save_global(&["subagentDefaultModel"]) + } + + /// Set (or, with `None`, remove) the global `subagentDefaultThinking`. + /// + /// # Errors + /// + /// Returns an error when the global settings file cannot be written. + pub fn set_subagent_default_thinking(&mut self, level: Option) -> Result<()> { + self.global.subagent_default_thinking = level; + self.save_global(&["subagentDefaultThinking"]) + } + #[must_use] pub fn get_auxiliary_model(&self) -> Option<&str> { self.merged.auxiliary_model.as_deref() diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rs index e2b89038c11..a38dac996eb 100644 --- a/crates/pa-core/src/settings/types.rs +++ b/crates/pa-core/src/settings/types.rs @@ -305,7 +305,14 @@ pub struct Settings { pub onboarding_completed: Option, pub default_provider: Option, pub default_model: Option, + /// Model ("provider/model-id") a spawned agent runs on when its spawn call names none; unset + /// or `parent` inherits the parent's model. The session override beats it. pub subagent_default_model: Option, + /// Thinking level a spawned agent runs at when its spawn call names none (`off` ... `max`, or + /// `parent`, which lets a project setting override a global level); unset inherits the + /// parent's level. Clamped to what the helper's model supports. Raw text: the getter + /// validates it. + pub subagent_default_thinking: 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 0d77f693cca..251f4bc5a18 100644 --- a/crates/pa-daemon/README.md +++ b/crates/pa-daemon/README.md @@ -83,7 +83,13 @@ Supervisor-backed RLM child sessions worker's supervisor link - one supervised worker process per child - and the parent-side registry serves `rlm.list_subagents`/`rlm.collect`/ `rlm.delete_subagent` with TS-parity selector errors; child model resolution -and thinking-level validation live in `rlm_child_model.rs`; the create +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 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 a6180d92505..00232bc88f1 100644 --- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs +++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs @@ -952,6 +952,13 @@ impl SessionEngine for AgentSessionEngine { .semantic_identity .lock() .expect("semantic identity lock") = semantic_identity; + // The helper-model override: the session file's latest `subagent_model_state` row (a + // `set_subagent_model`, or an RLM child's birth row the worker wrote at create), else the + // create's own. + let subagent_override = pa_core::session_engine::helper_model::persisted_session_override( + identity.session_file.as_deref(), + ) + .unwrap_or(identity.subagent_override); if let Some(children) = &self.children { let parent = ParentIdentity { rlm_depth: identity.rlm_depth, @@ -962,6 +969,7 @@ impl SessionEngine for AgentSessionEngine { session_file: identity.session_file.clone(), thinking: identity.thinking.clone(), child_script: identity.child_script, + subagent_override, }; children.set_identity(parent); } @@ -1346,6 +1354,43 @@ impl SessionEngine for AgentSessionEngine { Ok(result) } + fn subagent_model_status(&self) -> Value { + let session = self + .children + .as_ref() + .map(|children| children.subagent_override()) + .unwrap_or_default(); + let settings = pa_core::session_engine::helper_model::HelperDefaults::load_settings( + &self.cwd(), + &self.config.agent_dir, + ); + let plan = + pa_core::session_engine::helper_model::plan_helper(None, None, &session, &settings); + let model_known = plan.model.value.as_deref().map(|reference| { + crate::rlm_child_model::helper_model_known(&self.config.agent_dir, reference) + }); + json!({ + "model": plan.model.value, + "modelSource": plan.model.source.wire_name(), + "modelKnown": model_known, + "thinking": plan.thinking.value, + "thinkingSource": plan.thinking.source.wire_name(), + "session": session, + "settings": settings, + }) + } + + fn set_subagent_model( + &self, + layer: pa_core::session_engine::helper_model::HelperDefaults, + ) -> anyhow::Result<()> { + let Some(children) = &self.children else { + anyhow::bail!("This session has no RLM child runtime"); + }; + children.set_subagent_override(layer); + Ok(()) + } + fn run_prompt( &self, _prompt_index: usize, 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 3bb3f59870e..ae3b4715ed3 100644 --- a/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs +++ b/crates/pa-daemon/src/agent_engine/tests/rlm_children.rs @@ -1,4 +1,5 @@ -//! The rlm-children tests (the persisted max-depth scan, the settled-child release probe). +//! The rlm-children tests (the persisted max-depth scan, the settled-child release probe, the +//! helper-model session override). use super::*; use pa_core::session_engine::rlm_host::persisted_rlm_max_depth; @@ -384,3 +385,128 @@ fn can_passivate_worker_mirrors_the_release_gates_and_adds_the_registry_rule() { )); assert_eq!(fired.load(std::sync::atomic::Ordering::SeqCst), 1); } + +/// The session override of the helper model: `set_subagent_model` replaces what the spawns read +/// (the status names each field's layer and checks the model against the catalog), and a +/// session re-seeds from its persisted `subagent_model_state` row ahead of the create's own +/// override. +#[test] +fn the_session_override_beats_the_settings_file_and_reseeds_from_the_session_file() { + use pa_core::session_engine::helper_model::{session_override_row, HelperDefaults}; + let dir = tempfile::TempDir::new().unwrap(); + let agent_dir = dir.path().join("agent"); + std::fs::create_dir_all(&agent_dir).unwrap(); + std::fs::write( + agent_dir.join("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 } + ] + } + } + }) + .to_string(), + ) + .unwrap(); + std::fs::write( + agent_dir.join("settings.json"), + json!({ "subagentDefaultModel": "test-provider/helper-flash", "subagentDefaultThinking": "high" }) + .to_string(), + ) + .unwrap(); + let engine = AgentSessionEngine::new(AgentEngineConfig { + cwd: dir.path().to_path_buf(), + agent_dir, + provider: None, + model: None, + api_key: None, + thinking: None, + session_dir: None, + session_file: None, + faux_script: None, + supervisor_link: Some(crate::agent_engine::SupervisorLinkConfig { + socket_path: dir.path().join("dead.sock"), + active_session_id: "parent-session".to_string(), + worker_token: "token".to_string(), + }), + telemetry_disabled: None, + cron_store: None, + queued_steering_probe: None, + }) + .unwrap(); + assert_eq!( + crate::engine::SessionEngine::subagent_model_status(&engine), + json!({ + "model": "test-provider/helper-flash", + "modelSource": "settings", + "modelKnown": true, + "thinking": "high", + "thinkingSource": "settings", + "session": {}, + "settings": { "model": "test-provider/helper-flash", "thinking": "high" }, + }) + ); + let unknown = HelperDefaults::new(Some("cpa-r/not-in-catalog"), None).unwrap(); + crate::engine::SessionEngine::set_subagent_model(&engine, unknown.clone()).unwrap(); + assert_eq!( + crate::engine::SessionEngine::subagent_model_status(&engine), + json!({ + "model": "cpa-r/not-in-catalog", + "modelSource": "session", + "modelKnown": false, + "thinking": "high", + "thinkingSource": "settings", + "session": { "model": "cpa-r/not-in-catalog" }, + "settings": { "model": "test-provider/helper-flash", "thinking": "high" }, + }) + ); + let children = engine + .children + .as_ref() + .expect("a linked engine hosts children"); + assert_eq!(children.subagent_override(), unknown); + + // A re-seed: the session file's latest row (the worker writes it) beats the create's own + // override; a cleared row clears it. + let session_file = dir.path().join("session.jsonl"); + let row = |layer: &HelperDefaults| { + let mut entry = session_override_row(layer); + entry["type"] = json!("custom"); + entry["id"] = json!("o1"); + entry["timestamp"] = json!("2026-01-01T00:00:01.000Z"); + entry.to_string() + }; + let header = json!({ "type": "session", "version": 3, "id": "s", "timestamp": "2026-01-01T00:00:00.000Z", "cwd": "/w" }) + .to_string(); + let inherited = HelperDefaults::new(Some("test-provider/helper-flash"), None).unwrap(); + let configure = |session_file: Option| { + crate::engine::SessionEngine::configure_rlm_identity( + &engine, + crate::engine::RlmSessionIdentity { + session_file, + subagent_override: inherited.clone(), + ..Default::default() + }, + ) + .unwrap(); + }; + let persisted = HelperDefaults::new(Some("parent"), Some("max")).unwrap(); + std::fs::write(&session_file, [header.clone(), row(&persisted)].join("\n")).unwrap(); + configure(Some(session_file.to_string_lossy().to_string())); + assert_eq!(children.subagent_override(), persisted); + std::fs::write( + &session_file, + [header, row(&persisted), row(&HelperDefaults::default())].join("\n"), + ) + .unwrap(); + configure(Some(session_file.to_string_lossy().to_string())); + assert_eq!(children.subagent_override(), HelperDefaults::default()); + // No row (a fresh RLM child before its birth row, or no file): the create's override. + configure(None); + assert_eq!(children.subagent_override(), inherited); +} diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rs index 59c96d299a8..b2650b31633 100644 --- a/crates/pa-daemon/src/engine.rs +++ b/crates/pa-daemon/src/engine.rs @@ -511,6 +511,36 @@ pub trait SessionEngine: Send + Sync { let _ = global; Ok(json!({ "maxDepth": max_depth, "source": "chat", "globalSaved": false })) } + + /// 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. + fn subagent_model_status(&self) -> Value { + json!({ + "model": null, + "modelSource": "parent", + "modelKnown": null, + "thinking": null, + "thinkingSource": "parent", + "session": {}, + "settings": {}, + }) + } + + /// 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. + /// + /// # Errors + /// + /// Returns an error when the session cannot hold an override. + fn set_subagent_model( + &self, + layer: pa_core::session_engine::helper_model::HelperDefaults, + ) -> Result<()> { + let _ = layer; + anyhow::bail!("This session does not support a helper-model override") + } } #[cfg(test)] diff --git a/crates/pa-daemon/src/engine/wire.rs b/crates/pa-daemon/src/engine/wire.rs index 8d981efe0dd..b8730e2a2db 100644 --- a/crates/pa-daemon/src/engine/wire.rs +++ b/crates/pa-daemon/src/engine/wire.rs @@ -274,6 +274,9 @@ pub struct RlmSessionIdentity { /// file is a top-level runtime and spawns no edge, and a replacement /// runtime has none. pub semantic_spawn: Option, + /// The helper-model override the create carries (an RLM parent's own); a persisted + /// `subagent_model_state` row in the session file beats it. + pub subagent_override: pa_core::session_engine::helper_model::HelperDefaults, } /// A created session's semantic-edge provenance (TS diff --git a/crates/pa-daemon/src/headless_client.rs b/crates/pa-daemon/src/headless_client.rs index d99fadb0e6d..c75f0f58c7b 100644 --- a/crates/pa-daemon/src/headless_client.rs +++ b/crates/pa-daemon/src/headless_client.rs @@ -78,6 +78,9 @@ pub struct HostedSessionOptions { pub telemetry_disabled: bool, /// The session's `--offline`/`--no-skills` policy. pub session_policy: SessionPolicy, + /// 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, } /// What the daemon reported for the hosted session. @@ -194,6 +197,20 @@ 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 + .server_capabilities + .iter() + .any(|capability| capability == 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 + ); + } let policy_supported = self .link .server_capabilities @@ -262,6 +279,18 @@ impl HostedHeadlessSession { .and_then(Value::as_str) .map(str::to_string) .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() { + let set = DaemonCommand::SetSubagentModel { + id: None, + active_session_id: active_session_id.clone(), + model: options.subagent_override.model.clone(), + thinking: options.subagent_override.thinking.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 2204e5b486a..decf38caeb1 100644 --- a/crates/pa-daemon/src/headless_client/tests.rs +++ b/crates/pa-daemon/src/headless_client/tests.rs @@ -104,6 +104,7 @@ impl FakeSupervisor { session_path: None, telemetry_disabled: false, session_policy: SessionPolicy::default(), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), } } diff --git a/crates/pa-daemon/src/protocol.rs b/crates/pa-daemon/src/protocol.rs index 49891a2f91f..9941234632b 100644 --- a/crates/pa-daemon/src/protocol.rs +++ b/crates/pa-daemon/src/protocol.rs @@ -168,6 +168,9 @@ pub const KNOWN_COMMAND_TYPES: &[&str] = &[ "list_persistent_shells", "tail_persistent_shell", "kill_persistent_shell", + // Oneiron fork (capability `subagent_model`): the session's helper-model override. + "get_subagent_model_status", + "set_subagent_model", ]; /// Parsed client command envelope. @@ -363,6 +366,9 @@ pub fn default_server_capabilities() -> Vec { // Fork-only (revision 31): the create config's // `offline`/`noSkills` session policy. crate::session_policy::SESSION_POLICY_CAPABILITY, + // Fork-only: `get_subagent_model_status`/`set_subagent_model`, the + // session's helper-model override. + pa_types::daemon::SUBAGENT_MODEL_CAPABILITY, ] .iter() .map(std::string::ToString::to_string), @@ -866,6 +872,12 @@ pub fn command_active_session_id(command: &DaemonCommand) -> Option<&str> { | DaemonCommand::SetRlmMaxDepth { active_session_id, .. } + | DaemonCommand::GetSubagentModelStatus { + active_session_id, .. + } + | DaemonCommand::SetSubagentModel { + active_session_id, .. + } | DaemonCommand::GetSessionContext { active_session_id, .. } @@ -1056,6 +1068,8 @@ pub fn command_type_name(command: &DaemonCommand) -> &'static str { DaemonCommand::SetSessionName { .. } => "set_session_name", DaemonCommand::GetRlmMaxDepthStatus { .. } => "get_rlm_max_depth_status", DaemonCommand::SetRlmMaxDepth { .. } => "set_rlm_max_depth", + DaemonCommand::GetSubagentModelStatus { .. } => "get_subagent_model_status", + DaemonCommand::SetSubagentModel { .. } => "set_subagent_model", 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 4a3ebc8d7cb..7aba7be3288 100644 --- a/crates/pa-daemon/src/rlm_child_model.rs +++ b/crates/pa-daemon/src/rlm_child_model.rs @@ -6,6 +6,10 @@ use std::path::Path; 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, +}; /// Close matches listed in model-resolution errors. const MODEL_ERROR_SUGGESTION_LIMIT: usize = 3; @@ -116,6 +120,159 @@ pub fn resolve_child_model_unchecked( Err(model_unavailable_error(reference, target, &candidates)) } +/// 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)] +pub struct HelperRequest<'a> { + pub model: Option<&'a str>, + pub thinking: Option<&'a str>, + pub parent_model: Option<&'a str>, + /// The parent's thinking level, when the host knows it. + pub parent_thinking: Option<&'a str>, + /// The session override. + pub session: &'a HelperDefaults, + /// The settings file (`subagentDefaultModel`/`subagentDefaultThinking`). + pub settings: &'a HelperDefaults, +} + +/// A child's model and thinking after the helper order, with the layer each came from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResolvedHelper { + /// The catalog selector the child runs on. + pub selector: String, + pub model_source: HelperSource, + /// The level the child runs at (clamped to its catalog model); `None` when neither a layer + /// nor the parent names one (the child's worker picks its default). + pub thinking: Option, + pub thinking_source: HelperSource, +} + +/// 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. +/// +/// # 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. +pub fn resolve_helper( + agent_dir: &Path, + request: HelperRequest<'_>, + target: &str, + allowlist: &crate::model_allowlist::DaemonAllowlist, +) -> Result { + let resolved = resolve_helper_unchecked(agent_dir, request, target)?; + crate::model_allowlist::assert_allowed(allowlist, &resolved.selector)?; + Ok(resolved) +} + +/// The helper resolution before the allowlist gate (the daemonless print host's entry). The +/// spawn call's own values keep their strict checks; a default model the catalog does not know +/// 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. +/// +/// # Errors +/// Returns an error when the spawn call's own model or thinking level does not resolve, or when +/// no model resolves at all. +pub fn resolve_helper_unchecked( + agent_dir: &Path, + request: HelperRequest<'_>, + target: &str, +) -> Result { + let plan = plan_helper( + request.model, + request.thinking, + 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( + agent_dir, + Some(reference), + request.parent_model, + target, + )?, + HelperSource::Spawn, + ), + (Some(reference), source) => { + if let Ok(selector) = resolve_child_model_unchecked( + agent_dir, + Some(reference), + request.parent_model, + target, + ) { + (selector, source) + } else { + if first_unknown_helper_model(reference, source) { + eprintln!("{}", unknown_helper_model_warning(reference, source)); + } + (parent()?, HelperSource::Parent) + } + } + (None, _) => (parent()?, HelperSource::Parent), + }; + let thinking = match (plan.thinking.value, plan.thinking.source) { + (Some(level), HelperSource::Spawn) => { + assert_thinking_supported(agent_dir, Some(&level), &selector)?; + Some(level) + } + // A default level, else the parent's own, clamps to what the selector's catalog model + // supports (the level the child runs at); a model outside the catalog (a scripted + // verification model) keeps the level as given. + (level, _) => level + .or_else(|| request.parent_thinking.map(str::to_string)) + .map(|level| { + let catalog_model = selector.split_once('/').and_then(|(provider, id)| { + crate::state_getters::worker_model_registry(agent_dir) + .get_rlm_searchable_models() + .into_iter() + .find(|model| model.provider == provider && model.id == id) + .cloned() + }); + match (catalog_model, thinking_level_from_str(&level)) { + (Some(model), Some(requested)) => { + pa_ai::models::clamp_thinking_level(&model, requested) + .wire_name() + .to_string() + } + _ => level, + } + }), + }; + Ok(ResolvedHelper { + selector, + model_source, + thinking, + thinking_source: plan.thinking.source, + }) +} + +/// The startup check of the helper model a session's spawns default to (the session override, +/// else the settings file): the warning line when the catalog does not know it, `None` when it +/// does, when none is set, or when this process already warned about it. +#[must_use] +pub fn unknown_helper_model_notice( + cwd: &Path, + agent_dir: &Path, + session: &HelperDefaults, +) -> Option { + 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)) +} + +/// Whether a default helper model reference resolves against the catalog the spawns use +/// (`parent` always does). +#[must_use] +pub fn helper_model_known(agent_dir: &Path, reference: &str) -> bool { + reference == pa_core::session_engine::helper_model::INHERIT_PARENT + || resolve_child_model_unchecked(agent_dir, Some(reference), None, "subagent").is_ok() +} + /// A requested thinking level must be supported by the resolved model; /// an out-of-catalog model (a scripted verification model) passes unchecked. /// @@ -610,6 +767,188 @@ mod tests { assert!(preview.ends_with("...")); } + fn helper_layer(model: Option<&str>, thinking: Option<&str>) -> HelperDefaults { + HelperDefaults::new(model, thinking).unwrap() + } + + fn helper( + dir: &Path, + (model, thinking): (Option<&str>, Option<&str>), + session: &HelperDefaults, + settings: &HelperDefaults, + ) -> Result { + resolve_helper( + dir, + HelperRequest { + model, + thinking, + parent_model: Some("test-provider/glm-5.3"), + parent_thinking: None, + session, + settings, + }, + "subagent", + &crate::model_allowlist::DaemonAllowlist::Unrestricted, + ) + } + + /// The helper order per field: the spawn call, the session override, the settings file, + /// the parent. + #[test] + fn an_unpinned_spawn_takes_the_helper_defaults_in_order() { + let dir = tempfile::TempDir::new().unwrap(); + write_catalog(dir.path()); + let settings = helper_layer(Some("test-provider/glm-5.3-turbo"), Some("max")); + let session = helper_layer(Some("test-provider/glm-5.3"), None); + let none = HelperDefaults::default(); + // A spawn without model= gets the settings file's model; the default thinking level + // clamps to the non-reasoning catalog model. + assert_eq!( + helper(dir.path(), (None, None), &none, &settings).unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3-turbo".to_string(), + model_source: HelperSource::Settings, + thinking: Some("off".to_string()), + thinking_source: HelperSource::Settings, + } + ); + // The session override beats the settings file, field by field. + assert_eq!( + helper(dir.path(), (None, None), &session, &settings).unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3".to_string(), + model_source: HelperSource::Session, + thinking: Some("off".to_string()), + thinking_source: HelperSource::Settings, + } + ); + // The spawn call's own values beat both. + assert_eq!( + helper( + dir.path(), + (Some("glm-5.3-turbo"), Some("off")), + &session, + &settings + ) + .unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3-turbo".to_string(), + model_source: HelperSource::Spawn, + thinking: Some("off".to_string()), + thinking_source: HelperSource::Spawn, + } + ); + // Nothing configured: the parent's model, and the host keeps the parent's level. + assert_eq!( + helper(dir.path(), (None, None), &none, &none).unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3".to_string(), + model_source: HelperSource::Parent, + thinking: None, + thinking_source: HelperSource::Parent, + } + ); + } + + /// An unknown default never fails a spawn: it falls back to the parent's model. The spawn + /// call's own model and thinking level keep their strict checks. + #[test] + fn an_unknown_default_falls_back_to_the_parent_but_a_pinned_one_fails() { + let dir = tempfile::TempDir::new().unwrap(); + write_catalog(dir.path()); + let none = HelperDefaults::default(); + let unknown = helper_layer(Some("cpa-r/missing-helper"), Some("high")); + assert_eq!( + helper(dir.path(), (None, None), &none, &unknown).unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3".to_string(), + model_source: HelperSource::Parent, + thinking: Some("off".to_string()), + thinking_source: HelperSource::Settings, + } + ); + let error = helper( + dir.path(), + (Some("cpa-r/missing-helper"), None), + &none, + &none, + ) + .unwrap_err(); + assert!(error.to_string().contains("is unavailable"), "{error}"); + let error = helper(dir.path(), (None, Some("high")), &none, &none).unwrap_err(); + assert!(error.to_string().contains("not supported"), "{error}"); + // `parent` in a default layer pins the parent's model and level past the settings file. + let pinned = helper_layer(Some("parent"), Some("parent")); + let settings = helper_layer(Some("test-provider/glm-5.3-turbo"), Some("off")); + assert_eq!( + helper(dir.path(), (None, None), &pinned, &settings).unwrap(), + ResolvedHelper { + selector: "test-provider/glm-5.3".to_string(), + model_source: HelperSource::Parent, + thinking: None, + thinking_source: HelperSource::Parent, + } + ); + // The parent's own level reports the level the child runs at: clamped to the helper's + // non-reasoning model. + let resolved = resolve_helper_unchecked( + dir.path(), + HelperRequest { + model: None, + thinking: None, + parent_model: Some("scripted/faux-1"), + parent_thinking: Some("high"), + session: &HelperDefaults::default(), + settings: &helper_layer(Some("test-provider/glm-5.3"), None), + }, + "subagent", + ) + .unwrap(); + assert_eq!( + resolved, + ResolvedHelper { + selector: "test-provider/glm-5.3".to_string(), + model_source: HelperSource::Settings, + thinking: Some("off".to_string()), + thinking_source: HelperSource::Parent, + } + ); + assert!(helper_model_known(dir.path(), "parent")); + assert!(helper_model_known( + dir.path(), + "test-provider/glm-5.3-turbo" + )); + assert!(!helper_model_known(dir.path(), "cpa-r/missing-helper")); + } + + /// The daemon allowlist gates the helper model like any resolved model. + #[test] + fn the_allowlist_refuses_a_helper_model_outside_it() { + let dir = tempfile::TempDir::new().unwrap(); + write_catalog(dir.path()); + let settings = helper_layer(Some("test-provider/glm-5.3-turbo"), None); + let error = resolve_helper( + dir.path(), + HelperRequest { + model: None, + thinking: None, + parent_model: Some("prime-inference/z-ai/glm-5.3"), + parent_thinking: None, + session: &HelperDefaults::default(), + settings: &settings, + }, + "subagent", + &crate::model_allowlist::DaemonAllowlist::Allowed( + vec!["prime-inference/*".to_string()], + ), + ) + .unwrap_err(); + let refusal = error + .downcast_ref::() + .expect("typed refusal"); + assert_eq!(refusal.selector, "test-provider/glm-5.3-turbo"); + } + #[test] fn the_binding_lane_keeps_far_more_than_the_preview_cap() { // The collect envelope's full-answer lane: a fenced JSON output diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rs index 02d9cf72cb5..82339942ccf 100644 --- a/crates/pa-daemon/src/rlm_children.rs +++ b/crates/pa-daemon/src/rlm_children.rs @@ -10,6 +10,7 @@ use std::time::{Duration, Instant}; use anyhow::{anyhow, bail, Context, Result}; use pa_core::kernel::rlm_runtime::create_default_rlm_subagent_session_name; +use pa_core::session_engine::helper_model::HelperDefaults; use pa_core::session_engine::rlm_host::{ RlmChildResult, RlmCreateSessionHandle, RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle, RlmSpawnRequest, RlmSubagentActivity, RlmSubagentEntry, @@ -28,10 +29,7 @@ use pa_core::session_engine::rlm_host::{ rlm_child_session_dir, rlm_depth_limit_error, spawn_name_unavailable_error, }; -use crate::rlm_child_model::{ - assert_thinking_supported, cap_text, compact_rlm_text, resolve_child_model, rlm_child_label, - ANSWER_TEXT_MAX_CHARS, -}; +use crate::rlm_child_model::{cap_text, compact_rlm_text, rlm_child_label, ANSWER_TEXT_MAX_CHARS}; use crate::supervisor_link::SupervisorLink; use crate::util::now_ms; @@ -100,6 +98,9 @@ pub struct ParentIdentity { pub thinking: Option, /// Verification seam: create children with a scripted engine file. pub child_script: Option, + /// The session override of the helper model (`--subagent-model`, `/subagent-model`, or the + /// parent's own override for an RLM child): spawns read it before the settings file. + pub subagent_override: HelperDefaults, } impl ParentIdentity { @@ -784,6 +785,34 @@ impl SupervisorChildSessions { self.inner.identity.lock().expect("identity lock").model = Some(model); } + /// The session override of the helper model that spawns read. + /// + /// # Panics + /// + /// Panics when the identity mutex is poisoned. + #[must_use] + pub fn subagent_override(&self) -> HelperDefaults { + self.inner + .identity + .lock() + .expect("identity lock") + .subagent_override + .clone() + } + + /// Replace the session override of the helper model: the next spawn reads it. + /// + /// # Panics + /// + /// Panics when the identity mutex is poisoned. + pub fn set_subagent_override(&self, layer: HelperDefaults) { + self.inner + .identity + .lock() + .expect("identity lock") + .subagent_override = layer; + } + /// Set the session's RLM depth bound: the registry is the bound every /// spawn checks, so children respect it immediately. /// diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs index e8680162462..337ec60d9bd 100644 --- a/crates/pa-daemon/src/rlm_children/host.rs +++ b/crates/pa-daemon/src/rlm_children/host.rs @@ -2,42 +2,53 @@ //! (`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 crate::rlm_child_model::{resolve_helper, HelperRequest, ResolvedHelper}; + use super::{ - assert_thinking_supported, bail, create_default_rlm_subagent_session_name, json, now_ms, - resolve_child_model, rlm_child_label, rlm_depth_limit_error, spawn_name_unavailable_error, Arc, - ChildCloseReason, ChildObservationSource, ChildRecord, Context, DaemonCommand, Duration, - Instant, Mutex, Path, PathBuf, Result, RlmChildResult, RlmCreateSessionHandle, - RlmCreateSessionRequest, RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle, - RlmSpawnRequest, RlmSubagentEntry, RlmSubagentHost, SpawnNameReservationGuard, - SupervisorChildSessions, SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS, - RENAME_TIMEOUT_MS, + bail, create_default_rlm_subagent_session_name, json, now_ms, rlm_child_label, + rlm_depth_limit_error, spawn_name_unavailable_error, Arc, ChildCloseReason, + ChildObservationSource, ChildRecord, Context, DaemonCommand, Duration, Instant, Mutex, Path, + PathBuf, Result, RlmChildResult, RlmCreateSessionHandle, RlmCreateSessionRequest, + RlmDeleteSubagentResult, RlmHostFuture, RlmSpawnHandle, RlmSpawnRequest, RlmSubagentEntry, + RlmSubagentHost, SpawnNameReservationGuard, SupervisorChildSessions, + SupervisorChildSessionsInner, Value, KILL_TIMEOUT_MS, RENAME_TIMEOUT_MS, }; -/// Resolve the child model with the daemon `allowedModels` allowlist enforced, refusing loudly with -/// the typed error and the `model refused` event; the settings read runs on the blocking pool. -async fn resolve_child_model_allowlisted( +/// 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. +async fn resolve_child_helper( this: &SupervisorChildSessionsInner, - reference: Option<&str>, + model: Option<&str>, + thinking: Option<&str>, surface: &'static str, target: &str, -) -> Result { +) -> 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(); - let allowlist = tokio::task::spawn_blocking(move || { - crate::model_allowlist::load(Path::new(&load_cwd), &agent_dir) + let (allowlist, settings) = tokio::task::spawn_blocking(move || { + ( + crate::model_allowlist::load(Path::new(&load_cwd), &agent_dir), + HelperDefaults::load_settings(Path::new(&load_cwd), &agent_dir), + ) }) .await - .context("the allowlist load task join failed")?; - match resolve_child_model( - &this.agent_dir, - reference, - identity.model.as_deref(), - target, - &allowlist, - ) { - Ok(model) => Ok(model), + .context("the settings load task join failed")?; + let request = HelperRequest { + model, + thinking, + parent_model: identity.model.as_deref(), + parent_thinking: identity.thinking.as_deref(), + session: &identity.subagent_override, + settings: &settings, + }; + match resolve_helper(&this.agent_dir, request, target, &allowlist) { + Ok(resolved) => Ok(resolved), Err(error) => { if let Some(refusal) = error.downcast_ref::() { this.model_refusal_telemetry.note_refused( @@ -111,15 +122,16 @@ impl RlmSubagentHost for SupervisorChildSessions { let admission = async { this.assert_name_available(&name, identity.rlm_depth + 1) .await?; - let model = resolve_child_model_allowlisted( + let helper = resolve_child_helper( &this, request.model.as_deref(), + request.thinking.as_deref(), "spawn", "subagent", ) .await?; - assert_thinking_supported(&this.agent_dir, request.thinking.as_deref(), &model)?; - let thinking = request.thinking.as_deref().or(identity.thinking.as_deref()); + let model = helper.selector; + let thinking = helper.thinking; let child_dir = this.child_session_dir(&child_id, &identity)?; let cwd = identity.cwd.clone().unwrap_or_else(|| "/".to_string()); let runtime_metadata = json!({ @@ -136,7 +148,7 @@ impl RlmSubagentHost for SupervisorChildSessions { Some(&request.prompt), identity.rlm_depth + 1, &model, - thinking, + thinking.as_deref(), &cwd, &child_dir, request.spawned_by_request_id.as_deref(), @@ -191,10 +203,10 @@ impl RlmSubagentHost for SupervisorChildSessions { this.children.lock().await.push(Arc::clone(&record)); this.refresh_running().await; this.emit_child_update(&record).await; - anyhow::Ok((record, created, model)) + anyhow::Ok((record, created, model, thinking)) } .await; - let (record, created, model) = admission?; + let (record, created, model, thinking) = admission?; // The task prompt runs detached from the spawn admission: the // handle returns at registration and the child's first turn // starts after the parent's continuation request is in flight. @@ -301,6 +313,7 @@ impl RlmSubagentHost for SupervisorChildSessions { name, session_dir: created.session_dir, model, + thinking, }) }) } @@ -315,14 +328,15 @@ impl RlmSubagentHost for SupervisorChildSessions { if identity.rlm_depth != 0 { bail!("rlm.create_session is available only from a depth-0 session"); } - let model = resolve_child_model_allowlisted( + let helper = resolve_child_helper( &this, request.model.as_deref(), + request.thinking.as_deref(), "create_session", "top-level session", ) .await?; - assert_thinking_supported(&this.agent_dir, request.thinking.as_deref(), &model)?; + let model = helper.selector; // A depth-0 resident session is created exactly like a client // `create`: the shared sessions dir and the requested cwd. let cwd = match &request.cwd { @@ -333,7 +347,7 @@ impl RlmSubagentHost for SupervisorChildSessions { let sessions_dir = crate::paths::sessions_dir(&this.agent_dir)?; std::fs::create_dir_all(&sessions_dir) .with_context(|| format!("create sessions dir {}", sessions_dir.display()))?; - let thinking = request.thinking.as_deref().or(identity.thinking.as_deref()); + let thinking = helper.thinking; let created = this .launch_child( "root", @@ -341,7 +355,7 @@ impl RlmSubagentHost for SupervisorChildSessions { &request.prompt, 0, &model, - thinking, + thinking.as_deref(), &cwd.to_string_lossy(), &sessions_dir, None, @@ -368,6 +382,7 @@ impl RlmSubagentHost for SupervisorChildSessions { .unwrap_or_else(|| created.active_session_id.clone()), session_file: created.session_file.unwrap_or_default(), model, + thinking, }) }) } diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rs index 363c41a5a1f..62cdcb176d3 100644 --- a/crates/pa-daemon/src/rlm_children/lifecycle.rs +++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs @@ -99,6 +99,11 @@ impl SupervisorChildSessionsInner { if let Some(thinking) = thinking { config["thinking"] = json!(thinking); } + // The parent's helper-model override rides down the recursion: the child's own spawns + // resolve through it, and the child persists it at birth. + if let Some(config) = config.as_object_mut() { + identity.subagent_override.write_into(config); + } if let Some(parent_file) = &identity.session_file { config["parentSessionPath"] = json!(parent_file); } diff --git a/crates/pa-daemon/src/rlm_surface.rs b/crates/pa-daemon/src/rlm_surface.rs index a230bd37760..d6aa6525a3c 100644 --- a/crates/pa-daemon/src/rlm_surface.rs +++ b/crates/pa-daemon/src/rlm_surface.rs @@ -1,5 +1,6 @@ //! The RLM child-management surface: the worker arms for -//! `cancel_rlm_child`, `delete_rlm_subagent`, and `set_rlm_max_depth`. +//! `cancel_rlm_child`, `delete_rlm_subagent`, and `set_rlm_max_depth`, +//! plus the fork's `get_subagent_model_status`/`set_subagent_model`. //! Each handler answers the exact TS wire shape; the behavior lives in //! the engine seams and the supervisor-backed children registry. @@ -95,6 +96,83 @@ impl Worker { Err(error) => response_failure(None, "set_rlm_max_depth", &error.to_string(), None), } } + + /// `get_subagent_model_status` (fork-only): the helper model and thinking level this + /// session's spawns resolve to when the call names none, with the layer each came from. + pub(crate) async fn handle_get_subagent_model_status(&self) -> DaemonResponse { + if let Err(response) = self.require_created("get_subagent_model_status") { + return response; + } + // The status reads the settings file and the model catalog: off the worker's runtime. + let engine = std::sync::Arc::clone(&self.engine); + match tokio::task::spawn_blocking(move || engine.subagent_model_status()).await { + Ok(status) => response_success(None, "get_subagent_model_status", Some(status)), + Err(error) => response_failure( + None, + "get_subagent_model_status", + &format!("helper model status task failed: {error}"), + None, + ), + } + } + + /// `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 + /// `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 { + if let Err(response) = self.require_created("set_subagent_model") { + return response; + } + let field = |key: &str| payload.get(key).and_then(Value::as_str); + let layer = match pa_core::session_engine::helper_model::HelperDefaults::new( + field("model"), + field("thinking"), + ) { + Ok(layer) => layer, + Err(error) => return response_failure(None, "set_subagent_model", &error, None), + }; + // 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 + // a row too): a resume, a respawn or an idle wake re-seeds from it. A session without a + // file keeps the override for this worker only. + { + let mut core = self.core.lock().unwrap(); + 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); + } + if let Some(store) = core.store.as_mut() { + if let Err(error) = store.persist_entry("custom", row) { + return response_failure( + None, + "set_subagent_model", + &format!( + "the helper model applies to this worker but was not saved: {error}" + ), + None, + ); + } + } + } + // The status reads the settings file and the model catalog: off the worker's runtime. + let engine = std::sync::Arc::clone(&self.engine); + let status = match tokio::task::spawn_blocking(move || engine.subagent_model_status()).await + { + Ok(status) => status, + Err(error) => { + return response_failure( + None, + "set_subagent_model", + &format!("helper model status task failed: {error}"), + None, + ) + } + }; + response_success(None, "set_subagent_model", Some(status)) + } } #[cfg(test)] @@ -193,6 +271,160 @@ mod tests { ); } + /// A real-agent worker (the faux engine) over an existing session file, so the durable store + /// writes straight to it. + async fn agent_worker_at(root: &std::path::Path, extra: &serde_json::Value) -> Arc { + std::fs::create_dir_all(root).unwrap(); + let file = root.join("session.jsonl"); + if !file.exists() { + std::fs::write( + &file, + json!({ + "type": "session", "version": 3, "id": "helper-file", + "timestamp": "2026-01-01T00:00:00.000Z", "cwd": root.display().to_string(), + }) + .to_string() + + "\n", + ) + .unwrap(); + } + let config = crate::worker::WorkerConfig { + socket_path: root.join("worker.sock"), + supervisor_socket_path: std::path::PathBuf::new(), + token: "token".to_string(), + worker_instance_id: String::new(), + active_session_id: "helper-session".to_string(), + agent_dir: root.join("agent"), + recovery_journal_path: root.join("recovery.jsonl"), + telemetry_disabled: None, + script: Some(json!({ "engine": "faux", "responses": ["ack"] })), + }; + let worker = Arc::new(Worker::new(config, None)); + let mut create = json!({ + "sessionPath": file.display().to_string(), + "cwd": root.display().to_string(), + }); + if let (Some(create), Some(extra)) = (create.as_object_mut(), extra.as_object()) { + create.extend(extra.clone()); + } + let created = worker.dispatch("create", &create).await; + assert!(created.success, "create failed: {created:?}"); + assert!( + worker.agent_engine.is_some(), + "the faux script builds the agent engine" + ); + worker + } + + /// The rows the session file holds, as the layer each one sets. + fn override_rows( + root: &std::path::Path, + ) -> Vec { + std::fs::read_to_string(root.join("session.jsonl")) + .unwrap() + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|entry| entry["customType"] == "subagent_model_state") + .map(|entry| { + pa_core::session_engine::helper_model::HelperDefaults::new( + entry["data"]["model"].as_str(), + entry["data"]["thinking"].as_str(), + ) + .unwrap() + }) + .collect() + } + + /// `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. + #[tokio::test] + async fn set_subagent_model_persists_its_row_in_the_session_file() { + use pa_core::session_engine::helper_model::HelperDefaults; + let root = std::env::temp_dir().join(format!("pa-worker-helper-{}", uuid::Uuid::new_v4())); + let worker = agent_worker_at(&root, &json!({})).await; + let set = worker + .dispatch( + "set_subagent_model", + &json!({ "activeSessionId": "helper-session", "model": "parent", "thinking": "max" }), + ) + .await; + assert!(set.success, "{set:?}"); + assert_eq!( + set.data.as_ref().map(|status| status["session"].clone()), + Some(json!({ "model": "parent", "thinking": "max" })) + ); + let status = worker + .dispatch( + "get_subagent_model_status", + &json!({ "activeSessionId": "helper-session" }), + ) + .await; + assert_eq!(status.data, set.data); + let cleared = worker + .dispatch( + "set_subagent_model", + &json!({ "activeSessionId": "helper-session" }), + ) + .await; + assert!(cleared.success, "{cleared:?}"); + assert_eq!( + override_rows(&root), + vec![ + HelperDefaults::new(Some("parent"), Some("max")).unwrap(), + HelperDefaults::default(), + ] + ); + let invalid = worker + .dispatch( + "set_subagent_model", + &json!({ "activeSessionId": "helper-session", "thinking": "loud" }), + ) + .await; + assert!(!invalid.success); + assert_eq!(override_rows(&root).len(), 2); + // No settings surface, no row. + let scripted = created_worker().await; + let refused = scripted + .dispatch( + "set_subagent_model", + &json!({ "activeSessionId": "rlm-session", "model": "parent" }), + ) + .await; + assert!(!refused.success); + } + + /// An RLM child's inherited override (`subagentModel`/`subagentThinking` on its create) is + /// written once as the file's birth row and seeds the session; a respawn over a file that + /// already holds a row (a later choice) keeps that row. + #[tokio::test] + async fn an_inherited_override_is_written_once_as_the_birth_row() { + use pa_core::session_engine::helper_model::HelperDefaults; + let root = std::env::temp_dir().join(format!("pa-worker-birth-{}", uuid::Uuid::new_v4())); + let inherited = json!({ "subagentModel": "parent", "subagentThinking": "low" }); + let worker = agent_worker_at(&root, &inherited).await; + let birth = HelperDefaults::new(Some("parent"), Some("low")).unwrap(); + assert_eq!(override_rows(&root), vec![birth.clone()]); + let status = worker + .dispatch( + "get_subagent_model_status", + &json!({ "activeSessionId": "helper-session" }), + ) + .await; + assert_eq!( + status.data.map(|status| status["session"].clone()), + Some(json!({ "model": "parent", "thinking": "low" })) + ); + // A create over a file that already holds a row (a respawn replaying the keys; a copy, + // since the first worker keeps the file's runtime lease) adds no row. + let replay = root.join("replay"); + std::fs::create_dir_all(&replay).unwrap(); + std::fs::copy(root.join("session.jsonl"), replay.join("session.jsonl")).unwrap(); + let replayed = agent_worker_at(&replay, &inherited).await; + assert_eq!(override_rows(&replay), vec![birth]); + drop((worker, replayed)); + } + #[tokio::test] async fn missing_required_fields_fail() { let worker = created_worker().await; diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs index 5bb6c124878..06a4938b3c1 100644 --- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs +++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs @@ -320,6 +320,9 @@ impl Supervisor { "promptTemplates", "autonomous", "executionMode", + // 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, ] { 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 8aef0523ff0..49f2b277f70 100644 --- a/crates/pa-daemon/src/worker/commands.rs +++ b/crates/pa-daemon/src/worker/commands.rs @@ -171,6 +171,8 @@ impl Worker { // The engine call blocks on the engine runtime, so it // runs on a blocking thread like every other engine call. "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, "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/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rs index cefe30a9c5c..539a63778ae 100644 --- a/crates/pa-daemon/src/worker/create.rs +++ b/crates/pa-daemon/src/worker/create.rs @@ -205,6 +205,12 @@ impl Worker { .get("childScript") .and_then(Value::as_str) .map(str::to_string); + // The helper-model override an RLM parent passes down (`subagentModel`/ + // `subagentThinking`); the durable create replays it. + let subagent_override = payload + .as_object() + .map(pa_core::session_engine::helper_model::HelperDefaults::from_create_config) + .unwrap_or_default(); // Set by the fresh-path arm when the name landed in its single rewrite: // the shared name persist must not append a second `session_info` line. @@ -558,6 +564,28 @@ impl Worker { // record only once the disclosure is durable (a requested record with no // disclosure row is vacuously durable; no requested record adds no key). let mut interrupted_compaction_persisted = interrupted_compaction_requested; + // An RLM child's inherited helper-model override is its birth row: a resume, an idle + // wake or a reopen of the child's own file reads it back (the durable create keys replay + // only on a respawn), and a later `set_subagent_model` row supersedes it. A file that + // already holds a row keeps it; a failed write fails the create. + if !subagent_override.is_empty() && !store.path.as_os_str().is_empty() { + let path = store.path.to_string_lossy().to_string(); + if pa_core::session_engine::helper_model::persisted_session_override(Some(&path)) + .is_none() + { + if let Err(error) = store.persist_entry( + "custom", + pa_core::session_engine::helper_model::session_override_row(&subagent_override), + ) { + return response_failure( + None, + "create", + &format!("the inherited helper-model override was not saved: {error:#}"), + None, + ); + } + } + } // The core lock stays inside this block: everything after it may await, // and a std MutexGuard must never ride an await point. let (summary, rlm_depth) = { @@ -636,6 +664,7 @@ impl Worker { thinking, child_script: child_script.clone(), semantic_spawn, + subagent_override, }) { return response_failure(None, "create", &error.to_string(), None); } diff --git a/crates/pa-daemon/src/worker/lifecycle.rs b/crates/pa-daemon/src/worker/lifecycle.rs index 1b596685467..de7ecaf0d8f 100644 --- a/crates/pa-daemon/src/worker/lifecycle.rs +++ b/crates/pa-daemon/src/worker/lifecycle.rs @@ -293,6 +293,8 @@ impl Worker { child_script, // A TS replacement runtime has no semantic spawn. semantic_spawn: None, + // The moved-to session's own persisted override (if any) applies. + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }) { Ok(()) => self.reseed_rlm_children().await, Err(error) => eprintln!("pa-daemon: replacement identity rebind failed: {error:#}"), diff --git a/crates/pa-daemon/tests/agent_family_e2e.rs b/crates/pa-daemon/tests/agent_family_e2e.rs index 1e88ffc25c0..c60373425d6 100644 --- a/crates/pa-daemon/tests/agent_family_e2e.rs +++ b/crates/pa-daemon/tests/agent_family_e2e.rs @@ -415,6 +415,7 @@ async fn parent_child_agent_message_round_trip_end_to_end() { session_file: Some(parent_session_file), thinking: None, child_script: Some(child_script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { @@ -744,6 +745,7 @@ async fn family_edges_never_cross_families_end_to_end() { session_file: Some(file.clone()), thinking: None, child_script: Some(kid_script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { @@ -884,6 +886,7 @@ async fn family_edges_never_cross_families_end_to_end() { session_file: Some(kid_a_file.clone()), thinking: None, child_script: Some(kid_script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let grandkid_handle = kid_children .spawn(RlmSpawnRequest { @@ -1202,6 +1205,7 @@ async fn parent_renames_a_child_end_to_end() { session_file: Some(parent_session_file.clone()), thinking: None, child_script: Some(child_script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { diff --git a/crates/pa-daemon/tests/agents_view_roster_e2e.rs b/crates/pa-daemon/tests/agents_view_roster_e2e.rs index db1feca1324..826fca938e8 100644 --- a/crates/pa-daemon/tests/agents_view_roster_e2e.rs +++ b/crates/pa-daemon/tests/agents_view_roster_e2e.rs @@ -416,6 +416,7 @@ async fn rlm_children_key_the_roster_by_parent_path_and_child_id() { session_file: Some(parent_file.to_string_lossy().to_string()), thinking: None, child_script: Some(script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children diff --git a/crates/pa-daemon/tests/command_breadth.rs b/crates/pa-daemon/tests/command_breadth.rs index e3ebaf05f55..079b1a58603 100644 --- a/crates/pa-daemon/tests/command_breadth.rs +++ b/crates/pa-daemon/tests/command_breadth.rs @@ -446,6 +446,14 @@ const WIRE_FIXTURES: &[(&str, &str)] = &[ "set_rlm_max_depth", r#"{"type": "set_rlm_max_depth", "activeSessionId": "sess", "maxDepth": 2}"#, ), + ( + "get_subagent_model_status", + r#"{"type": "get_subagent_model_status", "activeSessionId": "sess"}"#, + ), + ( + "set_subagent_model", + r#"{"type": "set_subagent_model", "activeSessionId": "sess", "model": "cpa-r/deepseek-flash-1017", "thinking": "max"}"#, + ), ( "rename_saved_session", r#"{"type": "rename_saved_session", "sessionPath": "/tmp/x.jsonl", "name": "x"}"#, @@ -563,6 +571,9 @@ fn known_command_types_match_the_ts_list() { | "list_persistent_shells" | "tail_persistent_shell" | "kill_persistent_shell" + // Oneiron fork: the helper-model override. + | "get_subagent_model_status" + | "set_subagent_model" ), "unexpected non-TS command type: {extra}" ); diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rs index b5f890afa39..133fea41afd 100644 --- a/crates/pa-daemon/tests/idle_passivation_e2e.rs +++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs @@ -287,6 +287,7 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_agent_message( session_file: Some(parent_session_file), thinking: None, child_script: Some(child_script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { @@ -604,6 +605,7 @@ async fn a_parent_rename_after_a_revival_and_second_passivation_reaches_the_chil session_file: Some(parent_session_file), thinking: None, child_script: Some(child_script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { diff --git a/crates/pa-daemon/tests/launch_env_e2e.rs b/crates/pa-daemon/tests/launch_env_e2e.rs index f1f0b13471e..fc86e09a43d 100644 --- a/crates/pa-daemon/tests/launch_env_e2e.rs +++ b/crates/pa-daemon/tests/launch_env_e2e.rs @@ -538,6 +538,7 @@ async fn an_rlm_spawn_child_inherits_the_parent_worker_env() { session_file: Some(agent_dir.join("parent.jsonl").to_string_lossy().to_string()), thinking: None, child_script: Some(script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { diff --git a/crates/pa-daemon/tests/rlm_children_e2e.rs b/crates/pa-daemon/tests/rlm_children_e2e.rs index 614f34b8b6d..e99ffecd81b 100644 --- a/crates/pa-daemon/tests/rlm_children_e2e.rs +++ b/crates/pa-daemon/tests/rlm_children_e2e.rs @@ -209,6 +209,7 @@ fn children(socket: &Path, agent_dir: &Path, script: &Path, depth: u32) -> Super session_file: Some(agent_dir.join("parent.jsonl").to_string_lossy().to_string()), thinking: None, child_script: Some(script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); sessions.set_parent_session_name(Some("parent-name".to_string())); sessions @@ -616,6 +617,75 @@ async fn rlm_recursion_bound_is_enforced() { ); } +/// The helper model: a spawn that names no model runs on the settings file's +/// `subagentDefaultModel` instead of the parent's model, the session override beats the +/// settings file, and the spawn call's own model beats both (the handle reports what the child +/// runs on). +#[tokio::test] +async fn an_unpinned_spawn_runs_on_the_helper_model() { + 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": "session-pick", "name": "Session", "contextWindow": 1000, "maxTokens": 100 } + ] + } + } + }) + .to_string(), + ) + .expect("models.json"); + std::fs::write( + agent_dir.join("settings.json"), + json!({ "subagentDefaultModel": "test-provider/helper-flash" }).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 handle = children + .spawn(spawn_request("helper-a", "use the helper")) + .await + .expect("spawn on the settings default"); + assert_eq!(handle.model, "test-provider/helper-flash"); + assert_eq!(handle.thinking, None); + + children.set_subagent_override( + pa_core::session_engine::helper_model::HelperDefaults::new( + Some("test-provider/session-pick"), + Some("off"), + ) + .expect("override"), + ); + let handle = children + .spawn(spawn_request("helper-b", "use the session pick")) + .await + .expect("spawn on the session override"); + assert_eq!(handle.model, "test-provider/session-pick"); + assert_eq!(handle.thinking.as_deref(), Some("off")); + + let handle = children + .spawn(RlmSpawnRequest { + model: Some("test-provider/helper-flash".to_string()), + ..spawn_request("helper-c", "pinned") + }) + .await + .expect("spawn on the pinned model"); + assert_eq!(handle.model, "test-provider/helper-flash"); + 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/rlm_roster_walk_e2e.rs b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs index 0c5edfb00ff..6a959560baa 100644 --- a/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs +++ b/crates/pa-daemon/tests/rlm_roster_walk_e2e.rs @@ -351,6 +351,7 @@ async fn subscribe_after_spawn_then_shutdown_seeds_the_passive_child() { session_file: Some(parent_file.clone()), thinking: None, child_script: Some(script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); let handle = children .spawn(RlmSpawnRequest { diff --git a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs index b51f200ce0f..d66348a7563 100644 --- a/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs +++ b/crates/pa-daemon/tests/rlm_spawn_replacement_e2e.rs @@ -221,6 +221,7 @@ fn children(socket: &Path, agent_dir: &Path, script: &Path) -> SupervisorChildSe session_file: Some(agent_dir.join("parent.jsonl").to_string_lossy().to_string()), thinking: None, child_script: Some(script.to_string_lossy().to_string()), + subagent_override: pa_core::session_engine::helper_model::HelperDefaults::default(), }); sessions } diff --git a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs index 471f1299cea..02c3ae25fa3 100644 --- a/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs +++ b/crates/pa-daemon/tests/supervisor_e2e/lifecycle.rs @@ -20,7 +20,7 @@ fn supervisor_end_to_end_scripted_session_lifecycle() { // TS-main bundle reports the same schema id at the hello). The combined // Rust schema is revision 33 and retains the fork's revision-31 // capabilities (`worker_startup_failure`, `session_tool_selection`, - // `session_policy`). + // `session_policy`), plus the fork's capability-gated `subagent_model`. assert_eq!( hello["protocol"], serde_json::json!({ @@ -72,6 +72,7 @@ fn supervisor_end_to_end_scripted_session_lifecycle() { "worker_startup_failure", "session_tool_selection", "session_policy", + "subagent_model", ]) ); diff --git a/crates/pa-tui/src/client_settings.rs b/crates/pa-tui/src/client_settings.rs index 2ca34ea0f82..541b4826396 100644 --- a/crates/pa-tui/src/client_settings.rs +++ b/crates/pa-tui/src/client_settings.rs @@ -18,6 +18,31 @@ pub trait ClientSettings: Send + Sync { anyhow::bail!("Harness refinement settings are unavailable") } + /// `subagentDefaultModel`: the helper model spawned agents run on when the spawn call names + /// none (`provider/model-id`; unset inherits the parent's model). + fn subagent_default_model(&self) -> Option { + None + } + /// Persist (or, with `None`, remove) `subagentDefaultModel` globally. + /// + /// # Errors + /// Returns an error if the settings store fails or is unavailable. + fn set_subagent_default_model(&self, _model: Option<&str>) -> Result<()> { + anyhow::bail!("Helper model settings are unavailable") + } + /// `subagentDefaultThinking`: the helper thinking level (a level name; unset inherits the + /// parent's level). + fn subagent_default_thinking(&self) -> Option { + None + } + /// Persist (or, with `None`, remove) `subagentDefaultThinking` globally. + /// + /// # Errors + /// Returns an error for an unknown level or failed persistence. + fn set_subagent_default_thinking(&self, _level: Option<&str>) -> Result<()> { + anyhow::bail!("Helper model settings are unavailable") + } + /// Automatic compaction percentage ceiling; output headroom may trigger earlier. fn compaction_threshold_percent(&self) -> f64; /// Persist the percentage globally. diff --git a/crates/pa-tui/src/interactive.rs b/crates/pa-tui/src/interactive.rs index 827130dd95c..bd2c5bde345 100644 --- a/crates/pa-tui/src/interactive.rs +++ b/crates/pa-tui/src/interactive.rs @@ -110,6 +110,11 @@ pub struct ModelSelection { pub api_key: Option, /// The requested thinking level (`--thinking`); the worker clamps it to the supported levels. pub thinking: Option, + /// The launch helper model for spawned agents (`--subagent-model`, `PRIME_SUBAGENT_MODEL`): + /// set on the opened session before the first prompt, like `/subagent-model`. + pub subagent_model: Option, + /// The launch helper thinking level (`--subagent-thinking`, `PRIME_SUBAGENT_THINKING`). + pub subagent_thinking: Option, } /// Adoption telemetry for interactive-view interactions: the composition diff --git a/crates/pa-tui/src/interactive/run.rs b/crates/pa-tui/src/interactive/run.rs index da720f37dbf..bb978540433 100644 --- a/crates/pa-tui/src/interactive/run.rs +++ b/crates/pa-tui/src/interactive/run.rs @@ -723,6 +723,9 @@ async fn run_interactive_surface( ) .await; } + // The helper model for spawned agents: the launch override lands before the first prompt, + // and an unknown default warns (fork-only). + session.apply_launch_subagent_model(&mut view).await; // The once-per-installation telemetry disclosure (TS // agent-session-services): rendered as an info row here — the alt // screen hides any pre-TUI stderr print, so the row is the only diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rs index 9371c1c4e02..f00e375f6b1 100644 --- a/crates/pa-tui/src/session_ui/commands.rs +++ b/crates/pa-tui/src/session_ui/commands.rs @@ -784,6 +784,10 @@ impl SessionUi { self.handle_rlm_max_depth_command(view, &resolved.args) .await; } + "subagent-model" => { + self.handle_subagent_model_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 6f03da734f2..2a7ae694614 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/reload command surface. The +//! confirm flow, and the fast/rlm-max-depth/subagent-model/reload command surface. The //! fullscreen toggle is retired (the operator's 2026-09-28 ruling removed //! the setting and the command). use super::{ @@ -245,6 +245,12 @@ impl SessionUi { values.theme = settings.theme().unwrap_or_else(|| "prime".to_string()); // The tier row preselects the saved default instead of the struct default. values.default_service_tier = settings.default_service_tier(); + values.subagent_model = settings + .subagent_default_model() + .unwrap_or_else(|| crate::settings_menu::HELPER_PARENT.to_string()); + values.subagent_thinking = settings + .subagent_default_thinking() + .unwrap_or_else(|| crate::settings_menu::HELPER_PARENT.to_string()); } else { values.show_images = true; values.auto_resize_images = true; @@ -258,7 +264,24 @@ impl SessionUi { values.theme = "prime".to_string(); // No settings seam: the tier row reads "default", never a blank value. values.default_service_tier = "default".to_string(); + values.subagent_model = crate::settings_menu::HELPER_PARENT.to_string(); + values.subagent_thinking = crate::settings_menu::HELPER_PARENT.to_string(); } + // The helper-model choices: `parent`, the saved value (even off-catalog, so the row's + // value stays selectable), then the signed-in providers' catalog models. + let mut helper_models = vec![crate::settings_menu::HELPER_PARENT.to_string()]; + if !helper_models.contains(&values.subagent_model) { + helper_models.push(values.subagent_model.clone()); + } + for model in &self.model_catalog { + let selector = format!("{}/{}", model.provider, model.id); + if self.model_configured_providers.contains(&model.provider) + && !helper_models.contains(&selector) + { + helper_models.push(selector); + } + } + values.available_helper_models = helper_models; // This surface ships the builtin themes. values.available_themes = pa_types::themes::BUILTIN_THEME_NAMES .iter() @@ -579,6 +602,20 @@ impl SessionUi { "thinking" => { self.apply_thinking_level(value, view).await; } + "subagent-model" | "subagent-thinking" => { + // `parent` removes the settings default; spawns read the file at spawn time. + let saved = (value != crate::settings_menu::HELPER_PARENT).then_some(value); + if let Some(settings) = &self.client_settings { + let result = if id == "subagent-model" { + settings.set_subagent_default_model(saved) + } else { + settings.set_subagent_default_thinking(saved) + }; + if let Err(error) = result { + self.error_row(&format!("{error:#}"), view); + } + } + } "theme" => { if let Some(settings) = &self.client_settings { if let Err(error) = settings.set_theme(value) { @@ -766,6 +803,136 @@ impl SessionUi { } } + // Helper model (/subagent-model) + + /// 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 + /// the session's override immediately, never touching the running turn (`default` leaves a + /// field to the settings file, `parent` keeps the spawning agent's value). + pub(super) async fn handle_subagent_model_command(&mut self, view: &mut AgentView, args: &str) { + const USAGE: &str = + "Usage: /subagent-model [|parent|default] [|parent]"; + let tokens: Vec<&str> = args.split_whitespace().collect(); + let field = |token: &str| (token != "default").then(|| token.to_string()); + let command = match tokens.as_slice() { + [] => DaemonCommand::GetSubagentModelStatus { + id: None, + active_session_id: self.active_session_id.clone(), + rest: Map::default(), + }, + [model, thinking @ ..] if thinking.len() <= 1 => { + let thinking = thinking.first().copied(); + if let Some(level) = thinking.filter(|level| { + !matches!(*level, "default" | crate::settings_menu::HELPER_PARENT) + && pa_types::ai::thinking_level_from_str(level).is_none() + }) { + self.note_as( + &format!("Unknown thinking level \"{level}\". {USAGE}"), + StatusKind::Warning, + view, + ); + return; + } + DaemonCommand::SetSubagentModel { + id: None, + active_session_id: self.active_session_id.clone(), + model: field(model), + thinking: thinking.and_then(field), + rest: Map::default(), + } + } + _ => { + self.note_as(USAGE, StatusKind::Warning, view); + return; + } + }; + self.subagent_model_request(command, view).await; + } + + /// 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. + 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 + .client_settings + .as_ref() + .is_some_and(|settings| settings.subagent_default_model().is_some()); + if !launch && !configured { + return; + } + let command = if launch { + DaemonCommand::SetSubagentModel { + id: None, + active_session_id: self.active_session_id.clone(), + model, + thinking, + rest: Map::default(), + } + } else { + DaemonCommand::GetSubagentModelStatus { + id: None, + active_session_id: self.active_session_id.clone(), + rest: Map::default(), + } + }; + self.subagent_model_request(command, view).await; + } + + /// 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) + { + self.note_as( + "The running daemon does not support helper-model overrides (no subagent_model capability); stop it so a current one starts", + StatusKind::Warning, + view, + ); + return; + } + let status = match self + .bounded_request(Duration::from_millis(UI_REQUEST_TIMEOUT_MS), command) + .await + { + Ok(status) => status, + Err(error) => { + self.error_row(&format!("{error:#}"), view); + return; + } + }; + let described = |value: &str, source: &str, fallback: &str| match status + .get(value) + .and_then(Value::as_str) + { + Some(value) => format!( + "{value} ({})", + status + .get(source) + .and_then(Value::as_str) + .unwrap_or_default() + ), + None => fallback.to_string(), + }; + 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); + 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" + ), + StatusKind::Warning, + view, + ); + } + } + /// The Ctrl+O cycle saves the new level as the global `chatDetail` setting, so every later chat /// opens at it. A failed save lands only in the settings store's diagnostics. pub(crate) fn save_chat_detail(&self, view: &AgentView) { diff --git a/crates/pa-tui/src/settings_menu/menu_tests.rs b/crates/pa-tui/src/settings_menu/menu_tests.rs index 368b6f0d15f..d83b5a39410 100644 --- a/crates/pa-tui/src/settings_menu/menu_tests.rs +++ b/crates/pa-tui/src/settings_menu/menu_tests.rs @@ -58,7 +58,13 @@ fn tabs_partition_the_settings_rows() { ), ( "Models", - vec!["thinking", "transport", "default-service-tier"] + vec![ + "thinking", + "transport", + "default-service-tier", + "subagent-model", + "subagent-thinking" + ] ), ( "Display", @@ -223,6 +229,79 @@ fn enter_opens_the_service_tier_submenu_preselected_and_selection_applies() { .any(|row| row.contains("Enter/Space change · Esc close"))); } +#[test] +fn the_helper_model_rows_persist_a_catalog_model_and_a_thinking_level() { + let values = SettingsCurrentValues { + subagent_model: "cpa-r/deepseek-flash-1017".to_string(), + available_helper_models: vec![ + HELPER_PARENT.to_string(), + "cpa-r/deepseek-flash-1017".to_string(), + "cpa-r/kimi-k3.1".to_string(), + ], + subagent_thinking: HELPER_PARENT.to_string(), + ..Default::default() + }; + let mut menu = SettingsMenu::new(settings_menu_rows(&values)); + // 2 jumps to the Models tab; three downs reach the helper-model row + // (thinking, transport, default-service-tier, subagent-model). + menu.handle_key("2", &kb()); + for _ in 0..3 { + menu.handle_key("down", &kb()); + } + let text = render_text(&menu); + assert!(text + .iter() + .any(|row| row.contains("Helper model") && row.contains("cpa-r/deepseek-flash-1017"))); + assert_eq!(menu.handle_key("enter", &kb()), SettingsMenuAction::None); + let text = render_text(&menu); + assert!(text.iter().any(|row| row.contains("Helper Model"))); + assert!(text + .iter() + .any(|row| row.contains("parent") && row.contains("The spawning agent's model"))); + // The submenu preselects the saved model; one down picks the next catalog model. + menu.handle_key("down", &kb()); + assert_eq!( + menu.handle_key("enter", &kb()), + SettingsMenuAction::Change { + id: "subagent-model", + value: "cpa-r/kimi-k3.1".to_string() + } + ); + // Back on the list: `parent` (no settings default) is the first choice. + assert_eq!(menu.handle_key("enter", &kb()), SettingsMenuAction::None); + menu.handle_key("down", &kb()); + assert_eq!( + menu.handle_key("enter", &kb()), + SettingsMenuAction::Change { + id: "subagent-model", + value: HELPER_PARENT.to_string() + } + ); + // The thinking row cycles from `parent` through the levels in place. + menu.handle_key("down", &kb()); + assert_eq!( + menu.handle_key("right", &kb()), + SettingsMenuAction::Change { + id: "subagent-thinking", + value: "off".to_string() + } + ); + assert_eq!( + menu.handle_key("left", &kb()), + SettingsMenuAction::Change { + id: "subagent-thinking", + value: HELPER_PARENT.to_string() + } + ); + assert_eq!( + menu.handle_key("left", &kb()), + SettingsMenuAction::Change { + id: "subagent-thinking", + value: "max".to_string() + } + ); +} + #[test] fn typing_filters_the_active_tab_and_esc_cancels() { let mut menu = menu(); diff --git a/crates/pa-tui/src/settings_menu/mod.rs b/crates/pa-tui/src/settings_menu/mod.rs index ee84ac102a1..21ff30e1f4b 100644 --- a/crates/pa-tui/src/settings_menu/mod.rs +++ b/crates/pa-tui/src/settings_menu/mod.rs @@ -35,8 +35,26 @@ pub enum SettingsSubmenu { Warnings, /// "Default Service Tier" (TS `SERVICE_TIER_OPTIONS`). ServiceTier, + /// "Helper Model" (fork-only): `parent` plus the catalog selectors of the signed-in + /// providers, for `subagentDefaultModel`. + HelperModel { models: Vec }, } +/// The helper-model rows' value for "no settings default": spawns use the parent's value. +pub const HELPER_PARENT: &str = "parent"; + +/// The helper-thinking row's values: `parent` (no settings default) and the thinking levels. +const HELPER_THINKING_CHOICES: [&str; 8] = [ + HELPER_PARENT, + "off", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", +]; + /// The service-tier descriptions the TS settings submenu lists. #[must_use] pub fn service_tier_description(tier: &str) -> &'static str { @@ -332,6 +350,24 @@ pub fn settings_menu_rows(current: &SettingsCurrentValues) -> Vec, pub theme: String, pub available_themes: Vec, + /// `subagentDefaultModel`, [`HELPER_PARENT`] when unset. + pub subagent_model: String, + /// The helper-model submenu's choices: [`HELPER_PARENT`] first. + pub available_helper_models: Vec, + /// `subagentDefaultThinking`, [`HELPER_PARENT`] when unset. + pub subagent_thinking: String, } impl SettingsMenu { @@ -537,12 +579,16 @@ impl SettingsMenu { }; let row = &mut self.rows[row_index]; if let Some(kind) = row.submenu.clone() { - // The tier submenu preselects the row's current tier. + // The tier and helper-model submenus preselect the row's current value. let selected = match &kind { SettingsSubmenu::ServiceTier => SERVICE_TIER_CHOICES .iter() .position(|tier| *tier == row.current) .unwrap_or(0), + SettingsSubmenu::HelperModel { models } => models + .iter() + .position(|model| *model == row.current) + .unwrap_or(0), _ => 0, }; self.sub = Some(SubmenuState { @@ -592,6 +638,7 @@ impl SettingsMenu { SettingsSubmenu::Theme { themes } => themes.len(), SettingsSubmenu::Warnings => 1, SettingsSubmenu::ServiceTier => SERVICE_TIER_CHOICES.len(), + SettingsSubmenu::HelperModel { models } => models.len(), }; if kb.matches(key, "tui.select.up") { if options > 0 { @@ -614,24 +661,12 @@ impl SettingsMenu { if kb.matches(key, "tui.select.confirm") || key == "space" { let row_id = self.rows[sub.row].id; let value = match &sub.kind { - SettingsSubmenu::Thinking { levels } => { - levels - .get(sub.selected) - .cloned() - .map(|level| SettingsMenuAction::Change { - id: row_id, - value: level, - }) - } - SettingsSubmenu::Theme { themes } => { - themes - .get(sub.selected) - .cloned() - .map(|name| SettingsMenuAction::Change { - id: row_id, - value: name, - }) - } + SettingsSubmenu::Thinking { levels: values } + | SettingsSubmenu::Theme { themes: values } + | SettingsSubmenu::HelperModel { models: values } => values + .get(sub.selected) + .cloned() + .map(|value| SettingsMenuAction::Change { id: row_id, value }), SettingsSubmenu::Warnings => Some(SettingsMenuAction::Change { id: "warnings-anthropic-extra-usage", value: if sub.selected == 0 { @@ -846,6 +881,18 @@ impl SettingsMenu { .map(|tier| (tier.to_string(), Some(service_tier_description(tier)))) .collect(), ), + SettingsSubmenu::HelperModel { models } => ( + "Helper Model", + "Model for spawned agents when the spawn names none", + models + .iter() + .map(|model| { + let description = + (model == HELPER_PARENT).then_some("The spawning agent's model"); + (model.clone(), description) + }) + .collect(), + ), }; let mut lines: Vec = Vec::new(); // The list view's full-width top rule stays over the submenu too (the diff --git a/crates/pa-tui/src/settings_menu/tabs.rs b/crates/pa-tui/src/settings_menu/tabs.rs index 3a64f04b940..de65393b4d4 100644 --- a/crates/pa-tui/src/settings_menu/tabs.rs +++ b/crates/pa-tui/src/settings_menu/tabs.rs @@ -28,7 +28,13 @@ const TAB_LAYOUT: &[TabLayout] = &[ }, TabLayout { name: "Models", - ids: &["thinking", "transport", "default-service-tier"], + ids: &[ + "thinking", + "transport", + "default-service-tier", + "subagent-model", + "subagent-thinking", + ], }, TabLayout { name: "Display", diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs index fb6bcaa3780..670a29adc8f 100644 --- a/crates/pa-types/src/daemon/command.rs +++ b/crates/pa-types/src/daemon/command.rs @@ -1123,6 +1123,28 @@ pub enum DaemonCommand { #[serde(flatten)] rest: JsonMap, }, + /// Fork-only (capability `subagent_model`): the helper model and thinking level the + /// session's spawns resolve to when the call names none, with the layer each came from. + GetSubagentModelStatus { + #[serde(default, skip_serializing_if = "Option::is_none")] + id: Option, + active_session_id: String, + #[serde(flatten)] + rest: JsonMap, + }, + /// Fork-only (capability `subagent_model`): replace the session's helper-model override. + /// An absent field leaves it to the settings file; `parent` keeps the parent's value. + SetSubagentModel { + #[serde(default, skip_serializing_if = "Option::is_none")] + id: Option, + active_session_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + thinking: Option, + #[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 d256acf602e..a71c33d5328 100644 --- a/crates/pa-types/src/daemon/mod.rs +++ b/crates/pa-types/src/daemon/mod.rs @@ -42,6 +42,11 @@ pub const DAEMON_PROTOCOL_VERSION: u64 = 7; pub const DAEMON_SCHEMA_REVISION: u64 = 33; pub const DAEMON_SCHEMA_ID: &str = "protocol-7-schema-33-20261024a1f7"; +/// Fork-only server capability (no schema bump: a client checks it before it sends either +/// command): the daemon answers `get_subagent_model_status` and `set_subagent_model`, the +/// session's helper-model override, and its RLM creates carry `subagentModel`/`subagentThinking`. +pub const SUBAGENT_MODEL_CAPABILITY: &str = "subagent_model"; + 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 7d70510fb40..85d56e8862d 100644 --- a/crates/pa-types/src/daemon/plane.rs +++ b/crates/pa-types/src/daemon/plane.rs @@ -88,6 +88,9 @@ pub fn command_plane(command_type: &str) -> DaemonCommandPlane { | "export_jsonl" | "get_rlm_max_depth_status" | "set_rlm_max_depth" + // Oneiron fork: the helper-model override serves one session. + | "get_subagent_model_status" + | "set_subagent_model" | "get_session_context" | "get_session_tree" | "get_user_messages_for_forking" @@ -149,6 +152,8 @@ const READ_ONLY_DAEMON_COMMANDS: &[&str] = &[ "get_system_prompt", "get_rlm_max_depth_status", "get_tool_definition", + // Oneiron fork. + "get_subagent_model_status", ]; /// TS `isDaemonMutatingCommand`: mutates unless in the read-only table. diff --git a/crates/pa-types/src/slash_commands.rs b/crates/pa-types/src/slash_commands.rs index cddab2721e6..099387f6062 100644 --- a/crates/pa-types/src/slash_commands.rs +++ b/crates/pa-types/src/slash_commands.rs @@ -73,6 +73,7 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: &[BuiltinSlashCommand] = &[ BuiltinSlashCommand { name: "goal", description: "Set or view a persistent goal; supports pause, resume, and clear", execution: SlashCommandExecution::Session, argument_hint: Some("[objective]"), aliases: &[], takes_argument: true }, 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: "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 new file mode 100644 index 00000000000..450af4e71fd --- /dev/null +++ b/docs/oneiron/HELPER-MODEL.md @@ -0,0 +1,95 @@ +# Helper model for spawned agents (Oneiron fork) + +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. + +## Resolution order + +Each field (model, thinking level) resolves on its own. The first layer that names a value wins: + +1. the spawn call: `rlm.spawn(..., model=..., thinking=...)`; +2. the session override: `--subagent-model`/`--subagent-thinking`, the env vars + `PRIME_SUBAGENT_MODEL`/`PRIME_SUBAGENT_THINKING`, or `/subagent-model` in the TUI; +3. the settings file: `subagentDefaultModel`/`subagentDefaultThinking`; +4. the parent's own model and thinking level (upstream behavior). + +The value `parent` at layer 2 or 3 stops the walk and keeps the parent's value. + +- The spawn call's own values keep their strict checks: an unknown model or an unsupported + thinking level fails the spawn. +- 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 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 +`rlm.create_session` (`crates/pa-daemon/src/rlm_children/host.rs`) and the direct print +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. + +## Settings file + +`~/.prime/agent/settings.json` (the Rust side-by-side install reads `~/.prime/agent-rs/`): + +| Key | Type | Default | Meaning | +|---|---|---|---| +| `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) | + +Example: `{"subagentDefaultModel": "cpa-r/deepseek-flash-1017", "subagentDefaultThinking": "max"}`. + +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. + +## Session override + +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 "..." +``` + +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. + +## 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. +- `/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. +- `/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. + +## Visibility + +- The `rlm.spawn` and `rlm.create_session` handles carry `model` and `thinking`: the level the + 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. + +## 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. diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py index 376e1e02fdc..abcf5abc185 100644 --- a/prime-agent-runtime/src/rlm/__init__.py +++ b/prime-agent-runtime/src/rlm/__init__.py @@ -21,6 +21,7 @@ class RLMSpawnHandle: name: str session_dir: Path model: str + thinking: str | None = None @dataclass(frozen=True) @@ -30,6 +31,7 @@ class RLMCreateSessionHandle: name: str session_file: Path model: str + thinking: str | None = None @dataclass(frozen=True) @@ -105,11 +107,13 @@ def _spawn_handle_from_payload(payload: Any) -> RLMSpawnHandle: model = payload.get("model") if not all(isinstance(value, str) and value for value in (child_id, name, session_dir, model)): raise RuntimeError("rlm.spawn returned an invalid spawn handle") + thinking = payload.get("thinking") return RLMSpawnHandle( rlm_child_id=child_id, name=name, session_dir=Path(session_dir), model=model, + thinking=thinking if isinstance(thinking, str) and thinking else None, ) @@ -123,12 +127,14 @@ def _create_session_handle_from_payload(payload: Any) -> RLMCreateSessionHandle: model = payload.get("model") if not all(isinstance(value, str) and value for value in (active_session_id, session_id, name, session_file, model)): raise RuntimeError("rlm.create_session returned an invalid payload structure") + thinking = payload.get("thinking") return RLMCreateSessionHandle( active_session_id=active_session_id, session_id=session_id, name=name, session_file=Path(session_file), model=model, + thinking=thinking if isinstance(thinking, str) and thinking else None, ) @@ -177,9 +183,13 @@ async def spawn( """Spawn a recursive Prime Agent child and return once its task is admitted. ``name`` is required and must be unique among siblings. - ``model`` selects a child with an exact ``provider/model`` selector. + ``model`` selects a child with an exact ``provider/model`` selector; omitted, the child runs + on the configured helper model (the session's override, then settings + ``subagentDefaultModel``), else the parent model. ``thinking`` sets the child reasoning level (e.g. 'off', 'low', 'medium', 'high'); - defaults to the parent level; levels invalid for the resolved model fail the spawn. + omitted, the helper thinking level applies (session override, then + ``subagentDefaultThinking``), else the parent level; levels invalid for the resolved model + fail the spawn. The handle's ``model`` and ``thinking`` report what the child runs on. """ if not isinstance(prompt, str): raise TypeError(f"prompt must be str, got {type(prompt).__name__}")