Skip to main content

agentmux_srv_core/backend/
agent_runtime.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The runtime flags a pane's CLI is given, decided in srv.
5//!
6//! The runtime menu shows `agent:runtime` block meta; the process runs on
7//! `cmd:args`. The frontend keeps the two in step (`buildPaneArgs`), but
8//! `agent.open` — MCP `OpenAgent`, layouts, `agent.define` + open — builds a
9//! pane without the frontend. It wrote `cmd:args` from the catalog alone and no
10//! `agent:runtime`, so the pane's CLI ran on its own default model (Opus 5.5 /
11//! medium on current CLIs) while the menu fell back to Sonnet / high. A pane
12//! with a session on file spawns eagerly at open, before any message, so
13//! nothing ever corrected it.
14//! docs/retro/RETRO_RESUMED_AGENT_SPAWNS_WITHOUT_RUNTIME_FLAGS_2026_09_30.md,
15//! docs/reports/REPORT_AGENT_RUNTIME_BINDINGS_2026_09_30.md (G3).
16//!
17//! Two entry points, one decision, for the two providers whose model the menu
18//! wires (Claude, Codex):
19//!
20//! - [`seed_launch`] — a pane `agent.open` is creating.
21//! - [`with_runtime_flags`] — a pane that already exists, at the moment it
22//!   spawns. srv never reads `agent:runtime` otherwise, and a persistent
23//!   process never re-reads `cmd:args`, so a pane saved before the fixes (or
24//!   written by any path that forgets) would run on the CLI default for its
25//!   whole life. This is the backstop that makes srv authoritative at the one
26//!   moment it matters.
27//!
28//! The defaults are duplicated from the frontend by necessity and pinned to
29//! its by `providers/runtime-defaults-consistency.test.ts`.
30
31use serde::{Deserialize, Serialize};
32use serde_json::{json, Value};
33
34use crate::backend::obj::MetaMapType;
35use crate::backend::providers::default_model_for;
36
37mod choice;
38pub use choice::{flags_pin, is_claude_effort, is_claude_model_name, provider_flags_pin, runtime_choice, RuntimeChoice};
39
40/// `DEFAULT_RUNTIME_CONFIG.permissionMode` in `frontend/app/agent-model/document-state.ts`.
41pub(crate) const DEFAULT_PERMISSION_MODE: &str = "bypass";
42/// `DEFAULT_RUNTIME_CONFIG.effort` in `frontend/app/agent-model/document-state.ts`.
43pub(crate) const DEFAULT_EFFORT: &str = "high";
44
45/// Flags this module owns. Stripped from the catalog args so a base that ever
46/// grows one cannot double it.
47const OWNED_FLAGS: &[&str] = &["--model", "-m", "--effort"];
48
49/// What an agent process was actually spawned with: the runtime flags in its
50/// final argv. The Runtime menu shows what was REQUESTED (`agent:runtime`);
51/// this is what the process was GIVEN, so the menu can say when they differ.
52/// `None` for a flag the argv does not carry — the CLI then uses its own default.
53#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
54pub struct SpawnRuntime {
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub model: Option<String>,
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub effort: Option<String>,
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub permission_mode: Option<String>,
61}
62
63/// The runtime flags in `args`. The LAST occurrence of a repeated flag wins,
64/// which is how the CLI is expected to read them (unverified; it matters only
65/// when `provider_flags` repeats a flag the runtime already set).
66/// `--dangerously-skip-permissions` reads as `bypass`; `--permission-mode X`
67/// as `X`.
68pub fn spawn_runtime_from_args(args: &[String]) -> SpawnRuntime {
69    let mut out = SpawnRuntime::default();
70    let mut i = 0;
71    while i < args.len() {
72        let a = args[i].as_str();
73        let next = || args.get(i + 1).cloned();
74        match a {
75            "--model" | "-m" => {
76                if let Some(v) = next() {
77                    out.model = Some(v);
78                    i += 1;
79                }
80            }
81            "--effort" => {
82                if let Some(v) = next() {
83                    out.effort = Some(v);
84                    i += 1;
85                }
86            }
87            "--permission-mode" => {
88                if let Some(v) = next() {
89                    out.permission_mode = Some(v);
90                    i += 1;
91                }
92            }
93            "--dangerously-skip-permissions" => out.permission_mode = Some("bypass".to_string()),
94            _ => {
95                if let Some(v) = a.strip_prefix("--model=") {
96                    out.model = Some(v.to_string());
97                } else if let Some(v) = a.strip_prefix("--effort=") {
98                    out.effort = Some(v.to_string());
99                } else if let Some(v) = a.strip_prefix("--permission-mode=") {
100                    out.permission_mode = Some(v.to_string());
101                }
102            }
103        }
104        i += 1;
105    }
106    out
107}
108
109/// What the running CLI says it is ACTUALLY using, from its `get_settings`
110/// answer (`applied`): the alias on the command line resolved to a concrete
111/// model, and the effort in force. `None` for a field the CLI reports as null
112/// (Haiku has no effort).
113#[derive(Debug, Clone, Default, PartialEq, Eq)]
114pub struct EffectiveRuntime {
115    pub model: Option<String>,
116    pub effort: Option<String>,
117}
118
119/// Prefix of the `request_id` of our `get_settings` requests, so the answer can
120/// be told from the answers to anything else.
121pub const SETTINGS_REQUEST_PREFIX: &str = "agentmux-settings-";
122
123/// The control request asking a running Claude CLI what it is using. Observed
124/// on CLI 2.1.285 to be answered straight after spawn, with no account and no
125/// message (docs/specs/SPEC_RUNTIME_MENU_REMAINING_GAPS_2026_10_01.md §7.3).
126pub fn settings_request_line() -> String {
127    json!({
128        "type": "control_request",
129        "request_id": format!("{SETTINGS_REQUEST_PREFIX}{}", uuid::Uuid::new_v4()),
130        "request": { "subtype": "get_settings" },
131    })
132    .to_string()
133}
134
135/// The effective runtime in a `get_settings` answer, or `None` for any other
136/// frame, an error answer (a CLI that has no `get_settings`) or one without
137/// `applied`. The shape is `{type: control_response, response: {subtype:
138/// success, request_id, response: {applied: {model, effort, ...}}}}`.
139pub fn effective_from_control_response(frame: &Value) -> Option<EffectiveRuntime> {
140    if frame.get("type").and_then(Value::as_str) != Some("control_response") {
141        return None;
142    }
143    let resp = frame.get("response")?;
144    if resp.get("subtype").and_then(Value::as_str) != Some("success") {
145        return None;
146    }
147    if !resp
148        .get("request_id")
149        .and_then(Value::as_str)
150        .is_some_and(|id| id.starts_with(SETTINGS_REQUEST_PREFIX))
151    {
152        return None;
153    }
154    let applied = resp.get("response")?.get("applied")?.as_object()?;
155    let field = |k: &str| {
156        applied
157            .get(k)
158            .and_then(Value::as_str)
159            .filter(|v| !v.is_empty())
160            .map(str::to_string)
161    };
162    Some(EffectiveRuntime { model: field("model"), effort: field("effort") })
163}
164
165/// The `agentruntime` event's payload (`mps_events::AgentRuntime`). An absent value is
166/// omitted, not null; what the CLI reported is sent only while a process runs.
167#[derive(Debug, Clone, PartialEq, serde::Serialize, ts_rs::TS)]
168#[ts(export, export_to = "../../../frontend/types/rpc/")]
169pub struct AgentRuntimeEvent {
170    pub blockid: String,
171    pub running: bool,
172    pub restart_pending: bool,
173    #[serde(skip_serializing_if = "Option::is_none")]
174    #[ts(optional)]
175    pub model: Option<String>,
176    #[serde(skip_serializing_if = "Option::is_none")]
177    #[ts(optional)]
178    pub effort: Option<String>,
179    #[serde(skip_serializing_if = "Option::is_none")]
180    #[ts(optional)]
181    pub permission_mode: Option<String>,
182    #[serde(skip_serializing_if = "Option::is_none")]
183    #[ts(optional)]
184    pub effective_model: Option<String>,
185    #[serde(skip_serializing_if = "Option::is_none")]
186    #[ts(optional)]
187    pub effective_effort: Option<String>,
188    /// The model the last reply of this process came from (the API's own `model` field), when it has replied: srv drops
189    /// what it saw from an earlier process that ran another model, so this is never the previous model's.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    #[ts(optional)]
192    pub observed_model: Option<String>,
193}
194
195/// The `agentruntime` event for one pane (persisted, so a menu that mounts late
196/// still gets the latest). `running` is `None` when no process is alive — then
197/// there is nothing for the menu to compare against. `effective` is what the
198/// CLI reported using, when it has (see [`EffectiveRuntime`]).
199pub fn agent_runtime_event(
200    block_id: &str,
201    running: Option<&SpawnRuntime>,
202    restart_pending: bool,
203    effective: Option<&EffectiveRuntime>,
204) -> AgentRuntimeEvent {
205    let effective = effective.filter(|_| running.is_some());
206    AgentRuntimeEvent {
207        blockid: block_id.to_string(),
208        running: running.is_some(),
209        restart_pending,
210        model: running.and_then(|rt| rt.model.clone()),
211        effort: running.and_then(|rt| rt.effort.clone()),
212        permission_mode: running.and_then(|rt| rt.permission_mode.clone()),
213        effective_model: effective.and_then(|e| e.model.clone()),
214        effective_effort: effective.and_then(|e| e.effort.clone()),
215        observed_model: None,
216    }
217}
218
219/// The model the last reply of `block_id`'s running process came from: none while nothing runs or before its first reply
220/// (a process started on another model has dropped what an earlier one's reply named: `context_reading::drop_model_other_than`).
221fn observed_model(block_id: &str, running: bool) -> Option<String> {
222    running.then(|| crate::backend::context_reading::get(block_id)).flatten().and_then(|r| r.model)
223}
224
225pub fn publish_agent_runtime(
226    broker: &crate::backend::mps::Broker,
227    block_id: &str,
228    running: Option<&SpawnRuntime>,
229    restart_pending: bool,
230    effective: Option<&EffectiveRuntime>,
231) {
232    let mut payload = agent_runtime_event(block_id, running, restart_pending, effective);
233    payload.observed_model = observed_model(block_id, running.is_some());
234    crate::backend::agent_runtime_latest::record(&payload);
235    broker.publish_event::<crate::backend::mps_events::AgentRuntime>(&payload, vec![format!("block:{block_id}")], 1);
236}
237
238pub struct SeededLaunch {
239    /// The argv to store as `cmd:args`.
240    pub cli_args: Vec<String>,
241    /// The value for `agent:runtime`, or `None` for a provider whose model the
242    /// menu does not wire (the pane keeps whatever the menu falls back to).
243    pub runtime: Option<Value>,
244}
245
246/// The value of `--flag value` or `--flag=value` in `flags`, if present; the last one when it repeats.
247pub(crate) fn flag_value<'a>(flags: &'a [String], names: &[&str]) -> Option<&'a str> {
248    // The LAST occurrence wins, as the CLI reads a repeated flag (observed on CLI
249    // 2.1.285: `--model opus --model haiku` sends Haiku, and the reverse sends Opus;
250    // the frontend's `modelFromFlags` agrees). Returning the first decided on Opus
251    // and handed Haiku an `--effort` it does not take.
252    let mut found = None;
253    let mut it = flags.iter();
254    while let Some(f) = it.next() {
255        for n in names {
256            if f == n {
257                if let Some(v) = it.next() {
258                    found = Some(v.as_str());
259                }
260                break;
261            }
262            if let Some(v) = f.strip_prefix(&format!("{n}=")) {
263                found = Some(v);
264                break;
265            }
266        }
267    }
268    found
269}
270
271/// `args` without any `--model` / `-m` (and its value) or `--model=…`.
272fn without_model_flags(args: Vec<String>) -> Vec<String> {
273    let mut out = Vec::with_capacity(args.len());
274    let mut it = args.into_iter();
275    while let Some(a) = it.next() {
276        if a == "--model" || a == "-m" {
277            it.next();
278        } else if !a.starts_with("--model=") {
279            out.push(a);
280        }
281    }
282    out
283}
284
285/// `base` without any of [`OWNED_FLAGS`] (and their values).
286fn without_owned_flags(base: Vec<String>) -> Vec<String> {
287    let mut out = Vec::with_capacity(base.len());
288    let mut it = base.into_iter();
289    while let Some(a) = it.next() {
290        if OWNED_FLAGS.contains(&a.as_str()) {
291            it.next();
292            continue;
293        }
294        if OWNED_FLAGS.iter().any(|f| a.starts_with(&format!("{f}="))) {
295            continue;
296        }
297        out.push(a);
298    }
299    out
300}
301
302/// What the user last picked in the Runtime menu for an agent (`last_runtime`
303/// on `db_agents`), already validated. Each setting is optional: only what was
304/// picked is here, and the rest keeps coming from the definition.
305#[derive(Debug, Clone, Default, PartialEq, Eq)]
306pub struct Remembered {
307    pub permission_mode: Option<String>,
308    pub model: Option<String>,
309    pub effort: Option<String>,
310}
311
312const PERMISSION_MODES: &[&str] = &["bypass", "auto", "acceptEdits", "plan", "default"];
313const EFFORT_LEVELS: &[&str] = &["low", "medium", "high", "xhigh", "max"];
314/// The flag a control-protocol (persistent) agent is launched with; its
315/// presence in the catalog args is what makes `bypass` become `default`.
316const CONTROL_PROTOCOL_FLAG: &str = "--permission-prompt-tool";
317
318impl Remembered {
319    /// Parse the stored JSON for `provider_id`. Only Claude is covered: its
320    /// model namespace is known here (`opus` / `sonnet` / `haiku` or a concrete
321    /// `claude-…` id), and anything else, or anything malformed, is dropped
322    /// setting by setting.
323    pub fn parse(provider_id: &str, raw: &str) -> Remembered {
324        if provider_id != "claude" || raw.is_empty() {
325            return Remembered::default();
326        }
327        let Ok(Value::Object(obj)) = serde_json::from_str::<Value>(raw) else {
328            return Remembered::default();
329        };
330        let get = |k: &str| obj.get(k).and_then(Value::as_str).filter(|v| !v.is_empty());
331        Remembered {
332            permission_mode: get("permissionMode")
333                .filter(|m| PERMISSION_MODES.contains(m))
334                .map(str::to_string),
335            effort: get("effort").filter(|e| EFFORT_LEVELS.contains(e)).map(str::to_string),
336            model: get("model")
337                .filter(|m| matches!(*m, "opus" | "sonnet" | "haiku") || m.starts_with("claude-"))
338                .map(str::to_string),
339        }
340    }
341
342    fn is_empty(&self) -> bool {
343        self.permission_mode.is_none() && self.model.is_none() && self.effort.is_none()
344    }
345}
346
347/// `args` without the permission flags (`--permission-mode X`,
348/// `--dangerously-skip-permissions`).
349fn without_permission_flags(args: Vec<String>) -> Vec<String> {
350    let mut out = Vec::with_capacity(args.len());
351    let mut it = args.into_iter();
352    while let Some(a) = it.next() {
353        if a == "--permission-mode" {
354            it.next();
355            continue;
356        }
357        if a == "--dangerously-skip-permissions" || a.starts_with("--permission-mode=") {
358            continue;
359        }
360        out.push(a);
361    }
362    out
363}
364
365/// `flags` without the `names` flags (and their values), `--flag=value` too.
366fn without_flags(flags: Vec<String>, names: &[&str]) -> Vec<String> {
367    let mut out = Vec::with_capacity(flags.len());
368    let mut it = flags.into_iter();
369    while let Some(f) = it.next() {
370        if names.contains(&f.as_str()) {
371            it.next();
372            continue;
373        }
374        if names.iter().any(|n| f.starts_with(&format!("{n}="))) {
375            continue;
376        }
377        out.push(f);
378    }
379    out
380}
381
382/// Lay what the user last picked over the definition, the way the frontend's
383/// launch does (`resolveLaunchRuntime`): the remembered setting beats the
384/// definition's flag for it, and that flag is taken out of the pane's copy.
385///
386/// Returns `(base, pane_flags, permission_mode)`: the catalog args (their
387/// permission flags replaced when a mode is remembered), the flags to hand to
388/// [`seed_launch`] and to store as `agent:provider_flags`, and the mode the
389/// menu must show (`None` = leave what `seed_launch` says).
390pub fn apply_remembered(
391    provider_id: &str,
392    base: Vec<String>,
393    provider_flags: &str,
394    remembered: &Remembered,
395) -> (Vec<String>, String, Option<String>) {
396    if provider_id != "claude" || remembered.is_empty() {
397        return (base, provider_flags.to_string(), None);
398    }
399    let mut flags: Vec<String> = provider_flags.split_whitespace().map(str::to_string).collect();
400    let mut base = base;
401    let mut front: Vec<String> = Vec::new();
402
403    // The model that will run: remembered, else the definition's, else the default.
404    let model = remembered
405        .model
406        .clone()
407        .or_else(|| flag_value(&flags, &["--model", "-m"]).map(str::to_string));
408    if let Some(m) = &remembered.model {
409        flags = without_flags(flags, &["--model", "-m"]);
410        front.extend(["--model".to_string(), m.clone()]);
411    }
412    if let Some(e) = &remembered.effort {
413        flags = without_flags(flags, &["--effort"]);
414        if model.as_deref().map_or(true, model_takes_effort) {
415            front.extend(["--effort".to_string(), e.clone()]);
416        }
417    }
418    // A model that takes no `--effort` must not be left with the definition's.
419    if model.as_deref().is_some_and(|m| !model_takes_effort(m)) {
420        flags = without_flags(flags, &["--effort"]);
421    }
422
423    let mut mode_for_menu = None;
424    if let Some(mode) = &remembered.permission_mode {
425        let control = base.iter().any(|a| a == CONTROL_PROTOCOL_FLAG);
426        base = without_permission_flags(base);
427        flags = without_permission_flags(flags);
428        let wire = if control && mode == "bypass" { "default" } else { mode.as_str() };
429        if wire == "bypass" {
430            front.push("--dangerously-skip-permissions".to_string());
431        } else {
432            front.extend(["--permission-mode".to_string(), wire.to_string()]);
433        }
434        mode_for_menu = Some(mode.clone());
435    }
436
437    front.extend(flags);
438    (base, front.join(" "), mode_for_menu)
439}
440
441/// The models this provider's accounts list, when AgentMux knows them: Codex's
442/// from its CLI's per-account cache (`codex_models`); empty otherwise.
443fn account_listed_models(provider_id: &str) -> Vec<String> {
444    if provider_id == "codex" {
445        crate::backend::codex_models::installed_common_model_ids()
446    } else {
447        Vec::new()
448    }
449}
450
451/// The model a pane starts on: the first its accounts list, when known, else
452/// the catalog default (`default_model_for`). For Codex an unknown list (a
453/// fresh sign-in before its first turn) gives `""`: no `--model`, so the CLI
454/// picks one the account offers rather than a catalog id it may not run.
455/// `None` for a provider whose model the runtime menu does not wire.
456fn launch_default_model(provider_id: &str, listed: &[String]) -> Option<String> {
457    let catalog = default_model_for(provider_id)?;
458    Some(match listed.first() {
459        Some(first) => first.clone(),
460        None if provider_id == "codex" => String::new(),
461        None => catalog.to_string(),
462    })
463}
464
465/// Build `cmd:args` and `agent:runtime` for a freshly opened pane.
466///
467/// `base` is the catalog argv for the pane's controller. `provider_flags` is
468/// the agent definition's own flags: they are appended last, exactly as the
469/// frontend does, and a `--model` / `--effort` among them is the agent's own
470/// choice — it becomes the runtime the menu shows and no second flag is added,
471/// so the two cannot disagree.
472pub fn seed_launch(
473    provider_id: &str,
474    base: Vec<String>,
475    provider_flags: &str,
476) -> SeededLaunch {
477    let flags: Vec<String> = provider_flags
478        .split_whitespace()
479        .map(str::to_string)
480        .collect();
481    let listed = account_listed_models(provider_id);
482    let Some(default_model) = launch_default_model(provider_id, &listed) else {
483        let mut cli_args = base;
484        cli_args.extend(flags);
485        return SeededLaunch {
486            cli_args,
487            runtime: None,
488        };
489    };
490
491    let flag_model = flag_value(&flags, &["--model", "-m"]);
492    let flag_effort = flag_value(&flags, &["--effort"]);
493    let model = flag_model.map(str::to_string).unwrap_or(default_model);
494    let effort = flag_effort.unwrap_or(DEFAULT_EFFORT).to_string();
495
496    let mut cli_args = without_owned_flags(base);
497    // Codex reads its prompt from stdin via a trailing `-`, so it must stay last
498    // however many flags land after the catalog args: held back here, put back
499    // after the definition's own flags below. (The spawn path re-normalizes it
500    // too, `build_codex_argv`, but the stored `cmd:args` should be right as is.)
501    let marker = if provider_id == "codex" && cli_args.last().map(String::as_str) == Some("-") {
502        cli_args.pop()
503    } else {
504        None
505    };
506    match provider_id {
507        "claude" => {
508            if flag_model.is_none() {
509                cli_args.extend(["--model".to_string(), model.clone()]);
510            }
511            // Haiku takes no `--effort` (the pinned CLI drops it; older CLIs forwarded
512            // it and the API answered 400); the frontend skips it the same way.
513            if flag_effort.is_none() && model_takes_effort(&model) {
514                cli_args.extend(["--effort".to_string(), effort.clone()]);
515            }
516        }
517        "codex" => {
518            if flag_model.is_none() && !model.is_empty() {
519                cli_args.extend(["--model".to_string(), model.clone()]);
520            }
521        }
522        _ => {}
523    }
524    cli_args.extend(flags);
525    cli_args.extend(marker);
526
527    SeededLaunch {
528        cli_args,
529        runtime: Some(json!({
530            "permissionMode": DEFAULT_PERMISSION_MODE,
531            "model": model,
532            "effort": effort,
533        })),
534    }
535}
536
537/// Whether `--effort` is passed for `model`. Haiku takes none (the pinned CLI drops
538/// it; older CLIs forwarded it and the API answered HTTP 400 on
539/// every turn). Matches the model id as well as the alias, case-insensitively —
540/// this was `model == "haiku"`, so a concrete Haiku id still got the flag.
541/// Mirrors `modelTakesEffort` in frontend/app/view/agent/runtime-capabilities.ts.
542pub(crate) fn model_takes_effort(model: &str) -> bool {
543    !model.to_ascii_lowercase().contains("haiku")
544}
545
546/// The model a Claude Code agent pointed at a custom server (`ANTHROPIC_BASE_URL` in its `cmd:env` that is
547/// not Anthropic's) asks it for: `ANTHROPIC_MODEL`, else the alias (`sonnet`, `opus`, `haiku`) the CLI maps to
548/// that tier's `ANTHROPIC_DEFAULT_*_MODEL`. None where the agent is not on a custom server, or names no model.
549pub fn endpoint_model(meta: &MetaMapType) -> Option<String> {
550    let env = meta.get("cmd:env")?.as_object()?;
551    // Names are read without regard to case, as the launch does (`spawn_env::endpoint`).
552    let all = |name: &str| {
553        let mut spellings: Vec<_> = env.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)).collect();
554        spellings.sort_by(|a, b| a.0.cmp(b.0));
555        spellings.into_iter().filter_map(|(_, v)| v.as_str()).map(str::trim).filter(|v| !v.is_empty()).collect::<Vec<_>>()
556    };
557    let get = |name: &str| all(name).into_iter().next();
558    all("ANTHROPIC_BASE_URL").into_iter().find(|u| !crate::backend::agent_env::is_anthropic_url(u))?;
559    get("ANTHROPIC_MODEL").map(str::to_string).or_else(|| {
560        [("ANTHROPIC_DEFAULT_SONNET_MODEL", "sonnet"), ("ANTHROPIC_DEFAULT_OPUS_MODEL", "opus"), ("ANTHROPIC_DEFAULT_HAIKU_MODEL", "haiku")]
561            .into_iter()
562            .find(|(name, _)| get(name).is_some())
563            .map(|(_, alias)| alias.to_string())
564    })
565}
566
567/// Claude model names: the aliases and concrete ids. A pane carried over from
568/// before per-provider models can have one stored for a Codex agent; it must
569/// never reach Codex, which rejects it (frontend `buildRuntimeArgs.ts` guards the
570/// same way).
571fn is_claude_model(m: &str) -> bool {
572    matches!(m, "opus" | "sonnet" | "haiku") || m.starts_with("claude-")
573}
574
575/// A one-shot pane's (a container agent's) `cmd:args` with the `--model` and `--effort` the pane's runtime picker has
576/// since moved past taken out, so that `with_runtime_flags` lays the runtime's own over them. The picker records a
577/// container agent's choice in `agent:runtime` only (each turn reads `cmd:args` again, and no process restarts), but
578/// `with_runtime_flags` never overrides a flag already there, so a `--model` stored at launch kept the turns on the
579/// old model while the pane said the new one. The definition's own flags are the operator's choice and stay
580/// (`provider_flags_pin`), and a pane with no runtime choice keeps the flags it has.
581pub fn runtime_over_stale_flags(meta: &MetaMapType, args: Vec<String>) -> Vec<String> {
582    let raw_provider = crate::backend::obj::meta_get_string(meta, "agentProvider", "");
583    if crate::backend::providers::resolve_provider_alias(&raw_provider) != "claude" {
584        return args;
585    }
586    let (pins_model, pins_effort) = provider_flags_pin(meta);
587    let chose = |key: &str| meta.get("agent:runtime").and_then(|r| r.get(key)).and_then(Value::as_str).is_some_and(|v| !v.is_empty());
588    let mut args = args;
589    if chose("model") && !pins_model {
590        args = without_model_flags(args);
591    }
592    if chose("effort") && !pins_effort {
593        args = without_flags(args, &["--effort"]);
594    }
595    args
596}
597
598/// `args` as stored in `cmd:args`, plus any runtime flag it lacks, taken from
599/// the pane's `agent:runtime` (or the defaults when it has none).
600///
601/// Never overrides a flag already present: the frontend's rebuild and
602/// [`seed_launch`] put them there, and a definition's own `--model` is the
603/// agent's choice. Leaves alone a provider the menu does not wire, an unknown
604/// provider, and an empty argv (nothing to extend). Idempotent.
605pub fn with_runtime_flags(meta: &MetaMapType, args: Vec<String>) -> Vec<String> {
606    let raw_provider = crate::backend::obj::meta_get_string(meta, "agentProvider", "");
607    let listed = account_listed_models(crate::backend::providers::resolve_provider_alias(&raw_provider));
608    let args = with_runtime_flags_listed(meta, args, &listed);
609    crate::backend::agent_mcp_flag::with_mcp_config_flag(meta, args)
610}
611
612/// [`with_runtime_flags`], given the models the provider's accounts list.
613fn with_runtime_flags_listed(meta: &MetaMapType, args: Vec<String>, listed: &[String]) -> Vec<String> {
614    if args.is_empty() {
615        return args;
616    }
617    // `agentProvider` is written from the definition's `provider` verbatim, and
618    // that may be a legacy alias ("claude-code", "codex-cli"). Resolve it, or a
619    // pane on an alias — exactly the old, pre-existing kind this backstop exists
620    // for — would silently get nothing (ReAgent P1 on #4116). Unknown → "".
621    let raw_provider = crate::backend::obj::meta_get_string(meta, "agentProvider", "");
622    let provider_id = crate::backend::providers::resolve_provider_alias(&raw_provider);
623    // An agent pointed at a server of its own asks that server for the model its environment names, not
624    // for a Claude model the server does not have (a local Ollama answers `claude-sonnet-5-5` with 404).
625    if provider_id == "claude" {
626        if let Some(model) = endpoint_model(meta) {
627            let mut out = without_flags(without_model_flags(args), &["--effort"]);
628            out.extend(["--model".to_string(), model]);
629            return out;
630        }
631    }
632    let Some(default_model) = launch_default_model(provider_id, listed) else {
633        return args;
634    };
635    let runtime = |key: &str| {
636        meta.get("agent:runtime")
637            .and_then(|r| r.get(key))
638            .and_then(Value::as_str)
639            .filter(|v| !v.is_empty())
640            .map(str::to_string)
641    };
642
643    let mut args = args;
644    let mut have_model = flag_value(&args, &["--model", "-m"]).map(str::to_string);
645    // A Codex model already in the stored argv (an older pane's `--model
646    // gpt-5.5`) that no account lists any more is dropped and chosen again
647    // below, unless it is the agent definition's own choice.
648    if provider_id == "codex" && !listed.is_empty() {
649        let definition_flags: Vec<String> = crate::backend::obj::meta_get_string(meta, "agent:provider_flags", "")
650            .split_whitespace()
651            .map(str::to_string)
652            .collect();
653        let definition_model = flag_value(&definition_flags, &["--model", "-m"]);
654        if let Some(m) = have_model.as_deref() {
655            if !listed.iter().any(|l| l == m) && definition_model != Some(m) {
656                args = without_model_flags(args);
657                have_model = None;
658            }
659        }
660    }
661    let have_effort = flag_value(&args, &["--effort"]).is_some();
662    let model = have_model.clone().unwrap_or_else(|| {
663        runtime("model")
664            .filter(|m| match provider_id {
665                // A model no Codex account lists any more (gpt-5.5 on
666                // 2026-10-22) would fail every turn: the default instead.
667                "codex" => !is_claude_model(m) && (listed.is_empty() || listed.iter().any(|l| l == m)),
668                _ => true,
669            })
670            .unwrap_or_else(|| default_model.clone())
671    });
672
673    let mut out = args;
674    match provider_id {
675        "claude" => {
676            if have_model.is_none() {
677                out.extend(["--model".to_string(), model.clone()]);
678            }
679            if !have_effort && model_takes_effort(&model) {
680                let effort = runtime("effort").unwrap_or_else(|| DEFAULT_EFFORT.to_string());
681                out.extend(["--effort".to_string(), effort]);
682            }
683        }
684        "codex" => {
685            if have_model.is_none() && !model.is_empty() {
686                // The stdin marker `-` must end up last even when the stored
687                // argv has flags after it (provider_flags were appended past it).
688                let marker = out.iter().rposition(|a| a == "-").map(|i| out.remove(i));
689                out.extend(["--model".to_string(), model]);
690                out.extend(marker);
691            }
692        }
693        _ => {}
694    }
695    out
696}
697
698/// Write the three keys that must travel together into a new pane's meta:
699/// `cmd:args` (what runs), `agent:runtime` (what the menu shows) and
700/// `agent:provider_flags` (what the frontend's per-send rebuild reapplies — it
701/// starts from the catalog and would drop the definition's flags on the first
702/// send otherwise, #2872). One call, so no caller can write one without the
703/// others.
704pub fn apply_to_meta(meta: &mut MetaMapType, seeded: SeededLaunch, provider_flags: &str) {
705    meta.insert("cmd:args".to_string(), json!(seeded.cli_args));
706    if let Some(runtime) = seeded.runtime {
707        meta.insert("agent:runtime".to_string(), runtime);
708    }
709    meta.insert("agent:provider_flags".to_string(), json!(provider_flags));
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715
716    fn ss(v: &[&str]) -> Vec<String> {
717        v.iter().map(|x| x.to_string()).collect()
718    }
719
720    #[test]
721    fn the_spawn_runtime_is_read_from_the_final_argv() {
722        let rt = spawn_runtime_from_args(&ss(&[
723            "--input-format",
724            "stream-json",
725            "--permission-mode",
726            "default",
727            "--model",
728            "opus",
729            "--effort",
730            "max",
731        ]));
732        assert_eq!(rt.model.as_deref(), Some("opus"));
733        assert_eq!(rt.effort.as_deref(), Some("max"));
734        assert_eq!(rt.permission_mode.as_deref(), Some("default"));
735    }
736
737    #[test]
738    fn a_flag_the_argv_lacks_is_none_which_means_the_cli_default() {
739        let rt = spawn_runtime_from_args(&ss(&["--permission-mode", "default", "--resume", "sid"]));
740        assert_eq!(rt.model, None);
741        assert_eq!(rt.effort, None);
742    }
743
744    #[test]
745    fn every_spelling_of_a_flag_is_read_and_the_last_one_wins() {
746        assert_eq!(
747            spawn_runtime_from_args(&ss(&["--model=opus"]))
748                .model
749                .as_deref(),
750            Some("opus")
751        );
752        assert_eq!(
753            spawn_runtime_from_args(&ss(&["-m", "gpt-5.5"]))
754                .model
755                .as_deref(),
756            Some("gpt-5.5")
757        );
758        assert_eq!(
759            spawn_runtime_from_args(&ss(&["--effort=low"]))
760                .effort
761                .as_deref(),
762            Some("low")
763        );
764        assert_eq!(
765            spawn_runtime_from_args(&ss(&["--model", "sonnet", "--model", "haiku"]))
766                .model
767                .as_deref(),
768            Some("haiku")
769        );
770        assert_eq!(
771            spawn_runtime_from_args(&ss(&["--dangerously-skip-permissions"]))
772                .permission_mode
773                .as_deref(),
774            Some("bypass")
775        );
776        // a flag with no value is not a value
777        assert_eq!(spawn_runtime_from_args(&ss(&["--model"])).model, None);
778    }
779
780    #[test]
781    fn the_event_says_what_runs_and_whether_a_restart_is_coming() {
782        let rt = SpawnRuntime {
783            model: Some("sonnet".into()),
784            effort: None,
785            permission_mode: Some("default".into()),
786        };
787        let v = serde_json::to_value(agent_runtime_event("b1", Some(&rt), true, None)).unwrap();
788        assert_eq!(v["blockid"], "b1");
789        assert_eq!(v["running"], true);
790        assert_eq!(v["model"], "sonnet");
791        assert_eq!(v["permission_mode"], "default");
792        assert_eq!(v["restart_pending"], true);
793        assert!(
794            v.get("effort").is_none(),
795            "an absent flag is omitted, not null"
796        );
797
798        let none = serde_json::to_value(agent_runtime_event("b1", None, false, None)).unwrap();
799        assert_eq!(none["running"], false);
800        assert!(none.get("model").is_none());
801        assert!(v.get("effective_model").is_none(), "nothing reported yet");
802    }
803
804    #[test]
805    fn the_event_carries_what_the_cli_reported_only_while_a_process_runs() {
806        let rt = SpawnRuntime { model: Some("sonnet".into()), ..Default::default() };
807        let eff = EffectiveRuntime { model: Some("claude-sonnet-5-5".into()), effort: None };
808        let v = serde_json::to_value(agent_runtime_event("b1", Some(&rt), false, Some(&eff))).unwrap();
809        assert_eq!(v["effective_model"], "claude-sonnet-5-5");
810        assert!(v.get("effective_effort").is_none(), "a null effort (Haiku) is omitted");
811        // a stale report must not outlive its process
812        let gone = serde_json::to_value(agent_runtime_event("b1", None, false, Some(&eff))).unwrap();
813        assert!(gone.get("effective_model").is_none());
814    }
815
816    #[test]
817    fn a_get_settings_answer_is_read_and_nothing_else_is() {
818        let ok = json!({"type":"control_response","response":{
819            "subtype":"success","request_id":"agentmux-settings-1",
820            "response":{"applied":{"model":"claude-opus-5-5","effort":"medium","advisor":null}}}});
821        assert_eq!(
822            effective_from_control_response(&ok),
823            Some(EffectiveRuntime { model: Some("claude-opus-5-5".into()), effort: Some("medium".into()) })
824        );
825        let haiku = json!({"type":"control_response","response":{
826            "subtype":"success","request_id":"agentmux-settings-2",
827            "response":{"applied":{"model":"claude-haiku-4-5-20251001","effort":null}}}});
828        assert_eq!(effective_from_control_response(&haiku).unwrap().effort, None);
829
830        // someone else's request id, an error answer, no `applied`, other frames
831        for bad in [
832            json!({"type":"control_response","response":{"subtype":"success","request_id":"other-1","response":{"applied":{"model":"x"}}}}),
833            json!({"type":"control_response","response":{"subtype":"error","request_id":"agentmux-settings-3","error":"Unsupported"}}),
834            json!({"type":"control_response","response":{"subtype":"success","request_id":"agentmux-settings-4","response":{}}}),
835            json!({"type":"control_request","request_id":"agentmux-settings-5","request":{"subtype":"get_settings"}}),
836            json!({"type":"result"}),
837        ] {
838            assert_eq!(effective_from_control_response(&bad), None, "{bad}");
839        }
840    }
841
842    #[test]
843    fn the_settings_request_is_a_get_settings_control_request() {
844        let v: Value = serde_json::from_str(&settings_request_line()).unwrap();
845        assert_eq!(v["type"], "control_request");
846        assert_eq!(v["request"]["subtype"], "get_settings");
847        assert!(v["request_id"].as_str().unwrap().starts_with(SETTINGS_REQUEST_PREFIX));
848        assert_ne!(settings_request_line(), settings_request_line(), "each request has its own id");
849    }
850
851    fn s(v: &[&str]) -> Vec<String> {
852        v.iter().map(|x| x.to_string()).collect()
853    }
854    fn after(args: &[String], flag: &str) -> Option<String> {
855        args.iter()
856            .position(|a| a == flag)
857            .and_then(|i| args.get(i + 1))
858            .cloned()
859    }
860
861    // ---- what the user last picked ----
862
863    fn remembered(json: &str) -> Remembered {
864        Remembered::parse("claude", json)
865    }
866    fn persistent_base() -> Vec<String> {
867        s(&["-p", "--input-format", "stream-json", "--permission-prompt-tool", "stdio", "--permission-mode", "default"])
868    }
869
870    #[test]
871    fn remembered_is_parsed_setting_by_setting_and_only_for_claude() {
872        let r = remembered(r#"{"model":"opus","effort":"xhigh","permissionMode":"plan"}"#);
873        assert_eq!(r.model.as_deref(), Some("opus"));
874        assert_eq!(r.effort.as_deref(), Some("xhigh"));
875        assert_eq!(r.permission_mode.as_deref(), Some("plan"));
876        assert_eq!(remembered(r#"{"model":"claude-fable-5-1"}"#).model.as_deref(), Some("claude-fable-5-1"));
877        // invalid settings are dropped on their own, the rest survive
878        let r = remembered(r#"{"model":"gpt-5","effort":"ludicrous","permissionMode":"plan"}"#);
879        assert_eq!((r.model, r.effort), (None, None));
880        assert_eq!(r.permission_mode.as_deref(), Some("plan"));
881        for bad in ["", "not json", "[]", "5", "null"] {
882            assert_eq!(remembered(bad), Remembered::default(), "{bad:?}");
883        }
884        assert_eq!(Remembered::parse("codex", r#"{"model":"opus"}"#), Remembered::default());
885    }
886
887    #[test]
888    fn nothing_remembered_changes_nothing() {
889        let (base, flags, mode) = apply_remembered("claude", persistent_base(), "--model opus --add-dir /x", &Remembered::default());
890        assert_eq!(base, persistent_base());
891        assert_eq!(flags, "--model opus --add-dir /x");
892        assert_eq!(mode, None);
893    }
894
895    #[test]
896    fn a_remembered_model_and_effort_beat_the_definitions_flags() {
897        let r = remembered(r#"{"model":"sonnet","effort":"low"}"#);
898        let (base, flags, mode) = apply_remembered("claude", persistent_base(), "--model opus --effort max --add-dir /x", &r);
899        assert_eq!(flags, "--model sonnet --effort low --add-dir /x");
900        assert_eq!(mode, None);
901        // and seed_launch then shows exactly that, with no second flag
902        let out = seed_launch("claude", base, &flags);
903        let rt = out.runtime.unwrap();
904        assert_eq!((rt["model"].as_str(), rt["effort"].as_str()), (Some("sonnet"), Some("low")));
905        assert_eq!(out.cli_args.iter().filter(|a| *a == "--model").count(), 1);
906        assert_eq!(out.cli_args.iter().filter(|a| *a == "--effort").count(), 1);
907    }
908
909    #[test]
910    fn a_setting_not_picked_keeps_the_definitions_flag() {
911        let r = remembered(r#"{"model":"sonnet"}"#);
912        let (_, flags, _) = apply_remembered("claude", persistent_base(), "--model opus --effort max", &r);
913        assert_eq!(flags, "--model sonnet --effort max");
914    }
915
916    #[test]
917    fn haiku_is_never_left_with_an_effort() {
918        let r = remembered(r#"{"model":"haiku","effort":"high"}"#);
919        let (_, flags, _) = apply_remembered("claude", persistent_base(), "--effort max", &r);
920        assert_eq!(flags, "--model haiku");
921        // remembered Haiku, definition's effort only
922        let r = remembered(r#"{"model":"haiku"}"#);
923        let (_, flags, _) = apply_remembered("claude", persistent_base(), "--model opus --effort max", &r);
924        assert_eq!(flags, "--model haiku");
925    }
926
927    #[test]
928    fn a_remembered_mode_replaces_the_catalog_and_definition_mode_flags() {
929        let r = remembered(r#"{"permissionMode":"plan"}"#);
930        let (base, flags, mode) = apply_remembered("claude", persistent_base(), "--dangerously-skip-permissions --add-dir /x", &r);
931        assert!(!base.iter().any(|a| a == "--permission-mode"), "{base:?}");
932        assert_eq!(flags, "--permission-mode plan --add-dir /x");
933        assert_eq!(mode.as_deref(), Some("plan"));
934        let out = seed_launch("claude", base, &flags);
935        assert_eq!(after(&out.cli_args, "--permission-mode").as_deref(), Some("plan"));
936        assert_eq!(out.cli_args.iter().filter(|a| *a == "--permission-mode").count(), 1);
937        assert!(!out.cli_args.iter().any(|a| a == "--dangerously-skip-permissions"));
938    }
939
940    #[test]
941    fn bypass_on_a_control_protocol_agent_is_default_on_the_wire_but_bypass_in_the_menu() {
942        let r = remembered(r#"{"permissionMode":"bypass"}"#);
943        let (_, flags, mode) = apply_remembered("claude", persistent_base(), "", &r);
944        assert_eq!(flags, "--permission-mode default");
945        assert_eq!(mode.as_deref(), Some("bypass"));
946        // a one-shot agent (no control protocol) gets the real bypass flag
947        let one_shot = s(&["-p", "--output-format", "stream-json"]);
948        let (_, flags, _) = apply_remembered("claude", one_shot, "", &r);
949        assert_eq!(flags, "--dangerously-skip-permissions");
950    }
951
952    #[test]
953    fn other_providers_are_left_alone() {
954        let r = Remembered { model: Some("opus".into()), ..Default::default() };
955        let (base, flags, mode) = apply_remembered("codex", s(&["exec", "-"]), "--x", &r);
956        assert_eq!((base, flags.as_str(), mode), (s(&["exec", "-"]), "--x", None));
957    }
958
959    #[test]
960    fn claude_gets_the_models_and_effort_its_menu_will_show() {
961        let out = seed_launch("claude", s(&["--permission-mode", "default"]), "");
962        assert_eq!(after(&out.cli_args, "--model").as_deref(), Some("sonnet"));
963        assert_eq!(after(&out.cli_args, "--effort").as_deref(), Some("high"));
964        let rt = out.runtime.unwrap();
965        assert_eq!(rt["model"], "sonnet");
966        assert_eq!(rt["effort"], "high");
967        assert_eq!(rt["permissionMode"], "bypass");
968    }
969
970    #[test]
971    fn the_args_and_the_runtime_always_agree() {
972        for (provider, flags) in [
973            ("claude", ""),
974            ("claude", "--model opus --effort max"),
975            ("claude", "--model=claude-fable-5-1"),
976            ("claude", "--model haiku"),
977            ("codex", ""),
978            ("codex", "--model gpt-5.4"),
979        ] {
980            let base = if provider == "codex" {
981                s(&["exec", "--json", "-"])
982            } else {
983                s(&["--permission-mode", "default"])
984            };
985            let out = seed_launch(provider, base, flags);
986            let rt = out.runtime.unwrap();
987            let in_args = out
988                .cli_args
989                .iter()
990                .enumerate()
991                .find_map(|(i, a)| match a.as_str() {
992                    "--model" => out.cli_args.get(i + 1).cloned(),
993                    _ => a.strip_prefix("--model=").map(str::to_string),
994                })
995                // Codex with no known account list names none: runtime "".
996                .unwrap_or_default();
997            assert_eq!(rt["model"], in_args, "{provider} {flags:?}");
998        }
999    }
1000
1001    // ReAgent P2 on #4152. A repeated flag: the LAST wins, as the CLI reads it
1002    // (observed on 2.1.285) and as the frontend's modelFromFlags does. flag_value
1003    // used to return the first, so `--model opus --model haiku` was decided as Opus
1004    // (and given --effort) while the CLI ran Haiku, which takes no effort.
1005    #[test]
1006    fn a_repeated_flag_is_decided_on_the_last_one_as_the_cli_reads_it() {
1007        let out = seed_launch("claude", s(&[]), "--model opus --model haiku");
1008        assert!(
1009            !out.cli_args.iter().any(|a| a == "--effort"),
1010            "{:?}",
1011            out.cli_args
1012        );
1013        assert_eq!(out.runtime.unwrap()["model"], "haiku");
1014
1015        let meta = meta_with("claude", None);
1016        let filled = with_runtime_flags(&meta, s(&["--model", "opus", "--model", "haiku"]));
1017        assert!(!filled.iter().any(|a| a == "--effort"), "{filled:?}");
1018
1019        // and the other way round: the last model takes effort
1020        let out = seed_launch("claude", s(&[]), "--model haiku --model opus");
1021        assert_eq!(after(&out.cli_args, "--effort").as_deref(), Some("high"));
1022
1023        // a repeated --effort: the last one is the definition's choice
1024        let out = seed_launch("claude", s(&[]), "--effort low --effort max");
1025        assert_eq!(out.runtime.unwrap()["effort"], "max");
1026    }
1027
1028    #[test]
1029    fn effort_is_for_models_that_take_it_whatever_the_haiku_id_looks_like() {
1030        for haiku in [
1031            "haiku",
1032            "Haiku",
1033            "claude-haiku-4-5",
1034            "claude-haiku-4-5-20251001",
1035        ] {
1036            assert!(!model_takes_effort(haiku), "{haiku}");
1037            // seeded
1038            let seeded = seed_launch("claude", s(&[]), &format!("--model {haiku}"));
1039            assert!(
1040                !seeded.cli_args.iter().any(|a| a == "--effort"),
1041                "{haiku}: {:?}",
1042                seeded.cli_args
1043            );
1044            // filled into a stored pane
1045            let meta = meta_with("claude", Some(json!({"model": haiku})));
1046            let filled = with_runtime_flags(&meta, s(&["-p"]));
1047            assert!(
1048                !filled.iter().any(|a| a == "--effort"),
1049                "{haiku}: {filled:?}"
1050            );
1051        }
1052        for other in [
1053            "sonnet",
1054            "opus",
1055            "claude-sonnet-5-5",
1056            "claude-opus-5-5",
1057            "claude-fable-5-1",
1058        ] {
1059            assert!(model_takes_effort(other), "{other}");
1060        }
1061    }
1062
1063    #[test]
1064    fn haiku_gets_no_effort_flag() {
1065        let out = seed_launch("claude", s(&[]), "--model haiku");
1066        assert!(
1067            !out.cli_args.iter().any(|a| a == "--effort"),
1068            "{:?}",
1069            out.cli_args
1070        );
1071    }
1072
1073    #[test]
1074    fn a_definitions_own_model_is_the_runtime_and_is_not_doubled() {
1075        let out = seed_launch("claude", s(&[]), "--model opus --effort max");
1076        assert_eq!(
1077            out.cli_args.iter().filter(|a| *a == "--model").count(),
1078            1,
1079            "{:?}",
1080            out.cli_args
1081        );
1082        assert_eq!(
1083            out.cli_args.iter().filter(|a| *a == "--effort").count(),
1084            1,
1085            "{:?}",
1086            out.cli_args
1087        );
1088        let rt = out.runtime.unwrap();
1089        assert_eq!(rt["model"], "opus");
1090        assert_eq!(rt["effort"], "max");
1091    }
1092
1093    #[test]
1094    fn provider_flags_stay_last_as_in_the_frontend() {
1095        let out = seed_launch(
1096            "claude",
1097            s(&["--permission-mode", "default"]),
1098            "--add-dir /tmp",
1099        );
1100        assert_eq!(
1101            out.cli_args[out.cli_args.len() - 2..],
1102            s(&["--add-dir", "/tmp"])
1103        );
1104    }
1105
1106    #[test]
1107    fn codex_keeps_its_stdin_marker_last() {
1108        let out = seed_launch("codex", s(&["exec", "--json", "-"]), "--model gpt-6-astra");
1109        assert_eq!(
1110            out.cli_args,
1111            s(&["exec", "--json", "--model", "gpt-6-astra", "-"])
1112        );
1113    }
1114
1115    #[test]
1116    fn codex_keeps_its_stdin_marker_last_whatever_the_definition_adds() {
1117        // ReAgent P1 on #4114: a definition's own --model (flag_model is Some)
1118        // skipped the old marker handling and left `-` mid-argv.
1119        for flags in [
1120            "--model gpt-5.4",
1121            "-m gpt-5.4",
1122            "--model=gpt-5.4",
1123            "--add-dir /tmp",
1124            "--model gpt-5.4 --add-dir /tmp",
1125            "",
1126        ] {
1127            let out = seed_launch("codex", s(&["exec", "--json", "-"]), flags);
1128            assert_eq!(
1129                out.cli_args.last().map(String::as_str),
1130                Some("-"),
1131                "{flags:?}: {:?}",
1132                out.cli_args
1133            );
1134            assert_eq!(
1135                out.cli_args.iter().filter(|a| *a == "-").count(),
1136                1,
1137                "{flags:?}: {:?}",
1138                out.cli_args
1139            );
1140        }
1141    }
1142
1143    #[test]
1144    fn a_codex_definitions_model_is_the_runtime_with_the_marker_last() {
1145        let out = seed_launch("codex", s(&["exec", "--json", "-"]), "--model gpt-5.4");
1146        assert_eq!(
1147            out.cli_args,
1148            s(&["exec", "--json", "--model", "gpt-5.4", "-"])
1149        );
1150        assert_eq!(out.runtime.unwrap()["model"], "gpt-5.4");
1151    }
1152
1153    #[test]
1154    fn a_catalog_base_that_grows_a_model_flag_cannot_double_it() {
1155        let out = seed_launch(
1156            "claude",
1157            s(&["--model", "opus", "--permission-mode", "default"]),
1158            "",
1159        );
1160        assert_eq!(after(&out.cli_args, "--model").as_deref(), Some("sonnet"));
1161        assert_eq!(out.cli_args.iter().filter(|a| *a == "--model").count(), 1);
1162    }
1163
1164    #[test]
1165    fn a_provider_the_menu_does_not_wire_is_left_alone() {
1166        for id in [
1167            "gemini",
1168            "kimi",
1169            "qwen",
1170            "openclaw",
1171            "copilot",
1172            "pi",
1173            "muxcode",
1174        ] {
1175            let out = seed_launch(id, s(&["--yolo"]), "--x y");
1176            assert!(out.runtime.is_none(), "{id}");
1177            assert_eq!(out.cli_args, s(&["--yolo", "--x", "y"]), "{id}");
1178        }
1179    }
1180
1181    #[test]
1182    fn the_meta_a_pane_opens_with_has_all_three_keys_in_agreement() {
1183        let mut meta = MetaMapType::new();
1184        let seeded = seed_launch(
1185            "claude",
1186            s(&["--permission-mode", "default"]),
1187            "--model opus",
1188        );
1189        apply_to_meta(&mut meta, seeded, "--model opus");
1190        let args: Vec<String> = serde_json::from_value(meta["cmd:args"].clone()).unwrap();
1191        assert_eq!(after(&args, "--model").as_deref(), Some("opus"));
1192        assert_eq!(meta["agent:runtime"]["model"], "opus");
1193        assert_eq!(meta["agent:provider_flags"], "--model opus");
1194    }
1195
1196    #[test]
1197    fn a_provider_without_a_runtime_still_records_its_flags() {
1198        let mut meta = MetaMapType::new();
1199        apply_to_meta(
1200            &mut meta,
1201            seed_launch("gemini", s(&["--yolo"]), "--x y"),
1202            "--x y",
1203        );
1204        assert!(!meta.contains_key("agent:runtime"));
1205        assert_eq!(meta["agent:provider_flags"], "--x y");
1206    }
1207
1208    fn meta_with(provider: &str, runtime: Option<Value>) -> MetaMapType {
1209        let mut m = MetaMapType::new();
1210        m.insert("agentProvider".to_string(), json!(provider));
1211        if let Some(r) = runtime {
1212            m.insert("agent:runtime".to_string(), r);
1213        }
1214        m
1215    }
1216
1217    /// #49047: a container agent's picker writes `agent:runtime` only, and the `--model` stored at launch outranked it, so
1218    /// the turns ran on the old model while the chip said the new one.
1219    #[test]
1220    fn a_one_shot_panes_runtime_choice_outranks_the_flags_stored_at_launch() {
1221        let meta = meta_with("claude", Some(json!({"model": "sonnet", "effort": "high"})));
1222        let stored = s(&["-p", "--model", "claude-fable-5-2", "--effort", "max", "--verbose"]);
1223        let args = with_runtime_flags(&meta, runtime_over_stale_flags(&meta, stored.clone()));
1224        assert_eq!(after(&args, "--model").as_deref(), Some("sonnet"));
1225        assert_eq!(after(&args, "--effort").as_deref(), Some("high"));
1226        assert!(args.contains(&"--verbose".to_string()), "the other flags stay");
1227        // Without the fix the stored flag won.
1228        assert_eq!(after(&with_runtime_flags(&meta, stored), "--model").as_deref(), Some("claude-fable-5-2"));
1229    }
1230
1231    #[test]
1232    fn the_definitions_own_model_and_a_pane_with_no_choice_keep_their_flags() {
1233        let mut pinned = meta_with("claude", Some(json!({"model": "sonnet", "effort": "high"})));
1234        pinned.insert("agent:provider_flags".to_string(), json!("--model claude-fable-5-2"));
1235        let args = runtime_over_stale_flags(&pinned, s(&["-p", "--model", "claude-fable-5-2", "--effort", "max"]));
1236        assert_eq!(after(&args, "--model").as_deref(), Some("claude-fable-5-2"), "the operator's pin stays");
1237        assert_eq!(after(&args, "--effort"), None, "an effort the definition does not pin is left to the runtime's own");
1238        let none = meta_with("claude", None);
1239        assert_eq!(runtime_over_stale_flags(&none, s(&["-p", "--model", "opus"])), s(&["-p", "--model", "opus"]));
1240        let codex = meta_with("codex", Some(json!({"model": "gpt-5.4"})));
1241        assert_eq!(runtime_over_stale_flags(&codex, s(&["exec", "--model", "x"])), s(&["exec", "--model", "x"]));
1242    }
1243
1244    /// #3680: a Claude agent working in the user's own project gets the config AgentMux wrote
1245    /// outside that project, once, and no other provider is given the flag (srv hands them the
1246    /// servers from the same file).
1247    #[test]
1248    fn a_user_project_turn_is_pointed_at_the_agents_config_outside_it_once() {
1249        let data = tempfile::tempdir().unwrap();
1250        let project = tempfile::tempdir().unwrap();
1251        let project_str = project.path().to_string_lossy().into_owned();
1252        crate::backend::mcp_config_file::with_data_home(data.path(), || {
1253            let path = crate::backend::mcp_config_file::relocated_path(&project_str).unwrap();
1254            crate::backend::mcp_config_file::write_relocated(&path, r#"{"mcpServers":{"agentmux":{}}}"#).unwrap();
1255            let mut meta = meta_with("claude", None);
1256            meta.insert("cmd:cwd".to_string(), json!(project_str));
1257            let out = with_runtime_flags(&meta, s(&["--model", "sonnet"]));
1258            let at = out.iter().position(|a| a == "--mcp-config").expect("a Claude turn is pointed at its config");
1259            assert_eq!(out[at + 1], path.to_string_lossy());
1260            assert_eq!(with_runtime_flags(&meta, out.clone()).iter().filter(|a| *a == "--mcp-config").count(), 1, "added once");
1261
1262            let mut codex = meta_with("codex", None);
1263            codex.insert("cmd:cwd".to_string(), json!(project_str));
1264            assert!(!with_runtime_flags(&codex, s(&["exec", "-"])).iter().any(|a| a == "--mcp-config"));
1265        });
1266    }
1267
1268    #[test]
1269    fn a_stored_pane_with_no_flags_gets_what_its_menu_shows() {
1270        let meta = meta_with(
1271            "claude",
1272            Some(json!({"model": "opus", "effort": "max", "permissionMode": "bypass"})),
1273        );
1274        let out = with_runtime_flags(&meta, s(&["--permission-mode", "default"]));
1275        assert_eq!(after(&out, "--model").as_deref(), Some("opus"));
1276        assert_eq!(after(&out, "--effort").as_deref(), Some("max"));
1277    }
1278
1279    #[test]
1280    fn a_pane_with_no_runtime_at_all_gets_the_defaults() {
1281        let out = with_runtime_flags(
1282            &meta_with("claude", None),
1283            s(&["--permission-mode", "default"]),
1284        );
1285        assert_eq!(after(&out, "--model").as_deref(), Some("sonnet"));
1286        assert_eq!(after(&out, "--effort").as_deref(), Some("high"));
1287    }
1288
1289    #[test]
1290    fn flags_already_present_are_never_overridden_or_doubled() {
1291        let meta = meta_with("claude", Some(json!({"model": "sonnet", "effort": "low"})));
1292        let args = s(&["--model", "opus", "--effort", "max"]);
1293        assert_eq!(with_runtime_flags(&meta, args.clone()), args);
1294    }
1295
1296    #[test]
1297    fn a_model_flag_without_an_effort_still_gets_the_runtimes_effort() {
1298        let meta = meta_with("claude", Some(json!({"model": "sonnet", "effort": "low"})));
1299        let out = with_runtime_flags(&meta, s(&["--model", "opus"]));
1300        assert_eq!(after(&out, "--model").as_deref(), Some("opus"));
1301        assert_eq!(after(&out, "--effort").as_deref(), Some("low"));
1302    }
1303
1304    #[test]
1305    fn haiku_gets_no_effort_whether_it_comes_from_the_args_or_the_runtime() {
1306        let from_args = with_runtime_flags(&meta_with("claude", None), s(&["--model", "haiku"]));
1307        assert!(!from_args.iter().any(|a| a == "--effort"), "{from_args:?}");
1308        let from_runtime = with_runtime_flags(
1309            &meta_with("claude", Some(json!({"model": "haiku"}))),
1310            s(&["-p"]),
1311        );
1312        assert!(
1313            !from_runtime.iter().any(|a| a == "--effort"),
1314            "{from_runtime:?}"
1315        );
1316        assert_eq!(after(&from_runtime, "--model").as_deref(), Some("haiku"));
1317    }
1318
1319    #[test]
1320    fn it_is_idempotent() {
1321        let meta = meta_with("claude", Some(json!({"model": "opus", "effort": "max"})));
1322        let once = with_runtime_flags(&meta, s(&["--permission-mode", "default"]));
1323        assert_eq!(with_runtime_flags(&meta, once.clone()), once);
1324    }
1325
1326    #[test]
1327    fn codex_gets_its_model_before_the_stdin_marker() {
1328        let meta = meta_with("codex", Some(json!({"model": "gpt-5.4"})));
1329        let out = with_runtime_flags(&meta, s(&["exec", "--json", "-"]));
1330        assert_eq!(out, s(&["exec", "--json", "--model", "gpt-5.4", "-"]));
1331    }
1332
1333    #[test]
1334    fn codex_keeps_its_stdin_marker_last_even_when_flags_sit_after_it() {
1335        let meta = meta_with("codex", Some(json!({"model": "gpt-5.4"})));
1336        let out = with_runtime_flags(&meta, s(&["exec", "--json", "-", "--add-dir", "/tmp"]));
1337        assert_eq!(
1338            out,
1339            s(&[
1340                "exec",
1341                "--json",
1342                "--add-dir",
1343                "/tmp",
1344                "--model",
1345                "gpt-5.4",
1346                "-"
1347            ])
1348        );
1349    }
1350
1351    #[test]
1352    fn a_claude_model_stored_on_a_codex_pane_never_reaches_codex() {
1353        for stale in ["opus", "sonnet", "haiku", "claude-sonnet-5-5"] {
1354            let meta = meta_with("codex", Some(json!({ "model": stale })));
1355            // No account list in tests: the CLI picks, so no `--model` at all.
1356            let out = with_runtime_flags(&meta, s(&["exec", "-"]));
1357            assert_eq!(out, s(&["exec", "-"]), "{stale}");
1358            let listed = s(&["gpt-6-astra"]);
1359            let out = with_runtime_flags_listed(&meta, s(&["exec", "-"]), &listed);
1360            assert_eq!(after(&out, "--model").as_deref(), Some("gpt-6-astra"), "{stale}");
1361        }
1362    }
1363
1364    /// Codex's accounts list their own models (SPEC_CODEX_OAUTH_IN_CONNECTORS_AND_EMAIL_LABELS_2026_10_22.md §4):
1365    /// a pane srv opens starts on the first of them, and a stored model none
1366    /// lists is replaced by it rather than failing every turn.
1367    #[test]
1368    fn a_codex_pane_starts_on_and_keeps_to_what_its_accounts_list() {
1369        let listed = s(&["gpt-7-nova", "gpt-6-astra"]);
1370        assert_eq!(launch_default_model("codex", &listed).as_deref(), Some("gpt-7-nova"));
1371        assert_eq!(launch_default_model("codex", &[]).as_deref(), Some(""), "no list yet: none, the CLI picks");
1372        assert_eq!(seed_launch("codex", s(&["exec", "-"]), "").cli_args, s(&["exec", "-"]));
1373        assert_eq!(launch_default_model("aider", &listed), None, "a provider the menu doesn't wire");
1374
1375        let run = |model: &str| {
1376            let meta = meta_with("codex", Some(json!({ "model": model })));
1377            after(&with_runtime_flags_listed(&meta, s(&["exec", "-"]), &listed), "--model")
1378        };
1379        assert_eq!(run("gpt-6-astra").as_deref(), Some("gpt-6-astra"), "a listed pick is kept");
1380        assert_eq!(run("gpt-5.5").as_deref(), Some("gpt-7-nova"), "a retired one is replaced");
1381
1382        // Already in the stored argv (an older pane): replaced too, once, and
1383        // the stdin marker stays last; but the definition's own model is kept.
1384        let mut meta = meta_with("codex", Some(json!({ "model": "gpt-5.5" })));
1385        let out = with_runtime_flags_listed(&meta, s(&["exec", "--model", "gpt-5.5", "-"]), &listed);
1386        assert_eq!(out, s(&["exec", "--model", "gpt-7-nova", "-"]));
1387        meta.insert("agent:provider_flags".to_string(), json!("--model gpt-5.5"));
1388        let out = with_runtime_flags_listed(&meta, s(&["exec", "-", "--model", "gpt-5.5"]), &listed);
1389        assert_eq!(after(&out, "--model").as_deref(), Some("gpt-5.5"), "the definition's choice");
1390    }
1391
1392    #[test]
1393    fn a_pane_recorded_under_a_legacy_provider_alias_is_still_filled() {
1394        // ReAgent P1 on #4116: `agentProvider` is the definition's provider as typed.
1395        for alias in ["claude-code", "claude_code"] {
1396            let meta = meta_with(alias, Some(json!({"model": "opus", "effort": "max"})));
1397            let out = with_runtime_flags(&meta, s(&["--permission-mode", "default"]));
1398            assert_eq!(after(&out, "--model").as_deref(), Some("opus"), "{alias}");
1399            assert_eq!(after(&out, "--effort").as_deref(), Some("max"), "{alias}");
1400        }
1401        let meta = meta_with("codex-cli", Some(json!({"model": "gpt-5.4"})));
1402        assert_eq!(
1403            with_runtime_flags(&meta, s(&["exec", "--json", "-"])),
1404            s(&["exec", "--json", "--model", "gpt-5.4", "-"])
1405        );
1406    }
1407
1408    #[test]
1409    fn it_leaves_alone_what_it_cannot_judge() {
1410        // not wired, unknown, no provider recorded, and an empty argv
1411        for provider in ["gemini", "kimi", "mystery", ""] {
1412            let args = s(&["--yolo"]);
1413            assert_eq!(
1414                with_runtime_flags(&meta_with(provider, None), args.clone()),
1415                args,
1416                "{provider:?}"
1417            );
1418        }
1419        assert!(with_runtime_flags(&meta_with("claude", None), vec![]).is_empty());
1420    }
1421
1422    fn endpoint_meta(env: Value) -> MetaMapType {
1423        let mut m = meta_with("claude", Some(json!({"model": "sonnet", "effort": "high", "permissionMode": "bypass"})));
1424        m.insert("cmd:env".to_string(), env);
1425        m
1426    }
1427
1428    #[test]
1429    fn an_agent_on_a_custom_server_asks_it_for_its_own_model_not_a_claude_one() {
1430        let meta = endpoint_meta(json!({"ANTHROPIC_BASE_URL": "http://192.0.2.68:11434", "ANTHROPIC_MODEL": "flint:40b-a2b"}));
1431        // srv's own default (`--model claude-sonnet-5-5 --effort high`) is already in the stored argv.
1432        let args = ss(&["--print", "--model", "claude-sonnet-5-5", "--effort", "high", "--resume", "sid"]);
1433        let out = with_runtime_flags_listed(&meta, args, &[]);
1434        assert_eq!(out, ss(&["--print", "--resume", "sid", "--model", "flint:40b-a2b"]));
1435        // Idempotent: a second pass changes nothing.
1436        assert_eq!(with_runtime_flags_listed(&meta, out.clone(), &[]), out);
1437    }
1438
1439    #[test]
1440    fn with_no_model_named_the_tiers_alias_is_used_and_anthropic_itself_is_left_alone() {
1441        let tier = endpoint_meta(json!({"ANTHROPIC_BASE_URL": "http://localhost:11434", "ANTHROPIC_DEFAULT_SONNET_MODEL": "qwen3-coder:30b"}));
1442        assert_eq!(endpoint_model(&tier).as_deref(), Some("sonnet"));
1443        let none = endpoint_meta(json!({"ANTHROPIC_BASE_URL": "http://localhost:11434"}));
1444        assert_eq!(endpoint_model(&none), None);
1445        let anthropic = endpoint_meta(json!({"ANTHROPIC_BASE_URL": "https://api.anthropic.com", "ANTHROPIC_MODEL": "claude-opus-5-5"}));
1446        assert_eq!(endpoint_model(&anthropic), None);
1447        let out = with_runtime_flags_listed(&anthropic, ss(&["--print"]), &[]);
1448        assert!(out.contains(&"--model".to_string()) && !out.contains(&"claude-opus-5-5".to_string()), "{out:?}");
1449    }
1450
1451    #[test]
1452    fn the_endpoint_names_are_read_in_any_case() {
1453        let meta = endpoint_meta(json!({"anthropic_base_url": "http://localhost:11434", "Anthropic_Model": "flint:40b-a2b"}));
1454        assert_eq!(endpoint_model(&meta).as_deref(), Some("flint:40b-a2b"));
1455        let both = endpoint_meta(json!({"ANTHROPIC_BASE_URL": "https://api.anthropic.com", "anthropic_base_url": "http://localhost:11434", "ANTHROPIC_MODEL": "m"}));
1456        assert_eq!(endpoint_model(&both).as_deref(), Some("m"), "a spelling that is not Anthropic's decides");
1457    }
1458
1459    #[test]
1460    fn an_agent_with_no_endpoint_keeps_the_model_flags_it_has() {
1461        let meta = meta_with("claude", Some(json!({"model": "sonnet", "effort": "high", "permissionMode": "bypass"})));
1462        let args = ss(&["--print", "--model", "opus", "--effort", "max"]);
1463        assert_eq!(with_runtime_flags_listed(&meta, args.clone(), &[]), args);
1464    }
1465
1466    #[test]
1467    fn the_event_names_the_model_of_the_running_process_last_reply_and_nothing_before_it() {
1468        let block = format!("rt-{}", uuid::Uuid::new_v4());
1469        assert_eq!(observed_model(&block, true), None, "no reply yet");
1470        crate::backend::context_reading::observe_claude_frame(
1471            &block,
1472            &serde_json::json!({"type": "assistant", "message": {"id": "m1", "model": "claude-fable-5-2",
1473                "usage": {"input_tokens": 2, "cache_creation_input_tokens": 1000, "cache_read_input_tokens": 99_000}}}),
1474        );
1475        assert_eq!(observed_model(&block, true).as_deref(), Some("claude-fable-5-2"));
1476        assert_eq!(observed_model(&block, false), None, "nothing runs: nothing is said");
1477        crate::backend::context_reading::drop_model_other_than(&block, "sonnet");
1478        assert_eq!(observed_model(&block, true), None, "a process started on another model has not replied yet");
1479        crate::backend::context_reading::forget(&block);
1480    }
1481}